File size: 19,988 Bytes
152e0c1
af1bee9
152e0c1
 
330591c
af1bee9
152e0c1
 
 
af1bee9
152e0c1
 
af1bee9
 
 
 
 
 
 
 
 
152e0c1
af1bee9
152e0c1
af1bee9
 
 
152e0c1
af1bee9
 
152e0c1
af1bee9
 
 
 
 
152e0c1
af1bee9
152e0c1
af1bee9
152e0c1
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152e0c1
 
 
 
 
 
 
 
 
 
af1bee9
 
 
fc62edf
152e0c1
 
af1bee9
 
 
 
 
152e0c1
af1bee9
 
 
 
 
 
 
 
 
 
 
 
fc62edf
af1bee9
fc62edf
 
152e0c1
 
af1bee9
152e0c1
af1bee9
fc62edf
 
af1bee9
152e0c1
 
 
 
 
 
 
 
 
 
 
 
 
af1bee9
 
152e0c1
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
152e0c1
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
152e0c1
af1bee9
1de224d
 
152e0c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1de224d
 
152e0c1
 
1de224d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ccfcfd5
 
 
 
 
 
 
 
 
 
152e0c1
ccfcfd5
152e0c1
 
 
 
 
 
ccfcfd5
1de224d
 
af1bee9
 
 
152e0c1
af1bee9
 
 
152e0c1
 
 
 
af1bee9
 
 
 
 
152e0c1
 
 
 
 
af1bee9
 
152e0c1
 
 
 
 
 
af1bee9
 
 
 
 
 
 
 
 
 
 
152e0c1
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152e0c1
 
 
 
af1bee9
 
 
 
 
 
152e0c1
 
af1bee9
 
 
152e0c1
 
af1bee9
152e0c1
 
af1bee9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# Oracle AI Agent Studio β†’ Astra

This guide explains how an Oracle Fusion Cloud AI Agent Studio workflow runs a patch test cycle in Astra. Fusion
owns the schedule, the synthetic test data and both human approvals. Astra (LangGraph) writes the test scripts,
runs the browser tests and reports back. The OpenAPI spec is `web/src/api/openapi.json` (tag **agent-studio**). The live `/api/docs` page is off on the public Space (`FPT_API_DOCS=0`).

Some names on the wire still say `patchwise` (the scope `patchwise.invoke`, the `X-Patchwise-*` headers, the
`pwc_`/`pws_`/`pwk_`/`pwa_` prefixes). They are part of the contract the Fusion workflows already use and do not change.

```

Oracle Fusion Cloud                                        Astra

───────────────────                                        ─────

Scheduler (weekly)

  β”” AI Agent Studio workflow

     1 Read module space

     2 Generate synthetic test data JSON

     3 Mask / validate          ── POST /api/agent-studio/v1/test-data/check ──▢ (optional pre-check)

     4 Human approval (data)    ── POST /api/agent-studio/v1/cycles ───────────▢ test script generator

     5 Email + notification     ◀── callback scripts_ready β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

     6 Human approval (start)   ── POST /api/agent-studio/v1/cycles/{id}/approval β–Ά Playwright browser runner

                                                                                   (User B, TEST_US_BU)

                                ◀── callback failures_need_review (if any) ─────── triage (a person, in Astra)

     7 Email + notification     ◀── callback results / stopped ────────────────── reports

                                ◀── callback paused (optional, may be ignored) ─── a restart interrupted the run

Release watch agent             ◀── callback patch_update ───────────────────── web crawler of Oracle release notes

```

**Contract:** test data is **synthetic only**, with no personal data and no real transactions. Astra refuses values
that look like an email address, a phone or card number, or a national id (`NOT_SYNTHETIC`). Every approval is made by
a person: the two in Fusion are forwarded with that person's name, and test failures are always decided by a person
in Astra, never automatically.

## Users and privileges

| Who | Where | Can |
|---|---|---|
| User A | Fusion only | data roles for the workflow; never given to Astra |
| User C | the OAuth client (`patchwise.invoke`) | start cycles, read them, forward approvals. Cannot list runs or touch anything else |
| User B | the Fusion test pod's sign-in, stored in Astra | the browser tests: action privileges only, in test business unit `TEST_US_BU` |

