# All-Platform Campaign Manager: Implementation Plan

## 1. Purpose and scope

Build a campaign manager with a guided, wizard-like editing experience for
campaigns already created by this application or adopted from an advertising
platform. The product should let a user inspect a campaign, edit supported
settings at the correct hierarchy, review the exact proposed changes, approve
them, and verify the resulting platform state.

The manager must also handle edits made outside this application. A person may
change a campaign in Meta Ads Manager, Google Ads, or LinkedIn Campaign
Manager. Those edits must be visible to this application before it lets a user
approve a conflicting change.

This plan is for **all platforms the repository can currently publish to**:

- Meta
- Google Ads
- LinkedIn

TikTok and Taboola have platform rule classes, but the platform configuration
does not currently register campaign publishers for them. They are not part of
the initial deliverable. Add them only after their API integration and
editable-entity capabilities are implemented and tested; do not make a UI
claim that the app can manage them merely because platform rules exist.

The Jira request ARB-267 is Meta-focused and supplies useful Meta field and
validation requirements. This plan generalizes the Campaign Manager to
multiple platforms without pretending their campaign hierarchies or editable
fields are the same.

### Product boundary

This feature is an **editor and reconciled local mirror**, not an automatic
replica of every object in every connected account:

- Users explicitly choose an allowed account and open/adopt a campaign.
- The platform is authoritative for the live campaign state.
- The application stores an ownership-scoped local representation and the
  last successful platform snapshot.
- A fresh platform read is required before consequential edits and again
  immediately before applying an approved change.
- Unsupported or unrepresented remote settings are retained where practical,
  shown as read-only/unsupported, and never erased by a partial update.

## 2. Current repository baseline

### 2.1 Existing building blocks

- `CampaignImporter` adopts Meta, Google, and LinkedIn campaigns.
- `Campaign` stores shared campaign identity, objective, budget, currency,
  account and platform references.
- `CampaignAdSet` stores Meta-oriented child settings; the `HasAdSets` trait
  routes the campaign's legacy single-ad-set view into the first child row.
- `CampaignChange`, `PendingChanges`, `CampaignUpdater`, approval bindings,
  and platform guardrails provide existing edit/change-history patterns.
- `EditEntity` can update a subset of Meta ad-set and ad fields and Google
  ad-group/ad fields; LinkedIn entity changes have a separate management path.
- `ListCampaignStructure` reads live campaign children for Meta, Google, and
  LinkedIn.
- `GraphApi`, `GoogleAdsService`, and `LinkedInRestApi` are the provider
  boundaries for reads and mutations.
- The Creative Livewire wizard is a UX reference for multi-step interaction,
  not a campaign editor or a platform synchronization mechanism.

### 2.2 Existing import is not a complete remote mirror

Import currently saves a useful subset of campaign data, not every remote
field:

- **Meta:** `CampaignImporter::adopt()` reads the campaign and its ad sets.
  The first ad set is reflected through campaign-compatible fields; additional
  ad sets become `CampaignAdSet` rows. The importer keeps some audience
  details in `external_ids`, locations/placements in simplified forms, and
  common budget/bid/schedule values. It does not produce a complete editable
  representation of all remote targeting, placements, schedules, budget
  controls, and optimization properties.
- **Google:** `adoptGoogle()` stores a campaign profile and selected criteria
  such as location and Search keywords. Google ad groups, ads, and Performance
  Max asset groups use Google-specific entity shapes; they are not a complete
  `CampaignAdSet` mirror.
- **LinkedIn:** `adoptLinkedIn()` stores the campaign profile and campaign
  group ID. The platform hierarchy and edit surface are LinkedIn-specific;
  present edit support is narrower than the proposed editor.
- **External edits:** import/adoption does not currently constitute a complete,
  scheduled sync of every campaign setting after every external Ads Manager
  change. A local `published_state` is a comparison baseline, not proof that
  the platform still has those values.
- **Local child rows:** a row with an external ID may still have missing,
  stale, or simplified settings. Presence of an ID is not proof of a complete
  local record.

Therefore the answer to “do we have all required data?” is **no**. The app has
some stored facts, has live read APIs for important objects, and lacks a
complete canonical/local representation of all editable fields across all
three platforms.

### 2.3 Support boundary by platform

| Platform | Campaign publishing exists | Hierarchy in provider | Current editor foundation | Initial manager scope |
|---|---:|---|---|---|
| Meta | Yes | Campaign → ad set → ad | Subset of ad-set/ad updates; pause/activate/duplicate/delete have separate tools | Full manager, with explicit field support by capability |
| Google Ads | Yes | Campaign → ad group/ad; Performance Max → asset group/assets | Campaign updates, ad-group updates, keyword edits, status operations exist in separate paths | Full manager, using Google-native entity vocabulary and capabilities |
| LinkedIn | Yes | Campaign group → campaign → creative | Campaign update/publish patterns and narrow entity edits exist | Full manager, using LinkedIn-native entities and capability limits |
| TikTok | No current campaign publisher | Not implemented for campaign management | Rules exist; adapter is unimplemented | Not writable in initial delivery; optional discovery/read-only phase |
| Taboola | No current campaign publisher | Not implemented for campaign management | Rules exist; publisher absent | Not writable in initial delivery; optional discovery/read-only phase |

“Full manager” means a common product shell and a complete inventory of
supported fields for each platform, not that every provider field is editable
in place. Some changes must remain read-only, require a replacement entity, or
be refused if the provider cannot safely update them.

## 3. Product and safety principles

1. **Live state wins.** Local values are a cache and a workflow baseline, not a
   substitute for a fresh read of a live campaign.
2. **Do not silently overwrite an outside edit.** Re-read, compare, and present
   conflicts before applying.
3. **Use platform-native entity boundaries.** Do not flatten Google ad groups,
   LinkedIn campaign groups, Meta ad sets, and Meta campaigns into a fictional
   common “ad set” that loses meaning.
4. **Common wizard, capability-driven fields.** Share navigation, diff review,
   approval, and status UX. Render field groups from the selected platform's
   capabilities and schema.
5. **Explicit read-only and unsupported states.** Never omit a remote field
   silently if it affects delivery or could be destroyed by a replace/update.
6. **No success-shaped failures.** Report rejected, partial, normalized, stale,
   and unverified outcomes separately.
7. **Approval is bound to the exact diff.** A change other than the approved
   one requires a new review. A review does not itself mutate the platform.
8. **No destructive action by default.** Deletion, archive, pause, and
   activation remain distinct actions with the existing delivery checks and
   approval semantics.
9. **No credentials or raw sensitive tokens in snapshots.** Store account and
   object IDs and safe provider responses only; scrub tokens and sensitive
   personal targeting data according to existing logging/privacy policy.
10. **Adapter completeness is explicit.** A platform must declare each field
    as editable, conditionally editable, read-only, replacement-only, or
    unsupported before the wizard offers it.

## 4. Recommended architecture

### 4.1 Campaign Manager UI

Create a dedicated authenticated Campaign Manager area, separate from the
chat-only `EditEntity` interaction:

1. **Campaign list:** show campaigns the user owns or is authorized to manage,
   platform/account, remote ID, status, last sync, and sync health.
2. **Open/import:** select an allowed account and a campaign, then explicitly
   adopt or attach it if it is not already managed locally. Detect ownership
   conflicts; never reveal another user's imported campaign data.
3. **Refresh:** read the campaign and child structure from the provider. Show
   when it was read and which fields could not be fetched.
4. **Choose entity:** select a campaign, ad set/ad group, ad, asset group, or
   other supported entity using the platform's terminology.
5. **Wizard steps:** overview/status; budget and bidding; audience and
   delivery; schedule; optimization/tracking; assets/creatives where relevant.
   Hide steps that do not apply. Do not mix campaign-level and child-level
   settings.
6. **Review diff:** show current live value, saved local value, proposed value,
   source and last-read time. Highlight any remote drift from local state and
   any potential learning/delivery impact.
7. **Validate and approve:** run server-side provider/capability rules, then
   request explicit approval for spend/delivery-affecting actions.
8. **Apply and verify:** write only the approved allowlisted fields, fetch the
   changed entity again, and show confirmed readback or a clearly identified
   partial/failure state.

The existing Creative wizard is a useful reference for Livewire step state,
validation, and rendering. The campaign editor needs extra security controls:
server-side entity ownership checks, locked identity/selection state, fresh
provider reads, an approval-bound diff, and write/readback reconciliation.

### 4.2 Platform capability contract

Introduce or extend a platform-management adapter contract. It should provide
operations conceptually equivalent to:

- List/manageable accounts using the authenticated user's permissions.
- List campaigns within an account, with pagination and account scoping.
- Read a campaign profile and all relevant child entities, including
  pagination.
- Normalize a remote entity into a platform-neutral envelope plus
  platform-specific settings.
