# Gateway math and Precise workflows

Authority: current implementation and operator notes. The repository tests and `describe` output are runtime truth. Nothing in this page claims a deployment.

## What works now

The Gateway runs named, domain-neutral mathematical methods and retains their literal result records. The Precise Harness owns named workflows, turns workflow data into method calls, interprets the returned results, and appends a new immutable cycle when an outcome arrives.

These names are a builder and drill-down surface. A Product customer connects sources, confirms a field map once, and states a measured goal; the Product harness chooses and composes the fitting workflows, reruns them when data changes, and keeps the last complete answer visible during the refresh. Its artifact projector must return the finest supported controllable primitives, such as creative × channel × audience × placement, with measured contribution, uncertainty, interactions, current size, and marginal value. Unsupported dimensions remain missing, and measured decomposition is not a causal claim. Calls, actions, and outcomes remain Product state.

A retained continuation workflow keeps its initial input, exact outcome bytes and values, completed and pending cycles, every step's literal input and output, and the Gateway run references and digests. This is durable execution history. It is not a hidden model, an incrementally updated primitive, or Precise Decision Learning state.

The default development tree exposes 24 methods:

- 17 dependency-light TypeScript methods;
- four contribution methods from the trace-score Python worker;
- three calibration, response, and regime methods from the calibration-breadth Python worker.

The standing composition exposes the 17 dependency-light methods without worker configuration. It exposes all 24 only when both worker URLs and their immutable release digests are configured. Worker-backed method versions contain the bound implementation digest, and workflow definitions resolve those exact versions from the mounted catalog.

Run the connected surfaces:

```bash
cd harness
npm run precise -- describe
npm run precise -- math methods
npm run precise -- workflow workflows
```

The default tree loads worker processes lazily. Listing methods and workflows does not start Python.

## Ownership

The Gateway owns:

- the method catalog and its input/output schemas;
- execution controls, method implementation binding, and tenant-bound run identity;
- literal method output and diagnostics;
- immutable terminal run records in memory, local files, or GCS.

The Precise Harness owns:

- `understand-the-book`, `find-the-next-move`, `design-the-test`, and `measure-and-learn`;
- focused caller-selected workflows;
- method-input transforms and dependencies;
- exact-versus-sampled variants and same-cycle comparisons;
- interpreted cycle findings and comparison with the prior outcome cycle;
- complete step inputs and outputs, raw Gateway references, append-only cycle history, and outcome continuation.

Another company can define its own workflow and artifact layer over the same Gateway methods. It does not need a fork of the math.

## Gateway commands

The mounted child is `math`.

| Command | Input | Result |
|-|-|-|
| `methods` | `{}` | Mounted method names, implementation-bound versions, schemas, and scaling modes. |
| `run` | `{request_id, method, input, seed?, resources?}` | One verified terminal `gateway.run/v1` record. |
| `result` | `{run_id}` | The retained result or `null`. |
| `status` | `{run_id}` | Current process-local active status or the retained terminal status. |
| `cancel` | `{run_id}` | Cancellation result; cancellation is separate from analytical `not_computable`. |

`request_id` is idempotent inside a tenant. Repeating the same request returns the same run. Reusing it for different method, input, implementation version, seed, or resources is a conflict.

The public run request does not accept `method_version`. The Gateway injects the version from its own catalog. A result binds tenant, request, method, method version, input digest, execution-control digest, status, output, diagnostics, and a digest of the complete retained record.

### Execution controls

`resources` currently supports:

- `items`: maximum length admitted for any input array;
- `samples`: ceiling applied to methods with a sample-count control;
- `time_ms`: cooperative in-process deadline and a real HTTP/subprocess deadline;
- `memory_bytes`: `null` only; a non-null value is rejected because this executor cannot measure memory honestly.

Seeds are non-negative safe integers. Malformed method input, non-finite arithmetic, and an exhausted declared deadline become retained terminal diagnostics. Network, worker-process, and HTTP 5xx availability failures remain retryable and do not mint a false terminal computation.

### Current async boundary

Method execution is concurrent where a workflow DAG has independent ready steps, but `math run` itself still waits for a terminal record. Queued and running state exists only in the serving process. Terminal results are durable; active jobs are not a restartable queue yet. `status` and `cancel` are useful during a concurrent in-process call, not evidence of a detached job service.

## Precise workflow commands

The mounted child is `workflow`.

| Command | Input | Result |
|-|-|-|
| `workflows` | `{}` | Definitions with step IDs, resolved method versions, dependencies, accepted statuses, and input contracts. |
| `start` | `{workflow_id, workflow, input}` | First immutable cycle and current workflow state. |
| `focus` | `{workflow_id, methods, input}` | A focused one-cycle workflow over caller-selected mounted methods. |
| `outcome` | `{workflow_id, event_id, event_bytes, outcome}` | Duplicate-safe successor cycle after exact byte/value verification. |
| `result` | `{workflow_id}` | Current append-only record or `null`. |

Workflow input is a JSON object with `method_inputs`. A step reads its step ID first and its method name as a fallback. Later outcome data can merge method-specific overrides and the workflow-level input patch into each new cycle's inputs; the producer does not need to resend every complete request. A dependent step may derive a fit from an earlier result in the same cycle.

