# sf-decomposer

[![NPM](https://img.shields.io/npm/v/sf-decomposer.svg?label=sf-decomposer)](https://www.npmjs.com/package/sf-decomposer)
[![Downloads/week](https://img.shields.io/npm/dw/sf-decomposer.svg)](https://npmjs.com/package/sf-decomposer)
[![GitHub Marketplace](https://img.shields.io/badge/marketplace-sf--decomposer-blue?logo=github)](https://github.com/marketplace/actions/sf-decomposer)
[![License](https://img.shields.io/badge/License-MIT-yellow.svg)](https://raw.githubusercontent.com/mcarvin8/sf-decomposer/main/LICENSE.md)
[![codecov](https://codecov.io/gh/mcarvin8/sf-decomposer/graph/badge.svg?token=YFU52L4XM5)](https://codecov.io/gh/mcarvin8/sf-decomposer)
[![Mutation testing badge](https://img.shields.io/endpoint?style=flat&url=https%3A%2F%2Fbadge-api.stryker-mutator.io%2Fgithub.com%2Fmcarvin8%2Fsf-decomposer%2Fmain)](https://dashboard.stryker-mutator.io/reports/github.com/mcarvin8/sf-decomposer/main)
[![Performance](https://img.shields.io/badge/Performance-Dashboard-58a6ff)](https://mcarvin8.github.io/sf-decomposer/dev/bench/runtime/)

**Decomposes** large Salesforce metadata XML files into smaller, version-control–friendly files (XML, JSON, YAML, JSON5), and **recomposes** them back into deployment-ready metadata.

- Using the Salesforce CLI? Start at [Setup](#setup).
- Running this in GitHub CI without the CLI? Skip straight to [GitHub Action](#github-action).
- No Salesforce CLI at all? Use the [standalone command](#standalone-command-without-the-salesforce-cli) from `sf-decomposer-core`.
- Using Claude Code, GitHub Copilot, or another AI coding agent? Install the [agent skills](#ai-coding-agent-skills).

<!-- TABLE OF CONTENTS -->
<details>
  <summary>Table of Contents</summary>

- [Setup](#setup)
  - [1. Requirements](#1-requirements)
  - [2. Install the Plugin](#2-install-the-plugin)
  - [3. Configure .forceignore](#3-configure-forceignore)
  - [4. Configure Hooks](#4-configure-hooks-recommended)
- [Daily Workflow](#daily-workflow)
- [Commands](#commands)
- [GitHub Action](#github-action)
- [Standalone Command (without the Salesforce CLI)](#standalone-command-without-the-salesforce-cli)
- [AI Coding Agent Skills](#ai-coding-agent-skills)
- [Reference](#reference)
  - [Decompose Strategies](#decompose-strategies)
  - [Supported Metadata](#supported-metadata)
  - [Manifest-scoped Runs](#manifest-scoped-runs)
  - [Per-Type & Per-Component Overrides](docs/CONFIGURATION.md)
  - [Ignore Files](#ignore-files)
  - [Using with sfdx-git-delta](#using-with-sfdx-git-delta)
  - [Troubleshooting](#troubleshooting)
- [Tested Against Real Projects](#tested-against-real-projects)
- [Built With](#built-with)
- [Migrating from Native Decomposition](#migrating-from-native-decomposition)
- [Contributing](#contributing)
- [Issues](#issues)
- [License](#license)

</details>

---

## Setup

Complete these steps once per project. After setup, see [Daily Workflow](#daily-workflow).

### 1. Requirements

- [Salesforce CLI](https://developer.salesforce.com/tools/sfdxcli) (`sf`) installed
- Node.js 22.19 or later
- A Salesforce DX project with `sfdx-project.json` and package directories

**Supported Platforms**

sf-decomposer depends on [config-disassembler-node](https://github.com/mcarvin8/config-disassembler-node), which ships prebuilt native binaries as platform-specific optional npm packages — your package manager installs only the one matching your `os` / `cpu` / `libc`:

| Platform    | Architectures                        |
| ----------- | ------------------------------------ |
| **macOS**   | x64 (Intel), arm64 (Apple Silicon)   |
| **Linux**   | x64 (gnu + musl), arm64 (gnu + musl) |
| **Windows** | x64, arm64                           |

If your platform or architecture is not listed, open an [issue](https://github.com/mcarvin8/sf-decomposer/issues).

### 2. Install the Plugin

```bash
sf plugins install sf-decomposer@x.y.z
```

### 3. Configure .forceignore

**Required.** The Salesforce CLI must ignore decomposed files or `sf` commands will fail. Configure this before running any decompose or retrieve commands.

**Option A — Automatic (recommended):** Pass `--update-forceignore` on your first `sf decomposer decompose` run. The plugin appends type-level wildcard patterns to `.forceignore` — one ignore pattern for decomposed pieces and one negation to re-allow the original metadata file — creating the file if it doesn't exist. Subsequent runs only add new entries; existing ones are never duplicated.

```bash
sf decomposer decompose -m "flow" -m "permissionset" --postpurge --update-forceignore
```

**Option B — Manual:** Copy the [sample .forceignore](https://raw.githubusercontent.com/mcarvin8/sf-decomposer/main/examples/.forceignore) into your project root and adjust the extension patterns for your chosen format (`.xml`, `.json`, `.yaml`, etc.).

### 4. Configure Hooks (Recommended)

Hooks auto-decompose after `sf project retrieve start` and auto-recompose before `sf project deploy start` / `validate` — eliminating manual steps entirely.

Add `.sfdecomposer.config.json` to your project root. Copy and customize one of the sample configs:

- [Basic sample](https://raw.githubusercontent.com/mcarvin8/sf-decomposer/main/examples/.sfdecomposer.config.json) — one format and strategy for all types
- [Sample with overrides](https://raw.githubusercontent.com/mcarvin8/sf-decomposer/main/examples/.sfdecomposer.config.overrides.json) — vary format/strategy per metadata type or component

| Option                       | Required    | Description                                                                                                                                                                                                                 |
| ---------------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `metadataSuffixes`           | Conditional | Comma-separated metadata suffixes to decompose/recompose. Required unless `manifest` is set; when both are set, run is scoped to the intersection.                                                                          |
| `manifest`                   | Conditional | Path (relative to project root) to a `package.xml` manifest. When set, only listed components are decomposed/recomposed.                                                                                                    |
| `ignorePackageDirectories`   | No          | Comma-separated package directories to skip.                                                                                                                                                                                |
| `prePurge`                   | No          | Remove existing decomposed files before decomposing (default: false).                                                                                                                                                       |
| `postPurge`                  | No          | After decompose: remove originals; after recompose: remove decomposed files (default: false).                                                                                                                               |
| `decomposedFormat`           | No          | `xml`, `json`, `json5`, or `yaml` (default: xml).                                                                                                                                                                           |
| `strategy`                   | No          | `unique-id` \| `grouped-by-tag` (default: unique-id).                                                                                                                                                                       |
| `decomposeNestedPermissions` | No          | With `grouped-by-tag`, set `true` to further decompose permission set and muting permission set object/field permissions.                                                                                                   |
| `updateForceignore`          | No          | Set `true` to automatically add decomposed file paths to `.forceignore` after each hook-triggered decomposition (default: false).                                                                                           |
| `updateGitattributes`        | No          | Set `true` to automatically add root metadata file patterns to `.gitattributes` after each hook-triggered decomposition (default: false).                                                                                   |
| `skipPrerunHook`             | No          | Set `true` to skip the automatic recompose that fires before `sf project deploy start/validate` (default: false). Useful when you recompose manually in a pre-commit hook and don't want a second recompose at deploy time. |
| `skipPostRetrieveHook`       | No          | Set `true` to skip the automatic decompose that fires after `sf project retrieve start` (default: false).                                                                                                                   |
| `overrides`                  | No          | Array of per-type and/or per-component overrides. See [CONFIGURATION.md](docs/CONFIGURATION.md).                                                                                                                            |

---

## Daily Workflow

**With hooks configured** (recommended):

```
retrieve → auto-decomposes → review & commit → deploy → auto-recomposes
```

```bash
sf project retrieve start          # hooks decompose automatically
git add . && git commit -m "..."   # commit decomposed files
sf project deploy start            # hooks recompose automatically
```

**Without hooks** (manual):

```bash
# After retrieve: decompose
sf decomposer decompose -m "flow" -m "labels" --postpurge

# Before deploy: recompose, then deploy
sf decomposer recompose -m "flow" -m "labels"
sf project deploy start
```

Pass `-x manifest/package.xml` to both `decompose` and `recompose` (and `deploy`) to scope a run to just the components in a deploy manifest.

---

## Commands

<!-- biome-ignore format: oclif readme writes this list with `*` bullets -->
<!-- commands -->
* [`sf decomposer decompose`](#sf-decomposer-decompose)
* [`sf decomposer recompose`](#sf-decomposer-recompose)
* [`sf decomposer verify`](#sf-decomposer-verify)

## `sf decomposer decompose`

Decomposes the metadata files created by retrievals.

```
USAGE
  $ sf decomposer decompose [--json] [--flags-dir <value>] [-m <value>...] [-x <value>] [--prepurge] [--postpurge] [-f
    xml|json|yaml|json5] [-i <value>...] [-s unique-id|grouped-by-tag] [-p] [-c] [--update-forceignore]
    [--update-gitattributes]

FLAGS
  -c, --config
      Load all settings from .sfdecomposer.config.json in the repo root. When set, all top-level fields (metadataSuffixes,
      manifest, prePurge, postPurge, decomposedFormat, strategy, ignorePackageDirectories, decomposeNestedPermissions,
      updateForceignore, updateGitattributes) and the "overrides" array are applied. Explicit CLI flags take precedence
      over config values. Makes --metadata-type and --manifest optional when either is defined in the config.

  -f, --format=<option>
      [default: xml] File format for the decomposed files.
      <options: xml|json|yaml|json5>

  -i, --ignore-package-directory=<value>...
      Ignore a package directory.

  -m, --metadata-type=<value>...
      The metadata suffix to process, such as 'flow', 'labels', etc., or an exact type name such as 'CustomSite' for a
      type whose suffix is shared with another type. Required unless --manifest is provided.

  -p, --decompose-nested-permissions
      Additionally decompose object and field permissions on a permission set when strategy is set to "grouped-by-tag".

  -s, --strategy=<option>
      [default: unique-id] Strategy to follow when decomposing files.
      <options: unique-id|grouped-by-tag>

  -x, --manifest=<value>
      Path to a package.xml manifest file. When provided, only the metadata listed in the manifest is decomposed. If
      --metadata-type is also provided, the intersection of the two is used.

  --postpurge
      Purge the original files after decomposing them.

  --prepurge
      Purge directories of pre-existing decomposed files.

  --update-forceignore
      Automatically add decomposed file paths to .forceignore after successful decomposition.

  --update-gitattributes
      Automatically add root metadata file patterns to .gitattributes after successful decomposition, suppressing noisy
      diffs on recomposed files while keeping them tracked for tools like sfdx-git-delta.

GLOBAL FLAGS
  --flags-dir=<value>  Import flag values from a directory.
  --json               Format output as json.

DESCRIPTION
  Decomposes the metadata files created by retrievals.

  Decompose large metadata files into smaller files.

  You should run this after you retrieve metadata from an org.

EXAMPLES
  `sf decomposer decompose -m "flow" -f "xml" --prepurge --postpurge`

  `sf decomposer decompose -m "flow" -m "labels" -f "xml" --prepurge --postpurge`

  `sf decomposer decompose -m "flow" -f "xml" -i "force-app"`

  `sf decomposer decompose -x "manifest/package.xml" --postpurge`

  `sf decomposer decompose -x "manifest/package.xml" -m "flow"`
```

_See code: [src/commands/decomposer/decompose.ts](https://github.com/mcarvin8/sf-decomposer/blob/main/src/commands/decomposer/decompose.ts)_

## `sf decomposer recompose`

Recomposes the files created by the `decompose` command before deployments.

```
USAGE
  $ sf decomposer recompose [--json] [--flags-dir <value>] [-m <value>...] [-x <value>] [--postpurge] [-i <value>...]
  [-c]

FLAGS
  -c, --config                               Load all settings from .sfdecomposer.config.json in the repo root. When
                                             set, top-level fields (metadataSuffixes, manifest, postPurge,
                                             ignorePackageDirectories) are applied. Explicit CLI flags take precedence
                                             over config values. Makes --metadata-type and --manifest optional when
                                             either is defined in the config.
  -i, --ignore-package-directory=<value>...  Ignore a package directory.
  -m, --metadata-type=<value>...             The metadata suffix to process, such as 'flow', 'labels', etc., or an exact
                                             type name such as 'CustomSite' for a type whose suffix is shared with
                                             another type. Required unless --manifest is provided.
  -x, --manifest=<value>                     Path to a package.xml manifest file. When provided, only the metadata
                                             listed in the manifest is recomposed. If --metadata-type is also provided,
                                             the intersection of the two is used.
      --postpurge                            Purge the decomposed files after recomposing them.

GLOBAL FLAGS
  --flags-dir=<value>  Import flag values from a directory.
  --json               Format output as json.

DESCRIPTION
  Recomposes the files created by the `decompose` command before deployments.

  Recompose the decomposed files into deployment-compatible metadata files.

  You should run this before you deploy decomposed metadata to an org.

EXAMPLES
  `sf decomposer recompose -m "flow" --postpurge`

  `sf decomposer recompose -m "flow" -i "force-app"`

  `sf decomposer recompose -x "manifest/package.xml" --postpurge`

  `sf decomposer recompose -x "manifest/package.xml" -m "flow"`
```

_See code: [src/commands/decomposer/recompose.ts](https://github.com/mcarvin8/sf-decomposer/blob/main/src/commands/decomposer/recompose.ts)_

## `sf decomposer verify`

Round-trip verify that decompose followed by recompose preserves your metadata byte-for-byte.

```
USAGE
  $ sf decomposer verify [--json] [--flags-dir <value>] [-m <value>...] [-x <value>] [-f xml|json|yaml|json5] [-i
    <value>...] [-s unique-id|grouped-by-tag] [-p] [-c]

FLAGS
  -c, --config
      Load all settings from .sfdecomposer.config.json in the repo root. When set, all top-level fields (metadataSuffixes,
      manifest, decomposedFormat, strategy, ignorePackageDirectories, decomposeNestedPermissions) and the "overrides"
      array are applied. Explicit CLI flags take precedence over config values. Makes --metadata-type and --manifest
      optional when either is defined in the config.

  -f, --format=<option>
      [default: xml] File format to decompose into for the round-trip check.
      <options: xml|json|yaml|json5>

  -i, --ignore-package-directory=<value>...
      Ignore a package directory.

  -m, --metadata-type=<value>...
      The metadata suffix to verify, such as 'flow', 'labels', etc., or an exact type name such as 'CustomSite' for a type
      whose suffix is shared with another type. Required unless --manifest is provided.

  -p, --decompose-nested-permissions
      Additionally decompose object and field permissions on a permission set when strategy is set to "grouped-by-tag".

  -s, --strategy=<option>
      [default: unique-id] Strategy to follow when decomposing files for the round-trip check.
      <options: unique-id|grouped-by-tag>

  -x, --manifest=<value>
      Path to a package.xml manifest file. When provided, only the metadata listed in the manifest is verified. If
      --metadata-type is also provided, the intersection of the two is used.

GLOBAL FLAGS
  --flags-dir=<value>  Import flag values from a directory.
  --json               Format output as json.

DESCRIPTION
  Round-trip verify that decompose followed by recompose preserves your metadata byte-for-byte.

  For every parent metadata XML file belonging to the requested metadata types, disassembles and
  reassembles it in an isolated temp directory using the same flags and `.sfdecomposer.config.json`
  overrides you would use in production, then compares the reconstructed XML against the original.
  Comparison is **structural**: content must match, and element-order differences are reported
  separately. The command never modifies your working tree.

  Repeated sibling elements keep their original order through a round trip (recorded in
  `.element_order.json`), so files normally come back byte-identical. Files whose only delta is
  element order are surfaced as informational notices ("reordered") and do not fail the run. This
  happens when the order can't be recorded, for example different tags interleaved (`<a>`, `<b>`,
  `<a>`) or a grouped-by-tag `group` rule. Some metadata depends on order (picklist values,
  page-layout sections, approval steps), so review reordered files before committing. Genuine
  semantic differences are reported as drift and exit non-zero, which makes the command suitable as
  a CI gate before committing strategy, format, or override changes.

EXAMPLES
  `sf decomposer verify -m "permissionset" -f "xml"`

  `sf decomposer verify -m "permissionset" -m "profile" -s "grouped-by-tag" -p`

  `sf decomposer verify -x "manifest/package.xml" --config`
```

_See code: [src/commands/decomposer/verify.ts](https://github.com/mcarvin8/sf-decomposer/blob/main/src/commands/decomposer/verify.ts)_
<!-- commandsstop -->

---

## GitHub Action

`decompose`, `recompose`, and `verify` are also available as a GitHub Action — a container action, so it needs **no Salesforce CLI and no `sf-decomposer` plugin install**. One action, dispatched by a `mode` input, mirrors the three CLI commands one-for-one: same flags (as inputs), same `.sfdecomposer.config.json` support via `config: true`.

```yaml
- uses: actions/checkout@v7

- name: Decompose retrieved metadata
  uses: mcarvin8/sf-decomposer@v7
  with:
    mode: decompose
    metadata-type: |
      permissionset
      flow
    postpurge: "true"

- name: Verify the round trip before merging
  uses: mcarvin8/sf-decomposer@v7
  with:
    mode: verify
    config: "true"
```

Or point it at an existing `.sfdecomposer.config.json` for either step instead of listing flags: `with: { mode: decompose, config: 'true' }`.

**Inputs** (all optional except `mode`; multi-value inputs are newline-separated, matching `actions/checkout`'s own multiline convention):

| Input                          | Used by              | Description                                                                       |
| ------------------------------ | -------------------- | --------------------------------------------------------------------------------- |
| `mode`                         | all                  | `decompose`, `recompose`, or `verify`.                                            |
| `metadata-type`                | all                  | Metadata suffix(es) to process, one per line.                                     |
| `manifest`                     | all                  | Path to a package.xml manifest to scope the run to.                               |
| `ignore-package-directory`     | all                  | Package director(y/ies) to skip, one per line.                                    |
| `config`                       | all                  | Read settings from `.sfdecomposer.config.json`, same as the CLI's `--config`.     |
| `format`                       | decompose, verify    | `xml`, `json`, `json5`, or `yaml`. Default `xml`.                                 |
| `strategy`                     | decompose, verify    | `unique-id` or `grouped-by-tag`. Default `unique-id`.                             |
| `decompose-nested-permissions` | decompose, verify    | With `grouped-by-tag`, further decompose permission set object/field permissions. |
| `prepurge`                     | decompose            | Remove existing decomposed files before decomposing.                              |
| `postpurge`                    | decompose, recompose | After decompose, remove originals; after recompose, remove decomposed files.      |
| `update-forceignore`           | decompose            | Append decomposed file patterns to `.forceignore`.                                |
| `update-gitattributes`         | decompose            | Mark decomposed files as generated in `.gitattributes`.                           |

**Outputs:** `metadata` (newline-separated list of processed suffixes), `types-count`; `verify` additionally sets `drift-count` and `reordered-count`, and fails the step when `drift-count` is greater than 0.

See [`action.yml`](action.yml) for the full input/output reference.

---

## Standalone Command (without the Salesforce CLI)

[`sf-decomposer-core`](https://www.npmjs.com/package/sf-decomposer-core) publishes the same decompose, recompose, and verify logic as a plain Node.js command, `sf-decomposer`, with no Salesforce CLI and no plugin install. Its only dependency is `config-disassembler`. Flags, `.sfdecomposer.config.json`, and output match `sf decomposer <command>`, plus `--json`.

```bash
npx sf-decomposer-core decompose -m "flow" -m "permissionset"
npx sf-decomposer-core recompose -m "flow" -m "permissionset" --postpurge
npx sf-decomposer-core verify -x "manifest/package.xml" --config
```

The retrieve/deploy [hooks](#4-configure-hooks-recommended) need the Salesforce CLI, so run `decompose` and `recompose` yourself (or from a pre-commit hook) when using the standalone command. The package also exports a programmatic API; see [its README](packages/core/README.md).

---

## AI Coding Agent Skills

Two [Agent Skills](https://agentskills.io) let Claude Code, GitHub Copilot, and other coding agents work with large metadata files through sf-decomposer. Both run [`sf-decomposer-core`](#standalone-command-without-the-salesforce-cli) with `npx`, so they need Node.js 22.19+ and no Salesforce CLI.

| Skill                         | What it does                                                                                                                                                                                                                                                                                    |
| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `sf-decomposer-edit-metadata` | Reads, compares, or changes large metadata files, such as "give Sales Ops read on Account.Industry" or "which permission sets can edit Opportunity.Amount". In projects that don't use sf-decomposer, it splits only the files it needs and rebuilds them, so only the intended change remains. |
| `sf-decomposer-setup`         | Sets up sf-decomposer in a project: types, strategy and format, a round-trip check, `.sfdecomposer.config.json`, `.forceignore`, `.gitattributes`, and a recompose hook.                                                                                                                        |

```sh
# Claude Code (type these inside a Claude Code session)
/plugin marketplace add mcarvin8/sf-decomposer
/plugin install sf-decomposer@sf-decomposer

# GitHub Copilot CLI (reads the same marketplace files)
copilot plugin marketplace add mcarvin8/sf-decomposer
copilot plugin install sf-decomposer@sf-decomposer

# Any agent, with the skills CLI (skills.sh.json points it at plugins/sf-decomposer/skills)
npx skills add mcarvin8/sf-decomposer

# Any agent, with the GitHub CLI
gh skill install mcarvin8/sf-decomposer --agent github-copilot
```

See the [plugin README](plugins/sf-decomposer/README.md) for example requests and data handling.

---

## Reference

### Decompose Strategies

Two primary strategies control how nested XML elements are split on disk. Both round-trip deterministically and can be mixed across types — or even across components of the same type — via the `overrides` array (see [CONFIGURATION.md](docs/CONFIGURATION.md)). When switching strategies for an existing component, pass `--prepurge` (or `prePurge: true`) to remove leftover files from the prior strategy before writing new ones.

**Nested vs. leaf elements**

The decomposition strategies operate on nested XML elements. A nested element is a child of the root element that contains its own child elements. These are the entries split into separate files or subdirectories. Nesting is what matters, not repetition: a nested element is split out even if it appears only once. In practice, though, most nested elements are repeatable blocks such as `<fieldPermissions>`.

A leaf element is a property or scalar value that contains only text, with no child elements. Leaf content stays in the original XML file unless the type's decomposition rules explicitly extract it to a sidecar file (see `externalServiceRegistration`). This holds even when a leaf element repeats: a list like `<narrowComponents>` on a home page layout is still leaf content.

A file with no nested elements at all is **leaf-only**: there is nothing to split, so decompose skips it and leaves it untouched (logged at `RUST_LOG=error`, not a failure). [METADATA_SUPPORT.md](./docs/METADATA_SUPPORT.md) lists which types are leaf-only.

**XML comments**

Comments stay where they were through decompose and recompose:

- A comment above an element, such as a note or commented-out XML, travels with that element. It goes into the element's decomposed file and is written back on its own line just above it, even if elements are reordered.
- A comment after an element's last child stays just before its closing tag.
- A comment in an element's text stays part of that text. That includes the placeholders Salesforce retrieves for untranslated values, such as `<translation><!-- Planned --></translation>` in a global value set translation or `<label><!-- Status --></label>` in an object translation.

A comment written on the same line as the next element (`--><value>`) comes back on its own line. A file with a comment _outside_ its root element (before or after it) is left untouched, the same way as a leaf-only file (logged at `RUST_LOG=error`, not a failure), because there is no element to carry that comment.

Example:

```xml
<PermissionSet xmlns="http://soap.sforce.com/2006/04/metadata">
  <label>HR Admin</label>
  <description>Access for HR admins</description>

  <fieldPermissions>
    <field>Job_Request__c.SalaryPay__c</field>
    <editable>true</editable>
    <readable>true</readable>
  </fieldPermissions>

  <fieldPermissions>
    <field>Job_Request__c.Salary__c</field>
    <editable>false</editable>
    <readable>true</readable>
  </fieldPermissions>
</PermissionSet>
```

Nested elements:

```xml
<fieldPermissions>
    <field>Job_Request__c.SalaryPay__c</field>
    <editable>true</editable>
    <readable>true</readable>
</fieldPermissions>
<fieldPermissions>
    <field>Job_Request__c.Salary__c</field>
    <editable>false</editable>
    <readable>true</readable>
</fieldPermissions>
```

Leaf/scalar elements:

```xml
<label>HR Admin</label>
<description>Access for HR admins</description>
```

#### unique-id strategy (default)

Each nested element gets its own file, named by one or more unique-id fields (or a content hash when no UID is found). Leaf elements stay in a file named like the original XML.

```
permissionsets/
└── HR_Admin/
    ├── HR_Admin.permissionset-meta.xml             ← leaf properties (label, description, userLicense, ...)
    ├── .key_order.json                             ← preserves original element order
    ├── applicationVisibilities/
    │   └── JobApps__Recruiting.applicationVisibilities-meta.xml
    ├── classAccesses/
    │   └── Send_Email_Confirmation.classAccesses-meta.xml
    ├── fieldPermissions/
    │   ├── Job_Request__c.SalaryPay__c.fieldPermissions-meta.xml
    │   └── Job_Request__c.Salary__c.fieldPermissions-meta.xml
    ├── objectPermissions/
    │   └── Job_Request__c.objectPermissions-meta.xml
    ├── pageAccesses/
    │   └── Job_Request_Web_Form.pageAccesses-meta.xml
    ├── recordTypeVisibilities/
    │   └── Recruiting.DevManager.recordTypeVisibilities-meta.xml
    ├── tabSettings/
    │   └── Job_Request__c.tabSettings-meta.xml
    └── userPermissions/
        └── APIEnabled.userPermissions-meta.xml
```

**Filename safety.** Two safety nets apply automatically. Neither requires configuration:

- **Path-segment sanitization (silent).** Characters illegal or reserved on at least one supported filesystem — path separators (`/`, `\`), Windows-reserved chars (`:`, `*`, `?`, `"`, `<`, `>`, `|`), and ASCII control bytes — are replaced with `_`; trailing `.` and spaces are stripped. Sanitized filenames are byte-stable across platforms.
- **Sibling-collision fallback (emits `WARN`).** When two or more siblings of the same parent tag would resolve to the same filename (the configured unique-id elements are too narrow, or sanitization folded two distinct values together), every sibling in the colliding group is written to its own per-element SHA-256 shard instead. No row is silently overwritten.

If you see a hash-named shard and want to know whether it came from a collision (vs. a missing UID), set `RUST_LOG=warn` and rerun — see [Rust crate logging](#xml-disassemble-output-rust-crate).

**Extending with multiLevel.** When a metadata type has deeply-nested repeatable blocks (a block inside a block), add a `multiLevel` override to decompose those inner arrays into their own subdirectories. `bot` and `loyaltyProgramSetup` ship with built-in `multiLevel` defaults applied automatically. See the [admin handbook](https://github.com/mcarvin8/sf-decomposer/blob/main/docs/HANDBOOK.md) for ready-to-paste recipes for Bots, Flexipages, Layouts, Flows, and more.

**Type-specific notes (unique-id):**

- **Custom Labels (`labels`)** — always forced to `unique-id` (grouped-by-tag would be a no-op since every element shares the same tag). Each label becomes its own file:

  ```
  labels/
  ├── CustomLabels.labels-meta.xml                    ← original file (safe to delete after decompose)
  ├── quoteAuto.label-meta.xml                        ← one file per <labels> entry, named by fullName
  └── quoteManual.label-meta.xml
  ```

- **Bot (`bot`)** — built-in `multiLevel` default applies two rules automatically: `botDialogs` (outer, keyed by `developerName`) and `botSteps` (inner, keyed by `type`). No config needed to get the canonical layout; override only to change it. See the [admin handbook](https://github.com/mcarvin8/sf-decomposer/blob/main/docs/HANDBOOK.md) for the full layout, step-shape notes, and single-rule variant.

  ```
  bots/
  └── Sample_Chat_Bot/
      ├── Sample_Chat_Bot.bot-meta.xml                 ← bot header (untouched)
      ├── v1/
      │   ├── nlpProviders/
      │   │   └── EinsteinAi.nlpProviders-meta.xml
      │   ├── botDialogs/                              ← outer rule: one directory per dialog
      │   │   ├── Welcome/
      │   │   │   ├── Welcome.xml                      ← dialog leaf properties
      │   │   │   └── botSteps/                        ← inner rule: one entry per step
      │   │   │       ├── 853b6432/                    ← step with nested content → subdir
      │   │   │       │   └── ...
      │   │   │       └── 9d031e75.botSteps-meta.xml   ← step with no nested content → leaf file
      │   │   └── ...
      │   ├── .multi_level.json                        ← required for recompose; do not hand-edit
      │   └── v1.botVersion-meta.xml
      └── ...
  ```

- **Loyalty Program Setup (`loyaltyProgramSetup`)** — always forced to `unique-id` with a built-in `multiLevel` default that splits `<programProcesses>` into per-process folders containing per-`<parameters>` / per-`<rules>` files. Recompose always removes the decomposed tree (with or without `--postpurge`); rely on version control to inspect it after a deploy.

  ```
  loyaltyProgramSetups/
  └── Cloud_Kicks_Inner_Circle/
      ├── Cloud_Kicks_Inner_Circle.loyaltyProgramSetup-meta.xml   ← leaf properties (e.g. label)
      ├── .key_order.json
      ├── .multi_level.json                                       ← required for recompose; do not hand-edit
      └── programProcesses/                                       ← one folder per process, named by processName
          ├── Manual Points Adjustments/
          │   ├── Manual Points Adjustments.xml                   ← process leaf properties
          │   ├── .key_order.json
          │   ├── parameters/                                     ← one file per parameter, named by parameterName
          │   │   ├── EA_PerAdjustmentRewardTracking.parameters-meta.xml
          │   │   ├── EventType.parameters-meta.xml
          │   │   └── ...
          │   └── rules/                                          ← one file per rule, named by ruleName
          │       ├── Bulk Voucher Upload.rules-meta.xml
          │       ├── Finalize.rules-meta.xml
          │       └── Set Up Step.rules-meta.xml
          ├── Member Enrollment Process/
          │   └── ...                                             ← same shape per process
          └── ...
  ```

- **External Service Registration (`externalServiceRegistration`)** — the `<schema>` field (an embedded OpenAPI/JSON blob) is always extracted to a sidecar YAML file regardless of `--format`. The `<operations>` array is decomposed via `unique-id`, each entry named by its `<name>` element. Leaf properties remain in the main XML file.

  ```
  externalServiceRegistrations/
  ├── DropboxFileManagerHandler.externalServiceRegistration-meta.xml   ← original file (safe to delete after decompose)
  └── DropboxFileManagerHandler/
      ├── DropboxFileManagerHandler.externalServiceRegistration-meta.xml  ← leaf properties (<schema> and <operations> stripped)
      ├── DropboxFileManagerHandler.yaml                                   ← sidecar: <schema> content as YAML (always YAML)
      └── operations/                                                      ← one file per <operations> entry, named by <name>
          └── uploadFile.operations-meta.xml
  ```

#### grouped-by-tag strategy

All elements with the same tag (e.g. `<fieldPermissions>`) go into one file named after the tag (e.g. `fieldPermissions.xml`). Leaf elements are still grouped in the original-named file. Best for types with many small repeatable tags where one-file-per-element diffs would be noisy.

```
permissionsets/
└── HR_Admin/
    ├── HR_Admin.permissionset-meta.xml             ← leaf properties only
    ├── .key_order.json
    ├── applicationVisibilities.xml                 ← all applicationVisibilities entries
    ├── classAccesses.xml                           ← all classAccesses entries
    ├── fieldPermissions.xml                        ← all fieldPermissions entries
    ├── objectPermissions.xml
    ├── pageAccesses.xml
    ├── recordTypeVisibilities.xml
    ├── tabSettings.xml
    └── userPermissions.xml
```

**Extending with splitTags.** A `splitTags` override lets specific tags within a `grouped-by-tag` run break out into per-element files (split mode) or sub-grouped files (group mode), while all other tags stay grouped. See [splitTags grammar](docs/CONFIGURATION.md#splittags-grammar).

**Extending with decomposeNestedPermissions.** For `permissionset` and `mutingpermissionset`, add `--decompose-nested-permissions` (`-p`) to further decompose `<objectPermissions>` into per-object files and group `<fieldPermissions>` by object — similar to Salesforce's `decomposePermissionSetBeta2` but with more format and strategy options.

Recompose writes `<objectPermissions>` and `<fieldPermissions>` back in their original order, even when field permissions for different objects were interleaved. The order is recorded in `.element_order.json` and `.group_order.json` beside the decomposed files. Entries added after decomposing follow the recorded ones.

```bash
sf decomposer decompose -m "permissionset" -s "grouped-by-tag" -p
sf decomposer decompose -m "mutingpermissionset" -s "grouped-by-tag" -p
```

```
permissionsets/
└── HR_Admin/
    ├── HR_Admin.permissionset-meta.xml             ← leaf properties
    ├── .key_order.json
    ├── applicationVisibilities.xml                 ← grouped-by-tag stays grouped
    ├── classAccesses.xml
    ├── pageAccesses.xml
    ├── recordTypeVisibilities.xml
    ├── tabSettings.xml
    ├── userPermissions.xml
    ├── fieldPermissions/                           ← grouped per object (decompose-nested-permissions)
    │   └── Job_Request__c.fieldPermissions-meta.xml
    └── objectPermissions/                          ← one file per object
        └── Job_Request__c.objectPermissions-meta.xml
```

---

### Supported Metadata

All parent and child metadata types from this plugin's vendored copy of the [@salesforce/source-deploy-retrieve](https://github.com/forcedotcom/source-deploy-retrieve) (SDR) metadata registry are supported, except where noted below. Child types (e.g. `field`, `listView`, `validationRule`) resolve via their parent in the registry and behave like any other type — most are leaf-only and will be skipped non-fatally if their files contain no nested repeatable elements (the Rust disassembler logs a skip at `RUST_LOG=error`, but the CLI does not fail).

**Where files are found.** Like the Salesforce CLI (SDR), sf-decomposer finds a type's files by their `*.{suffix}-meta.xml` suffix anywhere in a package directory. That includes custom-named folders (`unpackaged/pre/1_settings/`), differently cased folders (`permissionSets/`), nested subfolders (`flexipages/record-pages/`), and other types' folders. The exceptions are the types SDR resolves by folder: bundles (`aura`, `lwc`, ...), bots, object translations, and the other strict-folder types. Folder-organized types (reports, dashboards, documents, email templates) and labels keep their own folder layout. Manifest-scoped runs (`--manifest`) still look in folders named after each type.

Use the metadata **suffix** for `-m` / `--metadata-type`, as in the vendored [`metadataRegistry.json`](src/metadata/registry/metadataRegistry.json) (synced weekly from upstream SDR — see [`sync-metadata-registry.yml`](.github/workflows/sync-metadata-registry.yml)), or infer from the file name: `*.{suffix}-meta.xml`. A few suffixes are shared by more than one type (e.g. `site` is both SiteDotCom and CustomSite) and only select one of them; pass the exact type name instead (`-m CustomSite`) to select another. Config `overrides` use the same value you pass to `-m`.

**Common Examples:**

| Metadata Type                 | CLI value                     | Notes                                                                                                                                                                                                                                                                                                                      |
| ----------------------------- | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Custom Labels                 | `labels`                      | Strategy overridden to `unique-id` if `grouped-by-tag` is provided (grouping labels by tag would be no different from the original file).                                                                                                                                                                                  |
| Workflows                     | `workflow`                    |                                                                                                                                                                                                                                                                                                                            |
| Profiles                      | `profile`                     |                                                                                                                                                                                                                                                                                                                            |
| Permission Sets               | `permissionset`               | Supports `--decompose-nested-permissions` with grouped-by-tag.                                                                                                                                                                                                                                                             |
| Muting Permission Sets        | `mutingpermissionset`         | Extends permission set metadata type. Supports `--decompose-nested-permissions` with grouped-by-tag.                                                                                                                                                                                                                       |
| AI Scoring Model Definition   | `aiScoringModelDefinition`    |                                                                                                                                                                                                                                                                                                                            |
| Decision Matrix Definition    | `decisionMatrixDefinition`    |                                                                                                                                                                                                                                                                                                                            |
| Bot                           | `bot`                         | Built-in `multiLevel` default splits `botDialogs` (by `developerName`) and `botSteps` (by `type`) automatically. No config required; override only to change the layout. See [Decompose Strategies](#decompose-strategies) and the [admin handbook](https://github.com/mcarvin8/sf-decomposer/blob/main/docs/HANDBOOK.md). |
| Marketing App Extension       | `marketingappextension`       |                                                                                                                                                                                                                                                                                                                            |
| Loyalty Program Setup         | `loyaltyProgramSetup`         | Always forced to `unique-id`; `grouped-by-tag` is overridden. Built-in `multiLevel` splits `<programProcesses>` into per-process folders automatically. Recompose always removes the decomposed tree. See [Decompose Strategies](#decompose-strategies).                                                                   |
| External Service Registration | `externalServiceRegistration` | The `<schema>` field is always extracted to a sidecar YAML file (format forced to YAML regardless of `--format`). The `<operations>` array follows normal `unique-id` decomposition, named by `<name>`. See [Decompose Strategies](#decompose-strategies).                                                                 |

For a comprehensive breakdown of supported, leaf-only, and unsupported metadata types — including multi-level decomposition patterns, Salesforce native decomposition conflicts, and adapter strategy limitations — see [**METADATA_SUPPORT.md**](./docs/METADATA_SUPPORT.md).

#### Exceptions

| Situation                                                                                                             | Message                                                                                                                           |
| --------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `botVersion` used directly                                                                                            | Automatically redirected to `bot` with a warning. No error is thrown.                                                             |
| Child type stored with its parent (e.g. `assignmentRule`, `sharingCriteriaRule`, `workflowAlert`, `fieldTranslation`) | Automatically redirected to the parent suffix (e.g. `assignmentRules`) with a warning. No error is thrown.                        |
| Custom Objects                                                                                                        | `Custom Objects are not supported by this plugin.`                                                                                |
| Unsupported SDR strategies (e.g. matchingContentFile, digitalExperience, mixedContent, bundle)                        | `Metadata types with [matchingContentFile, digitalExperience, mixedContent, bundle] strategies are not supported by this plugin.` |
| Invalid or unknown suffix or type name                                                                                | `Metadata type not found for the given suffix or type name: [value].`                                                             |

---

### Manifest-scoped Runs

`-x` / `--manifest` is supported by every `sf decomposer` command and accepts the same `package.xml` you pass to `sf project deploy start -x`. Only the listed components are decomposed/recomposed; everything else is left alone.

- Wildcards (`<members>*</members>`) expand against your local source.
- Folder members (e.g. `MyFolder/MyReport`) resolve by walking the folder.
- Types the plugin does not support (e.g. `CustomObject`, `ApexClass`) are skipped with a warning, so the same manifest can drive both deploys and decomposer runs.
- If both `--metadata-type` and `--manifest` are supplied, the run is scoped to their intersection.

Example manifest:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
  <types>
    <members>HR_Admin</members>
    <name>PermissionSet</name>
  </types>
  <types>
    <members>Case</members>
    <name>Workflow</name>
  </types>
  <version>58.0</version>
</Package>
```

```bash
sf decomposer recompose -x "manifest/package.xml"
sf project deploy start -x "manifest/package.xml"
```

---

### Per-Type & Per-Component Overrides

The optional `overrides` array in `.sfdecomposer.config.json` lets you vary format, strategy, and decomposition options per metadata suffix or per individual component without splitting the run into multiple invocations.

See [CONFIGURATION.md](docs/CONFIGURATION.md) for the full reference: override fields, component key conventions, precedence rules, and grammar for `splitTags`, `multiLevel`, and `uniqueIdElements`.

---

### Ignore Files

#### .forceignore

The Salesforce CLI must **ignore** decomposed files and **allow** recomposed files. Use `--update-forceignore` on your first `sf decomposer decompose` run to populate this file automatically, or copy the [sample .forceignore](https://raw.githubusercontent.com/mcarvin8/sf-decomposer/main/examples/.forceignore) and set patterns for the extensions you use (`.xml`, `.json`, `.yaml`, etc.).

> **Note:** For each processed type, `--update-forceignore` adds a pattern like `**/flows/**/*.xml` (ignore all decomposed pieces) plus `!**/flows/*.flow-meta.xml` (re-allow the original file). Labels use a flat pattern (`**/labels/*.xml` + `!**/labels/*.labels-meta.xml`, re-allowing the labels file under any name) since they decompose directly into the type directory. Bots use a component-dir pattern (`**/bots/**/*.xml` + `!**/bots/*/*.bot-meta.xml` + `!**/bots/*/*.botVersion-meta.xml`) to handle nested decomposed files and both original suffixes. Directories shared by several metadata types (e.g. `moderation`, which holds both `keywords` and `rule` files) use a nested-only pattern (`**/moderation/*/**/*.xml`) so the other types' original files stay deployable; decompose and recompose likewise only touch the requested type's files there. Folders a type's files are found in by suffix (see [Supported Metadata](#supported-metadata)) get a path-specific pair, such as `unpackaged/pre/1_settings/*/**/*.xml` + `!unpackaged/pre/1_settings/*.settings-meta.xml`. If you used `--update-forceignore` (or `--update-gitattributes`) before sf-decomposer found files outside the type's folders, run it again so those folders' decomposed files are ignored.

#### .sfdecomposerignore

Optional. In the project root, list paths/patterns to skip when **decomposing** (same syntax as [.gitignore 2.22.1](https://git-scm.com/docs/gitignore)). Ignored files are not recomposed from.

#### .gitignore

Optional. Ignore recomposed metadata so it isn't committed. See the [sample .gitignore](https://raw.githubusercontent.com/mcarvin8/sf-decomposer/main/examples/.gitignore).

---

### Using with sfdx-git-delta

[sfdx-git-delta](https://github.com/scolladon/sfdx-git-delta) (sgd) detects changed metadata by comparing git refs. It finds changes by looking for root-level metadata files — e.g. `flows/MyFlow.flow-meta.xml` — matching patterns from the Salesforce metadata registry.

sf-decomposer is compatible with sgd as long as those root files are present in git at the point sgd runs.

#### Recommended: keep root files in git and recompose before commit

For `sfdx-git-delta` to detect a change, the root metadata file must be updated in git. Keeping root files in the repository is not enough by itself: if you edit decomposed files but commit without recomposing, the root file will remain unchanged, and sgd may not detect the metadata change.

Without `--postpurge`, the original root metadata file stays in the repo alongside the decomposed pieces. After recomposition, the root file is updated and sgd detects the change normally. No extra sgd configuration is needed.

#### Recommended sgd config and pre-commit setup

Add the following to `.sfdecomposer.config.json`:

```json
{
  "metadataSuffixes": "flow,permissionset",
  "postPurge": false,
  "decomposedFormat": "xml",
  "skipPrerunHook": true
}
```

- **`postPurge: false`** — keeps root files in git so sgd can detect changes.
- **`skipPrerunHook: true`** — disables the automatic recompose that fires before `sf project deploy start`. Since root files are already recomposed at commit time (by the pre-commit hook below), the prerun hook would just repeat that work redundantly. Skipping it also avoids a full-workspace recompose when sgd has already scoped the deploy to a subset of components.

Install the bundled pre-commit hook (copy and make executable):

```bash
cp examples/pre-commit .husky/pre-commit
# or for a plain git hook:
cp examples/pre-commit .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit
```

The hook runs `sf decomposer recompose --config`, then stages the updated root files so they are included in the commit. sgd then sees the updated root files when it compares refs in CI.

> **Note:** With `skipPrerunHook: true`, any `sf project deploy start` that runs without going through the pre-commit hook first (e.g., an emergency manual deploy) will not auto-recompose. In that case, run `sf decomposer recompose --config` manually before deploying.

Use one of these workflows depending on your setup:

- **Pre-commit hook (recommended):** Install `examples/pre-commit` as described above. The hook recomposes automatically before every commit.
- **Manual:** Run `sf decomposer recompose --config` before each `git commit`.

**Suppressing diff noise on root files.** Keeping root files in git means `git diff` and GitHub PR views show both the root file and the decomposed pieces. Pass `--update-gitattributes` on your first `sf decomposer decompose` run to suppress that noise automatically:

```bash
sf decomposer decompose -m "flow" -m "permissionset" --update-gitattributes
```

This appends patterns like the following to `.gitattributes`, creating the file if it doesn't exist:

```gitattributes
**/flows/*.flow-meta.xml -diff linguist-generated=true
**/permissionsets/*.permissionset-meta.xml -diff linguist-generated=true
```

- `-diff` — `git diff` / `git show` skip textual content for these files
- `linguist-generated=true` — GitHub collapses the file in PR diff views; the file is still expandable

Git still tracks the root files, so sgd works. The root files become invisible noise during code review. You can also set `updateGitattributes: true` in `.sfdecomposer.config.json` to apply this automatically after every hook-triggered decomposition.

#### If you use `--postpurge`

`--postpurge` removes the root metadata file after decomposing. Only the decomposed pieces remain in git. sgd cannot detect changes to these nested files — they do not match the registry's file patterns.

**For CI pipelines**, explicitly recompose into a temporary commit before running sgd, then continue without pushing the commit (CI runners are ephemeral):

```bash
sf decomposer recompose -m "flow" -m "permissionset"
git add -A && git commit -m "ci: recompose for sgd" --no-verify

sf sgd source delta --from "$PREV_DEPLOYMENT_SHA" --to HEAD --output ./delta
sf project deploy start --source-dir ./delta
# temporary commit is discarded when the runner tears down
```

#### Incompatibility: `--postpurge` + sgd + prerun hook

The sf-decomposer prerun hook recomposes automatically when `sf project deploy start` fires — but that happens **after** sgd has already produced its delta. sgd runs on the committed (decomposed-only) state and cannot identify the changed components.

If you use the prerun hook, do not combine it with `--postpurge` and sgd. The compatible combinations are:

| Setup                                                             | Works?                                                                          |
| ----------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| No `--postpurge` + sgd + hook                                     | ✅ Root files in git; hook recompose at deploy is harmless (redundant but safe) |
| No `--postpurge` + sgd + pre-commit hook + `skipPrerunHook: true` | ✅ Recomposed before commit; deploy hook skipped intentionally                  |
| No `--postpurge` + sgd, no hook                                   | ✅ Recompose manually before commit                                             |
| `--postpurge` + hook, no sgd                                      | ✅ Full deploy; hook recomposes at deploy time                                  |
| `--postpurge` + sgd + CI recompose commit, no hook                | ✅ Explicit recompose step before sgd                                           |
| `--postpurge` + sgd + hook                                        | ❌ sgd runs before hook; delta is wrong                                         |

---

### Troubleshooting

#### Missing sfdx-project.json

The plugin looks for `sfdx-project.json` from the current directory up to the drive root. If it's not found:

```
Error (1): sfdx-project.json not found in any parent directory.
```

#### Package Directories Not Found for Given Metadata Type

This plugin relies on a vendored snapshot of the @salesforce/source-deploy-retrieve metadata registry to map each metadata type to its expected directory name.

If you provide a metadata type whose corresponding directory does not exist in any of your package directories, the plugin will fail with:

```
No directories named ${metadataTypeEntry.directoryName} were found in any package directory.
```

For example, if you attempt to decompose Custom Labels but none of your package directories contain a "labels" folder, the plugin will throw this error.

#### Removing References to Deleted or Uninstalled Metadata

Permission sets, profiles, and similar files keep references to objects, fields, classes, and pages even after those components are deleted from the org or their managed package is uninstalled. Deploys then fail on the stale references. Salesforce does not remove these entries for you.

With the `unique-id` strategy, each reference is its own file named after the component it points to, so removing a reference means deleting that file and recomposing. The plugin rebuilds the XML from whatever files remain.

```bash
# 1. Decompose with unique-id (the default)
sf decomposer decompose -m "permissionset" -m "profile"

# 2. Delete the decomposed files for the stale components, e.g. an uninstalled "oldns" package
find force-app -path "*permissionsets/*" -name "*oldns__*" -delete
find force-app -path "*profiles/*" -name "*oldns__*" -delete

# 3. Review what was removed, then recompose
git status
sf decomposer recompose -m "permissionset" -m "profile"
```

You can delete single files, whole folders (for example every `classAccesses/` entry), or pattern matches across many components. Check every folder: references to namespaced components show up in `objectPermissions/`, `fieldPermissions/`, `tabSettings/`, `recordTypeVisibilities/`, `classAccesses/`, `pageAccesses/`, and others. Grep the decomposed tree for the namespace or component name before recomposing, and review the diff to confirm nothing else matched the pattern.

This cleanup doesn't work with `grouped-by-tag`, because all entries for a tag share one file. Run step 1 with `-s unique-id --prepurge` to switch first. The `--decompose-nested-permissions` layout splits only `objectPermissions/` and `fieldPermissions/` by object; other tags stay grouped.

#### XML disassemble output (Rust crate)

The underlying Rust crate logs through [env_logger](https://docs.rs/env_logger). Set `RUST_LOG` to opt into more verbosity:

| Level            | What it covers                                                                                                                                                                                |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `RUST_LOG=error` | Default. Parse errors and skipped files: leaf-only XML (nothing to decompose), an empty root element, or [comments outside the root element](#decompose-strategies).                          |
| `RUST_LOG=warn`  | Adds [sibling-collision fallback](#filename-safety-unique-id) signals — one line per colliding group (parent tag, collided id, sibling count). **Recommended in CI** when shipping overrides. |
| `RUST_LOG=off`   | Disables rust crate logging. **Recommended** for the `sf decomposer verify` command.                                                                                                          |

Example `WARN` (CustomApplication where four `actionOverrides` siblings shared the action name `View`):

```
[2026-05-04T15:21:09Z WARN config_disassembler::xml::builders::build_disassembled_files]
  uniqueIdElements collision: <actionOverrides> id "View" matched 4 sibling elements;
  falling back to SHA-256 content hashes for the colliding group.
  Consider adding more discriminating fields to uniqueIdElements for this metadata type.
```

---

## Tested Against Real Projects

Every week, CI decomposes and recomposes the metadata in public Salesforce DX projects, each pinned to a fixed commit, on Linux and Windows. It checks that every file comes back byte-for-byte; the only accepted difference is whitespace in files formatted with tools like Prettier. The [corpus coverage page](https://github.com/mcarvin8/sf-decomposer/blob/main/scripts/corpus/COVERAGE.md) lists the projects and the metadata types verified in each.

To check that your own project's metadata survives a round trip, without changing any files, run [`sf decomposer verify`](#sf-decomposer-verify).

---

## Built With

- [config-disassembler-node](https://github.com/mcarvin8/config-disassembler-node) – Disassemble large XML files into smaller, manageable files and reassemble when needed. Node.js + Rust (NAPI-RS).
- [@salesforce/source-deploy-retrieve](https://github.com/forcedotcom/source-deploy-retrieve) – Source of the vendored metadata registry (`src/metadata/registry/metadataRegistry.json`), synced weekly. Not a runtime dependency — this plugin ships its own minimal registry lookup and package.xml parser instead.

---

## Migrating from Native Decomposition

Already using Salesforce CLI built-in `decomposePermissionSetBeta2`, `decomposeCustomLabelsBeta`, or similar presets? See [MIGRATION.md](https://github.com/mcarvin8/sf-decomposer/blob/main/docs/MIGRATION.md) before switching over to sf-decomposer.

---

## Contributing

Contributions are welcome. See [CONTRIBUTING.md](https://github.com/mcarvin8/sf-decomposer/blob/main/CONTRIBUTING.md).

---

## Issues

Please open an [issue](https://github.com/mcarvin8/sf-decomposer/issues) to report any bugs or suggest new features.

---

## License

[MIT](LICENSE.md). Bundled third-party material (Salesforce's metadata
registry from `@salesforce/source-deploy-retrieve`, Apache-2.0) is listed in
[THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