- Declare entity and field capabilities for this exact platform, objective,
  campaign type, status, and entity state.
- Validate a proposed patch without writing.
- Apply an allowlisted patch to the exact entity.
- Read back the entity after a successful mutation.
- Return stable provider errors, partial outcomes, and retryability.

Keep platform specifics in Meta, Google, and LinkedIn adapters; keep wizard
steps, diff presentation, approval binding, and change lifecycle shared.

### 4.3 Local data model

Avoid one enormous JSON blob as the sole source of truth. Keep searchable,
relational identifiers and common values normalized, while retaining a
versioned provider payload for settings the canonical schema does not yet
model.

Recommended model boundaries:

- **Managed campaign:** owner, platform, account ID, external campaign ID,
  provider-native type/URN, canonical objective, currency/timezone, local
  lifecycle, active/archived state, and sync metadata.
- **Platform entity:** parent ID, platform, entity type (campaign, ad set,
  ad group, campaign group, asset group, ad/creative), external ID, native
  status and effective/delivery status, stable ordering/name, and last-seen
  state. Entity hierarchy must allow platform-specific parent-child
  relationships.
- **Normalized settings:** common identity, budget amount/mode/level, bid
  intent and provider strategy, dates, status, and explicitly shared
  objective facts.
- **Platform settings:** typed per-platform fields where needed plus a
  provider payload JSON for lossless supported readback. The JSON must be
  versioned and must not be blindly posted back as a patch.
- **Targeting and delivery:** structured include/exclude geo, audiences,
  demographics, interests/keywords, placements/positions, devices, and
  automation settings, with entity scope and provenance.
- **Optimization and tracking:** objective/optimization event, promoted
  object, attribution settings, billing event, conversion IDs, tracking
  configuration and provider readback. Keep immutable/read-only distinctions.
- **Budget schedule and pacing:** schedule windows, timezone, dayparting,
  pacing, min/max spend constraints and their campaign/ad-set-level owner.
- **Assets/creatives:** remote IDs/URNs, local asset references, approval and
  replacement lineage; don't assume every remote creative is owned locally.
- **Sync snapshot:** source timestamp, sync start/completion, requested
  objects/fields, pagination-complete flag, result status, safe error, and
  per-field availability.
- **Change record:** actor, exact entity, exact before/after diff, approval
  reference, policy/version, provider request ID (if available), attempt
  status, response summary, readback result, and timestamps.

For every field that matters to editing, retain:

```text
local value
last observed remote value
last successful sync time / source timestamp
source (platform, user edit, import, application write)
availability (available, missing, stale, unsupported, invalid)
```

An application write is not “remote truth” until the provider confirms and a
readback verifies the result. A remote UI edit becomes the new observed remote
value only after a successful refresh.

### 4.4 Snapshot and three-way reconciliation

For each entity, compare:

- **B (baseline):** last known remote snapshot that the local pending changes
  were based on.
- **L (local):** current proposed/local value.
- **R (remote):** freshly fetched platform value.

For every field:

- If `L == B` and `R != B`, there is an outside platform edit. Update the
  observed remote baseline and local mirror; do not overwrite it.
- If `L != B` and `R == B`, this is an application-only pending edit; it can
  proceed after validation and approval.
- If `L != B` and `R != B` and `L != R`, there is a conflict. Stop and show
  both values; require the user to choose which value to keep.
- If `L == R`, the values are already in sync; do not send a redundant write.
- If `R` is missing, stale, incomplete, or provider read fails, block
  consequential updates and say why. Never convert “unknown” to null/zero and
  clear a remote value.

After an approved apply, re-read only the affected entity/fields where
possible, verify the provider's normalized value, then update the baseline and
local mirror. If a batch partially succeeds, record each entity/field outcome;
never roll the entire local snapshot forward as though every write worked.

### 4.5 Sync lifecycle for edits made in platform UIs

Use a layered synchronization approach:

1. **Refresh on manager open:** fresh-read profile and relevant child entities.
2. **Refresh before review:** ensure the diff is based on current remote state.
3. **Refresh before apply:** approval is valid only if the remote state still
   matches the reviewed baseline for fields being changed.
4. **Read back after apply:** confirm success and capture provider
   normalization.
5. **Background reconciliation:** periodically refresh managed campaigns as
   operationally justified. Use provider webhooks/change notifications only
   where the platform supports them reliably; do not assume all platforms
   provide complete setting-change notifications.
6. **Manual refresh and sync health:** show last successful sync, stale
   warning, and retry action. One provider failure must not make other
   platforms or campaigns appear empty.

Use pagination and bounded reads. Do not enumerate every campaign and every
detail for every account on every page request. Only sync explicitly managed
campaigns unless the product separately approves account-wide import scope.

## 5. Data inventory required for a safe manager

### 5.1 Required for every managed campaign/entity

- Platform key and API/provider version where useful.
- Account/customer ID; owner/authorization scope; account currency and
  timezone.
- External campaign ID and all relevant entity IDs with correct parent links.
- Entity type and native campaign type (e.g. Google Search vs Performance
  Max).
- Campaign name, native status, effective status, delivery/review status.
- Objective and objective-specific optimization event.
- Budget amount, currency, mode (daily/lifetime/total), level, and applicable
  minimum/maximum/schedule controls.
- Bid strategy, bid/target amount, pacing and strategy constraints.
- Start/end dates, schedule/timezone, and whether each field can still change.
- Full supported targeting and delivery configuration, including exclusions.
- Tracking/conversion setup and attribution settings when exposed.
- Remote timestamps/version/ETag where a provider offers them; otherwise the
  last-read time and stable field snapshot.
- Spend/impressions and other delivery data only where needed for the screen
  or a safety rule, with range and source. Active and paused entities can
  have spend; paused does not mean no historic delivery.
- Completeness, freshness and errors for each read; preserve unknowns.

### 5.2 Meta data inventory

Use Meta-native entity scopes: campaign, ad set, ad, and creative. At minimum
inventory:

- Campaign: name, status/effective status, objective, buying type, special ad
  categories, campaign budget configuration/CBO state, and account identity.
- Ad set: name, status/effective status, daily/lifetime budget and spend
  limits; budget schedules; bid strategy/amount/constraints; pacing; start/end
  time; ad-set schedule/dayparting; full `targeting` payload and normalized
  geo, exclusions, age, gender, locale, custom audiences/lookalikes, detailed
  targeting, audience automation/relaxation, placements and positions, device
  targeting, and carrier settings.
- Optimization/delivery: `optimization_goal`, `billing_event`,
  `destination_type`, promoted object/pixel/conversion event, frequency
  control, value-rule references, attribution specs and learning/status facts
  where readable.
- Ad/creative: IDs, parent ad set, statuses, creative identity and supported
  copy/media/destination fields; keep remote-only creative data read-only if
  there is no safe local replacement workflow.
- Diagnostics: spend and delivery for both active and paused campaigns, read
  range/currency, effective status, account timezone.

Some ARB-267 fields are Meta-version- or objective-dependent. Confirm each
field against the installed Graph API version and account before enabling it.
Do not treat ticket field names as proof a field is valid for every Meta
objective or mutable after launch.

### 5.3 Google Ads data inventory

Use Google-native structure; do not model everything as a Meta ad set:

- Account/customer ID, currency/timezone, campaign resource ID/type, status,
  serving status, channel subtype, objective/conversion goals, budget
  resource and shared-budget status.
- Campaign budget resource, amount, period, shared references and any supported
  budget limits/schedules.
- Campaign bid strategy, strategy resource/portfolio, target CPA/ROAS where
  applicable, and strategy-specific constraints.
- Campaign network/device/language/location/exclusion settings, start/end
  dates, schedule/ad-schedule criteria.
- Search ad groups, status/type, CPC bids, keywords and match types, negative
  criteria, audiences, ads and approval policy status.
- Display-specific ad-group targeting/placements and ads.
- Performance Max asset groups, asset group status, assets/asset groups and
  applicable listing-group signals; never show them as ad groups if that is
  inaccurate.
- Conversion goals/actions, attribution/conversion source, tracking template
  and URL suffix where available and writable.
- Spend/serving facts with date range and data freshness.

Map the ticket's Meta-specific fields into Google equivalents only where a
real Google field has the same business meaning. For example, “ad set” maps
to different Google entities by campaign type; budget and bid strategy
typically live at campaign level, not on the ad group.

### 5.4 LinkedIn data inventory

Use LinkedIn-native hierarchy: account → campaign group → campaign → sponsored
creative/ad. At minimum inventory:

- Ad account ID, currency/timezone, campaign group ID/name/status and any
  shared-group constraints.
- Campaign ID/name/objective/status/serving statuses, campaign type/format,
  associated organization, campaign group relationship.
