---
title: OpenFlange Pipe Specification
spec: openflange.org/pipe/v0.1
version: 0.1.0-draft
status: experimental
updated: 2026-12-03
summary: The pipe contract — the OPENFLANGE.md manifest, named input and output ports, schemas, parameters, implementations, permissions and package discovery.
---

# OpenFlange Pipe Specification v0.1

This specification defines the OpenFlange pipe contract: the `OPENFLANGE.md` manifest file, whose YAML frontmatter declares a pipe's named input and output ports, schemas, parameters, implementation and permissions. It also defines how pipes are grouped into packages and how a processor must validate a manifest.

This document is published at <https://openflange.org/pipe/v0.1>. Its identifier, `openflange.org/pipe/v0.1`, is that URL without the scheme, and is the value documents of this kind carry in `spec:`.

## At a glance

- **Identifier:** `openflange.org/pipe/v0.1` — the value of `spec:` in documents of this kind
- **Published at:** <https://openflange.org/pipe/v0.1> (raw Markdown: <https://openflange.org/pipe/v0.1.md>)
- **Version:** 0.1.0-draft
- **Status:** experimental (feature maturity labels are listed in the document)
- **Updated:** 2026-12-03
- **JSON Schemas (2020-12):**
  - <https://openflange.org/schemas/pipe-v0.1.schema.json>
  - <https://openflange.org/schemas/package-v0.1.schema.json>
  - <https://openflange.org/schemas/error-v0.1.schema.json>
- **Related specifications:**
  - Pipeline: <https://openflange.org/pipeline/v0.1>
  - CLI protocol: <https://openflange.org/cli/v0.1>
  - HTTP Pipe Protocol: <https://openflange.org/http/v0.1>
  - Standard library: <https://openflange.org/std/v0.1>
  - Portable tests: <https://openflange.org/test/v0.1>
  - Lockfile: <https://openflange.org/lock/v0.1>
  - Registry: <https://openflange.org/registry/v0.1>
  - Package index: <https://openflange.org/package/v0.1>

## Minimal example

A complete, valid pipe: one file named `OPENFLANGE.md`.

```markdown openflange:manifest
---
spec: openflange.org/pipe/v0.1
id: lowercase
version: 0.1.0
inputs:
  text: {schema: {format: json-schema, definition: {type: string}}}
outputs:
  text: {schema: {format: json-schema, definition: {type: string}}}
implementation:
  type: expression
  language: starlark
  expression: text.lower()
---
# Lowercase

Implements the [OpenFlange](https://openflange.org/) specification.
```

Input stream `"Alice@Example.COM"` (one JSON string per line) produces
`"alice@example.com"`.

## 1. Introduction

OpenFlange is an open standard for discovering, connecting and executing
composable data-processing components. Its unit is the **pipe**: an opaque,
reusable transformation with named inputs and outputs. *Different pipes. One
standard.* — a pipe can be a Starlark expression, an R script, a Go binary, a
remote HTTP service or a pipeline of other pipes, and a consumer connects it
the same way in every case.

