Quorentra

Quorentra Safe CRM Mutations from ChatGPT: Building from Zero — Part 18

Series: Building Quorentra CRM from Zero — A Modular, ChatGPT-Native AI CRM

Building the first governed CRM write operation with opportunity stage updates, explicit confirmation, RBAC, optimistic concurrency, idempotency, audit events, and authoritative post-mutation results.

Quorentra Safe CRM Mutations from ChatGPT - Building from Zero — Part 18
Quorentra Safe CRM Mutations from ChatGPT – Building from Zero — Part 18

1. Introduction

In Part 17, Quorentra became interactive inside ChatGPT.

A user could ask:

Show my EUR pipeline.

Then navigate:

Pipeline
↓
View Opportunities
↓
Filter by Stage
↓
Opportunity List
↓
Opportunity Detail

The embedded Quorentra component could initiate governed MCP tool calls such as:

list_opportunities
list_opportunities_by_stage
get_opportunity

That gave us a useful CRM workspace inside ChatGPT.

But every capability remained read-only.

The user could inspect CRM state.

The user could not change it.

Part 18 crosses that boundary.

For the first time, we will allow a user to say:

Move the Microsoft 365 Migration opportunity to negotiation.

and have Quorentra safely update the authoritative CRM record.

But we will not simply give ChatGPT unrestricted database-changing tools.

Instead, we will build a governed mutation pipeline:

User Intent
↓
Entity Resolution
↓
Read Current State
↓
Authorization
↓
Validate Proposed Change
↓
Present Confirmation
↓
User Confirms
↓
Execute Mutation
↓
Audit
↓
Return Authoritative Result
↓
Refresh UI

This distinction is fundamental.

ChatGPT may interpret what the user wants.

Quorentra decides whether and how that change is allowed.


2. What Are We Building?

Our first mutation will be deliberately narrow:

update_opportunity_stage

The workflow begins with:

Move the Microsoft 365 Migration opportunity to negotiation.

ChatGPT identifies the relevant Opportunity.

Quorentra retrieves its current state:

Opportunity:
Microsoft 365 Migration
Company:
Contoso
Current Stage:
Proposal
Requested Stage:
Negotiation

Before anything changes, the user sees:

┌────────────────────────────────────────────┐
│ QUORENTRA │
│ Update Opportunity │
│ │
│ Microsoft 365 Migration │
│ Contoso │
│ │
│ Stage │
│ │
│ Proposal │
│ ↓ │
│ Negotiation │
│ │
│ This will update the CRM record. │
│ │
│ [Cancel] [Confirm Update] │
└────────────────────────────────────────────┘

Only:

Confirm Update

executes the mutation.


3. Why Opportunity Stage First?

We could begin with:

Create Company
Create Contact
Create Opportunity
Edit Amount
Delete Opportunity
Mark Opportunity Won

But changing an Opportunity stage is a much better first write operation.

It changes:

one entity
one field

from:

one controlled value

to:

another controlled value

For example:

proposal
↓
negotiation

That gives us a mutation that is:

Easy to understand
Easy to validate
Easy to authorize
Easy to confirm
Easy to audit
Easy to test
Easy to reverse manually

It is ideal for establishing the Quorentra mutation architecture.


4. The Mutation Boundary

Until Part 17, our architecture was primarily:

User
↓
ChatGPT
↓
Read Tool
↓
Quorentra
↓
CRM Data

Part 18 introduces:

User
↓
ChatGPT
↓
Mutation Intent
↓
Quorentra
↓
CRM State Changes

This deserves a much stronger security model.

A read mistake might show the wrong authorized record.

A mutation mistake can change business state.

That difference matters.


5. Read Tools and Write Tools Are Not Equivalent

A read tool such as:

get_opportunity

asks:

What is the current state?

A write tool such as:

update_opportunity_stage

asks:

Change the current state.

Therefore write tools require additional controls.

Our mutation architecture will introduce:

Explicit write permissions
Strict schemas
Current-state validation
Concurrency protection
Confirmation
Idempotency
Transactions
Audit logging
Post-write verification

6. Our Core Principle

From this point onward, Quorentra follows this rule:

AI interpretation never equals mutation authority.

ChatGPT may conclude:

The user wants Opportunity X
moved to Negotiation.

That does not mean the database changes immediately.

It means Quorentra has received a proposed action.


7. Proposed Action Versus Executed Action

We distinguish:

Proposed Mutation

from:

Executed Mutation

A proposed mutation says:

Opportunity:
Microsoft 365 Migration
Current:
Proposal
Requested:
Negotiation

An executed mutation means:

PostgreSQL now stores:
stage = negotiation

These are different states.

That distinction is central to safe AI-assisted software.


8. The Full Part 18 Flow

Our target architecture is:

User
│
│ "Move Microsoft 365 Migration
│ to negotiation."
▼
ChatGPT
│
▼
get_opportunity
│
▼
Quorentra
│
▼
Current State
│
▼
Prepare Mutation
│
▼
Confirmation UI
│
│ user clicks
│ Confirm Update
▼
update_opportunity_stage
│
▼
Authentication
│
▼
TenantContext
│
▼
RBAC
│
▼
Current-State Check
│
▼
Transition Validation
│
▼
Concurrency Check
│
▼
Database Transaction
│
├── Update Opportunity
│
└── Write Audit Event
│
▼
Commit
│
▼
Updated Opportunity
│
▼
Widget Refresh
│
▼
ChatGPT Confirmation

Every layer has a clear responsibility.


9. Starting Checkpoint

Before changing anything, verify Part 17.

From:

quorentra/chatgpt-ui

run:

npm run build

Then:

cd ..\backend
python -m pytest

Start Quorentra.

Start the MCP server.

Then verify:

Show my EUR pipeline.

Select:

View Opportunities

Open:

Microsoft 365 Migration

Confirm the Opportunity Detail view works.

Only then introduce mutation capabilities.


10. Define the Permission

Part 17 relied on:

opportunities.read

Part 18 requires:

opportunities.update

Do not treat:

opportunities.read

as sufficient.

The distinction must exist in the authorization layer.


11. Example Role Matrix

Conceptually:

RoleRead OpportunitiesUpdate Opportunities
Viewer✓—
Member✓✓
Manager✓✓
Admin✓✓
Owner✓✓

The exact role model can evolve.

The important point is:

read permission
≠
write permission

12. The Mutation Tool

Introduce:

update_opportunity_stage

Its contract should remain narrow.

Conceptually:

Name:
update_opportunity_stage
Purpose:
Change the stage of one Opportunity.
Permission:
opportunities.update
Mutation:
Yes
Scope:
Active authenticated organization

Avoid creating:

update_opportunity

with dozens of optional fields as our first write tool.


13. Why Narrow Mutation Tools?

Compare:

{
"opportunity_id": "...",
"stage": "negotiation"
}

with:

