A useful Agentforce prototype can begin with a topic, a set of instructions, and one or two actions. A production agent is a different architecture problem because it must operate across transactions, retrieve governed data, survive partial failures, avoid duplicate side effects, and provide enough telemetry for support teams to reconstruct what happened. The LLM remains important, but it is only one runtime component inside that larger system.
The terms prompt engineering, context engineering, harness engineering, loop engineering, and graph engineering describe different responsibilities in that architecture. They are not successive replacements for one another, and they are not synonyms for “use more agents.” Each term points to a separate design boundary: instructions, runtime information, durable execution, recurrence, and coordination.
This article develops those boundaries through a Salesforce use case that is familiar to service and integration teams. An ecommerce company wants an agent to resolve delayed shipments using Service Cloud data, an external carrier API, inventory availability, and replacement policies. The example is intentionally more technical than a product demonstration because the interesting questions are about state, transactions, security, orchestration, testing, and cost.
Five layers, five architecture responsibilities
The cleanest way to reason about the terminology is to identify which part of the system owns each concern. Prompt and context engineering shape an individual reasoning turn. Harness, loop, and graph engineering govern how those turns participate in a reliable business process.
| Layer | Architecture question | Typical Salesforce implementation surface |
|---|---|---|
| Prompt engineering | What role, objective, constraints, and output contract apply to this turn? | Agent Script instructions, topics, Prompt Templates, action descriptions |
| Context engineering | Which records, knowledge, action results, and external facts should the model see now? | CRM data, Knowledge, Data 360 grounding, retrievers, Flow/Apex action outputs |
| Harness engineering | How does work continue across steps, failures, and context resets? | Agentforce runtime, actions, Flow/Apex orchestration, durable state, tests, retry policy |
| Loop engineering | What starts the next run, and how does the system own a recurring responsibility? | Platform Events, Change Data Capture, scheduled automation, queues, persisted checkpoints |
| Graph engineering | How do deterministic steps, specialist agents, approvals, and parallel branches connect? | Topics and subagents, actions, Flow, Apex, MuleSoft, external orchestrators |
The boundaries overlap in real implementations. A harness can contain a graph, a graph can contain agent nodes with internal tool loops, and a long-running loop needs a harness on every iteration. The terms remain useful because they prevent teams from trying to solve every failure by editing the prompt.

