> For the complete documentation index, see [llms.txt](https://triton.pharos.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://triton.pharos.ai/instrumentation-skills/instrument-apex.md).

# Instrument Apex

The instrument-apex skill adds Triton logging to an Apex class or trigger — transactions, catch blocks, DML and callout payloads — then optionally deploys it.

The **instrument-apex** skill reads an Apex class or trigger, works out what *kind* of code it is, and adds Triton 2.0 instrumentation that follows the same patterns you'd write by hand — the entry-point template, resume-first transactions, `logNow` in every catch, `dmlResults` on partial DML, callout payloads, and flush at the right boundaries. Then it shows you the diff and, if you want, deploys.

{% hint style="info" %}
**Invocation is agent-specific.** In agents that support slash commands (Claude Code, Cursor) you invoke it as `/pharos:instrument-apex <path>`; in others you point the agent at this skill and give it the path. See [Running these in your agent](https://triton.pharos.ai/instrumentation-skills.md#running-these-in-your-agent). The `/pharos:` form below is a readable stand-in for "run this skill."
{% endhint %}

## Usage

{% code lineNumbers="true" %}

```bash
/pharos:instrument-apex <path> [--area <Area>] [--type <Type>] [--deploy]
```

{% endcode %}

| Argument   | Required | Meaning                                                                                                                                                                      |
| ---------- | :------: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `<path>`   |     ✅    | The `.cls` or `.trigger` file to instrument. If omitted, the skill asks.                                                                                                     |
| `--area`   |          | The business/functional Area for these logs. If omitted, the skill **infers** it from the code and matches related code. Accepts any String — enum values are just examples. |
| `--type`   |          | Technical classification. Defaults to `Backend`; inferred per method (e.g. `BackendCall` for callouts). Accepts any String.                                                  |
| `--deploy` |          | Deploy the file after you accept the diff. Without it, the skill asks at the end.                                                                                            |

{% hint style="info" %}
Logs are created by passing a fluent `TritonBuilder` to `Triton.log(...)` (buffered) or `Triton.logNow(...)` (immediate). Builders come from `Triton.t` — the template-derived builder that auto-stamps the current transaction id — or from `Triton.makeBuilder()` for a fresh one.
{% endhint %}

## What it instruments

The skill classifies the file's **structure** first, because the transaction and flush pattern depends on it — a trigger handler, an `@AuraEnabled` controller, a batch, a queueable, an `@future`, and a plain service class each get treated differently. Test classes (`@isTest`) are left alone entirely.

From there it applies:

* **Entry-point template.** At the start of the entry-point method (never a shared `static {}` block — the template is a shared static and the last writer wins), it sets the template with the Category, Type, and Area, then creates each log from `Triton.t`.
* **Resume-first transactions.** It always resumes an existing transaction before starting a new one, per the structure (see below).
* **Try/catch logging.** Every catch gets a `Triton.logNow(...)` with `.exception(e)` before the original `throw` — the flow is preserved, only logging is added.
* **DML result logging.** After partial-success DML (`allOrNone = false`), it adds `.dmlResults(results)`. A failure becomes a `DMLResult` log at ERROR with an issue; when every row succeeded, nothing is emitted, so the skill never wraps it in an `if`.
* **Callout / integration logging.** HTTP calls get `.integrationPayload(req, res)` and `Type.BackendCall` — the category stays the default `Apex`.
* **`System.debug` → Triton.** Every `System.debug(...)` in non-test code becomes a buffered `Triton.debug(...)`. (Debug lines are safe in production — verbosity is governed by Log Level metadata.)
* **Performance marks, where a span earns its place.** For a stretch of work that should show up as a span rather than as one timed log, the skill wraps it in `Triton.startMark()` / `Triton.endMark()` (closed in a `finally`), using `Triton.startTriggerMark()` in trigger handlers. Everything logged inside nests under the mark, and names are derived from the stack trace, so no strings are hand-typed. Marks are not added to every entry point; a one-off duration on a single log is still timed by hand. See [Performance Marks in Apex](https://triton.pharos.ai/common-apex-usage-patters/performance-marks.md).
* **Flush at boundaries.** `Triton.flush()` is added at the end of triggers, each batch `execute` chunk and `finish`, `Queueable`/`Schedulable` `execute`, `@future`, `@AuraEnabled`, and REST/invocable methods — **never** inside a loop.
* **Related objects.** Record ids flowing through a method are attached with `.relatedObject(id)` / `.relatedObjects(ids)`, prioritized on error and DML logs.

{% hint style="success" %}
**Auto-enrichment — don't add it by hand.** `Triton.log()` captures the stack trace, operation name, governor **limit info**, and (for Apex-category logs) the execution context automatically at log time. The skill deliberately does *not* add these manually, and neither should you.
{% endhint %}

### Template initialization

The entry-point method opens with the template:

{% code lineNumbers="true" %}

```apex
Triton.setTemplate(
    Triton.makeBuilder()                       // makeBuilder() defaults Category = Apex
        .type(TritonTypes.Type.Backend)
        .area(TritonTypes.Area.OpportunityManagement)
);

// then, per log:
Triton.info(Triton.t.summary('Fetching opportunities'));
```

{% endcode %}

### Transaction management (resume-first, per structure)

The goal is **one correlated transaction** across the whole call chain, so the skill always resumes first.

**Synchronous entry points** (`@AuraEnabled`, REST, `@InvocableMethod`) resume a caller-supplied id if there is one:

{% code lineNumbers="true" %}

```apex
if (String.isNotBlank(transactionId)) {
    Triton.resumeTransaction(transactionId);
} else {
    Triton.startTransaction();
}
```

{% endcode %}

{% hint style="info" %}
**The sanctioned signature exception.** Adding an optional `transactionId` parameter to an *entry-point* method — so it can stitch into an instrumented LWC's transaction — is the one time the skill will change a method signature. It's flagged explicitly in the diff. Everywhere else, signatures, access modifiers, and return types are left untouched. If you'd rather not touch the signature at all, the skill can use `Triton.withCache()` at entry instead, which carries the id via platform cache with zero param changes. Pick one mechanism per call chain and keep the LWC side consistent (the LWC skill passes a param named `transactionId`).
{% endhint %}

Other structures each get their own handling:

* **Trigger handlers** guard the start (`if (Triton.TRANSACTION_ID == null) Triton.startTransaction();`) so before/after and recursion don't reset the id, and log affected ids with `.relatedObjects(...)`, built null-safely — see [Trigger handlers](#trigger-handlers-logging-never-fails-the-write) below.
* **Batchable** classes implement `Database.Stateful` and take the caller's id in the constructor, but only *store* it there: the constructor runs in the caller's transaction, so `startTransaction()` there would overwrite the caller's id. `start` resumes that id (or starts one if there's none), `resumeTransaction(this.txId)` re-establishes it at the top of each `execute` and in `finish`, and the class **flushes per `execute` chunk** and in `finish` (each chunk is its own transaction).
* **Queueable / Schedulable** take a `String txId` constructor arg, resume it at the top of `execute`, and flush before returning.
* **@future** takes a `String transactionId` param (only primitives cross the boundary), resumes it, and flushes before returning.
* **Async dispatch sites** thread the current id through the hop:

{% code lineNumbers="true" %}

```apex
System.enqueueJob(new MyQueueable(payload, Triton.TRANSACTION_ID));
// or: myFutureMethod(recordId, Triton.TRANSACTION_ID);
```

{% endcode %}

* **Private / service methods** never start, resume, or stop a transaction — they use the ambient one set by the entry point. `Triton.stopTransaction()` is only ever called at a true end-of-chain boundary (batch `finish`, top-level entry-point completion).

### Try/catch — log and rethrow

`.exception(e)` sets the type, ERROR level, summary, stack trace, details, and flags issue creation — so no redundant `.level(...)`. Downgrading it — `Triton.warning(Triton.t.exception(e))` — keeps the exception detail but withdraws the issue; an explicit `.createIssue()` keeps it. A custom summary must chain **after** `.exception(e)`, or it gets overwritten:

{% code lineNumbers="true" %}

```apex
} catch (Exception e) {
    Triton.logNow(
        Triton.t
            .exception(e)
            .summary('AccountService.recalculate failed')  // optional; MUST follow .exception()
    );
    throw e;   // original throw behavior preserved
}
```

{% endcode %}

### DML result logging

{% code lineNumbers="true" %}

```apex
List<Database.SaveResult> results = Database.insert(records, false);
Triton.log(
    Triton.makeBuilder()
        .area(TritonTypes.Area.Accounts)   // Area set on the builder (or via template)
        .dmlResults(results)               // nothing is emitted when every row succeeded
);
```

{% endcode %}

### Callout / integration logging

{% code lineNumbers="true" %}

```apex
HttpResponse res;
try {
    res = new Http().send(req);
    if (res.getStatusCode() < 200 || res.getStatusCode() >= 300) {
        Triton.logNow(
            Triton.makeBuilder()
                .type(TritonTypes.Type.BackendCall)
                .area(TritonTypes.Area.RestAPI)
                .summary('Callout failed: ' + res.getStatus())
                .details('statusCode=' + res.getStatusCode())
                .integrationPayload(req, res)
                .error()
        );
    }
} catch (Exception e) {
    Triton.logNow(
        Triton.makeBuilder()
            .area(TritonTypes.Area.RestAPI)
            .exception(e)
            .integrationPayload(req, res)
    );
}
```

{% endcode %}

### Trigger handlers: logging never fails the write

A trigger runs inside someone else's DML. On a managed-package object — or any object a system or integration user writes to — a throw from your handler rolls back a write you don't own and may not be able to test as. Logging must never be the reason that happens.

**What Triton guarantees.** `Triton.log` and the level methods, `logNow`, `flush`, `flushTop`, the Flow **Log** action, and the LWC endpoint catch their own failures. If Pharos refuses a publish, those logs are dropped and the failure is written to the Apex debug log at `ERROR`; the business write goes ahead.

**What the skill still takes care of in your code:**

* **Null-safe builder arguments.** The builder expression runs in your code before Triton is called, so Triton can't catch what throws there — `Trigger.newMap.keySet()` in before insert, `record.Parent__r.Name` on an unqueried relationship, `e.getCause().getMessage()` when there's no cause. Record ids are built like this:

{% code lineNumbers="true" %}

```apex
Set<Id> recordIds = Trigger.newMap != null ? Trigger.newMap.keySet()
                  : Trigger.oldMap != null ? Trigger.oldMap.keySet()
                  : new Set<Id>();
Triton.info(Triton.t.summary('AccountTriggerHandler ' + Trigger.operationType).relatedObjects(recordIds));
```

{% endcode %}

* **Governor limits.** `System.LimitException` can't be caught by anyone. In a 200-record trigger the skill buffers with `Triton.log(...)` — never `logNow` in a loop — flushes once at the end of the handler, and keeps per-record details lean.
* **No new `try/catch` around business logic.** Where a catch already exists, it logs and keeps the existing throw or return.
* **One publish on managed-package objects.** `Triton.log(...)` plus a single `Triton.flush()` as the handler's last statement, rather than `logNow`. The [audit](https://triton.pharos.ai/instrumentation-skills/audit-logging.md) flags `logNow` and `flush` on these paths for review.

**The test it adds.** The skill adds a test that performs the triggering DML as a low-privilege user and asserts the write landed:

{% code lineNumbers="true" %}

```apex
@IsTest
private static void test_accountTrigger_write_survives_a_restricted_user() {
    User restricted = new User(
        ProfileId = [SELECT Id FROM Profile WHERE Name = 'Minimum Access - Salesforce' LIMIT 1].Id,
        Alias = 'trtnrst', Email = 'restricted@example.com',
        Username = 'restricted.' + System.currentTimeMillis() + '@example.com',
        LastName = 'Restricted', TimeZoneSidKey = 'GMT', LocaleSidKey = 'en_US',
        EmailEncodingKey = 'UTF-8', LanguageLocaleKey = 'en_US');
    insert restricted;
    // Assign only the permission sets the object needs.

    System.runAs(restricted) {
        Test.startTest();
        insert new Account(Name = 'Acme');
        Test.stopTest();
    }
    System.assertEquals(1, [SELECT COUNT() FROM Account], 'The instrumented trigger must not fail the write');
}
```

{% endcode %}

Know what this doesn't prove. `System.runAs` enforces record sharing only, not object or field permissions, and a user you can create in a test can't reproduce a hidden platform integration user. A passing test shows the handler survives a restricted human user; Triton's never-throw guarantee is what covers the rest. To prove your code survives a refused publish, see [`TritonTestFactory.failPublishing()`](https://triton.pharos.ai/methods-reference/apex-methods-reference/tritontestfactory.md#failpublishing).

## Review the diff

Before writing anything, the skill presents a summary — the structure it classified, the template it set, how it handled transactions, and counts of try/catch, DML, callout, `System.debug`, and flush changes (plus any sanctioned signature change) — followed by the key changes. You answer:

* **`yes`** — apply and write the file.
* **`modify`** — give free-form corrections; the skill re-applies and asks again.
* **`skip`** — stop without writing.

## Deploy

The instrumented content is written back to the **original** file (never a new one). Then, with `--deploy` or on confirmation:

{% code lineNumbers="true" %}

```bash
sf project deploy start --source-dir <path-to-file> --json
# or, if only sfdx is available:
sfdx force:source:deploy -p <path-to-file> --json
```

{% endcode %}

A `"status": "Succeeded"` reports the deployed component; failures show the component-failures table and stop without reverting your file.

## Where to go next

* [Instrument LWC](https://triton.pharos.ai/instrumentation-skills/instrument-lwc.md) — the front-end half of a stitched transaction.
* [Instrument Flows](https://triton.pharos.ai/instrumentation-skills/instrument-flows.md) — the Flow leg of the same trace.
* [Instrument the Org](https://triton.pharos.ai/instrumentation-skills/instrument-org.md) — run this skill across every class and trigger at once.
* [Logging in Apex](https://triton.pharos.ai/common-apex-usage-patters.md) · [Transaction Management](https://triton.pharos.ai/triton-best-practices/transaction-management.md) — the hand-written patterns the skill automates.
* [Performance Marks in Apex](https://triton.pharos.ai/common-apex-usage-patters/performance-marks.md) — the mark API the skill wraps entry points in.
* [Spans & Distributed Tracing](https://triton.pharos.ai/end-to-end/spans-and-tracing.md) — how these correlated transactions map to OpenTelemetry.