{
"opportunity_id": "...",
"name": "...",
"company_id": "...",
"amount": "...",
"currency": "...",
"stage": "...",
"probability": "...",
"expected_close_date": "...",
"owner_id": "...",
"description": "..."
}

The first contract has a much smaller mutation surface.

That makes it easier to:

Understand
Authorize
Validate
Confirm
Audit
Test

14. Initial Input Contract

At first glance, we might define:

class UpdateOpportunityStageInput(BaseModel):
opportunity_id: UUID
stage: OpportunityStage

But this is not enough.

We also need stale-state protection.


15. The Stale-State Problem

Suppose ChatGPT retrieves:

Current Stage:
Proposal

Then another salesperson changes the Opportunity to:

Negotiation

before our user confirms.

Our confirmation screen still says:

Proposal → Negotiation

but that is no longer the current state.

We need to detect this.


16. Expected Current State

Add:

expected_current_stage

to the mutation request.

Conceptually:

class UpdateOpportunityStageInput(BaseModel):
opportunity_id: UUID
expected_current_stage: OpportunityStage
new_stage: OpportunityStage

The request becomes:

{
"opportunity_id": "...",
"expected_current_stage": "proposal",
"new_stage": "negotiation"
}

17. Compare-and-Set Semantics

The server now performs:

Update Opportunity
only if
current stage = expected stage

Conceptually:

Expected:
proposal
Database:
proposal
→ proceed

But:

Expected:
proposal
Database:
negotiation
→ reject as stale

This prevents blindly overwriting newer state.


18. Optimistic Concurrency

This is a simple form of:

optimistic concurrency control

We assume concurrent changes are relatively uncommon.

We do not lock the record while the user considers the confirmation.

Instead, we verify that the state is still what we expected at execution time.


19. A More General Version Field

Longer term, we may add:

version

to mutable CRM entities.

For example:

Opportunity
version = 7

The mutation request can then say:

{
"opportunity_id": "...",
"expected_version": 7,
"new_stage": "negotiation"
}

The database updates only if:

version = 7

and increments it to:

8

This scales better as mutations become more complex.


20. Which Approach Should the MVP Use?

For the first mutation, we can use:

expected_current_stage

because it makes the concept easy to understand.

However, introducing an integer:

version

now is a strong architectural improvement.

For a CRM intended to support:

Multiple users
ChatGPT
Widgets
Automations
Future agents

optimistic record versioning is worth establishing early.


21. Add version to Opportunity

Conceptually:

version: Mapped[int] = mapped_column(
Integer,
nullable=False,
default=1,
)

Every successful mutation increments:

version = version + 1

This gives us a general concurrency mechanism.


22. Create the Migration

Generate:

alembic revision --autogenerate -m "add opportunity version"

Review the generated migration.

Then:

alembic upgrade head

Existing Opportunities should receive:

version = 1

or an equivalent safe migration default.


23. Update Opportunity Schemas

Opportunity responses should now include:

version

For example:

{
"id": "...",
"name": "Microsoft 365 Migration",
"stage": "proposal",
"version": 1
}

The UI can carry this version into a future mutation request.


24. Mutation Input With Version

Our final input becomes:

class UpdateOpportunityStageInput(BaseModel):
opportunity_id: UUID
expected_version: int
expected_current_stage: OpportunityStage
new_stage: OpportunityStage
idempotency_key: UUID

Now we have protection against:

Stale state
Duplicate execution

25. Why Both Version and Current Stage?

The version provides strong concurrency protection.

The expected stage provides semantic validation and better diagnostics.

For example:

Expected version:
7
Current version:
8

tells us the record changed.

Meanwhile:

Expected stage:
proposal
Current stage:
negotiation

helps us explain what changed.


26. Idempotency

Another mutation problem is duplicate execution.

Suppose the user clicks:

Confirm Update

once.

The network response is delayed.

The user clicks again.

Without protection, the same logical action could execute twice.

For a stage update, the result may happen to be harmless.

For future actions such as:

Create Task
Create Note
Create Opportunity
Send Email

duplicate execution could be serious.

So we introduce idempotency now.


27. Idempotency Key

Each proposed mutation receives a unique:

idempotency_key

For example:

9a17e0b5-...

The same proposed action always uses the same key.

If the request is retried, Quorentra recognizes it as the same logical mutation.


28. Never Generate a New Key on Retry

Incorrect:

Click
→ key A
Timeout
Retry
→ key B

Quorentra sees two independent operations.

Correct:

Proposed Mutation
→ key A
Confirm
→ key A
Timeout
Retry
→ key A

Now the server can safely recognize the retry.


29. Where Should the Key Be Generated?

The proposed-action layer should generate it before confirmation.

Conceptually:

prepare_opportunity_stage_update
↓
idempotency_key
↓
Confirmation UI
↓
Confirm
↓
update_opportunity_stage

This binds confirmation and execution to the same logical action.


30. Do We Need a Prepare Tool?

We could let ChatGPT construct the confirmation data itself.

But that creates ambiguity about:

Current authoritative state
Version
Allowed transition
Idempotency key

A stronger architecture introduces:

prepare_opportunity_stage_update

as a read-only validation capability.


31. The Prepare Tool

Conceptually:

prepare_opportunity_stage_update
Input:
opportunity_id
new_stage
Permission:
opportunities.update
Mutation:
No
Purpose:
Validate and prepare a proposed stage update.

It returns:

{
"opportunity_id": "...",
"opportunity_name": "Microsoft 365 Migration",
"company_name": "Contoso",
"current_stage": "proposal",
"new_stage": "negotiation",
"expected_version": 7,
"idempotency_key": "...",
"requires_confirmation": true
}

32. Why the Prepare Tool Is Valuable

The model says:

I think the user wants this change.

The prepare tool says:

Quorentra confirms this is the current
record and this proposed change is valid.

The execution tool says:

Quorentra has now performed the change.

These are three different stages.


33. The Three-Phase Mutation Model

Our architecture becomes:

Interpret
↓
Prepare
↓
Confirm
↓
Execute

More precisely:

ChatGPT
│
▼
Interpret User Intent
│
▼
prepare_opportunity_stage_update
│
▼
Validated Proposed Action
│
▼
Confirmation UI
│
▼
User Confirmation
│
▼
update_opportunity_stage
│
▼
Authoritative Result

This is a strong pattern we can reuse later.


34. Confirmation Is Not a Boolean From the Model

Do not allow ChatGPT to send:

{
"confirmed": true
}

and treat that as proof the user confirmed.

The confirmation must come from the appropriate trusted interaction flow.

The model should not be able to manufacture user confirmation.


35. Confirmation Token

A stronger design can bind the prepared action to execution using a server-generated:

confirmation_token

or prepared-action identifier.

For example:

prepared_action_id

The confirmation UI receives it.

The execution request references it.

This avoids trusting client-reconstructed mutation details.


36. Prepared Mutation Record

Conceptually, Quorentra could persist:

