Leak Lens — API

Paste the code, get a leak audit and a corrected rewrite.

API tokens Open the app

Audit your TypeScript for leaks from your own scripts

Send TypeScript or JavaScript — a class, a widget, a controller, a service, a test file, or several files at once — and get back one JSON object: an honest clean / patch / leaking verdict, the six-step disposable walk, findings ranked by severity each carrying corrected code, a twelve-item checklist scored against the paste, and a complete corrected rewrite of what you sent. Everything this app does goes through the SkillSafe App API — plain JSON over HTTPS — so you can wire the audit into a CI gate, a pull-request bot, or a pre-merge check that refuses a class calling this._register() inside a method that runs on every keystroke. Every code step below is shown in cURL, Python, JavaScript, Go, Java, Ruby, PHP and C#; pick a language once and the whole page follows.

Basics

Base URL: https://api.skillsafe.ai/v1/app-api, app slug leak-lens. Every request sends Authorization: Bearer <token> and JSON bodies with Content-Type: application/json. Responses are wrapped in an envelope: {"data": …} on success, {"error": {"code", "message"}} on failure. The audit itself is produced by the gpt-terra model. Estimates are free; runs are metered against your credit balance. There is a single run task — 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 paste).
404Unknown job or record id.
429Too many requests — back off and retry; the semantic search over saved audits is the usual trigger.
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 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. The examples call the api() helper built in step 2.

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

export TOKEN=$(curl -s -X POST "$API/guest" \
  -H "Content-Type: application/json" \
  -d '{"slug":"leak-lens"}' | jq -r '.data.token')

# or paste your personal token from https://leak-lens.skillsafe.ai/tokens.html:
#   export SKILLSAFE_TOKEN="..." ; export TOKEN="$SKILLSAFE_TOKEN"
token = api("POST", "/guest", {"slug": "leak-lens"})["token"]   # helper: step 2
const { token } = await api("POST", "/guest", { slug: "leak-lens" }); // helper: step 2
var guest struct{ Token string `json:"token"` }
err := call("POST", "/guest", map[string]string{"slug": "leak-lens"}, &guest) // helper: step 2
String envelope = api("POST", "/guest", """
    {"slug":"leak-lens"}""");            // helper: step 2
// token is at data.token in the returned JSON
token = api("POST", "/guest", { slug: "leak-lens" })["token"]   # helper: step 2
$token = api("POST", "/guest", ["slug" => "leak-lens"])["token"];   // helper: step 2
var guest = await SkillSafe.ApiAsync(HttpMethod.Post, "/guest",
    new { slug = "leak-lens" });          // helper: step 2
var token = guest.GetProperty("token").GetString();

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

Step 2 — 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. No app-slug header is needed once you hold a token: the token is already scoped to leak-lens, and the slug only appears in the /guest body.

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";
var 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 3 — Check who you are and your balance

GET /me

Returns subject_type ("user" or "guest"), subject_id and your credits balance. Credits are integers: 10,000 credits is one US dollar, which is how the app renders its price meter. Check this before auditing a large paste — a guest subject has no balance of its own, so a metered run under a guest token only works while the app is sponsored (see sponsor_enabled in step 4).

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 4 — 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 feeding in a whole directory of widgets and want a ceiling before spending credits.

Input fieldTypeNotes
codestring, requiredThe TypeScript or JavaScript to audit: a class, a widget, a controller, a service, a test file, or several files concatenated with file-name comment headers. Very long pastes may be clipped middle-out, with a [... clipped ...] marker showing exactly where — the audit never comments on code it cannot see. The web UI caps the paste at 100,000 characters and the notes at 20,000.
runtimestringvscode | electron | browser | node | unknown — which idiom set applies, and therefore what the fixes are written in. vscode assumes the reference helpers (addDisposableListener, Event.once, DisposableStore, MutableDisposable, this._register()); electron adds IPC teardown and webContents lifetime; browser gets platform-native corrections only (removeEventListener, { signal } from an AbortController, observer.disconnect(), { once: true }); node gets emitter.off, unsubscribe(), stream.destroy(), unref(). On unknown the runtime is inferred from the paste and the assumption is stated in overview.
notesstring, optionalExtra context: what the component does, which methods run repeatedly, how long this object lives relative to the model it listens to, what a parent outside the paste already disposes.
prescan_factsobject, optionalWhat a client-side pattern scan mechanically detected in the code: {"leaks": [], "lifecycles": [], "signals": []}. Each entry is {id, label} — matched leak anti-patterns (raw-add-event-listener, on-property-handler, global-target-listener, register-outside-constructor, interval-not-cleared, observer-not-disconnected, test-suite-without-leak-guard, …), disposable declarations found (lifecycle-class-iconwidget, lifecycle-slot-_searchListener) and counted lifetime signals (signal-register, signal-add-event-listener, signal-set-interval, signal-mutable-disposable, …). Every 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 three empty arrays.
retry_notestring, optionalOnly set by the app's automatic reformat retry when a first reply was not valid JSON. Leave it out.

The estimate response, field by field:

FieldMeaning
modelThe model that will actually run the audit — gpt-terra for this app.
model_aliasThe alias the app declared, which is what a future model swap changes; pin your logging to this rather than to model.
markup_bpsThe app's markup over raw model cost, in basis points (100 bps = 1%).
hold_creditsThe reservation, not the price: the worst case the platform puts on hold while the job runs. What you actually pay comes back as charged_credits when the job settles, and it is normally well below the hold because the hold assumes a maximum-length reply.
min_creditsThe smallest balance that may start a run at all. A balance between min_credits and hold_credits can still run, but the reply may be cut short — the job then comes back with truncated set.
sponsor_enabledtrue when the app is currently sponsoring runs, so a guest token can audit without a balance. The web UI reads exactly this field to decide whether to show "free to try" or ask you to sign in.
cat > icon_widget.ts <<'TS'
export class IconWidget extends Disposable {
  private readonly el = document.createElement('img');

  constructor(private readonly model: IModel) {
    super();
    this.el.onload = () => this.layout();
    window.addEventListener('resize', () => this.layout());
    setInterval(() => this.poll(), 1000);
  }

  startSearch(): void {
    this._register(this.model.onResults(() => this.render()));
  }
}
TS

jq -n --rawfile c icon_widget.ts \
  '{code: $c, runtime: "vscode", notes: "startSearch() runs on every keystroke.",
    prescan_facts: {leaks: [], lifecycles: [], signals: []}}' > input.json

curl -s -X POST "$API/estimate" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d @input.json | jq '.data | {model, hold_credits, min_credits, sponsor_enabled}'
CODE = """export class IconWidget extends Disposable {
  private readonly el = document.createElement('img');

  constructor(private readonly model: IModel) {
    super();
    this.el.onload = () => this.layout();
    window.addEventListener('resize', () => this.layout());
    setInterval(() => this.poll(), 1000);
  }

  startSearch(): void {
    this._register(this.model.onResults(() => this.render()));
  }
}"""

payload = {
    "code": CODE,
    "runtime": "vscode",
    "notes": "startSearch() runs on every keystroke.",
    "prescan_facts": {"leaks": [], "lifecycles": [], "signals": []},
}

