ASO Studio — API

Paste your app store listing, get an ASO specialist's audit.

API tokens Open the app

Audit app store listings from your own scripts

Send a mobile app's store listing — the Apple App Store fields (title, subtitle, promotional text, keyword field, description) or the Google Play ones (title, short description, description) — plus the keywords you want to rank for, and get back one structured JSON object: a strong / needs_work / weak posture, a field-by-field audit with character counts against the platform limits, prioritized findings across title, keywords, description, conversion and compliance, a primary / secondary / long-tail keyword plan with dropped targets explained, and a rewritten metadata package that fits every limit. The same audit the web form runs, callable from a release checklist, a localization pipeline, or a script that sweeps a whole portfolio of apps. One paste in, one audit out, no follow-up calls and no session state to carry.

StatusMeaning
401Missing or expired token — create a new session.
402Not enough credits — top up at skillsafe.ai/account/credits.
403The token isn't allowed to do this (e.g. a guest auditing a very large listing).
404Unknown job or record id.
5xxTransient platform error — retry with backoff.

Browsers enforce CORS for this API, so run these examples from a server, script or terminal — not from another website's frontend.

Step 0 — A tiny client

Every task below is a single HTTP call, so start with a short helper that adds the auth header, sends JSON and unwraps the data envelope. The later steps reuse it.

export API="https://api.skillsafe.ai/v1/app-api"
export TOKEN="YOUR_TOKEN"      # see step 1

# every call looks like:
#   curl -s "$API/..." -H "Authorization: Bearer $TOKEN" [-d '{json}']
# jq is used below to pull fields out of the {"data": ...} envelope
import json, requests

API = "https://api.skillsafe.ai/v1/app-api"
TOKEN = "YOUR_TOKEN"  # see step 1 — read it from your shell environment in real code

def api(method, path, body=None, **headers):
    res = requests.request(method, API + path, json=body,
                           headers={"Authorization": f"Bearer {TOKEN}", **headers})
    payload = res.json()
    if not res.ok:
        raise RuntimeError(payload.get("error", {}).get("message", res.reason))
    return payload["data"]
// Node 18+ (built-in fetch)
const API = "https://api.skillsafe.ai/v1/app-api";
const TOKEN = "YOUR_TOKEN"; // see step 1 — read it from your shell environment in real code

async function api(method, path, body, extraHeaders = {}) {
  const res = await fetch(API + path, {
    method,
    headers: { Authorization: `Bearer ${TOKEN}`, "Content-Type": "application/json", ...extraHeaders },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  const json = await res.json();
  if (!res.ok) throw new Error(json.error?.message ?? res.statusText);
  return json.data;
}
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

const API = "https://api.skillsafe.ai/v1/app-api"

var token = os.Getenv("SKILLSAFE_TOKEN") // see step 1

func call(method, path string, body, out any) error {
	var buf bytes.Buffer
	if body != nil {
		json.NewEncoder(&buf).Encode(body)
	}
	req, _ := http.NewRequest(method, API+path, &buf)
	req.Header.Set("Authorization", "Bearer "+token)
	req.Header.Set("Content-Type", "application/json")
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer res.Body.Close()
	var env struct {
		Data  json.RawMessage `json:"data"`
		Error *struct{ Message string `json:"message"` } `json:"error"`
	}
	json.NewDecoder(res.Body).Decode(&env)
	if res.StatusCode >= 400 {
		return fmt.Errorf("api %s %s: %s", method, path, env.Error.Message)
	}
	if out == nil {
		return nil
	}
	return json.Unmarshal(env.Data, out)
}
// Java 17+, no dependencies. Pair with your JSON library (Jackson, Gson…)
// to read fields out of the returned envelope.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class SkillSafe {
    static final String API = "https://api.skillsafe.ai/v1/app-api";
    static final String TOKEN = System.getenv("SKILLSAFE_TOKEN"); // see step 1
    static final HttpClient HTTP = HttpClient.newHttpClient();

    static String api(String method, String path, String jsonBody) throws Exception {
        var req = HttpRequest.newBuilder(URI.create(API + path))
            .header("Authorization", "Bearer " + TOKEN)
            .header("Content-Type", "application/json")
            .method(method, jsonBody == null
                ? HttpRequest.BodyPublishers.noBody()
                : HttpRequest.BodyPublishers.ofString(jsonBody))
            .build();
        var res = HTTP.send(req, HttpResponse.BodyHandlers.ofString());
        if (res.statusCode() >= 400) throw new RuntimeException(res.body());
        return res.body(); // envelope: {"data": …}
    }
}
require "net/http"
require "json"

API = "https://api.skillsafe.ai/v1/app-api"
TOKEN = ENV.fetch("SKILLSAFE_TOKEN") # see step 1

def api(method, path, body = nil)
  uri = URI(API + path)
  req = Net::HTTP.const_get(method.capitalize).new(uri)
  req["Authorization"] = "Bearer #{TOKEN}"
  req["Content-Type"] = "application/json"
  req.body = body.to_json if body
  res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |h| h.request(req) }
  payload = JSON.parse(res.body)
  raise (payload.dig("error", "message") || res.message) unless res.is_a?(Net::HTTPSuccess)
  payload["data"]
end
<?php
const API = "https://api.skillsafe.ai/v1/app-api";
$TOKEN = getenv("SKILLSAFE_TOKEN"); // see step 1

function api(string $method, string $path, ?array $body = null): mixed {
    global $TOKEN;
    $ch = curl_init(API . $path);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST  => $method,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => [
            "Authorization: Bearer $TOKEN",
            "Content-Type: application/json",
        ],
        CURLOPT_POSTFIELDS     => $body === null ? null : json_encode($body),
    ]);
    $payload = json_decode(curl_exec($ch), true);
    $status  = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    curl_close($ch);
    if ($status >= 400) {
        throw new Exception($payload["error"]["message"] ?? "HTTP $status");
    }
    return $payload["data"];
}
// .NET 8+
using System.Net.Http.Json;
using System.Text.Json;

static class SkillSafe
{
    const string Api = "https://api.skillsafe.ai/v1/app-api";
    static readonly HttpClient Http = new();

    static SkillSafe() =>
        Http.DefaultRequestHeaders.Authorization =
            new("Bearer", Environment.GetEnvironmentVariable("SKILLSAFE_TOKEN")); // see step 1

    public static async Task<JsonElement> ApiAsync(HttpMethod method, string path, object? body = null)
    {
        var req = new HttpRequestMessage(method, Api + path);
        if (body != null) req.Content = JsonContent.Create(body);
        var res = await Http.SendAsync(req);
        var json = await res.Content.ReadFromJsonAsync<JsonElement>();
        if (!res.IsSuccessStatusCode)
            throw new Exception(json.GetProperty("error").GetProperty("message").GetString());
        return json.GetProperty("data");
    }
}

Step 1 — Get a token

POST /guest

A guest token lets you check balances and estimate costs for free. For metered audit runs billed to your own account, use your personal token: open the token page, sign in with SkillSafe, and press Copy shell export — it puts export SKILLSAFE_TOKEN="…" on your clipboard, which every example below reads. Treat the token like a password: it can spend your credits. For fully headless scripts, POST /guest mints a guest token with no browser involved.

curl -s -X POST "$API/guest" \
  -H "Content-Type: application/json" \
  -d '{"slug":"aso-studio"}' | jq -r '.data.token'
token = api("POST", "/guest", {"slug": "aso-studio"})["token"]
const { token } = await api("POST", "/guest", { slug: "aso-studio" });
var guest struct{ Token string `json:"token"` }
err := call("POST", "/guest", map[string]string{"slug": "aso-studio"}, &guest)
String envelope = api("POST", "/guest", """
    {"slug":"aso-studio"}""");
