# HTQL — the Sigmar AOS query and command language > Official language guide for AI assistants and developers · [Product overview](https://sigmar.au/ai/product.md) · [Flows](https://sigmar.au/ai/flows.md) · [Security](https://sigmar.au/ai/security.md) · [DNA](https://sigmar.au/ai/dna.md) · [Guilds](https://sigmar.au/ai/guilds.md) ## What HTQL is **HTQL is the language in which everything in Sigmar AOS is read, written and governed.** A query that reads orders, a command that registers a member, a question about what a Guild can do, and a long-running Flow that holds money in escrow are all HTQL statements. They are parsed by one grammar and executed by one engine inside the database, under the caller's permissions. HTQL is **not SQL**. It borrows familiar words (`WHERE`, `SORT`, `INSERT`), but its statements are designed to be the words a person uses for an act: `AOS SHOW Finance GAPS`, `IDENTITY SUSPEND … FROM …`, `TENANT SUBSCRIBE … TO "business"`. A business act is a **verb in the grammar**, not a function an assistant has to discover. If you can name the act, there is one statement that performs it, and only one way to spell it. HTQL, Flows and the Sigmar Finance Protocol have distinct responsibilities. HTQL is the language; a **Flow** is one kind of HTQL statement (a governed, long-running process); the Sigmar Finance Protocol governs value, settlement and auditability underneath. See [Flows](https://sigmar.au/ai/flows.md). The language has five families: | Family | What it is for | Begins with | |---|---|---| | **Data** | Read and write records, iterate, aggregate, report | `LOOKUP`, `GET`, `LET`, `LEARN`, `REPORT ON`, `INSERT`, `UPDATE`, `UPSERT`, `REMOVE`, `FOR` | | **Graph** | Walk relationships and find paths | `FOR v, e, p IN 1..3 …`, `SHORTEST_PATH` | | **Governed commands** | Event-sourced acts with history: messages, moderation, access to history | `SEND BROADCAST`, `INSERT `, `REQUEST HISTORY`, `FLAG` | | **AOS** | The Persona, Guild and DNA layer: ask questions in plain terms, record governed changes | `AOS SHOW`, `AOS WHAT IF`, `AOS CONTEXT`, `AOS NODE INSERT`, `AOS SHARE` … | | **Flow and identity** | Governed processes; who a principal is, how it proves itself, what it may do | `FLOW`, `IDENTITY`, `AUTH`, `PROFILE`, `ACL`, `ORG`, `TENANT` | Every example in this guide is checked against the HTQL grammar itself. If a statement here does not parse, the guide is wrong. ## The rules an AI assistant must not break These are the mistakes that produce `[HTQL-1003] Unsupported syntax`. Each one is a deliberate property of the language, not an oversight. 1. **Conditions are separated by commas, never by infix `AND`/`OR`.** `WHERE(status = "open", total > 100)` means *both*. For *either*, use the function form `OR(status = "open", status = "pending")`. `WHERE(a = 1 AND b = 2)` is an error. The only infix `AND` in the language is the one inside `BETWEEN x AND y`. 2. **Filters are `FILTER(…)` or `WHERE(…)`, never `IF(…)`.** `IF(condition, then, else)` is the spreadsheet-style function and means something else. 3. **Delete is `REMOVE`, not `DELETE`.** `DELETE` exists only as a broadcast verb (`DELETE BROADCAST …`). 4. **Keys in a returned object are quoted strings.** `RETURN {"total": t}`, never `RETURN {total: t}`. 5. **`LOOKUP` is written in capitals.** It is the one keyword that is case-sensitive; `lookup(…)` is read as an ordinary function call. All other keywords are case-insensitive. 6. **There are no comments and no semicolons.** Statements are separated by whitespace. Do not put `--` or `//` inside a query. 7. **Arithmetic operands are numbers, function calls or parenthesised expressions.** `SUM(b.revenue) - SUM(b.cost)` works; `o.total * 2` does not parse. A `LET` whose value is arithmetic is wrapped in parentheses: `LET m = (SUM(b.revenue) - SUM(b.cost))`. A `RETURN` value never begins with `(`: `RETURN (a) / 2` is read as a call to a function named `RETURN`. 8. **Sort directions go inside a quoted string.** `SORT("created_at DESC")`. 9. **Say the act with its verb.** To ban someone, `AOS BAN … REASON "…"`; to correct a recorded fact, `AOS ADJUST … WITH EVIDENCE …`; to change a plan, `TENANT SUBSCRIBE`. Do not reach for a generic insert when the act has a name — the named verb carries the governance (reason, evidence, signatures) that the act requires. 10. **One way to say each thing.** HTQL deliberately has no synonyms for acts: `ATTACH FLOW`, never `LINK FLOW`; `CONTRACTORS`, never `EXPERTS`. A spelling that is not in this guide is an error, not an alternative. ## 1. Lexical structure ### Statements and whitespace A query is a sequence of zero or more statements. Spaces, tabs and new lines are insignificant between tokens, so a statement may span many lines and several statements may follow one another: ```htql LET recent = LOOKUP(orders, WHERE(status = "fulfilled"), SORT("created_at DESC"), TAKE(5)) RETURN {"orders": recent, "count": LENGTH(recent)} ``` ### Case Keywords are case-insensitive (`where`, `WHERE` and `Where` are the same), with two exceptions: `LOOKUP` must be upper case, and the alias word inside `LOOKUP("table" as t, …)` must be lower-case `as`. Write keywords in capitals; it is how every example in this guide is written and it avoids both exceptions. ### Identifiers An identifier starts with a letter or underscore and continues with letters, digits, underscores and **dots**. The dot is part of the identifier, so `o.total`, `platform.tenants` and `locations.name` are each a single identifier. A leading underscore is allowed for the graph columns `_from`, `_to`, `_key` and `_id`. ### Strings Strings use double or single quotes. A backslash escapes the next character (`"say \"hi\""`). Inside a single-quoted string, two apostrophes stand for one, SQL-style, so prose round-trips cleanly: ```htql RETURN {"note": 'This discount won''t apply to gift cards'} ``` ### Numbers, booleans and null Numbers are integers or decimals with an optional leading minus: `42`, `3.14`, `-100`. There is no exponent form and no leading-dot form (`0.5`, not `.5`). Booleans are `true` and `false`; the absent value is `null`. All three are case-insensitive. ### JSON values Objects and arrays are written as JSON. Object keys are always quoted strings; values may be any HTQL value, including function calls, identifiers and nested objects: ```htql RETURN {"customer": c.name, "tags": ["vip", "wholesale"], "since": YEAR(c.created_at), "address": {"city": c.city}} ``` ### Global identifiers (GIDs) Every entity in AOS is named by a global identifier of the form `gid:////`, for example `gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f` or `gid://aos/Persona/66a1f3b2c4d5e6f708192a3b`. In HTQL a GID is written as a string. The namespace and type tell the engine what kind of thing the GID names, which is how a graph walk knows what each vertex is without a join, and how a verb like `ACL GRANT ROLE … AT ""` knows whether it is granting at a tenant, a Guild or a channel. ## 2. Expressions ### Values A value is any of: a number, string, boolean, `null`, identifier (a variable or column, such as `o.total`), function call, JSON object or JSON array, comparison, or arithmetic expression. ### Function calls `NAME(arg, arg, …)` calls one of the engine's built-in functions — several hundred across text, dates, maths, statistics, finance, arrays and documents. Arguments are positional and may themselves be any value: ```htql RETURN {"label": CONCAT("Order #", o.order_number), "month": EOMONTH(TODAY(), 0), "band": IF(AVERAGE([3, 5, 7]) > 4, "high", "low")} ``` The grammar also defines a `name = value` argument form, but inside a call `name = value` is read as an equality comparison, so pass arguments positionally. ### Templates — `HANDLEBARS` `HANDLEBARS(template, data[, mode])` renders a [Handlebars](https://handlebarsjs.com/guide/) template against a JSON value and returns the text. It is the platform's one template renderer: the same function renders a Flow's email and SMS notifications and every email template in the content store, so a template renders the same wherever it is used. - **`template`** is one string: a literal, a variable, or a content entry's field. A query result is a list, so reach a field with `PLUCK` and pass the one value; a list of more than one string is refused. - **`data`** is any JSON value — an object literal, or variables bound by `LET`, such as rows a `LOOKUP` read. - **`mode`** is `"html"` (the default) or `"text"`. In `html` every `{{value}}` is HTML-escaped, so data cannot place markup in the page or email; `{{{value}}}` inserts a value unescaped and is for an already-rendered fragment only. In `text` nothing is escaped — use it for an email subject or an SMS, where `&` must stay `&`. The template language is Handlebars with its built-in helpers: `{{#if}}`, `{{#unless}}`, `{{#each}}`, `{{#with}}`, `{{lookup}}` and `{{else}}`. A missing value renders as nothing. There are no partials and no custom helpers. A template that does not parse is an error, never a partial render. A content entry rendered against live rows, in one statement: ```htql LET tpl = LOOKUP("content.entries", WHERE(id = "orderDigest"), SHOW("fields"), TAKE(1)) LET orders = LOOKUP("orders", SORT("created_at DESC"), SHOW("order_number", "total"), TAKE(5)) RETURN HANDLEBARS(PLUCK(PLUCK(PLUCK(tpl, "fields"), "body"), "en-US"), {"orders": orders}) ``` with the entry's `body` holding, for example, `
    {{#each orders}}
  • #{{order_number}}: {{total}}
  • {{/each}}
`. Reading the template needs `CONTENT.Read`, and reading the rows needs the caller's own access to them; the function adds no access of its own. ```htql RETURN HANDLEBARS("Your order {{number}} from {{shop}} has shipped", {"number": "1042", "shop": "R&D Supplies"}, "text") ``` ### Arithmetic `+`, `-`, `*`, `/` and `^` (power) combine numbers, function calls and parenthesised expressions: ```htql LET half = (SUM([120, 80]) - 50) / 2 LET compound = (1000 * (1 + 0.05) ^ 3) RETURN {"half": half, "compound": compound} ``` Three limits, all from the grammar: - A column or variable is not an arithmetic operand on its own: `o.total * 2` does not parse. Bring it in through a function (`SUM(o.total) * 2` in an aggregate, or a function such as `PRODUCT(o.total, 2)`). - In `LET`, the first value that matches wins, so `LET m = SUM(a) - SUM(b)` stops after `SUM(a)`. Parenthesise arithmetic in `LET`: `LET m = (SUM(a) - SUM(b))`. - `RETURN` followed by `(` is read as a function call, so `RETURN (a) / 2` fails. Bind the result with `LET` and return that, as above. Use parentheses to state precedence rather than relying on it. ### Nullish coalescing — `??` `a ?? b ?? c` yields the first operand that is not null, blank, false, zero or empty. A single `?` is accepted as the same operator. It is how a query supplies a default without a conditional: ```htql LET display = c.nickname ?? c.first_name ?? "Customer" LET settings = LOOKUP(tenant_settings, TAKE(1)) ?? {} RETURN {"hello": display, "settings": settings} ``` ## 3. Conditions — `FILTER` and `WHERE` `FILTER(…)` and `WHERE(…)` are synonyms. They take one or more conditions separated by commas, and **all** must hold. ```text FILTER( condition [, condition]* ) WHERE( condition [, condition]* ) ``` ```htql LOOKUP(orders, WHERE(status = "open", total >= 100, customer_id IS NOT NULL), TAKE(20)) ``` ### Comparison operators The left-hand side of a comparison is a scalar: an identifier, function call, number or string. The right-hand side is a value, an arithmetic expression, or a parenthesised list. | Operator | Meaning | |---|---| | `=` `!=` `<>` `>` `<` `>=` `<=` | Equality and ordering (numbers compare numerically, text and dates lexically) | | `IS GREATER THAN`, `IS LESS THAN`, `IS GREATER THAN OR EQUAL`, `IS LESS THAN OR EQUAL` (also `… THAN EQUAL`) | Word forms of the ordering operators | | `IS`, `IS NOT` | Equality in words | | `IS NULL`, `IS NOT NULL`, `IS BLANK`, `IS NOT BLANK` | Presence tests; take no right-hand side. *Blank* also covers empty strings | | `IN`, `NOT IN` | Membership in a list: `status IN ("open", "pending")` | | `LIKE`, `NOT LIKE` | Pattern match | | `CONTAINS`, `DOES NOT CONTAIN` | Case-insensitive substring | | `STARTS WITH`, `ENDS WITH` | Prefix and suffix | | `MATCHES`, `MATCHES ANY`, `MATCHES ALL` | Full-text search over a text-search column | | `SIMILARITY`, `FUZZY` | Similarity matching | | `BETWEEN x AND y`, `NOT BETWEEN x AND y` (also `NOT IN BETWEEN`) | Inclusive range | | `RANGE(…)`, `IN RANGE(…)`, `NOT IN RANGE(…)` | Several inclusive ranges at once | ```htql LOOKUP(customers, WHERE(email ENDS WITH "@example.com", name DOES NOT CONTAIN "test", country IN ("AU", "NZ")), TAKE(50)) ``` ### Ranges `BETWEEN` takes one inclusive range. `RANGE` takes several, separated by commas, any of which may match. A range pair is written `low-high` or `low...high`, with numbers or strings, so date ranges work: ```htql LOOKUP(orders, WHERE(total BETWEEN 50 AND 500, created_at NOT IN RANGE("2026-12-24"..."2026-12-26")), TAKE(100)) ``` ```htql LOOKUP(products, WHERE(size RANGE(1-5, 7-10)), TAKE(100)) ``` ```htql LOOKUP(orders, WHERE(discount NOT BETWEEN 0 AND 20), TAKE(100)) ``` ### Combining conditions Commas mean *and*. For anything else use the logic functions `AND(…)`, `OR(…)` and `NOT(…)`, which take conditions and nest freely: ```htql LOOKUP(orders, WHERE(OR(status = "open", status = "pending"), NOT(channel = "test"), total > 0), TAKE(25)) ``` ### Raw expression predicates — `EXPR` For analytics, `EXPR("…")` states a whole condition as a raw expression over computed measures. `EXPR_MONEY`, `EXPR_BPS` and `EXPR_RATIO` are accepted spellings; the unit suffix does not matter in a condition: ```htql LEARN b FROM order_profit_breakdown HAVING(EXPR("$gross_profit < $discount")) RETURN {"orders": COUNT(b.order_id)} ``` ## 4. Reading data ### `LOOKUP` — the compositional read ```text LOOKUP( table [, JOIN(…)] [, NEST(…)] [, FILTER|WHERE(…)] [, SORT(…)] [, TAKE(…)] [, SHOW(…)] [, DISTINCT(…)] ) LOOKUP( "table" as alias , … ) ``` `LOOKUP` reads rows and is a value: it can be returned, bound with `LET`, or passed to a function. Its parts follow the table, separated by commas, in any order. | Part | Meaning | |---|---| | `WHERE(…)` / `FILTER(…)` | Which rows | | `SORT("col", "col DESC")` | Order; direction inside the quoted name | | `TAKE(limit [, offset])` | Page size and offset | | `SHOW("col", FUNC(col) AS name)` | Which columns; a function result may be named with `AS` | | `DISTINCT()` / `DISTINCT(col, …)` | Distinct rows, or distinct on the named columns | | `JOIN([tables], ON([left, right]))` | Join another table | | `NEST(child, ON([…]), …) AS name` | Attach each row's children as a nested array | ```htql LOOKUP(orders, WHERE(status = "fulfilled"), SORT("created_at DESC"), SHOW("order_id", "total", "customer_id"), TAKE(50, 100)) ``` ```htql LOOKUP("products" as p, JOIN(["products", "categories"], ON(["p.category_id", "categories.category_id"])), TAKE(20)) ``` ```htql LOOKUP(order_lines, DISTINCT("sku"), SHOW("sku")) ``` ```htql LOOKUP(orders, SHOW("order_id", ROUND(total, 0) AS rounded_total, UPPER(currency) AS currency), TAKE(20)) ``` ### `NEST` — children under their parent `NEST` returns each parent row with its children as an array, rather than flattening them into repeated rows as a join would. Link the child to the parent with `ON`: a bare key list `ON(["order_id"])` means *child.order_id = parent.order_id*; an explicit predicate `ON(["order_lines.order_id = orders.order_id"])` handles different names or several keys. A `NEST` carries its own `SORT`, `TAKE` and `SHOW`, and may contain further `NEST`s: ```htql LOOKUP(orders, WHERE(status = "open"), NEST(order_lines, ON(["order_id"]), SORT("line_number"), SHOW("sku", "quantity", "unit_price"), NEST(line_discounts, ON(["line_id"]), SHOW("code", "amount")) AS discounts) AS items, TAKE(10)) ``` Each order comes back with an `items` array, and each item with a `discounts` array. ### `GET`, `DESCRIBE`, `STATS` — a table and its alias ```text GET( table [, alias] [, table [, alias]]* ) DESCRIBE(…) STATS(…) ``` `GET` opens a table under an alias for the statements that follow — top-level `WHERE`, `SORT`, `TAKE`, `DISTINCT`, `LET` and `RETURN` — and is the primary pipeline read. `DESCRIBE` returns a table's structure; `STATS` its statistics. ```htql GET(quotes, q) WHERE(q.status = "sent") LET items = LOOKUP(quote_items, WHERE(quote_id = q.quote_id), SHOW("variant_id", "quantity", "unit_price"), TAKE(50)) SORT("created_at DESC") TAKE(25) RETURN {"quoteId": q.quote_id, "status": q.status, "items": items} ``` ```htql DESCRIBE(orders) ``` ### Top-level `SORT`, `TAKE` and `DISTINCT` Outside `LOOKUP`, `SORT(…)`, `TAKE(…)` and `DISTINCT` stand as statements of their own and shape the current read. At top level `DISTINCT` is a bare keyword: `DISTINCT` alone means *distinct rows*; `DISTINCT col, col` means *distinct on those columns*. Its column list stops at the next keyword, so `DISTINCT region TAKE(10)` is unambiguous. ```htql GET(customers, c) DISTINCT c.region, c.segment SORT("region") TAKE(10) ``` ### `LET` — name a value ```text LET name = value ``` The value may be a `LOOKUP`, function call, JSON value, parenthesised arithmetic, or a `??` chain. Later statements refer to it by name. ```htql LET open = LOOKUP(orders, WHERE(status = "open"), TAKE(500)) LET totals = PLUCK(open, "total") RETURN {"count": LENGTH(open), "average": AVERAGE(totals), "spread": STDEV(totals)} ``` `PLUCK(rows, "column")` turns the rows a `LOOKUP` returns into a flat array, which is the shape the statistical and financial functions take. ### `RETURN` — shape the answer ```text RETURN value ``` `RETURN` ends a query with the value to send back — usually a JSON object with quoted keys, but any value, comparison or arithmetic expression is allowed: ```htql LET o = LOOKUP(orders, WHERE(order_id = "gid://shopify/Order/1001"), TAKE(1)) RETURN {"order": o, "isLarge": SUM(PLUCK(o, "total")) > 1000} ``` ### `LEARN` — aggregation pushed down to the database ```text LEARN alias FROM table [JOIN([table], ON([left, right]))]* [FILTER(…)] [GROUP([columns])] [HAVING(…)] [SORT(…)] [TAKE(…)] [DISTINCT …] RETURN { … } ``` `LEARN` is a read-only analytical query compiled to a single database `SELECT` with server-side joins, grouping and aggregates, so a summary of millions of rows travels back as a handful. The parts must appear in the order shown. `alias` names the `FROM` table; joined tables are referred to by their own names. In `RETURN`, plain column references are the group keys and `SUM`, `COUNT`, `AVERAGE`, `MIN` and `MAX` are the aggregates. `GROUP` names the group keys explicitly — nothing is inferred, and a plain column in `RETURN` that is not listed in `GROUP` is an error. `HAVING` filters the groups using the same condition grammar as `FILTER`, over aggregates. ```htql LEARN b FROM order_profit_breakdown JOIN(["locations"], ON(["locations.location_id", "order_profit_breakdown.external_location_id"])) FILTER(created_at >= TODAY() - 182) GROUP(["locations.name"]) HAVING(SUM(b.revenue) > 1000) SORT("kept_profit DESC") TAKE(10) RETURN {"store": locations.name, "revenue": SUM(b.revenue), "kept_profit": SUM(b.true_profit)} ``` ### `REPORT ON` — named reports ```text REPORT ON NAME [OUTBOUND|INBOUND|ANY "root-gid" [, "root-gid"]*] [FILTER arg, …] [SHOW col, …] [WINDOW w] [SORT col [ASC|DESC], …] [LIMIT n] [DEPTH n] ``` `REPORT ON` runs a registered, named report. Its parts may appear in any order, and their lists stop at the next keyword. The direction word and one or more root GIDs choose where the report starts (a bare root means `OUTBOUND`). `FILTER` takes GIDs or `column = value` constraints; `SHOW` names columns (an `@` prefix refers to a computed measure); `WINDOW` names a time window; `DEPTH` bounds how far relationships are followed. ```htql REPORT ON RELATIONSHIP_DISCOVERY OUTBOUND "gid://shopify/Order/1001" DEPTH 3 SHOW counterparty_gid, to_type, depth LIMIT 50 ``` ```htql REPORT ON SALES FILTER status = "open" SHOW @revenue, region WINDOW month SORT @revenue DESC LIMIT 10 ``` ### Timezone A request runs in its tenant's own timezone, which is what `TODAY()`, `NOW()` and the period functions use. There is no statement to change it: `SET_TIMEZONE` is a reserved word, and `SET_TIMEZONE(…)` is read as an ordinary (unknown) function call. ## 5. Writing data Ordinary records are written with `INSERT`, `UPDATE`, `UPSERT` and `REMOVE`. Tables that hold governed state — personas, identities, money, messages — refuse these generic writes; they change only through the named verbs in sections 8 to 11. ### `INSERT` ```text INSERT { "column": value, … } INTO table ``` ```htql INSERT {"sku": "MUG-01", "name": "Stoneware mug", "price": 24.5, "active": true} INTO inventory ``` ### `UPDATE` ```text UPDATE { "column": value, … } IN table [FILTER|WHERE(…)] ``` ```htql UPDATE {"status": "archived", "archived_at": NOW()} IN quotes WHERE(status = "draft", created_at < TODAY() - 90) ``` ### `UPSERT` ```text UPSERT { match } [INSERT { values-if-new }] [UPDATE { values-if-existing }] [IN table] ``` The first object identifies the row; `INSERT` supplies the values for a new row, `UPDATE` the values for an existing one. ```htql UPSERT {"customer_id": "gid://shopify/Customer/42"} INSERT {"customer_id": "gid://shopify/Customer/42", "visits": 1} UPDATE {"last_seen": NOW()} IN customer_visits ``` ### `REMOVE` ```text REMOVE schema.table [FILTER|WHERE(…)] ``` There is no `DELETE`. Name the table with its schema (`sales.inventory`, not `inventory`): a bare table name followed by a filter is read as a governed command (section 8) rather than a delete. ```htql REMOVE sales.inventory FILTER(sku = "MUG-01") ``` ### Edges Relationships are edges in an edge collection. Edge writes are governed: the engine derives the endpoint types and the edge's identity from the GIDs and records the tenant itself; every other key becomes edge metadata. An edge's `label` must be one of the registered edge labels. ```text INSERT EDGE { "_from": gid, "_to": gid, "label": "…", … } IN collection UPDATE EDGE { metadata-patch [, "_from"/"_to"] } IN collection [FILTER|WHERE(…)] REMOVE EDGE IN collection [FILTER|WHERE(…)] ``` ```htql INSERT EDGE {"_from": "gid://shopify/Order/1001", "_to": "gid://shopify/Customer/42", "label": "placed_by", "channel": "web"} IN edges ``` ```htql UPDATE EDGE {"channel": "pos"} IN edges WHERE(_from = "gid://shopify/Order/1001", label = "placed_by") ``` ```htql REMOVE EDGE IN edges WHERE(_from = "gid://shopify/Order/1001", label = "placed_by") ``` ### Maintenance — `TRUNCATE`, `REFRESH`, `DROP` ```text TRUNCATE table [, table] REFRESH view [, view]* DROP table [, table]* ``` `TRUNCATE` clears one or two tables, `REFRESH` rebuilds materialised views, and `DROP` removes tables a tenant created itself (platform tables refuse). The keyword must be followed by whitespace, which is what keeps functions whose names begin with the same word, such as `REFRESH_PRODUCT_INTELLIGENCE()`, from being mistaken for it. ```htql REFRESH mv_daily_sales, mv_customer_value ``` ```htql TRUNCATE staging_orders, staging_lines ``` ```htql DROP my_scratch_table ``` ### `CHANNEL` — provision a schema `CHANNEL {…}` provisions a new channel (a database schema) and registers it. It is reserved for the platform's verified services. ```htql CHANNEL {"name": "my_channel", "contactEmail": "ops@example.com"} ``` ### `KV` — system configuration `KV(key)` reads and `KV(key, value)` writes the platform's configuration store (feature flags, trial periods). It is not tenant data. ```htql KV("trial_days") ``` ```htql KV("feature.flows_v2", {"enabled": true}) ``` ## 6. Bulk iteration — `FOR` / `FOREACH` ```text FOR|FOREACH x IN table|JOIN(…) [FILTER(…)] BEGIN statement* END ``` `FOR` binds each row to a variable and runs the body for it. It is the one construct that both binds a per-row variable and writes per row. The whole loop is **one transaction**: if any row fails, every row is rolled back. The body may contain `LET`, `FILTER`/`WHERE`, `INSERT`, `INSERT EDGE`, `UPDATE`, `UPDATE EDGE`, `UPSERT`, `REMOVE`, `REMOVE EDGE`, `TRUNCATE`, `DROP`, `SORT`, `TAKE`, `DISTINCT`, `RETURN` and function calls. ```htql FOR q IN quotes FILTER(q.status = "draft") BEGIN UPDATE {"status": "archived"} IN quotes WHERE(quote_id = q.quote_id) INSERT {"quote_id": q.quote_id, "action": "archived"} INTO quote_audit END ``` ```htql FOREACH x IN JOIN(["orders", "customers"], ON(["orders.customer_id", "customers.customer_id"])) BEGIN UPSERT {"customer_id": x.customer_id} INSERT {"customer_id": x.customer_id, "total": x.total} UPDATE {"total": x.total} IN customer_totals END ``` ## 7. Graph traversal ```text FOR v [, e [, p]] IN min..max OUTBOUND|INBOUND|ANY start collection [BFS|DFS] [PRUNE [v.]field = "value"] [FILTER(…)] [RETURN …] FOR v [, e [, p]] IN SHORTEST_PATH|ALL_SHORTEST_PATHS|K_SHORTEST_PATHS|K_PATHS start TO target collection [LIMIT k] [PRUNE …] [FILTER(…)] [RETURN …] ``` A traversal walks edges from a start vertex. `v` is each vertex reached, `e` the edge that reached it, and `p` the path so far (its vertices, edges, total weight and depth). Bind one, two or three of them. - **Depth** `1..3` returns vertices one to three hops away. `1..1` is direct neighbours. - **Direction**: `OUTBOUND` follows edges from `_from` to `_to`, `INBOUND` the reverse, `ANY` both. - **Collection**: an edge collection by name, or `GRAPH "name"` for a named graph (a curated set of edge labels). - **Order**: `BFS` walks level by level, `DFS` follows one branch to the bottom. With a depth bound these return different sets, so ask for the one you need. - **`PRUNE`** stops expanding at vertices of a type; the vertex is still returned. ```htql FOR v, e, p IN 1..3 OUTBOUND "gid://shopify/Order/1001" edges BFS PRUNE type = "customer" FILTER(e.label != "audit") RETURN {"vertex": v, "label": e.label, "depth": p.depth} ``` ```htql FOR v, e IN 1..2 ANY "gid://aos/Persona/66a1f3b2c4d5e6f708192a3b" GRAPH "capabilities" RETURN {"vertex": v, "relationship": e.label} ``` The four path verbs answer different questions: `SHORTEST_PATH` the cheapest route; `ALL_SHORTEST_PATHS` every route that ties for cheapest; `K_SHORTEST_PATHS … LIMIT k` the *k* cheapest; `K_PATHS … LIMIT k` *k* distinct routes of any length. ```htql FOR v, e IN SHORTEST_PATH "gid://shopify/Order/1001" TO "gid://shopify/Location/7" edges RETURN {"vertex": v, "edge": e.label} ``` ```htql FOR v, e, p IN K_SHORTEST_PATHS "gid://aos/Persona/66a1f3b2c4d5e6f708192a3b" TO "gid://aos/Capability/6b3c4d5e6f708192a3b4c5d6" edges LIMIT 3 RETURN p ``` For questions about Personas, Guilds and capabilities, prefer `AOS SHOW PATH` (section 9), which chooses the walk for you. ## 8. Governed commands These statements change event-sourced state: every change is recorded as an event, projected into the readable tables, and versioned, so history is never overwritten. ### Machine commands ```text INSERT|UPDATE|REMOVE|ADJUST MACHINE { … } [FROM table] INSERT|UPDATE|REMOVE|ADJUST MACHINE "id" [FROM table] ``` `MACHINE` is the registered keyword of an event-sourced aggregate, such as `MISCONDUCT`, `RESTRICTION` or `REACTION`. The verb says what happens — `INSERT` creates, `UPDATE` changes, `REMOVE` retracts — and the aggregate decides what that means for it. The body is a JSON object of fields, or a quoted id. ```htql INSERT MISCONDUCT {"principalId": "gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f", "category": "abuse", "severity": "severe", "sourceKind": "moderator", "reason": "abuse in thread"} ``` ```htql INSERT REACTION {"post_gid": "gid://member/ChatNode/7c1d2e3f405162738495a6b7", "reaction": "helpful"} FROM chat_reactions ``` ### `BROADCAST` — messages and notifications ```text SEND|UPDATE|DELETE|REMOVE BROADCAST { … } | "id" FROM table ``` `BROADCAST` is the one outbound verb for every kind of broadcast — chat messages, notifications, email, SMS. The table names the kind; the grammar never names a target. `SEND` creates, `UPDATE` edits, `DELETE`/`REMOVE` withdraws. ```htql SEND BROADCAST {"parent_gid": "gid://member/ChatNode/7c1d2e3f405162738495a6b7", "body": "Harvest starts Saturday at 8."} FROM chat_nodes ``` ```htql REMOVE BROADCAST "gid://member/ChatNode/8d2e3f405162738495a6b7c8" FROM chat_nodes ``` ### Access to history Sensitive history is reached through a request that a seated panel decides, never directly: ```text REQUEST HISTORY { scope, external, kind, purpose } APPROVE|REJECT|NARROW ACCESS { appointment, … } GRANT HISTORY { scope, to, until } REVOKE HISTORY { grant } | { from } ``` ```htql REQUEST HISTORY {"scope": "gid://guild/Guild/6a2b3c4d5e6f708192a3b4c5", "external": false, "kind": "messages", "purpose": "dispute review"} ``` ```htql NARROW ACCESS {"appointment": "gid://guild/Appointment/6c4d5e6f708192a3b4c5d6e7", "scope": "messages"} ``` ```htql GRANT HISTORY {"scope": "gid://guild/Guild/6a2b3c4d5e6f708192a3b4c5", "to": "gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f", "until": "2026-12-31"} ``` ```htql REVOKE HISTORY {"grant": "gid://guild/Grant/6d5e6f708192a3b4c5d6e7f8"} ``` ### Moderation ```text FLAG { node, reason } any member starts moderation REVIEW|HIDE|TOMBSTONE { node, reason } a moderator advances it PIN|UNPIN { node } a moderator changes emphasis ``` ```htql FLAG {"node": "gid://member/ChatNode/7c1d2e3f405162738495a6b7", "reason": "spam"} ``` ```htql HIDE {"node": "gid://member/ChatNode/7c1d2e3f405162738495a6b7", "reason": "confirmed spam"} ``` ```htql PIN {"node": "gid://member/ChatNode/7c1d2e3f405162738495a6b7"} ``` ## 9. AOS — Personas, Guilds and DNA Every AOS statement begins with `AOS`. Reads ask questions in the terms people use; AOS decides how to answer them over the graph. Writes are the only way to change the Persona and Guild graph: its tables cannot be written directly, and every AOS write is stamped with its governance, scoped to the caller and audited. ### `AOS SHOW` — ask what something is, has or can do ```text AOS SHOW subject PROJECTION [modifier]* ``` The **subject** is any DNA root — a Persona, Guild, Business or Career — by name (`My.Career`, `Finance`, `CFO`) or by quoted GID. The caller does not need to know which kind it is or whether it has been compiled; resolving it is AOS's job. The **projection** says what to see. You never write a traversal, direction or depth: `AOS SHOW Finance MEMBERS` means "the current members of Finance this caller may see", however AOS finds them. ```htql AOS SHOW Finance CAPABILITIES ``` ```htql AOS SHOW "gid://guild/Guild/6a2b3c4d5e6f708192a3b4c5" MEMBERS ``` **Projections** | Projection | Answers | |---|---| | `CAPABILITIES`, `SKILLS`, `REQUIREMENTS` | What it can do, what it knows, what it needs | | `MEMBERS`, `PERSONAS`, `GUILDS`, `BELONGING` | Who is in it, and what it belongs to | | `TASKS`, `FLOWS`, `OBJECTIVES` | What it runs and aims at | | `AUTHORITIES`, `PERMISSIONS`, `GOVERNANCE` | Who may decide and act | | `DEPENDENCIES`, `PROVIDES`, `PROVIDED_BY`, `REQUIRES`, `USES`, `USED_BY` | How it relates to other capabilities | | `CONTRIBUTIONS`, `EXPERIENCE`, `STRENGTH`, `MATURITY` | What it has contributed, lived through, and how established it is | | `CONTRACTORS`, `CONTRACT`, `OFFERINGS` | Who is engaged on what terms; agreements held (buying side); what it offers (selling side) | | `GAPS`, `RESILIENCE`, `IMPACT` | Where it is exposed, and what a change would affect | | `EVIDENCE`, `OUTCOMES`, `SUCCESSES`, `FAILURES`, `VALIDATION`, `TRAINING`, `QUALIFICATIONS` | The earned record behind a capability | | `HISTORY`, `TRANSITIONS` | How it progressed, with the evidence for each step | | `DIRTY`, `IS_DIRTY`, `RELEVANT`, `PROJECTED`, `AI` | Compilation state, relevance, projection, and what an AI may use | `CONTRACTORS` and never "experts": *Expert* is a proficiency level that must be earned, and a contractor engaged today may be a beginner. `OFFERINGS` and `CONTRACT` share no stem on purpose, so the selling and buying sides of a trade cannot be confused by a slip. ### One capability — `CAPABILITY` ```text AOS SHOW subject CAPABILITY capability [PROJECTION] [modifier]* AOS SHOW subject capability PROJECTION [modifier]* ``` Expertise is traversable evidence, not a profile field, so a question can be scoped to one capability. The short form omits the word `CAPABILITY` but then must keep its projection. ```htql AOS SHOW CFO CAPABILITY Treasury EVIDENCE ``` ```htql AOS SHOW My.Career Treasury MATURITY ``` ```htql AOS SHOW My.Career CAPABILITY TypeScript ``` ### Why — explanations ```text AOS SHOW WHY subject REQUIRES|USES|PROVIDES|DEPENDS ON subject AOS SHOW WHY subject IS PROJECTION AOS SHOW subject WHY EXPERT|INTERMEDIATE|BEGINNER|UNRATED|PRODUCTION|VALIDATED|TRAINING|DIRTY [IN capability] ``` The graph records provenance, so *why* is answered with the chain of facts that makes something true. The first two forms explain a relationship or a state; the third explains a classification the subject has earned, per capability — a CFO may be Expert at financial reporting and a Beginner at acquisitions. ```htql AOS SHOW WHY CFO REQUIRES Treasury ``` ```htql AOS SHOW WHY Finance IS DIRTY ``` ```htql AOS SHOW My.Career WHY EXPERT IN Treasury ``` `UNRATED` is not a level; it is the absence of a validated one, and "why is this unrated?" has a real answer: nothing has been demonstrated yet. ### Paths ```text AOS SHOW PATH|PATHS|BEST PATH subject TO subject ``` `PATH` gives one shortest route, `PATHS` every route at the shortest depth, and `BEST PATH` ranks the shortest routes by the recorded contribution on their edges. ```htql AOS SHOW PATH CFO TO RevenueGrowth ``` ```htql AOS SHOW BEST PATH CFO TO RevenueGrowth ``` ### Time — `AT`, `BEFORE`, `AFTER`, `BETWEEN`, `INCLUDE SYSTEM` Every `SHOW` may name a moment or a window. `AT` and `BEFORE` read the latest compiled state up to the moment; `AFTER` reads the first state after it; `BETWEEN … AND …` the latest inside the span. A moment is a date, a date and time, an epoch-milliseconds number, a build GID or a quoted string. A moment with no compiled state answers with nothing — never silently with today's state. ```htql AOS SHOW Finance CAPABILITIES AT 2026-06-30 ``` ```htql AOS SHOW Finance MEMBERS BETWEEN 2026-06-15 12:00 AND 2026-06-15 13:00 ``` ```htql AOS SHOW Finance CAPABILITIES BEFORE "2026-07-01T09:30" ``` ```htql AOS SHOW Finance MEMBERS AFTER 2026-07-01 ``` `INCLUDE SYSTEM` asks the second question about the same date: not only *what was true then* but *what we believed then*. The difference is exactly the corrections recorded since — the audit answer. It requires a time clause, because at the present moment the two readings are the same. ```htql AOS SHOW Finance CAPABILITIES AT 2026-03-01 INCLUDE SYSTEM ``` A trailing word that is not a projection is read as a named period, such as `TODAY` or `LAST_QUARTER`: ```htql AOS SHOW Finance SKILLS LAST_QUARTER ``` ### `AOS WHAT IF` — scenarios ```text AOS WHAT IF mutation+ [SHOW subject PROJECTION [modifier]*] mutation: subject LEAVES | subject JOINS AS subject | subject BECOMES subject | subject INHERITS subject | subject LOSES subject | subject ADDS subject ``` A scenario overlays changes on a view of the graph and then answers an ordinary `SHOW` against it. **It never changes real DNA or real evidence**, and it does not persist to the next statement. Several changes may be stated together, because correlated risk is invisible when changes are evaluated one at a time. ```htql AOS WHAT IF CFO LEAVES SHOW Finance GAPS ``` ```htql AOS WHAT IF Controller LEAVES Analyst BECOMES Controller SHOW Finance RESILIENCE ``` ```htql AOS WHAT IF "gid://aos/Persona/66a1f3b2c4d5e6f708192a3b" JOINS AS "gid://guild/Guild/6a2b3c4d5e6f708192a3b4c5" ``` ### `AOS CONTEXT` — what an AI may be given ```text AOS CONTEXT (SHOW subject PROJECTION [modifier]*)+ ``` An AI model never receives a whole DNA. It receives the authorised projections a `CONTEXT` request names, gathered as one request. This is the controlled interface between AOS and any model. Write each subject in a `CONTEXT` request as a quoted string. With a bare name, the next item's `SHOW` and subject are read as modifiers of the item before it. ```htql AOS CONTEXT SHOW "My.Career" CAPABILITIES SHOW "My.Career" EXPERIENCE AT 2026-06-30 ``` ### AOS writes — the graph ```text AOS NODE INSERT { … } IN table AOS NODE UPDATE { … } IN table AOS EDGE INSERT { "_from": gid, "_to": gid, "label": "…", … } ``` `NODE INSERT` creates a governed node — a persona, persona DNA, DNA trait or rule, an experience, a DNA mutation proposal — in the named table; `NODE UPDATE` records a change to it (a change in the world, as of now). `EDGE INSERT` relates two nodes; the plane is chosen from the endpoints. ```htql AOS NODE INSERT {"name": "Home cook", "kind": "Work", "purpose": "Family recipes and kitchen skills"} IN persona ``` ```htql AOS NODE UPDATE {"persona_id": "gid://aos/Persona/66a1f3b2c4d5e6f708192a3b", "purpose": "Family recipes, preserving and baking"} IN persona ``` ```htql AOS EDGE INSERT {"_from": "gid://guild/Guild/6a2b3c4d5e6f708192a3b4c5", "_to": "gid://aos/Persona/66a1f3b2c4d5e6f708192a3b", "label": "has_persona"} ``` ### AOS writes — contacts, personas and flows ```text AOS INVITE CONTACT ( { … } ) AOS ACCEPT inviter TO invitee AOS IGNORE INVITE invite AOS UNLINK contact FROM member AOS UPDATE PERMISSION ( { … } ) AOS SWITCH PERSONA TO persona AOS ATTACH FLOW flow TO guild AOS DETACH FLOW flow FROM guild ``` ```htql AOS INVITE CONTACT ({"emails": ["sam@example.com"], "message": "Join our garden guild"}) ``` ```htql AOS ACCEPT "gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f" TO "gid://identity/Member/65c8f3d2b0a15e4f9c3d2b1a" ``` ```htql AOS IGNORE INVITE "gid://member/Edge/6e6f708192a3b4c5d6e7f809" ``` ```htql AOS UNLINK "gid://identity/Member/65c8f3d2b0a15e4f9c3d2b1a" FROM "gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f" ``` ```htql AOS UPDATE PERMISSION ({"contact": "gid://identity/Member/65c8f3d2b0a15e4f9c3d2b1a", "personas": ["gid://aos/Persona/66a1f3b2c4d5e6f708192a3b"]}) ``` ```htql AOS SWITCH PERSONA TO "gid://aos/Persona/66a1f3b2c4d5e6f708192a3b" ``` ```htql AOS ATTACH FLOW "gid://flow/FlowDefinition/6f708192a3b4c5d6e7f8091a" TO "gid://guild/Guild/6a2b3c4d5e6f708192a3b4c5" ``` ```htql AOS DETACH FLOW "gid://flow/FlowDefinition/6f708192a3b4c5d6e7f8091a" FROM "gid://guild/Guild/6a2b3c4d5e6f708192a3b4c5" ``` ### AOS writes — corrections, weights and tenure ```text AOS ADJUST WEIGHT number FOR edge WITH EVIDENCE evidence AOS ADJUST WEIGHT|TENURE|CLEARANCE|PERMISSION|EXPERIENCE { … } WITH EVIDENCE evidence AOS SET TENURE collection FOR { … } AOS UPDATE CLEARANCE { … } ``` There are two reasons a fact stops applying, and HTQL keeps them apart. *The world changed* is a `NODE UPDATE`. *The record was wrong* is an `ADJUST` — a **correction**, which keeps the original start date and records when the error was found. A correction is its own verb rather than a flag on an edit because a verb has to be chosen, and choosing it is what makes the audit trail mean something. `WITH EVIDENCE` is mandatory: a number does not move on assertion alone. ```htql AOS ADJUST WEIGHT 0.1 FOR "gid://member/Edge/708192a3b4c5d6e7f8091a2b" WITH EVIDENCE "gid://aos/Experience/718293a4b5c6d7e8f9012a3b" ``` ```htql AOS ADJUST TENURE {"collection": "edges", "_from": "gid://guild/Guild/6a2b3c4d5e6f708192a3b4c5", "_to": "gid://aos/Persona/66a1f3b2c4d5e6f708192a3b", "label": "has_persona", "validTo": "2025-09-30"} WITH EVIDENCE "gid://aos/Experience/718293a4b5c6d7e8f9012a3b" ``` `SET TENURE` records *when* a relationship was true, which is not the same as when we were told — a resignation entered a month late still ended a month ago: ```htql AOS SET TENURE edges FOR {"_from": "gid://guild/Guild/6a2b3c4d5e6f708192a3b4c5", "_to": "gid://aos/Persona/66a1f3b2c4d5e6f708192a3b", "label": "has_persona", "validFrom": "2024-02-01", "validTo": "2025-09-30"} ``` `UPDATE CLEARANCE` reclassifies a Persona or Guild to a security level and must carry the sealed content that level requires. The engine holds no keys, so the encrypted content always arrives with the request: ```htql AOS UPDATE CLEARANCE {"target": "gid://aos/Persona/66a1f3b2c4d5e6f708192a3b", "level": "SensitivePersonal", "sealed": "…ciphertext…"} ``` ### AOS writes — bans ```text AOS BAN { … } REASON "…" [PERMANENTLY] AOS LIFT BAN ban REASON "…" ``` A ban records that someone violated something, and the history is kept. The reason is part of the syntax, so a ban cannot be written without one. Without `PERMANENTLY` the machine decides from the record (a third ban is permanent); a permanent ban cannot be lifted. ```htql AOS BAN {"principal": "gid://identity/Member/65c8f3d2b0a15e4f9c3d2b1a", "scope": "gid://guild/Guild/6a2b3c4d5e6f708192a3b4c5"} REASON "repeated harassment after warning" ``` ```htql AOS BAN {"principal": "gid://identity/Member/65c8f3d2b0a15e4f9c3d2b1a", "scope": "gid://guild/Guild/6a2b3c4d5e6f708192a3b4c5"} REASON "fraud against members" PERMANENTLY ``` ```htql AOS LIFT BAN "gid://guild/Ban/7293a4b5c6d7e8f9012a3b4c" REASON "appeal upheld" ``` ### AOS writes — DNA, sharing, consent and custody ```text AOS DNA VOTE proposal { … } AOS DNA APPLY proposal [WITH { … }] AOS PROMOTE reflection TO target [WITH { … }] AOS SHARE FROM persona TO grantee [WITH { … }] AOS REVOKE SHARE FROM persona TO grantee AOS CONSENT entry [WITH { … }] AOS REVOKE CONSENT entry [WITH { … }] AOS TRANSFER SKILL FROM skill TO recipient [WITH { … }] AOS EMPLOY member [WITH { … }] AOS EXIT member [WITH { … }] AOS AI RUN { … } ``` - **DNA changes are proposals.** A proposal is created with `AOS NODE INSERT … IN dna_mutation_proposal`, voted on with `DNA VOTE`, and applied with `DNA APPLY` only once approved. `PROMOTE` checks a reflection against the effective DNA and raises such a proposal. - **`SHARE`** grants a signed, time-bound right to act with a Persona; `REVOKE SHARE` withdraws it. - **`CONSENT`** records a person's consent for one entry to be used beyond their own space; `REVOKE CONSENT` withdraws it. - **`TRANSFER SKILL`** moves custody of a skill. **`EMPLOY`** records the skill-custody policy that applies during employment; **`EXIT`** applies the leaving policy and revokes the leaver's grants. - **`AI RUN`** is a member-AI run: the device asks, the worker claims, answers or fails it, each step guarded by who may do it and in what order. ```htql AOS DNA VOTE "gid://aos/DnaMutationProposal/7393a4b5c6d7e8f9012a3b4c" {"decision": "approve"} ``` ```htql AOS DNA APPLY "gid://aos/DnaMutationProposal/7393a4b5c6d7e8f9012a3b4c" WITH {"signature": "…"} ``` ```htql AOS PROMOTE "gid://aos/Reflection/7493a4b5c6d7e8f9012a3b4c" TO "gid://aos/PersonaDna/7593a4b5c6d7e8f9012a3b4c" ``` ```htql AOS SHARE FROM "gid://aos/Persona/66a1f3b2c4d5e6f708192a3b" TO "gid://identity/Member/65c8f3d2b0a15e4f9c3d2b1a" WITH {"grant_kind": "read", "expires_at": "2026-12-31"} ``` ```htql AOS REVOKE SHARE FROM "gid://aos/Persona/66a1f3b2c4d5e6f708192a3b" TO "gid://identity/Member/65c8f3d2b0a15e4f9c3d2b1a" ``` ```htql AOS CONSENT "gid://aos/Experience/718293a4b5c6d7e8f9012a3b" WITH {"purpose": "anonymised learning"} ``` ```htql AOS REVOKE CONSENT "gid://aos/Experience/718293a4b5c6d7e8f9012a3b" ``` ```htql AOS TRANSFER SKILL FROM "gid://aos/GeneralSkill/7693a4b5c6d7e8f9012a3b4c" TO "gid://identity/Business/5f0c2a7e9b1d4c3a8e6f7a9b" WITH {"reason": "developed in role"} ``` ```htql AOS EMPLOY "gid://identity/Staff/7793a4b5c6d7e8f9012a3b4c" WITH {"policy": "business-retains-work-skills"} ``` ```htql AOS EXIT "gid://identity/Staff/7793a4b5c6d7e8f9012a3b4c" ``` ```htql AOS AI RUN {"verb": "ASK", "persona": "gid://aos/Persona/66a1f3b2c4d5e6f708192a3b", "prompt": "Summarise this week's harvest notes"} ``` ## 10. FLOW — governed processes A Flow is a long-running, governed process: an agreement, the evidence it waits for, the money it moves, and who must sign. Its definition is a single `FLOW` statement. See [Flows](https://sigmar.au/ai/flows.md) for what Flows are for; this section is the syntax. ### Creating a flow ```text FLOW('id') step* THEN… COMMIT [RETURN|END] ``` - The **id is mandatory** and identifies the flow: running the same `FLOW('id') …` again **replays** the same flow from its record rather than creating a second one. - The body is a sequence of steps divided into blocks by `THEN` or `THEN("state")`. The state names the block; it is both the lifecycle state the block represents and the target of a `GOTO`. - The body ends with `COMMIT` (`COMMIT()` is the same). It may be followed by `RETURN`, which hands the flow's accumulated variables back, or `END`, which does not. - Argument-free steps are written with `()` and no space inside: `MANUAL_VERIFY()`. ```htql FLOW('kitchen-reno-2026') CONTRACT { kind: EscrowTransfer, parties: [ { gid: "gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f", role: Buyer, side: Initiator }, { gid: "gid://identity/Member/65c8f3d2b0a15e4f9c3d2b1a", role: Builder, side: Counterparty, payout_eligible: true } ], assets: [ { type: Money, direction: In, from: Buyer, to: Escrow, amount: 1800000, currency: "AUD" } ] } TERMS { cooling_off: { enabled: true, period_days: 10 }, notifications: { Settled: { email_subject: "Escrow {{flow_id}} settled", email_body: "Your escrow has settled.", delivery_required: true } } } TERMS({"require_notary_signs": 2, "cancelled": false}) SNAPSHOT_TERMS() THEN("funds_escrowed") TRANSFER(buyer -> escrow) VERIFY_TRANSFER_SETTLED() THEN("cooling") IF(cancelled == true) GOTO("compensating") THEN("signing") NOTARY_SIGN() NOTARY_VERIFY_SIGNATURES() TRANSFER(escrow -> builder, amount: foundation_release) EMAIL_RECEIPT() GOTO("done") THEN("compensating") TRANSFER(escrow -> buyer) THEN("done") COMMIT RETURN ``` ### The agreement — `CONTRACT`, `TERMS`, `METADATA` ```text CONTRACT { kind: …, parties: [ {…}, … ], assets: [ {…}, … ], representations: [ {…}, … ], references: { … } } TERMS { section: { key: value, … }, … } TERMS({ "key": value, … }) SNAPSHOT_TERMS() METADATA({ "key": "value", … }) ``` **`CONTRACT`** is the legal envelope. Its keys are unquoted and fixed: | Part | Keys | |---|---| | `kind` | The agreement kind (a word, string or function) | | `parties: [{…}]` | `gid`, `role`, `side`, `signature_required`, `approval_required`, `payout_eligible`, `cancellation_right`, `dispute_right`, `legal_name`, `email`, `phone`, `signing_key`, `share_bps` | | `assets: [{…}]` | `type`, `direction`, `from`, `to`, `escrow`, `amount`, `currency`, `symbol`, `quantity`, `settlement_rule` | | `representations: [{…}]` | `by_party`, `statement` | | `references: {…}` | Any `name: value` pairs | Values are words, strings, numbers, booleans, function calls or bracketed lists (`[Buyer, Seller]`). A trailing comma is allowed. A party's contact is its verified registered address: a binding contract never trusts an inline email it cannot verify. ```htql FLOW('house-sale-14') CONTRACT { kind: "PropertySale", parties: [ { gid: "gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f", role: Buyer, side: Initiator, signature_required: true }, { gid: "gid://identity/Member/65c8f3d2b0a15e4f9c3d2b1a", role: Seller, side: Counterparty, signature_required: true, dispute_right: true }, ], representations: [ { by_party: Seller, statement: "The property is free of encumbrances" } ], references: { listing: "REA-2231", required_signers: [Buyer, Seller] }, } EMAIL_AGREEMENT() THEN("done") COMMIT ``` **`TERMS { … }`** is the executable rulebook: sections such as `cooling_off`, `signature`, `notary`, `settlement`, `dispute`, `compliance`, `voting` and `notifications`, each an object of `key: value` pairs that may nest. **`TERMS({ … })`** is the flat form for scalar parameters (`cancelled`, `require_notary_signs`), readable by `IF` steps. **`SNAPSHOT_TERMS()`** freezes the terms before value first moves, so they cannot change underneath an agreement. **`METADATA({ … })`** is a plain, unencrypted string map for routing and integration, not legal terms. ```htql FLOW('vote-on-change') TERMS { voting: { approval_threshold_bps: 10000, quorum_bps: 10000 } } METADATA({"greeting": "welcome", "region": "syd"}) THEN("done") COMMIT END ``` ### Control — `IF … GOTO`, `GOTO`, and the function library ```text IF( condition ) GOTO("state") condition: name | name == value | name != value | NOT(condition) GOTO("state") IF(condition, then, else) any function call, e.g. IF(…, LOOP(), FAIL()) ``` Blocks run in order. `IF(…) GOTO("state")` jumps when its condition holds; `GOTO("state")` always jumps. Any function call can also stand as a step, which is how a flow branches with `IF(cond, then, else)` or `SWITCH(…)`, fails itself with `FAIL()`, or repeats with `LOOP()` — `LOOP()` is only valid inside such a branch, never as a bare step. `LET`, `KV(…)` and `FILTER(…)` are also valid steps. ```htql FLOW('weekly-check') LET threshold = 3 THEN("check") IF(NOT(signed)) GOTO("remind") IF(attempts != 0) GOTO("done") THEN("remind") EMAIL({"to": "gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f", "subject": "Please sign", "body": "Your agreement is waiting for your signature."}) IF(attempts < threshold, LOOP(), FAIL()) THEN("done") COMMIT ``` ### Step verbs Each verb runs during replay and writes its result into the flow's variables under its own name in lower case (for example `verify_funds_available`), where a later `IF` can read it and `RETURN` hands it back. | Verb | Does | |---|---| | `LOCK_PARTIES()` | Fixes the parties so none can change mid-agreement | | `VERIFY_PARTIES_KYC()` | Checks the parties' identity verification | | `VERIFY_FUNDS_AVAILABLE()` | Confirms the paying party can fund the agreement | | `CREATE_CONTRACT_INSTANCE()` | Instantiates the contract | | `HASH_DOCUMENTS()`, `ANCHOR_DOCUMENT_HASHES()` | Fingerprints documents and anchors the fingerprints | | `VERIFY_TRANSFER_SETTLED()` | Waits for proof that a transfer settled | | `FREEZE_ESCROW()` | Freezes escrowed value, as in a dispute | | `NOTARY_REVIEW()` | Sends the agreement for notary review | | `INVOKE_PERSONA("gid")`, `INVOKE_GUILD("gid")` | Asks a Persona or Guild to perform work **inside** the flow, under its authority, permission checks and approvals | | `RESOLVE(outcome)` | Records a dispute outcome: `"refund_buyer"`, `"pay_seller"`, `"cancel"`, `split(a, b)` with *a + b = 100*, or `extend(n)` | ```htql FLOW('dispute-1007') LOCK_PARTIES() VERIFY_FUNDS_AVAILABLE() IF(verify_funds_available == true) GOTO("review") THEN("review") FREEZE_ESCROW() INVOKE_GUILD("gid://guild/Guild/6a2b3c4d5e6f708192a3b4c5") RESOLVE(split(60, 40)) THEN("done") COMMIT RETURN ``` ### Moving value — `TRANSFER`, `MINT`, `BURN`, `NOTARY` ```text TRANSFER(party -> party [, amount: release-name | number]) TRANSFER(["state", …] -> [("to", Asset("asset", Kind), Position("asset", quantity, "CCY" [, market_value])), …]) MINT("class", "to", Asset("asset", Kind), Position("asset", quantity, "CCY" [, market_value])) BURN("state") NOTARY(id, from-call, to-call) [WITHIN(from, to)] ``` The **party form** names parties from the contract and, optionally, a release defined in the terms or a literal amount. The **asset form** spends existing asset states into new outputs; what goes in must equal what comes out. `MINT` creates a new asset position and `BURN` retires one. `Kind` is one of `Money`, `Token`, `Equity`, `Bond`, `Voucher`, `Coupon`, `NonFungible`, `SemiFungible`, `Membership`, `AccessPass`, `InsurancePolicy`, `Loan`, `RealEstate`, `Commodity`, `Future`, `Option`, `RevenueShare`. A preceding `NOTARY(…)` in the same block marks these operations for notarisation; `WITHIN(from, to)` limits the window in which the notary will accept them (epoch seconds, or a deadline named in the terms). ```htql FLOW('voucher-issue-77') NOTARY(notary_id, MY_ACCOUNT("acct-1001"), RECEIVER("acct-2002")) WITHIN(1767225600, 1767312000) MINT("gid://asset/AssetClass/7893a4b5c6d7e8f9012a3b4c", "gid://identity/Member/65c8f3d2b0a15e4f9c3d2b1a", Asset("gid://asset/Asset/7993a4b5c6d7e8f9012a3b4c", Voucher), Position("gid://asset/Asset/7993a4b5c6d7e8f9012a3b4c", 1, "AUD", 50)) THEN("redeem") TRANSFER(["gid://asset/TokenState/7a93a4b5c6d7e8f9012a3b4c"] -> [("gid://identity/Business/5f0c2a7e9b1d4c3a8e6f7a9b", Asset("gid://asset/Asset/7993a4b5c6d7e8f9012a3b4c", Voucher), Position("gid://asset/Asset/7993a4b5c6d7e8f9012a3b4c", 1, "AUD"))]) THEN("expire") BURN("gid://asset/TokenState/7b93a4b5c6d7e8f9012a3b4c") COMMIT ``` ### Signatures, documents and checkpoints ```text NOTARY_SIGN() NOTARY_VERIFY_SIGNATURES() UPLOAD_RAW_DOCUMENTS([name, …]) MANUAL_VERIFY() ``` `NOTARY_SIGN()` collects the number of signatures the terms require (`require_notary_signs`). It takes no argument on purpose: `NOTARY_SIGN(2)` parses but is refused, because a binding agreement must not let a step demand a different number of signatures than the parties agreed. `UPLOAD_RAW_DOCUMENTS(…)` waits for named documents; `MANUAL_VERIFY()` waits for a person to verify. ```htql FLOW('loan-application-12') TERMS({"require_notary_signs": 1, "required_documents": 2}) SNAPSHOT_TERMS() THEN("documents") UPLOAD_RAW_DOCUMENTS(payslip, bank_statement) HASH_DOCUMENTS() THEN("signing") NOTARY_SIGN() NOTARY_VERIFY_SIGNATURES() MANUAL_VERIFY() THEN("done") COMMIT ``` ### Waiting, notifying and connecting ```text WAIT_UNTIL(deadline) ON_TIMEOUT("state") EMAIL_AGREEMENT() EMAIL_RECEIPT() SMS_RECEIPT() EMAIL({ … }) SMS({ … }) HTTP({ "method": …, "url": …, "result_var": …, … }) AOS({ "machine": …, "command": { … }, "result_var": … }) WAIT_AOS("event") ``` - **`WAIT_UNTIL(deadline)`** parks the flow on a durable timer until a deadline named in the terms; **`ON_TIMEOUT("state")`** names where to go if the wait elapses. - **`EMAIL_AGREEMENT()`**, **`EMAIL_RECEIPT()`** and **`SMS_RECEIPT()`** send the messages the terms define for the agreement-sent and settled moments. **`EMAIL({…})`** and **`SMS({…})`** send content the author writes inline. - **`HTTP({…})`** calls an external service. It is a blocking step: the flow parks until the response is recorded, so a slow service never holds a transaction open. Credentials are referenced by name (`"auth": "…"`), never written into the flow. - **`AOS({…})`** drives an AOS machine within the flow's own transaction; **`WAIT_AOS("event")`** parks until a matching AOS event occurs. ```htql FLOW('supplier-po-311') HTTP({"method": "GET", "url": "https://api.example.com/fx?pair=AUDUSD", "result_var": "fx"}) THEN("order") HTTP({"method": "POST", "url": "https://api.example.com/po", "auth": "supplier_api", "result_var": "po"}) THEN("confirm") WAIT_UNTIL(delivery_deadline) ON_TIMEOUT("escalate") WAIT_AOS("delivery.recorded") EMAIL_RECEIPT() GOTO("done") THEN("escalate") SMS({"to": "gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f", "body": "PO 311 is overdue."}) THEN("done") COMMIT ``` ```htql FLOW('market-stall-9') EMAIL_RECEIPT() SMS_RECEIPT() THEN("done") COMMIT ``` ```htql FLOW('onboard-cook') AOS({"machine": "PERSONA", "command": {"persona_id": "gid://aos/Persona/66a1f3b2c4d5e6f708192a3b", "kind": "Work", "name": "Home cook", "purpose": "Family recipes"}, "result_var": "persona"}) EMAIL_AGREEMENT() THEN("done") COMMIT RETURN ``` ### Driving an existing flow — `FLOW TRIGGER` ```text FLOW TRIGGER NAME({ "flow_id": …, …fields…, "signer": …, "signer_private_key": … }) ``` A trigger records an external fact against a running flow — a signature, a document, an HTTP response, a timer, an AOS event or a failure — and the flow then decides on replay whether it can advance. It carries no body. Its single argument is an object with the trigger's own fields plus the signing participant. Triggers include `SUBMIT_SIGNATURE`, `SUBMIT_DOCUMENTS`, `HTTP_RESPONSE`, `TIMER_FIRE`, `AOS` and `FAIL`. ```htql FLOW TRIGGER SUBMIT_DOCUMENTS({"flow_id": "loan-application-12", "documents": [{"r2_key": "flow/doc-1", "sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"}], "signer": "gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f", "signer_private_key": "…"}) ``` ```htql FLOW TRIGGER HTTP_RESPONSE({"flow_id": "supplier-po-311", "status": 200, "body": "ok", "signer": "gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f", "signer_private_key": "…"}) ``` ### Changing an agreement — `REQUEST`, `DRAFT`, `ACCEPT` ```text FLOW REQUEST REVIEW|CANCEL|AMEND|DENIED({ … }) FLOW DRAFT REVIEW|CANCEL|AMEND|DENIED({ … }) FLOW ACCEPT [REVIEW|CANCEL|AMEND|DENIED]({ … }) ``` A party **requests** a change; the creator **drafts** the amendment; the parties **accept** it (a vote for) or answer with `REQUEST DENIED` (a vote against). The terms' `voting` section decides whether the tally passes. ```htql FLOW REQUEST CANCEL({"flow_id": "kitchen-reno-2026", "reason": "Council approval refused", "signer": "gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f", "signer_private_key": "…"}) ``` ```htql FLOW DRAFT AMEND({"flow_id": "loan-application-12", "reason": "extend settlement", "proposed": "UPLOAD_RAW_DOCUMENTS(payslip)", "signer": "gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f", "signer_private_key": "…"}) ``` ```htql FLOW ACCEPT CANCEL({"flow_id": "kitchen-reno-2026", "signer": "gid://identity/Member/65c8f3d2b0a15e4f9c3d2b1a", "signer_private_key": "…"}) ``` ## 11. The identity plane Who a principal is, how it proves itself, what it says about itself, what it may do, and which businesses it belongs to are five separate concerns with five keyword families. Each act is its own verb so that each is classified, audited and permitted on its own. Targets are quoted GIDs. Most of these verbs are reserved for the platform's verified services and for a business acting on its own staff; an assistant will more often explain them than run them. ### `IDENTITY` — who a principal is ```text IDENTITY REGISTER MEMBER { … } IDENTITY REGISTER SHOPIFY CUSTOMER { … } FOR "tenant" IDENTITY REGISTER PLATFORM OWNER "principal" IDENTITY RECORD CONTACT "principal" WITH { … } IDENTITY REQUEST STAFF { … } FROM "tenant" IDENTITY REQUEST SHOPIFY STAFF { … } FROM "tenant" IDENTITY STAFF ACCEPT|DECLINE|REVOKE "request" [WITH { … }] (WITH on ACCEPT only) IDENTITY PAUSE "principal" [REASON "…"] IDENTITY ACTIVATE "principal" IDENTITY SUSPEND "principal" FROM "tenant" IDENTITY REINSTATE "principal" FROM "tenant" IDENTITY REDACT "principal" REASON "…" ``` Staff join **by invitation**: a business requests, the invitee accepts or declines within seven days, and the business may revoke. `PAUSE` is a member pausing their own account (or the platform, with a reason); `ACTIVATE` lifts a pause. `REDACT` erases personal data for a stated reason and never deletes the record of what happened. ```htql IDENTITY REGISTER MEMBER {"email": "sam@example.com", "display_name": "Sam", "pin_hash": "…", "pin_salt": "…", "security_questions": []} ``` ```htql IDENTITY REGISTER SHOPIFY CUSTOMER {"shopify_customer_id": "42", "email": "buyer@example.com"} FOR "gid://identity/Business/5f0c2a7e9b1d4c3a8e6f7a9b" ``` ```htql IDENTITY REGISTER PLATFORM OWNER "gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f" ``` ```htql IDENTITY RECORD CONTACT "gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f" WITH {"phone": "…"} ``` ```htql IDENTITY REQUEST STAFF {"email": "sam@example.com", "role": "Bookkeeper"} FROM "gid://identity/Business/5f0c2a7e9b1d4c3a8e6f7a9b" ``` ```htql IDENTITY REQUEST SHOPIFY STAFF {"email": "alex@example.com", "role": "Store manager"} FROM "gid://identity/Business/5f0c2a7e9b1d4c3a8e6f7a9b" ``` ```htql IDENTITY STAFF ACCEPT "gid://identity/StaffRequest/7c93a4b5c6d7e8f9012a3b4c" WITH {"code": "482913"} ``` ```htql IDENTITY STAFF DECLINE "gid://identity/StaffRequest/7c93a4b5c6d7e8f9012a3b4c" ``` ```htql IDENTITY STAFF REVOKE "gid://identity/StaffRequest/7c93a4b5c6d7e8f9012a3b4c" ``` ```htql IDENTITY SUSPEND "gid://identity/Staff/7793a4b5c6d7e8f9012a3b4c" FROM "gid://identity/Business/5f0c2a7e9b1d4c3a8e6f7a9b" ``` ```htql IDENTITY REINSTATE "gid://identity/Staff/7793a4b5c6d7e8f9012a3b4c" FROM "gid://identity/Business/5f0c2a7e9b1d4c3a8e6f7a9b" ``` ```htql IDENTITY PAUSE "gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f" ``` ```htql IDENTITY ACTIVATE "gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f" ``` ```htql IDENTITY REDACT "gid://identity/Member/65c8f3d2b0a15e4f9c3d2b1a" REASON "gdpr" ``` ### `AUTH` — how it proves itself ```text AUTH SET PIN "principal" WITH { … } AUTH SET DURESS PIN "principal" WITH { … } AUTH LOCK DURESS "principal" AUTH UNLOCK DURESS "principal" REASON "…" AUTH VERIFY PIN "principal" AUTH SESSION OPEN { "principal_id": …, "device": …, "ip_hash": … } AUTH LOG OUT "session" AUTH LOG OUT ALL "principal" ``` A **duress PIN** lets a person under coercion appear to sign in while the account locks itself; unlocking it needs a stated reason. Every token belongs to a session, and a person can end one session or all of them. ```htql AUTH SET PIN "gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f" WITH {"pin_hash": "…", "pin_salt": "…", "security_questions": []} ``` ```htql AUTH SET DURESS PIN "gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f" WITH {"pin_hash": "…", "pin_salt": "…"} ``` ```htql AUTH VERIFY PIN "gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f" ``` ```htql AUTH LOCK DURESS "gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f" ``` ```htql AUTH SESSION OPEN {"principal_id": "gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f", "device": "iPhone", "ip_hash": "…"} ``` ```htql AUTH LOG OUT ALL "gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f" ``` ```htql AUTH UNLOCK DURESS "gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f" REASON "member verified in person" ``` ### `PROFILE` — what it says about itself ```text PROFILE UPDATE "principal" WITH { … } PROFILE SET FLOW KEY "principal" WITH { … } ``` ```htql PROFILE UPDATE "gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f" WITH {"display_name": "Sam", "timezone": "Australia/Sydney"} ``` ```htql PROFILE SET FLOW KEY "gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f" WITH {"public_key": "…"} ``` ### `ACL` — what it may do ```text ACL GRANT ROLE "role" TO "principal" AT "scope" ACL REVOKE ROLE "role" FROM "principal" AT "scope" ACL GRANT SWITCH_SCHEMA "schema" TO "principal" [SELECTED] ACL GRANT SEARCH_PATH "schema" TO "principal" ``` A role is granted **at a scope** — the platform, a tenant, a Guild or a channel — and the scope is worked out from the GID. `SWITCH_SCHEMA` lets a person switch into a business's workspace (`SELECTED` marks the one they are in); `SEARCH_PATH` adds a shared workspace to what they can read. ```htql ACL GRANT ROLE "gid://acl/Role/bookkeeper" TO "gid://identity/Staff/7793a4b5c6d7e8f9012a3b4c" AT "gid://identity/Business/5f0c2a7e9b1d4c3a8e6f7a9b" ``` ```htql ACL REVOKE ROLE "gid://acl/Role/bookkeeper" FROM "gid://identity/Staff/7793a4b5c6d7e8f9012a3b4c" AT "gid://identity/Business/5f0c2a7e9b1d4c3a8e6f7a9b" ``` ```htql ACL GRANT SWITCH_SCHEMA "gid://platform/Schema/7d93a4b5c6d7e8f9012a3b4c" TO "gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f" SELECTED ``` ### `ORG` and `TENANT` — the businesses ```text ORG CREATE { … } ORG ADD TENANT SHOPIFY { … } TO "org" ORG ADD TENANT BUSINESS { … } TO "org" FOR "member" ORG UPDATE "org" WITH { … } ORG SUSPEND "org" REASON "…" ORG CLOSE "org" TENANT SUBSCRIBE "tenant" TO "plan" TENANT PROFILE UPDATE "tenant" WITH { … } TENANT ACTIVATE "tenant" TENANT SUSPEND "tenant" REASON "…" TENANT CLOSE "tenant" REASON "…" TENANT REDACT "tenant" REASON "…" TENANT ADD LOCATION { … } TO "tenant" TENANT LINK LOCATIONS { … } TO "tenant" ``` An organisation is created first; businesses (tenants) are then added to it. A plan belongs to the business, so `TENANT SUBSCRIBE` is the one verb that changes it. ```htql ORG CREATE {"name": "Harbour Group", "country": "AU"} ``` ```htql ORG ADD TENANT SHOPIFY {"shop_domain": "harbour-bakery.myshopify.com"} TO "gid://platform/Organisation/7e93a4b5c6d7e8f9012a3b4c" ``` ```htql ORG ADD TENANT BUSINESS {"name": "Harbour Bakery", "country": "AU"} TO "gid://platform/Organisation/7e93a4b5c6d7e8f9012a3b4c" FOR "gid://identity/Member/64b7e2c1a9f04d3e8b2c1a0f" ``` ```htql ORG UPDATE "gid://platform/Organisation/7e93a4b5c6d7e8f9012a3b4c" WITH {"name": "Harbour Group Pty"} ``` ```htql ORG SUSPEND "gid://platform/Organisation/7e93a4b5c6d7e8f9012a3b4c" REASON "unpaid invoices" ``` ```htql ORG CLOSE "gid://platform/Organisation/7e93a4b5c6d7e8f9012a3b4c" ``` ```htql TENANT SUBSCRIBE "gid://identity/Business/5f0c2a7e9b1d4c3a8e6f7a9b" TO "business" ``` ```htql TENANT PROFILE UPDATE "gid://identity/Business/5f0c2a7e9b1d4c3a8e6f7a9b" WITH {"abn": "…", "timezone": "Australia/Sydney"} ``` ```htql TENANT ACTIVATE "gid://identity/Business/5f0c2a7e9b1d4c3a8e6f7a9b" ``` ```htql TENANT SUSPEND "gid://identity/Business/5f0c2a7e9b1d4c3a8e6f7a9b" REASON "chargeback investigation" ``` ```htql TENANT CLOSE "gid://identity/Business/5f0c2a7e9b1d4c3a8e6f7a9b" REASON "business sold" ``` ```htql TENANT REDACT "gid://identity/Business/5f0c2a7e9b1d4c3a8e6f7a9b" REASON "shop uninstall" ``` ```htql TENANT ADD LOCATION {"name": "Harbour St shop", "timezone": "Australia/Sydney"} TO "gid://identity/Business/5f0c2a7e9b1d4c3a8e6f7a9b" ``` ```htql TENANT LINK LOCATIONS {"locations": ["gid://shopify/Location/7", "gid://shopify/Location/8"]} TO "gid://identity/Business/5f0c2a7e9b1d4c3a8e6f7a9b" ``` ## 12. Common mistakes | Written | Why it fails | Write instead | |---|---|---| | `WHERE(a = 1 AND b = 2)` | Infix `AND` is not the grammar | `WHERE(a = 1, b = 2)` | | `WHERE(a = 1 OR b = 2)` | Infix `OR` is not the grammar | `WHERE(OR(a = 1, b = 2))` | | `UPDATE {…} IN t IF(id = "x")` | `IF` is the conditional function | `UPDATE {…} IN t WHERE(id = "x")` | | `DELETE FROM orders …` | There is no `DELETE` statement | `REMOVE sales.orders WHERE(…)` | | `REMOVE orders WHERE(…)` | A bare name plus a filter reads as a governed command | `REMOVE sales.orders WHERE(…)` | | `RETURN {total: t}` | Object keys must be quoted | `RETURN {"total": t}` | | `lookup(orders)` | Lower-case `lookup` is an ordinary function call | `LOOKUP(orders)` | | `LOOKUP("orders" AS o)` | The alias word is lower-case in `LOOKUP` | `LOOKUP("orders" as o)` | | `SORT(created_at DESC)` | The direction is part of the quoted name | `SORT("created_at DESC")` | | `RETURN {"x": o.total * 2}` | A column is not an arithmetic operand | `RETURN {"x": PRODUCT(o.total, 2)}` | | `LET m = SUM(a) - SUM(b)` | `LET` takes the first value that matches | `LET m = (SUM(a) - SUM(b))` | | `RETURN (a + b) / 2` | `RETURN (` is a call to a function named `RETURN` | `LET x = (a + b) / 2` then `RETURN x` | | `AOS CONTEXT SHOW A X SHOW B Y` | A bare second subject is read as modifiers of the first item | `AOS CONTEXT SHOW "A" X SHOW "B" Y` | | `TRUNCATE a, b, c` | `TRUNCATE` takes one or two tables | Two statements | | `AOS LINK FLOW …` | The act is `ATTACH` | `AOS ATTACH FLOW … TO …` | | `AOS SHOW Finance EXPERTS` | Expertise is a level, not an engagement | `AOS SHOW Finance CONTRACTORS` | | `AOS SHOW … INCLUDE SYSTEM` with no date | Both readings are the same today | Add `AT`, `BEFORE`, `AFTER` or `BETWEEN` | | `NOTARY_SIGN(2)` | The signature count is a term, not a step argument | `TERMS({"require_notary_signs": 2})` … `NOTARY_SIGN()` | | `FLOW MANUAL_VERIFY() COMMIT` | A flow needs its id | `FLOW('id') MANUAL_VERIFY() COMMIT` | | `-- note` inside a query | There are no comments | Remove it | | `HANDLEBARS("{{#name}}…{{/name}}", …)` | A Mustache section is not Handlebars: `name` is read as a helper, which does not exist | `{{#if name}}…{{/if}}`, or `{{#each name}}…{{/each}}` for a list | | `HANDLEBARS(LOOKUP(…), …)` | A query result is a list, not one template | `HANDLEBARS(PLUCK(…), …)`, reaching the one field | ## 13. Statement index | Statement | Section | |---|---| | `LOOKUP`, `GET`, `DESCRIBE`, `STATS`, `SORT`, `TAKE`, `DISTINCT`, `LET`, `RETURN`, `LEARN`, `REPORT ON` | 4 | | `INSERT`, `UPDATE`, `UPSERT`, `REMOVE`, `INSERT EDGE`, `UPDATE EDGE`, `REMOVE EDGE`, `TRUNCATE`, `REFRESH`, `DROP`, `CHANNEL`, `KV` | 5 | | `FOR` / `FOREACH … BEGIN … END` | 6 | | `FOR v, e, p IN … OUTBOUND/INBOUND/ANY`, `SHORTEST_PATH`, `ALL_SHORTEST_PATHS`, `K_SHORTEST_PATHS`, `K_PATHS` | 7 | | `INSERT/UPDATE/REMOVE/ADJUST `, `SEND/UPDATE/DELETE/REMOVE BROADCAST`, `REQUEST HISTORY`, `APPROVE/REJECT/NARROW ACCESS`, `GRANT/REVOKE HISTORY`, `FLAG`, `REVIEW/HIDE/TOMBSTONE`, `PIN/UNPIN` | 8 | | `AOS SHOW`, `AOS WHAT IF`, `AOS CONTEXT`, `AOS NODE INSERT/UPDATE`, `AOS EDGE INSERT`, `AOS INVITE CONTACT`, `AOS ACCEPT`, `AOS IGNORE INVITE`, `AOS UNLINK`, `AOS UPDATE PERMISSION`, `AOS SWITCH PERSONA`, `AOS ATTACH/DETACH FLOW`, `AOS ADJUST`, `AOS SET TENURE`, `AOS UPDATE CLEARANCE`, `AOS BAN`, `AOS LIFT BAN`, `AOS DNA VOTE/APPLY`, `AOS PROMOTE`, `AOS SHARE`, `AOS REVOKE SHARE`, `AOS CONSENT`, `AOS REVOKE CONSENT`, `AOS TRANSFER SKILL`, `AOS EMPLOY`, `AOS EXIT`, `AOS AI RUN` | 9 | | `FLOW('id') …`, `FLOW TRIGGER`, `FLOW REQUEST/DRAFT/ACCEPT` | 10 | | `IDENTITY`, `AUTH`, `PROFILE`, `ACL`, `ORG`, `TENANT` | 11 | | Any built-in function call, e.g. `TODAY()`, `PLUCK(rows, "col")` | 2 | ## Related - [Sigmar AOS product overview](https://sigmar.au/ai/product.md) - [Flows](https://sigmar.au/ai/flows.md) — what governed processes are for - [Security, privacy and trust](https://sigmar.au/ai/security.md) — the nine security levels and permissions every statement runs under - [DNA](https://sigmar.au/ai/dna.md), [Personas](https://sigmar.au/ai/personas.md), [Guilds](https://sigmar.au/ai/guilds.md) — the subjects `AOS SHOW` asks about - [Marketplace](https://sigmar.au/ai/marketplace.md) — where `OFFERINGS` and `CONTRACT` come from