Skip to content

forcedotcom/sf-skills / skills/platform-datamask-run

platform-datamask-run

Verified

Data Mask end-to-end operation on a sandbox: configure a masking policy over PII, run the masking job, poll it to completion, report masked-record results, and abort an in-progress run. Use when the user needs to run, monitor, or cancel a Salesforce Data Mask job, mask PII/sandbox data, or work with DataMaskPolicy / DataMaskPolicyJobRun. TRIGGER when: user runs a data mask job, masks sandbox PII, polls masking status, reports masked records, or aborts a running mask. DO NOT TRIGGER when: writing anonymization Apex by hand (use platform-apex-generate), generating test data (use platform-data-manage), or deploying unrelated metadata (use platform-metadata-deploy).

FileKindSize
SKILL.mdskill md20.0 KB
references/api-surface.mdmarkdown8.2 KB
references/policy-authoring.mdmarkdown14.9 KB
references/run-and-abort.mdmarkdown6.6 KB
scripts/poll-job.shexecutablescript5.7 KB

references/policy-authoring.md

View on GitHub
# Authoring a DataMaskPolicy

`DataMaskPolicy` is a **thin Metadata API shell**. Only three elements serialize into its
metadata — `<label>`, `<description>`, `<runOnRefresh>`. Object and field membership is **NOT**
part of the Metadata API shape (`DataMaskPolicy` has `childXmlNames: []` — there is no inline
`<policyObjects>` / `<policyFields>`). Membership lives in two separate **Tooling API** entities,
`DataMaskPolicyObject` and `DataMaskPolicyField`, which you insert as rows.

Authoring a complete, runnable policy from scratch is therefore a **two-step** operation:

1. **Metadata API deploy** the thin `DataMaskPolicy` shell. This is what creates the policy *with
   an active revision* — the child rows in step 2 depend on it.
2. **Tooling API insert** the `DataMaskPolicyObject` (one per target object) and its
   `DataMaskPolicyField` rows (one per masked field).

> **Order matters.** If you create the parent via the Tooling API instead of a Metadata deploy,
> it has no active revision, and the child insert fails with
> `INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY`. Always Metadata-deploy the shell first.

Reuse an existing policy when one fits; author a new one only when needed.

## Reuse first
```bash
sf data query --use-tooling-api --target-org <alias> \
  --query "SELECT Id, DeveloperName, MasterLabel FROM DataMaskPolicy"
```
If a policy already targets the object/fields you need, use its `Id` and skip authoring.

## Step 1 — Metadata-deploy the thin shell

The `.dataMaskPolicy` metadata file carries ONLY these three elements. `<masterLabel>`,
`<developerName>`, `<sampleSize>`, and any membership element are **rejected** — they are not part
of the type. (There is **no `sampleSize` field anywhere** on `DataMaskPolicy` — to mask only a
subset of records, use the row filter on `DataMaskPolicyObject`; see "Masking only a subset" below.)

```xml
<?xml version="1.0" encoding="UTF-8"?>
<DataMaskPolicy xmlns="http://soap.sforce.com/2006/04/metadata">
    <label>Contact PII Mask</label>
    <description>Masks core Contact PII in sandbox.</description>
    <runOnRefresh>false</runOnRefresh>
</DataMaskPolicy>
```

Deploy it in **mdapi (metadata) format** with a `package.xml`. `DataMaskPolicy` has **no
source-format SDR registry entry**, so a `--source-dir` deploy fails with *"Could not infer a
metadata type"*. Lay the file out as `dataMaskPolicies/Contact_PII_Mask.dataMaskPolicy` alongside
a `package.xml`:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <types>
        <members>Contact_PII_Mask</members>
        <name>DataMaskPolicy</name>
    </types>
    <version>67.0</version>
</Package>
```

```bash
sf project deploy start --metadata-dir <mdapi-dir> --target-org <alias>
```

The developer name of the created policy is the metadata member name (`Contact_PII_Mask`). Resolve
its Id before step 2:
```bash
sf data query --use-tooling-api --target-org <alias> \
  --query "SELECT Id FROM DataMaskPolicy WHERE DeveloperName = 'Contact_PII_Mask'"
