# ICPP — The Internet C++ Interpreter — User Manual

**ICPP** is the scripting mode of the **kcpp** toolchain, invoked as `kcpp -icpp <file>`.
It is a C-like interpreted language that reuses kcpp's own parser and type system, adds
exactly **one** new piece of syntax (`$var`), and exposes a large library of **325 registered
builtin functions** — database access, strings/regex/sed, files and filesystem, binary
reading, containers (lists/maps/sets/tuples/dicts), hex/bit manipulation, process execution
and a test harness, threads and CPU affinity, image/OCR/biometric utilities, a software
graphics canvas, an MCP + OpenAI client, and a full tensor / neural-network / autodiff engine.

> Copyright (c) 2026 **Muhammad Anisur Rahman**. Free to use and distribute under the **MIT License**.
> SPDX-License-Identifier: MIT.

---

## Table of contents

1. [Introduction — the single-syntax philosophy](#1-introduction)
2. [Running ICPP](#2-running-icpp)
3. [Language reference](#3-language-reference)
4. [Builtin function reference](#4-builtin-function-reference) — the core of the manual
   - [4.1 Output & string building](#41-output--string-building)
   - [4.2 Strings](#42-strings)
   - [4.3 Regex (`icpp_re`) and sed (`ised`)](#43-regex-and-sed)
   - [4.4 SQL / ISQL database bridge](#44-sql--isql-database-bridge)
   - [4.5 Files and file inspection](#45-files-and-file-inspection)
   - [4.6 Filesystem operations](#46-filesystem-operations)
   - [4.7 Sequential file reading](#47-sequential-file-reading)
   - [4.8 Environment & time](#48-environment--time)
   - [4.9 Binary buffers and chunked file IO](#49-binary-buffers-and-chunked-file-io)
   - [4.10 Hex and bit manipulation](#410-hex-and-bit-manipulation)
   - [4.11 Lists and split/join](#411-lists-and-splitjoin)
   - [4.12 Maps and dicts](#412-maps-and-dicts)
   - [4.13 Sets](#413-sets)
   - [4.14 Tuples](#414-tuples)
   - [4.15 Process execution & test harness](#415-process-execution--test-harness)
   - [4.16 The `i*` shell utilities](#416-the-i-shell-utilities)
   - [4.17 Threads and CPU affinity](#417-threads-and-cpu-affinity)
   - [4.18 Images, OCR, fingerprints/AFIS](#418-images-ocr-fingerprintsafis)
   - [4.19 Software graphics canvas](#419-software-graphics-canvas)
   - [4.20 MCP client + JSON](#420-mcp-client--json)
   - [4.21 OpenAI-compatible chat](#421-openai-compatible-chat)
   - [4.22 CGI parameter access](#422-cgi-parameter-access)
   - [4.23 Tensor engine — core operations](#423-tensor-engine--core-operations)
   - [4.24 Tensor engine — neural-network / LLM layers](#424-tensor-engine--neural-network--llm-layers)
   - [4.25 Autodiff (backward / gradient rules)](#425-autodiff-backward--gradient-rules)
   - [4.26 Optimizer & persistence](#426-optimizer--persistence)
   - [4.27 Text embedding & chatbot/RAG support](#427-text-embedding--chatbotrag-support)
   - [4.28 Core C builtins](#428-core-c-builtins)
   - [4.29 Python and Java inside ICPP](#429-python-and-java-inside-icpp)
   - [4.30 Digests, base64, and a page that allows its own script](#430-digests-base64-and-a-page-that-allows-its-own-script)
   - [4.31 Ciphers, signatures, key derivation and randomness](#431-ciphers-signatures-key-derivation-and-randomness)
   - [4.32 HTTPS requests](#432-https-requests)
   - [4.33 QR codes and barcodes](#433-qr-codes-and-barcodes)
   - [4.34 Reading QR codes and barcodes from pictures](#434-reading-qr-codes-and-barcodes-from-pictures)
   - [4.35 Checked SQL commands, transactions and handle ownership](#435-checked-sql-commands-transactions-and-handle-ownership)
   - [4.36 External jobs and local communication transport](#436-external-jobs-and-local-communication-transport)
   - [4.37 Durable ISQL worker queue](#437-durable-isql-worker-queue)
   - [4.38 Math: minimum, maximum, roots, logarithms and trigonometry](#438-math-minimum-maximum-roots-logarithms-and-trigonometry)
   - [4.39 Resumable attachment storage](#439-resumable-attachment-storage)
   - [4.40 Session tokens and request identity](#440-session-tokens-and-request-identity)
5. [The library / `#include` manifest system](#5-the-library--include-manifest-system)
6. [The `i*` aliases for Files/FS builtins](#6-the-i-aliases-for-filesfs-builtins)
7. [Shell redirection in command lines](#7-shell-redirection-in-command-lines)
8. [Known issues](#8-known-issues)
9. [Worked examples](#9-worked-examples)
10. [Appendix A — alphabetical builtin index](#appendix-a--alphabetical-builtin-index)

---

## 1. Introduction

### What ICPP is

ICPP ("Internet C++") is an interpreter embedded in `kcpp.exe`. It runs a C-like script
directly, without a separate compile/link/run cycle. It was created to give the kcpp
toolchain a scripting layer for three broad jobs that recur across this project:

- **RTL / regression driving** — run a tool (compiler, simulator, fitter), inspect what it
  produced, assert on it, and exit with a status a CI job can read.
- **Web / template work** — `<?icpp ... ?>` blocks embedded in HTML, served by `iwebserver`.
- **AI / ML work** — a native tensor engine with forward layers, an autodiff (backward) set,
  an SGD optimizer, tokenizer, plus clients for MCP tool servers and OpenAI-compatible chat.

### The single-syntax philosophy

ICPP is deliberately **almost entirely just C**. Functions, `int` / `double` / `char *`
locals and parameters, `if` / `else` / `while` / `do`-`while` / `for`, arithmetic and logical
operators, `++` / `--`, `#include` — all behave as in C. **The one and only new piece of
syntax is `$var`**, a dynamically-typed local. Everything else that looks "new" — strings,
lists, tensors, regex, database queries — is expressed as ordinary **function calls** into the
builtin library. There is no new object syntax, no new control flow, no operator overloading.
If you know C and you know the names of the builtins, you know ICPP.

Two small optional keyword additions (`function`/`subroutine` for typeless function
definitions, and `rtlbegin`/`rtlend` for embedded verbatim Verilog) are described in
[§3](#3-language-reference); both exist only in `-icpp` mode and are backward-compatible with
plain C that happens to use those identifiers.

---

## 2. Running ICPP

### From the command line

```
kcpp.exe -icpp myscript.icpp
```

The conventional extension is `.icpp`, though `.c` also works (kcpp's normal parser handles
the file either way). A script needs a `main()`:

```c
// hello.icpp
int main(void)
{
    iprint("hello, world\n");
    return 0;
}
```

```
> kcpp.exe -icpp hello.icpp
hello, world
```

`main()` may be declared `int main(void)` or `void main()`; both appear throughout the test
suite. When it returns `int`, that value is **not** automatically the process exit code — use
`icpp_exit(code)` when you need to set the exit status explicitly (the idiomatic CI ending is
`icpp_exit(icpp_test_summary());`).

### Diagnostics and teaching mode

- **`KCPP_DIAG_ICPP=1`** (environment variable) — turns on a detailed trace of parsing,
  identifier resolution, and expression evaluation. This is the single most useful tool for
  debugging a script that produces a wrong number or crashes.
- **`kcpp -icpp -llmtrace script.icpp`** (or `KCPP_LLMTRACE=1`) — prints an educational,
  step-by-step walkthrough of every LLM-pipeline builtin as it runs (tokenizing, embedding
  lookup, positional encoding, linear layers, attention with per-head scores / causal masking
  / softmax weights, loss, the backward pass, and the SGD update), with *why* each step
  exists, in student-facing language. Matrices print up to 8×8. Output lines are prefixed
  `[llmtrace]` so they are easy to filter.

### Embedded in HTML (`<?icpp ... ?>`)

An HTML file may embed ICPP code inside `<?icpp ... ?>` processing blocks. When such a page is
requested through `iwebserver`, the server sets the CGI-style `QUERY_STRING` environment
variable from the request's query parameters and runs the interpreter over the page; the code
inside each `<?icpp ... ?>` block executes and its output is spliced into the surrounding HTML
sent to the browser. Inside the block, [`icpp_getparam(name)`](#422-cgi-parameter-access)
reads a query parameter, and [`iprint`](#41-output--string-building) writes into the page.

```html
<html>
<body>
  <h1>Search results</h1>
  <?icpp
    char *q;
    q = icpp_getparam("q");
    iprint("<p>You searched for: ", q, "</p>");
  ?>
</body>
</html>
```

### Including other files

`#include "otherfile.icpp"` splices another ICPP source file in at that point — for both
function definitions and top-level statements. This is how reusable ICPP libraries
(for example `icpp_autodiff.c`, or the conformance suite's `libfixture.icpp`) are pulled into a
script. See [§5](#5-the-library--include-manifest-system) for the manifest conventions that go
with it.

---

## 3. Language reference

### Types

ICPP supports the C scalar types the interpreter needs:

| Type | Notes |
|---|---|
| `int` | 32-bit integer. Also the type used to hold **handles** (see below) — a tensor/list/map/connection handle is just an `int` you pass around. |
| `double` | IEEE double. Real double arithmetic, parameters, and return values all work correctly (this was historically buggy and is now fixed and regression-covered). |
| `char *` | String pointer. A `char *` local may be assigned a string literal (`p = "hello";`) and passed to any string builtin. |
| `void` | For functions that return nothing. |
| `$var` | The one dynamically-typed slot — see below. |

Global variables are supported (`int g_global;` at file scope), and behave as globals across
functions.

### Definition order: ICPP has no forward declarations

**Within a file, a function must be defined above any call that passes it
arguments.** There is no forward declaration to write, and no header to
include.

```c
int outer(int v) { return inner(v); }   /* inner is defined below - REPORTED */
int inner(int v) { return v > 10; }
```

That is reported, naming the function and saying to move it:

```
'inner' is called with arguments before it is defined. ICPP has no forward
declarations: move the definition of 'inner' above this call.
```

A forward call that passes **no** arguments does work:

```c
char *first(void)  { if (second() == 1) { return "yes"; } return "no"; }
int   second(void) { return 1; }        /* fine - nothing is passed */
```

Worth stating plainly because the failure used to be silence: before
2026-09-23 a forward call killed the interpreter outright, with no output and
no message, so it read as a crash in whichever statement happened to contain
the call rather than as anything to do with order.

### `$var` — the dynamically-typed local

```c
$x = 5;
$y = tensor_get(handle, 0, 0);
```

A `$var` needs no declaration and infers its type (int / double / handle) from whatever it is
assigned. Internally it has a single generic 8-byte storage slot, wide enough for an int, a
double, or a handle.

**Important semantic**: a `$var`'s initializer is evaluated **at parse time**, not at the point
the statement appears to run. Ordinary (non-`$var`) statements run at normal interpreted
runtime. Mixing the two where ordering matters can surprise you. The safe, well-tested pattern:
**use plain typed locals (`int`, `double`) for anything inside a function body or a loop**, and
reserve `$var` for simple top-level scratch values in `main()` where parse-time evaluation does
not matter. A `$var` initializer must be resolvable at parse time — so a `$var` inside a
function body **cannot** be initialized from that function's parameters:

```c
int f(int x)
{
    $y = x * 2;   // parse error: "Initializing symbol 'y' must be constant number"
    return $y;
}
```

Use a plain typed local instead (`int y; y = x * 2; return y;`).

### Variable declaration & statements

Declarations are C-style (`int x; double d; char *s;`). Multiple declarations are typically
written one per statement in this codebase's scripts. Assignment, calls, and control flow are
all standard C.

### Functions — typed and typeless

**Typed functions** are ordinary C:

```c
int add(int a, int b) { return a + b; }
double scaled(double x) { return x * 1.5; }
```

**Typeless functions** use the `function` keyword (synonym: `subroutine`) — no return type, no
parameter types. Both are determined **at runtime, per call**; the same target can serve
doubles on one call and ints on the next:

```c
function scale(x, f)
{
    return x * f;
}

d = scale(2.5, 4.0);   // double path -> 10.0
i = scale(6, 7);       // SAME function, int path -> 42
m = scale(1.25, 2);    // mixed args promote like C -> 2.5
```

Rules:

- Top-level definitions only, and only in `-icpp` mode (in a plain kcpp compile, the keyword
  is a clean error).
- Each parameter is the same generic 8-byte runtime-typed slot a `$var` uses; its actual type
  is stamped from whatever each call's argument evaluates to.
- `return expr;` returns whatever type `expr` evaluated to at runtime; a function with no
  `return` may be called as a plain statement.
- Typeless functions compose and recurse; define before use, same as typed functions.
- Supported value kinds: ints, handles, and doubles. (String-typed *typeless* parameters/
  returns are not covered in this version — a typed `char *f(char *s)` is the way to return a
  string, as `libfixture.icpp`'s `fx_shout` does.)

### Control flow & operators

`if`/`else`, `while`, `do { } while (...)`, and `for (init; cond; step)` all work, with both
braced and braceless bodies, and standalone `{ }` scoping blocks. Arithmetic (`+ - * / %`),
comparison (`< <= > >= == !=`), logical (`&& || !`), bitwise (`& | ^ ~ << >>`), compound
assignment (`+= -= *= /= %= <<= >>= &= |= ^=`), and `++`/`--` (post-increment/decrement) are
supported. `int`, `double` and `float` convert into each other the way C converts them, at
assignment, argument passing and `return`. `+` also joins strings: two strings (a literal, a
`char *`, or a `$var` holding text) join, and a `$var` holding text joins a number too
(`$s + 5` is `"abc5"`). A `char *` plus a number is still pointer arithmetic, as in C. Keep a join
by assigning it to a `$var`. From the core conformance suite, every one of these asserts the correct value:

```c
int fact(int n) { if (n <= 1) return 1; int r; r = n * fact(n - 1); return r; }
int sum_while(int n) { int i; int s; s = 0; i = 1; while (i <= n) { s = s + i; i = i + 1; } return s; }
int for_sum(int n)   { int i; int s; s = 0; for (i = 1; i <= n; i = i + 1) s = s + i; return s; }
// fact(5)==120, sum_while(100)==5050, for_sum(10)==55
```

`return n * fact(n - 1);` works directly too.

### Handles

Nearly everything that is not a plain number or string in this library — a tensor, a database
connection, a query result, a list, a map, a set, an open file, an image canvas, an MCP
connection — is an **opaque handle**: an `int` returned by a constructor function, passed to
every function that operates on that object, and released with a matching
`_free` / `_disconnect` / `_fclose` call. Handles are never dereferenced in script code.

```c
int t;
t = tensor_new(2, 2);      // t is a handle
tensor_set(t, 0, 0, 5.0);  // operate via the handle
tensor_free(t);            // release when done
```

### `rtlbegin` / `rtlend` — embedded verbatim Verilog

```c
rtlbegin
module hand_counter (input clk, input rst_n, output [7:0] count);
    always @(posedge clk or negedge rst_n)
        if (!rst_n) count <= 0; else count <= count + 1;
endmodule
rtlend
```

Everything between the two keywords is passed straight through: the ICPP parser never
tokenizes it, and the interpreter ignores the block. `kcpp -rtl` copies it byte-for-byte into
the `.v` output, ahead of the generated modules so those can instantiate it. Multiple blocks
concatenate in source order. Both keywords are `-icpp`-mode only; an unterminated block is an
error naming the opening line.

---

## 4. Builtin function reference

This is the core of the manual. The registered builtins and runtime additions appear below,
grouped by category. Each entry gives the **signature** — the name, its argument count and the
return type exactly as registered in `sysfunc.c` — a one-line description, and, for
representative builtins, a short example.

Conventions used in the signatures:

- A trailing `-> T` is the registered return type. `-> int (handle)` means the return is an
  `int` used as an opaque handle.
- Argument *names* are descriptive; the interpreter checks **arity** (argument count), so the
  count shown is authoritative. `(...)` marks a **variadic** builtin (registered arg count −1).
- "1/0" means an `int` boolean; "−1" is the common bad-handle / not-found sentinel.

### 4.1 Output & string building

| Builtin | Signature | Description |
|---|---|---|
| `iprint` | `iprint(...)` -> void | Prints each argument in order, concatenated, **no format string**. Strings pass through as-is; doubles auto-format with `%g`, ints with `%d`. The general-purpose print statement for ICPP. |
| `ifprint` | `ifprint(path, ...)` -> void | `iprint`'s print-to-**file** sibling: same argument formatting, **appended** to `path` as a line (file created if absent). Good for building transcripts/logs and appending to a knowledge-base file. |
| `isprint` | `isprint(...)` -> `char *` | `iprint`'s build-a-**string** sibling — returns the concatenation instead of printing. Shares its implementation with `icpp_concat` (two names, one handler). |
| `icpp_concat` | `icpp_concat(...)` -> `char *` | Builds a string from mixed strings/numbers. Identical to `isprint`. |
| `printf` | `printf(char *fmt, ...)` -> void | Standard C conversions: `%d %i %u %x %X %o %c %s %f %e %g %p %%`, with flags, width, precision, `*` and `l`/`ll`. Each argument is converted to what its conversion expects (`%f` of an int prints `3.000000`). Every call ends its output line: `printf("a"); printf("b\n");` prints two lines. |

```c
iprint("count=", 3, " ratio=", 1.5, "\n");        // count=3 ratio=1.5
char *msg; msg = isprint("user", 42, "@site");     // "user42@site"
ifprint("bot_kb.txt", "We open at 9am and close at 6pm");  // append one line
```

### 4.2 Strings

| Builtin | Signature | Description |
|---|---|---|
| `icpp_strlen` | `icpp_strlen(char *s)` -> `int` | String length. |
| `icpp_strcmp` | `icpp_strcmp(char *a, char *b)` -> `int` | −1 / 0 / 1 (clamped), 0 when equal. |
| `icpp_strstr` | `icpp_strstr(char *hay, char *needle)` -> `int` | 0-based index of first occurrence, −1 if absent. |
| `icpp_search_txt` | `icpp_search_txt(char *needle, char *buffer)` -> `int` | 0-based index of `needle` in `buffer`, **case-insensitive**, −1 if absent. Note the argument order: the text searched for comes first. Added 2026-09-16. |
| `icpp_starts_with` | `icpp_starts_with(char *s, char *prefix)` -> `int` | 1/0. |
| `icpp_ends_with` | `icpp_ends_with(char *s, char *suffix)` -> `int` | 1/0. |
| `icpp_substr` | `icpp_substr(char *s, int start, int len)` -> `char *` | Substring of `len` chars from 0-based `start`. |
| `icpp_html_escape` | `icpp_html_escape(char *s)` -> `char *` | Escapes `& < > " '` for printing into a page. **Use it on every value that came from a visitor.** `iprint` writes its arguments verbatim, so a query parameter printed without this is a cross-site scripting hole - and a page cannot define its own helper, because icpptpl wraps every block into one `main()`. `&` is escaped first, so an already-escaped entity is escaped once, not twice. |
| `icpp_upper` | `icpp_upper(char *s)` -> `char *` | Uppercased copy. |
| `icpp_lower` | `icpp_lower(char *s)` -> `char *` | Lowercased copy. |
| `icpp_trim` | `icpp_trim(char *s)` -> `char *` | Leading/trailing whitespace removed. |
| `icpp_replace_all` | `icpp_replace_all(char *s, char *from, char *to)` -> `char *` | Every occurrence of `from` replaced by `to`. |
| `icpp_atoi` | `icpp_atoi(char *s)` -> `int` | Decimal string to int; skips leading whitespace, honors a leading sign, stops at the first non-digit (so `"350 ps"` -> 350). Use this for decimal text; `icpp_parse_hex` is base-16. |

```c
icpp_assert_eq_str(icpp_substr("hello world", 6, 5), "world", "substr");
icpp_assert_eq_str(icpp_upper("Hello"), "HELLO", "upper");
icpp_assert_eq_str(icpp_trim("  hi  "), "hi", "trim");
icpp_assert_eq_str(icpp_replace_all("a-b-c", "-", "+"), "a+b+c", "replace_all");
icpp_assert_eq_int(icpp_atoi("123"), 123, "atoi");
```

### 4.3 Regex and sed

| Builtin | Signature | Description |
|---|---|---|
| `icpp_re` | `icpp_re(char *input, char *directive)` -> `char *` | Regex match/substitute over a clean-room engine. |
| `ised` | `ised(char *text, char *script)` -> `char *` | `sed`-style stream editor on a string; returns the edited text. |
| `ised_file` | `ised_file(char *path, char *script)` -> `int` | Applies the sed script to a file **in place**; returns 1 if it changed the file, 0 if unchanged, −1 if unreadable. Only rewrites when something actually changed. |

**`icpp_re` directive language** (a small sed-like mini-language):

- `"m/PATTERN/"` — return the first matched substring, or `""` if no match.
- `"s/PATTERN/REPLACE/"` — return `input` with the **first** match of `PATTERN` replaced by
  `REPLACE`; unchanged if no match. `REPLACE` may reference capture groups with `\1`..`\9`.
  Single substitution only (no `/g` flag on `icpp_re`).
- Anything else — treated as a bare `PATTERN`, same as `"m/PATTERN/"`.

Pattern syntax: literal chars, `.`, `^`/`$` anchors, greedy `*` `+` `?`,
`[abc]`/`[^abc]`/`[a-z]` classes, `\d \D \s \S \w \W` shorthands, `(...)` capture groups,
`|` alternation.

```c
iprint(icpp_re("abc123", "m/[0-9]+/"));           // "123"
iprint(icpp_re("2026-07-31", "s/-/./"));          // "2026.07-31" (first match only)
```

**`ised`** implements the `s` command from the POSIX description (clean-room, no GNU sed read):
`s<D>pattern<D>replacement<D>[g][i]` where the delimiter `<D>` is whatever follows `s` (so
`s|/usr|/opt|` works without escaping slashes). `&` is the whole match, `\1`..`\9` are capture
groups, `\&` is a literal ampersand, `\n`/`\t` are recognized in the replacement, and the `g`
flag substitutes all occurrences on each line. `ised` processes line by line and never returns
NULL (so it chains with `icat`/`igrep`). An unparsable script returns the text **unchanged**
(and warns on stderr) rather than blanking it.

```c
iprint(ised("a-b-c", "s/-/+/g"));                 // "a+b+c"
ised_file("config.txt", "s|/usr/local|/opt|g");   // rewrite paths in place
```

> Note the two documented open bugs affecting these: interpret-mode ternary and regex `\N`
> backreference escaping — see [§8](#8-known-issues).

### 4.4 SQL / ISQL database bridge

Bridges ICPP to the ISQL database engine (statically linked; `isqldll.dll` is a load-time
dependency of `kcpp.exe`). Connection and result handles are `int`s.

| Builtin | Signature | Description |
|---|---|---|
| `icpp_sql_connect` | `icpp_sql_connect(char *dsn)` -> `int` | Open a connection; returns a connection handle. |
| `icpp_sql_connect_remote` | `icpp_sql_connect_remote(char *host, char *port, char *user, char *password [, char *database])` -> `int` | Connect to a running `isqlserverd` over TCP; returns a connection handle, or 0. See below. |
| `icpp_sql_query` | `icpp_sql_query(int conn, char *sql)` -> `int` | Run a query; returns a result handle. |
| `icpp_sql_query_params` | `icpp_sql_query_params(conn, template, ...values)` -> `int` | Validate and bind text/numeric values at `?` placeholders; returns a result handle, or 0 for local validation failure. |
| `icpp_sql_next` | `icpp_sql_next(int result)` -> `int` | Advance to the next row: 1 = a row is available, 0 = done. |
| `icpp_sql_get` | `icpp_sql_get(int result, char *colname)` -> `char *` | The current row's value for `colname`. |
| `icpp_sql_count` | `icpp_sql_count(int result)` -> `int` | Row count. |
| `icpp_sql_free` | `icpp_sql_free(int result)` -> void | Release a result handle. |
| `icpp_sql_disconnect` | `icpp_sql_disconnect(int conn)` -> void | Close a connection. |
| `icpp_sql_status` | `icpp_sql_status(int conn)` -> `char *` | Last status / error message. |

```c
int c; int r;
c = icpp_sql_connect("default");
r = icpp_sql_query(c, "SELECT name, city FROM people");
while (icpp_sql_next(r)) {
    iprint(icpp_sql_get(r, "name"), " - ", icpp_sql_get(r, "city"), "\n");
}
icpp_sql_free(r);
icpp_sql_disconnect(c);
```

Use parameters for values supplied by users:

```c
$q = icpp_sql_query_params($db,
    "insert into messages (id, body) values (?, ?);", 42, "It's ready?");
$status = icpp_sql_status($db);
icpp_sql_free($q);
$q = icpp_sql_query_params($db, "select body from messages where id=?;", 42);
while (icpp_sql_next($q)) { iprint(icpp_sql_get($q, "body")); }
icpp_sql_free($q);
```

Here `$db` is an open connection and `messages` is an existing table. This is
client-side binding to the ISQL text API, not native prepared statements. ICPP
doubles single quotes in text and formats numbers as decimal. Keep the template
in application code; placeholders represent values, never identifiers or SQL
fragments. Quoted question marks are literals. Write SQL `NULL` directly in the
template when needed. Text `"NULL"` and numeric 0 are ordinary values.

Limits: 64 values, 65536 expanded bytes, one statement with an optional final
semicolon. Template comments, unmatched quotes, missing/extra parameters and
nonfinite numbers fail before execution. Local failure returns 0 and sets
`icpp_sql_status($db)` without including parameter contents. After execution,
the existing cursor/status contract applies: a nonzero handle is not proof of
SQL success. Inspect status and the expected result, then free the cursor.
Embedded ISQL is covered by `23_sql_params.icpp`, which passes on Windows x64 and Linux x64;
remote execution has not yet been qualified for this API.

`icpp_sql_connect` opens a database home on this machine (embedded, owner access, no login).
`icpp_sql_connect_remote` is a client of a running `isqlserverd` and logs in with a real account;
every other `icpp_sql_*` call works the same on either. It never hangs: the host is probed with a
3-second timeout first, because the engine's own connect has none. Credentials containing `;` `'`
`,` or a control character are refused (0 is returned), not escaped. An ordinary account must pass
its database as the fifth argument; a superuser may omit it. One cursor per remote connection -
open a second connection for two result sets at once. `icpp_sql_disconnect` wipes the password,
which is otherwise held for the life of the connection.

```c
int c;
c = icpp_sql_connect_remote("db.example.com", "1972", "appuser", pw, "appdb");
if (c == 0) { iprint("database unavailable\n"); return 1; }
```

Compose SQL text with `isprint(...)`:
`icpp_sql_query(c, isprint("SELECT * FROM t WHERE id=", id));`

### 4.5 Files and file inspection

Text-file helpers built for verification workflows (comparing a simulation transcript against
an expected file) but general-purpose. Every function here also has a short `i*` alias — see
[§6](#6-the-i-aliases-for-filesfs-builtins).

| Builtin | Signature | Description |
|---|---|---|
| `icpp_file_read` | `icpp_file_read(char *path)` -> `char *` | Whole file as text (bounded ~4 KB — for larger files use `icat`, or the streaming helpers below). |
| `icpp_file_write` | `icpp_file_write(char *path, char *text)` -> `int` | **Truncating** write (binary mode, byte-for-byte); 1 on success, 0 on failure. Counterpart to `ifprint`'s append. |
| `icpp_file_size` | `icpp_file_size(char *path)` -> `int` | File size in bytes. |
| `icpp_file_exists` | `icpp_file_exists(char *path)` -> `int` | 1/0. |
| `icpp_file_mtime` | `icpp_file_mtime(char *path)` -> `int` | Modification time (epoch seconds). |
| `icpp_file_lines` | `icpp_file_lines(char *path)` -> `int` | Line count. |
| `icpp_file_line` | `icpp_file_line(char *path, int n)` -> `char *` | The 1-based `n`-th line. |
| `icpp_file_contains` | `icpp_file_contains(char *path, char *needle)` -> `int` | 1/0, −1 unreadable; **streams**, so huge logs are fine. |
| `icpp_file_replace` | `icpp_file_replace(char *path, char *from, char *to)` -> `int` | In-file replace `from`→`to`. |
| `icpp_file_diff` | `icpp_file_diff(char *a, char *b)` -> `int` | 0 = identical; else the 1-based first differing line; −1 unopenable. Line endings normalized (CRLF vs LF compare equal). |
| `icpp_file_hash` | `icpp_file_hash(char *path)` -> `char *` | FNV-1a 32-bit content hash, hex (distinct files essentially never collide). |
| `icpp_file_fingerprint` | `icpp_file_fingerprint(char *path)` -> `char *` | Block-level fuzzy fingerprint: file split into 16 chunks, each FNV-1a-hashed (128 hex chars). A **byte-level** near-duplicate detector, NOT a perceptual/visual hash. |

```c
ifile_write("probe.txt", "line1\nline2\nline3\n");
icpp_assert_eq_int(icpp_file_lines("probe.txt"), 3, "file_lines");
icpp_assert_eq_int(icpp_file_contains("probe.txt", "line2"), 1, "file_contains");
```

### 4.6 Filesystem operations

Each also has an `i*` alias (see [§6](#6-the-i-aliases-for-filesfs-builtins)).

| Builtin | Signature | Description |
|---|---|---|
| `icpp_mkdir` | `icpp_mkdir(char *path)` -> `int` | Create a directory. |
| `icpp_remove` | `icpp_remove(char *path)` -> `int` | Delete a file. |
| `icpp_rename` | `icpp_rename(char *from, char *to)` -> `int` | Rename/move. |
| `icpp_cwd` | `icpp_cwd()` -> `char *` | Current working directory. |
| `icpp_chdir` | `icpp_chdir(char *path)` -> `int` | Change directory. |
| `icpp_glob` | `icpp_glob(char *pattern)` -> `int` (list handle) | Non-recursive glob (e.g. `"*.v"`); returns a **list handle** of matching file names (directories excluded). Free the list with `icpp_list_free`. |
| `icpp_glob_r` | `icpp_glob_r(char *dir, char *pattern)` -> `int` (list handle) | Recursive glob under `dir`. |

```c
int files; int i;
files = icpp_glob("*.icpp");
for (i = 0; i < icpp_list_count(files); i = i + 1)
    iprint(icpp_list_get(files, i), "\n");
icpp_list_free(files);
```

### 4.7 Sequential file reading

Line-at-a-time reading over an opaque file handle. Each has an `if*` alias.

| Builtin | Signature | Description |
|---|---|---|
| `icpp_fopen` | `icpp_fopen(char *path)` -> `int` (file handle) | Open for sequential reading; 0/bad handle on failure. |
| `icpp_fgets` | `icpp_fgets(int handle)` -> `char *` | Next line, with the trailing `\n`/`\r` stripped; `""` at EOF. |
| `icpp_feof` | `icpp_feof(int handle)` -> `int` | 1 once end-of-file has been reached. |
| `icpp_fclose` | `icpp_fclose(int handle)` -> void | Close the handle. |

```c
int f; char *line;
f = ifopen("big.log");
while (!ifeof(f)) {
    line = ifgets(f);
    if (icpp_strstr(line, "ERROR") >= 0) iprint(line, "\n");
}
ifclose(f);
```

### 4.8 Environment & time

| Builtin | Signature | Description |
|---|---|---|
| `icpp_getenv` | `icpp_getenv(char *name)` -> `char *` | Environment variable value, `""` if unset. Alias: `igetenv`. |
| `icpp_setenv` | `icpp_setenv(char *name, char *value)` -> `int` | Set an environment variable. Alias: `isetenv`. |
| `icpp_time` | `icpp_time()` -> `int` | Current time as Unix epoch seconds. |
| `icpp_date_string` | `icpp_date_string()` -> `char *` | Local date-time as `"YYYY-MM-DD HH:MM:SS"`. |
| `icpp_elapsed_ms` | `icpp_elapsed_ms()` -> `int` | Milliseconds since its first call — a run timer for "suite took N ms" reporting. |

```c
iprint("started ", icpp_date_string(), "\n");
// ... work ...
iprint("took ", icpp_elapsed_ms(), " ms\n");
```

### Cooperative worker shutdown

Use `icpp_worker_begin()` before a persistent worker loop. It returns 1 on
success. `icpp_worker_stopping()` returns 0 while running, 1 after a stop request,
and -1 outside an initialized lifecycle. `icpp_worker_request_stop()` requests
a stop (1 success, 0 uninitialized). `icpp_worker_wait(ms)` returns 1 after the
timeout, 0 on stop, or -1 for invalid state/argument/OS error. The timeout must
be an integer from 0 to 60000 ms. `icpp_worker_end()` restores the old handlers
(1 success, 0 error). Repeated begin preserves an outstanding stop; repeated end
is harmless.

```c
int main(void)
{
    if (icpp_worker_begin() == 0) { return 1; }
    $ticks = 0;
    $error = 0;
    while (icpp_worker_stopping() == 0) {
        iprint("work tick ", $ticks);
        $ticks = $ticks + 1;
        if ($ticks == 3) { icpp_worker_request_stop(); }
        $wait = icpp_worker_wait(100);
        if ($wait < 0) { $error = 1; icpp_worker_request_stop(); }
    }
    // Close cursors, buffers, connections, and other resources here.
    if (icpp_worker_end() == 0) { return 1; }
    return $error;
}
```

SIGINT/SIGTERM request shutdown; Windows console Ctrl+C/Ctrl+Break do too.
Waits use monotonic time and stop checks at intervals no larger than 50 ms,
subject to scheduling. Handlers only set a flag. They do not run interpreted
code. Keep the interpreter on one thread; `ithread_create` runs external
commands and does not make interpreted functions thread-safe.

This is cooperative lifecycle support, not a worker pool, queue, event loop, or
forced cancellation. A blocked SQL/HTTP operation must return before the script
can clean up. A supervisor still needs an exit deadline; forced process kill and
Windows close/logoff/shutdown do not guarantee cleanup. Call begin/end from the
interpreter thread. Windows API and native signal/cancellation tests pass,
and `25_worker_lifecycle.icpp` passes on Linux x64; actual console/service shutdown
integration still needs qualification.

### 4.9 Binary buffers and chunked file IO

Reads raw bytes (the one thing the text file builtins cannot do). A buffer is an opaque handle;
free it when done or you leak the whole file.

| Builtin | Signature | Description |
|---|---|---|
| `icpp_bin_read` | `icpp_bin_read(char *path)` -> `int` (buffer handle) | Reads the whole file, up to 64 MiB; 0 on failure. Larger files require chunk reads. |
| `icpp_bin_new` | `icpp_bin_new(size)` -> handle | Allocate 0 to 67108864 zeroed bytes; 0 on failure. |
| `icpp_bin_set` | `icpp_bin_set(handle, offset, byte)` -> int | Set a byte from 0 to 255; 1 success, 0 invalid argument. |
| `icpp_bin_read_chunk` | `icpp_bin_read_chunk(path, offset, count)` -> handle | Read at most count bytes. EOF returns a valid empty buffer; 0 means error. |
| `icpp_bin_write` | `icpp_bin_write(handle, path)` -> int | Create or truncate a binary file; return byte count or -1 on error. |
| `icpp_bin_write_at` | `icpp_bin_write_at(handle, path, offset)` -> int | Update an existing file; offset may equal EOF to append, but may not exceed EOF. Return byte count or -1. |
| `icpp_bin_size` | `icpp_bin_size(int handle)` -> `int` | Byte count; −1 on a bad handle. |
| `icpp_bin_get` | `icpp_bin_get(int handle, int offset)` -> `int` | The byte (0..255) at `offset`; **−1** out of range (so a real 0 byte is distinguishable from an error). |
| `icpp_bin_diff` | `icpp_bin_diff(int a, int b, int start)` -> `int` | The first offset `>= start` where the two buffers differ; **−1** when they are identical from there on. If one buffer is shorter, its size counts as a difference. **−2** on a bad handle or a negative start. Walk every difference with `d = icpp_bin_diff(a, b, d + 1)` — byte-by-byte comparison in script costs minutes per megabyte. |
| `icpp_bin_int32` | `icpp_bin_int32(int handle, int offset)` -> `int` | 32-bit **little-endian** integer at that byte offset; 0 if out of range. |
| `icpp_bin_float` | `icpp_bin_float(int handle, int offset)` -> `double` | 32-bit float at that **byte** offset, widened to double; 0.0 if out of range. |
| `icpp_bin_find` | `icpp_bin_find(int handle, char *text)` -> `int` | Byte offset of the first occurrence of `text`, −1 if absent. Length-based search, so embedded NULs do not end it early (e.g. "which DLLs does this .exe import"). |
| `icpp_bin_free` | `icpp_bin_free(int handle)` -> `int` | Free the buffer. |

```c
int b;
b = icpp_bin_read("vec.bin");
iprint("size=", icpp_bin_size(b), " first float=", icpp_bin_float(b, 0), "\n");
if (icpp_bin_find(b, "msvcr") >= 0) iprint("links a VC runtime\n");
icpp_bin_free(b);
```

All new numeric arguments must be integers, not strings or fractional numbers.
Buffers retain NUL and high-bit bytes. Chunk counts are bounded to 64 MiB;
offsets currently range from 0 through 2147483647. Free each chunk after use.
Handles are opaque: freeing releases its slot, double-free is harmless, and a
stale handle cannot access a later allocation. Limit: 4095 live binary buffers
per interpreter process. The subsystem is intended for the interpreter thread.

```c
$bytes = icpp_bin_new(4);
if ($bytes == 0) { icpp_exit(1); }
icpp_bin_set($bytes, 0, 0);
icpp_bin_set($bytes, 1, 255);
icpp_bin_set($bytes, 2, 13);
icpp_bin_set($bytes, 3, 10);
$written = icpp_bin_write($bytes, "payload.bin");
icpp_bin_free($bytes);
if ($written != 4) { icpp_exit(1); }
$part = icpp_bin_read_chunk("payload.bin", 1, 2);
if ($part == 0) { icpp_exit(1); }
iprint(icpp_bin_get($part, 0)); // 255
icpp_bin_free($part);
```

File APIs use the existing `ICPP_FILE_ROOT` gate. These are file primitives, not
HTTP multipart or resumable-upload protocols. Writes are not atomic, locked, or
fsync-durable; an IO failure may leave a partial file. Use an application-owned
temporary path, check the returned count, then publish only after validation.
Conformance: `24_binary_write.icpp` exercises byte preservation, bounds, stale
handles, chunk reads, range writes, and 5000 allocation/free cycles.

### 4.10 Hex and bit manipulation

RTL work is hex-first; these give a script hex I/O and Verilog-style bit slicing.

| Builtin | Signature | Description |
|---|---|---|
| `icpp_hex` | `icpp_hex(int value, int digits)` -> `char *` | Zero-padded lowercase hex, **no** `0x` prefix; `digits<=0` means "as many as needed", clamped to 8. Negatives print as their 32-bit two's-complement pattern (`icpp_hex(-1, 8)` -> `"ffffffff"`). |
| `icpp_parse_hex` | `icpp_parse_hex(char *s)` -> `int` | Parse hex; tolerates `ff`, `FF`, `0xff`, `0XFF`, and leading spaces. |
| `icpp_bits` | `icpp_bits(int value, int hi, int lo)` -> `int` | Verilog's `value[hi:lo]` bit slice. Indices in either order are accepted (swapped), clamped to 0..31. |
| `icpp_bin` | `icpp_bin(int value, int width)` -> `char *` | MSB-first `0`/`1` text, exactly `width` bits (clamped to 32). |

```c
icpp_assert_eq_int(icpp_parse_hex("ff"), 255, "parse_hex");
icpp_assert_eq_str(icpp_hex(255, 2), "ff", "hex");
iprint("ctrl[7:4]=", icpp_bits(0xAB, 7, 4), "\n");   // 10
iprint("bin=", icpp_bin(5, 4), "\n");                // 0101
```

### 4.11 Lists and split/join

Handle-based, ordered list of strings. Stored strings are copied (reuse your buffers freely).

| Builtin | Signature | Description |
|---|---|---|
| `icpp_list_new` | `icpp_list_new()` -> `int` (handle) | New empty list. |
| `icpp_list_add` | `icpp_list_add(int h, char *s)` -> `int` | Append; returns the new count. |
| `icpp_list_get` | `icpp_list_get(int h, int i)` -> `char *` | 0-based element; out-of-range gives `""`. |
| `icpp_list_set` | `icpp_list_set(int h, int i, char *s)` -> `int` | **Replace** element `i` (a copy of `s` is stored); 1 on success, 0 when `i` is negative or past the end. It never extends the list - use `icpp_list_add` for that. |
| `icpp_list_count` | `icpp_list_count(int h)` -> `int` | Element count. |
| `icpp_list_sort` | `icpp_list_sort(int h)` -> `int` | Lexicographic in-place sort. |
| `icpp_list_free` | `icpp_list_free(int h)` -> void | Free the list. |
| `icpp_split` | `icpp_split(char *text, char *sep)` -> `int` (list handle) | Split `text` on the **literal string** `sep`; the trailing field is kept. Returns a list handle. |
| `icpp_join` | `icpp_join(int h, char *sep)` -> `char *` | Join a list's elements with `sep`. |

```c
int L;
L = icpp_split("a::b::c", "::");           // 3 items
icpp_assert_eq_int(icpp_list_count(L), 3, "split");
iprint(icpp_join(L, "-"));                 // "a-b-c"
icpp_list_free(L);
```

### 4.12 Maps and dicts

A linear-scan association array of string→string, sized for script use. The `icpp_dict_*`
names are **Python-familiar aliases** for the identical `icpp_map_*` implementation (same
handle interchangeably usable through either name).

| Builtin | Signature | Description |
|---|---|---|
| `icpp_map_new` | `icpp_map_new()` -> `int` (handle) | New empty map. |
| `icpp_map_set` | `icpp_map_set(int h, char *key, char *val)` -> `int` | Insert/**replace** (existing key is overwritten, not duplicated). |
| `icpp_map_get` | `icpp_map_get(int h, char *key)` -> `char *` | Value, `""` if absent — use `has` to distinguish. |
| `icpp_map_has` | `icpp_map_has(int h, char *key)` -> `int` | 1/0. |
| `icpp_map_count` | `icpp_map_count(int h)` -> `int` | Entry count. |
| `icpp_map_keys` | `icpp_map_keys(int h)` -> `int` (list handle) | Keys in insertion order (free the returned list). |
| `icpp_map_delete` | `icpp_map_delete(int h, char *key)` -> `int` | Remove a key. |
| `icpp_map_free` | `icpp_map_free(int h)` -> void | Free the map. |
| `icpp_dict_new` | `icpp_dict_new()` -> `int` (handle) | Alias of `icpp_map_new`. |
| `icpp_dict_set` | `icpp_dict_set(int h, char *k, char *v)` -> `int` | Alias of `icpp_map_set`. |
| `icpp_dict_get` | `icpp_dict_get(int h, char *k)` -> `char *` | Alias of `icpp_map_get`. |
| `icpp_dict_has` | `icpp_dict_has(int h, char *k)` -> `int` | Alias of `icpp_map_has`. |
| `icpp_dict_count` | `icpp_dict_count(int h)` -> `int` | Alias of `icpp_map_count`. |
| `icpp_dict_keys` | `icpp_dict_keys(int h)` -> `int` (list handle) | Alias of `icpp_map_keys`. |
| `icpp_dict_delete` | `icpp_dict_delete(int h, char *k)` -> `int` | Alias of `icpp_map_delete`. |
| `icpp_dict_free` | `icpp_dict_free(int h)` -> void | Alias of `icpp_map_free`. |

```c
int M;
M = icpp_map_new();
icpp_map_set(M, "one", "1");
icpp_map_set(M, "two", "2");
icpp_assert_eq_str(icpp_map_get(M, "one"), "1", "map get");
icpp_map_delete(M, "one");
icpp_assert_eq_int(icpp_map_has(M, "one"), 0, "map delete");
icpp_map_free(M);
```

### 4.13 Sets

A set of unique strings.

| Builtin | Signature | Description |
|---|---|---|
| `icpp_set_new` | `icpp_set_new()` -> `int` (handle) | New empty set. |
| `icpp_set_add` | `icpp_set_add(int h, char *value)` -> `int` | Add (duplicates ignored). |
| `icpp_set_has` | `icpp_set_has(int h, char *value)` -> `int` | 1/0 membership. |
| `icpp_set_count` | `icpp_set_count(int h)` -> `int` | Element count. |
| `icpp_set_remove` | `icpp_set_remove(int h, char *value)` -> `int` | Remove an element. |
| `icpp_set_items` | `icpp_set_items(int h)` -> `int` (list handle) | Members as a list (free it). |
| `icpp_set_free` | `icpp_set_free(int h)` -> void | Free the set. |

```c
int S; int L;
S = icpp_set_new();
icpp_set_add(S, "apple");
icpp_set_add(S, "apple");                 // dup -> ignored
icpp_assert_eq_int(icpp_set_count(S), 1, "dedup");
L = icpp_set_items(S);
icpp_list_free(L);
icpp_set_free(S);
```

### 4.14 Tuples

An immutable ordered sequence of strings: once you **read** it (any `count`/`get`), it is
sealed and further `add`s are rejected with −1.

| Builtin | Signature | Description |
|---|---|---|
| `icpp_tuple_new` | `icpp_tuple_new()` -> `int` (handle) | New empty tuple (still mutable until first read). |
| `icpp_tuple_add` | `icpp_tuple_add(int h, char *value)` -> `int` | Append while unsealed; **−1** once sealed. |
| `icpp_tuple_get` | `icpp_tuple_get(int h, int index)` -> `char *` | 0-based element (this seals the tuple). |
| `icpp_tuple_count` | `icpp_tuple_count(int h)` -> `int` | Element count (this seals the tuple). |
| `icpp_tuple_free` | `icpp_tuple_free(int h)` -> void | Free the tuple. |

```c
int T; int n;
T = icpp_tuple_new();
icpp_tuple_add(T, "x"); icpp_tuple_add(T, "y");
icpp_assert_eq_int(icpp_tuple_count(T), 2, "count seals it");
n = icpp_tuple_add(T, "z");
icpp_assert_eq_int(n, -1, "immutable after read");
icpp_tuple_free(T);
```

### 4.15 Process execution & test harness

These make an ICPP script a drop-in replacement for a Perl/Python/shell regression driver.

| Builtin | Signature | Description |
|---|---|---|
| `icpp_exec` | `icpp_exec(char *cmdline)` -> `int` | Run it; child output goes to your console; returns the exit code (−1 = could not start). |
| `icpp_exec_capture` | `icpp_exec_capture(char *cmdline)` -> `char *` | Returns the child's stdout **and stderr** merged as a string. |
| `icpp_exec_to_file` | `icpp_exec_to_file(char *cmdline, char *path)` -> `int` | Both streams into `path`; then search it with the streaming `icpp_file_contains`/`icpp_file_diff`. |
| `icpp_exec_status` | `icpp_exec_status()` -> `int` | Exit code of the last `icpp_exec_capture` (which returns text, not a code). |
| `icpp_assert` | `icpp_assert(int cond, char *msg)` -> `int` | Prints `PASS:`/`FAIL:`, counts it. |
| `icpp_assert_eq_int` | `icpp_assert_eq_int(int actual, int expected, char *msg)` -> `int` | Same, printing **both** values on mismatch. |
| `icpp_assert_eq_str` | `icpp_assert_eq_str(char *actual, char *expected, char *msg)` -> `int` | Same, for strings. |
| `icpp_test_summary` | `icpp_test_summary()` -> `int` | Prints `=== N checks: P passed, F failed ===`; returns **F** (the failure count). |
| `icpp_exit` | `icpp_exit(int code)` -> void | Terminate immediately with that exit status. |

The idiomatic CI ending: `icpp_exit(icpp_test_summary());` — the process exit code becomes the
number of failed checks.

```c
int rc;
rc = icpp_exec_to_file("kcpp.exe -rtl design.icpp", "gen.log");
icpp_assert_eq_int(rc, 0, "RTL generated");
icpp_assert_eq_int(icpp_file_contains("gen.log", "** Error"), 0, "no errors");
icpp_exit(icpp_test_summary());
```

### 4.16 The `i*` shell utilities

grep/cat/cut/etc. without leaving ICPP. Every string-returning one allocates a result sized to
what it produced (no 4 KB ceiling), so `icat` of a 200 KB log returns 200 KB.

| Builtin | Signature | Description |
|---|---|---|
| `icat` | `icat(char *path)` -> `char *` | The whole file. |
| `ihead` | `ihead(char *path, int n)` -> `char *` | First `n` lines. |
| `itail` | `itail(char *path, int n)` -> `char *` | Last `n` lines (ring buffer — works on a multi-GB transcript). |
| `igrep` | `igrep(char *path, char *text)` -> `char *` | The lines containing `text`. |
| `igrep_count` | `igrep_count(char *path, char *text)` -> `int` | How many lines contain it. |
| `icut` | `icut(char *text, char *delim, int field)` -> `char *` | The 1-based `field` of every line. Takes **text** (not a path), so it composes: `icut(icat(f), ":", 3)`. |
| `ils` | `ils(char *dir)` -> `char *` | One entry per line; directories end in `/`. |
| `ifind` | `ifind(char *dir, char *pattern)` -> `char *` | Matching paths, searched recursively (`*` and `?`). |
| `ireplace` | `ireplace(char *path, char *from, char *to)` -> `int` | Byte-exact in-file replace; returns the count. |
| `ibash` | `ibash(char *cmdline)` -> `char *` | Runs the line under `bash -c`; returns its output. Needs a bash on PATH (Git for Windows/WSL/MSYS2); with none, the result is empty and `icpp_exec_status()` is −1. |
| `imake` | `imake(char *args)` -> `int` | Runs **kmake** (not nmake, not mingw32-make); build output streams to the console. Finds kmake via `$KMAKE_EXE`, then beside the running exe, then PATH. |
| `ikill` | `ikill(char *who)` -> `int` | Kill matching processes (`who` = pid or image name); returns how many. Terminates without cleanup, and by name kills every copy. |
| `irunning` | `irunning(char *who)` -> `int` | How many matching processes are alive. |
| `isleep` | `isleep(int ms)` -> `int` | Block for `ms` milliseconds. |
| `ised` | `ised(char *text, char *script)` -> `char *` | sed on a string — see [§4.3](#43-regex-and-sed). |
| `ised_file` | `ised_file(char *path, char *script)` -> `int` | sed on a file in place — see [§4.3](#43-regex-and-sed). |

(`iprint`, `ifprint`, `isprint` are in [§4.1](#41-output--string-building); the file-oriented
`i*` aliases such as `icat`'s cousins `ifile_read`/`iglob`/etc. are in
[§6](#6-the-i-aliases-for-filesfs-builtins).)

```c
if (icpp_strstr(itail("vsim.log", 20), "ALL PASSED") >= 0)
    iprint("passed with ", igrep_count("vsim.log", "Warning"), " warnings\n");
iprint(icut(igrep("parts.txt", "MRR"), ":", 3));   // 3rd colon field of matching lines
if (irunning("vsim.exe")) ikill("vsim.exe");
imake("makefile");
```

### 4.17 Threads and CPU affinity

Run several **external commands** at once and pin them to cores.

| Builtin | Signature | Description |
|---|---|---|
| `ithread_create` | `ithread_create(char *cmdline)` -> `int` | Start the command on a thread; returns a handle, or −1. |
| `ithread_join` | `ithread_join(int handle)` -> `int` | Wait; returns **that command's** exit code. |
| `ithread_barrier` | `ithread_barrier()` -> `int` | Wait for every outstanding thread; returns how many. |
| `ithread_affinity_set` | `ithread_affinity_set(int handle, int mask)` -> `int` | `handle>=0` pins that worker thread; `handle<0` sets the **process** affinity (which children inherit). |
| `CPU_ZERO` | `CPU_ZERO()` -> `int` | Return an empty CPU mask. |
| `CPU_SET` | `CPU_SET(int cpu, int mask)` -> `int` | **Return** `mask` with `cpu` added (ICPP has no output parameters, so the mask is returned). |
| `icpu_count` | `icpu_count()` -> `int` | Logical processor count, so a script can size its own fan-out. |

```c
int m; int a; int b;
m = CPU_ZERO(); m = CPU_SET(0, m); m = CPU_SET(1, m);
ithread_affinity_set(-1, m);               // children inherit PROCESS affinity
a = ithread_create("vsim.exe -c -do run_a.do");
b = ithread_create("vsim.exe -c -do run_b.do");
icpp_assert_eq_int(ithread_join(a), 0, "run A passed");
ithread_barrier();
```

> **A thread runs an external command, never an interpreted ICPP function.** The interpreter is
> not reentrant (a call writes shared state in the function prototype), so two threads inside
> the same ICPP function would corrupt each other's parameter addresses. Prefer `ithread_join`'s
> return value over `icpp_exec_status()` with threads (that status is a single global the
> threads race for). To pin a *tool* to cores, set the **process** affinity (`handle<0`) before
> launching it; a child inherits the process mask, not the creating thread's.

### 4.18 Images, OCR, fingerprints/AFIS

Two **independent** fingerprint matchers with non-comparable scales, plus perceptual image
hashing, cropping, and OCR.

| Builtin | Signature | Description |
|---|---|---|
| `icpp_image_phash` | `icpp_image_phash(char *path)` -> `char *` | Perceptual hash of an image (decodes real pixels via stb_image). |
| `icpp_phash_similarity` | `icpp_phash_similarity(char *a, char *b)` -> `int` | Similarity (0–100-ish) between two perceptual hashes. |
| `icpp_image_crop` | `icpp_image_crop(char *in, int x, int y, int w, int h, char *out)` -> `int` | Crop a rectangle from `in` and write it to `out`; success 1/0. |
| `icpp_ocr_extract` | `icpp_ocr_extract(char *image_path)` -> `char *` | Extract text from an image (shells to the vendored Tesseract). |
| `icpp_file_fingerprint` | `icpp_file_fingerprint(char *path)` -> `char *` | Byte-level block fingerprint — see [§4.5](#45-files-and-file-inspection). |
| `icpp_fingerprint_similarity` | `icpp_fingerprint_similarity(char *a, char *b)` -> `int` | Percentage (0–100) of matching blocks between two `icpp_file_fingerprint` strings. |
| `icpp_fingerprint_match` | `icpp_fingerprint_match(char *scan_path, char *template_path)` -> `int` | Biometric fingerprint match via **NIST NBIS** (mindtct + bozorth3). |
| `icpp_afis_extract` | `icpp_afis_extract(char *image_path)` -> `int` (handle) | Extract minutiae with the in-tree **SourceAFIS-to-C** port; 0 = failure. Handle-based so 1:N identification extracts once and matches many. |
| `icpp_afis_minutiae` | `icpp_afis_minutiae(int handle)` -> `int` | Minutiae count; −1 = bad handle. |
| `icpp_afis_match` | `icpp_afis_match(int probe, int candidate)` -> `double` | Similarity score (the probe's edge hash is built on first use and cached on its handle). |
| `icpp_afis_match_files` | `icpp_afis_match_files(char *p1, char *p2)` -> `double` | One-shot convenience: extract both and match. |
| `icpp_afis_free` | `icpp_afis_free(int handle)` -> void | Free an AFIS handle. |

> The NBIS (`icpp_fingerprint_match`) and SourceAFIS (`icpp_afis_*`) scores are **not comparable
> to each other** — different algorithms, unrelated scales — but each separates genuine from
> impostor pairs on its own scale. Pick a threshold per matcher from your own data.

```c
int probe; int candidate;
probe = icpp_afis_extract("probe.png");
candidate = icpp_afis_extract("candidate.png");
if (icpp_afis_match(probe, candidate) >= 40.0) iprint("MATCH\n");
icpp_afis_free(probe);
icpp_afis_free(candidate);
```

### 4.19 Software graphics canvas

A handle-based RGB canvas rendered in software and saved as a real PNG (vendored
`stb_image_write`). Colors are `0xRRGGBB` ints (red `16711680`, green `65280`, blue `255`).

| Builtin | Signature | Description |
|---|---|---|
| `icpp_img_new` | `icpp_img_new(int w, int h)` -> `int` (handle) | New white canvas. |
| `icpp_img_set` | `icpp_img_set(int h, int x, int y, int rgb)` -> `int` | Set a pixel. |
| `icpp_img_get` | `icpp_img_get(int h, int x, int y)` -> `int` | Pixel color, −1 out of bounds. |
| `icpp_img_line` | `icpp_img_line(int h, int x0, int y0, int x1, int y1, int rgb)` -> `int` | Bresenham line. |
| `icpp_img_rect` | `icpp_img_rect(int h, int x, int y, int w, int ht, int rgb)` -> `int` | Rectangle outline. |
| `icpp_img_fill_rect` | `icpp_img_fill_rect(int h, int x, int y, int w, int ht, int rgb)` -> `int` | Filled rectangle. |
| `icpp_img_save_png` | `icpp_img_save_png(int h, char *path)` -> `int` | Write PNG; 1/0. |
| `icpp_img_free` | `icpp_img_free(int h)` -> void | Free the canvas. |

```c
int c;
c = icpp_img_new(64, 64);
icpp_img_fill_rect(c, 0, 0, 64, 64, 255);          // blue background
icpp_img_line(c, 0, 0, 63, 63, 16711680);          // red diagonal
icpp_img_save_png(c, "out.png");
icpp_img_free(c);
```

### 4.20 MCP client + JSON

ICPP is an MCP (Model Context Protocol) **client** over stdio: it spawns a tool server as a
child process and speaks newline-delimited JSON-RPC 2.0 over its stdin/stdout, with the
`initialize` handshake included.

| Builtin | Signature | Description |
|---|---|---|
| `icpp_mcp_connect` | `icpp_mcp_connect(char *cmdline)` -> `int` (handle) | Spawn the server and perform the handshake; 0 = failure. A bare relative exe name resolves against the current directory. |
| `icpp_mcp_list_tools` | `icpp_mcp_list_tools(int h)` -> `char *` | The server's raw `tools/list` JSON — drill in with `icpp_json_get`. |
| `icpp_mcp_call` | `icpp_mcp_call(int h, char *tool, char *argsjson)` -> `char *` | Call a tool; returns `result.content[0].text` (or the raw response). If `argsjson` has no `"`, you may use single quotes — `"{'a':3,'b':4}"` — auto-converted. |
| `icpp_mcp_disconnect` | `icpp_mcp_disconnect(int h)` -> void | Close the server's stdin (EOF), wait, terminate a straggler. |
| `icpp_json_get` | `icpp_json_get(char *json, char *path)` -> `char *` | Extract by dotted path, e.g. `"result.tools.0.name"` (numeric segment = array index). Strings come back unescaped; objects/arrays come back as raw JSON for further drilling. Works on any JSON. |

```c
int h;
h = icpp_mcp_connect("test_mcp_server.exe");
iprint(icpp_json_get(icpp_mcp_list_tools(h), "result.tools.0.name"), "\n");  // add
iprint(icpp_mcp_call(h, "add", "{'a':3,'b':4}"), "\n");                       // 7
icpp_mcp_disconnect(h);
```

### 4.21 OpenAI-compatible chat

| Builtin | Signature | Description |
|---|---|---|
| `icpp_openai_chat` | `icpp_openai_chat(char *base_url, char *api_key, char *model, char *prompt)` -> `char *` | One-call chat completion: POSTs `{base_url}/v1/chat/completions` (WinHTTP handles TLS), returns the assistant reply (`choices[0].message.content`), or the raw error JSON, or `""` on transport failure. Shares the transport of section 4.32, so it is bounded by `ICPP_HTTPS_TIMEOUT_MS` and the 8 MB cap; it is deliberately exempt from the reserved-address rule, because its endpoints are local model servers and its URL is written by the script author rather than arriving from a form. Works against `https://api.openai.com` (key required) and local OpenAI-compatible servers (Ollama, LM Studio, etc.). Empty key = no Authorization header. |

```c
iprint(icpp_openai_chat("http://localhost:11434", "", "llama3", "Say hi in one word"));
```

### 4.22 CGI parameter access

| Builtin | Signature | Description |
|---|---|---|
| `icpp_getparam` | `icpp_getparam(char *name)` -> `char *` | Read one parameter from a CGI-style `QUERY_STRING` (as set by `iwebserver` before running the interpreter), URL-decoded; `""` if not found or no query string. Used inside `<?icpp ... ?>` pages. |

```c
char *user;
user = icpp_getparam("user");                 // ?user=anis  ->  "anis"
iprint("<p>Hello, ", user, "</p>");
```

### 4.23 Tensor engine — core operations

A tensor is a 2D, row-major array of `double`, referenced by an opaque handle. All shapes are
`[rows, cols]`. Handles are freed with `tensor_free`.

| Builtin | Signature | Description |
|---|---|---|
| `tensor_new` | `tensor_new(int rows, int cols)` -> `int` (handle) | Zero-filled tensor. |
| `tensor_free` | `tensor_free(int handle)` -> void | Release. |
| `tensor_get` | `tensor_get(int handle, int row, int col)` -> `double` | Element read. |
| `tensor_set` | `tensor_set(int handle, int row, int col, double value)` -> `int` | Element write (1 = ok). |
| `tensor_rows` | `tensor_rows(int handle)` -> `int` | Row count. |
| `tensor_cols` | `tensor_cols(int handle)` -> `int` | Column count. |
| `tensor_init_spread` | `tensor_init_spread(int handle, int seed)` -> `int` | Deterministically fill with spread-out values from `seed` (a training-free initializer). |
| `tensor_matmul` | `tensor_matmul(int A, int B)` -> `int` (handle) | Matrix multiply; `A.cols` must equal `B.rows`. |
| `tensor_add` | `tensor_add(int A, int B)` -> `int` (handle) | Elementwise add (identical shapes, no broadcasting). |
| `tensor_sub` | `tensor_sub(int A, int B)` -> `int` (handle) | Elementwise subtract. |
| `tensor_scale` | `tensor_scale(int handle, double factor)` -> `int` (handle) | Elementwise scalar multiply. |
| `tensor_transpose` | `tensor_transpose(int handle)` -> `int` (handle) | `[r,c]` -> `[c,r]`. |
| `tensor_relu` | `tensor_relu(int handle)` -> `int` (handle) | Elementwise `max(0,x)`. |
| `tensor_softmax` | `tensor_softmax(int handle)` -> `int` (handle) | Row-wise, numerically stable. |
| `tensor_argmax` | `tensor_argmax(int handle, int row)` -> `int` | Column index of the largest value in that row ("which class"). |
| `tensor_linear` | `tensor_linear(int x, int weight, int bias)` -> `int` (handle) | `x @ weight + bias`, bias `[1,out]` broadcast down each row. The standard trainable projection layer. |

```c
int a; int b; int c;
a = tensor_new(2, 2); tensor_set(a, 0, 0, 1.0); tensor_set(a, 1, 1, 1.0);
b = tensor_new(2, 2); tensor_set(b, 0, 1, 2.0); tensor_set(b, 1, 0, 3.0);
c = tensor_matmul(a, b);
iprint("c[0][1]=", tensor_get(c, 0, 1), "\n");
tensor_free(a); tensor_free(b); tensor_free(c);
```

### 4.24 Tensor engine — neural-network / LLM layers

| Builtin | Signature | Description |
|---|---|---|
| `tensor_layernorm` | `tensor_layernorm(int x, int gamma, int beta, double eps)` -> `int` | Row-wise normalize to mean 0 / var 1, then scale/shift; `gamma`/`beta` are `[1,cols]`. |
| `tensor_embedding_lookup` | `tensor_embedding_lookup(int table, int ids)` -> `int` | `table` is `[vocab,d_model]`, `ids` is `[1,n]` of token IDs (doubles, rounded); gathers `n` rows. |
| `tensor_causal_mask` | `tensor_causal_mask(int scores)` -> `int` | Force upper-triangular (future) positions to a large negative number, for autoregressive attention. |
| `tensor_positional_encoding` | `tensor_positional_encoding(int seq_len, int d_model)` -> `int` | Fixed sinusoidal encoding, no learned parameters. |
| `tensor_multihead_attention` | `tensor_multihead_attention(int Q, int K, int V, int num_heads, int causal)` -> `int` | Real per-head column slicing; Q's row count may differ from K/V's (cross-attention). |
| `tensor_self_attention` | `tensor_self_attention(int x, int wq, int bq, int wk, int bk, int wv, int bv, int wo, int bo, int num_heads, int causal)` -> `int` | Full trainable layer: Q/K/V/output projections + attention, all from one input `x`. (11 args.) |
| `tensor_cross_attention` | `tensor_cross_attention(int query_x, int kv_x, int wq, int bq, int wk, int bk, int wv, int bv, int wo, int bo, int num_heads, int causal)` -> `int` | As above, but Q from `query_x` and K/V from a different sequence `kv_x`. (12 args.) |
| `tensor_tokenize` | `tensor_tokenize(char *text)` -> `int` | Byte-level: a `[1,strlen(text)]` tensor of raw byte values (vocab 256, no OOV). |
| `tensor_detokenize` | `tensor_detokenize(int handle)` -> `char *` | Exact inverse of `tensor_tokenize`. |
| `tensor_cross_entropy_loss` | `tensor_cross_entropy_loss(int logits, int targets)` -> `double` | `logits` `[seq_len,vocab]`, `targets` `[1,seq_len]`; returns the **mean** per-token loss. |

> **Scope note**: attention's *backward* pass (§4.25) is only mathematically correct for
> `num_heads=1`. Forward attention supports any `num_heads`; training a true multi-head model
> would need a native multi-head backward op.

### 4.25 Autodiff (backward / gradient rules)

This is **explicit backprop**, not an autodiff graph: save whatever forward tensors a backward
call needs, and call the backward functions yourself in reverse order. Each rule below was
verified by numerical gradient checking.

| Builtin | Signature | Gradient of |
|---|---|---|
| `tensor_relu_backward` | `tensor_relu_backward(int x, int dy)` -> `int` (dx) | `relu(x)`; needs the forward **input** `x`. |
| `tensor_softmax_backward` | `tensor_softmax_backward(int y, int dy)` -> `int` (dx) | `softmax(x)`; needs the forward **output** `y`. |
| `tensor_layernorm_backward_x` | `tensor_layernorm_backward_x(int x, int gamma, int dy, double eps)` -> `int` (dx) | layernorm input gradient. |
| `tensor_layernorm_backward_gamma` | `tensor_layernorm_backward_gamma(int x, int dy, double eps)` -> `int` (dgamma) | layernorm scale gradient. |
| `tensor_layernorm_backward_beta` | `tensor_layernorm_backward_beta(int dy)` -> `int` (dbeta) | Pure sum-over-rows; also reusable for any broadcast-bias gradient. |
| `tensor_embedding_lookup_backward` | `tensor_embedding_lookup_backward(int table, int ids, int dy)` -> `int` (dtable) | Scatter-**add** (a repeated token ID accumulates gradient from every occurrence). |
| `tensor_cross_entropy_loss_backward` | `tensor_cross_entropy_loss_backward(int logits, int targets)` -> `int` (dlogits) | `(softmax(logits) - one_hot(target)) / N`; no upstream gradient argument (always the last op). |

### 4.26 Optimizer & persistence

| Builtin | Signature | Description |
|---|---|---|
| `tensor_sgd_step` | `tensor_sgd_step(int param, int grad, double lr)` -> void | **Mutates `param` in place** — the one deliberate exception to the "always return a fresh handle" rule, because a parameter persists across thousands of steps (like a real `optimizer.step()`). There is no `zero_grad`; accumulate a mini-batch with ordinary `tensor_add` into a fresh (zero-filled) accumulator. |
| `tensor_save` | `tensor_save(int handle, char *path)` -> `int` | Persist a tensor as inspectable text (`ICPPTENSOR rows cols` + one `%.17g` value per line). This is how an LLM trained by one ICPP script is used by another. |
| `tensor_load` | `tensor_load(char *path)` -> `int` (handle) | Load a tensor saved with `tensor_save`. |

### 4.27 Text embedding & chatbot/RAG support

Native support for the customer-support chatbot library (`icpp_chatbot.c`, itself written with
ICPP's typeless `function`s). See also `icpp_file_line`/`icpp_file_lines`
([§4.5](#45-files-and-file-inspection)) and `icpp_openai_chat`
([§4.21](#421-openai-compatible-chat)), which the bot also uses.

| Builtin | Signature | Description |
|---|---|---|
| `icpp_text_embed` | `icpp_text_embed(char *text, int dim)` -> `int` (tensor `[1,dim]`) | Hashed character-bigram embedding (deterministic, training-free; lowercased, whitespace-collapsed). Use dim 256. |
| `tensor_cosine` | `tensor_cosine(int a, int b)` -> `double` | Cosine similarity of two same-shaped tensors — the ranking half of retrieval. |

```c
// simple RAG retrieval: pick the closest KB line to a question
int q; int best; int i; double s; double bestscore;
q = icpp_text_embed("what time do you open", 256);
best = -1; bestscore = -2.0;
for (i = 1; i <= icpp_file_lines("bot_kb.txt"); i = i + 1) {
    int e; e = icpp_text_embed(icpp_file_line("bot_kb.txt", i), 256);
    s = tensor_cosine(q, e);
    if (s > bestscore) { bestscore = s; best = i; }
    tensor_free(e);
}
iprint("bot: ", icpp_file_line("bot_kb.txt", best), "\n");
tensor_free(q);
```

### 4.28 Core C builtins

| Builtin | Signature | Description |
|---|---|---|
| `malloc` | `malloc(int size)` -> `void *` | Allocate `size` zero-initialized bytes (the returned block is zeroed). |
| `printf` | `printf(char *fmt, ...)` -> void | See [§4.1](#41-output--string-building). |

---

### 4.29 Python and Java inside ICPP

Each runs a program and returns **everything it printed** as a string. Nothing is spawned: no
`python.exe`, no JVM and no temporary file. The languages live in `kpython` and `kjava` libraries
(`.dll`/`.so`), which are loaded on first use from `$KCPP_KPYTHON`/`$KCPP_KJAVA`, then from the
directory holding kcpp, then from the system search path.

| Builtin | Signature | Description |
|---|---|---|
| `pscript` | `pscript(char *source)` -> `char *` | Run Python source held in a string. |
| `python` | `python(char *path)` -> `char *` | Run a Python file. |
| `jscript` | `jscript(char *source)` -> `char *` | Run Java source held in a string. |
| `java` | `java(char *path)` -> `char *` | Run a Java file. |

```c
$n = icpp_atoi(pscript("print(6 * 7)"));        // 42
$r = pscript("print(7 // 2)\nprint(7 / 2)");     // "3\n3.5\n" - Python's own division rules
$j = jscript("class M { public static void main(String[] a) { System.out.println(7 / 2); } }");  // "3\n"
```

Both are **subsets**. Python has numbers, strings, lists, `def`/`return`/recursion,
`if`/`elif`/`else`, `while`, `for`-in, and string and list methods. It has no classes, imports,
dicts, comprehensions or standard library. Java has `int`/`long`/`double`/`String`/`boolean`, arrays,
recursive methods, `if`/`else`, `while`, `for` and for-each, and string methods. It has no instances,
inheritance, generics, exceptions or class library. **Errors come back in the returned string, never
as a crash**: `python error, line 1: name 'x' is not defined`, or `python error: cannot open 'f.py'`.
A missing library is reported the same way. Output is capped at 64 KB per call.

**Language sessions: one value seen from ICPP, Python, Java and JSON.** `pscript`/`jscript`
throw everything away when the run ends. A *session* keeps a language's symbol table alive
between runs and lets ICPP read and write it directly, so a value computed in Python can be
read by Java or by the page without printing and parsing it. JSON is a language here too: a
document parsed once *is* a symbol table, every leaf at its dotted path.

| Builtin | Signature | Description |
|---|---|---|
| `icpp_lang_open` | `icpp_lang_open(char *lang)` -> `int` | `"python"`, `"java"` or `"json"`. A session id, or **0** if the library could not be loaded (the reason is printed). |
| `icpp_lang_run` | `icpp_lang_run(int id, char *source)` -> `char *` | Run source in the session (for JSON: parse a document into it). Returns what it printed; errors come back in the text. Functions and variables survive to the next run. |
| `icpp_lang_set` | `icpp_lang_set(int id, char *name, value)` -> `int` | Set a variable. A number crosses as a number, text as text. For JSON the name is a dotted path, which builds a document. |
| `icpp_lang_get` | `icpp_lang_get(int id, char *name)` -> `char *` | A value as text; `""` for an unknown name. A JSON container reads back as the JSON it was written as; a long whole number stays exact. |
| `icpp_lang_getnum` | `icpp_lang_getnum(int id, char *name)` -> `double` | A value as a number. It is a `double` — compare it as one (`== 42`), not with `icpp_assert_eq_int`. |
| `icpp_lang_has` | `icpp_lang_has(int id, char *name)` -> `int` | 1 if the name is there. |
| `icpp_lang_kind` | `icpp_lang_kind(int id, char *name)` -> `char *` | `"none"`, `"bool"`, `"int"`, `"real"`, `"text"`, `"list"`, or `"missing"`. |
| `icpp_lang_names` | `icpp_lang_names(int id)` -> `char *` | Every name the session holds, comma-separated (`"n,m"`). |
| `icpp_lang_limit` | `icpp_lang_limit(int id, int ms)` -> `int` | CPU-time limit for one run (below); 0 removes it. |
| `icpp_lang_close` | `icpp_lang_close(int id)` -> `int` | Free the session; a closed session holds nothing. |

```c
$py = icpp_lang_open("python");
icpp_lang_set($py, "n", 6);
icpp_lang_run($py, "m = n * 7");
$m = icpp_lang_getnum($py, "m");                       // 42

$js = icpp_lang_open("json");
icpp_lang_run($js, "{\"order\":{\"id\":\"ORD-77\",\"lines\":[{\"item\":\"desk\",\"qty\":2}]}}");
iprint(icpp_lang_get($js, "order.lines.0.item"));      // desk
icpp_lang_close($py);
icpp_lang_close($js);
```

JSON is strict RFC 8259: single quotes, trailing commas, comments and NaN are refused, and the
error names the line and column. Conformance coverage: `16_lang_sessions.icpp` (35 checks).

**A run can be given a time limit.** `icpp_lang_limit(id, ms)` caps how long one
`icpp_lang_run` on that session may take, which is what makes it safe to run source
you did not write — `while True: pass` cannot be interrupted from outside, so the
interpreter checks between statements whether its time is up. A run that reaches
the limit ends as an ordinary error (`script exceeded its time limit`) and leaves
the session usable. The limit is CPU time, not wall time: a spinning script burns
CPU, while a slow one on a loaded machine should not be killed for it. It returns 1
when the language library can enforce the limit and 0 when it is too old to — treat
0 as "do not run source you did not write through this library".

### 4.30 Digests, base64, and a page that allows its own script

A browser runs an inline script only if the page's Content Security Policy allows it, and the honest
way to allow exactly one script is to name its SHA-256 — not `'unsafe-inline'`, which allows every
other script as well. These let a page do that for itself, with no help from whatever serves it.

| Builtin | Signature | Description |
|---|---|---|
| `icpp_sha256` | `icpp_sha256(char *text)` -> `char *` | SHA-256, as 64 hex characters. |
| `icpp_sha256_base64` | `icpp_sha256_base64(char *text)` -> `char *` | The same digest in base64 — what a policy names. |
| `icpp_base64` | `icpp_base64(char *text)` -> `char *` | Base64 encode. |
| `icpp_unbase64` | `icpp_unbase64(char *text)` -> `char *` | Base64 decode; whitespace is skipped and anything else ends the decode, so mangled input gives back what was readable. |
| `icpp_script` | `icpp_script(char *path)` -> `char *` | The file wrapped in `<script>…</script>`, with its digest remembered for the policy. `""` if the file cannot be read. |
| `icpp_script_src` | `icpp_script_src(char *path)` -> `char *` | Its policy source alone, `'sha256-…'`, also remembered. Use in `<head>`, before the script is printed. |
| `icpp_script_srcs` | `icpp_script_srcs()` -> `char *` | Every source asked for so far, space separated, ready for `script-src`. A file asked for twice is listed once. |

**A page that allows its own script.** The policy must reach the browser before the thing it governs,
so take the digest in `<head>` and print the script at the end — both read the same file, so they
cannot drift apart:

```html
<head>
<?icpp
    $ignored = icpp_script_src("skillpicker.js");
    iprint("<meta http-equiv='Content-Security-Policy' content=\"default-src 'self'; ",
           "script-src ", icpp_script_srcs(), "\">");
?>
</head>
<body>
  <!-- ... the page ... -->
<?icpp iprint(icpp_script("skillpicker.js")); ?>
</body>
```

Served, that becomes:

```html
<meta http-equiv='Content-Security-Policy' content="default-src 'self'; script-src 'sha256-uNFB0ew8vPTNvVEY5HmGeKJGlvyfHER2san4/5gEkZ0='">
...
<script>/* the file, exactly */</script>
```

A working page built this way ships in `test/icpp_conformance/skillpicker_demo.icpp.html`: a field
where tapping a suggested skill, or typing one and pausing, adds a chip with an `x` that removes it.

**The digest covers what is printed, not what is on disk.** On Windows a stdout in text mode rewrites
`\n` as `\r\n`, so hashing the file itself would name bytes the browser never receives and the
script would be refused. `icpp_script` and `icpp_script_src` ask stdout which mode it is in and hash
accordingly; on Linux nothing is rewritten and the digest is the file's. What they cannot account for
is output rewritten afterwards by something else — print what was hashed.

> `icpp_sha256` is a **hash**, not a password scheme. Storing passwords needs a key-derivation
> function (scrypt, Argon2); this is not one.

### 4.31 Ciphers, signatures, key derivation and randomness

Section 4.30 hashes. These do the other half: sign a webhook, store a password, keep a secret at
rest, and get bytes nobody can guess. All of it in process, so a key lives in a `$var` rather than
on a command line where `ps` can read it.

| Builtin | Signature | Description |
|---|---|---|
| `icpp_hmac_sha256` | `icpp_hmac_sha256(char *key, char *text)` -> `char *` | 64 hex characters. The key is **raw text, not hex**. RFC 2104 / FIPS 198-1, so it agrees with every payment provider's `hmac.new(key, msg, sha256)`. |
| `icpp_pbkdf2` | `icpp_pbkdf2(char *password, char *salt_hex, int iterations)` -> `char *` | 64 hex (32 bytes), PBKDF2-HMAC-SHA256. The **salt is hex**, not text — a salt is random bytes, and a random byte is not a character. `""` if the salt is not hex, or `iterations` is outside 1…10000000. |
| `icpp_random_hex` | `icpp_random_hex(int nbytes)` -> `char *` | `2 x nbytes` hex characters from the **OS CSPRNG** — `BCryptGenRandom` on Windows, `/dev/urandom` on Linux. `nbytes` is 1…64; anything else, or a CSPRNG that will not answer, gives `""`. |
| `icpp_encrypt` | `icpp_encrypt(char *key_hex, char *plaintext)` -> `char *` | AES-256-GCM. Returns base64 of `IV(12) + tag(16) + ciphertext`, so decrypting needs the key and nothing else. |
| `icpp_decrypt` | `icpp_decrypt(char *key_hex, char *blob)` -> `char *` | The plaintext, or `""`. |
| `icpp_base64_encode` | `icpp_base64_encode(char *text)` -> `char *` | The OpenSSL-shaped spelling of `icpp_base64`. **The same builtin**, not a second implementation. |
| `icpp_base64_decode` | `icpp_base64_decode(char *text)` -> `char *` | Likewise for `icpp_unbase64`. |

**Verifying a webhook, which is the common case.** A provider signs the raw body with your secret
and you must compare against the *raw* body — not a re-encoded copy, because re-encoding changes
bytes and the signature is over bytes:

```c
void main()
{
    char *secret; char *raw; char *mine;
    secret = icpp_getenv("STRIPE_WEBHOOK_SECRET");
    raw    = icpp_file_read("body.json");
    mine   = icpp_hmac_sha256(secret, raw);
    if (icpp_strcmp(mine, icpp_getparam("signature")) == 0)
        printf("signature good\n");
    else
        printf("REJECTED - do not act on this request\n");
}
```

**Storing a password.** Never the password, never a bare SHA-256 of it. A salt per user, and
iterations high enough to hurt:

```c
    char *salt; char *hash;
    salt = icpp_random_hex(16);                 /* 16 bytes, new for every user */
    hash = icpp_pbkdf2("correct horse battery", salt, 600000);
    /* store salt AND hash; to check a login, run the same call again */
```

**A secret at rest.**

```c
    char *key; char *blob; char *back;
    key  = icpp_random_hex(32);                 /* 32 bytes = AES-256; keep it off the page */
    blob = icpp_encrypt(key, "4242424242424242");
    back = icpp_decrypt(key, blob);             /* "" if the key or the blob is wrong */
```

Four things worth knowing before you rely on any of it:

- **`icpp_decrypt` returns `""` for every failure and does not say which.** Wrong key, truncated
  blob, tampered ciphertext — all `""`. That is deliberate: a decryption oracle that explains itself
  is a decryption oracle. It also means `""` is never partial plaintext.
- **Iterations are the entire mechanism of `icpp_pbkdf2`.** It is slow on purpose. A few hundred
  thousand is the point; lowering it to make a login feel quick removes the protection.
- **A Linux build made without the OpenSSL headers has no AES at all**, and `icpp_encrypt` /
  `icpp_decrypt` return `""` there rather than falling back to something weaker. Hashing, HMAC,
  PBKDF2 and `icpp_random_hex` still work.
- **`icpp_sha256` is a hash, not a password scheme.** For a password, `icpp_pbkdf2`.

### 4.32 HTTPS requests

One round trip, in process. A page can call a payment API without a shell, and the key stays in a
`$var`.

| Builtin | Signature | Description |
|---|---|---|
| `icpp_https_get` | `icpp_https_get(char *url, char *headers)` -> `char *` | The response body; `""` on transport failure. |
| `icpp_https_post` | `icpp_https_post(char *url, char *headers, char *body)` -> `char *` | The same, with a body. |
| `icpp_https_status` | `icpp_https_status()` -> `int` | The HTTP status of the **last completed** call; `0` if none completed. |

`headers` is **one string, lines separated by `\n`**, and `""` means none:

```c
void main()
{
    char *body; char *head;
    head = icpp_concat("Authorization: Bearer ", icpp_getenv("STRIPE_SECRET_KEY"),
                       "\nContent-Type: application/x-www-form-urlencoded");
    body = icpp_https_post("https://api.stripe.com/v1/charges", head,
                           "amount=2000&currency=usd&source=tok_visa");

    if (icpp_https_status() == 200)
        printf("charged: %s\n", icpp_json_get(body, "id"));
    else if (icpp_https_status() == 0)
        printf("no answer at all - network, DNS or timeout\n");
    else
        printf("declined (%d): %s\n", icpp_https_status(),
               icpp_json_get(body, "error.message"));
}
```

**An HTTP error is not a transport failure.** A 401 returns its body *and* a status of 401, so the
script can read the provider's own message. `""` with status `0` is the only "we never got an
answer" — so test the status, not whether the body is empty.

**No redirects are followed.** A 30x comes back as-is and the script decides. Following one silently
is how a request carrying an `Authorization` header replays that header at whatever host the
redirect named.

Both `http://` and `https://` are accepted; a URL with no scheme is refused rather than guessed, so
a request meant for TLS cannot go out in the clear. The certificate **and the host name** are
verified — WinHTTP on Windows, OpenSSL on Linux. A Linux build made without the OpenSSL headers
fails an `https://` URL cleanly instead of sending your key to port 443 in plaintext.

| Environment variable | Default | Meaning |
|---|---|---|
| `ICPP_HTTPS_TIMEOUT_MS` | `30000` | Connect, read and write timeout in milliseconds. Read once. A value that does not parse, or is `<= 0`, keeps the default — it never means "no timeout". |
| `ICPP_HTTPS_ALLOW_PRIVATE` | unset | `1` permits loopback, private and link-local addresses. |

**The timeout is not a comfort setting.** A page-driven request with no timeout hangs the thread
serving it, and `iwebserver` is thread-per-connection: enough hung requests and the process dies.
That is a denial of service reachable from a page, which is why it cannot be switched off.

**A URL a page supplies cannot reach loopback, private, link-local or other reserved addresses.**
Without that rule `icpp_https_get` pointed at `169.254.169.254` reads cloud instance credentials,
and pointed at `127.0.0.1` reaches every admin port on the machine. **The check is made on the
resolved address, after DNS** — a host name that resolves to `127.0.0.1` would walk straight through
a check made on the spelling. Set `ICPP_HTTPS_ALLOW_PRIVATE=1` when you genuinely mean to call a
service on your own machine.

Two more, both of which surprise people:

- **The response is capped at 8 MB**, and a body containing an embedded NUL will look short, because
  bodies come back as ICPP strings. Fine for JSON; binary belongs in a file.
- **Header lines containing a CR or a control character, or lacking a colon, are dropped** rather
  than repaired. A header assembled from a form field is how header injection starts.

**Never log the `headers` argument and never print it into a page.** It is where the key is.

#### Sending email: `icpp_send_email`

| Builtin | Signature | Description |
|---|---|---|
| `icpp_send_email` | `icpp_send_email(char *from, char *to, char *message)` -> `int` | `1` when the mail service accepted the message, `0` otherwise. |

Mail goes out over **HTTPS, not SMTP**: hosting providers commonly block outbound SMTP, so an SMTP
builtin would work on a dev box and fail in production. The default service is Resend
(`https://api.resend.com/emails`), over the same transport, timeout and address rules as
`icpp_https_post`.

**The API key is never an argument.** It is read from the environment, so it is not in the page
source and not in a `$var` a template might print:

| Variable | Meaning |
|---|---|
| `ICPP_MAIL_KEY` | the mail service's API key; unset -> every call returns `0` |
| `ICPP_MAIL_URL` | the endpoint, default `https://api.resend.com/emails` |

- `from` is `"Name <addr@domain>"` or `"addr@domain"`; the domain must be verified with the service.
- `to` is one address, or several separated by commas.
- `message` may begin with a `Subject: ...` line; the rest is the body. No subject line gives
  `(no subject)`. A body whose first non-blank character is `<` is sent as **HTML**, anything else
  as plain text.

```c
void main()
{
    $msg = icpp_concat("Subject: Your report is ready\n",
                       "<p>Hello,</p><p>Your test has been graded.</p>");
    if (icpp_send_email("JIPSAT <noreply@jipsat.com>", "candidate@example.com", $msg) == 1)
        printf("sent\n");
    else
        printf("not sent (HTTP %d)\n", icpp_https_status());
}
```

An address containing a CR or LF, or one without `@`, is refused before anything is sent.
`icpp_https_status()` afterwards holds the service's HTTP status, `0` when nothing was sent.

### 4.33 QR codes and barcodes

A shop prints codes: a QR code on a flyer that opens the site, a barcode on a
product label that the till reads. These two builtins make them as SVG, in
process, from the published standards (ISO/IEC 18004, 15417, 15420) with no
library and no temporary file. A page prints the string inline and the browser
draws it at any size; it prints crisp because the SVG asks for
`shape-rendering="crispEdges"`, which is what keeps a small code scannable.

| Builtin | Signature | Description |
|---|---|---|
| `icpp_qrcode_svg` | `icpp_qrcode_svg(char *text, int module_px)` -> `char *` | A QR code holding `text` (byte mode, error-correction level M, the smallest version 1..40 that fits, up to 2331 bytes), as an SVG document. `module_px` is the size of one module in pixels (1..40; 0 or out of range means 4); the quiet zone is 4 modules. `""` when `text` is empty or too long. |
| `icpp_barcode_svg` | `icpp_barcode_svg(char *text, char *kind, int module_px)` -> `char *` | A one-dimensional barcode with the text printed under the bars. `kind` is `"code128"` (any printable ASCII, 1..80 characters; code set B; the checksum symbol is added), `"ean13"` (12 digits get their check digit computed, 13 are verified and refused when wrong) or `"upca"` (11 or 12 digits, likewise). `module_px` is the width of the narrowest bar in pixels. `""` for anything that cannot be encoded - a character outside the set, the wrong number of digits, a bad check digit, an unknown kind. |

Both return `""` on every failure and say nothing about which, so a script has
one thing to test for. The result is a complete `<svg>` element: print it where
the picture should appear.

```c
/* A "scan to open" code on a flyer page. */
iprint("<p>", icpp_qrcode_svg("https://nouhata.com/", 6), "</p>");

/* A product label: the SKU as Code 128, and the retail number as EAN-13. */
iprint(icpp_barcode_svg("NOUHATA-SKU-0001", "code128", 2));
iprint(icpp_barcode_svg("400638133393", "ean13", 2));   /* prints 4006381333931 */

$svg = icpp_barcode_svg($typed, "ean13", 2);
if (icpp_strlen($svg) == 0) iprint("<p class=\"error\">That is not a valid EAN-13 number.</p>");
```

Reading a code from a picture is the other half: see 4.34.

### 4.34 Reading QR codes and barcodes from pictures

The other half: a photo of a flyer, a screenshot, a scan of a label, and the
text that was in the code. Own implementation of ISO/IEC 18004, 15417 and
15420 - the writers of 4.33 run backwards, sharing their tables - with no
decoding library; the picture file itself is opened by the image builtins'
decoder (PNG, JPEG, BMP, GIF, TGA, PSD).

| Builtin | Signature | Description |
|---|---|---|
| `icpp_qrcode_read` | `icpp_qrcode_read(char *path)` -> `char *` | The text in the QR code found in the picture, or `""`. Any version 1..40 and all four error-correction levels; numeric, alphanumeric and byte segments (bytes come back as they were encoded, UTF-8 in practice), Kanji as its Shift JIS bytes. The code may be rotated, upside down, tilted, photographed at an angle, unevenly lit, blurred, or partly smudged (up to what its error-correction level can repair). It must be dark on light. |
| `icpp_barcode_read` | `icpp_barcode_read(char *path)` -> `char *` | The text of the Code 128, or the digits of the EAN-13 / UPC-A, found in the picture, or `""`. A UPC-A comes back as its 13-digit EAN form (leading zero included), which is how the till stores it. The label may be rotated by any right angle or upside down, tilted a little, unevenly lit or slightly blurred; the check digit or checksum must hold, so a misread comes back as `""` rather than as wrong digits. |
| `icpp_barcode_kind` | `icpp_barcode_kind()` -> `char *` | `"ean13"` or `"code128"` after a successful `icpp_barcode_read`, `""` after a failed one. |

Reading takes a few tens of milliseconds for a photo; very large pictures are
shrunk first. Nothing is written to disk and nothing leaves the machine.

```c
/* A seller photographs a product's barcode from the phone: the upload is
   already on disk, so ask it what it says and find the product. */
$digits = icpp_barcode_read($upload);
if (icpp_strlen($digits) > 0 && icpp_strcmp(icpp_barcode_kind(), "ean13") == 0)
    $c = icpp_sql_query(db, icpp_concat("select product_id,title from products where barcode=", nh_q($digits), ";"));

/* A scan of a flyer: where does its QR code point? */
$url = icpp_qrcode_read("uploads/flyer.jpg");
if (icpp_strlen($url) == 0) iprint("<p>No QR code could be read in that picture.</p>");
```

### 4.35 Checked SQL commands, transactions and handle ownership

`icpp_sql_exec_params($connection, $template, ...$values)` uses the same checked
value binding as `icpp_sql_query_params`, but returns **1 only when ISQL reports
successful execution**, and 0 for validation, handle, capacity or engine errors.
It releases the temporary result automatically. Inspect `icpp_sql_status($connection)`
immediately on failure. Success is not an affected-row count: an UPDATE that
matches no rows can succeed. For SELECT results, use `icpp_sql_query_params`.

`icpp_sql_commit($connection)` and `icpp_sql_rollback($connection)` execute the
engine's COMMIT and ROLLBACK commands and return 1/0 with the same status contract.
There is no relational BEGIN command here. Transactions are scoped by the engine's
user/database context, not an independent ICPP connection. Relational writes can
be visible before COMMIT, and recovery preserves open relational writes after a
crash. These APIs do not provide ACID isolation or atomic distributed job claims.
DDL, vector transactions, concurrent writers and externally modified tables need
separate qualification. Do not share an account/database transaction context
between unrelated writers expecting independent rollback.

**Engine requirement:** the September SDK DLL failed a before-image test, turning
`baseline` into `aseline` during rollback. The corrected local source-build DLL
passes that test and reconnect persistence. Qualified Windows x64 DLL SHA256:
`AC5926CB59C6F44915C3377AD2638EABA752F19F7E4F31FF3DFBAE72D40359B6`.
Use the qualified runtime package; the function name cannot make an older server
or DLL transaction-safe. Remote servers must be qualified independently.

Example after creating a disposable `command_test(id int, label char(240))` table:

```icpp
$ok = icpp_sql_exec_params($db,
    "insert into command_test values (?, ?);", 1, "baseline");
if ($ok == 1) { $ok = icpp_sql_commit($db); }
if ($ok == 0) { iprint(icpp_sql_status($db)); }
$ok = icpp_sql_exec_params($db,
    "update command_test set label=? where id=?;", "changed", 1);
if ($ok == 1) { $ok = icpp_sql_rollback($db); }
// On the qualified engine, label is now "baseline" again.
```

SQL handles are opaque, generation-tagged positive integers. They must not be
constructed, incremented, stored across processes, converted from text or passed
as floating-point numbers. A freed handle cannot alias a later allocation.
Cursor functions reject connection handles; disconnect rejects cursor handles.
Disconnect closes and invalidates every cursor owned by that connection.
Column indexes must be nonnegative integers without overflowing the engine's
one-based conversion. Invalid reads return 0 or an empty string; invalid teardown
is harmless. A remote connection accepts only one active cursor: free it before
issuing another query, checked command, COMMIT or ROLLBACK. A rejected command
does not overwrite that cursor's result.

```icpp
$q = icpp_sql_query_params($db, "select * from command_test where id=?;", 1);
while (icpp_sql_next($q)) { iprint(icpp_sql_get($q, "label")); }
icpp_sql_free($q);
$q = 0;
icpp_sql_disconnect($db);
$db = 0;
```

Regression cases: `26_sql_handles.icpp` (24 checks) and
`27_sql_commands.icpp` (17 checks), using `ICPP_GAP_TEST_HOME` for a disposable
database. No missing-engine result counts as a pass.

### 4.36 External jobs and local communication transport

#### External jobs

These functions run a trusted executable without invoking a shell. The interpreter
remains single-threaded. Arguments use the executable's Windows command-line rules;
never construct them from unvalidated request input. The existing execution sandbox
gate is checked before launch. At most 16 job handles can be live, including finished
jobs that have not been freed.

| Function | Result |
|---|---|
| `icpp_job_start($exe, $arguments, $timeout_ms)` | Positive handle, or 0 on failure. Deadline: 1–86400000 ms. |
| `icpp_job_state($job)` | 0 running, 1 completed, 2 timed out, 3 cancelled, -1 invalid. |
| `icpp_job_exit($job)` | Process exit code after completion; -1 while running or invalid. |
| `icpp_job_cancel($job)` | 1 for a valid handle, 0 invalid. Cancellation is asynchronous. |
| `icpp_job_free($job)` | Cancels if needed, waits for cleanup, frees the slot; 1 success, 0 invalid. |

A native watcher enforces deadlines even while the interpreter is busy. A Windows
Job Object contains descendants; timeout/cancellation terminates that group. Closing
the owning process also closes the job and requests descendant termination. Timeout
uses exit code 124; cancellation uses 125. A normally completed process may itself
return those codes, so use `icpp_job_state` to distinguish the outcome. Successful
parent completion also terminates remaining descendants. Output is not captured by
these APIs; design the worker's output contract explicitly. These are execution
primitives, not a durable queue or exactly-once delivery system.

```icpp
$exe = icpp_getenv("TRUSTED_WORKER_EXE");
icpp_worker_begin();
$job = icpp_job_start($exe, "--once", 30000);
if ($job != 0) {
    while (icpp_job_state($job) == 0 && icpp_worker_stopping() == 0) {
        icpp_worker_wait(50);
    }
    if (icpp_worker_stopping() != 0) { icpp_job_cancel($job); }
    iprint("state=", icpp_job_state($job), " exit=", icpp_job_exit($job));
    icpp_job_free($job);
}
icpp_worker_end();
```

Tests: `native/test_jobs.c` (52 checks) and `28_jobs.icpp` (14 checks). The latter
requires `ICPP_JOB_TEST_EXE` pointing to the compiled native fixture. Both pass on
Windows x64 and on Linux x64. Live deployment supervisor termination still needs
separate qualification.

#### HTTP request and WebSocket transport

*Qualified on Windows x64. The Linux x64 build compiles the same transport over POSIX
sockets, but no conformance file drives it yet: treat it as unqualified on Linux.*

The listener binds **127.0.0.1 only**, with 32 combined listener/peer slots. This is
an HTTP/1.1 backend for an application event loop. Public TLS routing, trusted proxy
configuration, user sessions and authorization are application/deployment concerns.
An Origin allowlist is useful for browser requests but is not user authentication.

| Function | Contract |
|---|---|
| `icpp_net_listen($port)` | Listener handle or 0; port 1–65535. |
| `icpp_net_accept($listener, $ms)` | Parsed HTTP peer or 0; one total accept/header deadline, 1–60000 ms. |
| `icpp_net_header($peer, $name)` | Header text, or empty. `:method` and `:path` expose request metadata. |
| `icpp_net_state($handle)` | 1 listener, 2 HTTP peer, 3 WebSocket, 0 invalid/closed. |
| `icpp_net_error()` | Last transport diagnostic; do not use as a per-peer state store. |
| `icpp_net_close($handle)` | Release listener/peer; 1 success, 0 invalid. |
| `icpp_http_remaining($peer)` | Remaining Content-Length bytes; -1 invalid. |
| `icpp_http_read($peer, $count, $ms)` | Binary buffer handle or 0; count 1–65536, deadline 1–60000 ms. EOF returns a valid zero-byte buffer. |
| `icpp_http_reply($peer, $status, $text)` | Send bounded plain-text response and close; 1 success, 0 failure. |
| `icpp_ws_upgrade($peer)` | Validate RFC 6455 handshake and upgrade; 1 success, 0 failure. Authorize first. |
| `icpp_ws_recv($peer, $ms)` | Complete message as binary buffer, or 0 on idle/error/close. Check peer state to distinguish idle. |
| `icpp_ws_opcode($peer)` | Last received data opcode: 1 text, 2 binary, 0 none, -1 invalid. |
| `icpp_ws_send($peer, $buffer, $opcode, $ms)` | Send data or control frame; 1 success, 0 invalid/failure. Opcodes 1, 2, 9 ping, 10 pong. |

HTTP headers are capped at 8191 bytes. Duplicate headers, Transfer-Encoding, Expect,
malformed header names and control characters are rejected. Content-Length is bounded
at 1 GiB; applications must impose smaller per-user/request limits as appropriate.
The transport does not parse multipart bodies or chunked transfer coding. It never
maps URL paths to filesystem paths. Authorize and choose a trusted destination first.
Body reads allocate at most 64 KiB. Each returned binary handle must be freed.

WebSocket messages are capped at 65536 bytes; control frames at 125 bytes. Incoming
frames must be masked. Fragmentation with interleaved control frames is supported;
text and close reasons undergo UTF-8 validation. Unsupported extensions/RSV bits,
reserved opcodes and invalid lengths are rejected. Ping receives pong automatically.
There is no outgoing application queue: sends are synchronous and bounded by their
deadline. A failed partial read/write closes the peer so a later call cannot interpret
remaining bytes as a fresh frame. A peer that remains idle is not closed automatically;
the application needs its own heartbeat/idle policy and fair multi-peer scheduling.
Compression and subprotocol negotiation are not implemented.

Example of bounded, authorized body streaming inside an HTTP handler:

```icpp
// $peer is already authenticated; $destination is a server-chosen file.
$offset = 0;
$empty = icpp_bin_new(0);
$ok = icpp_bin_write($empty, $destination) == 0;
icpp_bin_free($empty);
while ($ok && icpp_http_remaining($peer) > 0) {
    $chunk = icpp_http_read($peer, 16384, 1000);
    if ($chunk == 0) { $ok = 0; }
    else {
        $length = icpp_bin_size($chunk);
        $ok = icpp_bin_write_at($chunk, $destination, $offset) == $length;
        if ($ok) { $offset = $offset + $length; }
        icpp_bin_free($chunk);
    }
}
if ($ok) { icpp_http_reply($peer, 200, isprint($offset)); }
else { icpp_net_close($peer); }
```

The local integration fixture `transport_fixture.icpp` demonstrates exact decimal
Upload-Offset checking and resuming a server-owned attachment file after restart.
It uses a **test-only** bearer value and Origin policy. It is not a production
authentication example. Upload ownership, metadata, checksums, locking, quotas and
atomic publication remain separate work; partial bytes are not a completed attachment.
For string equality in ICPP, use `icpp_strcmp($left, $right) == 0`.

The external protocol driver `icpp-gap-work/test-transport.cjs` runs a real Edge browser
against the ICPP fixture, plus raw hostile-frame and streaming-upload cases. All 21
checks passed, including exact binary contents, stale offsets, restart resume,
interrupted bodies and header rejection. Browser automation is test tooling; the
server and upload handler are implemented in ICPP and its native runtime.

### 4.37 Durable ISQL worker queue

Include `KamrangaC++/lib/chat_email_queue.icpp` using a path relative to your script.
Every participant must use the same permanent local lock-file path and the same
ISQL database. Do not delete/replace that lock file, bypass the queue functions to
write `ce_jobs`, or operate unrelated transactions under the same database/user.
This design serializes cooperating processes on one host; it is not a distributed
lock or a substitute for engine isolation. A network-filesystem lock is unqualified.

`icpp_lock_acquire($path, $ms)` acquires a filesystem-backed exclusive lock and returns
a positive opaque handle, or 0 on failure/timeout. Timeout is 0–60000 ms; 0 tries once.
`icpp_lock_release($handle)` returns 1 on release, 0 for an invalid/stale handle.
The OS releases a lock if its owning process terminates. File access passes the
runtime sandbox gate. The anchor file remains after release, by design.

Queue APIs return 1/0 except claim, which returns a map handle or 0:

| Function | Purpose |
|---|---|
| `ce_queue_init($db,$lockfile)` | Create or validate `ce_jobs`. |
| `ce_queue_put($db,$lockfile,$id,$kind,$payload,$maxtries,$now)` | Idempotent enqueue by ID; conflicting kind/payload reuse fails. |
| `ce_queue_claim($db,$lockfile,$worker,$now,$seconds)` | Claim ready work or recover an expired lease. Lease: 1–3600 seconds. |
| `ce_queue_update($db,$lockfile,$id,$fence,$now,$mode,$delay,$error)` | Complete (mode 1), retry (2), or renew (3). |

Pass trusted server epoch seconds as `$now`, not timestamps supplied by an HTTP
client. Current queue timestamps use ISQL int and are bounded below the signed
32-bit limit; migration is required before 2038. IDs/workers allow 64 bytes, kind
32 bytes, payload 4096 bytes, errors 1024 bytes. Attempts are limited to 1–100.
Retry delay is 0–3600 seconds; renewing requires a positive duration.

A claim map contains `id`, `kind`, `payload`, `fence`, and `attempt`. Free it with
`icpp_map_free`. The cryptographically random fencing token changes on every claim;
completion/renewal/retry requires the current token and a still-live lease. Expired
or replayed completions fail. A final failed attempt moves to `dead`; a completed
job moves to `done`. Dead and completed records are retained for inspection.
An expired final attempt is moved to `dead` by the next claim; that claim can return
0 even if other work exists, so polling should continue. Queue capacity/retention
and monitoring remain application policy.

```icpp
$lockfile = isprint($private_dir, "/jobs.lock");
ce_queue_init($db, $lockfile);
$now = icpp_time();
ce_queue_put($db, $lockfile, "notification-42", "push", "message-id=42", 3, $now);
$job = ce_queue_claim($db, $lockfile, "worker-1", $now, 60);
if ($job != 0) {
    $id = icpp_map_get($job, "id");
    $fence = icpp_map_get($job, "fence");
    // Execute an idempotent handler, renewing before the lease expires.
    $completed = ce_queue_update($db, $lockfile, $id, $fence, icpp_time(), 1, 0, "");
    icpp_map_free($job);
}
```

Delivery is **at least once**. If a handler performs an external side effect and
dies before recording completion, a later worker can repeat it. Use the stable job
ID as an idempotency key where supported. A fencing token protects queue state;
it cannot revoke an already-started external request. Do not mark completion until
the handler reports success. Use bounded `icpp_job_start` execution for blocking work.

Validation: `30_durable_queue.icpp` passed 28 checks (enqueue deduplication, leases,
renewal, reconnect recovery, fencing, retry delay, dead letters and completion).
`31_queue_processes.icpp` passed 7 checks, including simultaneous contenders and
automatic lock release after terminating the holder. Run only with disposable
`ICPP_GAP_TEST_HOME` and `ICPP_GAP_TEST_FILES`; tests reset the fixture queue.

### 4.38 Math: minimum, maximum, roots, logarithms and trigonometry

`icpp_min(a, b)` returns the smaller number. `icpp_max(a, b)` returns the
larger number. `min(a, b)` and `max(a, b)` are equivalent short names.
These built-ins require exactly two finite numeric arguments. Integers,
decimals, and mixed integer/decimal pairs are accepted; strings are not
converted to numbers. An invalid type, NaN, infinity, or wrong argument count
produces an interpreter error.

The selected operand retains its numeric type. Equal values select the first
operand, including when one is an integer and the other is a decimal, or when
the operands are positive and negative zero. These APIs compare scalar values;
`tensor_argmax()` instead returns a tensor element's index.

```cpp
int main(void)
{
    $smallest = icpp_min(3, 8);       // 3
    $largest = icpp_max(-8, -3);      // -3
    $price = icpp_min(12.50, 9.75);   // 9.75 (decimal)
    $mixed = icpp_max(2, 2.5);       // 2.5 (decimal)
    $short_name = max(9, 4);         // 9
    iprint($smallest, " ", $largest, " ", $price, " ", $mixed);

    // Clamp a percentage to the inclusive range 0 through 100.
    $requested = 125;
    $percentage = icpp_min(100, icpp_max(0, $requested)); // 100

    // Compare more than two values by nesting calls.
    $lowest = icpp_min(icpp_min(12, 5), 9); // 5
    iprint($percentage, " ", $lowest);
    return 0;
}
```

Invalid examples (run separately; each produces an error):

```cpp
icpp_min("3", 8);    // numeric strings are not accepted
icpp_max(8);         // missing second argument
icpp_min(1, 2, 3);   // use nested calls for three values
```

Conformance coverage: `KamrangaC++/test/icpp_conformance/34_min_max.icpp`.

Validation: 32 numeric checks in `34_min_max.icpp` and 8 invalid-input subprocess
checks in `35_min_max_errors.icpp` pass on Windows x64 and Linux x64.

#### Roots, logarithms, powers and trigonometry

Every one of these takes `int` or `double` arguments and **returns a `double`**. A domain
error (the square root of a negative, the logarithm of zero, `asin(2)`) or a result that is
not finite is an **interpreter error**, never a silent `nan` — a NaN in a budget prints as a
believable `nan dB` and is easy to miss. Angles are radians.

| Builtin | Signature | Description |
|---|---|---|
| `icpp_sqrt` | `icpp_sqrt(x)` -> `double` | Square root; `x` must be `>= 0`. |
| `icpp_pow` | `icpp_pow(x, y)` -> `double` | `x` to the power `y`. |
| `icpp_exp` | `icpp_exp(x)` -> `double` | e to the power `x`. |
| `icpp_log` | `icpp_log(x)` -> `double` | Natural logarithm; `x > 0`. |
| `icpp_log10` | `icpp_log10(x)` -> `double` | Base-10 logarithm; `x > 0`. |
| `icpp_sin` / `icpp_cos` / `icpp_tan` | `icpp_sin(x)` -> `double` | Sine, cosine, tangent of `x` radians. |
| `icpp_asin` / `icpp_acos` | `icpp_asin(x)` -> `double` | Inverse sine / cosine; `x` in `-1 … 1`. |
| `icpp_atan2` | `icpp_atan2(y, x)` -> `double` | The angle of the point (`x`, `y`), `-pi … pi`. |
| `icpp_floor` | `icpp_floor(x)` -> `double` | Largest whole number `<= x` (`floor(-2.5)` is `-3`). |
| `icpp_fabs` | `icpp_fabs(x)` -> `double` | Absolute value. |
| `icpp_atof` | `icpp_atof(char *text)` -> `double` | Text to a number, as a database column or a split field arrives. Leading/trailing spaces and an exponent are accepted (`" -1.25e2 "` is `-125`); a number passes through. Text that is not a finite number is an error, unlike C's silent `0`. |
| `icpp_fixed` | `icpp_fixed(x, digits)` -> `char *` | `x` as text with exactly `digits` decimals (0 … 15), rounded, never in exponent form: `icpp_fixed(140.8237, 2)` is `"140.82"`, `icpp_fixed(2.5e6, 0)` is `"2500000"`. `iprint` uses `%g`, so this is how a table cell or a price is printed. |

Number literals take an exponent: `1.5e3`, `2E-2`, `6.371e+6`, `1e3`. A name that merely
starts with `e` is unaffected.

```c
void main()
{
    $d = icpp_sqrt(3.0 * 3.0 + 4.0 * 4.0);                    // 5
    $db = 10.0 * icpp_log10(1.380649e-23);                    // -228.599 (Boltzmann, dBW/K/Hz)
    $deg = icpp_atan2(1.0, 1.0) * 180.0 / 3.14159265358979;   // 45
    $price = icpp_atof("12.50") * 3;                          // 37.5
    iprint(icpp_fixed($d, 1), " ", icpp_fixed($db, 2), " ", icpp_fixed($deg, 0), " ", icpp_fixed($price, 2));
    // 5.0 -228.60 45 37.50
}
```

Conformance coverage: `36_math.icpp` (29 checks).

### 4.39 Resumable attachment storage

Include `KamrangaC++/lib/chat_email_upload.icpp`. This library stores ownership,
accepted offsets, reservations and completion state in ISQL; private files hold
attachment bytes. It is a library, not an HTTP upload endpoint.

All cooperating processes must use the same permanent lock file, database and
private storage directory. Keep the directory outside the web root. Derive the
owner from a verified session; never trust a client-supplied owner, storage path,
quota or clock. Pass validated integral byte counts and server epoch seconds.

| API | Result |
|---|---|
| `ce_upload_init(db, lockfile)` | 1 when the schema is usable; otherwise 0 |
| `ce_upload_create(db, lockfile, directory, owner, total, checksum, now, quota)` | Random 32-character upload ID; empty string on failure |
| `ce_upload_info(db, lockfile, owner, id)` | Map with string values `received`, `total`, `state`, `checksum`; 0 on failure. Free the map. |
| `ce_upload_append(db, lockfile, directory, owner, id, offset, chunk, now)` | 1 on accepted write, otherwise 0; caller retains and frees the binary buffer |
| `ce_upload_finish(db, lockfile, directory, owner, id, now)` | 1 after size/hash verification and publication, otherwise 0 |
| `ce_upload_abort(db, lockfile, directory, owner, id)` | 1 after removing a pending upload and reservation, otherwise 0 |

Each upload allows at most 64 MiB; chunks are 1–65,536 bytes. The supplied owner
quota is at most 1 GiB and counts both pending and completed reservations.
Checksum input must be 64 lowercase SHA-256 hexadecimal characters. Uploads
expire after 24 hours. Completion retries succeed only while unexpired and when
the stored blob still matches its expected size/hash.

On resumption, read `received` from `ce_upload_info`, convert it with `icpp_atoi`,
and send the next bytes from that exact offset. Replayed/stale offsets fail.
An uncommitted file tail is truncated before the next accepted write. A blob
published before an interrupted metadata update is checked and reconciled by
`ce_upload_finish`. A failed append is not an acknowledgement: read metadata
again before retrying. A checksum mismatch leaves the upload pending; abort it
and create a fresh upload to replace incorrect bytes already accepted.

Native storage helpers:

| API | Behavior |
|---|---|
| `icpp_file_create_exclusive(path)` | Create an empty file without overwriting; 1/0 |
| `icpp_file_sync(path)` | Flush an existing writable file to the OS storage interface; 1/0 |
| `icpp_file_truncate(path, length)` | Shrink and sync; rejects growth; 1/0 |
| `icpp_file_publish(source, target)` | Sync then publish without replacing a target; 1/0; use the same filesystem |
| `icpp_file_sha256(path)` | Stream the file and return 64 lowercase hex characters, or an empty string on failure |

Linux publication uses a hard link followed by unlinking the source. A source
copy can remain if cleanup fails, and parent directories are not fsynced; this
is not a guarantee against power loss. Linux hashing requires an OpenSSL-enabled
build. Automatic expiry cleanup, completed-attachment deletion/quota reclamation,
and HTTP endpoint integration remain application work.

The complete runnable example below uses a disposable ISQL home and private
file directory supplied through `ICPP_GAP_TEST_HOME` and `ICPP_GAP_TEST_FILES`.
Save it in `KamrangaC++/test/icpp_conformance/manual_upload_example.icpp`; run
`kcpp -icpp manual_upload_example.icpp` from that directory. It uploads the three
bytes `abc`, checks the accepted offset and verifies publication. It retains its
demo metadata/blob for inspection. Do not run these examples against production
data or combine their transactions with unrelated work on the same ISQL user/database.

```cpp
#include "../../lib/chat_email_upload.icpp"
int main(void)
{
    $home = icpp_getenv("ICPP_GAP_TEST_HOME");
    $files = icpp_getenv("ICPP_GAP_TEST_FILES");
    if (icpp_strlen($home) == 0 || icpp_strlen($files) == 0) { icpp_exit(1); return 1; }
    $db = icpp_sql_connect($home);
    if ($db == 0) { icpp_exit(1); return 1; }
    $lock = isprint($files, "/manual-uploads.lock");
    $directory = isprint($files, "/manual-uploads");
    icpp_mkdir($directory);
    icpp_assert(ce_upload_init($db, $lock) == 1, "initialize uploads");
    // Demo identity only; a server must obtain this from its verified session.
    $owner = isprint("demo-", icpp_random_hex(8));
    $now = icpp_time();
    $checksum = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
    $id = ce_upload_create($db, $lock, $directory, $owner, 3, $checksum, $now, 1024);
    if (icpp_strlen($id) != 32) { icpp_sql_disconnect($db); icpp_exit(1); return 1; }
    $chunk = icpp_bin_new(3);
    icpp_bin_set($chunk, 0, 97); // a
    icpp_bin_set($chunk, 1, 98); // b
    icpp_bin_set($chunk, 2, 99); // c
    $info = ce_upload_info($db, $lock, $owner, $id);
    if ($info == 0) { icpp_bin_free($chunk); icpp_sql_disconnect($db); icpp_exit(1); return 1; }
    $offset = icpp_atoi(icpp_map_get($info, "received"));
    icpp_map_free($info);
    $ok = ce_upload_append($db, $lock, $directory, $owner, $id, $offset, $chunk, icpp_time());
    icpp_bin_free($chunk);
    icpp_assert($ok == 1, "append abc at accepted offset");
    if ($ok) {
        icpp_assert(ce_upload_finish($db, $lock, $directory, $owner, $id, icpp_time()) == 1, "verify and finalize");
        icpp_assert_eq_str(icpp_file_sha256(isprint($directory, "/", $id, ".blob")), $checksum, "published checksum");
    } else {
        ce_upload_abort($db, $lock, $directory, $owner, $id);
    }
    icpp_sql_disconnect($db);
    icpp_exit(icpp_test_summary());
    return 0;
}

```

### 4.40 Session tokens and request identity

Include `KamrangaC++/lib/chat_email_sessions.icpp`. This library manages sessions
after a trusted login flow authenticates a user. It does not verify passwords,
perform OAuth login, configure TLS or create response cookies.

| API | Result |
|---|---|
| `ce_session_init(db, lockfile)` | 1 when the schema is usable; otherwise 0 |
| `ce_session_issue(db, lockfile, subject, now, ttl)` | 64-character random bearer token; empty string on failure |
| `ce_session_subject(db, lockfile, token, now)` | Verified subject, or empty string for invalid/expired/revoked tokens or lookup failure |
| `ce_session_revoke(db, lockfile, token)` | 1 on successful update, including an already absent well-formed token; otherwise 0 |
| `ce_session_cookie(header)` | Exactly one valid `ce_session` token; empty string on invalid/duplicate/missing cookie |
| `ce_request_subject(db, lockfile, peer, expected_origin, now)` | Verified subject for an accepted HTTP peer, or empty string |

Tokens contain 256 random bits; ISQL stores only their SHA-256 hashes. Subjects
are 1–64 characters and TTLs are 1–86,400 seconds. The supplied `now` must be
trusted server epoch seconds. Expiration is exclusive: `now == expires` is
expired. Use the same permanent lock anchor for every session participant.
Current timestamps are bounded by signed 32-bit storage; migration beyond 2038
has not been implemented. Expired/revoked row retention cleanup is not automatic.

`ce_request_subject` gives a present Authorization header precedence. It accepts
the exact `Bearer ` prefix followed by a valid token. Without Authorization, it
requires an exact match to the configured, nonempty Origin and then parses the
session cookie. Invalid Authorization does not fall back to cookies. The cookie
path therefore rejects requests with no Origin, including some navigation/GET
requests; account for this explicitly in endpoint design.

Use TLS for tokens in transit and never log tokens or Authorization/Cookie
headers. A browser integration must set `Secure`, `HttpOnly`, appropriate
`SameSite`, path and expiry attributes using its response layer; the current
plain-text `icpp_http_reply` helper does not set custom cookie headers. Resolve
identity before accepting an upload or upgrading a WebSocket, then perform the
application's resource authorization checks. The existing transport test fixture
uses fixture authentication and is not a production session integration.

Save this example beside the upload example as `manual_session_example.icpp`
and run `kcpp -icpp manual_session_example.icpp` with the same disposable
environment variables. It demonstrates issue, lookup, cookie parsing, expiration
and logout without printing the bearer token. Its hardcoded subject is for the
example only and must be replaced by the result of a verified login.

```cpp
#include "../../lib/chat_email_sessions.icpp"
int main(void)
{
    $home = icpp_getenv("ICPP_GAP_TEST_HOME");
    $files = icpp_getenv("ICPP_GAP_TEST_FILES");
    if (icpp_strlen($home) == 0 || icpp_strlen($files) == 0) { icpp_exit(1); return 1; }
    $db = icpp_sql_connect($home);
    if ($db == 0) { icpp_exit(1); return 1; }
    $lock = isprint($files, "/manual-sessions.lock");
    icpp_assert(ce_session_init($db, $lock) == 1, "initialize sessions");
    // Demo only: production code must first verify the user's login.
    $subject = "manual-demo-user";
    $now = icpp_time();
    $token = ce_session_issue($db, $lock, $subject, $now, 3600);
    if (icpp_strlen($token) != 64) { icpp_sql_disconnect($db); icpp_exit(1); return 1; }
    // Never print or log the bearer token.
    icpp_assert_eq_str(ce_session_subject($db, $lock, $token, $now + 1), $subject, "valid session");
    $cookie = isprint("ce_session=", $token);
    icpp_assert(icpp_strcmp(ce_session_cookie($cookie), $token) == 0, "parse request cookie");
    icpp_assert_eq_str(ce_session_subject($db, $lock, $token, $now + 3600), "", "expiry boundary");
    icpp_assert(ce_session_revoke($db, $lock, $token) == 1, "logout revokes session");
    icpp_assert_eq_str(ce_session_subject($db, $lock, $token, $now + 2), "", "revoked token denied");
    icpp_sql_disconnect($db);
    icpp_exit(icpp_test_summary());
    return 0;
}

```

Example validation: the upload example above passes 4 checks and the session example
6 checks, each with its own disposable ISQL home (`32_upload_states.icpp` and
`33_sessions.icpp` pass on Windows x64 and Linux x64).

---

## 5. The library / `#include` manifest system

An ICPP library is an ordinary `.icpp` file pulled in with `#include "libname.icpp"`. It may
carry a **manifest** in special `//@icpp-*` comment tags at the top, which the `icpp_lib_*`
builtins can query at runtime. This is how a script can gate on a library's version for
backward compatibility.

### Manifest tags

```c
//@icpp-library    libfixture
//@icpp-version     1.2.0
//@icpp-author      Muhammad Anisur Rahman
//@icpp-copyright   (c) 2026 Muhammad Anisur Rahman - MIT
//@icpp-contact     contact@chapai.ai
//@icpp-requires    0.40                ; minimum interpreter version
//@icpp-since       1.2.0: added fx_shout(); 1.1.0: initial   ; what's new
//---------------------------------------------------------------
char *fx_shout(char *s) { return icpp_upper(isprint(s, "!")); }
int   fx_double(int x)  { return x + x; }
```

Recognized tags: `//@icpp-library`, `//@icpp-version`, `//@icpp-author`, `//@icpp-copyright`,
`//@icpp-contact`, `//@icpp-requires`, `//@icpp-since`. Text after a `;` on a tag line is a
comment.

### Query builtins

| Builtin | Signature | Description |
|---|---|---|
| `icpp_lib_field` | `icpp_lib_field(char *file, char *field)` -> `char *` | Read one manifest field (e.g. `"library"`, `"author"`) from a file's header. |
| `icpp_lib_version` | `icpp_lib_version(char *file)` -> `char *` | Shortcut for the `version` field. |
| `icpp_version_cmp` | `icpp_version_cmp(char *a, char *b)` -> `int` | **Semantic** version compare: −1 / 0 / 1. `1.10.0 > 1.9.0` (unlike a string compare). |

```c
#include "libfixture.icpp"
// the included functions are callable:
icpp_assert_eq_str(fx_shout("hi"), "HI!", "included lib function");
icpp_assert_eq_int(fx_double(21), 42, "included lib function 2");
// query the manifest:
icpp_assert_eq_str(icpp_lib_version("libfixture.icpp"), "1.2.0", "lib_version");
icpp_assert_eq_str(icpp_lib_field("libfixture.icpp", "author"), "Muhammad Anisur Rahman", "author");
// backward-compat gate: require >= 1.2.0
icpp_assert_eq_int(icpp_version_cmp(icpp_lib_version("libfixture.icpp"), "1.2.0") >= 0, 1, "gate");
```

---

## 6. The `i*` aliases for Files/FS builtins

Every Files/Filesystem/sequential-read/env builtin is registered **twice**: under its
`icpp_*` name and under a short `i*` name. Both names dispatch to the identical implementation
(they share a function id), and the `icpp_*` names keep working — the aliases are purely
additive. Use whichever reads better.

| `icpp_*` name | `i*` alias |
|---|---|
| `icpp_fopen` | `ifopen` |
| `icpp_fclose` | `ifclose` |
| `icpp_fgets` | `ifgets` |
| `icpp_feof` | `ifeof` |
| `icpp_file_read` | `ifile_read` |
| `icpp_file_write` | `ifile_write` |
| `icpp_file_exists` | `ifile_exists` |
| `icpp_file_size` | `ifile_size` |
| `icpp_file_mtime` | `ifile_mtime` |
| `icpp_file_line` | `ifile_line` |
| `icpp_file_lines` | `ifile_lines` |
| `icpp_file_contains` | `ifile_contains` |
| `icpp_file_replace` | `ifile_replace` |
| `icpp_file_diff` | `ifile_diff` |
| `icpp_file_hash` | `ifile_hash` |
| `icpp_file_fingerprint` | `ifile_fingerprint` |
| `icpp_glob` | `iglob` |
| `icpp_glob_r` | `iglob_r` |
| `icpp_mkdir` | `imkdir` |
| `icpp_chdir` | `ichdir` |
| `icpp_cwd` | `icwd` |
| `icpp_remove` | `iremove` |
| `icpp_rename` | `irename` |
| `icpp_getenv` | `igetenv` |
| `icpp_setenv` | `isetenv` |

```c
ifile_write("conf_probe.txt", "line1\nline2\nline3\n");   // == icpp_file_write
iremove("conf_probe.txt");                                // == icpp_remove
```

(The `icpp_dict_*` names in [§4.12](#412-maps-and-dicts) are the same idea applied to the map
builtins — Python-familiar aliases sharing the map implementation.)

---

## 7. Shell redirection in command lines

Any command line passed to `icpp_exec` (and friends), `ithread_create`, etc. may use the
shell's own operators — `2>&1`, `>`, `>>`, `<`, `|`, `&`, `&&`. When one of these is present,
the command is handed to the command processor, so it means exactly what it means at a prompt:

```c
icpp_exec("vsim.exe -c -do run.do > sim.log 2>&1");   // merge stderr into the log
icpp_exec("vlog.exe design.v 2> errors.txt");         // stderr only
icpp_exec("vlog.exe design.v 2>/dev/null");           // discard stderr
icpp_exec("kcpp.exe -rtl d.icpp | findstr Error");    // pipes work too
```

Specifically supported redirection forms include `2>&1` (merge stderr into stdout) and
`2>/dev/null` / `2>NUL` (discard stderr). Without any operator, the program is started
**directly**, which is faster and keeps a bare relative program name resolving against the
current directory.

Note that `icpp_exec_capture` and `icpp_exec_to_file` **already** merge stderr into what they
collect, so `2>&1` is only needed there if you want the shell to do something *further* with
it. A shell builtin (`dir`, `echo`, `copy`) is not a program, so it needs the shell — give it
an operator, or spell it `cmd /c dir ...`.

---

## 8. Known issues

None are open. `test/icpp_conformance/90_known_issues.icpp` holds any confirmed open bug (it
asserts the correct value, and the runner treats it as expected-to-fail), and it is empty.

### 8.1 Fixed, and pinned by the conformance suite

Listed so nobody re-investigates ground already covered. Each has a regression check in
`test/icpp_conformance/`:

- **`!`, `~`, and stacked prefixes** (`!0`, `!$x`, `!!x`, `~~x`, `!-x`) used to crash or fail to
  parse. On a pointer, only NULL is false, as in C, so `!""` is 0.
- **`float`** used to read as 0. More widely, int and double used to be copied as raw bytes at
  assignment, argument passing and `return`: `int i; i = 13.0;` stored 0. All three now convert as C
  does.
- **Deep recursion on Linux** segfaulted past a few thousand calls: the interpreter recurses
  natively per interpreted call and Linux gave the main thread its 8 MB default stack, where
  Windows links kcpp.exe with 256 MB. kcpp now raises its own stack limit to 256 MB (as far
  as the hard limit allows) and restarts itself once at start-up. Pinned by `39_call_depth.icpp`.
- **`$s + "y"`** used to produce garbage; `+` now joins strings (see §3, *Control flow & operators*).
- **Every compound assignment** (`+=`, `-=`, `*=`, `/=`, `%=`, `<<=`, `>>=`, `&=`, `|=`, `^=`) used to
  crash the interpreter.
- **`printf`** used to substitute only `%d` and `%s`; it now supports the standard C conversions.
- **`icpp_concat` / `isprint`** used to cut their result at 4095 bytes, silently.
- **`icpp_getparam` and `icpp_sql_get`** used to cut a value at 1023 bytes, and **`icpp_trim`,
  `icpp_substr`, `icpp_replace_all`, `icpp_upper`, `icpp_lower`, `icpp_html_escape`, `icpp_getenv`,
  `icpp_json_get`** and (on Windows) **`icpp_setenv`** at 4095 - all silently. A long form field, a
  long text column, or a JSON reply of a few KB came back short. Each result is now as long as its
  data. `icpp_file_read` is still bounded (~4 KB; use `icat`).
- **`iprint` / `ifprint`** joined their arguments into a fixed 2048-byte buffer with no length check,
  so printing more than 2 KB in one call wrote past it. They now allocate what the arguments need.
- **A source line longer than about 4 KB** used to crash the interpreter while reading it, with no
  message - a long string literal, or simply a long expression. Lines are now good to 65535 bytes,
  and a longer one is reported rather than fatal.
- **A recursive call inside `return`** (`return n * fact(n - 1);`) used to return garbage.
- **The ternary `?:`** used to yield its true value even when the condition was false.
- **`s///` backreferences** (`\1`..`\9`) were never broken. The old test wrote the directive without
  the escaping that a C string literal needs: `"s/(c)(a)(t)/\\3\\2\\1/"` gives `"tac"`.
- **A `$var` assigned from a function parameter** (`$y = x * 2;`) works: a `$var` is assigned at run
  time like any other variable.
- **Also fixed earlier:** braceless `if`/`for`/`while` bodies and standalone `{ }` blocks; `char *`
  locals assigned a string literal; and all `double` arithmetic, parameters and return values.

---

## 9. Worked examples

All examples draw on real conformance-suite / test syntax so they actually run.

### 9.1 A self-checking core-language test (`kcpp -icpp`)

```c
// core.icpp
int g_global;
int add(int a, int b) { return a + b; }
int for_sum(int n) { int i; int s; s = 0; for (i = 1; i <= n; i = i + 1) s = s + i; return s; }

void main()
{
    int x; int y; int rc;
    icpp_assert_eq_int(2 + 3, 5, "add");
    icpp_assert_eq_int(17 % 5, 2, "mod");
    x = 10; y = 3;
    if (x > y) icpp_assert_eq_int(1, 1, "gt"); else icpp_assert_eq_int(0, 1, "gt");
    icpp_assert_eq_int(add(add(1, 2), add(3, 4)), 10, "nested calls");
    icpp_assert_eq_int(for_sum(10), 55, "for");
    g_global = 77;
    icpp_assert_eq_int(g_global, 77, "global");
    x = 5; x++;
    icpp_assert_eq_int(x, 6, "post-increment");
    rc = icpp_test_summary();
    icpp_exit(rc);                 // exit code = number of failed checks
}
```

### 9.2 A dynamic web page (`<?icpp ?>` + `iwebserver`)

```html
<!-- greet.icpp.html -->
<html><body>
<h1>Greeter</h1>
<?icpp
    char *name;
    name = icpp_getparam("name");
    if (icpp_strlen(name) == 0) name = "stranger";
    iprint("<p>Hello, ", name, "!</p>");
    iprint("<p>Server time: ", icpp_date_string(), "</p>");
?>
</body></html>
```

Request `greet.icpp.html?name=Anis` and the page renders "Hello, Anis!" with the current time.

### 9.3 A data-processing script (parse a simulation transcript)

```c
// scan.icpp - the kind of job normally written in Perl
void main()
{
    int fields; int kv; int seen; int i; int val; int rc;
    seen = icpp_map_new();
    for (i = 1; i <= icpp_file_lines("sim.log"); i = i + 1) {
        // "# 100 ns SIG=top.dut.addr VAL=deadbeef"
        fields = icpp_split(icpp_file_line("sim.log", i), " ");
        if (icpp_list_count(fields) >= 5) {
            kv = icpp_split(icpp_list_get(fields, 4), "=");   // VAL=deadbeef
            if (icpp_list_count(kv) == 2)
                icpp_map_set(seen, "addr", icpp_list_get(kv, 1));
            icpp_list_free(kv);
        }
        icpp_list_free(fields);
    }
    val = icpp_parse_hex(icpp_map_get(seen, "addr"));         // 0xdeadbeef
    iprint("upper nibble = ", icpp_hex(icpp_bits(val, 31, 28), 1), "\n");   // d
    icpp_map_free(seen);
    rc = icpp_test_summary();
    icpp_exit(rc);
}
```

### 9.4 A tiny tensor / ML snippet (forward + backward + SGD step)

```c
// one training step of a single linear layer + cross-entropy
void main()
{
    int x; int w; int b; int logits; int targets; int dlogits; int dw; int db;
    double loss;

    x = tensor_new(1, 3); tensor_set(x, 0, 0, 1.0); tensor_set(x, 0, 1, 0.5); tensor_set(x, 0, 2, -1.0);
    w = tensor_new(3, 2); tensor_init_spread(w, 1);
    b = tensor_new(1, 2);
    targets = tensor_new(1, 1); tensor_set(targets, 0, 0, 1.0);   // class 1

    logits = tensor_linear(x, w, b);
    loss   = tensor_cross_entropy_loss(logits, targets);
    iprint("loss=", loss, "\n");

    dlogits = tensor_cross_entropy_loss_backward(logits, targets);
    dw = tensor_linear_backward_w(x, w, dlogits);   // from icpp_autodiff.c
    db = tensor_linear_backward_b(dlogits);          // from icpp_autodiff.c
    tensor_sgd_step(w, dw, 0.05);
    tensor_sgd_step(b, db, 0.05);

    tensor_free(x); tensor_free(w); tensor_free(b); tensor_free(targets);
    tensor_free(logits); tensor_free(dlogits); tensor_free(dw); tensor_free(db);
}
```

(`tensor_linear_backward_w` / `tensor_linear_backward_b` are script-composed helpers in the
reusable `icpp_autodiff.c` library — `#include "icpp_autodiff.c"` — built from the native
backward primitives in [§4.25](#425-autodiff-backward--gradient-rules). The full tested MLP and
transformer training loops live in `test/PhaseA/dnn_mlp_check.c` and
`test/PhaseA/training_loop_check.c`.)

### 9.5 A regex / string example

```c
void main()
{
    int rc;
    // match: pull the first run of digits
    icpp_assert_eq_str(icpp_re("order#4821 shipped", "m/[0-9]+/"), "4821", "match digits");
    // string transforms
    icpp_assert_eq_str(icpp_upper(icpp_trim("  hello  ")), "HELLO", "trim+upper");
    icpp_assert_eq_str(icpp_replace_all("a.b.c", ".", "/"), "a/b/c", "replace_all");
    // sed on a string, global
    icpp_assert_eq_str(ised("x-y-z", "s/-/_/g"), "x_y_z", "sed global");
    rc = icpp_test_summary();
    icpp_exit(rc);
}
```

---

## Appendix A — alphabetical builtin index

Every registered builtin, with its argument count (`va` = variadic) and return type, and the
section that documents it. `H` = handle (registered as `int`).

| # | Builtin | Args | Returns | Section |
|---|---|---|---|---|
| 1 | `CPU_SET` | 2 | int | 4.17 |
| 2 | `CPU_ZERO` | 0 | int | 4.17 |
| 3 | `ibash` | 1 | char * | 4.16 |
| 4 | `icat` | 1 | char * | 4.16 |
| 5 | `ichdir` | 1 | int | 4.6 / 6 |
| 6 | `icpp_acos` | 1 | double | 4.38 |
| 7 | `icpp_afis_extract` | 1 | int (H) | 4.18 |
| 8 | `icpp_afis_free` | 1 | void | 4.18 |
| 9 | `icpp_afis_match` | 2 | double | 4.18 |
| 10 | `icpp_afis_match_files` | 2 | double | 4.18 |
| 11 | `icpp_afis_minutiae` | 1 | int | 4.18 |
| 12 | `icpp_asin` | 1 | double | 4.38 |
| 13 | `icpp_assert` | 2 | int | 4.15 |
| 14 | `icpp_assert_eq_int` | 3 | int | 4.15 |
| 15 | `icpp_assert_eq_str` | 3 | int | 4.15 |
| 16 | `icpp_atan2` | 2 | double | 4.38 |
| 17 | `icpp_atof` | 1 | double | 4.38 |
| 18 | `icpp_atoi` | 1 | int | 4.2 / 4.10 |
| 19 | `icpp_barcode_kind` | 0 | char * | 4.34 |
| 20 | `icpp_barcode_read` | 1 | char * | 4.34 |
| 21 | `icpp_barcode_svg` | 3 | char * | 4.33 |
| 22 | `icpp_base64` | 1 | char * | 4.30 |
| 23 | `icpp_base64_decode` | 1 | char * | 4.31 |
| 24 | `icpp_base64_encode` | 1 | char * | 4.31 |
| 25 | `icpp_bin` | 2 | char * | 4.10 |
| 26 | `icpp_bin_diff` | 3 | int | 4.9 |
| 27 | `icpp_bin_find` | 2 | int | 4.9 |
| 28 | `icpp_bin_float` | 2 | double | 4.9 |
| 29 | `icpp_bin_free` | 1 | int | 4.9 |
| 30 | `icpp_bin_get` | 2 | int | 4.9 |
| 31 | `icpp_bin_int32` | 2 | int | 4.9 |
| 32 | `icpp_bin_new` | 1 | int | 4.9 |
| 33 | `icpp_bin_read` | 1 | int (H) | 4.9 |
| 34 | `icpp_bin_read_chunk` | 3 | int | 4.9 |
| 35 | `icpp_bin_set` | 3 | int | 4.9 |
| 36 | `icpp_bin_size` | 1 | int | 4.9 |
| 37 | `icpp_bin_write` | 2 | int | 4.9 |
| 38 | `icpp_bin_write_at` | 3 | int | 4.9 |
| 39 | `icpp_bits` | 3 | int | 4.10 |
| 40 | `icpp_chdir` | 1 | int | 4.6 |
| 41 | `icpp_concat` | va | char * | 4.1 |
| 42 | `icpp_cos` | 1 | double | 4.38 |
| 43 | `icpp_cwd` | 0 | char * | 4.6 |
| 44 | `icpp_date_string` | 0 | char * | 4.8 |
| 45 | `icpp_decrypt` | 2 | char * | 4.31 |
| 46 | `icpp_dict_count` | 1 | int | 4.12 |
| 47 | `icpp_dict_delete` | 2 | int | 4.12 |
| 48 | `icpp_dict_free` | 1 | void | 4.12 |
| 49 | `icpp_dict_get` | 2 | char * | 4.12 |
| 50 | `icpp_dict_has` | 2 | int | 4.12 |
| 51 | `icpp_dict_keys` | 1 | int (H) | 4.12 |
| 52 | `icpp_dict_new` | 0 | int (H) | 4.12 |
| 53 | `icpp_dict_set` | 3 | int | 4.12 |
| 54 | `icpp_elapsed_ms` | 0 | int | 4.8 |
| 55 | `icpp_encrypt` | 2 | char * | 4.31 |
| 56 | `icpp_ends_with` | 2 | int | 4.2 |
| 57 | `icpp_exec` | 1 | int | 4.15 |
| 58 | `icpp_exec_capture` | 1 | char * | 4.15 |
| 59 | `icpp_exec_status` | 0 | int | 4.15 |
| 60 | `icpp_exec_to_file` | 2 | int | 4.15 |
| 61 | `icpp_exit` | 1 | void | 4.15 |
| 62 | `icpp_exp` | 1 | double | 4.38 |
| 63 | `icpp_fabs` | 1 | double | 4.38 |
| 64 | `icpp_fclose` | 1 | void | 4.7 |
| 65 | `icpp_feof` | 1 | int | 4.7 |
| 66 | `icpp_fgets` | 1 | char * | 4.7 |
| 67 | `icpp_file_contains` | 2 | int | 4.5 |
| 68 | `icpp_file_create_exclusive` | 1 | int | 4.39 |
| 69 | `icpp_file_diff` | 2 | int | 4.5 |
| 70 | `icpp_file_exists` | 1 | int | 4.5 |
| 71 | `icpp_file_fingerprint` | 1 | char * | 4.5 / 4.18 |
| 72 | `icpp_file_hash` | 1 | char * | 4.5 |
| 73 | `icpp_file_line` | 2 | char * | 4.5 |
| 74 | `icpp_file_lines` | 1 | int | 4.5 |
| 75 | `icpp_file_mtime` | 1 | int | 4.5 |
| 76 | `icpp_file_publish` | 2 | int | 4.39 |
| 77 | `icpp_file_read` | 1 | char * | 4.5 |
| 78 | `icpp_file_replace` | 3 | int | 4.5 |
| 79 | `icpp_file_sha256` | 1 | char * | 4.39 |
| 80 | `icpp_file_size` | 1 | int | 4.5 |
| 81 | `icpp_file_sync` | 1 | int | 4.39 |
| 82 | `icpp_file_truncate` | 2 | int | 4.39 |
| 83 | `icpp_file_write` | 2 | int | 4.5 |
| 84 | `icpp_fingerprint_match` | 2 | int | 4.18 |
| 85 | `icpp_fingerprint_similarity` | 2 | int | 4.18 |
| 86 | `icpp_fixed` | 2 | char * | 4.38 |
| 87 | `icpp_floor` | 1 | double | 4.38 |
| 88 | `icpp_fopen` | 1 | int (H) | 4.7 |
| 89 | `icpp_getenv` | 1 | char * | 4.8 |
| 90 | `icpp_getparam` | 1 | char * | 4.22 |
| 91 | `icpp_glob` | 1 | int (H) | 4.6 |
| 92 | `icpp_glob_r` | 2 | int (H) | 4.6 |
| 93 | `icpp_hex` | 2 | char * | 4.10 |
| 94 | `icpp_hmac_sha256` | 2 | char * | 4.31 |
| 95 | `icpp_html_escape` | 1 | char * | 4.2 |
| 96 | `icpp_http_read` | 3 | int | 4.36 |
| 97 | `icpp_http_remaining` | 1 | int | 4.36 |
| 98 | `icpp_http_reply` | 3 | int | 4.36 |
| 99 | `icpp_https_get` | 2 | char * | 4.32 |
| 100 | `icpp_https_post` | 3 | char * | 4.32 |
| 101 | `icpp_https_status` | 0 | int | 4.32 |
| 102 | `icpp_image_crop` | 6 | int | 4.18 |
| 103 | `icpp_image_phash` | 1 | char * | 4.18 |
| 104 | `icpp_img_fill_rect` | 6 | int | 4.19 |
| 105 | `icpp_img_free` | 1 | void | 4.19 |
| 106 | `icpp_img_get` | 3 | int | 4.19 |
| 107 | `icpp_img_line` | 6 | int | 4.19 |
| 108 | `icpp_img_new` | 2 | int (H) | 4.19 |
| 109 | `icpp_img_rect` | 6 | int | 4.19 |
| 110 | `icpp_img_save_png` | 2 | int | 4.19 |
| 111 | `icpp_img_set` | 4 | int | 4.19 |
| 112 | `icpp_job_cancel` | 1 | int | 4.36 |
| 113 | `icpp_job_exit` | 1 | int | 4.36 |
| 114 | `icpp_job_free` | 1 | int | 4.36 |
| 115 | `icpp_job_start` | 3 | int | 4.36 |
| 116 | `icpp_job_state` | 1 | int | 4.36 |
| 117 | `icpp_join` | 2 | char * | 4.11 |
| 118 | `icpp_json_get` | 2 | char * | 4.20 |
| 119 | `icpp_lang_close` | 1 | int | 4.29 |
| 120 | `icpp_lang_get` | 2 | char * | 4.29 |
| 121 | `icpp_lang_getnum` | 2 | double | 4.29 |
| 122 | `icpp_lang_has` | 2 | int | 4.29 |
| 123 | `icpp_lang_kind` | 2 | char * | 4.29 |
| 124 | `icpp_lang_limit` | 2 | int | 4.29 |
| 125 | `icpp_lang_names` | 1 | char * | 4.29 |
| 126 | `icpp_lang_open` | 1 | int | 4.29 |
| 127 | `icpp_lang_run` | 2 | char * | 4.29 |
| 128 | `icpp_lang_set` | 3 | int | 4.29 |
| 129 | `icpp_lib_field` | 2 | char * | 5 |
| 130 | `icpp_lib_version` | 1 | char * | 5 |
| 131 | `icpp_list_add` | 2 | int | 4.11 |
| 132 | `icpp_list_count` | 1 | int | 4.11 |
| 133 | `icpp_list_free` | 1 | void | 4.11 |
| 134 | `icpp_list_get` | 2 | char * | 4.11 |
| 135 | `icpp_list_new` | 0 | int (H) | 4.11 |
| 136 | `icpp_list_set` | 3 | int | 4.11 |
| 137 | `icpp_list_sort` | 1 | int | 4.11 |
| 138 | `icpp_lock_acquire` | 2 | int | 4.37 |
| 139 | `icpp_lock_release` | 1 | int | 4.37 |
| 140 | `icpp_log` | 1 | double | 4.38 |
| 141 | `icpp_log10` | 1 | double | 4.38 |
| 142 | `icpp_lower` | 1 | char * | 4.2 |
| 143 | `icpp_map_count` | 1 | int | 4.12 |
| 144 | `icpp_map_delete` | 2 | int | 4.12 |
| 145 | `icpp_map_free` | 1 | void | 4.12 |
| 146 | `icpp_map_get` | 2 | char * | 4.12 |
| 147 | `icpp_map_has` | 2 | int | 4.12 |
| 148 | `icpp_map_keys` | 1 | int (H) | 4.12 |
| 149 | `icpp_map_new` | 0 | int (H) | 4.12 |
| 150 | `icpp_map_set` | 3 | int | 4.12 |
| 151 | `icpp_max` | 2 | int | 4.38 |
| 152 | `icpp_mcp_call` | 3 | char * | 4.20 |
| 153 | `icpp_mcp_connect` | 1 | int (H) | 4.20 |
| 154 | `icpp_mcp_disconnect` | 1 | void | 4.20 |
| 155 | `icpp_mcp_list_tools` | 1 | char * | 4.20 |
| 156 | `icpp_min` | 2 | int | 4.38 |
| 157 | `icpp_mkdir` | 1 | int | 4.6 |
| 158 | `icpp_net_accept` | 2 | int | 4.36 |
| 159 | `icpp_net_close` | 1 | int | 4.36 |
| 160 | `icpp_net_error` | 0 | char * | 4.36 |
| 161 | `icpp_net_header` | 2 | char * | 4.36 |
| 162 | `icpp_net_listen` | 1 | int | 4.36 |
| 163 | `icpp_net_state` | 1 | int | 4.36 |
| 164 | `icpp_ocr_extract` | 1 | char * | 4.18 |
| 165 | `icpp_openai_chat` | 4 | char * | 4.21 |
| 166 | `icpp_parse_hex` | 1 | int | 4.10 |
| 167 | `icpp_pbkdf2` | 3 | char * | 4.31 |
| 168 | `icpp_phash_similarity` | 2 | int | 4.18 |
| 169 | `icpp_pow` | 2 | double | 4.38 |
| 170 | `icpp_qrcode_read` | 1 | char * | 4.34 |
| 171 | `icpp_qrcode_svg` | 2 | char * | 4.33 |
| 172 | `icpp_random_hex` | 1 | char * | 4.31 |
| 173 | `icpp_re` | 2 | char * | 4.3 |
| 174 | `icpp_remove` | 1 | int | 4.6 |
| 175 | `icpp_rename` | 2 | int | 4.6 |
| 176 | `icpp_replace_all` | 3 | char * | 4.2 |
| 177 | `icpp_script` | 1 | char * | 4.30 |
| 178 | `icpp_script_src` | 1 | char * | 4.30 |
| 179 | `icpp_script_srcs` | 0 | char * | 4.30 |
| 180 | `icpp_search_txt` | 2 | int | 4.2 |
| 181 | `icpp_send_email` | 3 | int | 4.32 |
| 182 | `icpp_set_add` | 2 | int | 4.13 |
| 183 | `icpp_set_count` | 1 | int | 4.13 |
| 184 | `icpp_set_free` | 1 | void | 4.13 |
| 185 | `icpp_set_has` | 2 | int | 4.13 |
| 186 | `icpp_set_items` | 1 | int (H) | 4.13 |
| 187 | `icpp_set_new` | 0 | int (H) | 4.13 |
| 188 | `icpp_set_remove` | 2 | int | 4.13 |
| 189 | `icpp_setenv` | 2 | int | 4.8 |
| 190 | `icpp_sha256` | 1 | char * | 4.30 |
| 191 | `icpp_sha256_base64` | 1 | char * | 4.30 |
| 192 | `icpp_sin` | 1 | double | 4.38 |
| 193 | `icpp_split` | 2 | int (H) | 4.11 |
| 194 | `icpp_sql_commit` | 1 | int | 4.35 |
| 195 | `icpp_sql_connect` | 1 | int (H) | 4.4 |
| 196 | `icpp_sql_connect_remote` | 4 | int (H) | 4.4 |
| 197 | `icpp_sql_count` | 1 | int | 4.4 |
| 198 | `icpp_sql_disconnect` | 1 | void | 4.4 |
| 199 | `icpp_sql_exec_params` | 2 | int | 4.35 |
| 200 | `icpp_sql_free` | 1 | void | 4.4 |
| 201 | `icpp_sql_get` | 2 | char * | 4.4 |
| 202 | `icpp_sql_next` | 1 | int | 4.4 |
| 203 | `icpp_sql_query` | 2 | int (H) | 4.4 |
| 204 | `icpp_sql_query_params` | 2 | int | 4.4 |
| 205 | `icpp_sql_rollback` | 1 | int | 4.35 |
| 206 | `icpp_sql_status` | 1 | char * | 4.4 |
| 207 | `icpp_sqrt` | 1 | double | 4.38 |
| 208 | `icpp_starts_with` | 2 | int | 4.2 |
| 209 | `icpp_strcmp` | 2 | int | 4.2 |
| 210 | `icpp_strlen` | 1 | int | 4.2 |
| 211 | `icpp_strstr` | 2 | int | 4.2 |
| 212 | `icpp_substr` | 3 | char * | 4.2 |
| 213 | `icpp_tan` | 1 | double | 4.38 |
| 214 | `icpp_test_summary` | 0 | int | 4.15 |
| 215 | `icpp_text_embed` | 2 | int (H) | 4.27 |
| 216 | `icpp_time` | 0 | int | 4.8 |
| 217 | `icpp_trim` | 1 | char * | 4.2 |
| 218 | `icpp_tuple_add` | 2 | int | 4.14 |
| 219 | `icpp_tuple_count` | 1 | int | 4.14 |
| 220 | `icpp_tuple_free` | 1 | void | 4.14 |
| 221 | `icpp_tuple_get` | 2 | char * | 4.14 |
| 222 | `icpp_tuple_new` | 0 | int (H) | 4.14 |
| 223 | `icpp_unbase64` | 1 | char * | 4.30 |
| 224 | `icpp_upper` | 1 | char * | 4.2 |
| 225 | `icpp_version_cmp` | 2 | int | 5 |
| 226 | `icpp_worker_begin` | 0 | int | 4.8 |
| 227 | `icpp_worker_end` | 0 | int | 4.8 |
| 228 | `icpp_worker_request_stop` | 0 | int | 4.8 |
| 229 | `icpp_worker_stopping` | 0 | int | 4.8 |
| 230 | `icpp_worker_wait` | 1 | int | 4.8 |
| 231 | `icpp_ws_opcode` | 1 | int | 4.36 |
| 232 | `icpp_ws_recv` | 2 | int | 4.36 |
| 233 | `icpp_ws_send` | 4 | int | 4.36 |
| 234 | `icpp_ws_upgrade` | 1 | int | 4.36 |
| 235 | `icpu_count` | 0 | int | 4.17 |
| 236 | `icut` | 3 | char * | 4.16 |
| 237 | `icwd` | 0 | char * | 4.6 / 6 |
| 238 | `ifclose` | 1 | void | 4.7 / 6 |
| 239 | `ifeof` | 1 | int | 4.7 / 6 |
| 240 | `ifgets` | 1 | char * | 4.7 / 6 |
| 241 | `ifile_contains` | 2 | int | 6 |
| 242 | `ifile_diff` | 2 | int | 6 |
| 243 | `ifile_exists` | 1 | int | 6 |
| 244 | `ifile_fingerprint` | 1 | char * | 6 |
| 245 | `ifile_hash` | 1 | char * | 6 |
| 246 | `ifile_line` | 2 | char * | 6 |
| 247 | `ifile_lines` | 1 | int | 6 |
| 248 | `ifile_mtime` | 1 | int | 6 |
| 249 | `ifile_read` | 1 | char * | 6 |
| 250 | `ifile_replace` | 3 | int | 6 |
| 251 | `ifile_size` | 1 | int | 6 |
| 252 | `ifile_write` | 2 | int | 6 |
| 253 | `ifind` | 2 | char * | 4.16 |
| 254 | `ifopen` | 1 | int (H) | 4.7 / 6 |
| 255 | `ifprint` | va | void | 4.1 |
| 256 | `igetenv` | 1 | char * | 4.8 / 6 |
| 257 | `iglob` | 1 | int (H) | 6 |
| 258 | `iglob_r` | 2 | int (H) | 6 |
| 259 | `igrep` | 2 | char * | 4.16 |
| 260 | `igrep_count` | 2 | int | 4.16 |
| 261 | `ihead` | 2 | char * | 4.16 |
| 262 | `ikill` | 1 | int | 4.16 |
| 263 | `ils` | 1 | char * | 4.16 |
| 264 | `imake` | 1 | int | 4.16 |
| 265 | `imkdir` | 1 | int | 6 |
| 266 | `iprint` | va | void | 4.1 |
| 267 | `iremove` | 1 | int | 6 |
| 268 | `irename` | 2 | int | 6 |
| 269 | `ireplace` | 3 | int | 4.16 |
| 270 | `irunning` | 1 | int | 4.16 |
| 271 | `ised` | 2 | char * | 4.3 / 4.16 |
| 272 | `ised_file` | 2 | int | 4.3 / 4.16 |
| 273 | `isetenv` | 2 | int | 4.8 / 6 |
| 274 | `isleep` | 1 | int | 4.16 / 4.17 |
| 275 | `isprint` | va | char * | 4.1 |
| 276 | `itail` | 2 | char * | 4.16 |
| 277 | `ithread_affinity_set` | 2 | int | 4.17 |
| 278 | `ithread_barrier` | 0 | int | 4.17 |
| 279 | `ithread_create` | 1 | int | 4.17 |
| 280 | `ithread_join` | 1 | int | 4.17 |
| 281 | `java` | 1 | char * | 4.29 |
| 282 | `jscript` | 1 | char * | 4.29 |
| 283 | `malloc` | 1 | void * | 4.28 |
| 284 | `max` | 2 | int | 4.38 |
| 285 | `min` | 2 | int | 4.38 |
| 286 | `printf` | va | void | 4.1 / 4.28 |
| 287 | `pscript` | 1 | char * | 4.29 |
| 288 | `python` | 1 | char * | 4.29 |
| 289 | `tensor_add` | 2 | int (H) | 4.23 |
| 290 | `tensor_argmax` | 2 | int | 4.23 |
| 291 | `tensor_causal_mask` | 1 | int (H) | 4.24 |
| 292 | `tensor_cols` | 1 | int | 4.23 |
| 293 | `tensor_cosine` | 2 | double | 4.27 |
| 294 | `tensor_cross_attention` | 12 | int (H) | 4.24 |
| 295 | `tensor_cross_entropy_loss` | 2 | double | 4.24 |
| 296 | `tensor_cross_entropy_loss_backward` | 2 | int (H) | 4.25 |
| 297 | `tensor_detokenize` | 1 | char * | 4.24 |
| 298 | `tensor_embedding_lookup` | 2 | int (H) | 4.24 |
| 299 | `tensor_embedding_lookup_backward` | 3 | int (H) | 4.25 |
| 300 | `tensor_free` | 1 | void | 4.23 |
| 301 | `tensor_get` | 3 | double | 4.23 |
| 302 | `tensor_init_spread` | 2 | int | 4.23 |
| 303 | `tensor_layernorm` | 4 | int (H) | 4.24 |
| 304 | `tensor_layernorm_backward_beta` | 1 | int (H) | 4.25 |
| 305 | `tensor_layernorm_backward_gamma` | 3 | int (H) | 4.25 |
| 306 | `tensor_layernorm_backward_x` | 4 | int (H) | 4.25 |
| 307 | `tensor_linear` | 3 | int (H) | 4.23 |
| 308 | `tensor_load` | 1 | int (H) | 4.26 |
| 309 | `tensor_matmul` | 2 | int (H) | 4.23 |
| 310 | `tensor_multihead_attention` | 5 | int (H) | 4.24 |
| 311 | `tensor_new` | 2 | int (H) | 4.23 |
| 312 | `tensor_positional_encoding` | 2 | int (H) | 4.24 |
| 313 | `tensor_relu` | 1 | int (H) | 4.23 |
| 314 | `tensor_relu_backward` | 2 | int (H) | 4.25 |
| 315 | `tensor_rows` | 1 | int | 4.23 |
| 316 | `tensor_save` | 2 | int | 4.26 |
| 317 | `tensor_scale` | 2 | int (H) | 4.23 |
| 318 | `tensor_self_attention` | 11 | int (H) | 4.24 |
| 319 | `tensor_set` | 4 | int | 4.23 |
| 320 | `tensor_sgd_step` | 3 | void | 4.26 |
| 321 | `tensor_softmax` | 1 | int (H) | 4.23 |
| 322 | `tensor_softmax_backward` | 2 | int (H) | 4.25 |
| 323 | `tensor_sub` | 2 | int (H) | 4.23 |
| 324 | `tensor_tokenize` | 1 | int (H) | 4.24 |
| 325 | `tensor_transpose` | 1 | int (H) | 4.23 |

---

*End of the ICPP User Manual. Copyright (c) 2026 Muhammad Anisur Rahman — MIT License.*