Prompt and context engineering define the reasoning boundary
For the delayed-shipment use case, prompt engineering defines the agent’s scope and behavioral contract. The instructions can require the agent to verify the customer, avoid promising a replacement before eligibility is confirmed, and hand off cases that exceed a financial threshold. Action descriptions also matter because the reasoning engine uses them to select the appropriate capability.
Instructions should not carry business rules that require deterministic enforcement. A sentence such as “never replace an order worth more than ₹50,000 without approval” helps the model plan, but the Apex or Flow action that creates the replacement must enforce the same rule. The prompt guides reasoning; the action boundary protects data and side effects when the reasoning is wrong.
Context engineering decides what the model receives for the current decision. A shipment-resolution turn might need the Case ID, Order Summary ID, promised delivery date, latest carrier event, replacement entitlement, available stock, and relevant Knowledge excerpt. It does not need the customer’s entire activity history or every article in the service knowledge base.
Salesforce supports several context paths, and they serve different access patterns. Transactional facts can come from narrowly scoped SOQL, Flow, or Apex actions, while unstructured policy content can be grounded through Knowledge, an Agentforce Data Library, or retrieval over Data 360. Salesforce’s Agentforce documentation also defines actions as callable tasks backed by Flow, Apex, or Prompt Templates, which makes the action input and output schema part of the context contract (Salesforce Developers).
The context contract deserves the same care as an API contract. Inputs should use stable identifiers instead of customer-entered names where possible, and outputs should distinguish SUCCESS, NOT_FOUND, NOT_ELIGIBLE, RETRYABLE_ERROR, and FATAL_ERROR rather than returning prose for every outcome. Structured results reduce tokens, simplify routing, and give the harness something deterministic to evaluate.
Security belongs inside this boundary rather than being added after the agent works. Salesforce agents respect platform access controls, but execution context varies by agent type and custom actions inherit the behavior of their underlying Flow, Apex, or Prompt Template. Architects should use a unique agent user where applicable, grant least privilege through permission sets, enforce sharing and user-mode data operations in Apex, and treat external credentials as a separate authorization surface (Salesforce Well-Architected, Salesforce Help).
Harness engineering is the durable control plane
An Agentforce session can reason about the delayed shipment and invoke an action, but the business process may outlive that session. The carrier could be unavailable, inventory could be replenished tomorrow, or a high-value replacement could wait several hours for approval. A harness provides the execution lifecycle that continues outside one prompt and one context window.
The harness should persist business progress separately from conversational history. For this use case, a custom Agent_Work_Item__c record or an external workflow store could contain a correlation key, current state, attempt count, next-run time, policy version, last error, and references to produced artifacts. The conversation may help explain a decision, but it should not be the system of record for whether the replacement was actually created.
A robust harness iteration has a narrow transaction boundary:
- Load the work item and acquire an execution guard.
- Select one eligible step from durable state.
- Build the minimum context required for that step.
- Invoke one action or specialist agent.
- Validate the structured result and any expected side effect.
- Commit the new state, attempt metadata, and next transition.
- Enqueue or publish the continuation only after the state is durable.
This structure permits context resets without losing the process. It also prevents a common failure mode in which the model summarizes earlier work as complete even though no committed record or external confirmation exists. Completion is derived from state and evidence, not from the model’s final sentence.
Idempotency must be implemented below the reasoning layer. A replacement action can use a deterministic key such as CaseId + ResolutionType + ShipmentVersion, store it in a unique External ID field, and upsert rather than insert blindly. The model may recommend retrying, but Apex, Flow, middleware, or the target service must ensure that a retry cannot create a second replacement.
Transaction design also matters when Salesforce and the carrier system cannot commit atomically. Treat the workflow as a saga: commit a local intent, perform the remote operation through a Named Credential or integration layer, record the external reference, and define a compensating path for partial failure. If downstream event consumers depend on records written in the publishing transaction, use the appropriate Publish After Commit behavior rather than allowing them to race uncommitted data (Salesforce Integration Patterns).
Testing should target the harness contract, not only the wording of the final response. Salesforce’s agent testing APIs can define expected action sequences, context variables, and response expectations, while Apex and Flow tests validate the deterministic action layer. A meaningful regression suite should cover duplicate triggers, carrier timeouts, stale inventory, policy changes, denied permissions, approval rejection, and replay after a partially completed run (Salesforce Developers).

Loop engineering makes the process proactive
The harness can finish work reliably after it receives a work item. Loop engineering defines how new work is detected, how unresolved work returns, and how the system decides that no further run is required. In other words, the harness owns an execution, while the loop owns a continuing operational responsibility.
The delayed-shipment loop can begin from several Salesforce mechanisms. Change Data Capture can react to relevant record changes, a custom Platform Event can represent a signal from the carrier integration, and scheduled Flow or Apex can sweep orders whose promised date has passed without a terminal shipment event. The correct trigger depends on latency, event source, volume, ordering requirements, and recovery expectations rather than on which tool is easiest to demo.
An event-driven version could publish Late_Shipment_Detected__e with CorrelationKey__c, OrderId__c, ObservedAt__c, CarrierEventVersion__c, and ReasonCode__c. The subscriber creates or updates the durable work item and then exits quickly, allowing the harness to process the resolution in separate transactions. External publishers and subscribers can use Pub/Sub API, which Salesforce documents as a unified interface for platform events and Change Data Capture (Salesforce Developers).
Event transport is not workflow state. Consumers must tolerate retries, duplicate business signals, late arrival, and changes that make earlier work obsolete. Correlation keys, version checks, unique constraints, and explicit state transitions should decide whether an event creates work, advances existing work, or is safely ignored.
The loop also needs a control policy. Retryable carrier errors can use exponential backoff with a maximum attempt count, while policy ambiguity should move the work item to human review immediately. A terminal state must stop future automation, and a manual override must be able to cancel or supersede an in-flight run.
Loop engineering therefore extends beyond a schedule or a while statement. The production concern is a feedback system with a trigger, a durable checkpoint, a verifier, a next-run policy, a budget, and an escalation path. Without those elements, recurrence increases the rate of repeated failure rather than the rate of useful work.