est = api("POST", "/estimate", payload)
print("model:", est["model"], "/", est["model_alias"])
print("worst case:", est["hold_credits"], "credits; minimum:", est["min_credits"])
print("sponsored:", est["sponsor_enabled"])
const code = `export class IconWidget extends Disposable {
  private readonly el = document.createElement('img');

  constructor(private readonly model: IModel) {
    super();
    this.el.onload = () => this.layout();
    window.addEventListener('resize', () => this.layout());
    setInterval(() => this.poll(), 1000);
  }

  startSearch(): void {
    this._register(this.model.onResults(() => this.render()));
  }
}`;

const payload = {
  code,
  runtime: "vscode",
  notes: "startSearch() runs on every keystroke.",
  prescan_facts: { leaks: [], lifecycles: [], signals: [] },
};

const est = await api("POST", "/estimate", payload);
console.log(`${est.model} (${est.model_alias}) markup ${est.markup_bps} bps`);
console.log("worst case:", est.hold_credits, "credits; minimum:", est.min_credits);
const code = `export class IconWidget extends Disposable {
  private readonly el = document.createElement('img');

  constructor(private readonly model: IModel) {
    super();
    this.el.onload = () => this.layout();
    window.addEventListener('resize', () => this.layout());
    setInterval(() => this.poll(), 1000);
  }

  startSearch(): void {
    this._register(this.model.onResults(() => this.render()));
  }
}`

payload := map[string]any{
	"code":    code,
	"runtime": "vscode",
	"notes":   "startSearch() runs on every keystroke.",
	"prescan_facts": map[string]any{
		"leaks": []any{}, "lifecycles": []any{}, "signals": []any{},
	},
}

var est struct {
	Model       string `json:"model"`
	ModelAlias  string `json:"model_alias"`
	MarkupBps   int64  `json:"markup_bps"`
	HoldCredits int64  `json:"hold_credits"`
	MinCredits  int64  `json:"min_credits"`
	Sponsored   bool   `json:"sponsor_enabled"`
}
err := call("POST", "/estimate", payload, &est)
String code = """
    export class IconWidget extends Disposable {
      private readonly el = document.createElement('img');

      constructor(private readonly model: IModel) {
        super();
        this.el.onload = () => this.layout();
        window.addEventListener('resize', () => this.layout());
        setInterval(() => this.poll(), 1000);
      }

      startSearch(): void {
        this._register(this.model.onResults(() => this.render()));
      }
    }""";

String jsonPayload = """
    {"code": %s, "runtime": "vscode",
     "notes": "startSearch() runs on every keystroke.",
     "prescan_facts": {"leaks": [], "lifecycles": [], "signals": []}}
    """.formatted(toJsonString(code));

String envelope = api("POST", "/estimate", jsonPayload);
// data.model, data.model_alias, data.markup_bps,
// data.hold_credits (the reservation), data.min_credits, data.sponsor_enabled
CODE_TEXT = <<~'TS'
  export class IconWidget extends Disposable {
    private readonly el = document.createElement('img');

    constructor(private readonly model: IModel) {
      super();
      this.el.onload = () => this.layout();
      window.addEventListener('resize', () => this.layout());
      setInterval(() => this.poll(), 1000);
    }

    startSearch(): void {
      this._register(this.model.onResults(() => this.render()));
    }
  }
TS

payload = { code: CODE_TEXT, runtime: "vscode",
            notes: "startSearch() runs on every keystroke.",
            prescan_facts: { leaks: [], lifecycles: [], signals: [] } }

est = api("POST", "/estimate", payload)
puts "#{est["model"]} (#{est["model_alias"]}) markup #{est["markup_bps"]} bps"
puts "worst case: #{est["hold_credits"]} credits; minimum: #{est["min_credits"]}"
$code = <<<'TS'
export class IconWidget extends Disposable {
  private readonly el = document.createElement('img');

  constructor(private readonly model: IModel) {
    super();
    this.el.onload = () => this.layout();
    window.addEventListener('resize', () => this.layout());
    setInterval(() => this.poll(), 1000);
  }

  startSearch(): void {
    this._register(this.model.onResults(() => this.render()));
  }
}
TS;

$payload = [
    "code"          => $code,
    "runtime"       => "vscode",
    "notes"         => "startSearch() runs on every keystroke.",
    "prescan_facts" => ["leaks" => [], "lifecycles" => [], "signals" => []],
];

$est = api("POST", "/estimate", $payload);
echo "{$est['model']} ({$est['model_alias']})\n";
echo "worst case: {$est['hold_credits']} credits; minimum: {$est['min_credits']}\n";
var code = """
    export class IconWidget extends Disposable {
      private readonly el = document.createElement('img');

      constructor(private readonly model: IModel) {
        super();
        this.el.onload = () => this.layout();
        window.addEventListener('resize', () => this.layout());
        setInterval(() => this.poll(), 1000);
      }

      startSearch(): void {
        this._register(this.model.onResults(() => this.render()));
      }
    }
    """;

var payload = new {
    code,
    runtime = "vscode",
    notes = "startSearch() runs on every keystroke.",
    prescan_facts = new {
        leaks = Array.Empty<object>(), lifecycles = Array.Empty<object>(),
        signals = Array.Empty<object>(),
    },
};

var est = await SkillSafe.ApiAsync(HttpMethod.Post, "/estimate", payload);
Console.WriteLine($"{est.GetProperty("model")}: hold {est.GetProperty("hold_credits")}, " +
                  $"min {est.GetProperty("min_credits")}");

prescan_facts is how you make the audit answer for things you already know about. Send {"leaks": [{"id": "raw-add-event-listener", "label": "raw addEventListener"}], "lifecycles": [{"id": "lifecycle-class-iconwidget", "label": "IconWidget extends Disposable"}], "signals": [{"id": "signal-set-interval", "label": "setInterval x1"}]} and every one of those ids comes back in coverage_check — addressed, or explained away as a false positive (a listener on an element that is itself thrown away with its DOM node, an interval cleared in a file you did not paste). Nothing you flag is silently dropped.

Step 5 — 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 corrected rewrite is written out in full). The job also carries charged_credits once it settles, and truncated: true when the reply was cut short by the available balance.

Always send an Idempotency-Key header. A run is metered, and a socket that dies after the server accepted the job is indistinguishable, from your side, from one that never arrived — so a naive retry buys the same audit twice. A retry that reuses the key is answered with the original job instead of starting a second one, which is why the key must be derived from the input rather than from the attempt: this app hashes code, runtime and notes (FNV-1a, then hash:length) into leak-lens:<hash>:a<attempt>, and only bumps the attempt counter when it deliberately wants a fresh run — its one automatic reformat retry. Generate a fresh key when the input changes; reuse it byte-for-byte when you are retrying the same request.

# derive the key from the input, so a retry of this exact audit reuses it
KEY="leak-lens:$(shasum -a 256 input.json | cut -c1-16):a1"

