# App lifecycle

Use one App document as the product unit. The CLI and MCP surfaces represent the
same lifecycle.

## CLI loop

<!-- flow-authoring:start -->
An App is an uploaded frontend plus a backend written in the Wrapflow flow language: its tables, the endpoints its pages call, and its background jobs.
Write the App for its users. Keep the name Wrapflow and Wrapflow account, hosting, storage, and draft/release mechanics out of the App's UI or help. Terms such as hosting, storage, drafts, and owner remain appropriate for App-domain concepts, such as event hosting, storage units, article drafts, or an App role named owner. Describe what the user can do.
The page reads only what a view offers. Choose owner, signedIn, roles("manager"), app or public. `app`: whoever can open this App; its sharing and sign-in on the Publish page decide, so making the App public opens this to visitors. For an owner's summary, write view(name: "Summary", access: {read: owner}) do, write the read pipeline in the body and close it with end. Removing that block removes the page's read even when a scheduled email still uses the result. When two views need the same rows, name the calculation above them and start each view with that name.

flow 1
let orders = table(name: "orders", columns: {status: text(), customer: text(), total: number()})
let open = orders |> filter(where: status == "open")
view(name: "open-orders", access: {read: signedIn}) do
  open |> select(columns: [customer, total])
end
view(name: "open-count", access: {read: public}) do
  open
    |> aggregate(metrics: {orders: count()})
    |> select(columns: [orders])
end

Read with describe kind:"flow", keep revision.id as expectedRevision → edit the text → apply {text, expectedRevision} → test → publish. Exact edits use {edits:[{find,replace}], expectedRevision} against that same read.
Define each name above the line that uses it, including tables named in fields and commands called by scenarios. For tables whose fields refer to each other, list their names first with let a, b, then a = table(...) and b = table(...). A command keeps its let because its name after let names the public operation; a saved view needs a let only when another line reads it. A top-level let such as let tomorrow = orders |> filter(where: pickup_date == addDays(today(), 1)) defines a calculation that runs each time a schedule, view or other chain uses it. A bare word names a declared value, a column or request field, or a listed choice. Text and data are quoted, including one word: name: "tasks", defaultValue: "todo", input: {title: "Example"}. Column names stay bare: columns: [title, status]. A command reference uses its let name: command: add_task. A pull states its name: explicitly. Tables and named commands use name: with - as _; views, parameters and unnamed commands keep their let. Expressions print and, or and not, double-quoted text literals, and one space around binary operators. Calls and records have no inner padding; commas and colons have one following space. An unchanged apply keeps the stored expression spelling. A chain of steps reads top to bottom with |>, and the pipe supplies the step's first input: let open = orders |> filter(where: status == "open") |> select(columns: [id, status]) means the same as orders |> filter(...) then ... |> select(...), and the let binds the last step. Writing input: inside a piped step is refused: the pipe is its input. A step with two inputs takes the piped value as its first and names the other: let result = orders |> join(right: customers, on: {left: customer_id, right: id}, type: inner, rightDedupe: none) |> select(columns: [id]) means the same as orders |> join(right: customers, ...) then select. A single step uses the same spelling: let open = orders |> filter(where: status == "open"). A chain can also start from a step call that reads no input. A view starts its body with the table or let name. A step taking several sources still names them together as input: [a, b]. Named-input step calls still parse. A step that reads no input (table, a command) cannot follow |>; it may head a chain. Keep a let for a value read more than once or by a branch; a step read once is written into the chain.
List expressions and operations:
Values can be lists [a, b] or objects {key: value}. Read value.key or value[key]; list indexes start at zero. get(value, key, fallback) uses the fallback only for a missing key, retaining a stored null, false or zero. put(value, key, replacement) returns an immutable replacement; append(list, value) adds one member. in tests list membership or an object's own keys. Multi-branch expressions use case(when(total >= 100, then: "large"), when(total >= 20, then: "medium"), else: "small").
Inside a value, x |> f(a) passes x as f's first argument. map(each:), filter(where:), find(where:), any(where:) and all(where:) accept an optional author-chosen row name, such as map(lines, each: line => ({qty: line.qty + 1})). Without a name, bare names read only the element's fields; outer values keep qualified names such as input.extra, current.lines or a named outer row. Plain values require a name. reduce(from:, each:) names both its running value and element; it has no implicit acc, item or index. Bodies are expressions; object results print with parentheses. Nested filter(where:), sort(by:), derive(columns:), select(columns:) and aggregate(groupBy:, metrics:) take the same arguments as table steps. Use sort(by: [name, {column: total, direction: desc}]); a plain column means ascending. Ordering clauses on window, datasetQuery, jsonArray and topNPerGroup use orderBy: with the same entries. A direct table view orders by one entry, sort(by: [name]) or sort(by: [{column: total, direction: desc}]). Grouping, metric domains, empty global groups and payload ordering match the table step. Every derived column reads the original element; use successive derives for dependencies. Iteration is bounded at 10,000 items and shares the expression work budget.
list(column:) collects a column into a real list, retains null/missing cells, false and zero, and returns [] for an empty global group. Sort the input first when order matters. join(list, separator) joins text values; an empty list gives "", and a null or non-text member gives null. Both operations refuse results above their existing list/byte/string limits rather than truncating. For example:
```flow
flow 1
let greeting = sample(dataset: customers)
  |> aggregate(metrics: {names: list(column: name)})
  |> derive(columns: {text: join(names, ", ")})
# @layout {"n":{"greeting_sample1":[null,null,null,null,"names_sample1",null,"ca1ccbca"],"greeting_aggregate1":[null,null,null,null,"names",null,"9dd1793c"]}}
```
Scalar math: sqrt(n) is the square root, pow(base, exponent) raises a base to a power, and log(n) is the natural logarithm. They accept finite numbers only; null, numeric text and booleans are not coerced. Invalid domains or non-finite results give null (sqrt(-1), pow(0, -1), log(0)); zero results are 0. For example, sqrt(81) is 9, pow(2, -3) is 0.125 and log(1) is 0. Use coalesce when a result needs a default.
```flow
flow 1
let math = sample(dataset: orders)
  |> derive(columns: {root: sqrt(81), power: pow(2, -3), logarithm: log(1)})
# @layout {"n":{"math_sample1":[null,null,null,null,"values",null,"85de4522"]}}
```
uuid() returns a fresh lowercase UUIDv4; random() returns a fresh number in [0, 1). Both take zero arguments and generate a new value for each call, row and evaluation. They work in native Flow expressions, computed writes and table JavaScript functions. Deterministic command JavaScript rules exclude randomness; generate the value in an earlier Flow step and pass it through input. These calls do not take a seed and their results are not replay-stable.
```flow
flow 1
let rows = table(name: "rows", columns: {label: text()})
view(name: "Result", access: {read: owner}) do
  rows |> derive(columns: {identifier: uuid(), draw: random()})
end
# @layout {"n":{"Result_rows":[null,null,null,null,"result"]}}
```
Value formatting: formatNumber(n, digits?) returns text using JavaScript's fixed-decimal toFixed rules (default 0 digits, integer 0–100; magnitudes at least 1e21 use exponential notation). It does not add grouping or a currency symbol, and binary floating-point rounding applies. formatDate(d, pattern) formats a strict ISO date/datetime in UTC using numeric tokens yyyy, MM, dd, HH, mm, ss and SSS. Punctuation is literal; quote literal words with single quotes and escape an apostrophe with two quotes. Unquoted ASCII letters must form one supported token; other widths (MMMM, dddd) and unclosed quotes return null. Invalid dates, null/wrong-type operands and invalid precision return null without coercion. Pattern/result text uses the existing 262,144-character bound; exceeding it visibly refuses. No ambient locale or wall clock is read. Both calls work in every expression and computed write.
```flow
flow 1
let rows = table(name: "rows", columns: {amount: number(), at: datetime()})
view(name: "Result", access: {read: owner}) do
  rows |> derive(columns: {price: formatNumber(amount, 2), day: formatDate(at, "dd/MM/yyyy")})
end
# @layout {"n":{"Result_rows":[null,null,null,null,"result"]}}
```
Text digests: hash(text) returns the lowercase 64-character hex SHA-256 of UTF-8 text; hmac(key, text) returns the lowercase hex HMAC-SHA-256 with a UTF-8 key and message. Null, wrong types and malformed Unicode return null without coercion. Each text argument uses the existing 262,144-character cap; oversized input visibly refuses and expression work/result budgets still apply. Both are deterministic in every expression and computed write.
```flow
flow 1
let rows = table(name: "rows", columns: {payload: text()})
view(name: "Result", access: {read: owner}) do
  rows |> derive(columns: {digest: hash(payload), signature: hmac("example-key", payload)})
end
# @layout {"n":{"Result_rows":[null,null,null,null,"result"]}}
```
Text encoding: base64Encode(text) returns standard padded Base64 of UTF-8 text; base64Decode(text) reads that spelling back into UTF-8 text. Missing padding, nonzero padding bits, whitespace, URL-safe Base64 and invalid UTF-8 return null. urlEncode(text) escapes one URL component (a space becomes %20); urlDecode(text) reverses percent escaping and preserves literal +. Malformed escapes, lone Unicode surrogates when encoding, and non-text/null inputs return null. Input and result text are bounded to 262,144 characters; exceeding the limit is a visible refusal. Existing expression and sandbox work budgets also apply. These deterministic calls work in every expression and computed write. Base64 is encoding, not encryption.
```flow
flow 1
let encoded = sample(dataset: orders)
  |> derive(columns: {base64: base64Encode("å😀"), decoded: base64Decode("w6Xwn5iA"), component: urlEncode("tea + cake"), restored: urlDecode("tea%20%2B%20cake")})
# @layout {"n":{"encoded_sample1":[null,null,null,null,"values",null,"85de4522"]}}
```
A named field at any depth can be omitted unless it declares required: true. The list itself can be required; a list can still be empty.
| Input or write | Effect |
|---|---|
| Absent optional field | No value was supplied. |
| Explicit null or empty text ("") | Refused when required: true; on an optional scalar input, leaves it unset on create and empty or null both clear on patch (json() stores null; list/object refuse null). |
| Form default | Supplies the form's initial value. |
| Field omitted from a patch | Keeps the stored value. |