```

## Step 2 — Tooling-insert the object + field membership

Insert one `DataMaskPolicyObject` per target object, then one `DataMaskPolicyField` per masked
field against that object's Id.

```bash
# One object row
sf data create record --use-tooling-api --sobject DataMaskPolicyObject --target-org <alias> \
  --values "ParentPolicyId=<policyId> ObjectReference=Contact FilterEnabled=false RunInSerialMode=false"
# → returns the DataMaskPolicyObject Id, use it as <objectId> below

# One field row per masked field
sf data create record --use-tooling-api --sobject DataMaskPolicyField --target-org <alias> \
  --values "ParentPolicyObjectId=<objectId> FieldReference=FirstName MaskingCategory=library MaskValue=first_name"
```

### Field treatment columns

Each `DataMaskPolicyField` carries a `MaskingCategory` plus a `MaskValue` — there is **no
`MaskingRuleType` column** (older docs claiming values like `RandomEmail` / `RandomPhoneNumber`
were wrong; that column does not exist).

- `MaskingCategory` — `library` (pick a value from the built-in library, the common case),
  `characters` (random characters), `replaceRandom` (random replacement), or `numberRange`.
- `MaskValue` depends on the category:
  - `library` — a snake_case library token identifying the value set. Verified tokens:
    `first_name`, `last_name`, `full_name`, `name`, `email`, `phone`, `street`, `city`, `state`,
    `postal_code`, `postal_code_ca`, `country`, `country_abbr`, `ssn`, `account_name`, `URL`.
    Use the token exactly as written here (the frontend name, not an internal name).
  - `characters` and `replaceRandom` — the field's **type group**, not its raw type: `Text` for
    Text, Text Area, Long Text Area, Rich Text Area, Encrypted and Address; `Date` for Date and
    Date/Time; `Number` for Number, Percent and Currency; Time, Checkbox, Phone, Email and URL are
    their own groups. A raw type such as `Long Text Area` fails the run with `UNKNOWN_EXCEPTION`
    ("Mask With Random is not supported for field type Long Text Area"). Left empty, the run fails
    with `UNKNOWN_EXCEPTION` ("Mask Value is required for Replace Random field").
  - `numberRange` — no `MaskValue`; set `MinMaskValue` and `MaxMaskValue` instead (the UI defaults
    are `0` and `100`; Geolocation latitude `-90`/`90`, longitude `-180`/`180`).

## Choosing the fields from Core's classification

The Data Mask UI's "Automatic PII rules" are driven by a per-field `recommendedPiiType` that Core's
classifier computes. Use the same source here so the skill and the UI recommend the same fields. Do
this once per target object, before inserting any `DataMaskPolicyField` row.

1. **Call the classification operation** through the `project-codey` server's `dispatch_readonly`
   tool. It takes a `path`, not an operationId: `path`
   `/headless/invoke/platform/datamask/data-mask-policy/get-object-fields-with-masking-info`, `method`
   `GET`, and `query_params` `{objectApiName: <object>, includePicklistValues: false,
   includeFilterOnlyFields: false}` (for example `objectApiName: "Contact"`). Omit `policyObjectId` (a
   new object has no `DataMaskPolicyObject` row yet). If this path 404s, re-resolve it with `find_route`
   rather than guessing. The `.../data-mask-policy-builder/...` route serves the same operation but does
   not take the two picklist/filter params.
2. **Read the response.** The result is `{status_code, body}`, where `body` is an array with one entry
   per field. Each entry carries `apiName`, `label`, `type`, and `recommendedPiiType` (`null` when Core
   has no recommendation). Any other shape counts as a failed call (step 4).
3. **Map each recommendation to a treatment**, the way the UI does. Compare `recommendedPiiType`
   case-insensitively. Core has already applied the sensitivity feature flag and the field's
   compliance categories, so do not re-derive the decision from `sensitivity` or `categories`.
   - A verified library token (see "Field treatment columns") → `MaskingCategory=library`,
     `MaskValue=<that token>`. This also holds for a Long Text Area or Rich Text Area field (for
     example a `street` field): the UI hides library values for those types, the backend accepts
     them.
   - `characters` → `MaskingCategory=characters`; `replaceRandom` → `MaskingCategory=replaceRandom`.
     Both need `MaskValue` = the field's **type group** (`Text`, `Date`, ...), never the raw `type`.
   - `numberRange` → `MaskingCategory=numberRange` with the `MinMaskValue`/`MaxMaskValue` defaults.
   - Any other recommendation (`title`, `middle_name`, `salutation`, `suffix`, `country_code`,
     `state_code`, `credit_card`, `sin`, `nino`, `password`, `full_address`, `date`, `datetime`,
     `picklist`) is one the UI does not apply either. **Leave the field unmasked and report it
     as unmapped, with its sensitivity, so the user can add it by choice. Do not guess a `MaskValue`.**
   - A field with no `recommendedPiiType` is not masked. List it in the report.
   - If the object has a subset filter and a recommended field is also the filter field (for example
     `LastName`), masking it changes the value the filter matches on, so a second run of the same
     policy matches nothing. Mention this in the report.
   - If the policy object already exists (its Id starts with `8po`), the UI does not auto-apply
     recommendations to it. Add only the fields the user asked for and list the other
     recommendations as suggestions.
4. **Fall back only when the call fails** (refused, errored, the `project-codey` server is unavailable,
   or the response shape is unrecognized). Then use the static table below and state in the report that
   the field list came from the static table, not from Core. When the call succeeds, Core's answer is
   authoritative. Do not add fields from the static table.

### Custom fields: check access for the masking service

The masking service runs as the org's Platform Integration User. On a test sandbox, custom
(`__c`) fields were silently left unchanged when that user had no field-level access to them; the
job still ended `completed` and wrote no per-field detail rows. Standard fields were unaffected.
After a run that includes custom fields, sample a few records. If a custom field did not change,
check field access for the integration user before re-running.

## Fallback treatments (static table)

Use this table **only** when the classification call in "Choosing the fields from Core's classification"
fails. When the call succeeds, use Core's `recommendedPiiType` and skip this table. The table is narrower than Core:

- It covers only the standard fields listed below. It does not apply Core's label, type, or encryption
  rules, so it misses fields Core does recommend (for Contact: the Other* address fields, `Fax`,
  `HomePhone`, `OtherPhone`, `AssistantPhone`).
- Core's type-based fallback classifies some text fields as `characters` (for Contact, `AssistantName`)
  and some date fields as `replaceRandom` (for Contact, `Birthdate`). Both map to their `MaskingCategory`
  value with `MaskValue` set to the field's Salesforce type (`Text` for AssistantName, `Date` for
  Birthdate), so they are masked, not reported as unmapped.

Match the `MaskValue` to the field's semantics — do **not** apply one blanket replacement:

| Field | MaskingCategory | MaskValue |
|-------|-----------------|-----------|
| FirstName | `library` | `first_name` |
| LastName | `library` | `last_name` |
| Email | `library` | `email` |
| Phone / MobilePhone | `library` | `phone` |
| MailingStreet | `library` | `street` |
| MailingCity | `library` | `city` |
| MailingState | `library` | `state` |
| MailingPostalCode | `library` | `postal_code` |
| MailingCountry | `library` | `country` |

Do not mask system fields (`Id`, `CreatedDate`, `OwnerId`, etc.).

## Editing membership

To **add** a field, insert another `DataMaskPolicyField` row. To **remove** one, delete its row:
```bash
sf data delete record --use-tooling-api --sobject DataMaskPolicyField \
  --record-id <fieldRowId> --target-org <alias>