Independent ready steps run concurrently. Stored result order follows definition order, so scheduling does not change retained bytes. A deterministic method-input error ends the cycle; it does not retry forever. Every Gateway terminal result, including an unaccepted or future status, remains referenced in the failed cycle.

### What the workflow state means

Within one cycle, a step can consume only the outputs of dependencies named in the workflow. The current named workflows have two such links:

- `value/additive-fit` supplies the fit used by `value/additive-predict` in `understand-the-book`;
- `value/gradient-fit` supplies the fit used by `value/gradient-analyze` in `understand-the-book`, `find-the-next-move`, and `measure-and-learn`.

The other named steps are parallel analyses. Saturation does not currently feed the frontier, the frontier does not feed pricing or portfolio selection, and the test-design methods do not feed one another. Their results are retained and compared, but the workflow does not yet turn them into one product decision.

Across cycles, the workflow rebuilds each step input by replaying the original `method_inputs`, all earlier outcome patches, and the new patch. Nested objects merge; later values replace earlier arrays or scalar values. Every step then runs again under a new cycle request. Earlier fits, estimates, and models stay in history; they are not silently installed as the current state of a primitive. A Product adapter must translate a real outcome into the method patches the next cycle needs.

A durable store also retains a pending cycle and every step that already finished. After a restart, completed steps are reused and only unfinished or retryable work runs again. This recovery relies on the same deterministic Gateway request IDs and durable terminal run records.

## Interpretation and adversarial runs

`understand-the-book` runs exact and sampled variants for Shapley, pair interaction, and Owen contribution. Exact work may return `not_computable` at its explicit exponential limit while the sampled variant continues. The workflow accepts and retains both.

Each cycle artifact contains:

- the exact Gateway run IDs, method versions, result digests, statuses, diagnostic digests, and output digests;
- comparisons with the same step in the previous outcome cycle;
- same-cycle comparisons between repeated methods;
- aligned numeric estimate gaps and sampled uncertainty where the result exposes them;
- plain findings for missing keys, status disagreement, diagnostics, and changed results.

These findings are interpretation, not permission. They do not suppress raw results or stop a caller from selecting another estimator, value function, grouping, seed, or sample design.

## Outcome continuation

There are two real entry paths:

1. An authenticated caller invokes `workflow outcome` with exact JSON bytes and the parsed value. The Harness verifies that the two representations match before appending a cycle.
2. The standing composition reads a tenant-bound create-only outcome head after a signed `subject_head.advanced` event. The source record binds subject, sequence, tenant, and content digest. Duplicate delivery is harmless; the same event ID with different bytes is an integrity error.

The outcome store has local-file and generation-checked GCS implementations. The standing composition exposes the producer/store port to the authorized Product adapter but intentionally has no unauthenticated HTTP write route. The host or Product source lands the bytes, then sends only the signed pointer event.

Workflow persistence has memory, local-file, and GCS implementations. GCS revisions are content-addressed before a generation-CAS head update, so a crash between those writes cannot reserve the next revision forever.

The signed path verifies subject, sequence, tenant, and content digest before continuation. The workflow cycle itself currently retains the event ID, exact outcome bytes, and parsed outcome value, but not the signed subject ID, head sequence, and head digest as a direct source reference. A product that displays source lineage must join that separate custody record until this link is carried into the cycle.

## Product fit and current limits

This workflow service is suitable for reusable math orchestration, focused analysis, adversarial estimator comparison, restart-safe result history, and demos that show how results change after an outcome.

It is not, by itself, the state model for the Trust Portal or a product that claims a closed learning loop. Precise Decision Learning remains separate and owns baseline observations, recommendations, actual exposure, mature outcomes, scores, learning decisions, exact source references, accepted learned-state successors, and any authorized action. A product workflow may call this math and retain these run records without treating them as those Product records.

Three persistence limits matter for long-lived workflows:

- a waiting continuation workflow can continue only while its exact workflow and method versions remain mounted; changing a method or workflow version currently leaves that workflow readable but unable to accept another outcome;
- each settled step writes another complete workflow revision containing all earlier cycles and full step inputs and outputs, so stored and written bytes grow quickly with step count and cycle count;
- active method execution is not durable, as described above. A restart reuses a terminal record if one landed or reruns the pending pure calculation; it does not resume the old process.

## Scaling

There is no global item limit of 16.

- Exact Shapley is explicitly bounded at 20 players because it enumerates an exponential game.
- Exact pair interaction and exact Owen calculation are explicitly bounded at 16 players for the same reason.
- `auto` routes larger Shapley, pair, and Owen requests to sampled implementations.
- Pair interaction accepts a sparse requested pair list instead of allocating every pair.
- `contribution/from-observations` reduces caller-evaluated permutation prefixes or sparse four-corner samples for arbitrary vertical value functions. Its memory grows with the supplied observations and requested players or pairs, not with `2^n`.
- A complete coalition table remains available for small custom finite games; it is not the large-`n` transport.

The bridge request limit is 16 MiB and worker HTTP concurrency is bounded. Those are service-protection limits, not analytical item caps.

## Deployment status

The code is connected in the default development tree and the standing composition. No recorded staging revision contains this build. The 2026-09-02 staging observation, `app_rev_4ac0c1d7`, predates the current `math` child and default continuation workflows. A later standing deployment needs durable run/workflow storage plus release-bound worker URLs if it is expected to expose worker-backed methods.