dedupe(columns: [...]) keeps the first arriving row for each distinct combination. Sort the input first when the winner matters.

A checkout declares its currency. The amount is in the smallest currency unit, so this ticket costs EUR 15.

```flow
flow 1
let ticket = checkout(name: "ticket", productName: "Ticket", amount: 1500, currency: "eur")
```

JSON values: parseJson(text) reads JSON text into a list, object or scalar; invalid JSON or a non-text runtime input gives null. toJson(value) writes canonical JSON text with stable object-key order; toJson(null) gives the text "null", retaining false and zero. entries(object) returns its own [key, value] pairs in canonical order, preserving null, false and zero; other containers and scalars give null. Parsed values have an unknown shape; read members with existing access or get. These helpers reuse the structured-value limits (depth 16, 10,000 list items, 1,000 object fields, 262,144 text characters and 1 MiB canonical bytes), including the additional nesting of entries' result. parseJson also caps input at 1,048,576 characters. Unsafe keys, non-finite numbers and excessive values are refused, never converted into successful nulls.
```flow
flow 1
let json = sample(dataset: orders)
  |> derive(columns: {encoded: toJson({count: 0, active: false}), decoded: parseJson("false"), pairs: entries({ready: false})})
# @layout {"n":{"json_sample1":[null,null,null,null,"values",null,"85de4522"]}}
```
An insert line accepts rows: for a batch of rows instead of set:. For example, insert(table: reservations, rows: input.lines |> map(each: line => ({sku: line.sku, qty: line.qty}))). It reads declared input.<field> values and must produce 1–20 records; clocks, uuid() and random() must arrive through input so retries plan the same rows; every row is validated before any write starts. Literal strings in rows are quoted. rows: holds several rows; write one row with set:. A check that reads the table the batch goes into is written directly below the insert, where it sees the rows of the batch too; a refused check saves no row. The input list declares max: 20 or less. Nothing below a batch insert reads a row from it. The writes of a command save together when their tables are in the same database; a refused row then leaves every row unchanged. When they are in different databases, each write saves in turn and a refused row undoes the earlier writes in reverse order; an earlier write stays applied only when someone else changed its row in between. A patch can assign computed lists and objects. Every assignment reads the same stored row; the result must satisfy the target field schema and bounds, and a refused result writes nothing. Literal objects stay data, including an object with an expression key. Flow literals are escaped automatically in saved definitions.
```flow
flow 1
let result = request(
  fields: {
    lines: list(
      of: {sku: text(max: 2000, required: true), qty: number(required: true)},
      max: 20,
      required: true
    )
  }
)
  |> derive(columns: {lines: lines |> filter(where: qty > 0) |> derive(columns: {doubled: qty * 2}) |> sort(by: [sku]) |> select(columns: [sku, qty, doubled]), grouped: lines |> aggregate(groupBy: [sku], metrics: {qty: sum(column: qty)}), total: lines |> reduce(from: 0, each: (total, line) => total + line.qty)})
# @flow {"expectedOutput":{"targetNodeId":"result","columns":[{"name":"lines","type":"any"},{"name":"grouped","type":"any"},{"name":"total","type":"number"}]}}
# @layout {"n":{"result_request1":[null,null,null,null,"incoming",null,"839d528e"]}}
```

For a calculation that stores nothing, request supplies one row of caller inputs. On a released Request Flow, the invoke-v1 endpoint controls access and the declared output target answers the call. A saved view reads rows from a table or an App query.
```flow
flow 1
let quote = request(fields: {quantity: number(required: true)})
  |> derive(columns: {price: quantity * 9.5})
  |> select(columns: [price])
# @flow {"expectedOutput":{"targetNodeId":"quote","columns":[{"name":"price","type":"number"}]}}
```