// token is at data.token in the returned JSON
token = api("POST", "/guest", { slug: "aso-studio" })["token"]
$token = api("POST", "/guest", ["slug" => "aso-studio"])["token"];
var guest = await SkillSafe.ApiAsync(HttpMethod.Post, "/guest",
    new { slug = "aso-studio" });
var token = guest.GetProperty("token").GetString();

The app stores this browser's token under the localStorage key skillsafe_app_token:aso-studio, on the app's own origin. The token page reads and manages it for you — you never need to open developer tools.

Step 2 — Check who you are and your balance

GET /me

Returns subject_type ("user" or "guest"), subject_id and your credits balance. Check this before auditing a long description or a batch of listings.

curl -s "$API/me" -H "Authorization: Bearer $TOKEN" | jq '.data'
me = api("GET", "/me")
print(me["subject_type"], me["credits"])
const me = await api("GET", "/me");
console.log(me.subject_type, me.credits);
var me struct {
	SubjectType string `json:"subject_type"`
	Credits     int64  `json:"credits"`
}
err := call("GET", "/me", nil, &me)
String envelope = api("GET", "/me", null);
// data.subject_type, data.credits
me = api("GET", "/me")
puts "#{me["subject_type"]}: #{me["credits"]} credits"
$me = api("GET", "/me");
echo "{$me['subject_type']}: {$me['credits']} credits\n";
var me = await SkillSafe.ApiAsync(HttpMethod.Get, "/me");
Console.WriteLine($"{me.GetProperty("subject_type")}: {me.GetProperty("credits")} credits");

Step 3 — Estimate the cost

POST /estimate

Send exactly the input you would send to /run; the response's hold_credits is the worst-case cost. Nothing is charged and no job is created, so estimating is free — useful when you are sweeping a portfolio of listings and want a ceiling before spending credits.

Input fieldTypeNotes
platformstring, requiredapple | google — which store's rules apply. It decides both the character limits enforced and which fields exist: Apple gets subtitle, promotional_text and keyword_field; Google gets short_description and has no keyword field at all.
app_namestringThe app's name, e.g. PantryPal. Used to name the audit and to keep the brand where you want it in the rewritten title.
categorystringThe store category, e.g. Food & Drink or Productivity — it sets what browsing competition the keyword plan assumes.
audiencestringWho the app is for, in a sentence. The rewritten copy is aimed at this reader.
featuresstringKey features and unique value, free text. This is the ground truth for every claim in the rewrite — nothing that isn't here, in description, or in context may be invented into the new copy. Clipped middle-out if very long, with a # [... clipped ...] marker showing where.
titlestringThe current store title (both platforms, 30-char limit).
subtitlestring, apple onlyThe current Apple subtitle (30 chars).
promotional_textstring, apple onlyThe current Apple promotional text (170 chars) — the field you can change without shipping a build.
keyword_fieldstring, apple onlyThe current Apple 100-character keyword field: comma-separated, no spaces after commas, no duplicates or plural duplicates, and never words already in the title or subtitle — those are indexed already.
short_descriptionstring, google onlyThe current Google Play short description (80 chars).
descriptionstringThe current full description (4000 chars on both stores). Paragraph breaks are plain \n\n. Clipped middle-out if very long.
target_keywordsstringComma-separated keywords you want to rank for, e.g. grocery list, pantry tracker, food waste, meal planner. The keyword plan splits these into primary, secondary and long-tail, and drops the ones it judges irrelevant or unwinnable — each with a reason.
contextstring, optionalAnything else that constrains the rewrite: named competitors, the market and language, the pricing model, hard requirements ("the brand name must stay first in the title"), review quotes or metrics you want cited. Clipped if very long.
prescan_factsobject, optionalWhat a client-side scan mechanically recognized: {"items": [], "flags": []}. Each entry is {id, label}. Item ids look like field:title (a character count against the limit) and kw:targets; flag ids are <check>:<name>limit:title-over, limit:subtitle-underused, limit:description-missing, kwfield:spaces, kwfield:dups, kwfield:wasted, kw:uncovered, kw:title-frontload, desc:fold, desc:caps. Every flag id you send comes back in coverage_check. The web UI fills this from its own free prescan; API callers may omit the field or send the two empty arrays.
retry_notestring, optionalOnly set by the app's automatic reformat retry when a first reply was not valid JSON. Leave it out.
cat > input.json <<'JSON'
{
  "platform": "apple",
  "app_name": "PantryPal",
  "category": "Food & Drink",
  "audience": "Home cooks who meal-plan weekly and hate wasting groceries",
  "features": "Scans grocery receipts into a pantry inventory. Expiry reminders before food goes bad. Recipes ranked by what is already in the pantry. Shared household lists. Works offline.",
  "title": "PantryPal - Grocery List, Pantry & Meal Planner App",
  "subtitle": "Grocery list & meal planner",
  "promotional_text": "",
  "keyword_field": "grocery, grocery list, groceries, pantry, meal planner, recipes, food, shopping list, list",
  "description": "PantryPal was founded in 2023 by two engineers who kept throwing away spinach.\n\nFEATURES: receipt scanning, expiry tracking, recipe matching, shared lists, offline mode.\n\nDownload PantryPal today, the BEST pantry app on the App Store!",
  "target_keywords": "grocery list, pantry tracker, food waste, meal planner",
  "context": "Competing with AnyList and Paprika. The brand name must stay first in the title.",
  "prescan_facts": {"items": [], "flags": []}
}
JSON

curl -s -X POST "$API/estimate" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d @input.json | jq '.data.hold_credits'
payload = {
    "platform": "apple",
    "app_name": "PantryPal",
    "category": "Food & Drink",
    "audience": "Home cooks who meal-plan weekly and hate wasting groceries",
    "features": "Scans grocery receipts into a pantry inventory. Expiry reminders "
                "before food goes bad. Recipes ranked by what is already in the "
                "pantry. Shared household lists. Works offline.",
    "title": "PantryPal - Grocery List, Pantry & Meal Planner App",
    "subtitle": "Grocery list & meal planner",
    "promotional_text": "",
    "keyword_field": "grocery, grocery list, groceries, pantry, meal planner, "
                     "recipes, food, shopping list, list",
    "description": "PantryPal was founded in 2023 by two engineers who kept throwing "
                   "away spinach.\n\nFEATURES: receipt scanning, expiry tracking, "
                   "recipe matching, shared lists, offline mode.\n\nDownload PantryPal "
                   "today, the BEST pantry app on the App Store!",
    "target_keywords": "grocery list, pantry tracker, food waste, meal planner",
    "context": "Competing with AnyList and Paprika. The brand name must stay first in the title.",
    "prescan_facts": {"items": [], "flags": []},
}

est = api("POST", "/estimate", payload)
print("worst case:", est.get("hold_credits", est.get("credits")), "credits")
const payload = {
  platform: "apple",
  app_name: "PantryPal",
  category: "Food & Drink",
  audience: "Home cooks who meal-plan weekly and hate wasting groceries",
  features:
    "Scans grocery receipts into a pantry inventory. Expiry reminders before food " +
    "goes bad. Recipes ranked by what is already in the pantry. Shared household " +
    "lists. Works offline.",
  title: "PantryPal - Grocery List, Pantry & Meal Planner App",
  subtitle: "Grocery list & meal planner",
  promotional_text: "",
  keyword_field:
    "grocery, grocery list, groceries, pantry, meal planner, recipes, food, shopping list, list",
  description:
    "PantryPal was founded in 2023 by two engineers who kept throwing away spinach.\n\n" +
    "FEATURES: receipt scanning, expiry tracking, recipe matching, shared lists, offline mode.\n\n" +
    "Download PantryPal today, the BEST pantry app on the App Store!",
  target_keywords: "grocery list, pantry tracker, food waste, meal planner",
  context: "Competing with AnyList and Paprika. The brand name must stay first in the title.",
  prescan_facts: { items: [], flags: [] },
};

