# Merging and closeout

[Documentation index](README.md) · [Safety and receipts](2026-10-06-safety-and-receipts.md) · [Workspace operations](2026-10-06-workspace-operations.md)

Plastic merges into the loaded workspace branch. Switching afterward does not move or integrate an earlier source-branch checkin.

## Choose a route

| Tool | Use | Boundary |
|---|---|---|
| `plastic_merge` | One noninteractive workspace merge | Native completion, not semantic correctness |
| `plastic_mergeToBranch` | Clean-start switch/update/merge/checkin sequence | One attempt per mutation; earlier effects remain recorded |
| `plastic_mergeBranches` | Workspace-free server-side merge | Separate same-repository/server contract below |

All workspace merge/checkin/closeout previews are zero-command plans, not conflict or readiness analysis. Undiscovered closeout defaults remain explicitly unresolved in preview.

## merge

The schema v2 receipt reports the exact request/argv, actual attempt/exit, `commandCompleted`, bounded native diagnostics and projection completeness. Native Plastic owns selector resolution and merge applicability. Branch, changeset, label and shelveset operands are forwarded without rewriting. Default auto uses `--nointeractiveresolution --mergetype=try --conflict-markers`; source/destination policies deliberately prefer a contributor and require explicit intent.

There are no per-file action proofs, one-link rules or Xlink ownership queries. Unfamiliar progress output does not turn observed native completion into failure. Native nonzero exit, stream failure, timeout, cancellation or unknown terminal state stops dependent actions. Partial effects can remain; do not replay automatically. Inspect/reconcile/validate native conflicts before another deliberate action. See [markers](2026-10-23-marker-merges-and-comments.md).

### Workspace observations

Status reports native facts and read completeness, not permission for a subsequent VCS operation. Standalone checkin forwards exact selected paths/options once and lets Plastic enforce eligibility. Deleted, moved, directory or unfamiliar pending records do not by themselves prohibit checkin or establish that workspace content needs repair. Compound closeout requires a clean start only because it performs an automatic checkin.

## mergeToBranch

```text
plastic_mergeToBranch(source="/main/owned-feature", target="/main", message="Merge owned feature", preflight=true)
```

Normal execution discovers a missing source from the loaded branch and a missing target from one exact source-parent query. Preview performs no discovery; omitted defaults remain unresolved. Branch inputs remain hierarchical branch selectors, not arbitrary merge operands.

The convenience sequence requires a complete clean initial pending inventory AND no merge state, even already on the target. It never discards work to become clean. It skips unnecessary switching, updates when requested, merges once and checks in once after prior native success. The stage ledger retains earlier effects and final informational observations. There is no duplicate ownership/readiness/checkin-preflight protocol or automatic recovery.

### Investigating unknown readiness

Schema v2 has no adapter-owned `checkinReadiness` assertion. Native merge completion does not mean semantic correctness, and clear markers do not prove all conflicts resolved. Native checkin enforces its own eligibility. Use standalone operations for deliberately selected pending work; closeout is only a clean-start convenience.

### Readiness and message admission

Explicit and derived comments are validated before mutation; CR/LF comments are supported, unsafe controls are not. An invalid derived comment stops before switching. Missing/ambiguous required branch or clean-start evidence stops the automatic workflow, not standalone commands.

No source-head lock, concurrent-edit isolation, scope exhaustion, rollback or atomic cross-repository transaction is claimed. Native failures stop continuation, without automatic checkin/undo/switch-back/replay.

### Bounds

Workspace mutation requests and argv have execution byte budgets. Diagnostic retention is 64 KiB stdout/16 KiB stderr, but streams continue draining to a real terminal event rather than killing a verbose command. Deadline/cancellation and bounded missing-terminal retirement remain. Identity observations have separate byte-budget/completeness facts; no semantic file-count cap is imposed. See the [receipt contract](2026-10-06-safety-and-receipts.md).

## Xlinks

Workspace merge and checkin delegate linked-repository behavior to Plastic. There is no adapter-owned mount inventory, ownership reconstruction, one-mount restriction, file-count limit or supported-status composition matrix.