```flow
flow 1
let lists = table(
  name: "lists",
  columns: {
    items: list(
      of: {id: text(max: 2000, required: true), done: checkbox(required: true)},
      max: 2,
      required: true
    ),
    edits: number(),
    payload: json(),
    echo: json(),
    state: object(
      of: {count: number(required: true), flags: list(of: checkbox(), max: 2, required: true)}
    )
  }
)
let toggle = command(
  inputs: {recordId: reference(table: lists), selected: text()},
  access: {call: signedIn, edits: [creator]}
) do
  let current = lists |> filter(where: id == input.recordId) |> one()
  patch(table: lists, recordId: input.recordId, set: {items: current.items |> map(each: entry => if(entry.id == input.selected, then: put(entry, "done", not entry.done), else: entry)), edits: current.edits + 1, state: {count: current.edits + 1, flags: current.items |> map(each: entry => entry.done)}, payload: {expression: "current.items"}, echo: {literal: {expression: "current.items"}}})
end
```

A named if block chooses a command's answer record (put each arm's record on its own line and finish with return reply):
```flow
flow 1
let orders = table(name: "orders", columns: {qty: number()})
let add_order = command(
  inputs: {qty: type(orders.qty)},
  outputs: {tier: text()},
  access: {call: owner}
) do
  let reply = if(input.qty > 10) do
    {tier: "bulk"}
  else
    {tier: "standard"}
  end
  insert(table: orders, set: {qty: input.qty})
  return reply
end
```
A table keeps columns: {title: text()}. A command declares inputs: {title: type(notes.title)} to follow the column’s type and limits, or inputs: {title: text(required: true)} to narrow them; inputs: {} accepts no request fields. A patch or delete declares the record id inside inputs:, inputs: {recordId: reference(table: tickets)} when it changes tickets; the page passes it in the call options, execute(input, {recordId}), never as an input field. A patch or delete command that is not owner-only adds edits: inside access:, e.g. access: {call: signedIn, edits: [creator]} (or [readers] or [roles("operator")]). Who may call a command is access: {call: owner}, signedIn, roles("manager"), app or public; a public command with a send, fetch, webSearch or ai step needs rateLimit: {per: visitor, max: 10, every: minute}. Add actorLabel: "Team lead" when How it works should show a different caller name than the role. `app`: whoever can open this App; its sharing and sign-in on the Publish page decide, so making the App public opens this to visitors. A view keeps access: {read: ...}. Every write names every value it sets; a column it leaves out takes its defaultValue:. Write a local value as set: {tier: tier}. Name row columns as input.title or price.amount. In set:, the printer lists assigned inputs in header order, then the other assignments. Declare each caller value in inputs:; a temporary input such as code: text() can be read as input.code without storing it and needs its own name, distinct from table columns. Write patch(table: tickets, recordId: input.recordId, set: {status: "closed"}). set: accepts expressions on insert and patch, including input.qty, price.amount, actor.email, now(), today() and current.edits + 1 after let current = tickets |> filter(where: id == input.recordId) |> one(). A write reads rows it names (insert(table: quotes, set: {amount: price.amount})); zero or multiple rows refuse the call. A local value uses let clean = lower(trim(input.email)) and later lines read clean or {{clean}}. Choose between two values with if(condition, then: a, else: b), in a let line or inside set:, e.g. set: {size: if(input.qty >= 10, then: "bulk", else: "single")}. An if(...) do ... end block holds lines, not a value, and a write stands outside it. A command body runs top to bottom. A let that reads a row or computes a value stands above the check lines: those lets run first, then the checks with the write. A check on a row a let read is checked again when the write saves, so a change made in between is caught. In one database the checks and every insert and patch line save together or not at all, so a failing check, above or below the write, refuses the command and leaves every table unchanged. Across databases each write saves in turn, where other readers can see it; a later write that fails or a check that refuses undoes the earlier ones in reverse order, and an earlier write stays only when someone else changed its row in between. Sends (email, slack, discord, sendHttp) run after the transaction commits, and a failed send never undoes the write. Build text in set:, rows:, a let line or a send from inputs, a read row or an earlier let ("Ordered {{input.qty}} of {{input.sku}}"); bare {{...}} is refused in every condition, calculated column, check message, answer record and larger expression (write sku == input.x for a value, or string("{{x}}") for that text as written). Command reads apply the caller’s row access; a reference table with access: {rows: [creator], commands: read} lets commands read every row. A filtered read such as let product = products |> filter(where: sku == input.sku) |> one() requires exactly one match; check(product.stock >= input.qty, message: "Out of stock") rechecks that row in the write transaction. A request check such as check(input.qty > 0, message: "Enter a quantity") runs with a single insert or patch. A local let may repeat an input name (read as input.<name>), never a table, view, command, reserved name or column read bare in a condition. On a table row, id, createdAt and updatedAt are built-in metadata; do not add columns with those names to columns: (use another name such as code or openedAt). Declare answers in outputs: {title: type(tickets.title), status: type(tickets.status)}, with id: reference(table: tickets) for a returned id and datetime() for timestamps (kind only, no input constraints). Write return saved (after let saved = ...) only when the header declares outputs:; omit return without outputs:, and only record id and version answer. With several writes, a command answers with one of them, in this order: its patch on input.recordId if it has one; else the write a final return <name> names (outputs: {} when no column should leave); else its first write. A stock change is never the answer: the one write beside it is. Lines below the writes read only the answering row. A command always writes a table; for a read-only calculation, use let quote = request(fields: {quantity: number(required: true)}) |> derive(columns: {price: quantity * 9.5}) |> select(columns: [price]). A named if block chooses the answer record (each arm ends with its record on its own line, then return reply). To change a stock number on one table beside an insert or patch on another, read the row, check that enough is left when lowering, patch the stock column, and write the other row (both run together). outputs: also maps JSON paths on fetch and sendHttp ({rate: "data.rate", tracking}) or checks JSON types ({amount: number(path: "price.amount"), currency: text()}). Numeric text needs number(...) before math or numeric comparison; invalid math yields null; + joins two texts with no implicit number conversion.
Shared team data: A view filter cannot read actor.id or actor.email. For per-person rows, set access: {rows: [creator]} (or {person: member} or {email: member_email}) on the table and access: {read: signedIn} on the view; use access: {rows: [signedIn]} for shared team rows. Restrict the App's audience to invited people for a private team.
For live team access, propose the invited emails with apply {appId, invite: {emails: [...]}, idempotencyKey: <new key>} and show the owner the approval link; publish again after approval. let login = signin(draft: true) is draft-only. People with access sign in with a code Wrapflow emails them, sent by the platform rather than the App; avoid silently narrowing the App to the owner. People with access and readers whose access depends on a verified email need a Wrapflow sign-in email on their first visit, even with password sign-in. This is platform account mail, separate from messages the App sends. If asked for "no email" or "no outside messages", do not stop before building: build the draft, note this email, and ask "This cannot be done without a sign-in email. Do you accept that?" at request_release. Keep the requested audience; never switch it to avoid asking.
Calendar dates and weekday rule: use one zone for date stamps, filters and page labels. Read the App's timeZone in describe, status or list_apps; if null, ask the person you are building for and save it with ship_app {timeZone} or apply {appId, appTimeZone}. If nobody can answer, leave it null, use UTC and say so in your final message; never guess a zone. today() is the UTC date and today("Europe/Stockholm") is the date in that zone. For a local calendar action, replace Europe/Stockholm with that saved zone and compute the date on the server before the write:
```flow
flow 1
let events = table(name: "events", columns: {event_day: date()})
let record_day = command(name: "record-day", inputs: {}, access: {call: owner}) do
  let local_day = today("Europe/Stockholm")
  insert(table: events, set: {event_day: local_day})
end
```
A command can reject past dates and closed weekdays on the server, independently of a page or a capacity guard. Check the requested date above the write:
```flow
flow 1
let bookings = table(name: "bookings", columns: {day: date(required: true)})
let book = command(inputs: {day: type(bookings.day)}, access: {call: owner}) do
  check(
    input.day >= today("Europe/Stockholm") and weekday(input.day) != "Saturday" and weekday(input.day) != "Sunday",
    message: "Choose today or a later weekday."
  )
  insert(table: bookings, set: {day: input.day})
end
```
input.day >= today("Europe/Stockholm") accepts today in the App's zone and later dates. Replace the example zone with the App's saved timeZone; the clock comes from the server, never the caller. This protects direct calls; a page's minimum date cannot. Keep the slot capacity check separate. Test yesterday, today and a later weekday near local midnight in winter and summer. weekday(input.day) names the weekday of the supplied calendar day; it does not convert an instant into the App's timeZone. To open Saturday later, remove its inequality and test that updated command. A weekday rule does not enforce a per-day hours range; do not promise hours that the command does not check.
The page computes its current calendar date with Intl.DateTimeFormat and that same timeZone (formatToParts gives year, month and day). Keep a stored YYYY-MM-DD as a calendar day; converting its UTC midnight to the browser's zone can change the displayed date. Compare calendar-day ordinals, Date.UTC(year, month - 1, day) / 86400000, rather than elapsed local-midnight milliseconds across daylight-saving changes. Do not mix a UTC stamp or toISOString().slice(0, 10) with a browser-local date.
Choose initial state from the prompt. Creating a record does not mean its tracked action happened: leave unreported action dates and completion state unknown unless creation explicitly performs that action. Stamp creation separately. Show the unknown state honestly and let the person record or correct the event; do not invent a past action to fill a required field. Never use creation or today as a missing action date: a never-done recurring action is due now unless the prompt gives a start date.
Elapsed time: addHours(d, n) and addMinutes(d, n) return a UTC ISO datetime, preserving seconds and milliseconds. A date starts at UTC midnight. addMinutes takes whole minutes; addHours may be fractional when it resolves to whole minutes (1.5 means 90 minutes). They measure elapsed time, independent of daylight-saving transitions. Invalid dates, nonnumeric/null offsets, fractional minutes and results outside years 0000–9999 return null. The same calls work in ordinary expressions, computed writes, transition rules and closed saved-view or guard values; a clock-dependent view advances its cutoff on every read.
```flow
flow 1
let reminders = sample(dataset: orders)
  |> derive(columns: {reminder: addMinutes(addHours("2026-11-10T10:00:00Z", 1.5), -15)})
# @layout {"n":{"reminders_sample1":[null,null,null,null,"orders",null,"85de4522"]}}
```
Command windows:
Check the stored event before accepting a reservation. The caller sends the event code. The App reads the event and uses its own clock to check that the start is at least two hours away.
```flow
flow 1
let events = table(
  name: "events",
  key: [code],
  columns: {code: text(required: true), starts_at: datetime(required: true)}
)
let reservations = table(
  name: "reservations",
  columns: {event: text(required: true), guest: text(required: true)}
)
let reserve_event = command(
  name: "reserve-event",
  inputs: {event: type(reservations.event), guest: type(reservations.guest)},
  access: {call: owner}
) do
  check(
    count(table: events, where: code == input.event and starts_at >= addHours(now(), 2)) >= 1,
    message: "Reservations close two hours before the event."
  )
  insert(table: reservations, set: {event: input.event, guest: input.guest})
end
```
Read an uploaded file with rows |> readDocument(fileColumn: receipt): PDF, Word, Excel, CSV, text, Markdown or HTML, up to 10 MiB per file and 300 PDF pages; one run reads at most 20 MB of files in total. PDF text is limited to 8 MiB. Default mode text adds text, pages, title, language, has_text (false for a scanned PDF); mode: rows (CSV or Excel, optional sheet) emits one row per parsed row. No OCR, no AI credits.
Write rows from a Flow: a Flow writes the rows it fetched or computed into its own table through one of its commands. rows |> appCommand(command: add_reading, inputs: {station, temp}) runs that command once per row (a patch or delete adds recordId: <the column that holds the row id>) and answers with one outcome row per call, which a later step can aggregate or email. status is completed, refused (code and error say why, nothing was saved and the run goes on) or held (a draft run). Give the table a key so a row that arrives again, in any order, is written once; add onExisting: <patch command> to change the row the table already holds (an upsert), otherwise that row is refused. A schedule or another Flow runs appCommand as the App owner, so give its command access: {call: owner}. A Flow cannot supply an App role or run a command on a table shared with a command whose audience includes other people. app: "<appId>", command: "<name>" runs another App's command.
One App shares another's table with from: "<sourceAppId>/<entity>". On the source, list the reader App in that table's readers: apply {appId: "<sourceAppId>", grantReader: {appId: "<readerAppId>", table: "rooms"}} writes the readers (and optional columns) argument itself and revokeReader removes one — no Flow text edit for the grant — or write readers: ["<readerAppId>"] on the source table directly; in the reader, let rooms = table(name: "rooms", from: "<sourceAppId>/rooms") takes its fields. Release is required only for live use; publish the source App at /apps/<sourceAppId>?tab=publish. Drafts can share before release: the reader's draft reads the source draft's rows.
Read the App's members: appMembers(statuses: [active, invited]) answers the people on the App's Access list, including invited emails before they sign in, one row each with email, name (their email when they gave none), role, status (invited or active) and last_signed_in_at; appMembers(statuses: [active]) reads only those who have signed in. The account owner's row has role "owner"; other rows keep their assigned App role. Signing in or opening an owner draft preview adds an active owner entry. Exclude the owner's email when the list means the invited team. Use it instead of a roster table, so a reminder follows the people the owner invites. Member emails stay the owner's: those rows can feed filter, join, aggregate, email, alert and sendHttp steps. To show members or a calculation such as who has not posted in the App, bind the appMembers(statuses: [active, invited]) result or the calculation with let and declare view(name: "missing-members", access: {read: owner}) do, then missing |> select(columns: [email, name]), then end. The server admits only the account owner, never an App role named owner. A public or member view, an unguarded result, or saving those rows in a table, chart, file, appCommand or another Flow is refused with app_members_not_owner_only. Email everyone who has not checked in today; replace the example zone with the App's saved timeZone (read timeZone from describe, status or list_apps; if null, ask the owner and save it with ship_app {timeZone} or apply {appId, appTimeZone}):
```flow
flow 1
let checkins = table(name: "checkins", columns: {day: date(), email: email()})
let today_checkins = checkins |> filter(where: day == today("Europe/Stockholm"))
appMembers(statuses: [active, invited])
  |> join(right: today_checkins, type: anti, on: {left: email, right: email}, rightDedupe: none)
  |> email(fanOut: {recipientColumn: email}, subject: "Check in by 10:00", body: "Hi {{name}}, we have not heard from you today.", attachment: false)
# @layout {"n":{"_effect_1_appMembers1":[1,null,null,null,"members",null,"5465b825"],"today_checkins":[2],"_effect_1_join1":[null,null,null,null,"missing",null,"2cca5843"],"_effect_1":[null,null,null,null,"remind"]}}
```
updatedAt is display-only; keep exported layout and metadata. Publish uses the existing owner approval.
Write `flow 1`. Command steps run in authored order under one resource budget and replay contract, with or without a transform. A retry key cannot switch programs: finish its original invocation, and use a new key after changing the command. Other Flow version headers are refused.
A text field holds up to 500,000 characters in one value (`max:` sets its limit; the default is 2,000), so write long text whole and never split it across fields. Above 10,000 characters a field is long text: lists and queries omit it unless `select` names it, and it cannot be unique, filtered, sorted or searched. One table's long text fields declare at most 500,000 characters together.
App backends cannot contain showTable or other display steps. End with a data step such as aggregate, join or limit; present results in the frontend through the App Contract.
For 'this month', declare the date field as date and filter dynamically at read time using the App's saved timeZone (read timeZone in describe, status or list_apps; if null, ask the owner and save it with ship_app {timeZone} or apply {appId, appTimeZone}). Replace Europe/Stockholm with that zone: records |> filter(where: left(date, 7) == left(today("Europe/Stockholm"), 7)). This date filter and the following aggregate also work on tables larger than the in-memory row cap. A hard-coded year-month becomes stale. Derive status inclusion from the individual App request; preserve requested total submissions, pending exposure, rejected totals, or approved-only totals. If the subset is ambiguous, clarify which statuses count and state it in the App. Only for explicitly requested approved-only totals, use records |> filter(where: left(date, 7) == left(today("Europe/Stockholm"), 7) and status == "approved"); add a scenario with approved, rejected, pending, and next-month rows.
Conditions are expressions everywhere: a filter where, a view filter(where:) and the where of a check. Read the row a patch changes with let current = orders |> filter(where: id == input.recordId) |> one(). Expression operators: == != < <= > >=, joined with and / or (parentheses group). Writing let n = count(table: guests) or let total = sum(table: bookings, column: seats) reads a snapshot before the write, so two callers at once can see the same value in set: or if(...). Put the count directly in check(count(table: guests) < 40, message: "Full") to enforce the limit in the write transaction against concurrent callers. A row read with let found = T |> filter(where: ...) |> one() that a check reads (check(found.seats >= 1, ...)) is checked again inside the write; a check on a value computed from it on another let line (let left = found.seats - input.n, check(left >= 0, ...)) compares what was read before the write, so write the comparison in the check itself. A count or sum check names its table and refusal message; a request or current-row check such as check(input.qty > 0, message: "Enter a quantity") needs no table. Above the write, check(count(table: signups, where: shift == input.shift) < 4, message: "Full") counts stored rows; below the write, <= 4 includes the proposed row. Both refuse the command without saving. Use sum(table: bookings, column: seats, where: day == input.day) to total a field. Request rules run before rows are counted. Compare with <, <=, ==, > or >= and a number. References: a field by name; a param(...) name (in top-level let steps, not a view body); input.x (view or command input); now(), today(), monthStart(), monthEnd(), weekStart(), weekEnd() (Monday to Sunday, UTC; a whole week is field >= weekStart() and field <= weekEnd()); field == null matches absent values, and a whole month is field >= monthStart() and field <= monthEnd(); offset a clock with addDays(now(), -7), addHours(now(), -2) or addMinutes(now(), -30) (not now() - 7 days). view(name: "mine", inputs: {vis: text()}, access: {read: signedIn}) do visits |> filter(where: visitor == input.vis and sentAt < now()) end; a write rate limit is rateLimit: {per: visitor, max: 200, every: day} on the command (per: visitor, person, owner, everyone or a field; every: minute, hour, day, "6h" or "30s"; several allowed, each with message:). check(current.state == "open", message: "Must be open"); view(name: "open-orders", access: {read: owner}) do orders |> filter(where: status == "open") |> select(columns: [id]) end. Saved views and checks accept or across comparisons (and binds tighter than or; parentheses group; at most six comparisons after grouping): status == "open" or score > 3 (related-row alternatives remain unsupported in views). Checks also accept closed dates, clocks, inputs, caller values and earlier step outputs in alternatives (where: status == "held" or sent_at >= addDays(now(), -1); status == "held" or quantity >= input.quantity; owner == actor.id or quantity >= price.quantity; every referenced input/output must be available). A view accepts whole-day clock arithmetic: due >= addDays(today(), -6), evaluated on every read (clock views poll). Views and checks may negate parenthesised equality groups, such as not (status == "open" or tier != "gold"); not status == "open" is refused. Negated ordering, in, contains, row arithmetic, me and duration-unit clock offsets are refused. A page text search is not a view filter: contains(...) and count(...) over a field are refused there, and a filter of `count(name, input.search) > 0 or input.search == ""` never saves. Write the view without the text match (view(name: "products", access: {read: public}) do products |> select(columns: [id, name]) end) and pass the words on the read as `search: {text: <words>, fields: [name]}`; the search ignores case and matches a substring (not on aggregated views or long text); omit `search` when the box is empty, because an empty or whitespace-only text is refused with 400. To refuse a repeat of a value, put the field in the table `key:` (for example key: [email]) instead of a check(count(...) < 1) over the same table; a create that repeats the key is refused 409 with code stable_key_conflict. A command cutoff uses addMinutes or addHours: check(current.starts_at >= addMinutes(now(), 1440), message: "Too late.") checks the stored row, and check(input.starts_at >= addMinutes(now(), 1440), message: "Too late.") checks a new time; on a related table, check(count(table: classes, where: class_code == input.class_code and starts_at >= addMinutes(now(), 240)) >= 1, message: "Booking closed."). Conditions are unquoted boolean expressions: write where: score > 0, never where: "score > 0".
Write every condition as an unquoted expression: where: status == "open" or check(input.qty > 0, message: "..."). where: rows(...) and where: [{field: status, op: eq, value: "open"}] are refused. A quoted value inside a condition is fine: where: status == "open".
In Flow 1 a null or missing value is decided by the comparison itself, wherever the condition is written: `field != value` keeps it, `field == value` and the ordering comparisons (`<`, `<=`, `>`, `>=`) do not, and `field == null` matches it. A filter drops every row whose condition is not true, so name the null case on its own (`field == null`) when such a row must stay. Omitting the `flow 1` header does not change this rule.
An AI step names the columns it adds. Write input |> ai(instruction: "Read the receipt.", attachment: photo, outputs: {amount: number(), purchasedOn: text()}). In a command, bind the result and save its fields with set:. A validate step declares outputs: {valid: checkbox(), rejections: text()}. Failed rules are JSON-encoded text. A saved scenario is a statement: scenario(name: "check-notes") do ... end. Lines run in order on private rows. Before the first operation, seed(table: notes, set: {title: "A"}). Bind a seed to pass its .id to recordId or a reference field. A keyed seed uses its key, and the first unkeyed row has ID seed-<entity>-1. Write let answer = call(command: add_note, as: anonymous, inputs: {title: "B"}), then expect(answer.record.title == "B"). A command that ends with return saved, the row it wrote, answers under .record, for a scenario and for a page alike: expect(answer.record.status == "pending"). let reply = if(...) do {...} else {...} end with return reply sets .response and .outcome. An ordinary unkeyed create can pass answer.recordId to a later ID input for that table. A bare call or read must succeed. Wrap one operation in expectRefusal(status: 409, code: "command_precondition") do ... end to check a refusal; a check: that fails is 409 command_precondition, while an input that is empty, missing or the wrong type is 422 invalid_command_input. Every call and read names its caller: anonymous, owner or signedIn(user: "ada@test", roles: ["manager"]). A read uses read(view: all_notes, as: owner) and optional inputs. Check its total with ==, >= or <=, its ordered .items or .groups with expectRows or expectGroups and inOrder: (comparing only the columns listed), or its .items with expectEach or expectSome and matches:. A calculated read has .result.table.rows. Put each expect directly below its operation. setClock(now: "2026-03-01T09:00:00Z") moves simulated time. recordAnswer(step: book.price, value: {amount: 12}) supplies the next call of book with the named step’s answer. Requirement scenarios generate steps from requirement: {class: capacityByGroup|relativeTime|actorOwnership, statement: "...", ...} (complete saving examples are in the reference under "Requirement scenario examples"). A status that moves in steps is an enum column with a default, status: enum(options: ["pending", "approved", "rejected"], defaultValue: "pending"), and each move is a patch command. Its header is inputs: {recordId: reference(table: claims), decision: enum(required: true, options: ["approved", "rejected"])} and access: {call: roles("manager"), edits: [roles("manager")]}. Its body reads the row with let current = claims |> filter(where: id == input.recordId) |> one(), refuses a wrong starting status with check(current.status == "pending", message: "Only a pending claim can be decided"), and writes patch(table: claims, recordId: input.recordId, set: {status: input.decision}). decision is an input with its own type, so a call with another value is refused. The check is enforced with the write. An insert that leaves status out of set: starts the row at the default. The column does not list the allowed moves: status changes wherever a set: writes it, so the commands that write it are the moves. Persistence still needs an explicit saved scenario journey; sequential checks do not cover concurrent requests or browser reloads.
Parameters: a Flow's tunable assumptions are declared as statements.
- View inputs: declare inputs: {start: date()} in the header (allowed types: text(), number(), checkbox(), date()) and use filter(where: day >= input.start) in the body. The wire field is params. Send {params: {start: "2026-01-15"}} when reading the view. Every date parameter is required and must be a real YYYY-MM-DD calendar date; timestamps and impossible dates are refused. A date field needs a date parameter, not text; datetime fields cannot use view parameters.
- A parameter is a name, a kind and a default: let limit = param(kind: number(), default: 10), let label = param(kind: text(), default: "Untitled"), let status = param(kind: enum(options: ["new", "done"]), default: "new"). A checkbox uses checkbox() and a duration uses duration(). Put enum choices, number bounds and text length inside the type call, as in number(min: 1, max: 20) or text(max: 80). Every parameter declares its default:.
- Define a parameter above its use and read its name in expressions: filter(where: score > limit). When a column shares the name, write col("limit") or param.limit; over input, write input.limit or param.limit. The clock inputs are $runDate and $runDatetime.
- A type call can also set its label. A parameter can declare id, range, step, exposed, checks and a saved value that differs from its default.

