EnergyVenom commited on
Commit
fc62edf
·
verified ·
1 Parent(s): dbd6aed

Patchwise Agent Studio: Oracle AI Agent Studio cycles

Browse files
coworker/api/routes/agent_studio.py CHANGED
@@ -82,6 +82,7 @@ class CycleIn(BaseModel):
82
  masked: bool | None = None
83
  validated: bool | None = None
84
  module_space: dict[str, Any] | None = None
 
85
 
86
 
87
  class ApprovalIn(BaseModel):
@@ -98,7 +99,13 @@ def check_test_data(body: dict, request: Request, client: dict = Depends(agent_c
98
  td = validate_test_data(body.get("test_data"))
99
  except AgentStudioError as e:
100
  return {"ok": False, "code": e.code, "problem": str(e)}
101
- return {"ok": True, "areas": {a: sorted(k) for a, k in td.items()}}
 
 
 
 
 
 
102
 
103
 
104
  @router.post("/agent-studio/v1/cycles", status_code=202, summary="Start a test cycle with approved synthetic test data")
@@ -117,6 +124,15 @@ def get_cycle(cycle_id: str, request: Request, client: dict = Depends(agent_clie
117
  _fail(e)
118
 
119
 
 
 
 
 
 
 
 
 
 
120
  @router.post("/agent-studio/v1/cycles/{cycle_id}/approval", summary="The person's start-testing decision, made in Fusion")
121
  def approval(cycle_id: str, body: ApprovalIn, request: Request, client: dict = Depends(agent_client)):
122
  try:
 
82
  masked: bool | None = None
83
  validated: bool | None = None
84
  module_space: dict[str, Any] | None = None
85
+ package: dict[str, Any] | None = Field(None, description="the approved test data package (V3.6 workflows): kept with the cycle")
86
 
87
 
88
  class ApprovalIn(BaseModel):
 
99
  td = validate_test_data(body.get("test_data"))
100
  except AgentStudioError as e:
101
  return {"ok": False, "code": e.code, "problem": str(e)}
102
+ from ...platform import fusion_catalog
103
+ from ...platform.agent_studio import AREA_ALIASES
104
+ known = {x["code"] for x in fusion_catalog.areas(request.app.state.svc.cfg.home)}
105
+ sent = [str(a).upper() for a in body.get("test_data") or {}]
106
+ return {"ok": True, "areas": {a: sorted(k) for a, k in td.items()},
107
+ "mapped": {a: AREA_ALIASES[a] for a in sent if a in AREA_ALIASES},
108
+ "not_testable": sorted(a for a in td if a not in known)}
109
 
110
 
111
  @router.post("/agent-studio/v1/cycles", status_code=202, summary="Start a test cycle with approved synthetic test data")
 
124
  _fail(e)
125
 
126
 
127
+ @router.get("/agent-studio/cycles/{cycle_id}/package")
128
+ def cycle_package(cycle_id: str, request: Request, user: Principal = Depends(require("admin"))):
129
+ """The test data package the Fusion side approved for this cycle."""
130
+ try:
131
+ return _studio(request).package(cycle_id)
132
+ except AgentStudioError as e:
133
+ _fail(e)
134
+
135
+
136
  @router.post("/agent-studio/v1/cycles/{cycle_id}/approval", summary="The person's start-testing decision, made in Fusion")
137
  def approval(cycle_id: str, body: ApprovalIn, request: Request, client: dict = Depends(agent_client)):
138
  try:
coworker/platform/agent_studio.py CHANGED
@@ -49,6 +49,17 @@ _PII = [
49
  ]
50
  _KEY = re.compile(r"^[a-z][a-z0-9_]{0,39}$")
51
  _AREA = re.compile(r"^[A-Z][A-Z0-9]{1,5}$")
 
 
 
 
 
 
 
 
 
 
 
52
 
53
 
54
  class AgentStudioError(ValueError):
@@ -96,7 +107,8 @@ def validate_test_data(test_data) -> dict[str, dict[str, list[str]]]:
96
  raise AgentStudioError("BAD_TEST_DATA", f"'{area}' is not a business area code with its keys (AP, PO, GL ...)")
97
  if len(keys) > 40:
98
  raise AgentStudioError("BAD_TEST_DATA", f"{code}: at most 40 keys")
99
- out[code] = {}
 
100
  for key, vals in keys.items():
101
  if not _KEY.match(str(key)):
102
  raise AgentStudioError("BAD_TEST_DATA", f"{code}.{key}: keys are lower case words joined by _ (business_unit)")
@@ -110,13 +122,16 @@ def validate_test_data(test_data) -> dict[str, dict[str, list[str]]]:
110
  continue
111
  if len(s) > 200:
112
  raise AgentStudioError("BAD_TEST_DATA", f"{code}.{key}: a value is longer than 200 characters")
 
113
  for rx, what in _PII:
 
 
114
  if rx.search(s):
115
  raise AgentStudioError("NOT_SYNTHETIC", f"{code}.{key} looks like {what}: send synthetic test data only, "
116
  f"no personal or payment data")
117
  clean.append(s)
118
  if clean:
119
- out[code][key] = clean
120
  return {a: k for a, k in out.items() if k}
121
 
122
 
@@ -208,7 +223,19 @@ class AgentStudio:
208
  pod = next((p for p in pods if p["kind"] == "fusion" and p.get("is_default")), None) or next((p for p in pods if p["kind"] == "fusion"), None)
209
  if pod is None or pod["kind"] != "fusion":
210
  raise AgentStudioError("NO_ENVIRONMENT", "no Oracle Fusion test environment is registered in Patchwise", 409)
211
- areas = [str(a).upper() for a in body.get("areas") or td.keys()]
 
 
 
 
 
 
 
 
 
 
 
 
212
  callback = _check_url(body.get("callback_url"), "callback address") or client.get("callback_url")
213
  # a full browser run as the action-only test user; a server set to quick simulations (tests, trials) simulates
214
  mode = "stub" if self.svc.cfg.playwright_mode == "stub" else "live"
@@ -228,13 +255,16 @@ class AgentStudio:
228
  self.db.insert("agent_cycles", {"cycle_id": cycle_id, "run_id": run_id, "client_id": client["client_id"],
229
  "correlation_id": str(body.get("correlation_id") or "")[:120] or None, "pod_id": pod["id"],
230
  "release": body.get("release"), "areas": json.dumps(areas), "test_data": json.dumps(td),
 
 
231
  "data_meta": json.dumps(meta), "data_approved_by": approved_by, "callback_url": callback,
232
  "last_status": "queued", "created_at": now_iso(), "updated_at": now_iso()})
233
  self.db.add_event(run_id, "agent_studio", "message", {"message": f"Started by Oracle AI Agent Studio with synthetic test data "
234
  f"approved in Fusion by {approved_by}."})
235
  self.svc.audit.append("agent_studio.cycle_started", actor=f"agent-studio:{client['client_id']}", run_id=run_id,
236
  summary=f"{cycle_id} {areas} data approved by {approved_by}",
237
- payload={"cycle_id": cycle_id, "areas": areas, "keys": {a: sorted(k) for a, k in td.items()}})
 
238
  return self.cycle(cycle_id)
239
 
240
  def cycle(self, cycle_id: str, client_id: str | None = None) -> dict:
@@ -243,10 +273,18 @@ class AgentStudio:
243
  raise AgentStudioError("NO_CYCLE", f"no test cycle {cycle_id}", 404)
244
  run = self.db.get_run(c["run_id"]) or {}
245
  return {"cycle_id": c["cycle_id"], "run_id": c["run_id"], "correlation_id": c["correlation_id"], "release": c["release"],
246
- "areas": _j(c["areas"]) or [], "status": run.get("status"), "waiting_for": _waiting(run),
 
247
  "data_approved_by": c["data_approved_by"], "scripts_approved_by": c["scripts_approved_by"],
248
  "links": self._links(c["run_id"]), "created_at": c["created_at"]}
249
 
 
 
 
 
 
 
 
250
  def cycles(self, limit: int = 50) -> list[dict]:
251
  return [self.cycle(r["cycle_id"]) for r in self.db.q("SELECT cycle_id FROM agent_cycles ORDER BY created_at DESC LIMIT ?", (limit,))]
252
 
@@ -287,7 +325,7 @@ class AgentStudio:
287
  self.db.update("agent_cycles", "cycle_id", cycle_id, scripts_approved_by=who, scripts_approved_at=now_iso(), updated_at=now_iso())
288
  self.svc.audit.append("agent_studio.approval", actor=actor, run_id=c["run_id"], summary=f"{cycle_id} {decision}",
289
  payload={"cycle_id": cycle_id, "decision": decision})
290
- return self.cycle(cycle_id)
291
 
292
  def _links(self, run_id: str) -> dict:
293
  from ..channels.core import absolute
@@ -382,6 +420,16 @@ class AgentStudio:
382
  return {"verdict": "Ready" if ready else "Not ready", "areas": areas}
383
 
384
  # ------------------------------------------------------------ release watch
 
 
 
 
 
 
 
 
 
 
385
  def check_releases(self, actor: str = "release-watch") -> dict:
386
  """Read Oracle's What's New for each Fusion pod's release and area in use; new or changed items go to every
387
  client's release watch address as one patch_update (the Fusion agent drafts the impact assessment)."""
@@ -416,10 +464,7 @@ class AgentStudio:
416
  (*key, json.dumps(sorted(c.get("id") for c in changes if c.get("id"))), now_iso()))
417
  checked.append({"release": p["release"], "area": code, "changes": len(changes), "new": len(new)})
418
  if new:
419
- found.setdefault(p["release"].upper(), []).extend(
420
- {"id": c.get("id"), "area": code, "title": c.get("title") or c.get("summary"), "on_by_default": bool(c.get("on_by_default")),
421
- "impact": c.get("impact"), "action_to_enable": c.get("action"), "link": (c.get("sources") or [{}])[0].get("url")}
422
- for c in new)
423
  sent = 0
424
  for rel, items in found.items():
425
  for cl in self.db.q("SELECT * FROM agent_clients WHERE revoked_at IS NULL AND release_watch_url IS NOT NULL"):
 
49
  ]
50
  _KEY = re.compile(r"^[a-z][a-z0-9_]{0,39}$")
51
  _AREA = re.compile(r"^[A-Z][A-Z0-9]{1,5}$")
52
+ # The Fusion workflows (PATCH_TEST_*_V3_6) name a few areas by their own codes: Cash Management CE, Projects PJ, and the
53
+ # requisition and receipt steps REQ and RCV, which Patchwise tests as part of Purchasing.
54
+ AREA_ALIASES = {"CE": "CM", "PJ": "PPM", "REQ": "PO", "RCV": "PO"}
55
+ # Identifiers the Fusion side made for tests start with TEST_ (often a Fusion record number behind it): not personal data
56
+ TEST_PREFIX = "TEST_"
57
+ MAX_PACKAGE = 2_000_000
58
+
59
+
60
+ def area_code(area) -> str:
61
+ code = str(area).strip().upper()
62
+ return AREA_ALIASES.get(code, code)
63
 
64
 
65
  class AgentStudioError(ValueError):
 
107
  raise AgentStudioError("BAD_TEST_DATA", f"'{area}' is not a business area code with its keys (AP, PO, GL ...)")
108
  if len(keys) > 40:
109
  raise AgentStudioError("BAD_TEST_DATA", f"{code}: at most 40 keys")
110
+ code = area_code(code) # REQ and RCV join PO, CE is CM, PJ is PPM
111
+ out.setdefault(code, {})
112
  for key, vals in keys.items():
113
  if not _KEY.match(str(key)):
114
  raise AgentStudioError("BAD_TEST_DATA", f"{code}.{key}: keys are lower case words joined by _ (business_unit)")
 
122
  continue
123
  if len(s) > 200:
124
  raise AgentStudioError("BAD_TEST_DATA", f"{code}.{key}: a value is longer than 200 characters")
125
+ test_id = s.upper().startswith(TEST_PREFIX)
126
  for rx, what in _PII:
127
+ if test_id and what != "an email address":
128
+ continue # TEST_300000047382915: a test identifier made from a Fusion record number
129
  if rx.search(s):
130
  raise AgentStudioError("NOT_SYNTHETIC", f"{code}.{key} looks like {what}: send synthetic test data only, "
131
  f"no personal or payment data")
132
  clean.append(s)
133
  if clean:
134
+ out[code][key] = list(dict.fromkeys(out[code].get(key, []) + clean))[:6]
135
  return {a: k for a, k in out.items() if k}
136
 
137
 
 
223
  pod = next((p for p in pods if p["kind"] == "fusion" and p.get("is_default")), None) or next((p for p in pods if p["kind"] == "fusion"), None)
224
  if pod is None or pod["kind"] != "fusion":
225
  raise AgentStudioError("NO_ENVIRONMENT", "no Oracle Fusion test environment is registered in Patchwise", 409)
226
+ asked = list(dict.fromkeys(area_code(a) for a in (body.get("areas") or td.keys())))
227
+ runnable = set(reg.run_areas(pod))
228
+ areas = [a for a in asked if a in runnable]
229
+ skipped = [{"area": a, "reason": f"Patchwise cannot test {a} on {pod['name']}"} for a in asked if a not in runnable]
230
+ if not areas:
231
+ raise AgentStudioError("BAD_TEST_DATA", f"none of the areas {', '.join(asked) or '(none)'} can be tested on {pod['name']}; "
232
+ f"it can test {', '.join(sorted(runnable)) or 'none yet (run Discover)'}")
233
+ package = body.get("package")
234
+ if package is not None and not isinstance(package, dict):
235
+ raise AgentStudioError("BAD_JSON", "package must be the test data package object")
236
+ package_json = json.dumps(package) if package else None
237
+ if package_json and len(package_json) > MAX_PACKAGE:
238
+ raise AgentStudioError("BAD_TEST_DATA", f"the package is larger than {MAX_PACKAGE // 1_000_000} MB")
239
  callback = _check_url(body.get("callback_url"), "callback address") or client.get("callback_url")
240
  # a full browser run as the action-only test user; a server set to quick simulations (tests, trials) simulates
241
  mode = "stub" if self.svc.cfg.playwright_mode == "stub" else "live"
 
255
  self.db.insert("agent_cycles", {"cycle_id": cycle_id, "run_id": run_id, "client_id": client["client_id"],
256
  "correlation_id": str(body.get("correlation_id") or "")[:120] or None, "pod_id": pod["id"],
257
  "release": body.get("release"), "areas": json.dumps(areas), "test_data": json.dumps(td),
258
+ "skipped_areas": json.dumps(skipped), "package": package_json,
259
+ "package_id": str((package or {}).get("package_id") or "")[:120] or None,
260
  "data_meta": json.dumps(meta), "data_approved_by": approved_by, "callback_url": callback,
261
  "last_status": "queued", "created_at": now_iso(), "updated_at": now_iso()})
262
  self.db.add_event(run_id, "agent_studio", "message", {"message": f"Started by Oracle AI Agent Studio with synthetic test data "
263
  f"approved in Fusion by {approved_by}."})
264
  self.svc.audit.append("agent_studio.cycle_started", actor=f"agent-studio:{client['client_id']}", run_id=run_id,
265
  summary=f"{cycle_id} {areas} data approved by {approved_by}",
266
+ payload={"cycle_id": cycle_id, "areas": areas, "skipped_areas": [x["area"] for x in skipped],
267
+ "package_id": (package or {}).get("package_id"), "keys": {a: sorted(k) for a, k in td.items()}})
268
  return self.cycle(cycle_id)
269
 
270
  def cycle(self, cycle_id: str, client_id: str | None = None) -> dict:
 
273
  raise AgentStudioError("NO_CYCLE", f"no test cycle {cycle_id}", 404)
274
  run = self.db.get_run(c["run_id"]) or {}
275
  return {"cycle_id": c["cycle_id"], "run_id": c["run_id"], "correlation_id": c["correlation_id"], "release": c["release"],
276
+ "areas": _j(c["areas"]) or [], "skipped_areas": _j(c.get("skipped_areas")) or [], "package_id": c.get("package_id"),
277
+ "status": run.get("status"), "waiting_for": _waiting(run),
278
  "data_approved_by": c["data_approved_by"], "scripts_approved_by": c["scripts_approved_by"],
279
  "links": self._links(c["run_id"]), "created_at": c["created_at"]}
280
 
281
+ def package(self, cycle_id: str) -> dict:
282
+ """The test data package the Fusion side approved for this cycle (its source of truth for payloads and create order)."""
283
+ c = self.db.one("SELECT package FROM agent_cycles WHERE cycle_id=?", (cycle_id,))
284
+ if not c:
285
+ raise AgentStudioError("NO_CYCLE", f"no test cycle {cycle_id}", 404)
286
+ return _j(c["package"]) or {}
287
+
288
  def cycles(self, limit: int = 50) -> list[dict]:
289
  return [self.cycle(r["cycle_id"]) for r in self.db.q("SELECT cycle_id FROM agent_cycles ORDER BY created_at DESC LIMIT ?", (limit,))]
290
 
 
325
  self.db.update("agent_cycles", "cycle_id", cycle_id, scripts_approved_by=who, scripts_approved_at=now_iso(), updated_at=now_iso())
326
  self.svc.audit.append("agent_studio.approval", actor=actor, run_id=c["run_id"], summary=f"{cycle_id} {decision}",
327
  payload={"cycle_id": cycle_id, "decision": decision})
328
+ return {**self.cycle(cycle_id), "decision": decision}
329
 
330
  def _links(self, run_id: str) -> dict:
331
  from ..channels.core import absolute
 
420
  return {"verdict": "Ready" if ready else "Not ready", "areas": areas}
421
 
422
  # ------------------------------------------------------------ release watch
423
+ @staticmethod
424
+ def release_item(c: dict, area: str, release: str) -> dict:
425
+ """One new What's New item as the Fusion callback workflow reads it (title, description, release, area and the
426
+ oracle.com source as source_url)."""
427
+ url = (c.get("sources") or [{}])[0].get("url")
428
+ return {"id": c.get("id"), "area": area, "release": str(release).upper(), "title": c.get("title") or c.get("summary"),
429
+ "description": c.get("summary") or c.get("description") or c.get("impact") or "",
430
+ "on_by_default": bool(c.get("on_by_default")), "impact": c.get("impact"), "action_to_enable": c.get("action"),
431
+ "link": url, "source_url": url}
432
+
433
  def check_releases(self, actor: str = "release-watch") -> dict:
434
  """Read Oracle's What's New for each Fusion pod's release and area in use; new or changed items go to every
435
  client's release watch address as one patch_update (the Fusion agent drafts the impact assessment)."""
 
464
  (*key, json.dumps(sorted(c.get("id") for c in changes if c.get("id"))), now_iso()))
465
  checked.append({"release": p["release"], "area": code, "changes": len(changes), "new": len(new)})
466
  if new:
467
+ found.setdefault(p["release"].upper(), []).extend(self.release_item(c, code, p["release"]) for c in new)
 
 
 
468
  sent = 0
469
  for rel, items in found.items():
470
  for cl in self.db.q("SELECT * FROM agent_clients WHERE revoked_at IS NULL AND release_watch_url IS NOT NULL"):
coworker/platform/migrations/023_agent_studio_v36.sql ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ -- 023: the Fusion workflows V3.6 send the approved test data package with each cycle; areas Patchwise cannot test on
2
+ -- the pod are skipped (and said) instead of refusing the whole cycle.
3
+ ALTER TABLE agent_cycles ADD COLUMN package TEXT;
4
+ ALTER TABLE agent_cycles ADD COLUMN package_id TEXT;
5
+ ALTER TABLE agent_cycles ADD COLUMN skipped_areas TEXT;
coworker/tests/test_agent_studio_v36.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The Fusion AI Agent Studio workflows V3.6 (PATCH_TEST_START_CYCLE_V3_6, PATCH_TEST_CALLBACK_V3_6 and the relay) call
2
+ Patchwise with these exact bodies: checkTestData {test_data, package}; createCycle {test_data, data_approved_by, areas,
3
+ correlation_id, package}; approveCycle {decision, approved_by}. The callback workflow reads event, cycle_id,
4
+ correlation_id, scenarios[{id,title}], verdict, reason; the release watch reads items/changes with title, description,
5
+ release, area and an oracle.com link."""
6
+ from __future__ import annotations
7
+
8
+ import unittest
9
+
10
+ from coworker.platform.agent_studio import AgentStudio, Courier, validate_test_data
11
+ from coworker.tests.test_ai_scenarios import fusion_app
12
+
13
+ # the flat test_data of DERIVE_TEST_DATA: Fusion values, TEST_ identifiers made from Fusion's own numbers
14
+ TD = {
15
+ "AP": {"business_unit": "US1 Business Unit", "supplier": "Lee Supplies", "supplier_site": "Lee US1", "currency": "USD", "invoice_amount": "1250.00"},
16
+ "AR": {"business_unit": "US1 Business Unit", "customer": "Computer Service and Rentals", "currency": "USD", "invoice_amount": "500"},
17
+ "GL": {"ledger": "US Primary Ledger", "currency": "USD", "journal_source": "Manual", "journal_category": "Adjustment"},
18
+ "PO": {"procurement_bu": "US1 Business Unit", "supplier": "Lee Supplies", "supplier_site": "Lee US1", "item": "AS54888",
19
+ "currency": "USD", "quantity": "1", "unit_price": "25"},
20
+ "REQ": {"business_unit": "US1 Business Unit", "item": "AS54888", "quantity": "1"},
21
+ "OM": {"business_unit": "US1 Business Unit", "source_transaction_number": "TEST_300000047382915", "currency": "USD"},
22
+ "PJ": {"project_number": "TEST_1000123456", "project_name": "Test Project"},
23
+ "HCM": {"legal_employer": "US1 Legal Entity", "person_number": "TEST_955160008193"},
24
+ }
25
+ PACKAGE = {"schema_version": "1.0", "package_id": "pkg-PT34-20261114-1200", "run_ref": "PT34-20261114-1200",
26
+ "summary": {"ready": 8}, "modules": [{"code": "AP", "status": "ready", "test_identifiers": {"invoice_number": "TEST_INV_20261114_0001"},
27
+ "scenarios": [{"id": "standard_invoice", "status": "ready", "create_order": 40}]}],
28
+ "diagnostics": [], "approval": {"decision": "approved", "approved_by": "sai@example.test", "approved_at": "2026-11-14T12:00:00Z"}}
29
+
30
+
31
+ class TestAgentStudioV36(unittest.TestCase):
32
+ @classmethod
33
+ def setUpClass(cls):
34
+ cls.app, cls.c, cls.svc, cls.h, cls.pod_id = fusion_app()
35
+ r = cls.c.post("/api/agent-studio/clients", json={"name": "Fusion V3.6", "callback_url": "https://relay.example/patchwise/callback",
36
+ "release_watch_url": "https://relay.example/patchwise/release-watch"}, headers=cls.h["admin"])
37
+ assert r.status_code == 201, r.text
38
+ cls.client = r.json()
39
+ tok = cls.c.post("/oauth/token", data={"grant_type": "client_credentials", "client_id": cls.client["client_id"],
40
+ "client_secret": cls.client["client_secret"], "scope": "patchwise.invoke"}).json()["access_token"]
41
+ cls.auth = {"Authorization": f"Bearer {tok}"}
42
+
43
+ def test_a_test_identifiers_built_from_fusion_numbers_are_synthetic(self):
44
+ out = validate_test_data(TD)
45
+ self.assertEqual(out["OM"]["source_transaction_number"], ["TEST_300000047382915"])
46
+ self.assertEqual(out["HCM"]["person_number"], ["TEST_955160008193"])
47
+ r = self.c.post("/api/agent-studio/v1/test-data/check", json={"test_data": TD, "package": PACKAGE}, headers=self.auth)
48
+ self.assertEqual(r.status_code, 200, r.text)
49
+ self.assertTrue(r.json()["ok"], r.json())
50
+ # a real phone number is still refused, TEST_ or not
51
+ bad = self.c.post("/api/agent-studio/v1/test-data/check", json={"test_data": {"AP": {"supplier": "+1 415 555 0100"}}}, headers=self.auth).json()
52
+ self.assertEqual((bad["ok"], bad["code"]), (False, "NOT_SYNTHETIC"))
53
+
54
+ def test_b_every_v36_area_code_is_understood(self):
55
+ r = self.c.post("/api/agent-studio/v1/test-data/check", json={"test_data": TD}, headers=self.auth).json()
56
+ self.assertTrue(r["ok"], r)
57
+ # REQ joins PO, PJ is PPM; HCM is not a Patchwise Fusion area (said, not refused)
58
+ self.assertEqual(sorted(r["areas"]), ["AP", "AR", "GL", "HCM", "OM", "PO", "PPM"])
59
+ self.assertEqual(r["mapped"], {"REQ": "PO", "PJ": "PPM"})
60
+ self.assertEqual(r["not_testable"], ["HCM"])
61
+ self.assertEqual(r["areas"]["PO"], sorted(set(TD["PO"]) | set(TD["REQ"])))
62
+
63
+ def test_z_create_approve_and_the_callbacks_the_workflow_reads(self):
64
+ body = {"test_data": TD, "data_approved_by": "saiuttamdutt.veeravajhula@cesltd.com", "areas": sorted(TD),
65
+ "correlation_id": "PT34-20261114-1200", "package": PACKAGE}
66
+ r = self.c.post("/api/agent-studio/v1/cycles", json=body, headers=self.auth)
67
+ self.assertEqual(r.status_code, 202, r.text)
68
+ cyc = r.json()
69
+ self.assertTrue(cyc["cycle_id"])
70
+ self.assertEqual(cyc["package_id"], "pkg-PT34-20261114-1200") # the approved package is kept with the cycle
71
+ self.assertNotIn("REQ", cyc["areas"])
72
+ self.assertIn("PO", cyc["areas"])
73
+ self.assertIn("HCM", [x["area"] for x in cyc["skipped_areas"]]) # skipped and said, the rest still runs
74
+ pkg = self.c.get(f"/api/agent-studio/cycles/{cyc['cycle_id']}/package", headers=self.h["admin"]).json()
75
+ self.assertEqual(pkg["run_ref"], "PT34-20261114-1200")
76
+ self.app.state.runs.drain()
77
+ studio = AgentStudio(self.svc)
78
+ Courier(self.svc, self.app.state.runs, watch_hours=0).studio.watch_runs(self.app.state.runs)
79
+ ready = next(d for d in studio.deliveries() if d["event"] == "scripts_ready")["payload"]
80
+ self.assertEqual((ready["cycle_id"], ready["correlation_id"]), (cyc["cycle_id"], "PT34-20261114-1200"))
81
+ self.assertTrue(ready["scenarios"] and all(s.get("id") and s.get("title") for s in ready["scenarios"]))
82
+
83
+ # SCRIPTS_DECISION sends approved_by as a label: "<address with ' at '> (<run ref>)"
84
+ dec = {"decision": "approve", "approved_by": "saiuttamdutt.veeravajhula at cesltd.com (PT34-20261114-1200)"}
85
+ r = self.c.post(f"/api/agent-studio/v1/cycles/{cyc['cycle_id']}/approval", json=dec, headers=self.auth)
86
+ self.assertEqual(r.status_code, 200, r.text)
87
+ out = r.json()
88
+ self.assertEqual((out["cycle_id"], out["decision"]), (cyc["cycle_id"], "approve")) # the workflow's output spec
89
+ self.assertTrue(out["status"])
90
+ self.app.state.runs.drain()
91
+ Courier(self.svc, self.app.state.runs, watch_hours=0).studio.watch_runs(self.app.state.runs)
92
+ run = self.svc.db.get_run(cyc["run_id"])
93
+ if run["status"] == "completed":
94
+ res = next(d for d in studio.deliveries() if d["event"] == "results")["payload"]
95
+ self.assertIn(res["verdict"], ("Ready", "Not ready"))
96
+
97
+ def test_release_watch_items_carry_what_the_workflow_reads(self):
98
+ studio = AgentStudio(self.svc)
99
+ item = studio.release_item({"id": "C1", "title": "Invoice approval rule changes", "summary": "Approvers by amount",
100
+ "sources": [{"url": "https://docs.oracle.com/en/cloud/saas/readiness/26d/fin.html"}]}, "AP", "26D")
101
+ for k in ("title", "description", "release", "area", "source_url"):
102
+ self.assertTrue(item.get(k), k)
103
+
104
+
105
+ if __name__ == "__main__":
106
+ unittest.main()
docs/AGENT_STUDIO.md CHANGED
@@ -62,7 +62,9 @@ Send it as `Authorization: Bearer pwa_…` on every call below.
62
 
63
  ### Check test data (optional)
64
 
65
- `POST /test-data/check` with `{"test_data": {...}}` returns `{"ok": true, "areas": {...}}` or `{"ok": false, "code", "problem"}`.
 
 
66
 
67
  ### Start a cycle (after the person approves the data)
68
 
@@ -80,14 +82,16 @@ POST /cycles
80
 
81
  | Field | Notes |
82
  |---|---|
83
- | `test_data` | `{AREA: {key: value or [values]}}`. Area codes such as AP, PO, AR, GL. Keys are lower_snake_case. At most 20 areas, 40 keys each, values of 200 characters or less. These values are tried **first** by the browser runner, before the pod's own |
84
  | `data_approved_by` | required: who approved the data in Fusion |
85
- | `areas` | defaults to the test data's areas |
 
86
  | `environment` | the Patchwise test environment's name; defaults to the default Fusion pod |
87
  | `callback_url` | defaults to the client's callback address |
88
  | `correlation_id` | your workflow's id, echoed in every callback |
89
 
90
- The response is **202** with `{"cycle_id": "cyc_…", "run_id": "…", "status", "waiting_for", "links": {"run", "excel", "report"}}`.
 
91
 
92
  ### Where a cycle is
93
 
 
62
 
63
  ### Check test data (optional)
64
 
65
+ `POST /test-data/check` with `{"test_data": {...}}` returns `{"ok": true, "areas": {...}, "mapped": {...}, "not_testable": [...]}`
66
+ or `{"ok": false, "code", "problem"}`. `mapped` lists the Fusion workflow's own area codes Patchwise renamed (below);
67
+ `not_testable` lists areas Patchwise has no Fusion tests for (HCM, PAY, ABS, BEN, IRC today).
68
 
69
  ### Start a cycle (after the person approves the data)
70
 
 
82
 
83
  | Field | Notes |
84
  |---|---|
85
+ | `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 |
86
  | `data_approved_by` | required: who approved the data in Fusion |
87
+ | `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 |
88
+ | `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` |
89
  | `environment` | the Patchwise test environment's name; defaults to the default Fusion pod |
90
  | `callback_url` | defaults to the client's callback address |
91
  | `correlation_id` | your workflow's id, echoed in every callback |
92
 
93
+ The response is **202** with `{"cycle_id": "cyc_…", "run_id": "…", "areas", "skipped_areas", "package_id", "status", "waiting_for", "links": {"run", "excel", "report"}}`.
94
+ The approval answer has the same shape plus `decision`.
95
 
96
  ### Where a cycle is
97
 
web/src/api/openapi.json CHANGED
@@ -700,6 +700,19 @@
700
  ],
701
  "title": "Module Space"
702
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
703
  "release": {
704
  "anyOf": [
705
  {
@@ -4749,6 +4762,47 @@
4749
  ]
4750
  }
4751
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4752
  "/api/agent-studio/deliveries": {
4753
  "get": {
4754
  "operationId": "list_deliveries_api_agent_studio_deliveries_get",
 
700
  ],
701
  "title": "Module Space"
702
  },
703
+ "package": {
704
+ "anyOf": [
705
+ {
706
+ "additionalProperties": true,
707
+ "type": "object"
708
+ },
709
+ {
710
+ "type": "null"
711
+ }
712
+ ],
713
+ "description": "the approved test data package (V3.6 workflows): kept with the cycle",
714
+ "title": "Package"
715
+ },
716
  "release": {
717
  "anyOf": [
718
  {
 
4762
  ]
4763
  }
4764
  },
4765
+ "/api/agent-studio/cycles/{cycle_id}/package": {
4766
+ "get": {
4767
+ "description": "The test data package the Fusion side approved for this cycle.",
4768
+ "operationId": "cycle_package_api_agent_studio_cycles__cycle_id__package_get",
4769
+ "parameters": [
4770
+ {
4771
+ "in": "path",
4772
+ "name": "cycle_id",
4773
+ "required": true,
4774
+ "schema": {
4775
+ "title": "Cycle Id",
4776
+ "type": "string"
4777
+ }
4778
+ }
4779
+ ],
4780
+ "responses": {
4781
+ "200": {
4782
+ "content": {
4783
+ "application/json": {
4784
+ "schema": {}
4785
+ }
4786
+ },
4787
+ "description": "Successful Response"
4788
+ },
4789
+ "422": {
4790
+ "content": {
4791
+ "application/json": {
4792
+ "schema": {
4793
+ "$ref": "#/components/schemas/HTTPValidationError"
4794
+ }
4795
+ }
4796
+ },
4797
+ "description": "Validation Error"
4798
+ }
4799
+ },
4800
+ "summary": "Cycle Package",
4801
+ "tags": [
4802
+ "agent-studio"
4803
+ ]
4804
+ }
4805
+ },
4806
  "/api/agent-studio/deliveries": {
4807
  "get": {
4808
  "operationId": "list_deliveries_api_agent_studio_deliveries_get",
web/src/api/schema.d.ts CHANGED
@@ -125,6 +125,26 @@ export interface paths {
125
  patch?: never;
126
  trace?: never;
127
  };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  "/api/agent-studio/deliveries": {
129
  parameters: {
130
  query?: never;
@@ -2661,6 +2681,13 @@ export interface components {
2661
  module_space?: {
2662
  [key: string]: unknown;
2663
  } | null;
 
 
 
 
 
 
 
2664
  /**
2665
  * Release
2666
  * @description the quarterly update under test, e.g. 26B
@@ -4111,6 +4138,37 @@ export interface operations {
4111
  };
4112
  };
4113
  };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4114
  list_deliveries_api_agent_studio_deliveries_get: {
4115
  parameters: {
4116
  query?: never;
 
125
  patch?: never;
126
  trace?: never;
127
  };
128
+ "/api/agent-studio/cycles/{cycle_id}/package": {
129
+ parameters: {
130
+ query?: never;
131
+ header?: never;
132
+ path?: never;
133
+ cookie?: never;
134
+ };
135
+ /**
136
+ * Cycle Package
137
+ * @description The test data package the Fusion side approved for this cycle.
138
+ */
139
+ get: operations["cycle_package_api_agent_studio_cycles__cycle_id__package_get"];
140
+ put?: never;
141
+ post?: never;
142
+ delete?: never;
143
+ options?: never;
144
+ head?: never;
145
+ patch?: never;
146
+ trace?: never;
147
+ };
148
  "/api/agent-studio/deliveries": {
149
  parameters: {
150
  query?: never;
 
2681
  module_space?: {
2682
  [key: string]: unknown;
2683
  } | null;
2684
+ /**
2685
+ * Package
2686
+ * @description the approved test data package (V3.6 workflows): kept with the cycle
2687
+ */
2688
+ package?: {
2689
+ [key: string]: unknown;
2690
+ } | null;
2691
  /**
2692
  * Release
2693
  * @description the quarterly update under test, e.g. 26B
 
4138
  };
4139
  };
4140
  };
4141
+ cycle_package_api_agent_studio_cycles__cycle_id__package_get: {
4142
+ parameters: {
4143
+ query?: never;
4144
+ header?: never;
4145
+ path: {
4146
+ cycle_id: string;
4147
+ };
4148
+ cookie?: never;
4149
+ };
4150
+ requestBody?: never;
4151
+ responses: {
4152
+ /** @description Successful Response */
4153
+ 200: {
4154
+ headers: {
4155
+ [name: string]: unknown;
4156
+ };
4157
+ content: {
4158
+ "application/json": unknown;
4159
+ };
4160
+ };
4161
+ /** @description Validation Error */
4162
+ 422: {
4163
+ headers: {
4164
+ [name: string]: unknown;
4165
+ };
4166
+ content: {
4167
+ "application/json": components["schemas"]["HTTPValidationError"];
4168
+ };
4169
+ };
4170
+ };
4171
+ };
4172
  list_deliveries_api_agent_studio_deliveries_get: {
4173
  parameters: {
4174
  query?: never;