Graph engineering makes dependencies explicit
The shipment-resolution workflow contains work that can be decomposed. Carrier investigation, inventory lookup, entitlement evaluation, and fraud screening may be independent reads, while replacement creation must wait for their results. Graph engineering models those relationships as nodes and edges instead of asking one agent to discover the full control flow repeatedly.
A node can be deterministic code, a Flow, an Apex action, an external service, a human approval, or a specialist agent. An edge can be unconditional, conditional on structured output, or driven by an event. The graph becomes an executable description of which component may act, what it must receive, and which transitions are valid afterward.
For this use case, an intake node first validates identity and required identifiers. Three independent nodes then retrieve carrier status, replacement inventory, and policy entitlement. A deterministic join verifies that all required evidence is present, after which a policy gate routes the case to automatic replacement, human approval, or a no-replacement response.
The LLM should be placed where semantic judgment adds value, such as interpreting an unusual carrier note or composing a customer-specific explanation. Deterministic nodes should retain calculations, authorization, record locking, monetary thresholds, and side-effect validation. This mixed graph is usually more reliable than making every node agentic.
Agentforce provides native concepts for topics, subagents, actions, context, and guardrails, while Salesforce’s enterprise agentic architecture guidance describes supervisor and specialist patterns for multi-agent systems. Flow, Apex, MuleSoft, and external orchestrators can implement additional graph edges when the process crosses systems or requires durable waiting. The logical graph should not be confused with a promise that every branch executes concurrently; actual parallelism depends on the selected runtime and transaction model (Salesforce Architects).
Graphs and loops are not competing architectures. A loop is a cyclic graph, and a production agent graph often contains retries, human waits, or evaluator feedback edges. The useful distinction is emphasis: loop engineering focuses on recurrence and convergence, while graph engineering focuses on decomposition, dependencies, and routing.

Harness cost is an architecture metric
Model price alone does not describe the cost of an agent transaction. Every reasoning call can include system instructions, topic and action descriptions, tool schemas, retrieved context, conversation history, and previous action results. The harness may make several calls before the user sees one response, and a graph may run several independent contexts.
This is why an identical model can have different effective costs in chat, a coding agent, and a multi-agent workflow. Anthropic reported that agents in its workloads used about four times as many tokens as chat interactions, while multi-agent systems used about fifteen times as many; those figures are observations from particular workloads rather than universal multipliers (Anthropic). The architecture lesson is that orchestration and context have a measurable unit cost.
Prompt caching can reduce repeated processing when the system prefix and tool definitions remain stable across adjacent calls. It does not eliminate the cost of newly retrieved Salesforce records, large action outputs, model responses, failed retries, or additional agent nodes. Context design, action granularity, and topology therefore remain cost controls even when the provider supports caching.
Salesforce teams should measure cost at the accepted business outcome rather than at the individual prompt. For a shipment-resolution process, useful metrics include agent turns, action invocations, retrieved tokens, retries, elapsed time, approval rate, escalation rate, duplicate side effects prevented, and cases that pass post-action verification. A low-cost run that leaves the Order Summary and Case inconsistent is not an optimization.
The same telemetry supports production diagnosis. Correlation IDs should connect the initial event, agent session, work item, Apex or Flow execution, external callout, and final business record. Salesforce provides agent testing and session-tracing capabilities, but application-level state and integration logs are still required to explain behavior across transaction and system boundaries.