PreparedMutation
├── id
├── organization_id
├── user_id
├── mutation_type
├── entity_type
├── entity_id
├── expected_version
├── old_value
├── proposed_value
├── idempotency_key
├── expires_at
├── executed_at
└── created_at

This is more infrastructure than our first mutation strictly requires.

But it creates a robust foundation.


37. MVP Choice

For Part 18, we will introduce a lightweight persisted:

MutationRequest

because it gives us:

Trusted confirmation binding
Idempotency
Expiry
Auditability
Concurrency metadata

in one place.

This is worth the additional table.


38. Create mutation_requests

Conceptually:

mutation_requests
├── id
├── organization_id
├── user_id
├── mutation_type
├── entity_type
├── entity_id
├── expected_version
├── old_value
├── proposed_value
├── status
├── idempotency_key
├── expires_at
├── executed_at
├── created_at
└── updated_at

Possible statuses:

pending
executed
cancelled
expired
failed

39. Why Persist Pending Mutations?

Without persistence:

Confirmation UI

may be holding the only copy of the proposed action.

That makes the browser too authoritative.

With persistence:

Quorentra

knows exactly what action was prepared.

The component only references:

mutation_request_id

when confirming.

That is much safer.


40. Mutation Request Ownership

Every pending mutation belongs to:

organization_id
user_id

Execution must verify both.

A MutationRequest prepared by User A must not automatically be executable by User B.

Likewise, a request from Tenant A must never execute inside Tenant B.


41. Mutation Expiry

A confirmation should not remain valid indefinitely.

For example:

expires_at =
created_at + 10 minutes

If the user returns tomorrow and clicks an old confirmation card:

Mutation request expired.

Quorentra should require a new preparation step.

This reduces stale-action risk.


42. Why Ten Minutes?

Ten minutes is not a universal rule.

It is simply a reasonable MVP starting point for an interactive confirmation.

The important principle is:

confirmation has bounded lifetime

We can make this configurable later.


43. Mutation Audit Versus Mutation Request

These are related but different.

A:

MutationRequest

represents:

what was proposed

An:

AuditEvent

records:

what actually happened

We should not confuse the two.


44. Create an Audit Event Model

Conceptually:

audit_events
├── id
├── organization_id
├── actor_user_id
├── action
├── entity_type
├── entity_id
├── mutation_request_id
├── old_values
├── new_values
├── invocation_source
├── created_at
└── metadata

For our first mutation:

action =
opportunity.stage.updated

45. Example Audit Event

Conceptually:

{
"action": "opportunity.stage.updated",
"entity_type": "opportunity",
"entity_id": "...",
"old_values": {
"stage": "proposal"
},
"new_values": {
"stage": "negotiation"
},
"invocation_source": "chatgpt_widget"
}

The event records business-relevant facts.


46. Do Not Log Secrets

Audit events should not become dumping grounds for:

JWTs
Access tokens
Authorization headers
Passwords
API keys
Raw secrets

Audit what changed.

Do not log credentials.


47. Database Transaction Boundary

The Opportunity update and AuditEvent creation should occur in the same database transaction.

Conceptually:

BEGIN
verify mutation request
verify version
update opportunity
increment version
insert audit event
mark mutation request executed
COMMIT

If audit creation fails:

ROLLBACK

The CRM should not silently change without its required audit record.


48. Mutation Service

Create a dedicated application service.

For example:

app/services/opportunity_mutation_service.py

This service owns the mutation workflow.

Avoid putting all mutation logic inside:

MCP tool handler

or:

REST endpoint

The service should be reusable.


49. Service Boundary

Conceptually:

MCP
│
▼
OpportunityMutationService
▲
│
REST

Both interfaces can eventually reuse the same governed write logic.

Again:

interface
≠
business logic

50. Prepare Method

Conceptually:

prepare_stage_update(
actor,
opportunity_id,
new_stage,
)

should:

Resolve active tenant
Check opportunities.update
Load Opportunity tenant-safely
Validate requested stage
Validate transition
Create MutationRequest
Return proposed action

It does not update the Opportunity.


51. Execute Method

Conceptually:

execute_stage_update(
actor,
mutation_request_id,
)

should:

Load MutationRequest tenant-safely
Verify user ownership
Verify status = pending
Verify not expired
Load Opportunity
Verify current version
Verify current stage
Revalidate transition
Update stage
Increment version
Write AuditEvent
Mark MutationRequest executed
Commit
Return updated Opportunity

Notice the repeated validation.

That is intentional.


52. Validate Again at Execution

Never assume:

It was valid when prepared,
therefore it is valid now.

Between prepare and execute:

Record may change
Permission may change
Membership may change
Business rules may change
Request may expire

Therefore execution revalidates.


53. Stage Transition Rules

Should any stage be allowed to move to any other stage?

For the MVP, we should make this explicit.

Our stages are:

qualification
discovery
proposal
negotiation
won
lost

We can define a transition policy.


54. Example Transition Policy

A simple initial policy could allow:

qualification
→ discovery
→ proposal
→ negotiation
→ won

with:

qualification
discovery
proposal
negotiation

also able to transition to:

lost

We may additionally allow backward movement where real sales workflows require it.


55. Do Not Hard-Code Transition Logic in React

Avoid:

if (
currentStage === "proposal" &&
newStage === "negotiation"
) {
allow();
}

React may present available options.

But the server determines whether the transition is valid.

The domain layer remains authoritative.


56. Create a Stage Transition Policy

Conceptually:

ALLOWED_STAGE_TRANSITIONS = {
"qualification": {
"discovery",
"lost",
},
"discovery": {
"qualification",
"proposal",
"lost",
},
"proposal": {
"discovery",
"negotiation",
"lost",
},
"negotiation": {
"proposal",
"won",
"lost",
},
}

Whether Won/Lost can be reopened should be a deliberate business decision.


57. Won and Lost Need Special Treatment

Closing an Opportunity can have more business significance than moving:

proposal → negotiation

For the first implementation, we may restrict the first ChatGPT mutation to open-stage transitions.

That means:

won
lost

remain unavailable through this tool initially.

Later we can create:

close_opportunity_won
close_opportunity_lost

with stronger workflows.


58. Narrow Tools Again

This gives us:

update_opportunity_stage

for normal pipeline movement.

Later:

close_opportunity_won
close_opportunity_lost

can capture additional data such as:

actual close date
loss reason
competitor
final value

Specific business capabilities are better than generic record mutation.


59. Prepare Tool Result

For:

proposal → negotiation

the prepare tool returns:

{
"mutation_request_id": "...",
"opportunity": {
"id": "...",
"name": "Microsoft 365 Migration",
"company_name": "Contoso"
},
"change": {
"field": "stage",
"old_value": "proposal",
"new_value": "negotiation"
},
"expires_at": "2026-08-02T10:10:00Z",
"requires_confirmation": true
}

This is ideal structured input for the confirmation component.