## 1. Set up (an Astra admin)

1. **Test environments**: register the Fusion test pod with User B's sign-in (it is stored in the vault and never shown).
2. **Agent Studio β†’ Clients β†’ New client**: name it and give the HTTPS **callback address** (step 5/7 in Fusion), and
   optionally a **release watch address**. The `client_id`, `client_secret` (`pws_…`) and `signing_key` (`pwk_…`) are
   shown **once**. Store them in Fusion's credential store and nowhere else.
3. In Agent Studio, add a REST tool / external connection:
   - Token URL `https://<space>/oauth/token`, grant `client_credentials`, scope `patchwise.invoke`.
   - Base URL `https://<space>/api/agent-studio/v1`.

To revoke a client, delete it in the same screen. Its tokens stop working at once.

## 2. The calls

### Token

```http

POST /oauth/token

Content-Type: application/x-www-form-urlencoded



grant_type=client_credentials&client_id=…&client_secret=…&scope=patchwise.invoke

```

HTTP Basic or a JSON body also work. The response is `{"access_token":"pwa_…","token_type":"Bearer","expires_in":3600,"scope":"patchwise.invoke"}`.
Send it as `Authorization: Bearer pwa_…` on every call below. Treat the token as opaque; only its `pwa_` prefix is
fixed.

**How tokens behave.** A token is signed by Astra (HMAC-SHA256 over the client id and the expiry time), so Astra checks
it without looking it up. A restart that restores an older saved state therefore does not end a token the Fusion side
has cached: it stays valid for its hour. The key is the vault secret `agent_studio.token_key`. Set
`FPT_SECRET_AGENT_STUDIO_TOKEN_KEY` on the server to keep it fixed; otherwise Astra makes one the first time and keeps
it in the saved state. Changing the key ends every token already issued, and the Fusion side then asks for a new one.
Every call still checks the client: a revoked client's tokens are refused at once (`401 invalid_token`). Tokens issued
before tokens were signed keep working until they expire.

### Check test data (optional)

`POST /test-data/check` with `{"test_data": {...}}` returns `{"ok": true, "areas": {...}, "mapped": {...}, "not_testable": [...]}`
or `{"ok": false, "code", "problem"}`. `mapped` lists the Fusion workflow's own area codes Astra renamed (below);
`not_testable` lists areas Astra has no Fusion tests for (HCM, PAY, ABS, BEN, IRC today).

### Start a cycle (after the person approves the data)

```http

POST /cycles

Idempotency-Key: 6c1f…            (optional)

{

  "test_data": {"AP": {"business_unit": "TEST_US_BU", "supplier": ["Test Supplier A", "Test Supplier B"], "currency": "USD"}},

  "data_approved_by": "Priya (Fusion QA)",

  "areas": ["AP"],

  "release": "26B",

  "correlation_id": "wf-2026-46",

  "environment": "Fusion test pod"

}

```

| Field | Notes |
|---|---|
| `test_data` | `{AREA: {key: value or [values]}}`. Area codes such as AP, PO, AR, GL. The workflow codes CE, PJ, REQ and RCV are read as CM, PPM, PO and PO (REQ and RCV keys merge into PO). Keys are lower_snake_case. At most 20 areas, 40 keys each, values of 200 characters or less. Values that look like an email are always refused; values that look like a phone, card, account or national id number are refused unless they start with `TEST_` (a test identifier made from a Fusion record number, e.g. `TEST_300000047382915`). These values are tried **first** by the browser runner, before the pod's own |
| `data_approved_by` | required: who approved the data in Fusion |
| `areas` | defaults to the test data's areas. Areas the pod cannot test are skipped and listed in `skipped_areas`; the cycle is refused (`BAD_TEST_DATA`) only when none can be tested |
| `package` | optional: the approved test data package of the V3.6 workflows (up to 2 MB). Kept with the cycle; its `package_id` is in the response and admins read it at `GET /api/agent-studio/cycles/{cycle_id}/package` |
| `depth` | `regression` (default): every approved scenario of each area, every priority, plus one end-to-end flow per business process of the area (at most `FPT_FUSION_REGRESSION_FLOWS`, 3) and the cross-area flows (Procure-to-Pay ...) when all their areas are tested. It also asks the AI model for one scenario per standard regression and edge-case check of the area (the `regression` list of `coworker/platform/fusion_catalog.py`: refusals, boundaries, duplicates, state changes, defaults, searches) that no library scenario covers yet, at most `FPT_FUSION_REGRESSION_CHECKS` (25, 0 = off) per area. `standard`: the patch's P1 scenarios and the ones its changes touch. `smoke`: the quickest check. Anything else is refused (`BAD_DEPTH`) |
| `environment` | the Astra test environment's name; defaults to the default Fusion pod |
| `callback_url` | defaults to the client's callback address |
| `correlation_id` | your workflow's id, echoed in every callback. Also makes the start safe to retry (below) |