JOB_ID=$(curl -s -X POST "$API/run" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -H "Idempotency-Key: $KEY" \
  -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 '
  "\(.audit_name) [\(.verdict_level)]: \(.verdict)",
  "",
  "STEPS",
  (.steps[] | "  [\(.status)] \(.step) - \(.note)"),
  "",
  "FINDINGS",
  (.findings[] | "  (\(.severity)) \(.category): \(.title)"),
  "",
  "CHECKLIST",
  (.checklist[] | "  [\(.status)] \(.item) - \(.note)")' audit.json

# and drop the corrected code straight into the repo
jq -r '.rewrite.code' audit.json > "$(jq -r '.rewrite.filename' audit.json)"   # audited.ts
import time

job_id = api("POST", "/run", payload,
             **{"Idempotency-Key": "leak-lens:iconwidget-v1:a1"})["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["audit_name"]} [{audit["verdict_level"]}]: {audit["verdict"]}')
for step in audit["steps"]:
    print(f'  [{step["status"]:>4}] {step["step"]:<24} {step["note"]}')
for f in audit["findings"]:
    print(f'  ({f["severity"]}) {f["category"]}: {f["title"]}')
    if f["fix_code"]:
        print(f'      {f["fix_code"]}')
for item in audit["checklist"]:
    print(f'  [{item["status"]:>4}] {item["item"]:<44} {item["note"]}')
for c in audit["coverage_check"]:
    print(f'  {c["id"]}: {"ok" if c["addressed"] else "SET ASIDE"} - {c["note"]}')

with open(audit["rewrite"]["filename"], "w", encoding="utf-8") as fh:   # audited.ts
    fh.write(audit["rewrite"]["code"])

# a run that fails the checklist is a CI failure
fails = [c for c in audit["checklist"] if c["status"] == "fail"]
if audit["verdict_level"] == "leaking" or fails:
    raise SystemExit(1)
import { writeFileSync } from "node:fs";

const { job_id } = await api("POST", "/run", payload,
  { "Idempotency-Key": "leak-lens:iconwidget-v1:a1" });

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.audit_name} [${audit.verdict_level}]: ${audit.verdict}`);
for (const step of audit.steps) {
  console.log(`  [${step.status}] ${step.step}: ${step.note}`);
}
for (const f of audit.findings) {
  console.log(`  (${f.severity}) ${f.category}: ${f.title}`);
  if (f.fix_code) console.log(`      ${f.fix_code}`);
}
for (const item of audit.checklist) console.log(`  [${item.status}] ${item.item}: ${item.note}`);
for (const c of audit.coverage_check) {
  console.log(`  ${c.id}: ${c.addressed ? "ok" : "SET ASIDE"} - ${c.note}`);
}

writeFileSync(audit.rewrite.filename, audit.rewrite.code);   // audited.ts
if (audit.verdict_level === "leaking") 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 {
	AuditName    string `json:"audit_name"`
	VerdictLevel string `json:"verdict_level"`
	Verdict      string `json:"verdict"`
	Steps        []struct {
		Step, Status, Note string
	} `json:"steps"`
	Findings []struct {
		Severity, Category, Title, Detail string
		FixCode                           string `json:"fix_code"`
	} `json:"findings"`
	Checklist []struct {
		Item, Status, Note string
	} `json:"checklist"`
	Rewrite struct {
		Filename, Code string
	} `json:"rewrite"`
	NextSteps []string `json:"next_steps"`
	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.AuditName, audit.VerdictLevel, audit.Verdict)
for _, s := range audit.Steps {
	fmt.Printf("  [%s] %s: %s\n", s.Status, s.Step, s.Note)
}
for _, f := range audit.Findings {
	fmt.Printf("  (%s) %s: %s\n", f.Severity, f.Category, f.Title)
}
for _, c := range audit.Checklist {
	fmt.Printf("  [%s] %s: %s\n", c.Status, c.Item, c.Note)
}
os.WriteFile(audit.Rewrite.Filename, []byte(audit.Rewrite.Code), 0o644) // audited.ts
// Send the same idempotency key on every retry of this input. With the helper
// from step 2, add the header where the request is built:
//   .header("Idempotency-Key", "leak-lens:iconwidget-v1:a1")
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
// audit_name, verdict_level, verdict, overview, steps[] (six steps with step/status/note),
// findings[] (severity/category/title/detail/fix_code), checklist[] (item/status/note),
// coverage_check[] (id/addressed/note), rewrite{filename, code}, next_steps[] and summary.
// Finally write the corrected code to disk:
//   Files.writeString(Path.of(rewriteFilename), rewriteCode);   // audited.ts
started = api("POST", "/run", payload)   # add the Idempotency-Key header in api()

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["audit_name"]} [#{audit["verdict_level"]}]: #{audit["verdict"]}"
audit["steps"].each { |s| puts "  [#{s["status"]}] #{s["step"]}: #{s["note"]}" }
audit["findings"].each do |f|
  puts "  (#{f["severity"]}) #{f["category"]}: #{f["title"]}"
  puts "      #{f["fix_code"]}" unless f["fix_code"].to_s.empty?
end
audit["checklist"].each { |c| puts "  [#{c["status"]}] #{c["item"]}: #{c["note"]}" }
audit["coverage_check"].each { |c| puts "  #{c["id"]}: #{c["addressed"] ? "ok" : "SET ASIDE"}" }

File.write(audit["rewrite"]["filename"], audit["rewrite"]["code"])   # audited.ts
$started = api("POST", "/run", $payload);   // add the Idempotency-Key header in api()

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['audit_name']} [{$audit['verdict_level']}]: {$audit['verdict']}\n";
foreach ($audit["steps"] as $s) {
    echo "  [{$s['status']}] {$s['step']}: {$s['note']}\n";
}
foreach ($audit["findings"] as $f) {
    echo "  ({$f['severity']}) {$f['category']}: {$f['title']}\n";
    if ($f["fix_code"] !== "") { echo "      {$f['fix_code']}\n"; }
}
foreach ($audit["checklist"] as $item) {
    echo "  [{$item['status']}] {$item['item']}: {$item['note']}\n";
}
foreach ($audit["coverage_check"] as $c) {
    echo "  {$c['id']}: " . ($c["addressed"] ? "ok" : "SET ASIDE") . "\n";
}

file_put_contents($audit["rewrite"]["filename"], $audit["rewrite"]["code"]);   // audited.ts
// The helper from step 2 plus one header: req.Headers.Add("Idempotency-Key", key);
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("audit_name")} " +
                  $"[{audit.GetProperty("verdict_level")}]: {audit.GetProperty("verdict")}");
foreach (var s in audit.GetProperty("steps").EnumerateArray())
{
    Console.WriteLine($"  [{s.GetProperty("status")}] {s.GetProperty("step")}: {s.GetProperty("note")}");
}
foreach (var f in audit.GetProperty("findings").EnumerateArray())
{
    Console.WriteLine($"  ({f.GetProperty("severity")}) {f.GetProperty("category")}: " +
                      $"{f.GetProperty("title")}");
}
foreach (var c in audit.GetProperty("checklist").EnumerateArray())
{
    Console.WriteLine($"  [{c.GetProperty("status")}] {c.GetProperty("item")}: {c.GetProperty("note")}");
}

var rewrite = audit.GetProperty("rewrite");
await File.WriteAllTextAsync(rewrite.GetProperty("filename").GetString()!,   // audited.ts
                             rewrite.GetProperty("code").GetString()!);

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 (step 7) before it falls back to a retry_note reformat run under a bumped idempotency key.

Step 6 — Stream the audit as it is written

POST /run-stream

/run-stream takes exactly the same body and the same Idempotency-Key as /run, but answers with server-sent events, so you can show progress instead of a spinner — useful here because the corrected rewrite makes for a long reply. This app's own progress panel is this endpoint: it watches the accumulating text for "steps", "findings", "checklist" and "rewrite" to light up its stage list. 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).
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: $KEY" \
  -d @input.json

# event: job
# data: {"job_id":"job_...","status":"running"}
#
# event: delta
# data: {"text":"{\"audit_name\":\"IconWidget"}
# ...
# event: done
# data: {"job_id":"job_...","status":"succeeded","charged_credits":734,"output":{"output":"{...}"}}
import json, requests

result = None
with requests.post(
    API + "/run-stream",
    headers={"Authorization": f"Bearer {TOKEN}",
             "Idempotency-Key": "leak-lens:iconwidget-v1:a1"},
    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["audit_name"])
for step in audit["steps"]:
    print(f'  [{step["status"]}] {step["step"]}')
open(audit["rewrite"]["filename"], "w", encoding="utf-8").write(audit["rewrite"]["code"])
const res = await fetch(API + "/run-stream", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${TOKEN}`,
    "Content-Type": "application/json",
    "Idempotency-Key": "leak-lens:iconwidget-v1:a1",
  },
  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.audit_name}`);
for (const step of audit.steps) console.log(`  [${step.status}] ${step.step}`);
writeFileSync(audit.rewrite.filename, audit.rewrite.code);   // audited.ts
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", "leak-lens:iconwidget-v1:a1")

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 5, then write audit.Rewrite.Code to disk.
// 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", "leak-lens:iconwidget-v1:a1")
    .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
// audit_name, verdict_level, steps[], findings[], checklist[], rewrite{filename, code} 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"] = "leak-lens:iconwidget-v1:a1"
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["audit_name"]}"
audit["steps"].each { |s| puts "  [#{s["status"]}] #{s["step"]}" }
File.write(audit["rewrite"]["filename"], audit["rewrite"]["code"])   # audited.ts
$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: leak-lens:iconwidget-v1:a1",
    ],
    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['audit_name']}\n";
foreach ($audit["steps"] as $s) { echo "  [{$s['status']}] {$s['step']}\n"; }
file_put_contents($audit["rewrite"]["filename"], $audit["rewrite"]["code"]);   // audited.ts
var req = new HttpRequestMessage(HttpMethod.Post, Api + "/run-stream") {
    Content = JsonContent.Create(payload),
};
req.Headers.Add("Idempotency-Key", "leak-lens:iconwidget-v1:a1");

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("audit_name"));
foreach (var s in audit.GetProperty("steps").EnumerateArray())
    Console.WriteLine($"  [{s.GetProperty("status")}] {s.GetProperty("step")}");
var rw = audit.GetProperty("rewrite");
await File.WriteAllTextAsync(rw.GetProperty("filename").GetString()!,   // audited.ts
                             rw.GetProperty("code").GetString()!);

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. If the stream dies mid-flight, the deltas you already have are worth keeping: the app closes the open braces and renders whatever sections arrived rather than discarding a paid run.

Step 7 — Parsing the audit

One JSON object, always the same shape — but it arrives as a string nested at output.output on the job, so there are two parses: the envelope, then the model's own JSON. Every array is present (findings is empty only if the paste is genuinely clean); steps always has exactly the six audit steps, checklist always has exactly the twelve items, and rewrite.code is never empty. If the paste was too thin to audit responsibly, you still get this object: what is there gets audited, the verdict says the paste is thin, and what you would need to show lands in next_steps. If the paste is not code at all, you still get the object — one high-severity finding explaining what arrived, every step at risk, every checklist item at na, and a rewrite.code comment block saying what to paste instead.

FieldTypeMeaning
audit_namestringA short name for the audit, taken from the code's own class or file naming.
verdict_levelstringclean (the paste follows the disposal rules and nothing material was found), patch (findings exist but are medium or low, or bite only at scale) or leaking (a high finding means the code leaks as pasted).
verdictstringOne or two sentences: does it leak, what leaks and how fast, and the single most important change.
overviewstringOne or two paragraphs: what this code does, and the pattern behind what was found. On runtime: "unknown" this is where the inferred runtime is stated.
stepsarray of 6{step, status, note} — the six audit steps listed below, each exactly once and in order. status is pass (the paste shows this handled correctly), risk (fragile, or the paste gives no evidence either way) or fail (a real defect lives here, backed by a finding). Each note points at something concrete in the paste; a step with no evidence is risk, never pass.
findingsarray{severity, category, title, detail, fix_code}. severity is high (it leaks on a path a user will actually hit — a listener added per call with no removal, a global-target listener never removed, an uncleared interval, an undisposed store held by a long-lived object) | medium (leaks only under a specific sequence, retains a bounded amount, or will leak once the method starts being called repeatedly) | low (hygiene). category is one of dom-listener, one-shot-event, repeated-registration, model-lifetime, resource-pool, timer, observer, test-guard, other. detail quotes the class, method, field or expression it concerns and says how the leak scales; fix_code is corrected code in your own names and style, valid for the declared runtime, or an empty string when the finding is a judgement call rather than a mechanical fix.
checklistarray of 12{item, status, note} — the twelve disposable items listed below, each exactly once and in order. status is pass, fail (a finding backs it) or na (the paste gives no evidence either way). The note says what was seen, or what is missing.
coverage_checkarray{id, addressed, note} — one entry per prescan_facts item you sent (raw-add-event-listener, lifecycle-class-iconwidget, signal-set-interval, …), saying where the audit covers it or why it was set aside. A pattern match can be a false positive; the note says so. Nothing you flagged is silently dropped.
rewriteobject{filename, code}filename is normally audited.ts (audited.js for plain JavaScript, or a name suggested by your own file headers), and code is your own code with every finding fixed: same classes, same method names, same behaviour, same comments, corrected lifetimes. It matches the declared runtime — no MutableDisposable smuggled into a plain browser paste — and it is a complete drop-in replacement for what you pasted, not a fragment and not a sketch with holes.
next_stepsstring[]Ordered and concrete: move the resize listener onto the disposable store, clear the poll interval in dispose(), add the suite leak guard, and so on. Work that depends on code outside the paste belongs here rather than in a speculative finding.
summarystring3–5 sentences a reviewer could paste straight into a pull request.

The six audit steps, in order, spelled exactly like this:

stepWhat its note covers
DOM event listenersEvery DOM handler tracked and disposable: this._register(addDisposableListener(...)) in the reference idiom, a stored handler removed in teardown or an AbortController signal in a plain browser. Raw .onload = / .onclick = property assignment is worse than addEventListener because it silently replaces the previous handler while still retaining its closure. Listeners on window, document and globalThis are the most dangerous: those targets outlive every component.
One-time eventsA subscription to an event that can only fire once (onDidDispose, onWillDispose, onDidClose, a first-change event) stays registered forever after it fires. Event.once(model.onDidDispose)(...), or { once: true } in a browser runtime.
Repeated method callsObjects created in a method that runs more than once must not be registered to the class store: every call adds another listener that lives as long as the class. A MutableDisposable field guarantees at most one live listener, or the method returns an IDisposable the caller owns. this._register() outside a constructor or one-shot initializer is the signature of this bug.
Model-tied storesA DisposableStore scoped to a model's lifetime must dispose itself when that model does, with the subscription that does it inside the store: store.add(model.onWillDispose(() => store.dispose())). The note says which way round the lifetimes actually go in your paste.
Resource poolsFactory methods minting pooled objects (list rows, tree nodes, editor widgets) must register each item's disposables to that item, not to the pool class, and hand the caller something disposable.
Test leak guardsA suite that creates disposables calls ensureNoDisposablesAreLeakedInTestSuite(), so CI catches the leak instead of a user. A paste with no tests at all is risk, not pass — the guard is simply unobservable, and it lands in next_steps.

The twelve checklist items, in order, spelled exactly like this:

itemWhat its note covers
DOM listeners registered disposablyEvery DOM listener is owned by something that will remove it — a store, a returned disposable, or an aborted signal.
No raw on* property handlersNo .onload = / .onclick = / .onchange = assignment; handlers go through a disposable registration.
One-shot lifecycle events use Event.onceEvents that can fire only once unsubscribe themselves after firing.
No _register() in repeatedly-called methodsthis._register() appears only in constructors and one-shot initializers.
MutableDisposable guards single-slot listenersA listener that is re-created per call lives in a MutableDisposable slot, so assigning it disposes the previous one.
Factory-created objects own their disposablesPooled or per-row objects carry their own store and their own dispose().
Model-scoped stores dispose on onWillDisposeA store tied to a model's lifetime is torn down by that model's own teardown event.
Timers and intervals cleared on disposeEvery setInterval and long-lived setTimeout is cleared in teardown (and unref()'d where that is the Node idiom).
Observers and AbortControllers torn downMutationObserver / ResizeObserver / IntersectionObserver disconnected, AbortController aborted exactly once, subscriptions unsubscribed.
Every disposable field is owned by somethingNo disposable field is left with no owner — each is registered to a store or disposed by the class that holds it.
Test suites assert no leaked disposablesSuites that create disposables call the leak guard at the top.
dispose() is idempotent and completeA second dispose() is harmless, and the first one tears down everything the class holds.

A small, realistic result for the IconWidget paste above, trimmed for length:

{
  "audit_name": "icon_widget.ts - IconWidget listener lifetimes",
  "verdict_level": "leaking",
  "verdict": "IconWidget leaks one model listener per startSearch() call and never clears its
              poll interval, so a keystroke-driven search grows listeners without bound; move
              the search subscription into a MutableDisposable slot first.",
  "overview": "A Disposable subclass that renders an icon and polls a model. The base class
               gives it a store, but three of its four registrations bypass it: an onload
               property assignment, a window listener added outside the store, and a bare
               setInterval. The fourth, in startSearch(), uses the store correctly but is
               called repeatedly, which is its own leak.",
  "steps": [
    { "step": "DOM event listeners", "status": "fail",
      "note": "'this.el.onload = () => this.layout()' and the bare
               window.addEventListener('resize', ...) are both untracked; the window
               listener retains the widget for the life of the page." },
    { "step": "One-time events", "status": "risk",
      "note": "No lifecycle-event subscription in the paste - onload is effectively one-shot
               and would be better as { once: true } or addDisposableListener." },
    { "step": "Repeated method calls", "status": "fail",
      "note": "startSearch() calls this._register(this.model.onResults(...)), so every
               keystroke adds a listener that lives as long as the widget." },
    { "step": "Model-tied stores", "status": "risk",
      "note": "The widget subscribes to `model` but the paste never shows which outlives the
               other; no store is tied to model.onWillDispose." },
    { "step": "Resource pools", "status": "pass",
      "note": "No factory or pooled objects in the paste." },
    { "step": "Test leak guards", "status": "risk",
      "note": "No tests pasted, so the suite guard is unobservable here." }
  ],
  "findings": [
    { "severity": "high", "category": "repeated-registration",
      "title": "startSearch() registers a model listener to the class store on every call",
      "detail": "'this._register(this.model.onResults(() => this.render()))' inside
                 startSearch() adds one listener per call and never removes the previous
                 one; at one call per keystroke this grows linearly with typing.",
      "fix_code": "private readonly _searchListener = this._register(new MutableDisposable());\n\nstartSearch(): void {\n  this._searchListener.value = this.model.onResults(() => this.render());\n}" },
    { "severity": "high", "category": "dom-listener",
      "title": "The resize listener on window is never removed",
      "detail": "'window.addEventListener('resize', () => this.layout())' keeps the closure,
                 and therefore the whole widget, alive for the life of the page.",
      "fix_code": "this._register(addDisposableListener(window, 'resize', () => this.layout()));" },
    { "severity": "medium", "category": "dom-listener",
      "title": "onload is a property assignment, not a disposable registration",
      "detail": "'this.el.onload = () => this.layout()' silently replaces any previous
                 handler and is not torn down with the widget.",
      "fix_code": "this._register(addDisposableListener(this.el, 'load', () => this.layout()));" },
    { "severity": "high", "category": "timer",
      "title": "The poll interval is never cleared",
      "detail": "'setInterval(() => this.poll(), 1000)' outlives dispose(), so poll() keeps
                 running against a dead widget once per second.",
      "fix_code": "const poll = setInterval(() => this.poll(), 1000);\nthis._register(toDisposable(() => clearInterval(poll)));" }
  ],
  "checklist": [
    { "item": "DOM listeners registered disposably", "status": "fail",
      "note": "Neither the onload handler nor the window resize listener is registered." },
    { "item": "No raw on* property handlers", "status": "fail",
      "note": "this.el.onload is a property assignment." },
    { "item": "One-shot lifecycle events use Event.once", "status": "na",
      "note": "No lifecycle event is subscribed in the paste." },
    { "item": "No _register() in repeatedly-called methods", "status": "fail",
      "note": "startSearch() calls this._register() on every invocation." }
  ],
  "coverage_check": [
    { "id": "raw-add-event-listener", "addressed": true,
      "note": "Covered by the resize finding - moved onto addDisposableListener." },
    { "id": "on-property-handler", "addressed": true,
      "note": "Covered: this.el.onload becomes a registered 'load' listener." },
    { "id": "signal-set-interval", "addressed": true,
      "note": "The poll interval is cleared through toDisposable in the rewrite." },
    { "id": "lifecycle-class-iconwidget", "addressed": true,
      "note": "The class under audit; it already extends Disposable, so the store exists." }
  ],
  "rewrite": { "filename": "audited.ts",
               "code": "export class IconWidget extends Disposable { ... }" },
  "next_steps": [
    "Introduce a MutableDisposable slot for the startSearch() subscription.",
    "Move the onload and resize handlers onto addDisposableListener.",
    "Clear the poll interval through toDisposable(() => clearInterval(poll)).",
    "Add ensureNoDisposablesAreLeakedInTestSuite() to the widget's test suite."
  ],
  "summary": "IconWidget extends Disposable but bypasses its own store three times. ..."
}

Parse defensively: strip a code fence if there is one, take the text from the first { to the last }, then validate the shape before you act on it — the app treats a missing audit step, a missing checklist item or an empty rewrite.code as a parse failure and retries once with a retry_note.

# the envelope, then the model's JSON string, then a shape check
jq -r '.data.output.output' job.json \
  | sed -e 's/^```[a-z]*//' -e 's/```$//' > audit.json