This document specifies the pipe **contract**: the manifest file
`OPENFLANGE.md`, and what its ports, schemas, parameters, implementation and
permissions mean. Companion specifications cover composition and execution
([Pipeline](https://openflange.org/pipeline/v0.1)), local executables ([CLI](https://openflange.org/cli/v0.1)),
remote services ([HTTP](https://openflange.org/http/v0.1)), discovery
([Registry](https://openflange.org/registry/v0.1)), the [standard library](https://openflange.org/std/v0.1),
[portable tests](https://openflange.org/test/v0.1) and the [lockfile](https://openflange.org/lock/v0.1). Each is
versioned independently.

### 1.1 Conventions

The key words MUST, MUST NOT, REQUIRED, SHALL, SHALL NOT, SHOULD, SHOULD NOT,
RECOMMENDED, MAY and OPTIONAL are to be interpreted as described in RFC 2119
and RFC 8174 when, and only when, they appear in capitals.

Fenced examples whose info string contains `openflange:<kind>` are normative
and machine-checked against the JSON Schemas in [`schemas/`](https://openflange.org/schemas/).
The schema for manifest frontmatter is
`https://openflange.org/schemas/pipe-v0.1.schema.json`. Where prose and schema
disagree, the prose is authoritative and the disagreement is a defect to be
reported.

A **runner** is any software that validates and executes pipes and pipelines.
A **consumer** is whoever uses a pipe: the author of a pipeline, or a person
invoking a runner.

### 1.2 Citing this document

Normative statements are cited by **section number**, for example
`pipe/v0.1 §4.2`, and numbered or bulleted rules within a section by their
position, for example `pipe/v0.1 §4.2(3)`. Section numbers are stable
within v0.1: sections are appended, never renumbered. Every heading has a
stable fragment identifier derived from its text (lower-cased; characters
other than letters, digits, spaces, hyphens and underscores removed; spaces
replaced by hyphens), so a section is addressable as
`https://openflange.org/pipe/v0.1#<fragment>`. Cross-references to other
OpenFlange specifications are absolute URLs of that form. This document
does not rely on images; its diagrams are text.

## 2. Terminology

- **pipe** — an opaque, reusable transformation contract with one or more
  named inputs and one or more named outputs. "Composite" describes how a pipe
  is implemented (by a pipeline); it is not a separate consumer-facing type.
- **source** — a pipe with zero inputs and one or more outputs.
- **sink** — a pipe with one or more inputs and zero outputs.
- **pipeline** — a directed acyclic graph of node instances.
- **subpipeline** — a pipeline used within another pipeline; it may have zero
  or more external inputs and outputs.
- **node** — an instance of a pipe inside a pipeline.
- **port** — a named interface of a pipe: an input or an output.
- **stream** — the data flowing through a connected port during a run.
- **run** — one execution instance of a pipe or pipeline.
- **dataset** — a named, reusable collection of records.
- **workflow** — RESERVED for future control-flow orchestration. This
  specification does not define workflows, and the word MUST NOT be used for
  pipelines in OpenFlange documents or tools.

## 3. Feature maturity

Every feature carries one of four labels: `proposed` (under discussion; may
change or vanish at any time), `experimental` (specified and implementable;
may change in a minor version with a changelog entry), `stable` (covered by
the compatibility guarantees), `deprecated` (scheduled for removal).

| Feature | Maturity |
|---|---|
| Manifest file, safe YAML, attribution link (section 4) | experimental |
| Core fields: `spec`, `id`, `version`, metadata, `maturity`, `scope` (5) | experimental |
| `cardinality`, `deterministic`, function-like pipes (5.4) | experimental |
| `requires` and mandatory-feature rejection (5.5) | experimental |
| `x-` extension keys (5.6) | experimental |
| Batch mode: `batch` for `executable` and `script` implementations (5.7, 9.5) | experimental (feature `batch`) |
| Ports of kind `records`, `values`, `text`, `binary` (6) | experimental |
| Ports of kind `batches` and the `arrow` schema format (6) | experimental (optional capability `arrow`) |
| Ports of kind `windows` (6) | proposed (window framing) |
| Optional ports (`required: false`) (6.4) | experimental |
| Variadic inputs (6.5) | experimental (feature `variadic`) |
| Parameters, including `minLength`, `maxLength`, `pattern` (7) | experimental |
| Implementations `builtin`, `expression`, `script`, `executable`, `http`, `pipeline` (8) | experimental |
| Starlark binding (9) | experimental |
| Permissions and grants (10) | experimental |
| Package discovery, `openflange.yaml`, npm `package.json` key (11) | experimental |
| Implementation type `wasm` | reserved; not specified |

Nothing in this specification is `stable` or `deprecated` in v0.1.

## 4. The manifest file

### 4.1 File

Every pipe has a manifest: a UTF-8 Markdown file named `OPENFLANGE.md`
(exactly this name, case-sensitive). It consists of YAML **frontmatter**
followed by a Markdown **body**.

- The file MUST be valid UTF-8 and MUST NOT begin with a byte order mark.
- The first line MUST be exactly `---`. The frontmatter ends at the next line
  that is exactly `---`. A trailing carriage return on these lines is
  tolerated.
- The frontmatter is the **authoritative machine-readable contract**. The
  body is documentation for humans; apart from the attribution link (4.3) a
  runner MUST NOT derive behaviour from it.

A manifest that violates these rules is rejected with `E_MANIFEST`.

### 4.2 Safe YAML

Manifests are untrusted input. A processor MUST parse frontmatter — and every
other OpenFlange YAML document — as follows:

1. YAML 1.2 **core schema** only. `yes`, `no`, `on`, `off` are strings; `010`
   is the integer ten; dates such as `2026-12-03` are strings.
2. No custom tags. Any explicit tag other than the core-schema tags MUST be
   rejected.
3. **Anchors and aliases MUST be rejected**, as MUST merge keys (`<<`). This
   removes alias-expansion ("billion laughs") attacks by construction.
4. **Duplicate mapping keys MUST be rejected**, at every nesting level.
5. The YAML text MUST NOT exceed 1 MiB (1 048 576 bytes).
6. Exactly one YAML document; the top-level node MUST be a mapping.
7. Mapping keys MUST be strings.

A duplicate key is reported as `E_DUPLICATE`; any other violation as
`E_MANIFEST`. A processor MUST apply these checks before any other
interpretation, and SHOULD use a streaming check so that a hostile document
cannot exhaust memory before it is rejected.

After parsing, the frontmatter MUST validate against the manifest schema. A
schema violation is `E_MANIFEST`. In particular, **unknown top-level keys are
rejected** unless they are extension keys (5.6).

### 4.3 Attribution link

The Markdown body MUST contain at least one **visible Markdown hyperlink whose
destination is exactly `https://openflange.org/`**. A manifest without one is
rejected with `E_ATTRIBUTION`. The link is an attribution to the standard; it
is not an endorsement, certification or trademark licence (see `BRAND.md`).

Normatively, with the body interpreted as CommonMark:

- The link MUST be a CommonMark *link* — an inline link `[text](https://openflange.org/)`,
  a reference link whose definition has that destination, or an autolink
  `<https://openflange.org/>`.
- The destination MUST equal the string `https://openflange.org/` exactly:
  scheme `https`, lower-case host, a single trailing slash, no path, query or
  fragment. `https://openflange.org` (no slash), `http://openflange.org/` and
  `https://www.openflange.org/` do not satisfy the requirement.
- The link text MUST contain at least one non-whitespace character. An image
  (`![...](...)`) is not a hyperlink.
- A bare URL in running text is not a link (CommonMark has no bare-URL
  autolinks; processors MUST NOT apply the GitHub "extended autolink"
  extension for this check).
- Text that CommonMark does not parse as a link does not count: links inside
  **HTML comments**, raw HTML (including `<a href>`), **code spans**,
  **fenced code blocks** and indented code blocks are ignored.

The recommended sentence is:

> Implements the [OpenFlange](https://openflange.org/) specification.

## 5. Frontmatter

### 5.1 Fields

| Key | Required | Type and constraints |
|---|---|---|
| `spec` | yes | The constant `openflange.org/pipe/v0.1`. |
| `id` | yes | `^[a-z0-9][a-z0-9-]{0,63}$`. Identifies the pipe within its package or publisher namespace. |
| `version` | yes | SemVer 2.0.0 version of the pipe **contract and behaviour**. |
| `title` | no | Short human-readable name. |
| `description` | no | One-paragraph description. |
| `license` | no | SPDX licence expression chosen by the pipe's author. |
| `keywords` | no | List of unique strings. |
| `maturity` | no | `proposed` \| `experimental` \| `stable` \| `deprecated`. Maturity of this pipe, declared by its author. |
| `scope` | no | Processing scope: `record` (default) \| `window` \| `dataset` (5.3). |
| `cardinality` | no | `one-to-one` \| `any` (default) (5.4). |
| `deterministic` | no | Boolean, default `false` (5.4). |
| `batch` | no | Batch mode: `{maxItems, maxWaitMs}` (5.7). Absent: the pipe is not in batch mode. |
| `requires` | no | List of mandatory feature identifiers (5.5). |
| `inputs` | see 5.2 | Map of port name to Port (6). |
| `outputs` | see 5.2 | Map of port name to Port (6). |
| `parameters` | no | Map of parameter name to Parameter (7). |
| `implementation` | yes | Implementation (8). |
| `permissions` | no | Permissions the pipe needs (10). Default: none. |
| `x-<vendor>-<name>` | no | Extension (5.6). |

A runner MUST reject a manifest whose `spec` it does not implement
(`E_UNSUPPORTED` if the value is a syntactically valid OpenFlange spec
identifier of another version; `E_MANIFEST` otherwise).

### 5.2 Pipes, sources and sinks

The kind of a pipe follows from its ports:

- no inputs and at least one output — a **source**;
- at least one input and no outputs — a **sink**;
- at least one input and at least one output — a (plain) **pipe**.

A manifest with neither inputs nor outputs is invalid (`E_MANIFEST`). An
absent `inputs` or `outputs` key is equivalent to an empty map. A port name
MUST be unique within its direction; the same name MAY be used for one input
and one output (as in `lowercase`: `text` → `text`).

### 5.3 Processing scope

`scope` tells consumers how much data the pipe needs before it can produce
output, so that they can reason about memory and latency:

- `record` — processes item by item with bounded state. The default.
- `window` — processes one window at a time; its primary input is normally of
  kind `windows`. Memory is bounded by the window size.
- `dataset` — materialises its whole input before producing output (for
  example a statistical summary). Memory is proportional to the input.
  Materialisation is always explicit: a runner MUST NOT buffer a whole stream
  on behalf of a pipe that did not declare `dataset` scope.

Scope is a declaration; it does not change stream semantics.

### 5.4 Cardinality, determinism and function-like pipes

`cardinality` describes the relation between input items and output items:

- `any` (default) — no promise.
- `one-to-one` — the pipe emits **exactly one output item for every input
  item, in the same order**. It MUST only be declared by a pipe with exactly
  one input, exactly one output and `scope: record` (`E_MANIFEST` otherwise).

`deterministic: true` declares that the same input item and the same
parameters always give the same output item, and that the pipe performs no
I/O. The default is `false`.

A pipe with exactly one input, exactly one output, `scope: record`,
`cardinality: one-to-one` and `deterministic: true` is **function-like**.
Hosts — query languages, spreadsheets, user interfaces — MAY call a
function-like pipe as a scalar function (see
RFC 0002 (`rfcs/0002-pipes-as-query-functions.md` in the specification repository)).

Enforcement:

- An `expression` implementation is one-to-one by construction (8.2).
- For every other implementation type, a runner MUST enforce a declared
  `cardinality: one-to-one` at run time: an input item that yields zero or
  more than one output item fails the node with `E_RUNTIME`. A runner MUST
  NOT repair the stream (for example by inserting `null`).
- `deterministic` cannot be verified in general and a runner is not required
  to. Hosts that depend on it SHOULD accept only in-process implementations
  (`builtin`, Starlark `expression` or `script`, pipelines of those) that
  declare and imply no permissions.

A pipe that can route an item to another output instead of producing a
result — such as the reference `mask-email`, which has a `rejected` output —
is not one-to-one and MUST NOT declare it.

### 5.5 Mandatory features (`requires`)

`requires` lists features a runner MUST implement in order to run the pipe
correctly. **A runner MUST reject a manifest that requires a feature it does
not implement or does not recognise**, with `E_UNSUPPORTED`; ignoring an
unknown entry is not permitted.

Feature identifiers defined by v0.1:

| Identifier | Meaning | Maturity |
|---|---|---|
| `windows` | `windows` ports and window framing | proposed |
| `processing-time-windows` | processing-time window semantics | proposed |
| `arrow` | `batches` ports, Arrow IPC streams, `arrow` schema format | experimental |
| `variadic` | variadic inputs | experimental |
| `batch` | batch mode (5.7) | experimental |

A manifest that uses one of `windows`, `processing-time-windows`, `arrow`
or `variadic` MUST list it. `batch` is different: the top-level `batch` key
is itself the demand (a runner that does not know the key rejects the
manifest as an unknown top-level key, and a runner that knows it MUST
honour or refuse it, 5.7), so a manifest that declares `batch` MAY list the
feature but need not. The identifier exists so that runners can report the
capability. Vendor features use
the form `x-<vendor>-<name>` and are, by the rule above, rejected by every
runner that does not know them.

### 5.6 Extensions

Keys beginning with `x-` are extension keys. They are permitted at the top
level of the frontmatter and inside ports, port schemas, parameters, known
implementation objects and permissions. The recommended form is
`x-<vendor>-<name>`. A processor MUST preserve extension keys it does not
understand when rewriting a manifest and MUST NOT fail because of them.
Extensions MUST NOT change the meaning of standard keys; a behaviour that a
runner must honour belongs in `requires`.

### 5.7 Batch mode

> **Maturity: experimental.** Decided 2026-12-03; see RFC 0003
> (`rfcs/0003-batch-mode.md` in the specification repository). Batch mode
> is for `executable` and `script` implementations only.

```yaml
batch:
  maxItems: 100
  maxWaitMs: 1000
```

A pipe MAY declare **batch mode**. Its implementation then receives the
items of its input in **slices of up to `maxItems` items** instead of one
item at a time. Batch mode exists for implementations that live outside
the runner — a subprocess in R, Python, Node or any other language, or a
script — and that otherwise pay a cost per record, or need a bounded group
of records to vectorise an operation or to make one external call: a
request to a language model or an embedding service, an enrichment lookup,
a bulk insert, a vectorised R or Python function.

| Key | Required | Type and constraints |
|---|---|---|
| `maxItems` | yes | Integer, 1 to 1 000 000. The largest slice the implementation receives. |
| `maxWaitMs` | no | Integer, 0 to 3 600 000, default `0`. The longest time, in milliseconds, the runner may hold the first item of a pending slice while waiting for more. `0`: the runner never waits. |
| `delivery` | no | `lines` (default) or `file`: how a slice reaches an `executable` implementation — as one JSON array on a line of standard input, or as an NDJSON file whose path the program is given. Only for `executable` implementations and `script` implementations in `r`, `python` or `node`. |

The runner accumulates items and delivers a slice when the first of three
things happens — `maxItems` is reached, `maxWaitMs` has elapsed since the
first pending item arrived, or the input ends. One slice is in flight at a
time, and **while the implementation works on it the runner keeps
accumulating the next**, so a busy pipe receives fuller slices without any
waiting. The rule is normative and is defined in the
[Pipeline specification, section 8.11](https://openflange.org/pipeline/v0.1#811-batch-mode).
There is **no minimum size**: every slice has between 1 and `maxItems`
items, and an implementation MUST accept any size in that range, including
a slice of one. Without `batch`, a pipe behaves exactly as if this section
did not exist.

**Preconditions.** A manifest that declares `batch` MUST satisfy all of the
following (`E_MANIFEST` otherwise):

1. The pipe has **exactly one input port**. Sources, and pipes with two or
   more inputs, cannot declare batch mode in v0.1.
2. That input is of kind `records`, `values` or `windows` (on a `windows`
   port one window frame is one item), and is not variadic.
3. The implementation type is `executable` or `script` (in any language).
   Batch mode MUST NOT be declared with:
   - `builtin` — an implementation inside the runner already receives its
     input in whatever units the runner's native interface provides and
     controls its own reads, so a declaration would add nothing;
   - `expression` — per item by construction (8.2);
   - `pipeline` — a composite has no implementation of its own to hand
     slices to; the pipes used inside it declare batch mode themselves;
   - `http` — v0.1 defines no batch mode for the HTTP Pipe Protocol: a
     remote pipe already receives a continuous stream and can group it
     itself.
4. `delivery: file` is declared only with an `executable` implementation or
   a `script` implementation in `r`, `python` or `node`. A Starlark script
   always receives a slice as a list in memory.
5. The placeholders `{batch.input}` and `{batch.output}` in the `command`
   of an `executable` implementation
   ([CLI specification, section 5.2](https://openflange.org/cli/v0.1#52-batch-files))
   are used only together with `delivery: file`; `{batch.output}` requires
   `{batch.input}`; `command[0]` contains neither; and no other token of
   the form `{batch.<name>}` appears in `command`. This rule applies to
   every manifest, also one without `batch`.

**Batch boundaries are not semantic.** This is the central rule:

- A conformant batch-mode pipe MUST produce **the same output items, in the
  same order, on every output, however its input is split into slices**.
  Slicing the input as `[a, b, c]`, as `[a]`, `[b, c]` or as `[a]`, `[b]`,
  `[c]` gives identical output streams. Where the slices fall depends on
  timing, on the consumer's settings and on the runner, and a pipe MUST NOT
  let it show.
- A pipe that needs to compute *over a group* — a sum per hundred records,
  "the first item of each group" — does not want batch mode. Grouping with
  meaning is a **window**: use
  [`std:window`](https://openflange.org/std/v0.1#55-windows) and consume window frames.
- State that persists across slices (a counter, a deduplication set) is
  permitted exactly as it is for a per-item pipe; it MUST NOT depend on
  where slices begin and end.
- A runner cannot verify this in general. Portable tests can pin batch
  settings so that the same expectations are asserted under several slice
  sizes ([Portable tests, section 3.4](https://openflange.org/test/v0.1#34-batch-settings)),
  and authors SHOULD test at least `maxItems: 1` and a size larger than the
  input.

**Composition with `cardinality: one-to-one`.** A pipe MAY declare both.
Each slice MUST then yield **exactly as many output items as it has input
items, in the same order**; the i-th output of a slice corresponds to its
i-th input. A slice that yields fewer or more fails the node with
`E_RUNTIME` (5.4 applies per slice). A batch-mode pipe that is otherwise
function-like (5.4) remains function-like; how hosts batch scalar calls is
future work (RFC 0003).

**Consumers** may tighten, never loosen, the declared settings per node
([Pipeline specification, section 3.8](https://openflange.org/pipeline/v0.1#38-node-batch-settings)).
Authors SHOULD therefore declare the *largest* slice and the *longest* wait
the implementation is prepared for.

**Delivery by implementation type.**

| Implementation | A slice is delivered as | Maturity |
|---|---|---|
| `executable`; `script` in `r`, `python`, `node` — `delivery: lines` | one line holding a JSON array of the slice's items, answered by one line holding a JSON array of output items ([CLI specification, section 5.1](https://openflange.org/cli/v0.1#51-batch-framing)) | experimental |
| `executable`; `script` in `r`, `python`, `node` — `delivery: file` | an NDJSON file per slice in a directory private to the node; the program is told the path on standard input, or — when `command` contains `{batch.input}` — is started once per slice ([CLI specification, section 5.2](https://openflange.org/cli/v0.1#52-batch-files)) | experimental |
| `script`, `language: starlark` | one call of `process_batch(items, params)` with a list (9.5) | experimental |
| `builtin`, `expression`, `pipeline`, `http` | not permitted (`E_MANIFEST`) | — |

**Capability.** A runner MUST NOT run a pipe that declares `batch` without
batching it. A runner that does not implement batch mode for the pipe's
implementation type and language MUST reject the manifest at validation
time with `E_UNSUPPORTED`, and MUST report for which implementation types
it supports the feature `batch` (capability discovery, section 8).

## 6. Ports

```yaml
kind: records
required: true
variadic: false
description: One customer per item.
schema:
  format: json-schema
  definition: {type: object}
mediaTypes: [application/x-ndjson]
```

Port names match `^[a-zA-Z][a-zA-Z0-9_]{0,63}$`. Every key of a port is
optional; `text: {}` declares an untyped required `records` port.

### 6.1 Kind

`kind` states what a stream on the port carries. The stream formats are
defined in the [Pipeline specification, section 7](https://openflange.org/pipeline/v0.1#7-streams).

| kind | carries |
|---|---|
| `records` | JSON values, normally objects, one per item |
| `values` | JSON scalars, one per item |
| `batches` | Arrow record batches (transport units of typed rows) |
| `windows` | window frames (proposed) |
| `text` | opaque UTF-8 text |
| `binary` | opaque bytes |

If `kind` is omitted it is `values` when the port has a `json-schema` schema
whose definition has a `type` keyword naming only scalar types (`string`,
`integer`, `number`, `boolean`, `null`), and `records` otherwise.

### 6.2 Schema

`schema` describes the *logical* shape of the data, independently of its
encoding. A port without `schema` is **untyped** and accepts anything of its
kind.

- `format` — `json-schema` (the default), `arrow`, or a vendor format
  `x-<vendor>-<name>`. A runner MUST treat a format it does not understand as
  untyped for compatibility checking and MUST NOT fail solely because of it.
- Exactly one of `definition` (inline) and `path` (a file in the package,
  see 12) MUST be present.

For `records` and `values` ports the schema describes **one item**, not the
stream. For `windows` ports it describes one item inside a window. For `text`
and `binary` ports a schema has no defined meaning and SHOULD be omitted.

**JSON Schema.** The dialect is JSON Schema 2020-12. `$ref` MUST resolve
within the same document; a runner MUST NOT fetch remote references.
`format` keywords are annotations.

**Arrow.** The definition is the JSON form
`{fields: [{name, type, nullable}]}`, with `nullable` defaulting to `true`
and type names written as in Arrow: `int64`, `float64`, `utf8`, `bool`,
`binary`, `decimal128(p,s)`, `timestamp[us, UTC]`, `date32` (and the other
Arrow primitive names by the same convention).

```yaml openflange:pipe
spec: openflange.org/pipe/v0.1
id: orders-source
version: 0.1.0
requires: [arrow]
outputs:
  orders:
    kind: batches
    schema:
      format: arrow
      definition:
        fields:
          - {name: id, type: int64, nullable: false}
          - {name: total, type: "decimal128(18,2)"}
          - {name: placed, type: "timestamp[us, UTC]"}
implementation: {type: builtin, name: "builtin:example/orders"}
```

Schema compatibility between connected ports is decided by the pipeline
compiler ([Pipeline specification, section 6](https://openflange.org/pipeline/v0.1#6-compilation-and-validation)).

### 6.3 Media types

`mediaTypes` lists the encodings the port can read or write, in order of
preference. When omitted, the default for the kind applies
(`application/x-ndjson` for `records` and `values`, and so on). Logical
schema and encoding are separate: two ports with the same schema and
different media types are connected by negotiation or by an explicit
conversion, never by guessing.

### 6.4 Required and optional ports

`required` defaults to `true`.

- A **required input** MUST be connected to a producer. An empty stream is a
  valid connection: "connected and empty" is different from "disconnected".
- A **required output** MUST have a consumer or an explicit discard.
- An **optional input** (`required: false`) MAY be left disconnected; the
  implementation is told and MUST work without it.
- An **optional output** MAY be left disconnected or be disabled by the
  consumer. The implementation is told the set of enabled ports before it
  processes anything, MUST NOT require a reader for a disabled output, and
  MUST NOT silently discard data that it can only deliver there unless
  discarding is the documented meaning of leaving that port disconnected.

Whether leaving an optional output disconnected means "discard" or "fail"
is part of each pipe's documented contract. The reference `mask-email` pipe
fails a run when an invalid address has nowhere to go; `std:filter` discards
non-matching items. Record-level errors are ordinary data on a declared
port; nothing is implicit.

### 6.5 Variadic inputs

An input with `variadic: true` accepts a list of producers and presents them
to the implementation as an ordered list of streams. It is the only way
several producers can feed one logical input, and in v0.1 only `builtin`
implementations can declare it (`std:merge`). A manifest declaring a variadic
input MUST list `variadic` in `requires`. `variadic` is not permitted on
outputs.

## 7. Parameters

Parameters configure a node. They are **immutable for the duration of a node
execution**: data that changes during a run travels on streams, not in
parameters. Secrets are never parameters (10.4).

```yaml
preserveFirst:
  type: integer
  default: 1
  minimum: 0
  maximum: 8
  description: Number of leading characters left unmasked.
```

| Key | Meaning |
|---|---|
| `type` | REQUIRED. `string` \| `integer` \| `number` \| `boolean` \| `array` \| `object`. |
| `default` | Value used when the consumer supplies none. MUST itself satisfy the declaration. |
| `required` | Default `false`. A required parameter without a default MUST be supplied. |
| `description` | Human-readable. |
| `enum` | Non-empty list of permitted values. |
| `minimum`, `maximum` | Inclusive bounds; meaningful for `integer` and `number`. |
| `minLength`, `maxLength` | For `string` only: inclusive bounds on the length **in Unicode code points** (not bytes, not UTF-16 code units). Non-negative integers. |
| `pattern` | For `string` only: a regular expression the value must match. |

Parameter names match `^[a-zA-Z][a-zA-Z0-9_]{0,63}$`. Two parameters of one
pipe MUST NOT differ only in a way that maps them to the same environment
variable name under the [CLI specification](https://openflange.org/cli/v0.1) (`E_MANIFEST`).

A value is checked against the declaration **before the node starts**:
`integer` accepts JSON numbers with no fractional part; `number` accepts any
JSON number; a violation of type, `enum`, numeric bounds, length bounds or
`pattern` is `E_PARAM`. A parameter
with neither a supplied value nor a default is absent from the resolved
parameters.

**String constraints.**

1. `minLength`, `maxLength` and `pattern` MUST only appear on parameters of
   type `string`, and `minLength` MUST NOT exceed `maxLength`
   (`E_MANIFEST` otherwise).
2. Length is the number of Unicode code points of the value. No
   normalisation is applied: `"é"` written as one code point has length 1,
   written as `e` plus a combining accent it has length 2. `"🙂"` has
   length 1.
3. `pattern` uses the RE2 regular-expression syntax (the common subset of
   RE2 and ECMA-262: no look-around, no back-references), matched against
   the code points of the value. As in JSON Schema the match is **not
   anchored**: the value is accepted if the expression matches anywhere in
   it; authors write `^…$` to constrain the whole value. A `pattern` that
   is not a valid expression makes the manifest invalid (`E_MANIFEST`).
4. A value violating any of them is `E_PARAM`, like any other bound.

"Exactly one Unicode code point" is therefore declared as
`minLength: 1, maxLength: 1`.

Constraints that the declaration still cannot express are the
implementation's responsibility: it MUST check them and fail, rather than
proceed with a meaningless value.

How a consumer binds parameters (`$param`, `$env`, `$expr`) is defined in the
[Pipeline specification, section 5](https://openflange.org/pipeline/v0.1#5-parameters-and-secrets).

## 8. Implementations

`implementation` says how the contract is realised. It is discriminated by
`type`. The separation is deliberate: the contract (ports, parameters) is the
same whether the pipe runs in-process, as a subprocess or on a remote server.

| type | fields | executes |
|---|---|---|
| `builtin` | `name` | inside the runner |
| `expression` | `language`, `expression` | inside the runner |
| `script` | `language`, `path`, `entrypoint`, `usage` | inside the runner (Starlark) or as a subprocess |
| `executable` | `command`, `stdin`, `stdout`, `env`, `usage` | as a subprocess |
| `http` | `url`, `pipe` | on a remote server |
| `pipeline` | `path` | as a subpipeline |

`wasm` is reserved for a future version. A runner MUST reject, with
`E_UNSUPPORTED`, an implementation `type` it does not implement — including
`wasm`, vendor types (`x-…`) it does not know, and any other unknown value —
and a `language` it does not implement. The manifest schema deliberately does
not enumerate `type`, so that this is reported as an unsupported feature
rather than as a malformed manifest.

A runner MUST be able to report which implementation types and languages it
supports before execution (capability discovery), and MUST perform this check
at validation time, not when the node starts.

### 8.1 builtin

```yaml
implementation: {type: builtin, name: "std:filter"}
```

The runner provides the implementation. `name` is `std:<name>` for standard
library pipes or `builtin:<runtime>/<name>` for runtime-specific ones.
`builtin` is used by the manifests of standard and runtime pipes; a pipe
author cannot add behaviour to a runner this way. A `builtin`
implementation MUST NOT be combined with `batch` (5.7).

### 8.2 expression

```yaml
implementation:
  type: expression
  language: starlark
  expression: text.lower()
```

A per-item expression. The pipe MUST have exactly one input and exactly one
output (`E_MANIFEST` otherwise). For each input item the expression is
evaluated and its value is emitted on the output: exactly one output item per
input item, in order. The only language defined by v0.1 is `starlark` (9).
An `expression` implementation MUST NOT be combined with `batch` (5.7).

### 8.3 script

```yaml
implementation:
  type: script
  language: starlark
  path: mask.star
  entrypoint: process
```

`path` is a file in the package (12). With `language: starlark` the script
runs in-process under the binding of section 9, and `entrypoint` names the
function the runner calls: for each item, default `process`; or, when the
manifest declares `batch` (5.7), for each slice, default `process_batch`
(9.5). An explicit `entrypoint` overrides the default in both cases.

Other languages are **sugar for `executable`** with the conventional
interpreter, following the [CLI specification](https://openflange.org/cli/v0.1):

| language | equivalent command |
|---|---|
| `r` | `["Rscript", "--vanilla", <path>]` |
| `python` | `["python3", <path>]` |
| `node` | `["node", <path>]` |

For these, `entrypoint` is ignored, the sole or first-declared input is bound
to stdin and the sole or first-declared output to stdout, and the pipe
**requires the `subprocess` permission** exactly like an `executable`. A
runner that lacks the interpreter MUST report `E_UNSUPPORTED` at validation
time. When the manifest declares `batch`, the subprocess receives slices
in the array framing of the CLI specification, section 5.1.

### 8.4 executable

```yaml
implementation:
  type: executable
  command: ["./bin/validate-email", "--strict"]
  stdin: records
  stdout: valid
  env: {LC_ALL: C}
```

- `command` is an argument vector. It is executed directly, **never through a
  shell**; no word splitting, globbing or variable expansion is performed. If
  `command[0]` contains a `/` it is a path relative to the manifest (12);
  otherwise it is looked up on the subprocess `PATH`.
- `stdin` names the input port bound to standard input and `stdout` the output
  port bound to standard output. When omitted, the sole input and the sole
  output are bound; if there are several ports and no binding is named, none
  is bound to that standard stream. Other enabled ports are reached through
  the authenticated loopback endpoints of the CLI protocol.
- `env` adds literal, non-secret environment variables.
- `usage: true` (experimental) asks the runner for the usage reporting
  endpoint of the
  [CLI specification, section 5.3](https://openflange.org/cli/v0.1#53-usage-reporting),
  through which the program reports counters such as language-model
  tokens for the run report. Default `false`. It is a request, not a
  requirement: the pipe MUST work without the endpoint. The key is also
  valid on a `script` that runs as a subprocess; on a Starlark script,
  which runs inside the runner, it is an error of the manifest
  (`E_MANIFEST`).

The process protocol — configuration file, parameters, endpoints, exit
status, cancellation — is the [CLI specification](https://openflange.org/cli/v0.1).
For a pipe in batch mode (5.7) it also defines the framing: one JSON
array per line in both directions, or — with `delivery: file` — one NDJSON
file per slice. Only with `delivery: file` may `command` contain the
placeholders `{batch.input}` and `{batch.output}`; the runner then starts
the command once per slice with the paths substituted, and `{{` in any
element of such a `command` stands for a literal `{`.

### 8.5 http

```yaml
implementation:
  type: http
  url: https://pipes.example.com/v1
  pipe: validate-email
```

`url` is the base URL of a server speaking the
[HTTP Pipe Protocol](https://openflange.org/http/v0.1); `pipe` is the remote pipe id and
defaults to this manifest's `id`. The pipe requires the `network` permission
for the URL's `host:port` and `remoteData` for its host (10.2), because
record data leaves the machine. The local manifest is the contract the
consumer compiles against; the runner MUST verify at session creation that
the remote definition satisfies it and fail with `E_PROTOCOL` otherwise.
An `http` implementation MUST NOT be combined with `batch` (5.7).

### 8.6 pipeline

```yaml
implementation:
  type: pipeline
  path: pipeline.yaml
```

A composite pipe. `path` names a pipeline file
([Pipeline specification](https://openflange.org/pipeline/v0.1)) whose `inputs.<name>`
sources and `outputs` entries are exactly this manifest's ports, and whose
`$param` bindings refer to this manifest's parameters. Consumers cannot tell,
and need not know, that a pipe is composite. A composite MUST NOT declare
`batch` (5.7); the nodes inside it may be batch-mode pipes.

## 9. Starlark binding

This section is the language binding for `language: starlark`
(`experimental`). Language bindings are versioned with this specification in
v0.1 and are expected to be versioned separately later.

### 9.1 Dialect

The language is Starlark as specified by the Starlark language specification,
with these properties, which a conformant runner MUST provide:

- strings are sequences of UTF-8 bytes with the methods `elems()`,
  `codepoints()` and `codepoint_ords()`; `len(s)` counts bytes. Code-point
  logic MUST use `codepoints()`;
- integers have arbitrary precision; floats are IEEE 754 doubles;
- `load` statements are not available; there is no file, network, clock,
  random-number or environment access;
- top-level code runs once per node execution, before the first item;
  module globals are frozen afterwards;
- recursion is not available (standard Starlark).

A runner SHOULD bound the number of execution steps per item and MUST fail
the node with `E_RESOURCE` when a bound is exceeded. Evaluation errors,
including a call to the built-in `fail(msg)`, fail the node with
`E_RUNTIME`. Syntax errors and unresolved names are reported at validation
time (`E_MANIFEST` for a pipe's own code, `E_PARAM` for an expression
supplied as a parameter).

### 9.2 Value mapping

| JSON | Starlark |
|---|---|
| object | `dict` (member order preserved) |
| array | `list` |
| string | `string` |
| number written as an integer literal (no fraction, no exponent) | `int`, exactly |
| any other number | `float` |
| `true` / `false` | `bool` |
| `null` | `None` |

In the other direction `int` is written as an integer literal of any size,
`float` as the shortest literal that round-trips (a non-finite float fails
with `E_RUNTIME`), `tuple` as an array; dict keys MUST be strings. Any other
value fails with `E_RUNTIME`.

A non-integer number that passes *through* Starlark is therefore subject to
double precision. Pipes that must preserve decimals exactly MUST NOT route
them through arithmetic in Starlark; passing an item through a standard pipe
that does not modify it preserves it exactly
([Pipeline specification, section 7.3](https://openflange.org/pipeline/v0.1#73-number-fidelity)).

### 9.3 Expressions

An `expression` implementation is evaluated with two names bound:

- the **input port's name** — the current item (in `lowercase`, the variable
  is `text`). v0.1 supports a single input;
- `params` — a dict of the node's resolved parameters.

The value of the expression is emitted on the sole output; `None` is emitted
as JSON `null`. If the port name is not a valid Starlark identifier or
collides with `params`, the manifest is invalid (`E_MANIFEST`).

### 9.4 Scripts

The script defines the entry point `def process(item, params)`, called once
per input item in order. v0.1 scripts have a single input. Predeclared
functions:

- `emit(port, value)` — writes `value` to the named output. It MAY be called
  any number of times per item, for any declared output.
- `enabled(port)` — returns `True` if the named output is enabled for this
  node execution.

Rules:

1. If the pipe declares **exactly one output**, a non-`None` return value is
   emitted on it, after any values emitted by `emit` during the call.
   Returning `None` emits nothing (the item is consumed).
2. If the pipe declares several outputs, the behaviour of a non-`None`
   return value is not defined by v0.1; portable scripts MUST use `emit` and
   return `None`.
3. `emit` to an undeclared port fails with `E_RUNTIME`.
4. `emit` to a declared output that is **not enabled** fails with
   `E_RUNTIME`: data is never dropped silently. A script that wants
   "discard if nobody listens" semantics tests `enabled(port)` first.
5. On an input of kind `windows`, `item` is the whole window frame as a
   dict (`item["window"]`, `item["items"]`).

### 9.5 Batch scripts

When the manifest declares `batch` (5.7), the script is called **once per
slice** instead of once per item. The entry point is
`def process_batch(items, params)` — the default `entrypoint` name is
`process_batch` when `batch` is declared, and an explicit `entrypoint`
still overrides it.

- `items` is a `list` of the slice's items in input order, each mapped as
  in 9.2. It is never empty and never longer than the effective
  `maxItems`. On an input of kind `windows` each element is a whole window
  frame.
- `params`, `emit(port, value)` and `enabled(port)` are exactly as in 9.4.
  `emit` MAY be called any number of times per slice.

Rules:

1. If the pipe declares exactly one output — or several, of which exactly
   one is required — a non-`None` return value MUST be a `list` (or
   `tuple`) of output items. Its elements are emitted on that output, in
   order, after any values emitted by `emit` during the call. An empty list
   emits nothing. Any other non-`None` return value fails the node with
   `E_RUNTIME`; in particular a single item is not accepted in place of a
   list, so that an item that is itself a list is never ambiguous.
2. Returning `None` emits nothing beyond what `emit` wrote.
3. With several required outputs (or none), a non-`None` return value is
   not defined by v0.1, as in 9.4(2); portable scripts use `emit`.
4. Rules 9.4(3) and 9.4(4) apply unchanged.
5. With `cardinality: one-to-one`, each call MUST produce exactly
   `len(items)` items on the output, in the order of `items`
   (`E_RUNTIME` otherwise).
6. The step bound of 9.1 applies per call, that is per slice.

A script MUST give the same output however its input is sliced (5.7). The
simplest way is to write the per-item logic as a function and map it:

```python
def mask(email, params):
    ...

def process_batch(items, params):
    return [mask(e, params) for e in items]
```

For such a script batch mode saves only the per-call overhead of the
interpreter. Starlark has batch mode chiefly because it is the
dependency-free, network-free runtime in which the invariants of 5.7 can be
demonstrated portably; the large gains are for subprocess implementations
(RFC 0003 has measurements).

## 10. Permissions

### 10.1 Model

A pipe **declares** what it needs; the consumer **grants**; the runner
**enforces or refuses**. There is no third option: a runner that cannot
enforce a restriction MUST NOT pretend to, and MUST NOT run a node whose
required permissions have not been granted (`E_PERMISSION`).

```yaml
permissions:
  network: ["api.example.com:443"]
  filesystem: {read: ["./data"], write: []}
  subprocess: true
  environment: ["HOME"]
  secrets: ["OPENAI_API_KEY"]
  remoteData: ["api.example.com"]
```

| Key | Declares |
|---|---|
| `network` | Destinations the pipe connects to, as `host:port`. |
| `filesystem.read`, `filesystem.write` | Paths the pipe reads or writes. Relative paths resolve against the manifest (12). |
| `subprocess` | The pipe starts a process. |
| `environment` | Names of environment variables the pipe reads. |
| `secrets` | Names of secrets the pipe needs (10.4). |
| `remoteData` | Hosts to which **record data** is transmitted. Distinct from `network`: a pipe may download a model (network) without sending data anywhere. |

### 10.2 Required permissions

The permissions a node *requires* are those its manifest declares plus those
its implementation implies:

- `executable`, and `script` in a language other than Starlark, imply
  `subprocess: true`;
- `http` implies `network` for the `host:port` of `url` (port 443 for
  `https`, 80 for `http` when not written) and `remoteData` for its host;
- `builtin`, Starlark `expression` and `script`, and a `pipeline` composed
  only of those, are **in-process** and imply nothing.

Authors SHOULD declare implied permissions explicitly so that the manifest
reads truthfully. Some standard I/O pipes have requirements derived from
their parameters ([Standard library, section 5.7](https://openflange.org/std/v0.1#57-sources-and-sinks)).

### 10.3 Grants

Grants use the same shape as `permissions`. They are given per node
(`grants:` in a pipeline file), or for a whole run by the invoker (CLI
`--grant`, or explicit trusted mode). A required permission is satisfied
when:

- `subprocess` — it is granted `true`;
- `network`, `environment`, `secrets`, `remoteData` — the exact entry is
  granted (no wildcards in v0.1);
- `filesystem` — a granted path equals the required path or is a directory
  containing it, after both are made absolute and symbolic links resolved.

**Composite children cannot exceed their parent's grants.** The grants
available inside a composite pipe are those granted to the node that
instantiates it; a `grants:` entry inside the composite's pipeline file that
is not covered by them is `E_PERMISSION`. A composite's manifest SHOULD
declare the union of what its children require.

**Trusted mode** grants everything every node declares or implies. It MUST
be explicit (never a default, never inferred from the environment), and a
runner entering it MUST state, on its diagnostics channel, that restrictions
are **not sandbox-enforced**. See section 15.

### 10.4 Secrets and environment

Secrets are not parameters, never appear in manifests, pipeline files,
lockfiles, execution plans, argument vectors, logs or reports, and are
delivered out of band. A pipe names the secrets it needs; the consumer maps
each name to a reference in the runner's secret provider
([Pipeline specification, section 5.3](https://openflange.org/pipeline/v0.1#53-secrets)).

A subprocess receives a **minimal environment**: `PATH`, `HOME`, `LANG`,
`TMPDIR`, the variables named in a granted `environment` list, the literal
`env` of its implementation, the protocol variables of the CLI
specification, and granted secrets. It MUST NOT receive the runner's ambient
environment, database credentials, cloud credentials or any secret that was
not granted to that node.

## 11. Packages and discovery

A **package** is a directory. Its **package root** is that directory. The
rules below are specified in full, together with the index file format, in
the [Package index specification](https://openflange.org/package/v0.1).

1. An `OPENFLANGE.md` at the package root is the package's **default pipe**.
2. Additional pipes live in subdirectories, each with its own
   `OPENFLANGE.md`. Each pipe's manifest paths resolve against its own
   directory but may reach anywhere inside the package root.
3. An optional `openflange.yaml` at the package root lists pipes explicitly.
   When present it is authoritative: `default` names the default pipe and
   `pipes` lists every manifest (or directory containing one). Paths are
   relative to the package root and subject to section 12.
4. Without an index, a tool discovering pipes MUST find every
   `OPENFLANGE.md` under the package root, MUST skip directories named
   `node_modules` and those beginning with `.`, and MUST NOT follow symbolic
   links out of the package root.
5. An npm package MAY instead point at its manifest from `package.json`:
   `"openflange": {"manifest": "path/OPENFLANGE.md"}`. This takes the place
   of rule 1 for that package.

```yaml openflange:package
spec: openflange.org/package/v0.1
default: pipes/normalize-and-mask-email
pipes:
  - pipes/lowercase
  - pipes/mask-email
  - pipes/normalize-and-mask-email
```

Two pipes of one package MUST NOT share an `id` (`E_DUPLICATE`). A reference
to a package without a sub-path selects its default pipe; a reference to a
package with no default and no sub-path is `E_REF`.

## 12. Paths

Every path in a manifest — `implementation.path`, a relative `command[0]`,
`schema.path`, `permissions.filesystem` entries — is a **relative path that
resolves against the directory containing the manifest** and MUST stay
inside the package root. A processor MUST reject with `E_PATH`:

- absolute paths (leading `/` or `\`, or a drive or scheme prefix);
- paths containing a backslash or a NUL character;
- paths whose `..` segments lead outside the package root;
- paths that, after resolving symbolic links, lie outside the package root.

The check MUST be made on the resolved, real path at the time of use, not
only lexically at validation time. `permissions.filesystem` entries that
intentionally name locations outside the package cannot be expressed
relatively; such access is requested through parameters and granted by the
consumer.

## 13. Validation and errors

A processor validates a manifest in this order and SHOULD report every
problem it can find at a stage rather than stopping at the first:

1. **Parse** — file rules (4.1) and safe YAML (4.2): `E_MANIFEST`,
   `E_DUPLICATE`.
2. **Schema** — the manifest schema: `E_MANIFEST`.
3. **Semantics** — attribution (`E_ATTRIBUTION`), paths (`E_PATH`),
   unsupported implementation type, language or required feature
   (`E_UNSUPPORTED`), and the structural rules the schema cannot express
   (`E_MANIFEST`): `expression` port counts, `stdin`/`stdout` naming declared
   ports, `one-to-one` preconditions, `batch` preconditions (5.7), defaults
   satisfying their declaration, `minimum` ≤ `maximum`, `minLength` ≤ `maxLength`, string constraints only
   on string parameters, valid `pattern` expressions.

Errors are structured objects (`code`, `message`, optional `node`, `port`,
`details`); the format and the complete code registry are in the
[Pipeline specification, section 11](https://openflange.org/pipeline/v0.1#11-errors).

## 14. Examples

### 14.1 lowercase

A complete manifest file. It is function-like.

```markdown openflange:manifest
---
spec: openflange.org/pipe/v0.1
id: lowercase
version: 0.1.0
title: Lowercase
description: Lower-cases strings.
license: Apache-2.0
cardinality: one-to-one
deterministic: true
inputs:
  text: {schema: {format: json-schema, definition: {type: string}}}
outputs:
  text: {schema: {format: json-schema, definition: {type: string}}}
implementation:
  type: expression
  language: starlark
  expression: text.lower()
---
# Lowercase

Lower-cases every string it receives.

Implements the [OpenFlange](https://openflange.org/) specification.
```

Both ports are of kind `values` (a scalar JSON Schema type), so the stream
is one JSON string per NDJSON line: `"Alice@Example.COM"` in,
`"alice@example.com"` out.

### 14.2 mask-email

```markdown openflange:manifest
---
spec: openflange.org/pipe/v0.1
id: mask-email
version: 0.1.0
title: Mask email
description: Masks the middle of the local part of an email address.
license: Apache-2.0
inputs:
  email: {schema: {format: json-schema, definition: {type: string}}}
outputs:
  email: {schema: {format: json-schema, definition: {type: string}}}
  rejected:
    kind: records
    required: false
    description: Items that are not valid addresses, as {value, reason}.
    schema:
      format: json-schema
      definition:
        type: object
        required: [value, reason]
        properties:
          reason: {type: string}
parameters:
  character: {type: string, default: "*", minLength: 1, maxLength: 1, description: Exactly one Unicode code point.}
  preserveFirst: {type: integer, default: 1, minimum: 0, maximum: 8}
  preserveLast: {type: integer, default: 1, minimum: 0, maximum: 8}
implementation:
  type: script
  language: starlark
  path: mask.star
---
# Mask email

Masks the local part of an email address, keeping the first and last
characters: `alice@example.com` becomes `a***e@example.com`.

**Masking is not anonymisation.** The domain and the edge characters are
preserved and can still identify a person.

Implements the [OpenFlange](https://openflange.org/) specification.
```

Semantics (operating on Unicode code points):

- The address is split at the last `@`. It is valid when it is a string with
  exactly one `@`, a non-empty local part, a non-empty domain and no
  whitespace.
- An invalid item is **not masked**. It is emitted on `rejected` as
  `{"value": <input>, "reason": "<text>"}`. If `rejected` is not connected,
  the item fails the run with `E_RUNTIME`; it is never dropped.
- With local-part length L, `preserveFirst` f and `preserveLast` l: if
  L > f + l the result is the first f characters, L − f − l copies of
  `character`, and the last l characters. If L ≤ f + l the whole local part
  is replaced by L copies of `character`, so a short local part is never
  revealed entirely. `ab@x.io` becomes `**@x.io`.
- The domain is unchanged. `ünïcödé@example.com` becomes
  `ü*****é@example.com`.
- `character` must be exactly one code point; the manifest declares this
  as `minLength: 1, maxLength: 1`, so `"**"` and `""` are rejected with
  `E_PARAM` before the run starts.

The pipe is not `one-to-one`: an input item can go to `rejected`.

### 14.3 A composite pipe

```markdown openflange:manifest
---
spec: openflange.org/pipe/v0.1
id: normalize-and-mask-email
version: 0.1.0
inputs:
  email:
    schema:
      format: json-schema
      definition: {type: string}
outputs:
  email:
    schema:
      format: json-schema
      definition: {type: string}
implementation:
  type: pipeline
  path: pipeline.yaml
---
# Normalize and mask email

Implements the [OpenFlange](https://openflange.org/) specification.
```

The referenced `pipeline.yaml` is shown in the
[Pipeline specification, section 13](https://openflange.org/pipeline/v0.1#13-examples).

### 14.4 A multi-port executable

`validate-email` has two inputs and three outputs, two of them optional. It
is the interoperability fixture used by the CLI and HTTP specifications.

```yaml openflange:pipe
spec: openflange.org/pipe/v0.1
id: validate-email
version: 0.1.0
title: Validate email
description: Splits records into valid and rejected by their email member.
license: Apache-2.0
inputs:
  records: {kind: records}
  lookup: {kind: records, required: false, description: Optional domain block-list.}
outputs:
  valid: {kind: records}
  rejected: {kind: records, description: "Invalid records as {record, reason}."}
  stats: {kind: records, required: false, description: One summary record at end of stream.}
implementation:
  type: executable
  command: ["./bin/validate-email"]
  stdin: records
  stdout: valid
permissions:
  subprocess: true
```

### 14.5 An R summary through ordinary Unix pipes

A `dataset`-scope pipe implemented by an R script that reads NDJSON on
stdin and writes NDJSON on stdout. Nothing about the script is OpenFlange
specific; the manifest only describes it.

```yaml openflange:pipe
spec: openflange.org/pipe/v0.1
id: r-summary
version: 0.1.0
title: R summary
description: Count, mean, median and standard deviation of the `value` member.
license: Apache-2.0
scope: dataset
inputs:
  records:
    schema:
      format: json-schema
      definition:
        type: object
        required: [value]
        properties:
          value: {type: number}
outputs:
  summary:
    schema:
      format: json-schema
      definition:
        type: object
        required: [count, mean, median, sd]
implementation:
  type: script
  language: r
  path: summary.R
permissions:
  subprocess: true
```

```r
# summary.R (requires jsonlite; dataset scope)
library(jsonlite)
con <- file("stdin", open="r")
records <- stream_in(con, verbose=FALSE)
close(con)
x <- records$value
result <- data.frame(count=length(x), mean=mean(x), median=median(x), sd=sd(x))
stream_out(result, stdout(), verbose=FALSE)
```

The same script runs without any runner:

```sh
printf '%s\n' '{"value":10}' '{"value":20}' '{"value":30}' | Rscript --vanilla summary.R
# {"count":3,"mean":20,"median":20,"sd":10}
```

A production version handles empty input and missing or non-numeric values
deliberately (the snippet above does not).

### 14.6 Invalid manifests

No ports at all:

```yaml openflange:pipe invalid
spec: openflange.org/pipe/v0.1
id: nothing
version: 0.1.0
implementation: {type: builtin, name: "builtin:example/nothing"}
```

An unknown top-level key (not an `x-` extension):

```yaml openflange:pipe invalid
spec: openflange.org/pipe/v0.1
id: lowercase
version: 0.1.0
owner: data-team
inputs: {text: {}}
outputs: {text: {}}
implementation: {type: expression, language: starlark, expression: text.lower()}
```

The same information as a valid extension:

```yaml openflange:pipe
spec: openflange.org/pipe/v0.1
id: lowercase
version: 0.1.0
x-acme-owner: data-team
inputs: {text: {}}
outputs: {text: {}}
implementation: {type: expression, language: starlark, expression: text.lower()}
```

### 14.7 A batch-mode pipe

A function-like pipe whose script receives slices of up to 100 addresses.
The output is the same for every slicing.

```markdown openflange:manifest
---
spec: openflange.org/pipe/v0.1
id: domain-of
version: 0.1.0
title: Domain of
description: Extracts the domain of an email address.
license: Apache-2.0
cardinality: one-to-one
deterministic: true
batch:
  maxItems: 100
  maxWaitMs: 50
inputs:
  email: {schema: {format: json-schema, definition: {type: string}}}
outputs:
  domain: {schema: {format: json-schema, definition: {type: string}}}
implementation:
  type: script
  language: starlark
  path: domain.star
---
# Domain of

Implements the [OpenFlange](https://openflange.org/) specification.
```

```python
# domain.star
def process_batch(items, params):
    return [e.rpartition("@")[2] for e in items]
```

Invalid — batch mode on a pipe with two inputs (`E_MANIFEST`):

```yaml openflange:pipe invalid
spec: openflange.org/pipe/v0.1
id: join-batch
version: 0.1.0
batch: {maxItems: 10}
inputs: {left: {}, right: {}}
outputs: {out: {}}
implementation: {type: executable, command: ["join-records"]}
```

## 15. Security considerations

A manifest, and everything it points to, is untrusted input until a consumer
decides otherwise.

- **Malicious manifests.** Safe YAML parsing (4.2) is mandatory: size limit,
  no aliases, no custom tags, no duplicate keys. Schema validation happens
  before any path is opened or any code is loaded. Inline schemas MUST NOT
  trigger network fetches. Documentation in the body is never executed.
- **Path traversal.** Section 12 is mandatory and applies to the resolved
  real path at time of use; symbolic links inside a package MUST NOT be a way
  out of it.
- **Permissions: enforce or refuse.** A runner MUST refuse to run a node
  whose required permissions are not granted, and MUST NOT claim to enforce a
  restriction it cannot enforce. Declarations are also documentation for the
  human who grants; they are not proof of what the code does.
- **A subprocess is not a sandbox.** Running an executable as a child
  process with a minimal environment limits accidental leakage; it does not
  stop the process from opening files or sockets with the user's authority.
  Runners that cannot isolate (namespaces, containers, VMs, WASM) MUST say so
  and MUST treat a `subprocess` grant as "this code runs with my authority".
  Untrusted code needs real isolation, which is outside v0.1.
- **Trusted mode is honest.** Explicit trusted mode exists for code the
  consumer has decided to trust. It MUST be explicit, MUST announce that
  restrictions are not sandbox-enforced, and MUST NOT be described as a
  security feature.
- **Secret leakage.** Secrets are separate from parameters, are delivered out
  of band, and MUST NOT appear in manifests, plans, argument vectors, logs,
  error messages or reports. Subprocesses never inherit ambient secrets or
  database credentials (10.4).
- **Remote data transmission.** `remoteData` makes "record data leaves this
  machine" a distinct, grantable fact. `http` implementations imply it.
- **Package lifecycle scripts.** Installing a package MUST NOT execute code
  from it (npm installs use `--ignore-scripts`; see the
  [Lockfile specification](https://openflange.org/lock/v0.1)).
- **SSRF and redirects.** Fetching manifests, schemas or remote definitions
  follows the bounded-fetch rules of the
  [Pipeline specification, section 12](https://openflange.org/pipeline/v0.1#12-security-considerations).
- **Batch mode and resources.** A batch-mode node holds at most
  2 × `maxItems` items (one slice in flight, one accumulating) and adds at
  most `maxWaitMs` of latency; both are bounded by the schema and may be
  tightened by the consumer. A runner MAY refuse (`E_RESOURCE`) settings
  beyond a configured limit. Batch mode grants no permission: a pipe that
  sends slices to a remote service still declares `network` and
  `remoteData`.
- **Batch files.** With `delivery: file` the runner writes record data to
  files in a directory it creates for the node (CLI specification, section
  5.2). Reading and writing *that directory* needs no `filesystem`
  permission: the grant is implicit in the protocol and limited to the
  directory. It is not a sandbox — a subprocess can open any file its user
  can — and it does not replace the `subprocess` grant. Placeholders are
  substituted with runner-generated paths only; record data and parameters
  are never substituted into a command.
- **Resource exhaustion.** Starlark execution SHOULD be step-bounded;
  manifests are size-bounded; stateful pipes declare their bounds and fail
  with `E_RESOURCE` rather than grow without limit.
- **`deterministic` is a claim.** Hosts relying on it SHOULD restrict
  themselves to in-process implementations without permissions (5.4).

## 16. Compatibility and versioning

- This specification is identified by `openflange.org/pipe/v0.1`; its
  document version is 0.1.0-draft. The identifier names the major.minor
  contract; a manifest states it in `spec`.
- While the status is `experimental`, a later 0.x version MAY make
  incompatible changes; each is listed in `CHANGELOG.md`. `proposed`
  features may change without notice.
- Schema files are immutable per version: `pipe-v0.1.schema.json` will only
  change to fix defects against this text.
- Unknown top-level keys are rejected, so new standard keys are a
  spec-version change; `x-` keys are the forward-compatible escape hatch;
  `requires` is how a manifest demands behaviour.
- A pipe's own `version` follows SemVer with respect to its contract:
  removing or renaming a port or parameter, tightening an input schema,
  loosening an output schema, making a port required or changing documented
  behaviour is a breaking change.
- Error codes are append-only.

The repository-wide policy is `COMPATIBILITY.md` in the specification repository.

## 17. Deferred

Explicitly not part of v0.1:

- WebAssembly (`wasm`) implementations and browser execution;
- dynamic ports (ports created by parameters or at run time) — ports are
  static;
- variadic inputs for non-builtin implementations; multi-input Starlark
  scripts and expressions;
- a **minimum batch size** (`minItems`) for batch mode, batch mode for
  pipes with several inputs, batch mode for `builtin` implementations and
  over the HTTP Pipe Protocol, batch files in CSV, Arrow or Parquet,
  several slices in flight at once (parallel workers), and batched
  invocation of function-like pipes by hosts (RFC 0003);
- richer parameter constraints (nested schemas for `array` and `object`
  parameters, formats, cross-parameter rules);
- sandboxing profiles and isolation requirements for untrusted code;
- stream reconnect and resume; checkpointing and recovery;
- event-time watermarks and session windows (see RFC 0001);
- distributed scheduling and multi-runner execution;
- separately versioned language bindings (R, Python, Node SDK conventions
  beyond the CLI protocol).