- Daily or total budget, budget currency, bid/optimization strategy and unit
  cost/target, run schedule.
- Targeting criteria with included and excluded audiences, professional
  attributes, locations, languages, and any supported expansion settings.
- Optimization target/conversion rule, lead-gen form and tracking/insight tag
  links where applicable.
- Sponsored creative IDs, status, format, organization/post/video URNs and
  creative content/asset references when accessible.
- Spend/delivery facts with range and sync time.

Campaign-group changes may affect multiple child campaigns. Before editing a
group, enumerate and verify every child; refuse shared changes unless the user
explicitly selects the intended scope and the operation is safe.

### 5.5 Data that should not be treated as a reusable editable snapshot

- Access tokens, refresh tokens, secrets, or authorization headers.
- Ephemeral signed media URLs; store remote media IDs and refresh URLs when
  needed.
- Provider response fields that are volatile, calculated, or read-only unless
  their meaning is documented.
- “0” for a failed/missing query; missing data must remain explicitly missing.
- Any remote-only child entity not fully read because of pagination.
- Private or sensitive audience data beyond what is necessary for the
  campaign-management purpose and permitted by platform policy.

## 6. Platform-specific edit capability matrix

The exact field matrix must be discovered and encoded per API version, account,
objective, campaign type, status, and entity. This table describes initial
planning boundaries, not a promise that every provider allows every operation.

| Area | Meta | Google Ads | LinkedIn |
|---|---|---|---|
| Name/status | Campaign/ad set/ad paths exist; archive/delete separate from pause | Campaign/ad group/ad operations exist with Google status vocabulary | Campaign/group/creative status paths exist; group scope must be checked |
| Budget | Campaign or ad-set level; daily/lifetime; CBO constraints/schedules vary | Campaign budget resource; shared budget implications; not ad-group budget | Campaign daily/total budget; campaign group may have shared constraints |
| Bidding | Ad-set strategy/amount/constraints; objective-dependent | Campaign strategy/targets; ad-group CPC only for supported configurations | Campaign optimization target/unit cost; supported combinations vary by objective |
| Targeting | Rich ad-set `targeting`, with nested targeting and placements | Campaign/ad-group criteria vary by campaign type; PMax has distinct signals | Campaign targeting criteria with LinkedIn-specific professional audiences |
| Placements/devices | Placement and device settings are targeting; some combinations/automation are coupled | Networks/devices/criteria vary by campaign type | Placement/delivery options are not Meta-equivalent |
| Schedule | Start/end; dayparting and budget-mode constraints | Campaign/ad schedule criteria; dates and rules are resource-specific | Campaign run schedule; verify update support and timezone semantics |
| Optimization/tracking | Promoted object, goal, billing, attribution; often constrained after launch | Conversion goals/actions, bidding strategy, attribution; not a direct field-by-field Meta map | Objective/optimization/conversion setup with LinkedIn-specific constraints |
| Read-only/replacement | Objective and several structural fields should remain locked; creatives may require replacement | Some ads/assets are immutable or policy-limited; replacement path may be required | Creative replacement often requires a new creative; group/campaign relationships constrain edits |

The server-side adapter must return the actual capabilities for the selected
entity. The UI must not infer editability from a field being present in a
stored JSON payload.

## 7. Guided wizard interaction

### Step 1: Choose campaign and refresh

- Filter by allowed account, platform, name/ID, campaign type, and status.
- Refresh the remote campaign profile and all relevant children.
- If import is new, show owner/account and child counts before adopting.
- If the remote read is partial, display missing fields and disable edits
  depending on them.

### Step 2: Choose the entity and fields

- Display native hierarchy and IDs; do not assume the first child is the one
  the user means.
- Show provider status and effective/delivery status.
- Render only fields advertised as editable by the provider capability
  response.
- Organize field groups by platform concepts, with shared labels only for
  genuinely equivalent semantics.

### Step 3: Validate each section

- Validate type/range/enums and required dependencies on the server.
- Validate cross-field constraints together (e.g. budget mode + schedule,
  bid strategy + bid amount, objective + optimization event).
- Validate account currency/timezone and convert monetary values correctly.
- Preserve omitted nested values; a partial form submission must not clear
  settings the user did not edit.
- Identify changes likely to reset learning or alter delivery, with a specific
  explanation and fresh provider facts.

### Step 4: Review changes

Show:

- Current live value and source timestamp.
- Current saved/local value when it differs from live.
- Proposed value and exact entity ID.
- Learning/delivery, budget and parent/child impact warnings.
- Uneditable fields left unchanged.
- Any outside-platform changes discovered since the last snapshot.

Require the user to resolve conflicts instead of silently merging values with
different semantics.

### Step 5: Approve and apply

- Bind approval to account, campaign, entity, exact patch, user, and remote
  snapshot/version/fingerprint.
- Re-read before writing. If material remote fields changed, invalidate the
  approval and show a new diff.
- Send a minimal allowlisted patch to one provider entity at a time unless
  provider transactions guarantee atomicity.
- Use idempotency/retry protections where supported. Do not blindly retry
  non-idempotent creates or duplicates.

### Step 6: Verify and reconcile

- Read back the updated entity and compare normalized values.
- If provider normalization is expected (rounding, enum, timezone), show the
  accepted result.
- Update local settings, platform snapshot, field provenance, sync times, and
  change audit only for confirmed fields.
- For partial success, list which fields/entities succeeded and failed.
- Offer refresh/retry only when safe; never report “updated” before confirmation.

## 8. Implementation workstreams and task breakdown

### Workstream A — Scope, provider capability inventory, and UX contract

1. Confirm initial writable platforms are Meta, Google Ads, and LinkedIn;
   track TikTok/Taboola as future platform adapters.
2. Inventory campaign/entity/field APIs by API version, objective, campaign
   type, status, and account permission.
3. Mark each ticket field as editable, conditional, read-only, replacement
   only, or unsupported for each platform.
4. Define hierarchy vocabulary and the wizard's shared navigation/step model.
5. Agree import scope: explicit adoption of selected campaigns, not silently
   importing every campaign from all accounts.

**Deliverables:** approved capability matrix, provider field catalog, UX
acceptance criteria, and explicit non-goals.

### Workstream B — Reconciled local data model

1. Audit `Campaign`, `CampaignAdSet`, `CampaignAd`, `GoogleAdsCampaign`,
   `external_ids`, `meta`, `published_state`, `CampaignChange`, and targeting
   tables for duplicate/ambiguous ownership.
2. Define a platform-neutral entity identity/parent model that can represent
   Meta ad sets, Google ad groups and asset groups, and LinkedIn campaign
   groups/campaigns/creatives without synonym loss.
3. Normalize common data (identity, status, budget, objective, dates, currency)
   and retain schema-versioned provider-specific settings.
4. Add per-field provenance/availability and per-entity sync status.
5. Add migrations, indexes, unique constraints for platform/account/entity
   identity, and tenant/owner isolation.
6. Preserve backward compatibility with current campaign publishing, editing,
   performance, chat, and MCP paths.

**Acceptance:** importing the same entity twice is idempotent; same external
ID in different accounts is handled correctly; unsupported/missing fields
remain distinguishable from null/zero; no secret is persisted in platform
snapshots.

### Workstream C — Read adapters and initial import/reconciliation

1. Implement or consolidate platform reads behind management adapters.
2. Add account-scoped pagination for campaigns and child entities.
3. Read back complete supported campaign profiles and child settings.
4. Track pagination completeness and partial-provider errors.
5. Import/adopt selected campaigns and all in-scope children, with ownership
   and account allowlist checks before detailed reads.
6. Implement manual refresh, refresh-on-open, and sync-health visibility.
7. Add background reconciliation only for explicitly managed campaigns and
   with rate limits, overlap prevention, and per-platform operational metrics.
8. Add external-drift detection and three-way comparison.

**Acceptance:** a platform UI edit appears after refresh, is recorded as remote
drift, and is not overwritten by an older local value; partial pages are not
reported as complete; failures are not presented as empty campaigns.

### Workstream D — Wizard UX

1. Add authenticated campaign list/manager routes and authorization policies.
2. Implement campaign selection, explicit import/adoption, account chooser,
   platform/entity selector, and refresh state.
3. Create reusable wizard shell with locked campaign/account/entity IDs and
   server-side ownership revalidation on every Livewire action.
4. Build common steps for overview, budget/bidding, audience/delivery,
   schedule, optimization/tracking, and creative/assets.
5. Render platform-specific controls from capability metadata and show
   read-only/unsupported fields with explanations.
6. Build a review-diff page with stale and conflict states.
7. Add responsive behavior, accessibility labels/keyboard navigation,
   loading states, and explicit error/retry messages.

**Acceptance:** a wizard cannot change its entity/account through a forged
client payload; unsupported fields cannot be submitted even if manually
injected; all changes are previewed before approval.