A Salesforce reference implementation
The five engineering layers can be mapped to deployable Salesforce artifacts. The following design is not the only valid implementation, but it separates probabilistic reasoning from transactional control. That separation gives developers testable action contracts and gives architects explicit recovery and governance boundaries.
| Concern | Suggested artifact | Primary verification |
|---|---|---|
| Agent role and routing | Agent Script topics and instructions | Utterance routing and negative-scope tests |
| Grounded context | Knowledge/Data 360 retriever and narrow data actions | Relevance, freshness, and unauthorized-data tests |
| Transactional tools | Invocable Apex, Flow actions, or secured external actions | Apex/Flow unit tests and user-context tests |
| Durable progress | Agent_Work_Item__c or external workflow state | State-transition and concurrency tests |
| Recurring trigger | Platform Event, CDC, scheduled Flow, or Scheduled Apex | Replay, duplicate, backoff, and terminal-state tests |
| Cross-system access | Named Credential, MuleSoft, or governed MCP tool | Authentication, timeout, schema, and failure tests |
| Agent regression | Agentforce Testing API or Agentforce DX | Expected topic, action sequence, and response criteria |
| Operations | Session tracing plus application and integration telemetry | Correlated trace from trigger to committed outcome |
The implementation should start with one agent and a small action surface. Introduce specialist agents only when their context, permissions, evaluation criteria, or ownership genuinely differ. A graph of agents that all receive the same context and call the same tools increases coordination cost without creating meaningful separation of concerns.
Architecture review should focus on failure paths before expanding autonomy. Developers need to know what happens when an action times out after the external system has already committed, when an approval arrives after the policy version changes, or when the same event is received twice. Architects need to know which system owns truth, which state transition is authoritative, and which compensating action restores consistency.
The following rules provide a practical baseline for that review:
- Keep monetary limits, authorization, and irreversible side effects in deterministic code or Flow.
- Persist workflow state outside the agent session and version the policy used for each decision.
- Make every effectful action idempotent and return a structured outcome with an external reference.
- Use narrow action schemas so the model cannot supply fields it is not authorized to control.
- Separate investigation, approval, execution, and verification when their security or failure modes differ.
- Apply least privilege to agent users, Apex execution, Flow context, Named Credentials, and external principals.
- Put hard bounds on turns, retries, elapsed time, token or credit usage, and parallel branches.
- Test expected action sequences and prohibited actions, not only final response quality.
- Correlate events, sessions, actions, callouts, state changes, and human decisions.
- Provide an explicit terminal state, cancellation path, and human escalation queue.
These controls do not make the reasoning deterministic. They constrain where non-determinism is allowed and make its consequences observable. That is the architectural shift behind harness, loop, and graph engineering.
Final perspective
Prompt engineering defines instructions, while context engineering assembles the information for one decision. Harness engineering turns decisions into durable execution, loop engineering gives that execution a trigger and feedback cycle, and graph engineering organizes dependencies across deterministic services, agents, and people. A production Agentforce solution normally uses all five concerns even if the implementation does not use all five labels.
For Salesforce developers, the key design unit is the action contract and its transaction behavior. For architects, it is the end-to-end control plane: identity, data boundaries, state ownership, event semantics, recovery, observability, and cost. The LLM should reason inside those boundaries rather than being expected to create them at runtime.
The best architecture is not the one with the most agents or the deepest graph. It is the smallest system that can complete the business process, prove what it changed, recover from partial failure, and stop safely. Add autonomy only after those properties are visible in the design and executable in tests.
Sources and further reading
The four Caleb Writes Code videos provided the conceptual starting point for this article. Salesforce platform mappings were checked against current official developer and architecture documentation. The delayed-shipment example and implementation design are independent of the examples used in the videos.
- Loop Engineering explained in 8min
- Agent Harness explained in 8min
- Graph Engineering explained in 8min
- Why harness is SO expensive
- Agentforce Actions
- Enterprise Agentic Architecture and Design Patterns
- Agentic Patterns and Implementation with Agentforce
- Using the Right Tools and Patterns for Event-Driven Architectures
- Build Tests in Metadata API
- Salesforce Well-Architected: Secure
- How Anthropic built its multi-agent research system