60. Build the Confirmation UI

Create:

chatgpt-ui/src/mutations/
├── OpportunityStageConfirmation.tsx
├── MutationResult.tsx
└── mutations.css

The confirmation view displays:

Opportunity
Company
Current Stage
Requested Stage
Warning that CRM data will change
Confirm
Cancel

Nothing more is required.


61. Confirmation Component

Conceptually:

<OpportunityStageConfirmation
opportunityName="Microsoft 365 Migration"
companyName="Contoso"
currentStage="proposal"
newStage="negotiation"
onConfirm={handleConfirm}
onCancel={handleCancel}
/>

The component does not receive:

organization_id
user_id

because those remain server-side concerns.


62. Confirmation Language

Use explicit wording:

This will update the CRM record.

Avoid vague wording such as:

Continue?

The user should understand what will happen.


63. Show the Exact Change

The most important information is:

Proposal
↓
Negotiation

The confirmation should make the before/after state obvious.

This reduces accidental mutations.


64. Confirm Button

Use a clear action label:

Confirm Update

rather than:

OK

The button describes the action.


65. Cancel Button

Cancel should:

not call the mutation tool

and should return the user to the Opportunity Detail view.

Optionally, Quorentra can mark the MutationRequest:

cancelled

for auditability.


66. Should Cancellation Be Persisted?

Because we already persist MutationRequest, marking:

status = cancelled

is useful.

It tells us:

The action was prepared
but deliberately not executed.

This can later help understand user behavior and confirmation friction.


67. Confirm Handler

Conceptually:

async function handleConfirm() {
setLoading(true);
setError(null);
try {
const result =
await callMcpTool<MutationResult>(
"update_opportunity_stage",
{
mutation_request_id:
mutationRequest.id,
}
);
setMutationResult(result);
} catch (error) {
setError(
normalizeMutationError(error)
);
} finally {
setLoading(false);
}
}

Notice how little information the client sends.


68. Why Only mutation_request_id?

The browser does not resend:

old stage
new stage
version
tenant
user

The server already stored the prepared action.

This prevents the component from modifying the proposed mutation between:

Prepare

and:

Execute

That is a major security improvement.


69. Do Not Trust Hidden Form Fields

A common web mistake is assuming hidden UI values are trustworthy.

For example:

<input
type="hidden"
name="new_stage"
value="negotiation"
/>

is still client-controlled data.

Persisted server-side MutationRequest state is stronger.


70. Execution Authorization

When:

update_opportunity_stage

runs, check:

authenticated user
active organization
mutation request organization
mutation request user
opportunities.update
request status
request expiry
entity tenant ownership
entity version
current stage
transition validity

Only then execute.


71. Permission Can Change

Suppose a Manager prepares the update.

Before clicking Confirm, an administrator changes the user’s role to Viewer.

Execution must fail.

The fact that permission existed during preparation does not grant permanent write authority.

Authorization is checked again at execution.


72. Membership Can Change

Likewise, if the user is removed from the organization after preparation:

Confirm Update

must fail.

A pending MutationRequest is not a permanent capability token.


73. Stale Record Example

Prepared:

Microsoft 365 Migration
Proposal → Negotiation
Version 7

Before confirmation, another user changes:

Proposal → Discovery
Version 8

Our execution detects:

expected_version = 7
current_version = 8

and rejects the mutation.


74. User-Facing Stale Error

Do not show:

409 OCC_VERSION_MISMATCH

as the primary UI.

Show:

This opportunity changed after the update
was prepared.
Current stage: Discovery
Review the latest information before
trying again.

Then offer:

[Review Opportunity]

75. Why Not Automatically Retry?

Because automatically retrying could change the meaning.

The user confirmed:

Proposal → Negotiation

They did not necessarily confirm:

Discovery → Negotiation

A stale mutation requires renewed user review.


76. Idempotent Execution

Suppose the first execution succeeds:

Proposal → Negotiation

but the response is lost.

The UI retries with the same:

mutation_request_id

Quorentra sees:

status = executed

and returns the original successful result.

It does not execute a second mutation.


77. Store Execution Result

To support this, the MutationRequest can retain:

result_snapshot

or enough metadata to reconstruct the successful result.

For the MVP, storing:

executed_at
result_version

may be sufficient.

The important property is deterministic retry behavior.


78. Transaction Example

Conceptually:

async with session.begin():
request = load_mutation_request(...)
validate_request(request)
opportunity = load_opportunity_for_update(...)
validate_version(opportunity, request)
old_stage = opportunity.stage
opportunity.stage = request.proposed_value
opportunity.version += 1
audit_event = AuditEvent(
action="opportunity.stage.updated",
old_values={"stage": old_stage},
new_values={
"stage": opportunity.stage
},
)
session.add(audit_event)
request.status = "executed"
request.executed_at = utcnow()

All state changes commit together.


79. Row-Level Concurrency

The actual database update should be designed to avoid a race between:

version check

and:

update

A strong pattern is an atomic conditional update:

UPDATE opportunities
SET
stage = :new_stage,
version = version + 1
WHERE
id = :id
AND organization_id = :organization_id
AND version = :expected_version

Then verify exactly one row changed.


80. Why Atomic Conditional Update?

Without it:

Read version 7
↓
Another transaction writes version 8
↓
Our transaction writes anyway

can still happen under some patterns.

The conditional update turns concurrency validation into part of the mutation itself.


81. Tenant Predicate Belongs in the Update

Notice:

organization_id = :organization_id

belongs directly in the mutation query.

Do not:

load by tenant
then update only by id

when a tenant predicate can be preserved throughout the operation.

Defense in depth remains important.


82. Post-Mutation Result

After successful execution, return the authoritative updated Opportunity.

For example:

{
"success": true,
"mutation_request_id": "...",
"opportunity": {
"id": "...",
"name": "Microsoft 365 Migration",
"company_name": "Contoso",
"stage": "negotiation",
"version": 8
},
"change": {
"old_value": "proposal",
"new_value": "negotiation"
}
}

The UI should render from this server result.


83. Do Not Optimistically Pretend Success

Avoid:

User clicks Confirm
↓
React immediately displays Negotiation
↓
Server call happens later

For authoritative CRM mutations, wait for the server result.

The UI can show:

Updating opportunity…

until Quorentra confirms success.


84. Mutation Success View

After execution:

┌────────────────────────────────────────────┐
│ QUORENTRA │
│ Opportunity Updated │
│ │
│ Microsoft 365 Migration │
│ Contoso │
│ │
│ Stage │
│ Proposal → Negotiation │
│ │
│ Update completed successfully. │
│ │
│ [View Opportunity] │
└────────────────────────────────────────────┘

The user gets explicit confirmation.


85. Refresh the Opportunity Detail

After success, replace the old Opportunity state with the authoritative returned record.

Do not leave:

Proposal

displayed in another part of the component.

The UI state must reconcile with the mutation result.