const est = await api("POST", "/estimate", payload);
console.log("worst case:", est.hold_credits ?? est.credits, "credits");
payload := map[string]any{
	"platform": "apple",
	"app_name": "PantryPal",
	"category": "Food & Drink",
	"audience": "Home cooks who meal-plan weekly and hate wasting groceries",
	"features": "Scans grocery receipts into a pantry inventory. Expiry reminders " +
		"before food goes bad. Recipes ranked by what is already in the pantry. " +
		"Shared household lists. Works offline.",
	"title":            "PantryPal - Grocery List, Pantry & Meal Planner App",
	"subtitle":         "Grocery list & meal planner",
	"promotional_text": "",
	"keyword_field":    "grocery, grocery list, groceries, pantry, meal planner, recipes, food, shopping list, list",
	"description": "PantryPal was founded in 2023 by two engineers who kept throwing away spinach.\n\n" +
		"FEATURES: receipt scanning, expiry tracking, recipe matching, shared lists, offline mode.\n\n" +
		"Download PantryPal today, the BEST pantry app on the App Store!",
	"target_keywords": "grocery list, pantry tracker, food waste, meal planner",
	"context":         "Competing with AnyList and Paprika. The brand name must stay first in the title.",
	"prescan_facts": map[string]any{
		"items": []any{}, "flags": []any{},
	},
}

var est struct{ HoldCredits int64 `json:"hold_credits"` }
err := call("POST", "/estimate", payload, &est)
// A text block keeps the JSON readable; \\n\\n stays a JSON escape, not a real newline.
String jsonPayload = """
    {"platform": "apple",
     "app_name": "PantryPal",
     "category": "Food & Drink",
     "audience": "Home cooks who meal-plan weekly and hate wasting groceries",
     "features": "Scans grocery receipts into a pantry inventory. Expiry reminders before food goes bad. Recipes ranked by what is already in the pantry. Shared household lists. Works offline.",
     "title": "PantryPal - Grocery List, Pantry & Meal Planner App",
     "subtitle": "Grocery list & meal planner",
     "promotional_text": "",
     "keyword_field": "grocery, grocery list, groceries, pantry, meal planner, recipes, food, shopping list, list",
     "description": "PantryPal was founded in 2023 by two engineers who kept throwing away spinach.\\n\\nFEATURES: receipt scanning, expiry tracking, recipe matching, shared lists, offline mode.\\n\\nDownload PantryPal today, the BEST pantry app on the App Store!",
     "target_keywords": "grocery list, pantry tracker, food waste, meal planner",
     "context": "Competing with AnyList and Paprika. The brand name must stay first in the title.",
     "prescan_facts": {"items": [], "flags": []}}
    """;

String envelope = api("POST", "/estimate", jsonPayload);
// worst-case cost is at data.hold_credits
payload = {
  platform: "apple",
  app_name: "PantryPal",
  category: "Food & Drink",
  audience: "Home cooks who meal-plan weekly and hate wasting groceries",
  features: "Scans grocery receipts into a pantry inventory. Expiry reminders before " \
            "food goes bad. Recipes ranked by what is already in the pantry. Shared " \
            "household lists. Works offline.",
  title: "PantryPal - Grocery List, Pantry & Meal Planner App",
  subtitle: "Grocery list & meal planner",
  promotional_text: "",
  keyword_field: "grocery, grocery list, groceries, pantry, meal planner, recipes, food, shopping list, list",
  description: "PantryPal was founded in 2023 by two engineers who kept throwing away spinach.\n\n" \
               "FEATURES: receipt scanning, expiry tracking, recipe matching, shared lists, offline mode.\n\n" \
               "Download PantryPal today, the BEST pantry app on the App Store!",
  target_keywords: "grocery list, pantry tracker, food waste, meal planner",
  context: "Competing with AnyList and Paprika. The brand name must stay first in the title.",
  prescan_facts: { items: [], flags: [] }
}

est = api("POST", "/estimate", payload)
puts "worst case: #{est["hold_credits"] || est["credits"]} credits"
$payload = [
    "platform"         => "apple",
    "app_name"         => "PantryPal",
    "category"         => "Food & Drink",
    "audience"         => "Home cooks who meal-plan weekly and hate wasting groceries",
    "features"         => "Scans grocery receipts into a pantry inventory. Expiry reminders "
                        . "before food goes bad. Recipes ranked by what is already in the "
                        . "pantry. Shared household lists. Works offline.",
    "title"            => "PantryPal - Grocery List, Pantry & Meal Planner App",
    "subtitle"         => "Grocery list & meal planner",
    "promotional_text" => "",
    "keyword_field"    => "grocery, grocery list, groceries, pantry, meal planner, recipes, food, shopping list, list",
    "description"      => "PantryPal was founded in 2023 by two engineers who kept throwing away spinach.\n\n"
                        . "FEATURES: receipt scanning, expiry tracking, recipe matching, shared lists, offline mode.\n\n"
                        . "Download PantryPal today, the BEST pantry app on the App Store!",
    "target_keywords"  => "grocery list, pantry tracker, food waste, meal planner",
    "context"          => "Competing with AnyList and Paprika. The brand name must stay first in the title.",
    "prescan_facts"    => ["items" => [], "flags" => []],
];

$est = api("POST", "/estimate", $payload);
echo "worst case: " . ($est["hold_credits"] ?? $est["credits"]) . " credits\n";
var payload = new {
    platform = "apple",
    app_name = "PantryPal",
    category = "Food & Drink",
    audience = "Home cooks who meal-plan weekly and hate wasting groceries",
    features = "Scans grocery receipts into a pantry inventory. Expiry reminders before " +
               "food goes bad. Recipes ranked by what is already in the pantry. Shared " +
               "household lists. Works offline.",
    title = "PantryPal - Grocery List, Pantry & Meal Planner App",
    subtitle = "Grocery list & meal planner",
    promotional_text = "",
    keyword_field = "grocery, grocery list, groceries, pantry, meal planner, recipes, food, shopping list, list",
    description = "PantryPal was founded in 2023 by two engineers who kept throwing away spinach.\n\n" +
                  "FEATURES: receipt scanning, expiry tracking, recipe matching, shared lists, offline mode.\n\n" +
                  "Download PantryPal today, the BEST pantry app on the App Store!",
    target_keywords = "grocery list, pantry tracker, food waste, meal planner",
    context = "Competing with AnyList and Paprika. The brand name must stay first in the title.",
    prescan_facts = new {
        items = Array.Empty<object>(), flags = Array.Empty<object>(),
    },
};

var est = await SkillSafe.ApiAsync(HttpMethod.Post, "/estimate", payload);
Console.WriteLine($"worst case: {est.GetProperty("hold_credits")} credits");

prescan_facts.flags is how you make the audit answer for things you already know about. Send {"items": [{"id": "field:title", "label": "Title 51 / 30"}], "flags": [{"id": "limit:title-over", "label": "Title is 21 chars over the 30-char limit"}, {"id": "kwfield:wasted", "label": "Keyword-field terms already indexed via title: grocery, pantry"}]} and every flag id comes back in coverage_check — addressed by a finding, or set aside with the reason. Nothing you flag is silently dropped, which makes it the field to assert on in a pipeline check.