Example:

```flow
flow 1
let habits = table(name: "habits", label: "Habits", columns: {habit: text(required: true, max: 80)})
let entries = table(name: "entries", label: "Entries", columns: {habit: text(), score: number()})
let kept = entries
  |> filter(where: score > 0)
  |> aggregate(groupBy: [habit], metrics: {total: sum(column: score)})
view(name: "Result", access: {read: owner}) do
  habits
    |> join(right: kept, type: left, on: {left: habit, right: habit}, columns: [total], rightDedupe: none)
    |> limit(count: 100)
end
# @layout {"n":{"Result_rows_join1":[null,null,null,null,"result_join1",null,"38c755d6"],"Result_rows":[null,null,null,null,"result"]}}
```

Sequential action:

```flow
flow 1
let products = table(name: "products", columns: {sku: text(), stock: number()})
let orders = table(name: "orders", columns: {sku: text(), qty: number(), status: text()})
let audit = table(name: "audit", columns: {what: text()})
let place_order = command(
  inputs: {sku: text(required: true), qty: number(required: true)},
  outputs: {sku: type(orders.sku), qty: type(orders.qty), status: type(orders.status)},
  access: {call: public},
  rateLimit: {per: visitor, max: 10, every: minute}
) do
  check(
    count(table: products, where: sku == input.sku and stock >= input.qty) >= 1,
    message: "Out of stock"
  )
  let order = insert(table: orders, set: {sku: input.sku, qty: input.qty, status: "placed"})
  insert(table: audit, set: {what: "Ordered {{input.qty}} of {{input.sku}}"})
  if(order.qty > 100) do
    slack(channel: "C08ABCD1234", body: "Large order {{order.sku}}", connectionId: "conn_1")
  else
    email(to: ["ops@example.test"], subject: "Order {{order.sku}}", body: "Wrapflow update.")
  end
  return order
end
```
<!-- flow-authoring:end -->