86. What About the Pipeline Summary?

Changing:

Proposal → Negotiation

does not change:

amount
probability

in our current model unless probability is automatically tied to stage.

Therefore the pipeline totals may remain unchanged.

But future stage rules could alter probability.

The safest approach is:

invalidate potentially affected cached views

after a mutation.


87. Simple MVP Cache Strategy

We do not need a sophisticated query cache.

After successful mutation:

mark pipeline as stale
mark opportunity list as stale

When the user returns to those views, reload them.

This is simple and reliable.


88. Do Not Build Complex Client Caching Yet

Avoid introducing:

Redux
React Query
Global normalized entity cache
Complex invalidation graph

for three views.

Simple explicit refresh logic is enough.

Again:

complexity should follow need.


89. Model-Initiated Versus Widget-Initiated Mutation

The proposed action may originate from:

ChatGPT conversation

or:

widget interaction

For example:

Conversation:

Move this to negotiation.

or UI:

[Move to Negotiation]

Both should ultimately use the same:

prepare
confirm
execute

pipeline.


90. One Mutation Architecture

Do not create:

ChatGPT mutation logic

and separate:

Widget mutation logic

Both should call:

OpportunityMutationService

The interface may differ.

The authority path should not.


91. Invocation Source

Audit events should record where the action originated.

For example:

chatgpt_model
chatgpt_widget
rest_api

Later:

automation
agent
integration

may be added.

This becomes valuable governance metadata.


92. User Is Still the Actor

Even if ChatGPT interpreted the command, the business actor remains the authenticated user.

Therefore:

actor_user_id

should identify the user.

The invocation source can separately say:

chatgpt_model

This distinction matters.


93. AI Is Not the Tenant

Never create a fictional:

ChatGPT organization

or use the model as the tenant identity.

The tenant remains the user’s active Quorentra organization.

The model is an interface/orchestration layer.


94. Mutation Tool Metadata

The MCP tool should clearly indicate that it changes state according to the current SDK’s mutation/read-only annotations.

Conceptually:

readOnlyHint = false

and appropriate destructive/idempotency annotations where supported.

Tool metadata helps the host reason about the capability.

But metadata does not replace backend enforcement.


95. Tool Description

A strong tool description might be:

Execute a previously prepared and confirmed
Quorentra Opportunity stage update.
This tool changes CRM data.
The mutation request must belong to the
authenticated user and active organization,
must be pending and unexpired, and all
authorization and concurrency checks are
performed server-side.

The description should make the side effect explicit.


96. Do Not Let the Execution Tool Accept Arbitrary Stage Data

Because we persist MutationRequest, execution needs only:

{
"mutation_request_id": "..."
}

That is much safer than:

{
"opportunity_id": "...",
"new_stage": "negotiation",
"confirmed": true
}

The latter trusts too much client-controlled state.


97. REST Parity

Even though this series is ChatGPT-native, the mutation service should support REST later.

For example:

POST /api/v1/opportunities/{id}/stage-change-requests

and:

POST /api/v1/mutation-requests/{id}/execute

could reuse the same application service.

We do not need to build every REST route in Part 18 if it distracts from the milestone.

But the architecture should allow it.


98. Audit Retrieval

We should not yet build a full audit UI.

But we should be able to inspect:

audit_events

during testing.

For example:

Opportunity:
Microsoft 365 Migration
Action:
opportunity.stage.updated
Actor:
User X
Old:
proposal
New:
negotiation
Source:
chatgpt_widget

This proves governance works.


99. Prepare Tests

Test:

valid stage transition creates pending request
invalid transition fails
wrong tenant fails
missing opportunity fails
viewer fails
member succeeds
request stores current version
request stores old stage
request stores proposed stage
request has expiry

The Opportunity itself must remain unchanged after preparation.


100. Confirmation Tests

Verify:

Cancel does not update Opportunity
Cancel marks request cancelled
Cancelled request cannot execute
Expired request cannot execute

A confirmation workflow is only trustworthy if cancellation is real.


101. Execution Tests

Test:

valid pending request executes
Opportunity stage changes
version increments
audit event is created
request becomes executed
executed_at is populated
authoritative updated Opportunity is returned

These are the core success-path tests.


102. Permission Tests

Viewer:

prepare → denied
execute → denied

Member with:

opportunities.update

can proceed.

If permission is removed between prepare and execute:

execute → denied

This test is particularly important.


103. Tenant Isolation Tests

Create:

Tenant A
Opportunity A
Tenant B
Opportunity B

Tenant A must not:

prepare mutation for Opportunity B
execute MutationRequest from Tenant B
read MutationRequest from Tenant B

All three boundaries need tests.


104. Mutation Request Ownership Test

Create a pending request as:

User A

within Tenant A.

Attempt execution as:

User B

within the same tenant.

Our initial policy should reject this.

Later we may deliberately support approval workflows where another authorized user can approve an action.

But that is not the MVP.


105. Expiry Test

Create a request whose:

expires_at

is in the past.

Execution must return:

expired

and must not change the Opportunity.


106. Concurrency Test

Prepare:

Proposal → Negotiation
Version 7

Then simulate another update:

Proposal → Discovery
Version 8

Now execute the prepared request.

Expected:

stale mutation

The Opportunity remains:

Discovery

107. Idempotency Test

Execute a valid request.

Expected:

Proposal → Negotiation
Version 8

Execute the same request again.

Expected:

same successful logical result

not:

Version 9

The second call must not produce another business mutation.


108. Audit Idempotency Test

Likewise, retrying an already executed request must not create a duplicate:

opportunity.stage.updated

AuditEvent.

One logical mutation should produce one mutation audit event.


109. Transaction Rollback Test

Simulate an AuditEvent persistence failure.

Expected:

Opportunity update rolls back
MutationRequest remains unexecuted

We should never end up with:

CRM changed
Audit missing

for a mutation requiring audit.


110. UI Tests

Frontend tests should verify:

confirmation shows exact Opportunity
confirmation shows Company
old stage renders
new stage renders
Confirm button works
Cancel works
loading disables duplicate confirmation
success state renders
stale state renders
permission error renders
expired state renders

111. End-to-End Scenario

Seed:

Contoso
Microsoft 365 Migration
Stage: Proposal
Version: 7

Then ask:

Move the Microsoft 365 Migration opportunity to negotiation.

Expected:

ChatGPT resolves Opportunity
↓
prepare_opportunity_stage_update
↓
Confirmation UI

The database must still contain:

stage = proposal

at this point.


112. Confirm the Update

Click:

Confirm Update

Expected:

update_opportunity_stage
↓
OpportunityMutationService
↓
Database Transaction
↓
AuditEvent
↓
Updated Opportunity

Now PostgreSQL contains:

stage = negotiation
version = 8

113. Verify the Audit Event

Expected:

action:
opportunity.stage.updated
old:
proposal
new:
negotiation
actor:
authenticated user
organization:
active tenant
source:
chatgpt_model or chatgpt_widget