Step 4 — Run the audit and wait for the result

POST /run
GET /jobs/{job_id}

/run takes the same input as /estimate, places a credit hold and returns a job_id. Poll /jobs/{job_id} every 1–2 seconds until status is succeeded or failed (a run typically takes 30–90 s, since the reply carries a fully rewritten description as well as the audit). Always send an Idempotency-Key header so a network retry can't start a second, double-charged run. The audit is in output — usually nested as output.output, and as a JSON string, so parse defensively. The samples below print the posture, the field audit, the prioritized findings, the keyword plan and the rewritten title, then save the whole object to audit.json.

JOB_ID=$(curl -s -X POST "$API/run" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -H "Idempotency-Key: as-$(date +%s)" \
  -d @input.json | jq -r '.data.job_id')

while :; do
  JOB=$(curl -s "$API/jobs/$JOB_ID" -H "Authorization: Bearer $TOKEN")
  STATUS=$(echo "$JOB" | jq -r '.data.status')
  [ "$STATUS" = "succeeded" ] || [ "$STATUS" = "failed" ] && break
  sleep 2
done

# unwrap the audit once, then read it
echo "$JOB" | jq -r '.data.output.output' > audit.json

jq -r '
  "\(.review_name) [\(.posture)]: \(.verdict)",
  "",
  "FIELD AUDIT",
  (.field_audit[] | "  \(.field) \(.chars) [\(.status)] - \(.reading)"),
  "",
  "FINDINGS",
  (.findings[] | "  [\(.priority)] \(.id) \(.category) \(.resource): \(.problem)"),
  "",
  "KEYWORD PLAN",
  "  primary:    \(.keyword_plan.primary | join(", "))",
  "  secondary:  \(.keyword_plan.secondary | join(", "))",
  "  long tail:  \(.keyword_plan.long_tail | join(", "))",
  (.keyword_plan.dropped[] | "  dropped \(.keyword) - \(.reason)"),
  "",
  "REWRITE",
  (.optimized_metadata | to_entries[] | "  \(.key): \(.value)"),
  "",
  "QUICK WINS",
  (.quick_wins[] | "  - \(.)"),
  "",
  "FOCUS AREAS",
  (.focus_areas[] | "  \(.area) - \(.why)"),
  "",
  "COVERAGE",
  (.coverage_check[] | "  \(.id): \(if .addressed then "ok" else "SET ASIDE" end) - \(.note)")' \
  audit.json

# fail the pipeline on anything critical
jq -e '[.findings[] | select(.priority == "critical")] | length == 0' audit.json > /dev/null \
  || { echo "critical findings present"; exit 1; }

# and on a rewritten Apple title that would not fit
jq -e '(.optimized_metadata.title | length) <= 30' audit.json > /dev/null \
  || { echo "rewritten title is over 30 chars"; exit 1; }
import time

job_id = api("POST", "/run", payload,
             **{"Idempotency-Key": "as-001"})["job_id"]

while True:
    job = api("GET", f"/jobs/{job_id}")
    if job["status"] in ("succeeded", "failed"):
        break
    time.sleep(1.5)

if job["status"] == "failed":
    raise RuntimeError(job.get("error", "run failed"))

raw = job["output"]
if isinstance(raw, dict) and "output" in raw:
    raw = raw["output"]
audit = json.loads(raw) if isinstance(raw, str) else raw

print(f'{audit["review_name"]} [{audit["posture"]}]: {audit["verdict"]}')
for r in audit["field_audit"]:
    print(f'  {r["field"]:<18} {r["chars"]:<12} {r["status"]:<10} {r["reading"]}')
for f in audit["findings"]:
    print(f'  [{f["priority"]:>8}] {f["id"]} {f["category"]} {f["resource"]}')
    print(f'      L:{f["likelihood"]}/S:{f["severity"]} {f["problem"]}')
    print(f'      fix: {f["fix"]}')
    if f["snippet"]:
        print("      snippet:", f["snippet"].splitlines()[0], "...")
kp = audit["keyword_plan"]
print("  primary:", ", ".join(kp["primary"]))
print("  secondary:", ", ".join(kp["secondary"]))
print("  long tail:", ", ".join(kp["long_tail"]))
for d in kp["dropped"]:
    print(f'  dropped {d["keyword"]} - {d["reason"]}')
for field, value in audit["optimized_metadata"].items():
    print(f'  new {field} ({len(value)} chars): {value[:60]}')
for w in audit["quick_wins"]:
    print("  win:", w)
for a in audit["focus_areas"]:
    print(f'  focus {a["area"]} {a["finding_ids"]} - {a["why"]}')
for c in audit["coverage_check"]:
    print(f'  {c["id"]}: {"ok" if c["addressed"] else "SET ASIDE"} - {c["note"]}')

with open("audit.json", "w", encoding="utf-8") as fh:
    json.dump(audit, fh, indent=2)

critical = [f for f in audit["findings"] if f["priority"] == "critical"]
if critical:
    raise SystemExit(f"{len(critical)} critical finding(s)")
import { writeFileSync } from "node:fs";

const { job_id } = await api("POST", "/run", payload,
  { "Idempotency-Key": crypto.randomUUID() });

let job;
do {
  await new Promise((r) => setTimeout(r, 1500));
  job = await api("GET", `/jobs/${job_id}`);
} while (job.status !== "succeeded" && job.status !== "failed");

if (job.status === "failed") throw new Error(job.error ?? "run failed");

const raw = job.output?.output ?? job.output;
const audit = typeof raw === "string" ? JSON.parse(raw) : raw;

console.log(`${audit.review_name} [${audit.posture}]: ${audit.verdict}`);
for (const r of audit.field_audit) {
  console.log(`  ${r.field} ${r.chars} [${r.status}]: ${r.reading}`);
}
for (const f of audit.findings) {
  console.log(`  [${f.priority}] ${f.id} ${f.category} ${f.resource}`);
  console.log(`      L:${f.likelihood}/S:${f.severity} - ${f.fix}`);
}
const kp = audit.keyword_plan;
console.log(`  primary: ${kp.primary.join(", ")}`);
console.log(`  secondary: ${kp.secondary.join(", ")}`);
console.log(`  long tail: ${kp.long_tail.join(", ")}`);
for (const d of kp.dropped) console.log(`  dropped ${d.keyword} - ${d.reason}`);
for (const [field, value] of Object.entries(audit.optimized_metadata)) {
  console.log(`  new ${field} (${value.length} chars): ${value.slice(0, 60)}`);
}
for (const w of audit.quick_wins) console.log(`  win: ${w}`);
for (const a of audit.focus_areas) {
  console.log(`  focus ${a.area} (${a.finding_ids.join(", ")}): ${a.why}`);
}
for (const c of audit.coverage_check) {
  console.log(`  ${c.id}: ${c.addressed ? "ok" : "SET ASIDE"} - ${c.note}`);
}

writeFileSync("audit.json", JSON.stringify(audit, null, 2));

const critical = audit.findings.filter((f) => f.priority === "critical");
if (critical.length) process.exitCode = 1;
var started struct{ JobID string `json:"job_id"` }
if err := call("POST", "/run", payload, &started); err != nil {
	log.Fatal(err)
}

var job struct {
	Status string          `json:"status"`
	Error  string          `json:"error"`
	Output json.RawMessage `json:"output"`
}
for {
	if err := call("GET", "/jobs/"+started.JobID, nil, &job); err != nil {
		log.Fatal(err)
	}
	if job.Status == "succeeded" || job.Status == "failed" {
		break
	}
	time.Sleep(1500 * time.Millisecond)
}

