---
title: 'Safe AI Content Updates with Change Proposals'
url: 'http://phramecms.org/cookbook/safe-ai-content-updates-with-proposals'
markdown_url: 'http://phramecms.org/cookbook/safe-ai-content-updates-with-proposals.md'
bundle: recipe
category: ai-workflows
difficulty: intermediate
packages_used:
  - phramecms/proposal
  - phramecms/entity
  - phramecms/user
  - phramecms/mcp
  - phramecms/admin
summary: 'Give an AI agent a propose.*-scoped token with zero live write permission, stage entity.update proposals over MCP, detect stale beforeHash conflicts, and review or approve changes in /admin/proposals.'
source: 'https://github.com/PhrameCMS/docs/blob/main/cookbook/safe-ai-content-updates-with-proposals.md'
updated_at: '2026-12-04T21:49:38+00:00'
---

# Safe AI Content Updates with Change Proposals

When giving an AI coding or editorial agent access to production content, you want the agent to read existing articles, validate proposed edits against your live bundle JSON Schema, and compute an exact diff — **without ever being able to write live content or approve its own changes**.

This recipe walks through the complete workflow using `propose.*` scopes, MCP `proposal_create`, optimistic `beforeHash` conflict detection, and human review in `/admin/proposals` or `./bin/phrame op:run proposal.approve`.

---

## Step 1: Issue a Propose-Only AI Agent Token

Grant the agent read scopes, `proposal.create`, `proposal.read`, and **only** `propose.entity.content.article.update`. Critically, omit `entity.content.article.update`, `entity.content.article.publish`, and `proposal.review`:

```bash
./bin/phrame op:run agent_token.create \
  --input='{
    "name": "copy-editor-agent",
    "scopes": [
      "schema.read",
      "entity.content.article.read",
      "proposal.create",
      "proposal.read",
      "propose.entity.content.article.update"
    ]
  }' \
  --scopes=agent_token.write --json
```

> You can also mint this token during initial setup via `./bin/phrame site:install --issue-agent-token --agent-name=copy-editor-agent --agent-scopes='schema.read,entity.content.article.read,proposal.create,proposal.read,propose.entity.content.article.update' --json`.

Because the token holds `propose.entity.content.article.update` (and not `entity.content.article.update`):

- Any direct call to `entity_update` (or `PATCH /api/v1/content/content/article/{id}`) fails with `authorization_denied` / HTTP `403`.
- Calling `proposal_create` with `"operation": "entity.update"` succeeds: `ProposalCreateOperation` wraps the agent in `PhrameCms\Proposal\Security\ProposalPreviewActor` **exclusively** for a single `dryRun: true` simulation, validates the fields against the compiled bundle JSON Schema, records the exact `diff`, `beforeHash`, and `afterHash`, and stores a `pending` proposal (`prop_<hex>`).

---

## Step 2: Stage an Entity Update via MCP (`proposal_create`)

First, the agent inspects the current entity (via `entity_get` or MCP resource `phrame://content/content/article/<entity-id>`) and then stages an update through `POST /mcp` (or `./bin/phrame-mcp`):

```bash
curl -fsS -X POST https://cms.example.test/mcp \
  -H "Authorization: Bearer <agent-token>" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/call",
    "params": {
      "name": "proposal_create",
      "arguments": {
        "operation": "entity.update",
        "input": {
          "id": "ent_01examplearticle",
          "fields": {
            "summary": "Updated summary aligned with the 0.1 release notes."
          },
          "log_message": "AI copy-edit: tighten release summary"
        },
        "reason": "Fix outdated release date and tighten summary copy"
      }
    }
  }'
```