The response is **202** with `{"cycle_id": "cyc_…", "run_id": "…", "areas", "skipped_areas", "package_id", "status", "waiting_for", "links": {"run", "excel", "report"}}`.
The approval answer has the same shape plus `decision`.

**Starting is safe to retry.** A call that timed out or got no answer can be sent again. Astra does not start a second
cycle or run in these cases:

- **Same `Idempotency-Key` header** (optional, up to 200 characters, per client). Astra returns the cycle that key
  made, whatever state it is in now.
- **Same `correlation_id`** from the same client while that cycle's run is still going (queued, running, or waiting

  for an approval or a decision). Once that cycle has finished, failed, been interrupted or been cancelled, the same

  `correlation_id` starts a new cycle. A workflow that sends the same id every week keeps working.



A repeated start gets the same **202** and the same body as the first call, plus the response header
`Idempotent-Replayed: true`. Astra saves the cycle as soon as it starts, and saves the start-testing decision as soon
as it is made, so a restart a few minutes later does not lose either one.

### Where a cycle is

`GET /cycles/{cycle_id}` returns the same shape. `waiting_for` is one of these exact strings (they do not change):
- `"approval in Oracle Fusion (start testing)"`;
- `"a person to decide the failures (in Patchwise)"`;
- `null`.

### The start-testing decision (step 6)

```http

POST /cycles/{cycle_id}/approval

{"decision": "approve", "approved_by": "Priya (Fusion QA)", "scenario_ids": ["AP-AI-003", "AP-FUS-001"]}

```

- Leaving out `scenario_ids` approves every scenario offered.
- `"reject"` cancels the cycle; `comment` is kept.
- Astra records the actor as `Priya (Fusion QA) (in Oracle Fusion)`.

### Errors

The body is `{"code", "detail", "request_id"}`.

| Status | Codes |
|---|---|
| 400 | `BAD_TEST_DATA`, `NOT_SYNTHETIC`, `NOT_APPROVED`, `BAD_DECISION`, `UNKNOWN_SCENARIO`, `BAD_URL` |
| 401 | `invalid_client`, `invalid_token` |
| 404 | `NO_CYCLE`, `NO_ENVIRONMENT` |
| 409 | the run is not waiting for that decision, or no Fusion environment exists |
| 422 | a required field is missing |

## 3. Callbacks (Astra β†’ Fusion)

Each OAuth client chooses how its events reach Fusion (**Agent Studio β†’ OAuth clients β†’ Delivery**).

### Delivery semantics (all three modes)

- **At least once.** An event can arrive more than once: a retry after a lost answer, a pull event handed out again,
  an admin sending a dead letter again, or an event made again after a restart restored an older saved state.
- **Stable ids.** Every event has a `delivery_id` (in the body, the `X-Patchwise-Delivery` header and the `deliveryId`
  parameter). The same logical event always has the same id. Astra derives it from the cycle, the event type and how
  many events of that type the cycle had before, so a copy made again after a restore keeps its id. Use
  `delivery_id` to drop repeats.
- **Order.** Events of one cycle are queued in the order they happen. A `paused` event that was not delivered before a
  newer event of its cycle is dropped (listed as `superseded`), so it never arrives after the cycle has moved on.