// job.Output is {"output": "<json string>"} — unwrap, then unmarshal:
type Audit struct {
	ReviewName    string   `json:"review_name"`
	Posture       string   `json:"posture"`
	Verdict       string   `json:"verdict"`
	ExecSummary   string   `json:"exec_summary"`
	Assumptions   []string `json:"assumptions"`
	OpenQuestions []string `json:"open_questions"`
	FieldAudit []struct {
		Field, Chars, Status, Reading string
	} `json:"field_audit"`
	Findings []struct {
		ID, Category, Severity, Likelihood, Priority string
		Resource, Problem, Impact, Fix, Snippet      string
	} `json:"findings"`
	OptimizedMetadata map[string]string `json:"optimized_metadata"`
	KeywordPlan struct {
		Primary   []string `json:"primary"`
		Secondary []string `json:"secondary"`
		LongTail  []string `json:"long_tail"`
		Dropped   []struct {
			Keyword, Reason string
		} `json:"dropped"`
	} `json:"keyword_plan"`
	CoverageCheck []struct {
		ID, Note  string
		Addressed bool
	} `json:"coverage_check"`
	QuickWins  []string `json:"quick_wins"`
	FocusAreas []struct {
		Area, Why  string
		FindingIDs []string `json:"finding_ids"`
	} `json:"focus_areas"`
	Summary string `json:"summary"`
}
var wrapper struct{ Output string `json:"output"` }
json.Unmarshal(job.Output, &wrapper)
var audit Audit
json.Unmarshal([]byte(wrapper.Output), &audit)

fmt.Printf("%s [%s]: %s\n", audit.ReviewName, audit.Posture, audit.Verdict)
for _, r := range audit.FieldAudit {
	fmt.Printf("  %s %s [%s]: %s\n", r.Field, r.Chars, r.Status, r.Reading)
}
for _, f := range audit.Findings {
	fmt.Printf("  [%s] %s %s %s: %s\n", f.Priority, f.ID, f.Category, f.Resource, f.Problem)
}
fmt.Println("  primary:", strings.Join(audit.KeywordPlan.Primary, ", "))
for field, value := range audit.OptimizedMetadata {
	fmt.Printf("  new %s (%d chars)\n", field, len(value))
}
for _, a := range audit.FocusAreas {
	fmt.Printf("  focus %s %v: %s\n", a.Area, a.FindingIDs, a.Why)
}
os.WriteFile("audit.json", []byte(wrapper.Output), 0o644)
String envelope = api("POST", "/run", jsonPayload);
String jobId = /* data.job_id via your JSON library */;

while (true) {
    String job = api("GET", "/jobs/" + jobId, null);
    String status = /* data.status */;
    if (status.equals("succeeded") || status.equals("failed")) break;
    Thread.sleep(1500);
}
// The audit is at data.output.output as a JSON string — parse it again, then read
// review_name, posture, verdict, exec_summary, assumptions[], open_questions[],
// field_audit[] (field/chars/status/reading),
// findings[] (id/category/severity/likelihood/priority/resource/problem/impact/fix/snippet),
// optimized_metadata (title, subtitle, promotional_text, keyword_field,
//   short_description, description — only the fields that exist on the platform),
// keyword_plan (primary[], secondary[], long_tail[], dropped[{keyword, reason}]),
// coverage_check[] (id/addressed/note), quick_wins[],
// focus_areas[] (area/why/finding_ids[]) and summary.
// Finally keep the audit on disk:
//   Files.writeString(Path.of("audit.json"), auditJson);
started = api("POST", "/run", payload)

job = nil
loop do
  job = api("GET", "/jobs/#{started["job_id"]}")
  break if %w[succeeded failed].include?(job["status"])
  sleep 1.5
end
raise (job["error"] || "run failed") if job["status"] == "failed"

raw = job["output"].is_a?(Hash) ? job["output"].fetch("output", job["output"]) : job["output"]
audit = raw.is_a?(String) ? JSON.parse(raw) : raw

puts "#{audit["review_name"]} [#{audit["posture"]}]: #{audit["verdict"]}"
audit["field_audit"].each { |r| puts "  #{r["field"]} #{r["chars"]} [#{r["status"]}]: #{r["reading"]}" }
audit["findings"].each do |f|
  puts "  [#{f["priority"]}] #{f["id"]} #{f["category"]} #{f["resource"]}"
  puts "      L:#{f["likelihood"]}/S:#{f["severity"]} - #{f["fix"]}"
end
kp = audit["keyword_plan"]
puts "  primary: #{kp["primary"].join(", ")}"
puts "  secondary: #{kp["secondary"].join(", ")}"
kp["dropped"].each { |d| puts "  dropped #{d["keyword"]} - #{d["reason"]}" }
audit["optimized_metadata"].each { |field, value| puts "  new #{field} (#{value.length} chars)" }
audit["quick_wins"].each { |w| puts "  win: #{w}" }
audit["focus_areas"].each { |a| puts "  focus #{a["area"]} #{a["finding_ids"].join(", ")}" }
audit["coverage_check"].each { |c| puts "  #{c["id"]}: #{c["addressed"] ? "ok" : "SET ASIDE"}" }

File.write("audit.json", JSON.pretty_generate(audit))
exit 1 if audit["findings"].any? { |f| f["priority"] == "critical" }
$started = api("POST", "/run", $payload);

do {
    sleep(2);
    $job = api("GET", "/jobs/" . $started["job_id"]);
} while (!in_array($job["status"], ["succeeded", "failed"]));

if ($job["status"] === "failed") {
    throw new Exception($job["error"] ?? "run failed");
}

$raw = is_array($job["output"]) ? ($job["output"]["output"] ?? $job["output"]) : $job["output"];
$audit = is_string($raw) ? json_decode($raw, true) : $raw;

echo "{$audit['review_name']} [{$audit['posture']}]: {$audit['verdict']}\n";
foreach ($audit["field_audit"] as $r) {
    echo "  {$r['field']} {$r['chars']} [{$r['status']}]: {$r['reading']}\n";
}
foreach ($audit["findings"] as $f) {
    echo "  [{$f['priority']}] {$f['id']} {$f['category']} {$f['resource']}\n";
    echo "      L:{$f['likelihood']}/S:{$f['severity']} - {$f['fix']}\n";
}
$kp = $audit["keyword_plan"];
echo "  primary: " . implode(", ", $kp["primary"]) . "\n";
foreach ($kp["dropped"] as $d) {
    echo "  dropped {$d['keyword']} - {$d['reason']}\n";
}
foreach ($audit["optimized_metadata"] as $field => $value) {
    echo "  new $field (" . mb_strlen($value) . " chars)\n";
}
foreach ($audit["quick_wins"] as $w) {
    echo "  win: $w\n";
}
foreach ($audit["focus_areas"] as $a) {
    echo "  focus {$a['area']}: " . implode(", ", $a["finding_ids"]) . "\n";
}
foreach ($audit["coverage_check"] as $c) {
    echo "  {$c['id']}: " . ($c["addressed"] ? "ok" : "SET ASIDE") . "\n";
}

file_put_contents("audit.json", json_encode($audit, JSON_PRETTY_PRINT));
var started = await SkillSafe.ApiAsync(HttpMethod.Post, "/run", payload);
var jobId = started.GetProperty("job_id").GetString();

JsonElement job;
while (true)
{
    job = await SkillSafe.ApiAsync(HttpMethod.Get, $"/jobs/{jobId}");
    var status = job.GetProperty("status").GetString();
    if (status is "succeeded" or "failed") break;
    await Task.Delay(1500);
}