### Workstream E — Validation and approvals

1. Define typed field schemas/rules per platform and entity.
2. Implement dependent-field validation in a single server-side validation
   service used by both preview and apply.
3. Add budget/minimum/currency ceilings and required confirmation thresholds.
4. Implement platform/objective-specific learning-phase warnings.
5. Bind approval to the exact approved field patch and fresh snapshot version.
6. Re-check entity membership, account permission, kill switch, cooldown, and
   daily change limits at apply time.
7. Ensure destructive operations reuse the separate delete/activation gates.

**Acceptance:** stale approval, changed diff, changed remote state, wrong
account/entity, or invalid dependency blocks the write with a clear message.

### Workstream F — Mutation adapters and readback

1. Implement minimal allowlisted patch builders for Meta, Google Ads, and
   LinkedIn, respecting native resource boundaries.
2. Never submit the entire provider payload as a write body.
3. Implement safe handling for replacement-only settings (for example
   immutable ad creatives/assets).
4. Make each provider call auditable and associate it with the approved
   `CampaignChange`.
5. Verify provider response and live readback before advancing local state.
6. Record provider normalization, per-field outcomes, retryability, and
   partial failures.
7. Keep pause, activate, archive, duplicate, and delete semantics explicit and
   separate; do not infer archive=delete or pause=archive.

**Acceptance:** a provider rejection leaves local baseline unchanged; a
successful request with mismatching readback is not reported as fully applied;
one entity's failure does not mark other entities as successful.

### Workstream G — Background sync and platform UI changes

1. Define freshness SLAs by platform and data type.
2. Add a scheduler/job for explicitly managed campaigns, with pagination,
   overlap locks, rate budgets, and retries.
3. Use webhooks only where they are supported and verified; scheduled or
   on-demand reads remain the fallback.
4. Track last attempt, last success, latest remote update timestamp if
   available, pagination, and provider error.
5. Add alerting/metrics for sync failures, stale campaigns, permission changes,
   rate limits, partial snapshots, and drift.
6. Let users manually refresh and recover from reauthorization without
   accidentally writing stale local values.

**Acceptance:** platform-side UI changes are eventually visible without
pretending a failed sync is current; scheduler retries do not duplicate
mutations.

### Workstream H — Regression, rollout, and operations

1. Build provider fake/fixture coverage for representative objectives,
   campaign types, and child hierarchies.
2. Run read-only shadow reconciliation against permitted test accounts.
3. Compare imported canonical fields to raw provider responses; investigate
   every lossy or ambiguous field.
4. Roll out read-only manager first, then edit a small allowlisted set of
   low-risk fields per platform.
5. Enable risky categories progressively (budget/bid, targeting, schedule,
   optimization) after per-platform signoff.
6. Keep global write kill switch and feature flags by platform/field category.
7. Document support runbooks, rate-limit handling, authorization failures,
   rollback limitations, and audit lookup.

**Acceptance:** rollback/disable path is tested; no platform is marked writable
until its capability, validation, mutation, readback, and failure tests pass.

## 9. Suggested delivery phases

### Phase 0 — Discovery and field contract

Complete Workstream A. Confirm if “all platforms” means all currently
publishable providers (Meta, Google, LinkedIn); this plan assumes that. List
TikTok/Taboola as future until their publisher and management APIs are
implemented.

**Gate:** approved field capability matrix and representative test accounts.

### Phase 1 — Read-only Campaign Manager

Build account/campaign/entity listing, explicit adoption, refresh, live
hierarchy, status, budgets, bids, targeting summary, schedule, delivery/spend,
source timestamps, and sync failures. No edits from the wizard yet.

**Gate:** remote UI edits are visible after refresh; complete/partial/failed
reads are distinguishable; users cannot see another owner's imported data.

### Phase 2 — Local sync model and conflict detection

Implement entity snapshots, provenance, field availability, sync metadata,
three-way comparison, and background reconciliation for managed campaigns.

**Gate:** external changes cause a conflict or baseline refresh instead of
silent overwrite.

### Phase 3 — Low-risk edits

Enable name and selected supported schedule/status-adjacent non-spend fields
per platform, after approval and readback. Keep pause/activate in existing
guarded workflows.

**Gate:** exact entity/account scoping, approval binding, readback,
auditability, and failure handling pass across each platform.

### Phase 4 — Budget and bidding

Enable each platform's actual budget/bid fields, limits, currency, budgets at
the right hierarchy, and learning-impact confirmations. Respect budget mode
and shared-budget behavior.

**Gate:** no cross-level budget writes; ceilings and confirmations work for
each supported currency; external drift invalidates stale approval.

### Phase 5 — Audience, placements, schedule, optimization

Enable complex nested targeting and delivery only after field-by-field
capability and merge behavior is proven. Implement replacement/read-only
behavior for fields that cannot be changed in place.

**Gate:** omitted values are preserved; unsupported fields fail closed; every
provider payload and response is tested against saved fixtures and test
accounts.

**Progress — slice 1, end dates (built):**

- New `schedule` category (`CAMPAIGN_MANAGER_EDIT_CATEGORIES=...,schedule`),
  field `end_time` on Meta ad sets and LinkedIn campaigns
  (`runSchedule.end`). Meta campaign `stop_time` stays locked because Graph
  derives it from the ad sets. Google is not offered: its reader has no end
  date yet.
- Entered as a local date-time in the zone the platform reports. Meta's zone
  comes from the offset on the ad set's own times; LinkedIn uses UTC epoch
  milliseconds.
- Stored and compared as moments. Meta is sent ISO 8601 with offset.
  LinkedIn is sent the whole `runSchedule` with the reported start kept, so
  the omitted value is preserved.
- Fails closed when:
  - the end is in the past or within 60 minutes;
  - the end is not after the start;
  - the run has already ended;
  - the current end is unreadable;
  - LinkedIn has no start;
  - free text is entered.
- A lifetime or total budget is re-checked against the floor and ceiling over
  the new length, and the re-pacing ("spread over N days instead of M") must
  be acknowledged.
- Tests: `tests/Feature/CampaignManagerScheduleEditTest.php`. A real Meta
  write was verified on campaign #64: the end was moved and confirmed by
  readback, after one Stale refusal caused by Meta normalizing targeting on
  its own. LinkedIn still needs a test account before `linkedin` goes into
  `CAMPAIGN_MANAGER_EDIT_PLATFORMS`.

**Progress — slice 2, status (built):**

- New `status` category, field `status`, on every level of every platform:
  - Meta: campaign, ad set, ad.
  - Google: campaign, ad group, ad, asset group.
  - LinkedIn: group, campaign, creative.
- Options are in each platform's own vocabulary:
  - Meta: ACTIVE / PAUSED / ARCHIVED.
  - Google: ENABLED / PAUSED.
  - LinkedIn: ACTIVE / PAUSED / ARCHIVED. A creative's status is written as
    `intendedStatus`.
- Fails closed on archived objects, statuses outside the options (DRAFT,
  REMOVED, DELETED…), a missing status, and a Google ad with no ad group id.
- A status is written to that one object only:
  - Meta: Graph, never the MCP.
  - Google: `setChildStatus` for children, `setLiveStatus` with only the
    campaign id for the campaign.
  - LinkedIn: one `$set`. A group is refused when it holds other campaigns.
- Turning the campaign itself on runs `Publisher::activationProblems` first
  and refuses with nothing sent. On success it sets `activated_at`; pausing
  the campaign clears it.
- Acknowledgements:
  - Any start: "starts spending…".
  - Restart after 7+ days paused: learning warning. The pause date comes from
    the latest status drift, or `first_seen_at`.
  - Archive.
- Any bid change now needs an acknowledgement (ticket rule), not only changes
  over the percent limit.
- Fixed while verifying:
  - Meta campaign readback was memoized within the request, so
    campaign-level edits would have read back as "unconfirmed". The reader
    now reads the campaign fresh.
  - Stale detection now ignores `effective_status`. Meta's ad review changes
    it continuously and nobody sets it. It is still recorded as drift.
- Tests: `tests/Feature/CampaignManagerStatusEditTest.php` (12). A real Meta
  pause and restore was done on campaign #64's ad, with the campaign paused
  so nothing could spend.

**Progress — slice 3, quick wins (built):**

- Meta ad sets are now read with the settings Ads Manager can change:
  `effective_status`, `destination_type`, `attribution_spec`,
  `is_dynamic_creative`, `pacing_type`, `bid_constraints`, `adset_schedule`,
  `frequency_control_specs`, and the spend caps and targets (as money). The
  first sync after this records the new keys once as drift. That is expected.