```
The parent `DataMaskPolicy` shell does not need to be redeployed to change membership.

## Masking only a subset of records (a "sample" run)

There is **no `sampleSize`** on `DataMaskPolicy`, and **there is no `LIMIT`** — Data Mask has no
row-cap concept. To process only a subset of an object's rows, you write a **selective `WHERE`
predicate** that genuinely matches fewer rows, on the **`DataMaskPolicyObject`** row (not on the
policy). The masked count equals however many rows satisfy that predicate — so the predicate itself
*is* the subset. Three columns control it:

| Column | Type | Purpose |
|--------|------|---------|
| `FilterEnabled` | boolean | `true` turns the row filter on (default `false` = mask the whole object) |
| `WhereCriteria` | string, **max 40 chars** | A SOQL-style predicate — the human-readable form, e.g. `LastName LIKE '%son%'` |
| `RawFilterData` | textarea (JSON) | The **structured** form the engine actually executes (see the op list below) |

> **The engine masks exactly the rows the predicate matches — there is no `LIMIT`.** A `LIMIT`
> clause in `WhereCriteria` is silently ignored: `LastName != 'X' LIMIT 20` masked **all 407**
> Contacts, because `LastName != 'X'` matches every row and the `LIMIT` did nothing. To mask a
> subset you must pick a predicate that is **actually selective** — e.g. `LastName LIKE '%son%'`
> (25 rows) or `MailingState = 'NY'` (3 rows), verified with a `SELECT COUNT()` first. An
> always-true predicate is **not** a subset.
>
> **`RawFilterData` is what runs — its `operation` must be one of the engine's supported ops:**
> `eq`, `ne`, `lt`, `gt`, `ge`, `le`, `contains`, `not_contains`, `in`, `not_in`. Anything else
> (e.g. `startsWith`) fails the run with a `422` `literal_error`. `LIKE '%son%'` maps to
> `{"operation":"contains","value":"son"}`; `= 'NY'` maps to `{"operation":"eq","value":"NY"}`.
> `WhereCriteria` and `RawFilterData` must express the **same** predicate.
>
> **The predicate must also be valid SOQL** (Data Mask runs a planning `SELECT count() FROM <object>
> WHERE <predicate>` from it). **Do NOT filter on `Id`.** `Id != 'null'` fails with `invalid ID
> field: null` / `INVALID_QUERY_FILTER_OPERATOR` and makes the whole **job fail** with 0 records
> masked. Filter on a text field (`LastName`, `MailingState`, …), not `Id`.

Set them when you insert (or update) the object row. Example — mask the Contacts whose last name
contains `son` (a real subset; verify the count with `SELECT count() FROM Contact WHERE LastName
LIKE '%son%'` first). `RawFilterData` mirrors it with `operation: contains`:
```bash
sf data create record --use-tooling-api --sobject DataMaskPolicyObject --target-org <alias> \
  --values "ParentPolicyId=<policyId> ObjectReference=Contact RunInSerialMode=false \
FilterEnabled=true WhereCriteria=\"LastName LIKE '%son%'\" \
RawFilterData={\"type\":\"and\",\"filters\":[{\"type\":\"field_filter\",\"field\":\"LastName\",\"operation\":\"contains\",\"value\":\"son\"}]}"
```
To turn an existing object row into a subset run, update it instead:
```bash
sf data update record --use-tooling-api --sobject DataMaskPolicyObject --record-id <objectId> \
  --target-org <alias> --values "FilterEnabled=true WhereCriteria=\"LastName LIKE '%son%'\" \
RawFilterData={\"type\":\"and\",\"filters\":[{\"type\":\"field_filter\",\"field\":\"LastName\",\"operation\":\"contains\",\"value\":\"son\"}]}"
```
After the run, confirm the masked count in `DataMaskPolicyJobRunDtl` matches the predicate's row
count and is **less than** `SELECT COUNT() FROM Contact` — proving it masked a subset, not the whole
table. `WhereCriteria` is only **40 characters**, so keep the predicate short.

## Verifying the policy after creation
```bash
# Confirm the object + field membership landed
sf data query --use-tooling-api --target-org <alias> \
  --query "SELECT Id, FieldReference, MaskingCategory, MaskValue FROM DataMaskPolicyField \
           WHERE ParentPolicyObjectId = '<objectId>'"
```
Use the policy `Id` as `<policyId>` in the run/abort sequence (`run-and-abort.md`).
finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the workStars: 322kUpdated Claude CodeCodexVerifiedInstall
systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixesStars: 322kUpdated Claude CodeCodexVerifiedInstall
test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation codeStars: 322kUpdated Claude CodeCodexVerifiedInstall
skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.Stars: 198kUpdated Claude CodeCodexVerifiedInstall