var rawText = job.GetProperty("output").GetProperty("output").GetString();
using var doc = JsonDocument.Parse(rawText!);
var audit = doc.RootElement;

Console.WriteLine($"{audit.GetProperty("review_name")} " +
                  $"[{audit.GetProperty("posture")}]: {audit.GetProperty("verdict")}");
foreach (var r in audit.GetProperty("field_audit").EnumerateArray())
{
    Console.WriteLine($"  {r.GetProperty("field")} {r.GetProperty("chars")} " +
                      $"[{r.GetProperty("status")}]: {r.GetProperty("reading")}");
}
foreach (var f in audit.GetProperty("findings").EnumerateArray())
{
    Console.WriteLine($"  [{f.GetProperty("priority")}] {f.GetProperty("id")} " +
                      $"{f.GetProperty("category")} {f.GetProperty("resource")} " +
                      $"(L:{f.GetProperty("likelihood")}/S:{f.GetProperty("severity")})");
}
foreach (var field in audit.GetProperty("optimized_metadata").EnumerateObject())
{
    Console.WriteLine($"  new {field.Name} ({field.Value.GetString()!.Length} chars)");
}
foreach (var a in audit.GetProperty("focus_areas").EnumerateArray())
{
    Console.WriteLine($"  focus {a.GetProperty("area")}: {a.GetProperty("why")}");
}

await File.WriteAllTextAsync("audit.json", rawText!);