```sh
# Create an empty App. Your AI defines the backend and uploads the UI.
node ./node_modules/@wrapflow/cli/wf.mjs app create "<name>" --frontend external

# Keep the returned App ID. Inspect returns frontendLane, frontendRevision,
# and frontendUpdatedAt without returning the saved handoff HTML.
node ./node_modules/@wrapflow/cli/wf.mjs app operations inspect <app-id>
node ./node_modules/@wrapflow/cli/wf.mjs app integration contract <app-id>

# External App-owned project (the default for frameworks or mature UI libraries).
node ./node_modules/@wrapflow/cli/wf.mjs app integration client <app-id> --file src/wrapflow.generated.ts

# Change the backend through describe/apply/test (see the flow-authoring path
# above), then regenerate the client from the updated App Contract.
# Edit an external frontend in its own project; see Hosted HTML convenience
# below for revision-guarded changes to a hosted single-file frontend.

# Review and resolve every fixture target before proof.
node ./node_modules/@wrapflow/cli/wf.mjs app operations fixtures <app-id>
# If required: node ./node_modules/@wrapflow/cli/wf.mjs app operations fixtures decide <app-id> --request-id <id> \
#   --decision <clear|promote> --target 'flow-id|collection-id|fixture-v2:…'

# Capability preflight: do not run proof until this read succeeds. This read
# requires an admin-scope token; the read+run+draft token `wf login` mints
# is rejected with 403 for the missing admin permission, and
# the correct response then is to stop with the App as a draft.
node ./node_modules/@wrapflow/cli/wf.mjs app publish <app-id> > release-preflight.json
# Stop at the draft unless proofStartAvailable is true, both an authorized
# publishing path and a present operator are available, and that operator reviewed the
# complete exposure block (anonymous/authenticated resources, authentication,
# Checkout, and files).

# Start one empirical Browser proof. Keep the returned proofId and attemptId.
node ./node_modules/@wrapflow/cli/wf.mjs app publish <app-id> --checks --request-id <idempotency-key> --reviewed-exposure --reviewed-authority-digest <reviewDigest>
# Use reviewDigest from the exact release-preflight.json snapshot the operator
# reviewed. If it changes, present the new snapshot for fresh review; never
# silently substitute a newly fetched digest.
# The CLI re-reads and displays current authority before either start or retry,
# then stops unless checksAvailable is still true, the acknowledgement is
# present, and the reviewed digest still matches.

# Poll until that exact proofId is eligible, then save and review the same
# authority snapshot. The status command reports hosting, not proof status.
node ./node_modules/@wrapflow/cli/wf.mjs app publish <app-id> > release-review.json

# Present the current exposure block to the operator again. Construct and
# explicitly approve the complete AppReleaseRequestV2:
# requestKey, slug, expectedFrontendRevision, expectedLiveDeploymentId,
# expectedContract, expectedDraftIdentity, empiricalProofId,
# fixtureDecisionReceipts, dataMigrationPlanHash, reviewedAuthorityDigest.
# Copy expectedDraftIdentity from draftIdentity and reviewedAuthorityDigest
# from reviewDigest in that exact reviewed release-review.json snapshot.
# Save that request as release-authority.json;
# release-review.json is evidence input, not the request. If authority, proof,
# operator review, or publishing becomes unavailable, stop at the draft.
node ./node_modules/@wrapflow/cli/wf.mjs app publish <app-id> --authority release-authority.json

# Confirm the resulting hosted deployment only after release.
node ./node_modules/@wrapflow/cli/wf.mjs app status <app-id>
```

