# Communication Hub

Communication Hub turns a business event into a traceable **communication Task**. It resolves recipients and content, creates channel Executions, records each delivery Attempt, and manages receipts, retries and recovery. It also supports document processing through registered DOCUMENT services and records customer interactions alongside outbound history.

Start with the model below, then follow the [configuration and integration walkthrough](./comm_hub_e2e.md). Field definitions, request/response schemas and SDK operations are in the [Connect Hub API Reference](https://docs.insuremo.com/tech/pro/sdk/api/connecthub). Route examples use the service-relative `/comm/v1` prefix. Through the generated SDK/gateway, retain `/connect-hub/comm/v1`; do not add a tenant path segment or remove the service prefix.

## 1. Architecture and responsibilities

![Communication Hub architecture and responsibility boundaries](./image/comm_hub/task-architecture.png)

| Component | Responsibility |
| --- | --- |
| Business API / iComposer | Complete the business operation; build Payload and RequestId; orchestrate document generation, archiving and communication when required. |
| Communication Hub | Validate and accept Tasks; freeze configuration; resolve Executions; apply preferences and delivery policies; dispatch Attempts; retain receipts, history and recovery state. |
| Service driver / integration adapter | Map the accepted request to a transport or provider; deduplicate delivery requests; report trustworthy results. Provider-specific integration can run in iComposer. |
| Channel provider | Deliver email, SMS or other configured channels and return provider evidence. |
| Customer-facing application | Receive replies, acknowledgements and preference changes; submit explicitly correlated Interactions. |

The Hub owns the communication execution lifecycle. A separate business workflow is not required to send each channel request, but iComposer can compose several Tasks and external operations. A provider's HTTP acknowledgement, final delivery receipt and customer's acknowledgement are three separate facts.

### The runtime model

| Object | Meaning | Example |
| --- | --- | --- |
| Task | One accepted business communication request. | Notify a customer that policy P-10001 was issued. |
| Execution | One unit of DELIVERY or DOCUMENT work selected from a Binding. | Email the policy holder; send an SMS fallback; generate and archive a document. |
| Attempt | One recorded dispatch claim/attempt for an Execution; it may stop before invocation. | First receiver call; a later safe retry; an explicit successful resend. |
| Operation | A durable DOCUMENT checkpoint within an Attempt. | GENERATE or ARCHIVE, with its own result and evidence. |
| Interaction | An inbound customer/provider event with explicit correlation. | Reply, acknowledgement, complaint or opt-out. |

“Send a notification” is the business use case. The current API submits a **Task**; channel messages are represented by **DELIVERY Executions**. `RequestId` identifies the caller's submission, `TaskId` groups the work, `ExecutionId` identifies one execution, and `AttemptId` identifies one dispatch. Do not substitute one identifier for another.

## Console navigation

Open **Comm Hub** in the tenant console. Under **Definitions**, use **Context Definitions**, **Services**, **Templates** and **Notification Definitions**. The Definition's **Execution Configuration** tab manages Bindings. **Tasks** and **Executions** provide runtime history.

The screenshots show real English console pages with synthetic demonstration records. Where an older control differs from the API contract, the accompanying caption explains the applicable behavior. Their resource codes identify existing examples; use your own tenant resources when following the API samples. The table below identifies operations available in the illustrated console and operations accessed through the API.

| Operation | Console shown in this guide | API integration |
| --- | --- | --- |
| Choose submission timing | A single **Submit Task** action, without a Sync/Async selector. | Choose `/tasks/submit` or `/tasks/submitAsync`; use the corresponding `WithFiles` route for multipart input. |
| Inspect submitted attachment history | Execution detail shows receipts, output archival and Attempts. It has no managed attachment-history view. | Use `/tasks/attachments` for submitted members and `/attachments/list` for Attempt snapshots; download through the matching authorized Task or Attempt route. |

**Archived Output Files** contains receiver-produced outputs. It is separate from the submitted input attachments and their Attempt snapshots.

## 2. Configuration model

![Definition, Binding, Context, Template and Service relationships](./image/comm_hub/task-configuration.png)

| Resource | Contract |
| --- | --- |
| Definition | A unique `DefinitionCode`, Context reference, strategy and defaults. Owns Bindings. |
| Binding | An execution configuration: Service, Template, condition and kind-specific settings. |
| Context | Reusable JSONPath extraction and native typed variables. |
| Template | A tenant-unique `TemplateCode`, optional channel applicability, rendering language and content. |
| Service | A named driver configuration with `ServiceKind=DELIVERY` or `DOCUMENT` and declared capabilities. |
| Delivery Policy | Allowed-time and frequency restrictions, explicitly linked to DELIVERY Bindings. |
| Accepted snapshot | The immutable configuration and content used by an accepted Task, including delayed execution and retries. |

A Definition's `EffectiveKind` comes from its enabled Bindings. An enabled Definition must have at least one usable Binding; enabled Bindings must use the same ServiceKind. Use separate Definitions/Tasks when composing document processing and delivery.

**DELIVERY Bindings** select recipient role/channel, REQUEST or CONTEXT recipients, rendering, Parameters, completion policy, preferences, retry policy, delivery policy and attachment requirements. `ALL` executes eligible channels for a role; `FALLBACK` advances through ordered alternatives only when the preceding outcome permits it. A role override changes that role's strategy. Fallback candidates for a role must refer to the same nonblank preference subject when one is required.

**DOCUMENT Bindings** use SERVICE rendering and the required output contract. They do not use delivery recipients, channels, preferences, delivery policies, delivery attachment selections or channel order. Discover installed driver capabilities before choosing GENERATE and/or ARCHIVE operations. Bundled email/SMS drivers are DELIVERY services; document processing requires a registered capable DOCUMENT driver.

### Configuration workflow

1. Choose an eligible CommHub Group and create the Context.
2. Register Services and validate their settings/capabilities.
3. Save Templates and preview their content against the Context.
4. Create a disabled Definition, add Bindings and applicable delivery policies.
5. Preview Binding resolution, conditions, recipients, content and attachment metadata.
6. Enable the complete compatible Definition.

### Editing and revisions

Read a resource's detail before editing. Return its current `Revision` as `ExpectedRevision` on mutation; Binding mutations use the owning Definition's revision. This is optimistic concurrency control, not a business-version or template-activation mechanism. Reload and reconcile a revision conflict before retrying the edit.

Saves replace editable fields. Preserve intended conditions, policy links, overrides and output requirements explicitly. There are two important omission exceptions:

- Template `Contents` omitted: retain existing content bindings. `[]` removes bindings subject to usable-content/reference checks; null is invalid.
- Context `SamplePayload` omitted: preserve the stored original. Explicit null clears it. Do not save a masked preview as the original sample.

Copies get new owned IDs while retaining shared references; a copied Definition starts disabled. Check template references before deletion, including references from disabled configurations. Existing Tasks continue with accepted configuration; editing a Template or retry default does not rewrite their history.

### Service Parameters and Binding overrides

![Service defaults, Binding overrides and accepted Parameters](./image/comm_hub/task-parameters.png)

`Settings` holds transport/runtime configuration, such as URLs, timeouts and file-reporting identity. `Parameters` holds named business delivery inputs. Service Parameters provide reusable defaults; Binding Parameters override an entire entry by name or add an entry. A required Service VARIABLE remains required after override. Parameters are resolved only for applicable Bindings and frozen into accepted execution data.

```json
{
  "Parameters": {
    "AccountName": { "Source": "VARIABLE", "Binding": "MailAccount", "Required": true },
    "Cc": { "Source": "CONSTANT", "Value": ["agent@example.com"] }
  }
}
```

This is a parameter fragment. VARIABLE selects an exact declared Context variable and may set Required (default false); it must not contain Value. CONSTANT requires a native JSON Value, including explicit null only when the parameter permits it, and must not contain Binding or Required. Preserve false, zero, arrays and objects. An empty editor is not JSON null. The outbound request contains the single merged Parameters map and outbound Variables, not extracted Context aliases or separate Service/Binding parameter maps.

| Driver | Business Parameters | Completion and attachments |
| --- | --- | --- |
| PLATFORM_EMAIL | AccountName; optional Cc/Bcc native arrays of plain email-address strings | ACCEPTED only; supports attachments. |
| PLATFORM_SMS | AccountName, required SignName, optional Boolean AutoAddSign and UseZhBracket | ACCEPTED only; no attachments. |
| REST_WEBHOOK | Receiver-defined keys; do not impose built-in EMAIL/SMS keys | Callback-capable; choose supported completion and attachment capabilities. |

Display the technical parameter `Name`, translated `Label` and actual Context variable name separately. Do not insert UseZhBracket by default.

`GET /services/driverTypes` returns Parameters metadata (name, type, requiredness, allowed sources, length/format and help/label references) plus separate RecipientAddress metadata. The primary address remains a Binding/request routing input, not Parameters.To. Subject and Body remain template inputs.

Omitting AccountName on a Binding inherits the Service entry. Omit it at both levels to use the default account path: the Hub uses its configured fallback when available, otherwise delegates default selection to the platform service in the actual sending context. A configured CONSTANT AccountName must be a nonblank string; `Value: null` and an empty string are invalid. A VARIABLE uses Binding and optional Required, never Value. Required=true rejects missing/null/blank resolution (after preprocessing when enabled, otherwise before Task writes); an optional variable retains omission/default behavior. An explicit account must exist in the sending context. Driver metadata does not expose tenant account values.

Cc/Bcc overrides replace rather than concatenate lists. A Binding constant `[]` suppresses an inherited Service Cc list; removing the override restores inheritance. To/Cc/Bcc share one email Execution, preference decision and retry lifecycle. Use `Addresses` for multiple To recipients, or `Address` for one, never both. Ordinary EMAIL needs no user-configured Role. The notification-associated RecipientId controls RESPECT for the whole email; refusal suppresses To, Cc and Bcc together. Native arrays are required; comma/semicolon strings and display-name addresses are not supported. Without preprocessing, invalid effective parameter types/values for applicable Bindings are rejected before Task acceptance; HTTP 400 is not queued work. With enabled preprocessing, static parameter references are still checked at acceptance, while resolved values are validated after the hook and before provider invocation. Parameter validation does not prove that provider accounts, signs or templates exist.

## 3. Context, template rendering and masking

Context aliases select objects; variables extract native JSON values from Payload or an alias. With `Source: "Payload"`, `$` selects the entire business Payload object, while `$.Payload` selects a nested property literally named Payload inside it. It does not select the Task submission envelope. With `Source: "Context.Customer"`, paths are relative to that selected customer object. EXTRACT supports SINGLE/LIST results, required values and defaults. CONSTANT stores a native JSON literal, including explicit null. No `ValueType` is needed.

```json
{
  "Contexts": { "Customer": { "Path": "$.Policy.Customer" } },
  "Variables": {
    "PolicyNo": { "Source": "Payload", "Path": "$.Policy.PolicyNo", "Required": true },
    "CustomerName": { "Source": "Context.Customer", "Path": "$.Name", "DefaultValue": "Customer" },
    "CustomerEmail": { "Source": "Context.Customer", "Path": "$.Email", "Required": true },
    "BrandName": { "Mode": "CONSTANT", "Value": "Example Insurance" }
  }
}
```

This is a Context configuration fragment; save requests also contain the resource's code, name and GroupId. Payload is caller-defined business JSON, not a rigid product schema. Routing fields, recipients and attachment descriptors belong in the submission envelope.

![Context variable extraction, default value and MaskOnSend](./image/comm_hub/ui-context-masking.jpg)

**Context detail:** `Source` and `Selector` extract the value. `Default Value` handles an absent optional value. `MaskOnSend` and `MaskRule` govern outbound masking, independently of history display masking.

### Template language and content

![Template source, rendering and accepted content](./image/comm_hub/task-template.png)

`TemplateLanguage` selects **syntax**, not customer locale:

| Language | Example | Behavior |
| --- | --- | --- |
| `FREEMARKER` | `${CustomerName}` or `${CustomerName!""}` | Supported FreeMarker data expressions and control constructs under the Hub's template restrictions. |
| `HANDLEBARS` | `{{CustomerName}}` | Data paths, explicit parent paths and bounded if/unless/each/with helpers. Raw/triple interpolation, arbitrary helpers, partials/loaders and implicit parent fallback are rejected. |

Provide the language explicitly whenever Hub-rendered Subject or BODY source exists, including file-backed BODY content. Changing the language revalidates the source; it does not translate it. Provider-only or opaque document content can omit it when there is no Hub source.

`ReferencedVariables` is a derived, sorted set of root names. Declare every referenced root in Context, including roots used in conditions and default expressions. Requiredness belongs to Context variables, not a separate template variable schema.

| Content / mode | Use |
| --- | --- |
| `ContentRole=BODY`, `ManagementMode=INLINE` | Text source stored with the Template. |
| `ContentRole=BODY`, `ManagementMode=FILE` | Immutable uploaded source validated with the selected template language. |
| `ContentRole=TEMPLATE`, `ManagementMode=FILE` | Opaque receiver/document template bytes interpreted by the selected service. |
| Binding `RenderMode=HUB` | Hub renders supported Subject/BODY from resolved variables. |
| Binding `RenderMode=SERVICE` | The service renders using accepted variables and its template contract. |
| `ProviderTemplateReference` | Provider-side template identity, separate from the local TemplateCode. |

### Choose the rendering owner

`ContentType`, `TemplateLanguage`, `ManagementMode` and `RenderMode` answer different questions:

| Choice | Meaning | Integration consequence |
| --- | --- | --- |
| TEXT / HTML | Output format. | HTML customer values are escaped and supported markup follows the HTML policy; TEXT preserves literal text. |
| FREEMARKER / HANDLEBARS | Syntax of Hub-owned source. | Use the matching syntax for Subject and BODY. It does not select the provider's engine. |
| INLINE / FILE | Where BODY source is stored. | INLINE holds source text; FILE holds uploaded source bytes. Both use the selected Hub language when the Hub renders. |
| HUB | CommHub renders the content. | The receiver receives rendered content and masked Variables. |
| SERVICE | The selected service renders or handles a template-free event. | The receiver receives masked Variables and any applicable template identity, without a Hub-rendered Subject/Body. |

| Driver / source | RenderMode | Allowed grammar | What happens at dispatch |
| --- | --- | --- | --- |
| PLATFORM_EMAIL + Hub BODY | HUB | FREEMARKER or HANDLEBARS | Hub renders Subject/Body, then sends; no Container template synchronization. |
| PLATFORM_EMAIL + Hub BODY, INLINE or FILE | SERVICE | HANDLEBARS only | Hub synchronizes the accepted source to the same-code Container template, then sends Variables. |
| PLATFORM_EMAIL + provider-only template | SERVICE | No Hub source grammar | Uses ProviderTemplateReference; does not upload a Hub BODY. |
| PLATFORM_SMS + Hub BODY, INLINE or FILE | SERVICE only | HANDLEBARS only | Same-code Container SMS template must already exist; Hub updates managed content without replacing third-party mappings. |
| PLATFORM_SMS + provider-only template | SERVICE only | No Hub source grammar | Requires ProviderTemplateReference; uses the existing provider/Container template. |

SMS HUB rendering is rejected. SMS does not accept message attachments. Both built-in PLATFORM_EMAIL and PLATFORM_SMS require ReceiptMode=ACCEPTED; use a driver with an actual final-receipt contract for DELIVERED. ProviderTemplateReference is required for provider-only SMS, not when a valid Hub BODY supplies the template. Provider variable names remain case-sensitive.

### Automatic Container synchronization

Save and preview never trigger synchronization. At delivery, the built-in driver queries the target template. Identical managed content is left unchanged; an older differing target can be partially updated; a differing target with equal/newer time causes a content-conflict failure before send. EMAIL can create an absent same-code target. SMS cannot create an absent target because its third-party template mapping must already exist.

Updates use the Container's `update_options: {"full_update": false}` and preserve unmanaged fields such as SMS third_code and sender_properties. This internal Container option is not a CommHub Task field. Template synchronization may modify a same-code Container record: use dedicated, intentionally managed codes; do not share a code with an independently edited template and assume last-write-wins. Hub-managed SMS source still needs a compatible existing supplier mapping.

TemplateCode is unique within the tenant; Channel does not form a compound template identity. TEMPLATE-only binary templates do not need a Subject, BODY, Channel or ContentType. Accepted source bytes and the selected language are retained for existing Tasks.

Use `/templates/extractVariables`, `/templates/validateHtml` and `/templates/previewContent` for unsaved source, supplying TemplateLanguage. Use saved-template previews for persisted content. `/templates/htmlPolicy` describes accepted HTML/CSS; rendered HTML follows the Hub's sanitization policy. Preview performs no delivery.

![Handlebars template with subject and body](./image/comm_hub/ui-template-content.jpg)

**Template detail:** choose the template grammar, then author Subject and Body using Context variable names. Template Language is not the recipient language.

### Service preprocessing

Use optional Service `Preprocessing` to enrich or transform **Variables** before delivery, for example adding a customer-facing description from another service. Configure it alongside `Settings`, not inside driver Settings. It applies only to DELIVERY services and uses POST with JSON. See the [configuration and request/response example](./comm_hub_e2e.md#optional-add-service-preprocessing).

| Setting | Meaning |
| --- | --- |
| Enabled | Set true to run the hook; missing legacy configuration is disabled. |
| Url | Hook endpoint. |
| HeaderTemplate | Optional string-valued headers. Authorization is resolved from current Service configuration at execution time and excluded from accepted business snapshots. |
| ConnectTimeoutMs / ReadTimeoutMs | Each accepts 100–300000 ms; defaults are 5000 / 10000 ms. |

On Service create, omitted Preprocessing is disabled. On update, omission preserves it; explicit null clears/disables it. Read Service detail and save its other fields with ExpectedRevision. Accepted Tasks retain their selected preprocessing configuration and inputs; editing the Service does not enable the hook for older Tasks.

![Service preprocessing and reuse of prepared content](./image/comm_hub/task-preprocessing.png)

When an eligible delivery Attempt is prepared, the Hub calls the hook before HUB rendering and final delivery-parameter validation. The request contains RequestId, TaskId, ExecutionId, ServiceCode and Variables. The hook's RequestId is stable for this Execution's preparation stage; it is distinct from the caller's Task RequestId and any Resend RequestId. Implement idempotency against that stage identity: a timeout can occur after the hook has run.

Return only a JSON object with an optional `Variables` object. Merge is by **top-level key**: a supplied non-null value replaces that key, null deletes it, and an omitted key retains its value. Nested objects and arrays replace whole values; they are not recursively merged. `{}` and `{"Variables": {}}` mean no change; `{"Variables": null}` is invalid. The response cannot replace the envelope, recipients, routing, identity, template source, Subject, BodyText or BodyHtml. Outbound masking, size limits and final parameter/driver validation still apply.

The Hub persists successful merged Variables before rendering and persists final prepared content before calling the provider. A successful hook is not called again if rendering later fails. Once preparation is READY, ordinary delivery retries reuse the prepared Variables/rendered content. Ordinary retries may still prepare new DMS attachment bytes; successful Resend instead reuses the original successful Attempt's frozen content **and** attachments.

Transport failures, timeouts, non-2xx responses or invalid responses stop preparation before any provider call. Transport failures and HTTP 429/5xx can be classified for retry; invalid output is not automatically retryable. Inspect the recorded error and server action eligibility instead of deriving a retry action from HTTP status alone. A preparation retry before recorded hook success uses the same stage RequestId. There is no separate public API to invoke the hook. Execution detail exposes a safe `Preprocessing` summary with RequestId, State, HookCompletedAt and ErrorCode; use Attempt diagnostics for retained HTTP evidence.

### Display masking and outbound masking

These are independent policies:

- **Display:** the global `CommHubMasking` DataTable has `JsonKey`, `ExactMatch` (`Y`/`N`) and `MaskRule`. Matching is case-insensitive on JSON key names throughout nested objects and arrays, not on JSONPath. Exact matches take precedence. An unavailable or invalid policy fails closed; a successfully loaded empty table declares no masks.
- **Sending:** an EXTRACT variable can specify `MaskOnSend: true` with `MaskRule`. The default is false. Keep recipient address variables suitable for actual routing.
- **Original access:** history READ plus `COMMHUB_DATA_UNMASK` enables applicable explicit original-data operations, with auditing and no-store responses. Routine history/preview remains permission-aware.

Compact MaskRule examples: `*` masks all; `{3}*` retains a prefix; `*{4}` retains a suffix; `{4}*{4}` retains both. Short values that cannot safely preserve those portions are fully masked. Use synthetic data for shared samples and previews.

## 4. Submit a notification Task

![Task submission, initial observation and asynchronous delivery](./image/comm_hub/task-submit-sequence.png)

Choose the API by **input form** and **response timing**:

| POST route | Input | Accepted submission response |
| --- | --- | --- |
| `/tasks/submit` | JSON; optional uploaded FileIds/DMS attachments | 200 when initial work settles within the observation window; otherwise 202. |
| `/tasks/submitAsync` | Same JSON | 202, including equivalent completed duplicates. |
| `/tasks/submitWithFiles` | Multipart Request plus inline Files; may also reference FileIds/DMS | Same bounded observation as submit. |
| `/tasks/submitWithFilesAsync` | Same multipart | 202. |

The table describes accepted submissions. Validation failures are rejected requests, not queued work. All four return `CommTaskSubmissionResult` and use the `CommTask` SDK. Their operationIds are `commHubSubmitTask`, `commHubSubmitTaskAsync`, `commHubSubmitTaskWithFiles` and `commHubSubmitTaskWithFilesAsync`.

Sync observes initial driver/pre-execution outcomes for **20 seconds by default**, configurable from 1 to 60 seconds. It does not wait for final delivery and has no per-request wait-time field. Use Async for a future `ExecuteAt` or an active TCC/global transaction; Sync rejects those cases before durable inline upload.

```json
{
  "RequestId": "policy-issued-P-10001",
  "DefinitionCode": "POLICY_ISSUED",
  "CustomerId": "C-001",
  "RefType": "POLICY",
  "RefNumber": "P-10001",
  "SenderApp": "policy-service",
  "Payload": {
    "Policy": { "PolicyNo": "P-10001", "Customer": { "PartyId": "C-001", "Name": "Ada", "Email": "ada@example.com" } }
  }
}
```

This example uses the CONTEXT Binding configured in the walkthrough. REQUEST Bindings use explicit Recipients; CONTEXT Bindings resolve them from declared variables. `CustomerId` anchors the customer timeline and is separate from `RecipientId`, the preference subject. Payload is limited to 64 KiB serialized JSON. TraceId comes from request context, not the body.

![Completed Task and its channel Execution](./image/comm_hub/ui-task-detail.jpg)

**Task detail:** follow the Execution ID from the Task. Completed means the configured completion contract was satisfied; inspect Receipt Mode and evidence to understand the milestone.

### Read progress correctly

Follow the response's Location or query `GET /task-requests/getById?requestId=...`. Inspect CommandStatus, TaskAvailable, TaskStatus and per-execution outcomes. The submitting principal can read its limited progress; another principal requires Task-history READ authority.

- HTTP 200 means **initial observation settled**, not “delivered”. HTTP 202 means inspect progress, not “successful delivery”.
- `PENDING_COMMIT` may have no TaskId. Dispatch waits for transaction confirmation.
- On a successful progress lookup, `TaskAvailable=false`, absent TaskStatus and empty/omitted Executions mean online Task evidence is unavailable; do not label it running or successful. A submit HTTP 400 is a rejected request, even if a Location or TaskAvailable field is present; do not poll it as accepted work.
- Progress contains at most the first 200 Executions. Use paged execution/history APIs for the complete record.
- `ReceiptPending`, `OutcomeUncertain`, `NeedsAttention`, `Finished` and UTC `NextAttemptAt` explain the current operational state. INITIAL_INTENT / INITIAL_SETTLED / INITIAL_CLOSED events describe observation, not delivery milestones.

### Idempotency and scheduling

Keep the same RequestId and equivalent input when recovering a lost response. Equivalent Sync/Async submissions in the same input form share the accepted Task. Changed content, attachment references, bytes or metadata conflict; use the returned ErrorCode rather than assuming all conflicts are HTTP 409. Keep inline file content, FileKey and metadata stable when replaying the request; do not substitute a different input identity under the same RequestId.

For a new business intent, use a new RequestId. `OriginalTaskId` links that new submission to an earlier Task; it does not retry or copy it. A cancelled transactional command replay is still cancelled, not a new send.

`ExecuteAt` and `ExpiresAt` are tenant-local date-times without an offset or zone suffix, for example `2026-12-01T09:00:00`. Send the chosen tenant-local values, not browser-local values converted to UTC. DST gaps and overlaps are rejected; choose an unambiguous local time. When both are supplied, ExpiresAt must be later than ExecuteAt. Acceptance freezes the resolved UTC deadlines and scheduling timezone. ExecuteAt delays eligibility; delivery windows and expiry still apply. Use Async for future scheduling. Configuration and preparation inputs are frozen while the Task waits; an enabled hook prepares the content when the delivery becomes eligible.

## 5. Attachments and immutable Attempt evidence

![Attachment inputs, preparation, delivery and history access](./image/comm_hub/task-attachments.png)

| Input source | Descriptor | Byte behavior |
| --- | --- | --- |
| Uploaded file | `Source: "UPLOAD"`, `FileId` | An immutable READY upload owned by the same tenant and original uploader. |
| Inline multipart file | `Source: "UPLOAD"`, matched `Files[FileKey]` part | Only on WithFiles routes; the part name identifies the logical file, independent of order. |
| DMS document | `Source: "DMS"`, `Dms: { "DocId": 70001 }` | Caller authorization at new acceptance; each new eligible Attempt captures the current bytes. |

Definition `Attachments` declares slots as `{FileKey, Name, Cardinality}`. SINGLE permits at most one member; MULTIPLE permits a variable number, subject to the total Task limit. Omitted Cardinality defaults to SINGLE; preserve MULTIPLE explicitly when saving an existing slot. Bindings select slots through `{FileKey, Required}`. Each Task attachment has its own unique **FileKey** and a **SlotKey** identifying the selected Definition slot. Omitted/null SlotKey falls back to the member FileKey for legacy one-file submissions. Several members can share a SlotKey and filename, but FileKeys remain unique per Task and case-sensitive. Both keys match `[A-Za-z][A-Za-z0-9_]{0,59}`.

Required means at least one eligible, authorized, usable member for that slot after the enabled Binding's conditions and filters apply. Validation occurs before acceptance; declaring a slot alone does not make it mandatory. An empty Binding selection sends no managed attachments. Referenced slots cannot be removed or renamed until referencing Bindings, including disabled ones, are updated. Optional RoleFilter is a legacy filter; omit it for ordinary email groups. Filtered-out members do not satisfy Required.

A link is an ordinary Context variable; the Hub does not fetch a URL or generate a share link from an attachment descriptor. CLOUD_DISK remains unavailable because native object authorization is not integrated. Use an authorized application integration to retrieve and upload bytes, or provide a share link.

Multipart requires exactly one **Request** part with `application/json` and one binary **Files[FileKey]** part for each inline UPLOAD input. The input descriptor supplies FileKey and Source, without FileId. Part order and original filename do not identify the file. Duplicate, malformed, missing or unreferenced parts are rejected, as is supplying both FileId and an inline part for the same input. JSON submit needs FileId for UPLOAD. Do not put Base64 bytes in Payload.

**Configuration/content snapshots and attachment snapshots have different boundaries:** accepted templates remain fixed for all Attempts; DMS bytes are captured per new eligible Attempt and may differ across retries. Once prepared, that Attempt's attachment bytes and hash are immutable. Replaying the accepted submission does not resnapshot attachments.

| Operation | Access / meaning |
| --- | --- |
| POST `/attachments/upload` (multipart `File`) | Creates an upload and returns FileId, name, media type, size and hash. |
| GET `/attachments/getById?fileId=...` | Upload metadata for its tenant/original uploader. |
| GET `/attachments/download?fileId=...` | Verified immutable upload bytes for its tenant/original uploader. |
| GET `/attachments/list?executionId=...&pageIndex=0&pageSize=20` | Safe accepted-input/Attempt metadata with Execution-history READ. |
| GET `/attachments/downloadSnapshot?attemptId=...&attachmentId=...` | Exact historical bytes, requiring history READ and DATA_UNMASK. |
| GET `/attachments/downloadForDelivery?callbackId=...&fileKey=...` | Receiver access with delivery-file API authority, tenant isolation and the accepted Attempt/FileKey relationship. No fixed account binding is required. |

Use `GET /tasks/attachments?taskId=...&pageIndex=0&pageSize=20` for one row per submitted member, including Tasks with no Attempt. Rows include AttachmentId, FileKey, SlotKey, SlotName, FileName, Source and DownloadAvailable. Metadata requires Task history READ. `GET /tasks/attachments/download?taskId=...&attachmentId=...` additionally requires `COMMHUB_DATA_UNMASK`, Task membership and retained upload bytes; it is audited and uses no-store. DownloadAvailable describes retained upload availability, not the caller's unmask permission. A DMS reference has no Task-owned upload to download; inspect a retained Attempt snapshot separately. Do not present repeated Attempt snapshots as multiple submitted files.

### Access identities for attachments

| Operation | Required identity and authority |
| --- | --- |
| Read Task history | `COMMHUB_NOTIFICATIONS` READ authority. The permission code retains its established name. |
| Read Execution and attachment metadata | `COMMHUB_MESSAGES` READ authority. Metadata access does not grant original-file access. |
| Download historical original bytes | Execution-history READ plus `COMMHUB_DATA_UNMASK`. The server checks authority for each request. |
| Download bytes as the receiver | All drivers require delivery-file API authority, the same tenant and the accepted Attempt/FileKey relationship; no fixed account binding is required. |
| Read a DMS source | The submitting caller must pass native DMS authorization. The worker also needs its approved tenant-scoped DMS reader credential. |

Receiver downloads and file reports use the relevant CommHub API authority, tenant isolation, the correct Attempt/FileKey and valid manifest relationships. No driver requires a fixed FileReportUserId binding. Existing legacy values do not grant access. ReportId replay/conflict checks remain in effect. DOCUMENT execution uses the tenant platform background identity. Human downloads of retained originals keep their separate READ and unmask requirements.

Configure the worker's `comm-hub.dms-reader-token` through the deployment's approved secret mechanism. Never place its value in Service Settings, business Payload, screenshots or accepted snapshots. A missing worker credential does not justify bypassing the caller's DMS authorization.

Revoking original-data authority blocks subsequent original downloads while permitted metadata remains readable. UI visibility and caller-supplied headers cannot grant access. Use the established permission codes rather than deriving new codes from the Task and Execution resource names.

`SnapshotAvailable` distinguishes a logical input from prepared bytes; preparation is not delivery. A missing snapshot does not fall back to current DMS bytes. A receiver cannot use an old callback to read a later/superseded Attempt.

The default `comm-hub.attachment.max-files` limit is five total member files per Task (not per slot); a positive deployment setting can raise it. Other default limits are 20 MiB per file, 25 MiB combined actual bytes, and 256 KiB for multipart Request JSON. Configure bounded native multipart parser limits (default upper bounds: 20MB/file and 26MB/request); smaller limits remain effective. Upload routes reject unsafe parser configuration with 503 and known oversized input with 413. SystemFile storage must be shared and durable for multi-instance reads; supported native storage adapters include SystemFile and S3.

## 6. Deliver a message and receive its result

![Receiver submission and final receipt sequence](./image/comm_hub/task-delivery-sequence.png)

The Hub evaluates eligibility, conditions, preferences and delivery policy before invoking a receiver. An eligible claim records an Attempt; enabled Service preprocessing and final content validation complete before invocation. Attachment preparation freezes bytes for a STANDARD Attempt, while RESEND reuses the successful Attempt files. The service/adapter must preserve the outbound correlation identities and deduplicate its receiver requests. `ClientRequestId` identifies receiver work; `CallbackId` routes evidence to the correct Attempt.

REST_WEBHOOK sends a flat JSON object containing the accepted outbound envelope plus ClientRequestId, CallbackId and CallbackPath. It does not wrap it in `Outbound` or expose raw Payload, Context aliases or Settings. `Variables` and merged `Parameters` are separate native objects. Input attachment descriptors identify individual member FileKeys and authorized DownloadPaths; SlotKey is not the download selector.

The outbound identity fields include TaskId, ExecutionId, AttemptId, ServiceCode, DefinitionCode and accepted DefinitionId. TemplateId/TemplateCode identify the selected local template when applicable; older envelopes may lack numeric IDs and template-free Bindings omit template fields. Do not reconstruct historical IDs from current configuration. In HUB mode, the receiver gets the prepared Subject and BodyText or BodyHtml plus Variables; SERVICE mode delegates rendering without a Hub-rendered body. Each actual call has its own ClientRequestId and CallbackId, including a Resend call.

### Webhook events without recipients or templates

A REST_WEBHOOK Binding can omit RecipientSource for recipient-free delivery. Do not supply artificial email addresses or customer identities. This path does not resolve recipient preferences or role-based fallback; it uses independent ALL execution while other applicable delivery policy checks remain. Recipient-oriented email/SMS configurations retain their recipient requirements.

For a template-free Event Binding, select a registered EVENT channel supported by the Service, use SERVICE rendering and omit TemplateCode. The receiver gets configured Variables and Parameters, without TemplateId, TemplateCode, ProviderTemplateReference, Subject or Body fields. To send the full business Payload deliberately, declare a variable with `Source: "Payload", Path: "$"`; the Hub does not implicitly add raw Payload to the envelope.

A REST_WEBHOOK receiver returns successful acceptance only after taking delivery responsibility. It translates the outbound request to the provider, retains the provider reference and reports evidence through `POST /callbacks/result` with the `X-Comm-Callback-Id` header. Use the authorized callback identity, not an operator's history permission, for machine results.

| Binding receipt mode | Delivery milestone |
| --- | --- |
| `DELIVERED` | Acceptance leaves receipt tracking open. Final delivered/failed evidence determines the delivery outcome. |
| `ACCEPTED` | Receiver acceptance satisfies the configured delivery milestone. This does not prove customer delivery. |

`ReceiptMode` and `ReceiptTimeoutSeconds` belong to the DELIVERY **Binding**, not the Service. DELIVERED requires a callback-capable driver and a timeout of 1–604800 seconds. ACCEPTED omits the timeout. DOCUMENT Bindings omit both fields and follow document output completion. Built-in PLATFORM_EMAIL and PLATFORM_SMS support ACCEPTED only.

`ReceiptEvidence` records provider facts separately from ExecutionStatus. Required outputs must also be satisfied before the Execution is complete. An ACCEPTED-mode completed milestone is not automatically undone by a later failed-provider receipt; retain and display that later evidence separately. Customer acknowledgement is an Interaction, not a delivery receipt.

Common ExecutionStatus values are WAITING, SCHEDULED, READY, SUBMITTED, ACCEPTED, COMPLETED, FAILED, SKIPPED, CANCELLED and EXPIRED. Read the accompanying evidence and flags: an uncertain outcome must not be treated as a confirmed failure merely because the initial call ended.

## 7. Timeouts, retry and fallback

![Timeout classification and safe retry decisions](./image/comm_hub/task-retry-decision.png)

### Four independent time boundaries

| Boundary | What it means | Correct response |
| --- | --- | --- |
| Submit observation window | The caller stops waiting for initial work. | Return 202 and query progress; do not resubmit a new business request. |
| Driver connect/read timeout | The receiver call did not produce a usable answer. | Distinguish a proven pre-send failure from a possibly accepted request. |
| Receipt deadline | Final delivery evidence has not arrived within ReceiptTimeoutSeconds. | Treat the outcome as uncertain; obtain evidence before a resend/fallback. |
| ExecuteAt / ExpiresAt | Business dispatch window. | Wait until due; expire undispatched work after the deadline. |

For REST_WEBHOOK, a proven connection failure before sending and HTTP 429 (rejected **before acceptance**) can permit retry. A lost response after sending, ambiguous transport failure or HTTP 5xx can mean the receiver already accepted; the Hub holds the outcome as uncertain. Other definitive nonretryable failures terminate that attempt's retry path. The automatic Retryable flag does not override uncertainty and is not a manual-action eligibility flag.

### Automatic retry

A new Attempt is created only when the result is safely retryable and policy, expiry, cancellation and attempt limits allow it. `MaxAttempts` includes the first attempt. Definition defaults can be overridden on a Binding using all four retry fields together:

```text
MaxAttempts = 3
RetryInitialDelaySeconds = 300
RetryBackoffMultiplier = 2
RetryMaxDelaySeconds = 3600

After attempt 1: wait 300 seconds
After attempt 2: wait 600 seconds
After attempt 3: no automatic attempt remains
```

The retry delay grows exponentially and is capped by RetryMaxDelaySeconds. `NextAttemptAt` is the authoritative scheduled retry time; delivery policies can constrain actual dispatch. Existing accepted Tasks retain their accepted retry configuration.

With `FALLBACK`, the next eligible channel is an alternative Execution, not another Attempt of the first channel. Do not advance while the earlier provider outcome is uncertain. With `ALL`, eligible channels execute independently; a successful email does not imply SMS success.

![One failed Attempt followed by an accepted Attempt](./image/comm_hub/ui-retry-attempts.jpg)

**Attempt history:** the first Attempt remains Failed after a later Attempt is Accepted. Preserve this history when diagnosing retries. The action bar shows current eligibility, which can differ from an earlier Attempt's automatic retry classification.

### Operator actions

Read `GET /executions/actionEligibility?executionId=...` before offering an action. The server returns an `Actions` list with Action, Allowed, ReasonCode and ReasonParams for RETRY, RECOVER, RECONCILE, CANCEL, STOP_RETRIES and SUBMIT_RESULT. Use native booleans; never treat a nonempty `"N"` string as true. Manual retry eligibility is independent of automatic retryability; use the returned RETRY action rather than deriving permission from Retryable or a status label. Mutation APIs take JSON request bodies with ExecutionId, ExpectedRevision and action-specific fields, including RequestId where required.

| Action | Purpose |
| --- | --- |
| Retry | Request a server-authorized manual delivery Attempt with ExecutionId, RequestId, Reason and ExpectedRevision. It may exceed the automatic budget but does not restart the automatic retry cycle; uncertainty remains a guard. |
| Reconcile | Obtain/record authoritative operation evidence before deciding what is safe next. |
| Recover | Resume eligible incomplete archive work using retained inputs; do not regenerate or resend. |
| Submit result | Record an authorized verified outcome with the required supporting evidence. |
| Cancel | Cancel eligible work; cannot retract a provider delivery already performed. |
| Stop retries | Block future automatic/manual retries and successful resends, including queued resend before invocation. An invocation already in flight continues; recorded history is retained. |

**Delivered but awaiting required archival output:** retain delivered evidence and finish the missing output work. Do not restart a delivery-receipt timeout or resend the communication to repair archive completion.

### Send again after success: Resend

Use Resend for a deliberate additional delivery of the same successful content. Use Retry for an eligible failed original delivery. Neither requires creating a new Task. If the content or recipients must change, submit a new business Task with a fresh RequestId instead.

![Successful resend with an independent request and Attempt](./image/comm_hub/task-resend.png)

`GET /executions/actionEligibility?executionId=...` returns a sibling `Resend` object with Allowed and ReasonCode, alongside the existing Actions list. Resend is not an extra Actions enum. Use the current Revision and check `Resend.Allowed` before calling `POST /executions/resend`; the server checks again at submission and invocation. Submission and verified Attempt results require `COMMHUB_MESSAGES_OPS_WRITE`; reading resend progress requires Execution history READ.

| Boundary | Resend behavior |
| --- | --- |
| Original outcome | Same Task and Execution; original success, receipt/output result and Task completion remain. Resend has its own result. |
| Eligibility | Successful completed DELIVERY Execution, retained successful STANDARD Attempt content and prepared attachments, unexpired lifetime and retries not stopped. Unresolved work blocks a competing send. |
| Identity | One RequestId per explicit resend intent, scoped to the Execution. It creates at most one RESEND Attempt, possibly none if stopped, expired or suppressed before allocation. |
| Frozen content | Reuse the successful Attempt's envelope, rendered content and immutable attachment bytes. Do not rerun preprocessing, render templates or recapture DMS files. Per-call Attempt/callback/deduplication identities are new. |
| Policy | Recheck preferences, sending windows, expiry and frequency caps. Each admitted resend owns its own quota unit when caps apply; it does not reuse the original send's quota. A deferral remains the same intent. |
| Failure / uncertainty | No automatic retry chain or fallback is started by a failed Resend. Uncertain submission/receipt remains unresolved until evidence settles it. A later eligible explicit resend uses a fresh RequestId. |

The request contains ExecutionId, ExpectedRevision, RequestId (up to 64 characters) and Reason (up to 300 characters). An exact replay with the same ExecutionId/RequestId and Reason returns the recorded generation and current result without another Attempt or quota charge; ExpectedRevision remains required but is not part of replay identity. Changing Reason conflicts. For a new intent, stale ExpectedRevision is rejected.

HTTP 200 and `Accepted=true` acknowledge the resend intent, not delivery. Follow `GET /executions/resendResult?executionId=...&requestId=...`, including when AttemptId is absent. State can be QUEUED, DEFERRED, IN_PROGRESS, AWAITING_RECEIPT, AWAITING_OUTPUT or UNCERTAIN; terminal results are SUCCEEDED, FAILED, STOPPED, EXPIRED and SUPPRESSED. Read Terminal, ReasonCode, ReadyAt and ExpiresAt. Execution detail's LatestResend shows the latest intent; older RESEND_REQUESTED events contain DispatchRequestId for querying older results.

When allocated, use its exact AttemptId to inspect `/executions/attempts`, `/executions/request`, `/executions/error` and related events. Report provider receipts using that Attempt's CallbackId. ACCEPTED completion still means provider acceptance; DELIVERED completion waits for final evidence and any required output. An authorized operator can resolve uncertain RESEND evidence through `/attempts/result`, specifying the exact Execution/Attempt and structured SubmissionDisposition with supporting evidence. FAILED alone does not establish non-acceptance or release quota. Do not use the original Execution result operation to overwrite resend history.

See the [Resend API walkthrough](./comm_hub_e2e.md#send-again-after-a-successful-delivery) for the call sequence.

## 8. Document processing and recovery

![Document operation checkpoints and recovery boundaries](./image/comm_hub/task-document-recovery.png)

A DOCUMENT driver declares supported GENERATE/ARCHIVE operations and lookup capabilities. GENERATE returns typed opaque Artifacts; ARCHIVE returns a DocId. A failed operation reports a ReasonCode, without success artifacts. These are recorded checkpoints, so partial success survives a later failure.

For archive-only services, `InputFiles` supplies existing authorized DMS inputs; it is separate from DELIVERY `Attachments`. Generation services produce their own artifacts. The Hub does not implicitly pass outputs from one Binding to another.

Recovery reuses retained successful outputs and resumes eligible missing/definitively failed archive operations. An UNKNOWN operation requires reconciliation through authorized lookup, callback or verified operator evidence. Unknown work is not automatically regenerated. A stale attempt can be retired/requeued only where the recorded checkpoint proves the external operation was never invoked. Generic file reports cannot settle DOCUMENT operation outcomes.

## 9. Typical composition: issue, archive, notify and respond

![Policy issuance composition across business, documents, delivery and interactions](./image/comm_hub/task-policy-composition.png)

A typical iComposer business flow combines:

1. **Issue policy.** Commit the policy operation and establish a stable business reference.
2. **Produce the policy document.** Invoke a configured DOCUMENT Task or external document service. Query its outcome and complete required archive work before using its DocId.
3. **Submit the notification.** Create a DELIVERY Task with policy/customer data, an authorized DMS attachment and/or an application-managed link.
4. **Deliver by role.** For example, email the policy holder with an SMS fallback; use ALL for channels that should both run. The adapter owns provider-specific mapping and callbacks.
5. **Record results.** Delivery receipts update the Attempt/Execution; business applications query progress and history.
6. **Capture the customer's response.** The portal or inbound integration records an explicitly linked Interaction and performs the applicable preference update.

A receipt timeout at step 4 pauses unsafe resend/fallback until evidence resolves the earlier outcome. An archive failure at step 2 resumes archival work, not policy issuance or document generation. An SMS link is supplied by the business application; it is not generated by attachment processing.

### Interactions, preferences and timeline

Supported interaction types include MESSAGE, ACK, FILE, CONTACT, OPT_OUT, BOUNCE and COMPLAINT. Use trusted SourceSystem/SourceId and explicit Task/Execution/business/customer correlation; do not infer identity from free text or an address alone. The Hub does not mirror outbound messages into inbound Interactions.

`SourceSystem` + `SourceId` identifies an idempotent interaction within the tenant; it is not a source-registration requirement. Record through an authenticated caller with the relevant CommHub API permission. Replaying the same pair requires the same original content and caller; conflicting content or caller is rejected. A registered source UserId or AllowPreferences setting is not required.

For new OPT_OUT and COMPLAINT interactions, an explicit RecipientId/channel target (or one resolved from a linked DELIVERY Execution) applies a refusal once, atomically with recording the interaction. Inspect `PreferenceApplied` and `PreferenceReason`: `PREFERENCE_TARGET_MISSING` requires explicit attribution; historical `PREFERENCE_SOURCE_UNAUTHORIZED` remains a retained decision, not a new source-registration requirement. When the recipient target is missing, explicitly complete attribution with `/interactions/link` and `ExpectedRevision`; omitted attribution fields are cleared, so include the fields to retain. An applied preference target cannot be changed. Replay does not override a later explicit opt-in. Existing applied results and historical source-denied decisions remain unchanged; there is no automatic historical replay. BOUNCE is diagnostic and does not change preferences. Execution-linked feedback must match the referenced DELIVERY Execution and its attribution; no fixed reporting-account binding is required.

Interaction files use CommHub permissions, same-tenant valid DMS references and retained metadata checks. Recording/linking them does not require the caller's DMS permission, source RefTypes, document ownership or a business-association grant. Download through `/interactions/files/download` requires Interaction READ plus `COMMHUB_DATA_UNMASK`, membership in the interaction's retained files and matching metadata. This interaction-file contract is separate from DELIVERY attachment submission, which retains its DMS authorization rules.

The customer timeline combines logical Executions and Interactions with paging and display masking. Use CustomerId as the explicit anchor. Preferences are keyed by the customer RecipientId and channel; keep receipt reporting, interaction recording and preference management as distinct integration operations.

Under RESPECT, an explicit allow/refusal wins. When no row exists, use the effective `DefaultAllowed` returned by `/preferences/getBySubjectId`; the built-in default is true, and deployments can explicitly set false. Missing Preferences means no stored rows, not refusal or consent. BYPASS skips preference evaluation, including explicit refusal, but does not bypass other validation. The default is read-only service configuration, not a customer or Binding field.

`POST /preferences/save?subjectId=...` accepts `Rows: [{Channel, OptedIn}]` and Source, updates only submitted channels atomically, and leaves other channels unchanged. Preferences are checked again at dispatch/retry. An all-skipped Task can be NO_ACTION: no delivery occurred. Changing a default does not replay old skipped Tasks.

## 10. Operations and configuration history

Start investigation with RequestId, TaskId or the business reference. Execution and Attempt ErrorCode/ErrorMessage provide safe business summaries; unknown technical errors use generic text, without raw provider responses or exception details. Use correlation IDs and controlled operational logs for deeper diagnosis. Inspect the accepted configuration snapshot, the affected Execution, its Attempts and events before selecting an action. Keep current configuration and the accepted snapshot visible as separate records.

| Capability | Operational use |
| --- | --- |
| Template content history | Use `/templates/history/list` and `/templates/history/detail` to inspect retained revisions; `/templates/contents/text` and `/templates/files/download` expose the selected immutable content under their permissions. |
| Template file input | Upload opaque templates or file-backed BODY source with `/templates/files/upload`. Template content uploads are separate from runtime `/attachments/upload`. |
| Accepted configuration | `/configuration-snapshots/getById`, `/configuration-snapshots/list` and `/configuration-snapshots/tasks` connect immutable configuration to its accepted Tasks. |
| Generated/archived files | `/files/list` and `/files/download` expose retained output records under their access rules. A runtime input attachment is not a generated output. |
| Alerts | `/alerts/list` provides operational alerts. Receipt timeout, unknown outcomes and terminal failure need different responses; an alert is not another ExecutionStatus. |
| Timeline | `/timeline/list` requires CustomerId or paired RefType/RefNumber; supplying both narrows the result to their intersection. It pages masked Execution and Interaction summaries. |

### Delivery policy behavior

Time restrictions use allowed local-time intervals, including overnight intervals, and EVERY_DAY or WORKDAY_ONLY calendar selection. Frequency caps apply all configured rolling limits. A policy's GroupId is configuration ownership, not a quota dimension.

For cap overflow, `SUPPRESS` ends the candidate; `DEFER` schedules its next eligible time without advancing fallback. Preferences and current dispatch eligibility still matter when scheduled/retried work becomes due. Retained accepted configuration does not mean a revoked customer preference can be ignored.

Operational workers process due work, retries, receipt deadlines and recovery. When scheduled work is late, inspect its policy/expiry and worker health before issuing a manual retry. Receiver deduplication and callback correlation remain necessary even when the Hub serializes its own state transitions.

### Background processing and alert notifications

The sweeper runs by default with CommHub. Set `comm-hub.sweep.enabled=false` explicitly to disable it. When enabled, it processes records that meet the existing due-state rules, including scheduled work, retries, receipt deadlines and recovery; enabling it does not authorize an unsafe resend. During a rolling upgrade, update all workers sharing the queue before relying on the simplified interaction and REST_WEBHOOK rules.

Background workers respect the platform runtime scheduling state. Scans use bounded pages and advancing cursors, with tenant concurrency isolation and fair progression; sending can use otherwise idle capacity. These controls are cooperative scheduling budgets and database query hints, not a guaranteed hard query timeout on every database. Inspect worker health and due-state evidence when work is late.

Operational alerts are published through EventBridge on `GimoBus`, with source `gimo:commhub` and type `commhub:alert:DeadLetter`. Match OPEN and RECOVERED transitions by `IncidentId` and `Scope`. Configure notification rules to require `AlertEnabled=true` and select the intended transition and destination. This event extension comes from the platform-wide `alert.enabled` setting, whose default is false; it is shared with other platform capabilities, including Batch and TCC. There is no separate CommHub alert-enable switch. Events can still reach EventBridge while notifications are disabled; bridge acceptance is not proof that a downstream notification was received.

To enable alert routing:

1. Create a dedicated CommHub / EventBridge Group in the PUB module.
2. Register and activate source `gimo:commhub` and event type `commhub:alert:DeadLetter` on the existing `GimoBus`.
3. Configure `CommHubAlertOpen` and `CommHubAlertRecovered` rules for that source/type, matching OPEN and RECOVERED respectively. Both rules must require `AlertEnabled=true` and use approved notification targets.

`AlertEnabled` is captured when an event is created and retained in its stored event payload. Changing `alert.enabled` later does not rewrite historical pending events.

The alert publisher waits at most five seconds during shutdown. Unfinished durable publication records remain available for recovery; the wait limit does not guarantee that every event has reached its destination before shutdown.

### Request, error and pagination details

Task.TraceId records submission; Execution.TraceId tracks the latest claimed attempt; each Attempt.TraceId identifies that Attempt's logs. Backend logs carry BusinessKeyContext.CommHubTaskId. An Attempt's legacy Request is the Hub's outbound business envelope. Optional PreprocessingExchange and DeliveryExchange separately describe retained HTTP evidence; these are sanitized records, not raw wire captures.

| Need | Method and path suffix |
| --- | --- |
| Masked full submitted Request | GET tasks/request?taskId=... |
| Original full submitted Request | POST tasks/request/original with TaskId |
| Masked retained outbound for one Attempt | GET executions/request?executionId=...&attemptId=... |
| Original retained outbound | POST executions/request/original with ExecutionId and optional AttemptId |
| Download Request JSON | GET tasks/request/download or executions/request/download with matching selectors; original=false by default. |
| Original business Payload only | POST tasks/original — different from the full Task Request. |

Always select attemptId to inspect a specific older Attempt. Omission selects the current active Attempt, not an arbitrary failed one. Read Available/Masked; a historical or never-invoked Attempt can legitimately have no retained request. Never reconstruct missing evidence from current template/configuration.



Use `/executions/error?executionId=...&attemptId=...` for one Attempt and `/tasks/error?taskId=...&executionId=...&attemptId=...` for Task-scoped diagnostics. Protected POST `/executions/error/original` and `/tasks/error/original` expose originals under the matching history READ plus `COMMHUB_DATA_UNMASK`. Details can include HttpStatus, ResponseBody, ResponseTraceId and StackTrace when retained. Check Available/Masked; do not reconstruct absent evidence. Original request downloads require an explicit `original=true` choice and the same dual authorization.

Service template selection returns the requested page and current tenant-scoped totals from the upstream template service. Follow its returned status and paging metadata; the selector does not impose an additional 2,000-template verification limit. Selection is authoring assistance and does not replace save, preview or dispatch validation.

Ordinary pages return `TotalElements`, `TotalPages`, `NumberOfElementsInCurrentPage` and `ElementsInCurrentPage`. Execution `/files/list` is different: `Files`, `RenderUsages`, `FileTotal`, `RenderUsageTotal` and shared `PageIndex`, `PageSize`, `PageCount`. Executions and Interactions support `sortDirection=ASC|DESC`, default DESC; do not assume Task lists support that parameter.

### Inspect submitted files, historical Bindings and Attempt diagnostics

Start with `/tasks/request` and `/tasks/attachments`, then page `/executions/list?taskId=...`. Task detail's embedded Executions can be partial; honor ExecutionsHasMore. Execution summaries expose accepted BindingId, and `/executions/getById` can return a safe `Binding` projection with DefinitionId, DefinitionRevision, RenderMode and accepted attachment Slots. Use this snapshot and the recorded Execution outcome after current configuration changes. Older records may lack these fields; do not infer them from a live editor.

Tasks and Executions support `orgCodes=A,B` as one comma-separated query parameter. It matches the Task's optional OrgCode, which is also projected on Execution history. Trim organization values at submission; this is a filter, not an authorization grant. Do not replace it with an unsupported singular orgCode query.

For one Attempt, call `/executions/request?executionId=...&attemptId=...`. Its optional PreprocessingExchange and DeliveryExchange contain Method, HttpStatus, RequestBodyState, ResponseBodyState and retained body text. Default reads mask retained bodies without loading original text. Protected `POST /executions/request/original` with ExecutionId and AttemptId requires Execution READ plus `COMMHUB_DATA_UNMASK` and is audited. Render original bodies as text, never active HTML.

| Evidence | Interpretation |
| --- | --- |
| No exchange | Evidence is unavailable for that Attempt, including older history. |
| Exchange without HttpStatus | No HTTP response was observed. |
| RETAINED / EMPTY | A body was retained (masked by default), or the body was empty. |
| TOO_LARGE / OMITTED | Body text was not retained; do not interpret this as an empty response. |

Legacy Available describes the outbound Request only: a failed hook can have PreprocessingExchange even when Available=false. The hook exchange belongs to the Attempt that ran it; ordinary retries using prepared content and Resend do not create another hook call. A new delivery exchange belongs to the newly invoked Attempt. Immediate HTTP acceptance, provider receipt and error diagnostics remain separate evidence. Request downloads retain their existing snapshot contract.

Recognized credentials, links and attachment bytes are removed from captured bodies. The per-body setting `comm-hub.history.http-exchange.max-body-mb` accepts integer values 1–16 (default 5; each MB is 1048576 bytes); absent or invalid values use the default. Oversized body text is omitted. When tenant encryption is disabled, only metadata is retained and body state is OMITTED. Lowering the limit does not make older retained bodies unreadable.

### Transactions and portability

Use Async submission inside an active TCC/global transaction. PENDING_COMMIT describes an accepted command awaiting confirmation; cancellation does not authorize dispatch. Recover a lost submission response using the original RequestId and inspect the existing command before starting new work.

Configuration DataIO exports reusable configuration, including template language/content references and selected-engine validation. Runtime Tasks, uploads, Attempts, operation evidence and byte snapshots remain runtime history. Do not use a configuration import as a way to replay communications.

## 11. API map and integration checklist

| Area | Main routes |
| --- | --- |
| Configuration | `/definitions/*`, `/bindings/*`, `/context-definitions/*`, `/templates/*`, `/services/*`, `/delivery-policies/*` |
| Submit and progress | Four `/tasks/submit...` variants; `/task-requests/getById` |
| Runtime history | `/tasks/list`, `/tasks/getById`, `/executions/list`, `/executions/getById`, `/executions/attempts`, `/executions/events`, `/executions/operations` |
| Results and operations | `/callbacks/result`, `/executions/actionEligibility`, `/executions/retry`, `/executions/resend`, `/executions/resendResult`, `/attempts/result`, `/executions/recover`, `/executions/reconcile`, `/executions/result`, `/executions/cancel`, `/executions/stopRetries` |
| Attachment inputs/history | `/tasks/attachments`, `/tasks/attachments/download`, `/attachments/upload`, `/attachments/getById`, `/attachments/download`, `/attachments/list`, `/attachments/downloadSnapshot`, `/attachments/downloadForDelivery` |
| Customer activity | Interaction, preference and timeline operations in the API reference. |

Use the [Connect Hub API Reference](https://docs.insuremo.com/tech/pro/sdk/api/connecthub) for complete contracts; the [walkthrough](./comm_hub_e2e.md) assembles the main calls in order.

Before integrating, establish stable RequestIds, explicit receipt semantics, receiver deduplication and callback identity. Choose Sync versus Async deliberately. Preserve uncertainty in status displays. Configure only supported source/driver capabilities and separate human original-data access from machine attachment access. Configuration DataIO moves configuration; it does not transfer runtime uploads, Tasks, Attempts or their byte snapshots.

## SDK compatibility

SDK 1.2.100 includes request SlotKey/Cardinality. In its generated `CommDefinitionAttachment` response model, typed `getCardinality()` can retain SINGLE while the underlying Map/original response contains MULTIPLE. Read the actual Map value or use the Map-based iComposer Utils result; do not treat the typed default as authoritative. The generated response getter remains a limitation.