depending on the interaction path.


114. Verify Through Read Tools

Now call:

get_opportunity

Expected:

stage = negotiation

Then:

list_opportunities_by_stage(
stage = "negotiation"
)

must include the Opportunity.

And:

list_opportunities_by_stage(
stage = "proposal"
)

must not.

This verifies consistency across interfaces.


115. ChatGPT Response

After successful execution, ChatGPT can say:

Microsoft 365 Migration for Contoso has been
moved from Proposal to Negotiation.

The statement is grounded in the authoritative post-mutation result.

ChatGPT should not announce success before Quorentra returns success.


116. Failure Response

If the mutation fails because the record changed:

The opportunity changed before the update
could be applied. It is currently in Discovery,
so the Proposal → Negotiation confirmation is
no longer valid.

This is much better than silently forcing the old action.


117. Never Hide Mutation Failure

A conversational system can be tempted to smooth over errors.

Do not do that for business mutations.

If the CRM was not changed, say clearly that it was not changed.

Accuracy matters more than conversational smoothness.


118. Mutation Observability

Log:

mutation_request_id
tool_name
actor_user_id
organization_id
entity_type
entity_id
invocation_source
result
duration_ms

Avoid logging full sensitive payloads unnecessarily.

This gives us operational traceability.


119. Useful Mutation Metrics

Later we can track:

prepared mutations
confirmed mutations
cancelled mutations
expired mutations
failed mutations
stale mutations
permission failures
execution latency

These metrics will help us evaluate whether the confirmation model is working well.


120. Confirmation Rate

For example:

100 prepared
82 confirmed
10 cancelled
8 expired

can reveal whether:

confirmation UI

is useful or overly burdensome.

This becomes product intelligence.


121. Do Not Remove Confirmation Based Only on Usage

If users confirm 99% of updates, that does not automatically mean confirmation is unnecessary.

Confirmation requirements should be based on:

Risk
Reversibility
Business impact
User expectations

not merely click-through rate.


122. Future Mutation Risk Classes

Later we can define:

Class 1 — Low Risk
Class 2 — Moderate Risk
Class 3 — High Risk

For example:

Add internal note
→ Class 1
Change opportunity stage
→ Class 2
Delete company
→ Class 3

Each class can have different governance.


123. Reversibility Matters

Changing:

Proposal → Negotiation

is relatively easy to reverse.

Deleting:

Company

may remove or affect:

Contacts
Opportunities
Activities
Tasks
Documents

Therefore mutation policy should consider reversibility.


124. External Side Effects Matter Even More

Later Quorentra may support:

Send Email
Schedule Meeting
Send Teams Message
Trigger Workflow
Create Invoice

These actions affect systems outside Quorentra.

They require even stronger governance.

Part 18 establishes the pattern we will build upon.


125. AI Agents Will Use the Same Boundary

Eventually, Quorentra may have AI agents that recommend or initiate actions.

For example:

Opportunity Agent:
"This deal has been in Proposal for 21 days.
Consider moving it to Negotiation after
customer confirmation."

The agent still should not bypass:

RBAC
Mutation policy
Validation
Audit

Agentic execution must use the same governed capabilities.


126. One Mutation Layer for Everyone

Our target architecture is:

ChatGPT
Widget
REST Client
Automation
Future AI Agent
External Integration
│
▼
Governed Mutation Service
│
├── Authentication
├── Tenant Isolation
├── RBAC
├── Validation
├── Concurrency
├── Idempotency
├── Audit
└── Transaction
│
▼
PostgreSQL

This is much stronger than implementing safety separately in every interface.


127. Project Structure

Our backend now grows to something like:

backend/app/
├── models/
│ ├── opportunity.py
│ ├── mutation_request.py
│ └── audit_event.py
│
├── schemas/
│ ├── opportunity.py
│ └── mutation.py
│
├── repositories/
│ ├── opportunity_repository.py
│ ├── mutation_request_repository.py
│ └── audit_repository.py
│
├── services/
│ ├── opportunity_service.py
│ └── opportunity_mutation_service.py
│
└── mcp/
└── tools/
└── opportunity_mutations.py

The frontend adds:

chatgpt-ui/src/
└── mutations/
├── OpportunityStageConfirmation.tsx
├── MutationResult.tsx
└── mutations.css

The mutation architecture remains modular.


128. Migration Strategy

Part 18 likely requires database migrations for:

Opportunity.version
mutation_requests
audit_events

Create them carefully.

For development, one migration is acceptable if all three changes belong to this milestone.

For a production system, smaller migrations may be preferable.

Always inspect generated Alembic migrations before applying them.


129. Database Constraints

Where appropriate, add constraints for:

MutationRequest.status
mutation type
entity type

But avoid duplicating complex domain rules entirely in SQL.

Database constraints protect structural integrity.

Application services protect business semantics.

Both layers have value.


130. Audit Records Should Be Append-Only

Ordinary application workflows should not casually update or delete AuditEvents.

Conceptually:

AuditEvent

is append-only.

Later, retention and privacy requirements may require controlled archival or deletion policies.

But normal CRM mutation code should not rewrite history.


131. Timestamp Discipline

Use consistent UTC timestamps for:

created_at
updated_at
expires_at
executed_at

Convert to local display formats only in the UI.

Do not store browser-local timestamps as authoritative mutation times.


132. Server Time Is Authoritative

The component should not decide:

this request has expired

based solely on browser time.

It may display a countdown.

But the server determines whether execution is still valid.

Client clocks are not authoritative.


133. Confirmation Countdown

Later, the UI could show:

Confirmation expires in 8 minutes.

But this is optional for the MVP.

A simple expiry error is sufficient.

Do not overbuild the first mutation interface.


134. Cancellation Flow

If the user clicks:

Cancel

the widget can invoke:

cancel_mutation_request

or simply abandon it and allow expiry.

Because we persist MutationRequest status, an explicit cancel capability is cleaner.

It remains a mutation of workflow state, not CRM business state.


135. Do We Need Confirmation for Cancellation?

No.

Cancelling a pending mutation prevents a CRM change.

It does not require another confirmation dialog.

Avoid confirmation loops.


136. Mutation Error Taxonomy

Introduce clear error types such as:

MUTATION_NOT_FOUND
MUTATION_EXPIRED
MUTATION_CANCELLED
MUTATION_ALREADY_EXECUTED
MUTATION_STALE
MUTATION_PERMISSION_DENIED
INVALID_STAGE_TRANSITION

The UI can map these to useful messages.


137. Why Stable Error Codes?

Do not make the UI depend on parsing:

"The opportunity was modified since..."

Instead:

code = MUTATION_STALE

is machine-stable.

The human-readable message can evolve independently.


138. Structured Mutation Errors

Conceptually:

{
"error": {
"code": "MUTATION_STALE",
"message": "The opportunity changed after the mutation was prepared.",
"details": {
"current_stage": "discovery"
}
}
}