jq -e '
  (.steps      | length) == 6  and
  (.checklist  | length) == 12 and
  (.rewrite.code | length) > 0 and
  (.verdict_level | IN("clean","patch","leaking"))' audit.json > /dev/null \
  && echo "shape ok" || echo "malformed audit - re-run with a retry_note"
import json, re

STEPS = ["DOM event listeners", "One-time events", "Repeated method calls",
         "Model-tied stores", "Resource pools", "Test leak guards"]

def parse_audit(job):
    raw = job.get("output")
    if isinstance(raw, dict):
        raw = raw.get("output", raw)
    if not isinstance(raw, str):
        return raw
    text = re.sub(r"^```[a-z]*\s*", "", raw.strip())
    text = re.sub(r"```\s*$", "", text)
    i, j = text.find("{"), text.rfind("}")
    if i < 0 or j <= i:
        raise ValueError("no JSON object found")
    audit = json.loads(text[i:j + 1])
    if [s["step"] for s in audit["steps"]] != STEPS:
        raise ValueError("steps must be the six audit steps, in order")
    if len(audit["checklist"]) != 12:
        raise ValueError("checklist must have all twelve items")
    if not audit["rewrite"]["code"].strip():
        raise ValueError("rewrite.code must be non-empty")
    return audit

audit = parse_audit(job)
worst = min((f["severity"] for f in audit["findings"]),
            key=lambda s: ["high", "medium", "low"].index(s), default="none")