The model is asked for one JSON object and nothing else, but a stray code fence or preamble is always possible. Strip a leading ```json fence, take the text between the first { and the last }, and only then parse — that is what the app does before it falls back to a retry_note reformat run.

The audit object — output schema

One JSON object, always the same shape. Every array is present, and the audit is grounded in the listing you pasted alone: every claim in the rewritten copy traces back to features, description or context, and download numbers, ratings, rankings and competitor metrics are never invented — market claims you did not supply arrive as entries in assumptions instead. Fields you did not send are reported as gaps rather than filled in silently. Expect four to twelve findings on a typical listing — a genuinely well-optimized listing may honestly yield two or three, and findings is never empty.

FieldTypeMeaning
review_namestringA short title naming the app and the store — e.g. PantryPal — Apple listing audit. Falls back to Untitled listing audit.
posturestringstrong | needs_work | weak. See the table below.
verdictstringOne sentence naming the single most important change.
exec_summarystringTwo or three paragraphs, separated by blank lines: what the listing does well, what is broken, and what the rewrite changes.
assumptionsstring[]Assumptions made about the app, the market or the competition. Read these first — a wrong assumption invalidates the advice built on it.
open_questionsstring[]Facts that would change the advice if known.
field_auditarray{field, chars, status, reading} — one row per field you actually provided. field is the field name (title, subtitle, keyword_field, …); chars is the count against the limit as a short string ("27 / 30"); status is ok | over | underused | missing; reading is one sentence on that field as pasted.
findingsarrayThe prioritized findings table — ids AS-001, AS-002, … in sequence, at least one entry. Columns are listed below.
optimized_metadataobjectThe rewritten package. title is always present; the rest appear only when they exist on the chosen platform and were written: subtitle, promotional_text, keyword_field (Apple), short_description (Google), and description on both, with \n\n paragraph breaks. Empty fields are dropped rather than returned blank. Every value is meant to fit its platform limit — the app re-counts each one client-side, and so should you.
keyword_planobject{primary, secondary, long_tail, dropped}. The first three are string arrays, tiered by how much of the indexed real estate a term deserves; dropped is {keyword, reason} for targets judged irrelevant or unwinnable — every drop carries its reason.
coverage_checkarray{id, addressed, note} — one entry per prescan_facts.flags id you sent, each appearing exactly once. See the semantics below.
quick_winsstring[]Changes that can go live without submitting a new app version. On the Apple App Store that is the promotional text only — title, subtitle, keyword field and description are version-gated. On Google Play all store-listing text qualifies, subject to the usual listing review. May be empty. The web UI states the platform rule deterministically above this list rather than relying on the model to get it right.
focus_areasarray{area, why, finding_ids} — what to fix first, one sentence tied to the audit, and the finding ids that motivate it. Every id in finding_ids exists in findings.
summarystringClosing paragraph: the posture in plain language, and the one metric to watch after shipping the rewrite.

The three posture values:

postureWhat it means
strongThe listing is well optimized as pasted: every field inside its limit, the highest-value keyword front-loaded, a description that sells above the fold. Findings still exist, but they are polish and the keyword plan, not repairs. A genuinely good listing lands here rather than having severity manufactured for it.
needs_workA solid core with real gaps: a subtitle wasting half its characters, target keywords that appear in no searchable field, a description that buries the pitch under company history, an Apple keyword field spending characters on words the title already indexes.
weakFundamental problems: a field blown past its hard limit (so the store would truncate or reject it), the target keywords essentially absent, a description that does not sell, or copy that leans on claims stores reject ("#1", "best").

Each entry in findings:

ColumnMeaning
idSequential AS-001, AS-002, … — the stable handle referenced from focus_areas[].finding_ids.
categorytitle | keywords | description | conversion | compliance | localization | data. data is for gaps in what you sent; compliance for copy a store review would push back on.
severitylow | medium | high — how much it costs when it bites.
likelihoodlow | medium | high — how likely it is to bite.
prioritycritical | high | medium | low — severity by likelihood. critical is reserved for things the store itself would act on or that cost ranking outright (a field over its hard limit, target keywords indexed nowhere, a rejectable superlative), so sort on this field and work top-down. This is also the field to gate a pipeline on.
resourceThe field or keyword this is about — e.g. title, keyword_field, or "pantry tracker" — always something grounded in what you sent.
problemWhat is wrong, with the exact text quoted and the character count where it helps.
impactWhat it costs in ranking or conversion terms.
fixThe specific change to make.
snippetExact before/after text, shown verbatim. Empty string when quoting would add nothing.

coverage_check semantics:

CaseWhat you get
Every flag id you sentEach prescan_facts.flags id appears in coverage_check exactly once. Nothing you flagged is silently dropped, which makes this the field to assert on in a pipeline check. Ids in prescan_facts.items are not reconciled here — they ground the character counts in field_audit instead.
addressed: trueThe flag is covered by the audit; note says how it was confirmed and fixed in the rewrite.
addressed: falseThe flag was deliberately set aside; note gives the reason — a lint that fired but is not a real problem for this listing (a short subtitle that is deliberate branding, a "duplicate" that is a distinct localized term).
Nothing sentOmit prescan_facts, or send the two empty arrays, and coverage_check comes back empty. The rest of the audit is unaffected.

A small, realistic result for the cluttered PantryPal listing above, trimmed for length:

{
  "review_name": "PantryPal — Apple listing audit",
  "posture": "weak",
  "verdict": "The title is 21 characters over Apple's 30-char limit, so it is truncated in
              search results before any keyword work matters.",
  "exec_summary": "The app itself is clearly described and the feature set is strong.

                   The listing is not. The title blows the 30-char limit, the keyword field
                   spends characters on spaces, plural duplicates and words the title already
                   indexes, and the description opens with founding history instead of the
                   benefit. Two of four target keywords appear in no searchable field.

                   The rewrite front-loads 'Grocery List' behind the brand, moves the pantry
                   and waste terms into the keyword field, and leads the description with the
                   saved-groceries benefit.",
  "assumptions": [
    "English (US) storefront only; no localized listings were supplied.",
    "No ratings or download figures were provided, so no social proof is claimed in the rewrite."
  ],
  "open_questions": [
    "Which of the four target keywords currently drives installs?",
    "Is 'PantryPal' already ranking on brand searches, or is the name itself the growth constraint?"
  ],
  "field_audit": [
    { "field": "title", "chars": "51 / 30", "status": "over",
      "reading": "Truncated by the store; everything after 'Grocery List' is invisible in search." },
    { "field": "subtitle", "chars": "27 / 30", "status": "ok",
      "reading": "Fits, but duplicates title terms instead of adding new indexed words." },
    { "field": "keyword_field", "chars": "92 / 100", "status": "underused",
      "reading": "Roughly a third is wasted on spaces, plurals and words the title indexes already." },
    { "field": "description", "chars": "233 / 4000", "status": "underused",
      "reading": "Opens with company history; the benefit never appears above the fold." }
  ],
  "findings": [
    { "id": "AS-001", "category": "title",
      "severity": "high", "likelihood": "high", "priority": "critical",
      "resource": "title",
      "problem": "\"PantryPal - Grocery List, Pantry & Meal Planner App\" is 51 chars against a 30-char limit.",
      "impact": "The store truncates it, so 'Pantry & Meal Planner App' is never seen and the
                 characters spent on it return nothing.",
      "fix": "Cut to the brand plus the single highest-value phrase, and move the rest into the
              subtitle and keyword field.",
      "snippet": "before: PantryPal - Grocery List, Pantry & Meal Planner App (51)\nafter:  PantryPal: Grocery List (23)" },
    { "id": "AS-002", "category": "keywords",
      "severity": "high", "likelihood": "high", "priority": "high",
      "resource": "keyword_field",
      "problem": "Spaces after every comma, 'grocery'/'groceries' as a plural duplicate, and
                  'grocery', 'pantry' and 'meal planner' repeated from the title and subtitle.",
      "impact": "About 30 of 100 indexed characters buy nothing, crowding out 'pantry tracker'
                 and 'food waste', which appear in no field at all.",
      "fix": "Drop the spaces and every term already in the title or subtitle; spend the freed
              characters on the uncovered targets.",
      "snippet": "after: pantrytracker,foodwaste,expiry,inventory,receipt,scanner,leftovers,fridge" }
  ],
  "optimized_metadata": {
    "title": "PantryPal: Grocery List",
    "subtitle": "Pantry tracker & meal plans",
    "promotional_text": "New: scan a receipt and your pantry fills itself — then cook from what you already have.",
    "keyword_field": "pantrytracker,foodwaste,expiry,inventory,receipt,scanner,leftovers,fridge,shopping",
    "description": "Stop throwing away food you forgot you bought.\n\nScan your grocery receipt
                    and PantryPal builds your pantry for you, reminds you before anything expires,
                    and suggests recipes from what is already on the shelf.\n\nShared household
                    lists sync instantly. Works offline, no account needed.\n\nStart your first
                    pantry scan today."
  },
  "keyword_plan": {
    "primary": ["grocery list", "pantry tracker"],
    "secondary": ["meal planner", "food waste", "expiry tracker"],
    "long_tail": ["receipt scanner grocery", "cook with what I have", "fridge inventory app"],
    "dropped": [
      { "keyword": "food", "reason": "Single generic word; dominated by delivery apps and it
                                      cannibalizes characters better spent on 'food waste'." },
      { "keyword": "list", "reason": "Already indexed via the title's 'Grocery List'." }
    ]
  },
  "coverage_check": [
    { "id": "limit:title-over", "addressed": true, "note": "AS-001; new title is 23 / 30." },
    { "id": "kwfield:spaces", "addressed": true, "note": "AS-002; spaces removed in the rewrite." },
    { "id": "kwfield:wasted", "addressed": true, "note": "AS-002; title/subtitle terms dropped." },
    { "id": "desc:caps", "addressed": false, "note": "Set aside — the ALL-CAPS 'FEATURES' header is
                                                      replaced wholesale by the rewritten description." }
  ],
  "quick_wins": [
    "Ship the new keyword field and promotional text now — neither needs an app update.",
    "Replace the description; the first two lines are what most users ever read."
  ],
  "focus_areas": [
    { "area": "Title real estate",
      "why": "A truncated title is the one problem that makes every other optimization invisible.",
      "finding_ids": ["AS-001"] },
    { "area": "Keyword-field efficiency",
      "why": "The two uncovered target keywords fit easily once the wasted characters are freed.",
      "finding_ids": ["AS-002"] }
  ],
  "summary": "Weak as pasted, and cheaply fixable: the limits and the keyword field are mechanical
              problems with mechanical answers. Ship the rewrite, then watch impression-to-install
              conversion on the storefront for two weeks — that is where a front-loaded title and a
              benefit-led description show up first."
}

This is AI-generated listing optimization of the metadata as pasted, not a guarantee of store approval or ranking outcomes: it sees only what you sent, never the store's live search results, your competitors' real data or your install funnel. Check assumptions and open_questions, re-count every rewritten field against its limit before you submit, and keep a human in the loop.

Step 5 — Stream the audit as it is written

POST /run-stream

/run-stream takes exactly the same body as /run but answers with server-sent events, so you can show progress instead of a spinner — useful here because a full rewritten description makes for a long reply. This app's own progress panel is this endpoint. Events are separated by a blank line; each has an event: line and a data: line carrying JSON.

EventPayloadMeaning
job{job_id, status}Sent once, when the job is accepted — show "starting".
delta{text}A chunk of the reply, in order. Append it; the accumulated length is your only progress signal (the total is not known in advance). The app advances its step list by watching for the "review_name", "field_audit", "findings", "optimized_metadata", "keyword_plan" and "coverage_check" keys as they arrive.
done{job_id, status, charged_credits, output}The final, authoritative result — read the audit from output.output rather than trusting concatenated deltas, and the settled price from charged_credits.
error{code, message}Replaces done when the run fails.
# -N disables buffering so events print as they arrive
curl -N -s -X POST "$API/run-stream" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -H "Idempotency-Key: as-$(date +%s)" \
  -d @input.json

# event: job
# data: {"job_id":"job_...","status":"running"}
#
# event: delta
# data: {"text":"{\"review_name\":\"PantryPal — Apple"}
# ...
# event: done
# data: {"job_id":"job_...","status":"succeeded","charged_credits":588,"output":{"output":"{...}"}}
import json, requests

result = None
with requests.post(
    API + "/run-stream",
    headers={"Authorization": f"Bearer {TOKEN}",
             "Idempotency-Key": "as-001"},
    json=payload,
    stream=True,
) as r:
    r.raise_for_status()
    event = None
    for line in r.iter_lines(decode_unicode=True):
        if not line:
            continue
        if line.startswith("event:"):
            event = line[len("event:"):].strip()
        elif line.startswith("data:"):
            data = json.loads(line[len("data:"):].strip())
            if event == "delta":
                print(".", end="", flush=True)          # live progress
            elif event == "done":
                result = data
            elif event == "error":
                raise RuntimeError(data.get("message", "run failed"))

audit = json.loads(result["output"]["output"])            # authoritative
print("charged:", result["charged_credits"], "-", audit["review_name"])
print("posture:", audit["posture"])
for f in audit["findings"]:
    print(f'  [{f["priority"]}] {f["id"]} {f["resource"]}: {f["problem"]}')
print("new title:", audit["optimized_metadata"]["title"])
with open("audit.json", "w", encoding="utf-8") as fh:
    json.dump(audit, fh, indent=2)
const res = await fetch(API + "/run-stream", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${TOKEN}`,
    "Content-Type": "application/json",
    "Idempotency-Key": crypto.randomUUID(),
  },
  body: JSON.stringify(payload),
});