Only expose safe details.


139. Retry Policy

Some failures are retryable:

Temporary network failure
Transient server failure

Some are not:

Permission denied
Expired request
Stale request
Invalid transition

The UI should distinguish them.

Do not show:

Try Again

when retrying the same action can never succeed.


140. Stale Mutation Recovery

For:

MUTATION_STALE

offer:

[Review Latest Opportunity]

Then reload:

get_opportunity

The user can decide what to do based on current state.


141. Permission Recovery

For:

MUTATION_PERMISSION_DENIED

show:

You do not have permission to update this opportunity.

Do not repeatedly retry.

The user may need an administrator to change their role.


142. Expiry Recovery

For:

MUTATION_EXPIRED

show:

This confirmation expired because the CRM
may have changed.
Prepare the update again to continue.

Then offer:

[Prepare Again]

This obtains fresh authoritative state.


143. Confirmation Cannot Be Reused for a Different Mutation

A MutationRequest for:

Proposal → Negotiation

cannot be used to execute:

Proposal → Lost

The server owns the proposed value.

The confirmation is bound to one exact action.


144. Confirmation Cannot Be Reused for Another Opportunity

Likewise:

MutationRequest A

for:

Microsoft 365 Migration

cannot mutate:

Azure Modernization

The entity ID is fixed server-side.


145. Confirmation Cannot Cross Tenants

Even if an attacker somehow obtains a MutationRequest UUID from another tenant:

execute

must fail because every lookup includes:

organization_id

Never treat UUID unpredictability as tenant security.


146. The Widget Does Not Decide Permissions

We may hide:

Move Stage

from a Viewer for better UX.

But that is not security.

The server must still reject the tool call if the Viewer somehow triggers it.

This distinction should remain explicit throughout Quorentra.


147. UI Capability Hints

Later, the backend can provide authorized capability hints such as:

{
"can_update_stage": true
}

to help the UI decide which controls to display.

But the execution service still rechecks permission.

Capability hints improve UX.

They do not grant authority.


148. ChatGPT Tool Selection

When the user says:

Move this to negotiation.

ChatGPT should not call:

update_opportunity_stage

immediately.

The intended sequence is:

resolve entity
↓
prepare_opportunity_stage_update
↓
confirmation
↓
update_opportunity_stage

Tool descriptions should reinforce this.


149. Execution Tool Should Reject Unprepared Actions

If the model somehow calls:

update_opportunity_stage

without a valid pending:

mutation_request_id

the server rejects it.

This is crucial.

Safety should not depend solely on the model choosing the expected tool sequence.


150. Backend Enforcement Beats Prompt Enforcement

We can instruct ChatGPT:

Always ask for confirmation.

That is useful.

But the stronger rule is:

The mutation cannot execute without a
valid prepared MutationRequest.

The backend makes the policy enforceable.


151. Confirmation Architecture Summary

The complete flow is now:

User Intent
│
▼
ChatGPT
│
▼
Resolve Opportunity
│
▼
prepare_opportunity_stage_update
│
▼
MutationRequest
status = pending
│
▼
Confirmation UI
│
┌──┴──────────────┐
│ │
▼ ▼
Cancel Confirm
│ │
▼ ▼
cancel execute
│ │
▼ ▼
cancelled Transaction
│
▼
Audit
│
▼
Success

This is the first genuinely governed AI-assisted CRM workflow in Quorentra.


152. Version Update

Part 18 adds the first controlled write capability.

Update:

app/core/constants.py

from:

APP_VERSION = "0.4.0"

to:

APP_VERSION = "0.5.0"

This is a significant milestone.

Quorentra can now safely modify CRM state from the ChatGPT experience.


153. Quorentra 0.5.0

Our MVP status becomes:

Platform
├── FastAPI ✓
├── PostgreSQL ✓
├── SQLAlchemy ✓
└── Alembic ✓
Identity
├── Organizations ✓
├── Users ✓
├── Memberships ✓
├── Authentication ✓
└── JWT ✓
Security
├── TenantContext ✓
├── Tenant Isolation ✓
├── RBAC ✓
├── Read Permissions ✓
└── Write Permissions ✓
CRM
├── Companies ✓
├── Contacts ✓
└── Opportunities ✓
Sales
├── Pipeline ✓
├── Opportunity Stages ✓
├── Probability ✓
└── Weighted Pipeline ✓
Interfaces
├── REST ✓
├── MCP ✓
└── ChatGPT ✓
ChatGPT UI
├── Pipeline Widget ✓
├── Opportunity List ✓
├── Opportunity Detail ✓
├── Widget Tool Calls ✓
└── Mutation Confirmation UI ✓
Mutation Governance
├── Prepare Mutation ✓
├── Explicit Confirmation ✓
├── Mutation Request ✓
├── Expiry ✓
├── Cancellation ✓
├── Optimistic Concurrency ✓
├── Idempotency ✓
├── Atomic Execution ✓
├── Audit Events ✓
├── Old/New Value Capture ✓
├── Invocation Source ✓
└── Post-Mutation Verification ✓
ChatGPT Write Operations
├── Update Opportunity Stage ✓
├── Create Company -
├── Create Contact -
├── Create Opportunity -
├── Edit Opportunity -
├── Close Opportunity -
└── Delete Records -
Activities -
Tasks -
AI Intelligence -

154. Acceptance Criteria

Part 18 is complete when:

✓ Part 17 regression suite remains green
✓ opportunities.update permission exists
✓ Viewer cannot update Opportunities
✓ authorized role can prepare updates
✓ Opportunity version exists
✓ existing records migrate safely
✓ version is returned by read models
✓ MutationRequest model exists
✓ AuditEvent model exists
✓ migrations apply successfully
✓ prepare_opportunity_stage_update exists
✓ prepare tool does not mutate CRM data
✓ current Opportunity is tenant-scoped
✓ current stage is captured
✓ expected version is captured
✓ proposed stage is validated
✓ pending request is created
✓ request has expiry
✓ request belongs to user and tenant
✓ confirmation UI exists
✓ exact Opportunity is displayed
✓ Company is displayed
✓ old stage is displayed
✓ new stage is displayed
✓ CRM side effect is clearly stated
✓ Confirm Update exists
✓ Cancel exists
✓ Cancel does not change Opportunity
✓ cancelled request cannot execute
✓ update_opportunity_stage exists
✓ execution accepts mutation_request_id
✓ arbitrary client stage cannot be substituted
✓ execution rechecks authentication
✓ execution rechecks tenant
✓ execution rechecks permission
✓ execution rechecks expiry
✓ execution rechecks request status
✓ execution rechecks Opportunity version
✓ execution rechecks current stage
✓ transition is revalidated
✓ update uses tenant predicate
✓ update uses concurrency predicate
✓ version increments exactly once
✓ Opportunity update is transactional
✓ AuditEvent is transactional
✓ MutationRequest execution state is transactional
✓ audit failure rolls back CRM mutation
✓ idempotent retry does not repeat mutation
✓ idempotent retry does not create duplicate audit event
✓ stale mutation is rejected
✓ stale mutation does not overwrite newer data
✓ stale UI explains what happened
✓ expired mutation is rejected
✓ permission change before execution is respected
✓ membership removal before execution is respected
✓ Tenant A cannot mutate Tenant B
✓ Tenant A cannot execute Tenant B MutationRequest
✓ User B cannot execute User A pending request
✓ authoritative updated Opportunity is returned
✓ UI waits for server success
✓ Opportunity Detail refreshes
✓ affected cached views are invalidated
✓ audit event records actor
✓ audit event records tenant
✓ audit event records entity
✓ audit event records old value
✓ audit event records new value
✓ audit event records invocation source
✓ audit log contains no credentials
✓ get_opportunity shows updated stage
✓ stage list queries show updated stage
✓ ChatGPT reports success only after server success
✓ Quorentra reports version 0.5.0