print(audit["verdict_level"], "- worst finding:", worst)
const STEPS = ["DOM event listeners", "One-time events", "Repeated method calls",
  "Model-tied stores", "Resource pools", "Test leak guards"];

function parseAudit(job) {
  let raw = job.output?.output ?? job.output;
  if (typeof raw !== "string") return raw;
  const text = raw.trim().replace(/^```[a-z]*\s*/i, "").replace(/```\s*$/, "");
  const i = text.indexOf("{"), j = text.lastIndexOf("}");
  if (i < 0 || j <= i) throw new Error("no JSON object found");
  const audit = JSON.parse(text.slice(i, j + 1));
  const steps = audit.steps.map((s) => s.step);
  if (steps.join("|") !== STEPS.join("|")) throw new Error("steps must be the six, in order");
  if (audit.checklist.length !== 12) throw new Error("checklist must have all twelve items");
  if (!audit.rewrite.code.trim()) throw new Error("rewrite.code must be non-empty");
  return audit;
}

const audit = parseAudit(job);
const highs = audit.findings.filter((f) => f.severity === "high");
const fails = audit.checklist.filter((c) => c.status === "fail");
console.log(`${audit.verdict_level}: ${highs.length} high, ${fails.length} checklist fails`);
var STEPS = []string{"DOM event listeners", "One-time events", "Repeated method calls",
	"Model-tied stores", "Resource pools", "Test leak guards"}

