AltusPlatform AI Support
Below is a copy/paste-ready instruction pack for OpenAI Codex in VS Code to build the AltusPlatform AI Support WordPress plugin (PHP 7.4.11 → 8.4 compatible), with Microsoft 365 multi-inbox monitoring, OpenAI triage + recommended actions, human approval, safe DB writes to Argus/Altus tables, and a suggested email reply draft.
CODEX BUILD INSTRUCTIONS — AltusPlatform AI Support Plugin (WordPress)
0) Objective
Create a WordPress plugin: altus-ai-support that:
-
Allows WordPress superusers only to connect their Microsoft Office 365 account (Graph OAuth).
-
Monitors inboxes for all connected accounts (Managing Director / CSM / CSA) for inbound support requests.
-
Uses OpenAI to classify emails and generate recommended platform actions (structured JSON).
-
Presents a WP-Admin queue of requests with statuses:
-
Open, In-Process, Closed, Not a platform request
-
-
Provides an Approve Actions flow: human confirms → plugin executes actions safely:
-
Create users (WP user + ACC contact)
-
Verify user to minisite (ae_verified_members + acc_keys)
-
Enroll user to course (ae_enrollments)
-
Check enrollment/completion (ae_enrollments)
-
Reset post-test/test attempts (ae_test_attempts)
-
-
Drafts a suggested email reply summarizing what was done (stored in system + optionally ready-to-send via Graph with explicit click-to-send).
1) Hard Requirements
-
PHP compatibility: Must run on PHP 7.4.11 through 8.4.
-
Security:
-
WP Admin pages require manage_options (or stricter: administrator + is_super_admin() on multisite).
-
Every action uses nonces, capability checks, and server-side validation.
-
All DB writes must be parameterized via $wpdb->prepare() and use the Argus-Core DB variables.
-
-
Argus-Core DB variables:
-
Use ../wp-content/plugins/altus-core/config.php
-
$client_server_database = WP site DB
-
$acc_server_database = Altus Client Center DB (shared)
-
$master_key = tenant key
-
-
Logging: Use Codex-style update logs at:
-
/wp-content/plugins/altus-ai-support/logs/update-log.txt
-
-
No silent automation: The plugin never executes platform changes without a human clicking Approve & Execute.
2) Plugin Structure
Create folder: wp-content/plugins/altus-ai-support/
Files / Classes
altus-ai-support.php (bootstrap)
includes/class-aais-activator.php
includes/class-aais-capabilities.php
includes/class-aais-crypto.php (encrypt/decrypt tokens)
includes/class-aais-graph-client.php (Graph OAuth + API)
includes/class-aais-inbox-monitor.php (polling/delta sync)
includes/class-aais-openai.php (OpenAI calls + schema enforcement)
includes/class-aais-request-repository.php (CRUD for requests)
includes/class-aais-action-planner.php (convert AI output -> action objects)
includes/class-aais-action-executor.php (DB updates; dry-run support)
includes/class-aais-admin.php (menus + pages)
includes/class-aais-ajax.php (approve/execute, refine, status updates)
includes/db/schema.php (custom tables)
assets/admin.css
assets/admin.js
logs/update-log.txt
3) Data Model (Custom Tables)
Create two custom tables in the WP database (NOT in altuscampus__cc):
3.1
wp_aais_accounts
Stores connected O365 accounts per WP superuser (or per site). Minimal fields:
-
id BIGINT PK
-
wp_user_id BIGINT
-
tenant_id VARCHAR(128) NULL
-
account_email VARCHAR(190)
-
graph_user_id VARCHAR(128)
-
access_token_enc LONGTEXT (encrypted)
-
refresh_token_enc LONGTEXT (encrypted, if applicable)
-
expires_at DATETIME
-
delta_link LONGTEXT NULL (for message delta sync)
-
status ENUM(‘connected’,‘error’,‘revoked’)
-
created_at, updated_at
3.2
wp_aais_requests
Stores each detected support request email and workflow state:
-
id BIGINT PK
-
source_account_id BIGINT (FK -> accounts)
-
message_id VARCHAR(256) (Graph message id)
-
internet_message_id VARCHAR(256) NULL
-
from_email VARCHAR(190)
-
from_name VARCHAR(190) NULL
-
subject TEXT
-
received_at DATETIME
-
body_excerpt MEDIUMTEXT
-
body_full LONGTEXT (optional; store sanitized/plaintext)
-
classification ENUM(‘platform_request’,‘not_platform_request’,‘unknown’)
-
status ENUM(‘open’,‘in_process’,‘closed’,‘not_platform_request’)
-
ai_summary LONGTEXT NULL
-
ai_actions_json LONGTEXT NULL (validated JSON schema)
-
refinement_notes LONGTEXT NULL
-
execution_log LONGTEXT NULL
-
reply_draft LONGTEXT NULL
-
created_by_wp_user_id BIGINT NULL
-
updated_by_wp_user_id BIGINT NULL
-
created_at, updated_at
Indexes:
-
(status, received_at)
-
(message_id)
-
(source_account_id, received_at)
4) Microsoft 365 / Graph Integration
4.1 OAuth
-
Implement OAuth authorization code flow using Microsoft identity platform.
-
Store client id/secret in WP admin settings (superusers only).
-
Redirect URI: wp-admin/admin.php?page=aais-settings&oauth=callback
-
Scopes:
-
offline_access
-
Mail.Read
-
Mail.ReadWrite (only if you want to set categories / move messages)
-
Mail.Send (ONLY if implementing click-to-send reply; otherwise omit)
-
User.Read
-
4.2 Polling / Delta Sync
-
Use WP-Cron to run every 5 minutes:
-
aais_cron_poll_inboxes
-
-
For each connected account:
-
Use Graph delta query for messages in Inbox:
-
/me/mailFolders/inbox/messages/delta
-
-
Persist delta_link to avoid reprocessing.
-
-
For each new message:
-
Ignore auto-replies and out-of-office:
-
headers / subject contains “Automatic reply”, “Out of Office”, etc.
-
-
Create wp_aais_requests row if not existing.
-
4.3 Minimal Message Parsing
-
Store:
-
from, subject, receivedDateTime
-
body preview + optionally full body (converted to plaintext)
-
-
Strip signatures as best-effort (simple heuristics ok).
5) OpenAI Integration (Classification + Action Plan)
5.1 Settings
-
Store OpenAI API key in wp_options (autoload = no).
-
Model configurable (default: “gpt-4.1-mini” or similar).
-
Temperature low: 0.2.
5.2 Output MUST be Strict JSON
Codex must implement schema validation. If invalid, mark request as unknown and require manual review/refine.
5.3 The “Triage Prompt” (System + User)
System message:
-
You are a support operations assistant for AltusPlatform.
-
You must output ONLY valid JSON matching the schema.
-
You must never invent IDs; if missing, ask for clarification in clarifying_questions.
User message includes:
-
Email metadata + plaintext body
-
Known tenant $master_key
-
Allowed actions list and constraints
5.4 JSON Schema (store in code as reference)
AI must return:
{
"classification": "platform_request|not_platform_request|unknown",
"confidence": 0.0,
"summary": "string",
"clarifying_questions": ["string"],
"actions": [
{
"type": "create_user|verify_member|minisite_lookup|enroll_user|check_enrollment|reset_test_attempts",
"reason": "string",
"inputs": {
"email": "string",
"first_name": "string|null",
"last_name": "string|null",
"minisite_key": "string|null",
"course_id": "int|null",
"master_key": "string",
"notes": "string|null"
},
"risk_level": "low|medium|high"
}
],
"reply_draft": "string"
}
Rules:
-
course_id must be numeric if present.
-
email must be present for user-specific actions.
-
If missing info, put it in clarifying_questions and keep actions minimal.
6) Admin UI Requirements
Create WP-Admin menu: AltusPlatform AI Support
6.1 Pages
-
Inbox Requests (Queue)
-
Table view, paginated, filter by status/classification, search by email/subject.
-
Columns: Received, From, Subject, Classification, Status, Assigned To, Updated.
-
Clicking row opens “Request Detail”.
-
Request Detail
-
Show email body (sanitized), metadata
-
Show AI summary + recommended actions (render from ai_actions_json)
-
Controls:
-
Status dropdown
-
“Refine Request” textarea → re-run OpenAI with added guidance
-
“Approve & Execute Actions” button (nonce protected)
-
“Dry Run” mode checkbox (shows what WOULD change)
-
Execution log panel
-
Reply draft panel with “Copy” and optional “Send via Graph” (explicit confirmation)
-
-
Settings
-
Microsoft App config: client id/secret, tenant mode (common vs single tenant)
-
OpenAI config: key, model, safety toggles
-
Polling interval
-
Data retention: auto-delete closed requests after N days (optional)
-
Connected Accounts
-
List connected O365 accounts, status, last sync time
-
Connect/disconnect buttons
6.2 Roles / Access
-
Only WP superusers can access pages.
-
If multisite: require is_super_admin().
7) Action Executor (DB Operations)
7.1 Use Argus-Core DB Connections
Load altus-core/config.php. Use $wpdb or mysqli consistently (prefer $wpdb).
You will need two DB handles:
-
WP DB: normal $wpdb
-
ACC DB: connect using credentials in Argus-Core config OR use existing patterns in your codebase.
7.2 Supported Actions and DB Implementation
A) Create User (WP + ACC Contact)
-
WP user:
-
wp_create_user() with secure random password
-
set role based on business rule (default subscriber)
-
ACC contact:
-
Insert into acc_contacts (in $acc_server_database) with master_key
-
Insert meta into acc_contactsmeta as needed
Must:
-
De-dupe by email
-
If user exists: do not recreate; link/return IDs
B) Verify Member to Minisite
-
Lookup minisite in acc_keys using minisite_key
-
Insert/update ae_verified_members row tying:
-
contact_id
-
minisite/master_key fields as defined in existing schema
-
C) Enroll User into Course
-
Insert into ae_enrollments:
-
master_key, blog_master_key, contact_id, course_id, enrolled=1, timestamp
-
-
Prevent duplicates (unique check on contact_id+course_id+blog_master_key)
D) Check Enrollment/Completion
-
Query ae_enrollments for contact_id + course_id
-
Return status summary to UI and to reply draft
E) Reset Post-Test Attempts
-
In ae_test_attempts:
-
Identify rows by contact_id + course_id (and optionally quiz/test id)
-
Either delete attempts or set attempt counters based on existing conventions
-
-
Record an audit note in execution_log with before/after counts
7.3 Execution Safety Rules
-
All actions:
-
Validate email format
-
Validate course_id integer
-
Validate user exists or can be created
-
Validate master_key matches current site context
-
-
Add “dry run” path that only simulates queries and logs intended changes.
8) Workflow State Machine
-
New email → request created with:
-
status=open
-
classification=unknown until AI runs
-
-
AI triage runs:
-
If classification=platform_request: remain open
-
If not: set status=not_platform_request
-
-
Human sets in_process when working
-
On approve/execute success:
-
set status=closed
-
store execution_log + reply_draft
-
9) Refinement Loop
On Request Detail page:
-
Staff enters refinement notes (“Be specific…”).
-
Plugin calls OpenAI again with:
-
original email
-
previous AI JSON
-
refinement notes
-
-
Replace ai_actions_json + reply_draft if new output validates.
10) Suggested Reply Draft
-
Always generate a reply draft from OpenAI.
-
UI shows it as editable (WYSIWYG not required; plaintext ok).
-
Optional: “Send via Graph” button:
-
Requires Mail.Send
-
Must show a final confirmation modal
-
Sends reply referencing original message (Graph createReply + send)
-
If you do NOT implement sending:
-
Provide “Copy to clipboard” and “Download .txt”.
11) Observability / Logging
-
Every cron run logs:
-
accounts polled, new messages found, failures
-
-
Every action execution logs:
-
who approved (wp_user_id)
-
timestamp
-
before/after counts (where applicable)
-
SQL errors (sanitized)
-
12) Deliverables / Acceptance Tests
Codex must deliver:
-
Plugin activates and creates tables
-
Superuser can connect O365 account and see it listed
-
Cron pulls emails and creates request rows
-
Request Queue shows items with pagination and filters
-
OpenAI triage runs and produces validated JSON
-
Request Detail shows recommended actions
-
“Dry run” shows planned changes
-
“Approve & Execute” performs DB updates safely:
-
create user (WP + acc_contacts)
-
enroll user (ae_enrollments)
-
reset attempts (ae_test_attempts)
-
-
Reply draft is produced and stored
-
All admin interactions are nonce protected + capability protected
13) Implementation Notes (Don’t Skip)
-
Use encryption for tokens:
-
openssl_encrypt() with key derived from AUTH_KEY/SECURE_AUTH_KEY
-
Store IV + ciphertext (base64)
-
-
Do not autoload large options.
-
Do not store raw HTML email; store plaintext.
-
Add a “Disconnect” button that revokes local tokens and marks account revoked.
NEXT: Build Focus Area — Reset Post-Test Attempts
Codex should implement “reset_test_attempts” first end-to-end:
-
Email → AI → action plan → approve → DB update → reply draft
Then expand to other action types.
If you want, I can also generate the exact Codex prompt for Phase 1 (scaffold + DB tables + admin pages + OAuth connect flow), and a Phase 2 prompt (OpenAI triage + action executor with dry run + reset_test_attempts).