const reader = res.body.getReader();
const decoder = new TextDecoder();
let buf = "", done = null;

for (;;) {
  const chunk = await reader.read();
  if (chunk.done) break;
  buf += decoder.decode(chunk.value, { stream: true });
  const frames = buf.split("\n\n");
  buf = frames.pop();
  for (const frame of frames) {
    const name = /^event:\s*(.+)$/m.exec(frame)?.[1];
    const body = /^data:\s*(.+)$/m.exec(frame)?.[1];
    if (!name || !body) continue;
    const data = JSON.parse(body);
    if (name === "delta") process.stdout.write(".");   // live progress
    if (name === "done") done = data;
    if (name === "error") throw new Error(data.message ?? "run failed");
  }
}

const audit = JSON.parse(done.output.output);
console.log(`\n${done.charged_credits} credits - ${audit.review_name} [${audit.posture}]`);
for (const f of audit.findings) console.log(`  [${f.priority}] ${f.id} ${f.resource}`);
console.log("new title:", audit.optimized_metadata.title);
writeFileSync("audit.json", JSON.stringify(audit, null, 2));
body, _ := json.Marshal(payload)
req, _ := http.NewRequest("POST", API+"/run-stream", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", "as-001")

res, err := http.DefaultClient.Do(req)
if err != nil {
	log.Fatal(err)
}
defer res.Body.Close()

var event string
var final map[string]any
sc := bufio.NewScanner(res.Body)
sc.Buffer(make([]byte, 0, 64*1024), 4*1024*1024)
for sc.Scan() {
	line := sc.Text()
	switch {
	case strings.HasPrefix(line, "event:"):
		event = strings.TrimSpace(strings.TrimPrefix(line, "event:"))
	case strings.HasPrefix(line, "data:"):
		var data map[string]any
		json.Unmarshal([]byte(strings.TrimPrefix(line, "data:")), &data)
		switch event {
		case "delta":
			fmt.Print(".") // live progress
		case "done":
			final = data
		case "error":
			log.Fatal(data["message"])
		}
	}
}
// final["output"].(map[string]any)["output"].(string) is the audit JSON —
// unmarshal it into the Audit struct from step 4, then write it to audit.json.
// Java 17+ — read the stream line by line instead of buffering the body.
var req = HttpRequest.newBuilder(URI.create(API + "/run-stream"))
    .header("Authorization", "Bearer " + TOKEN)
    .header("Content-Type", "application/json")
    .header("Idempotency-Key", "as-001")
    .POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
    .build();

var res = HTTP.send(req, HttpResponse.BodyHandlers.ofLines());
String event = null, done = null;
for (String line : (Iterable<String>) res.body()::iterator) {
    if (line.startsWith("event:")) {
        event = line.substring(6).trim();
    } else if (line.startsWith("data:")) {
        String data = line.substring(5).trim();
        if ("delta".equals(event)) System.out.print(".");   // live progress
        else if ("done".equals(event)) done = data;
        else if ("error".equals(event)) throw new RuntimeException(data);
    }
}
// parse `done`, then parse data.output.output again — it is a JSON string holding
// review_name, posture, verdict, field_audit[], findings[], optimized_metadata,
// keyword_plan, coverage_check[], quick_wins[], focus_areas[] and the rest.
require "net/http"
require "json"

uri = URI(API + "/run-stream")
req = Net::HTTP::Post.new(uri)
req["Authorization"] = "Bearer #{TOKEN}"
req["Content-Type"] = "application/json"
req["Idempotency-Key"] = "as-001"
req.body = payload.to_json

event = nil
done = nil
Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
  http.request(req) do |res|
    res.read_body do |chunk|
      chunk.each_line do |line|
        line = line.strip
        if line.start_with?("event:")
          event = line.delete_prefix("event:").strip
        elsif line.start_with?("data:")
          data = JSON.parse(line.delete_prefix("data:").strip)
          case event
          when "delta" then print "."           # live progress
          when "done"  then done = data
          when "error" then raise (data["message"] || "run failed")
          end
        end
      end
    end
  end
end

audit = JSON.parse(done["output"]["output"])
puts "\n#{done["charged_credits"]} credits - #{audit["review_name"]} [#{audit["posture"]}]"
audit["findings"].each { |f| puts "  [#{f["priority"]}] #{f["id"]} #{f["resource"]}" }
puts "new title: #{audit["optimized_metadata"]["title"]}"
File.write("audit.json", JSON.pretty_generate(audit))
$event = null;
$done  = null;

$ch = curl_init(API . "/run-stream");
curl_setopt_array($ch, [
    CURLOPT_POST       => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer $TOKEN",
        "Content-Type: application/json",
        "Idempotency-Key: as-001",
    ],
    CURLOPT_POSTFIELDS => json_encode($payload),
    CURLOPT_WRITEFUNCTION => function ($ch, $chunk) use (&$event, &$done) {
        foreach (explode("\n", $chunk) as $line) {
            $line = trim($line);
            if (str_starts_with($line, "event:")) {
                $event = trim(substr($line, 6));
            } elseif (str_starts_with($line, "data:")) {
                $data = json_decode(trim(substr($line, 5)), true);
                if ($event === "delta") { echo "."; }        // live progress
                elseif ($event === "done") { $done = $data; }
                elseif ($event === "error") { throw new Exception($data["message"] ?? "run failed"); }
            }
        }
        return strlen($chunk);
    },
]);
curl_exec($ch);
curl_close($ch);

$audit = json_decode($done["output"]["output"], true);
echo "\n{$done['charged_credits']} credits - {$audit['review_name']} [{$audit['posture']}]\n";
foreach ($audit["findings"] as $f) {
    echo "  [{$f['priority']}] {$f['id']} {$f['resource']}\n";
}
echo "new title: {$audit['optimized_metadata']['title']}\n";
file_put_contents("audit.json", json_encode($audit, JSON_PRETTY_PRINT));
var req = new HttpRequestMessage(HttpMethod.Post, Api + "/run-stream") {
    Content = JsonContent.Create(payload),
};
req.Headers.Add("Idempotency-Key", "as-001");

using var res = await Http.SendAsync(req, HttpCompletionOption.ResponseHeadersRead);
using var reader = new StreamReader(await res.Content.ReadAsStreamAsync());

string? evt = null, done = null;
while (await reader.ReadLineAsync() is { } line)
{
    if (line.StartsWith("event:")) evt = line[6..].Trim();
    else if (line.StartsWith("data:"))
    {
        var data = line[5..].Trim();
        if (evt == "delta") Console.Write(".");            // live progress
        else if (evt == "done") done = data;
        else if (evt == "error") throw new Exception(data);
    }
}

using var final = JsonDocument.Parse(done!);
var text = final.RootElement.GetProperty("output").GetProperty("output").GetString();
using var auditDoc = JsonDocument.Parse(text!);
var audit = auditDoc.RootElement;
Console.WriteLine($"{audit.GetProperty("review_name")} [{audit.GetProperty("posture")}]");
foreach (var f in audit.GetProperty("findings").EnumerateArray())
    Console.WriteLine($"  [{f.GetProperty("priority")}] {f.GetProperty("id")} {f.GetProperty("resource")}");
await File.WriteAllTextAsync("audit.json", text!);

In a browser, the native EventSource only speaks GET, and this endpoint is a POST — read the fetch response body incrementally, as the JavaScript sample above does. On an idempotent replay the server may answer with a plain JSON envelope instead of an event stream; check the Content-Type before you start parsing frames.