func parseAudit(raw string) (*Audit, error) {
	t := strings.TrimSpace(raw)
	if k := strings.Index(t, "\n"); strings.HasPrefix(t, "```") && k > 0 {
		t = t[k+1:]
	}
	t = strings.TrimSuffix(strings.TrimSpace(t), "```")
	i, j := strings.Index(t, "{"), strings.LastIndex(t, "}")
	if i < 0 || j <= i {
		return nil, fmt.Errorf("no JSON object found")
	}
	var a Audit // the struct from step 5
	if err := json.Unmarshal([]byte(t[i:j+1]), &a); err != nil {
		return nil, err
	}
	if len(a.Steps) != len(STEPS) {
		return nil, fmt.Errorf("steps must contain all six audit steps")
	}
	for n, s := range a.Steps {
		if s.Step != STEPS[n] {
			return nil, fmt.Errorf("step %d is %q, want %q", n, s.Step, STEPS[n])
		}
	}
	if len(a.Checklist) != 12 {
		return nil, fmt.Errorf("checklist must contain all twelve items")
	}
	if strings.TrimSpace(a.Rewrite.Code) == "" {
		return nil, fmt.Errorf("rewrite.code must be non-empty")
	}
	return &a, nil
}
// The two-parse rule: data.output.output is a JSON *string*, so unwrap it,
// clean it, and parse it again with your JSON library.
static final List<String> STEPS = List.of(
    "DOM event listeners", "One-time events", "Repeated method calls",
    "Model-tied stores", "Resource pools", "Test leak guards");

static String cleanAuditJson(String raw) {
    String t = raw.strip()
        .replaceFirst("^```[a-zA-Z]*\\s*", "")
        .replaceFirst("```\\s*$", "");
    int i = t.indexOf('{'), j = t.lastIndexOf('}');
    if (i < 0 || j <= i) throw new IllegalArgumentException("no JSON object found");
    return t.substring(i, j + 1);
}
// Then assert, before acting on it:
//   steps has all six of STEPS, in order; checklist has twelve items;
//   rewrite.code is non-blank; verdict_level is clean | patch | leaking.
// Anything else means re-running with a retry_note instead of trusting the reply.
STEPS = ["DOM event listeners", "One-time events", "Repeated method calls",
         "Model-tied stores", "Resource pools", "Test leak guards"].freeze

def parse_audit(job)
  raw = job["output"].is_a?(Hash) ? job["output"].fetch("output", job["output"]) : job["output"]
  return raw unless raw.is_a?(String)

  text = raw.strip.sub(/\A```[a-z]*\s*/i, "").sub(/```\s*\z/, "")
  i, j = text.index("{"), text.rindex("}")
  raise "no JSON object found" if i.nil? || j.nil? || j <= i

  audit = JSON.parse(text[i..j])
  raise "steps must be the six audit steps, in order" if audit["steps"].map { |s| s["step"] } != STEPS
  raise "checklist must have all twelve items" if audit["checklist"].length != 12
  raise "rewrite.code must be non-empty" if audit["rewrite"]["code"].to_s.strip.empty?
  audit
end

audit = parse_audit(job)
puts "#{audit["verdict_level"]}: #{audit["findings"].count { |f| f["severity"] == "high" }} high"
const STEPS = ["DOM event listeners", "One-time events", "Repeated method calls",
               "Model-tied stores", "Resource pools", "Test leak guards"];

function parse_audit(array $job): array {
    $raw = is_array($job["output"]) ? ($job["output"]["output"] ?? $job["output"]) : $job["output"];
    if (!is_string($raw)) { return $raw; }

    $text = preg_replace('/^```[a-z]*\s*/i', "", trim($raw));
    $text = preg_replace('/```\s*$/', "", $text);
    $i = strpos($text, "{");
    $j = strrpos($text, "}");
    if ($i === false || $j === false || $j <= $i) {
        throw new Exception("no JSON object found");
    }
    $audit = json_decode(substr($text, $i, $j - $i + 1), true);
    if (array_column($audit["steps"], "step") !== STEPS) {
        throw new Exception("steps must be the six audit steps, in order");
    }
    if (count($audit["checklist"]) !== 12) {
        throw new Exception("checklist must have all twelve items");
    }
    if (trim($audit["rewrite"]["code"]) === "") {
        throw new Exception("rewrite.code must be non-empty");
    }
    return $audit;
}
static readonly string[] Steps = {
    "DOM event listeners", "One-time events", "Repeated method calls",
    "Model-tied stores", "Resource pools", "Test leak guards",
};