Most importantly:

A ChatGPT request can now result in a real CRM state change without allowing the model, widget, or client to bypass Quorentra’s authorization, validation, concurrency, confirmation, transaction, and audit boundaries.


155. What We Have Achieved

The Quorentra interaction model has evolved substantially.

Earlier:

User
↓
REST
↓
CRM

Then:

User
↓
ChatGPT
↓
MCP
↓
CRM

Then:

User
↓
ChatGPT
↓
Interactive UI
↓
MCP
↓
CRM

Now:

User Intent
↓
ChatGPT
↓
Governed Proposed Action
↓
Confirmation
↓
Authorized Mutation
↓
Audit
↓
CRM

This is the foundation of a trustworthy ChatGPT-native business application.


156. The Critical Separation

We now have three responsibilities:

ChatGPT
├── Understand language
├── Resolve intent
└── Orchestrate capabilities
Quorentra UI
├── Present CRM information
├── Collect explicit interaction
└── Present confirmation
Quorentra Core
├── Authenticate
├── Resolve tenant
├── Authorize
├── Validate
├── Control concurrency
├── Execute transactions
├── Audit
└── Persist authoritative state

None of these layers should take over the responsibilities of another.


157. ChatGPT Is Powerful Because It Does Less

The model does not need direct database access.

It does not need SQL.

It does not need to implement RBAC.

It does not need to understand database transactions.

It needs high-quality capabilities such as:

get_opportunity
prepare_opportunity_stage_update
update_opportunity_stage

Quorentra handles everything behind those boundaries.

This is a much safer way to build AI-native enterprise software.


158. The Next Logical Capability

Now that we can safely modify an existing record, the next step is creating new CRM records.

A particularly useful workflow is:

Create a new opportunity for Contoso.

This introduces several new challenges.

Unlike a stage update, record creation requires multiple fields.

For example:

Company
Opportunity Name
Amount
Currency
Stage
Probability
Expected Close Date

Some information may be missing from the user’s request.


159. Conversational Data Collection

Suppose the user says:

Create an opportunity for Contoso.

ChatGPT cannot safely invent:

Opportunity name
Amount
Currency
Close date

Instead, it needs to collect missing required information.

For example:

What should the opportunity be called?
What is the estimated value?
Which currency should I use?
What is the expected close date?

This introduces:

multi-turn mutation preparation

160. Structured Draft State

We will need a server-side representation of an incomplete proposed record.

Conceptually:

OpportunityDraft
├── company_id
├── name
├── amount
├── currency
├── stage
├── probability
├── expected_close_date
└── missing_fields

ChatGPT can help fill the draft.

Quorentra validates it.

Only a complete draft can become a prepared creation mutation.


161. AI Must Not Invent Required Business Facts

This will become another major principle:

Missing CRM facts should be requested, derived from authoritative data where appropriate, or explicitly defaulted by business policy — not silently invented by the model.

For example:

User:
"Create an opportunity for Contoso."

Quorentra should not randomly decide:

Amount = €100,000
Probability = 75%
Close Date = next month

unless those are explicit, documented business defaults.


162. Defaults Versus Guesses

A default is:

Stage = Qualification

because Quorentra business policy defines all new Opportunities that way.

A guess is:

Amount = €50,000

because the model thinks that sounds reasonable.

Defaults are deterministic business rules.

Guesses are not.

That distinction will matter in Part 19.


163. Creation Is More Complex Than Update

Our first update involved:

one known entity
one field
one old value
one new value

Creation involves:

entity resolution
required fields
optional fields
defaults
validation
duplicate considerations
confirmation
idempotency
transaction
audit

This is why it belongs in its own article.


164. Next Article

In Part 19, we will build:

Creating Opportunities from ChatGPT — Conversational Drafts, Validation, Confirmation, and Safe Record Creation

The target interaction will begin with:

User:
"Create a new opportunity for Contoso."

ChatGPT and Quorentra will collaboratively build a structured draft:

Company:
Contoso
Opportunity Name:
Microsoft Copilot Deployment
Amount:
€120,000
Stage:
Qualification
Probability:
20%
Expected Close:
30 November 2026

Before creation, Quorentra will present:

┌────────────────────────────────────────────┐
│ QUORENTRA │
│ Create Opportunity │
│ │
│ Company │
│ Contoso │
│ │
│ Opportunity │
│ Microsoft Copilot Deployment │
│ │
│ Value │
│ €120,000 │
│ │
│ Stage │
│ Qualification │
│ │
│ Probability │
│ 20% │
│ │
│ Expected Close │
│ 30 November 2026 │
│ │
│ This will create a new CRM record. │
│ │
│ [Cancel] [Create Opportunity] │
└────────────────────────────────────────────┘

Only after confirmation:

Create Opportunity
↓
Authentication
↓
TenantContext
↓
opportunities.create
↓
Draft Validation
↓
Company Validation
↓
Idempotency
↓
Database Transaction
↓
Create Opportunity
↓
Audit Event
↓
Commit
↓
Authoritative Opportunity
↓
ChatGPT + UI

Part 19 will introduce:

Opportunity creation permissions
Conversational draft state
Missing-field detection
Multi-turn information collection
Server-side business defaults
Draft validation
Company resolution
Ambiguous Company handling
Duplicate awareness
Prepared creation requests
Confirmation
Idempotent record creation
Transactional creation
Creation audit events
Authoritative post-create results
Widget refresh
Pipeline invalidation
Opportunity-list invalidation
Failure recovery
Tenant isolation
RBAC

That will give Quorentra its first complete:

Natural Language
↓
Structured Business Intent
↓
User Confirmation
↓
New CRM Record

workflow.

At that point, the ChatGPT-native Quorentra MVP will no longer merely expose an existing CRM.

It will allow users to operate the CRM conversationally while Quorentra remains the system that governs every business action.

Quorentra

Contact

Menu

Designed with WordPress