- **Dead letters.** An event that runs out of tries is kept as a **dead letter**: 6 sends for the URL and Fusion
  modes, or 20 pickups without a confirmation in pull mode. Astra writes an audit entry
  (`agent_studio.dead_letter`) and sends the admins one notification ("event(s) could not be delivered to Oracle
  Fusion"). The event shows as `dead` under **Agent Studio β†’ Callbacks**. An admin sends it again with **Send again**
  (`POST /api/agent-studio/deliveries/{delivery_id}/requeue`); its tries start over with the same `delivery_id`. A
  pull confirmation that arrives after the event became a dead letter still counts.

### Oracle Fusion directly (recommended; no relay)

Astra signs in to your OCI IAM identity domain with a confidential app (client credentials). The client secret is
write-only and kept in the vault; the token is held in memory only. Astra then starts the callback workflow:
`POST {Fusion address}/api/fusion-ai/orchestrator/agent/v2/{workflow code}/invokeAsync`, by default
`PATCH_TEST_CALLBACK_V3_7`.

The body is `{message, conversational, invocationMode, status, parameters}`. `parameters` holds what the workflow's
`READ_EVENT` reads:

- `event`, `cycleId`, `correlationId`, `deliveryId`;
- `payloadJson`: the body below as a string, with lists cut to 50 items when it would pass 60 KB;
- `verified: "sha256"`;
- `source`: `callback`, or `release_watch` for `patch_update`.

The settings are:

- the Fusion address, the token address, the client id and the client secret;
- the scope, only if your identity domain needs one;
- the workflow code, the invocation mode (`END_USER` or `ADMIN`) and the workflow status (`PUBLISHED` or `DRAFT`).

A 401 refreshes the token once. **Test sign-in** checks the app without starting a workflow. Fusion's `jobId` is
shown under **Callbacks**. The API is `PUT /api/agent-studio/clients/{id}/delivery` and
`POST /api/agent-studio/clients/{id}/delivery/test` (admin).

### Fusion picks them up (pull; no OCI IAM app)

Nothing is sent. Use this mode when nobody can create a confidential app in the pod's identity domain, for example on
a demo pod. The Fusion workflow asks for its events with the same OAuth client it uses for every other call, usually
in a **While Loop** with a **Wait** of 2 to 5 minutes after `createCycle`.

- **Pick up:** `POST /api/agent-studio/v1/events/claim` with `{"cycle_id": "cyc_…", "max": 5}`. Both fields are
  optional. The answer is `{events, count, more, confirm_within_s}`. Each event is the callback body below, plus
  `delivery_id` and `pickup` (how many times it was handed out).
- **Confirm:** `POST /api/agent-studio/v1/events/ack` with `{"delivery_ids": ["dlv_…"]}`. A confirmed event is not
  handed out again. Confirm every event you pick up, including types your workflow ignores (such as `paused`).

`POST /test-data/check` with `{"pickup": {"max": 1, "cycle_id": "cyc_…"}}` answers as `/events/claim`, and
`{"confirm": ["dlv_…"]}` answers as `/events/ack`, so a workflow can use its existing tool function.

An event that isn't confirmed within 5 minutes is handed out again, up to 20 times; after that it is a dead letter
(above). A client only sees and confirms its own events. To keep this mode on a server without saved state, add
`"delivery": "pull"` to the client in `FPT_SECRET_AGENT_STUDIO_BOOTSTRAP_CLIENTS`.

### Callback address (a relay or any receiver)

Callbacks are sent with `POST` to the callback address, as `Content-Type: application/json`, with these headers:

- `X-Patchwise-Event`: the event's name.
- `X-Patchwise-Delivery`: the event's stable id; use it to ignore duplicates.
- `X-Patchwise-Signature: sha256=<hex>`: an HMAC-SHA256 of the **raw body** with the client's signing key.

Answer with any 2xx code. Anything else, or no answer within 20 s, is retried after 1, 2, 4, 8 and 16 minutes (six
tries in all). Delivery state is listed under **Agent Studio β†’ Callbacks**. A callback is never sent unsigned: if the
client's signing key is missing from the vault, Astra logs an error and does not send it. The try counts as failed,
with the error "no signing key …", so the event ends up as a dead letter an admin can send again once the key is
back.

Every body has `event`, `delivery_id`, `sent_at`, `cycle_id`, `run_id`, `correlation_id` and `links`, plus:

| Event | When | Extra fields |
|---|---|---|
| `scripts_ready` | test scripts written, waiting for step 6 | `scenarios[]` (`id`, `title`, `area`, `priority`, `written_by`, `covers_patch_change`, `steps`), `count`, `approve_with`. `links.excel` is the test script |
| `failures_need_review` | some tests failed | `note`: a person decides each failure in Astra; `scenarios[]`, `count` |
| `results` | finished | `verdict` (`Ready` / `Not ready`), `areas[]` (`area`, `verdict`, `rule_result`, `counts`), `scenarios[]` |
| `stopped` | failed, cancelled or killed | `status`, `reason`, `resumable` (true for `failed`: an admin can resume the run, and the cycle then reports again) |
| `paused` | **optional, new.** A backend restart interrupted the run. It is not over: once an admin resumes it, the cycle goes on and sends its next events as usual | `status` (`interrupted`), `reason`, `resumable: true` |
| `patch_update` | the release watch found new items (to the release watch address) | `release`, `count`, `changes[]` (`id`, `area`, `title`, `on_by_default`, `impact`, `action_to_enable`, `link`) |

`paused` is the only event type the existing callback workflows (up to V3.11) do not know. They can ignore it. An
interrupted run used to be reported as `stopped`, but it can be resumed, so it is now `paused`. Astra keeps watching a
cycle whose run failed or was interrupted, and reports again (`scripts_ready`, `failures_need_review`, `results` or
`stopped`) when the resumed run moves on. New optional fields such as `resumable` may appear in any event; ignore
fields you do not know.

Verify a callback before using it:

```python

import hmac, hashlib

def verify(signing_key: str, raw_body: bytes, header: str) -> bool:

    want = "sha256=" + hmac.new(signing_key.encode(), raw_body, hashlib.sha256).hexdigest()

    return hmac.compare_digest(want, header or "")

```

## 4. The release watch

Every 24 hours (setting `agent_studio_watch_hours`; 0 turns it off), Astra reads Oracle's What's New for each
Fusion pod's release and for the areas in use. New items go to every client's release watch address as one
`patch_update`. The Fusion release watch agent drafts the impact assessment and emails it. Admins can run a check at
once with **Agent Studio β†’ Release watch β†’ Check now** (`POST /api/agent-studio/release-watch/check`).

## 5. The stand-in (no Fusion needed)

**Agent Studio β†’ Stand-in** plays the Fusion side through the same public API, for demos and tests:

1. Set a client's callback address to `https://<space>/api/agent-studio/standin/inbox`.
2. Send synthetic test data from the console.
3. Watch `scripts_ready` arrive (with its signature checked).
4. Approve in the console.
5. Watch `results` arrive.

The console only calls what Fusion would call. It cannot skip a human decision.

## 6. Where the data lives

The backend is the same as Astra v1. Supabase Auth handles sign-in and registration. An encrypted snapshot of the
app's data (the SQLite database, which holds the `agent_*` tables, plus the vault with the signing keys and the token
key, reports and evidence) is saved to a private Supabase Storage bucket whenever the database changes, and restored
after a restart. A new client, a revoked client, a new cycle and a start-testing decision ask for a save at once.
This Space uses **its own bucket, `patchwise-agent-studio`** (set in the Dockerfile), in the same Supabase project, so
it never overwrites v1's saved state. It also has its own `FPT_STATE_KEY`.

Space secrets to set:
- `SUPABASE_ANON_KEY` and `SUPABASE_SERVICE_KEY` (the same project as v1);
- `FPT_SECRET_FRONTIER_API_KEY`;
- `FPT_SECRET_FUSION_USERNAME` and `FPT_SECRET_FUSION_PASSWORD` (User B);
- optionally `FPT_SECRET_AGENT_STUDIO_TOKEN_KEY`, so tokens stay valid even if the saved state is lost.

## 7. Security notes

- Client secrets are stored hashed. Signing keys and the token key are kept in the vault. Access tokens are signed,
  not stored; tokens from before that change are stored hashed until they expire.
- A token is for this API only: it cannot read runs or call any other `/api` route.
- Callbacks go only to the client's own HTTPS address, through the egress gate, and every one is audited. They are
  never sent without a signature.
- Rotate a client's credentials by creating a new client and revoking the old one.