static JsonDocument ParseAudit(JsonElement job)
{
    var raw = job.TryGetProperty("output", out var o) && o.ValueKind == JsonValueKind.Object
        ? o.GetProperty("output").GetString()
        : o.GetString();
    var text = (raw ?? "").Trim();
    if (text.StartsWith("```")) text = text[(text.IndexOf('\n') + 1)..];
    if (text.EndsWith("```")) text = text[..^3];
    int i = text.IndexOf('{'), j = text.LastIndexOf('}');
    if (i < 0 || j <= i) throw new InvalidOperationException("no JSON object found");

    var doc = JsonDocument.Parse(text[i..(j + 1)]);
    var root = doc.RootElement;
    var got = root.GetProperty("steps").EnumerateArray()
        .Select(s => s.GetProperty("step").GetString()).ToArray();
    if (!got.SequenceEqual(Steps))
        throw new InvalidOperationException("steps must be the six audit steps, in order");
    if (root.GetProperty("checklist").GetArrayLength() != 12)
        throw new InvalidOperationException("checklist must have all twelve items");
    if (string.IsNullOrWhiteSpace(root.GetProperty("rewrite").GetProperty("code").GetString()))
        throw new InvalidOperationException("rewrite.code must be non-empty");
    return doc;
}

The rewrite is a starting point, not a sign-off: it is written to be complete and self-consistent with the findings, but it is AI-generated and it only sees what you pasted. Read it, run tsc and your test suite against it, and keep the human review in the loop before it goes anywhere near production.

Step 8 — Storing audits

POST /collections/audits/records
POST /collections/audits/query
POST /collections/audits/similar
GET /collections/audits/records/{record_id}
DELETE /collections/audits/records/{record_id}

The app declares one collection, audits, and that is the system of record behind its history panel — past audits follow the user across devices instead of sitting in one browser's localStorage. You can write to it from a script exactly as the app does, which is how a CI job accumulates a leak history for a repository.

Two details decide whether your integration works. First, records nest under doc: create takes {"doc": {…}}, and query, get and similar all return {record_id, doc: {…}, created_at} — read record.doc.verdict_level, never record.verdict_level. Second, the sort key is sort, an object, not order_by: an unrecognised key is ignored silently and you get created_at desc back without any error to tell you why. Query answers with {"data": {"records": […]}, "meta": {"pagination": {"has_more", "next_cursor"}}}.

The collection is acl_read: owner / acl_write: user, so rows are scoped to the subject that wrote them: a row written under a guest token belongs to that guest and will not appear once the user signs in. Documents are capped at 64 KB, which a single 100 KB paste blows on its own — the app keeps its records under 58 KB by shedding the pasted input first (marking input_dropped) and the rewrite second (rewrite_dropped). Do the same rather than letting a write fail.

doc fieldTypeMeaning
titlestringDisplay name for the row — the app stores audit_name.
verdict_levelstringclean | patch | leaking, copied off the audit.
runtimestringThe runtime the audit ran under, so a history list can be filtered by idiom set.
findings_countnumberfindings.length — cheap to sort and chart without re-reading the audit.
fails_countnumberHow many checklist items came back fail.
summarystringFirst 1,000 characters of summary (or verdict). One of the embedded fields, so it drives semantic search.
ran_atstringISO-8601 timestamp. Sort on this rather than on created_at if you ever back-fill older runs.
auditobjectThe whole parsed audit object from step 7.
metaobjectRun metadata: {secs, charged, model, when}.
inputobject or null{code, runtime, notes, prescan_facts} so the run can be repeated, or null with input_dropped: true when the paste would break the size cap.
COL="$API/collections/audits"

# 1. save the audit that just finished
jq -n --slurpfile a audit.json --arg rt "vscode" '{doc: {
    title:          $a[0].audit_name,
    verdict_level:  $a[0].verdict_level,
    runtime:        $rt,
    findings_count: ($a[0].findings   | length),
    fails_count:    ([$a[0].checklist[] | select(.status == "fail")] | length),
    summary:        ($a[0].summary // $a[0].verdict)[0:1000],
    ran_at:         (now | todate),
    audit:          $a[0],
    meta:           {model: "gpt-terra"},
    input:          null
  }}' > record.json

RECORD_ID=$(curl -s -X POST "$COL/records" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d @record.json | jq -r '.data.record.record_id')

# 2. list the ten most recent - note `sort`, an object, NOT `order_by`
curl -s -X POST "$COL/query" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{"sort":{"field":"ran_at","dir":"desc"},"limit":10}' \
  | jq -r '.data.records[] | "\(.doc.ran_at)  [\(.doc.verdict_level)]  \(.doc.title)"'

# 3. semantic search over title, summary and runtime
curl -s -X POST "$COL/similar" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{"text":"listener added on every keystroke","limit":5}' \
  | jq -r '.data.records[] | "\(.score)  \(.doc.title)"'
COL = "/collections/audits"

fails = sum(1 for c in audit["checklist"] if c["status"] == "fail")
doc = {
    "title": audit["audit_name"],
    "verdict_level": audit["verdict_level"],
    "runtime": payload["runtime"],
    "findings_count": len(audit["findings"]),
    "fails_count": fails,
    "summary": (audit["summary"] or audit["verdict"])[:1000],
    "ran_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
    "audit": audit,
    "meta": {"model": "gpt-terra"},
    "input": None,          # drop the paste rather than break the 64 KB cap
}

record = api("POST", COL + "/records", {"doc": doc})["record"]
print("saved", record["record_id"])

# `sort` is an object, NOT `order_by` - an unknown key falls back to created_at desc
page = api("POST", COL + "/query", {"sort": {"field": "ran_at", "dir": "desc"}, "limit": 10})
for rec in page["records"]:
    d = rec["doc"]                       # always unwrap doc
    print(f'{d["ran_at"]}  [{d["verdict_level"]:>7}]  {d["title"]}  '
          f'({d["findings_count"]} findings, {d["fails_count"]} fails)')

hits = api("POST", COL + "/similar",
           {"text": "listener added on every keystroke", "limit": 5})["records"]
for h in hits:
    print(round(h.get("score", 0), 3), h["doc"]["title"])
const COL = "/collections/audits";

const fails = audit.checklist.filter((c) => c.status === "fail").length;
const doc = {
  title: audit.audit_name,
  verdict_level: audit.verdict_level,
  runtime: payload.runtime,
  findings_count: audit.findings.length,
  fails_count: fails,
  summary: (audit.summary || audit.verdict).slice(0, 1000),
  ran_at: new Date().toISOString(),
  audit,
  meta: { model: "gpt-terra" },
  input: null,            // drop the paste rather than break the 64 KB cap
};

const { record } = await api("POST", `${COL}/records`, { doc });
console.log("saved", record.record_id);

// `sort` is an object, NOT `order_by`
const page = await api("POST", `${COL}/query`,
  { sort: { field: "ran_at", dir: "desc" }, limit: 10 });
for (const rec of page.records) {
  const d = rec.doc;                     // always unwrap doc
  console.log(`${d.ran_at} [${d.verdict_level}] ${d.title} (${d.findings_count} findings)`);
}

const { records } = await api("POST", `${COL}/similar`,
  { text: "listener added on every keystroke", limit: 5 });