A native checkin can emit root and linked changeset identities together. Schema v2 preserves their repository, server, branch and mount as observations. `createdChangeset` is the unique observed root emission and can be null even when the command completed; `linkedChangesets` contains observed mounted emissions. Inspect `identityObservation` separately from command completion. See [checkin](2026-10-06-workspace-operations.md#checkin) and [receipt semantics](2026-10-06-safety-and-receipts.md#workspace-mutation-receipt-v2).

For reproducible sandbox checks, see the [live Xlink test instructions](2026-10-26-live-workspace-regressions.md#writable-xlink-checkin-regression). Those tests do not establish an atomic cross-repository transaction or semantic merge correctness.

## mergeBranches

This route has no workspace mutation/fallback. Supply distinct fully qualified source/target branches in the same exact requested repository/server. The default `mode="apply"` requires a nonempty message; `mode="analyze"` is read-only remote conflict discovery and rejects a message, resolution file or conflict policy.

```text
plastic_mergeBranches(source="br:/main/source@Example Repository@example@unity", target="br:/main/target@Example Repository@example@unity", message="Merge source", preflight=true)
```

Inputs allow unambiguous `br:/branch@repository@server`, including literal host or full cloud/unity server suffix. Each control caps 4,096 UTF-16 code units. Workdir, unknown controls, malformed Unicode, and `@` inside branch/repository are rejected. Absolute local resolution-input paths are preserved, not trimmed or rewritten.

| Outcome/evidence | Interpretation |
|---|---|
| Preflight | Zero CLI; validates supplied local inputs and renders command intent, not remote conflicts |
| Analyzed | Complete supported point-in-time remote output; no applying command or contributor export |
| Completed | Admitted complete exit emitted one exact target/root changeset; conflict candidates require verified result inputs |
| No-op / ALREADY_CONNECTED | Classification with effect not-proven; not independently verified unchanged state |
| Conflict / unsupported / uncertain / failed | Stop; possible effects are not ruled out |

Applying performs one local help syntax check and at most one noninteractive server merge. Exact decimal ID/emitted server qualifier remain separate from requested server spelling; alias equivalence is unverified.

No source-link/head-exclusive/global/Xlink/rollback proof, retries, head unification or shelveset mode. Undetected server-side Xlink effects remain possible; accepting a full xlink conflict path does not verify linked-repository ownership or effects.

### Agent conflict-resolution workflow

1. **Inspect:** call `mode="analyze"` to execute `cm merge <source> --to=<target>` without `--merge`. Unlike `preflight`, this contacts the server. Read `conflictPaths`, parse/capture completeness and omission counts. Analysis supports the captured three-field `APPLY ADD/RM/FSPROT` and `DIS_OP_WARN CHG` profiles with bounded repository-absolute paths. `parse.warningsObserved` counts supported CHG discard warnings; it does not prove identical contributor content. Empty, malformed, unsupported-operation/subtype (including directory-conflict), other warning or failed output remains uncertain, not a clean merge. Applying has separate terminal/input verification. `analyzed` means a supported observation, not absence of conflicts.
2. **Understand contributors:** independently inspect base/source/destination for each conflict. The exact destination conflict path is usable as a resolution key, not a workspace path. This tool does not retrieve content or assign meanings to the numeric FILE_CONFLICT fields. If needed, use a read-only `cm merge <qualified-source> --to=<qualified-target> --printcontributors` inspection, without `--merge`, to establish contributor identities. Use `plastic_diff(mode="revisions", ...)` for deliberate comparisons after verifying file/repository/server-qualified selectors. For full bytes unavailable through typed tools, follow the [historical export fallback](../skills/using-plastic/references/changeset-operations.md#historical-export-fallback): fresh external temporary destinations only, never canonical workspace files or guessed revision IDs. Writable xlinks need independently verified linked-repository identities; do not qualify their revision IDs against the root repository by assumption.
3. **Resolve and validate:** write merged content into new local result files outside the workspace; preserve immutable contributor baselines. Review the result and run relevant validation before submission. Binary files may use `keep`, but choosing a side deliberately discards the other contributor's conflicting changes. Directory conflicts are not solved by this JSON feature; stop and choose a separately authorized workflow.
4. **Submit:** create a UTF-8 JSON file as below and pass its absolute path as `fileConflictsResolutionsFile` with a merge message. Each `path` must exactly match its observed FILE_CONFLICT destination path, including any writable-xlink prefix. Each entry requires exactly one of `keep` (`source`/`destination`) or an absolute readable regular `resultFile`. Duplicate paths and unknown fields are rejected. Input validation caps JSON at 1 MiB / 500 entries and records its SHA-256 plus counts, not file contents. The resultFile-only candidate-success route additionally hashes bounded canonical regular inputs before help, before dispatch and after completion; see [input verification](#result-file-input-verification).
5. **Observe:** inspect the receipt and any emitted target changeset. Never automatically retry a conflict, timeout or uncertain applying result. Keep source/target heads and all input files unchanged between inspection, validation and submission; these calls provide no transaction, head lock or atomic input snapshot; result-input hashes are not general server-byte proof. If the inputs or heads change, reassess instead of reusing stale merged content. The CLI owns current-conflict matching; its documented invalid-resolution rejection happens before upload, but opaque failures do not establish rollback.

```text
plastic_mergeBranches(source="br:/main/source@Example Repository@example@unity", target="br:/main@Example Repository@example@unity", mode="analyze")
plastic_mergeBranches(source="br:/main/source@Example Repository@example@unity", target="br:/main@Example Repository@example@unity", message="Integrate reviewed resolutions", fileConflictsResolutionsFile="/tmp/resolutions.json")
```

```json
{
  "resolutions": [
    { "path": "/src/Player.cs", "resultFile": "/tmp/merged/Player.cs" },
    { "path": "/art/logo.png", "keep": "source" },
    { "path": "/README.md", "keep": "destination" }
  ]
}
```

The paths above are POSIX examples; on Windows supply native absolute local input paths. The tool and `cm` never change/delete the caller's JSON or result files. The JSON takes precedence over an optional explicit `unlistedConflictPolicy="source"|"destination"`, which emits `--keepsource`/`--keepdestination` only for that intentional fallback. Omit it to keep the existing noninteractive behavior for unlisted conflicts; never select a fallback automatically. `--nointeractiveresolution` is always present, including analysis. The resolution flag is required in local help only when a file is supplied, so ordinary merges retain their existing capability requirements. Shelve sources/results are not added by this feature.

### Result-file input verification

The candidate-success route requires unique canonical conflict paths exactly covered by resultFile-only entries, with no keep or unlisted-discard policy. Result inputs must be regular nonsymlink files at canonical absolute paths. Aggregate result bytes are bounded to 4 MiB. Hash/identity observations are taken before help, revalidated before dispatch and checked after completion. Missing, changed, extra or mismatched inputs leave completion unverified; any observed emitted changeset remains recorded and must not be retried automatically.

`parse.resolvedConflictsVerified` counts candidates with matching stable caller inputs, not general proof of server-stored bytes. `parse.unknownOperationClasses` is a bounded closed set of sanitized classes; `unknownOperations` counts classes, not raw opcode strings. Exact root target branch/repository/server identity is required; alias equivalence is unverified. Observations do not lock the server or files: keep inputs and contributor heads immutable until completion.

### Server merge bounds

Stdout 64 KiB/stderr 16 KiB, fatal UTF-8, nullable observed start/terminal/exit facts. Help: 3 second deadline and 32,768 decoded-unit stdout gate (the updated help exceeds the former 16 KiB limit); merge: 30 second deadline with bounded termination escalation. Capture uncertainty never implies cancellation or safe replay.

Classify full framing/records before one aggregate 100-reference projection budget. Unknown/contradictory/malformed/overlimit evidence cannot become success. DTO 131,072 UTF-8 bytes; presentation 24,000 units. Core text/fenced JSON and native text/JSON share one observation; failures return native isError with no diagnostic duplication.

## Follow-up decisions

Inspect merge metadata and pending scope rather than assuming exit 0 permits checkin. Use finalization only with explicit policy intent, not as automatic conflict repair. Manual resolution and any later applying call remain agent/user decisions with their own scope.

For source/consumer/platform limits, see [receipt semantics](2026-10-06-safety-and-receipts.md#evidence-and-transport-limits) and [the workflow skill](../skills/using-plastic/SKILL.md).