The MCP response contains the created proposal (`status: "pending"`), including its `id` (`prop_...`), computed `diff`, and `beforeHash` (a SHA-256 hash of the article's state at staging time).

The agent can later check pending or rejected proposals (including any human `review_note`) by reading MCP resources `phrame://proposals/pending` and `phrame://proposals/recent`.

---

## Step 3: Handle `beforeHash` Optimistic Concurrency Conflicts

Between the moment the AI agent stages `prop_...` and the moment a human reviews it, another editor might edit the same article.

When a reviewer approves a proposal, `ProposalApproveOperation` re-runs the target `entity.update` in `dryRun: true` mode under the **reviewer's own identity and live permissions** and compares `actual_before_hash` against the stored `proposal.beforeHash`:

1. **Pre-check without applying (`dry_run: true`)**:

```bash
./bin/phrame op:run proposal.approve \
  --input='{"id":"prop_..."}' \
  --scopes='proposal.review,entity.content.article.update' \
  --dry-run --json
```

Inspect `"stale": true|false` and `"diff"` in the output.

2. **Live approval when stale (`stale: true`, `force: false`)**:

If the underlying article changed since staging and `force` is `false`, `ProposalApproveOperation` aborts without mutating the entity and throws `PhrameCms\Proposal\Exception\ProposalConflictException` containing `$expectedBeforeHash`, `$actualBeforeHash`, and `$freshDiff`.

- **In `/admin/proposals/{id}`**: `ProposalAdminController` catches the conflict, returns HTTP `409 Conflict`, and renders the **fresh diff against current live state** so the human can decide whether to:
  - **Reject** (`POST /admin/proposals/{id}/reject`) with a `review_note` asking the agent to rebase its edit on the latest revision, or
  - **Force Approve & Apply** (`force=1`) if the edit is still valid on top of the current state.
- **In CLI**: Pass `"force": true` only after reviewing the fresh dry-run diff:

```bash
./bin/phrame op:run proposal.approve \
  --input='{"id":"prop_...","review_note":"Verified against latest revision","force":true}' \
  --scopes='proposal.review,entity.content.article.update' \
  --json
```

---

## Step 4: Human Review & Approval in `/admin/proposals`

When there is no conflict (`stale: false`), a human reviewer with `proposal.review` and `entity.content.article.update` opens `/admin/proposals`:

1. Click the pending proposal to view the target operation, canonical JSON input, stored diff, proposing agent display name, `on_behalf_of` attribution, and `beforeHash` / `afterHash`.
2. Optionally run a **Dry-Run Re-check** (`dry_run`), add a `review_note`, and click **Approve & Apply** (`POST /admin/proposals/{id}/approve`).
3. PhrameCMS executes `entity.update` live under the **human reviewer's** identity, appends an immutable entity revision, records both audit entries under the same `appliedCorrelationId`, and transitions the proposal to `approved`.

---

## Step 5: End-to-End In-Process Verification Test

Verify every security and conflict invariant in PHPUnit with zero external servers:

```php
<?php

declare(strict_types=1);

namespace App\Tests\Proposal;

use PhrameCms\Config\ConfigModule;
use PhrameCms\Core\Exception\AuthorizationException;
use PhrameCms\Core\Kernel;
use PhrameCms\Core\Operation\ExecutionContext;
use PhrameCms\Core\Operation\OperationBus;
use PhrameCms\Core\Operation\OperationRequest;
use PhrameCms\Core\Security\ActorType;
use PhrameCms\Database\DatabaseModule;
use PhrameCms\Database\Schema\SchemaInstallRunner;
use PhrameCms\Entity\EntityModule;
use PhrameCms\Mcp\Contract\McpServerInterface;
use PhrameCms\Mcp\McpModule;
use PhrameCms\Mcp\Protocol\JsonRpcRequest;
use PhrameCms\Proposal\Exception\ProposalConflictException;
use PhrameCms\Proposal\ProposalModule;
use PhrameCms\User\Security\AuthenticatedActor;
use PhrameCms\User\UserModule;
use PHPUnit\Framework\TestCase;

final class SafeAiContentProposalWorkflowTest extends TestCase
{
    public function testProposeOnlyAgentCannotWriteDirectlyAndConflictIsDetected(): void
    {
        $kernel = new Kernel([
            new DatabaseModule('memory://'),
            new ConfigModule(),
            new UserModule(),
            new EntityModule(),
            new ProposalModule(),
            new McpModule(),
        ]);
        $kernel->boot();

        $container = $kernel->container();
        $container->getTyped(SchemaInstallRunner::class, SchemaInstallRunner::class)->installAll();

        $bus = $container->getTyped(OperationBus::class, OperationBus::class);
        $mcp = $container->getTyped(McpServerInterface::class, McpServerInterface::class);

        $human = new AuthenticatedActor(
            id: 'usr_editor',
            type: ActorType::Human,
            scopes: ['schema.modify', 'entity.content.article.create', 'entity.content.article.update', 'proposal.review'],
        );
        $humanCtx = new ExecutionContext($human, 'corr-setup');

        // Seed content/article bundle and one existing article
        $bus->execute(new OperationRequest('entity_type.create', ['id' => 'content', 'label' => 'Content'], $humanCtx));
        $bus->execute(new OperationRequest('bundle.create', ['entity_type' => 'content', 'id' => 'article', 'label' => 'Article'], $humanCtx));
        $bus->execute(new OperationRequest('field_storage.create', ['entity_type' => 'content', 'name' => 'title', 'type' => 'string'], $humanCtx));
        $bus->execute(new OperationRequest('field_storage.create', ['entity_type' => 'content', 'name' => 'summary', 'type' => 'string'], $humanCtx));
        $bus->execute(new OperationRequest('field_instance.attach', [
            'entity_type' => 'content', 'bundle' => 'article', 'field_name' => 'title', 'label' => 'Title', 'required' => true,
        ], $humanCtx));
        $bus->execute(new OperationRequest('field_instance.attach', [
            'entity_type' => 'content', 'bundle' => 'article', 'field_name' => 'summary', 'label' => 'Summary',
        ], $humanCtx));

        $article = $bus->execute(new OperationRequest('entity.create', [
            'entity_type' => 'content',
            'bundle' => 'article',
            'fields' => ['title' => 'Release 0.1', 'summary' => 'Original summary'],
        ], $humanCtx));
        $articleId = (string) $article->data['entity']['id'];

        $agent = new AuthenticatedActor(
            id: 'tok_copy_editor',
            type: ActorType::Agent,
            scopes: [
                'entity.content.article.read',
                'proposal.create',
                'proposal.read',
                'propose.entity.content.article.update',
            ],
            onBehalfOf: 'usr_editor',
        );

        // 1. Direct entity.update is denied for the propose-only agent
        try {
            $bus->execute(new OperationRequest(
                operation: 'entity.update',
                input: ['id' => $articleId, 'fields' => ['summary' => 'Direct bypass attempt']],
                context: new ExecutionContext($agent, 'corr-bypass'),
            ));
            self::fail('Expected AuthorizationException for direct write.');
        } catch (AuthorizationException) {
            // Expected
        }

        // 2. Agent stages update through MCP proposal_create
        $rpc = $mcp->handle(
            new JsonRpcRequest(
                jsonrpc: '2.0',
                id: 1,
                method: 'tools/call',
                params: [
                    'name' => 'proposal_create',
                    'arguments' => [
                        'operation' => 'entity.update',
                        'input' => [
                            'id' => $articleId,
                            'fields' => ['summary' => 'AI-refined summary'],
                            'log_message' => 'Tighten copy',
                        ],
                        'reason' => 'Improve clarity',
                    ],
                ],
            ),
            $agent,
        );
        self::assertNotNull($rpc);
        $staged = json_decode((string) $rpc->result['content'][0]['text'], true, 512, JSON_THROW_ON_ERROR);
        $proposalId = (string) $staged['data']['proposal']['id'];

        // 3. Simulate a concurrent human edit on the same article
        $bus->execute(new OperationRequest(
            operation: 'entity.update',
            input: ['id' => $articleId, 'fields' => ['title' => 'Release 0.1 (Final)']],
            context: new ExecutionContext($human, 'corr-concurrent'),
        ));

        // 4. Dry-run approval detects staleness without mutating state
        $check = $bus->execute(new OperationRequest(
            operation: 'proposal.approve',
            input: ['id' => $proposalId],
            context: new ExecutionContext($human, 'corr-check', dryRun: true),
        ));
        self::assertTrue($check->data['stale']);

        // 5. Live approval without force throws ProposalConflictException
        try {
            $bus->execute(new OperationRequest(
                operation: 'proposal.approve',
                input: ['id' => $proposalId],
                context: new ExecutionContext($human, 'corr-approve-1'),
            ));
            self::fail('Expected ProposalConflictException on stale beforeHash.');
        } catch (ProposalConflictException $e) {
            self::assertSame($proposalId, $e->proposalId);
            self::assertNotSame($e->expectedBeforeHash, $e->actualBeforeHash);
        }

        // 6. After inspecting the fresh diff, reviewer explicitly approves with force: true
        $approved = $bus->execute(new OperationRequest(
            operation: 'proposal.approve',
            input: [
                'id' => $proposalId,
                'review_note' => 'Title edit is orthogonal; applying summary update.',
                'force' => true,
            ],
            context: new ExecutionContext($human, 'corr-approve-2'),
        ));

        self::assertSame('approved', $approved->data['proposal']['status']);
        self::assertSame('AI-refined summary', $approved->data['execution']['data']['entity']['fields']['summary']);
        self::assertSame('Release 0.1 (Final)', $approved->data['execution']['data']['entity']['fields']['title']);
    }
}
```

## Related Documentation

- [AI Change Proposals & Human Approval Queue](../guides/proposals.md) — Architecture of `ProposalPreviewActor`, lifecycle states, and `/admin/proposals`.
- [Users, RBAC, and AI Agent Tokens](../guides/users-rbac-tokens.md) — Designing least-privilege scopes and auditing agent activity.
- [Operations & MCP Reference](../reference/operations-mcp.md) — Full table of `proposal.*` and `entity.*` operations and MCP resources.
- [Custom Operation Across CLI, MCP, and Change Proposals](./custom-operation-cli-mcp-proposals.md) — Making your own custom operations proposal-compatible.