- Start date before launch, for Meta ad sets and LinkedIn campaigns:
  - Refused once the start is less than an hour away or has passed.
  - Start and end are checked against each other, including the other value
    in the same proposal.
  - Lifetime budgets are re-paced over the new run, in one note that covers
    both moves.
  - LinkedIn sends `runSchedule` with the reported end kept, or left open.
- Locked fields now say why (ARB-267's locked-fields requirement):
  - Fixed by the platform: Meta objective / buying type / destination /
    dynamic creative / promoted object; Google channel type and ad group
    type; LinkedIn objective and campaign type.
  - Not changeable here yet: targeting, optimization goal, bid strategy,
    billing event, attribution, pacing, dayparting, frequency, spend caps;
    Google keywords and start date; LinkedIn targeting and optimization
    target. Only settings the object actually has are listed.
- Any bid change now needs acknowledgement because it can restart learning.
- Tests: 5 new in `CampaignManagerScheduleEditTest`, 1 in
  `CampaignManagerSyncTest`.

**Progress — slice 4, duplicate and delete (built):**

- Structural edits share the wizard and the audit trail. `campaign_entity_edits`
  gained `action` (`edit` | `delete` | `duplicate`) and `details` (delivery
  at proposal, copy id and name, pending flag). History shows "Delete" or
  "Paused copy {name}".
- Each `EntityWriter` gained `delivery()`, `delete()` and `duplicate()`.
  - Meta: copies through `/copies` with `status_option=PAUSED`. The chat
    tools keep their ACTIVE default, because the new `$status` parameter
    defaults to ACTIVE. A campaign delete removes its ads, then its ad sets,
    then the campaign.
  - Google: `duplicateAdGroup` / `duplicateAd` (responsive search ads only),
    and `removeEntity`.
  - LinkedIn: delete through `LinkedInManagement::delete`. A draft is
    removed; anything that has run goes to PENDING_DELETION. There is no copy
    operation, so duplicate is refused with that reason.
- Offered by type (`EditCapabilities::ACTIONS`):
  - campaign: delete only. Copying a whole campaign stays in chat, as a draft.
  - ad set, ad group and ad: delete and duplicate.
  - asset group: neither.
- Each one is gated by the `duplicate` / `delete` entries in
  `CAMPAIGN_MANAGER_EDIT_CATEGORIES`.
- Delete guards:
  - lifetime spend and impressions are shown, alongside "cannot be undone,
    pause instead";
  - it always needs acknowledgement;
  - delivery is re-read at confirm, and if it grew the edit is marked Stale
    and nothing is sent;
  - LinkedIn parents that still have children are refused.
- Deleting the campaign itself returns the local record to draft and sends
  the wizard back to the list, with a message.
- The usual stale check, guardrails (kill switch, allow list, cooldown) and
  readback still apply. The cooldown was seen blocking a delete live.
- Live check on campaign #64: duplicated an ad (a paused copy appeared on
  Meta), then deleted that copy. Both were Applied and confirmed, and the copy
  was marked removed in the mirror.
- Tests: `CampaignManagerStructureEditTest` (9).

**Progress — slice 5, bid strategy (built):**

- New category `bid_strategy`. The env setting is
  `CAMPAIGN_MANAGER_EDIT_CATEGORIES=…,bid,bid_strategy,…`.
- **Meta:**
  - The strategy is set where the budget is held: on the ad set when it has
    its own budget, on the campaign under Advantage campaign budget. The other
    level shows a lock with the reason.
  - Choices: Highest volume (no cap), Cost per result goal (cost cap), Bid cap.
  - Both caps need a bid, entered in the same form. The bid field appears only
    for those strategies.
  - Moving the campaign to a cap is refused until every ad set has a bid.
  - A ROAS goal (`LOWEST_COST_WITH_MIN_ROAS`) stays in Ads Manager.
  - Confirmed live: Meta clears `bid_amount` itself on a move to highest
    volume. The resulting drift row is attributed to the edit.
- **Google (campaign):**
  - The profile now reads the bidding strategy type, any portfolio strategy,
    and the target CPA and target ROAS.
  - Choices: Maximize conversions (optional target CPA), Maximize conversion
    value (optional target ROAS), Maximize clicks, Manual CPC. Performance Max
    offers only the first two.
  - Refused for portfolio strategies and for channels other than Search,
    Display and Performance Max.
  - Sent as one `updateLiveCampaign` with a leaf mask. A cleared target is an
    empty block.
  - Display's `TARGET_CPA` is read as Maximize conversions.
- **LinkedIn (campaign):**
  - The strategy is `optimizationTargetType`. The choices come from the
    objective's allowable-combinations table.
  - Every choice except "Maximum delivery" needs a unit cost, sent in the same
    `$set`. `costType` is not changed.
  - An unknown objective is refused.
- **Shared behaviour:**
  - An amount the chosen strategy does not read is dropped before the
    proposal is stored (`prune`).
  - Changes are shown in form order. MySQL JSON does not keep key order.
  - Strategy names are shared by the form, the review, the history, the drift
    rows and the facts panel.
  - Every strategy change has to be acknowledged ("back into learning"), with
    extra notes for:
    - no cap;
    - the cap amount;
    - Manual CPC;
    - campaign-wide changes.
- **Live check on campaign #64, ad set 2:**
  - Highest volume → cost cap at 2.00 USD: Applied and confirmed.
  - Then back to highest volume: Applied, and Meta cleared the bid.
- **Tests:**
  - `CampaignManagerBidStrategyTest` (11).
  - A Google profile parsing test in `GoogleCampaignImportTest`.
- **Still unverified:**
  - Live Google and LinkedIn writes. These need test accounts.
  - Whether LinkedIn wants a `costType` change for some combinations.

**Progress — Google run dates (built):**

- Google campaign start and end dates are editable through the same schedule
  rules as Meta.
- A start on a campaign that has already started is refused with the reason.

**Progress — optimization goal (read-only after launch):**

- Initially supported eligible goal changes, but the owner confirmed on
  November 10 that ARB-267 requires post-launch goals to be read-only.
- The goal remains visible in object details and is explicitly locked in
  the wizard. Both new proposals and existing pending goal proposals are
  refused; the native writer also rejects the field.
- Conversion-event editing remains separate and available for eligible
  existing pixels. Billing event and attribution are explicitly read-only.

**Progress — spend limits and frequency (built):**