Wrapflow does not design the App. Define the backend with the flow-authoring path above, then upload the UI. Ask the user only when the answer changes product scope, permissions, money movement, identity, or public release behavior.

Use the latest frontend revision returned by inspect or save. A stale revision is a
real concurrency conflict: re-inspect, reconcile the other edit, and retry. Do
not overwrite it blindly.

## Uploaded UI bundle

The default MCP App uses external frontend authority and can host its UI files
on Wrapflow. Upload a plain HTML/CSS/JavaScript bundle with
`ship_app {appId, idempotencyKey, ui:{files:[…]}}` or `upload_app_ui`. In
`index.html`, import the App's same-origin client and use only resource names
returned by `describe {appId, kind:"ui"}`:

```html
<script type="module">
  import { WrapflowApp } from '/_wrapflow/client.mjs'
  const app = await WrapflowApp.connect()
  const page = await app.view('requests').query()
</script>
```

Relative CSS, JavaScript, images, and fonts may accompany the page. Test reads
and writes through `test`, `look`, and saved-state browser checks before
requesting the owner review link. This uploaded bundle is distinct from both a
separately hosted framework project and the hosted lane below.

## Hosted interface

Direct hosted-HTML saves were removed: `PUT /api/apps/:id/frontend` refuses with
`hosted_frontend_requires_project`, and there is no `wf app save` or
`saveAppFrontend`. A hosted App's interface is a TypeScript project edited in
the Studio or rebuilt by Chat. `wf advanced get <app-id> --file index.html` still
reads the compiled document. To ship a hand-authored page, use the uploaded UI
bundle lane above.