for (const r of records) console.log(r.score, r.doc.title);
const col = "/collections/audits"

fails := 0
for _, c := range audit.Checklist {
	if c.Status == "fail" {
		fails++
	}
}
doc := map[string]any{
	"title":          audit.AuditName,
	"verdict_level":  audit.VerdictLevel,
	"runtime":        "vscode",
	"findings_count": len(audit.Findings),
	"fails_count":    fails,
	"summary":        audit.Summary,
	"ran_at":         time.Now().UTC().Format(time.RFC3339),
	"audit":          audit,
	"meta":           map[string]any{"model": "gpt-terra"},
	"input":          nil,
}

var created struct {
	Record struct {
		RecordID string `json:"record_id"`
	} `json:"record"`
}
if err := call("POST", col+"/records", map[string]any{"doc": doc}, &created); err != nil {
	log.Fatal(err)
}

// `sort` is an object, NOT `order_by`.
var page struct {
	Records []struct {
		RecordID string `json:"record_id"`
		Doc      struct {
			Title         string `json:"title"`
			VerdictLevel  string `json:"verdict_level"`
			RanAt         string `json:"ran_at"`
			FindingsCount int    `json:"findings_count"`
		} `json:"doc"`
	} `json:"records"`
}
q := map[string]any{"sort": map[string]string{"field": "ran_at", "dir": "desc"}, "limit": 10}
if err := call("POST", col+"/query", q, &page); err != nil {
	log.Fatal(err)
}
for _, r := range page.Records {
	fmt.Printf("%s [%s] %s\n", r.Doc.RanAt, r.Doc.VerdictLevel, r.Doc.Title)
}
// Create: POST /collections/audits/records with {"doc": { ... }}
String recordJson = """
    {"doc": {
      "title": %s,
      "verdict_level": "leaking",
      "runtime": "vscode",
      "findings_count": 4,
      "fails_count": 4,
      "summary": %s,
      "ran_at": "%s",
      "audit": %s,
      "meta": {"model": "gpt-terra"},
      "input": null
    }}""".formatted(toJsonString(auditName), toJsonString(summary),
                    java.time.Instant.now().toString(), auditJson);
String created = api("POST", "/collections/audits/records", recordJson);
// data.record.record_id

// List: the key is `sort` (an object), NOT `order_by` - an unknown key is
// ignored silently and you get created_at desc back with no error.
String page = api("POST", "/collections/audits/query", """
    {"sort": {"field": "ran_at", "dir": "desc"}, "limit": 10}""");
// data.records[] -> each is {record_id, doc: {...}, created_at}; read fields off .doc,
// and data has meta.pagination.has_more / next_cursor for the next page.

// Semantic search over the embedded fields (title, summary, runtime):
String hits = api("POST", "/collections/audits/similar", """
    {"text": "listener added on every keystroke", "limit": 5}""");
COL = "/collections/audits"

fails = audit["checklist"].count { |c| c["status"] == "fail" }
doc = {
  title:          audit["audit_name"],
  verdict_level:  audit["verdict_level"],
  runtime:        payload[:runtime],
  findings_count: audit["findings"].length,
  fails_count:    fails,
  summary:        (audit["summary"] || audit["verdict"])[0, 1000],
  ran_at:         Time.now.utc.iso8601,
  audit:          audit,
  meta:           { model: "gpt-terra" },
  input:          nil      # drop the paste rather than break the 64 KB cap
}

record = api("POST", "#{COL}/records", { doc: doc })["record"]
puts "saved #{record["record_id"]}"

# `sort` is an object, NOT `order_by`
page = api("POST", "#{COL}/query", { sort: { field: "ran_at", dir: "desc" }, limit: 10 })
page["records"].each do |rec|
  d = rec["doc"]                        # always unwrap doc
  puts "#{d["ran_at"]} [#{d["verdict_level"]}] #{d["title"]} (#{d["findings_count"]} findings)"
end

hits = api("POST", "#{COL}/similar", { text: "listener added on every keystroke", limit: 5 })
hits["records"].each { |h| puts "#{h["score"]} #{h["doc"]["title"]}" }
const COL = "/collections/audits";

$fails = count(array_filter($audit["checklist"], fn($c) => $c["status"] === "fail"));
$doc = [
    "title"          => $audit["audit_name"],
    "verdict_level"  => $audit["verdict_level"],
    "runtime"        => $payload["runtime"],
    "findings_count" => count($audit["findings"]),
    "fails_count"    => $fails,
    "summary"        => substr($audit["summary"] ?: $audit["verdict"], 0, 1000),
    "ran_at"         => gmdate("c"),
    "audit"          => $audit,
    "meta"           => ["model" => "gpt-terra"],
    "input"          => null,   // drop the paste rather than break the 64 KB cap
];

$record = api("POST", COL . "/records", ["doc" => $doc])["record"];
echo "saved {$record['record_id']}\n";

// `sort` is an object, NOT `order_by`
$page = api("POST", COL . "/query", ["sort" => ["field" => "ran_at", "dir" => "desc"], "limit" => 10]);
foreach ($page["records"] as $rec) {
    $d = $rec["doc"];                   // always unwrap doc
    echo "{$d['ran_at']} [{$d['verdict_level']}] {$d['title']}\n";
}

$hits = api("POST", COL . "/similar", ["text" => "listener added on every keystroke", "limit" => 5]);
foreach ($hits["records"] as $h) { echo "{$h['score']} {$h['doc']['title']}\n"; }
const string Col = "/collections/audits";

var fails = audit.GetProperty("checklist").EnumerateArray()
    .Count(c => c.GetProperty("status").GetString() == "fail");

var doc = new {
    title = audit.GetProperty("audit_name").GetString(),
    verdict_level = audit.GetProperty("verdict_level").GetString(),
    runtime = "vscode",
    findings_count = audit.GetProperty("findings").GetArrayLength(),
    fails_count = fails,
    summary = audit.GetProperty("summary").GetString(),
    ran_at = DateTime.UtcNow.ToString("o"),
    audit,
    meta = new { model = "gpt-terra" },
    input = (object?)null,   // drop the paste rather than break the 64 KB cap
};

var created = await SkillSafe.ApiAsync(HttpMethod.Post, Col + "/records", new { doc });
Console.WriteLine("saved " + created.GetProperty("record").GetProperty("record_id"));

// `sort` is an object, NOT `order_by`
var page = await SkillSafe.ApiAsync(HttpMethod.Post, Col + "/query",
    new { sort = new { field = "ran_at", dir = "desc" }, limit = 10 });
foreach (var rec in page.GetProperty("records").EnumerateArray())
{
    var d = rec.GetProperty("doc");     // always unwrap doc
    Console.WriteLine($"{d.GetProperty("ran_at")} [{d.GetProperty("verdict_level")}] " +
                      $"{d.GetProperty("title")}");
}

var hits = await SkillSafe.ApiAsync(HttpMethod.Post, Col + "/similar",
    new { text = "listener added on every keystroke", limit = 5 });

Read the history through POST /collections/audits/query, not through the key-value GET /data/{key} endpoint: that one caches per subject and key for about 90 seconds, so a single stored document would stop reflecting new runs right after the first read. The query path returns fresh rows immediately after a write, which is why the app's own history panel is built on it.