- Meta campaign `spend_cap` and ad set daily/lifetime spend limits. A blank
  value removes the limit (Meta's sentinel), and it reads back as "No limit".
- Meta frequency caps apply to Reach ad sets only. Elsewhere the field is
  locked with the reason.
- Live check on campaign #64: a 150 USD cap was applied and then removed.
  Both were confirmed by readback.

**Progress — targeting and placements (built, Meta ad sets):**

- Editable: countries, youngest/oldest age (18–65+), gender and placements
  (`publisher_platforms`).
- Everything else in the targeting spec is read fresh before the write and
  sent back unchanged. That covers interests, behaviours, custom audiences,
  exclusions, languages and the positions of the platforms that are kept.
- Values are normalized before they are compared, so Meta's own rewrites do
  not show as drift.
- **Refused, with the reason:**
  - countries when the location uses regions, cities, radius or zips;
  - age and gender when Advantage+ audience is on.
- Detailed targeting was initially locked; the November 10 expansion below
  now adds validated native audience editors.
- **Live check on ad set 2:**
  - Countries US → US+CA and gender → Women: Applied and confirmed. The six
    interests and the Facebook positions were kept.
  - Meta then refused US-only targeting on this account (subcode 3858634: a
    verified advertiser is needed for those locations). The app reported it
    cleanly as "Not applied".
  - The gender was reverted. The countries remain US+CA until the account is
    verified.

**Progress — whole-campaign duplicate (built, Meta):**

- Meta campaigns now have "Duplicate this campaign". The copy is built in
  stages:
  1. the campaign is copied on its own (`deep_copy=false`, paused, renamed
     " - copy");
  2. each live ad set is copied into it;
  3. ads are copied one by one when an ad set has more than one.
- Meta refuses any copy of three or more objects in one call (subcode
  1885194), which the live test found. That limit also applies to the
  stand-alone ad-set duplicate, which now uses the same staged copy.
- A copy that fails part way is deleted again: ads first, then ad sets, then
  the campaign. This was confirmed live.
- The copy is adopted for the same owner (`CampaignImporter::adopt`), read
  straight away, and linked from the result ("Open the copy").
- **Refused, with the reason:**
  - Google: no native whole-campaign copy endpoint; reconstruction is not
    implemented. Existing ad-group/ad duplication remains available.
  - LinkedIn: native copies are not implemented. Recreating campaign and
    creative objects is separate work, not an inherent impossibility.
- Live check on campaign #64: the copy (1 ad set, 3 ads, all paused) arrived
  as campaign #67. It was then deleted from the manager.
- Tests: `CampaignManagerStructureEditTest` (14).

**Progress — advanced all-platform ticket controls (November 10):**

- ARB-267 applies to Meta, Google Ads and LinkedIn, despite its Meta-only
  wording. Use native capabilities, not Meta field names on other platforms.
- Meta ad sets:
  - Included/excluded countries, regions, cities with radii, zips and custom
    coordinates; location types and audience locale IDs.
  - Included/excluded custom audiences, including existing lookalike audience
    IDs; detailed AND/OR interest, behaviour and demographic groups.
  - Advantage+ audience and custom/lookalike audience expansion.
  - Publisher-specific positions, including Threads; device platforms,
    operating systems/versions, included/excluded devices and carrier/Wi-Fi.
  - Delivery pacing, lifetime-budget dayparting, ROAS-floor bidding and
    existing-pixel conversion events. Pixel/app/page/destination identities
    are preserved. Value optimization requires Purchase.
  - Scheduled budget boosts through the separate budget-schedule API edge.
    Owned schedule IDs, future/nonoverlapping windows and product budget
    ceilings are enforced. Daily-budget-only increases also revalidate
    existing boosts and refuse incomplete schedule reads. Unchanged daily
    budgets do not block unrelated edits. Monetary values use native minor
    units or percentages.
  - A missing/partial schedule response locks schedule editing; explicit
    disabled scheduling is normalized to an empty list.
- Google:
  - Campaign geographic includes/excludes, languages, device exclusions and
    account-time-zone delivery schedules for Search/Display.
  - Native ad-group age, gender, remarketing/user-interest/custom/combined
    audience criteria. Account ownership and baseline criterion IDs checked.
  - Requested criterion families mutate atomically; unrelated criteria,
    keywords, custom device bid modifiers and targeting/observation mode stay
    unchanged. Missing native criterion identity/type data fails explicitly.
  - Display/Video frequency caps use native repeated-field update masks.
    Display permits impression caps only; duplicate cap keys are rejected.
- LinkedIn:
  - Native targeting criteria and audience expansion through one partial
    update. Validates include-AND/OR/exclude structure, native targeting URNs
    and mandatory included location; does not translate Meta country codes.
- Common UI:
  - Advanced structured fields use collapsed JSON editors with examples.
    Validation errors reopen the corresponding section. Human-readable labels
    accompany the native settings; untouched fields are not submitted.
  - Review, explicit confirmation, fresh reads, ownership checks, drift
    detection and post-write verification still apply.
  - Explicit lifetime-spend/impression retrieval on active and paused
    campaigns, independent of write enablement. Reporting failures are shown
    as errors, never zero-spend fallbacks.
- Verification:
  - 204 affected tests passed (892 assertions), including native mutation
    payloads, malformed input, ownership, stale reads and readback mismatch.
  - Full suite before the final guard refinements: 4,164/4,173 passed;
    nine failures in the previously failing ROI verdict/optimization advisor
    tests. The affected suite was rerun after the final guard refinements.
  - Read-only live Meta syncs succeeded with the expanded field contract.
  - Internal browser: authenticated campaign/detail/editor rendering,
    collapsed advanced controls, malformed JSON errors reopening the correct
    section, and lifetime-spend retrieval on a paused campaign verified. The
    invalid form was reset. No advertising writes made in this round.

**Temporary testing rollout:**

- Campaign Manager uses committed `visible_platforms` and `edit_platforms`
  arrays in `config/campaign-manager.php`, both initially `['meta']`.
  Environment overrides for these two settings are deliberately ignored so
  rollout releases are controlled by commits. Google and LinkedIn are excluded
  from listings, platform filters, direct manager page/edit access and scheduled
  manager reconciliation. Their readers, writers and chat/publishing flows
  remain intact. After Meta acceptance, set both arrays to `['meta', 'linkedin']`;
  after LinkedIn and the remaining Google acceptance, set both to
  `['meta', 'linkedin', 'google']`. Visibility does not override the separate
  editing-platform gate. Rebuild or clear Laravel's configuration cache during
  deployment after changing these arrays. Other operational settings retain
  their existing environment controls.
- Automated regression tests explicitly enable all three platforms; dedicated
  rollout tests verify that Meta-only visibility cannot be bypassed with a URL.

**Remaining limits and acceptance gaps:**

- Google writes have automated feature/HTTP coverage and approved PAUSED-only
  Search live acceptance. Display/Performance Max, populated reporting and
  browser mutation acceptance remain pending; keep Google's write gate disabled.
  LinkedIn's approved DRAFT-only acceptance and enabled gate are recorded below.
- Google paused whole-campaign and asset-group reconstruction is implemented
  for supported native configurations; the completion scope and explicit
  refusals are recorded below. LinkedIn campaign and creative reconstruction
  are implemented; shared campaign groups are not copied as a side effect.
- Google native conversion-goal editing is implemented with category/origin
  pairs and existing enabled custom goals. Google campaign goal selection and
  restoration of customer defaults are live verified; selecting a shared custom
  goal remains covered by automated tests only. LinkedIn conversion-rule
  associations are live verified.
- Meta detailed-targeting exclusions are retired by the API; custom-audience
  and geographic exclusions remain editable.
- Meta v23's writable ad-set contract does not expose `value_rule_set_id`.
  The manager explicitly locks it rather than sending an unsupported field.
- LinkedIn does not receive fictitious Meta pacing/dayparting fields.
  Its native pacing strategy is creation-only and locked after creation.
  Native Brand Awareness frequency optimization and Audience Network delivery
  are implemented separately, using LinkedIn's own contracts.
- Meta optimization goal, billing event and attribution remain read-only,
  matching the owner's confirmed ticket interpretation.
- Ticket must not be marked fully complete until the remaining authorized
  Google live validation requirements are resolved. LinkedIn
  reporting acceptance also needs a populated, authorized delivery report;
  empty reports remain unknown, not zero.

**Meta acceptance follow-up — November 10:**

- Owner confirmed read-only optimization goal and approved a disposable
  paused campaign copy for live verification, followed by deletion.
- Optimization-goal proposals, previously pending proposals and direct
  writer payloads are refused. Published conversion events are also immutable;
  a different event uses the explicit paused-ad-set-copy workflow below.
- Billing-event and attribution locks now describe the settled post-launch
  contract rather than suggesting those editors are pending.
- Explicit pacing and delivery windows cannot contradict one another:
  supplied pacing must include `day_parting` for nonempty windows.
- Disposable campaign #68 was created with one ad set and three ads, all
  paused. Source campaign #64 was not changed by the acceptance tests.
- Languages `[6]`, Facebook feed-only positions, mobile-only devices and
  Wi-Fi-only connection applied and were confirmed through fresh readback.
- Live budget-boost validation found two additional native constraints:
  endpoints on 15-minute boundaries and a minimum three-hour duration.
  Both are now enforced before mutation and covered by regression tests.
- After those fixes, a future three-hour $1 absolute boost was created and
  read back with Meta-assigned schedule ID `1066885396363837`.
- Live update verification found that Meta has retired
  `GraphHighDemandPeriodPost`, despite the v23 SDK still listing it.
  Changed boosts now delete the owned original and recreate through the
  supported ad-set edge. The review step explicitly warns that this is not
  atomic. A failed recreation reads back the missing original and reports
  partial application, including when schedules are the only edited field.
- Clearing detailed interests was applied and confirmed on the disposable
  ad set; its geography and other targeting remained intact.
- Budget replacement then succeeded with new schedule ID
  `1031115380002384`, and removal was also confirmed by empty readback.
- Disposable campaign #68 and its children were deleted through the manager;
  the confirmed result returned to the index and removed the copy. Its
  lifetime spend and impressions were both zero. Source #64 remains intact.
- With explicit owner approval, new paused, empty campaigns #69 and #70
  supplied eligible Reach/lifetime and existing-pixel SALES/VALUE fixtures.
  Their creation did not change the original daily-budget traffic campaign.
- Live confirmation succeeded for Reach frequency 3 per 7 days, all-days
  09:00-17:00 advertiser-time dayparting, minimum ROAS 2.5 on VALUE, and
  bid-cap accelerated pacing combined with dayparting.
- The wizard no longer submits untouched datetime-local values: displaying
  native timestamps at minute precision must not round their stored seconds
  during an unrelated edit.
- Live event updates exposed Meta error 100/3260011: a published ad set's
  pixel/conversion event cannot be edited in place. The owner selected an
  explicit new paused copy, preserving the original, instead of hiding the
  provider refusal behind an in-place workaround.
- The new event-copy selector stores and reviews the exact selected event,
  requires acknowledgement, validates platform/type/pixel/event/category,
  rechecks the baseline and native ownership, and creates the event on the
  new ad set from the outset. Old in-place event proposals and direct writer
  payloads are refused. VALUE has no alternative event to Purchase.
- Copies preserve targeting, pixel, goal, budgets, bidding, attribution,
  pacing, dayparting, applicable caps and future run dates. Scheduled boosts
  are recreated with new owned IDs. Ads are copied individually PAUSED.
  Unknown schedules and expired end dates fail explicitly rather than
  silently dropping configuration.
- Partial copy failures roll back the created ad set/ads. Cleanup refusal
  reports the remaining paused copy ID. Readback checks the selected event,
  pixel, paused status, copied ads and unchanged original before success.
- Browser acceptance on sales fixture #70 created ad set #25 with
  ADD_TO_CART; native reads confirmed the same existing pixel on both sets,
  the original #23 still PURCHASE, and both paused. The copy starts with its
  own learning and no performance history.
- Both additional fixture campaigns (#69 and #70), including all ad sets
  and the event copy, were deleted through the production manager editor.
  Each deletion read lifetime spend 0 and impressions 0 and confirmed
  removal. The browser index excludes both fixtures and retains source #64.
- Final affected regression: 244 passing tests, 2,363 assertions; Pint and
  diff whitespace checks passed. The earlier full-suite run had nine
  unrelated baseline ROI verdict/optimization-advisor failures.

**LinkedIn completion follow-up - November 10:**

- Owner approved disposable DRAFT-only live testing and cleanup, then approved
  enabling LinkedIn editing after successful verification. No campaign or
  creative was activated, and no sponsored post was published by these tests.
- Native campaign conversion associations now use the `campaignConversions`
  finder and composite-key PUT/DELETE operations. Complete reads validate
  campaign ownership, native conversion URNs, response shape and pagination.
  Only enabled rules on the same account can be added; an existing disabled
  association can be retained without recreating it.
- The editor has a native multiple-select conversion picker. Loading enabled
  account rules does not change the selection. Existing associations remain
  selectable, discovery errors are shown, and options are server-locked.
- Conversion associations are reviewed separately from other campaign edits.
  The expected baseline is rechecked immediately before mutation. Additions
  precede removals; review explicitly warns that these are separate, non-atomic
  calls. Partial failure triggers fresh readback even for a single edited field.
- Missing conversion access does not prevent unrelated campaign reads/edits.
  Associations remain unknown with an explicit error, and association edits
  and whole-campaign copies are locked until that baseline can be read.
- Campaign duplication reconstructs a new DRAFT campaign and DRAFT creatives
  under the same existing group. Fresh account/source membership checks,
  explicit writable campaign fields and exact readback protect against lossy
  copies. Conversion associations, targeting, budgets, bidding, native
  preferences, lead forms and applicable run dates are preserved.
- Creative duplication also creates DRAFT. Native inline content is preserved
  whole; sponsored references reuse existing content without editing/publishing
  its post. Enriched sponsored read responses are mapped back to their native
  reusable reference. Inline/enriched formats have automated coverage;
  sponsored-reference copies were also verified live.
- Unknown campaign settings, incomplete creative content and expired end dates
  refuse reconstruction before creation. A past start moves to now. Names
  respect LinkedIn's byte limit. Failed creation/readback removes only newly
  created objects, children first; cleanup failures identify remaining DRAFT IDs.
- Whole-campaign copies use LinkedIn adoption for the original owner, not the
  Meta importer. The central result verifies DRAFT states. Review, results and
  history consistently say DRAFT rather than falsely claiming PAUSED.
- Authoritative entity-page reads no longer use request-local memoization.
  This fixes a live-discovered issue where pre-write creative discovery hid a
  newly created creative during same-request readback.
- Native Audience Network delivery can be toggled while preserving existing
  offsite exclusions/preferences. Unknown settings stay locked; CTV campaigns
  cannot disable required offsite delivery. Targeting changes retain the
  existing learning warning and acknowledgement requirement.
- Native Brand Awareness frequency optimization supports MAX_FREQUENCY,
  3-30 impressions over exactly 7 days, with clear eligibility/rollout wording.
  Removing the preference restores automatic optimization through native
  partial-update field deletion. Unknown optimization-preference unions are
  locked rather than overwritten. Tighter-cap delivery warnings, validation,
  acknowledgement, drift checks and exact readback apply.
- Live disposable campaign #72 confirmed whole-campaign and standalone-creative
  copies plus conversion-rule addition/removal. Removal was accepted before
  the finder reflected it: the immediate result correctly remained Unconfirmed;
  a later fresh native read confirmed the removal. No false success was shown.
- Disposable #73 verified native name, daily budget, end date, audience
  expansion and Audience Network updates. Browser acceptance loaded account
  rules, selected a rule, reviewed the non-atomic warning, acknowledged it,
  applied it and displayed the exact confirmed native association.
- Disposable Brand Awareness campaign #74 verified a frequency cap of 3 per
  7 days, followed by confirmed removal. All fixtures and copied creatives
  remained DRAFT throughout.
- All three disposable native campaigns (#72/#73/#74) and their known copied
  creatives were removed. Cleanup freshly verified exact fixture IDs, account,
  DRAFT states, parent group and the complete expected child list; children
  were removed first, empty parents next, and native 404 confirmed campaign
  removal. Original campaigns #24/#65, shared groups and sponsored posts were
  not deleted or changed. Local fixture external IDs were cleared so the
  manager index no longer lists them; edit/call history remains available.
- Reporting returned empty analytics for the fixtures and an existing campaign.
  This is not sufficient proof of zero delivery or of reporting permission.
  The ordinary manager delivery/delete guard remains unchanged and refuses
  unknown delivery. Owner-approved cleanup of these known newly-created,
  never-activated DRAFT fixtures used explicit native deletion instead; it
  did not fabricate zero-spend/impression metrics or weaken general deletion.
- LinkedIn editing is now enabled in the approved local environment alongside
  Meta (`CAMPAIGN_MANAGER_EDIT_PLATFORMS=meta,linkedin`). Google remains gated.
  This is DRAFT-only acceptance, not a claim that every bid/targeting transition
  has been exercised live on serving campaigns or that reporting is verified.
- Final affected regression: 410 passing tests, 1,695 assertions, including
  24 LinkedIn-completion tests. Coverage includes native payloads, ownership,
  malformed/foreign/disabled rules, partial failure, permissions, drift,
  acknowledgement, copy adoption, rollback, cleanup failure, frequency limits,
  field removal, network/CTV constraints and readback mismatch.

**Google completion — native controls and safe reconstruction (built; Search live verified, remaining acceptance pending):**

- Campaign conversion goals now support customer defaults or campaign-specific
  category **and origin** pairs. An existing, enabled, same-account custom
  conversion goal can also be selected. Individual conversion actions are not
  confused with category/origin goals, and shared custom-goal definitions are
  never edited. Goal changes are reviewed separately, warn about learning and
  the two-call/non-atomic transition, check a fresh baseline and read back
  partial results rather than claiming nothing changed after a partial failure.
- Native network delivery and positive/negative geographic intent are editable.
  Partial network patches retain unedited switches; Search retains Google
  Search. Missing native settings lock only the affected controls.
- Search ad-group keyword editing supports additions, removals, match-type
  changes and negatives. Unchanged, case-insensitive identities retain native
  criterion IDs, status and history. Changes use one non-partial native batch;
  unrelated audiences and targeting-versus-observation mode remain unchanged.
  Missing keyword readback never compares equal to an explicit empty selection.
- Standard Search, standard Display and non-retail Performance Max campaign
  reconstruction creates an independent daily budget, a PAUSED campaign and
  PAUSED children. Native bidding, targets, dates/timezone, networks, geo intent,
  frequency caps, tracking, URL parameters, brand/text guidelines, inherited-asset
  exclusions, supported criteria, asset links, asset-set links and shared
  exclusion-set links are preserved where applicable. Expired ends are refused;
  an elapsed start moves forward. Shared assets/sets are referenced, not edited.
- Search and Display ad-group reconstruction preserves supported criteria,
  negatives, statuses, bids, native delivery modes, tracking, inherited-asset
  exclusions and scoped asset/asset-set links. Responsive Search ads retain
  pinned text. Responsive Display and image ads retain native creative content,
  existing assets, final/mobile URLs, tracking and custom parameters.
  Applicable criterion-level bid and URL/tracking overrides are also preserved.
  Automatically generated campaign device criteria and ad-group device bid
  modifiers are updated through their returned target resource IDs. Unset group
  multipliers remain inherited; zero-valued native bid defaults and inactive
  bids from other bidding strategies are not sent as writable overrides.
- Performance Max asset groups can also be reconstructed individually. Required
  asset links are created atomically with the PAUSED group through a temporary
  native resource ID; audience signals and search themes are preserved.
- Copies require fresh, exact settings, criteria/link sets, child counts and
  PAUSED-state readback. Only validated, newly created resources are eligible for
  cleanup; originals are not removed. Failed reconstruction removes incomplete
  copies and their new budget, while cleanup failures identify remaining paused
  resource IDs. Whole campaigns are adopted through the Google importer for the
  original owner; failed adoption/readback remains Unconfirmed.
- Unsupported specialized configurations refuse reconstruction rather than
  silently dropping settings: portfolio bidding, unsupported campaign subtypes
  and strategies, shopping/retail listing groups, Dynamic Search, experiments,
  AI Max, Local Services, native customizer values, legacy nondefault
  campaign-level ad rotation, non-device ad-group bid modifiers,
  unsupported criterion types and unsupported creative formats. This is not a
  claim to clone every possible Google Ads campaign.
- Lifetime reports require valid, unique, explicitly returned rows for every
  requested object. Empty/partial/foreign/malformed reports remain unknown.
  Explicit protobuf-zero rows remain valid zero, and positive sub-cent spend is
  retained. The chat delete path also rereads reporting after second confirmation;
  acknowledgement never bypasses unknown delivery.
- New native SELECT fields were checked against official v25 field metadata;
  message leaves and criterion-scope restrictions match the installed SDK.
  Automated coverage includes the real manager review/acknowledgement path,
  native payloads, keyword history, goal permissions/partial failure/drift,
  Display/image copies, Performance Max atomic creation and readback, rollback,
  cleanup failure, write gates and reporting failures.
- Live acceptance found additional native v25 constraints, now covered by
  regressions: goal endpoints do not accept `partialFailure`; scoped relation
  queries must select referenced parent IDs; array-shaped API errors retain
  their actionable messages; empty singular messages serialize as objects;
  deprecated campaign rotation is never written; Performance Max-only brand
  settings are omitted for other channels even when reported as false; and
  zero/unset or inactive bid fields are not written. Creative policy-review
  metadata is excluded from writes and comparison without dropping text or pins.
- Final affected regression: **687 passing tests, 2,527 assertions** across
  Campaign Manager and Google suites. Pint and whitespace checks pass.
- The owner approved PAUSED-only disposable fixtures in configured customer
  `3460855874`, cleanup, and enabling Google only after acceptance. Search
  acceptance confirmed native name/network/geo changes, category/origin goal
  selection, customer-goal restoration, keyword addition/removal/match changes,
  complete campaign reconstruction with an independent budget, standalone
  ad-group/ad copies, original-owner adoption and PAUSED hierarchy readback.
  Manager edits 72–76 applied successfully; native zero-delivery deletion
  through the manager also applied (77–78). The actual 60-second cooldown,
  ownership, drift and fresh reporting guards were retained throughout.
- Native lifetime rows explicitly returned zero spend and zero impressions
  before cleanup. Both disposable campaigns were confirmed REMOVED, their
  independent budgets removed, and local external IDs cleared while audit/edit
  history was preserved. Audit records confirm every budget and campaign
  created by the failed reconstruction attempts was also removed. No fixture
  was activated and no advertising spend occurred.
- The browser rendered the adopted Search copy, native paused child hierarchy
  and budget without a server error. This was read-only rendering, not browser
  mutation acceptance. Display/image and Performance Max reconstruction,
  shared custom-goal selection and populated reporting still require native
  acceptance; automated coverage is not a substitute.
- The persistent configured editing platforms remain `meta,linkedin`.
  Google remains disabled until its remaining acceptance work passes; the
  temporary process-local setting used for authorized fixture acceptance did
  not enable Google writes in the application.

### Phase 6 — Expand platform coverage

Only if separately approved, implement TikTok and Taboola campaign
read/adoption/edit adapters. Reuse the manager shell, not another platform's
field semantics.

**Gate:** each new platform has its own entity, capability, data, validation,
and readback conformance suite.

## 10. Test plan

### Provider and normalization tests

- Per-platform campaign profile and child entity reads.
- Account scoping and ownership denial before detailed reads.
- Pagination across campaigns and child objects; incomplete pagination state.
- Null/missing/zero, unknown enum, unsupported field, currency and timezone
  normalization.
- Native status vs effective/serving status.
- Platform-side update reflected after refresh.

### Diff and conflict tests

- No local change, remote change only: refresh local baseline without mutation.
- Local change only: propose diff and apply only after approval.
- Both changed to same value: no-op and reconcile.
- Both changed differently: conflict; no write.
- Missing/stale/read failure: block consequential change.
- A non-edited field changes remotely: preserve it in the provider payload and
  do not clear it.
- Partial pagination or incomplete response cannot replace a complete saved
  snapshot.

### Wizard and security tests

- Authentication, owner authorization, account allowlist, exact entity-child
  relationship, and CSRF/Livewire locked identifiers.
- Malformed/extra injected fields are rejected server side.
- Approval is bound to exact diff/entity/account/baseline.
- Reapproval required if diff or remote baseline changes.
- Accessibility and validation errors remain tied to wizard steps.

### Mutation and audit tests

- Minimal provider patch and correct native resource for each field.
- Currency minor units/micros and non-100 minor-unit currencies.
- Budget hierarchy/shared budget rules.
- Learning warning and field-dependent restrictions.
- Provider rejection does not update local baseline.
- Readback normalization/mismatch is surfaced.
- Partial batch outcomes are reported per object.
- Cooldown, daily cap, global write kill switch, idempotency, and retry
  behavior.

### Regression tests

- Existing chat `EditEntity`, `push_changes`, published-location editing,
  deletion, duplicate, and status tools keep their current contracts.
- Campaign create/publish for Meta, Google, and LinkedIn is unaffected.
- Existing performance and Whale data readers remain read-only and separate
  from editable campaign snapshots.
- TikTok and Taboola remain explicitly unsupported for campaign publishing
  and editing until their adapter work is complete.

## 11. Operational and product metrics

Track:

- Number of managed campaigns/entities by platform/account.
- Import/read success, pagination completeness, refresh latency, and stale
  entity count.
- External drift frequency and conflicts by field/platform.
- Proposed/approved/rejected/applied changes by field category.
- Provider success, normalization mismatch, partial failure, rate limiting,
  authorization failure, and retry counts.
- Time between provider success and local verified readback.
- Learning warnings displayed and changes abandoned after warnings.

Do not count a mutation as successful until the post-write readback confirms
the changed field. Do not describe remote drift as an application change.

## 12. Initial non-goals

- Editing every API field merely because a provider returns it.
- Mirroring every campaign and user in every connected ad account without an
  explicit product/privacy decision.
- Treating platform-specific entities as interchangeable.
- Sending stored provider JSON back wholesale.
- Automatic campaign optimization or AI-directed mutations.
- TikTok or Taboola editing before provider adapters exist.
- Promising atomic multi-entity transactions where a provider does not offer
  them.
- Assuming webhooks provide complete platform UI-change notifications.

## 13. Repository reference map

- Platform rules and publisher registration: `config/platforms.php`
- Campaign ownership and fields: `app/Models/Campaign.php`
- Meta-oriented child entity: `app/Models/CampaignAdSet.php`
- Campaign child relations: `app/Models/Concerns/HasAdSets.php`
- Campaign adoption: `app/Campaigns/CampaignImporter.php`
- Shared published-state diff: `app/Campaigns/PendingChanges.php`
- Approved campaign update flow: `app/Campaigns/CampaignUpdater.php`
- Existing entity editor: `app/Agent/Tools/Campaign/EditEntity.php`
- Live structure reader: `app/Agent/Tools/Campaign/ListCampaignStructure.php`
- Meta provider: `app/Services/Meta/Meta.php`, `app/Services/Meta/GraphApi.php`
- Google provider: `app/Services/GoogleAdsService.php`
- LinkedIn provider: `app/Services/LinkedIn/LinkedInRestApi.php`
- LinkedIn management: `app/Campaigns/LinkedInManagement.php`
- Provider write guardrails: `app/Services/Platforms/Support/Guardrails.php`
- Creative wizard reference: `app/Livewire/Creatives/ChatWizard.php`
- Existing edit tests: `tests/Feature/AnyAdSetCanBeEditedNotJustTheFirstTest.php`,
  `tests/Feature/EditingALiveCampaignIsNotPublishingTest.php`,
  `tests/Feature/LinkedInEditsReachTheLiveCampaignTest.php`,
  `tests/Feature/GoogleCampaignEditTest.php`
- Platform support boundaries: `app/Campaigns/Platforms/MetaRules.php`,
  `app/Campaigns/Platforms/GoogleRules.php`,
  `app/Campaigns/Platforms/LinkedInRules.php`,
  `app/Campaigns/Platforms/TikTokRules.php`,
  `app/Campaigns/Platforms/UnsupportedPlatformRules.php`

## 14. Local repository note

The repository ignores `docs/`. This plan is intentionally stored locally in
that ignored directory and has not been staged or committed.