## Default MCP loop

Connect to `https://wrapflow.com/mcp` and read `tools/list`. This endpoint
lists 17 tools, including `ship_app`, `describe`, `apply`, `upload_app_ui`,
`test`, `look`, `request_release`, `status`, and `call_command`; it does not list
`build_app`, `edit_app`, `create_app`, `define`, `inspect_app`,
`get_app_contract`, or `generate_app_client`.
Write the Flow text and frontend yourself; `ship_app` is not an AI prompt builder.

1. For a new App, call `ship_app` with `name`, `flow` (native Flow text), and
   a caller-owned `idempotencyKey` of 8–200 characters. Supply saved `scenarios`
   and `ui: {files: [{path, content}]}` when ready. The uploaded page may use
   JavaScript and relative assets; import `WrapflowApp` from
   `/_wrapflow/client.mjs`. Keep the returned `appId`. Retry identical
   arguments with the same key; use a new key for each change.
2. Call `describe {appId}` for the saved source, revisions and typed Contract;
   `describe {appId, kind:"contract"}` selects the Contract alone. Follow a
   paged response with `describe {cursor: metadata.nextPage.arguments.cursor}`.
   Use the returned client/spec URLs for the frontend integration.
3. For a backend edit, read `describe {pipelineId, kind:"flow"}`, edit the
   text, then call `apply {pipelineId, text, expectedRevision: revision.id}`.
   For a UI upload, including the first, pass `upload_app_ui` the
   `expectedFrontendRevision` from `describe {appId, kind:"ui"}` or the last
   upload result and an `idempotencyKey` (reuse it for identical retries; use a
   new key for a changed upload). Or use `ship_app {appId, idempotencyKey,
   ui:{files:[…]}}`; omit `flow`/`text`
   and scenarios to retain the existing backend and examples.
4. Run `test {pipelineId, kind:"scenario", scenario:{}}` for saved examples.
   Exercise the main frontend journey with `ship_app` browser `checks` or
   `journeys`; for writes, include `expectSaved` to verify persisted records.
   Use `look {appId}` to inspect the real draft. Follow the returned `next`:
   repair failures and resume `ship_app` with the same `appId` and a new
   `idempotencyKey` as directed. A bare page load or `backend_ready` does not
   prove the frontend works. Interactive checks can write draft Test data;
   inspect those rows before entering customer data.
5. Only after `ship_app` reports `status: "ready"` and its `next` calls
   `request_release`, call `request_release {appId}` for the owner approval
   path, then poll `status {appId}`. Report publication only when it says
   the deployment is live. If the owner gave your connection a standing
   release approval that covers the App, `request_release` runs the release
   checks and publishes instead; follow its `next` (call it again while the
   checks run). Anything the approval does not cover still returns the
   owner's link. When the customer asked for a public link, pass
   `audience: "public"`: publishing never widens access, so the reply says
   the App is not public yet and hands the owner the approval link with
   Public already selected; `status {appId, audience: "public"}` confirms.

## Advanced MCP loop

Use these product-level tools when Wrapflow MCP is the available authoring
surface. `/mcp` lists 17 tools, led by `ship_app` and including
`upload_app_ui` and `call_command`; the tools named below
that it does not list are on `/mcp/advanced` (`WRAPFLOW_MCP_PROFILE=advanced`
for `wf app integration mcp`):

1. `inspect_app` to choose an existing Flow. For a new App, `create_app` with
   `name` and optional `description` initializes its external frontend and returns
   `appId`, `flowId`, and `revision`.
2. `describe` with `kind: "flow"` and the Flow's `pipelineId`; keep the text
   and `revision.id`.
3. Edit the text and `apply` with `pipelineId`, `text`, and
   `expectedRevision: revision.id`. Keep layout/metadata and unrelated calls.
4. `test` with `kind: "scenario", scenario: {}`; then try the draft in its UI.
5. `inspect_app` with `section: "contract"`, then `generate_app_client` for
   the uploaded external frontend. Read `section: "ui"` before each upload.
6. Re-read `describe kind:"flow"` before the next edit.
7. `inspect_app` with `section: "fixtures"`, plus `decide_app_fixtures` for
   every required target.
8. Call `get_app_release_authority` as a capability preflight. Stop at the
   draft if authority is unavailable, `proofStartAvailable` is not `true`, or
   an authorized `publish` path and present operator are not
   available. Present its complete `exposure` block to that operator.
9. Only after that presentation, call `start_app_proof` with
   `{appId, requestKey: "<idempotency-key>", operation: "start", operatorReviewedExposure: true, reviewedAuthorityDigest: "<reviewDigest>"}`.
   Copy `reviewDigest` from that exact operator-reviewed authority snapshot.
   For a retry, use `operation: "retry"` and `retryOfProofId: "<proof-id>"`.
   The tool re-reads authority and stops unless `checksAvailable` is still
   `true` and the digest matches. If the snapshot changes, obtain fresh review;
   never silently replace the reviewed digest.
   Retain its exact proof and attempt IDs, then wait for that protected attempt
   to pass.
10. Poll `get_app_release_authority` for that exact proof ID. Present its current
    `exposure` again, review exact exercised interactions and every proof-runner
    capability boundary, then construct the exact AppReleaseRequestV2.
    Coverage v1 proves the hosted document; external coverage v2 proves only
    the deterministic backend Contract harness and explicitly reports
    `externalFrontendExercised: false`. Eligibility is scoped, not a claim of
    complete product coverage.
11. Only after the present operator explicitly approves that exact request and
    exposure, call `publish` with `appId`, all ten fields of the request above,
    and `operatorReviewedExposure: true`. Stop at the draft if any required
    capability becomes unavailable.

The eligible authority is scoped evidence, not a blanket pass. Review every
`coverage.exercisedInteractions` row and limitation. An eligible anonymous,
directly writable scalar entity can add `entity-lifecycle`, which exercises
create, exact readback, CAS patch, stale rejection, transaction commit and
rollback, wrong-owner denial, delete, and final absence in one isolated Browser
session. It names the exact entity only. `partial-entity-mutation-coverage`
means replace or another entity's mutations were not exercised, and
`no-anonymous-ownership-lifecycle` remains because the draft proof capability
does not prove production visitor cookie/token issuance. Proof evidence has no
slot for record IDs, capabilities, cookies, request bodies, or generated values.

Use `inspect_app` with `section: "frontend"` and `update_app_frontend` only for the hosted single-file
lane. Do not claim a separately hosted frontend is hosted by Wrapflow; only an
uploaded UI bundle is served from the App's Wrapflow origin.

Write replies answer in a few KB: whether the change saved, the new revision,
a short summary, any refusal, and the exact call for each larger body. They
never inline the interface HTML. Call `inspect_app` with `section: "frontend"`
for the HTML (large bodies page through `get_result_page`) and
`describe kind:"flow"` for the Flow text, or `inspect_app` for structure.

For exact backend changes, read the Flow text with `describe kind:"flow"`,
edit it, save it with `apply {text, expectedRevision}`, and check it with `test`.
For one typed entity or command, `describe` returns its exact JSON schema,
`test` preflights it without saving, and `define` writes that object. These
operations spend no credits.

## Deterministic authoring order

Create the App, initialize its backend if empty, then follow the Flow-text path:

1. MCP `create_app` with `name`, a short `purpose` sentence, and optional `description` /
   `node ./node_modules/@wrapflow/cli/wf.mjs app create "<name>" --frontend external`
   — an AI-free App container with external frontend authority initialized at
   revision 1. MCP initializes the external frontend automatically. Keep the
   returned App id and inspect the App for its lane and revision. SDK/HTTP
   creation and the CLI also support an explicit `hosted-single-file`, which
   starts with no saved page until its first hosted document is uploaded.
2. `create_app` (or `POST /api/apps`) atomically creates the App and its initial blank
   Flow, returning `appId`, `flowId`, and `revision`; use the returned `flowId`. An
   additional member can be created with `POST /api/apps/<app-id>/flows` (which adopts
   the initial blank Flow if it remains untouched), but describe never creates one.
3. `describe kind:"flow"`, edit text, `apply {text, expectedRevision}`, then
   `test` saved scenarios and try the draft. A single typed object can still
   be defined using the schema returned by describe.

`define` is App-aware: the command, spec, and returned definition are identical
either way, but on an App-owned Flow it persists only backend steps
(`source.collection`, `output.edits`), while on a standalone Flow it also
persists the legacy Flow-canvas presentation steps `output.input` and
`output.table`.

That is why the order is not interchangeable. `wf advanced create --empty` makes a
*standalone* Flow, so defining an entity on it writes presentation steps, and
attaching it to an App afterwards
(`PUT /api/apps/<app-id>/flows/<flow-id>`) then fails with `409`
`app_backend_presentation_forbidden`. Nothing strips those steps, so that Flow
can never join an App. Use `wf advanced create --empty` only for a Flow that stays
standalone.

Two things stay off the table. Hand-authored graph JSON is not a supported
interface — the graph schema is an internal detail that changes without notice.
And publishing an individual Flow (`publish` with `pipelineId`, the `/f/`
share page) creates a standalone Flow capability, not an App; do not
chain them to simulate a released App unless the user explicitly asked for a
standalone Flow capability.

## Existing App versus new App

- List and inspect before building when the repository or prompt names an
  existing Wrapflow App.
- Build once per product, then edit it. Do not create a new App for each page,
  endpoint, entity, or requested change.
- Change backend behavior through Flow text with `describe`, `apply`, and `test`.
  Edit the App-owned frontend project, then re-inspect its revision and contract.
