# Peios Specifications

> Common data structures, platform standards, and kernel and userspace protocol contracts.

---

# 1.1 Scope

_Peios Specifications / PCDS / Introduction_

> What PCDS defines — GUID, LUID, SID, the Security Descriptor family, the sealed secret and the key file — and what it deliberately leaves to the Peios Kernel TRM.

This document defines the common binary data structures shared across
Peios subsystems: three identifier types — the Globally Unique
Identifier (GUID), the Locally Unique Identifier (LUID), and the
Security Identifier (SID) — the Security Descriptor (SD) family, the
passphrase-sealed secret, and the key file.

This document covers:

- GUID — binary format, string representation, comparison semantics,
  and generation requirements
- LUID — binary format, comparison semantics, and allocation model
- SID — binary format, string representation, comparison
  semantics, and the well-known SID catalog
- SD — the security descriptor structure and its subtypes: ACL and
  ACE formats, access masks, ACE ordering, inheritance, ownership,
  conditional ACEs and their bytecode, claim attributes, and
  resource attributes
- Sealed secret — the `PEIOSEAL` binary format, how a secret is sealed
  under a passphrase and opened, and how a passphrase's text becomes
  bytes
- Key file — the `PEIOSKEY` binary format, which holds a key pair with
  its private key sealed or kept under access control, the key
  algorithms it can hold, and how it is read

This document does not cover:

- Well-known GUID and LUID values — defined in the specifications
  of the subsystems that declare them
- SID-bearing aggregate structures such as SID_AND_ATTRIBUTES —
  described in the Peios Kernel TRM §3.2.2
- The access-check algorithm that evaluates these structures —
  described in the Peios Kernel TRM §3.8
- Per-object-type SD storage locations — described in the Peios
  Kernel TRM §3.3.3 for processes and §3.9.5 for files
- Application-specific identifier namespaces
- What a sealed secret holds, and the file formats other than the key
  file that carry one, such as PSO's — defined by the programs that use
  them

Three of those exclusions point at a manual rather than at another
specification, which is deliberate and worth stating once. KACS — the
kernel's access-control implementation — is described in the Peios
Kernel TRM §3 and is not separately specified. Peios does not offer a
standard from which a second, independent access-control implementation
could be built; it offers a manual describing the one that exists.

What a third party does need is the other half: the structures that
cross the boundary into that implementation, and the rules for reading
and writing them. That is this document, and it is specified. Where a
structure's meaning depends on what KACS does with it, this document
names the manual article that describes the behavior rather than
restating it (Conventions §4.7).

---

# 1.2 Conventions

_Peios Specifications / PCDS / Introduction_

> The normative keywords PCDS uses, and the shared conventions it inherits from the PCSA conventions book.

The key words MUST, MUST NOT, SHOULD, SHOULD NOT, and MAY in this
document are to be interpreted as described in RFC 2119. Text set off as
a note is informative, not normative.

Everything else — roles, byte order, sizes, layout tables, notation,
strings, timestamps, citation, and the external standards this anthology
depends on — is defined in the Conventions book and is not restated
here. PCDS departs from none of it.

Where a chapter needs a convention of its own, that chapter states it.

---

# 2.1 Binary Format

_Peios Specifications / PCDS / GUID_

> The 128-bit GUID — its four-field binary layout, byte order, and the nil GUID sentinel.

A GUID (Globally Unique Identifier) is a 128-bit identifier with
global uniqueness guarantees, used to identify registry hives,
layers, object types, and other entities that require stable
identity across systems and reboots. The GUID with all 128 bits set
to zero is the **nil GUID**, a sentinel value meaning "no GUID" or
"unset."

A GUID is a 128-bit (16-byte) value with the following binary layout:

| Offset | Size | Field | Type |
|--------|------|-------|------|
| 0 | 4 | Data1 | uint32, little-endian |
| 4 | 2 | Data2 | uint16, little-endian |
| 6 | 2 | Data3 | uint16, little-endian |
| 8 | 8 | Data4 | uint8[8] |

The total size of a GUID MUST be exactly 16 bytes with no
padding.

Data1, Data2, and Data3 MUST be stored in little-endian byte
order.

Data4 is a raw byte array with no endianness interpretation.

> [!NOTE]
> This is the mixed-endian layout inherited from DCE RPC and
> MS-DTYP. The first three fields follow the platform's native byte
> order (little-endian on x86), while Data4 is a byte sequence with
> no integer interpretation.

## 2.1.1 Nil GUID

The nil GUID is the GUID with all 16 bytes set to zero.

The nil GUID is a valid GUID value. Specifications that require a
non-nil GUID MUST state this requirement explicitly.

The nil GUID MUST NOT be produced by the generation algorithm
defined in §2.4.

---

# 2.2 String Format

_Peios Specifications / PCDS / GUID_

> The braced 8-4-4-4-12 hex form of a GUID, its exact 38-character length, lowercase output, and case-insensitive parsing.

## 2.2.1 Canonical form

The canonical string representation of a GUID MUST use the following
format:

```
{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
```

The string MUST be exactly 38 characters: an opening brace, 32 hex
digits arranged in 8-4-4-4-12 groups separated by hyphens, and a
closing brace.

The fields map to the string as follows:

| Group | Digits | Source |
|-------|--------|--------|
| 1 | 8 | Data1, most significant nibble first |
| 2 | 4 | Data2, most significant nibble first |
| 3 | 4 | Data3, most significant nibble first |
| 4 | 4 | Data4[0] and Data4[1], in byte order |
| 5 | 12 | Data4[2] through Data4[7], in byte order |

For Data1, Data2, and Data3, the hex representation is of the
numeric value (most significant nibble first), not of the stored
byte order. For Data4, each byte is encoded in sequence with the
high nibble before the low nibble.

> [!NOTE]
> Example. Given the 16 bytes (in storage order):
>
> ```
> 04 03 02 01  06 05  08 07  09 0a  0b 0c 0d 0e 0f 10
> ```
>
> Data1 = 0x01020304 (little-endian), Data2 = 0x0506, Data3 = 0x0708.
> The string representation is:
>
> ```
> {01020304-0506-0708-090a-0b0c0d0e0f10}
> ```

## 2.2.2 Case

Canonical output MUST use lowercase hex digits (`a`–`f`).

## 2.2.3 Parsing

Parsers MUST accept both uppercase and lowercase hex digits.

Parsers MUST accept the braced form `{...}` and SHOULD accept the
unbraced form `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`.

Parsers MUST reject strings that do not have exactly the right
number of hex digits in each group.

---

# 2.3 Comparison

_Peios Specifications / PCDS / GUID_

> GUID equality is byte-for-byte on the binary form; no total ordering is defined, and a specification that needs one must define its own.

## 2.3.1 Equality

Two GUIDs are equal if and only if their 16-byte binary
representations are identical.

GUID comparison MUST be performed on the binary representation,
not on string representations.

> [!NOTE]
> Byte-for-byte comparison of the binary form avoids case
> sensitivity and brace-presence issues that would arise from
> comparing string representations.

## 2.3.2 Ordering

This document does not define a total ordering for GUIDs.
Specifications that require an ordered GUID collection MUST define
their ordering convention explicitly.

---

# 2.4 Generation

_Peios Specifications / PCDS / GUID_

> Peios GUIDs are RFC 4122 version 4 — filled from a cryptographic random source, with the version and variant bits fixed afterwards.

GUIDs generated by Peios MUST be version 4 (random) as defined in
RFC 4122 §4.4.

## 2.4.1 Algorithm

To generate a version 4 GUID:

1. Fill all 16 bytes with cryptographically random data.
2. Set the four most significant bits of Data3 to `0100`
   (version 4).
3. Set the two most significant bits of Data4[0] to `10`
   (RFC 4122 variant).

The resulting GUID has 122 random bits, 4 version bits, and
2 variant bits.

> [!NOTE]
> In terms of bit manipulation on the binary layout:
>
> ```
> Data3 = (Data3 & 0x0fff) | 0x4000
> Data4[0] = (Data4[0] & 0x3f) | 0x80
> ```

## 2.4.2 Randomness source

The random data MUST be obtained from a cryptographically secure
source.

In the kernel, this MUST be `get_random_bytes()` or equivalent.

In userspace, this MUST be `getrandom(2)` with no flags (blocking
until the entropy pool is initialized) or equivalent.

GUIDs MUST NOT be generated using a pseudorandom number generator
seeded from a predictable source.

---

# Appendix 2.A Prior Art

_Peios Specifications / PCDS / GUID_

> Where the Peios GUID comes from — MS-DTYP §2.3.4, RFC 4122 and DCE RPC — and the one place Peios normalizes differently.

## 2.A.1 MS-DTYP

The GUID type defined in this document derives from the Microsoft
Data Types specification (MS-DTYP), §2.3.4. The Peios GUID binary
format is identical to the MS-DTYP GUID. The Peios GUID string
format follows the same hyphenated hex convention but normalizes to
lowercase hex digits on output, where Microsoft implementations
typically produce uppercase.

## 2.A.2 RFC 4122

RFC 4122 ("A Universally Unique IDentifier (UUID) URN Namespace")
defines the UUID format and generation algorithms. The GUID
binary layout used by Microsoft and adopted by Peios is the
mixed-endian variant of the RFC 4122 UUID: the first three fields
are little-endian integers and the last field is a raw byte array.
This differs from the RFC 4122 network byte order representation
where all fields are big-endian.

Peios generates version 4 (random) GUIDs as defined in RFC 4122 §4.4.

## 2.A.3 DCE RPC

The GUID structure originates from the DCE 1.1 RPC specification,
which defined the `uuid_t` type with the same field layout. The
mixed-endian encoding reflects the DCE convention of encoding integer
fields in the sender's native byte order (little-endian on x86).

---

# 3.1 Binary Format

_Peios Specifications / PCDS / LUID_

> The 64-bit LUID — LowPart and HighPart, its boot-scoped uniqueness, and the nil LUID.

An LUID (Locally Unique Identifier) is a 64-bit identifier with
boot-scoped local uniqueness, used to identify transient entities
such as logon sessions and privilege instances that do not persist
across reboots. The LUID with all 64 bits set to zero is the
**nil LUID**, a sentinel value meaning "no LUID" or "unset."

An LUID is a 64-bit (8-byte) value with the following binary layout:

| Offset | Size | Field | Type |
|--------|------|-------|------|
| 0 | 4 | LowPart | uint32, little-endian |
| 4 | 4 | HighPart | uint32, little-endian |

The total size of an LUID MUST be exactly 8 bytes with no
padding.

Both fields MUST be stored in little-endian byte order.

> [!NOTE]
> MS-DTYP defines HighPart as a signed 32-bit integer (LONG). Peios
> uses unsigned uint32 for both fields. The signed type in MS-DTYP
> is a Win32 API convention with no semantic purpose — LUID values
> are never negative. See §3.A for the full divergence rationale.

## 3.1.1 Nil LUID

The nil LUID is the LUID with all 8 bytes set to zero
(LowPart = 0, HighPart = 0).

The nil LUID is a valid LUID value. The nil LUID MUST NOT be
assigned by the allocation algorithm defined in §3.3.

Specifications that require a non-nil LUID MUST state this
requirement explicitly.

---

# 3.2 Comparison

_Peios Specifications / PCDS / LUID_

> LUID equality compares both halves, and monotonic allocation within a boot must not be read as a temporal ordering across sources.

## 3.2.1 Equality

Two LUIDs are equal if and only if both their LowPart and HighPart
fields are identical.

## 3.2.2 Ordering

This document does not define a total ordering for LUIDs.
Although LUIDs are allocated monotonically within a boot session
(see §3.3), consumers MUST NOT rely on numeric ordering to infer
temporal relationships between LUIDs obtained from different
contexts.

---

# 3.3 Allocation

_Peios Specifications / PCDS / LUID_

> LUIDs are kernel-allocated, unique within a boot session, strictly monotonic, and never fabricated by userspace.

LUIDs MUST be allocated by the kernel.

## 3.3.1 Uniqueness scope

Each LUID MUST be unique within a single boot session.

LUID values MUST NOT be assumed unique across reboots. A value
allocated in one boot session MAY be reused in a subsequent boot
session.

## 3.3.2 Monotonicity

The kernel MUST allocate LUIDs in strictly monotonically increasing
order within a boot session, treating the two fields as a single
unsigned 64-bit integer (HighPart << 32 | LowPart).

The starting value of the allocation sequence after each boot is
implementation-defined.

> [!NOTE]
> Subsystems that define well-known LUID values (such as privilege
> identifiers) typically reserve values below the allocation starting
> point. The starting value should be chosen to leave room for
> current and future well-known values.

## 3.3.3 Fabrication prohibition

Userspace code MUST NOT fabricate LUID values. All LUIDs MUST be
obtained through the kernel allocation interface or from well-known
constants defined in a Peios specification.

---

# Appendix 3.A Prior Art

_Peios Specifications / PCDS / LUID_

> The LUID derives from MS-DTYP §2.3.7, diverging in one detail — HighPart is unsigned where MS-DTYP has it signed.

## 3.A.1 MS-DTYP

The LUID type defined in this document derives from the Microsoft
Data Types specification (MS-DTYP), §2.3.7.

The Peios LUID binary format diverges from MS-DTYP in one detail:
HighPart is an unsigned 32-bit integer (uint32) rather than the
signed 32-bit integer (LONG) used in MS-DTYP. The signed type in
MS-DTYP is a Win32 API convention with no semantic purpose — LUID
values are never negative. Making the field unsigned simplifies
comparison and eliminates a class of sign-extension bugs.

---

# 4.1 Binary Format

_Peios Specifications / PCDS / SID_

> The variable-length SID — revision, identifier authority, and up to fifteen sub-authorities, with the size limits that bound it.

A SID (Security Identifier) is a variable-length binary value that
uniquely identifies a principal — a user, group, service, machine, or
well-known entity. SIDs are the fundamental identity primitive of the
Peios security model: they appear in tokens as identity, in security
descriptors as access rules, and as references throughout the system.

A SID is encoded as a contiguous binary structure with the following
layout:

| Offset | Size | Field | Description |
|---|---|---|---|
| 0 | 1 | Revision | MUST be 1. |
| 1 | 1 | SubAuthorityCount | Number of sub-authorities. MUST be between 0 and 15 inclusive. |
| 2 | 6 | IdentifierAuthority | A 6-byte big-endian value identifying the authority that issued the SID. |
| 8 | 4 × SubAuthorityCount | SubAuthority[] | Array of 32-bit unsigned integers in little-endian byte order. |

The total size of a SID in bytes is `8 + (4 × SubAuthorityCount)`.
The minimum size is 8 bytes (zero sub-authorities). The maximum size
is 68 bytes (15 sub-authorities).

The last sub-authority in a SID is the **Relative Identifier (RID)**
— the portion that distinguishes individual principals within a
domain.

> [!NOTE]
> The IdentifierAuthority is the one big-endian field among the
> structures in this document — an MS-DTYP inheritance. The
> sub-authorities that follow it are ordinary little-endian integers.

---

# 4.2 String Format

_Peios Specifications / PCDS / SID_

> The S-R-I-S string form of a SID — how each component is rendered, and the rules for parsing one back.

SIDs are represented in string form as:

```
S-1-{authority}-{sub1}-{sub2}-...-{subN}
```

Where:

- `S` is a literal prefix.
- `1` is the revision number.
- `{authority}` is the IdentifierAuthority. If the upper 2 bytes are
  zero, this is the decimal representation of the lower 4 bytes.
  Otherwise, it is the lowercase hexadecimal representation of all
  6 bytes, zero-padded to 12 hex digits and prefixed with `0x`.
- Each `{subN}` is the decimal representation of the corresponding
  32-bit sub-authority.

> [!NOTE]
> Example SIDs: `S-1-5-18` (Local System), `S-1-5-32-544`
> (BUILTIN\Administrators),
> `S-1-5-21-3623811015-3361044348-30300820-1013` (a domain user).
> The meanings of well-known SID values are cataloged in §4.4.

---

# 4.3 Comparison

_Peios Specifications / PCDS / SID_

> SID equality is an exact binary match — no case folding, no normalization, no equivalence relation — and no total ordering is defined.

## 4.3.1 Equality

Two SIDs are equal if and only if their binary representations are
byte-for-byte identical.

SID comparison MUST be performed on the binary encoding, not the
string form. There is no case sensitivity, normalization, or
equivalence relation — equality is exact binary match.

## 4.3.2 Ordering

This document does not define a total ordering for SIDs.
Specifications that require an ordered SID collection MUST define
their ordering convention explicitly.

---

# 4.4 Well-Known SIDs

_Peios Specifications / PCDS / SID_

> The fixed SIDs every implementation must recognize — universal and creator authorities, NT Authority, BUILTIN, integrity and trust labels, confinement and capability SIDs.

The following SIDs have fixed values and well-defined meanings. An
implementation MUST recognize these SIDs and apply their defined
semantics wherever they are referenced. The access-check behavior
attached to them is described in the Peios Kernel TRM §3.8.

## 4.4.1 Universal authorities

| SID | Name | Description |
|---|---|---|
| S-1-0-0 | Nobody | The null SID. No principal. |
| S-1-1-0 | Everyone | Matches all principals, including anonymous. |
| S-1-2-0 | Local | Principals that log on locally (physically). |
| S-1-2-1 | Console Logon | Principals that log on via the physical console. |

## 4.4.2 Creator authorities

| SID | Name | Description |
|---|---|---|
| S-1-3-0 | Creator Owner | Placeholder in inheritable ACEs. Replaced with the creating principal's SID during inheritance. |
| S-1-3-1 | Creator Group | Placeholder in inheritable ACEs. Replaced with the creating principal's primary group SID during inheritance. |
| S-1-3-4 | Owner Rights | When present in a DACL, overrides the owner's implicit READ_CONTROL and WRITE_DAC grants. AccessCheck treats this SID as matching the object's owner. |

## 4.4.3 NT Authority (S-1-5)

| SID | Name | Description |
|---|---|---|
| S-1-5-2 | Network | Principals that authenticated over the network. |
| S-1-5-3 | Batch | Principals that logged on to run a scheduled job. |
| S-1-5-4 | Interactive | Principals that logged on interactively. |
| S-1-5-6 | Service | Principals that authenticated as a service. |
| S-1-5-7 | Anonymous | The anonymous identity. Carried by tokens at Anonymous impersonation level. |
| S-1-5-10 | Principal Self | Placeholder in ACEs on directory objects. Matches the caller when the caller's identity corresponds to the object's associated principal. Resolved via the `self_sid` parameter to AccessCheck. |
| S-1-5-11 | Authenticated Users | All principals that have been authenticated (excludes Anonymous). |
| S-1-5-14 | Remote Interactive | Principals that logged on interactively to a remote graphical desktop. Carried in addition to Interactive, never in place of it. |
| S-1-5-18 | Local System (SYSTEM) | The operating system's own identity. Highest privilege level. |
| S-1-5-19 | Local Service | A built-in service account with reduced privileges. |
| S-1-5-20 | Network Service | A built-in service account that can authenticate to remote services. |

## 4.4.4 Logon SIDs

| SID | Name | Description |
|---|---|---|
| S-1-5-5-*X*-*Y* | Logon SID | A per-authentication-event SID generated at LogonSession creation. *X* and *Y* are unique values. Injected into the token's groups with SE_GROUP_LOGON_ID. |

## 4.4.5 BUILTIN domain (S-1-5-32)

| SID | Name | Description |
|---|---|---|
| S-1-5-32-544 | BUILTIN\Administrators | The built-in administrators group. |
| S-1-5-32-545 | BUILTIN\Users | The built-in users group. |
| S-1-5-32-546 | BUILTIN\Guests | The built-in guests group. |
| S-1-5-32-551 | BUILTIN\Backup Operators | Members can bypass file security for backup and restore. |

> [!NOTE]
> Additional BUILTIN SIDs (S-1-5-32-547 through S-1-5-32-583) are
> defined by Active Directory. KACS does not assign special semantics
> to these SIDs — they participate in normal ACE matching like any
> other group SID. Their meaning is an administrative convention, not
> a kernel enforcement property.

## 4.4.6 Domain SIDs (S-1-5-21)

Domain-specific SIDs follow the pattern
`S-1-5-21-{DA1}-{DA2}-{DA3}-{RID}`, where the three domain authority
sub-authorities identify the domain and the RID identifies the
principal within that domain.

| RID | Name | Description |
|---|---|---|
| 500 | Domain Administrator | The built-in administrator account. |
| 501 | Domain Guest | The built-in guest account. |
| 512 | Domain Admins | The domain administrators group. |
| 513 | Domain Users | The domain users group. |
| 514 | Domain Guests | The domain guests group. |
| 515 | Domain Computers | Computer accounts in the domain. |

> [!NOTE]
> Domain SIDs are assigned by the domain controller and replicated
> through Active Directory. KACS does not create or manage domain
> SIDs — it evaluates them as opaque binary values during
> AccessCheck.

## 4.4.7 Mandatory integrity labels (S-1-16)

| SID | Name | Numeric level | Description |
|---|---|---|---|
| S-1-16-0 | Untrusted | 0 | Lowest trust. Sandboxed or experimental code. |
| S-1-16-4096 | Low | 4096 | Reduced trust. Services handling untrusted input. |
| S-1-16-8192 | Medium | 8192 | Standard trust. Default for interactive logons and most services. |
| S-1-16-12288 | High | 12288 | Elevated administrative logons. |
| S-1-16-16384 | System | 16384 | The kernel, peinit, and TCB services. |

The five levels above are the standard, well-known integrity levels;
in practice they behave like an enum. Technically the level is the
SID's single sub-authority as an unsigned integer: any `S-1-16-<n>`
with exactly one sub-authority is a valid level, and MIC compares
levels numerically. Non-standard values occur in Windows-interop SDs
— e.g. `S-1-16-8448` (medium-plus) or `S-1-16-20480` (protected). A
mandatory-label SID with a different identifier authority or more
than one sub-authority is malformed and rejected. The standard order
is System > High > Medium > Low > Untrusted.

## 4.4.8 Process trust labels (S-1-19)

| SID | Name | Description |
|---|---|---|
| S-1-19-0-0 | None / No trust | Default for unsigned processes. |
| S-1-19-512-1024 | Protected, Authenticode | Third-party signed binaries. |
| S-1-19-512-1536 | Protected, AntiMalware | Security tooling. |
| S-1-19-512-2048 | Protected, App | Peios-distributed applications. |
| S-1-19-512-4096 | Protected, Peios | Core Peios components. |
| S-1-19-512-8192 | Protected, PeiosTcb | Peios Trusted Computing Base. |
| S-1-19-1024-8192 | Isolated, PeiosTcb | Maximum isolation and trust. |

Trust labels encode two dimensions in the SID: the first
sub-authority is the PIP type axis and the second is the trust axis
(higher = more trusted). Dominance requires both dimensions to be
greater than or equal.

KACS currently standardizes these PIP type values:

- `0` = None
- `512` = Protected
- `1024` = Isolated

These values are standardized labels, not a closed enum for
AccessCheck. Other numeric type values remain valid and are compared
numerically by the same dominance rule.

## 4.4.9 Confinement SIDs (S-1-15)

| SID | Name | Description |
|---|---|---|
| S-1-15-2-*hash* | Confinement SID | Identifies a confined application. The sub-authorities are derived from the application identity. |
| S-1-15-2-1 | ALL_APPLICATION_PACKAGES | Matches all confined applications in normal confinement mode. |
| S-1-15-2-2 | ALL_RESTRICTED_APPLICATION_PACKAGES | Matches confined applications in both normal and strict confinement modes. Strict confinement is the mode where ALL_APPLICATION_PACKAGES is omitted from the capabilities. |

## 4.4.10 Capability SIDs (S-1-15-3)

| SID | Name | Description |
|---|---|---|
| S-1-15-3-1 | internetClient | Outbound internet access. |
| S-1-15-3-2 | internetClientServer | Inbound and outbound internet access. |
| S-1-15-3-3 | privateNetworkClientServer | LAN/private network access. |
| S-1-15-3-8 | enterpriseAuthentication | Domain credential access. |
| S-1-15-3-9 | sharedUserCertificates | Certificate store access. |
| S-1-15-3-10 | removableStorage | Removable media access. |

Capability SIDs 4–7 (picturesLibrary, videosLibrary, musicLibrary,
documentsLibrary) are reserved. Their SID values MUST NOT be
redefined.

Derived capabilities use 8 sub-authorities computed from the SHA-256
hash of the capability name:
`S-1-15-3-{h0}-{h1}-{h2}-{h3}-{h4}-{h5}-{h6}-{h7}`. The same name
always produces the same SID.

## 4.4.11 Service SIDs

Service SIDs follow the pattern `SERVICE\{service_name}` (e.g.,
`SERVICE\jellyfin`, `SERVICE\loregd`) and are added as a group in
the service's token. The token's primary user SID is the account the
service runs as (typically SYSTEM, LocalService, or NetworkService);
the service SID enables per-service access control — a file's DACL
can grant access to `SERVICE\jellyfin` specifically, rather than to
the broad account the service runs under.

The SID value is derived from the service name using a SHA-1 hash:
the UTF-16LE encoding of the uppercased service name is hashed, and
the 20-byte digest is split into five little-endian 32-bit
sub-authorities: `S-1-5-80-{h0}-{h1}-{h2}-{h3}-{h4}`. The same
service name always produces the same SID. This matches the Windows
service SID derivation (MS-DTYP compatible).

---

# Appendix 4.A Prior Art

_Peios Specifications / PCDS / SID_

> The SID derives from MS-DTYP §2.4.2, keeping both the packet encoding and the S-R-I-S string convention.

## 4.A.1 MS-DTYP

The SID type defined in this document derives from the Microsoft
Data Types specification (MS-DTYP), §2.4.2. The Peios binary
encoding is identical to the MS-DTYP packet representation, and the
string form follows the same `S-R-I-S` convention. The structure
itself originates in Windows NT, where it has been the principal
identity primitive since NT 3.1.

---

# 5.1 SD Structure

_Peios Specifications / PCDS / Security Descriptor_

> The Security Descriptor — owner, group, DACL and SACL, the self-relative binary layout, the sixteen control flags, and null DACL against empty DACL.

A Security Descriptor (SD) defines the complete security policy for a
protected object. Every protected object in Peios — every file, registry key,
IPC endpoint, service, token, and process — MUST have a Security Descriptor.

An SD has four components and a set of control flags:

- **Owner SID** — the principal that owns the object. The owner has implicit
  rights (READ_CONTROL and WRITE_DAC) unless suppressed by an OWNER RIGHTS
  ACE.

- **Group SID** — an optional primary group associated with the object. When
  present, it is stored and returned on query and used during CREATOR GROUP
  substitution during inheritance. When absent, no primary group is available
  for those metadata operations. No access control decision depends on the
  group SID directly. If an inheritance or ACL-rewrite operation must
  materialize a CREATOR GROUP SID and the source object SD has no group SID,
  KACS MUST fail closed rather than substitute another SID or silently drop
  the ACE.

- **DACL** (Discretionary Access Control List) — an ordered list of ACEs that
  define who is allowed or denied access. The object's owner controls the DACL
  (via WRITE_DAC).

- **SACL** (System Access Control List) — an ordered list of ACEs that define
  system-level policy. Despite the name, the SACL carries several distinct ACE
  types:
  - Audit ACEs — which access attempts to log.
  - Mandatory label ACE — the object's integrity level for MIC.
  - Resource attribute ACEs — name-value attributes for conditional ACE
    evaluation.
  - Scoped policy ID ACEs — references to central access policies.
  - Process trust label ACE — the object's PIP trust level.

  Modifying the SACL requires ACCESS_SYSTEM_SECURITY. ACCESS_SYSTEM_SECURITY
  is privilege-controlled: it is normally granted by SeSecurityPrivilege, and
  may also be granted by restore-intent SeRestorePrivilege in the
  `kacs_set_sd` cases described in the Peios Kernel TRM §3.9.6.

Both the DACL and SACL use the standard binary ACL format defined in §5.2.

## 5.1.1 Binary format

SDs use the self-relative binary format defined in MS-DTYP §2.4.6. The format
is a 20-byte header followed by the owner SID, optional group SID, SACL, and
DACL at offsets specified in the header.

| Offset | Size | Field | Description |
|---|---|---|---|
| 0 | 1 | `Revision` | MUST be 1. |
| 1 | 1 | `Sbz1` | Reserved. Preserved for format compatibility but not interpreted by KACS. When SE_RM_CONTROL_VALID is set in the control flags, this byte carries resource manager control bits defined by the originating system. |
| 2 | 2 | `Control` | Control flags, little-endian. |
| 4 | 4 | `OffsetOwner` | Offset to the owner SID, little-endian. 0 if absent. |
| 8 | 4 | `OffsetGroup` | Offset to the group SID, little-endian. 0 if absent. |
| 12 | 4 | `OffsetSacl` | Offset to the SACL, little-endian. 0 if absent. |
| 16 | 4 | `OffsetDacl` | Offset to the DACL, little-endian. 0 if absent. |

Field names are those of MS-DTYP §2.4.6.

The self-relative format packs everything into a contiguous byte buffer with
no pointers. This makes it suitable for storage (xattrs, database fields) and
wire transmission (IPC, SMB).

KACS MUST use the self-relative format exclusively.

## 5.1.2 Control flags

The SD's 16-bit Control field records metadata about the descriptor:

| Flag | Bit | Value | Description |
|---|---|---|---|
| SE_OWNER_DEFAULTED (OD) | 0 | 0x0001 | The owner was established by default means. |
| SE_GROUP_DEFAULTED (GD) | 1 | 0x0002 | The group was established by default means. |
| SE_DACL_PRESENT (DP) | 2 | 0x0004 | A DACL is present. If clear, AccessCheck treats the DACL as null (grants all access). |
| SE_DACL_DEFAULTED (DD) | 3 | 0x0008 | The DACL was established by default means. |
| SE_SACL_PRESENT (SP) | 4 | 0x0010 | A SACL is present. |
| SE_SACL_DEFAULTED (SD) | 5 | 0x0020 | The SACL was established by default means. |
| SE_DACL_TRUSTED (DT) | 6 | 0x0040 | Reserved metadata. Preserved during round-trip serialization. No operational semantics. |
| SE_SERVER_SECURITY (SS) | 7 | 0x0080 | Create a server ACL based on the input ACL. |
| SE_DACL_AUTO_INHERIT_REQ (AR) | 8 | 0x0100 | Requests that the DACL be auto-inherited from the parent. When clear on a creator SD, parent inheritance is suppressed even if SE_DACL_PROTECTED is not set. |
| SE_SACL_AUTO_INHERIT_REQ | 9 | 0x0200 | Requests that the SACL be auto-inherited from the parent. Same semantics as bit 8 for the SACL. |
| SE_DACL_AUTO_INHERITED (DI) | 10 | 0x0400 | The DACL was created through automatic inheritance. |
| SE_SACL_AUTO_INHERITED (SI) | 11 | 0x0800 | The SACL was created through automatic inheritance. |
| SE_DACL_PROTECTED (PD) | 12 | 0x1000 | The DACL is protected from inheritance. Inheritable ACEs from parent objects MUST NOT be merged. |
| SE_SACL_PROTECTED (PS) | 13 | 0x2000 | The SACL is protected from inheritance. |
| SE_RM_CONTROL_VALID (RM) | 14 | 0x4000 | The Sbz1 byte is interpreted as resource manager control bits. |
| SE_SELF_RELATIVE (SR) | 15 | 0x8000 | The SD is in self-relative format. MUST always be set for stored SDs. |

The architectural maximum SD size is 65,535 bytes. KACS MUST reject any parsed
or computed SD whose serialized self-relative byte length exceeds 65,535
bytes.

The DEFAULTED flags are metadata. During object-SD creation, KACS MUST set the
corresponding DEFAULTED flag when it supplies that component from a default
source rather than from an explicit creator SD component or inherited ACL.
KACS MUST NOT grant or deny access based solely on a DEFAULTED flag.

This document records the `SE_SERVER_SECURITY` flag value but does not
define the server-ACL construction algorithm. An implementation MUST
fail closed when a creator SD attempts to use `SE_SERVER_SECURITY`.

The PROTECTED flags are operationally significant. Setting SE_DACL_PROTECTED
prevents inheritance from parent objects — the object keeps its current ACEs
and stops accepting new inheritable ACEs from above.

## 5.1.3 Null DACL vs empty DACL

The SE_DACL_PRESENT flag distinguishes two states with very different security
consequences:

- **Null DACL** (SE_DACL_PRESENT not set) — no discretionary access control.
  AccessCheck grants all requested access to every caller. This SHOULD almost
  never be used.

- **Empty DACL** (SE_DACL_PRESENT set, zero ACEs) — AccessCheck grants no
  access to any caller (except the owner's implicit rights). An explicit
  statement that no principal has discretionary access.

Objects SHOULD always have a DACL. This is a preferred-object-shape
recommendation, not a fail-closed requirement. If object creation has no
explicit DACL, no inherited DACL, and the creator token has no default DACL,
the resulting object SD has a null DACL: SE_DACL_PRESENT is clear and the DACL
offset is zero.

---

# 5.2 ACL Format

_Peios Specifications / PCDS / Security Descriptor_

> The 8-byte ACL header and the contiguous ACE array it introduces, with the rules for parsing a self-delimiting ACE sequence.

An Access Control List (ACL) is the binary container for ACEs. DACLs, SACLs,
and CAAP policy ACL blobs all use the same standard binary ACL format.

## 5.2.1 Binary format

An ACL begins with an 8-byte header followed by `AceCount` ACEs packed
contiguously:

| Offset | Size | Field | Description |
|---|---|---|---|
| 0 | 1 | AclRevision | ACL revision number. Determines which ACE families the ACL formally permits. |
| 1 | 1 | Sbz1 | Reserved. Preserved for compatibility but not interpreted by KACS. |
| 2 | 2 | AclSize | Total size of the ACL in bytes, including the 8-byte header. Little-endian. |
| 4 | 2 | AceCount | Number of ACEs in the ACL. Little-endian. |
| 6 | 2 | Sbz2 | Reserved. Preserved for compatibility but not interpreted by KACS. |

The ACE array begins immediately at offset 8. Each ACE is self-delimiting via
its `AceSize` field. The parser walks the ACL by iterating exactly `AceCount`
ACEs within the `AclSize` boundary.

## 5.2.2 Parsing rules

- `AclSize` MUST be at least 8 bytes.
- `AclSize` MUST NOT exceed the containing buffer.
- The ACL body MUST contain exactly `AceCount` ACEs within the declared
  `AclSize`.
- Truncated ACEs, ACE overruns, or leftover bytes within `AclSize` are
  malformed.
- The architectural maximum ACL size is 64 KB because `AclSize` is a 16-bit
  field.

ACE structure, ACE-type definitions, and revision-versus-ACE-family rules are
specified in §5.4.

---

# 5.3 Access Masks

_Peios Specifications / PCDS / Security Descriptor_

> The 32-bit access mask — its object-specific, standard, special and generic right regions, the reserved bits, and generic mapping.

Every ACE carries an access mask — a 32-bit integer where each bit represents
a specific right. The same 32-bit layout is used in three contexts: the ACE's
mask (what the rule grants or denies), the requested access (what the caller
asks for), and the granted access (what AccessCheck returns).

## 5.3.1 Bit layout

The 32 bits are divided into four regions:

### 5.3.1.1 Object-specific rights (bits 0–15)

Defined by the object type. Different object types assign different meanings
to these bits. A file uses bits for read, write, append, execute; a registry
key uses bits for query value, set value, create subkey; a token uses bits for
query, duplicate, impersonate. Each subsystem defines its own mapping.

### 5.3.1.2 Standard rights (bits 16–20)

Common to all object types:

| Bit | Name | Value | Meaning |
|---|---|---|---|
| 16 | DELETE | 0x00010000 | Delete the object. |
| 17 | READ_CONTROL | 0x00020000 | Read the object's SD (excluding SACL). |
| 18 | WRITE_DAC | 0x00040000 | Modify the object's DACL. |
| 19 | WRITE_OWNER | 0x00080000 | Change the object's owner. |
| 20 | SYNCHRONIZE | 0x00100000 | Wait on the object. |

### 5.3.1.3 Special rights (bits 24–25)

| Bit | Name | Value | Meaning |
|---|---|---|---|
| 24 | ACCESS_SYSTEM_SECURITY | 0x01000000 | Read or write the SACL. Requires SeSecurityPrivilege. |
| 25 | MAXIMUM_ALLOWED | 0x02000000 | Not a real right. Request flag that tells AccessCheck to compute and return the maximum set of rights the caller would be granted. MUST NOT appear in an ACE. |

### 5.3.1.4 Generic rights (bits 28–31)

Abstract rights mapped to object-specific rights before evaluation:

| Bit | Name | Value |
|---|---|---|
| 28 | GENERIC_ALL | 0x10000000 |
| 29 | GENERIC_EXECUTE | 0x20000000 |
| 30 | GENERIC_WRITE | 0x40000000 |
| 31 | GENERIC_READ | 0x80000000 |

### 5.3.1.5 Reserved bits

Bits 21–23 and 26–27 are reserved and MUST NOT be used. An access mask
setting any of them is rejected: a desired access mask carrying one
fails the request, and an ACE mask carrying one makes the containing SD
unparseable.

## 5.3.2 Generic mapping

Generic rights exist because SDs need to be portable across object types. A
central access policy might say "allow GENERIC_READ on all objects" — and
GENERIC_READ means different specific bits for files versus registry keys.

Each object type defines a **GenericMapping** table:

| Field | Description |
|---|---|
| `read` | Specific + standard bits that GENERIC_READ maps to. |
| `write` | Specific + standard bits that GENERIC_WRITE maps to. |
| `execute` | Specific + standard bits that GENERIC_EXECUTE maps to. |
| `all` | Specific + standard bits that GENERIC_ALL maps to. |

Generic mapping happens once, at request time. AccessCheck MUST map any
generic bits in the desired mask to object-specific bits using the object
type's GenericMapping table, then clear the generic bits. The DACL walk
operates exclusively on specific and standard bits.

> [!NOTE]
> KACS maps ACE masks via GenericMapping at evaluation time (using a local
  variable — the ACE itself is never mutated). This is an intentional
  divergence: the reference model expects ACE masks to be pre-mapped at SD
  construction time. Defensive mapping at evaluation time handles two cases:
  (1) imported/external SDs that may contain unresolved generic bits, and (2)
  central access policy recovery ACEs that use GENERIC_ALL. Note: SD
  inheritance also maps generic bits on all ACEs when computing a child SD
  (see §5.6), so newly created SDs will not contain generic bits. The
  evaluation-time mapping is defense-in-depth for SDs from other sources.

---

# 5.4 ACE Types

_Peios Specifications / PCDS / Security Descriptor_

> Every ACE type and body layout — the single-SID, object, callback and resource-attribute families, the AceType constants, and the ACL revision rules.

An Access Control Entry (ACE) is a single rule in an ACL. Each ACE has a
header, an access mask, and a principal SID, with optional extensions for
object-type and conditional ACEs.

## 5.4.1 ACE header

Every ACE begins with a 4-byte header:

| Offset | Size | Field | Description |
|---|---|---|---|
| 0 | 1 | AceType | Identifies the ACE type. |
| 1 | 1 | AceFlags | Inheritance and audit flags. |
| 2 | 2 | AceSize | Total size of the ACE in bytes, including the header. MUST be a multiple of 4. |

The size includes trailing padding. Builders zero-pad a variable-length raw
body to the next four-byte boundary, including resource-attribute claims
whose final octet value has an arbitrary length. This padding belongs to the
ACE; it does not increase the claim's declared octet-value length.

## 5.4.2 ACE body layouts

The ACE header is followed by a type-specific body. Every multibyte integer in
the body is little-endian.

### 5.4.2.1 Single-SID ACE family

The following ACE types share the same binary layout:

- `ACCESS_ALLOWED_ACE`
- `ACCESS_DENIED_ACE`
- `SYSTEM_AUDIT_ACE`
- `SYSTEM_ALARM_ACE`
- `SYSTEM_MANDATORY_LABEL_ACE`
- `SYSTEM_SCOPED_POLICY_ID_ACE`
- `SYSTEM_PROCESS_TRUST_LABEL_ACE`

Layout:

| Offset | Size | Field | Description |
|---|---|---|---|
| 0 | 4 | AceHeader | Standard ACE header. |
| 4 | 4 | Mask | Access mask. |
| 8 | variable | Sid | Principal SID. Consumes the remainder of the ACE. |

Parsing rules:

- `AceSize` MUST be at least 16 bytes (header + mask + minimum SID).
- The SID MUST consume the remainder of the ACE exactly.

### 5.4.2.2 Object ACE family

The following ACE types share the object-ACE binary layout:

- `ACCESS_ALLOWED_OBJECT_ACE`
- `ACCESS_DENIED_OBJECT_ACE`
- `SYSTEM_AUDIT_OBJECT_ACE`
- `SYSTEM_ALARM_OBJECT_ACE`

Layout:

| Offset | Size | Field | Description |
|---|---|---|---|
| 0 | 4 | AceHeader | Standard ACE header. |
| 4 | 4 | Mask | Access mask. |
| 8 | 4 | Flags | Bitfield describing which GUIDs are present. |
| 12 | 0 or 16 | ObjectType | Present when `ACE_OBJECT_TYPE_PRESENT` is set. |
| 12 or 28 | 0 or 16 | InheritedObjectType | Present when `ACE_INHERITED_OBJECT_TYPE_PRESENT` is set. |
| variable | variable | Sid | Principal SID. Begins immediately after the optional GUID fields and consumes the remainder of the ACE. |

Object ACE flags:

| Flag | Value | Description |
|---|---|---|
| `ACE_OBJECT_TYPE_PRESENT` | 0x00000001 | `ObjectType` GUID is present. |
| `ACE_INHERITED_OBJECT_TYPE_PRESENT` | 0x00000002 | `InheritedObjectType` GUID is present. |

Parsing rules:

- `AceSize` MUST be large enough to contain the header, mask, flags, all GUIDs
  selected by `Flags`, and a complete SID.
- Unknown bits in `Flags` MUST be ignored.
- If neither GUID-presence bit is set, the ACE has no GUID fields and behaves
  like the corresponding basic ACE.
- GUID fields are opaque 16-byte values at this layer. Their interpretation is
  described in the Peios Kernel TRM §3.8.5.

### 5.4.2.3 Callback ACE family

The following ACE types extend the corresponding non-callback ACE layout by
appending `ApplicationData` at the end of the ACE:

- `ACCESS_ALLOWED_CALLBACK_ACE`
- `ACCESS_DENIED_CALLBACK_ACE`
- `SYSTEM_AUDIT_CALLBACK_ACE`
- `SYSTEM_ALARM_CALLBACK_ACE`
- `ACCESS_ALLOWED_CALLBACK_OBJECT_ACE`
- `ACCESS_DENIED_CALLBACK_OBJECT_ACE`
- `SYSTEM_AUDIT_CALLBACK_OBJECT_ACE`
- `SYSTEM_ALARM_CALLBACK_OBJECT_ACE`

For non-object callback ACEs, the body layout is:

| Offset | Size | Field | Description |
|---|---|---|---|
| 0 | 4 | AceHeader | Standard ACE header. |
| 4 | 4 | Mask | Access mask. |
| 8 | variable | Sid | Principal SID. |
| variable | variable | ApplicationData | Trailing type-specific bytes. Consumes the remainder of the ACE. |

For callback object ACEs, the body layout is:

| Offset | Size | Field | Description |
|---|---|---|---|
| 0 | 4 | AceHeader | Standard ACE header. |
| 4 | 4 | Mask | Access mask. |
| 8 | 4 | Flags | Object ACE flags. |
| 12 | 0 or 16 | ObjectType | Present when `ACE_OBJECT_TYPE_PRESENT` is set. |
| 12 or 28 | 0 or 16 | InheritedObjectType | Present when `ACE_INHERITED_OBJECT_TYPE_PRESENT` is set. |
| variable | variable | Sid | Principal SID. |
| variable | variable | ApplicationData | Trailing type-specific bytes. Consumes the remainder of the ACE. |

Parsing rules:

- The SID begins after the fixed fields and any optional GUIDs, exactly as in
  the corresponding non-callback ACE family.
- `ApplicationData` MAY be empty. Semantics for empty or malformed callback
  payloads are defined by the relevant subsystem.
- For conditional ACEs, `ApplicationData` carries the conditional expression
  bytecode defined in the Conditional ACE Bytecode Reference.

### 5.4.2.4 Resource attribute ACE

`SYSTEM_RESOURCE_ATTRIBUTE_ACE` uses the single-SID ACE prefix followed by
trailing application data:

| Offset | Size | Field | Description |
|---|---|---|---|
| 0 | 4 | AceHeader | Standard ACE header. |
| 4 | 4 | Mask | Reserved for compatibility. Not used for access decisions. |
| 8 | variable | Sid | MUST be Everyone (`S-1-1-0`). |
| variable | variable | ApplicationData | One claim entry using §5.9. Consumes the remainder of the ACE. |

Parsing rules:

- The SID MUST be Everyone.
- `ApplicationData` MUST contain exactly one claim entry using §5.9.

## 5.4.3 DACL ACE types

### 5.4.3.1 Basic ACEs

| Structure | Value | Effect |
|---|---|---|
| ACCESS_ALLOWED_ACE | 0x00 | Grants the specified rights to the SID. |
| ACCESS_DENIED_ACE | 0x01 | Denies the specified rights to the SID. |

### 5.4.3.2 Object-type ACEs

Extend basic ACEs with one or two GUIDs that scope the rule to a specific
property or object class. Used for Active Directory access control.

| Structure | Value | Effect |
|---|---|---|
| ACCESS_ALLOWED_OBJECT_ACE | 0x05 | Grants rights scoped to a property/class GUID. |
| ACCESS_DENIED_OBJECT_ACE | 0x06 | Denies rights scoped to a property/class GUID. |

The ObjectType GUID identifies the property or property set the ACE applies
to. The InheritedObjectType GUID restricts inheritance to child objects of a
specific class. Either or both GUIDs MAY be absent (indicated by a flags
field), in which case the ACE behaves like a basic ACE for that dimension.

### 5.4.3.3 Conditional ACEs

Extend basic and object-type ACEs with a conditional expression. The ACE only
takes effect if the expression evaluates to TRUE against the caller's token
attributes and the object's resource attributes.

| Structure | Value | Effect |
|---|---|---|
| ACCESS_ALLOWED_CALLBACK_ACE | 0x09 | Conditional allow. |
| ACCESS_DENIED_CALLBACK_ACE | 0x0A | Conditional deny. |
| ACCESS_ALLOWED_CALLBACK_OBJECT_ACE | 0x0B | Conditional allow, scoped to GUID. |
| ACCESS_DENIED_CALLBACK_OBJECT_ACE | 0x0C | Conditional deny, scoped to GUID. |

> [!NOTE]
> The term "callback" is historical. KACS evaluates conditional expressions
  inline during AccessCheck. The name is preserved for binary format
  compatibility. UI and UX layers MAY refer to callback ACEs exclusively as
  "conditional ACEs" for simplicity.

## 5.4.4 SACL ACE types

### 5.4.4.1 Audit ACEs

Trigger audit log entries when matching access attempts occur. The AceFlags
field carries SUCCESSFUL_ACCESS_ACE_FLAG (0x40) and/or FAILED_ACCESS_ACE_FLAG
(0x80).

| Structure | Value | Effect |
|---|---|---|
| SYSTEM_AUDIT_ACE | 0x02 | Audit access matching the SID and mask. |
| SYSTEM_AUDIT_OBJECT_ACE | 0x07 | Audit access scoped to a GUID. |
| SYSTEM_AUDIT_CALLBACK_ACE | 0x0D | Conditional audit. |
| SYSTEM_AUDIT_CALLBACK_OBJECT_ACE | 0x0F | Conditional audit, scoped to GUID. |

### 5.4.4.2 Alarm ACEs (continuous auditing)

> [!NOTE]
> These ACE types are reserved but unimplemented in the reference model. KACS
  repurposes them for continuous per-operation auditing: unlike standard audit
  ACEs (which emit a single event at handle creation), alarm ACEs configure
  per-operation audit masks that persist on the open handle. This creates no
  interoperability conflict because external sources never contain alarm ACEs.

| Structure | Value | Effect |
|---|---|---|
| SYSTEM_ALARM_ACE | 0x03 | Continuous audit for matching SID and mask. |
| SYSTEM_ALARM_OBJECT_ACE | 0x08 | Continuous audit scoped to a GUID. |
| SYSTEM_ALARM_CALLBACK_ACE | 0x0E | Conditional continuous audit. |
| SYSTEM_ALARM_CALLBACK_OBJECT_ACE | 0x10 | Conditional continuous audit, scoped to GUID. |

### 5.4.4.3 Mandatory label ACE

Defines the object's integrity level for MIC. Conforming producers SHOULD emit
at most one non-inherit-only mandatory-label ACE per SACL. Imported or
existing SACLs MAY contain multiple mandatory-label ACEs; MIC uses the first
non-inherit-only mandatory-label ACE as described in the Peios Kernel TRM
§3.8.3. Inherit-only mandatory-label ACEs do not apply to the current object.
The SID encodes the integrity level. The access mask encodes the MIC policy
(which operations are blocked for non-dominant callers).

| Structure | Value | Effect |
|---|---|---|
| SYSTEM_MANDATORY_LABEL_ACE | 0x11 | Sets the object's integrity level and MIC policy. |

### 5.4.4.4 Resource attribute ACE

Attaches name-value attributes to the object for conditional ACE evaluation.
The ACE's SID is always Everyone (`S-1-1-0`).

| Structure | Value | Effect |
|---|---|---|
| SYSTEM_RESOURCE_ATTRIBUTE_ACE | 0x12 | Defines a resource attribute on the object. |

### 5.4.4.5 Scoped policy ID ACE

References a central access policy by SID. During AccessCheck, the referenced
policy's rules are evaluated in addition to the object's own DACL.

| Structure | Value | Effect |
|---|---|---|
| SYSTEM_SCOPED_POLICY_ID_ACE | 0x13 | References a central access policy. |

### 5.4.4.6 Process trust label ACE

Defines the object's PIP trust level. The SID encodes the PIP type and trust
level. The access mask specifies the exact rights that non-dominant callers
are allowed.

| Structure | Value | Effect |
|---|---|---|
| SYSTEM_PROCESS_TRUST_LABEL_ACE | 0x14 | Sets the object's PIP trust level. |

## 5.4.5 Allocated but unimplemented ACE types

Two values in the range have a name but no KACS behavior.

| Structure | Value | Notes |
|---|---|---|
| ACCESS_ALLOWED_COMPOUND_ACE | 0x04 | Never implemented. Reserved. |
| SYSTEM_ACCESS_FILTER_ACE | 0x15 | Defined by MS-DTYP. Named by the KACS ABI for format parity; no KACS semantics. |

`ACCESS_ALLOWED_COMPOUND_ACE` was specified and then abandoned before any
conforming system implemented it. Nothing produces it.

`SYSTEM_ACCESS_FILTER_ACE` is different: it is a live MS-DTYP ACE type that
KACS has not implemented. The kernel ABI defines a constant for it
(`KACS_ACE_TYPE_SYSTEM_ACCESS_FILTER`) so that a decoder can put a name to the
byte, but no section of this specification assigns it meaning. A 0x15 ACE
therefore takes the unrecognized-ACE path described at the end of this
section: skipped during evaluation, preserved byte-for-byte on round-trip. An
implementation MUST NOT grant, deny, audit, or filter access on the basis of a
0x15 ACE.

Values above 0x15 are unallocated.

## 5.4.6 AceType constants

The tables above name each ACE **structure**. The `AceType` header field
carries a constant with its own name, which is what a reader decoding a
descriptor by hand will be holding. Both spellings, in value order:

| Value | AceType constant | Structure |
|---|---|---|
| 0x00 | `ACCESS_ALLOWED_ACE_TYPE` | `ACCESS_ALLOWED_ACE` |
| 0x01 | `ACCESS_DENIED_ACE_TYPE` | `ACCESS_DENIED_ACE` |
| 0x02 | `SYSTEM_AUDIT_ACE_TYPE` | `SYSTEM_AUDIT_ACE` |
| 0x03 | `SYSTEM_ALARM_ACE_TYPE` | `SYSTEM_ALARM_ACE` |
| 0x04 | `ACCESS_ALLOWED_COMPOUND_ACE_TYPE` | `ACCESS_ALLOWED_COMPOUND_ACE` |
| 0x05 | `ACCESS_ALLOWED_OBJECT_ACE_TYPE` | `ACCESS_ALLOWED_OBJECT_ACE` |
| 0x06 | `ACCESS_DENIED_OBJECT_ACE_TYPE` | `ACCESS_DENIED_OBJECT_ACE` |
| 0x07 | `SYSTEM_AUDIT_OBJECT_ACE_TYPE` | `SYSTEM_AUDIT_OBJECT_ACE` |
| 0x08 | `SYSTEM_ALARM_OBJECT_ACE_TYPE` | `SYSTEM_ALARM_OBJECT_ACE` |
| 0x09 | `ACCESS_ALLOWED_CALLBACK_ACE_TYPE` | `ACCESS_ALLOWED_CALLBACK_ACE` |
| 0x0A | `ACCESS_DENIED_CALLBACK_ACE_TYPE` | `ACCESS_DENIED_CALLBACK_ACE` |
| 0x0B | `ACCESS_ALLOWED_CALLBACK_OBJECT_ACE_TYPE` | `ACCESS_ALLOWED_CALLBACK_OBJECT_ACE` |
| 0x0C | `ACCESS_DENIED_CALLBACK_OBJECT_ACE_TYPE` | `ACCESS_DENIED_CALLBACK_OBJECT_ACE` |
| 0x0D | `SYSTEM_AUDIT_CALLBACK_ACE_TYPE` | `SYSTEM_AUDIT_CALLBACK_ACE` |
| 0x0E | `SYSTEM_ALARM_CALLBACK_ACE_TYPE` | `SYSTEM_ALARM_CALLBACK_ACE` |
| 0x0F | `SYSTEM_AUDIT_CALLBACK_OBJECT_ACE_TYPE` | `SYSTEM_AUDIT_CALLBACK_OBJECT_ACE` |
| 0x10 | `SYSTEM_ALARM_CALLBACK_OBJECT_ACE_TYPE` | `SYSTEM_ALARM_CALLBACK_OBJECT_ACE` |
| 0x11 | `SYSTEM_MANDATORY_LABEL_ACE_TYPE` | `SYSTEM_MANDATORY_LABEL_ACE` |
| 0x12 | `SYSTEM_RESOURCE_ATTRIBUTE_ACE_TYPE` | `SYSTEM_RESOURCE_ATTRIBUTE_ACE` |
| 0x13 | `SYSTEM_SCOPED_POLICY_ID_ACE_TYPE` | `SYSTEM_SCOPED_POLICY_ID_ACE` |
| 0x14 | `SYSTEM_PROCESS_TRUST_LABEL_ACE_TYPE` | `SYSTEM_PROCESS_TRUST_LABEL_ACE` |
| 0x15 | `SYSTEM_ACCESS_FILTER_ACE_TYPE` | `SYSTEM_ACCESS_FILTER_ACE` |

## 5.4.7 ACL revision

ACLs carry a revision number that constrains which ACE types MAY appear:

- **ACL_REVISION (0x02)** — basic ACE types (0x00, 0x01, 0x02, 0x03),
  mandatory label (0x11), resource attribute (0x12), scoped policy (0x13), and
  process trust label (0x14).
- **ACL_REVISION_DS (0x04)** — additionally permits object-type ACEs
  (0x05–0x08), callback ACEs (0x09–0x0C, 0x0D–0x10). Required for Active
  Directory access control.

When creating new ACLs containing only recognized ACE types, the revision MUST
be set to the minimum required by the ACE types present. When rewriting an
existing ACL while preserving one or more unrecognized ACE types, KACS MUST
set the revision to the greater of the minimum required by recognized ACE
types present and the source ACL revision. When parsing ACLs, KACS MUST NOT
reject an ACL based on revision-vs-ACE-type mismatch — accept permissively,
write correctly.

> [!NOTE]
> This diverges from strict MS-DTYP interpretation, where ACL_REVISION (0x02)
  does not permit SACL types 0x11-0x14. KACS accepts them under either
  revision to handle SDs that may have been constructed with a less strict
  tool. The evaluator handles all ACE types correctly regardless of ACL
  revision.

Unrecognized ACE types — every value not given semantics above, which today
means 0x04, 0x15, and everything from 0x16 up — MUST be silently skipped
during evaluation and preserved byte-for-byte during round-trip serialization.
The ACE's raw bytes (from `AceType` through `AceType + AceSize`) are stored
opaquely and written back unchanged. ACEs with `AceSize` not a multiple of 4
MUST be rejected (the containing ACL is malformed).

---

# 5.5 ACE Ordering

_Peios Specifications / PCDS / Security Descriptor_

> Canonical DACL order and why it is load-bearing — first-writer-wins means position decides the outcome — plus the ordering rules for a SACL.

The order of ACEs in a DACL determines the outcome of AccessCheck. AccessCheck
walks the DACL from first ACE to last, and the first-writer-wins principle
means each bit is decided at most once. ACE ordering is semantically
load-bearing.

## 5.5.1 Canonical ordering

Tools that author SDs SHOULD produce canonically-ordered DACLs. KACS MUST NOT
reject non-canonical DACLs — it evaluates whatever order it receives — but
non-canonical ordering can produce results that contradict administrative
intent.

The canonical order is:

1. **Explicit deny ACEs** — deny rules placed directly on this object (not
   inherited).
2. **Explicit allow ACEs** — allow rules placed directly on this object.
3. **Inherited deny ACEs** — deny rules inherited from parent objects (nearest
   parent first).
4. **Inherited allow ACEs** — allow rules inherited from parent objects.

Within each category, object-type ACEs (those scoped to a specific property
GUID) SHOULD be ordered after whole-object ACEs.

This ordering guarantees: explicit rules override inherited rules, denials
override allows at the same level, and whole-object rules override
property-scoped rules.

KACS kernel paths that evaluate, store, query, or set caller-supplied DACLs
MUST preserve the caller-supplied ACE order. KACS MUST NOT canonicalise those
DACLs by reordering deny ACEs, allow ACEs, whole-object ACEs, or object-type
ACEs.

When KACS constructs a file DACL by combining an explicit source DACL with an
inherited source DACL, it MUST emit the explicit ACE sequence before the
inherited ACE sequence. Within each sequence, KACS MUST preserve the
source-relative ACE order. This recombination rule is not a general canonical
sorting step.

## 5.5.2 SACL ordering

SACLs do not have a canonical ordering requirement. Audit ACEs are evaluated
independently (each matching ACE generates its own audit event). The mandatory
label ACE, resource attribute ACEs, and scoped policy ID ACEs are located by
type scan, not by position.

---

# 5.6 SD Inheritance

_Peios Specifications / PCDS / Security Descriptor_

> How inheritable ACEs propagate from a container to a new child — the inheritance flags, CREATOR OWNER and CREATOR GROUP substitution, and the algorithm itself.

Security Descriptors propagate structurally. When a file is created in a
directory, the directory's inheritable ACEs flow down to the new file's
SD. This automatic propagation is inheritance.

Inheritance applies to objects with a container/child relationship:
directories contain files and subdirectories, registry keys contain
subkeys and values. Objects without a container parent (standalone IPC
endpoints, tokens, processes) do not inherit.

## 5.6.1 Inheritance flags

Four flags in the ACE header's AceFlags field control propagation:

| Flag | Value | Description |
|---|---|---|
| OBJECT_INHERIT_ACE (OI) | 0x01 | Inherited by non-container children (files). For container children (subdirectories), inherited as inherit-only unless NP is also set. |
| CONTAINER_INHERIT_ACE (CI) | 0x02 | Inherited by container children (subdirectories). The inherited ACE remains inheritable (propagates to grandchildren) unless NP is also set. |
| NO_PROPAGATE_INHERIT_ACE (NP) | 0x04 | When inherited, OI and CI flags are cleared on the copy. One-level inheritance. |
| INHERIT_ONLY_ACE (IO) | 0x08 | Does not apply to the object it is attached to. Exists only to be inherited by children. |

A fifth flag records provenance:

| Flag | Value | Description |
|---|---|---|
| INHERITED_ACE | 0x10 | Set on ACEs created through inheritance (not explicitly placed). Determines ordering in canonical form. |

## 5.6.2 Common flag combinations

| Flags | Meaning |
|---|---|
| CI \| OI | Inherit to everything — containers and non-containers, recursively. |
| CI | Inherit to containers only, recursively. |
| OI | Inherit to non-containers only. Containers receive it as inherit-only. |
| CI \| OI \| IO | Inherit to everything, but do not apply to this object. |
| CI \| OI \| NP | Inherit to immediate children only. |
| CI \| NP | Inherit to immediate child containers only. |
| (none) | No inheritance. Applies only to this object. |

## 5.6.3 CREATOR OWNER and CREATOR GROUP

Two well-known SIDs receive special treatment during inheritance:

- **CREATOR OWNER (`S-1-3-0`)** — when an ACE with this SID is inherited
  by a child object, the SID is replaced with the owner SID of the new
  object (as determined by the owner computation above).

- **CREATOR GROUP (`S-1-3-1`)** — replaced with the primary group SID of
  the creating principal.

Substitution happens at inheritance time, in each ACE that applies to the
new object. An inherit-only ACE keeps the placeholder, so that each object
further down resolves it to its own owner or group (see the inherited ACEs
below).

## 5.6.4 The ACEs a child inherits

Each ACE of the parent's ACL contributes to a new child as follows. The
same rule applies to the DACL and the SACL.

1. **Whether it passes.** An ACE passes to a container child if it has CI,
   or OI without NP. It passes to a non-container child if it has OI.
   INHERIT_ONLY on the parent's ACE plays no part. An ACE that does not
   pass contributes nothing.

2. **The copy's flags.** The copy has INHERITED_ACE set and INHERIT_ONLY
   cleared, with three exceptions:
   - An ACE with OI and neither CI nor NP reaches a container as
     inherit-only (OI, IO): it applies to the objects inside, not to the
     container.
   - NP clears OI, CI and NP from the copy. The copy applies to the child
     and goes no further.
   - A non-container's copy has no OI, CI, NP or IO.

   Flags other than these (SUCCESSFUL_ACCESS_ACE, FAILED_ACCESS_ACE) are
   kept.

3. **Resolution.** A copy that applies to the child (IO clear) has
   CREATOR OWNER and CREATOR GROUP substituted, and its generic rights
   mapped through the child's GenericMapping (see below).

4. **The split.** An ACE that names CREATOR OWNER or CREATOR GROUP, or
   carries generic rights, and whose copy both applies to a container
   child and goes on from it (OI or CI still set), gives the child **two**
   ACEs, written one after the other:
   - the resolved copy, with OI, CI, NP and IO cleared, applying to the
     child alone; and
   - an inherit-only copy (the copy's flags with IO set), **left as
     written**: the placeholder unsubstituted and the generic rights
     unmapped.

   Resolving the ACE once and carrying the result down would grant the
   first creator over everything beneath, and map rights through one
   object type's mapping for objects of another. Carrying it unresolved
   would grant nothing here. A non-container gets the resolved copy alone.
   Every other ACE is inherited as one copy.

For example, a directory whose DACL holds `(A;OICIIO;GA;;;CO)` and
`(A;OICI;GR;;;AU)` gives a new subdirectory owned by alice
`(A;ID;FA;;;alice)(A;OICIIOID;GA;;;CO)(A;ID;FR;;;AU)(A;OICIIOID;GR;;;AU)`,
and a new file in it `(A;ID;FA;;;alice)(A;ID;FR;;;AU)`.

## 5.6.5 Inheritance algorithm

When a new object is created, its SD is computed from up to three
sources:

1. **Parent SD** — provides inheritable ACEs.
2. **Creator SD** — an explicit SD provided by the caller (if any).
3. **Creator token** — provides the default owner, primary group, and
   default DACL.

A creator SD with SE_SERVER_SECURITY set is rejected; see §5.1.

### 5.6.5.1 Owner

If the creator SD specifies an owner, use it. Otherwise, use the token's
owner SID.

### 5.6.5.2 Group

If the creator SD specifies a group, use it. Otherwise, use the token's
primary group SID.

### 5.6.5.3 DACL

The DACL is computed by merging explicit ACEs from the creator SD with
inheritable ACEs from the parent SD:

- If no creator SD is supplied and the parent has inheritable ACEs: the
  new object's DACL consists entirely of inherited ACEs from the parent.

- If no creator SD is supplied and the parent has no inheritable ACEs:
  the new object's DACL is the token's default DACL. If the token has no
  default DACL, the new object's DACL is null: SE_DACL_PRESENT is clear
  and the DACL offset is zero.

- If a creator SD is supplied but has no DACL (SE_DACL_PRESENT not set):
  the new object's DACL is computed as if no creator SD was supplied
  (inherit from parent, or fall back to the token's default DACL, or
  null DACL if the token has no default DACL).

- If a creator SD is supplied with a DACL (SE_DACL_PRESENT set):
  - Explicit ACEs from the creator SD are preserved.
  - If the creator SD's DACL is not protected (SE_DACL_PROTECTED not
    set) and SE_DACL_AUTO_INHERIT_REQ is set on the creator SD:
    inheritable ACEs from the parent are appended after the explicit
    ACEs. If SE_DACL_AUTO_INHERIT_REQ is not set, only the creator's
    explicit ACEs are used (no parent inheritance).
  - If the creator SD's DACL is protected: parent inheritance is
    blocked. Only the creator's explicit ACEs are used.

In all cases, the resulting DACL is post-processed:

- CREATOR OWNER / CREATOR GROUP SIDs are substituted with the actual
  owner and group in every ACE that applies to the object (INHERIT_ONLY
  clear). This substitution applies to the ACE's SID field
  only. ApplicationData — conditional expression bytecode — is copied
  verbatim: no SID substitution, no generic mapping, no offset
  adjustment. An implementation MUST NOT scan ApplicationData for
  CREATOR OWNER or CREATOR GROUP SIDs.
- Generic rights in every ACE that applies to the object (both explicit
  and inherited) are mapped to object-specific rights via the object
  type's GenericMapping, so no generic bits persist on an ACE the access
  check reads. An inherit-only ACE keeps its generic rights and
  placeholders as written, for the objects further down to resolve.
  Generic rights appearing inside ApplicationData are not mapped.
- The INHERITED_ACE flag is set on all ACEs that came from the parent.
- If any ACE was inherited from the parent, SE_DACL_AUTO_INHERITED is
  set on the new SD's control flags; if the DACL came from the token's
  default DACL instead, SE_DACL_DEFAULTED is set. The equivalent applies
  to SE_SACL_AUTO_INHERITED for the SACL.

An ACE of an unrecognized type is carried to the child unchanged apart
from its AceFlags byte (§5.4). Its mask is not mapped and its SID is not
substituted, because neither can be located within an opaque ACE.

### 5.6.5.4 SACL

Computed identically to the DACL, substituting SACL for DACL throughout.
The token has no "default SACL" — if no creator SACL is supplied and the
parent has no inheritable SACL ACEs, the new object has no SACL.

## 5.6.6 Eager evaluation

Inheritance is eager. The new object's SD is fully computed at creation
time. There is no lazy inheritance — the kernel MUST NOT walk up the
directory tree at access time to find inheritable ACEs.

A consequence of eager evaluation: modifying an inheritable ACE on a
parent object does not automatically update existing children. Existing
children retain the SD they were created with. Propagating the change to
descendants is an explicit operation, done by userspace, as below.

## 5.6.7 Re-propagation

Re-propagation brings existing descendants up to date with their parent.
The kernel has no primitive for it: the program that changed the parent
walks the tree. Every program that does MUST give the same result, which
is this.

For one child and one ACL (the DACL, the SACL, or each in turn):

1. If the child protects that ACL (SE_DACL_PROTECTED or
   SE_SACL_PROTECTED), it is left exactly as it is.
2. Otherwise, the child's ACEs with INHERITED_ACE set are removed, its
   other ACEs are kept in their order, and the ACEs the parent's ACL gives
   it (above, resolved against the child's own owner and group, through
   the child's object type's GenericMapping) are appended after them. The
   ACL is marked SE_DACL_AUTO_INHERITED or SE_SACL_AUTO_INHERITED.
3. A parent without that ACL gives nothing, so only the inherited ACEs are
   removed. A child without that ACL gets one only if something is
   inherited into it.

The owner, group and the ACL not being re-propagated are unchanged. A
child is re-propagated from its parent as the parent is after its own
re-propagation, so a walk goes parents first. A protected child still
passes its own ACEs on: its descendants are re-propagated from it as it
is. A failure on one child does not stop the walk: the rest are
re-propagated and the failures reported.

libpeios implements this as `reinherit_with` (`peios_sd_reinherit_ex`).

---

# 5.7 Ownership

_Peios Specifications / PCDS / Security Descriptor_

> The owner's implicit READ_CONTROL and WRITE_DAC, the OWNER RIGHTS ACE that suppresses them, and the rules for transferring ownership.

Every SD has an owner. Ownership confers two implicit rights that AccessCheck
grants regardless of what the DACL says:

- **READ_CONTROL** — the owner can always read the object's SD.
- **WRITE_DAC** — the owner can always modify the object's DACL.

These implicit grants are the "you can't lock yourself out" guarantee. Even if
the DACL grants the owner nothing, the owner can read and rewrite the DACL to
restore access.

Ownership is determined by SID equality against the caller's user SID or token
group SIDs. Deny-only flags affect ACE matching, but they do not change the
ownership relation itself.

## 5.7.1 OWNER RIGHTS (S-1-3-4)

The implicit READ_CONTROL and WRITE_DAC grants MAY be suppressed or modified
by including an ACE for the OWNER RIGHTS SID (`S-1-3-4`) in the DACL.

When AccessCheck detects any non-inherit-only access-control ACE targeting the
OWNER RIGHTS SID in the DACL (via a pre-scan before the DACL walk), the
implicit grant is suppressed. The owner's access then comes entirely from the
DACL walk — through ACEs matching their user SID, group SIDs, and any ACEs
targeting S-1-3-4.

This enables three patterns:

- **Suppress owner rights** — a deny ACE for S-1-3-4 with READ_CONTROL |
  WRITE_DAC.
- **Expand owner rights** — an allow ACE for S-1-3-4 with additional rights
  beyond the default.
- **Restrict owner rights** — an allow ACE for S-1-3-4 with only READ_CONTROL
  (no WRITE_DAC).

The OWNER RIGHTS pre-scan checks only for the presence of any non-inherit-only
access-control ACE targeting the OWNER RIGHTS SID in the DACL, not whether any
condition on the ACE evaluates to TRUE. A conditional ACE targeting OWNER
RIGHTS suppresses the implicit grant even if the condition later evaluates to
FALSE.

During the DACL walk, S-1-3-4 is treated as a normal SID. If the caller is the
owner, ACEs targeting S-1-3-4 match the caller. The suppression only removes
the automatic implicit grant; it does not isolate the owner from the rest of
the DACL.

## 5.7.2 Ownership transfer

Changing an object's owner requires WRITE_OWNER on the object. Without
SeTakeOwnershipPrivilege, the new owner MUST be the caller's own SID or a
group on the caller's token with SE_GROUP_OWNER (flag value 0x00000008; see
the Peios Kernel TRM §3.2.2).

SeTakeOwnershipPrivilege grants WRITE_OWNER on any object regardless of the
DACL (deny-proof, but subject to MIC/PIP). SeRestorePrivilege bypasses the
ownership SID constraint entirely — the `kacs_set_sd` syscall checks for
SeRestorePrivilege and, when present, skips the "own SID or SE_GROUP_OWNER
group" validation, allowing the caller to set ownership to any arbitrary SID.

---

# 5.8 Conditional ACEs

_Peios Specifications / PCDS / Security Descriptor_

> ACEs that carry a boolean expression — three-valued evaluation, attribute sources, SID matching, and the limits an expression must stay within.

Standard ACEs match on SID alone. Conditional ACEs add a boolean expression
that MUST also evaluate to TRUE for the rule to take effect. This enables
attribute-based access control (ABAC).

A conditional ACE is structurally identical to its non-conditional counterpart
with a conditional expression appended after the SID. The expression is stored
in a binary format defined by MS-DTYP §2.4.4.17.

## 5.8.1 Three-valued evaluation

Conditional expressions produce one of three results:

- **TRUE** — the condition is satisfied.
- **FALSE** — the condition is not satisfied.
- **UNKNOWN** — the condition could not be determined (missing attribute, type
  mismatch, malformed expression).

How the result affects the ACE depends on the ACE type:

| ACE type | TRUE | FALSE | UNKNOWN |
|---|---|---|---|
| Allow | ACE takes effect | ACE skipped | ACE skipped |
| Deny | ACE takes effect | ACE skipped | **ACE takes effect** |
| Audit | Event emitted | Event skipped | **Event emitted** |

This asymmetry is the fail-safe principle: uncertainty about whether to grant
results in no grant; uncertainty about whether to deny results in denial.

## 5.8.2 Expression language

The expression supports:

- **Relational operators:** `==`, `!=`, `<`, `<=`, `>`, `>=`
- **Set operators:** `Contains`, `Any_of`, `Not_Contains`, `Not_Any_of`
- **Membership operators:** `Member_of`, `Member_of_Any`, `Not_Member_of`,
  `Not_Member_of_Any`, `Device_Member_of`, `Device_Member_of_Any`,
  `Not_Device_Member_of`, `Not_Device_Member_of_Any`
- **Logical operators:** AND, OR, NOT
- **Existence tests:** `Exists`, `Not_Exists`
- **Literal values:** integers, strings, SIDs, octet strings, composites

## 5.8.3 Three-valued logic

| AND | TRUE | FALSE | UNKNOWN |
|---|---|---|---|
| TRUE | TRUE | FALSE | UNKNOWN |
| FALSE | FALSE | FALSE | FALSE |
| UNKNOWN | UNKNOWN | FALSE | UNKNOWN |

| OR | TRUE | FALSE | UNKNOWN |
|---|---|---|---|
| TRUE | TRUE | TRUE | TRUE |
| FALSE | TRUE | FALSE | UNKNOWN |
| UNKNOWN | TRUE | UNKNOWN | UNKNOWN |

NOT: TRUE↔FALSE; UNKNOWN→UNKNOWN.

Boolean coercion for logical operands: integer nonzero → TRUE, zero → FALSE.
String non-empty → TRUE, empty → FALSE. NULL → UNKNOWN. SID, octet, composite
→ UNKNOWN. Literal-origin values (values pushed directly from the bytecode,
not obtained via attribute lookup) used as operands in AND/OR/NOT → UNKNOWN
for the entire expression.

## 5.8.4 Attribute sources

Four attribute namespaces exist, resolved via bytecode opcodes:

| Opcode | Prefix | Source | Description |
|--------|--------|--------|-------------|
| 0xf9 | @User. | `token.user_claims` | Token-level claims set by authd at creation. |
| 0xfb | @Device. | `token.device_claims` | Device-level claims from the device token. |
| 0xfa | @Resource. | SD's SACL resource attribute ACEs | Per-object attributes, extracted in Pre-SACL walk. |
| 0xf8 | @Local. | `local_claims` parameter to AccessCheck | Per-call contextual attributes passed by the caller. Structured as a KACS claim array of length-prefixed claim entries, using §5.9. |

Attribute names are matched case-insensitively. `@User.Clearance`,
`@User.clearance`, and `@User.CLEARANCE` all resolve the same attribute.

## 5.8.5 Claim flags

Claim flags apply to token claims (@User., @Device.) and resource attributes
(@Resource.). @Local. claims also carry flags.

- **DISABLED (0x0010)** — the attribute is invisible to all conditions.
  Resolves as absent.
- **USE_FOR_DENY_ONLY (0x0004)** — the attribute participates only in
  deny-side conditional evaluation. Deny-side conditional evaluation includes
  deny ACE conditions and audit/alarm ACE conditions. For allow ACE
  conditions, it resolves as absent.

Empty attributes (zero values) are normalized to absent (NULL) at resolution
time (when the expression evaluator reads the attribute value during
AccessCheck).

Comparisons involving absent attributes evaluate to UNKNOWN. This includes
comparing two absent attributes with `==` or `!=`:
`@User.Missing == @Device.AlsoMissing` is UNKNOWN, not TRUE.

## 5.8.6 SID matching in expressions

The `Member_of` family evaluates group membership on the token. These
operators are polarity-aware: deny-only groups do not satisfy allow-ACE
conditions. Deny ACE conditions and audit/alarm ACE conditions use deny-side
membership polarity, so enabled groups and deny-only groups both participate.

An empty SID operand set uses normal set semantics: `Member_of({})` and
`Device_Member_of({})` return TRUE, while `Member_of_Any({})` and
`Device_Member_of_Any({})` return FALSE. The `Not_*` forms are the logical
inverse of those results.

> [!NOTE]
> KACS makes virtual groups (S-1-3-4 for owner, S-1-5-10 for PRINCIPAL_SELF)
  visible to conditional expressions. `Member_of({S-1-3-4})` returns TRUE when
  the active SID-matching view treats the caller as the owner. Normal
  evaluation, restricted evaluation, and confinement evaluation may supply
  different virtual-group views as defined in their respective sections. This
  is an intentional divergence for semantic consistency between the SID
  matcher and the expression evaluator.

> [!NOTE]
> KACS promotes between INT64 and UINT64 for relational operators: negative
  INT64 is always less than any UINT64. Without promotion, UINT64 claims are
  unusable in conditions because the bytecode encodes integer literals as
  signed.

## 5.8.7 Binary format

Conditional expressions are encoded as a stack-based bytecode program in
reverse Polish notation. The binary format is defined by MS-DTYP §2.4.4.17.4
and MUST be byte-compatible.

The expression bytecode begins with a 4-byte magic: `0x61 0x72 0x74 0x78`
("artx"). If the magic is absent or the expression is shorter than 4 bytes,
evaluation MUST return UNKNOWN.

Evaluation succeeds only if the final stack contains exactly one tri-state
result. If evaluation ends with zero entries, more than one entry, or a raw
non-boolean value still on the stack, the expression MUST evaluate to UNKNOWN.

The full operator bytecodes and literal encodings are specified in §5.11. KACS
implementations MUST be byte-compatible with MS-DTYP §2.4.4.17.4.

## 5.8.8 Limits

Implementations SHOULD enforce a maximum evaluation stack depth (recommended:
1024) and SHOULD return UNKNOWN for expressions that exceed it. Any bounds
violation during parsing (reading beyond the expression buffer, underflowing
the stack, integer overflow) MUST return UNKNOWN.

---

# 5.9 Claim Attribute Format

_Peios Specifications / PCDS / Security Descriptor_

> The CLAIM_SECURITY_ATTRIBUTE_RELATIVE_V1 entry — supported types, value encodings, single- and multi-entry containers, and validation.

KACS v0.20 uses a Windows-compatible `CLAIM_SECURITY_ATTRIBUTE_RELATIVE_V1`
entry format for:

- resource attributes in `SYSTEM_RESOURCE_ATTRIBUTE_ACE`
- token `user_claims`
- token `device_claims`
- `local_claims` passed to AccessCheck

The claim entry format itself is shared across all four surfaces. When
multiple entries are carried in one buffer (token claims or `local_claims`),
KACS wraps the Windows-compatible entry format in a simple length-prefixed
sequence so the buffer can be parsed deterministically without external
metadata.

## 5.9.1 Supported types

KACS v0.20 supports these claim value types:

| Type | Value | Notes |
|---|---|---|
| `INT64` | `0x0001` | Signed 64-bit integer. |
| `UINT64` | `0x0002` | Unsigned 64-bit integer. |
| `STRING` | `0x0003` | UTF-16LE string. |
| `SID` | `0x0005` | Binary SID. |
| `BOOLEAN` | `0x0006` | Stored as `u64`; normalized to true/false at resolution time. |
| `OCTET` | `0x0010` | Byte array. |

`FQBN` (`0x0004`) is reserved and not supported in KACS v0.20. Any unsupported
claim type makes the containing claim entry invalid.

## 5.9.2 Entry layout

All multibyte integers are little-endian. All offsets are relative to the
start of the claim entry.

| Offset | Size | Field | Description |
|---|---|---|---|
| 0 | 4 | `NameOffset` | Offset to the UTF-16LE null-terminated attribute name. |
| 4 | 2 | `ValueType` | One of the supported claim value types above. |
| 6 | 2 | `Reserved` | Reserved. Ignored by AccessCheck. Producers SHOULD set to 0. |
| 8 | 4 | `Flags` | Claim flags. |
| 12 | 4 | `ValueCount` | Number of values. May be 0. |
| 16 | `4 * ValueCount` | `ValueOffsets[]` | One relative offset per value. Interpretation depends on `ValueType`. |

Claim flags use the same meanings everywhere this format appears:

| Flag | Value | Meaning |
|---|---|---|
| `CLAIM_SECURITY_ATTRIBUTE_VALUE_CASE_SENSITIVE` | `0x0002` | String/octet comparisons using this attribute are case-sensitive. |
| `CLAIM_SECURITY_ATTRIBUTE_USE_FOR_DENY_ONLY` | `0x0004` | The attribute is visible only to deny-side conditional evaluation: deny ACE conditions and audit/alarm ACE conditions. |
| `CLAIM_SECURITY_ATTRIBUTE_DISABLED` | `0x0010` | The attribute is invisible to conditional evaluation. |
| `CLAIM_SECURITY_ATTRIBUTE_MANDATORY` | `0x0020` | The attribute MUST NOT be removed or modified by unprivileged callers. `kacs_set_sd` rejects attempts to remove or modify a MANDATORY attribute unless the caller has SeTcbPrivilege. |

Unknown flag bits are preserved but have no defined semantics.

## 5.9.3 Value encodings

### 5.9.3.1 INT64 / UINT64 / BOOLEAN

For `INT64`, `UINT64`, and `BOOLEAN`, each `ValueOffsets[i]` points directly
to an 8-byte scalar:

- `INT64`: signed 64-bit integer
- `UINT64`: unsigned 64-bit integer
- `BOOLEAN`: unsigned 64-bit integer, normalized at resolution time:
  - `0` = false
  - any non-zero value = true

### 5.9.3.2 STRING

For `STRING`, each `ValueOffsets[i]` points to a 4-byte `u32` named
`StringOffset`. `StringOffset` then points to the actual UTF-16LE
null-terminated string.

Strings are stored without a separate length field. The terminating UTF-16
null (`0x0000`) MUST appear within the containing claim entry.

### 5.9.3.3 SID

For `SID`, each `ValueOffsets[i]` points to a 4-byte `u32` named `SidOffset`.
`SidOffset` then points to a binary SID in the standard SID wire format.

### 5.9.3.4 OCTET

For `OCTET`, each `ValueOffsets[i]` points to a 4-byte `u32` named
`OctetOffset`. `OctetOffset` then points to:

| Offset | Size | Field | Description |
|---|---|---|---|
| 0 | 4 | `Length` | Byte length of the octet string. |
| 4 | `Length` | `Data` | Raw bytes. |

## 5.9.4 Single-entry containers

`SYSTEM_RESOURCE_ATTRIBUTE_ACE.ApplicationData` contains exactly one claim
entry and consumes the remainder of the ACE.

## 5.9.5 Multi-entry containers

Token claim buffers (`user_claims`, `device_claims`) and `local_claims` use a
KACS claim-array wrapper:

```
repeat until buffer exhausted:
  [entry_len:u32le]
  [entry_bytes: entry_len bytes]
```

Rules:

- `entry_len` MUST be non-zero.
- `entry_len` MUST fit entirely within the containing buffer.
- `entry_bytes` is one complete claim entry using the layout above.
- The parser consumes entries sequentially until the containing buffer length
  is exhausted exactly.

## 5.9.6 Validation rules

- The fixed header and `ValueOffsets[]` array MUST fit within the entry.
- Every offset and nested offset MUST remain within the entry bounds.
- Every string name and string value MUST terminate within the entry.
- Every referenced SID MUST be structurally valid.
- A malformed claim entry invalidates the containing surface:
  - malformed resource attribute ACE payload -> malformed SD for AccessCheck
  - malformed token claim buffer -> invalid token spec
  - malformed `local_claims` buffer -> invalid AccessCheck input

`ValueCount = 0` is valid. Empty attributes normalize to absent at resolution
time, as defined in §5.8.

---

# 5.10 Resource Attributes

_Peios Specifications / PCDS / Security Descriptor_

> Name-value metadata carried in the SACL for conditional ACEs to read — what resource attributes are, how they are stored, and which are protected.

A Security Descriptor MAY carry metadata about the object it protects —
descriptive properties rather than access rules. These are resource
attributes: name-value pairs stored as SYSTEM_RESOURCE_ATTRIBUTE_ACEs in the
SACL.

Resource attributes do not grant or deny access. They exist so that
conditional ACEs in the DACL can reference properties of the object during
evaluation. A conditional allow ACE might say "grant read access if
`@User.clearance >= @Resource.confidentiality`."

Each resource attribute ACE encodes a single named, typed, multi-valued
attribute. The name is a string. Values MAY be integers, strings, booleans,
SIDs, or byte arrays. The attribute data uses the claim entry format defined
in §5.9.

Multiple resource attribute ACEs MAY appear in the same SACL, each carrying a
different attribute. If two ACEs carry the same attribute name, the first one
wins — duplicates are silently ignored. Name comparison is case-insensitive,
matching the conditional expression evaluator's attribute name matching.

An inherit-only `SYSTEM_RESOURCE_ATTRIBUTE_ACE` does not apply to the object
it is attached to and MUST be ignored during resource-attribute extraction.

Resource attributes are extracted from the SACL before the DACL walk begins,
so they are available when conditional expressions need them.

A resource attribute marked `CLAIM_SECURITY_ATTRIBUTE_MANDATORY` is protected
metadata. Set-security operations MUST preserve each mandatory resource
attribute unless the caller has SeTcbPrivilege, as described in the Peios
Kernel TRM §3.4.2.

## 5.10.1 Claim types

| Type | Value | Description |
|---|---|---|
| INT64 | 0x0001 | Signed 64-bit integer. |
| UINT64 | 0x0002 | Unsigned 64-bit integer. |
| STRING | 0x0003 | Unicode string. |
| FQBN | 0x0004 | Fully Qualified Binary Name. Reserved — not supported in KACS v0.20. |
| SID | 0x0005 | Security identifier. |
| BOOLEAN | 0x0006 | Boolean value. |
| OCTET | 0x0010 | Byte array. |

Boolean values MUST be normalized to 1 (true) or 0 (false) at resolution time
(when the conditional expression evaluator reads the attribute value),
regardless of the wire encoding.

---

# 5.11 Conditional ACE Bytecode Reference

_Peios Specifications / PCDS / Security Descriptor_

> The postfix bytecode a conditional expression compiles to — magic signature, literal and operator tokens, and the integer encoding.

This section specifies the binary encoding for conditional ACE expressions.
The format is byte-compatible with MS-DTYP §2.4.4.17.4. Conditional
expressions are stored in the ApplicationData member of CALLBACK ACE types,
encoded in postfix (reverse Polish) notation.

## 5.11.1 Magic signature

A CALLBACK ACE contains a conditional expression if the ApplicationData begins
with `0x61 0x72 0x74 0x78` (the string "artx"). If the signature is absent or
the expression is shorter than 4 bytes, evaluation MUST return UNKNOWN.

## 5.11.2 Token formats

Each token begins with a single byte-code identifying the token type. All
multibyte integers, including Unicode characters, are stored least-significant
byte first (little-endian). Expressions end at the ACE boundary; any bytes
needed for DWORD alignment MUST be set to 0x00.

## 5.11.3 Literal tokens

| Token type | Byte-code | Token data encoding |
|---|---|---|
| Padding | 0x00 | No data. Used for DWORD alignment padding at end of expression. |
| Signed int8 | 0x01 | 1 QWORD (8 bytes LE) for the value (2's complement, range -128 to +127). 1 byte for sign. 1 byte for base. Total: 10 bytes. |
| Signed int16 | 0x02 | 1 QWORD (8 bytes LE) for the value (2's complement, range -32768 to +32767). 1 byte for sign. 1 byte for base. Total: 10 bytes. |
| Signed int32 | 0x03 | 1 QWORD (8 bytes LE) for the value (2's complement). 1 byte for sign. 1 byte for base. Total: 10 bytes. |
| Signed int64 | 0x04 | 1 QWORD (8 bytes LE) for the value (2's complement). 1 byte for sign. 1 byte for base. Total: 10 bytes. |
| Unicode string | 0x10 | 1 DWORD (4 bytes LE) for length in bytes. Then UTF-16LE code units (2 bytes each, LSB first). Not null-terminated. |
| Octet string | 0x18 | 1 DWORD (4 bytes LE) for length in bytes. Then raw bytes. |
| Composite | 0x50 | 1 DWORD (4 bytes LE) for total length in bytes of all contained elements. Then elements stored contiguously, each encoded per its own type rules. May be heterogeneous. |
| SID | 0x51 | 1 DWORD (4 bytes LE) for length in bytes. Then SID in binary representation (revision, sub-authority count, identifier authority, sub-authorities). |

### 5.11.3.1 Sign codes

Integer literals include a sign byte after the QWORD value:

| Sign | Code | Description |
|---|---|---|
| + | 0x01 | Explicit positive sign. |
| - | 0x02 | Negative. |
| None | 0x03 | No sign. Relational operators treat as positive. |

During relational evaluation, the sign byte determines the literal sign.
Positive (`0x01`) and no-sign (`0x03`) literals MUST be evaluated as the
positive magnitude of the QWORD value. Negative (`0x02`) literals MUST be
evaluated as the negative magnitude of the QWORD value. If the resulting
signed value does not fit the declared signed-width token, evaluation MUST
return UNKNOWN.

### 5.11.3.2 Base codes

Integer literals include a base byte after the sign byte. The base is for
display purposes only — the value is always stored as binary 2's complement
regardless of base:

| Base | Code | Description |
|---|---|---|
| Octal | 0x01 | Display as octal. |
| Decimal | 0x02 | Display as decimal. |
| Hexadecimal | 0x03 | Display as hexadecimal. |

### 5.11.3.3 Integer encoding example

The decimal value -1 encoded as a signed int64:

```
0x04 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0x02 0x02
 ^    ^-------- QWORD (2's complement) --------^  ^    ^
 |                                                 |    base=decimal
 byte-code=int64                                   sign=negative
```

## 5.11.4 Relational operator tokens

### 5.11.4.1 Binary relational operators

LHS is the second element on the stack, RHS is the top. If LHS and RHS are
different types, the entire conditional expression evaluates to UNKNOWN — with
the exception of INT64 and UINT64 which are promoted for comparison (see §5.8
for promotion rules). If either operand is UNKNOWN, the operation returns
UNKNOWN.

| Token type | Byte-code | Processing |
|---|---|---|
| == | 0x80 | TRUE if RHS equals LHS (single or set value); FALSE otherwise. |
| != | 0x81 | FALSE if RHS equals LHS; TRUE otherwise. |
| < | 0x82 | TRUE if LHS < RHS; FALSE otherwise. |
| <= | 0x83 | TRUE if LHS <= RHS; FALSE otherwise. |
| > | 0x84 | TRUE if LHS > RHS; FALSE otherwise. |
| >= | 0x85 | TRUE if LHS >= RHS; FALSE otherwise. |
| Contains | 0x86 | TRUE if LHS value(s) include all of RHS value(s); FALSE otherwise. |
| Any_of | 0x88 | TRUE if RHS includes any of LHS value(s); FALSE otherwise. |
| Not_Contains | 0x8e | Logical inverse of Contains. |
| Not_Any_of | 0x8f | Logical inverse of Any_of. |

String and octet string comparisons are byte-by-byte, case-insensitive by
default. If the CLAIM_SECURITY_ATTRIBUTE_VALUE_CASE_SENSITIVE flag (0x0002) is
set on either operand's attribute, comparison is case-sensitive.

### 5.11.4.2 Unary relational operators (SID membership)

The operand is the top of the stack and MUST be a SID literal or a composite
of SID literals.

| Token type | Byte-code | Processing |
|---|---|---|
| Member_of | 0x89 | TRUE if the token's group SIDs contain all SIDs in the operand. |
| Device_Member_of | 0x8a | TRUE if the token's device group SIDs contain all SIDs in the operand. |
| Member_of_Any | 0x8b | TRUE if the token's group SIDs contain any SID in the operand. |
| Device_Member_of_Any | 0x8c | TRUE if the token's device group SIDs contain any SID in the operand. |
| Not_Member_of | 0x90 | Logical inverse of Member_of. |
| Not_Device_Member_of | 0x91 | Logical inverse of Device_Member_of. |
| Not_Member_of_Any | 0x92 | Logical inverse of Member_of_Any. |
| Not_Device_Member_of_Any | 0x93 | Logical inverse of Device_Member_of_Any. |

For an empty SID operand set:

- `Member_of({})` and `Device_Member_of({})` return TRUE (vacuous truth).
- `Member_of_Any({})` and `Device_Member_of_Any({})` return FALSE.
- The `Not_*` forms are the logical inverse of those results.

## 5.11.5 Logical operator tokens

Logical operators test the logical value of operands and produce TRUE, FALSE,
or UNKNOWN. The logical value of an operand is determined by:

- Literal-origin value → error (entire expression returns UNKNOWN)
- Attribute with null value → UNKNOWN
- Attribute with integer value → TRUE if nonzero, FALSE if zero
- Attribute with string value → TRUE if non-empty, FALSE if empty
- Result value → the result's tri-state value

### 5.11.5.1 Unary logical operators

| Token type | Byte-code | Processing |
|---|---|---|
| Exists | 0x87 | TRUE if the operand is an attribute (@Local., @Resource., @User., or @Device.) with a non-null value. FALSE if the attribute is absent or null. Returns error (→ UNKNOWN) for literal operands. KACS divergence: extends Exists to all four namespaces (MS-DTYP restricts to Local/Resource only). |
| Not_Exists | 0x8d | Logical inverse of Exists. |
| NOT (!) | 0xa2 | TRUE→FALSE, FALSE→TRUE, UNKNOWN→UNKNOWN. |

### 5.11.5.2 Binary logical operators

LHS is the second element on the stack, RHS is the top.

| Token type | Byte-code | Processing |
|---|---|---|
| AND (&&) | 0xa0 | If either operand is FALSE, return FALSE. Else if either is UNKNOWN, return UNKNOWN. Else return TRUE. |
| OR (\|\|) | 0xa1 | If either operand is TRUE, return TRUE. Else if either is UNKNOWN, return UNKNOWN. Else return FALSE. |

## 5.11.6 Attribute reference tokens

Attribute names are encoded as Unicode strings (same format as the 0x10
literal: DWORD length + UTF-16LE code units). The byte-code determines which
namespace to look up the attribute in.

Attribute lookup is case-insensitive: the encoded name is matched against the
namespace's attribute names without regard to case.

| Token type | Byte-code | Namespace |
|---|---|---|
| @Local. | 0xf8 | Local claims (passed as AccessCheck parameter). |
| @User. | 0xf9 | User claims (from token.user_claims). |
| @Resource. | 0xfa | Resource attributes (from SACL resource attribute ACEs). |
| @Device. | 0xfb | Device claims (from token.device_claims). |

## 5.11.7 Complete byte-code summary

For quick reference, all byte-codes in numeric order:

| Byte-code | Token |
|---|---|
| 0x00 | Padding |
| 0x01 | Signed int8 literal |
| 0x02 | Signed int16 literal |
| 0x03 | Signed int32 literal |
| 0x04 | Signed int64 literal |
| 0x10 | Unicode string literal |
| 0x18 | Octet string literal |
| 0x50 | Composite literal |
| 0x51 | SID literal |
| 0x80 | == |
| 0x81 | != |
| 0x82 | < |
| 0x83 | <= |
| 0x84 | > |
| 0x85 | >= |
| 0x86 | Contains |
| 0x87 | Exists |
| 0x88 | Any_of |
| 0x89 | Member_of |
| 0x8a | Device_Member_of |
| 0x8b | Member_of_Any |
| 0x8c | Device_Member_of_Any |
| 0x8d | Not_Exists |
| 0x8e | Not_Contains |
| 0x8f | Not_Any_of |
| 0x90 | Not_Member_of |
| 0x91 | Not_Device_Member_of |
| 0x92 | Not_Member_of_Any |
| 0x93 | Not_Device_Member_of_Any |
| 0xa0 | AND (&&) |
| 0xa1 | OR (\|\|) |
| 0xa2 | NOT (!) |
| 0xf8 | @Local. attribute |
| 0xf9 | @User. attribute |
| 0xfa | @Resource. attribute |
| 0xfb | @Device. attribute |

KACS implementations MUST be byte-compatible with these encodings.

> [!NOTE]
> This byte-code table is reproduced from MS-DTYP §2.4.4.17.4 through
  §2.4.4.17.8 for specification self-containment. KACS-specific evaluation
  semantics (three-valued logic tables, INT64/UINT64 promotion, virtual group
  visibility in Member_of, polarity-aware SID matching) are defined in §5.8.

---

# Appendix 5.A Prior Art

_Peios Specifications / PCDS / Security Descriptor_

> Where the SD family comes from in MS-DTYP — the self-relative descriptor, the ACL and ACE formats, claim entries, and conditional bytecode.

## 5.A.1 MS-DTYP

The security descriptor family defined in this chapter derives from
the Microsoft Data Types specification (MS-DTYP): the self-relative
security descriptor (§2.4.6), the ACL and ACE binary formats, the
CLAIM_SECURITY_ATTRIBUTE_RELATIVE_V1 claim entry, and the conditional
expression bytecode (§2.4.4.17). Peios keeps the binary formats
byte-compatible so security descriptors round-trip with Windows
systems — over the wire and on NTFS volumes.

Deliberate divergences from the reference model are flagged inline as
notes where they occur: permissive ACL-revision parsing, the
repurposing of alarm ACEs for continuous auditing, evaluation-time
generic mapping, the extension of Exists to all four attribute
namespaces, INT64/UINT64 promotion in relational operators, and
virtual-group visibility in Member_of.

---

# 6.1 Binary Format

_Peios Specifications / PCDS / Sealed Secret_

> The PEIOSEAL v1 sealed secret — its 52-byte header, the Argon2id parameters and salt it records, the AES-256-GCM nonce, and the ciphertext and tag after it.

A **sealed secret** is a secret encrypted under a key derived from a
passphrase, in a self-describing blob: it records everything needed to
open it except the passphrase. The certificate authority keeps its
private keys in sealed secrets, and so do Peios Signed Objects' key
files.

This chapter specifies version 1, identified by the magic `PEIOSEAL`. It
says nothing of what the secret is: a caller seals whatever bytes it
holds and gives them meaning itself.

Unlike the rest of this document, every multi-byte integer in a sealed
secret is **big-endian**.

## 6.1.1 Layout

| Offset | Size | Field | Value |
|---:|---:|---|---|
| 0 | 8 | `magic` | ASCII `PEIOSEAL` |
| 8 | 1 | `version` | `1` |
| 9 | 1 | `kdf` | `1`, Argon2id version 0x13 |
| 10 | 4 | `memory` | Argon2 memory in KiB, uint32 |
| 14 | 4 | `passes` | Argon2 passes, uint32 |
| 18 | 4 | `lanes` | Argon2 lanes, uint32 |
| 22 | 1 | `salt_len` | `16` |
| 23 | 16 | `salt` | Argon2 salt |
| 39 | 1 | `cipher` | `1`, AES-256-GCM |
| 40 | 12 | `nonce` | AES-GCM nonce |
| 52 | n | `ciphertext` | The secret, encrypted; as long as the secret |
| 52 + n | 16 | `tag` | The AES-GCM authentication tag |

The first 52 bytes are the **header**. A sealed secret is at least 68
bytes long: the header and the tag around an empty ciphertext, which is
valid.

The `kdf` and `cipher` enumerations are closed for version 1. A value
other than `1` in either is not a version 1 sealed secret.

> [!NOTE]
> The header's fields are laid out so that a later version could add
> another key derivation, such as PBKDF2 for a FIPS-validated system,
> as a new `kdf` value. A version 1 reader refuses it rather than
> guessing.

---

# 6.2 Sealing

_Peios Specifications / PCDS / Sealed Secret_

> How a secret is sealed — a fresh salt and nonce, Argon2id deriving a 32-byte key, and AES-256-GCM with the whole header as associated data.

To seal a secret under a passphrase, a producer:

1. Draws a fresh 16-byte `salt` and a fresh 12-byte `nonce` from a
   cryptographically secure random number generator.
2. Chooses Argon2 parameters, `memory`, `passes` and `lanes`, within the
   bounds of §6.3.
3. Writes the header of §6.1 with those values.
4. Derives a 32-byte key with Argon2id, version 0x13 (RFC 9106), from
   the passphrase's bytes as the password and `salt` as the salt, with no
   secret value and no associated data.
5. Encrypts the secret with AES-256-GCM under that key and `nonce`, with
   the whole 52-byte header as the associated data, and appends the
   ciphertext and the 16-byte tag to the header.

A producer MUST draw a new salt and a new nonce for every seal, including
when it seals the same secret under the same passphrase again.

A producer SHOULD use 65,536 KiB of memory, 3 passes and 4 lanes, the
second recommended option of RFC 9106 §4, unless it has measured that
the machine that opens the secret can afford more.

The passphrase's bytes are used as they are given. Turning typed text
into those bytes is §6.4's.

> [!NOTE]
> The header is the cipher's associated data, so changing a recorded
> parameter, the salt or the nonce makes the tag fail. Lowering
> `memory` to make guessing cheaper therefore can't succeed without the
> passphrase. A fresh salt makes a fresh key on every seal, which is
> what makes a random 12-byte nonce safe: no key ever sees two nonces.

---

# 6.3 Opening

_Peios Specifications / PCDS / Sealed Secret_

> How a reader opens a sealed secret — the checks before any key is derived, the bounds on recorded parameters, and why every later failure is one error.

A reader MUST make these checks, in this order, before it derives a key,
and MUST treat a sealed secret that fails any of them as malformed:

1. It is at least 68 bytes long, and its first 8 bytes are `PEIOSEAL`.
2. `version` is `1`, `kdf` is `1`, and `cipher` is `1`.
3. `salt_len` is `16`.
4. `memory` is at most 1,048,576 KiB, `passes` is from 1 through 16,
   and `lanes` is from 1 through 16.

A reader MUST also treat as malformed any parameters its Argon2
implementation refuses, such as `memory` below 8 KiB for each lane.

The reader then derives the key as §6.2 does, with the recorded
parameters and salt, and decrypts with the recorded nonce and the header
as associated data.

A reader MUST report a failure to decrypt as one error, meaning that the
passphrase is wrong or the sealed secret has been altered. It MUST NOT
say which.

> [!NOTE]
> The bounds exist because the header is authenticated only after the
> derivation has run. Without them, a hostile sealed secret could make
> its reader spend gigabytes of memory or hours of work before failing.
> They are wide enough that a producer can raise its parameters a long
> way before it reaches them.

---

# 6.4 Passphrases

_Peios Specifications / PCDS / Sealed Secret_

> How typed text becomes a passphrase's bytes — Unicode NFKC, then UTF-8 — and the 15-character minimum for a passphrase that seals.

A sealed secret is opened by the same bytes that sealed it. Where a
passphrase is typed or read as text, two programs agree on its bytes
only if they turn text into bytes the same way.

A program that takes a passphrase as text MUST normalize it to Unicode
Normalization Form KC (NFKC, UAX #15) and use the UTF-8 encoding of the
result as the passphrase's bytes, both to seal and to open.

A program that seals a secret under a passphrase given as text MUST
refuse one shorter than 15 characters, counted as Unicode scalar values
of the normalized text. A program MUST NOT apply any strength rule when
it opens a sealed secret.

> [!NOTE]
> The same characters can be encoded more than one way: an accented
> letter can be one code point or a letter followed by a combining
> accent, depending on the keyboard and system. NFKC makes them one, so
> a passphrase typed on another machine still opens what it sealed.
> Fifteen characters is NIST SP 800-63B-4's minimum for a password used
> on its own. A sealed secret can be attacked offline by anyone who
> copies it, with nothing to limit their guesses, so length is what
> protects it; Argon2id only makes each guess slower.

---

# Appendix 6.A Prior Art

_Peios Specifications / PCDS / Sealed Secret_

> Where the sealed secret sits against PKCS

## 6.A.1 Encrypted PKCS #8

PKCS #8 (RFC 5958) encrypts a private key under a passphrase with a key
derivation and cipher named by ASN.1 algorithm identifiers, usually
PBKDF2 and AES-CBC. A sealed secret keeps the idea of recording the
derivation's parameters with the ciphertext, and drops ASN.1 for a fixed
layout. It uses a memory-hard derivation, Argon2id, and an authenticated
cipher whose associated data covers the parameters, which PKCS #8's
common profiles do not.

## 6.A.2 The age file encryption tool

age's scrypt recipient seals a file key under a passphrase, records its
work factor, and bounds it on reading so that a hostile file can't
demand unbounded work. A sealed secret does the same with Argon2id, and
bounds memory, passes and lanes separately.

## 6.A.3 Design influences

**One error for every failure to open.** A reader that said whether the
passphrase or the ciphertext was wrong would tell an attacker which.

**The secret is the caller's.** A sealed secret encrypts bytes and says
nothing of what they are, so each format that uses it, the certificate
authority's key files and PSO's, keeps its own envelope and its own
checks on what it unseals.

---

# 7.1 Binary Format

_Peios Specifications / PCDS / Key File_

> The PEIOSKEY v1 key file — its 14-byte header, the algorithm, protection and flags it records, the public key in the clear, and the private key after it.

A **key file** holds one asymmetric key pair: the public key in the
clear, so that a program can tell which key a file holds without opening
it, and the private key, either sealed under a passphrase or kept in the
clear for storage that access control protects. The certificate
authority keeps every CA key in a key file, and exports keys only as
sealed key files.

This chapter specifies version 1, identified by the magic `PEIOSKEY`.

Unlike most of this document, every multi-byte integer in a key file is
**big-endian**.

## 7.1.1 Layout

| Offset | Size | Field | Value |
|---:|---:|---|---|
| 0 | 8 | `magic` | ASCII `PEIOSKEY` |
| 8 | 1 | `version` | `1` |
| 9 | 1 | `algorithm` | The key's algorithm, §7.2 |
| 10 | 1 | `protection` | `1`, passphrase; `2`, access control |
| 11 | 1 | `flags` | Bit 0, not exportable; the other bits zero |
| 12 | 2 | `public_len` | Length of `public_key`, uint16 |
| 14 | `public_len` | `public_key` | The public key, a DER `SubjectPublicKeyInfo` |
| 14 + `public_len` | rest | `private_key` | The private key, as `protection` says |

The first 14 bytes are the **header**. `public_key` and `private_key`
are each at least one byte long, and `private_key` runs to the end of
the file.

`private_key` depends on `protection`:

- **`1`, passphrase:** a sealed secret (§6) of the private key's
  PKCS #8 encoding, sealed under the key's passphrase.
- **`2`, access control:** the private key's PKCS #8 encoding itself.
  Only the access control of the storage that holds the file keeps it
  secret.

The **not exportable** flag asks the program that holds the key never
to release it, even to a caller that may otherwise read it. It is
meaningful only with access-control protection: whoever has a sealed key
file and its passphrase already has the key.

The `algorithm` and `protection` enumerations and the `flags` bits are
closed for version 1. A value this chapter doesn't define is not a
version 1 key file.

> [!NOTE]
> Nothing before `private_key` is secret: a CA's certificate carries the
> same public key. Nor is it authenticated, even in a sealed key file,
> whose sealed secret covers only the private key. That is why a reader
> checks the private key against the recorded public key once it has
> opened it (§7.3).

---

# 7.2 Algorithms

_Peios Specifications / PCDS / Key File_

> The key algorithms a key file can hold, and the SubjectPublicKeyInfo and PKCS

| `algorithm` | Key | Public key | Private key |
|---:|---|---|---|
| `1` | ECDSA over NIST P-256 | `id-ecPublicKey`, curve `secp256r1` (RFC 5480) | ECPrivateKey (RFC 5915) |
| `2` | ECDSA over NIST P-384 | `id-ecPublicKey`, curve `secp384r1` (RFC 5480) | ECPrivateKey (RFC 5915) |
| `3` | RSA, 2048-bit modulus | `rsaEncryption` (RFC 8017) | RSAPrivateKey (RFC 8017) |
| `4` | RSA, 3072-bit modulus | `rsaEncryption` (RFC 8017) | RSAPrivateKey (RFC 8017) |
| `5` | RSA, 4096-bit modulus | `rsaEncryption` (RFC 8017) | RSAPrivateKey (RFC 8017) |

`public_key` is the key's DER `SubjectPublicKeyInfo` (RFC 5280), with
the algorithm identifier the table names. An elliptic-curve public key
is the uncompressed point. A writer MUST write the canonical DER
encoding, so that one key always has one encoding.

The private key is a version 1 PKCS #8 `PrivateKeyInfo` (RFC 5208)
carrying the key's own private-key structure from the table, with the
same algorithm identifier as `public_key`.

An RSA key's `algorithm` is fixed by the length of its modulus: an RSA
key of any other size can't be held in a version 1 key file.

> [!NOTE]
> A new algorithm takes the next free value. A version 1 reader refuses
> a value it doesn't know, so adding one never changes how an existing
> key file is read.

---

# 7.3 Reading

_Peios Specifications / PCDS / Key File_

> The checks a reader makes on a key file's header, and how it opens the private key and confirms that it matches the recorded public key.

A reader MUST treat a key file that fails any of these checks as
malformed:

1. It is at least 14 bytes long, and its first 8 bytes are `PEIOSKEY`.
2. `version` is `1`.
3. `algorithm` is a value §7.2 defines.
4. `protection` is `1` or `2`.
5. No bit of `flags` other than bit 0 is set, and bit 0 is clear if
   `protection` is `1`.
6. `public_len` is not zero, and at least one byte follows `public_key`.
7. `public_key` is the canonical DER encoding of a key of `algorithm`.

A reader can describe a key from these fields alone: its algorithm, its
public key, how it is protected, and whether it may be exported.

To open the private key, a reader takes `private_key` as it is, with
access-control protection, or opens it as a sealed secret under the
key's passphrase (§6.3), with passphrase protection. It then parses the
PKCS #8 encoding, and MUST refuse the key unless it is a key of
`algorithm` whose public key is exactly `public_key`.

A program that holds a key file whose not-exportable flag is set MUST
NOT release the private key, sealed or in the clear.

> [!NOTE]
> The last check is what makes the unauthenticated header safe. Someone
> who alters `public_key` or `algorithm` can make a key file describe
> another key, but not make it open as one: the private key no longer
> matches, and the reader refuses it.

---

# Appendix 7.A Prior Art

_Peios Specifications / PCDS / Key File_

> Where the key file sits against encrypted PKCS

## 7.A.1 PKCS #8 and PEM

An encrypted PKCS #8 file (RFC 5958) holds only the private key, under a
passphrase, and says nothing readable about which key it is until it is
opened. A key file keeps PKCS #8 for the private key, so that any
library can parse it once opened, and puts the public key and the
algorithm in front of it in the clear, so that a program can show which
key a file holds, or find the one it needs, without asking for a
passphrase.

## 7.A.2 Design influences

**One format, whatever protects the key.** A key kept by a service under
access control and a key sealed on removable media share a layout, so an
export is the same key in a different protection, not a different format.

**Readable, not trusted.** The header is there to describe the key, and
never decides what is opened: the private key is checked against it.

---

# 1.1 Scope

_Peios Specifications / PGSS / Introduction_

> What PGSS is, standards that Peios implements and another system could adopt, and the tests that separate a standard from a protocol.

This document defines the **Peios Generic System Standards (PGSS)**:
standards that Peios implements, written so that another system could
adopt them.

A standard belongs in this document when three things are true of it.

**It is useful outside Peios.** Another system could adopt the standard
without changing how the rest of that system works. A standard that
only makes sense given the Peios kernel, or given a particular Peios
component, belongs in PSPK or PSPU.

**It belongs to no implementation.** A PGSS standard describes a contract
between two roles, not the behavior of a particular program. Mainline
ships an implementation of each role; nothing in this document depends on
that implementation, or describes it.

**Either role may be replaced.** A third party MAY ship its own
implementation of one role — or of both — and interoperate with the other
unchanged. A standard that cannot survive that substitution is a
description of one system rather than a contract between two, and does
not belong here.

For each standard, this document covers:

- the channel it is offered on, and the access control governing it
- message framing, encoding, and the rules under which the format may be
  extended
- the messages exchanged, their fields, and the order in which they are
  exchanged
- the obligations binding on each role, including what a role MUST
  establish for itself rather than believe from a message
- the conformance requirements for each role

This document does not cover:

- How an implementation reaches the answers it gives — that is precisely
  what different systems exist to do differently
- The binary structures these protocols carry — defined in PCDS
- Protocols spoken across the kernel boundary — defined in PSPK
- Protocols between foundational userspace components — defined in PSPU
- Interfaces particular to one Mainline component — defined in the
  specification of the component that offers them

## 1.1.1 Distinguishing a standard from a protocol

The anthology's three protocol documents are told apart by who could
use them.

A standard in this document stands alone. A system that is not Peios
can implement it and interoperate with every other implementation.

PSPK and PSPU describe how the parts of Peios fit together: the kernel
boundary, and the protocols between foundational userspace components.
They have little use outside a system built from those parts.

Placement is a judgment about where a standard is most useful, not a
rule that can be applied mechanically.

## 1.1.2 What depends on these standards

No standard here is a test of whether a system is Peios. In practice a
system needs them all the same. They define mechanisms that many
separate components rely on, and a system that leaves one out cannot
expect software written for Peios to work with it.

> [!NOTE]
> The consequence of the second and third properties together is that
> conformance is checked against the protocol, never against Mainline. A
> system that speaks a standard correctly conforms to it, whatever it
> runs behind the channel and however it reaches its answers.

---

# 1.2 Conventions

_Peios Specifications / PGSS / Introduction_

> The normative keywords PGSS uses, and the shared conventions it inherits from the PCSA conventions book.

The key words MUST, MUST NOT, SHOULD, SHOULD NOT, and MAY in this
document are to be interpreted as described in RFC 2119. Text set off as
a note is informative, not normative.

Everything else — roles, byte order, sizes, layout tables, notation,
strings, timestamps, citation, and the external standards this anthology
depends on — is defined in the Conventions book and is not restated
here. PGSS departs from none of it.

Where a chapter needs a convention of its own, that chapter states it.

---

# 2.1 Scope and Roles

_Peios Specifications / PGSS / Logon_

> What PGSS Logon specifies and who its parties are — obtaining a token from an authority, resolving identity, and the boundaries the authority does not cross.

This chapter specifies **PGSS Logon**: the protocol by which a caller
obtains a KACS token and a logon session from an authentication
authority, and the protocol by which any program on the system resolves
an identity it already holds into a name, a SID, or the attributes a
POSIX program expects of one.

Two roles participate.

The **authority** is the process that listens on the logon socket. It
decides whether a logon succeeds, mints the resulting token, creates the
logon session, and answers identity lookups. There MUST be at most one
authority on a running system.

The **client** connects and speaks on a principal's behalf. It proposes
what kind of logon it wants, renders prompts and returns answers without
interpreting them, and receives the token and installs it itself. A
client is not trusted: everything it sends is a claim (§2.4).

The **principal** is the identity a logon is *for* — the person or
service being authenticated. The principal is not a party to the
conversation.

Both roles are publicly implementable. A third party MAY ship a
different authority, a different logon originator, or both, and
interoperate with the other half unchanged.

This chapter covers:

- the two channels an authority offers, and the access control
  governing each (§2.5, §2.14)
- message framing, header layout, and the rules under which the format
  may be extended (§2.6)
- the messages of the logon conversation, their fields, and their
  encodings (§2.7 to §2.10)
- the shape of a conversation: who speaks, in what order, and how it
  terminates (§2.3)
- the transfer of the minted token to the caller, and the
  session-profile values a logon originator needs in order to start a
  session (§2.9)
- credential handling obligations binding on both roles (§2.11, §2.12)
- what an authority MUST establish for itself rather than believe from
  a message (§2.4)
- resolving a principal to a name, a SID, a POSIX identifier, or the
  attributes a POSIX program expects of one (§2.13 to §2.18)
- how a bare name is resolved when more than one source could answer it
  (§2.15)
- how a service manager obtains a token for a service, where there is no
  credential to exchange (§2.19)
- how a principal changes their own credential (§2.20)
- the obligations binding on each role (§2.21)
- how a caller asks the authority to end a logon session — its own, or,
  where policy permits, somebody else's (§2.22)
- how a principal adds a credential of their own, such as an SSH public
  key, or removes one (§2.23)

This chapter does not cover:

- Tokens, SIDs, privileges, integrity levels, logon sessions, logon
  types, and access checks — described in the Peios Kernel TRM. SIDs
  and security descriptors are specified in PCDS.
- How an authority decides *whether* a credential is valid, where it
  keeps identity, which principals exist, or what they are called.
  Those belong to the authority's own design. Mainline's authority
  federates them over PSI, the Principal Source Interface, specified in
  PSPU §2.
- Credential enrolment — giving a principal a credential it does not
  have — and account administration, including setting a credential on
  another principal's behalf. Neither is specified.
- Service startup and ordering, described in the peinit TRM.

The distinction in the second point is the load-bearing one. PGSS Logon
specifies how a caller *asks* and how an authority *answers*. It says
nothing about how the authority reaches its answer, because that is
exactly what different systems will do differently, and constraining it
would make the standard a description of one implementation rather than
a contract between two.

> [!NOTE]
> Mainline's authority is `authd`, which federates authentication to
> separate principal-source processes over PSI (PSPU §2). That
> architecture is
> *one* way to satisfy this chapter. An authority that consults a single
> built-in database, or a remote directory, or a hardware token reader,
> conforms equally well provided it speaks this protocol correctly.

## 2.1.1 What the authority does not do

An authority MUST NOT be a process factory. It does not fork the
principal's shell, does not learn about controlling terminals,
environments, or session leadership, and does not decide what the caller
does with the token it receives.

The caller installs the token and proceeds. This keeps the most
privileged process on the system out of the business of launching
arbitrary programs, and it means a client can obtain a token for a
purpose the authority need never have anticipated.

The authority still starts nothing when it is asked to end a logon
session (§2.22). It MAY then end the processes running in that session,
and only those: ending what exists launches nothing, and the
prohibition is on launching.

> [!NOTE]
> This is why `AccessGranted` carries a descriptor and a session
> identifier and nothing else. There is no field describing what should
> happen next, because nothing about what happens next is the
> authority's concern.

## 2.1.2 Authentication and derivation

Two acts, deliberately separated.

**Authentication** establishes that the principal is who they claim. Its
output is an identity and nothing more.

**Derivation** constructs the token: which SIDs it carries, which
privileges, at what integrity level, with what projected identifiers.
Its inputs are the authenticated identity *and local policy*.

The separation matters because the second is where a machine's own rules
apply. An identity established elsewhere — by a directory, by a remote
authority — does not carry entitlements onto this machine with it. What
that identity *means* here is decided here, every time, by the authority
applying local policy.

An authority MUST perform derivation itself. It MUST NOT accept a token,
a privilege set, or an integrity level supplied by any other party,
whatever its trust level.

## 2.1.3 The token this chapter does not describe

This chapter governs the conversation and the delivery of its result. It
does not govern the *contents* of the token that results. What SIDs,
privileges, and integrity level a principal receives is derivation, and
derivation is the authority's judgment applied to local policy.

A caller that receives a token from this protocol has been told who it
may act as. It has not been told, and MUST NOT infer, anything further
about how that conclusion was reached.

---

# 2.2 Terminology

_Peios Specifications / PGSS / Logon_

> Terms this chapter borrows unchanged from the Peios Kernel TRM and PCDS, and the one it has to qualify — logon type.

Terms defined in the Peios Kernel TRM (token, logon session, privilege,
integrity level, logon type) and in PCDS (SID, security descriptor,
DACL) are used here with the same meaning and are not redefined.

**Authority.** The process that listens on the logon socket, decides
whether a logon succeeds, mints the resulting token, creates the logon
session, and answers identity lookups. There is at most one authority on
a running system.

**Client.** A process that connects to the authority. Also called the
*originator* when the emphasis is on whose identity the authority
verifies. There are four client roles — originating a logon, changing
the caller's own credential, looking an identity up, and ending a logon
session — and they are independent (§2.21).

**Principal.** The identity a logon is *for* — the person or service
being authenticated. The principal is not a party to the conversation;
the client speaks on their behalf.

**Conversation.** One connection's exchange, from the client's opening
message — a logon's, a credential change's (§2.20), an enrolment's
(§2.23), or a request to end a logon session (§2.22) — to a terminal message from the authority. One
connection carries exactly one conversation.

**Round.** One `CredentialRequest` from the authority and the
`CredentialResponse` that answers it. A conversation MAY take several
rounds.

**Terminal message.** `AccessGranted` or `AccessDenied` for a logon;
`CredentialChanged` or `AccessDenied` for a credential change (§2.20)
or an enrolment (§2.23);
`SessionEnded`, `SessionEndAllowed` or `AccessDenied` for a request to
end a logon session or to ask whether one may (§2.22). Exactly one is
sent, and nothing follows it.

**Credential material.** Any byte sequence a principal supplies as proof
of identity — a password, a one-time code, a response from a token.
Distinguished throughout from a **verifier**, which is what an authority
stores and which MUST NOT be usable as credential material.

**Prompt.** A request from the authority for one piece of credential
material, carrying enough description for a client to render it without
understanding what it is for.

**Derivation.** The authority's construction of a token's contents — its
SIDs, privileges and integrity level — from the authenticated identity
and local policy. Distinct from *authentication*, which establishes only
that the principal is who they claim.

**Attestation.** A trusted process's assertion that a logon should
happen, standing in for a credential where none exists and none should.
Distinct from *authentication*, which establishes that a principal is
who they claim by something only they could present; an attestation
establishes only that the party asking is one the authority permits to
ask (§2.19).

**Source.** A party an authority consults in order to answer a question
about identity. Whether an authority has sources at all, and what they
are, is its own design; the term appears here only where the protocol's
behavior depends on there being more than one possible answerer
(§2.15, §2.18).

## 2.2.1 A note on "logon type"

`LogonType` (§2.7) describes the *kind* of session being established —
interactive, network, batch, service. It is a property of the situation,
not of the principal, and the same principal may hold several sessions
of different types at once. Its values and meanings are defined by KACS
and described in the Peios Kernel TRM; this chapter carries it but does
not define it. The values are listed for reference in §2.B.

---

# 2.3 The Conversation

_Peios Specifications / PGSS / Logon_

> A logon is a conversation rather than a call — who may speak when, how it is bounded, and how it ends.

A logon is a conversation, not a call. The client opens it, the
authority asks for whatever the principal's policy requires, and the
authority ends it.

```
client                                   authority
  |                                          |
  |------------- LogonStart ---------------->|
  |                                          |
  |<--------- CredentialRequest -------------|   round 1
  |---------- CredentialResponse ----------->|
  |                                          |
  |<--------- CredentialRequest -------------|   round 2 (if required)
  |---------- CredentialResponse ----------->|
  |                                          |
  |<-- AccessGranted (+ token fd) -----------|   terminal
  |         or AccessDenied                  |
```

## 2.3.1 Why a conversation

The value of this shape is that **the client stays generic**. It does
not know what a password is. It renders the prompts it is given,
collects the answers, and returns them.

That is what makes multi-factor authentication,
password-expiry-forces-change, smartcards, or a policy that asks for a
second factor only from an unfamiliar host, changes to *authorities*
rather than to every client on the system. A protocol that named its
credential kinds would have to be revised, and every client rebuilt, for
each one.

Most logons are one round: the authority asks for everything the
principal's policy requires, in one array, and decides. The
conversational shape exists for what one round cannot express — choosing
between authentication paths, or a shared account where one credential
unlocks a requirement for another.

## 2.3.2 Sequence rules

A conversation MUST proceed as follows.

1. The client sends exactly one opening message: `LogonStart`,
   `CredentialChangeStart` to change its own credential (§2.20),
   `CredentialEnrollStart` to add or remove one of its own (§2.23), or
   `SessionEnd` or `SessionEndQuery` about a logon session (§2.22). It
   MUST be the first message. An authority MUST reject any conversation
   that opens with something else.
2. The authority sends zero or more `CredentialRequest` messages. Each
   MUST be answered by exactly one `CredentialResponse` before the
   authority sends anything further.
3. The authority sends exactly one terminal message: `AccessGranted` or
   `AccessDenied` for a logon, `CredentialChanged` or `AccessDenied` for
   a credential change or an enrolment, `SessionEnded` or `AccessDenied` for a
   `SessionEnd`, and `SessionEndAllowed` or `AccessDenied` for a
   `SessionEndQuery`.
4. Both parties close the connection.

`SessionEnd` and `SessionEndQuery` exchange no credentials: the
authority sends no `CredentialRequest` in reply to either, and the
conversation is the opening message and its terminal.

The authority MAY send a terminal message at any point after
`LogonStart`, including before any `CredentialRequest`. Zero rounds is a
conforming conversation: an authority that can decide from `LogonStart`
alone — a pre-authenticated caller, or a refusal on logon type — is not
required to ask for anything.

A client MUST NOT send a `CredentialResponse` that was not solicited by
a `CredentialRequest`. An authority MUST reject one that was not.

## 2.3.3 Bounding the conversation

An authority MUST bound the number of rounds it will conduct and MUST
bound the time it will wait for a `CredentialResponse`. Neither bound is
fixed by this chapter, since both are policy. An authority that exhausts
either MUST terminate with `AccessDenied` carrying `ConversationLimit`
rather than closing silently, so that the client can distinguish a
policy limit from a crash.

## 2.3.4 Termination

Exactly one terminal message is sent. After it, the authority MUST NOT
send anything further on that connection, and MUST close it.

A connection that closes without a terminal message is an *abnormal*
termination. A client MUST treat it as a failed logon and MUST NOT retry
automatically, since the reason is unknown and may be a policy refusal
the authority could not express.

---

# 2.4 What an Authority Must Not Trust

_Peios Specifications / PGSS / Logon_

> Nothing a client sends is trusted. Peer identity comes from the kernel, and every asserted field is a proposal to be constrained.

Nothing a client sends is trusted. This section states the rule once,
because every field in §2.7 is subject to it.

## 2.4.1 Peer identity

An authority MUST establish the connected peer's identity from the
**connected socket**, by reading the peer's token from the kernel. It
MUST NOT take the peer's identity from any message body, because there
is no field in which a client could put it that the client could not
also lie in.

An authority MUST NOT use `SO_PEERCRED` for this purpose. It answers a
similar-looking question and is the wrong answer: it returns the
*projected* UID, which cannot distinguish an authenticated principal
from an unauthenticated process running under the same projection, and
carries none of the token's SIDs, groups, integrity level or privileges.

> [!NOTE]
> On Peios many principals project to the same identifier, so a
> projected UID frequently identifies nobody in particular. Two
> different principals can share one. The peer token is the only thing
> that answers "who is this?" exactly.

## 2.4.2 Logon type

The authority MUST authorize Authenticate and Logon as distinct operations
against the verified caller token. A successful credential check alone does
not authorize token issuance. Disclosure authorization for Authenticate is
separate and precedes credential collection (§2.24).

`LogonStart.logon_type` is a **proposal**, not an instruction.

Only the caller knows whether an inbound connection is an interactive
shell or a batch command, so the caller has to be the one to say. But an
authority MUST constrain the proposal against what that verified peer is
permitted to request. Otherwise anything that can reach the socket can
mint itself an interactive session, and the logon type — which access
control decisions depend on — becomes a value chosen by the least
trusted party in the exchange.

## 2.4.3 Identifier

The identifier names the principal a logon is *for*. It is a claim about
who is being authenticated, and it is what the subsequent credential
exchange exists to test. An authority MUST NOT treat an identifier as
established until authentication has succeeded.

## 2.4.4 Everything else

`tty` and `remote_host` are unverified context. An authority MAY record
them, MAY use them in policy, and MUST NOT treat them as established
facts. A client that lies about its remote host is not prevented from
doing so by this protocol.

## 2.4.5 Access to the socket

Access to the logon socket MUST be controlled by a security descriptor.

It MUST NOT be controlled by process integrity level. PIP *can* gate a
socket, but using it here would require every future caller — a
graphical greeter, a web console, a remote access daemon — to be signed
at high trust merely to *collect a password*. Collecting a credential is
not a privileged act; deciding whether it is correct is, and that
decision happens on the other side of the socket.

The descriptor decides who may reach the socket, not what a peer may do
once there. Where it admits principals so that they can change their own
credential (§2.20) or enroll one (§2.23), it admits peers that may not originate logons, and
an authority MUST decide from each peer's identity whether it may
originate one.

Rate limiting is defense in depth. It is not the access control, and an
authority MUST NOT rely on it as such.

---

# 2.5 The Logon Channel

_Peios Specifications / PGSS / Logon_

> /run/logon.sock — the normative path, its access control, one conversation per connection, and why the channel does not multiplex.

## 2.5.1 Socket

An authority MUST listen on a `SOCK_STREAM` Unix domain socket at:

```
/run/logon.sock
```

The path is normative. It is the standard's path, not an
implementation's, and a client MUST NOT require configuration to find
it.

## 2.5.2 Access control

The socket MUST carry a security descriptor granting connect access to
the principals permitted to originate logons, to the principals
permitted to change their own credential (§2.20) or enroll one (§2.23),
and to those
permitted to end a logon session (§2.22). See §2.4 for why this,
and not process integrity, is the control — and why reaching the socket
is not, on its own, permission to originate a logon.

## 2.5.3 One conversation per connection

A connection carries exactly one conversation. The connection **is** the
conversation's identity.

There is therefore no correlation identifier in the header, and none is
needed: a message belongs to the conversation it arrived on. This
removes a class of error and attack — a forged or confused identifier
cannot attach a credential response to somebody else's logon, because
there is no identifier to forge.

It also bounds the credential's lifetime by the connection's, which
makes that the kernel's job to enforce rather than the authority's to
remember.

An authority MUST close the connection after sending its terminal
message. A client MUST close after receiving one.

A `ServiceAttest` (§2.19) is not a conversation and exchanges no
credential, but it is bound by the same rule: one per connection,
answered with one terminal message, and the connection closed. It is
carried here rather than on its own socket because it *is* a logon in
every respect except how the authority was satisfied — it creates a
session and mints a token — and because the volume is a handful of
requests at start-up rather than the sustained load §2.14 exists to
separate.

`SessionEnd` and `SessionEndQuery` (§2.22) are bound by the same rule:
one request per connection, one terminal message, and the connection
closed. They are here because ending a session is a decision about
logons, made by the party that created the session.

> [!NOTE]
> A protocol whose connections are long-lived and shared reaches the
> opposite conclusion, and multiplexes. PSI does (PSPU §2.7), and so
> does this chapter's own identity channel (§2.14). The difference is not
> inconsistency: a logon client's connection exists for one logon and
> is discarded, so paying for multiplexing here would buy nothing and a
> correlation identifier would only add something to forge.

## 2.5.4 Concurrency

An authority MUST serve conversations concurrently. A logon that stalls
— a principal who walks away mid-prompt — MUST NOT prevent other logons
from proceeding.

An authority MUST bound the number of conversations it will serve at
once, and MUST bound the time a conversation may remain open. Both are
policy; neither is fixed here.

## 2.5.5 Descriptor passing

The channel MUST support ancillary data (`SCM_RIGHTS`). The token is
transferred as a file descriptor alongside `AccessGranted` — see §2.9.

---

# 2.6 Message Framing

_Peios Specifications / PGSS / Logon_

> The header both channels share — magic, version, message type and size limit — and how a message body may be extended.

Both of an authority's channels use the framing specified here without
modification. The identity socket's departures are stated in §2.14; they
concern which message types are served where, not the encoding.

## 2.6.1 Header

Every message begins with a 12-byte header:

| Offset | Size | Field | Value |
|---|---|---|---|
| 0 | 4 | `magic` | `PGSL` (`50 47 53 4c`) |
| 4 | 2 | `version` | `5` |
| 6 | 2 | `msg_type` | See §2.A |
| 8 | 4 | `total_len` | Header plus body, in bytes |

`total_len` counts the header. A message is therefore self-delimiting
from its first 12 bytes, and a reader can size its buffer before reading
the body.

## 2.6.2 Magic

The magic MUST be checked on every message and MUST cause an immediate,
whole-connection failure when wrong.

This is not decoration. Peios protocols share this codec and this header
layout, and some of them share message bodies. A socket plugged into the
wrong daemon would otherwise *partially* work, which is far worse than
failing outright — a subtle misbehavior several fields in, rather than
a hard error on byte zero. A protocol reusing this codec MUST take a
distinct magic.

## 2.6.3 Version

A peer receiving a `version` it does not implement MUST refuse the
message. An authority MUST refuse with `AccessDenied` carrying
`UnsupportedVersion` where it can still encode one.

## 2.6.4 Size limit

A message MUST NOT exceed **65536 bytes** in total. A decoder MUST
reject a header declaring more, without reading the body, and MUST
reject one declaring fewer than the header's own length.

## 2.6.5 Message type

The high bit of `msg_type` marks a message sent by the **authority**.
Client messages have it clear. This is a readability property rather
than a security one — a peer MUST validate the message type it received
against what it expected, not merely against the direction bit.

## 2.6.6 Encoding

All multi-byte integers are little-endian.

**Strings** are UTF-8 and are **not NUL-terminated**. A string is
encoded as a `u32` byte count followed by exactly that many bytes. A
decoder MUST reject a string whose bytes are not valid UTF-8.

An empty string and an absent optional string are encoded identically,
as a zero byte count. A field documented as optional is therefore absent
when empty, and an implementation MUST NOT distinguish the two.

**Byte strings** are encoded the same way and carry no encoding
requirement.

**Arrays** are encoded as a `u32` element count followed by that many
length-framed structures. Every array in this chapter has a stated
maximum; an encoder MUST refuse to produce a longer one and a decoder
MUST reject one it receives. The same holds for every stated byte limit.

Two distinct length mechanisms therefore appear, and confusing them is
the most likely implementation error:

- **Byte strings and strings** are prefixed with a `u32` byte count, and
  the bytes follow immediately.
- **Structures and array elements** are prefixed with a `u32` byte count
  of the *whole structure*, and a decoder MUST skip to the structure's
  declared end after reading the fields it knows.

The second is what makes the format extensible.

## 2.6.7 Body extensibility

The body is a single length-framed structure, and **every structure and
every array element within it is length-framed too**.

A decoder reads the fields it knows and then skips to the structure's
declared end. A field appended by a newer peer is therefore stepped over
rather than mistaken for the next field — which is what makes the format
extensible *inside arrays*, where ignoring trailing bytes at the message
level would not help.

A structure that ends before a field an older encoder never wrote is not
an error. A decoder that reaches the end of a structure's body where an
optional trailing field would have been MUST substitute that field's
documented default (§2.7, §2.9) rather than failing.

The rules this keeps working under are binding on anyone revising this
chapter:

- Fields are **appended only**. Never reordered, never removed, never
  changed in meaning.
- A new field MUST be **optional with a safe default**, because older
  peers will not send it and will not read it.
- Adding a value to an enumeration is a **breaking change** and requires
  a version bump, because every peer is required to understand every
  value it is sent.

The last rule is the one that surprises people. An unknown enumeration
value cannot be safely ignored: a client that skipped an unrecognized
credential type would silently fail to collect something the authority
required, and an authority that skipped an unrecognized logon type would
grant the wrong kind of session.

There are exactly four exceptions, and each is stated where it applies:
`LogonStart.supported_credential_types`, which is a statement of
capability rather than an instruction (§2.7); `LogonStart.logon_type`,
which only the authority ever receives (§2.7); the field mask of
`Lookup`, whose reply says which bits it answered (§2.16); and a denial
code that only ever answers a message newer than every peer that does
not know it, so that no such peer is ever sent it (§2.B, §2.22, §2.23).

## 2.6.8 Diagnostic operation identifier

`CredentialRequest`, `AccessGranted`, `AccessDenied`, and `Authenticated` MAY
append an `operation_guid` byte string to their version-6 body fields. Absence
defaults to an empty string. An explicit empty string also means that no
identifier was supplied. A nonempty value MUST contain exactly 16 bytes in
the PCDS GUID byte layout and MUST NOT be the zero GUID.

The authority assigns this identifier to the operation. The identifier MUST
remain the same across that operation's replies. An authority MUST NOT copy
an upstream source's proposed identifier into this field as its own. Fields
added after this extension MUST follow `operation_guid`; they MUST NOT move it.

The identifier provides diagnostic correlation only. It conveys no identity,
credential proof, capability, access grant, or logon session. A client MUST NOT
change an authentication decision because this optional metadata is absent,
malformed, or inconsistent. It treats invalid correlation metadata as
unavailable while retaining the ordinary validation of the reply and its
credential or token result.

An authority MAY omit the field if diagnostic generation or message-size
bounds prevent including it. A client cannot require an identifier before
receiving a reply. Existing decoders skip the appended field through the
body's declared length. This extension introduces no message or enumeration
value and retains public framing version 6.

Authenticated can then append the source-owned credential binding in §2.24.
It follows the optional operation GUID slot, using an explicit empty GUID
field when necessary. These are distinct contracts: correlation is diagnostic
and cannot affect authentication; the credential binding records the specific
proof's reference and revision, without becoming proof or a capability.

## 2.6.9 Initial unpublished layout replacement

The coordinated SSH credential extension replaced the unpublished version-1
layout without retaining older codecs. Current LogonStart capability,
required-method and binding fields, Prompt parameters, and all current
Assertion fields are mandatory, including explicit empty/zero values.
Omitted mandatory fields fail decoding. The compatibility rules above apply
to future extensions of this replacement contract; they do not require
accepting the superseded development layout. See PGSS Logon §2.D.

Version 3 adds the mandatory claim-selection discriminator to AuthenticateStart
and the mandatory coverage discriminator to Authenticated (§2.24). It replaces
the unpublished version-2 public framing contract, without a compatibility
decoder. That development contract is superseded by version 4 below.
The separate principal-source protocol retains its own version.

Version 4 replaces the unpublished version-3 ASCII-only claim-name contract
with the KACS Unicode name rule (§2.24). Message body layouts are unchanged.
The framing version MUST still change: a Unicode-aware consumer MUST NOT
accept an older authority's named absence assertions. No compatibility
decoder is provided for that replacement.

Version 5 adds credential type 3, Mschapv2, and the mandatory length-framed
MSCHAPv2 success-output field in Authenticated (§2.24). The separate
principal-source protocol uses its own version 3 for the corresponding
source assertion output.

Version 6 adds credential type 4, Ntlmv2 (§2.11), and the mandatory
length-framed `ntlmv2_session_key` field in Authenticated (§2.24) and
AccessGranted (§2.9). AccessGranted's `profile` becomes mandatory, since
the new field follows it. Coordinated clients and authority MUST use
version 6. The principal-source protocol uses its own version 4 for the
corresponding source request and assertion fields.

---

# 2.7 LogonStart

_Peios Specifications / PGSS / Logon_

> The client's opening message — logon type, identifier, tty and remote host, and the credential types it can collect.

`msg_type` = `0x0001`. Client to authority. Opens the conversation; MUST
be the first message.

## 2.7.1 Layout

| Field | Encoding | Limit |
|---|---|---|
| `authentication` | nested length-framed AuthenticationRequest | §2.24 |
| `logon_type` | `u8` | §2.B |
| `tty` | string | 128 |
| `remote_host` | string | 256 |

Identifier, collection capabilities and method binding below belong to the
shared authentication structure. Logon adds only local session context.

Everything here is *asserted by the client*, and §2.4 governs all of it.

## 2.7.2 logon_type

The kind of session the client is asking for. **A proposal**, which the
authority MUST constrain against the verified peer — see §2.4.

Values are defined by KACS and listed for reference in §2.B.

### 2.7.2.1 The exception this field carries

A value MAY be added to this enumeration without a version bump. This is
the third departure from §2.6, and it turns on the same question that
rule turns on: which party has to understand the value. The rule binds
because every peer must understand every value it is *sent*, and
`logon_type` only ever travels client to authority. The authority is
therefore the only party that must understand a new one.

**An authority MUST refuse a `logon_type` it does not recognize**, with
`MalformedRequest` (§2.10). A message carrying a value the authority
cannot name is one it could not understand, and it is refused before
any question of what the peer is permitted arises.

Neither direction of mismatch is left to chance by that. An older client
never proposes a value it has not heard of, and a newer client proposing
one to an older authority is refused — so the failure is no session
rather than a session of the wrong kind, which is the outcome §2.6
exists to prevent.

## 2.7.3 identifier_type and identifier

Together these name the principal. `identifier_type` says how to read
`identifier`; `identifier` is **opaque bytes**, not a string.

Bytes rather than a string because an identifier is not always text. A
certificate thumbprint, a smartcard serial, or a binary principal name
are all reasonable identifiers, and a protocol that insisted on UTF-8
would exclude them. An authority that expects text MUST validate the
encoding itself.

An identifier MAY be empty. An empty identifier means *the principal is
not named here* — the authority is expected to determine it from the
credential, as with a smartcard that carries its own identity. Ntlmv2 is
the defined case: its request MUST name no principal, and its answer
does (§2.11).

`identifier_type` is distinct from `credential_type` (§2.8): this is the
claim of identity, that is the proof. A passkey names a principal and
proves them in one artefact; a username names them and proves nothing.

## 2.7.4 tty and remote_host

Unverified context, both optional, both empty when absent.

`tty` names the terminal the logon is happening on, where there is one.
`remote_host` names where a network logon came from.

An authority MAY use either in policy and MAY record either in its audit
trail. It MUST NOT treat either as established. A client that lies about
them is not prevented from doing so.

## 2.7.5 supported_credential_types

Every credential type this client can render, one byte each.

This is the client declaring its capabilities, and it is **binding on
the authority**: an authority MUST NOT send a prompt for a credential
type absent from this list (§2.8).

A client that supports nothing sends an empty list. That is meaningful
rather than degenerate — it says "I can complete a logon that requires
no interaction, and nothing else" — and an authority MUST either
complete the logon without prompting or deny it.

### 2.7.5.1 Mandatory capability and method fields

The capability list and following method/binding fields are mandatory in
the version-2 layout. Missing tails are malformed;
there is no absent-field Password default. An explicit empty list means
that the client cannot collect a credential.

A nonzero required method must appear in the capability list. The authority
rejects any source assertion that did not authenticate with that method.
The SSH binding is present exactly when SshPublicKey is advertised. It is
an enclosing length-framed structure containing 16 raw connection-ID bytes,
a session-identifier byte string (16–64 bytes), and a UTF-8 username
(1–256 bytes, no controls), equal to the Username identifier byte for byte.
Only the authorized SSH monitor may supply it; see §2.D.

**An unrecognized value is dropped, not refused.** A decoder MUST
discard a credential type it does not recognize and proceed with the
rest, leaving the intersection of what the client claims and what the
decoder understands. This is safe here and nowhere else, because the
field is a statement of capability rather than an instruction: an
authority that ignores a type it has never heard of merely declines to
use it, which is the correct outcome.

Without this, a client that learned a new credential type could not
speak to an older authority at all — the authority would be obliged by
§2.6 to refuse the whole message. The capability list exists precisely
so that an authority using a new type cannot reach an older client; it
would be self-defeating if a *client* using a new type could not reach
an older authority either.

---

# 2.8 Credential Exchange

_Peios Specifications / PGSS / Logon_

> CredentialRequest and CredentialResponse — messages, prompts, the client capability rule, and what an empty request means.

## 2.8.1 CredentialRequest

`msg_type` = `0x8001`. Authority to client.

| Field | Encoding | Limit |
|---|---|---|
| `messages` | array of *Message* | 8 |
| `prompts` | array of *Prompt* | 16 |

**Message:**

| Field | Encoding | Limit |
|---|---|---|
| `severity` | `u8` | §2.B |
| `text` | string | 512 |

**Prompt:**

| Field | Encoding | Limit |
|---|---|---|
| `credential_ref` | `u32` | — |
| `credential_type` | `u8` | §2.B |
| `credential_name` | string | 128 |
| `parameters` | length-framed bytes | 4096 |

Both arrays MAY be empty.

### 2.8.1.1 Messages

Text for the principal to read, before any prompt is presented. "Your
password expires in three days"; "Authenticating against the local
source".

A client MUST display messages it receives, in order, before the prompts
in the same request. It MUST NOT interpret them, and MUST NOT vary its
behavior on their content.

### 2.8.1.2 Prompts

Each prompt asks for one piece of credential material.

`credential_ref` identifies the prompt within the conversation. The
client echoes it back unchanged in its answer. It MUST be unique among
the prompts of a single request. An authority MAY reuse a value in a
later round.

`credential_name` is what to show the principal — "Password",
"Verification code". It is a display string. A client MUST NOT branch on
it; `credential_type` is what says how to collect the answer.

### 2.8.1.3 The client capability rule

An authority **MUST NOT** send a prompt whose `credential_type` is
absent from the client's `supported_credential_types` (§2.7).

This is a hard requirement rather than a courtesy. A client that
receives a prompt it cannot render has no good option: failing the logon
punishes the principal for a mismatch neither party chose, and *guessing*
— collecting a line of text for a credential type that is not a password
— may echo a secret to the screen. An authority that cannot proceed
within the client's declared capabilities MUST deny the logon instead.

A client that nevertheless receives an unrenderable prompt MUST fail the
conversation rather than guess.

### 2.8.1.4 Empty requests

A `CredentialRequest` with no prompts is valid. It carries messages
only, and the client MUST answer it with a `CredentialResponse` carrying
no answers. This is how an authority conveys information mid-conversation
without asking for anything.

## 2.8.2 CredentialResponse

`msg_type` = `0x0002`. Client to authority.

| Field | Encoding | Limit |
|---|---|---|
| `answers` | array of *Answer* | 16 |

**Answer:**

| Field | Encoding | Limit |
|---|---|---|
| `credential_ref` | `u32` | — |
| `data` | length-framed bytes | 32768 |

`credential_ref` MUST match a prompt from the request being answered.
`data` is the material the principal supplied — opaque bytes, no
encoding implied.

A client SHOULD answer every prompt it was given. An authority MUST NOT
assume it has: a missing answer is a failed logon, not a protocol
violation, and MUST be treated as such rather than as grounds to tear
down the connection.

An authority MUST match answers to prompts by `credential_ref` and MUST
NOT rely on ordering.

Both parties encode and decode this message under the obligations of
§2.12. The encoded message holds the credential just as much as the
`data` field inside it does.

> [!NOTE]
> A client that cannot collect an answer — the principal pressed escape
> — MAY send a response omitting it rather than closing the connection.
> That gives the authority the opportunity to deny cleanly with a reason
> the principal can read.

## 2.8.3 Typed parameters

Prompt parameters are mandatory, empty for Password, and carry the bounded
SshPublicKey disposition structure described in §2.D. They are protocol
input to the matching collector, never instructions to render or execute.
An ordinary password client must refuse an unsupported SSH prompt.

---

# 2.9 AccessGranted

_Peios Specifications / PGSS / Logon_

> The terminal success message — the token passed as a file descriptor and never named, the session id, and the profile that comes with it.

`msg_type` = `0x8002`. Authority to client. One of the two terminal
messages; nothing follows it.

| Field | Encoding | Limit |
|---|---|---|
| `session_id` | `u64` | |
| `profile` | length-framed structure | below |
| `ntlmv2_session_key` | length-framed bytes | 0 or 16 bytes |

**Ancillary data: the token, as one file descriptor via `SCM_RIGHTS`.**

## 2.9.1 The descriptor

The token MUST be transferred as a file descriptor attached to this
message. It MUST NOT be named, and there MUST be no path, handle, or
identifier by which another process could reach it.

Possession of the conversation is what confers the token. There is no
window in which a minted token exists under a name something else could
open, and no lookup that could be raced or guessed.

A client MUST read the descriptor from the ancillary data of this
message. An `AccessGranted` arriving without one is a protocol violation
and MUST be treated as a failed logon — a client MUST NOT proceed as
though a logon succeeded when it holds no token.

## 2.9.2 session_id

The logon session the token belongs to. The client MAY record it, MAY
report it, and needs it to relate this logon to the kernel's session
records.

It is informational to the protocol. The token is the thing that confers
authority; the session identifier merely names the session the token
already belongs to.

## 2.9.3 profile

Where the session starts, and what to call the principal. A
length-framed structure, so it can grow without displacing anything
appended to `AccessGranted` after it.

| Field | Encoding | Limit |
|---|---|---|
| `home` | string | 4096 |
| `shell` | string | 4096 |
| `display_name` | string | 256 |

`profile` is mandatory from version 6, because `ntlmv2_session_key`
follows it (§2.6). **Every field can be empty**, and an empty field means
*the authority did not say*. An authority that knows nothing about home
directories is conforming, and sends the structure with every field
empty.

A client MUST have a fallback for each field and MUST NOT treat an empty
value as an error.

`home` and `shell`, when non-empty, MUST be absolute paths. A client
MUST NOT execute a relative `shell` or resolve a relative `home` against
its own working directory. An authority with no value for a field MUST
leave it empty rather than invent one.

### 2.9.3.1 Why this is on the terminal message

Nothing here is an access-control input. No ACL names a home directory,
and the token carries none of these fields — so this is not identity,
and an authority that got it wrong would produce an inconvenient session
rather than an unsafe one.

It is here because the authority has just read these values in order to
decide the logon, and a caller that needs them in order to *start a
session* would otherwise have to ask a second time. A logon originator
cannot `chdir` or `exec` without them.

### 2.9.3.2 What this is not

It is not a directory lookup, and it MUST NOT be treated as one. It
answers for exactly one principal — the one who just authenticated — at
exactly one moment. It cannot answer for anybody else, it cannot answer
for a principal who never logged on, and nothing in this protocol says
what it means an instant later.

Resolving arbitrary principals to home directories or shells is §2.16's,
and a client that caches these values as though they had come from there
has misread them.

### 2.9.3.3 display_name

A human's name for a human to read.

It is deliberately **not** a GECOS field. GECOS is a comma-separated
`/etc/passwd` artefact carrying a name, an office, and two telephone
numbers in one string; a protocol that carried one would oblige every
client to parse it apart, and would tie this chapter to a file format it
has nothing to do with.

An implementation that must produce a GECOS field renders it *from*
this, not the other way round.

> [!NOTE]
> A client is not obliged to *use* any of this. Falling back to a fixed
> shell, or ignoring `display_name` entirely, is conforming. The fields
> exist so that a client which wants them does not need a second
> protocol.

## 2.9.4 ntlmv2_session_key

The NTLM `SessionBaseKey` when Ntlmv2 was verified (§2.11): exactly 16
bytes then, and empty for every other method. A client MUST fail the
logon on a missing or unexpected key, as it does on a missing token.

An originator serving a network protocol needs this key and the token
from the same exchange: the token decides what the principal can do, and
the key signs and seals what the protocol carries for them. Returning it
here avoids a second conversation, and a key that could be requested
separately from its token. It is exchange-specific and cannot be used to
authenticate again.

## 2.9.5 What the client does next

Installs the token, if that is what it wanted. The authority is not
involved and MUST NOT be told (§2.1).

A client that decides not to install the token MUST close the
descriptor. A logon session whose token is never installed still exists
as far as the kernel is concerned.

A client SHOULD NOT fail a logon because a `home` it was given does not
exist. The principal has authenticated and holds a token; refusing to
start their session over a missing directory turns a cosmetic problem
into being locked out. Starting elsewhere and saying so is the better
failure.

---

# 2.10 AccessDenied

_Peios Specifications / PGSS / Logon_

> The terminal failure message — a deliberately small denial vocabulary, and what a denial must never reveal.

`msg_type` = `0x8003`. Authority to client. The terminal failure message
of a logon, of a credential change (§2.20), of an enrolment (§2.23),
and of a request to end a
logon session or to ask whether one may (§2.22) alike; nothing follows
it.

| Field | Encoding | Limit |
|---|---|---|
| `denial` | `u32` | §2.B |
| `reason` | string | 512 |

## 2.10.1 denial

A code from a deliberately small vocabulary (§2.B), for a client that
needs to *act* differently — retry, offer a different account, report a
system fault.

`PermissionDenied` and `LogonTypeNotPermitted` are distinct on purpose:
the first says the peer may not use this socket for this at all, the
second that it may originate logons but not of this kind. A client can
act differently on each.

`NoSuchSession` answers only `SessionEnd` and `SessionEndQuery`, and
only a caller who would otherwise have been permitted (§2.22). Anybody
else is told `PermissionDenied`, so the code cannot be used to learn
which sessions exist.

`CredentialRejected` answers only `CredentialEnrollStart`, and says the
credential offered or named was refused, not the principal's proof of
who they are (§2.23).

## 2.10.2 reason

Text for the principal to read. A client SHOULD display it and MUST NOT
interpret it.

The division is the same one `CredentialRequest` makes between
`credential_type` and `credential_name`: the machine-readable field is
small and stable, the human-readable one is free.

`reason` MUST NOT narrow an `AuthenticationFailed` into a specific
cause.

## 2.10.3 What a denial must not reveal

The denial vocabulary deliberately does **not** distinguish "no such
principal" from "wrong credential". Both are `AuthenticationFailed`.

A protocol that distinguished them would make account enumeration a
supported feature: anyone able to reach the socket could test names and
learn which exist. An authority MUST NOT provide that distinction
through the denial code, through `reason`, or through observable timing.

The timing obligation is the one most often missed, and it binds even
though this chapter cannot check it. An authority whose
unknown-principal path returns faster than its wrong-credential path has
published the distinction it just declined to state — see §2.12.

> [!NOTE]
> An authority MAY record the distinction in an audit trail an
> administrator can read. What it must not do is return it to the
> caller.

---

# 2.11 Credential Types

_Peios Specifications / PGSS / Logon_

> What a credential type tells a client to collect, why the registry is kept short, and why credentials cross the socket in the clear.

A credential type tells a client **how to collect** an answer. It does
not tell it what the answer means.

| Value | Name | Collection |
|---|---|---|
| 1 | Password | A line of text, not echoed |
| 2 | SshPublicKey | Bound SSH candidate or signature proof; §2.D |
| 3 | Mschapv2 | Relay a source-issued challenge and typed password proof |
| 4 | Ntlmv2 | Relay an authority-issued challenge; the answer names the principal |

The registry is deliberately short. A type is added when a client would
need to collect something differently, not when an authority acquires a
new way of checking something.

> [!NOTE]
> A one-time code is collected exactly as a password is — a line of
> text, not echoed — so it needs no new type. An authority asks for it
> with `credential_type = Password` and a `credential_name` of
> "Verification code". A hardware token that requires a challenge to be
> relayed to a reader *would* need a new type, because no existing
> collection method produces the answer.
>
> This is the test to apply: does an existing client, understanding only
> the types it already has, collect the right thing? If yes, no new type
> is needed.

## 2.11.1 Adding a type

The initial unpublished type-2 extension replaced the version-1 layout
and all consumers together (§2.D). Future incompatible changes to a
published contract require the version discipline in §2.6.

An authority MUST NOT send a prompt for a type absent from the client's
`supported_credential_types`, so an authority using a new type simply
cannot reach an older client — which is the correct outcome, and is why
the capability list exists. The converse — a newer *client* reaching an
older authority — is what the dropping rule in §2.7 exists for.

## 2.11.2 MSCHAPv2 collection

A Mschapv2 prompt MUST carry exactly 16 bytes in `parameters`: the
source-issued authenticator challenge. Its answer MUST contain exactly
40 bytes, peer challenge (16 bytes) followed by NT response (24 bytes).
The originator relays this exchange inside its authenticated TLS tunnel;
it MUST NOT substitute a password prompt or supply a stored NT hash.

Verification follows RFC 2759. The source binds the challenge to the
account, credential revision and bounded conversation, and rechecks
current eligibility before asserting success. ChallengeHash uses the
exact wire username spelling, excluding any domain prefix as required
by RFC 2759; account-name lookup equivalence does not change those bytes.
MSCHAPv2 proves the account password through a different mechanism and
MUST follow the source's password-authentication eligibility policy.

A successful general authentication returns the 20-byte binary
AuthenticatorResponse in `mschapv2_success` (§2.24). The source MUST NOT
export its reusable NT hash. Credential storage and opportunistic
population of NT material remain source policy, not collection protocol.

## 2.11.3 NTLMv2 collection

Ntlmv2 is the only **identity-in-answer** type. NTLM sends its challenge
before the client names the principal, so the principal is known only
from the answer. The rules in this section depart from the conversation's
usual order for that reason, and apply to no other type.

An Ntlmv2 request MUST carry an empty identifier and MUST require Ntlmv2
(§2.24). An authority MUST refuse, as malformed, an Ntlmv2 request that
names a principal, advertises Ntlmv2 without requiring it, or advertises
any other type alongside it.

### 2.11.3.1 The challenge

The **authority** issues the challenge, not a source. It MUST generate
eight bytes from a cryptographically secure random source, send them as
the `parameters` of a single Ntlmv2 prompt, and accept exactly one
answer to that prompt. A challenge MUST NOT be reused, MUST be discarded
when the conversation ends, and is never returned in any result.

An originator relays the challenge as the NTLM `ServerChallenge`. It MUST
NOT substitute a challenge of its own, and MUST NOT supply a stored NT
hash or a password in place of the client's proof.

### 2.11.3.2 The answer

The answer's `data` is this structure:

| Field | Encoding | Limit |
|---|---|---|
| `user` | length-framed bytes, UTF-16LE | 2–512 bytes |
| `domain` | length-framed bytes, UTF-16LE | 0–512 bytes |
| `nt_response` | length-framed bytes | 48–4096 bytes |

`user` and `domain` are the `UserName` and `DomainName` of the NTLM
AUTHENTICATE message, byte for byte. `nt_response` is its
`NtChallengeResponse`: the 16-byte `NTProofStr` followed by the
`NTLMv2_CLIENT_CHALLENGE` structure, whose `RespType` and `HiRespType`
MUST both be 1. An odd length, an unpaired surrogate, or an empty `user`
is malformed. Anonymous NTLM, which has an empty user and response, is
not supported. The LMv2 response is not carried; NTLMv2 does not need it.

### 2.11.3.3 Naming the principal

The authority decodes `user` to UTF-8 and applies §2.15 to it, with the
same refusals as any other identifier. While this specification defines
no realm syntax, `domain` selects no source: the authority MUST route on
the decoded user alone, and SHOULD record `domain` in its audit trail.

Ignoring the domain for routing does not weaken the proof. The client
binds `domain` into `ResponseKeyNT`, and the source verifies with the
bytes it received, so the domain the client used is still the domain it
proved. Clients fill it in unpredictably: often with the name the user
typed before a backslash, and sometimes with a name of the client's own
choosing. A server that refused unfamiliar domains would refuse those
clients and gain nothing in return.

> [!NOTE]
> This rule exists because there are no realms yet. When realm syntax
> arrives, the intended rule is that a domain naming a known realm routes
> to that realm, and any other domain routes to the default realm, so
> clients that send an unfamiliar domain keep working.

The authority then routes on the decoded user exactly as it routes an
identifier (§2.15), and offers the challenge and answer to that one
source. It MUST NOT offer them to any other source, including when the
owning source fails or is unavailable.

### 2.11.3.4 Verification

The source verifies the answer by MS-NLMP §3.3.2, using its stored NT
hash for the principal:

- `ResponseKeyNT` is HMAC-MD5 keyed with the NT hash, over the UTF-16LE
  concatenation of the uppercased `user` and `domain`. §2.15 limits
  names to printable ASCII, so ASCII uppercasing is what matters; any
  other code unit uses its Unicode simple uppercase mapping, as the
  closest available approximation of a Windows client. `domain` is used
  exactly as received.
- The expected `NTProofStr` is HMAC-MD5 keyed with `ResponseKeyNT`, over
  the challenge followed by `nt_response` after its first 16 bytes. The
  comparison MUST take constant time.
- On success, `SessionBaseKey` is HMAC-MD5 keyed with `ResponseKeyNT`,
  over `NTProofStr`.

The source binds the proof to the account and credential revision, and
rechecks current eligibility, as for MSCHAPv2. NTLMv2 proves the account
password through a different mechanism and MUST follow the source's
password-authentication eligibility policy.

A successful result carries the 16-byte `SessionBaseKey` in
`ntlmv2_session_key` (§2.9, §2.24). It is derived for this exchange
alone, cannot be used to authenticate again, and is what the originator
needs for NTLM key exchange and SMB signing. The source MUST NOT export
its NT hash or `ResponseKeyNT`.

The originator, not the authority or source, processes the rest of the
NTLM exchange: key exchange, the message integrity code, and the
`AvPairs` the client returned. Because those pairs sit inside the proven
`nt_response`, an originator MAY rely on them once the result arrives.

## 2.11.4 Why passwords cross the local socket in the clear

Passwords travel this local socket as **plaintext**. SSH public-key
authentication instead carries public keys and signatures; private keys
never cross it. Remote SSH transport encrypts both authentication methods.
The local password choice allows the source to retain a memory-hard
password verifier without requiring a password-equivalent secret.
An optional MSCHAPv2-compatible source deliberately accepts that storage
trade-off for compatibility with remote challenge-response clients.

Challenge-response requires the verifier to store something it can
recompute the response from: either the plaintext, or a value that is
*password-equivalent*. NTLM works exactly this way — the stored hash is
as good as the password, forever, which is why pass-the-hash has been
the most valuable credential on a Windows network for twenty years.

A modern verifier — argon2id and its relatives — is deliberately **not**
password-equivalent and cannot answer a challenge. That is the property
that makes stealing the store meaningfully weaker than knowing the
passwords.

So challenge-response would trade a permanent weakness at rest for
protection of a channel that is not the weak point. Anyone able to read
this socket can already `ptrace` the process holding the password.

### 2.11.4.1 What would change the answer

A PAKE — OPAQUE, SRP — gives both properties at once: nothing
password-equivalent at rest, and no plaintext on the wire. It is worth
revisiting if an authority ever authenticates **across a network without
TLS**.

It is not worth its complexity for a local, kernel-mediated socket,
where the threat it defends against is already able to do worse.

### 2.11.4.2 What follows

Because plaintext crosses the wire, bounding how long it survives
becomes an obligation of both roles rather than a nicety. See §2.12.

---

# 2.12 Credential Handling

_Peios Specifications / PGSS / Logon_

> The obligations that make plaintext on the wire defensible — bounded lifetime, zeroing, and what must never reach a log.

These bind both roles. They are stated normatively because plaintext on
the wire (§2.11) is only defensible if its lifetime is short.

## 2.12.1 Bounding lifetime

An implementation MUST hold credential material in memory that is
**erased before it is released**, and the erasure MUST NOT be removable
by an optimizing compiler.

The obligation extends to **the encoded message**, not only to the
credential field. A `CredentialResponse` holds the password just as much
as the answer inside it does, and a buffer wiped at one level while
another copy is dropped unerased achieves nothing.

An implementation MUST erase:

- the buffer credential material was read into;
- any buffer it was copied into during encoding or decoding, including
  an intermediate allocation abandoned by a buffer that grew;
- any structure holding it once the conversation reaches a terminal
  state.

The middle clause is the one an implementation is most likely to miss.
A growable buffer that reallocates while a message is being encoded
leaves a complete copy of everything written so far in the abandoned
allocation, and erasing the buffer that survives does not touch it.
Reserving the encoded size before writing avoids the problem entirely.

## 2.12.2 What this does not promise

It guarantees that *these* buffers are erased before their memory is
reused. It cannot guarantee anything about copies made elsewhere — a
string the caller parsed a credential out of, a register or stack slot
the optimizer chose, a terminal's own input buffer. Those belong to
whoever made them.

Nor does it defend against a hostile kernel, a core dump, or swap. Those
are addressed elsewhere: process integrity protection, and disabling
core dumps for the authority.

## 2.12.3 Logging and diagnostics

An implementation MUST NOT write credential material to a log, an audit
record, an error message, or a debugging aid.

A type carrying credential material SHOULD render, under whatever debug
formatting its language provides, as a redaction rather than as its
contents. A stray diagnostic print is the most common way material
escapes a process that was otherwise careful, and the defense is to make
the careless thing produce nothing useful.

## 2.12.4 Collection

A client MUST collect a `Password` without echoing it. Where it cannot
establish that echo is suppressed, it MUST NOT collect the credential
anyway.

A client MUST NOT silently truncate an answer. `data` admits 32768 bytes
(§2.8); a client whose collection method admits fewer MUST fail the
conversation rather than send a prefix of what the principal supplied,
which would present as a wrong credential and leave the remainder in
whatever buffer it was read from.

## 2.12.5 Timing

An authority MUST NOT allow the *time* it takes to reach a denial to
distinguish an unknown principal from a bad credential (§2.10).

This is more demanding than it looks with a memory-hard verifier,
because the natural implementation returns immediately when a principal
does not exist and spends tens of milliseconds when one does. An
authority MUST perform equivalent work in both cases — verifying against
a decoy verifier that no credential matches is the usual construction.

> [!NOTE]
> A decoy derived from randomness at start-up, rather than from a
> constant, is not merely unguessable but not stable between boots
> either. An implementation built this way runs exactly one verification
> on both paths, including for a principal that requires no credential
> at all.

---

# 2.13 Identity Lookup

_Peios Specifications / PGSS / Logon_

> The second half of the chapter — turning an identity you already hold into something displayable, on a second socket rather than a second standard.

Sections 2.3 to 2.12 specify how a caller obtains a token. The remainder
of this chapter specifies how any program on the system turns an
identity it already holds into something it can display or compare: a
name into a SID, a SID into a name, a POSIX identifier into either.

It exists because a Linux program calls `getpwuid` and has never heard
of a token. Without this surface, every principal an authority mints
appears throughout the system as a bare number.

## 2.13.1 Why the authority answers this

An authority may federate identity to separate sources, and a source
counts POSIX identifiers **relative to a range the authority assigns
it**. The authority adds the base. No message in either direction
carries an absolute identifier to or from a source: a source asserts
relative numbers, and is asked by relative number or by SID.

The arithmetic that makes a number absolute therefore exists in exactly
one place, and only that place can invert it. No source can be asked
"who is uid 1001000", because no source is ever asked an absolute
number at all. The authority is not merely a convenient place to put
this — it is the only party the protocol permits to answer.

The same holds for names. A bare name may exist in more than one source,
and which one wins is a property of the system rather than of any source
in it (§2.15).

> [!NOTE]
> An authority that keeps all identity in one built-in database still
> satisfies this, and for it the rebasing question does not arise. The
> requirement is on the answer, not on how the answer is reached — as
> everywhere else in this chapter.

## 2.13.2 A second socket, not a second standard

Identity lookup is served on `/run/ident.sock` (§2.14), separately from
`/run/logon.sock`, by the same authority speaking the same framing
(§2.6).

The separation is **not** for isolation. One authority answers both, so
a defect or a hang in either reaches the other regardless; a second
socket buys nothing there and this chapter does not pretend otherwise.

It is for **admission**. A listening socket has one accept queue. A
single directory listing is thousands of lookups and a filesystem walk
is millions, where logons are a handful per boot — so a shared socket
would let an ordinary `find` fill the queue that an administrator needs
in order to sign in and stop it. Two sockets means the two populations
of caller cannot starve each other, whatever load either is under.

The second reason is access control. The set of programs that may
originate a logon is small and enumerable; the set that may look up a
name is every program on the system. Those want different security
descriptors, and a descriptor is a property of a socket.

## 2.13.3 Not a conversation

A logon is stateful: the connection *is* the conversation, and needs no
correlation identifier (§2.5).

A lookup is not. Requests are independent, a connection carries as many
as a client cares to send, and replies MAY return in an order other than
the one requests arrived in. Each request therefore carries a `tag` that
its reply echoes (§2.14).

> [!NOTE]
> That is what allows an authority to satisfy several outstanding
> requests from one connection together — against a remote source, in a
> single query — without a delay window that would tax a caller waiting
> on a single answer. Nothing here requires it, and an authority that
> answers strictly in order, one request at a time, is fully conformant.

## 2.13.4 Not authentication

No credential ever crosses this socket. There is no message with which a
client could offer one and none with which an authority could ask.

Everything here returns the kind of data a POSIX system has historically
kept in a world-readable file. An authority MAY nonetheless restrict
individual fields (§2.16), and the request names the fields it wants
precisely so that it can.

## 2.13.5 Not in this version

**Privileges, integrity levels, owner and default DACL are not returned
by any message here.** They are not identity: nothing stores them, and
an authority computes them from local policy at the moment it derives a
token (§2.1).

They are, however, deliberately *reserved* rather than excluded. An
authority that cannot be asked what a policy would produce can only be
verified by signing someone in and observing the result. A future
revision is expected to add a distinct request of the shape:

```
Evaluate { key, logon_type } -> { privileges, integrity, owner, default_dacl }
```

— a token that is derived and then discarded. It is parameterised by
logon type because the answer genuinely depends on it: an authority adds
SIDs reflecting *how* a principal signed in (§2.16), so "what privileges
does this principal have" has no single answer.

A revision MUST NOT instead add privileges or integrity as fields of
`Lookup` (§2.16). A field of a record describes something a source
holds; this does not.

---

# 2.14 The Identity Channel

_Peios Specifications / PGSS / Logon_

> /run/ident.sock — its path, access control, framing, multiplexing and bounds, and why it carries no descriptors.

## 2.14.1 Socket

An authority MUST listen on a `SOCK_STREAM` Unix domain socket at:

```
/run/ident.sock
```

The path is normative, for the same reason `/run/logon.sock` is: a name
resolver linked into every process on the system cannot be asked to find
it by configuration.

An authority MUST listen on both sockets. Offering one without the other
is not conformance — a system whose principals cannot be named is as
broken as one whose principals cannot sign in.

## 2.14.2 Access control

The socket MUST carry a security descriptor granting connect access to
every principal that runs ordinary programs.

This is the opposite posture to `/run/logon.sock`, and deliberately so.
A descriptor that withheld connect access would not protect anything: it
would make `ls -l` print numbers for the principals it excluded, while a
principal who *can* connect learns the same names either way.
Restriction, where an authority wants it, belongs on individual fields
(§2.16) — not on reaching the socket at all.

## 2.14.3 Framing

Messages use the header, magic, version, size limit and body
extensibility rules of §2.6 without modification. The message types
served here are disjoint from those of the logon socket (§2.A).

A message of one socket's range arriving on the other MUST be refused.
An authority MUST NOT serve a `Lookup` received on `/run/logon.sock`,
and MUST NOT serve a `LogonStart` received on `/run/ident.sock`.

> [!NOTE]
> Sharing the magic is what makes that a clean refusal rather than a
> parse failure. A peer connected to the wrong socket gets "this message
> is not served here" from byte six, instead of discovering the mistake
> several fields into a structure it has misread.

## 2.14.4 Multiplexing

A connection carries any number of requests. A client MAY have more than
one outstanding at a time, and an authority MAY answer them in any
order.

Every request carries a `tag`, a `u32` chosen by the client, and its
reply carries the same value. The tag is **in the message body**, not
the header, so that the header of §2.6 is unchanged.

A client MUST NOT reuse a tag while a request bearing it is outstanding.
An authority MUST echo the tag it received and MUST NOT interpret it
otherwise.

A client MUST NOT assume replies arrive in request order. An authority
that answers strictly in order is conformant; a client that depends on
it is not.

> [!NOTE]
> The contrast with §2.5 is deliberate rather than inconsistent. A logon
> connection exists for one logon and is discarded, so multiplexing
> would buy nothing and a correlation identifier would only add
> something to forge. A lookup connection is opened by a name resolver
> that may issue thousands of requests, and the identifier costs four
> bytes.

## 2.14.5 Concurrency and bounds

An authority MUST serve connections concurrently, and MUST NOT let a
slow answer on one connection delay answers on another.

An authority MUST bound the number of connections it will accept and the
number of requests it will hold outstanding per connection, and SHOULD
refuse further requests on a connection that exceeds the second rather
than closing it.

An authority MUST NOT wait indefinitely for a source. A request that
cannot be answered within the authority's own bound MUST be answered
`Unavailable` (§2.18). The bound is on the request, not on each source
consulted: an authority that walks several sources in turn MUST NOT let
the total exceed what it would have allowed one.

## 2.14.6 No descriptor passing

Nothing is transferred over this channel by descriptor. An authority
MUST ignore ancillary data received here.

## 2.14.7 Peer identity

An authority that restricts any field (§2.16) MUST establish peer
identity from the connected socket's peer token, as §2.4 requires, and
MUST NOT take it from a message body.

An authority that restricts no field MAY skip establishing peer
identity, since it would make no decision with it.

---

# 2.15 Names and Resolution

_Peios Specifications / PGSS / Logon_

> A name is opaque to the client — comparison, reserved characters, qualified names, and the search order an authority applies.

## 2.15.1 The name is opaque to the client

A name is carried as a single string. A client MUST forward what it was
given, unchanged, and MUST NOT parse, split, qualify, case-fold, or
otherwise interpret it.

All interpretation is the authority's.

This is the load-bearing rule of the section. If a client resolved part
of a name itself — chose which source to consult, or which of two
candidates wins — then that policy would live in every client
separately, and a native tool could resolve `jack` to a different
principal than a POSIX name resolver on the same machine. Two components
disagreeing about who a name refers to is not a display inconsistency;
it is a program acting on one principal's behalf while checking
another's access.

One authority means one answer, and it means a name resolves identically
here and in a logon (§2.7), because the same resolution serves both.

## 2.15.2 Comparison

Name comparison is **ASCII case-insensitive**.

This is normative rather than each source's own choice, because a system
may have more than one source and they must not disagree about whether
`JACK` is `jack`. An authority MUST establish the comparison for itself
rather than delegate it to whatever a source happens to do.

## 2.15.3 Reserved characters

A principal or group name MUST NOT contain any of:

| Character | Reserved for |
|---|---|
| `@` | Qualified names (below) |
| `\` | Qualified names, in the form some callers will type |
| `/` | Path separation — a name reaches a filesystem as a home directory |
| `:` | Field separation in POSIX `passwd` and `group` records |
| `,` | Member and subfield separation in POSIX `group` and GECOS records |

A name MUST NOT contain a byte outside the printable ASCII range
`0x20`–`0x7e`, and MUST NOT begin or end with a space.

An authority MUST refuse to create a name violating these rules, MUST
refuse one it is asked to resolve, and MUST refuse one asserted by a
source. The third is the one that matters: a name reaching a caller from
a source has crossed a boundary the other two never did, and it is the
one that ends up in a `passwd`-format record, an audit line, or a log.

The excluded control characters are the record separators. A name
carrying a newline could forge a whole line in a `passwd`-format file,
an audit record, or a log — and the damage is done by the reader, so it
cannot be prevented at the point the name is displayed.

The rules apply to every name an authority emits, including the names
carried alongside SIDs in references (§2.16), not only to the name a
request was keyed on.

> [!NOTE]
> The ASCII restriction is not an assumption that names are English. It
> is a decision to defer confusable and normalization handling rather
> than get them wrong: `jack` spelled with a Cyrillic `а` renders
> identically to `jack` and is a different principal, and the same name
> in NFC and NFD is two byte sequences that a comparison will call two
> people. Relaxing this later is backward compatible; tightening it
> later would mean renaming principals that already exist.

## 2.15.4 Qualified names

A name MAY be qualified with a realm, written `name@realm`.

**No realm syntax is defined in this version.** An authority MUST refuse
a name containing `@`, and the character is reserved so that a principal
literally named `jack@local` cannot come into existence before the
syntax does.

Nothing here changes when realms arrive: a qualified name is a different
string in the same field, parsed by the same authority. That is why the
field is one opaque string rather than a structured pair — a structure
would have put the parsing in the client, which the first rule of this
section forbids.

## 2.15.5 Search order

A bare name is resolved by consulting sources in an order that is
**local configuration of the authority**.

An authority MUST resolve in a configured order, MUST NOT derive that
order from the order in which sources registered, and MUST stop at the
first source that answers.

> [!NOTE]
> Registration order is whatever the boot happened to do. Making it
> decide who `jack` is would mean a slow disk could change which
> principal a name refers to.

## 2.15.6 Answers an authority holds itself

An authority MAY answer from its own knowledge, without consulting any
source. Well-known principals and groups — those whose SIDs are fixed by
the system rather than issued by anybody — are the ordinary case: their
names, and, for those whose membership is a rule, the fact that nothing
records it (§2.16), are properties of the system. Who is in a `BUILTIN`
group is not: it is recorded by the sources, and asked of them (§2.16).

Such an answer is subject to every rule in this section. In particular
an authority MUST apply the reserved-character and comparison rules to
it, and MUST NOT return an answer for a name it would have refused.

An answer of this kind is not an outage and does not make a reply
`Unavailable`, whatever the state of the configured sources. It is also
not a source: an authority MUST NOT report it in the `incomplete` list
of an enumeration (§2.17), and MUST NOT count it as a source having
answered for the purpose of §2.18.

## 2.15.7 Bare in, qualified out

Every successful reply carries the resolved **SID** and the **canonical
qualified name**, whatever form the request used (§2.16).

A caller that looked up a bare name can therefore always tell which
principal it got, compare two answers for identity, and record an
unambiguous name in a log. Ambiguity is permitted in what a caller may
ask; it is not permitted in what an authority answers.

Where no realm syntax exists, a canonical qualified name is
indistinguishable from a bare one, and the SID alongside it is what
carries the unambiguity. A client MUST NOT rely on the two being
distinguishable, in either direction: it MUST NOT assume a returned name
is unqualified, and MUST NOT treat one that is as a failure to
canonicalise.

## 2.15.8 Shadowing

Adding a source ahead of another in the search order changes which
principal a bare name resolves to. The new principal has a different
SID, so every security descriptor naming the old one stops applying to
the person now signing in under that name.

This is inherent to a flat namespace and this chapter does not forbid
it. An authority SHOULD detect it at logon — where the cost is one
additional query per sign-in rather than one per lookup — and SHOULD
record that a bare name resolved while another source could also have
answered.

An authority MUST NOT fail a logon because it could not complete that
check. A source being unreachable is not a reason to refuse a principal
whose own source answered.

---

# 2.16 Lookup

_Peios Specifications / PGSS / Logon_

> One request that answers every question a name resolver asks — keys, fields, memberships, and the present/withheld distinction.

One request answers every question a name resolver asks.

## 2.16.1 Lookup

`msg_type` = `0x0010`. Client to authority.

| Field | Encoding | Limit |
|---|---|---|
| `tag` | `u32` | §2.14 |
| `key_type` | `u8` | §2.B |
| `name` | string | 256 bytes |
| `sid` | length-framed bytes (SID) | 68 bytes |
| `unix_id` | `u32` | |
| `kind` | `u8` | §2.B |
| `fields` | `u32` | §2.B |

Exactly one of `name`, `sid` and `unix_id` is meaningful, selected by
`key_type`. An encoder MUST leave the others empty or zero, and a
decoder MUST ignore them.

### 2.16.1.1 key_type

| Value | Name | Answers |
|---|---|---|
| 1 | `Name` | `getpwnam`, `getgrnam` |
| 2 | `Sid` | Rendering a security descriptor |
| 3 | `UnixId` | `getpwuid`, `getgrgid` |

`UnixId` is a key even though **no source is ever asked one**. An
authority converts the number to a source and a relative identifier by
the range arithmetic it assigned, and asks that source by relative
identifier or by SID.

A source therefore never receives an absolute number here, exactly as it
never receives one during a logon. The property that made the authority
the only possible answerer (§2.13) is the same property that keeps this
side of it confined.

### 2.16.1.2 kind

| Value | Name |
|---|---|
| 0 | `Any` |
| 1 | `Principal` |
| 2 | `Group` |

A request for `Principal` MUST NOT be answered with a group, and a
request for `Group` MUST NOT be answered with a principal. Where the key
matches only an object of the other kind, the outcome is `NotFound`
(§2.18).

An authority MUST establish this for itself. Where the object came from
a source, the authority MUST check the kind it received against the kind
that was asked for, rather than relaying the source's answer and letting
the client discover the mismatch.

> [!NOTE]
> POSIX keeps users and groups in separate namespaces, so `getpwnam` and
> `getgrnam` can be asked the same string and expect different objects.
> Carrying the kind on the request is what lets both be served correctly
> without requiring an authority to forbid the collision.

### 2.16.1.3 fields

A bitmask of the attributes the reply should carry. Identity is not
among them: every successful reply carries the SID, the canonical
qualified name, and the kind actually found, and a client cannot decline
them.

| Bit | Name | Value encoding |
|---|---|---|
| 0 | `UNIX_ID` | `u32` |
| 1 | `PRIMARY_GROUP` | reference |
| 2 | `HOME` | string, 4096 bytes |
| 3 | `SHELL` | string, 4096 bytes |
| 4 | `DISPLAY_NAME` | string, 256 bytes |
| 5 | `GROUPS` | array of references, 128 |
| 6 | `MEMBERS` | array of references, 256 |
| 7 | `CLAIMS` | array of claim entries, 64 |
| 8 | `ENABLED` | `u8` |
| 9 | `LOGON_TYPES` | `u32` |
| 10 | `DESCRIPTION` | string, 1024 bytes |
| 11 | `CREDENTIAL_BINDINGS` | array of binding entries, 64 |

An authority MUST ignore a bit it does not implement, and MUST NOT
report it (below). Claim entries use the claim attribute format PCDS
§5.9 specifies.

`LOGON_TYPES` is a bitmask over the logon type values of §2.B: bit *n*
set means the principal may be used for logon type *n*. **Zero means the
holder states nothing**, not that nothing is permitted — a source that
predates the field sends zero, and an authority that read that as "no
logon permitted" would lock every principal on every existing system out
at once.

An authority substituting a default for zero MUST NOT include `Service`
in it. A principal that has never said how it may be used has certainly
not said it may be used for a credential-free service logon (§2.19).

`DESCRIPTION` says what a group is for, in words for a person to read,
on one line. A group with none is answered with an empty string: it has
no description, which is an answer. A principal has none, and the field
is withheld as `Absent` (below). An authority answers it for its own
well-known groups as well as relaying a source's.

`CREDENTIAL_BINDINGS` lists source-owned references and revisions for currently
eligible tracked credentials. Each length-framed array entry contains one
length-framed byte string of exactly 32 bytes: reference `[16]`, then revision
`[16]`. Both MUST be nonzero. References MUST be unique within the principal's
list. Comparison is opaque equality, scoped to that authoritative principal
SID; clients MUST NOT order revisions or treat either part as authority.

A present empty list establishes no eligible tracked binding. An unreported,
restricted, declined or oversized field establishes no such absence. A group
with no credential bindings is answered `Absent`. Disclosure requires the
existing Authenticate permission; ordinary name or membership resolution does
not grant it. It introduces no additional credential-operation permission.

The source MUST persist a binding before exposing it, and update its revision
atomically with actual credential replacement. Storage maintenance that does
not replace the underlying credential MUST NOT rotate it. A successful fresh
authentication can establish a proved binding (§2.24); lookup cannot advance
the revision that an existing session proved. These values convey no hash,
private key, bearer capability or proof of possession.

> [!NOTE]
> Field bits are the one place in this chapter where an enumeration may
> grow without a version bump (§2.6). It is safe here, and only here,
> because the reply says which fields it is answering: an older
> authority ignoring a newer bit is reported as not implementing it,
> rather than silently omitting something a client believed it had asked
> for.

Requesting only what is wanted is not primarily a bandwidth measure — a
`getpwuid` wants nearly every field anyway. It matters for the caller
that resolves a dozen SIDs to render a security descriptor and wants
only names, and it is the seam at which an authority can restrict
individual fields without restricting the socket (§2.14).

### 2.16.1.4 Claim disclosure

An authority MUST apply its claim-read policy to `Lookup` and `Enumerate`,
including enumeration of a group's members. A second interface MUST NOT
bypass a claim restriction enforced during `Authenticate` (§2.24).

`CLAIMS` requests the complete field, not a selection of claim names. Authd
requires an unscoped ReadClaim grant in AuthenticationSecurity and checks
each returned claim against its object ACEs. A grant for selected claim
names alone does not authorize this field. If a check fails, authd withholds
the complete field as `Restricted`; it does not return a partial array.
Without the unscoped grant, authd does not ask the source for claims and
reports `Restricted` independently of whether claims exist.

Authd establishes permission from the querying caller's peer token, without
collecting an account credential or requiring Authenticate or Logon access.
The same descriptor snapshot covers the complete request or enumeration
page. A later request on the connection captures a fresh snapshot. Unusable
policy restricts claims without preventing ordinary identity resolution.
Name, SID, number and membership lookup remain public.

## 2.16.2 LookupReply

`msg_type` = `0x8010`. Authority to client.

| Field | Encoding | Limit |
|---|---|---|
| `tag` | `u32` | §2.14 |
| `outcome` | `u8` | §2.B |
| `sid` | length-framed bytes (SID) | 68 bytes |
| `qualified_name` | string | 512 bytes |
| `kind_found` | `u8` | §2.B |
| `present` | `u32` | §2.B |
| `withheld` | array of withheld entries | 32 |
| `values` | array of length-framed values | 32 |

Where `outcome` is not `Found`, everything after it MUST be empty or
zero, and a client MUST NOT read it.

`kind_found` MUST be `Principal` or `Group`, never `Any`.

### 2.16.2.1 present, withheld and values

`values` holds one length-framed value for each bit set in `present`, in
**ascending bit order**. Each is length-framed so that a client can step
over a value whose field it does not recognize.

Every bit set in the request is in exactly one of three states:

- **set in `present`** — its value is in `values`;
- **listed in `withheld`** — with a reason, below;
- **in neither** — this authority does not implement the field.

The third state is a statement about the authority, not about the
object. An authority that implements a field MUST place every request
for it in one of the first two states, whatever happened underneath: a
field an authority supports but could not obtain is `Absent`,
`Declined`, `Restricted` or `TooLarge`, never silence. Reporting it as
neither would tell the client the authority cannot answer that question
at all, and a client is entitled to stop asking.

A withheld entry is a length-framed structure:

| Field | Encoding | Limit |
|---|---|---|
| `field` | `u32` | one bit, §2.B |
| `reason` | `u8` | §2.B |

| Reason | Meaning |
|---|---|
| `Absent` | The field has no value. |
| `Restricted` | The caller may not have this field. |
| `Declined` | The source will not produce it. |
| `TooLarge` | It exists and exceeds one reply. Use `Enumerate` (§2.17). |

Distinguishing these is the point of the structure. An empty member list
and a source that refuses to enumerate members are the same bytes to a
POSIX caller, and an administrator diagnosing a system needs to know
which one happened.

### 2.16.2.2 References

`PRIMARY_GROUP`, `GROUPS` and `MEMBERS` carry references rather than
bare SIDs:

| Field | Encoding | Limit |
|---|---|---|
| `sid` | length-framed bytes (SID) | 68 bytes |
| `name` | string | 512 bytes |
| `unix_id` | `u32` | |

An empty `name` means the authority has no name for that SID; a
`unix_id` of **zero** means it has no number for it. Both are ordinary
answers for a SID belonging to no source on this machine.

Zero is the only encoding of "no number". An authority MUST NOT
substitute a POSIX identifier that a caller could mistake for a real
one — a projection onto `nobody` is a rendering decision belonging to
whatever produces a `passwd` record, and putting it on the wire
destroys the distinction the client needs in order to make it.

Carrying the name is what keeps the round-trip discipline below intact.
A reply of bare SIDs would make a single `getgrnam` into one request
plus one per member.

## 2.16.3 Memberships

`GROUPS` on a principal is the membership question, and it is the
direction sources actually hold — the same one a logon uses. An
authority MUST answer it whenever it can answer anything about the
principal at all.

`MEMBERS` on a group is the reverse index, and it is not owed the same
guarantee.

An authority MUST return `MEMBERS` as withheld, rather than as an error
or an empty list, when it will not or cannot produce it:

- **`Declined`** where the source will not enumerate the group's
  members.
- **`TooLarge`** where the membership exceeds what one reply can carry.
- **`Absent`** where the group is not one that has recorded members at
  all.

That last case is not a limitation. A group's membership may be
**recorded** — held by a source, as a local group's is — or it may be a
**rule** an authority applies when it derives a token. Nothing records
who belongs to `Everyone`; an authority adds it to every token it mints.
Groups reflecting *how* a principal signed in are further still from a
recorded membership: they are properties of a logon rather than of a
principal, and the same principal is in one at a console and not over a
network.

An authority MUST report `Absent` for such a group rather than
manufacturing a list, and MUST NOT report `Declined`, which would
suggest an answer exists somewhere.

### 2.16.3.1 The BUILTIN groups

The `BUILTIN` groups (`S-1-5-32-…`, such as `Administrators`, `Users`
and `Guests`) are well-known, and the authority answers for them
itself (§2.15), but their membership is **recorded**, not a rule.
"`jack` is in `Administrators`" is a record a source keeps on this
machine's behalf (PSPU §2.19), as it keeps a local group's.

For `MEMBERS` on a `BUILTIN` group, an authority MUST therefore gather
the members each source records, from every source in its search order
that is permitted to assert memberships outside its domain (PSPU §2.19),
and MUST NOT report `Absent`. A source without that permission records
none that a token would carry, and is not asked.

- Where every such source answered and the list fits one reply, the
  members are present, in source order.
- Where it will not fit, `MEMBERS` is withheld as `TooLarge`, and the
  members are walked with `Enumerate` (§2.17).
- Where a source in the order could not be reached, or would not
  enumerate, `MEMBERS` is withheld as `Declined`. A list missing one
  source's members would look complete.

> [!NOTE]
> This asymmetry is deliberate and follows the shape of the data. "Which
> groups is this principal in" is answered by every source cheaply,
> because it is how memberships are stored. "Who is in this group" needs
> an index in the other direction, over a set that may be the whole of
> an organization — historically the reliable way to make a directory
> server fall over from a filesystem listing.

## 2.16.4 One round trip

An authority MUST be able to answer each of the following in a single
request:

| Caller wants | Request |
|---|---|
| A `passwd` record | `Lookup{key_type: UnixId or Name, kind: Principal, fields: UNIX_ID \| PRIMARY_GROUP \| HOME \| SHELL \| DISPLAY_NAME}` |
| A `group` record | `Lookup{key_type: UnixId or Name, kind: Group, fields: UNIX_ID \| MEMBERS}` |
| A principal's groups | `Lookup{key_type: Name, kind: Principal, fields: GROUPS}` |
| A name for a SID | `Lookup{key_type: Sid, kind: Any, fields: 0}` |

This is a design constraint on future revisions as much as a statement
about this one. A name resolver is called from every process on the
system, synchronously, and a field that cannot be fetched alongside the
record it belongs to turns one lookup into several.

---

# 2.17 Enumeration

_Peios Specifications / PGSS / Logon_

> Walking every principal or every member of a large group, with a cursor and no completeness guarantee.

`Lookup` answers about one object that a caller can already name.
Enumeration answers when it cannot: walking every principal on the
system, or every member of a group too large for one reply.

## 2.17.1 Enumerate

`msg_type` = `0x0011`. Client to authority.

| Field | Encoding | Limit |
|---|---|---|
| `tag` | `u32` | §2.14 |
| `kind` | `u8` | §2.B |
| `fields` | `u32` | §2.B |
| `of_key_type` | `u8` | §2.B |
| `of_name` | string | 256 bytes |
| `of_sid` | length-framed bytes (SID) | 68 bytes |
| `of_unix_id` | `u32` | |
| `cursor` | length-framed bytes | 256 bytes |

`kind` MUST NOT be `Any`. A caller enumerating is filling a `passwd` or
a `group` table, and the two are separate.

### 2.17.1.1 of

Where `of_key_type` is zero, the request enumerates every object of
`kind` that the authority knows.

Where it is non-zero, the named object MUST be a group, and the request
enumerates **that group's members**. This is the continuation path for a
`MEMBERS` field withheld as `TooLarge` (§2.16): the same answer, paged.
An authority that withholds `MEMBERS` as `TooLarge` MUST serve this
mode, since there is otherwise no way to obtain what it said existed.

A group's members are asked of the one source that holds the group. A
`BUILTIN` group is no source's, and its members are walked across every
source that may record them, in search order, as the whole table is
(§2.16); a source in the order that did not contribute is reported in
`incomplete`. A well-known group whose membership is a rule has no
members to walk, and is `NotFound` here.

> [!NOTE]
> Members are a field of `Lookup` for the common case and a mode of
> `Enumerate` for the large one, rather than a message of their own. The
> field keeps `getgrnam` to one round trip where the group is small,
> which is nearly always; this keeps the large case correct without a
> third request type or a partial member list, which would be worse than
> no list at all.

### 2.17.1.2 cursor

Empty on the first request. On a continuation it MUST be the `next`
returned by the immediately preceding reply.

A cursor is **opaque**. A client MUST NOT construct, parse or modify
one, and MUST NOT present one to a different authority or after
reconnecting.

An authority MUST reject a cursor it did not issue, or one it can no
longer honor, with `Malformed` (§2.18). It MUST NOT silently restart
the enumeration, and MUST NOT answer with an empty page and an empty
`next`: the first hands the caller a second copy of the beginning under
the impression it is continuing, and the second reports a truncated walk
as a complete one.

## 2.17.2 EnumerateReply

`msg_type` = `0x8011`. Authority to client.

| Field | Encoding | Limit |
|---|---|---|
| `tag` | `u32` | §2.14 |
| `outcome` | `u8` | §2.B |
| `entries` | array of entries | 256 |
| `next` | length-framed bytes | 256 bytes |
| `incomplete` | array of strings | 32 |

An entry is a length-framed structure carrying the same fields as a
successful `LookupReply` (§2.16), from `sid` through `values`.

An empty `next` means the enumeration is complete. A non-empty `next`
means there is more, **even if `entries` was empty** — an authority may
return a short or empty page while working through a source.

A client MUST continue until `next` is empty. A client MUST NOT infer
completion from an empty page.

A client MUST NOT report an enumeration as complete when it stopped for
any other reason. A transport failure, a timeout, or an outcome other
than `Found` mid-walk is a truncated enumeration, and a client that
presents it to its caller as the end of the list has manufactured an
empty system out of an outage — the same error §2.18 forbids on a single
lookup, at a scale where nothing records that it happened.

## 2.17.3 incomplete

Each string names a source that did not contribute: because it declined
to enumerate, or because it could not be reached.

An authority MUST list every such source. A client displaying an
enumeration SHOULD say that it is partial, and MUST NOT discard the list
without doing so.

> [!NOTE]
> A short list that looks complete is the failure this field exists to
> prevent. An administrator reading an account listing has no way to
> tell a machine with four principals from a machine whose directory did
> not answer, and the difference decides whether they are looking at the
> whole picture.

## 2.17.4 No completeness guarantee

An authority MUST NOT be required to enumerate.

A source may hold more principals than a reply, a page, or an
administrator's patience can carry, and a source backed by a remote
directory may be able to answer any single question while being quite
unable to answer all of them. `incomplete` is the honest outcome, not a
degraded one.

A caller MUST NOT treat enumeration as a way to test whether a principal
exists. `Lookup` answers that, exactly, at any scale.

---

# 2.18 Outcomes

_Peios Specifications / PGSS / Logon_

> The outcome every identity-channel reply carries — NotFound, Unavailable and Refused — and why these are not a security boundary.

Every reply on the identity channel carries an outcome.

| Value | Name | Meaning |
|---|---|---|
| 1 | `Found` | The request was answered. |
| 2 | `NotFound` | No such object, and every source that could have said so was asked. |
| 3 | `Unavailable` | A source that could have answered did not. |
| 4 | `Refused` | The caller may not make this request. |
| 5 | `Malformed` | The request could not be understood. |

Unlike the denial codes of §2.10, these are not a security boundary.
`NotFound` reveals that a name is unused, which is what a name lookup is
for.

An `EnumerateReply` carries an outcome on the same terms. An authority
MUST NOT report `Found` on a page it could not produce.

## 2.18.1 NotFound and Unavailable

**If any source that could have answered was unavailable, the outcome is
`Unavailable` — even if every source that did answer said no.**

This is the most important rule in this part of the chapter, and it is
stated normatively rather than left to implementations because it is
invisible when wrong.

An authority is expected to cache. A cache that is told `NotFound` will
store an absence, and if that absence was really a source being
unreachable, it has memoised an outage as a fact. The account comes back
when the source does; the cached answer does not. A principal is then
unable to sign in, or a file is shown as owned by a number, for as long
as the entry lives — with nothing in the system still recording that
anything failed.

`Unavailable` is not cacheable, and that is the whole of the difference.

An authority MUST NOT report `NotFound` unless every source in the
search order (§2.15) that could have answered was consulted and
answered. A source that does not serve lookups at all is not such a
source and does not need to be asked; a source that does, and could not
be reached, is.

> [!NOTE]
> The rule binds even where an authority does not cache, because its
> clients may. A name resolver is entitled to remember an answer for the
> length of a process, and it can only do that safely if the two are
> distinguishable.

## 2.18.2 Unavailable and the search order

An authority MUST consult sources in the configured order and MUST stop
at the first that answers, so an unreachable source **later** in the
order does not make an answer `Unavailable`. It was never going to be
asked.

An unreachable source **earlier** in the order does, even if a later one
holds a matching name — because the earlier source is the one whose
answer would have won.

> [!NOTE]
> Returning the later source's principal in that situation would be
> worse than failing. The name would resolve to a different SID than it
> does when the system is healthy, so access decisions would be made
> against the wrong principal precisely while something is broken.

## 2.18.3 Refused

Reserved for requests the caller is not permitted to make at all. A
restricted `CLAIMS` field does not refuse the request (§2.16).

It exists because the field mask (§2.16) is where restriction belongs,
and a request refused in its entirety needs an answer that is not
`NotFound`. An authority restricting a *field* MUST use the `Restricted`
withheld reason instead, and MUST still answer the rest of the request.

Because it is reserved, `Refused` MUST NOT be used for anything else. A
source that will not answer, a mode an authority has not implemented, or
a question it cannot serve are not the caller lacking permission, and
reporting them as `Refused` tells a client to stop asking on behalf of
this caller when the answer would be the same for every caller. Those
outcomes are `Unavailable`, `Absent`, or `Malformed` as the case
requires.

An authority MUST NOT use `NotFound` in place of `Refused` or of a
restricted field. Concealing a principal's existence from a caller that
may not read their shell protects nothing — the SID is already in the
file listing that prompted the lookup — and would make an authorization
decision indistinguishable from an empty system.

## 2.18.4 Timing

The prohibition in §2.10 on distinguishing an unknown principal from a
bad credential does not apply here. There is no credential, and
`NotFound` is an ordinary answer that this chapter states plainly.

An authority MUST NOT allow the *presence* of an answer in a cache to be
observable to a caller that would be refused the answer itself. Where no
field is restricted, nothing is refused, and the requirement is vacuous.

---

# 2.19 Service attestation

_Peios Specifications / PGSS / Logon_

> How a service manager obtains a token for a service it is launching — a request with no credential behind it, and the narrow conditions under which an authority may honor one.

`msg_type` = `0x0020`. Client to authority, on `/run/logon.sock`. A
complete request in one message; the authority answers with
`AccessGranted` (§2.9) or `AccessDenied` (§2.10) and nothing else
follows.

| Field | Encoding | Limit |
|---|---|---|
| `identity` | string | 128 |
| `service` | string | 256 |

A service has no human to prompt and no secret to present. This is the
message by which the component that launches services obtains a token
for one, and the whole of this section is about the conditions under
which an authority may answer it.

## 2.19.1 A service identity MUST NOT have a credential

An authority MUST NOT hold, store, or accept a credential for a service
identity, and MUST NOT offer a credential exchange for one.

This is not a convenience. A machine that could authenticate its own
services unattended would have to hold their secrets, so a credential
for a service identity implies a store of service credentials on every
machine that runs one — a structure that is read by anything which
compromises the machine, and which grants whatever those identities
were given. The requirement exists to make that structure impossible
rather than to make it careful.

What replaces the credential is *attestation*: the authority satisfies
itself about **who is asking**, and derives everything else.

## 2.19.2 Why this is not a `LogonStart`

A `LogonStart` (§2.7) followed by no credentials would encode the same
request. It is a separate message because the difference is structural
rather than cosmetic.

Accepting a credential-free `LogonStart` creates a path through an
authority's conversation handling on which **zero credentials
succeeds**. The only thing then standing between an arbitrary principal
and a credential-free token is the authorization check below being
correct — so a defect in that check is a complete authentication bypass
rather than a defect.

With a distinct message, the credential-free path is reachable only by
a message that carries no principal an authority would accept. The
check remains necessary; it stops being the only thing.

An authority MUST reject a `LogonStart` that completes without a
credential exchange for any identity it would accept here, and MUST
reject a `ServiceAttest` naming an identity it would accept there.

## 2.19.3 Who may send it

An authority MUST refuse a `ServiceAttest` unless **both** of the
following hold of the connected peer, each established from the
connection itself and never from the message:

1. The peer is a principal the authority permits to attest — this
   standard does not fix which, and an implementation SHOULD keep the
   set as small as one.
2. The peer is the process the platform designates as its service
   manager, established by a property of the connection that no other
   process can present.

Neither is sufficient alone, and an authority that checks only the first
has a much weaker rule than it appears to. On a system where platform
components share one identity — which is usual — the first condition
alone admits every daemon on the machine, so compromising any one of
them yields a token for any service identity the authority would mint.

An authority MUST answer a refusal with `PermissionDenied`.

> [!NOTE]
> On Peios the two facts are that the peer's token names SYSTEM, and
> that the peer is PID 1. The second is sound there for a reason
> specific to PID 1 — it cannot exit and be replaced while the system
> runs, and the credentials are captured by the kernel when the
> connection is made — and that reasoning does not extend to any other
> process identifier.

## 2.19.4 What the authority may attest

An authority MUST NOT mint a token under this message for a principal
that has not been designated as usable for a service logon.

The designation is a property of the principal, held wherever that
principal is held, and it is what keeps this message from being an
oracle that yields a credential-free token for anybody on the machine.
An authority that cannot determine whether a principal carries it MUST
refuse with `AccountRestricted`.

Identities the authority defines for itself — the platform's own service
identities, which no principal source holds and for which no credential
could exist — are designated by construction.

### 2.19.4.1 Peios virtual service accounts [*attestation.peios-service-is-a-virtual-account]

On Peios, `identity = "Service"` (case-insensitive) selects a distinct virtual
account whose user SID is the service SID derived from `service`. It uses the
same policy evaluation and Service logon groups as other attestations, without
LocalService or SYSTEM membership. The peer checks above precede this selection;
no credential-bearing logon is added. LocalService and NetworkService remain
available as shared account identities: their user SIDs are `S-1-5-19` and
`S-1-5-20`, respectively, while the derived per-service SID is a group.
For `Service`, that per-service SID is both user and group. The derived
groups are Everyone, Authenticated Users, Local and Service, plus the
kernel’s session-specific logon SID. Local policy determines privileges
and integrity for the resulting token.

A refusal here MUST NOT distinguish "no such principal" from "not
designated for service logon", for the reason given in §2.10.

## 2.19.5 `service`, and what the authority cannot check

`service` names the service being launched. The authority uses it to
derive the per-service identifier it stamps on the token, which is what
keeps two services running under the same identity distinguishable to an
access decision.

**An authority cannot verify it.** Elsewhere in this standard a peer's
claims are checked against the connection: an authority establishes who
is calling rather than believing what it is told. That is not available
here, because the process this request is about *does not exist yet* —
there is no token to interrogate and nothing to compare the name
against.

So `service` is taken on the peer's word. This is a genuine grant of
trust and it is not removable: the service manager holds the service
definitions, launches the process, and is the only component in a
position to know which service it is launching. It is the reason the set
of peers permitted to send this message is required to be as narrow as
it is.

An authority MUST reject an empty or unusable `service`, with
`MalformedRequest`. An empty name derives a well-formed identifier that
names nothing and that every service making the same mistake would
share.

## 2.19.6 The token

Answered with `AccessGranted` (§2.9), carrying the token as a descriptor
under the same rules as any other logon, and with the logon type
recorded as `Service`.

The `profile` structure SHOULD be empty. A service has no home
directory, no shell and no display name, and an authority that has
nothing to say MUST leave the fields empty rather than invent values.

### 2.19.6.1 The token is weaker, and MUST be

A token issued on attestation MUST NOT be usable to authenticate to
another system on this authority's behalf.

The evidence behind it does not travel. A credential a principal source
verified is evidence a second system could in principle have checked
too; a local process's word is evidence on one machine only, and a token
forwarded off the machine on the strength of it would let one system's
service manager act as an arbitrary account on another.

Where a platform expresses this as a level on the token, the level an
attested logon receives MUST be below the level a credentialled logon
receives, and MUST bound everything derived from that token.

An authority MUST record, in whatever it records for a credentialled
logon, that this logon was attested rather than authenticated. An audit
trail that cannot tell the two apart cannot answer which authority
vouched for a session.

---

# 2.20 Credential Change

_Peios Specifications / PGSS / Logon_

> How a principal changes their own credential — the opening message, why it names nobody, the proof it requires, and a terminal that mints nothing.

A principal changes their own credential by opening a conversation on
`/run/logon.sock` with `CredentialChangeStart`. The authority asks for
what it requires, in the rounds of §2.8, and ends the conversation with
`CredentialChanged` or `AccessDenied` (§2.10).

```
client                                   authority
  |                                          |
  |-------- CredentialChangeStart ---------->|   principal = the peer
  |                                          |
  |<--------- CredentialRequest -------------|   the current credential
  |---------- CredentialResponse ----------->|
  |                                          |
  |<--------- CredentialRequest -------------|   the new one
  |---------- CredentialResponse ----------->|
  |                                          |
  |<-- CredentialChanged --------------------|   terminal
  |         or AccessDenied                  |
```

Adding a credential beside the ones a principal has, such as an SSH
public key, or removing one, is the sibling conversation of §2.23.

Everything §2.3 says about the shape of a conversation applies
unchanged: one conversation per connection, bounded rounds, exactly one
terminal message. The client stays generic here as it does in a logon.
It renders the prompts it is given and returns the answers, and it does
not know what is being changed or how.

## 2.20.1 CredentialChangeStart

`msg_type` = `0x0030`. Client to authority. Opens the conversation; MUST
be the first message.

| Field | Encoding | Limit |
|---|---|---|
| `supported_credential_types` | length-framed bytes, one `u8` per type | 32 |

`supported_credential_types` carries the meaning and the capability rule
of the §2.7 field of the same name. It binds the authority, and a
decoder MUST drop a value it does not recognize rather than refuse the
message.

Unlike the §2.7 field, it is not optional. This message is newer than
the rule that made that field optional, so there is no older client
whose silence needs a default. An authority MUST refuse a
`CredentialChangeStart` that ends before the field with
`MalformedRequest`.

## 2.20.2 Whose credential

The principal whose credential changes is the **user of the connected
peer's token**, established from the socket as §2.4 requires. The
message carries no identifier, and an authority MUST NOT change the
credential of any other principal in this conversation.

The absence of an identifier is deliberate. A field naming a principal
would let anything that can reach the socket ask to change anybody's
credential, with only knowledge of that credential in the way. That is a
guessing surface over every account the authority holds, open to every
principal the socket admits. Taking the principal from the token
confines each caller to their own account.

An authority MUST refuse, with `AccountRestricted`, a change for a
principal it holds no changeable credential for. That includes a service
identity (§2.19), a platform identity no source holds, and a principal
that authenticates with no credential at all.

## 2.20.3 Proof of the current credential

A token is not proof enough. An authority MUST establish, within the
conversation, that the principal can present their current credential
before it changes that credential, and MUST refuse with
`AuthenticationFailed` where they cannot.

A token shows that someone signed in. It does not show that the person
at the keyboard now is that person. An unattended terminal holds a token
too, and a credential changed from one cannot be recovered by signing in
again, because the credential needed to sign in is the one that changed.

`AuthenticationFailed` keeps the wording rule of §2.10 here: `reason`
MUST NOT say what was wrong with the credential. The caller cannot use
the distinction to learn about another account, since only their own is
reachable, but a reason that varied would still tell a guesser which
part of a guess was right.

## 2.20.4 The new credential

What the authority asks for, and what it accepts, is its own policy. An
authority that refuses a proposed credential MAY say why in a message of
`Error` severity (§2.8) and ask again, within its round limit. An
authority that gives up MUST end the conversation with
`ConversationLimit`.

The new credential is credential material like any other. It is
collected and handled under §2.12, and the client neither knows nor
cares that it is new.

## 2.20.5 CredentialChanged

`msg_type` = `0x8030`. Authority to client. The successful terminal
message; nothing follows it.

It has no fields and no ancillary data. A change mints no token and
creates no session: the caller already holds a session, and the change
leaves it as it was. A client MUST NOT expect a descriptor with this
message, and MUST close one if one arrives.

An authority MUST NOT send `CredentialChanged` until the new credential
is the one a subsequent logon will be tested against. A principal told
about a change that is not yet durable can lose it, and finds out only
when the old credential works and the new one does not.

What a change does to sessions already established is the authority's
policy. This chapter specifies none.

## 2.20.6 Access to the socket

Every principal permitted to change their own credential needs connect
access to `/run/logon.sock` (§2.5), and most of them may not originate a
logon. The socket's descriptor therefore admits both kinds of peer and
cannot tell them apart. An authority whose descriptor admits a peer that
may not originate logons MUST decide, from each peer's identity (§2.4),
whether that peer may originate one. It MUST NOT treat reaching the
socket as that permission.

The two kinds of peer SHOULD NOT share one bound on concurrent
conversations (§2.5). A principal who can reach the socket to change a
password can also open connections and hold them open, and a shared
bound they could exhaust would stop the console signing anyone in.

## 2.20.7 An authority that does not offer it

An authority MAY decline to offer credential change. One that declines
MUST refuse `CredentialChangeStart` with `PermissionDenied`, and is
conforming.

---

# 2.21 Conformance

_Peios Specifications / PGSS / Logon_

> Every requirement of this chapter collected by role, for an implementation claiming to be a PGSS Logon authority or client.

A conforming implementation MUST satisfy every requirement in this
chapter. This section collects them by role.

## 2.21.1 Authority obligations

An implementation claiming to be a PGSS Logon authority MUST satisfy all
of the following.

### 2.21.1.1 Channel

1. Listen on `/run/logon.sock` as a `SOCK_STREAM` Unix domain socket
   (§2.5).
2. Control access to it with a security descriptor, not with process
   integrity and not with POSIX permission bits (§2.4).
3. Serve conversations concurrently, so that one stalled logon does not
   block others (§2.5).
4. Support `SCM_RIGHTS` on the channel (§2.9).

### 2.21.1.2 Framing

5. Reject any message whose magic is not `PGSL`, as a whole-connection
   failure (§2.6).
6. Reject any message whose version it does not implement, answering
   `UnsupportedVersion` where it can still encode a denial (§2.6).
7. Reject any message declaring more than 65536 bytes, or fewer than a
   header, without reading the body (§2.6).
8. Skip to a structure's declared end after reading known fields, rather
   than assuming its length, and substitute a documented default for an
   optional trailing field a peer did not write (§2.6).

### 2.21.1.3 Conversation

9. Require `LogonStart`, `CredentialChangeStart`,
   `CredentialEnrollStart`, `SessionEnd` or `SessionEndQuery` as the
   first message, and reject a conversation opening otherwise (§2.3).
10. Send exactly one terminal message, nothing after it, and close the
    connection (§2.3).
11. Bound the number of rounds, the time spent awaiting an answer, and
    the time a conversation may remain open, and terminate with
    `ConversationLimit` on exhausting any of them (§2.3, §2.5). A bound
    reached MUST produce a terminal message; closing the connection
    silently is what the code exists to prevent.
12. Reject a `CredentialResponse` it did not solicit (§2.3).
13. Match answers to prompts by `credential_ref`, never by position, and
    treat a missing answer as a failed logon rather than as grounds to
    tear down the connection (§2.8).

### 2.21.1.4 Trust

14. Establish peer identity from the connected socket's peer token,
    never from a message body, and never via `SO_PEERCRED` (§2.4).
15. Treat `logon_type` as a proposal and constrain it against the
    verified peer (§2.4).
16. Treat `identifier`, `tty` and `remote_host` as unverified claims
    (§2.4).

### 2.21.1.5 Derivation

17. Perform derivation itself, and never accept a token, privilege set
    or integrity level from another party (§2.1).
18. Never fork or exec on the client's behalf; never learn about
    terminals, environments or session leadership (§2.1).

### 2.21.1.6 Prompting

19. Never send a prompt for a credential type absent from the client's
    `supported_credential_types`, and deny the logon instead if it
    cannot proceed within them (§2.8).
20. Ensure `credential_ref` is unique among the prompts of one request
    (§2.8).
21. For Ntlmv2, issue the challenge itself: eight bytes from a
    cryptographically secure random source, in a single prompt, accepting
    one answer, never reused, and discarded with the conversation. Route
    on the answer's decoded user alone (§2.11).

### 2.21.1.7 Result

22. Transfer the token as a file descriptor in the ancillary data of
    `AccessGranted`, never by name (§2.9).
23. Never distinguish an unknown principal from a bad credential — by
    denial code, by reason text, or by timing (§2.10, §2.12).
24. Send `home` and `shell` as absolute paths, or empty, whatever their
    provenance; an authority with no value for a profile field MUST
    leave it empty rather than invent one (§2.9).

### 2.21.1.8 Credential handling

25. Erase credential material, and every buffer it was encoded and
    decoded through — including an allocation abandoned by a buffer that
    grew — before that memory is released (§2.12).
26. Never write credential material to a log, audit record, error
    message or diagnostic (§2.12).

### 2.21.1.9 Identity lookup

27. Listen on `/run/ident.sock` as well as `/run/logon.sock`, as a
    `SOCK_STREAM` Unix domain socket (§2.14).
28. Grant connect access to that socket, by security descriptor, to
    every principal that runs ordinary programs (§2.14).
29. Refuse a message of one socket's range received on the other
    (§2.14).
30. Echo each request's `tag`, and never interpret it otherwise
    (§2.14).
31. Serve requests concurrently, and never let a slow answer on one
    connection delay another (§2.14).
32. Bound the time spent answering a request, and answer `Unavailable`
    rather than waiting indefinitely (§2.14).
33. Ignore ancillary data received on the identity socket (§2.14).

### 2.21.1.10 Resolution

34. Interpret names itself, and never require a client to parse, qualify
    or case-fold one (§2.15).
35. Compare names ASCII case-insensitively, establishing the comparison
    itself rather than delegating it to a source (§2.15).
36. Refuse a name containing a reserved character, a byte outside
    `0x20`–`0x7e`, or a leading or trailing space — whether created
    locally, received in a request, asserted by a source, or carried
    alongside a SID in a reference (§2.15).
37. Resolve bare names in a configured order, never in registration
    order, stopping at the first source that answers (§2.15).
38. Carry the resolved SID and the canonical qualified name on every
    successful reply, whatever form the request used (§2.15).

### 2.21.1.11 Answers

39. Never answer a `Principal` request with a group, or a `Group`
    request with a principal, and establish the kind itself rather than
    relaying a source's (§2.16).
40. Ignore a field bit it does not implement, and never report it as
    present (§2.16).
41. Report each requested field it implements as present or as withheld
    with a reason, never as neither (§2.16).
42. Withhold `MEMBERS` with a reason rather than returning a partial or
    empty list, where it will not or cannot produce it (§2.16).
43. Report `Absent` rather than `Declined` for a group whose membership
    is a rule rather than a record, and gather a `BUILTIN` group's
    recorded members from the sources rather than reporting it `Absent`
    (§2.16).
44. Encode "no POSIX identifier" as zero, and never substitute a number
    a caller could mistake for a real one (§2.16).
45. Answer a `passwd` record, a `group` record, a principal's
    memberships, or a name for a SID, each in one request (§2.16).
46. Never report `NotFound` unless every source in the search order that
    could have answered was consulted and answered (§2.18).
47. Report `Unavailable` where a source earlier in the search order
    could not be reached (§2.18).
48. Never report `NotFound` in place of `Refused` or of a `Restricted`
    field, and never report `Refused` for anything other than a caller
    that may not make the request (§2.18).
49. List every source that did not contribute to an enumeration, and
    never report `Found` on a page it could not produce (§2.17, §2.18).
50. Reject a cursor it did not issue, or can no longer honor, with
    `Malformed` — never by restarting the walk and never by reporting it
    complete (§2.17).
51. Serve member enumeration where it withholds `MEMBERS` as `TooLarge`
    (§2.17).

### 2.21.1.12 Service attestation

An authority that implements `ServiceAttest` MUST satisfy all of the
following. An authority that does not implement it MUST refuse the
message, and is conforming.

52. Never hold, store, or accept a credential for a service identity,
    and never offer a credential exchange for one (§2.19).
53. Refuse a `ServiceAttest` unless both the peer's principal and the
    peer's being the platform's service manager are established from the
    connection, and never from the message (§2.19).
54. Answer a peer that satisfies neither condition, or only one, with
    `PermissionDenied` (§2.19).
55. Never mint a token under this message for a principal that has not
    been designated as usable for a service logon, and refuse with
    `AccountRestricted` where it cannot determine whether a principal
    carries that designation (§2.19).
56. Never let a refusal distinguish "no such principal" from "not
    designated for service logon" (§2.19, §2.10).
57. Reject an empty or unusable `service` with `MalformedRequest`
    (§2.19).
58. Record the logon type as `Service`, and leave every `profile` field
    empty rather than inventing a value (§2.19, §2.9).
59. Issue a token that cannot be used to authenticate to another system
    on the authority's behalf, at a level below the one a credentialled
    logon receives and bounding everything derived from it (§2.19).
60. Record that the logon was attested rather than authenticated,
    wherever it records what vouched for a credentialled logon (§2.19).
61. Reject a `LogonStart` that would complete with no credential
    exchange for an identity it accepts under `ServiceAttest`, and
    reject a `ServiceAttest` naming an identity it accepts under
    `LogonStart` (§2.19).

### 2.21.1.13 Logon type restrictions

62. Refuse a logon whose type the principal's holder does not permit,
    with `AccountRestricted`, after authentication rather than instead
    of it (§2.16, §2.10).
63. Read an unstated `LOGON_TYPES` as its own default rather than as
    "nothing permitted", and never include `Service` in that default
    (§2.16, §2.19).
64. Never widen what a principal's holder permits. Local policy may
    narrow it further; nothing may add to it (§2.16).
65. Refuse a `logon_type` it does not recognize, with
    `MalformedRequest` (§2.7, §2.10).

### 2.21.1.14 Credential change

An authority that implements `CredentialChangeStart` MUST satisfy all of
the following. An authority that does not implement it MUST refuse the
message with `PermissionDenied`, and is conforming. Obligations 10 to
13, 19, 20, 24 and 25 bind a change conversation as they bind a logon.

66. Change only the credential of the principal the connected peer's
    token names, established from the socket and never from a message
    (§2.20, §2.4).
67. Establish, within the conversation, that the principal can present
    their current credential before changing it, and refuse with
    `AuthenticationFailed` where they cannot (§2.20).
68. Refuse with `AccountRestricted` a principal it holds no changeable
    credential for, including every service identity (§2.20, §2.19).
69. Send `CredentialChanged` only once the new credential is the one a
    subsequent logon will be tested against (§2.20).
70. Mint no token and create no session for a change, and send no
    descriptor with `CredentialChanged` (§2.20).
71. End with `ConversationLimit` a change it gives up on for want of an
    acceptable new credential (§2.20).
72. Refuse a `CredentialChangeStart` that ends before
    `supported_credential_types` with `MalformedRequest` (§2.20).
73. Where the socket's descriptor admits peers that may not originate
    logons, decide from each peer's identity whether it may originate
    one, and never treat reaching the socket as that permission (§2.20,
    §2.4).

### 2.21.1.15 Ending a session

An authority that implements `SessionEnd` and `SessionEndQuery` MUST
satisfy all of the following. An authority that does not implement them
MUST refuse both with `PermissionDenied`, and is conforming. Obligations
5 to 8, 10 and 14 bind these requests as they bind a logon.

74. Never accept `SessionEndQuery` as `SessionEnd` or the reverse, and
    change nothing in answering `SessionEndQuery` (§2.22).
75. Answer `SessionEndQuery` with `SessionEndAllowed` exactly where a
    `SessionEnd` from the same peer would be permitted, and otherwise
    with the denial it would draw (§2.22).
76. Refuse, with `PermissionDenied`, a peer whose token is restricted,
    the SYSTEM and Anonymous sessions the kernel creates, and every
    session of logon type `Service`, whoever asks (§2.22).
77. Permit a caller to end a session whose user is the caller, of a
    logon type a person has, where the caller is a principal of an
    issued domain (§2.22).
78. Decide any other request by an access check of the caller's token
    against a descriptor local policy states — SYSTEM and Administrators
    alone where it states none, and nobody where it states one that
    cannot be used (§2.22).
79. Answer `NoSuchSession` only to a caller who may end other
    principals' sessions, and `PermissionDenied` to any other where the
    session does not exist (§2.22, §2.10).
80. End every process whose primary token belongs to the session —
    asking first, then, after a grace period of at most 10 seconds,
    without asking — and never a process only because one of its
    threads impersonates a token of the session (§2.22).
81. Address each signal by a reference that cannot come to name a
    different process, never by a process identifier looked up again
    (§2.22).
82. Look again after each round, bound the number of rounds, and answer
    within 30 seconds (§2.22).
83. Count in `remaining` every process it could not examine or end, and
    never fail the request for one (§2.22).
84. Hold no token of the session longer than it takes to read which
    session it belongs to, and never end its own process (§2.22).
85. Where the session is the one the connected peer's token belongs to,
    send `SessionEnded` before signaling anything, carrying what it
    found to end and a `remaining` of zero (§2.22).
86. Start nothing in ending a session (§2.1, §2.22).

### 2.21.1.16 Credential enrolment

An authority that implements `CredentialEnrollStart` MUST satisfy all of
the following. An authority that does not implement it MUST refuse the
message with `PermissionDenied`, and is conforming. Obligations 10 to
13, 19, 20, 24, 25, 68, 69 and 72 bind an enrolment as they bind a
credential change.

87. Add or remove only the credentials of the principal the connected
    peer's token names, established from the socket and never from a
    message (§2.23, §2.4).
88. For both `Add` and `Remove`, establish within the conversation that
    the principal can present their current credential before changing
    anything, and refuse with `AuthenticationFailed` where they cannot
    (§2.23).
89. Refuse with `AccountRestricted` a principal it holds no credential
    for that it can ask for as proof, including every service identity
    (§2.23, §2.19).
90. Refuse an `action` or `credential_type` it does not recognize with
    `MalformedRequest`, a `credential_type` it does not enroll with
    `PermissionDenied`, and a `CredentialEnrollStart` that ends before
    `material` with `MalformedRequest` (§2.23).
91. Refuse material it will not accept with `CredentialRejected`, check
    it again when applying the change, and never send
    `CredentialRejected` for a failed proof or in answer to any other
    message (§2.23, §2.B).
92. Leave unchanged which credentials the principal may sign in with
    (§2.23).

## 2.21.2 Client obligations

There are four client roles, and they are independent. A program may
be any of them, several, or none: a logon originator never looks a
principal up; a name resolver does the reverse.

An implementation originating logons MUST satisfy obligations 1 to 20.
An implementation performing identity lookup MUST satisfy 21 to 27. An
implementation changing its own principal's credential MUST satisfy
obligations 2 to 12 and 18 to 20, reading `CredentialChangeStart`
wherever they say `LogonStart`, and 28 and 29. An implementation adding
or removing its own principal's credentials MUST satisfy the same, reading
`CredentialEnrollStart` for `CredentialChangeStart`, and 34 and 35. An
implementation ending logon sessions MUST satisfy obligations 4 to 7 and
30 to 33.

### 2.21.2.1 Conversation

1. Send exactly one `LogonStart`, as the first message (§2.3).
2. Answer each `CredentialRequest` with exactly one `CredentialResponse`
   (§2.3).
3. Never send a `CredentialResponse` that was not solicited (§2.3).
4. Treat a connection that closes without a terminal message as a failed
   logon, and not retry automatically (§2.3).

### 2.21.2.2 Framing

5. Reject any message whose magic is not `PGSL` (§2.6).
6. Reject any message whose version it does not implement (§2.6).
7. Skip to a structure's declared end after reading known fields (§2.6).

### 2.21.2.3 Capabilities

8. Never declare in `supported_credential_types` a credential type it
   cannot render (§2.7). Declaring fewer than it can render is
   permitted, and an empty list is how a client asks for a logon
   requiring no interaction.
9. Fail the conversation, rather than guess, if it receives a prompt it
   cannot render (§2.8).

### 2.21.2.4 Rendering

10. Display received messages, in order, before the prompts of the same
    request (§2.8).
11. Not interpret or branch on message text, `credential_name`, or
    `reason` (§2.8, §2.10).
12. Echo `credential_ref` back unchanged (§2.8).

### 2.21.2.5 Result

13. Read the token descriptor from the ancillary data of
    `AccessGranted`, and treat an `AccessGranted` without one as a
    failed logon (§2.9).
14. Close the descriptor if it does not install the token (§2.9).
15. Have a fallback for every `profile` field, and treat an empty field,
    and an absent `profile`, identically and not as an error (§2.9).
16. Never execute a relative `shell`, nor resolve a relative `home`
    against its own working directory (§2.9). A `shell` containing no
    separator is relative, and MUST NOT be resolved against a search
    path.
17. Never treat `profile` as a directory lookup, nor cache it as an
    answer about any principal other than the one who just authenticated
    (§2.9).

### 2.21.2.6 Credential handling

18. Collect a credential only where it can establish that its collection
    method meets the type's requirements, and never collect a `Password`
    with echo enabled (§2.12).
19. Never silently truncate an answer to fit its own buffer (§2.12).
20. Erase credential material, and every buffer it was collected and
    encoded through, before that memory is released, and never write it
    to a log, error message or diagnostic (§2.12).

### 2.21.2.7 Identity lookup

21. Forward a name unchanged, and never parse, split, qualify or
    case-fold one (§2.15).
22. Never reuse a `tag` while a request bearing it is outstanding, and
    never assume replies arrive in request order (§2.14).
23. Treat a cursor as opaque: never construct, parse or modify one, nor
    present one to a different authority or across a reconnection
    (§2.17).
24. Continue an enumeration until `next` is empty, never infer
    completion from an empty page, and never present a walk it abandoned
    for any other reason as a complete one (§2.17).
25. Surface an enumeration's `incomplete` list rather than discarding it
    (§2.17).
26. Distinguish `NotFound` from `Unavailable`, and never cache the
    second as though it were the first (§2.18).
27. Never use enumeration to test whether a principal exists (§2.17).

Obligations 24 and 26 bind a client that caches for the lifetime of a
single process just as they bind an authority. A resolver that remembers
"no such user" through an outage will keep reporting it after the outage
ends, and one that reports a failed walk as an empty system does the
same thing to every principal at once.

### 2.21.2.8 Credential change

28. Send exactly one `CredentialChangeStart`, as the first message, and
    name no principal in it — there is no field for one (§2.20).
29. Treat `CredentialChanged` as the only successful outcome, expect no
    token with it, and close any descriptor that arrives with it
    (§2.20).

### 2.21.2.9 Ending a session

30. Send exactly one `SessionEnd` or `SessionEndQuery`, as the only
    message, and use `SessionEndQuery` — never `SessionEnd` — to learn
    whether ending a session would be permitted (§2.22).
31. Wait up to 60 seconds for the answer to `SessionEnd` before treating
    it as unanswered, and then not assume either outcome (§2.22).
32. Treat a non-zero `remaining` as a session that may still exist, and
    never read the counts as an outcome where the session was the
    caller's own (§2.22).
33. Treat a denial code it does not recognize as a refusal, not as an
    unreadable answer (§2.B).

### 2.21.2.10 Credential enrolment

34. Send exactly one `CredentialEnrollStart`, as the first message,
    with every field, and name no principal in it (§2.23).
35. Tell `CredentialRejected` (the material) apart from
    `AuthenticationFailed` (the proof) where it reports a refusal, and
    treat a denial code it does not recognize as a refusal (§2.23,
    §2.B).

## 2.21.3 What a client is not required to do

A client is **not** required to understand what any credential type
means, what any message says, or why a logon was denied. It renders what
it is given and returns what it collects.

That is the property the whole conversational shape exists to produce,
and a client that starts reasoning about the content of prompts has
given it up — it will need changing the next time an authority's policy
does.

---

# 2.22 Ending a Session

_Peios Specifications / PGSS / Logon_

> How a caller asks the authority to end a logon session — the question and the act as separate messages, who may end whose, what the authority ends and what it cannot reach, and the answer that goes first when the caller is in the session.

A caller asks the authority to end a logon session with `SessionEnd`,
and asks whether it may with `SessionEndQuery`. Each is a whole
conversation in one message, on `/run/logon.sock`: the client sends it
first and alone, and the authority answers with one terminal message.

```
client                                   authority
  |                                          |
  |------------ SessionEndQuery ------------>|   may I?
  |<-- SessionEndAllowed | AccessDenied -----|   nothing changed
  |                                          |

client                                   authority
  |                                          |
  |-------------- SessionEnd --------------->|   end it
  |                                          |   (ends its processes)
  |<---- SessionEnded | AccessDenied --------|   terminal
```

§2.3's rules hold for both: one per connection, the request as the
first and only client message, exactly one terminal message, and the
connection closed after it.

## 2.22.1 Why the authority

The kernel has no call that ends a logon session. A session lasts as
long as a token of it does, and is destroyed when the last reference
goes (Kernel TRM §3.2.7). Ending a session is therefore ending the
processes that run in it, after which the kernel does the rest.

Any sufficiently privileged program could do that walk. It belongs to
the authority for two reasons.

**One decision, one record.** The authority created the session and is
the component the standard already trusts to decide who may do what
with logons. A desktop's task manager, a principal manager and a
command-line tool asking it get the same answer, under one policy, and
leave one record of what was ended at whose request.

**It can finish.** A process in the session may be protected, or carry
a descriptor that does not let an administrator end it. A program doing
the walk itself can stop halfway and leave half a session. The
authority, as the most trusted process outside the kernel, can end what
an administrator's tools cannot.

## 2.22.2 SessionEndQuery

`msg_type` = `0x0041`. Client to authority. The whole request.

| Field | Encoding | Limit |
|---|---|---|
| `logon_session_id` | `u64` | — |

`logon_session_id` is the session's identifier: the `auth_id` every
token of the session carries.

The authority answers with `SessionEndAllowed` where a `SessionEnd` for
the same session from the same peer would be permitted now, and
otherwise with `AccessDenied` carrying the denial that `SessionEnd`
would draw. It MUST NOT signal any process, or change anything else,
in answering.

It exists so that a program can decide whether to offer the act at all.
A window that shows a person a button that can only fail has told them
something false.

## 2.22.3 SessionEnd

`msg_type` = `0x0040`. Client to authority. The whole request.

| Field | Encoding | Limit |
|---|---|---|
| `logon_session_id` | `u64` | — |

The authority ends the session's processes as §2.22 describes below and
answers with `SessionEnded`, or refuses with `AccessDenied`.

## 2.22.4 Why the question is a separate message

The two requests have the same body and differ only in `msg_type`. They
could have been one message with a flag saying "only ask". They are not,
for the reason `ServiceAttest` is not a `LogonStart` (§2.19): a flag
puts the path that ends a session on the same dispatch as the path that
must not, separated by one bit. With two messages, a probe cannot end a
session by any corruption or confusion of a field — only by being a
different message.

An authority MUST NOT accept either message as the other.

## 2.22.5 Who may end a session

The caller is the **user of the connected peer's token**, established
from the socket as §2.4 requires. An authority MUST refuse, with
`PermissionDenied`, a peer whose token is restricted: a restricted token
does not speak for its user's whole authority.

Unlike `CredentialChangeStart` (§2.20), these messages name their
subject. They have to: the usual caller is an administrator, and the
session is somebody else's. What the name buys is decided entirely by
who is asking.

An authority MUST apply the following, in this order.

1. **Never the kernel's sessions, never a service's.** An authority
   MUST refuse, with `PermissionDenied`, the session the kernel creates
   for SYSTEM, the one it creates for Anonymous, and every session whose
   logon type is `Service` — whoever asks, the session's own user and
   SYSTEM included. Every process on the machine descends from the first
   and depends on it. A service is stopped through the service manager,
   which knows how to stop it and whether to start it again; signing it
   out from under that manager does neither.
2. **Your own session.** An authority MUST permit a caller to end a
   session whose user is the caller, whose logon type is one a person
   has — one of those §2.B lists, other than `Service` — and whose user
   is a principal of an issued domain (`S-1-5-21-A-B-C-RID`). No grant
   is needed: signing yourself out is not a privilege. A well-known
   identity is not a person signing out, whatever its session's type.
3. **Anybody else's.** Otherwise, an authority MUST decide by an access
   check of the caller's token, for a right that means "end a session",
   against a security descriptor its local policy states.
   - Where local policy states no descriptor, the authority MUST permit
     SYSTEM and Administrators and nobody else.
   - Where it states one that cannot be used — the wrong type, empty,
     unreadable, or not a descriptor — the authority MUST permit nobody,
     and SHOULD record why. Falling back to the default would grant more
     than the site wrote to anybody the site meant to exclude, and
     nobody would notice; refusing everybody is noticed at once.
4. **No such session.** Where the session does not exist, an authority
   MUST answer `NoSuchSession` to a caller rule 3 permits, and
   `PermissionDenied` to any other.

The last rule is about disclosure. Which sessions exist — who is signed
in, and since when — is not something every principal may list, and a
`NoSuchSession` that differed from a refusal would let anybody who can
reach the socket enumerate sessions by number.

`PermissionDenied` and `NoSuchSession` are the only denials these
messages draw for a decision. `MalformedRequest`, `UnsupportedVersion`
and `Internal` keep their usual meanings (§2.10).

> [!NOTE]
> On Peios the descriptor is the `REG_SZ` value `SessionEndSecurity` on
> `Machine\Generic\Authn\Policy`, in SDDL, read on every request. The
> right is `0x1`, and every generic right maps to it. With the value
> absent the descriptor is `O:SYG:SYD:(A;;0x1;;;SY)(A;;0x1;;;BA)`. The
> kernel's sessions are 999 (SYSTEM) and 998 (Anonymous).

## 2.22.6 What the authority ends

An authority MUST end every process whose **primary** token belongs to
the session, by asking each to terminate, giving it a grace period, and
then terminating whatever is left without asking.

It MUST NOT signal a process because one of its threads is impersonating
a token of the session. A service that impersonates a person to answer
one request is not in that person's session, and ending it would end the
service for everybody.

It MUST address each signal to the process whose token it examined, by
a reference that cannot come to name a different process — never by a
process identifier looked up again, which may have been reused in the
meantime.

A process can start another during the grace period, and the new one
holds the session too. So after each round an authority MUST look again,
and end what it finds in a further round. It MUST bound the number of
rounds, and MUST bound the grace period. Both bounds are
implementation-defined, but the grace period MUST NOT exceed 10 seconds,
and the whole request MUST be answered within 30 seconds — half of the
60 a client waits (§2.21), so that a slow authority and a patient client
never meet at the same instant.

A process the authority cannot examine, or cannot signal, is not a
failure of the request. It is counted in `remaining`, and the authority
carries on with the rest.

An authority MUST NOT end its own process, and MUST NOT hold a token of
the session for longer than it takes to read which session the token
belongs to. Each token held is a reference that keeps the session alive.

An authority SHOULD record each `SessionEnd` it acts on — who asked,
which session and whose it was, and the counts it answered — wherever
it records logons.

This is the one thing the authority does to processes. It starts none,
and §2.1's prohibition stands.

> [!NOTE]
> Mainline's authority finds the session in
> `/sys/kernel/security/kacs/sessions`, walks `/proc`, opens each
> process by `pidfd_open` and reads its primary token through
> `kacs_open_process_token` on that pidfd, so the signal it later sends
> by `pidfd_send_signal` reaches the process whose token was read. It
> sends `SIGTERM`, waits up to 5 seconds for everything signaled to
> exit, sends `SIGKILL` to what is left, waits up to 1 second, and walks
> again — at most three rounds, so at most about 18 seconds.

## 2.22.7 SessionEnded

`msg_type` = `0x8040`. Authority to client. The successful terminal
message of `SessionEnd`; nothing follows it.

| Field | Encoding | Limit |
|---|---|---|
| `ended` | `u32` | — |
| `remaining` | `u32` | — |

`ended` is the number of processes of the session the authority
signaled that its last look no longer found.

`remaining` is the number of processes its last look did find still
holding the session, plus those it could not examine. Not zero means the
session may still exist, and a client SHOULD say so rather than report
the person signed out.

Both fields are mandatory. The message is newer than the rule that lets
a trailing field be absent, so there is no older authority whose silence
needs a default.

The counts are of processes, not of references. A session outlives its
processes wherever a reference the authority cannot see survives them —
see below — and such a reference is counted nowhere.

## 2.22.8 SessionEndAllowed

`msg_type` = `0x8041`. Authority to client. The successful terminal
message of `SessionEndQuery`; nothing follows it. It has no fields.

## 2.22.9 When the caller is in the session

A caller may end the session it is running in, and a person signing
themselves out usually does. Ending it ends the caller, and the
authority cannot answer a connection whose other end is gone.

So where the session being ended is the one the connected peer's token
belongs to, an authority MUST send `SessionEnded` **before** it signals
anything. Its `ended` is then the number of processes it found to end,
and `remaining` is zero: the counts say what the authority is about to
do, not what it achieved. It then ends the session exactly as it would
any other.

A client in that position MUST NOT read the counts as an outcome, and
SHOULD expect to be ended shortly after it reads them.

The connection is itself a reference to the caller's token, held by the
authority's end of the socket, so the session is not destroyed until the
authority has closed it.

## 2.22.10 What ending a session cannot reach

The kernel destroys a session when its last reference goes, and some
references are not processes running in the session:

- **A token descriptor held elsewhere.** A token can be passed between
  processes as a descriptor (Kernel TRM §3.2.7). A process outside the
  session holding one keeps the session alive after every process in it
  has ended, and nothing here finds it.
- **An impersonating thread.** By the rule above, a thread of another
  process impersonating a token of the session is not ended. The session
  lasts until that thread reverts.
- **A process not yet reaped.** A process that has exited still holds
  its token until its parent reaps it. It counts in `remaining`, and
  ending its parent, where that is in the session, usually releases it.

An authority is not required to find these, and a client MUST NOT
assume that `remaining` of zero means the session is gone.

## 2.22.11 Access to the socket

Every principal permitted to end its own session needs connect access to
`/run/logon.sock`. That is the same population §2.20 admits, and as
there, reaching the socket permits nothing by itself.

## 2.22.12 An authority that does not offer it

An authority MAY decline to offer ending sessions. One that declines
MUST refuse both `SessionEnd` and `SessionEndQuery` with
`PermissionDenied`, and is conforming.

---

# 2.23 Credential Enrolment

_Peios Specifications / PGSS / Logon_

> How a principal adds a credential of their own, such as an SSH public key, or removes one — the opening message, why it names nobody, the proof of the current credential it requires, and the denial that says the material was refused.

A principal adds a credential of their own beside the ones they have, or
removes one, by opening a conversation on `/run/logon.sock` with
`CredentialEnrollStart`. The only credential this section defines for
enrolment is an SSH public key (§2.D). The authority asks for the
principal's current credential, in the rounds of §2.8, and ends the
conversation with `CredentialChanged` or `AccessDenied` (§2.10).

```
client                                   authority
  |                                          |
  |-------- CredentialEnrollStart ---------->|   principal = the peer
  |                                          |   material: the key, or which
  |<--------- CredentialRequest -------------|   the current credential
  |---------- CredentialResponse ----------->|
  |                                          |
  |<-- CredentialChanged --------------------|   terminal
  |         or AccessDenied                  |
```

It is the sibling of a credential change (§2.20), and everything that
section says about the shape of the conversation, whose credential is
affected, and the terminal holds here unless this section says
otherwise. The difference is where the material travels: a change
collects the new credential in a round, while an enrolment carries it in
the opening message. That is possible because the material is public: an
SSH public key, or the fingerprint of one.

## 2.23.1 CredentialEnrollStart

`msg_type` = `0x0031`. Client to authority. Opens the conversation; MUST
be the first message.

| Field | Encoding | Limit |
|---|---|---|
| `supported_credential_types` | length-framed bytes, one `u8` per type | 32 |
| `action` | `u8` | §2.B |
| `credential_type` | `u8` | §2.B |
| `material` | string | 16384 |

Every field is mandatory. The message is newer than the rule that lets a
trailing field be absent, so there is no older client whose silence
needs a default, and a truncated message read with one could perform an
action nobody asked for. An authority MUST refuse a
`CredentialEnrollStart` that ends before `material` with
`MalformedRequest`.

### 2.23.1.1 supported_credential_types

The credential types the client can render, for the proof the authority
will ask for. It carries the meaning and the capability rule of the §2.7
field of the same name, and a decoder MUST drop a value it does not
recognize rather than refuse the message.

### 2.23.1.2 action

`1`, `Add`: enroll `material` as a new credential of the principal. `2`,
`Remove`: remove the credential `material` identifies. The values are
instructions rather than statements of capability, so a decoder MUST
refuse one it does not recognize with `MalformedRequest`.

### 2.23.1.3 credential_type

The kind of credential being added or removed, from the credential types
of §2.B. Only `SshPublicKey` is defined for enrolment. An authority MUST
refuse any other with `PermissionDenied`.

### 2.23.1.4 material

For `Add` of an `SshPublicKey`, one line of an OpenSSH public key file,
such as `~/.ssh/id_ed25519.pub`: the key type, the base64 key and an
optional comment. The comment MAY become the key's label.

For `Remove` of an `SshPublicKey`, the key's fingerprint as
`ssh-keygen -l` writes it: `SHA256:` and the unpadded base64 of the
SHA-256 of the key blob (§2.D).

## 2.23.2 Whose credential

The principal whose credentials change is the **user of the connected
peer's token**, as in §2.20, and for the same reason: a field naming a
principal would let anything that reaches the socket ask to add a key to
anybody's account. The message carries no identifier, and an authority
MUST NOT enroll a credential for, or remove one from, any other principal
in this conversation.

An authority MUST refuse, with `AccountRestricted`, a principal for
whom it holds no credential it can ask for as proof (below). That
includes a service identity (§2.19), a platform identity no source
holds, a principal that authenticates with no credential at all, and a
principal that authenticates only with the kind of credential being
enrolled. The `reason` SHOULD tell the principal that an administrator
can make the change for them.

## 2.23.3 Proof of the current credential

**Both actions require it.** An authority MUST establish, within the
conversation, that the principal can present their current credential
before it adds or removes anything, and MUST refuse with
`AuthenticationFailed` where they cannot. The rule and its wording
requirement are §2.20's.

A token shows that someone signed in, not that the person at the
keyboard now is that person. A key added from an unattended terminal is
a way back into the account for whoever added it, and outlives every
session; a key removed from one locks its owner out of every machine
that trusts it. Neither can be undone by signing in again.

The proof is a credential the principal already has and that is not the
one being enrolled. A principal who signs in only with SSH keys cannot
prove themselves with a key over this socket, since there is no
transport to bind the proof to (§2.D); such a principal is refused as
above.

## 2.23.4 Checking the material

The authority decides what it accepts: which key types and sizes, how
many keys a principal may hold, and whether a key may be held twice. It
SHOULD check the material before it asks for the current credential, so
that a principal is not asked for a password to be told their key is
unreadable, and it MUST check it again when it applies the change, since
the principal's credentials may have changed between the two.

An authority MUST refuse material it will not accept with
`CredentialRejected`, and SHOULD say why in `reason`: unreadable, an
unsupported type, a key the principal already has, one more than the
principal may have, or, for `Remove`, no key of the principal's with
that fingerprint. `CredentialRejected` answers only this message (§2.B).
It MUST NOT be used where the proof failed: that is
`AuthenticationFailed`, and the two are separate so that a client can
tell "your key" from "your password".

Enrolment does not change which credentials a principal may sign in
with. Whether an enrolled key is accepted at sign-in is the authority's
policy for that principal, as it is for a key an administrator adds.

## 2.23.5 CredentialChanged

The successful terminal message is §2.20's `CredentialChanged`, with
every rule that section states for it: no fields and no descriptor, and
not sent until the change is the one a subsequent logon will be tested
against. For `Remove`, that means the key no longer authenticates the
principal at their next sign-in.

Sessions already established are left as they were. Removing a key does
not end a session that was signed in with it; ending one is §2.22's.

## 2.23.6 Access to the socket

The socket admits the peers §2.20 admits, for the same reason, and §2.20's
rules on deciding who may originate a logon and on keeping such peers
off the originators' bound on conversations apply unchanged.

## 2.23.7 An authority that does not offer it

An authority MAY decline to offer enrolment, or to offer it for some
principals. One that declines MUST refuse `CredentialEnrollStart` with
`PermissionDenied`, and is conforming.

---

# 2.24 General Authentication

_Peios Specifications / PGSS / Logon_

> Verify credentials and disclose identity without creating a local token or session.

Authenticate and Logon share credential collection and identity validation.
Authenticate MUST NOT create an OS token, logon session or local user
environment. Its result is identity data, not a bearer credential, and MUST
NOT be accepted as a later request to issue a token.

The authority MUST establish the caller from the connected socket's token.
It MUST authorize the operation, requested groups and explicitly named claims
before collecting credentials. Unauthorized named disclosure MUST refuse the
request with PermissionDenied. AllPermitted instead requests the readable
subset and MUST preserve the distinction between absence and nondisclosure.

## 2.24.1 Shared AuthenticationRequest

This length-framed structure is shared by AuthenticateStart, LogonStart
(§2.7) and source authentication. It has no message header.

| Field | Encoding | Limit |
|---|---|---|
| identifier_type | u8 | §2.B |
| identifier | length-framed opaque bytes | 1024 bytes |
| supported_credential_types | length-framed bytes, one u8 per type | 32 entries |
| required_credential_type | u8; zero means none | §2.D |
| has_ssh_binding | u8, exactly 0 or 1 | |
| ssh_binding | nested length-framed structure, when present | §2.D |

Supported types bind what the caller can collect. A required type MUST be
supported and MUST have been verified for success. Advertising Password alone
does not exclude an intentional no-credential account. A password-based access
service using plaintext password verification MUST require Password. An
MSCHAPv2 originator MUST require Mschapv2 instead. An NTLMv2 originator
MUST require Ntlmv2, advertise only Ntlmv2, and send an empty identifier;
the principal is named by the answer (§2.11). SSH binding and
authorized-originator checks remain those of §2.D.

## 2.24.2 AuthenticateStart

Message type 0x0004, client to authority, first on /run/logon.sock.

| Field | Encoding | Limit |
|---|---|---|
| authentication | nested AuthenticationRequest | above |
| groups | u8, exactly 0 or 1 | |
| claim_selection | u8: 0 None, 1 Named, 2 AllPermitted | |
| claims | count and length-framed name entries, only for Named | 1–64 entries |

Each name entry contains one string of 1–255 UTF-8 bytes, without NUL.
Names compare using KACS's per-character Unicode lowercase mapping. This is
locale-independent, without Unicode normalization or full case folding:
Équipe and équipe are equivalent; ß and ss are not. Original spelling MUST
be preserved in returned claims. This rule applies to requested names,
source/result duplicate detection and named absence assertions.
Duplicate equivalent names MUST be refused as malformed.
None and AllPermitted carry no name array, including no zero count.

The authority uses CredentialRequest and CredentialResponse (§2.8), with the
same limits, cancellation and failure handling as Logon. Shared authentication
includes source routing, general account and credential checks, and validation
of source identity, memberships and typed claims. Local logon-type restrictions,
token privileges, POSIX projection and local setup belong to Logon finalization.

## 2.24.3 Authenticated

Message type 0x8004, authority to client, terminal success.

| Field | Encoding | Limit |
|---|---|---|
| user_sid | length-framed SID bytes | 68 bytes |
| canonical_name | string | 256 bytes |
| verified_credentials | length-framed bytes, one u8 per verified type | 32 entries |
| has_groups | u8, exactly 0 or 1 | |
| groups | count and length-framed entries, only when has_groups is 1 | 1024 entries |
| claim_coverage | u8: 0 None, 1 Named, 2 Complete, 3 Filtered | |
| claims | existing typed claim array (§2.16) | 64 entries |
| absent_claims | count and length-framed name entries | 64 entries |
| mschapv2_success | length-framed bytes | 0 or 20 bytes |
| ntlmv2_session_key | length-framed bytes | 0 or 16 bytes |
| operation_guid | optional trailing byte string (§2.6) | 0 or 16 bytes |
| credential_binding | optional trailing byte string | exactly 32 bytes if present |

`mschapv2_success` MUST contain exactly 20 bytes if Mschapv2 is verified
and MUST be empty otherwise. It is the exchange-specific server
AuthenticatorResponse, not a reusable credential or an OS token.
`ntlmv2_session_key` MUST contain exactly 16 bytes, the NTLM
`SessionBaseKey`, if Ntlmv2 is verified and MUST be empty otherwise
(§2.11). Clients MUST reject missing or unexpected method output. These
outputs use the existing authentication grant; they introduce no separate
permission.

`credential_binding` is reference `[16]` followed by revision `[16]`, as in
§2.16. It names the credential actually verified, scoped to the verified SID
and source. An authority MUST obtain it from that validated source assertion,
not from a later unrelated lookup. No-credential success MUST omit it. Older
sources or authorities can omit it; absence means unknown metadata, never
evidence that the credential was deleted. The binding grants no authority.

This additive extension follows `operation_guid`. An authority emitting a
binding without a diagnostic GUID MUST emit the explicit empty GUID field
first. It MUST NOT move the established diagnostic slot. A malformed GUID
alone MUST NOT turn a valid authentication into failure; when its framing
cannot locate a later binding safely, the binding remains unknown. A present
malformed binding is a protocol error. Existing readers skip appended fields
through the body length. Public framing remains version 6.

Each group entry contains one length-framed SID byte string. All SIDs MUST be
structurally valid. Groups MUST be complete validated source memberships,
without duplicates or locally synthesized token groups. has_groups MUST equal
the request flag; an unrequested set differs from a complete empty set.

For Named selection, each requested claim MUST occur exactly once, either in claims or
absent_claims, using the same name equivalence. No unrequested claim may be
returned. Absence means authorized but not asserted; it differs from a
permission failure. Claim names and values retain §2.16's bounds and types.

None selection MUST return None coverage with empty claims and absent_claims.
Named selection MUST return Named coverage. AllPermitted MUST return Complete
or Filtered coverage, readable claim values and an empty absent_claims array.
It MUST NOT disclose restricted names or counts. Duplicate equivalent returned
names MUST be rejected for every mode.

Complete guarantees the entire source claim set was disclosed and policy
permits disclosure throughout the claim namespace. An omitted name is then
known absent. Filtered means policy may withhold names; omission alone is
unknown, not absence. Coverage MUST depend on disclosure authorization rather
than whether this particular principal actually has a restricted claim. If
the authority cannot establish complete namespace disclosure safely, it MUST
report Filtered. A consumer MUST NOT grant access from a condition requiring
unknown information.

verified_credentials lists checks actually completed, without duplicates.
Every entry MUST be understood and supported by the request. An empty list
means deliberate source-authorized no-credential success; it MUST NOT satisfy
a nonzero required_credential_type.

Authenticated MUST NOT carry a descriptor through SCM_RIGHTS. A client MUST
close and reject any received descriptor, incomplete disclosure, or result
that fails the required proof. Failure uses AccessDenied (§2.10).

## 2.24.4 Local policy

Authd implements operation and disclosure authorization using the
AuthenticationSecurity descriptor under Machine\Generic\Authn\Policy.
Authenticate (0x1), Logon (0x2), ReadGroups (0x4) and ReadClaim (0x8)
are distinct rights. ReadClaim object ACEs target a deterministic claim GUID.
Claim-specific ACEs do not grant or deny root operation or group rights,
including through generic access masks.
See authd's registry manual for namespace, canonicalization, capability
assignment, defaults and administration.

Claim-read policy also applies to identity lookup and enumeration (§2.16).
Those requests ask for the complete claims field and do not collect a
credential. Authenticate can request named claims and authorize that selection
before collecting credentials, or request AllPermitted with coverage metadata.
Public identity and membership
lookup does not require Authenticate's ReadGroups grant.

ServiceAttest remains a separate PID-1-only path (§2.19). Authenticating a
principal does not grant authority to impersonate them or provision capabilities.

---

# Appendix 2.A Message Reference

_Peios Specifications / PGSS / Logon_

> Every message type by number and socket, the protocol constants, and the field limits.

## 2.A.1 Messages

### 2.A.1.1 On `/run/logon.sock`

| `msg_type` | Message | Direction | Defined in |
|---|---|---|---|
| `0x0001` | `LogonStart` | client → authority | §2.7 |
| `0x0004` | `AuthenticateStart` | client → authority | §2.24 |
| `0x8004` | `Authenticated` | authority → client | §2.24 |
| `0x0002` | `CredentialResponse` | client → authority | §2.8 |
| `0x8001` | `CredentialRequest` | authority → client | §2.8 |
| `0x8002` | `AccessGranted` | authority → client | §2.9 |
| `0x8003` | `AccessDenied` | authority → client | §2.10 |
| `0x0020` | `ServiceAttest` | client → authority | §2.19 |
| `0x0030` | `CredentialChangeStart` | client → authority | §2.20 |
| `0x8030` | `CredentialChanged` | authority → client | §2.20, §2.23 |
| `0x0031` | `CredentialEnrollStart` | client → authority | §2.23 |
| `0x0040` | `SessionEnd` | client → authority | §2.22 |
| `0x0041` | `SessionEndQuery` | client → authority | §2.22 |
| `0x8040` | `SessionEnded` | authority → client | §2.22 |
| `0x8041` | `SessionEndAllowed` | authority → client | §2.22 |

### 2.A.1.2 On `/run/ident.sock`

| `msg_type` | Message | Direction | Defined in |
|---|---|---|---|
| `0x0010` | `Lookup` | client → authority | §2.16 |
| `0x0011` | `Enumerate` | client → authority | §2.17 |
| `0x8010` | `LookupReply` | authority → client | §2.16 |
| `0x8011` | `EnumerateReply` | authority → client | §2.17 |

The high bit marks a message sent by the authority (§2.6). The two
ranges are disjoint, and a message of one range MUST be refused on the
other socket (§2.14).

## 2.A.2 Protocol constants

| Constant | Value | Defined in |
|---|---|---|
| Logon socket path | `/run/logon.sock` | §2.5 |
| Identity socket path | `/run/ident.sock` | §2.14 |
| Magic | `PGSL` (`50 47 53 4c`) | §2.6 |
| Version | `4` | §2.6 |
| Header size | 12 bytes | §2.6 |
| Maximum message size | 65536 bytes | §2.6 |
| Longest grace before a forced end | 10 seconds | §2.22 |
| Longest a `SessionEnd` may take to answer | 30 seconds | §2.22 |
| Least a client waits for that answer | 60 seconds | §2.21 |

## 2.A.3 Field limits

| Field | Maximum | Defined in |
|---|---|---|
| `identifier` | 1024 bytes | §2.7 |
| `tty` | 128 bytes | §2.7 |
| `remote_host` | 256 bytes | §2.7 |
| `supported_credential_types` | 32 entries | §2.7 |
| `messages` | 8 entries | §2.8 |
| `prompts` | 16 entries | §2.8 |
| `answers` | 16 entries | §2.8 |
| `text` | 512 bytes | §2.8 |
| `credential_name` | 128 bytes | §2.8 |
| `data` | 32768 bytes | §2.8 |
| `home` | 4096 bytes | §2.9 |
| `shell` | 4096 bytes | §2.9 |
| `display_name` | 256 bytes | §2.9 |
| `reason` | 512 bytes | §2.10 |
| `material` | 16384 bytes | §2.23 |
| `identity` | 128 bytes | §2.19 |
| `service` | 256 bytes | §2.19 |
| `name` (lookup key) | 256 bytes | §2.16 |
| `sid` | 68 bytes | §2.16 |
| `qualified_name` | 512 bytes | §2.16 |
| `withheld` | 32 entries | §2.16 |
| `values` | 32 entries | §2.16 |
| reference `name` | 512 bytes | §2.16 |
| `HOME`, `SHELL` | 4096 bytes | §2.16 |
| `DISPLAY_NAME` | 256 bytes | §2.16 |
| `GROUPS` | 128 entries | §2.16 |
| `MEMBERS` | 256 entries | §2.16 |
| `CLAIMS` | 64 entries | §2.16 |
| `DESCRIPTION` | 1024 bytes | §2.16 |
| `of_name` | 256 bytes | §2.17 |
| `cursor`, `next` | 256 bytes | §2.17 |
| `entries` | 256 entries | §2.17 |
| `incomplete` | 32 entries | §2.17 |
| `incomplete` source name | 32 bytes | §2.17 |

The 68-byte SID maximum is a property of the SID encoding rather than of
this chapter: an eight-byte prelude plus the fifteen sub-authorities the
one-byte count admits. It is specified in PCDS.

An encoder MUST refuse to produce a field exceeding its maximum; a
decoder MUST reject one it receives (§2.6).

---

# Appendix 2.B Enumerations

_Peios Specifications / PGSS / Logon_

> Every enumerated value the protocol carries — logon and identifier types, credentials, severities, denial codes, keys, kinds, fields and outcomes.

Adding a value to any enumeration here is a breaking change requiring a
version bump — see §2.6, which states the four exceptions and where
each is stated in full.

## 2.B.1 Logon types

Carried in `LogonStart.logon_type` (§2.7) as a `u8`. Semantics are
defined by KACS and described in the Peios Kernel TRM; this table is for
reference.

| Value | Name |
|---|---|
| 2 | Interactive |
| 3 | Network |
| 4 | Batch |
| 5 | Service |
| 8 | NetworkCleartext |
| 9 | NewCredentials |
| 10 | RemoteInteractive |

The gaps are deliberate: the numbering follows KACS, and values it does
not define are not available here.

A value MAY be added here without a version bump, for the reason §2.7
gives.

## 2.B.2 Identifier types

Carried in `LogonStart.identifier_type` (§2.7) as a `u8`.

| Value | Name | `identifier` holds |
|---|---|---|
| 1 | Username | A principal name |

## 2.B.3 Credential types

Carried in `Prompt.credential_type` (§2.8) and in
`LogonStart.supported_credential_types` (§2.7) as a `u8`. See §2.11 for
when a new one is warranted.

| Value | Name | Collection |
|---|---|---|
| 1 | Password | A line of text, not echoed |
| 2 | SshPublicKey | Bound SSH candidate or signature proof; §2.D |
| 3 | Mschapv2 | Source-issued challenge and typed password proof; §2.11 |
| 4 | Ntlmv2 | Authority-issued challenge; the answer names the principal; §2.11 |

## 2.B.4 Message severities

Carried in `Message.severity` (§2.8) as a `u8`.

| Value | Name |
|---|---|
| 0 | Info |
| 1 | Error |

## 2.B.5 Enrolment actions

Carried in `CredentialEnrollStart.action` (§2.23) as a `u8`.

| Value | Name | `material` holds |
|---|---|---|
| 1 | `Add` | The credential to enroll: for `SshPublicKey`, one line of an OpenSSH public key file |
| 2 | `Remove` | Which credential to remove: for `SshPublicKey`, its `SHA256:` fingerprint |

`CredentialEnrollStart.credential_type` takes a value from the
credential types above; only `SshPublicKey` is defined for enrolment.

## 2.B.6 Denial codes

Carried in `AccessDenied.denial` (§2.10) as a `u32`.

| Value | Name | Meaning |
|---|---|---|
| 1 | `MalformedRequest` | The message could not be understood. |
| 2 | `UnsupportedVersion` | The protocol version is not implemented. |
| 3 | `PermissionDenied` | The peer may not make this request at all. |
| 4 | `AuthenticationFailed` | The principal is unknown, or the credential is wrong. Deliberately one code — see §2.10. |
| 5 | `LogonTypeNotPermitted` | The peer may not request this kind of session. |
| 6 | `AccountRestricted` | The principal exists and authenticated, but policy refuses this logon; or, in a credential change, the principal has no credential that can be changed (§2.20). |
| 7 | `AuthorityUnavailable` | The authority cannot reach what it needs to decide. |
| 8 | `ConversationLimit` | Too many rounds, or too long without an answer. |
| 9 | `Internal` | The authority failed for a reason it will not describe. |
| 10 | `NoSuchSession` | There is no live logon session by that identifier. Answers only `SessionEnd` and `SessionEndQuery` (§2.22). |
| 11 | `CredentialRejected` | The credential offered for enrolment, or named for removal, was refused: unreadable, unsupported, already held, one too many, or not held. Answers only `CredentialEnrollStart` (§2.23). |

A denial code MAY be added without a version bump where it only ever
answers messages newer than it is — messages no peer that predates the
code can send — because such a peer is then never sent it. `NoSuchSession`
and `CredentialRejected` were added under this rule. A client of the newer messages SHOULD treat a
code it does not recognize as a refusal, reporting the code and
`reason`, rather than as an unreadable answer; it is the one place in
this chapter where a client may meet a denial newer than itself.

## 2.B.7 Key types

Carried in `Lookup.key_type` (§2.16) and `Enumerate.of_key_type`
(§2.17) as a `u8`. Zero in `of_key_type` means the field is unused.

| Value | Name | Key is in |
|---|---|---|
| 1 | `Name` | `name` |
| 2 | `Sid` | `sid` |
| 3 | `UnixId` | `unix_id` |

## 2.B.8 Object kinds

Carried in `Lookup.kind`, `LookupReply.kind_found` and `Enumerate.kind`
(§2.16, §2.17) as a `u8`.

| Value | Name |
|---|---|
| 0 | `Any` |
| 1 | `Principal` |
| 2 | `Group` |

`Any` is not valid in `kind_found` or in `Enumerate.kind`.

## 2.B.9 Fields

Carried in `Lookup.fields`, `Enumerate.fields` and `LookupReply.present`
(§2.16) as a `u32` bitmask, and in a withheld entry's `field` as a
single bit.

| Bit | Name | Value encoding |
|---|---|---|
| 0 | `UNIX_ID` | `u32` |
| 1 | `PRIMARY_GROUP` | reference |
| 2 | `HOME` | string |
| 3 | `SHELL` | string |
| 4 | `DISPLAY_NAME` | string |
| 5 | `GROUPS` | array of references |
| 6 | `MEMBERS` | array of references |
| 7 | `CLAIMS` | array of claim entries |
| 8 | `ENABLED` | `u8` |
| 9 | `LOGON_TYPES` | `u32` |
| 10 | `DESCRIPTION` | string |
| 11 | `CREDENTIAL_BINDINGS` | array of reference/revision entries |

A bit MAY be added without a version bump, because a reply states which
fields it answered and an authority MUST ignore a bit it does not
implement (§2.16).

## 2.B.10 Lookup outcomes

Carried in `LookupReply.outcome` and `EnumerateReply.outcome` (§2.18) as
a `u8`.

| Value | Name |
|---|---|
| 1 | `Found` |
| 2 | `NotFound` |
| 3 | `Unavailable` |
| 4 | `Refused` |
| 5 | `Malformed` |

## 2.B.11 Withheld reasons

Carried in a withheld entry's `reason` (§2.16) as a `u8`.

| Value | Name | Meaning |
|---|---|---|
| 1 | `Absent` | The field has no value. |
| 2 | `Restricted` | The caller may not have this field. |
| 3 | `Declined` | The source will not produce it. |
| 4 | `TooLarge` | It exists and exceeds one reply; use `Enumerate` (§2.17). |

---

# Appendix 2.C Prior Art

_Peios Specifications / PGSS / Logon_

> Where PGSS Logon sits against Windows LSA, PAM and POSIX name resolution — and which resemblances are deliberate.

## 2.C.1 Windows LSA

The closest predecessor is the Windows Local Security Authority and its
`LsaLogonUser` interface. What is taken and what is deliberately left is
worth stating, because the resemblance is close enough that the
differences matter.

**Taken.** The separation of *authentication* from *derivation* —
establishing who someone is, and then constructing a token for them, are
different acts by different rules. The idea that a logon produces both a
token and a session, and that the session records which authority
vouched for it. The vocabulary of logon types.

**Diverged.** LSA's authentication packages are DLLs loaded into the LSA
process, so a defect in any package is a defect in the most privileged
process on the system. Nothing in PGSS Logon admits an in-process
extension point; an authority that federates does so across a process
boundary of its own choosing.

**Rejected.** The challenge-response family (NTLM and successors).
Challenge-response requires the verifier to store something a response
can be recomputed from, which is password-equivalent material — the
pass-the-hash failure mode, where stealing the store is as good as
knowing the passwords. This chapter requires the opposite property: what
is stored MUST NOT be usable to authenticate. See §2.11.

## 2.C.2 PAM

Pluggable Authentication Modules supplies the conversation shape: an
authority that asks for what it needs, a client that renders prompts
without understanding them, and several rounds where policy requires
them. That shape is why adding a credential type is a change to
authorities and not to every client, and it is adopted wholesale.

What is not adopted is PAM's stacking, in which a credential is offered
to each module in turn until one accepts. Trying each source *with the
password* hands every source the credentials of every other source's
users, including on typos. Where an authority federates, resolution MUST
select the answering party before any credential is collected.

PAM is also an in-process module system, and the objection under
*Diverged* applies to it equally.

## 2.C.3 POSIX name resolution

The identity-lookup half of this chapter answers the questions
`getpwnam`, `getpwuid`, `getgrnam`, `getgrgid` and `getgrouplist` ask,
and its field mask, reference encoding and one-round-trip requirement
are shaped by what those calls need in one go.

What is not adopted is the `passwd` record itself. GECOS is not carried
(§2.9), the flat `name:uid:gid` tuple is replaced by a SID plus a set of
requested fields, and the reserved-character rules (§2.15) exist
precisely because a name that reaches those callers ends up in a
colon-and-comma-separated line that nothing else validates.

Nor is the assumption that an absence is authoritative. A world-readable
file cannot be unreachable, so POSIX has no vocabulary for "the source
that would have known did not answer"; §2.18 exists because a federated
authority does, and reporting that as "no such user" memoises an outage
as a fact.

## 2.C.4 Design influences

**Descriptor-passing over ambient authority.** The token is transferred
as a file descriptor rather than named, so that possession of the
conversation is what confers it. There is no window in which a minted
token exists under a name another process could reach for.

**One conversation per connection.** The connection *is* the
conversation's identity, so no correlation identifier exists to be
forged or confused. This is deliberately unlike the identity channel of
§2.14, and unlike PSI (PSPU §2.7), both of which multiplex because
their connections are long-lived.

**Capability declaration over negotiation.** A client states what it can
render and the authority works within it, rather than the two agreeing a
version or a profile. That is what lets a credential type be added to
authorities without a flag day, and it is why the capability list is the
one enumeration whose unknown values are dropped rather than refused
(§2.7).

---

# Appendix 2.D SSH Public-Key Authentication

_Peios Specifications / PGSS / Logon_

> The implementation contract for principal-owned SSH credentials, including proof collection, transport binding, and a coordinated replacement of the unpublished formats.

The SSH public-key extension is implemented in authd/lpsd and the Peios
OpenSSH port. PEI-67 tracks its release qualification. PGSS/PSI version 1 and
the unpublished lpsd store layout were replaced together without a version
bump or migration. Rebuild consumers together and explicitly reprovision
old development stores; lpsd never resets an unreadable store automatically.

An SSH public key is a credential of a principal. The principal source
stores the authorized key and verifies proof of possession. The logon
authority constrains the originator, applies policy, derives the token,
and grants the logon. SSH does not introduce a second account authority.

The first source implementation is lpsd. No `.ssh/authorized_keys` lookup
is performed. Client private keys and server host keys are not principal
credential records; their storage is outside this extension.

## 2.D.1 Responsibilities and trust

| Component | Responsibility |
|---|---|
| SSH client | Produces the standard SSH authentication signature using its private key |
| SSH transport and monitor | Establishes and retains the live transport binding; mediates credential collection |
| authd | Verifies the local originator, relays the credential exchange, enforces logon policy, and grants a token |
| lpsd | Owns local public-key credentials, checks their eligibility, verifies signatures, and asserts the principal |

A network-facing process does not receive authority to assert a principal
or obtain arbitrary logon tokens. The protected SSH monitor owns the PGSS
connection. A user session receives its resulting token, not the PGSS
connection, proof buffers, or monitor control channel.

Public-key verification does not replace disabled-account checks, logon
type restrictions, originator restrictions, or normal token derivation.
A valid signature alone never creates a session.

## 2.D.2 Principal storage and policy

lpsd extends each principal with an explicit authentication policy and a
bounded list of SSH public-key records. The existing principal SID remains
the account identity; names, key comments, and fingerprints do not replace it.

Each key record contains:

| Field | Representation |
|---|---|
| Record ID | Random 128-bit identifier, stable until deletion |
| Public key | Validated, canonical SSH public-key blob; at most 8192 bytes |
| Label | UTF-8 text, at most 128 bytes; no control characters |
| Created time | UTC Unix seconds, recorded by lpsd |

The fingerprint is derived as SHA-256 of the canonical SSH public-key
blob and displayed in OpenSSH's `SHA256:` base64 form without padding.
It is not separately stored as an authority. Labels are display metadata,
not executable `authorized_keys` options. There are at most 32 keys per
principal; duplicate key material within a principal is rejected. The same
key may be deliberately enrolled on different principals, but a proof
for one username does not authenticate another.

The initial algorithm set is plain Ed25519 and RSA with `rsa-sha2-256`
or `rsa-sha2-512` signatures. RSA moduli are 3072–8192 bits. RSA key blobs
use the SSH `ssh-rsa` key format; that does not enable SHA-1 signatures.
DSA, SHA-1 signatures, certificates, security-key variants, and additional
key families are rejected until their semantics are specified. Malformed
keys, noncanonical encodings, trailing data, and unsupported types are
rejected at enrollment and at authentication. A maintained SSH key/crypto
implementation performs decoding and verification; no new cryptographic
primitive is introduced here.

Authentication policy has an explicit mode:

- `Credentials`: a nonempty set of permitted methods, initially
  `Password` and/or `SshPublicKey`. One permitted method is sufficient.
- `NoCredential`: authentication is intentionally unnecessary.
- `Denied`: no new authentication is permitted by this source.

The principal's separate enabled flag is checked first. In Credentials
mode, a permitted method without corresponding usable credential material
fails; it does not select another mode. In particular, deleting the last
key on a key-only principal leaves that principal unable to authenticate.
NoCredential mode is never inferred from an empty verifier or key list.

Keys are enrolled in two ways. An administrator enrolls them through
lpsd's protected administrative interface: the `lps key add`,
`lps key list`, and `lps key remove` operations operate on one principal
and use its existing administration authorization checks. A principal
enrolls and removes their own through PGSS Logon's `CredentialEnrollStart`
(§2.23), described under *Self-service enrollment* below. Neither way
silently changes the principal's authentication policy. An explicit policy operation selects
password-only, key-only, either credential, NoCredential, or Denied.
NoCredential and Denied cannot be combined with credential methods.

Mutations are atomically persisted before success is acknowledged, using
the store's existing rollback-on-write-failure behavior. They invalidate
affected authentication state. Enrollment accepts a plain OpenSSH public
key line, including an optional label, but rejects private-key input and
`authorized_keys` options rather than silently ignoring them. Credential
inventory is not exposed through unauthenticated identity lookup.

Compound authentication such as password AND key is a separate extension.

## 2.D.3 Self-service enrollment

A principal adds or removes their own SSH public keys with
`CredentialEnrollStart` on `/run/logon.sock` (§2.23). The account is the
user of the caller's token; the message names nobody. Possessing a session
token does not by itself authorize adding a persistent credential, so both
adding and removing re-prove the principal's current password inside the
conversation, and a wrong one ends it with `AuthenticationFailed` and the
fixed `Authentication failed.` wording.

authd routes the conversation to the source that holds the principal as
PSI's `EnrollCredential` (PSPU §2.23), and only to a source declaring the
`ENROLLS_CREDENTIALS` capability; a source that does not is sent nothing,
and the caller is refused `PermissionDenied`. lpsd declares it, and:

- resolves the principal from the SID authd vouched for, with the rules a
  password change uses. A principal with no password to prove — policy
  `key` or `none`, or a password policy with no password set — is refused
  `AccountRestricted`, with words telling them to ask an administrator,
  before anything is asked;
- checks an added key line, or a removal's fingerprint, by the same store
  paths `lps key add` and `lps key remove` use — the same import, algorithm
  and size rules, duplicate rejection, 32-key limit and last-administrator
  rule — before asking for the password, and again when it applies the
  change. Material it refuses is `CredentialRejected`, with the store's
  reason;
- names a key for removal by its `SHA256:` fingerprint rather than the
  record ID `lps key remove` takes, because the fingerprint is what a person
  can read from their own `.pub` file. The key's comment becomes its label;
- persists the change with the administrative write's rollback, sends authd
  the same change notification an administrative write sends, and only then
  answers `CredentialChanged`.

Adding a key does not let it sign the principal in unless their policy is
`key` or `either`, which only an administrator sets. A principal whose
policy is `key` cannot use this path at all, since they have no password
to prove themselves with; removing the last key of such an account is
therefore never reachable here.

## 2.D.4 Store replacement and revocation

The unpublished store layout is replaced in place, retaining its existing
format-version marker. The reader and writer implement only the replacement
layout; there is no old-store importer, dual reader, or downgrade path.
Development images and test stores are explicitly reprovisioned from updated
inputs rather than carried forward from an earlier build.

Provisioning writes an explicit policy for every principal. Password-bearing
fixtures use Credentials/Password; intentionally passwordless fixtures,
including the live image account, explicitly use NoCredential. Key-only
fixtures use Credentials/SshPublicKey with enrolled keys. An empty verifier
or key list never selects NoCredential automatically.

Unreadable, truncated, or malformed state still fails closed. Clean replacement
does not mean that lpsd silently deletes a store or creates new identities on
a decode failure. Reprovisioning is an explicit development/build operation.

lpsd keeps a per-principal credential generation in pending conversations.
Immediately before issuing an assertion it rechecks the principal is
enabled, the method remains permitted, the selected key is still enrolled,
and the generation has not changed. A changed generation terminates the
attempt; the client may start again. A positive candidate-key probe is
never cached as authorization for a later signature.

The assertion is the authentication decision's ordering point: removals
committed before it take effect for that attempt; removals committed after
it affect subsequent attempts. Already issued tokens and sessions are not
terminated by deleting a key. Revoking an existing session remains an
explicit session operation.

## 2.D.5 Coordinated protocol replacement

`SshPublicKey` is credential type **2**; Password remains type 1. PGSS Logon
and PSI retain their existing header version **1**, magic, framing conventions,
and message-size ceilings. Each implements one codec for the revised layout.
There is no version negotiation, translation between old and new codecs, or
automatic fallback to the previous layout or a weaker credential.

This deliberately replaces unpublished contracts. The implementation updates
the existing enum-extension/version wording and message definitions together
with the code. authd, lpsd, login, GXWI, peinit, utilities, other active consumers,
and their dependency pins are rebuilt as needed for the revised shared types.
Old development binaries and stores are not a supported combination with the
replacement. Existing header-version and malformed-message checks remain;
they are not a compatibility mechanism for two layouts sharing version 1.

LogonStart contains `required_credential_type`, a `u8`: 0 leaves
the source's ordinary policy in control, 1 requires Password, and 2 requires
SshPublicKey. A nonzero value must appear in supported_credential_types.
PSI Authenticate carries the same requirement; its Assertion reports
`authenticated_credential_type` (0 means no credential). authd rejects a
result that fails a nonzero requirement. The SSH monitor selects 1 or 2
for its current method, so even an intentionally NoCredential principal
cannot produce an unearned successful SSH password/key authentication.
Rebuilt console and graphical clients retain their intended behavior by
explicitly declaring their capabilities and credential requirement.

The new fields follow the existing fields within their enclosing
length-framed structure. LogonStart appends required_credential_type, then
`has_ssh_binding` (u8, exactly 0 or 1), then the binding structure when
present. PSI Authenticate carries this extended LogonStart. Assertion
appends authenticated_credential_type. Prompt appends parameters. These
tails are mandatory even when their values are zero or empty;
truncation is an error, not permission to infer permissive defaults. Binding fields
are encoded in the order listed below: 16 raw connection-ID bytes, a byte
string session identifier, and a UTF-8 username. A binding is required for
type 2 and forbidden on attempts that do not advertise that type. Unknown
method values, invalid presence flags, and type-2 assertions in a
Password-only exchange are rejected.

PGSS and PSI share the revised credential bodies. The authority validates
and relays them without a legacy translation layer. The SSH
frontend advertises only the method of the current SSH authentication
attempt, so a separate password attempt remains possible only when policy
allows it.

A client advertising only Password is never sent type 2. A key-only account
reached through such a client is denied, not prompted for an invented
password and not granted without credentials. Identity, service-attestation,
and credential-change operations retain their intended behavior in the
coordinated build. This extension does not enable SSH key changes through
the password-change operation.

The new credential type is offered only to a client that declares it.
The authority also checks that the originator is allowed to provide SSH
transport bindings. Ordinary password collectors do not acquire that
authority by adding type 2 to their capability list.

## 2.D.6 Binding the proof to a connection

Standard SSH signs the initial transport session identifier together with
the authentication request. It does not sign a fresh arbitrary challenge
invented by PGSS. The client-facing exchange remains RFC 4252 public-key
authentication; no Peios client extension is required.

For a key attempt, LogonStart includes a typed `SshTransportBinding`
structure. Its fields are a monitor-generated 16-byte connection ID, the
initial SSH session identifier (16–64 bytes), and the exact SSH username
(1–256 UTF-8 bytes). The username equals LogonStart's Username identifier
byte for byte. Other identifier types are rejected for this credential.
The SSH service is fixed to `ssh-connection` and the method to `publickey`
for this first implementation. The binding is copied into PSI Authenticate
from authd's validated conversation state, not from an Answer.

The monitor's connection ID is a correlation value, not proof or a bearer
capability. authd accepts binding claims only from a specifically authorized
service originator verified through its kernel socket-peer token. The implementation requires an unrestricted SYSTEM peer with the
enabled, non-deny-only service SID derived from the fixed service name
`sshd`, in addition to the ordinary originator/logon-type checks. This is
an SSH-specific gate, not a general service-group policy union. The network child and logged-on user must lack that service
authority and access to its PGSS descriptors.

The monitor obtains the initial session identifier from trusted key-exchange
state and pins it for the connection, including across rekeys. It does not
accept an arbitrary hash supplied through its authentication IPC. The
trusted monitor creates a fresh 16-byte server KEXINIT cookie. Before
signing the initial exchange hash it validates the bounded structured
transcript, requires that cookie and its own host public key, and recomputes
the SHA-256 or SHA-512 exchange hash. It supports ML-KEM/X25519,
sntrup761/X25519 and Curve25519 exchanges.
Simply remembering the first hash a child asks the host key to sign is not
accepted as proof of freshness against a compromised child.

This is an explicit trust boundary: lpsd verifies the signature, while the
SSH transport component vouches for the live connection. lpsd cannot
independently prove network freshness from a caller-supplied transcript.
A compromised authorized transport component is outside the guarantee;
an ordinary local process or compromised network parser is not.

All candidate offers on one SSH connection retain the same binding. The
monitor serializes attempts, fixes the target username for that connection,
and rejects username changes. Disconnect, monitor exit, loss of authd, or
successful authentication makes pending attempts unusable. A connection
receives at most one granted logon token. The monitor does not let a child
open an independent PGSS conversation using a previously accepted proof.

## 2.D.7 Credential exchange

Prompt adds a length-framed `parameters` byte string, at most 4096
bytes. It is empty for Password. For SshPublicKey it contains a length-framed
structure containing a `disposition` byte: `0` initially, `1` for the previous
candidate being acceptable, and `2` for the previous candidate being
rejected. It describes only that candidate in that conversation; it never
asserts identity or grants access. There is one outstanding prompt, with a
fresh credential_ref for each round.

An SshPublicKey Answer.data contains a length-framed structure:

| Field | Encoding and limit |
|---|---|
| Operation | `u8`: 0 Candidate, 1 Proof |
| Signature algorithm | UTF-8 string, 1–64 bytes |
| Public key | Byte string, 1–8192 bytes |
| Signature | Byte string, 0–8192 bytes; empty exactly for Candidate |

The outer structure uses PGSS little-endian lengths. The public-key blob
and signature blob retain SSH's own encoding, including its big-endian
lengths. Unknown operations fail closed. Total answer
data remains below the existing 32768-byte ceiling; the parser additionally
rejects trailing fields outside this layout. No signed-data blob or
replacement session identifier is accepted in an answer.

For Candidate, lpsd checks whether that key and algorithm would be eligible
for the named principal and returns another SshPublicKey prompt with the
corresponding disposition. The monitor maps this to SSH's key-acceptable
reply or authentication failure. Unknown principals, disabled principals,
disallowed methods and unregistered keys all produce the same negative
result. Only one submission is in flight; the monitor consumes a disposition
before sending the next answer, abandons the PGSS exchange if the SSH client
switches methods, and never reports a probe response as logon success.
The positive result discloses eligibility of an already-presented
key, as standard SSH probing does; it does not enumerate keys.

For Proof, lpsd repeats eligibility checks and verifies the signature. A
client may send Proof without a preceding Candidate. Candidate success
never eliminates verification or the final account-state check. A bad
proof ends the PGSS attempt with a generic authentication failure. Trying
another key uses the next bounded SSH attempt; no proof is silently
reinterpreted as a different credential.

lpsd reconstructs the signed bytes exactly as RFC 4252 specifies: the
validated initial session identifier, message number 50, exact username,
`ssh-connection`, `publickey`, boolean true, algorithm and key blob. It
checks the algorithm agrees with the key and the signature's internal
algorithm identifier. There is no “verify these arbitrary bytes” API.
Case-insensitive principal lookup may resolve the username, but the signed
username is never case-normalized before signature verification.

When proof succeeds, lpsd emits the ordinary PSI assertion. The source
does not mint a token or choose additional privileges based on the key.
authd's AccessGranted is the only result permitting SSH authentication
success and session startup. Password and key are alternatives in the
initial policy model; partial success for multifactor authentication is
not implemented or advertised.

## 2.D.8 Bounds, logging and failure behavior

One SSH connection has at most 16 public-key submissions total, counting
Candidate and Proof, and at most 6 failed signed/password attempts. Probes
consume the submission budget but do not by themselves trigger persistent
account lockout. The whole authentication exchange has a 120-second
deadline, without resets for probes or switching methods. Existing tighter
system limits still apply. Unknown users take the same bounded failure
path; no guarantee of exact constant-time public-key lookup is made.

The authority logs the originator, logon type and result; the source logs
the selected key fingerprint on success, and granted sessions carry their
principal/session identifiers.
Neither passwords, complete proofs nor private material appear in logs.
PGSS wire credentials use the existing self-wiping buffers. Parsed public
keys and SSH signatures are short-lived public cryptographic data; neither
is a password-equivalent secret or reusable bearer token.

Cryptographic verification failure, unsupported algorithm, revoked key,
disabled principal and disallowed method produce generic authentication
failure to the remote client. Detailed operational reasons are available
only through privileged local diagnostics. Invalid framing and state
transitions terminate the relevant conversation; they never become a
passwordless attempt.

## 2.D.9 Qualification requirements

Required regression coverage includes:

- Successful key-only and password-only logons, and either-method policy;
  unsupported method and credential-free downgrade refusal.
- Rebuilt console/GXWI password logons and explicitly provisioned passwordless
  accounts, including fresh provisioning, restart, and failed store writes.
- Candidate acceptance without any assertion, direct Proof, multiple-key
  clients, budget exhaustion, cancellation, and identity-change refusal.
- Wrong signature, mismatched algorithm, wrong username/service/key,
  malformed nested lengths, unsupported versions, and cross-protocol input.
- Key removal, policy change and account disablement between Candidate and
  Proof and immediately before assertion; deletion of the last key.
- Captured proof replay on another SSH connection, an ordinary local PGSS
  connection, a new monitor, and after authd restart. Include a hostile
  network child proposing an old key-exchange hash, not just an honest
  client connecting twice.
- No PGSS or monitor descriptors, originator service authority, or elevated
  launch privileges inherited by the principal's shell.
- The final shell's actual primary token carries the intended principal,
  logon session, groups and policy, verified against kernel state.

## 2.D.10 Service operation

The package `dev.peios.openssh` provides the Peios OpenSSH server and ordinary
SSH command-line tools. Its source repository owns the port and Pekit recipe;
there are no downstream source patches in the package catalog.

All SSH logons use RemoteInteractive, including commands without a PTY and
SFTP. Password authentication requires an actual password; an intentionally
NoCredential account cannot log in through SSH. TCP, Unix-socket, agent,
X11 and tunnel forwarding are disabled in this first port.

The `sshd-service.reg` and `sshd-network.reg` vendor seeds are separate image
opt-ins. The Experimental edition enables both. `make boot` in `dist/release` forwards
localhost TCP 2222 to the guest's TCP 22. The service runs as SYSTEM with only SeChangeNotifyPrivilege,
SeAssignPrimaryTokenPrivilege and SeTcbPrivilege. The network seed permits
inbound TCP 22 and reserves that port for the sshd service SID. The network
child loses its privileges and service-group authority, receives an Everyone
restricting SID, and retains upstream chroot and seccomp protection. The
session child installs the granted principal token before accepting the
post-authentication network state.

Defaults are `/usr/etc/ssh/sshd_config`; administrator overrides may use
`/lcl/etc/ssh/sshd_config`. The port and password authentication are not
chosen there. They are machine policy, `Machine\Software\OpenSSH` `Port` and
`PasswordAuthentication` (both `REG_DWORD`, seeded 22 and 1), which
`start-sshd` reads at each start and passes to `sshd` as `-p` and
`-o PasswordAuthentication=`; `-p` makes `sshd` ignore every `Port` line. The
port, the service SID's reservation of it and the `ssh` firewall rule's
`DstPort.Equal` must agree, so the package's `ssh-settings` moves all three in
one registry transaction and then restarts the service; see
[Signing in over SSH](/peios/signing-in/signing-in-over-ssh.md). The service generates an Ed25519 host key on first
start in protected persistent `/var/state/sshd`, validates and reuses it on
subsequent starts, and fails on an invalid existing key. It never rotates a
key automatically. Client private keys remain with the client.

Provision a key-only account while disabled to avoid a temporary
NoCredential window:

```sh
lps add alice --no-password --disabled
lps key add alice /path/to/alice.pub laptop
lps policy alice key
lps enable alice
lps key list alice
```

Use `lps policy alice either` to allow either an enrolled key or an existing
password. Administrative key removal uses the record ID printed by
`lps key list`: `lps key remove alice RECORD_ID`. Self-service removal names
the key by fingerprint instead (§2.23). Changing material does not change
policy.

## 2.D.11 References

- [RFC 4252, section 7](https://www.rfc-editor.org/rfc/rfc4252.html#section-7):
  candidate-key queries, direct signed requests, and exact signed fields.
- [RFC 8332](https://www.rfc-editor.org/rfc/rfc8332.html): RSA SHA-2 signature
  algorithm names and reuse of the RSA public-key encoding.
- [OpenSSH Portable monitor](https://github.com/openssh/openssh-portable/blob/master/monitor.c):
  upstream privilege-separation integration reference; it does not by
  itself establish Peios originator authorization or this contract's
  trusted-transport freshness requirement.

---

# 3.1 Scope and Roles

_Peios Specifications / PGSS / MSIP_

> The protocol roles, interoperability requirements, and scope of MSIP.

The multi-surface interaction protocol (MSIP) lets a daemon drive one or more
user interfaces without depending on their rendering technology. It carries
information, progress, and requests for input as a conversation of pages.

The **daemon** owns the operation and its decisions. It offers conversation
kinds, issues turns, interprets answers, and chooses the next turn. The
**surface** renders elements, collects input, and returns answers. A terminal,
graphical application, web client, or automated client can act as a surface.

The person using a surface is not a protocol party, as with the principal of a
logon (§2.1). Both protocol roles are publicly implementable. A third party
MAY implement either role independently. A daemon offering a conversational
interface to generic surfaces MUST follow this chapter.

This chapter specifies the following contracts:

- Conversation ownership, persistence, and answer arbitration (§3.3).
- Trust, access control, and secret handling (§3.4).
- Framing and extensibility (§3.5).
- Greeting and binding (§3.6).
- Turns, elements, answers, and updates (§3.7 to §3.10).
- Completion, errors, and conformance (§3.11 and §3.12).

The daemon's specification defines its conversation kinds, refs, answer
meanings, and multiplicity policy. This chapter does not prescribe element
layout or an automated surface's answering policy.

---

# 3.2 Terminology

_Peios Specifications / PGSS / MSIP_

> Conversation identities, element references, and presentation hints.

The multi-surface interaction protocol (MSIP) distinguishes operation
identity, turn sequence, and element meaning.

**Conversation.** One instance of a flow, such as installation, first-boot
setup, or authorization. It belongs to the daemon and outlives individual
connections. The daemon assigns its identifier.

**Kind.** A flow name offered by a daemon, such as `install` or `oobe`. The
greeting lists available kinds.

**Turn.** One page, represented by an ordered element list. Its `seq`
increases with every turn and is the only turn identity cited in answers. A
turn MAY carry a stable template `id`. Turns with the same `id` MUST have the
same element refs and types, although their state can differ. A template id
need not be unique within a conversation.

**Element.** One item on a page, identified by a `ref` and an element `type`
from the negotiated set (§3.6).

**Ref.** An element's semantic identity. It is unique within a turn and stable
across turns and runs of the daemon. Repeating a question retains its ref,
including after validation failure or navigation. The daemon documents refs
and answer encodings; it does not promise a fixed turn sequence.

**Action.** A selectable element with no answer value. An answer names at most
one action. The daemon defines its meaning (§3.9).

**Attach.** Bind a connection to an existing conversation. Multiple
connections can attach simultaneously and receive the same broadcasts.

**Class.** A presentation token on a turn or element. A surface MAY use
classes for styling. Classes make no behavioral promise and are not cited in
answers.

---

# 3.3 The Conversation

_Peios Specifications / PGSS / MSIP_

> Conversation ownership, broadcast arbitration, persistence, and lifetime.

A surface opens a conversation, and the daemon drives it. The daemon issues
every turn; a bound surface answers the outstanding turn.

## 3.3.1 Opening a conversation

A daemon that needs to request input uses a conversation opened by a surface.
For example, a surface can open a persistent conversation and wait for a
passphrase request. The daemon still chooses when to issue a turn.

## 3.3.2 Broadcasting and arbitration

Every attached connection receives every TURN and UPDATE. Any attached surface
can answer the outstanding turn. The daemon arbitrates answers by `seq`:

- Apply the first valid answer, then issue the next turn or end the
  conversation. That broadcast acknowledges acceptance.
- Keep the turn open when validation fails. Broadcast element errors so every
  surface can correct its answer (§3.10).
- Ignore an answer for any other sequence number silently. A stale answer MUST
  NOT receive a protocol error.

Two authorized surfaces can submit competing answers. The protocol does not
designate a controlling surface or provide takeover operations.

## 3.3.3 Persistence

Disconnecting, closing, or crashing a surface does not end the conversation.
The daemon continues the operation. A replacement connection can attach and
receive the outstanding turn with all updates folded into it (§3.10).

Attachment provides current state, not a transcript. The protocol has no
history-replay operation.

## 3.3.4 Lifetime and multiplicity

A conversation exists from creation until END (§3.11). Its identifier MUST NOT
appear in listings after it ends.

A daemon SHOULD define a policy for abandoned conversations with no attached
surfaces and no progress. It can expire, cancel, or retain them. If a
conversation ends, the daemon reports END to every connection still attached.

The daemon defines how many conversations of each kind can exist. For a
singleton kind, a START while one exists attaches the caller to it and reports
`attached: true` (§3.6).

---

# 3.4 Trust and Access Control

_Peios Specifications / PGSS / MSIP_

> Peer authorization, presentation boundaries, and secret handling.

The daemon holds the authority needed for the operation. A surface presents
information and submits claims; its answers do not grant authority.

## 3.4.1 Daemon obligations

The daemon MUST validate every answer against the outstanding turn (§3.9). It
MUST NOT treat an answer as authorization or vary behavior based on
`Hello.surface`, which is an observability string.

The socket path has a security descriptor. Where authorization differs by kind
or conversation, the daemon MUST check the connection's verified peer identity
at START, ATTACH, and LIST. A LISTING MUST contain only conversations that the
caller could attach to.

A conversation identifier is unpredictable (§3.6), but its secrecy does not
authorize attachment. The ATTACH access check provides that control.

## 3.4.2 Surface obligations

A surface MUST treat names, help, messages, and other informational text as
display content. It MUST NOT interpret that text as instructions. Classes can
affect presentation but not protocol behavior.

A surface MUST fail a page it cannot render rather than infer an unsupported
element's meaning. Capability negotiation prevents this in a conforming pair
(§3.6).

## 3.4.3 Secrets

An element with `secret` set requires these protections:

- The surface MUST collect its value without echo, MUST NOT log it, and MUST
  NOT retain it beyond the answer carrying it.
- The daemon MUST NOT place a secret value in element state, updates, errors,
  or listings. Only the answer carries the collected secret.
- Neither role logs secret values at any verbosity.

A surface MUST NOT display a secret value supplied by a daemon beyond the
masked input it collects. A late joiner receives the question without another
surface's collected secret.

---

# 3.5 Message Framing

_Peios Specifications / PGSS / MSIP_

> The version-one header, JSON object body, limits, and extension rules.

Every multi-surface interaction protocol (MSIP) message has a 12-byte header
followed by one UTF-8 JSON object. The header uses the layout from §2.6 and
its own protocol magic.

## 3.5.1 Header

Integer fields are little-endian. The header fields are:

| Offset | Bytes | Field | Value |
| --- | --- | --- | --- |
| 0 | 4 | `magic` | `MSIP` (`4D 53 49 50`) |
| 4 | 2 | `version` | `1` |
| 6 | 2 | `msg_type` | Message identifier (§3.A) |
| 8 | 4 | `total_len` | Header and body length in bytes |

A decoder MUST check the magic on every message. Wrong magic is an immediate
connection failure. It MUST refuse an unsupported version by closing the
connection, optionally sending an Error if encoding remains safe.

A message MUST NOT exceed 1 MiB including its header. A decoder MUST reject a
declared length above this limit without reading the body. It MUST also reject
a length smaller than the header.

The high bit of `msg_type` is set for daemon messages and clear for surface
messages. A peer MUST check the actual type against its expected connection
state; checking direction alone is insufficient.

## 3.5.2 Body

The body is one JSON object as defined by RFC 8259. The header carries the
message type; the body does not repeat it. Message fields are specified in
§3.6 to §3.11 and summarized in §3.A.

A decoder MUST reject invalid UTF-8, invalid JSON, and JSON values that are
not objects as protocol errors (§3.11).

## 3.5.3 Extensibility

Extensions follow these rules:

- A decoder MUST ignore unknown object keys. Additional fields MUST be
  optional and have safe defaults for older peers.
- An absent optional field and its documented default MUST NOT be
  distinguished.
- Unknown values of `Refused.reason`, `Error.code`, and `End.outcome` MUST
  produce protocol errors. Extending those enumerations requires a protocol
  version change.

Element types use capability negotiation instead of a version change. A daemon
MUST NOT send a type absent from HELLO. Each type defines its own state keys
(§3.B). A surface that does not implement an added type omits it from HELLO.

---

# 3.6 Binding

_Peios Specifications / PGSS / MSIP_

> Greeting, authorization, and binding one connection to one conversation.

A connection carries at most one conversation during its lifetime. Closing the
connection detaches the surface. A surface needing two conversations opens two
connections.

## 3.6.1 Greeting

The first message MUST be the surface's Hello. Its fields are:

| Field | Meaning |
| --- | --- |
| `element_types` | Types that the surface can render |
| `surface` | Optional observability string, such as `install-tui/0.1` |

The daemon replies with Welcome, listing its conversation `kinds` and an
optional daemon observability string. The daemon MUST NOT vary behavior based
on `surface`.

The daemon MUST NOT send an element type absent from `element_types`. It MUST
refuse a binding with `unsupported_elements` when the conversation requires
types the surface cannot render.

## 3.6.2 Unbound connections

After WELCOME, a connection can send these messages:

- **List.** Receive a Listing of conversations the caller can attach to. An
  empty result is valid.
- **Start.** Open a conversation of a specified kind.
- **Attach.** Join a conversation by identifier.

Other messages on an unbound connection are protocol errors. A second binding
attempt on a bound connection is also a protocol error.

## 3.6.3 Successful binding

A successful Start or Attach receives Bound with the conversation identifier,
current `seq`, and `attached`. The latter is true when joining an existing
conversation. If a turn is outstanding, the daemon MUST immediately send its
folded state after Bound.

A daemon MAY implement a singleton kind by answering Start with an attachment
to its existing conversation. The reply reports `attached: true`.

A conversation identifier is 32 lowercase hexadecimal characters encoding 128
bits from a cryptographically secure source. It appears in Attach, Bound, and
Listing.

## 3.6.4 Refusal

Refused leaves the connection unbound. Its reasons are:

| Reason | Meaning |
| --- | --- |
| `access_denied` | Authorization failed |
| `unknown_kind` | The kind is unknown, or the conversation is absent or ended |
| `unsupported_elements` | The conversation requires undeclared element types |
| `unavailable` | The daemon offers the kind but cannot open a conversation |

The daemon MUST use Refused only for binding attempts. It SHOULD prefer
`unknown_kind` when the caller must not learn that a conversation exists. For
`unavailable`, it SHOULD explain the failure in `message` without disclosing
secrets.

---

# 3.7 Turns

_Peios Specifications / PGSS / MSIP_

> Sequence numbers, ordered elements, and progress-only turns.

The daemon advances a conversation by broadcasting Turn. The message describes
the complete page and closes the preceding turn.

## 3.7.1 Fields and sequence

Turn has these fields:

| Field | Meaning |
| --- | --- |
| `seq` | Sequence number |
| `id` | Optional template identity (§3.2) |
| `name` | Optional display title |
| `class` | Optional presentation hints |
| `elements` | Ordered element list |

Sequence numbers start at 1 and increase by exactly 1 for each turn. The
daemon MUST NOT reuse or rewind a sequence number within a conversation.
Answers to a superseded turn are stale (§3.3).

The daemon MUST order elements helpfully, and the surface SHOULD retain that
order. A surface MAY rearrange them; the daemon MUST NOT depend on their
visible order. Layout, grouping, and geometry belong to the surface. Protocol
extensions SHOULD retain this separation.

## 3.7.2 Turns without answers

A turn with no enabled inputs or actions expects no answer. The daemon
advances it independently, often updating a progress page until the work
completes (§3.10). A surface MUST NOT be required to acknowledge such a turn.

A turn expecting an answer remains outstanding until a valid answer is applied
or the daemon supersedes it. The daemon can issue a replacement turn at any
time.

---

# 3.8 Elements

_Peios Specifications / PGSS / MSIP_

> Common element fields, semantic references, and input roles.

An element is a JSON object with common fields and type-specific state. Its
ref identifies the meaning of the element rather than its screen position.

## 3.8.1 Common fields

The common fields and defaults are:

| Field | Default | Meaning |
| --- | --- | --- |
| `ref` | Required | Semantic identity, unique within the turn (§3.2) |
| `type` | Required | Negotiated element type |
| `name` | Absent | Display label |
| `class` | `[]` | Presentation hints |
| `help` | Absent | Explanatory text |
| `required` | `false` | A validating answer must supply a value |
| `default` | Absent | Value assumed when an optional input is omitted |
| `secret` | `false` | Secret-handling rules apply (§3.4) |
| `enabled` | `true` | Whether the element can be answered |
| `error` | Absent | Validation error set by UPDATE |

Additional keys are type-specific state (§3.B). A surface MAY substitute
translations keyed by element ref or turn id, with the supplied `name` and
`help` as fallbacks.

## 3.8.2 Unavailable elements

An element with `enabled: false` remains on the page. A surface SHOULD show it
as unavailable, with `help` explaining why. It MUST NOT collect input for it.
An answer supplying a value for it is a protocol error.

## 3.8.3 Roles

Element types have three roles:

- **Outputs:** `text`, `progress`, and `log` provide information. They receive
  no answers and are exempt from `required`.
- **Inputs:** `string`, `boolean`, `select`, and `table` collect typed values
  under their refs.
- **Actions:** `action` reports a selection without a value. An automated
  surface that can answer all inputs can select the primary action without
  interpreting navigation semantics.

---

# 3.9 Answers

_Peios Specifications / PGSS / MSIP_

> Answer encoding, action selection, required values, and arbitration.

A bound surface answers the outstanding turn with Answer. The daemon checks
the answer before applying domain-specific rules.

## 3.9.1 Encoding

Answer has these fields:

| Field | Meaning |
| --- | --- |
| `seq` | Turn being answered |
| `action` | Selected action ref, if present |
| `values` | Object mapping input refs to values |

The values MUST name only enabled inputs of the turn identified by `seq`.
Unknown refs and values for disabled elements, outputs, or actions are
protocol errors. Each value must match its element's answer encoding (§3.B),
including offered choices and selectable table rows.

## 3.9.2 Actions

When a turn has enabled actions, the answer MUST name exactly one. When it has
none, the answer MUST omit `action`. Naming any other element as an action is
a protocol error.

Only the daemon interprets actions such as next, back, or cancel. A surface
MUST NOT infer navigation semantics from action names.

## 3.9.3 Validation

An answer validates unless its selected action has `validate: false`. A
nonvalidating action can leave an incomplete page, but supplied values still
obey the structural rules.

For a validating answer:

- Every enabled, required input MUST have an explicit value in `values`.
- An omitted optional input with a default is treated as having that default.

The daemon then performs domain validation, such as checking that a selected
disk still exists. The protocol does not define those application rules.

## 3.9.4 Results

An answer has one of these results:

- **Stale:** Its sequence is not outstanding. The daemon ignores it silently.
- **Applied:** It is structurally sound and passes validation. The daemon
  acknowledges it through the next Turn or End, without echoing the answer.
- **Failed validation:** Required input is missing or domain validation fails.
  The daemon broadcasts element errors in an Update and keeps the turn open.

A structural violation instead receives Error on the offending connection. It
does not change the outstanding turn (§3.11).

---

# 3.10 Updates

_Peios Specifications / PGSS / MSIP_

> Sparse and full element updates and consistent folded state.

The daemon broadcasts Update to change the outstanding page without issuing
another turn. This supports progress, log output, and validation errors.

Update has these fields:

| Field | Meaning |
| --- | --- |
| `seq` | Outstanding turn sequence |
| `full` | Whether the update replaces the element list |
| `elements` | Complete elements or sparse patches |

## 3.10.1 Sparse updates

With `full` absent or false, each patch names an existing element by `ref` and
supplies changed fields. A key with value `null` removes that field. A patch
MUST NOT name an absent ref or contain a secret element's collected value
(§3.4).

Typical changes include progress values, appended log lines, errors,
availability, and refreshed choices. Log `append` entries fold into `lines`
(§3.B).

## 3.10.2 Full updates

With `full: true`, complete elements replace the element list. This is the
only way to change the set of refs within a turn. Such changes SHOULD be rare;
a surface is only required to render the replacement from scratch.

## 3.10.3 Folding

The daemon MUST fold each update into its stored turn. An attaching surface
receives this state rather than an update history (§3.6).

A surface MUST ignore updates for sequence numbers it does not hold. A sparse
update with an unknown ref indicates a daemon defect; the surface SHOULD fail
the conversation rather than infer a target.

---

# 3.11 Ending and Errors

_Peios Specifications / PGSS / MSIP_

> Terminal outcomes and per-connection protocol errors.

End finishes a conversation. Error reports a protocol violation on one
connection and does not finish the operation.

## 3.11.1 End

The daemon broadcasts End with these fields:

| Field | Meaning |
| --- | --- |
| `seq` | Final sequence number |
| `outcome` | `complete`, `cancelled`, or `failed` |
| `message` | Optional explanatory text |

`complete` reports success. `cancelled` reports abandonment by an action or
daemon policy. `failed` reports that the operation cannot continue. The daemon
SHOULD explain the result in preceding turns; the final message is a short
conclusion.

After END, the identifier MUST NOT appear in listings. Attach is refused with
`unknown_kind`. The daemon SHOULD close attached connections. A surface
renders the outcome and finishes the conversation.

## 3.11.2 Error

Error applies only to protocol violations. It does not represent staleness,
validation failure, or an operation result. Its codes are:

| Code | Violation |
| --- | --- |
| `malformed` | Invalid body or field |
| `unbound` | A message requires a binding, or a bound connection attempts another binding |
| `unknown_ref` | An answer names an absent ref |
| `bad_value` | Invalid input encoding, an ineligible element value, or an action-rule violation |
| `unexpected_type` | A message is invalid for the peer or connection state |

The sender MAY close the connection after Error. It MUST close it when further
decoding is unsafe. Other connections and the conversation remain unaffected.

---

# 3.12 Conformance

_Peios Specifications / PGSS / MSIP_

> The responsibilities required of daemons and surfaces.

Conformance requires the complete protocol, including authorization and
transport responsibilities outside a state-helper library.

## 3.12.1 Daemons

A conforming daemon satisfies these obligations:

- Protect its socket with a security descriptor and authorize START, ATTACH,
  and LIST using verified peer identity (§3.4).
- Assign identifiers from 128 cryptographically random bits and authorize
  attachment independently of identifier secrecy (§3.6).
- Send only declared element types and refuse unsupported bindings (§3.6).
- Broadcast turns, updates, and completion to all attached connections;
  provide folded state to late joiners (§3.3 and §3.10).
- Apply the first valid answer, retain turns after validation failure, ignore
  stale answers, and limit protocol errors to the offending connection (§3.9).
- Increase sequence numbers without reuse and keep secrets out of state,
  updates, errors, listings, and logs (§3.4 and §3.7).
- Document conversation kinds, refs, answer encodings, and multiplicity; keep
  presentation strings separate from behavior.

## 3.12.2 Surfaces

A conforming surface satisfies these obligations:

- Send HELLO first with its supported element types and reject pages it cannot
  render (§3.6).
- Respect input, output, action, availability, and secret-handling rules
  (§3.8).
- Answer only the outstanding sequence with permitted actions and input values
  (§3.9).
- Fold sparse updates, replace full updates, and ignore updates for other
  turns (§3.10).
- Treat informational text as display content and keep secrets masked,
  unlogged, and unretained (§3.4).

---

# Appendix 3.A Message Reference

_Peios Specifications / PGSS / MSIP_

> Every MSIP message; direction, type value, body fields; in one table per message.

Message type values. Surface-sent types have the high bit clear; daemon-sent
types have it set (`0x8000`).

| Message | Direction | `msg_type` |
|---|---|---|
| Hello | surface → daemon | `0x0001` |
| List | surface → daemon | `0x0002` |
| Start | surface → daemon | `0x0003` |
| Attach | surface → daemon | `0x0004` |
| Answer | surface → daemon | `0x0005` |
| Welcome | daemon → surface | `0x8001` |
| Listing | daemon → surface | `0x8002` |
| Bound | daemon → surface | `0x8003` |
| Refused | daemon → surface | `0x8004` |
| Turn | daemon → surface | `0x8005` |
| Update | daemon → surface | `0x8006` |
| Error | daemon → surface | `0x8007` |
| End | daemon → surface | `0x8008` |

Field tables. A field marked *opt* can be absent; its default is given in the
section that specifies the message.

**Hello** (§3.6): `element_types` (array of string), `surface` (opt string).

**Welcome** (§3.6): `kinds` (array of string), `daemon` (opt string).

**List** (§3.6): no fields.

**Listing** (§3.6): `conversations`; array of `{conversation, kind, seq}`.

**Start** (§3.6): `kind` (string).

**Attach** (§3.6): `conversation` (string, 32 lowercase hex).

**Bound** (§3.6): `conversation` (string), `seq` (number), `attached` (opt
bool, default false).

**Refused** (§3.6): `reason` (`access_denied` | `unknown_kind` |
`unsupported_elements` | `unavailable`), `message` (opt string).

**Turn** (§3.7): `seq` (number), `id` (opt string), `name` (opt string),
`class` (opt array of string), `elements` (array of element objects, §3.8).

**Update** (§3.10): `seq` (number), `full` (opt bool, default false),
`elements` (array of objects: patches when sparse, complete elements when
full).

**Answer** (§3.9): `seq` (number), `action` (opt string), `values` (opt
object, ref → value).

**Error** (§3.11): `code` (`malformed` | `unbound` | `unknown_ref` |
`bad_value` | `unexpected_type`), `message` (opt string).

**End** (§3.11): `seq` (number), `outcome` (`complete` | `cancelled` |
`failed`), `message` (opt string).

---

# Appendix 3.B Element Types

_Peios Specifications / PGSS / MSIP_

> The element-type set; state fields and answer encodings for text, string, boolean, select, table, progress, log, and action.

Each element type defines state fields beyond the common fields of §3.8 and,
for input types, the JSON encoding of its answer value. The set grows by
capability negotiation, not by version bump (§3.5); a new type is specified by
adding it here.

## 3.B.1 Text output

Prose for the person to read.

| State | Meaning |
|---|---|
| `text` | The content. |
| `detail` | What the content says, as structure. Optional; see *Detail*, at the end of this chapter. |

## 3.B.2 String input

One line of text; with `secret`, a password collector.

| State | Meaning |
|---|---|
| `min`, `max` | Length bounds, in characters. |
| `pattern` | Anchored regular expression the value must match. |
| `placeholder` | Input hint; not a default. |

Answer value: JSON string.

## 3.B.3 Boolean input

A boolean input collects a true or false value.

Answer value: JSON true/false.

## 3.B.4 Select input

Choose from what the daemon offers.

| State | Meaning |
|---|---|
| `choices` | Array of `{value, name, help?}`, in display order. |
| `multiple` | Zero or more choices rather than exactly one. |

Answer value: one choice's `value`; with `multiple`, an array of them. Values
are compared as exact JSON values.

## 3.B.5 Table input

Choose among rows that have more to say than a name: a `select` whose choices
are records. Disks, network interfaces, existing installations; anything a
person compares on several facts before picking one.

| State | Meaning |
|---|---|
| `columns` | Array of `{key, name, align?}`, in display order. `align` is `left` (default) or `right`; numbers and sizes read better right-aligned. |
| `rows` | Array of `{value, cells, enabled?, note?, detail?}`, in display order. `cells` maps a column `key` to display text; a key a row omits renders empty. `enabled` defaults to true; a false row is listed but is not an acceptable answer. `note` is a short remark shown with the row; typically why it is disabled. `detail` is what the row stands for, as structure; see *Detail*, at the end of this chapter. |
| `empty` | Text shown in place of the rows when there are none. |

Answer value: one enabled row's `value`. Values are compared as exact JSON
values.

A surface that cannot fit every column SHOULD drop columns from the right
rather than truncate every cell, so the daemon's column order is also its
priority order.

## 3.B.6 Progress output

How far along the work is.

| State | Meaning |
|---|---|
| `value` | Progress so far. |
| `max` | The whole; absent means indeterminate. |

## 3.B.7 Log output

Accumulating lines of detail.

| State | Meaning |
|---|---|
| `lines` | The lines so far. |
| `append` | *In a sparse patch only:* lines to add. |

`append` exists so progress detail need not resend the backlog; the daemon
folds appended lines into `lines` (§3.10), so a late joiner receives the
accumulated state.

## 3.B.8 Actions

An action has these state fields:

| State | Meaning |
|---|---|
| `validate` | Default true; false skips §3.9 validation. |
| `primary` | The action an unattended answerer selects. At most one per turn. |
| `destructive` | Selecting this destroys something; a surface SHOULD make it hard to select by accident. |

Answer value: none, ever. The selected action travels in `Answer.action`.

## 3.B.9 Detail

A `table` row and a `text` element can each carry a `detail`: an object of
further facts about what the words stand for, as structure rather than as
text. A row's cells say "931.5 GiB" and nothing of what is on the disk; its
`detail` gives the size in bytes and the partitions. A sentence says the whole
disk will be erased, Windows included; its `detail` gives the disk it is
about.

It exists for a surface that knows the page by its template id (§3.2) and
draws it as more than its elements. Its keys are the daemon's, documented with
the daemon's refs; this chapter defines none. A surface that does not know
them MUST ignore `detail`, and a daemon MUST NOT put there anything a person
needs to answer: a row's cells and note, and a text's words, remain everything
they say to a surface that draws them as they are.

---

# Appendix 3.C Design Background

_Peios Specifications / PGSS / MSIP_

> The design relationships behind independent surfaces, persistent conversations, and semantic element references.

The multi-surface interaction protocol (MSIP) separates operation authority
from presentation. The daemon describes questions and outputs through a
shared element vocabulary, so a different renderer can implement the same
contract.

## 3.C.1 Related protocols

Logon (§2) also separates a privileged requester from an untrusted renderer.
It uses a single connection without attachment, persistence, or broadcast.
MSIP retains a separate protocol because its conversations can outlive
connections and support several attached surfaces.

The original design review also considered PAM, Debconf, Subiquity, polkit,
and systemd password agents. The repository archive retains that review.
Those comparisons are design background, not conformance requirements or
claims that the protocols are interchangeable.

## 3.C.2 Arbitration and identity

Broadcast with first-valid-answer arbitration avoids assigning a controlling
surface. Sequence numbers identify the outstanding turn and make competing
late answers stale. The protocol needs no takeover or detach negotiation.

Stable element refs identify questions independently of the path through a
conversation. Template ids identify compatible page shapes. Neither promises
a fixed sequence of pages or determines what an action means.

---

# 4.1 Scope and Roles

_Peios Specifications / PGSS / Icons_

> What PGSS Icons specifies and who its parties are — an icon as a name, themes as the directories that give a name a picture, and the rules by which any file is given a name.

This chapter specifies **PGSS Icons**: how a program, a file, a
directory or a kind of thing on a Peios system is given an icon, and
where the icon comes from.

The chapter rests on one decision. An icon is a **name**, not a picture.
Every party that has something to say about what a thing looks like says
a name, and a name becomes a picture in one place only: the theme chain
(§4.4). A program carries its name in its own file; a file's owner may
set one on it; a file's own name and its type each yield one. Whoever
draws the thing looks the name up, and a theme that provides the same
name decides how it is drawn.

Two roles participate.

The **provider** puts icons where they can be found, and says which one
a thing has. A package that installs an icon into a theme is a provider.
So is a program that carries the name of its icon, and so is a person
who sets a name on a file they own.

The **consumer** draws. Given a thing, it finds the name by the rules of
§4.5 and the picture by the rules of §4.4, and draws what it finds. A
launcher, a taskbar, a file explorer and a compositor drawing window
frames are all consumers, and a provider cannot tell them apart.

Both roles are publicly implementable. A third party MAY ship a theme, a
program carrying an icon, or a consumer, and interoperate with the rest
unchanged. A consumer that draws icons for things it did not make MUST
find them as specified here, precisely so that a provider need say what
a thing looks like once, to everyone.

This chapter covers:

- what a name is, and which names mean what (§4.3)
- what a theme is, where themes are, and how a name becomes a file
  (§4.4)
- how a consumer finds the name for a file: the sources it consults and
  the order it consults them in (§4.5)
- how a file's type yields a name (§4.6)
- the names every system has (§4.A)

This chapter does not cover:

- What a program *is* to a desktop: its title, what it opens, how it is
  started. That is PGSS Applications (§5), which gives a program an
  icon by name under §4.5.
- How a consumer determines a file's type. §4.6 takes the type as
  given.
- How a consumer draws a picture, at what size, or in what color.
  Rendering is the consumer's.
- Pictures that are not icons: a thumbnail of a photograph, a preview of
  a document. A consumer that shows those shows them instead of an icon,
  by rules of its own.

---

# 4.2 Terminology

_Peios Specifications / PGSS / Icons_

> The nouns this chapter is specified in — icon, identifier, theme, base theme, chain, subject, source.

**Icon.** A picture that stands for a thing: a program, a file, a kind
of file, a directory. In this chapter an icon is always referred to by
its identifier, and the picture is whatever the theme chain gives that
identifier.

**Identifier.** The name of an icon: a short string in the form of §4.3.
`generic`, `inode-directory` and `dev.peios.gxwi.hello` are identifiers.

**Theme.** A directory holding one picture per identifier it provides,
in the form of §4.4. A theme provides an identifier if the directory
holds a file named for it.

**Base theme.** The theme every system has, on which every other stands.
It is where a program's own icon is installed, and it provides every
identifier of §4.A.

**Chain.** The ordered list of themes a consumer looks in. The chain is
the system's, not the consumer's: it is set as §4.4 says, and it always
ends in the base theme.

**Subject.** The thing a consumer wants an icon for: a path on the
filesystem, usually. §4.5 gives the rules for a path; a specification
that gives icons to other kinds of subject says how they yield an
identifier.

**Source.** One place an identifier for a subject may come from: the
file's extended attribute, the section a program carries, the file's
name, the file's type. §4.5 lists the sources and the order they are
consulted in.

Terms defined in PCDS (security descriptor) and in the Peios Kernel
TRM (extended attribute) are used with the same meaning and are not
redefined. *Media type* is used as RFC 6838 defines it.

---

# 4.3 Identifiers

_Peios Specifications / PGSS / Icons_

> The form of an icon's name, the prefixes that carry meaning, and which names a program may take for its own.

An identifier is a string of 1 to 255 bytes, each a lowercase ASCII
letter, an ASCII digit, `.`, `_` or `-`, whose first byte is a letter or
a digit:

```
identifier = first *254 rest
first      = %x61-7A / %x30-39
rest       = first / "." / "_" / "-"
```

A consumer MUST treat a string of any other form as no identifier: it
is not looked up, and the source it came from is passed over as though
it had said nothing (§4.5). This is what keeps a name from naming a
path: no identifier contains `/`, and none begins with `.`.

Identifiers are compared byte for byte. There is no case folding,
because there is no case.

## 4.3.1 Meaningful forms

Some forms of identifier are given meaning by this chapter, and a
provider MUST NOT use them for anything else:

| Form | Meaning | Defined in |
|---|---|---|
| `generic` | The icon of last resort | §4.5 |
| `directory-<name>` | A directory called `<name>` | §4.5 |
| `file-<name>` | A file called `<name>` | §4.5 |
| `<type>-<subtype>` | A file of that media type | §4.6 |
| `<type>` | A file of any subtype of that media type | §4.6 |

The set is closed. A future version of this chapter MAY add a form; a
provider MUST NOT invent one.

## 4.3.2 A program's own

A program's own icon is named for the program, in the reverse-DNS form
its package is named in (PSPU §5.3): `dev.peios.gxwi.hello`. The
package that installs the program installs the icon into the base
theme under that name, and the program carries the name (§4.5).

A provider MUST NOT install an icon under a name that is another
provider's, and a package manager MAY refuse a package that would. The
reverse-DNS form makes that a matter of who owns the domain.

> [!NOTE]
> The standard names of §4.A, the forms above and reverse-DNS names
> cannot collide: a reverse-DNS name has a dot in its first label
> position where the others have a hyphen or nothing. A theme can
> therefore provide all three kinds in one flat directory.

---

# 4.4 Themes

_Peios Specifications / PGSS / Icons_

> What a theme is on disk, where the chain is set, how a consumer turns an identifier into a file, and what the base theme must provide.

A theme is a directory under `/usr/share/icons/`, named for the theme,
holding one file per identifier it provides:

```
/usr/share/icons/<theme>/<identifier>.svg
```

A theme's name has the form of an identifier (§4.3). A theme is flat: a
consumer MUST NOT look in subdirectories of a theme, and a provider
MUST NOT put anything there that a consumer is meant to find.

## 4.4.1 Format

A theme's file is an SVG document. This version of the chapter
recognizes no other format: a file with another extension is not an
icon, whatever it holds.

An icon is drawn at whatever size the consumer needs, so a provider
SHOULD draw for a square canvas and SHOULD make sure the picture reads
at 16 pixels. A consumer draws the document as an image and MUST NOT
run any script in it.

> [!NOTE]
> Vector icons are what let a theme be one flat directory: there is no
> ladder of sizes to arrange, and no index is needed to find the right
> rung. A raster format, if a later version admits one, is an extension
> of the file's name and not of the theme's shape.

## 4.4.2 The base theme

The base theme is the directory `/usr/share/icons/base/`. Every system
MUST have it, and it MUST provide every identifier listed in §4.A.

The base theme is where a provider installs a program's own icon
(§4.3). Another theme MAY provide the same identifier, and is then
consulted first.

## 4.4.3 The chain

The chain is the ordered list of themes a consumer looks in. It is set
in the registry, so that every consumer on the system looks in the same
places:

| Key | Value | Type | Meaning |
|---|---|---|---|
| `Machine\Generic\Icons` | `Themes` | `REG_MULTI_SZ` | Theme names, first consulted first |

A consumer MUST append the base theme to whatever the value names, and
MUST ignore the base theme where the value names it, so that the chain
always ends in the base theme and nowhere else. An entry that is not in
the form of an identifier, or names a directory that is not there, is
passed over. The value absent, or the key absent, is a chain of the base
theme alone.

A consumer reads the chain when it starts and MAY read it again. A
change to the chain takes effect for a consumer when it next reads it.

## 4.4.4 Lookup

A consumer looks an identifier up by trying each theme in the chain, in
order, for a file named for the identifier, and takes the first it
finds. The lookup of an identifier no theme provides fails; §4.5 says
what a consumer does then.

A consumer MUST check the identifier's form before it looks it up
(§4.3). The form admits no `/` and no leading `.`, so a well-formed
identifier can name nothing outside the theme's directory.

## 4.4.5 Caching

Nothing in this chapter requires a consumer to keep any state between
lookups, and the flat form of a theme is chosen so that none is needed.
A consumer that nevertheless remembers a lookup MUST notice when the
theme's directory or the chain changes, or MUST say, in its own
documentation, how stale a remembered result may be.

---

# 4.5 From a File to an Identifier

_Peios Specifications / PGSS / Icons_

> The sources a consumer consults for a path's icon — a governing specification, the owner's attribute, the program's section, the name, the type — in order, and the icon of last resort.

Given a path, a consumer finds the identifier to draw by consulting the
sources below in order, and taking the first identifier that the chain
provides (§4.4). A source that yields no identifier, or one the chain
does not provide, is passed over and the next is consulted. If every
source is passed over, the identifier is `generic`, which the base
theme provides (§4.A).

A consumer MUST consult the sources in this order and MUST NOT skip
one.

## 4.5.1 A governing specification

A specification that says what a kind of file means to a desktop MAY
also say what icon it has. A consumer that implements such a
specification applies it first, and if it yields an identifier the
chain provides, that is the icon.

Such a specification MUST yield an identifier, to be looked up under
§4.4 like any other, and MUST NOT yield a picture.

> [!NOTE]
> This is the step by which a declaration that a program is an
> application, with a title and the types it opens, gives the program
> an icon. That declaration is PGSS Applications' (§5.5); this chapter
> only leaves it the first word.

## 4.5.2 The owner's word

A file or directory MAY carry the extended attribute `user.pgss.icon`,
whose value is an identifier. The attribute is the word of whoever owns
the file, and is consulted second.

A consumer MUST treat a value that is not in the form of an identifier
as no value. A consumer MAY treat a value ending in a NUL byte as
though the NUL were absent.

Because the attribute is in the `user` namespace, whoever can write the
file can set it, and it can be set on regular files and directories
only. A file that cannot carry an attribute is drawn by the sources
that follow.

## 4.5.3 The program's word

A regular file that is an ELF object MAY carry a section named
`.pgss.icon`, whose contents are an identifier, optionally followed by a
NUL byte and nothing else. The section is the word of whoever built the
program, and is consulted third.

A consumer finds the section by the object's section header table, by
name, and takes the first section of that name. A consumer MUST NOT
execute or load the object to find it, and MUST bound what it reads: a
header that points outside the file, a section header table of
implausible size, or a section longer than an identifier could be, is
no section.

A file that is not an ELF object, or is one without the section, is
drawn by the sources that follow.

> [!NOTE]
> The section holds a name and not a picture on purpose. A program that
> carried its own SVG could not be restyled by a theme, and a consumer
> listing a directory of programs would be handed a picture by every
> one of them. A name is a few bytes, and it is the theme's to draw.

## 4.5.4 The name

The fourth source is the file's own name. For a directory the candidate
is `directory-` followed by the name; for anything else it is `file-`
followed by the name; in both the name is converted to lowercase ASCII
first. If the result is not in the form of an identifier, which is so
for any name with a space or a non-ASCII character in it, the source
yields nothing.

So a directory called `Documents` is drawn as `directory-documents` if
the chain provides it, and a file called `Makefile` as `file-makefile`.
Which such names a theme provides is the theme's business; a consumer
MUST NOT special-case any.

## 4.5.5 The type

The fifth source is the file's type, which yields identifiers as §4.6
says.

## 4.5.6 Symbolic links

A consumer that shows a symbolic link as the thing it points to
consults the sources for the target. A consumer that shows it as a
link consults them for the link itself, and a link, being unable to
carry an attribute, is then drawn by its name or its type. A link whose
target does not exist is drawn as `generic`.

## 4.5.7 What an icon is not

An icon is what a thing looks like, and is chosen by parties that can
say anything. A consumer MUST NOT infer from a subject's icon what the
subject is, what it will do, or who made it. A file drawn as a program
is not thereby a program.

---

# 4.6 File Types

_Peios Specifications / PGSS / Icons_

> How a file's media type yields identifiers, in what order they are tried, and the two types every consumer can determine.

A file's type is a media type, `text/x-python`, `image/png`,
`inode/directory`. How a consumer determines it is outside this
chapter: by the file's name, by its contents, by a table of its own, or
by asking something else. This chapter says only what a type yields
once known.

## 4.6.1 From a type to identifiers

A media type yields two identifiers, tried in order:

1. The whole type, `<type>/<subtype>`, with `/` replaced by `-`.
2. The top-level type alone.

Any character in either that is not permitted in an identifier is
replaced by `-`, and the result is lowercase. So `image/svg+xml` yields
`image-svg-xml` and then `image`, and `text/x-python` yields
`text-x-python` and then `text`. The second lets a theme draw every
kind of text alike and still draw Python apart when it cares to.

A consumer MUST try both, in that order, and pass on to `generic`
(§4.5) when the chain provides neither.

## 4.6.2 Types every consumer determines

Whatever else it knows, a consumer MUST determine these:

| The file is | Type |
|---|---|
| A directory | `inode/directory` |
| A regular file that may be executed, and nothing better is known | `application/x-executable` |

"May be executed" means what it means to the system the consumer runs
on; on Peios, that the file's security descriptor grants the consumer
execute access.

## 4.6.3 Determining a type

A consumer MAY determine a type from the file's name alone, and a
consumer listing a directory usually should: reading every file to
sniff its contents is the cost that a name is meant to spare. A
consumer that reads contents MUST bound what it reads.

> [!NOTE]
> There is no system-wide table of types in this version. A consumer
> ships its own, which is enough for icons: a type a consumer does not
> know is drawn as `generic`, and nothing is misdrawn. A shared table is
> a matter for whichever chapter first needs two consumers to agree on
> what a file *is*, which is more than what it looks like.

---

# 4.7 Extension

_Peios Specifications / PGSS / Icons_

> What may be added to this chapter without breaking a conforming consumer or provider, and what may not.

## 4.7.1 Additive changes

The following are additive, and a consumer or provider built to this
version behaves correctly in their presence:

- A new identifier in §4.A. A theme that lacks it is a theme that does
  not provide it, which every consumer already handles.
- A new theme in the chain. A consumer built to this version looks in
  it like any other.
- A new source in §4.5, consulted after the type. A consumer built to
  this version draws `generic` where a newer one would draw the new
  source's icon.
- A new governing specification, consulted first under §4.5.

## 4.7.2 Changes requiring a new version

- A new file format in a theme (§4.4). A consumer built to this version
  does not find the file, so the identifier is not provided, so every
  subject that relies on it is misdrawn as something further down the
  chain.
- A new meaningful form of identifier (§4.3), since the set is closed.
- A change to the order of §4.5, or a source inserted before the type.
  Two consumers on one system would then disagree about what a file
  looks like.
- A change to the form of an identifier.

## 4.7.3 Reserved

The `pgss.icon` name, in the `user` extended-attribute namespace and as
the suffix of a section name, is this chapter's. A specification that
wants a file to carry something else MUST use another name.

---

# 4.8 Conformance

_Peios Specifications / PGSS / Icons_

> The obligations of each role, gathered in one place.

## 4.8.1 A conforming consumer

- Treats as an identifier only a string in the form of §4.3, and looks
  up nothing else.
- Looks in the themes of the chain in order, in `/usr/share/icons/` and
  in no subdirectory of a theme, for `<identifier>.svg`, and takes the
  first (§4.4).
- Reads the chain from `Machine\Generic\Icons` `Themes`, appends the
  base theme, and ignores the base theme anywhere else in the value
  (§4.4).
- Draws an SVG as an image and runs nothing in it (§4.4).
- Notices a change to a theme or the chain, or documents how stale a
  remembered lookup may be (§4.4).
- For a path, consults a governing specification, then
  `user.pgss.icon`, then `.pgss.icon`, then the name, then the type, in
  that order, and draws the first identifier the chain provides, or
  `generic` (§4.5).
- Finds `.pgss.icon` by the section header table, without executing or
  loading the object, and within bounds (§4.5).
- Derives the name source's identifier by lowercase ASCII conversion
  and prefix alone, and special-cases no name (§4.5).
- Yields from a type the whole type and then the top-level type, and
  determines at least a directory and an executable (§4.6).
- Infers nothing about a subject from its icon (§4.5).

## 4.8.2 A conforming provider

- Installs a theme as a flat directory of `<identifier>.svg` under
  `/usr/share/icons/<theme>/`, with the theme's name in the form of an
  identifier (§4.4).
- Uses a meaningful form of identifier for its meaning and no other,
  and a reverse-DNS name for a program's own icon (§4.3).
- Installs a program's own icon into the base theme, under a name
  within a domain it owns (§4.3).
- Carries a program's icon as an identifier in `.pgss.icon`, or sets
  one in `user.pgss.icon`, and never a picture (§4.5).

## 4.8.3 A conforming system

- Has the base theme at `/usr/share/icons/base/`, providing every
  identifier of §4.A (§4.4).

## 4.8.4 What conformance does not require

Conformance does not require a consumer to determine any file type
beyond a directory and an executable, to show thumbnails, to cache
anything, or to draw an icon at any particular size. It does not require
a provider to install more than the base theme.

---

# Appendix 4.A Standard Identifiers

_Peios Specifications / PGSS / Icons_

> The identifiers the base theme provides on every system, so that a consumer always has something to draw.

The base theme MUST provide every identifier below (§4.4). Another theme
MAY provide any of them. The set is closed for this version; a later
version MAY add to it (§4.7).

## 4.A.1 Last resort

| Identifier | Drawn for |
|---|---|
| `generic` | Anything no other source gives an icon (§4.5) |

## 4.A.2 Types

The identifiers the two types every consumer determines yield (§4.6),
and the top-level types a consumer is most likely to determine from a
name.

| Identifier | Drawn for |
|---|---|
| `inode-directory` | A directory |
| `application-x-executable` | A program |
| `application` | A file of any other `application/` type |
| `text` | A file of any `text/` type |
| `image` | A file of any `image/` type |
| `audio` | A file of any `audio/` type |
| `video` | A file of any `video/` type |

## 4.A.3 Named directories

The directories a person is most likely to keep, by the names they are
most likely to have (§4.5).

| Identifier | Drawn for |
|---|---|
| `directory-documents` | A directory called `Documents` |
| `directory-downloads` | A directory called `Downloads` |
| `directory-pictures` | A directory called `Pictures` |
| `directory-music` | A directory called `Music` |
| `directory-videos` | A directory called `Videos` |

---

# Appendix 4.B Prior Art

_Peios Specifications / PGSS / Icons_

> Where this chapter sits against the freedesktop icon specifications, Windows shell icons and MSIX, and which resemblances are deliberate.

## 4.B.1 The freedesktop icon theme and naming specifications

This chapter is, in outline, freedesktop's: an icon is a name, a theme
is a directory that gives names pictures, themes stand in a chain that
ends in `hicolor`, and a standard vocabulary lets one theme restyle a
whole desktop. What it drops is the size ladder and the index that the
ladder made necessary: with one vector file per name a theme is flat,
and there is no `icon-theme.cache` to rebuild. It also drops the
`Icon=` line of a desktop file as the only way a program gets a name,
in favor of the program carrying it.

The name source (§4.5) is not freedesktop's, which gives `Documents`
and `Downloads` their icons by configured path rather than by name. By
name is simpler and needs no configuration, and the editor icon themes
that color a `src` directory apart from a `test` one show what it is
for.

## 4.B.2 Windows

Windows puts the picture in the program: a PE file carries icon
resources, a shortcut or a registry `DefaultIcon` value points at
`path,index`, and the shell extracts what it finds. That gives a raw
executable an icon anywhere it is copied, which this chapter keeps by
having the program carry a name. It also makes every consumer a parser
of executables and every listing an extraction, which is why the shell
caches, and why this chapter has the program carry a name and not a
picture.

MSIX moved a packaged program's icons out of the binary into image
files named in the package manifest, which is the shape this chapter
gives a program's own icon: a file installed under a name the program
declares.

## 4.B.3 Design influences

**One resolver.** Every source yields a name, and a name becomes a
picture in one place, so that a theme restyles programs as well as
folders, and so that two consumers on one system cannot disagree about
what a file looks like without one of them being wrong.

**The owner's word above the program's.** `user.pgss.icon` is consulted
before `.pgss.icon` because an attribute is set on a particular file by
whoever has it, and a section is set on every copy by whoever built it.
The particular overrides the general, as a custom folder icon overrides
the folder icon.

**A hint, not a claim.** Anyone who owns a file can make it look like
anything, as anyone can on any other system. The chapter says so once
(§4.5) so that no consumer is built to trust it.

---

# 5.1 Scope and Roles

_Peios Specifications / PGSS / Applications_

> What PGSS Applications specifies and who its parties are — a program declared to a desktop by a file, the directory of such files as the catalog, and the rules by which a consumer lists, names, starts and opens with an application.

This chapter specifies **PGSS Applications**: what a program *is* to a
desktop on a Peios system. Its title, the icon it has, how it is
started, and what kinds of file it opens.

The chapter rests on one decision. An application is a **declaration**,
not a place. A program is not an application because of the directory
it is installed in or the name it is installed under, and a desktop
does not find applications by looking at programs. A package that ships
an application also installs one small file that says what it is, and
the directory of those files is the catalog (§5.4). Presence is the
catalog: nothing runs at install, nothing registers, and nothing
indexes.

Two roles participate.

The **provider** declares. A package that installs a program and its
declaration is a provider.

The **consumer** reads the declarations and acts on them. A launcher
that lists what can be started, a dock or taskbar that names a running
program, a file explorer that offers what opens a file, and a
compositor that starts what a launcher picks are all consumers, and a
provider cannot tell them apart.

Both roles are publicly implementable. A third party MAY ship an
application, or a consumer, and interoperate with the rest unchanged. A
consumer that lists, names or starts applications MUST find them as
specified here, precisely so that a provider need say what a program is
once, to everyone.

This chapter covers:

- what a declaration is, where it is, and what it says (§5.3)
- what the catalog is, and how a consumer reads it (§5.4)
- how a consumer finds the declaration for a program it has met,
  running or on disk, and so the program's title and icon (§5.5)
- how a consumer starts an application, bare or with a file (§5.6)
- which application opens a type of file when several could: the
  choices a person and the machine make, where they are kept, and how a
  consumer finds the default from them (§5.7)

This chapter does not cover:

- How a program that offers to set choices presents them. §5.7 says
  where a choice is kept and who may write it; a settings application's
  shape is its own.
- Declarations of a person's own, or of a system's local layer, beyond
  what the catalog's directory admits. This version has one catalog.
- How a consumer determines a file's type. §5.6 takes the type as given,
  as PGSS Icons §4.6 does.
- What a program does once started, or how a consumer confines it. The
  environment a consumer starts a program in is the consumer's.
- What a program looks like. That is PGSS Icons (§4); this chapter
  gives a program an icon by name, under §4.5, and says nothing about
  pictures.

---

# 5.2 Terminology

_Peios Specifications / PGSS / Applications_

> The nouns this chapter is specified in — application, declaration, id, catalog, program, title, listed, media type pattern, candidate, choice, default.

**Application.** A program as a desktop knows it: something with a
title that can be started from a launcher or opened with. In this
chapter an application is always what a declaration says, and nothing
is an application without one.

**Declaration.** The file that says what an application is, in the form
of §5.3. One file declares one application.

**Id.** The name of an application: the reverse-DNS string the
declaration's file is named for, in the form of an icon identifier
(PGSS Icons §4.3). `dev.peios.gexora` is an id.

**Catalog.** The directory holding every declaration on the system,
in the form of §5.4. A consumer that wants to know what applications
there are reads it.

**Program.** The file a declaration says to run: an absolute path. The
program is what a consumer executes, and what a consumer matches a
running process against (§5.5).

**Title.** What an application is called wherever a consumer shows it
to a person.

**Listed.** Whether a launcher shows the application among what can be
started. An application that is not listed is still an application: it
can be opened with, and a running one is still named by its
declaration.

**Media type pattern.** Either a media type, `image/png`, or a
top-level type and `*`, `image/*`, which stands for every subtype of
it. A declaration says what an application opens in these.

**Candidate.** An application that says it opens a file's media type,
and so may open the file (§5.6).

**Choice.** A media type pattern and the id of the application chosen
to open it, kept in the registry by a person for themselves or for the
machine as a whole (§5.7).

**Default.** The application a consumer opens a file with when it picks
one: the candidate the choices give the file's type, by the order of
§5.7. A type no usable choice is for has no default.

Terms defined in PGSS Icons (identifier, chain, consumer as one who
draws) are used with the same meaning and are not redefined, and nor are those of the registry (key, value, `REG_SZ`,
`CurrentUser\`), which are the Peios Kernel TRM's, or security
descriptor, which is PCDS's. *Media type* is used as RFC 6838 defines
it. *TOML* is the format at
toml.io, version 1.0.

---

# 5.3 The Declaration

_Peios Specifications / PGSS / Applications_

> One TOML file per application, named for its id, saying its title, its program, its icon, what it opens and whether it is listed — and what a consumer makes of one that is malformed.

A declaration is a file in the catalog's directory (§5.4), named for
the application's id:

```
/usr/share/apps/<id>.toml
```

The file's name is the declaration's id. Nothing in the file repeats
it, so the two cannot disagree.

## 5.3.1 The id

An id has the form of an icon identifier (PGSS Icons §4.3): 1 to 255
bytes of lowercase ASCII letters, digits, `.`, `_` and `-`, beginning
with a letter or a digit. A consumer MUST treat a file whose name,
before `.toml`, is of any other form as no declaration.

An id is reverse-DNS, within a domain the provider owns, in the form a
package is named in (PSPU §5.3): the package's own name, or a name
beneath it when one package ships more than one application. A provider
MUST NOT install a declaration under an id in another provider's
domain, and a package manager MAY refuse a package that would.

> [!NOTE]
> The id doubles as the default name of the application's icon. PGSS
> Icons §4.3 has a program's own icon named for its package in the same
> form, so the common case, one package, one program, one icon, needs
> no `icon` line and no second name.

## 5.3.2 The file

The file is a TOML document whose top-level table has these keys:

| Key | Type | Meaning |
|---|---|---|
| `title` | string | What the application is called. One line, not empty. Required. |
| `program` | string | The file to run: an absolute path. Required. |
| `arguments` | array of strings | What the program is always started with, in order, before anything else. Empty when absent. |
| `icon` | string | The identifier of its icon (PGSS Icons §4.3). The id when absent. |
| `description` | string | One line on what it is for. None when absent. |
| `opens` | array of strings | The media type patterns it opens. Empty when absent. |
| `listed` | boolean | Whether a launcher lists it. `true` when absent. |

An example, complete for a file explorer:

```toml
title = "Gexora"
description = "Browse the files on this system"
program = "/usr/bin/gexora"
opens = ["inode/directory"]
```

A provider MUST write a declaration that a TOML 1.0 parser accepts, and
MUST NOT rely on any key not in the table above being read.

## 5.3.3 What a consumer makes of it

A consumer MUST ignore a key it does not know. That is how a later
version of this chapter adds to a declaration (§5.8) without breaking
a consumer built to this one.

A declaration is **unusable**, and a consumer MUST treat it as no
declaration, when any of these holds:

- the file is not a TOML document a TOML 1.0 parser accepts
- `title` is absent, is not a string, is empty or is more than one line
- `program` is absent, is not a string, or is not an absolute path
- a key in the table is present with a value of another type

A consumer SHOULD say on its own log which file was unusable and why,
so that a broken package can be found, and MUST go on to the rest of
the catalog.

A declaration that is merely odd is set right, not thrown away:

- an `icon` that is not in the form of an identifier is treated as
  absent, and the icon is the id
- an entry in `opens` that is not a media type pattern is left out
- leading and trailing whitespace on `title`, `description` and `icon`
  is not part of the value

`arguments` is passed as given, byte for byte, with no whitespace
splitting, no quoting and no expansion (§5.6). A declaration is data,
and no part of it is a command line.

> [!NOTE]
> The program is an absolute path and not a name looked up along a
> `PATH` on purpose. A launcher runs what a package installed, and a
> file of the same name earlier on somebody's path is not it.

---

# 5.4 The Catalog

_Peios Specifications / PGSS / Applications_

> The directory of declarations, read whenever a consumer needs the list — no registration, no index, no cache required.

The catalog is the directory `/usr/share/apps/`. Every system MUST
have it, and it MUST be readable by anyone who can log on to a desktop:
every consumer reads it as the person it runs for.

The catalog is flat. A consumer MUST NOT look in subdirectories of
it, and a provider MUST NOT put anything there that a consumer is meant
to find. A file in it whose name does not end in `.toml`, or whose name
before `.toml` is not in the form of an id (§5.3), is not a declaration
and MUST be passed over.

## 5.4.1 Presence is the catalog

A declaration is in the catalog when its file is in the directory,
and out of it when the file is gone. Nothing else is required of a
provider: no command at install, no index to rebuild, no notice to any
consumer. A package that installs a declaration has shipped an
application, and one that removes it has withdrawn it.

A consumer MUST NOT require a provider to do anything beyond installing
the file.

## 5.4.2 Reading it

A consumer that needs the list reads the directory, and reads each
declaration by the rules of §5.3. A consumer that needs one application
by id MAY read that file alone, at `<id>.toml`, after checking the
id's form: the form admits no `/` and no leading `.`, so a well-formed
id can name nothing outside the directory.

A consumer SHOULD leave out of any list a declaration whose program is
not a regular file. Nothing is there to start, and a package that is
half installed or half removed should not be offered.

A consumer MAY order what it lists however it likes; a provider MUST
NOT rely on any order.

## 5.4.3 Caching

Nothing in this chapter requires a consumer to keep any state between
reads, and a catalog of a few hundred files is meant to be read
whenever a launcher opens. A consumer that nevertheless remembers what
it read MUST notice when the directory changes, or MUST say, in its own
documentation, how stale a remembered result may be.

> [!NOTE]
> This is the shape of PGSS Icons' theme (§4.4): a flat directory that
> is its own index. The desktop-file databases that other systems rebuild
> after every install exist because those catalogs could be anywhere and
> hold anything; a catalog that is one directory of small files needs none.

---

# 5.5 From a Program to its Declaration

_Peios Specifications / PGSS / Applications_

> How a consumer that has met a program — a running process, or a file — finds the application it is declared as, and so its title and icon.

A consumer often meets a program before it meets a declaration: a
compositor sees a process connect, a taskbar is told of its windows, a
file explorer lists an executable. This section says how such a
consumer finds the declaration, if there is one, and what it gets from
it.

## 5.5.1 Matching

A program matches a declaration when the program's file and the
declaration's `program` are the same file. Two paths name the same file
when they resolve, through every symbolic link, to the same path, or
when they refer to the same inode on the same device. The second is for
a system that presents one file at more than one path, as Peios' merged
views do (`/bin` over `/usr/bin`).

A consumer MUST match by file and MUST NOT match by name: a file called
`gexora` anywhere is not thereby Gexora.

For a running process, the program's file is the executable the process
is running, which on Peios is reached through `/proc/<pid>/exe`. A
consumer SHOULD match through the process rather than through the path
the process was started by, since the path may since have been
replaced.

When more than one declaration names the same program, the consumer
takes the one whose id sorts first, byte by byte. A provider SHOULD NOT
declare one program twice.

## 5.5.2 What the match gives

A program that matches a declaration **is** that application, and a
consumer showing it to a person SHOULD show the declaration's title
where it names the program as a whole, such as under a dock's icon,
whatever its windows are called. A window keeps its own title.

The declaration gives the program its icon. Under PGSS Icons §4.5, this
chapter is a governing specification, and the identifier it yields for
a program is the declaration's `icon`. A consumer that implements both
chapters consults it first: if the chain provides the identifier, that
is the icon, and if not, the consumer goes on to the sources §4.5 lists
after it. A program that matches no declaration is drawn by those
sources alone.

A consumer MUST NOT infer from a match anything the declaration does
not say. In particular, a declaration says nothing about who built the
program or whether it is trusted; it says what a package chose to call
it.

---

# 5.6 Starting and Opening

_Peios Specifications / PGSS / Applications_

> What a consumer runs to start an application bare or with a file, what it passes and how, which applications are candidates to open a file and which of them it picks, and what a consumer must take from the catalog rather than from a request.

## 5.6.1 Starting

To start an application, a consumer executes its `program` with its
`arguments`, in order, as the process's arguments after the program's
own name. Each argument is passed as one argument, byte for byte. A
consumer MUST NOT pass the program or the arguments through a shell,
MUST NOT split, join, quote or expand them, and MUST NOT look the
program up along a path: it is absolute.

What else the process is started with, its environment, its working
directory, its standard streams, what it is confined by, is the
consumer's. A compositor puts its display in the environment so that
the program can be an app; a consumer of another kind does whatever
its kind does.

A consumer MAY let a person add arguments of their own, as a launcher
does with the words typed after the application's name. They follow the
declaration's.

## 5.6.2 Opening

To open a file with an application, a consumer starts it as above with
one more argument last: the file's path, absolute. A file's path is
never put anywhere but last, and there is no placeholder syntax in this
version: a declaration whose `arguments` contains `%f` or `{file}` has
an argument that is those characters.

An application whose `opens` contains a pattern that a file's media
type matches is a **candidate** to open the file. A media type matches
`type/subtype` when it is equal to it, ignoring case, and matches
`type/*` when its top-level type is `type`. How the consumer knows the
file's type is its own, as in PGSS Icons §4.6.

A consumer that opens a file offers the candidates, or picks one of
them; which it does is the consumer's. A consumer that picks MUST pick
the file's default when its type has one (§5.7), and picks by a rule of
its own only when it has none. A consumer that offers SHOULD offer the
default first, or otherwise show which it is. A consumer MUST NOT read
a default from anywhere §5.7 does not name.

An application with no `opens` is a candidate for nothing, and is
started bare.

## 5.6.3 From the catalog, not from the request

A consumer often starts an application because something asked it to,
and the something is not always trustworthy: a page in a browser, a
message from another process. A consumer that starts an application on
a request that names it by id MUST take the program and the arguments
from the catalog as it stands at that moment, and MUST NOT take a
program or arguments from the request. The request says which
application; the declaration says what runs.

A request that names an id the catalog has no usable declaration for
starts nothing.

> [!NOTE]
> This is why a declaration is data and never a command line, and why
> the program is matched by file (§5.5) and named by absolute path
> (§5.3). A consumer that follows this section cannot be made to run
> anything a package did not install, whatever it is asked.

---

# 5.7 Defaults

_Peios Specifications / PGSS / Applications_

> Which application opens a type of file when several could — the person's choice, else the machine's — where each is kept in the registry, how a consumer finds the default from them, and who may set them.

A person may choose which application opens a type of file, and so may
whoever administers the machine, for everyone on it. Each such
**choice** is one value in the registry. The **default** for a media
type is the application the choices give it, by the rules of this
section, and it is what a consumer that picks among the candidates
(§5.6) opens a file with.

## 5.7.1 Where choices are kept

There are two places, each a registry key:

| Key | Whose choices |
|---|---|
| `CurrentUser\Generic\Applications\Defaults` | The person's. The kernel routes `CurrentUser\` to the caller's own `Users\<SID>\`, so each person has their own. |
| `Machine\Generic\Applications\Defaults` | The machine's: everyone's on it, for whatever they have not chosen themselves. |

Each value of either key is one choice:

| Part | Is |
|---|---|
| Name | A media type pattern (§5.2): the type the choice is for, `image/png`, or a top-level type and `*`, `image/*`. |
| Type | `REG_SZ`. |
| Data | The id (§5.3) of the application chosen, in UTF-8, with or without a terminating NUL. |

The registry compares value names ignoring case, as media types are
compared (§5.6), so one key holds at most one choice for a type however
it is spelt. A writer SHOULD write the name in lowercase. A consumer
reads the name ignoring case, and the data with leading and trailing
whitespace removed.

A value whose name is not a media type pattern, whose type is not
`REG_SZ`, or whose data is not in the form of an id is no choice. A
consumer passes over it, SHOULD say on its own log which value it
passed over and why, and goes on to the rest of the key.
[*applications.defaults.malformed-value-is-no-choice]

A key that is absent has no choices, and neither has one the consumer
may not read. Neither is an error. Anything in either key other than
its values, such as a subkey, is reserved (§5.8) and a consumer MUST
ignore it.

The person's choices are those of the person the file is opened for. A
consumer that runs as that person reads them through `CurrentUser\`. A
consumer that runs as anyone else MUST NOT read its own `CurrentUser\`
for them, since that is its own key and not the person's; it reads the
person's `Users\<SID>\Generic\Applications\Defaults` if it may, and
otherwise uses the machine's choices alone.
[*applications.defaults.person-is-whom-the-file-is-opened-for]

## 5.7.2 Finding the default

The default for a file whose media type is `type/subtype` is found by
trying these choices in order and taking the first that is usable:

1. the person's choice named `type/subtype`
   [*applications.defaults.order.person-exact]
2. the person's choice named `type/*`
   [*applications.defaults.order.person-pattern]
3. the machine's choice named `type/subtype`
   [*applications.defaults.order.machine-exact]
4. the machine's choice named `type/*`
   [*applications.defaults.order.machine-pattern]

A choice is **usable** for the file when the catalog has a usable
declaration for the id it names (§5.3, §5.4), and that application is a
candidate to open the file (§5.6). A choice that is not usable is
passed over and the next is tried. It is never an error: an application
that has been removed, or that no longer says it opens the type, is
simply no longer anybody's default, and nothing need be done about the
choice that named it. A consumer MAY say on its own log that it passed
one over. [*applications.defaults.unusable-choice-is-passed-over]

When no choice is usable, the type has no default, and a consumer that
picks uses its own rule among the candidates (§5.6).

A choice selects among the candidates and never adds one. A consumer
MUST NOT open a file with an application that is not a candidate for
it, whatever a choice says.
[*applications.defaults.a-choice-adds-no-candidate]

> [!NOTE]
> The person's choices come before the machine's whichever is the more
> particular. A person who chooses one application for `image/*` means
> every image, including the types the machine has chosen something
> else for; the machine's choices are what a person has not decided,
> not what overrules them.

A consumer reads the choices when it picks, or remembers them under the
rule of §5.4 for a remembered catalog: it MUST notice when either key
changes, or MUST say, in its own documentation, how stale a remembered
choice may be.

## 5.7.3 Setting them

A person sets their own choices by writing values in their own key, and
clears one by deleting its value. Whoever may write the machine's key
sets the machine's in the same way. A writer creates each key of the
path that is not there yet, one level at a time: the registry creates
no key on the way to another.

Who may write each key is that key's security descriptor, and nothing
else. A system MUST let every person who can log on to a desktop read
the machine's key, and SHOULD let only administrators write it, as a
Peios system's `Machine` hive does from its root: SYSTEM and
Administrators have full control, and Authenticated Users read. A
person's own key is theirs by the descriptor of their part of the
`Users` hive.

A program that offers to set choices, such as a settings application,
MUST find out whether it may write a key by asking the registry: by
opening the key for writing values, or, where the key is not there yet,
the nearest key above it that is for creating subkeys. It MUST NOT
infer the answer from the groups the person is in, since the
descriptor, and not membership, is what the registry checks.
[*applications.defaults.a-writer-asks-the-registry]

A writer SHOULD offer, for a type, only the applications that are
candidates for it, and for a pattern `type/*`, only those that say they
open `type/*`. It is not an error to write anything else: a choice that
is not usable is passed over when it is read.

> [!NOTE]
> Any program running as a person can change that person's choices, as
> it can change anything else of theirs. This section does not try to
> prevent it, since a program running as the person could as easily do
> whatever it would have done by being the default. What it does
> prevent is a choice opening a file with something that is not a
> candidate, or with something a package did not install.

---

# 5.8 Extension

_Peios Specifications / PGSS / Applications_

> What may be added to this chapter without breaking a conforming consumer or provider, and what may not.

## 5.8.1 Additive changes

The following are additive, and a consumer or provider built to this
version behaves correctly in their presence:

- A new key in a declaration (§5.3). A consumer built to this version
  ignores it, and a declaration that carries it is usable by that
  consumer as far as the keys it knows go. A new key MUST be optional,
  and its absence MUST mean what this version's consumers do.
- A new kind of consumer. A provider has nothing to do for it.
- A new declaration in the catalog, and a new provider.
- A second place for declarations, consulted after the catalog, such
  as a person's own. A consumer built to this version does not see it,
  and shows the system's applications where a newer one would show
  more.
- A subkey of a key of §5.7, or a new key beside `Defaults` under
  either `Applications` key. A consumer built to this version ignores
  them, and finds the same defaults as before.

## 5.8.2 Changes requiring a new version

- A change to the catalog's directory, or a subdirectory a consumer
  is meant to look in (§5.4). A consumer built to this version does not
  find what is there.
- A new file format or extension for a declaration (§5.3).
- A meaning for any sequence of characters in `arguments`, such as a
  placeholder for a file. A consumer built to this version passes it
  through as it is, so an application that relied on it would be
  started wrongly.
- A place for the file's path other than last (§5.6).
- A change to what makes a declaration unusable (§5.3), or to the
  match rule (§5.5). Two consumers on one system would then disagree
  about what is installed, or what a program is.
- A change to where choices are kept, to the form of a choice, or to
  the order they are tried in (§5.7), including a place for choices
  consulted between the person's and the machine's, such as a group's.
  Two consumers on one system would then open one file with different
  applications.

## 5.8.3 Reserved

The directory `/usr/share/apps/` is this chapter's, and so is the
`.toml` extension within it. The keys named in §5.3 are this chapter's:
a specification or a provider that wants a declaration to carry
something else MUST use another key, and SHOULD prefix it with a domain
it owns.

The registry keys `Machine\Generic\Applications` and
`CurrentUser\Generic\Applications`, and everything in them, are this
chapter's. Nothing else may keep anything there.

---

# 5.9 Conformance

_Peios Specifications / PGSS / Applications_

> The obligations of each role, gathered in one place.

## 5.9.1 A conforming consumer

- Reads declarations from `/usr/share/apps/` and no subdirectory of
  it, from files named `<id>.toml` with the id in the form of §5.3, and
  passes over any other file (§5.4).
- Requires nothing of a provider beyond the file's presence (§5.4).
- Reads a declaration by the rules of §5.3: takes the keys it knows,
  ignores the rest, treats an unusable declaration as none and goes on,
  and sets an odd one right as §5.3 says.
- Checks an id's form before making it a path (§5.4).
- Notices a change to the catalog, or documents how stale a
  remembered read may be (§5.4).
- Matches a program to a declaration by file, never by name, and
  through the process for a running one (§5.5).
- Yields the declaration's `icon` as the identifier for the program
  under PGSS Icons §4.5, and goes on to §4.5's other sources when the
  chain does not provide it (§5.5).
- Starts an application by executing its program with its arguments as
  given, without a shell, splitting, quoting, expansion or path lookup,
  and with a file's path last (§5.6).
- Takes the program and arguments from the catalog, never from a
  request that names an id (§5.6).
- When it picks among the candidates, picks the default where the type
  has one, and offers it first, or shows which it is, when it offers
  them (§5.6).
- Finds the default from the person's choices and then the machine's,
  each for the exact type and then for its top-level type and `*`, and
  passes over a choice that is malformed or not usable without treating
  it as an error (§5.7).
- Reads the person's choices as the person the file is opened for, and
  never through a `CurrentUser\` of its own on their behalf (§5.7).
- Opens a file with nothing that is not a candidate for it, whatever a
  choice says, and reads a default from nowhere but §5.7's keys (§5.6,
  §5.7).
- When it offers to set choices, finds out whether it may by asking
  the registry, never by the person's groups (§5.7).
- Infers nothing about a program from a match beyond what the
  declaration says (§5.5).

## 5.9.2 A conforming provider

- Installs a declaration as `/usr/share/apps/<id>.toml`, with the id in
  the form of §5.3 and within a domain it owns.
- Writes a TOML 1.0 document with a one-line `title` and an absolute
  `program`, and relies on no key outside the table of §5.3.
- Does not rely on any order of listing, on any consumer's reading a
  key it does not know, or on any placeholder in `arguments` (§5.3,
  §5.6).
- Does not declare one program twice (§5.5).

## 5.9.3 A conforming system

- Has the catalog at `/usr/share/apps/`, readable by anyone who can
  log on to a desktop (§5.4).
- Lets anyone who can log on to a desktop read
  `Machine\Generic\Applications\Defaults` where it is present, and
  SHOULD let only administrators write it (§5.7).

## 5.9.4 What conformance does not require

Conformance does not require a consumer to list applications in any
order, to show a description, to let a person add arguments, to cache
anything, to determine any file's type, or to offer to set choices. It does not require a
provider to declare every program it installs: a program with no
declaration is a program, and is still drawn and run as one.

---

# Appendix 5.A Prior Art

_Peios Specifications / PGSS / Applications_

> Where this chapter sits against freedesktop desktop entries and MIME applications, Windows' shortcuts, App Paths, registered applications and default choices, MSIX manifests and the former Atrium catalog, and which resemblances are deliberate.

## 5.A.1 The freedesktop desktop entry specification

This chapter is, in outline, a desktop entry: one small file per
application, installed by its package into a shared directory, with a
name, an icon, an executable and the MIME types it handles. `title` is
`Name`, `icon` is `Icon`, `opens` is `MimeType`, and `listed = false`
is `NoDisplay=true` without the double negative.

What it drops is `Exec`. A desktop entry's `Exec` is a command line
with its own quoting rules and a set of field codes, `%f`, `%F`, `%u`,
`%U`, `%i`, `%c`, `%k`, that every consumer must parse and expand, and
that have been the source of most of the specification's errata and
several of its security advisories. This chapter has `program`, an
absolute path, and `arguments`, an array that is passed as it is, with
the file last. There is nothing to parse and nothing to expand.

It also drops `Categories`, `Keywords`, `Actions`, `TryExec`,
`Terminal`, `StartupNotify` and the localised forms of every key,
along with `update-desktop-database` and the `mimeinfo.cache` it
builds. A first version needs a title, a program, an icon and the
types it opens, and a directory that is its own index.

## 5.A.2 Windows

Windows has three answers to what an application is, and this chapter
takes something from each. A Start Menu shortcut is a file in a shared
directory whose presence is the listing, which is the shape of §5.4.
`App Paths` in the registry lets a name resolve to an absolute path
without a `PATH` lookup, which is why `program` is absolute. Registered
applications and `Default Programs` let a program say what it opens,
which is `opens`. The default Windows keeps beside it, a machine's in
`HKEY_LOCAL_MACHINE` and a person's own `UserChoice` under
`HKEY_CURRENT_USER`, is the shape of §5.7: a person's choice before the
machine's, each a registry value.

What this chapter does not take is the registry as the place for
declarations. Peios has a registry and does not use it for them,
because a package installs files, and a file is present or it is not:
there is no second thing to keep consistent with the first. A choice is
another kind of thing. It is not installed by a package but made by a
person, it belongs to someone, and who may change it is a question of
access control. Keeping who-may-change-what is what the registry is
for, and `CurrentUser\` gives each person their own place without a
file in their home directory for every consumer to find.

Windows protects `UserChoice` with a hash, so that a program cannot
quietly make itself a person's default. §5.7 does not: a program
running as a person can already do whatever it would have done by
being the default, so the hash protects little that the person's own
token does not already give away. What a choice can never do here is
add a candidate, or run anything a package did not install.

## 5.A.3 freedesktop MIME applications

The freedesktop MIME applications specification keeps defaults in
`mimeapps.list` files, a person's in their configuration directory
before the system's, under `[Default Applications]`, with a list of
applications per type to try in order. §5.7 keeps the order, the
person's before the system's, and takes one application per choice
rather than a list: a choice that is not usable falls through to the
machine's, which is the second entry such a list exists for. It drops
the `[Added Associations]` and `[Removed Associations]` sections, which
let a person make an application a candidate for a type it does not
declare, or stop it being one; here a candidate is what a declaration
says, and nothing a person keeps can change it.

## 5.A.4 MSIX

An MSIX manifest declares an application's entry point, display name
and visual assets in one document the package ships, and the package
manager reads it at install. That is the shape of a declaration, kept
as a file the package installs rather than something the package
manager extracts, so that presence is enough.

## 5.A.5 Atrium

Atrium was Peios' previous web shell and has been completely replaced by
GXWI. Its historical application catalog influenced this chapter's
"presence is the catalog" rule: installing a declaration is enough;
nothing registers at install time.

This chapter carries forward TOML declarations and names derived from the
installed file, rather than a separate `id` key. The former Atrium model
loaded a web document from an application directory; PGSS Applications
declares a program to run and an icon name for PGSS Icons to resolve.

## 5.A.6 Design influences

**A declaration, not a place.** An application is what a file says it
is, and not where a binary sits. A program can be a command and an
application at once, a wrapper or a script can be an application, and
nothing about a program's path has to change for it to become one.

**Matched by file, named by path.** A running process is matched to its
declaration by the file it runs, and never by its name, so that no
program can borrow another's title by being called the same thing. A
declaration names its program absolutely for the same reason.

**Data, never a command line.** The one thing every consumer does with
a declaration is start a process from it, often because something
untrustworthy asked. Passing the program and arguments through exactly
as installed is what makes that safe, and is why there are no
placeholders, no shell and no lookup.

**One directory that is its own index.** As with PGSS Icons' themes,
the flat directory is chosen so that no state has to be built,
rebuilt or kept consistent, and so that a package's install and remove
are the whole of the provider's work.

**A choice selects; it never adds.** What may open a file is what
declarations say, and a person's or the machine's choice only says
which of those comes first. A choice that no longer fits is passed
over rather than repaired, so that removing an application, or a
package changing what it opens, needs nobody to tidy the registry
after it.

---

# 6.1 Scope and Roles

_Peios Specifications / PGSS / Events_

> What PGSS Events specifies and who its parties are — the emitter that writes an event and the consumer that reads it — and where the transport, storage and per-event reference are covered instead.

This chapter specifies **PGSS Events**: what an event on a Peios system
is called, what its payload carries and how, when it is written at all,
and how the vocabulary is cataloged.

The chapter rests on one decision. **A name is policy.** Every dot in an
event type is a place an administrator can attach a security descriptor,
and every field in a payload is an object an access check can grant or
deny. Two spellings of one value are two objects, and a descriptor that
denies one does not deny the other. So the names in this chapter are
fixed with the same care as an access mask, and each value has exactly
one of them.

Two roles participate.

| Role | Obligation |
|---|---|
| Emitter | Writes events. Everything an event is named, carries and encodes is an emitter obligation, as is deciding whether to write it at all (§6.9) and describing it in a fragment (§6.10). |
| Consumer | Reads events, or the catalog that describes them. A store, a viewer, a forwarder and a policy editor are all consumers. Every rule about interpreting a name or a value binds the consumer. |

A kernel subsystem is an emitter, and so is a daemon, a service and an
application. The emitter role does not depend on the path an event takes
to the stream: an event a daemon writes through the emission system
calls and an event the kernel writes on a daemon's behalf (§6.7) are
both held to this chapter.

Both roles are publicly implementable. A third party MAY ship an emitter
or a consumer and interoperate with the rest unchanged. That is the
reason the vocabulary is specified rather than left to each component:
a consumer that searches for a principal searches every emitter's events
with one query, and an emitter that names its fields as specified is
found by every consumer without either knowing the other.

This chapter covers:

- the form of an event type, and who may use which root (§6.3)
- the form of a field path, the roles and domains a path leads with, and
  the names under which a consumer exposes the record header (§6.4)
- the encoding of every kind of value (§6.5)
- how an event records success and failure (§6.6)
- how access decisions are recorded, including those a userspace
  component makes about objects it guards (§6.7)
- what is an event rather than a log line or a metric, and the tier each
  event declares (§6.8)
- the emission policy that decides whether an event type is written at
  all (§6.9)
- the catalog of event and field definitions, and the rules a
  definition must pass (§6.10)

This chapter does not cover:

- The record format, the header layout and the ring-buffer protocol a
  consumer follows to drain events. These are PSPK §2.
- How a process or kernel subsystem writes an event to the stream. The
  emission interfaces are described in the Peios Kernel TRM, and the
  libraries that wrap them in the SDK documentation.
- Storing, retaining and querying events, and per-field read access.
  The query language is PSPU §3; one implementation's storage and
  retention are described in the eventd TRM.
- The meaning of each event and field. That is reference material,
  generated from the catalog (§6.10) into the Events reference book.
- Log lines and metric samples, which are PSPU §3's. This chapter says
  only how to tell them from events (§6.8).
- How the kernel's access-check interface accepts and copies an audit
  context. This chapter says what a component passes (§6.7); the
  interface is described in the Peios Kernel TRM.

---

# 6.2 Terminology

_Peios Specifications / PGSS / Events_

> The nouns this chapter is specified in — event type, root, segment, field, path, role, domain, participant, fragment, tier, essential, emission policy, gating, variant and asserted field — and its notation for types and pseudocode.

**Event type.** The dotted name an event is written under, in the form
of §6.3. `kacs.audit.access.checked` is an event type.

**Segment.** One dot-separated part of an event type or of a field
path.

**Root.** The leading segments of an event type that name its owner: a
platform root, or a package name (§6.3).

**Platform root.** A short root reserved for one platform component,
listed in §6.A.

**Field.** One value in an event, named by its path. A field is either
in the payload or, for the header fields of §6.4, in the record header.

**Path.** The dotted name of a field. In a payload, each segment is a
map key and the path is the chain of maps leading to the value (§6.4).

**Role.** The leading segment of a path that names a participant in the
event: `subject`, `object`, `source`, `destination` or `emitter` (§6.4).

**Participant.** A party to an event that a role names: who acted, what
was acted on, where something came from or went to, and who wrote the
record.

**Domain.** The leading segment of a path that is not a role. A domain
names a property of the event itself, such as `outcome`, or a thing the
event happened within, such as a ring buffer (§6.4).

**Thing.** The segment after a role that says what kind of participant it
is: `token`, `process`, `file`, `key`.

**Variant.** A field that is another reading of a value with its own
field: the value before a change, the value asked for, the value
expected. A variant is named by a qualifier (§6.4).

**Fragment.** A file describing events and fields, in the form of §6.10.
**The catalog** is every fragment installed on a system.

**Tier.** How much an event matters to an operator, declared per event
type: `essential`, `standard`, `verbose` or `debug` (§6.8).

**Essential.** The tier of an event that is never switched off (§6.8).

**Emission policy.** The registry tree that switches event types on and
off (§6.9).

**Gating.** What decides whether one occurrence of an enabled event type
is recorded, where something other than the emission policy decides it:
a SACL, a token's audit policy. Declared per event type in its fragment.

**Asserted field.** A field whose value, on a kernel-originated record,
may have been supplied by userspace rather than observed by the kernel
(§6.7).

Terms defined in PSPK §2 — event, header, payload, origin class,
sequence — are used here with the same meaning and are not redefined,
and nor are those of PCDS (SID, GUID, LUID, security descriptor, SACL,
ACE), those of the registry (key, value, `REG_DWORD`, `Machine\`),
which are the Peios Kernel TRM's, or package name, which is PSPU §5.3's.
*MessagePack* is the format of the MessagePack specification, version
2.0.

## 6.2.1 Notation

### 6.2.1.1 Field types

A field's type is written `storage.semantic`: how the value is stored
on the wire, then what it means. `bin.sid` is a binary SID, `uint.time` a
point in time carried as an unsigned integer. One name carries both, so
a reader knows the wire form and the rendering without a lookup. A type
followed by `[]` is an array of that type. The types are listed in §6.5.

### 6.2.1.2 Pseudocode

The pseudocode in §6.9 uses the corpus conventions of the Conventions
book §2.3, and in addition:

| Notation | Meaning |
|---|---|
| `and`, `or`, `not` | Boolean operators |
| `for each x in list` | Iteration in list order |
| `absent` | No value: a key or registry value that does not exist |
| `return` | Ends the procedure with the value given |

---

# 6.3 Event Types

_Peios Specifications / PGSS / Events_

> The form of an event type — root, nouns, past-tense verb, at least three segments — the segment grammar, platform roots and package-name roots, and why every dot is a policy anchor.

An event type reads left to right as who wrote it, what it is about, and
what happened:

```text
<root>.<noun>[.<noun>…].<verb>
```

`kacs.audit.access.checked`, `peinit.job.started` and
`org.jellyfin.server.playback.started` are event types.

## 6.3.1 Form

An event type MUST have at least three segments: a root, at least one
noun, and a verb.

Every segment other than those of a package-name root (below) MUST match:

```text
[a-z][a-z0-9]*(-[a-z0-9]+)*
```

That is, lowercase ASCII, kebab-case within a segment, and no
underscores, capitals or empty segments. The event type MUST NOT contain
`/`.

## 6.3.2 Roots

The root names the owner of the event type.

A **platform component** has a platform root of one segment, listed in
§6.A. A platform root names a component, not a package: several
components shipped in one package each have their own root. An emitter
MUST NOT use a platform root it is not listed against.

**Every other emitter** roots its event types at its own package name
(PSPU §5.3), split into segments at its periods. A package named
`org.jellyfin.server` writes `org.jellyfin.server.playback.started`.
This holds for first-party applications as much as for third parties.
An emitter MUST NOT root an event type at a package name that is not
its own.

A platform root MUST NOT be a top-level domain in the DNS root zone, so
that no platform root can be mistaken for the first segment of a
package name. `netd` is a valid platform root; `net` is not.

> [!NOTE]
> A package name may contain characters the segment grammar above does
> not admit — a leading digit, or `+`. Its segments are used as they
> are. A query naming such a type has to quote it, because the query
> language's unquoted identifiers start with a letter and exclude `+`
> (PSPU §3.19).

A consumer can derive an event type's owner from its name: a platform
root through §6.A, and a package-name root as the longest installed
package name its leading segments spell. A consumer MUST NOT treat the
root as evidence of who wrote the event. The record header is that
evidence (§6.4): nothing in this version prevents an emitter from
writing under a root it does not own.

> [!NOTE]
> Enforcing root ownership needs a way to prove which package a running
> program belongs to, which Peios does not yet have. It is left to a
> later attested-events mechanism rather than approximated now. Until
> then, review of a package submitted to the Peios package repository
> includes checking that its events use its own root.

## 6.3.3 Nouns

After the root come one or more nouns, from general to specific.

An emitter SHOULD add a noun segment only where someone would plausibly
write a policy on the set of event types beneath it. A middle segment
that groups nothing anyone would grant, deny or switch off together
costs every name a segment and buys nothing; tidiness alone is not a
reason. The exception is a segment needed so that two event types do
not collide.

Depth is preferred to compounds: `lcs.audit.backup.started`, not
`lcs.audit.backup-started`. A compound word within a segment is for a
single concept that has no useful parent, such as `copied-up`.

## 6.3.4 The verb

The last segment is a past-tense verb saying what happened: `created`,
`started`, `ended`, `checked`, `used`, `refused`.

The verb SHOULD be neutral where a neutral verb still says what
happened, and MUST NOT be so neutral that it does not. `installed` is
right for a package installation even when the installation failed,
because the failure is carried in `outcome.success` (§6.6) and any
consumer can show it. `transaction.ended` is wrong: it does not say what
the transaction was.

An action that can succeed or fail is **one** event type (§6.6). An
event type that is only ever written on failure MAY say so in its verb,
as `stratafs.mutation.refused` does.

Distinct steps of a lifecycle are distinct event types:
`peinit.job.created`, `peinit.job.started` and `peinit.job.ended` are
three things that happen, not three outcomes of one.

## 6.3.5 Every dot is a policy anchor

A consumer that controls read access per event type resolves an event's
descriptor by trying the full type, then each shorter dotted prefix
(PSPU §3.28). A descriptor on `kacs.audit` therefore covers the audit
trail without the rest of KACS, and the emission policy is keyed the
same way (§6.9). This is why the noun rule above is about policy, and
why the segments are fixed rather than left to taste.

> [!NOTE]
> A form with a slash, `dev.peios.peinit/job.created`, was considered
> and rejected. In log origins a slash separates a producer from a part
> of it below policy granularity, and the descriptor resolver stops at
> the first slash. Every event type would then resolve only at its
> package, and the slash is not an identifier character in the query
> language, so every query would need quotes.

---

# 6.4 Fields

_Peios Specifications / PGSS / Events_

> How a field is named — role.thing.attribute for participants, domain.attribute for the event — nesting as the name, value-or-map, the header's names, related things, variants and standard attributes, and who may define a path.

A field is named for the part it plays in the event, then for what it
is, then for which property of it the value is:

```text
<role>.<thing>[.<thing>…].<attribute>      subject.token.sid
<domain>[.<…>].<attribute>                 outcome.success
```

## 6.4.1 Nesting is the name

A payload is a MessagePack map with string keys. A field's path is the
chain of keys leading to its value: `subject.token.sid` is the value at
`{subject: {token: {sid: …}}}`. An emitter MUST encode a path as nested
maps, one map per segment, and MUST NOT write a key containing `.`; such
a key is a different and unreachable field (PSPU §3.22).

Every segment of a path MUST match the segment grammar of §6.3,
including the segments of a package name that a third party's own
fields sit beneath (below). A package whose name has a segment the
grammar does not admit cannot define fields of its own.

**A path is either a value or a map, never both.** Once any event
carries a value at a path, no field may be defined beneath that path,
and a path defined as a map MUST NOT carry a value in any event. The
shape of a subtree is therefore decided before its first field is
defined, and the variant rule below exists so that it rarely has to be.

## 6.4.2 Roles

A path that describes a participant leads with its role. The roles are a
closed set.

| Role | Participant |
|---|---|
| `subject` | Whose authority the action used: the principal that acted |
| `object` | What the action was done to |
| `source` | Where something came from: the origin of a copy, of traffic, of data a backend supplied |
| `destination` | Where it went |
| `emitter` | Who was running when the record was written |

After the role comes the thing, and then the attribute:
`subject.token.sid`, `object.file.path`, `source.stratum.index`.

The emitter and the subject are different participants. The emitter is
whoever wrote the record; the subject is whoever acted. They are the
same on most events, and differ on every event one component writes
about another: an access check a daemon requests for a client has the
daemon as emitter and the client as subject. A consumer searching for
what a principal did MUST search `subject.*`, not `emitter.*`.

An event about an action MUST carry `subject.token.sid`, the SID of the
principal that acted, whether that principal is the caller whose token
the action ran under or the emitter acting on its own authority. The
header carries only token GUIDs (below), never a SID, so the SID is
a payload field in every case.

## 6.4.3 Domains

A path that does not describe a participant leads with a domain, then
the attribute: `outcome.success`, `access.granted`.

A domain names either a property of the event itself, or a thing the
event happened within without acting on it: a ring buffer, a
connection-tracking flow, a transaction. A thing the event acts on is a
participant and takes a role (`object.mount.path`); a thing it happens
within leads with its own name (`buffer.fill`, `flow.state`).

The **generic roots** are shared by every emitter and defined in the
platform fragment (§6.10):

| Root | Holds |
|---|---|
| `subject`, `object`, `source`, `destination`, `emitter` | The participants, and their common things: `token`, `process`, `file`, `key`, `session` |
| `event` | The record's own header values (below) |
| `access` | Rights asked for, granted and audited |
| `outcome` | Whether the action succeeded, and why not (§6.6) |
| `trigger` | Whatever caused the record to exist: an audit ACE, a blocking layer, a causing file |
| `operation` | What was attempted and how |
| `config` | A configuration value reported on |
| `policy` | A rule set in force |
| `transaction` | A transaction an operation belonged to |
| `fields` | Properties of the record's fields (§6.7) |

A platform component MAY define a domain of its own for things only it
has, such as a ring buffer or a service graph, and owns it (§6.10). Any
other emitter's own fields go beneath its package name (below), because
a domain is one segment wide and two vendors' choices would collide.

## 6.4.4 The header

The record header (PSPK §2) is stamped by the kernel and cannot be
forged by the emitter. A consumer that exposes header values by name
MUST expose them under these field paths:

| Header field (PSPK §2) | Field path | Type |
|---|---|---|
| `type` | `event.type` | `str` |
| `timestamp` | `event.time` | `uint.time` |
| `sequence` | `event.sequence` | `uint` |
| `cpu_id` | `event.cpu` | `uint` |
| — | `event.boot.guid` | `bin.guid` |
| `origin_class` | `emitter.class` | `uint.enum` |
| `effective_token_guid` | `emitter.token.guid` | `bin.guid` |
| `true_token_guid` | `emitter.true-token.guid` | `bin.guid` |
| `process_guid` | `emitter.process.guid` | `bin.guid` |

`event.boot.guid` is not in the record: it is the boot the consumer read
the record in, which the consumer supplies. `emitter.class` is a
`uint.enum` whose numbers are PSPK §2's origin classes, which is why it
is not a string (§6.5).

An emitter MUST NOT write any of these paths in a payload. Details of
the emitting process that the header does not carry — its PID, name and
executable — are payload fields under `emitter.process`.

## 6.4.5 Things and their relations

A thing related to a participant nests under it: the parent of a process
is `object.process.parent.pid`, the target of a registry symlink is
`object.key.target.guid`, the token a job runs as is
`object.job.token.sid`.

Two things of one kind that appear in one event are told apart by
direction where there is one: `source` and `destination`. Where there is
no direction, the second is named by its relation to the first, as
above. A path MUST NOT use `other`, `peer` or a similar segment to tell
two participants apart.

`key` as a thing means a registry key and nothing else. A cryptographic
key is a `signing-key`, a handle is a `handle`.

`capability` as a thing or attribute means a confinement capability SID.
A Linux capability is `linux.cap`, which is context for a privilege
decision and never the decision itself.

## 6.4.6 Many values

Many values of one field go in an array under a plural name:
`subject.token.groups`. Arrays that describe the same items are
parallel and share an index: `subject.token.group-attributes[i]`
describes `subject.token.groups[i]`.

## 6.4.7 Variants

A variant of a value is a sibling of it, named with a qualifier suffix,
and the plain name always holds the value in force:

| Path | Value |
|---|---|
| `policy.generation` | The generation now in force |
| `policy.generation-previous` | The generation it replaced |
| `object.key.path` | The key's resolved path |
| `object.key.path-requested` | The path as the caller wrote it |

A qualifier MAY also sit on a thing, where the variant is a whole
thing: `source.stratum-previous.path`.

The following qualifiers MAY be applied to any defined field or thing
without that variant being defined separately: `-previous`,
`-requested`, `-expected`, `-effective`, `-limit` and `-count`. This set
is closed in this version. Any other qualifier is part of a field's
name, and the field MUST be defined like any other (§6.10).

> [!NOTE]
> Variants are siblings rather than children because of the
> value-or-map rule. If before and after were last segments,
> `policy.generation.previous` could not exist beside a
> `policy.generation` that other events already carry as a value. A
> sibling also sorts next to the value it qualifies.

## 6.4.8 Standard attributes

These attributes MAY be attached to any defined thing or domain without
being defined separately: `count`, `limit`, `length`, `size`, `depth`,
`capacity`, `fill`, `duration`, `timeout`, `attempts`, `offset`,
`index`, `sequence`, `generation`, `digest`, `name`, `path`, `id`,
`guid`, `sid`, `type` and `state`. Each has the type its name implies in
§6.5. This set is closed in this version.

## 6.4.9 Who may define a path

Every path is defined exactly once across the catalog (§6.10).

The generic roots of the table above, and their common fields, are
defined in the platform fragment. A component defines the subtrees of
things only it knows about — StrataFS defines `source.stratum.*` — and
any domain of its own. Any emitter MAY carry a field defined by another
fragment without defining it.

A field that no generic path or platform subtree covers, and that an
emitter that is not a platform component needs, sits beneath its own
package name below the role:
`object.org.jellyfin.server.media.title`. Such a field SHOULD be rare,
and an emitter SHOULD use a defined field wherever one has the meaning
it needs.

An emitter MUST NOT write a field that the catalog does not define,
other than a variant or standard attribute permitted above.

## 6.4.10 Names are access control

A consumer that controls read access per field treats each path as an
object in an access check (PSPU §3.28). Because the path is nested, a
grant on `subject` can cover every identity field beneath it, including
fields defined later. Because each value has one path, a descriptor that
denies a value cannot be evaded by writing the value under a second
name. That is the security reason for the one-definition rule, and why
the catalog rejects a duplicate (§6.10).

---

# 6.5 Values

_Peios Specifications / PGSS / Events_

> The one wire form for every kind of value — binary SIDs and GUIDs, nanosecond times, real booleans, symbolic enumerations — the field types that name them, absent keys, and where this chapter departs from the shared data conventions.

Every value has one wire form, and the field's type names it. A payload
is one MessagePack map with string keys (PSPK §2).

## 6.5.1 Types

| Value | Wire form | Type |
|---|---|---|
| Principal | A binary SID (PCDS) | `bin.sid` |
| GUID | The 16-byte binary GUID (PCDS) | `bin.guid` |
| LUID | Unsigned integer | `uint.luid` |
| ACE | The binary ACE (PCDS) | `bin.ace` |
| Point in time | Unsigned integer, nanoseconds since the Unix epoch | `uint.time` |
| Duration | Unsigned integer, nanoseconds | `uint.duration` |
| Size in bytes | Unsigned integer | `uint.bytes` |
| Access mask | Unsigned integer | `uint.mask` |
| Flags | Unsigned integer | `uint.flags` |
| Integrity level | Unsigned integer, the integrity RID | `uint.integrity` |
| Error number | Signed integer, negative | `int.errno` |
| Boolean | MessagePack boolean | `bool` |
| Enumeration | String, kebab-case | `str.enum` |
| Numeric enumeration | Unsigned integer | `uint.enum` |
| Path | String | `str.path` |
| IP address | String, in the textual form for its family | `str.ip` |
| Digest | Binary | `bin` |
| Text | String | `str` |
| Other integer | Unsigned or signed integer | `uint`, `int` |

An emitter MUST encode a value in the wire form of its field's type. A
consumer MUST NOT accept a different form as the same value: a SID
written as an SDDL string is not a `bin.sid`.

**Enumerations are symbolic.** An enumeration is a kebab-case string
naming the value, `wrong-type` rather than `2`. A `uint.enum` is
permitted only where the numbers are fixed by another specification or
an external standard — an impersonation level, an address family — and
a consumer renders it by name. Every enumeration declares its values in
its fragment, or names the reason-code family it draws them from, and
states whether the set is closed (§6.10). A consumer that meets a value
of an open enumeration it does not know MUST treat it as a value rather
than an error, and SHOULD show it as written.

**Masks need their kind.** A `uint.mask` is decoded against the table
for the kind of thing it applies to, which the same record names in
`object.kind`. An event that carries a `uint.mask` field MUST carry
`object.kind`.

## 6.5.2 What an emitter does not write

- **An absent value.** A field with no value is omitted: the key is not
  written. An emitter MUST NOT write nil, an empty string or zero to
  mean "none".
- **The header again.** An emitter MUST NOT repeat in its payload a value
  the header already carries: the time, the sequence, or the emitter's
  token and process GUIDs (§6.4).
- **A name beside a SID.** A principal is carried as its SID only. An
  emitter MUST NOT carry a principal's name in a field; resolving a SID
  to a name is a consumer's convenience, done when the record is read.
- **Units in a name.** The type carries the unit. A duration is
  `operation.duration`, never `operation.duration-ns`.
- **Debugging output.** A string value MUST NOT be the output of a
  language's debug formatter. Its format is not stable and no consumer
  can rely on it.

> [!NOTE]
> Names are kept out of events because a name is not stable and a SID
> is. A principal renamed after the event would otherwise appear under
> its old name in every record written before the change, and a search
> by the new name would miss them.

## 6.5.3 Departures from the shared conventions

This chapter departs from the data conventions of the Conventions book
§3.3 on two points:

- **Timestamps** are unsigned integers counting nanoseconds since the
  Unix epoch, not RFC 3339 strings. The record header already carries
  time this way (PSPK §2), and one form for every time in a record lets
  a consumer compare them directly.
- **Digests** are carried as binary, not lowercase hexadecimal. A
  consumer renders them as hexadecimal for display.

---

# 6.6 Outcomes

_Peios Specifications / PGSS / Events_

> One event type per action, with success and failure in outcome.success, outcome.reason, outcome.errno and outcome.detail, and what each of the four may carry.

An action that can succeed or fail is one event type, and its result is
carried in `outcome.*`. "Everything that failed" is then one query across
every emitter, and no descriptor can show an action's successes while
hiding its failures.

An emitter MUST NOT define separate event types for the success and the
failure of one action. A type that only ever records failure is
permitted (§6.3).

## 6.6.1 The outcome fields

| Field | Type | Carries |
|---|---|---|
| `outcome.success` | `bool` | Whether the action did what was asked |
| `outcome.reason` | `str.enum` | Why it failed, or why a success was unusual |
| `outcome.errno` | `int.errno` | The error number it failed with |
| `outcome.detail` | `str` | Text for a person to read |

An event whose action can fail MUST carry `outcome.success`.

`outcome.reason` is symbolic. Its values are drawn from a named
reason-code family, or from an enumeration the event declares in its
fragment (§6.10). Where a kernel reason code exists for the decision, the
value is that code's name in kebab-case with its family prefix removed,
so that an event and a trace of the same decision describe it in the
same terms.

`outcome.errno` is the negative error number the operation returned,
`-13` for `EACCES`. It is omitted on success. A consumer renders it by
name.

`outcome.detail` is optional free text for a person. Nothing parses it,
and an emitter MUST NOT carry anything in it that a consumer would need
to filter on: that belongs in `outcome.reason` or in a field of its own.

Where a decision has more than two results, so that a boolean cannot
express it, `outcome.verdict` carries the result as an enumeration.

> [!NOTE]
> Before this chapter, the reason for one failure was written as
> `failure_reason`, `failure_cause`, `reason`, `error`, `detail`,
> `parse_error`, `finalization_detail`, `result` and `message`, and a
> descriptor denying one of them denied none of the others. The four
> fields above replace all nine.

---

# 6.7 Access Decisions

_Peios Specifications / PGSS / Events_

> Every access decision is recorded by the kernel's audit, including a daemon's about objects it guards — the audit context a component passes, asserted fields, default SACLs on guarded objects, and keeping those SACLs intact.

Every access decision is recorded the same way: by the kernel's access
audit, under the SACL of the object decided on. That holds for a decision
a userspace component makes about objects it guards itself — a service
manager's services, an event store's namespaces — as much as for a file.
"Who was refused what" is then one query, and a SACL governs a daemon's
objects as it governs a file.

## 6.7.1 A component that guards objects

An emitter that decides access to objects of its own:

- MUST make each decision through the kernel's access check, against the
  object's security descriptor;
- MUST pass the object's identity as the check's audit context (below);
- MUST NOT write an event of its own recording the decision, whether it
  granted or refused. It MAY write a log line about a refusal for its own
  debugging; that line is not the audit record.

A component MAY record the outcome of a protocol conversation, including
authentication or delivery failures, separately from the access audit. Such an
event MUST describe the completed operation rather than duplicate the descriptor
check, and MUST NOT be presented as satisfying SACL audit requirements.

## 6.7.2 The audit context

The audit context is one MessagePack map:

| Key | Value |
|---|---|
| `kind` | The kind of object, a kebab-case string: `service`, `job` |
| `<kind>` | Optional. A map of the object's identifying fields, under a key equal to the value of `kind` |

```text
{kind: "service", service: {name: "jellyfin"}}
```

The map MUST contain `kind`, MAY contain the map named by it, and MUST
contain nothing else. The kernel rejects a context that is not exactly
this shape: `kind` must be a string matching the segment grammar of
§6.3, the map under the kind's key must not be empty, and every key in
that map must match the same grammar, because each becomes a segment of
`object.<kind>.<key>`. A context with no body map is accepted; an empty
body map is not. Each field in that map MUST be a field the
component's fragment defines beneath `object.<kind>`, and MUST be marked
asserted there (§6.10).

The kernel's record of the decision then carries `object.kind` and the
object's fields as `object.service.name` and so on, beside the subject,
the access requested and granted, and the trigger, exactly as for any
other object. How the kernel's access-check interface accepts and copies
the context is described in the Peios Kernel TRM.

## 6.7.3 Asserted fields

The kernel cannot verify that a descriptor belongs to the service a
component names. A field the kernel copies from userspace is therefore
the component's claim: it is the identity of what the component actually
enforced, but the kernel did not observe it.

A kernel-originated record that carries any asserted value MUST carry
`fields.attestation.userspace` with the value `true`. A record that
carries none MUST omit the field. A record written by userspace never
carries it, because the origin class in its header (§6.4) already says
that the whole payload is the emitter's word.

A consumer MUST NOT present an asserted field as observed by the kernel.

## 6.7.4 The emitter and the subject

On a decision a component requests for a client, the record's header
names the component, as `emitter.*`, and the payload's `subject.*` names
the client whose access was checked (§6.4). The component's process
details are `emitter.process.*`.

A stateless check of a supplied, hypothetical subject is different from a check
of a real token. Its event type is `kacs.audit.subject.checked`. The kernel
records the real caller in `subject.token.sid`, and the supplied user SID, when
present, in the asserted field `source.supplied-subject.sid`. The latter is not
a token identity observed by the kernel and grants no token authority. The
record carries `fields.attestation.userspace`. The caller's enabled audit
privilege gates SACL emission; an explicit no-audit query flag suppresses that
emission. Neither changes the supplied subject's access decision.

## 6.7.5 Default SACLs

A component that guards objects SHOULD give each a default SACL with an
audit ACE that records failed access by Everyone, so that a refusal is
recorded without configuration. An administrator can narrow or remove it
per object like any other SACL. The exception is a kind of object so
numerous that recording every refusal would bury the record, which is
why files and registry keys carry no default SACL.

A component that stores a descriptor where writing the stored value
replaces the SACL without the privilege that normally guards a SACL —
for example, a whole descriptor kept as one registry value — MUST allow
that store to be written only by principals trusted to change audit
policy. A tool that edits such a descriptor's DACL MUST keep its SACL
intact.

> [!NOTE]
> Two other ways of recording refusals were considered. Adding a SACL to
> every descriptor just before the check would make the record's
> `trigger.ace` name an ACE that is not in the object's descriptor, could
> not be changed per object, and would be done differently by every
> component. Turning on failure auditing in every token's audit policy
> would record every refusal on every object, files included; that
> remains the tool for auditing everything one principal does.

---

# 6.8 Events, Logs and Tiers

_Peios Specifications / PGSS / Events_

> The two tests that decide whether something is an event, a log line or a metric, and the four tiers an event type declares — essential, standard, verbose and debug — with what makes an event essential.

## 6.8.1 Event, log or metric

An **event** is a discrete occurrence that someone may search for, alert
on, or attribute to a principal, one record at a time. It carries an
identity the kernel stamped (PSPK §2).

A **log line** is narrative for the people who maintain a component. Its
value is in reading the sequence, not in querying single records.

A **metric** is a sampled quantity, where the trend matters and no single
sample does.

An emitter MUST decide between them by two tests, in order:

1. **Does an operator care?** Events and metrics are for operators; logs
   are for developers. If an operator would not act on it, it is a log
   line, and the second test does not apply.
2. **Does one instance matter on its own?** If it does, it is an event,
   however frequent it is. If only the trend matters, it is a metric.

An emitter MUST NOT carry log text in an event. A message a person reads
belongs in `outcome.detail` (§6.6) where it explains the outcome, and in
the log otherwise.

> [!NOTE]
> An operator should not need to read logs in all but the rarest cases.
> If they do, something that should have been an event was written as a
> log line.

## 6.8.2 Tiers

Every event type declares one tier in its fragment (§6.10). The tiers are
a closed set.

| Tier | Meaning | On unless the policy says otherwise |
|---|---|---|
| `essential` | Extremely important and relatively rare, or governed by its own configuration | Always; cannot be switched off |
| `standard` | What an administrator reviews: lifecycle, configuration, failures | Yes |
| `verbose` | Detail for an active investigation | No |
| `debug` | For the component's developers | No |

A tier sets only the default. The emission policy switches a type on or
off whatever its tier, except an essential type, which it never switches
off (§6.9). A shipped default policy MUST NOT switch a `debug` type on.

## 6.8.3 Essential

An event type is essential for one of two reasons:

- **It is extremely important and relatively rare.** A logon session
  ending, or a configuration value rejected.
- **Its emission is already governed by its own configuration.** The
  kernel's access audit is the example: a SACL, or a token's audit
  policy, decides which occurrences are recorded. So is any event
  whose own configuration, such as a REPORT directive, decides whether
  it is written.

The second reason follows a principle that holds across Peios: **one
switch per thing.** Something already governed by its own configuration
does not also need an emission-policy switch before it works. Making an
administrator turn on the same thing in two places is what this rules
out.

An emitter MUST NOT declare an event type essential for any other
reason.

> [!NOTE]
> Nothing in a running system stops a third party declaring an event
> essential, and nothing tries to. Whether an essential event meets one
> of the two reasons is one of the checks made when a package is
> submitted to the Peios package repository.

---

# 6.9 Emission Policy

_Peios Specifications / PGSS / Events_

> How an event type is switched on or off — the per-segment Enabled values under Machine\Generic\Events, the walk that resolves them, tier defaults, essential types, the AND with SACLs and audit policy, noticing a change, and what an emitter does when it cannot read the policy.

An event type that is switched off is never written. Each emitter
decides, before it writes an event, whether its type is on, from a policy
kept in the registry. A consumer decides what to keep of what it reads;
it does not decide what is written.

The component that writes a record decides, whatever path the record
takes. A component that writes records of its own without going through
the kernel's event stream, straight into a store for example, is their
emitter for the purposes of this section, and applies the policy to
every type it writes that is not essential.
[*events.policy.whoever-writes-a-record-applies-the-policy]

## 6.9.1 The policy tree

The policy is the registry key `Machine\Generic\Events` and the keys
beneath it. There is one key per segment of an event type, so the
policy for an event type is found on the path that spells its segments
beneath `Events`, one key each, in order: the policy for
`kacs.audit.access.checked` is found by walking
`Events\kacs\audit\access\checked`.
[*events.policy.one-key-per-segment]

A package-name root (§6.3) is split at its periods like the rest of the
type, so a package's events sit beneath one key per segment of its
name: `org.jellyfin.server.playback.started` is found by walking
`Events\org\jellyfin\server\playback\started`, and `Events\org\jellyfin`
is the key that covers every package named beneath `org.jellyfin`. A
segment is used as it is, including one a package name gives that the
segment grammar of §6.3 does not admit.
[*events.policy.package-root-splits-per-segment]

The registry compares key and value names ignoring case, so the walk
does too.

Any key on such a path MAY hold a value named `Enabled`. A `REG_DWORD`
of `1` switches the event types beneath it on, and `0` switches them
off. An `Enabled` value of any other type, or a `REG_DWORD` holding any
other number, is ignored, as though it were absent.
[*events.policy.other-enabled-values-are-ignored]

Nothing else in the tree has a meaning. A key on no event type's path,
and any value other than `Enabled`, decides nothing.

## 6.9.2 Resolving a type

Whether an event type is on is decided by this procedure. The deepest
`Enabled` value on the type's path wins, and the type's tier decides when
there is none.

```text
enabled(event_type, tier) → bool
    if tier == essential
        return true                       // never consults the policy
    setting = absent
    key = Machine\Generic\Events          // absent if it does not exist
    for each segment in segments(event_type)
        if key == absent
            break
        setting = read_enabled(key, setting)
        key = subkey(key, segment)        // absent if it does not exist
    if key != absent
        setting = read_enabled(key, setting)
    if setting != absent
        return setting == 1
    return tier == standard               // standard on; verbose and debug
                                          // off; essential returned above

read_enabled(key, current) → setting
    value = value(key, "Enabled")         // absent if it does not exist
    if value is REG_DWORD and (value == 0 or value == 1)
        return value
    return current                        // ignored: keep what was found
```

Each rule of the procedure holds on its own:

- The `Enabled` value on the deepest key that has one decides. A
  value on `Events` itself applies to every type the keys beneath it
  do not decide. [*events.policy.deepest-enabled-wins]
- The key named by the whole type, its last segment included, is read
  like the keys above it. [*events.policy.the-types-own-key-counts]
- Where a key on the path does not exist, the keys beneath it do not
  either, and the deepest value found above it decides.
  [*events.policy.a-missing-key-ends-the-walk]
- A key the emitter may not read ends the walk as a missing one does.
  [*events.policy.an-unreadable-key-ends-the-walk]
- With no `Enabled` value on the path, a `standard` type is on, and a
  `verbose` or `debug` type is off (§6.8).
  [*events.policy.tier-decides-when-nothing-is-set]

An emitter MUST NOT write an event whose type this procedure finds off.
[*events.policy.an-off-type-is-not-written]

An emitter MUST write an essential event without consulting the policy,
whatever the tree holds. [*events.policy.essential-never-consults]

An emitter SHOULD make the decision before it builds the event's
payload, so that a type that is off costs nothing beyond the decision.
[*events.policy.decide-before-building]

### 6.9.2.1 Example

With no value on `Events`, `Events\kacs` holding `Enabled = 0`, and
`Events\kacs\audit` holding `Enabled = 1`:

| Event type | Tier | Decided by | On |
|---|---|---|---|
| `lcs.config.value.rejected` | `standard` | its tier | Yes |
| `kacs.caap.staging.diverged` | `standard` | `Events\kacs` | No |
| `kacs.audit.handle.used` | `standard` | `Events\kacs\audit` | Yes |
| `kacs.audit.access.checked` | `essential` | its tier, always | Yes |

With `Enabled = 0` on `Events` as well, `lcs.config.value.rejected` is
off and the other three are as before. A `verbose` or `debug` type in
the place of `lcs.config.value.rejected` would be off in both trees, and
in the place of `kacs.audit.handle.used` on in both.

## 6.9.3 Gating, SACLs and audit policy

For an event type with gating (§6.2), the policy and the gating decide
together, by AND: the type is written for an occurrence only if the
policy has it on and its gating asks for that occurrence.
[*events.policy.policy-and-gating-combine-by-and]

Neither widens the other. Switching a type on does not record an
occurrence that a SACL, or a token's audit policy, does not ask for; and
a SACL that asks for an occurrence does not record it while the policy
has its type off. The policy decides whether a kind of event exists at
all. The gating decides which occurrences of it are recorded, and only
the emitter can evaluate it, because only the emitter can see the
object.

An essential type's gating alone decides, because the policy never
switches it off (§6.8). The kernel's access audit is the case this is
for: `kacs.audit.access.checked` is essential, so whether an access
decision is recorded is the SACL's and the audit policy's choice alone,
and an administrator never has to switch the same thing on in two
places.

## 6.9.4 Noticing a change

An emitter MAY cache the policy in-process.

An emitter MUST apply a change to the policy to every decision it makes
one second or more after the change was committed, whether or not it
caches. [*events.policy.a-change-applies-within-one-second]
An emitter SHOULD apply it to the first decision it makes after the
commit, which an emitter that watches the tree can do.

A watch on the subtree of `Events` sees every change. An emitter that
writes under few roots MAY instead watch only the keys on its own types'
paths. A key that does not exist cannot be watched, so an emitter
watching for one to be created watches the nearest key above it that
does exist.

A change is not retroactive. An event written before it stays written,
and an occurrence decided before it stays decided.

## 6.9.5 When the policy cannot be read

An emitter that cannot read `Machine\Generic\Events` — before the
registry has a source for the `Machine` hive, where the key does not
exist, or where it may not read it — MUST decide by tier alone, as the
procedure does when no `Enabled` value is found.
[*events.policy.an-unreadable-policy-falls-back-to-tier]

It MUST NOT hold an event back to wait for the policy to become
readable. [*events.policy.no-waiting-for-the-policy]

Once the policy can be read, an emitter MUST apply it to every decision
it makes one second or more after it became readable.
[*events.policy.a-readable-policy-applies-within-one-second]

> [!NOTE]
> The kernel writes events from early in boot, before any registry
> source has registered. For that window its decisions are tier
> defaults: a `verbose` type the policy switches on is not written, and
> a `standard` type the policy switches off is. An operator who needs a
> boot-time event whatever the policy says has the essential tier, if
> the event meets one of its two reasons (§6.8), and nothing else.

## 6.9.6 Who may change it

Each key's security descriptor decides who may change the policy beneath
it, and inheritance carries that down the tree. This is why the policy
has one key per segment rather than one flat key per pattern: a grant on
`Events\org\jellyfin` lets whoever runs Jellyfin switch its events, and
reaches nothing else.

A conforming system:

- lets every emitter read `Machine\Generic\Events` and every key beneath
  it; [*events.policy.every-emitter-may-read-the-tree]
- lets only administrators write `Machine\Generic\Events` itself, and the
  keys of platform roots (§6.A);
  [*events.policy.only-administrators-write-platform-keys]
- SHOULD give `Machine\Generic\Events` a SACL that audits writes, so that
  a change to what is recorded is itself recorded.

> [!NOTE]
> Leaving the decision to the consumer was considered and rejected. The
> kernel's event stream drops its oldest events when a ring is full,
> whatever they are, so events nobody wanted would push the audit trail
> out of the ring. They would also cost an encoding on hot paths, and
> every reader of the ring would still see them.

---

# 6.10 The Catalog

_Peios Specifications / PGSS / Events_

> Where event and field definitions live — fragments in /usr/share/evman/ — the fragment format and its three record kinds, the platform fragment that holds the generic roots, and the rules every fragment must pass.

The catalog is the single source of every event type and field
definition. Everything else that lists them — reference documentation,
a viewer's field picker, a policy editor — is generated from it or
checked against it.

## 6.10.1 Fragments

An emitter MUST describe every event type it writes, and every field it
defines, in a **fragment**: a UTF-8 text file installed in
`/usr/share/evman/` with the extension `.evman`. A package installs one
fragment per component it ships, named for the component.

The **platform fragment**, `/usr/share/evman/kernel.evman`, defines the
generic roots of §6.4 and their common fields. A conforming system has
it.

A consumer that reads the catalog reads every `.evman` file in
`/usr/share/evman/`, and no subdirectory.

## 6.10.2 Format

A fragment is a sequence of records. Each record begins with an anchor
line of three hyphens, a space, the record kind, a space and the name it
defines:

```text
--- field subject.token.sid
--- group subject
--- event kacs.audit.access.checked
```

After the anchor come header lines of the form `key: value`, one per
line, then a blank line, then prose: the record's description. The
prose's first sentence is a complete summary of it. Inline markup in
prose is limited to `**bold**` and `` `code` ``.

### 6.10.2.1 Field records

| Key | Required | Value |
|---|---|---|
| `type` | Yes | The field's type (§6.5) |
| `values` | For an enumeration | The values, separated by `\|`, or the name of the reason-code family they are drawn from |
| `closed` | For an enumeration | `true` if no value may be added without a new version of the field |
| `asserted` | No | `true` if the value may be supplied by userspace on a kernel-originated record (§6.7) |
| `carried` | No | `header` for a header field (§6.4); absent for a payload field |

### 6.10.2.2 Group records

A group names a set of fields that always travel together, so that
events can include the set rather than list it. Its header lines are
`include:` lines, one field path each.

### 6.10.2.3 Event records

| Key | Required | Value |
|---|---|---|
| `tier` | Yes | The event type's tier (§6.8) |
| `gating` | If any | What decides which occurrences are recorded |
| `cardinality` | No | How many records one occurrence produces, where that is not one |

After the prose come the fields the event carries, one per line:

```text
include: subject
field: object.kind              required
field: object.file.path         when object.kind == file
field: access.granted           required
  The mask this check granted.
```

`include:` names a group. `field:` names a field, followed by when it is
present: `required`, `optional`, or `when` and a condition on another
field of the record. An indented paragraph after a `field:` line is a
**gloss**: what the field means in this event. A gloss MAY narrow the
field's definition and MUST NOT contradict it.

Where a field's definition leaves its values to the event, as
`outcome.reason` does (§6.6), the event declares them with indented
`values:` and `closed:` lines directly after the `field:` line, in the
form a field record uses:

```text
field: outcome.reason           when outcome.success == false
  values: disk-full | source-unreadable | cancelled
  closed: false
  Why the snapshot was not written.
```

## 6.10.3 Rules

Every fragment MUST pass these rules, checked across the whole catalog:

1. Every path a `field:` or `include:` line names is defined.
2. No path is defined by two fragments, and no path is defined twice in
   one.
3. No path is defined both as a value and as a map (§6.4).
4. Every event type a fragment defines begins with a root that fragment
   owns: a platform root listed against its component in §6.A, or its
   package's name.
5. A platform component's fragment defines fields only in the subtrees
   and domains of things it alone knows about (§6.4). Any other fragment
   defines fields only beneath its own package name below a role (§6.4).
6. Every name matches the grammar of §6.3 and §6.4, and every event
   type's last segment is a verb in the past tense.
7. Every enumeration declares its values or names its reason-code
   family, and says whether it is closed.
8. Every event type declares a tier, and an event type with gating
   declares it.
9. An event type that carries a `uint.mask` field carries `object.kind`
   (§6.5).

A tool that reads the catalog SHOULD report every rule a fragment
breaks. A consumer that acts on the catalog — one that decides access,
builds a field tree for a descriptor, or validates payloads against it —
MUST NOT treat a fragment that breaks rule 1, 2 or 3 as defining
anything. A tool that only displays the catalog MAY show such a
fragment's records, provided it warns that the fragment breaks those
rules.

> [!NOTE]
> Rule 2 is what stops one value acquiring three spellings again. Before
> the catalog existed nothing could have caught it, and the result was
> a field that a descriptor could deny under one name and leak under
> another (§6.4).

---

# 6.11 Extension

_Peios Specifications / PGSS / Events_

> What may be added to this chapter's vocabulary without breaking a conforming emitter or consumer — new event types, fields, enumeration values and platform roots — and what needs a new version.

## 6.11.1 Additive changes

The following are additive. An emitter and a consumer built to this
version behave correctly in their presence:

- A new event type, under a root its emitter owns.
- A new field, defined once in the catalog. A consumer that does not
  know a field still reads, stores and queries it by its path.
- A new value of an open enumeration, which a consumer built to this
  version treats as a value rather than an error (§6.5).
- A new platform root in §6.A, provided it is not already in use as a
  package name's first segment and is not a top-level domain.
- A new domain of a platform component's own (§6.4).
- A new key in a fragment record. A consumer that does not know a key
  ignores it.

## 6.11.2 Changes requiring a new version

- Renaming an event type or a field, or moving a field to another path.
  Every descriptor and every query written against the old name stops
  matching.
- Changing a field's type or wire form (§6.5).
- A new value of a closed enumeration.
- Defining a field beneath a path that is a value, or giving a value to
  a path that is a map (§6.4).
- A change to the roles, the qualifiers or the standard attributes of
  §6.4, or to the tiers of §6.8.
- A change to the policy tree's location or its resolution (§6.9).

## 6.11.3 Reserved

The roots in §6.A are reserved to the components listed against them.
The roles and generic roots of §6.4 are this chapter's, and only the
platform fragment defines fields directly beneath them. Every other
fragment is bound by rule 5 of §6.10.

`/usr/share/evman/` is this chapter's, and so is the `.evman` extension
within it. `Machine\Generic\Events` and every key and value beneath it
are this chapter's: nothing else may keep anything there.

---

# 6.12 Conformance

_Peios Specifications / PGSS / Events_

> The obligations of the emitter, the consumer and the system, gathered in one place, and what conformance does not require.

## 6.12.1 A conforming emitter

- Writes event types of at least three segments, kebab-case, ending in a
  past-tense verb, under a platform root listed against it or under its
  own package name (§6.3).
- Writes one event type per action, with the result in `outcome.*`, and
  carries `outcome.success` wherever the action can fail (§6.6).
- Encodes every path as nested maps, never as a key containing `.`, and
  writes only defined fields and the variants and standard attributes
  §6.4 permits (§6.4, §6.10).
- Writes nothing at a header path, and does not repeat a header value in
  its payload (§6.4, §6.5).
- Encodes each value in its type's wire form, omits a field that has no
  value, carries principals as SIDs without names, and writes no
  debugging output (§6.5).
- Carries `object.kind` wherever it carries an access mask (§6.5).
- Makes access decisions about objects it guards through the kernel's
  access check, passes the object's identity as the audit context, and
  writes no access-decision event of its own (§6.7).
- Keeps a stored descriptor's SACL intact and its store writable only by
  those trusted with audit policy (§6.7).
- Writes events, not log text, and declares each type's tier, choosing
  essential only for one of the two reasons of §6.8.
- Writes no event whose type the emission policy finds off, and an
  event of a gated type only where its gating also asks for it; writes
  essential events without consulting the policy; applies a change to
  it within one second; and falls back to tier defaults, without
  holding events back, when it cannot read it (§6.9).
- Installs a fragment describing every event type it writes and every
  field it defines, which passes the rules of §6.10.

## 6.12.2 A conforming consumer

- Exposes header values under the paths of §6.4.
- Does not treat an event type's root as evidence of who wrote it
  (§6.3), and does not present an asserted field as observed by the
  kernel (§6.7).
- Does not accept a value in a wire form other than its type's (§6.5).
- Treats an unknown value of an open enumeration as a value, not an
  error (§6.5).
- Reads the catalog from every `.evman` file in `/usr/share/evman/` and
  no subdirectory, and treats a fragment breaking rule 1, 2 or 3 as
  defining nothing (§6.10).

## 6.12.3 A conforming system

- Has the platform fragment at `/usr/share/evman/kernel.evman` (§6.10).
- Lets every emitter read `Machine\Generic\Events`, lets only
  administrators write it and the keys of platform roots, and SHOULD
  audit writes to it (§6.9).

## 6.12.4 What conformance does not require

Conformance does not require an emitter to write any particular event,
to cache the emission policy, or to define fields beyond those it
writes. It does not require a consumer to store, index or query events,
to read the catalog at all, or to resolve SIDs to names. It does not
require either role to know about any event type or field other than the
ones it writes or reads: an unknown event type is still an event, and an
unknown field is still a value at a path.

---

# Appendix 6.A Platform Roots

_Peios Specifications / PGSS / Events_

> The short event-type roots reserved to platform components, the component each belongs to, and the package that ships it.

The platform roots (§6.3). Every other emitter roots its event types at
its package name. This list is open: a root is added by appending it
under §6.11, and is never reassigned.

| Root | Component | Package |
|---|---|---|
| `kacs` | Kernel Access Control Subsystem | `dev.peios.kernel` |
| `lcs` | The kernel's registry (configuration store) | `dev.peios.kernel` |
| `kmes` | Kernel Mediated Event Subsystem | `dev.peios.kernel` |
| `stratafs` | StrataFS | `dev.peios.kernel` |
| `ntfe` | The kernel's network-policy engine | `dev.peios.kernel` |
| `peinit` | The service manager | `dev.peios.peinit` |
| `peipkg` | The package manager | `dev.peios.peipkg` |
| `eventd` | The event store | `dev.peios.eventd` |
| `authd` | The authentication daemon | `dev.peios.authd` |
| `lpsd` | The local principal source | `dev.peios.authd-lpsd` |
| `timed` | The time daemon | `dev.peios.timed` |
| `netd` | The network daemon | `dev.peios.netd` |
| `trustd` | The trust daemon | `dev.peios.trustd` |
| `radiusd` | The RADIUS authentication daemon | `dev.peios.radius` |
| `fservd` | The file server | `dev.peios.fservd` |
| `pkid` | The certificate authority service | `dev.peios.pki` |
| `cryptod` | The crypto policy service | `dev.peios.cryptod` |

These roots are reserved for components that write no events yet, and
MUST NOT be used by anything else:

| Root | Component |
|---|---|
| `resolvd` | The name-resolution daemon |
| `ud` | The user daemon |
| `loregd` | The log store |

> [!NOTE]
> A root names a component rather than a package because one package
> ships several components with separate concerns: the kernel package
> ships five, and an administrator who wants the access audit without
> the network-policy reports needs `kacs` and `ntfe` to be separate
> policy anchors.

---

# Appendix 6.B Prior Art

_Peios Specifications / PGSS / Events_

> The event vocabularies this chapter learned from — Windows event logging and auditing, the Elastic Common Schema and OpenTelemetry's semantic conventions — and where it departs from each.

This appendix is informative.

## 6.B.1 Windows event logging and auditing

Peios's access model is Windows's, and so is the shape of its audit:
SACLs with audit ACEs decide which accesses are recorded, and a token's
audit policy can force recording for one principal. Windows audit policy
also sits above SACLs, so that a category switched off suppresses even
records a SACL asks for. §6.9 keeps that relation for a gated event type
that is not essential, and drops it for the access audit itself, which
is essential so that a SACL alone decides (§6.8).

This chapter departs from Windows in its names. Windows identifies events
by numeric ID within a provider, and its payload fields are named per
event; the same value is `SubjectUserSid` in one event and `TargetSid`
in another. Here the name is the policy anchor, so every event type is
a dotted name and every value has one path.

## 6.B.2 Elastic Common Schema

The Elastic Common Schema names fields by dotted, nested paths and
shares a field set across sources, so that one query finds a host or a
user wherever it appears. This chapter takes the same approach.

It departs in leading with the participant's role rather than its kind:
`subject.token.sid`, where the schema leads with the kind of thing. A
consumer searching for a principal in any role searches across roles
either way, and leading with the role makes `subject` a single policy
anchor for "may see who did it".

## 6.B.3 OpenTelemetry semantic conventions

OpenTelemetry names attributes by dotted paths and keeps a registry of
them with stability levels, so that a name is defined once and
referenced everywhere. The catalog of §6.10 plays the registry's part,
and its rule that no path is defined twice is the same discipline,
checked mechanically.

It departs in fixing the type and wire form of every value, rather than
leaving encoding to each exporter, because the event stream is consumed
directly and a SID or a time written two ways is two values to every
query.

---

# 7.1 Scope and Roles

_Peios Specifications / PGSS / Signed Objects_

> What PGSS Signed Objects specifies, a certificate chain with warrants that vouches for a file's bytes, and the four roles that issue, keep, verify, and rely on it.

This chapter specifies the **Peios Signed Object (PSO)**: a way for a
party to vouch for the bytes of a file, and for a system to decide how
far that statement is trusted.

A PSO is not a bare signature. It is a chain of certificates ending in a
signed statement about one file, and every power the chain confers is
written into it as a warrant (§7.5). A verifier walks the chain, checks
that no certificate claims more than the one that issued it, and reports
which of the system's trust anchors the chain ends at.

Four roles participate.

| Role | Obligation |
|---|---|
| Authority | Holds a key and a certificate for it. Issues certificates, leaves, and revocations, and every rule on what those objects contain binds the authority. |
| Store keeper | Maintains the system's trust store (§7.10): which top-level certificates are trusted, which revocations apply, and what the administrator distrusts. |
| Verifier | Validates a bundle against a file and the trust store, and reports a result (§7.14). Every validation and rejection rule binds the verifier. |
| Consumer | Asks a verifier about a file and acts on the result. A consumer decides which results and which warrants it accepts. |

The authority and consumer roles are publicly implementable. A third
party MAY issue its own certificates and leaves, and MAY write a consumer
that gives its own meaning to a warrant, and interoperate with the rest
unchanged. A system has one store keeper and at least one verifier, and a
system with several verifiers MUST have them agree: two verifiers on one
system, given the same bundle, file, and store, return the same result.

This chapter covers:

- the chain and what each part of it is (§7.3)
- the encoding shared by every object, and the hash and signature
  algorithms (§7.4)
- warrants: their encoding, how they narrow, and the three this chapter
  defines (§7.5)
- certificates, leaves, and bundles (§7.6, §7.7, §7.8)
- where a bundle is carried and which bytes of the file it covers (§7.9)
- the trust store, and how a certificate that is not carried is found
  (§7.10, §7.11)
- revocation and distrust (§7.12, §7.13)
- verification and its results (§7.14)

This chapter does not cover:

- What any warrant other than `Delegate`, `Revoke`, and `Name` means.
  The specification of the consumer that acts on a warrant defines it.
- What a consumer does with a result: whether a program runs, at what
  protection, or whether a repository is believed. For executables on
  Peios that is PSPK §3.
- How a verifier inside a kernel is given the trust store, and the
  interface through which a store keeper changes it while the system
  runs. For the Peios kernel that is PSPK §6.
- How an administrator's approval is obtained. This chapter requires
  that it is (§7.10), and the store keeper's documentation says how.
- Key generation, custody, and rotation. Those are the authority's.
- Certificates for network protocols. Those are X.509 (RFC 5280) and are
  unrelated to this chapter.

---

# 7.2 Terminology

_Peios Specifications / PGSS / Signed Objects_

> The terms this chapter is specified in, covering object, root, top-level, intermediary, leaf, bundle, warrant, trust store, revocation, distrust, and quarantine.

**Object.** One of the encoded structures of this chapter: a certificate,
a leaf, a bundle, a revocation, or a distrust entry. Every object begins
with the header of §7.4.

**Root.** A public key a verifier is built with. A root has no
certificate and holds no warrants. It signs top-level certificates and
nothing else.

**Certificate.** An object that binds a public key to a name and a set of
warrants, signed by its issuer (§7.6). A certificate is a **top-level**
or an **intermediary**.

**Top-level.** A certificate at the head of a chain. A root signs it, or
it signs itself.

**Intermediary.** A certificate issued by a top-level or by another
intermediary.

**Leaf.** A signed statement that a file has a given content hash, made
under a name and requesting a set of warrants (§7.7). A leaf holds no
key, so nothing can be issued beneath it.

**Chain.** A leaf, the certificate that issued it, and each issuer in
turn up to a top-level.

**Bundle.** The object a file carries: a leaf and as much of its chain
as the signer chose to include (§7.8).

**Warrant.** A named power written into a certificate or requested by a
leaf (§7.5). A power that is not written down is not held.

**Trust store.** The directories that say which top-levels a system
trusts, which revocations it applies, and what its administrator
distrusts (§7.10).

**Enabled.** Said of a top-level the trust store accepts (§7.10).

**Quarantined.** Said of a self-signed top-level that a package ships
and the administrator has not approved (§7.10).

**Revocation.** A signed object by which an authority withdraws a
certificate or a leaf beneath it (§7.12).

**Distrust.** An unsigned entry by which a system's administrator
refuses a certificate or a leaf on that system (§7.13).

**Object hash.** The SHA-512 hash of all of an object's bytes, its
signature included (§7.4).

**Key hash.** The SHA-512 hash of a key type byte followed by the key it
describes (§7.4).

Terms defined in PSPU §5.2 (package and closure) are used with the same
meaning and are not redefined. *Extended attribute* is used as the Peios
Kernel TRM defines it.

---

# 7.3 The Chain

_Peios Specifications / PGSS / Signed Objects_

> How roots, top-level certificates, intermediaries, and a leaf link by hash into one chain, the limit on its depth, and why a leaf carries no key.

A chain has four kinds of member.

| Member | Signed by | Holds a key | Holds warrants |
|---|---|---|---|
| Root | Nothing | Yes | No |
| Top-level | A root, or itself | Yes | Yes |
| Intermediary | A top-level or an intermediary | Yes | Yes |
| Leaf | A top-level or an intermediary | No | Yes, as requests |

## 7.3.1 Links

Every certificate and every leaf names its issuer in an `issuer` field of
64 bytes:

- A leaf's and an intermediary's `issuer` is the object hash of the
  certificate that issued it.
- A top-level's `issuer` is the key hash of the root that signed it, or
  the key hash of its own key if it signed itself.

A link holds when the named issuer's key verifies the signature of the
object that names it.

> [!NOTE]
> The link is to a certificate, not to a key. One key can have two
> certificates with different warrants, and a link by key would let a
> signer choose whichever was more generous after the fact.

## 7.3.2 Roots

A verifier is built with one or more roots, each a key type and a key
(§7.4). A verifier MUST NOT accept a root from any other source, and
MUST treat every root it holds as equal: a chain that ends at any of
them is rooted.

A root's signature on a top-level says that the warrants the top-level
claims are valid. That is the whole of what a root asserts.

## 7.3.3 Depth

A chain MUST NOT hold more than 16 intermediaries between its leaf and
its top-level. A verifier MUST report a longer chain as invalid (§7.14).

An authority SHOULD keep a chain to fewer than 6 intermediaries. The
limit is set well above that so that it does not constrain how an
authority arranges custody of its keys: an offline certificate, a
certificate for each region or product, and a signing certificate that
is replaced on a schedule are each one intermediary.

## 7.3.4 Why a leaf holds no key

A leaf is a statement, not a certificate. An authority that signs files
already holds the key of the certificate it signs them under, so a key
for each leaf would be one more secret to protect with nothing gained.
Without a key, a leaf cannot issue anything, and a chain always ends
where a file begins.

---

# 7.4 Object Encoding

_Peios Specifications / PGSS / Signed Objects_

> The 6-byte header every object begins with, how an object is hashed and signed with SHA-512 and ML-DSA, the two key types, and the rule that the issuer's key decides the algorithm.

Every object is a sequence of fields in a fixed order with no padding.
No field is optional. Where a field's size varies, a length precedes it.

## 7.4.1 The header

Every object begins with these 6 bytes.

| Field | Type | Value |
|---|---|---|
| `magic` | `u8[3]` | `50 53 4f`, the ASCII bytes `PSO` |
| `kind` | `u8` | What the object is (§7.B) |
| `version` | `u8` | The format version. This chapter specifies `0x01`. |
| `reserved` | `u8` | `0x00` |

A verifier MUST treat an object whose `magic`, `version`, or `reserved`
differs from these values as malformed, and MUST treat an object as
malformed if its `kind` is not the kind the context calls for.

## 7.4.2 Malformed objects

An object is **malformed** if it does not decode exactly as its layout
gives: a field out of its permitted range, a length that runs past the
end of the object, a reserved bit that is set, or any byte after the
last field. A verifier MUST NOT repair, truncate, or reinterpret a
malformed object.

## 7.4.3 Hashes

Every hash in this chapter is SHA-512 (FIPS 180-4), 64 bytes, carried as
raw bytes.

The **object hash** of an object is the hash of all of its bytes, from
the first byte of the header through the last byte of its signature.

The **key hash** of a key is the hash of its key type byte followed by
the key's bytes.

Where a hash names a file in the trust store or in a directory of
certificates, the name is the hash in lowercase hexadecimal, 128
characters.

## 7.4.4 Keys

A key is a key type and the raw public key that the type implies.

| Key type | Algorithm | Public key | Signature |
|---|---|---|---|
| `0x01` | ML-DSA-65 | 1952 bytes | 3309 bytes |
| `0x02` | ML-DSA-87 | 2592 bytes | 4627 bytes |

The enumeration is closed (§7.15). A public key is the raw encoding of
FIPS 204, with no wrapper.

## 7.4.5 Signatures

A signature is the last field of the object it signs, and covers every
byte of the object before it, the header included.

```text
ML-DSA.Sign(private_key, bytes_before_signature, ctx = "")
```

This is pure ML-DSA, FIPS 204 Algorithm 2, with an empty context string.
An authority MUST NOT use the pre-hashing variant and MUST NOT set a
context.

**The issuer's key decides the algorithm.** A signed object does not
name the algorithm of its own signature. A verifier takes the algorithm,
and so the length of the signature field, from the key type of the
issuer the object names. A verifier MUST NOT take either from anything
in the object being verified.

> [!NOTE]
> The header is inside the signed bytes, and it carries the object's
> kind. A signature made over a leaf therefore cannot be presented as a
> signature over a certificate or a revocation: the bytes differ at
> offset 3. This is what separates the uses of one key, and it is why
> the context string can be left empty.

---

# 7.5 Warrants

_Peios Specifications / PGSS / Signed Objects_

> How a warrant is encoded, its flags and its three types, the rule that a child never holds more than its parent, how an unrecognized warrant is treated, and the Delegate, Revoke, and Name warrants.

A **warrant** is a named power. A certificate holds the warrants written
into it, and a leaf requests the warrants written into it. A power that
is not written down is not held: there is no default and no implied
warrant.

A warrant only ever grants. No warrant removes a power or narrows
another warrant, and a specification that defines a warrant MUST NOT
give it such a meaning.

## 7.5.1 Encoding

A warrant is encoded as follows.

| Field | Type | Description |
|---|---|---|
| `name_len` | `u8` | Length of `name`, from 1 through 255 |
| `name` | `u8[name_len]` | The warrant's name |
| `flags` | `u8` | Flags and type |
| `value_len` | `u16` | Length of `value` |
| `value` | `u8[value_len]` | The value, in the form its type gives |

A `name` holds only the ASCII letters, the ASCII digits, `.`, and `-`.
A name with no `.` is reserved to this chapter and to the Peios
specifications. Any other party MUST name its warrants beneath a domain
name it controls, written in reverse, as `com.example.Scanner`.

The warrants of one object are written in ascending order of `name`,
compared byte for byte, and no two have the same name.

## 7.5.2 Flags

The `flags` byte is read as follows.

| Bits | Mask | Meaning |
|---|---|---|
| 7 | `0x80` | Allow Equal |
| 6–4 | `0x70` | Type |
| 3 | `0x08` | Must Understand |
| 2–0 | `0x07` | Reserved, zero |

**Allow Equal** says whether a child's value can equal its parent's. If
the bit is clear, the child's value MUST be strictly narrower.

**Must Understand** says what a verifier that does not recognize the
warrant's name does with it. If the bit is set, the verifier MUST report
the chain as invalid. If the bit is clear, the verifier checks the
warrant as the narrowing rule requires and gives it no other effect.

## 7.5.3 Types

The type decides the form of the value and how one value is narrower
than another.

| Type | Name | Value |
|---|---|---|
| `0` | Set | Zero or more elements |
| `1` | Namespace | One or more names |
| `2` | Limit | One `u64` |

The enumeration is closed (§7.15). A warrant of any other type is
malformed.

A **Set** value is empty, or is elements separated by a single `00`
byte. An element is one or more bytes in the range `0x20` through
`0x7E`. No element appears twice. A Set with no elements is a plain
flag: the warrant is held or it is not.

A **Namespace** value has the form of a Set, and each element is a name:
labels of lowercase ASCII letters, digits, and `-`, joined by `.`, or
the single element `.`. A name is **within** another if the two are
equal, or if it ends with `.` followed by the other. Every name is
within `.`.

A **Limit** value is exactly 8 bytes, a `u64`.

> [!NOTE]
> The boundary matters. Under plain suffix matching `evilexample.com`
> is within `example.com`. Requiring the `.` before the suffix is what
> stops one publisher's namespace containing a stranger's. A name from
> an internationalized domain is written in its ASCII form.

## 7.5.4 Narrowing

A certificate or leaf is the **child** of the certificate that issued
it. For every warrant a child holds, a verifier MUST find that all of
the following hold, and MUST report the chain as invalid if any does
not:

1. The parent holds a warrant of the same name.
2. The two `flags` bytes are equal.
3. The child's value is no wider than the parent's.
4. If Allow Equal is clear, the child's value is not equal to the
   parent's.

For a Set, no wider means every element of the child's value is an
element of the parent's, and equal means the two hold the same
elements. For a Namespace, no wider means every name of the child's
value is within some name of the parent's, and equal means the two hold
the same names. For a Limit, no wider means the child's number is not
greater than the parent's.

A top-level has no parent, and its warrants are not narrowed against
anything.

A verifier applies these rules to every warrant, whether or not it
recognizes the name. The rules need only the flags and the value.

> [!NOTE]
> A child that claims more than its parent is rejected, not trimmed.
> Every certificate in a valid chain therefore states what it really
> holds, and a reader does not have to intersect a chain in their head
> to learn what a signer can do.

## 7.5.5 Warrants this chapter defines

Three warrants govern the chain itself. A leaf MUST NOT hold any of
them.

| Name | Type | Allow Equal | `flags` | Meaning |
|---|---|---|---|---|
| `Delegate` | Limit | Clear | `0x20` | How many certificates can stand between the holder and a leaf |
| `Name` | Namespace | Set | `0x90` | The names the holder's leaves can be issued under |
| `Revoke` | Set, empty | Set | `0x80` | The holder can revoke itself and what is beneath it (§7.12) |

A certificate can issue a certificate only if it holds `Delegate` with a
value of 1 or more. Because Allow Equal is clear, each certificate down
a chain holds a smaller value than its issuer or does not hold the
warrant at all. A certificate without `Delegate` issues leaves and
nothing else.

A leaf's `name` field MUST be within a name of its issuer's `Name`
warrant (§7.7). A certificate without `Name` cannot issue a leaf.

## 7.5.6 Other warrants

Every other warrant is defined by the specification of the consumer that
acts on it. A verifier reports the warrants a leaf holds, and gives none
of them any effect of its own.

---

# 7.6 Certificates

_Peios Specifications / PGSS / Signed Objects_

> The layout of a certificate, the two roles a certificate can have, what its issuer field names in each, and the rules on its subject name and key.

A certificate binds a key to a name and a set of warrants. Top-levels
and intermediaries share one layout.

| Field | Type | Description |
|---|---|---|
| header | 6 bytes | `kind` is `0x01` (§7.4) |
| `role` | `u8` | `0x01` for a top-level, `0x02` for an intermediary |
| `issuer` | `u8[64]` | The issuer (§7.3) |
| `name_len` | `u8` | Length of `name`, from 1 through 255 |
| `name` | `u8[name_len]` | The subject's name |
| `key_type` | `u8` | The type of `key` (§7.4) |
| `key` | By `key_type` | The subject's public key |
| `warrant_count` | `u8` | The number of warrants |
| `warrants` | Variable | That many warrants (§7.5) |
| `signature` | By the issuer's key type | Signature over every preceding byte |

The `role` enumeration is closed (§7.15).

## 7.6.1 Name

A certificate's `name` describes its holder to a person, as
`Example Corporation Signing 1`. It holds bytes in the range `0x20`
through `0x7E`. No rule of this chapter compares it with anything, and a
consumer MUST NOT make a decision on it.

> [!NOTE]
> The name is chosen by whoever made the certificate. What a signer can
> sign as is decided by its `Name` warrant, which its issuer bounded,
> and never by what its certificate calls itself.

## 7.6.2 Issuer and signature

For an intermediary, `issuer` is the object hash of the issuing
certificate, and the signature verifies under that certificate's key.

For a top-level, `issuer` is one of two things:

- **The key hash of a root.** The signature verifies under that root.
- **The key hash of the certificate's own key.** The certificate is
  **self-signed**, and the signature verifies under its own key.

A top-level whose `issuer` is neither a root the verifier holds nor its
own key hash was signed by a key the verifier does not have. A verifier
cannot check that signature, and treats the certificate as §7.14
describes.

---

# 7.7 Leaves

_Peios Specifications / PGSS / Signed Objects_

> The layout of a leaf, the two forms of content hash and when each is used, the name a leaf is issued under, and the warrants it requests.

A leaf states that a file has a given content hash. It is issued under a
name and requests warrants.

| Field | Type | Description |
|---|---|---|
| header | 6 bytes | `kind` is `0x02` (§7.4) |
| `hash_form` | `u8` | Which bytes `content_hash` covers (§7.9) |
| `content_hash` | `u8[64]` | The hash of those bytes |
| `issuer` | `u8[64]` | The object hash of the issuing certificate |
| `name_len` | `u8` | Length of `name`, from 1 through 255 |
| `name` | `u8[name_len]` | The name the leaf is issued under |
| `warrant_count` | `u8` | The number of warrants |
| `warrants` | Variable | That many warrants (§7.5) |
| `signature` | By the issuer's key type | Signature over every preceding byte |

## 7.7.1 Name

A leaf's `name` says who vouches for the file. It has the form of a
Namespace name other than `.` (§7.5), and MUST be within a name of the
issuing certificate's `Name` warrant.

Unlike a certificate's name, a leaf's name is bounded by the chain, so a
consumer can rely on it: a leaf named `scanner.example.com` was issued
by an authority that its own issuers allowed to sign for `example.com`.

## 7.7.2 Warrants

A leaf's warrants are the powers its signer asks for on behalf of the
file. They narrow against the issuing certificate as §7.5 requires, so a
leaf never holds a warrant its issuer lacks. A leaf MUST NOT hold
`Delegate`, `Name`, or `Revoke`.

A signer SHOULD request only what the file needs. A leaf that requests
every warrant its issuer holds gives each consumer more to act on than
the signer meant, and a signer that issues one certificate for many
kinds of file is the case where this matters.

## 7.7.3 What a leaf does not hold

A leaf holds no key, no time of signing, and no period of validity. A
verifier applies no clock to any object (§7.14).

> [!NOTE]
> Signatures that expire need a trusted timestamp to keep old files
> valid after their certificate's time has passed, and they need a
> clock the verifier can believe, which a system does not have early in
> boot and which an administrator can set. Withdrawal here is explicit,
> by revocation (§7.12), and there is nothing for a clock to decide.

---

# 7.8 Bundles

_Peios Specifications / PGSS / Signed Objects_

> The layout of a bundle, the order of the certificates it carries, why it can stop short of the top-level, and its size limit.

A **bundle** is what a file carries: a leaf, and as much of the leaf's
chain as the signer chose to include.

| Field | Type | Description |
|---|---|---|
| header | 6 bytes | `kind` is `0x03` (§7.4) |
| `cert_count` | `u8` | The number of certificates, from 0 through 17 |
| `leaf_len` | `u16` | Length of `leaf` |
| `leaf` | `u8[leaf_len]` | A leaf (§7.7) |
| certificates | Variable | `cert_count` entries, each a `u16` length and a certificate (§7.6) |

A bundle is not signed. Every object in it is.

## 7.8.1 Order

The first certificate is the one the leaf's `issuer` names. Each later
certificate is the one the certificate before it names. A top-level, if
the bundle carries one, is the last certificate. A bundle that breaks
this order is malformed.

## 7.8.2 Stopping short

A bundle need not carry the whole chain. Where it stops, the `issuer`
field of its last object names the next certificate, and a verifier
finds that certificate as §7.11 describes.

A signer chooses between two things:

- **A short bundle.** Each file carries its leaf and perhaps its signing
  certificate. The certificates further up are installed once and found
  by hash. A deep chain then costs each file nothing.
- **A complete bundle.** The file verifies with nothing else present, at
  a cost of about 5.3 KiB for each certificate.

A bundle MAY carry its top-level. A carried top-level is used to verify
the chain, and it is never enabled by being carried: only the trust
store enables a top-level (§7.10).

## 7.8.3 Size

A bundle MUST NOT exceed 65,536 bytes. A verifier MUST report a larger
bundle as invalid, whatever the depth of its chain.

> [!NOTE]
> The limit is the largest value an extended attribute can hold, so
> that the same bundle fits every place a bundle is carried (§7.9).
> Depth and size are separate limits, and a chain within the depth
> limit can still be too large to carry whole.

---

# 7.9 Carrying a Bundle

_Peios Specifications / PGSS / Signed Objects_

> The three places a bundle is carried, an ELF section, an extended attribute, and a detached file, the bytes each covers, and the order a verifier looks in them.

A bundle is carried in one of three places. The bundle's bytes are the
same in each.

| Place | Name | For | Hash form |
|---|---|---|---|
| ELF section | `.pso` | An ELF object | `0x02` |
| Extended attribute | `security.pso` | Any file | `0x01` |
| Detached file | `<file>.pso`, beside the file | Any file, where a consumer says so | `0x01` |

## 7.9.1 Hash forms

A leaf's `hash_form` says which bytes of the file its `content_hash`
covers. The enumeration is closed (§7.15).

**`0x01`, whole file.** The hash covers every byte of the file.

**`0x02`, ELF.** The hash covers the file with the contents of its
`.pso` section replaced by zeros. If the file also has a `.peios.sig`
section (PSPK §3.2), its contents are replaced by zeros as well. Only
section contents are replaced: the section headers, and every other byte
of the file, are hashed as they are.

A verifier MUST require the hash form the place calls for, and MUST
report a leaf with any other as invalid. A bundle moved from one place
to another does not verify.

> [!NOTE]
> A file that carries both `.pso` and `.peios.sig` is one that has to
> verify under this chapter and under the older format at once. Each
> signature would otherwise cover the other. A signer avoids the
> circle by adding the bundle first, with both sections zeroed, and the
> older signature second, over the result.

## 7.9.2 The ELF section

An ELF object SHOULD carry its bundle in a section named exactly `.pso`.
The name comparison covers the terminating NUL, so a longer name with
`.pso` as a prefix does not match. Where several sections have the name,
the one at the lowest index is used.

The section's type MUST be `SHT_PROGBITS`, and its range MUST lie within
the file. The file MUST be `ELFCLASS64` and `ELFDATA2LSB`, with
`e_shentsize` equal to 64 and a valid `e_shstrndx`.

A signer reserves the section at its final size before it hashes,
because the section headers are covered. The size is known in advance:
every field of a bundle has a length the signer can compute before it
signs.

## 7.9.3 The extended attribute

Any file MAY carry its bundle in the extended attribute `security.pso`.
This is the only place for a file that is not ELF, short of a detached
file.

An extended attribute belongs to the file as stored, not to its bytes,
so a signer cannot ship one. A signer writes the bundle as a detached
file, and whatever installs the file sets the attribute from it. For a
package, that is PSPU §5.16.

## 7.9.4 The detached file

A detached bundle is a file named for the file it covers, with `.pso`
added, in the same directory. A verifier looks for one only when the
consumer asks it to, as a consumer that fetches signed metadata does.

## 7.9.5 Lookup order

A verifier asked about a file, and not told where the bundle is, MUST
find it as follows:

1. If the file begins with `7f 45 4c 46`, read its ELF structures and
   look for a `.pso` section. If the section header is found, the bundle
   is the section's contents, and the extended attribute is not
   consulted, whatever happens next.
2. Otherwise, read `security.pso`. If it is present, it is the bundle.
3. Otherwise, the file has no bundle.

A failure after the section header is found, such as a wrong type, a
range outside the file, or a malformed bundle, makes the result invalid.
It does not send the verifier to the extended attribute.

> [!NOTE]
> Without this commitment, a party able to damage the section could
> choose which of the two places the verifier believed, and would
> choose the one it controlled.

A file with no bundle is not invalid. It is unsigned, which §7.14
reports as its own result.

---

# 7.10 The Trust Store

_Peios Specifications / PGSS / Signed Objects_

> The directories that hold top-levels, revocations, and distrust entries, which top-levels a store keeper enables, how a package's self-signed top-level is quarantined, and how approval is recorded as a link.

The **trust store** is the part of a system that says which top-levels
it trusts. A verifier accepts a top-level only if the trust store
enables it. A top-level found anywhere else, including in a bundle, is
not enabled.

## 7.10.1 Directories

The store is read from two trees.

| Directory | Written by | Holds |
|---|---|---|
| `/usr/share/pso/toplevel/` | Packages | Top-levels that packages ship |
| `/usr/share/pso/revocation/` | Packages | Revocations that packages ship |
| `/lcl/policy/pso/toplevel/` | The store keeper | Top-levels the administrator trusts |
| `/lcl/policy/pso/revocation/` | The store keeper | Revocations the store keeper has accepted |
| `/lcl/policy/pso/distrust/` | The store keeper | Distrust entries (§7.13) |

`/usr` here is the system's own, the closure a system runs as (PSPU
§5.27), and never the `/usr` of another closure.

Each entry is one object in a file of its own. A top-level or a
revocation is named by its object hash, and a distrust entry by the hash
it distrusts, in the form §7.4 gives. A store keeper MUST ignore an
entry whose content does not match its name.

## 7.10.2 Which top-levels are enabled

A store keeper enables a top-level in exactly these cases:

- It is in `/usr/share/pso/toplevel/`, its `issuer` is the key hash of a
  root the system's verifier holds, and its signature verifies under
  that root.
- It is in `/lcl/policy/pso/toplevel/`.

A top-level in `/usr/share/pso/toplevel/` that a root did not sign is
**quarantined**. It is present and it is not enabled.

> [!NOTE]
> `/usr` is written by packages. If a self-signed top-level were
> enabled by being there, installing any package would be enough to
> give its publisher a trust anchor. A root-signed top-level needs no
> such care, because the root's signature already vouches for what it
> claims.

## 7.10.3 Approval

An entry in `/lcl/policy/pso/toplevel/` is one of two things:

- **A file.** A top-level the administrator supplied directly.
- **A symbolic link** to the entry of the same name in
  `/usr/share/pso/toplevel/`. This is the administrator's approval of a
  quarantined top-level.

A store keeper MUST record an approval as a link and MUST NOT copy the
certificate. A link whose target is absent enables nothing.

A store keeper MUST resolve a link against the root of the system whose
store it is reading, which is not always the system it is running on.

> [!NOTE]
> The link leaves the package as the owner of the certificate. If the
> package later withdraws its top-level, the link dangles and the
> top-level stops being enabled, with no action from the administrator.
> A copy would outlive the package's own decision. A replacement
> certificate has a different hash, so it arrives quarantined and is
> approved on its own merits.

A store keeper MUST obtain the administrator's approval before it adds
an entry to `/lcl/policy/pso/toplevel/`, and MUST show the certificate's
name and every warrant it holds before the approval is given. How
approval is obtained is the store keeper's.

## 7.10.4 What enabling means

Enabling a top-level trusts its holder with every warrant the
certificate states. This chapter gives a store keeper no way to enable a
top-level for some of its warrants and not others.

For a root-signed top-level, the root vouches for those warrants. For
any other, nothing does: a self-signed top-level states whatever its
maker wrote. That difference is why §7.14 reports the two apart.

## 7.10.5 Access

The directories under `/lcl/policy/pso/` grant authority. A system MUST
restrict writing to them to its store keeper.

---

# 7.11 Finding Certificates

_Peios Specifications / PGSS / Signed Objects_

> How a verifier finds an intermediary that a bundle names but does not carry, by its hash in a directory packages install into, and why the directory needs no protection.

A bundle that stops short names a certificate it does not carry (§7.8).
A verifier finds it by its object hash.

## 7.11.1 Top-levels

If the hash is that of an enabled top-level, the verifier uses the
top-level from the trust store (§7.10).

## 7.11.2 Intermediaries

Otherwise the verifier reads the file named by the hash in
`/usr/share/pso/intermediate/`. A package that ships intermediaries
installs each there, in a file named by its object hash (§7.4).

The `/usr` in question is that of the party on whose behalf the
verifier is working: the process that asked, or the process loading the
file. Where the verifier works for the system itself, it is the
system's own.

A verifier MUST do all of the following:

- Read only a regular file, and follow no path to anything else.
- Read no more than 65,535 bytes.
- Check that the content's object hash is the hash it was looking for.
- Treat the certificate, once read, exactly as if the bundle had carried
  it.

A verifier MAY remember a certificate it has verified, by its hash. What
it remembers MUST NOT delay a change to the trust store: a revocation or
a distrust entry applies to every verification after it is accepted.

> [!NOTE]
> The directory is whatever the asking process has as its `/usr`, and
> a process can arrange for that to be anything. This is safe because
> a certificate found there proves itself: its hash has to match the
> one a signed object named, and it still has to chain to an enabled
> top-level. Placing a file there gains nothing. That is also why a
> system with many closures needs no central list of intermediaries:
> each closure carries the ones its own programs use.

## 7.11.3 When nothing is found

If the named certificate is in none of these places, the chain cannot
be completed. A verifier reports this as its own result, not as an
invalid chain (§7.14): a file whose intermediary is not installed has
not been altered.

---

# 7.12 Revocation

_Peios Specifications / PGSS / Signed Objects_

> The layout of a revocation, who can revoke what, why a revocation needs no root and no list signer, and how a store keeper accepts and keeps one.

A **revocation** is the act of an authority: a signed object that
withdraws a certificate or a leaf.

| Field | Type | Description |
|---|---|---|
| header | 6 bytes | `kind` is `0x04` (§7.4) |
| `target_type` | `u8` | `0x01` for a certificate, `0x02` for a leaf |
| `target` | `u8[64]` | The object hash of what is revoked |
| `signer` | `u8[64]` | Who signed the revocation |
| `signature` | By the signer's key type | Signature over every preceding byte |

The `target_type` enumeration is closed (§7.15).

## 7.12.1 Who can revoke

A revocation applies to a chain when its `target` is a member of the
chain and its `signer` is one of the following:

- **The target itself**, where the target is a certificate that holds
  `Revoke`. `signer` is the target's object hash.
- **A certificate above the target in the chain** that holds `Revoke`.
  `signer` is that certificate's object hash.
- **The root that signed the chain's top-level**, where the target is
  that top-level. `signer` is the root's key hash.

In each case the signature MUST verify under the signer's key. A
revocation that meets none of these does not apply, and a verifier MUST
ignore it.

Authority to revoke comes from standing above the target in its own
chain, and from nothing else. A revocation does not have to end at a
root. An authority whose top-level is self-signed revokes within its
own chain exactly as any other does.

> [!NOTE]
> A revocation can only take trust away, and only from what the signer
> issued or stands above. That is why it needs no vouching: an
> authority cannot reach a chain it is not part of. It is also why the
> set of revocations needs no signer of its own. Each entry proves
> itself, so any party can collect and pass them on.

## 7.12.2 Effect

A chain with a revoked member is refused (§7.14). Revoking a certificate
refuses every chain that passes through it, including every signature it
ever made: no object carries a time, so a revocation cannot be limited
to signatures made after some moment.

An authority that wants to limit the reach of a compromise SHOULD
replace its signing certificate on a schedule, so that revoking one
refuses only what that certificate signed.

A revocation stays in effect if its signer is later revoked.

## 7.12.3 Preparing a revocation in advance

An authority SHOULD sign a revocation for each certificate when the
certificate is made, and keep it apart from the key. Revoking then
means publishing a file, with no need for a key that might be offline,
lost, or in the wrong hands.

## 7.12.4 Accepting and keeping revocations

A store keeper takes revocations from `/usr/share/pso/revocation/` and
from any source it is configured to fetch from. It MUST accept a
revocation only when it holds, or is given with the revocation, the
certificates that show the revocation applies, and MUST then keep it in
`/lcl/policy/pso/revocation/`.

A store keeper MUST NOT remove a revocation it has accepted, including
when the package or source that supplied it withdraws it.

> [!NOTE]
> The attack on revocation is removal, not addition. An entry that
> arrives can only refuse something its signer was entitled to refuse.
> An entry that disappears restores trust in something its authority
> withdrew. A store keeper therefore needs no approval to add one and
> has no operation to remove one.

Accepting a revocation needs no approval from the administrator.

---

# 7.13 Distrust

_Peios Specifications / PGSS / Signed Objects_

> The layout of a distrust entry, how it differs from a revocation and from removing a top-level, and when an administrator's approval is needed.

**Distrust** is the act of an administrator: an unsigned entry that
refuses a certificate or a leaf on one system.

| Field | Type | Description |
|---|---|---|
| header | 6 bytes | `kind` is `0x05` (§7.4) |
| `target_type` | `u8` | `0x01` for a certificate, `0x02` for a leaf |
| `target` | `u8[64]` | The object hash of what is distrusted |

A distrust entry is kept in `/lcl/policy/pso/distrust/`, in a file named
by the hash it distrusts (§7.10). It never leaves the system it was
made on.

## 7.13.1 Effect

A chain with a distrusted member is refused (§7.14). Distrust takes
precedence over everything that enables or approves: a distrusted
top-level is not enabled, whatever else the trust store holds.

Distrust and revocation differ in who acts, and in nothing a consumer
can see.

| | Revocation | Distrust |
|---|---|---|
| Made by | An authority above the target | The system's administrator |
| Signed | Yes | No |
| Applies to | Every system that receives it | The system it was made on |
| Can be removed | No | Yes, with approval |

Distrust also differs from removing a top-level from the trust store. A
top-level that is not enabled can still head a chain that a consumer
accepts on its own terms (§7.14). A distrusted one cannot.

## 7.13.2 Approval

Adding a distrust entry takes trust away, and a store keeper MAY add one
without the approval §7.10 requires for a top-level.

Removing a distrust entry restores trust. A store keeper MUST obtain the
administrator's approval before it removes one, as it does before it
enables a top-level.

---

# 7.14 Verification

_Peios Specifications / PGSS / Signed Objects_

> What a verifier is given, the checks it makes in order, the seven results it can report, what it returns with each, and which results a consumer can rely on for what.

A verifier is given a file, or the content hash of one, and a bundle or
the means to find one (§7.9). It reports exactly one result.

## 7.14.1 Results

The results are listed from least to most trusted.

| Result | Meaning |
|---|---|
| Unsigned | The file has no bundle |
| Invalid | An object is malformed, a signature or a link fails, the content hash does not match, a warrant is added or widened, or a limit is exceeded |
| Incomplete | A certificate the chain names could not be found (§7.11) |
| Refused | The chain is otherwise sound, and a member is revoked or distrusted |
| Consistent | The chain is sound, and its top-level is not enabled |
| Unrooted | The chain is sound, and its top-level is enabled but not vouched for by a root |
| Rooted | The chain is sound, and its top-level is enabled and signed by a root the verifier holds |

A verifier that cannot make a check at all, for want of memory or of an
algorithm, MUST report an error and MUST NOT report any of these
results. "Could not be checked" and "did not verify" are different
answers.

## 7.14.2 The checks

A verifier MUST make these checks in this order, and reports the first
result that applies:

1. **Find the bundle.** If there is none, the result is Unsigned.
2. **Decode.** If the bundle or anything in it is malformed, or the
   bundle is over its size limit (§7.8), the result is Invalid.
3. **Check the content.** If the leaf's hash form is not the one the
   place calls for, or its content hash is not the file's (§7.9), the
   result is Invalid.
4. **Complete the chain.** Find each certificate the bundle names and
   does not carry (§7.11). If one is not found, the result is
   Incomplete. If the chain holds more than 16 intermediaries, the
   result is Invalid.
5. **Check the links.** Every `issuer` names the next member, every
   signature verifies, and only the last certificate is a top-level
   (§7.3, §7.6). A top-level whose issuer is a key the verifier does not
   hold has no signature the verifier can check, and passes this step
   unchecked. Any failure makes the result Invalid.
6. **Check the warrants.** Every child narrows against its parent, each
   certificate that issued a certificate holds `Delegate`, the leaf's
   name is within its issuer's `Name`, and the leaf holds none of the
   three warrants it is forbidden (§7.5). An unrecognized warrant with
   Must Understand set, anywhere in the chain, fails this step. Any
   failure makes the result Invalid.
7. **Apply revocations and distrust.** If a revocation applies to the
   chain (§7.12), or a member is distrusted (§7.13), the result is
   Refused.
8. **Place the top-level.** If the top-level is not enabled (§7.10), the
   result is Consistent. If it is enabled and step 5 verified its
   signature under a root, the result is Rooted. Otherwise the result is
   Unrooted.

A verifier applies no clock at any step. No object holds a time, and a
chain that verifies once verifies until it is revoked or distrusted.

## 7.14.3 What a verifier returns

With Consistent, Unrooted, and Rooted, a verifier MUST return:

- the leaf's name
- the leaf's warrants
- the object hash of the chain's top-level
- for Rooted, the key hash of the root

With Refused, a verifier MUST say whether the cause was a revocation or
a distrust entry. With any other result it returns nothing about the
chain.

The leaf's warrants are the chain's effective warrants. Step 6 has
already bounded them by every certificate above the leaf, so a consumer
needs nothing else from the chain, and MUST NOT decode the bundle to
reach a decision of its own.

## 7.14.4 What each result is good for

**Rooted** is the strongest statement a system can make about a file:
a root the verifier was built with vouches for the top-level's
warrants, and the system has that top-level enabled. A consumer that
grants anything an administrator could not grant MUST require it.

**Unrooted** says the system's administrator trusts the top-level, and
nothing more. The top-level's warrants are whatever its maker wrote. A
consumer MAY accept Unrooted for a decision that is the administrator's
to make, and SHOULD compare the returned top-level hash with the one it
expects where it expects a particular one.

**Consistent** says only that the chain agrees with itself. Anyone can
make such a chain. A consumer MUST NOT accept it unless it keeps its
own list of top-levels and finds the returned hash there.

**Refused**, **Incomplete**, **Invalid**, and **Unsigned** confer
nothing. A consumer MUST NOT treat Invalid as it treats Unsigned where
the difference matters to it: a file with no bundle made no claim, and a
file with a bad one made a claim that failed.

> [!NOTE]
> Invalid is not always tampering. A verifier that meets a warrant it
> does not recognize, with Must Understand set, reports Invalid for a
> chain a later verifier would accept. The guidance is the same either
> way, and a system that reports the cause to its administrator SHOULD
> distinguish the two.

---

# 7.15 Extension

_Peios Specifications / PGSS / Signed Objects_

> How PSO grows, through warrants any party can define, the Must Understand flag, the reserved bits and bytes, and the format version that closes every enumeration.

## 7.15.1 Additive changes

**Warrants.** The set of warrant names is open. Any party defines a
warrant by naming it as §7.5 requires and saying what it means to the
consumers that act on it. A verifier needs no change: it narrows every
warrant by its flags and value, and reports those a leaf holds.

**Certificates and revocations.** An authority issues these without
reference to any registry. A package installs intermediaries and
revocations into the directories of §7.10 and §7.11.

## 7.15.2 Warrants a verifier cannot ignore

A warrant that a verifier cannot safely ignore is marked Must Understand
(§7.5). A verifier that does not recognize it reports the chain as
invalid.

A specification that defines such a warrant accepts that every verifier
released before it reports chains holding the warrant as invalid, and
SHOULD set the flag only where a verifier that ignored the warrant would
reach a wrong result.

> [!NOTE]
> The flag exists so that a future need to restrict something does not
> force a format version. It is not a way to make warrants restrictive
> in general: a warrant still only grants (§7.5), and the flag says
> that a verifier has to know what is being granted.

## 7.15.3 Changes requiring a version

Every enumeration in this chapter is closed: object kinds, key types,
certificate roles, warrant types, hash forms, and target types (§7.B).
A new value in any of them, a new field in any layout, and any change to
the hash or signature algorithms require a new format version.

A verifier MUST treat an object whose `version` it does not implement as
malformed. A file that has to verify on systems of two versions carries
what each needs; this chapter does not define how two bundles share one
file.

## 7.15.4 Reserved space

The header's `reserved` byte and bits 2 through 0 of a warrant's `flags`
are reserved. An authority MUST write them as zero, and a verifier MUST
treat an object in which one is set as malformed.

> [!NOTE]
> Rejecting a set reserved bit is what lets a later version give it a
> meaning. A verifier that ignored the bit would accept an object whose
> meaning it had half understood.

---

# 7.16 Conformance

_Peios Specifications / PGSS / Signed Objects_

> The obligations of an authority, a store keeper, a verifier, and a consumer, gathered in one place, and what conformance leaves each free to do.

## 7.16.1 A conforming authority

- Encodes every object exactly as its layout gives, with reserved space
  zero (§7.4, §7.15).
- Signs with pure ML-DSA and an empty context, over every byte before
  the signature (§7.4).
- Issues a certificate only while holding `Delegate`, and gives no child
  a warrant it lacks or a value wider than its own (§7.5).
- Issues a leaf only under a name within its `Name` warrant, with the
  hash form the place calls for (§7.7, §7.9).
- Names a warrant of its own beneath a domain it controls (§7.5).
- Keeps a chain within 16 intermediaries and a bundle within 65,536
  bytes (§7.3, §7.8).

## 7.16.2 A conforming store keeper

- Enables a top-level only as §7.10 allows, and leaves a top-level that
  a package ships without a root's signature quarantined.
- Records an approval as a link, shows the certificate's name and
  warrants before the approval is given, and resolves links against the
  root it is reading (§7.10).
- Accepts a revocation only with the certificates that show it applies,
  and never removes one it has accepted (§7.12).
- Obtains approval before it removes a distrust entry (§7.13).

## 7.16.3 A conforming verifier

- Accepts roots only from its own build, and top-levels only from the
  trust store (§7.3, §7.10).
- Finds a bundle in the order of §7.9, and does not fall back to the
  extended attribute once an ELF section header is found.
- Takes the signature algorithm from the issuer's key type (§7.4).
- Narrows every warrant, recognized or not, and reports an unrecognized
  warrant with Must Understand set as invalid (§7.5).
- Finds a certificate that is not carried only as §7.11 gives, and
  checks its hash.
- Makes the checks of §7.14 in order, applies no clock, and reports one
  of the seven results or an error.
- Returns the leaf's name and warrants, the top-level's hash, and the
  root's key hash, with the results §7.14 lists.

## 7.16.4 A conforming consumer

- Requires Rooted for anything an administrator could not grant
  (§7.14).
- Accepts Consistent only against its own list of top-levels (§7.14).
- Decides on the leaf's name and warrants as returned, never on a
  certificate's name, and does not decode the bundle (§7.6, §7.14).

## 7.16.5 A conforming system

- Restricts writing beneath `/lcl/policy/pso/` to its store keeper
  (§7.10).
- Has every verifier on it return the same result for the same input
  (§7.1).

## 7.16.6 What conformance does not require

Conformance does not require a system to act on any result: what a
signed file is allowed to do is the consumer's. It does not require a
verifier to recognize any warrant but the three of §7.5, to remember
certificates between verifications, or to report why a chain is
invalid. It does not require an authority to use intermediaries, to
prepare revocations in advance, or to ship short bundles. It does not
say how a store keeper obtains approval, where it fetches revocations
from, or how a verifier is given the trust store.

---

# Appendix 7.A Limits

_Peios Specifications / PGSS / Signed Objects_

> Every size bound and count limit of PSO in one table, each with the article that defines it.

| Limit | Value | Defined in |
|---|---|---|
| Intermediaries between a leaf and its top-level | 16 | §7.3 |
| Recommended intermediaries | Fewer than 6 | §7.3 |
| Certificates in a bundle | 17 | §7.8 |
| Size of a bundle | 65,536 bytes | §7.8 |
| Size of a certificate found by hash | 65,535 bytes | §7.11 |
| Length of a certificate's or leaf's name | 1–255 bytes | §7.6, §7.7 |
| Length of a warrant's name | 1–255 bytes | §7.5 |
| Length of a warrant's value | 0–65,535 bytes | §7.5 |
| Warrants in one object | 255 | §7.6, §7.7 |
| Length of a hash | 64 bytes | §7.4 |
| Length of a hash as a file name | 128 characters | §7.4 |

---

# Appendix 7.B Enumerations

_Peios Specifications / PGSS / Signed Objects_

> Every enumerated value of PSO, covering object kinds, key types, certificate roles, warrant types, warrant flags, hash forms, target types, and results. Every enumeration is closed.

Every enumeration here is closed (§7.15).

## 7.B.1 Object kinds

The `kind` field of the header (§7.4).

| Value | Object | Defined in |
|---|---|---|
| `0x01` | Certificate | §7.6 |
| `0x02` | Leaf | §7.7 |
| `0x03` | Bundle | §7.8 |
| `0x04` | Revocation | §7.12 |
| `0x05` | Distrust | §7.13 |
| `0x06` | Store image | PSPK §6.3 |

## 7.B.2 Key types

The `key_type` field of a certificate, and the type of a root (§7.4).

| Value | Algorithm |
|---|---|
| `0x01` | ML-DSA-65 |
| `0x02` | ML-DSA-87 |

## 7.B.3 Certificate roles

The `role` field of a certificate (§7.6).

| Value | Role |
|---|---|
| `0x01` | Top-level |
| `0x02` | Intermediary |

## 7.B.4 Warrant types

Bits 6 through 4 of a warrant's `flags` (§7.5).

| Value | Type |
|---|---|
| `0` | Set |
| `1` | Namespace |
| `2` | Limit |

## 7.B.5 Hash forms

The `hash_form` field of a leaf (§7.9).

| Value | Form |
|---|---|
| `0x01` | Whole file |
| `0x02` | ELF, with signature sections zeroed |

## 7.B.6 Target types

The `target_type` field of a revocation and of a distrust entry (§7.12,
§7.13).

| Value | Target |
|---|---|
| `0x01` | Certificate |
| `0x02` | Leaf |

## 7.B.7 Results

The results a verifier reports are listed in §7.14 and are not repeated
here.

---

# Appendix 7.C Prior Art

_Peios Specifications / PGSS / Signed Objects_

> Where PSO sits against X.509 and Authenticode, authorization certificates, attenuating tokens, and OpenPGP revocation, and which resemblances are deliberate.

## 7.C.1 X.509 and code signing

The shape is the familiar one: a root, certificates that sign
certificates, and a signature on a file at the end. Three things differ
on purpose.

A leaf is a statement and not a certificate with a key, so a signing
key is never spread across every file it signs for.

Nothing expires. Code-signing systems built on X.509 need a trusted
timestamp so that a file signed while a certificate was valid stays
valid afterward, and a verifier that can trust a clock. PSO has neither
and withdraws trust by revocation alone.

What a certificate permits is written as warrants that every verifier
checks the same way, where X.509 spreads it across key usage, extended
key usage, name constraints, and policy extensions, each with rules of
its own.

## 7.C.2 Authorization certificates

SPKI (RFC 2693) certificates carry authorizations, and a delegated
authorization can be no wider than the one it came from. Warrants are
that idea with a fixed, small set of narrowing rules, chosen so that a
verifier can enforce them for a warrant it has never heard of.

## 7.C.3 Attenuating tokens

Macaroons and their successors let a holder narrow a credential and
pass it on, and never widen it. The narrowing rule of §7.5 has the same
direction. The difference is that a PSO chain is public and checked
against keys, and holds no shared secret.

## 7.C.4 OpenPGP

Preparing a revocation when a key is made, and keeping it apart from
the key, is long-standing practice with OpenPGP keys (RFC 9580 defines
the revocation signature). §7.12 recommends it for the same reason: the
moment a revocation is needed is the moment the key is least likely to
be at hand.

## 7.C.5 Design influences

**Reject, never trim.** A certificate that claims more than its issuer
is invalid. A reader of any valid certificate sees what it really
holds.

**The verifier knows no policy.** A verifier reports where a chain ends
and what its leaf holds. Which results and warrants matter is each
consumer's, so a new use of PSO needs a new warrant and no new verifier.

**Anchors are listed, never discovered.** A top-level is trusted
because the trust store holds it, and a certificate arriving with a
file can complete a chain but cannot anchor one.

**Taking away needs no permission.** A revocation and a distrust entry
can only refuse, so neither needs approval to add. Everything that
restores or grants trust does.

---

# 8.1 Scope and Roles

_Peios Specifications / PGSS / Indexing_

> What PGSS Indexing specifies, a per-item preference for how far search may index a file or directory, and the two roles that set and honour it.

This chapter specifies **PGSS Indexing**: how the owner of a file or
directory says how far a search index may record it, and how an indexer
honours what they said.

The chapter rests on one decision. The preference is a word on the item,
in an extended attribute, and a directory's word holds for everything
beneath it. One word on a folder keeps a whole tree out of search,
whatever program later creates files in it, without anyone marking each
file.

Two roles participate.

The **marker** says how an item may be indexed, by setting or removing
the attribute. A person running a command, a file manager with a
checkbox, and a file server translating a client's request are all
markers.

The **indexer** builds a record of files that people can search: their
names, their properties, their contents. A desktop search service and a
file server's search are indexers. Before it records anything of an item
it finds the item's preference by the rules of §8.3, and records no more
than the preference allows (§8.4).

Both roles are publicly implementable. A third party MAY ship a marker or
an indexer and interoperate with the rest unchanged.

This chapter covers:

- the attribute and the words it may hold (§8.2)
- how an indexer finds an item's preference from the item and the
  directories above it (§8.3)
- what each preference permits an indexer to record (§8.4)
- how a marker translates Windows' "not content indexed" attribute (§8.5)

This chapter does not cover:

- Who may search an index, or what a search returns to whom. An indexer
  answers searches under its own access control.
- Which locations an indexer covers at all. An indexer chooses where it
  looks; this chapter only narrows what it records where it does look.
- Thumbnails, previews and caches that are not a search index.
- Hiding a file from listings. A preference narrows search only; the
  item stays visible to anyone who can list its directory.

---

# 8.2 The Attribute

_Peios Specifications / PGSS / Indexing_

> The user.pgss.indexing extended attribute, the three words it may hold, and how a value that is not one of them is read.

A file or directory MAY carry the extended attribute
`user.pgss.indexing`, whose value is one of these words:

| Word | Meaning |
|---|---|
| `all` | Index normally: names, properties and contents. |
| `no-content` | Record the item's name and properties, not its contents. |
| `none` | Record nothing of the item. |

An item without the attribute has no preference of its own, and takes
its preference from the directories above it (§8.3).

A word is compared byte for byte. A marker MUST write one of the words
above, without a trailing NUL byte. An indexer MAY treat a value ending
in a NUL byte as though the NUL were absent.

## 8.2.1 A value that is not a word

An indexer MUST treat any other value, including an empty one, as
`no-content`. A value an indexer does not recognise is most likely a
word from a later version of this chapter or a mistake, and the person
who set it almost certainly wanted less indexing, not more. Reading it
as `no-content` keeps the item findable by name and keeps its contents
out of the index.

An indexer SHOULD make such values visible to whoever administers it, so
that a mistake can be found.

## 8.2.2 Where the attribute cannot be kept

Because the attribute is in the `user` namespace, whoever may write the
item's extended attributes can set it, and it can be set on regular files
and directories only. An item on a file system that cannot keep `user`
extended attributes has no preference of its own.

A marker acting on a person's direct request SHOULD tell them when it
could not keep the preference, rather than appear to succeed.

---

# 8.3 From an Item to Its Preference

_Peios Specifications / PGSS / Indexing_

> How an indexer finds an item's preference, the nearest word among the item and the directories above it, and how a directory loosens its parent's.

An item's preference is the word of the nearest of these that carries
`user.pgss.indexing`: the item itself, then its parent directory, then
each directory above that, up to the root of the namespace. If none
carries it, the preference is `all`.

A directory's word therefore holds for everything beneath it, files and
directories alike, until a nearer word says otherwise. `all` on a
subdirectory loosens a parent's `no-content` or `none` for the subtree
it heads.

```
Private/            user.pgss.indexing = none
  diary.txt         (none)           -> none: nothing recorded
  Shared/           user.pgss.indexing = all
    notes.txt       (none)           -> all: indexed normally
Projects/           user.pgss.indexing = no-content
  plan.odt          (none)           -> no-content: name only
```

An indexer MUST find the preference this way, and MUST NOT stop at the
item, or at the first directory it began indexing from.

## 8.3.1 Which path

An item may be reachable by more than one path: through hard links, bind
mounts, or symbolic links to a directory above it. An indexer applies
this section to the path by which it reached the item, and treats the
item as a separate entry under each path it records it by.

The walk crosses mount points: a mounted file system's root takes its
preference from the directory it is mounted on, as any other directory
does.

## 8.3.2 Change

A change to an item's attribute changes the preference of every item
beneath it that has no nearer word. An indexer SHOULD notice a change to
the attribute on a directory it indexes and apply it to the subtree. An
indexer that cannot notice changes MUST document how long it may go on
recording what a changed preference no longer allows, and MUST remove
what it recorded once it learns of the change.

---

# 8.4 What Each Preference Permits

_Peios Specifications / PGSS / Indexing_

> What an indexer may record of an item under each preference, and what it must remove when a preference narrows.

An item's **name and properties** are what the file system says about it
without its data being read: its name and path, its type as found from
its name, its size, its times and its owner. An item's **contents** are
its data, and everything an indexer would derive from reading it: words,
embedded properties such as a photograph's camera or a song's title,
extracted text, and anything computed from those.

| Preference | The indexer MAY record | The indexer MUST NOT |
|---|---|---|
| `all` | Name, properties and contents. | (no restriction from this chapter) |
| `no-content` | Name and properties. | Read the item's data for indexing, or record anything derived from it. |
| `none` | Nothing. | Record the item at all, or read its data for indexing. |

For a directory, `no-content` and `none` concern the directory itself;
what they mean for the items beneath it follows from §8.3, under which
those items share the directory's preference unless they carry their own.

An indexer MUST apply the preference before it reads an item's data. A
preference narrowed after an item was recorded MUST be applied to what
is already recorded: an indexer MUST remove what the new preference does
not allow, within the time §8.3 permits.

A preference narrows what an indexer records. It grants no access: an
indexer that may not read an item under its own access control does not
read it, whatever the preference says.

---

# 8.5 Windows

_Peios Specifications / PGSS / Indexing_

> How a marker translates Windows' FILE_ATTRIBUTE_NOT_CONTENT_INDEXED to and from user.pgss.indexing.

Windows marks a file or directory with `FILE_ATTRIBUTE_NOT_CONTENT_INDEXED`
(0x00002000) to say its contents are not to be indexed. A marker that
serves files to Windows clients, such as an SMB server, SHOULD translate
it as follows.

**Reporting.** The marker reports the attribute set on an item that itself
carries `no-content`, `none`, or a value §8.2 reads as `no-content`. It
reports it clear on an item that carries `all` or no value. It reports
only the item's own word, not one it would take from a directory above.

**Setting.** When a client sets the attribute on an item whose own
preference is `all` or absent, the marker writes `no-content`. When the
item already carries `no-content` or `none`, the marker leaves the word
as it is.

**Clearing.** When a client clears the attribute, the marker removes the
item's attribute, so that the item takes its preference from above. It
does not write `all`.

**Not kept.** On a file system that cannot keep the attribute, the marker
MAY accept the client's request and keep nothing, as Windows programs set
attribute bits in passing and failing the request would fail a copy.

A marker that translates the attribute MUST NOT also offer
`user.pgss.indexing` to the client as a Windows extended attribute,
since the client would then see one preference twice.

---

# 8.6 Extension

_Peios Specifications / PGSS / Indexing_

> What may be added to this chapter without breaking a conforming marker or indexer, and what may not.

## 8.6.1 Additive changes

- A new word in §8.2. An indexer built to this version reads it as
  `no-content`. For a word that permits no more than `no-content`, that
  is what it allows at most; for one that permits more, an older indexer
  records less than the word allows, which errs the safe way.
- A new source of preference consulted after the walk of §8.3 finds no
  word, such as a system-wide setting. An indexer built to this version
  indexes such items normally.

## 8.6.2 Changes requiring a new version

- A change to what an existing word permits.
- A change to the walk of §8.3, such as stopping at a mount point.

## 8.6.3 Reserved

The `pgss.indexing` name in the `user` extended-attribute namespace is
this chapter's.

---

# 8.7 Conformance

_Peios Specifications / PGSS / Indexing_

> The obligations of each role, gathered in one place.

## 8.7.1 A conforming indexer

- Finds each item's preference by the nearest `user.pgss.indexing` among
  the item and the directories above it, up to the root, and takes `all`
  where there is none (§8.3).
- Reads a value that is not one of the words as `no-content` (§8.2).
- Applies the preference before reading an item's data, and records no
  more than it permits (§8.4).
- Removes what a narrowed preference no longer permits, and notices
  changes or documents how long it may lag (§8.3, §8.4).

## 8.7.2 A conforming marker

- Writes only `all`, `no-content` or `none`, without a trailing NUL
  (§8.2).
- Acting on a person's direct request, tells them when the preference
  could not be kept (§8.2).
- Translating Windows' attribute, follows §8.5.

## 8.7.3 What conformance does not require

Conformance does not require a system to run an indexer, an indexer to
cover any particular location, or a marker to offer every word.

---

# Appendix 8.A Prior Art

_Peios Specifications / PGSS / Indexing_

> Where this chapter sits against Windows' not-content-indexed attribute, macOS's Spotlight exclusions, and the per-directory marker files of Linux tools.

## 8.A.1 Windows

Windows keeps one bit per item, `FILE_ATTRIBUTE_NOT_CONTENT_INDEXED`. A
folder's bit is copied onto items created in it, and changing a folder
asks whether to change what it already holds. This chapter keeps the
meaning of the bit as `no-content`, and adds `none` for keeping an item
out of search entirely, which Windows does only by excluding a location
from the indexer's own configuration.

The chapter does not copy a folder's word onto new items. Linux has no
way to give a new file an extended attribute from its directory, so a
copied word would hold only for files made by programs that know to copy
it. A word that holds for everything beneath a directory needs no
copying and covers every program.

## 8.A.2 macOS

Spotlight skips a directory whose name ends in `.noindex`, or which holds
a file named `.metadata_never_index`, and keeps a list of excluded
locations in its own settings. The marker-file form is the same idea as
§8.3: a directory says something about everything beneath it. An
extended attribute serves better than a marker file, because it does not
appear in listings and goes with the directory when it is moved.

## 8.A.3 Marker files on Linux

`.nomedia` (Android media scanners), `CACHEDIR.TAG` (backup tools) and
`.gitignore` all let a directory speak for its subtree. This chapter
takes their nearest-word rule, and lets a nearer word loosen a farther
one as a `.gitignore` negation does.

## 8.A.4 Design influences

**Less when unsure.** A value an indexer does not recognise narrows what
it records, because the cost of a wrong guess is uneven: an item missing
from search is found another way, and contents recorded against their
owner's wish cannot be unrecorded from whoever saw them.

**The owner's word, not the indexer's.** The preference is on the item,
so it travels with the item and binds every indexer, rather than being
one indexer's setting that another ignores.

---

# 1.1 Scope

_Peios Specifications / PSPK / Introduction_

> What PSPK is — the protocols spoken across the kernel boundary between a kernel subsystem and the userspace process serving it — and how trust runs across that line.

This document defines the **Peios System Protocols Kernel (PSPK)**: the
protocols spoken across the kernel boundary, between a kernel subsystem
and a userspace process that serves it.

A contract belongs in this document when both of these hold:

- one party is a kernel subsystem and the other is a userspace process;
  and
- the userspace side is a public, implementable role — a third party can
  write a program that fills it.

The two parties need not be in conversation. A live protocol has a
kernel subsystem and a process exchanging messages; a **format** has one
side producing an artifact that the other consumes, perhaps long
afterwards and on a different machine. Both are specified here, because
both are contracts a third party has to satisfy exactly.

The second condition is what separates a PSPK protocol from a system-call
surface. A system call is an interface the kernel offers to any program
that asks. A PSPK protocol is a contract the kernel depends on some
program to fulfil: the kernel is the party asking, and the userspace
process is authoritative for the answer.

For each protocol, this document covers:

- the channel, and how a userspace party attaches to it and is
  recognized
- message or artifact framing, encoding, and the rules under which the
  format may be extended
- the requests the kernel issues, the responses it expects, and their
  ordering
- what the kernel-side party validates for itself rather than believing
  from a response
- behavior on failure, refusal, and disconnection
- the conformance requirements for the userspace role

This document does not cover:

- The behavior and data model of the kernel subsystem itself — defined
  in that subsystem's specification
- System-call and ioctl surfaces — defined in that subsystem's
  specification
- The binary structures these protocols carry — defined in PCDS
- Standards another system could adopt — defined in PGSS
- Protocols between userspace components — defined in PSPU
- How a userspace implementation stores its data or computes its
  answers — its own design

## 1.1.1 Trust across the boundary

A PSPK protocol crosses a trust boundary in the direction that matters
most: a kernel subsystem is asking a lower-privileged process for
something it will then act on. Every specification in this document
therefore states explicitly which parts of a response the kernel
establishes for itself and which it takes on the userspace party's word.

## 1.1.2 Relationship to PGSS

A protocol in this document is specific to Peios. It is the interface a
particular Peios kernel subsystem uses to reach the processes that serve
it, and it has little use on a system built from different kernel
subsystems. That is what separates it from a PGSS standard, which
another system could adopt as it stands.

These protocols are specified because they are public even so: a third
party writing an implementation of the userspace role needs the
contract written down.

---

# 1.2 Conventions

_Peios Specifications / PSPK / Introduction_

> The normative keywords PSPK uses, and the shared conventions it inherits from the PCSA conventions book.

The key words MUST, MUST NOT, SHOULD, SHOULD NOT, and MAY in this
document are to be interpreted as described in RFC 2119. Text set off as
a note is informative, not normative.

Everything else — roles, byte order, sizes, layout tables, notation,
strings, timestamps, citation, and the external standards this anthology
depends on — is defined in the Conventions book and is not restated
here. PSPK departs from none of it.

Where a chapter needs a convention of its own, that chapter states it.

---

# 2.1 Scope and Roles

_Peios Specifications / PSPK / KMES Event Stream_

> The KMES contract and its two roles — the kernel as sole producer, userspace as consumer — and the privilege that gates attachment.

This chapter specifies the contract between the Kernel Mediated Event
Subsystem and the userspace processes that consume the events it
produces.

Two roles participate.

The **producer** is KMES, a subsystem of the Peios kernel. It
constructs events, stamps them with metadata that a consumer cannot
forge, places them in per-CPU shared memory ring buffers, and notifies
sleeping consumers. There is one producer.

The **consumer** is a userspace process that maps one or more ring
buffers and reads events from them. The consumer role is publicly
implementable: any process holding the required privilege MAY attach,
and more than one consumer MAY attach to the same buffer at the same
time. A conforming consumer is the subject of the requirements in this
chapter.

This chapter covers:

- the binary layout of an event, which a consumer MUST parse
- the layout of a mapped ring buffer and the meaning of each metadata
  field
- how a consumer attaches, maps, and discovers the buffer set
- the protocol a consumer follows to drain events, to detect and
  account for loss, and to sleep and be woken
- the protocol a consumer follows when the producer replaces a buffer
- the memory ordering both roles rely on

This chapter does not cover:

- how KMES constructs, stamps, buffers, or overwrites events — the
  producer's internals are described in the Peios Kernel TRM
- the emission interfaces, by which a process or kernel subsystem
  produces an event rather than consuming one
- event type vocabulary, payload schemas and the encoding of payload
  values — these are PGSS §6
- persistence, indexing and querying — the query language is PSPU §3,
  and storage is the concern of the event storage service

## 2.1.1 Producing versus consuming

Emission is not part of this contract. A process emits events by
calling the KMES emission system calls, which are an ordinary kernel
interface offered to any caller that holds the privilege — the kernel
computes the result and the caller reads it. Consumption is different:
the kernel deposits bytes in shared memory and depends on an
independently written program to interpret them correctly, to
sequence its reads against concurrent writes, and to notice when it
has fallen behind. That program's obligations have to be written down,
which is why they are here.

## 2.1.2 What the kernel establishes for itself

A consumer maps one page that it can write: the consumer metadata
page. Everything the kernel reads from that page is advisory.

KMES reads exactly one field from consumer-writable memory, the
`need_wake` flag, and treats any nonzero value as set. The flag can
only cause KMES to perform a wake that was not needed or to skip one
that was; it cannot affect the contents of the data region, the
producer metadata, the sequence numbering, or another consumer's view
of any of these. A consumer that corrupts the page — deliberately or
otherwise — degrades notification for consumers sharing that buffer
and nothing else.

Consumers MUST NOT rely on KMES validating anything else they write,
because KMES reads nothing else.

The reverse direction is stronger. The producer metadata page and the
data region are mapped read-only, and no privilege, capability, or
token grants a consumer write access to them. Every identity stamp in
an event header is captured by the kernel from kernel state at the
moment of the write; an emitting process cannot set, influence, or
suppress it. A consumer MAY therefore treat the identity fields of a
delivered event as authoritative.

## 2.1.3 Privilege and the trust model

Attaching requires SeSecurityPrivilege, which is a very high-trust
privilege. Direct ring buffer access is not the ordinary way to
consume events: it grants an unfiltered view of every event on the
system, with no per-event access control. Ordinary consumers obtain
events from the event storage service, which enforces per-event
access control on top of this interface.

Because the consumer metadata page is shared by every consumer
attached to a buffer, a consumer holding SeSecurityPrivilege can
suppress notification for the others attached to that buffer. This is
accepted rather than defended against: the privilege required to
attach at all is higher than the privilege this would subvert.

---

# 2.2 Event Format

_Peios Specifications / PSPK / KMES Event Stream_

> An event is one contiguous record — the packed header layout, the payload, event types, origin class, identity fields and ordering.

An event is an indivisible record: a packed binary header followed
immediately by a payload. Header and payload are always stored,
delivered, and consumed as one contiguous byte sequence, and neither
is meaningful alone.

## 2.2.1 Header layout

The header fields are laid out sequentially with no padding and no
alignment gaps. All multi-byte integers are little-endian.

| Offset | Size | Type | Field | Description |
|---|---|---|---|---|
| 0 | 4 | `u32` | `event_size` | Total size of the event, header plus payload, in bytes. |
| 4 | 4 | `u32` | `header_size` | Size of the header in bytes. |
| 8 | 8 | `u64` | `timestamp` | Wall clock time at emission, in nanoseconds since the Unix epoch. |
| 16 | 8 | `u64` | `sequence` | Per-CPU, per-boot monotonic sequence number. |
| 24 | 2 | `u16` | `cpu_id` | The CPU on which the event was emitted, identifying the ring buffer that carries it. |
| 26 | 1 | `u8` | `origin_class` | The emission path that produced the event. |
| 27 | 16 | `GUID` | `effective_token_guid` | GUID of the effective token of the emitting thread. Null GUID if unavailable. |
| 43 | 16 | `GUID` | `true_token_guid` | GUID of the emitting process's primary token. Null GUID if unavailable. |
| 59 | 16 | `GUID` | `process_guid` | GUID of the emitting process. Null GUID if unavailable. |
| 75 | 2 | `u16` | `type_len` | Length of the event type string in bytes. |
| 77 | `type_len` | `[u8]` | `type` | Event type string, UTF-8, not null-terminated. |

GUIDs use the binary format defined in PCDS and are opaque 16 bytes to
this contract. The **null GUID** is sixteen zero bytes and means the
field is not applicable or was not available.

`header_size` is `77 + type_len` in this version of the format. A
consumer MUST use `header_size` to locate the payload and MUST NOT
compute the payload offset from `77 + type_len` or from any other
constant, so that a future header extension does not break it. All
fields before `type` are at fixed offsets and will remain so.

The payload occupies the bytes from `header_size` to `event_size`. The
next event in a ring buffer begins `event_size` bytes after the start
of the current one, with no alignment padding between events.

## 2.2.2 Payload

The payload is exactly one MessagePack value, and its structure is
defined by the emitter. KMES does not interpret it.

A consumer MUST NOT assume a payload is present: an event emitted by a
kernel subsystem MAY have `event_size == header_size`, meaning a
header and no payload at all. Events emitted through the system calls
always carry a payload, because an empty byte sequence is not a valid
MessagePack value and is rejected at the syscall boundary.

Note that MessagePack encodes its own length prefixes big-endian,
whereas every integer in the event header is little-endian. Both
appear in one event.

## 2.2.3 Event types

The event type is an arbitrary UTF-8 string. KMES imposes no
structure, namespace, or naming convention on it, and applies no case
folding or normalization. Consumers MUST compare event types as raw
byte sequences.

## 2.2.4 Origin class

| Value | Origin |
|---|---|
| 0 | Userspace, via system call |
| 1 | KMES |
| 2 | KACS |
| 3 | LCS |
| 4 | NTFE |

Values 5–255 are unassigned. A consumer MUST tolerate an unrecognized
origin class rather than rejecting the event, so that a kernel
subsystem added later does not break it.

Events with origin class 0 were emitted through the system call
interface, and their origin class is set by the kernel, not by the
caller. A userspace emitter cannot claim to be a kernel subsystem.

## 2.2.5 Identity fields

The three identity GUIDs are captured by the kernel at the moment the
event is written to the ring buffer, not when the emitting call began.

- `effective_token_guid` is the token governing the emitting thread's
  access rights. If the thread was impersonating, this is the
  impersonation token; otherwise it equals `true_token_guid`.
- `true_token_guid` is the emitting process's primary token,
  regardless of impersonation.
- `process_guid` identifies the emitting process. It is assigned when
  the process is created and does not change across `exec`.

Any of the three MAY be the null GUID, meaning the kernel had no
identity to record — emission before the access control subsystem
initialized, or from a context with no associated process such as a
kernel worker thread. A consumer MUST treat a null identity as
"unattributed" and MUST NOT treat it as a valid GUID value that could
match a real token or process.

## 2.2.6 Ordering

Events from different CPUs are ordered by `timestamp`. Events with
identical timestamps from different CPUs were genuinely concurrent and
have no defined relative order.

Within a single CPU, `sequence` is the ordering primitive. It is
monotonic across wall clock discontinuities, which `timestamp` is not:
a clock adjustment can move timestamps backwards, and a consumer that
requires monotonic ordering within a CPU MUST use `sequence`. Events
with identical timestamps on the same CPU are ordered by `sequence`.

Each CPU numbers independently and there is no global sequence. The
counter starts at zero when the kernel module loads and is incremented
before a value is taken, so the first event on a CPU carries sequence
number 1 and **sequence 0 is never assigned**. The pair
(`cpu_id`, `sequence`) uniquely identifies an event within one boot.

A gap in the sequence for a given CPU means events were lost — either
overwritten before the consumer read them, or dropped by the kernel
before they reached the buffer. Sequence numbers are continuous across
a buffer replacement, so a generation change does not itself produce a
gap.

---

# 2.3 Attaching and Mapping

_Peios Specifications / PSPK / KMES Event Stream_

> How a consumer attaches to a per-CPU ring, the double mapping that makes wrapping invisible, and the producer metadata page.

## 2.3.1 Attaching

A consumer attaches to one per-CPU ring buffer at a time by calling
`kmes_attach` with a logical CPU index and a pointer to a `u64` that
receives the buffer's capacity. The call returns a file descriptor.

The caller MUST hold SeSecurityPrivilege, enabled; the call fails with
`EPERM` otherwise.

The CPU index uses the same numbering as the `cpu_id` field in the
ring buffer metadata and in event headers. Indexes run from 0 to one
below the *slot count*, and the set of buffers is fixed when KMES
initializes and does not change while the system runs.

The slot count is not the number of buffers. Slots are indexed by
logical CPU id, so a slot within the range holds no buffer when that
CPU is not possible, and the two quantities differ on any system whose
possible-CPU mask is sparse. An index at or beyond the slot count fails
with `EINVAL`, and so does an index inside it whose slot holds no
buffer; the two are not distinguishable from the return value.

A consumer discovers the slot count by calling `kmes_attach` with the
CPU index `KMES_ATTACH_QUERY_SLOTS`. The call writes the slot count
through the capacity pointer, returns 0, and opens no descriptor. It is
gated on SeSecurityPrivilege exactly as an attach is.

A consumer MUST enumerate by walking every index from 0 to one below
the slot count, and MUST treat `EINVAL` as "this slot holds no buffer"
and continue. A consumer MUST NOT treat the first `EINVAL` as the end
of the set: doing so silently abandons every buffer above the first
hole, whose events then accumulate and are overwritten with no consumer
able to reach them.

A consumer SHOULD attach to every buffer in the set: a buffer with no
consumer still receives events, and those events are lost when it
wraps.

A consumer MAY call `kmes_attach` more than once for the same CPU and
receives a distinct file descriptor each time. All descriptors for one
CPU refer to the same buffer, and therefore to the same producer
metadata, consumer metadata, and data region. Multiple consumers MAY
attach to one buffer concurrently. Each maintains its own read
position, in its own memory; the kernel does not track consumer read
positions, does not know how many consumers exist, and does not know
how far behind any of them is. The consumer metadata page is shared
per buffer and is not a per-consumer read-position store.

The descriptor supports exactly two operations: `mmap()` and
`close()`. Closing it invalidates the mapping.

## 2.3.2 Mapping

The consumer maps the whole region in a single call:

```
mmap(NULL, 8192 + 2 * capacity, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)
```

The mapping request MUST use `MAP_SHARED`, MUST pass an offset of
zero, and MUST pass a length of exactly `8192 + 2 * capacity`, where
`capacity` is the value `kmes_attach` returned. Any other combination
fails with `EINVAL`. The consumer does not map the regions separately.

The mapped region has three parts:

| Offset | Size | Region | Consumer access |
|---|---|---|---|
| 0 | 4096 | Producer metadata page | Read-only |
| 4096 | 4096 | Consumer metadata page | Read-write |
| 8192 | 2 × capacity | Data region | Read-only |

Per-page permissions are enforced by the kernel regardless of the
`PROT` flags requested: the producer metadata page and the data region
are mapped read-only whatever the consumer asks for, and no privilege
raises that. The consumer metadata page is writable by ordinary
stores.

`capacity` is always a power of two, so a position's offset within the
data region is `position & (capacity - 1)`.

## 2.3.3 The double mapping

The data region occupies `2 × capacity` bytes of address space backed
by `capacity` bytes of memory: the same pages appear twice,
consecutively. An event that crosses the end of the buffer is
therefore readable as one contiguous byte sequence starting at its
wrapped offset, and a consumer MUST NOT implement wrap handling of its
own. Reading an event at offset `position & (capacity - 1)` is always
correct, even when the event extends past `capacity`.

A consumer MUST NOT read past `event_size` bytes from the start of an
event. The data region is not scrubbed when events are overwritten, so
the bytes beyond an event are unrelated remnants of older events.

## 2.3.4 Producer metadata page

The producer metadata page is written by KMES and read by consumers.
Fields are separated onto 64-byte cache lines by update frequency, so
that the position fields KMES writes on every event do not invalidate
the line holding the fields it never writes.

### 2.3.4.1 Bytes 0–63: identification

| Offset | Size | Type | Field | Description |
|---|---|---|---|---|
| 0 | 8 | `[u8; 8]` | `magic` | `4B 4D 45 53 52 49 4E 47`, `KMESRING` in ASCII. Compared byte by byte, not as an integer. |
| 8 | 4 | `u32` | `version` | Ring buffer format version. This version is 1. |
| 12 | 2 | `u16` | `cpu_id` | The CPU this buffer belongs to. |
| 14 | 2 | `u16` | `reserved0` | Reserved, zero. |
| 16 | 8 | `u64` | `capacity` | Data region capacity in bytes. A power of two. |
| 24 | 8 | `u64` | `data_offset` | Offset from the start of the mapping to the data region. 8192. |
| 32 | 8 | `u64` | `generation` | Buffer generation. Starts at 1 for the first buffer on each CPU and increases by one each time the buffer is replaced. |
| 40 | 24 | -- | `reserved1` | Reserved, zero. |

A consumer MUST verify `magic` and `version` before trusting any other
field in the mapping.

A consumer MAY cache `magic`, `version`, `cpu_id`, `capacity`, and
`data_offset` for the lifetime of the mapping; these do not change
once the buffer exists. A consumer MUST NOT cache `generation`: it
shares this cache line but is written when the buffer is superseded,
and re-reading it is how a consumer learns that it must re-attach.

### 2.3.4.2 Bytes 64–127: positions

| Offset | Size | Type | Field | Description |
|---|---|---|---|---|
| 64 | 8 | `u64` | `write_pos` | Monotonically increasing byte offset at which the next event will be written. Never wraps. |
| 72 | 8 | `u64` | `tail_pos` | Byte offset of the oldest surviving event. Advanced by KMES as events are overwritten. |
| 80 | 48 | -- | `reserved2` | Reserved, zero. |

Both are absolute byte offsets that increase without bound; the
corresponding data region offset is the value masked with
`capacity - 1`. A `u64` byte offset does not overflow in any practical
deployment — at a sustained gigabyte per second it would take over
five hundred years — and consumers MUST NOT implement wrap handling
for these counters.

### 2.3.4.3 Bytes 128–191: notification

| Offset | Size | Type | Field | Description |
|---|---|---|---|---|
| 128 | 4 | `u32` | `futex_counter` | Incremented by KMES when it wakes sleeping consumers. |
| 132 | 60 | -- | `reserved3` | Reserved, zero. |

The counter is 32-bit because the Linux futex operates on 32-bit
integers, and it is incremented only when `need_wake` is set.

## 2.3.5 Consumer metadata page

| Offset | Size | Type | Field | Description |
|---|---|---|---|---|
| 4096 | 1 | `u8` | `need_wake` | Set by a consumer that is about to sleep. Read by KMES after writing an event; any nonzero value counts as set. |
| 4097 | 4095 | -- | `reserved4` | Reserved. |

This page is shared by every consumer attached to the buffer. A
consumer MUST NOT store per-consumer state on it, and in particular
MUST NOT store its read position there.

Consumers MUST NOT write to any offset in this page other than
`need_wake`. Reserved bytes are reserved for future extension of this
contract.

---

# 2.4 Consumer Protocol

_Peios Specifications / PSPK / KMES Event Stream_

> The consumer protocol — draining a ring, detecting loss, waiting for notification, handling buffer replacement, and the memory ordering it all rests on.

A consumer typically dedicates one thread to each buffer. Each thread
independently drains its buffer, sleeps when the buffer is empty, and
re-attaches when the buffer is replaced. The protocol uses no locks
and, while events are available, no system calls.

Each consumer keeps its own `read_pos` in its own memory. On first
attaching to a buffer, a consumer SHOULD set `read_pos` to the
buffer's current `tail_pos`, which starts it at the oldest surviving
event.

## 2.4.1 Draining

1. Load `write_pos` with acquire ordering. If `write_pos == read_pos`,
   no events are available: go to the notification wait.
2. Load `tail_pos` with acquire ordering. If `read_pos < tail_pos`,
   the events at the read position have been overwritten and the
   consumer has been lapped: set `read_pos = tail_pos`. The skipped
   span is lost, and will show up as a sequence gap.
3. Save the current `tail_pos` as `saved_tail`.
4. Read the event at data region offset `read_pos & (capacity - 1)`.
5. Re-read `tail_pos`. If it has advanced past `saved_tail` and
   `read_pos < tail_pos`, the event was overwritten while it was being
   read. The bytes just read MUST be discarded: go to step 2.
6. Check that `event_size > 0` and `event_size >= header_size`. If
   either fails, the bytes are not a valid event; the consumer SHOULD
   set `read_pos = tail_pos` and go to step 2. A consumer MUST perform
   this check: an `event_size` of zero would otherwise make the drain
   loop spin forever.
7. Process the event. Advance `read_pos` by the event's `event_size`.
   Go to step 1.

A consumer MUST NOT read beyond an event's `event_size` boundary.

Steps 3 and 5 are what make a lock-free read safe against a producer
that is overwriting the region being read. A consumer that omits the
re-read can process a torn event assembled from two different events'
bytes.

## 2.4.2 Detecting loss

A consumer SHOULD track the last sequence number it processed for each
CPU. A gap means events were lost, whether because they were
overwritten before being read or because the kernel dropped them
before they reached the buffer. The size of the gap is the number of
events lost.

Loss is a normal condition under load, not an error: the buffer
preserves recent events at the cost of old ones. A consumer SHOULD
report loss rather than treating it as fatal.

## 2.4.3 Notification wait

When a buffer is empty:

1. Store 1 to `need_wake` with release ordering.
2. Re-load `write_pos` with acquire ordering. If events arrived
   between the drain loop finding the buffer empty and this store,
   clear `need_wake` to 0 and return to the drain loop. This re-check
   is REQUIRED: without it, an event written in that window would find
   `need_wake` still clear, and the consumer would sleep with events
   waiting.
3. Read `futex_counter`.
4. Optionally spin, re-checking `write_pos`. If events arrive during
   the spin, clear `need_wake` to 0 and return to the drain loop. The
   spin duration is the consumer's choice, and a consumer MAY omit
   this step entirely.
5. Call `futex_wait(&futex_counter, last_seen_value)`, where
   `last_seen_value` is the value read in step 3. The kernel puts the
   thread to sleep only if `futex_counter` still holds that value, so
   a wake that arrived in the meantime is not missed.
6. On waking, clear `need_wake` to 0 and return to the drain loop.

The futex address is the `futex_counter` field in the mapped producer
metadata page. This is a **shared** futex, keyed by the page's backing
inode, and a consumer MUST wait on it as such: a wait issued with
`FUTEX_PRIVATE_FLAG` will never be woken.

Clearing `need_wake` to 0 in steps 2, 4, and 6 MAY be a relaxed store.
If KMES reads a stale set value after the consumer has cleared it, it
performs a wake on a thread that is already awake, which is harmless.

Under sustained load a consumer never reaches the notification wait:
it stays in the drain loop, `need_wake` stays 0, and the producer's
notification cost is a single byte read per event.

## 2.4.4 Buffer replacement

KMES replaces every buffer when its configured capacity changes.
Replacement preserves as many surviving events as the new capacity
allows and keeps sequence numbering continuous, but it invalidates
positions: the events are re-compacted from position 0 in the new
buffer, so the consumer's `read_pos` means nothing there.

After each drain cycle — the buffer emptied, or a batch limit reached
— a consumer SHOULD read `generation`. If it differs from the value
last seen:

1. Record the sequence number of the last event successfully processed
   from this buffer.
2. Finish draining the old buffer up to its `write_pos`, which is now
   frozen: KMES has stopped writing to it. A consumer MUST complete
   this drain before switching, or it loses every event written
   between its read position and the switchover.
3. Call `kmes_attach` for the same CPU to obtain a descriptor for the
   replacement buffer, and map it.
4. Read the new buffer's `capacity`, `write_pos`, and `tail_pos`.
5. Scan the new buffer for the first event whose sequence number is
   greater than the recorded one, and set `read_pos` to that event's
   position. A consumer MUST locate its position by sequence number
   and MUST NOT carry `read_pos` across.
6. Close the old descriptor and unmap the old buffer.
7. Resume draining from the new buffer.

The old buffer's pages remain valid for as long as any consumer keeps
them mapped, so a consumer is never racing to finish before the memory
disappears.

If the new capacity is large enough to hold everything that survived
in the old buffer, no events are lost across the replacement. If it is
smaller, the oldest surviving events are discarded until the remainder
fits — the same overwrite semantics applied against the smaller
capacity — so loss is bounded to the oldest part of the buffer and
appears as a sequence gap.

A consumer sleeping on the old buffer is woken when the replacement
happens, provided its `need_wake` was set, so it observes the
generation change rather than sleeping indefinitely on a buffer that
will never receive another event.

## 2.4.5 Memory ordering

| Operation | Ordering | Purpose |
|---|---|---|
| Producer stores `tail_pos` | release | The advanced tail is visible before the data that replaces the events it skipped past. |
| Producer stores `write_pos` | release | Complete event data is visible before the position that makes it reachable. |
| Producer stores `futex_counter` | release | A consumer waking from the futex observes all prior writes. |
| Consumer stores `need_wake = 1` | release | The producer observes the flag before the consumer waits. |
| Consumer stores `need_wake = 0` | relaxed | A stale read causes only a spurious wake. |
| Consumer loads `write_pos` in the drain loop | acquire | Pairs with the producer's release. |
| Consumer loads `write_pos` after setting `need_wake` | acquire | Closes the window between finding the buffer empty and announcing the sleep. |
| Consumer loads `tail_pos` | acquire | Pairs with the producer's release. |

For a given buffer there are exactly two kinds of party: one producer,
which is the kernel on the owning CPU, and any number of consumers.
There is no multi-producer contention to account for.

On x86-64 the producer's release stores compile to plain stores,
because the architecture does not reorder stores with other stores.
Consumers MUST NOT rely on that: the ordering above is required for
correctness on weaker architectures, and a consumer written without it
is incorrect on those machines whether or not it is observed to fail
on x86-64.

---

# 3.1 Scope and Roles

_Peios Specifications / PSPK / Binary Signing and PIP_

> How a binary is signed so the Peios kernel will accept it, who the signer and verifier are, and why signing is a contract rather than an implementation detail.

This chapter specifies how a binary is signed so that the Peios kernel
will accept it, and what the trust level a signature confers means.

Two roles participate.

The **signer** is a userspace program holding a private key. It
computes a content hash over a file, signs it, and attaches the
signature to that file. The signer role is publicly implementable: a
third party building software for Peios, or an organization operating
its own trust tier, MUST be able to produce an acceptable signature
from this chapter alone.

The **verifier** is the Peios kernel. It carries public keys, checks
signatures at execution, at library load and when it reads a file for
its own use (device firmware; §3.4), and derives a process's Process
Integrity Protection identity from whichever key verified. The
verifier role is not publicly implementable and is not specified here;
this chapter constrains it only where the signer needs guarantees
about what it will do.

This chapter covers:

- the signature blob's encoding
- where a signature is stored, and the order in which storage
  locations are consulted
- exactly which bytes are covered by the signature
- the signature algorithm, its parameters, and the absence of domain
  separation
- how a key is selected during verification, and how a trust tier
  follows from it
- the meaning of a PIP identity, and what a signer is asserting by
  requesting one
- the guarantees a signer may rely on, and the ones it may not

This chapter does not cover:

- how the kernel parses, hashes, or verifies — described in the Peios
  Kernel TRM
- how PIP is enforced between processes or against objects — likewise
  the TRM's concern
- key generation, custody, rotation, or distribution policy
- the process mitigations that compose with PIP, which are set by a
  process launcher and are unrelated to signing

## 3.1.1 Why signing is a contract and not an implementation detail

A binary's trust level is not something a process can request. There is
no runtime interface that confers PIP, no inherited grant from a
parent, and no flag at process creation. The **only** input is the
signature on the file being executed, and the only authority is the
key that verifies it.

That makes the signature the entire boundary. A signer that produces
a byte-for-byte correct blob over the correct bytes obtains a trust
tier; one that gets any of it wrong obtains none, silently, because an
unverifiable binary executes with no protection rather than failing to
execute. There is no error to observe and no diagnostic to read.

A specification is therefore the only thing standing between a signer
and a silent, total loss of the property it was trying to obtain.

## 3.1.2 What the kernel establishes for itself

The verifier trusts nothing in the artifact except the signature's
arithmetic.

The trust tier is **not** carried in the signature, the file, or any
metadata a signer controls. It is a property of the key that verified,
looked up in a table compiled into the kernel image. A signer cannot
encode, request, or influence the tier it receives; presenting a
signature made with a key the kernel does not carry is
indistinguishable from presenting no signature at all.

The signature covers the file's content, and the verifier re-derives
the content hash itself over a stable size snapshot rather than
trusting any length or digest recorded in the artifact.

A verified file is pinned against in-place modification for as long as
its inode lives, so a signer MUST NOT assume it can update signed
content in place. Replacement by a new inode is the only supported
update path.

## 3.1.3 Relationship to PGSS

Binary signing as this chapter specifies it is specific to the Peios
kernel, and is not a PGSS standard. A system that verifies no
signatures, or verifies them against different keys, loses the
protection and nothing else: PIP is additive protection rather than a
property every Peios system exhibits.

It is specified here because the contract is public even so. A third
party that wants its software to run at a trust tier — or that wants
to operate a tier of its own — needs the format written down exactly,
and needs to know which of the verifier's behaviors it may depend on.

---

# 3.2 Signature Format

_Peios Specifications / PSPK / Binary Signing and PIP_

> The fixed 3310-byte signature blob — where it is stored, the lookup order, what is covered, and how a key is selected and trusted.

## 3.2.1 The blob

A signature is a fixed 3310-byte blob, identical wherever it is
stored:

| Offset | Size | Field |
|---:|---:|---|
| 0 | 1 | Version. MUST be `0x01`. |
| 1 | 3309 | Raw ML-DSA-65 signature. |

Total 3310 bytes exactly. There is no length field, no algorithm
identifier, no key identifier, no timestamp and no padding. A blob of
any other length MUST be rejected, and so MUST a version byte other
than `0x01`.

Signers MUST NOT emit any other version. A verifier encountering one
MUST treat the file as unsigned rather than attempting a fallback
interpretation.

## 3.2.2 Storage

Two locations are defined. A verifier MUST consult them in this order.

### 3.2.2.1 ELF section

An ELF binary SHOULD carry its signature in a section named exactly
`.peios.sig`. The name comparison covers all eleven bytes including
the terminating NUL, so a longer name having `.peios.sig` as a prefix
MUST NOT match.

The section's type MUST be `SHT_PROGBITS` and its size MUST be exactly
3310. The range `[sh_offset, sh_offset + sh_size)` MUST lie entirely
within the file.

The containing file MUST be `ELFCLASS64`, MUST be `ELFDATA2LSB`, and
MUST carry `EV_CURRENT` in `e_ident[EI_VERSION]`. `e_shentsize` MUST
equal 64. `e_shstrndx` MUST NOT be `SHN_UNDEF` and MUST be less than
`e_shnum`. The section header table and the section-name string table
MUST both lie entirely within the file.

No alignment or flag requirement applies. `sh_addralign`, `sh_flags`,
`sh_addr`, `sh_link` and `sh_info` are not inspected, and the
section's index and position are unconstrained. Where several sections
share the name, the one at the lowest index is used.

A 32-bit or big-endian ELF cannot carry a signature at all: it fails
the structural requirements above, and a verifier MUST NOT fall back
to the extended attribute for it.

### 3.2.2.2 Extended attribute

Any file MAY carry its signature in the extended attribute
`security.peios.sig`. The value MUST be exactly 3310 bytes; any other
size MUST be treated as unsigned.

This is the only location available to non-ELF files, and it is
available to ELF files that carry no `.peios.sig` section header.

An extended attribute is a property of an inode, not of the file's
bytes, so a signer cannot ship one: it produces the blob and something
with the right to set `security.*` attributes on the destination
filesystem applies it when the file is created. On Peios that is the
package consumer, from a detached-signature payload entry named
`<file>.peios.sig` (PSPU §5.16). A signer that emits the blob under
that name beside the file it signs, and does not touch the file, has
done its whole job for this placement.

### 3.2.2.3 Lookup order and commitment

A verifier MUST determine the storage location as follows.

1. Read the first four bytes. A file shorter than four bytes, or whose
   first four bytes are not `\x7fELF`, is not ELF: go to step 3.
2. Parse the ELF structures and scan for a section named
   `.peios.sig`. **Once such a section header is found, the ELF path
   is committed**: the extended attribute MUST NOT be consulted,
   whatever happens next. A wrong type, a wrong size, an out-of-range
   offset, a read failure, a bad version byte or a failed verification
   all yield "unsigned". A structural failure encountered while
   parsing MUST commit the path in the same way. The single exception
   is `e_shnum == 0`, which does not commit.
3. Read `security.peios.sig`. If present and exactly 3310 bytes, use
   it.
4. Otherwise the file is unsigned.

The commitment rule is a security requirement rather than an
optimization. Without it, an attacker able to write a malformed ELF
section could force fallback to whichever location they more easily
controlled.

Where both locations are populated, the ELF section wins. A signer
SHOULD NOT populate both.

## 3.2.3 What is signed

The message is a 32-byte SHA-256 content hash. Which bytes it covers
depends on where the signature is stored, and a signer MUST use the
form matching its chosen location.

**ELF section source.** The hash covers the file with the section's
*contents* replaced by zeros:

```
SHA-256( file[0 .. sh_offset)
       || 0x00 × sh_size
       || file[sh_offset + sh_size .. file_size) )
```

Only the section **contents** are zeroed. The `Elf64_Shdr` entry
describing the section is hashed verbatim, as are the ELF header, the
program headers, the section-name string table and every other byte of
the file. The section header metadata is therefore integrity-protected
along with everything else, which is what stops an attacker relocating
or resizing the signature section without invalidating the signature.

This has a direct consequence for how a signer MUST work. The complete
file layout — including `sh_offset`, `sh_size`, `sh_name` and the
position of the section header table — MUST be final before the hash
is computed. The practical sequence is to reserve a 3310-byte
`.peios.sig` section filled with zeros, finalize the layout, hash the
file as it then stands, sign the hash, and write the blob into the
reserved bytes without touching anything else. Because the reserved
region is already zero, the file as hashed and the file as shipped
differ only in those 3310 bytes.

**Extended attribute source.** The hash covers the entire file with no
exclusions:

```
SHA-256( file[0 .. file_size) )
```

This applies to ELF files reaching the attribute path as well as to
non-ELF ones. The ELF-zeroed form is used **only** when the ELF
section is the signature source.

In both cases `file_size` is a snapshot taken at the start of
verification. A verifier MUST re-check the size before returning and
MUST discard the result if it changed.

## 3.2.4 Algorithm

The signature is **ML-DSA-65** as specified in FIPS 204. The public
key is 1952 bytes and the signature is 3309 bytes.

Signing is:

```
ML-DSA.Sign(private_key, content_hash, ctx = "")
```

and verification is the corresponding `ML-DSA.Verify`.

This is **pure** ML-DSA — FIPS 204 Algorithm 2 and Algorithm 3 — and
not HashML-DSA, the pre-hashing variant. The message happens to be a
32-byte SHA-256 hash, which pure ML-DSA signs directly. A signer MUST
NOT use the pre-hashing variant; a signature produced that way will
not verify.

The context string MUST be empty. Signers MUST NOT set a context.
Verifiers cannot express one, so a signature produced under a
non-empty context simply fails to verify rather than being detected
and reported.

It follows that ML-DSA's context field is **not** available for domain
separation between binary signatures and any other Peios signature
system. Separation MUST come from using distinct keys.

A signer MUST supply the public key as the **raw** 1952-byte key, not
an SPKI-wrapped DER encoding. From OpenSSL 3.5 or later, the raw key
is the trailing 1952 bytes of the DER public key.

## 3.2.5 Key selection and trust tiers

The blob carries no key identifier, so a verifier selects a key by
exhaustive trial: it tries each key in its table in order and takes
the first that verifies.

The trust tier is a property of **which key verified** — a `pip_type`
and a `pip_trust`, both unsigned integers — and never of anything the
signer encoded. A signer cannot express intent about the tier it
wants. It obtains whichever tier the verifier associates with the key
it used, and if the verifier carries no matching key the file is
simply unsigned.

Consequently:

- A signer that wants software to run at a tier MUST have its public
  key present in the verifier's table. Getting a key into that table
  is a deployment question, not a format question.
- A signer MUST NOT assume its signature is portable across systems
  carrying different key tables. The same file may be trusted on one
  and untrusted on another, with no observable difference in the file.
- Verification cost is linear in the number of keys, so a verifier MAY
  reasonably carry few.

---

# 3.3 The PIP Contract

_Peios Specifications / PSPK / Binary Signing and PIP_

> What a verified signature confers — a PIP type and trust level — how dominance is decided, and what may and may not be relied on.

A verified signature confers a **PIP identity**: a `pip_type` and a
`pip_trust`, both 32-bit unsigned integers, taken from the key that
verified. An unsigned, unverifiable or unrecognized binary confers
type 0 and trust 0, which means no protection.

This chapter states what that identity means to a party outside the
kernel — what a signer is asserting by obtaining one, what an object
owner is asserting by labeling an object, and what may and may not be
relied upon.

## 3.3.1 Dominance

All PIP enforcement reduces to one comparison:

```
dominates(caller, target):
    if target.pip_type == 0:
        return true
    return caller.pip_type  >= target.pip_type
       and caller.pip_trust >= target.pip_trust
```

Both axes are compared numerically. Neither is a closed enumeration:
a value carries no meaning beyond its ordering.

Three type values are conventional — 0 for None, 512 for Protected,
1024 for Isolated — but a specification MUST NOT assume they are the
only ones, and a party evaluating dominance MUST compare numerically
rather than switching on known values.

An unprotected target is dominated by everyone. This is what keeps
ordinary processes universally accessible whatever trust values a
caller carries, and it means PIP restricts access **to** protected
things rather than granting access to trusted callers.

Dominance is binary. A caller either dominates or does not; there is
no partial ordering and no per-operation granularity in PIP itself.

## 3.3.2 What a signer asserts

Obtaining a tier is an assertion about the **binary**, not about what
it will do. Specifically, a signer with a key at some tier asserts
that the signed file is fit to run at that tier, that its contents are
what the signer intended, and that the signer accepts the file being
treated as trusted by every dominance comparison on every system
carrying that key.

A signer MUST NOT treat a tier as a capability grant. A high tier
confers no privilege, no access right and no identity. It protects the
process from lower-tier processes and permits it to reach
higher-protected objects; it grants nothing on its own.

A signer SHOULD understand that a tier is inherited by children at
fork and re-derived at their exec. A protected process that execs an
unsigned binary loses protection entirely — protection follows the
binary, not the lineage.

## 3.3.3 What an object owner asserts

An object opts into PIP protection by carrying a process trust label
in its SACL, whose SID has the form `S-1-19-{type}-{trust}` — the
Process Trust authority with exactly two sub-authorities. A SID of any
other shape makes the descriptor malformed, and an evaluator MUST
reject it rather than guess.

The label's access mask names exactly the rights a **non-dominant**
caller may still receive. A dominant caller is unrestricted by the
label.

Two properties matter to anyone authoring one.

**There is no default.** An object with no trust label is unrestricted
by PIP, reachable by any process whatever its identity. Protection is
opt-in per object.

**Privileges do not compensate.** PIP revokes rights that privileges
granted, including `ACCESS_SYSTEM_SECURITY`. There is no relabel
equivalent, no administrative override, and no privilege that
substitutes for insufficient trust. An object owner labeling an
object may rely on this: a non-dominant caller cannot reach the
object's SACL to remove the label, which is what makes the protection
self-sustaining rather than trivially removable.

## 3.3.4 What may be relied upon

A party may rely on the following.

A tier is derived from the signature alone. No parent process, no
privilege, no runtime interface and no environment can confer,
elevate, or forge one — a compromised process running as SYSTEM cannot
grant PIP to an unsigned binary.

Impersonation does not alter it. PIP is read from per-process state
rather than from a token, so a service impersonating a client still
evaluates its own tier, and a process impersonating a token created
for a protected process gains nothing.

A verified file is pinned against in-place modification for as long as
its inode remains live. Ordinary, positioned and append writes,
truncation by descriptor or pathname, every `fallocate` mode, and
content-mutating and unrecognized ioctls are all refused on it, as is
mutation or removal of the signature attribute.

**A binary the kernel execs on its own behalf carries at least
PeiosTcb trust.** Where the kernel spawns a userspace helper for its
own purposes rather than at a process's request — resolving a module
name, and any comparable kernel-initiated exec — the implementation
MUST refuse the exec unless the binary's `pip_trust` is at least the
PeiosTcb level. A party may therefore rely on such a helper being
TCB-signed, and on the exec failing rather than proceeding at a lower
tier.

The refusal MUST apply equally when no tier could be derived at all.
"Could not establish trust" and "is not trusted" reach the same
outcome here, so that the requirement cannot be evaded by preventing
the derivation from running.

## 3.3.5 What may not be relied upon

A party MUST NOT rely on the following.

**Execution is not gated, with one exception.** A bad, tampered or
absent signature costs a binary its tier; it does not prevent
execution. PIP determines trust level, not permission to run.
Permission to run is the file's own security descriptor.

The exception is the kernel-initiated exec described above, where a
tier below PeiosTcb refuses the exec outright. It is confined to that
case for a reason: everywhere else there is a requesting process whose
own authority bounds what the exec can do, so an untrusted binary can
be allowed to run and simply carry no tier. A kernel-initiated exec has
no such process behind it — the kernel is acting on its own behalf, at
its own authority — so there is no lesser authority to fall back to and
nothing to bound the result. A party MUST NOT generalise the exception
to ordinary execs.

**Absence of a tier is not observable as an error.** There is no
diagnostic distinguishing "this binary is unsigned", "this signature
is malformed" and "this key is not in the table". All three produce a
process at type 0 and trust 0 with no indication.

**There is no revocation.** A signed binary later found to be
malicious cannot be invalidated. There is no hash blocklist and no
key-scoped revocation. The remedies are removing the file or replacing
the verifier's key table.

**A tier is not a container boundary.** PIP operates inside the
kernel's trust boundary. Kernel compromise voids it, DMA-capable
hardware bypasses it, and it offers nothing equivalent to
hypervisor-based isolation.

**Library trust is compared, not merely required.** Where a process
enables library signature verification, a library has to dominate the
loading process, so raising a process's tier narrows the set of
libraries it can load. A signer distributing libraries alongside a
high-tier program has to sign them at a tier that dominates it.

**Scripts take their interpreter's tier.** A script executed through a
`#!` line contributes nothing; the tier comes from the interpreter
binary. A signer MUST NOT expect signing a script to affect anything,
and an object owner MUST NOT treat "runs at a high tier" as evidence
that the code being run was signed.

---

# 3.4 Files the Kernel Loads

_Peios Specifications / PSPK / Binary Signing and PIP_

> The same signature, required on device firmware the kernel reads for its own use — what a firmware signer must produce and what the verifier does with it.

Executing a binary is not the only way file contents become code.
When a driver asks the kernel for device firmware, the kernel reads a
file from the filesystem and hands its bytes to hardware that can act
on host memory. A tampered firmware blob is at least as complete a
compromise as an unsigned binary running at the highest tier, and it
happens without an exec for the verifier to intercept. This section
extends the signature of §3.2 to those files.

## 3.4.1 What is covered

The verifier checks a signature on every file it reads through the
firmware loader — the mechanism a driver uses to request a named
blob, whether whole or in pieces. Files the kernel reads for other
purposes (a module, a policy file, a kexec image) have their own
integrity mechanisms and are not covered here.

Firmware is not executed by a process, so it obtains no PIP identity.
The signature is used for one decision only: whether the bytes reach
the device.

## 3.4.2 What a signer produces

A firmware file is never ELF. The signer therefore produces the
extended-attribute form of §3.2 — the 3310-byte blob over SHA-256 of
the **entire file as it sits on disk** — and delivers it as the
detached-signature payload entry of PSPU §5.16, `<file>.peios.sig`
beside the file in the package. The package consumer derives
`security.peios.sig` from it when the file is created.

Because the hash covers the on-disk bytes, a compressed blob is signed
in its compressed form. The kernel verifies before it decompresses,
which is the side of that boundary a verifier has to be on: the
decompressor is code that runs on untrusted input, and it must not run
on bytes that have not yet been checked.

A signer MUST NOT sign a symlink. The verifier reads through links
and checks the target's attribute; a signature on the link itself is
never consulted.

## 3.4.3 What the verifier requires

The verifier resolves the signature by the lookup of §3.2 and selects
a key by the trial of §3.2. It then requires that the key's tier be
the one that denotes the kernel's own trusted computing base
(PeiosTcb). A verified signature from a key at any other tier is
treated exactly as no signature: firmware runs with kernel privilege
on the far side of a bus, and no lower tier is fit to supply it.

A firmware file that is unsigned, unverifiable, or signed at an
insufficient tier is **refused**: the loader reports failure to the
requesting driver, which fails as it would for a missing file. The
verifier MUST NOT fall back to loading the file unsigned.

A verifier MAY provide a boot-time policy that reports rather than
refuses such a file, so that a system can be brought up with an
unsigned firmware set and the gaps found before refusal is turned on.
A verifier in that mode MUST record every file it would have refused,
and MUST NOT make the mode selectable at run time.

## 3.4.4 What a signer may rely on

- The bytes verified are the bytes delivered to the device. The
  verifier checks the buffer the loader will hand over, not a separate
  read of the file, so a file changed between the two is not a concern
  the signer has to design around.
- The check applies to every path the loader resolves, including
  paths an administrator has added to its search list. A signer
  cannot be shadowed by an unsigned file earlier in that list.
- The check does not apply to firmware pushed into a device by means
  other than the loader — a device's own update interface, for
  example. Those are the responsibility of the driver that exposes
  them.

---

# 4.1 Scope and Roles

_Peios Specifications / PSPK / Registry Source Interface_

> The RSI contract between the kernel's registry subsystem and the userspace sources that store data for it — and what a source is not.

This chapter specifies the **Registry Source Interface (RSI)**: the
protocol between the Peios kernel's registry subsystem and the
userspace processes that store registry data for it.

Two roles participate.

The **kernel** is LCS, the Layered Configuration Subsystem. It owns the
registry namespace, the layer model, access control, watches and
transactions, and it holds no storage of its own. There is one kernel.

The **source** is a userspace process that stores the data for one or
more hives and answers the kernel's requests about it. The source role
is publicly implementable: any process holding the required privilege
MAY register as a source, and the kernel is source-agnostic. A
conforming source is the subject of the requirements in this chapter.

The kernel is the party asking. A source is authoritative for the bytes
it returns and for nothing else.

This chapter covers:

- the character device, how a source attaches to it and is recognized,
  and the source slot lifecycle
- the framing and encoding of requests and responses, and the rules
  under which each may be extended
- every operation the kernel issues, its request payload, its response
  payload, and its meaning
- the status vocabulary a source answers with
- what the kernel validates for itself rather than believing
- the obligations a conforming source MUST satisfy

This chapter does not cover:

- The registry data model — hives, keys, path entries, values, layers,
  tombstones, resolution — which is described in the Peios Kernel TRM.
  A source does not need it.
- The system-call and ioctl surface the registry offers to ordinary
  programs, which is that subsystem's own documentation.
- The registry backup format, which is specified in its own chapter.
- How a source stores its data, serves concurrent requests, or computes
  its answers.

## 4.1.1 What a source is not

A source stores and returns. It MUST NOT resolve layers, filter results
by visibility, evaluate a Security Descriptor, interpret a path beyond
the parent and child names it is given, or dispatch a notification.
Every such decision belongs to the kernel, and a source that made one
would be making it with less information than the kernel has.

A source never learns the identity of the process on whose behalf a
request was issued. Requests carry no caller identity, and there is no
mechanism by which a source could obtain one.

## 4.1.2 What the kernel establishes for itself

The kernel validates that every response is structurally well-formed,
that names are valid, that Security Descriptors parse and satisfy the
mask rules, that sequence numbers cannot be from the future, and that
metadata blocks cover exactly the GUIDs they should. §4.5 lists these.

It cannot validate meaning. A source is inside the trusted computing
base precisely because the kernel has no independent copy of what a
source returns: a Security Descriptor granting everyone full access to
a sensitive key is a valid Security Descriptor, and the kernel will
enforce it.

A source is trusted with the correctness of the registry's access
control for the hives it backs. That is the whole trust model, and it
is why attaching requires the highest privilege the system has.

---

# 4.2 The Channel

_Peios Specifications / PSPK / Registry Source Interface_

> Attaching to /dev/pkm_registry — the privileges the open handler demands, registration, source slots, resuming a Down slot, and the optional lifetime extension.

## 4.2.1 The device

A source attaches by opening the character device `/dev/pkm_registry`.

The `open()` handler evaluates the calling thread's effective token.
The caller MUST hold `SeTcbPrivilege` and it MUST be **enabled**, not
merely present; `open()` fails `EPERM` otherwise. An unprivileged
process cannot obtain a descriptor to the device at all.

One open descriptor corresponds to one source connection.

## 4.2.2 Registration

Before entering the request loop a source MUST register its hives, by
issuing the `REG_SRC_REGISTER` ioctl on the device fd. The argument is
a `reg_src_register_args`:

| Field | Type | Description |
|---|---|---|
| `hive_count` | `u32` | Number of hive entries. MUST be non-zero. |
| `_pad` | `u32` | Reserved. MUST be zero. |
| `max_sequence` | `u64` | The highest sequence number persisted anywhere in this source's storage. A single value for the whole source, not per hive. |
| `hives_ptr` | `u64` | Userspace address of an array of `hive_count` `reg_src_hive_entry` structures. |

Each `reg_src_hive_entry`:

| Field | Type | Description |
|---|---|---|
| `name_len` | `u32` | Length of the hive name in UTF-8 bytes. |
| `_pad0` | `u32` | Reserved. MUST be zero. |
| `name_ptr` | `u64` | Userspace address of the hive name. Not null-terminated. |
| `root_guid` | `u8[16]` | The GUID of this hive's root key. MUST NOT be all-zero. |
| `flags` | `u32` | `RSI_HIVE_PRIVATE` (`0x01`). All other bits reserved and MUST be zero. |
| `_pad1` | `u32` | Reserved. MUST be zero. |
| `scope_guid` | `u8[16]` | The private scope identifier. MUST be all-zero unless `RSI_HIVE_PRIVATE` is set. |

Each hive carries its own name pointer; there is no separate array of
names.

The kernel validates, and registration fails if any of the following
does not hold:

- every hive name is valid — UTF-8, no null byte, no separator,
  non-empty, within the configured component length;
- no hive name is `CurrentUser` in any casing, which is reserved;
- the route identity of each hive — its case-folded name paired with
  its scope — does not collide with one held by an Active source
  (`EEXIST`);
- no root GUID is all-zero, and the root GUIDs within this request are
  distinct from each other;
- a hive without `RSI_HIVE_PRIVATE` carries an all-zero `scope_guid`;
- `hive_count` is within `MaxHivesPerSource` and the registered source
  count is within `MaxRegisteredSources` (`ENOSPC`);
- `max_sequence` is not `U64_MAX`, since the kernel MUST be able to
  allocate above it (`EOVERFLOW`).

`max_sequence` initializes the kernel's global sequence counter to at
least one above it, so that new writes always outrank anything already
persisted. A source MUST report it accurately; under-reporting it
allows a new write to collide with a stored entry.

## 4.2.3 Source slots

A successful registration creates a **source slot**, the kernel object
owning one connection and its hive set. A slot is Active or Down.

Each registered hive has a stable identity: its case-folded name, its
visibility, its scope GUID if private, and its root GUID.

A source crash or an fd close marks the slot Down. It does **not**
unregister the source or retire any hive identity. Down slots keep
their identities reserved, and collision checks include them. There is
no implicit retirement.

While a slot is Down its hives are unavailable; operations needing a
round trip fail, key descriptors held by processes remain valid, and
watches remain armed.

## 4.2.4 Resuming a Down slot

A new process MAY take over a Down slot. It MUST hold `SeTcbPrivilege`
and it MUST register **exactly the same hive set**: the same number of
hives, and for each of them the same case-folded name, the same
visibility, the same scope GUID and the same root GUID.

Partial resume is rejected. In particular:

- A request whose only mismatch is a different root GUID for an
  otherwise-matching hive fails `ESTALE`.
- Other partial or malformed resume attempts fail `EINVAL`.
- A collision with an **Active** slot fails `EEXIST`, and takes
  precedence over `ESTALE` when both would apply.

A source MUST NOT expect to add hives by resuming a Down slot with a
larger set; that is a partial-resume failure. New hives require a new
slot.

The kernel authenticates a replacement by `SeTcbPrivilege`, not by
process identity. Process identity cannot survive a crash and restart,
so nothing records or compares it.

On a successful resume the slot becomes Active and the kernel replays
any pending layer deletions before resuming normal traffic.

## 4.2.5 Before serving anything

A source MUST purge orphaned key records before completing
registration. An orphaned record is a key with no path entry in any
layer, left behind by a key that was unlinked but not dropped before
the previous shutdown.

If that cleanup cannot be completed, the source MUST fail registration
rather than become Active with known orphans. The kernel does not
verify this and cannot: it has no independent view of the source's
storage.

On first boot against an empty store, a source MUST create a root key
record for each hive it backs, generating a GUID for each and giving it
an appropriate default Security Descriptor, and MUST persist them. The
root GUIDs it then reports in registration are those. Subsequent
startups reuse the persisted ones.

## 4.2.6 The lifetime extension

A source MAY negotiate the lifetime extension. It tells the source how
long each request and transaction may live, and gives it a lease that
proves a transaction still has a live kernel-side owner. The RSI request
and response frames are unchanged by it. A source that does not
negotiate it gets the protocol described in the rest of this book.

All three ioctls are issued on the device fd. Every timestamp is an
absolute `CLOCK_MONOTONIC` time in nanoseconds.

### 4.2.6.1 Negotiation

To use the extension, a source MUST issue `REG_SRC_NEGOTIATE` before
`REG_SRC_REGISTER`. The argument is a `reg_src_negotiate_args` (16
bytes):

| Field | Type | Description |
|---|---|---|
| `version` | `u32` | `REG_SRC_LIFETIME_VERSION`, which is 1. |
| `flags` | `u32` | Reserved. MUST be zero. |
| `session` | `u64` | MUST be zero on input. On success, the kernel writes a nonzero session identifier, unique to this open fd and never reused by a later fd. |

Any other version, nonzero flags or a nonzero input session fails
`EINVAL`. Negotiating after registration, or on a connection that is
closing, fails `EBUSY`.

### 4.2.6.2 Request context

After reading a request and before responding to it, a negotiated source
MAY issue `REG_SRC_REQUEST_CONTEXT` with its session and the request's
id. The argument is a `reg_src_request_context_args` (40 bytes):

| Field | Type | Description |
|---|---|---|
| `session` | `u64` | The session returned by negotiation. |
| `request_id` | `u64` | The id of a request the source has read and not yet answered. |
| `request_deadline_ns` | `u64` | Output. When the kernel-side caller stops waiting, counting from when the request was queued. |
| `lifetime_deadline_ns` | `u64` | Output. The transaction's lifetime ceiling; zero for a transaction owned by one kernel operation, which has no separate ceiling. |
| `lease_deadline_ns` | `u64` | Output. The current cleanup lease; zero when the request has no live transaction owner. |

The context stays available after the kernel-side caller has given up,
until the source's response is accepted, so a source can still clean up
and answer a request it read late. A request the source has not read, or
has already answered, fails `ENOENT`.

### 4.2.6.3 Renewing a lease

`REG_SRC_RENEW` takes a `reg_src_renew_args` (32 bytes): `session` and
`transaction_id` as inputs, and `lifetime_deadline_ns` and
`lease_deadline_ns` as outputs. On success the lease is extended to at
most five seconds from now, and never past the lifetime ceiling.

Renewal succeeds only for an existing transaction that has not ended,
whose kernel-side owner (a transaction fd, or a kernel operation) is
still live, on this source's own session. An unknown, released, expired
or foreign transaction fails `ESTALE`. A lease that has expired cannot
be renewed back to life. Releasing the last owner, or aborting the
transaction, ends renewal before the abort message is delivered.

None of the three ioctls uses an in-flight request slot, so a saturated
request queue cannot prevent renewal. On a connection that has not
negotiated, is not Active, or names another session, request context and
renewal fail `ESTALE`.

### 4.2.6.4 What a negotiated source does with it

A source that negotiated:

- MUST stop holding transaction state (locks, an open storage
  transaction, a read snapshot) once that transaction's lease has
  expired or renewal has failed, and MUST treat the transaction as
  aborted from then on;
- MUST reject new operations on a transaction after its lifetime
  ceiling, and MUST serialize its rollback with the transaction's other
  operations and its commit;
- MUST report the true outcome of a commit it had already admitted when
  the lease or lifetime ran out, rather than inferring one from the
  expiry.

A lease is evidence that the kernel-side owner is alive. It is not an
inactivity timeout, and lease expiry does not change how the kernel
treats a commit response that arrives after its caller stopped waiting.

---

# 4.3 Message Framing

_Peios Specifications / PSPK / Registry Source Interface_

> The 22-byte request header and its response, the binary encoding, the asymmetry in how each side may be extended, and the concurrency rules.

The protocol is binary and multiplexed. All multi-byte integers are
little-endian.

## 4.3.1 The request header

A request is 22 bytes of header followed by an operation-specific
payload.

| Offset | Size | Field |
|---|---|---|
| 0 | 4 | `total_len` |
| 4 | 8 | `request_id` |
| 12 | 2 | `op_code` |
| 14 | 8 | `txn_id` |

`total_len` is the whole message including the header.

`request_id` matches a response to its request. Request ids are
allocated by the kernel, are strictly increasing within one connection,
and are never reused while that connection lives — including after a
request has timed out.

`txn_id` is the transaction the operation belongs to, or zero for none.
When non-zero, the source MUST process the operation inside that
transaction's context.

## 4.3.2 The response header

A response is 14 bytes of header followed by a payload. It carries no
`txn_id`.

| Offset | Size | Field |
|---|---|---|
| 0 | 4 | `total_len` |
| 4 | 8 | `request_id` |
| 12 | 2 | `op_code` |

A source MUST copy `request_id` from the request into its response, and
MUST set `op_code` to the request's operation code with the high bit
set — that is, `op_code | 0x8000`. Every operation has a named response
code for this value.

Every response payload begins with a `u32` status at offset 14, so the
minimum response size is 18 bytes.

## 4.3.3 Encoding

A **length-prefixed field** is a `u32` byte count followed by that many
bytes. Strings so encoded are UTF-8 and carry no terminator; a
terminator byte counted in the length is a null byte and is therefore
invalid. Some length-prefixed fields carry binary rather than text —
Security Descriptors and value data — and are not UTF-8.

A **GUID** is 16 raw bytes.

An **array** is a `u32` count followed by that many entries.

A **boolean** is one byte.

## 4.3.4 Extension, and its asymmetry

Requests and responses extend differently, and a source MUST implement
both rules.

A **request** MAY carry trailing fields beyond those a source
recognizes. A source MUST skip them, using `total_len` to find the end
of the message. This is how the kernel adds an optional field without
an RSI version bump.

A **response** MUST NOT. The kernel rejects any trailing bytes in a
response payload as malformed data. A source MUST emit exactly the
payload each operation defines, and no more. Extending the protocol in
this direction is done with new operations, never by growing an
existing payload.

## 4.3.5 Reading and writing

The device fd is message-oriented. `total_len` frames messages, but a
successful I/O call never splits or joins one.

**`read()`** returns exactly one complete request. If none is queued, a
blocking read waits until one is, or until the fd is closing, in which
case it returns 0. Under `O_NONBLOCK` an empty queue returns `EAGAIN`.
If the caller's buffer is too small for the next queued request,
`read()` returns `EMSGSIZE` and **does not consume it**.

**`write()`** submits exactly one complete response. The buffer length
MUST equal the response header's `total_len`, and MUST be at least the
response header size. A successful write is never short.

The following all fail `EINVAL` **and tear the connection down**,
marking the source Down:

- a length shorter than the response header;
- a length that does not equal `total_len`;
- an unknown `request_id`;
- a response to a request that has not been delivered;
- a second response to a request already answered;
- an `op_code` that is not the request's with the response bit set;
- a response written on a descriptor that is not the slot's active one.

A source that cannot frame its own messages correctly is not one whose
other answers can be relied on. Ordinary per-operation errors are
reported through the status vocabulary and do not tear anything down.

**`poll()`** reports the fd readable when at least one complete request
is queued, writable while the slot is Active, and `POLLHUP | POLLERR`
when the slot is Down or the fd is closing. An fd that is open but not
yet registered reports nothing.

## 4.3.6 Concurrency and timing

A source MAY process requests in any order and MUST handle multiple
in-flight requests without head-of-line blocking. Responses are matched
by `request_id`, not by arrival order.

The kernel bounds in-flight requests per source by
`MaxConcurrentRSIRequests`, default 256.

A source MUST respond to **every** request it has read, exactly once,
even if the kernel-side caller has already given up. The kernel applies
a request timeout — `RequestTimeoutMs`, default 30 seconds, measured
from the moment it first tries to reserve an in-flight slot and
covering the whole wait — and a source is **not** disconnected for
exceeding it. Late responses are validated and processed exactly like
on-time ones.

A timed-out request remains in the kernel's in-flight table, and keeps
occupying one of the source's slots, until the source answers or the
connection is torn down. A source that accumulates unanswered requests
will exhaust its own concurrency budget.

---

# 4.4 Operations

_Peios Specifications / PSPK / Registry Source Interface_

> All eighteen RSI operations — path, key, value and layer — and the rule that a source returns every layer-qualified entry without pre-filtering.

Eighteen operations. Every one that returns layer-qualified data MUST
return **all** entries across **all** layers: a source MUST NOT
pre-filter, resolve, or omit. The kernel decides what is effective.

Every response payload begins with a `u32` status. Payload fields
below are listed after it, in wire order, with no padding between them.
"Status only" means the payload is the status and nothing else — 18
bytes in total.

| Operation | Code | Response |
|---|---|---|
| `RSI_LOOKUP` | `0x0001` | `0x8001` |
| `RSI_CREATE_ENTRY` | `0x0002` | `0x8002` |
| `RSI_HIDE_ENTRY` | `0x0003` | `0x8003` |
| `RSI_DELETE_ENTRY` | `0x0004` | `0x8004` |
| `RSI_ENUM_CHILDREN` | `0x0005` | `0x8005` |
| `RSI_CREATE_KEY` | `0x0010` | `0x8010` |
| `RSI_READ_KEY` | `0x0011` | `0x8011` |
| `RSI_WRITE_KEY` | `0x0012` | `0x8012` |
| `RSI_DROP_KEY` | `0x0013` | `0x8013` |
| `RSI_QUERY_VALUES` | `0x0020` | `0x8020` |
| `RSI_SET_VALUE` | `0x0021` | `0x8021` |
| `RSI_DELETE_VALUE_ENTRY` | `0x0022` | `0x8022` |
| `RSI_SET_BLANKET_TOMBSTONE` | `0x0023` | `0x8023` |
| `RSI_BEGIN_TRANSACTION` | `0x0030` | `0x8030` |
| `RSI_COMMIT_TRANSACTION` | `0x0031` | `0x8031` |
| `RSI_ABORT_TRANSACTION` | `0x0032` | `0x8032` |
| `RSI_FLUSH` | `0x0040` | `0x8040` |
| `RSI_DELETE_LAYER` | `0x0050` | `0x8050` |

Any other operation code is invalid.

## 4.4.1 Path operations

### 4.4.1.1 `RSI_LOOKUP`

Look up a child entry under a parent key. This is the path-walking
primitive; the kernel issues one per path component.

**Request:** `parent_guid` (16), `child_name` (length-prefixed).

**Response:** `entry_count` (`u32`), then that many path entries:

| Size | Field |
|---|---|
| 4+n | `layer_name` |
| 1 | `target_type`: 0 = GUID, 1 = HIDDEN |
| 16 | `target_guid` |
| 8 | `sequence` |

then `metadata_count` (`u32`), then that many key metadata entries:

| Size | Field |
|---|---|
| 16 | `guid` |
| 4+n | `sd`, binary |
| 1 | `volatile` |
| 1 | `symlink` |
| 8 | `last_write_time` |

An empty response — `entry_count` zero — means the child does not exist
in any layer. That is an ordinary answer, not an error.

The metadata block is **deduplicated**: exactly one entry per distinct
GUID referenced by the path entries. A source MUST satisfy all of:

- every GUID appearing as a target has exactly one metadata entry;
- no metadata entry is duplicated;
- no metadata entry is unreferenced;
- no metadata GUID is all-zero;
- a HIDDEN entry MUST carry an all-zero `target_guid` and MUST NOT
  contribute a metadata entry.

Violating any of these is malformed data.

The kernel resolves symlink targets itself, by issuing a separate
`RSI_QUERY_VALUES` for the key's default value. A source MUST NOT
interpret the symlink flag or follow anything.

### 4.4.1.2 `RSI_CREATE_ENTRY`

Create a path entry `(parent, child_name, layer) → guid`.

**Request:** `parent_guid` (16), `child_name`, `layer_name`,
`child_guid` (16), `sequence` (`u64`).

**Response:** status only.

Always paired with `RSI_CREATE_KEY`, which carries the same GUID. The
kernel sends `RSI_CREATE_ENTRY` **first**, so that a losing race is
detected before a key record is created: an `RSI_ALREADY_EXISTS` here
means another writer got the name.

### 4.4.1.3 `RSI_HIDE_ENTRY`

Create a HIDDEN path entry at `(parent, child_name, layer)`.

**Request:** `parent_guid` (16), `child_name`, `layer_name`,
`sequence` (`u64`).

**Response:** status only.

### 4.4.1.4 `RSI_DELETE_ENTRY`

Remove the path entry at `(parent, child_name, layer)`, whether it was
a GUID entry or a HIDDEN one.

**Request:** `parent_guid` (16), `child_name`, `layer_name`.

**Response:** status only.

### 4.4.1.5 `RSI_ENUM_CHILDREN`

Enumerate every child entry under a parent, across all layers.

**Request:** `parent_guid` (16).

**Response:** `child_count` (`u32`), then per child:

| Size | Field |
|---|---|
| 4+n | `child_name` |
| 4 | `entry_count` |
| … | that many path entries, in the `RSI_LOOKUP` entry format |

followed by **one** metadata block, in the `RSI_LOOKUP` metadata
format, covering the distinct GUIDs across all children. Emitting it
once rather than per child is what makes this cheaper than a lookup per
name.

The same deduplication and closure rules apply, evaluated across the
whole response.

## 4.4.2 Key operations

### 4.4.2.1 `RSI_CREATE_KEY`

Create a key record. The GUID is assigned by the kernel.

**Request:** `guid` (16), `name`, `parent_guid` (16), `sd` (binary,
length-prefixed), `volatile` (1), `symlink` (1).

**Response:** status only.

The path entry linking the key into the namespace is created separately
by `RSI_CREATE_ENTRY`. For a symlink key, the target is written
afterwards as a default `REG_LINK` value through `RSI_SET_VALUE`.

A source MUST persist the GUID exactly as given: no rewriting, no
remapping, no reassignment. GUIDs are the kernel's identity for keys
and the source's primary key for storage.

### 4.4.2.2 `RSI_READ_KEY`

**Request:** `guid` (16).

**Response:** `name`, `parent_guid` (16), `sd`, `volatile` (1),
`symlink` (1), `last_write_time` (`i64`).

### 4.4.2.3 `RSI_WRITE_KEY`

Update a key's mutable fields.

**Request:** `guid` (16), `field_mask` (`u32`), then the named fields
in bit order.

| Bit | Field | Encoding |
|---|---|---|
| 0 | `sd` | length-prefixed |
| 1 | `last_write_time` | `i64` |

Only fields whose bit is set are present. Any other bit set in
`field_mask` is invalid.

**Response:** status only.

There is no way to express a change to the GUID, the volatile flag or
the symlink flag: those fields are simply absent from the request. A
source MUST reject a request attempting to modify an immutable field
with `RSI_INVALID`.

A `field_mask` of zero is a well-formed existence check that mutates
nothing.

### 4.4.2.4 `RSI_DROP_KEY`

Purge everything associated with a GUID: the key record, all value
entries across all layers, all path entries, and all blanket
tombstones.

**Request:** `guid` (16).

**Response:** status only.

`RSI_DROP_KEY` MUST be idempotent. If the GUID does not exist — already
purged by startup cleanup, say — the source MUST return `RSI_OK`.

The kernel issues this when the last descriptor to an unnamed key
closes, and it issues it **without a waiting caller**. A source MUST
answer it like any other request.

## 4.4.3 Value operations

### 4.4.3.1 `RSI_QUERY_VALUES`

Retrieve every layer entry for one value, or for all values on a key.

**Request:** `guid` (16), `value_name`, `query_all` (1). When
`query_all` is set the value name is empty and every value on the key
is returned.

**Response:** `entry_count` (`u32`), then per entry:

| Size | Field |
|---|---|
| 4+n | `value_name` |
| 4+n | `layer_name` |
| 4 | `type` |
| 4+n | `data`, binary |
| 8 | `sequence` |

then `blanket_count` (`u32`), then per blanket tombstone:

| Size | Field |
|---|---|
| 4+n | `layer_name` |
| 8 | `sequence` |

The blanket list is part of every response, including one for a single
named value: the kernel needs it to resolve that name.

A tombstone entry carries type `REG_TOMBSTONE` (`0xFFFF`) and
zero-length data. A source MUST NOT return a tombstone with data, an
undefined value type, or data exceeding the configured maximum value
size.

### 4.4.3.2 `RSI_SET_VALUE`

Store a value entry at `(guid, value_name, layer)`, replacing any
existing entry for that triple.

**Request:** `guid` (16), `value_name`, `layer_name`, `type` (`u32`),
`data`, `sequence` (`u64`), `expected_sequence` (`u64`).

**Response:** status only.

**Conditional writes.** A source MUST support `expected_sequence`.
Zero means unconditional. Non-zero means the source MUST **atomically**
verify that the current entry at `(guid, value_name, layer)` carries
that sequence number before writing, and MUST return `RSI_CAS_FAILED`
without writing if it does not match or if no entry exists.

The condition is against the layer's own entry, not against any
resolved value. A source does not know what is effective and MUST NOT
try to work it out.

### 4.4.3.3 `RSI_DELETE_VALUE_ENTRY`

Remove the entry at `(guid, value_name, layer)`, whether it was a value
or a tombstone.

**Request:** `guid` (16), `value_name`, `layer_name`.

**Response:** status only.

This operation MUST be idempotent: a source MUST return `RSI_OK` when
there was no entry to remove. The kernel does not mask `RSI_NOT_FOUND`
here, so a source returning it makes the caller's delete fail.

### 4.4.3.4 `RSI_SET_BLANKET_TOMBSTONE`

Set or remove a blanket tombstone on `(guid, layer)`.

**Request:** `guid` (16), `layer_name`, `set` (1), `sequence` (`u64`).

**Response:** status only.

## 4.4.4 Transaction operations

### 4.4.4.1 `RSI_BEGIN_TRANSACTION`

**Request:** `txn_id` (`u64`), `mode` (`u32`).

The transaction id appears in the payload. The request header's own
`txn_id` is zero for this operation, since the transaction does not yet
exist. `RSI_COMMIT_TRANSACTION` and `RSI_ABORT_TRANSACTION` carry it in
both places.

| Mode | Value | Meaning |
|---|---|---|
| `RSI_TXN_READ_WRITE` | 0 | An ordinary transaction. |
| `RSI_TXN_READ_ONLY` | 1 | A point-in-time read snapshot. |

**Response:** status only.

For `RSI_TXN_READ_WRITE`, reads tagged with the id MUST observe the
transaction's own uncommitted writes, and writes tagged with it MUST be
committed atomically by `RSI_COMMIT_TRANSACTION`.

For `RSI_TXN_READ_ONLY`, reads tagged with the id MUST observe a stable
point-in-time snapshot. The kernel MUST NOT send a mutating operation
with a read-only transaction id, and a source that receives one MUST
reject it with `RSI_INVALID` and MUST NOT mutate anything. A read-only
transaction is released with `RSI_ABORT_TRANSACTION`; the kernel MUST
NOT send `RSI_COMMIT_TRANSACTION` for one.

A source whose store cannot support a mode MAY answer
`RSI_TXN_NOT_SUPPORTED` for that mode. The two are independent: a
source MAY support read-only snapshots without supporting read-write
transactions.

### 4.4.4.2 `RSI_COMMIT_TRANSACTION`

**Request:** `txn_id` (`u64`).

**Response:** status only.

On success every change in the transaction MUST be durable. On failure
every change MUST be rolled back.

### 4.4.4.3 `RSI_ABORT_TRANSACTION`

**Request:** `txn_id` (`u64`).

**Response:** status only.

Sent when a transaction is closed without committing, on timeout, and
to release a read-only snapshot. The kernel MAY send it without a
waiting caller.

## 4.4.5 Layer operations

### 4.4.5.1 `RSI_DELETE_LAYER`

Remove everything tagged with a layer name.

**Request:** `layer_name`.

**Response:** `orphaned_guid_count` (`u32`), then that many GUIDs (16
each).

The source MUST atomically remove all path entries, all value entries
and all blanket tombstones whose layer is `layer_name`, and MUST NOT
remove any key record. Orphan cleanup is the kernel's, through
`RSI_DROP_KEY`.

`orphaned_guids` MUST list exactly the GUIDs that lost their last path
entry as a result, with no nil GUID and no duplicates. The kernel
tracks them for deferred deletion.

An unknown layer name is **not** an error. A source with no entries for
it MUST return `RSI_OK` with an empty orphan list — a layer may have
entries in one source and none in another.

## 4.4.6 Maintenance

### 4.4.6.1 `RSI_FLUSH`

Persist pending writes for one hive to durable storage.

**Request:** `hive_name`.

**Response:** status only, returned when persistence is confirmed.

This is the only operation that identifies its target by hive name
rather than by GUID, because flushing is a hive-level act — a WAL
checkpoint, say — not a key-level one.

---

# 4.5 Conformance

_Peios Specifications / PSPK / Registry Source Interface_

> The status vocabulary, the obligations not tied to one operation, what the kernel validates, and where the trust boundary falls.

A conforming source MUST satisfy every requirement in this chapter.
This section collects the obligations that are not tied to one
operation, and the status vocabulary.

## 4.5.1 Status codes

Every response payload begins with a `u32` status. Zero is success.

| Status | Code | Kernel maps to | Meaning |
|---|---|---|---|
| `RSI_OK` | 0 | success | The operation completed. |
| `RSI_NOT_FOUND` | 1 | `ENOENT` | A key, value or path entry does not exist. |
| `RSI_ALREADY_EXISTS` | 2 | `EEXIST` | A path entry or key already exists. |
| `RSI_STORAGE_ERROR` | 3 | `EIO` | A failure in the backing store. |
| `RSI_NOT_EMPTY` | 4 | `ENOTEMPTY` | A key still has children or values. |
| `RSI_TOO_LARGE` | 5 | `ENOSPC` | Value data exceeds the maximum size. |
| `RSI_TXN_BUSY` | 6 | `EBUSY` | A transaction could not take the write lock. |
| `RSI_INVALID` | 7 | `EINVAL` | A malformed request or an invalid field value. |
| `RSI_CAS_FAILED` | 8 | `EAGAIN` | A conditional write's sequence did not match. |
| `RSI_TXN_NOT_SUPPORTED` | 9 | `ENOTSUP` | This transaction mode is not supported. |

A source MUST NOT return a code outside this vocabulary. One outside it
is malformed data.

Source-specific detail is never surfaced to the process that made the
registry call. The status is the whole interface, and a source MUST
choose the code that most accurately describes what happened.

## 4.5.2 Obligations

**Respond to everything.** A source MUST send exactly one response for
every request it has read, even after the kernel-side caller has timed
out. A request the source has read and will never answer occupies an
in-flight slot until the connection is torn down.

**Return complete layer data.** When asked for values or path entries,
a source MUST return **all** layer entries. It MUST NOT pre-filter,
resolve, or omit any. Layer resolution is the kernel's.

**Order enumerations deterministically.** The same request against
unchanged hive state MUST return the same ordering every time. This
applies to the child list of `RSI_ENUM_CHILDREN`, the value entries and
the blanket tombstone list of `RSI_QUERY_VALUES`, and the path entries
of `RSI_LOOKUP`. Ascending folded name, then layer, then sequence
satisfies it.

This is correctness, not tidiness. The kernel exposes enumeration to
callers as a dense index walk — position 0, 1, 2 until exhaustion —
observing the source's ordering at each step. A source that returns the
same set in a different order across those observations makes the walk
revisit some entries and never see others, which surfaces as duplicate
and silently missing keys. An unordered SQL query or a hash-map
iteration does **not** satisfy this: `UNION ALL` without `ORDER BY` and
deliberately randomised map iteration both yield different orderings
for identical input.

The obligation constrains ordering **within one response** only. It
does not constrain the order in which concurrent requests are
processed, and it does not by itself make a multi-step enumeration
atomic against concurrent mutation — a caller that needs a stable view
across a whole walk uses a read-only transaction.

**Preserve GUIDs exactly.** A source MUST persist a GUID as given.

**Handle concurrency.** A source MUST handle multiple in-flight
requests without head-of-line blocking, and MAY process them in any
order.

**Serialize commits.** Concurrent read-write commits MUST be
serialized, and a commit MUST be atomic. The kernel does no conflict
detection: it relies on commits being ordered and atomic, and lets the
later write win by sequence number.

**Support conditional writes.** `expected_sequence` on `RSI_SET_VALUE`
MUST be honored atomically.

**Protect immutable fields.** `RSI_WRITE_KEY` requests attempting to
modify the GUID, the volatile flag or the symlink flag MUST be rejected
with `RSI_INVALID`.

**Create hive roots on first boot**, and **purge orphans before
registering**. Both are described in §4.2.

## 4.5.3 What the kernel validates

A source cannot rely on a malformed response being tolerated. The
kernel checks each of the following, and two categories of failure have
different consequences.

**Malformed data** — a structurally valid message with invalid content
— fails the request with `EIO`, emits an audit event naming the source
and the class of failure, and **leaves the source running**, since
corruption may be localised. The classes are: an unparseable or
mask-invalid Security Descriptor; an invalid layer name, key name or
value name; a payload of the wrong shape or with trailing bytes; a
metadata block that is incomplete, duplicated, unreferenced or nil; an
invalid value type, a tombstone carrying data, or oversized data; a
nil or duplicated orphan GUID; a status code outside the vocabulary;
and the two sequence rules below.

**Malformed protocol** — a structurally invalid message, a framing
error, an unknown or duplicate request id, an operation code that does
not match its request — is treated as a crash. The connection is torn
down and the source is marked Down.

### 4.5.3.1 The two sequence rules

A source MUST NOT return a layer-qualified entry whose sequence number
is greater than or equal to the next number the kernel would allocate.
Sources store the numbers the kernel assigns them and cannot
legitimately hold a future one. Without this rule a compromised source
could fabricate a sequence number and win every resolution tie in its
own hives.

A source MUST NOT return duplicate sequence numbers at the same
precedence where they would have to be compared to select a winner.
The kernel rejects the response rather than choosing arbitrarily.
Duplicates that are never compared are not an error.

## 4.5.4 The trust boundary

A source is inside the trusted computing base. The kernel has no
independent copy of anything a source returns, so a compromised source
controls the access-control outcome for its hives entirely: it can
return a permissive Security Descriptor for any key and the kernel will
enforce it. Structural validation catches malformed data; it cannot
catch data that is well-formed and false.

Three consequences follow that an operator should understand.

A source backing the hive that holds layer metadata can fabricate
precedence and enabled values, and so decide which layer wins every
resolution contest system-wide. The privilege check applied when
precedence is *written* does nothing about a fabricated *read*.

The same source can return permissive descriptors for layer metadata
keys, granting any process write access to any layer.

`SeRestorePrivilege` implies descriptor control: a restore replaces
every Security Descriptor in the subtree it covers.

Sources MUST therefore run with tightly scoped privileges and be
protected by descriptors on their service definitions. The kernel emits
an audit event for every source data validation failure.

---

# 5.1 Scope and Roles

_Peios Specifications / PSPK / Registry Backup Format_

> The byte stream representing a registry key and everything beneath it with full layer fidelity, its two roles, and the constraints that shaped it.

This chapter specifies the **registry backup format**: the byte stream
that represents a registry key and everything beneath it, with full
layer fidelity.

Two roles participate, and unlike a live protocol they need not exist
at the same time.

The **writer** produces a stream. The Peios kernel's registry subsystem
is one writer; so is any third-party tool that constructs a backup for
migration, provisioning or archival.

The **reader** consumes one. The kernel is a reader, and so is any tool
that inspects, converts or transforms a backup.

The format is specified rather than described because both roles are
publicly implementable, and because a stream outlives the process that
wrote it. A backup taken on one machine is restored on another, by a
different implementation, perhaps years later.

This chapter covers:

- the framing common to every record, and the encoding of its fields
- the versioning fields, and the rules under which the format may be
  extended
- every record type and its payload, in wire order
- the ordering of records within a stream
- the integrity trailer and exactly what it covers
- what a reader MUST validate, and what a restore MUST do with a
  stream it accepts

This chapter does not cover:

- The registry data model the stream represents — hives, keys, layers,
  tombstones, resolution — which is described in the Peios Kernel TRM.
- The Registry Source Interface, which is a separate chapter. The
  backup format is a kernel-level format; a registry source never sees
  one.
- The system calls that produce and consume a stream.
- The binary layout of a Security Descriptor or a SID, which is
  defined in PCDS. A backup carries them as opaque byte strings.

## 5.1.1 Design constraints

The format is shaped by five requirements, and an implementation of
either role has to respect all of them.

**Streamable.** A stream is written to an arbitrary descriptor — a
file, a pipe, a socket — in a single forward pass, and read back the
same way. Neither role may require seeking.

**Full layer fidelity.** Every path entry, value, tombstone and blanket
tombstone carries its layer tag. Restoring reconstructs the layered
state, not a flattened view of it.

**Depth-first pre-order.** A key's parent always appears before it, so
a reader can create keys top-down without buffering a tree.

**Descriptors inline.** Each key record carries its own Security
Descriptor, with no deduplication and no shared table. Redundancy is
left to external compression.

**Self-verifying.** A trailer carries a record count and a
cryptographic checksum, so truncation and corruption are detectable
before anything is acted on.

---

# 5.2 Stream Structure

_Peios Specifications / PSPK / Registry Backup Format_

> Record framing, field encoding, ordering, and how the format is versioned and extended.

All multi-byte integers in this format are **little-endian**, in the
record framing and in every payload.

## 5.2.1 Record framing

Every record begins with the same six-byte header.

| Offset | Size | Field |
|---|---|---|
| 0 | 2 | `record_type` |
| 2 | 4 | `record_len` |

`record_len` is the record's total size **including** this header, so
its minimum valid value is 6. The payload follows immediately.

A reader MUST validate `record_len >= 6` and MUST verify that the
record body can be read in full before acting on the record or
skipping it.

| Record | Code |
|---|---|
| `HEADER` | `0x01` |
| `LAYER` | `0x02` |
| `KEY` | `0x03` |
| `PATH_ENTRY` | `0x04` |
| `VALUE` | `0x05` |
| `BLANKET_TOMBSTONE` | `0x06` |
| `TRAILER` | `0xFF` |

## 5.2.2 Field encoding

A **length-prefixed field** is a `u32` byte count followed by that many
bytes. Names — hive name, layer name, child name, value name — are
UTF-8. Three length-prefixed fields are **binary, not UTF-8**: a
`LAYER` record's owner SID, a `KEY` record's Security Descriptor, and a
`VALUE` record's data.

A **GUID** is 16 raw bytes. An all-zero GUID is nil and is valid only
where a record's definition says so.

## 5.2.3 Ordering

```
HEADER                         exactly one, first
LAYER                          one per referenced layer, before any key data
  for each key, depth-first pre-order over the merged tree:
    KEY                        the key object
    PATH_ENTRY *               entries owned by this section
    VALUE *                    all layers' values for this key
    BLANKET_TOMBSTONE *        all layers' blankets for this key
TRAILER                        exactly one, last
```

The merged tree is the union of every layer's namespace. Depth-first
pre-order guarantees a key's parent precedes it.

The following are normative:

- `HEADER` MUST be the first record and MUST appear exactly once.
- Every `LAYER` record MUST precede all key data. A `LAYER` record
  after key data has begun is invalid.
- The **root** `KEY` record — the one whose GUID equals
  `HEADER.RootGUID` — MUST be the first `KEY` record in the stream, and
  MUST appear exactly once.
- Within a key's section, records MUST appear in the order
  `PATH_ENTRY`, then `VALUE`, then `BLANKET_TOMBSTONE`. A `PATH_ENTRY`
  after a `VALUE` or `BLANKET_TOMBSTONE` in the same section is
  invalid, as is a `VALUE` after a `BLANKET_TOMBSTONE`.
- No `PATH_ENTRY`, `VALUE` or `BLANKET_TOMBSTONE` may appear before the
  first `KEY` record.
- `TRAILER` MUST be the last record. Any record after it is invalid.

## 5.2.4 Which section a path entry belongs to

A `PATH_ENTRY` naming a key belongs to **that key's** section: it is
one of the incoming entries for the key whose section it is in.

A HIDDEN entry has no key, so it cannot have a section of its own. It
belongs to the section of the key that is its **parent**, alongside
that key's other records. A HIDDEN entry masking a name where no key
exists in any layer is still valid — it expresses that a layer hides a
name, whatever else is or is not there.

A writer MUST NOT emit a GUID-bearing `PATH_ENTRY` in the **root**
key's section. On restore, the target key's existing name is
authoritative and such a record would be discarded. A reader MUST skip
one rather than treat it as an error.

A path entry's parent GUID may belong to a key that only has path
entries in a different layer. The merged-tree walk handles that; it is
not a special case.

## 5.2.5 Versioning

`HEADER` carries two version numbers.

**`FormatVersion`** is the version the stream was written with.

**`MinReaderVersion`** is the oldest reader that can process the stream
correctly. A reader MUST reject a stream whose `MinReaderVersion`
exceeds its own supported version, before acting on any of it.

The current version is 21 in both fields, and readers support 21.

A writer that used only older features SHOULD set a lower
`MinReaderVersion`, so that older readers can restore the stream. A
writer MUST raise `MinReaderVersion` when a new record type is required
for a correct restore, so that an older reader refuses the stream
rather than restoring an incomplete one.

## 5.2.6 Extension

Extension is by **new record types only**.

Unknown record types MAY appear anywhere between `HEADER` and
`TRAILER`. When `MinReaderVersion` permits, a reader MUST skip them,
and MUST treat them as inert: they do not begin or end a key section,
do not satisfy any required record, do not declare a layer, and do not
affect root mapping, sequence remapping or any validation rule. They
**do** count toward `TRAILER.RecordCount` and they **are** covered by
the checksum.

A record payload MUST be consumed **exactly**. Trailing bytes inside a
record of a known type are invalid, even though `record_len` would
accommodate them. A reader MUST NOT skip unrecognized trailing data
within a known record, and a writer MUST NOT add any.

This is deliberately the opposite of the RSI's request convention. A
stream is replayed into mutations long after it was written, and a
field silently ignored there is data silently lost.

---

# 5.3 Records

_Peios Specifications / PSPK / Registry Backup Format_

> Every record type in wire order — HEADER, LAYER, KEY, PATH_ENTRY, VALUE, BLANKET_TOMBSTONE and TRAILER.

Payload fields are listed in wire order, immediately after the six-byte
framing header, with no padding between them.

## 5.3.1 `HEADER` — `0x01`

Exactly one, first in the stream. Fixed portion 44 bytes plus the hive
name.

| Size | Field | Description |
|---|---|---|
| 8 | `Magic` | The ASCII bytes `PEIOSREG` — `50 45 49 4F 53 52 45 47`. |
| 4 | `FormatVersion` | `u32`. |
| 4 | `MinReaderVersion` | `u32`. |
| 8 | `Timestamp` | `i64`, Unix nanoseconds. |
| 16 | `RootGUID` | The GUID of the key at the root of this backup. |
| 4+n | `HiveName` | The hive the backup was taken from. |

A reader MUST reject a stream whose magic does not match, and MUST
reject one whose `MinReaderVersion` exceeds its own supported version.

`HiveName` MUST be a valid hive name under the ordinary naming rules.

`RootGUID` is a **stream-local** identity for the backup root. On
restore it is remapped to the target key (§5.4).

## 5.3.2 `LAYER` — `0x02`

One per layer name that has layer-tagged data anywhere in the stream.
All `LAYER` records precede all key data.

| Size | Field | Description |
|---|---|---|
| 4+n | `Name` | The layer name. |
| 4 | `Precedence` | `u32`, as observed at backup time. |
| 1 | `Enabled` | `u8`. MUST be 0 or 1. |
| 4+n | `Owner` | Binary SID, as observed at backup time. |

A `LAYER` record is a **stream manifest entry**, not a backup of the
layer's definition. It records what the layer looked like when the
backup was taken so that a restore can validate the stream against it,
and it creates, updates, deletes, enables, disables and authorizes
nothing.

A layer's definition is backed up only when its metadata subtree is
itself inside the exported subtree, in which case it appears as
ordinary `KEY`, `PATH_ENTRY` and `VALUE` records like anything else.

A reader MUST validate that every layer name is valid, that folded
layer identities are unique within the manifest, that `Enabled` is 0 or
1, that `Owner` parses as a SID, and that **every** layer name
appearing in a `PATH_ENTRY`, `VALUE` or `BLANKET_TOMBSTONE` has exactly
one corresponding `LAYER` record.

## 5.3.3 `KEY` — `0x03`

One per distinct key object in the subtree, however many layers name
it.

| Size | Field | Description |
|---|---|---|
| 16 | `GUID` | The key's identity. MUST NOT be nil. |
| 4 | `Flags` | `u32`. Bit 0 volatile, bit 1 symlink. |
| 4 | `SDLength` | `u32`. |
| n | `SD` | The full Security Descriptor. |
| 8 | `LastWriteTime` | `i64`, Unix nanoseconds. |

Name and parent GUID are **absent**. They are derivable from the
`PATH_ENTRY` records in the key's own section, and carrying them
separately would let a stream contradict itself.

Undefined bits in `Flags` MUST be zero. A reader MUST reject a record
with any bit outside `0x03` set, rather than ignoring it.

`SD` MUST parse as a Security Descriptor and MUST have an owner.

## 5.3.4 `PATH_ENTRY` — `0x04`

One per name-to-key mapping per layer.

| Size | Field | Description |
|---|---|---|
| 16 | `ParentGUID` | The parent key. MUST NOT be nil. |
| 4+n | `ChildName` | The name under that parent. |
| 16 | `ChildGUID` | The key being named, or an **all-zero GUID** meaning HIDDEN. |
| 4+n | `LayerName` | The layer this entry belongs to. |
| 8 | `Sequence` | `u64`. |

`ChildGUID` is the only GUID field in the format that may be nil, and a
nil one means HIDDEN rather than "no key". No `KEY` record is emitted
for the zero GUID.

## 5.3.5 `VALUE` — `0x05`

One per value entry per layer, tombstones included.

| Size | Field | Description |
|---|---|---|
| 16 | `KeyGUID` | The key this value belongs to. MUST NOT be nil. |
| 4+n | `Name` | The value name; empty for the default value. |
| 4 | `Type` | `u32`. |
| 4 | `DataLength` | `u32`. |
| n | `Data` | The value's bytes. |
| 4+n | `LayerName` | The layer this entry belongs to. |
| 8 | `Sequence` | `u64`. |

`Type` MUST be one of the defined registry value types, or
`REG_TOMBSTONE` (`0xFFFF`). A tombstone MUST carry zero-length data.

## 5.3.6 `BLANKET_TOMBSTONE` — `0x06`

One per blanket tombstone per layer.

| Size | Field | Description |
|---|---|---|
| 16 | `KeyGUID` | The key this blanket belongs to. MUST NOT be nil. |
| 4+n | `LayerName` | The layer. |
| 8 | `Sequence` | `u64`. |

## 5.3.7 `TRAILER` — `0xFF`

Exactly one, last. Payload 40 bytes, so the whole record is 46.

| Size | Field | Description |
|---|---|---|
| 8 | `RecordCount` | `u64`. Every record in the stream, `HEADER` and `TRAILER` included. |
| 32 | `Checksum` | SHA-256. |

`RecordCount` MUST be at least 2 — a stream has at minimum a header and
a trailer.

### 5.3.7.1 What the checksum covers

The checksum is a SHA-256 over the bytes from the **start of the
`HEADER` record's framing header** through the **end of
`TRAILER.RecordCount`**, inclusive.

That is: every byte of every preceding record, then the trailer's own
six-byte framing header, then the eight bytes of `RecordCount`. The 32
checksum bytes themselves are not covered, and nothing follows them.

Skipped unknown records are covered, in full, like any other.

A reader MUST verify both `RecordCount` and `Checksum`. A stream whose
record count does not match, or whose checksum does not verify, MUST be
rejected.

---

# 5.4 Restoring

_Peios Specifications / PSPK / Registry Backup Format_

> Restoring is a replace rather than a merge — root remapping, GUID rules, parent validation, sequence remapping, and how layers survive.

Restoring is a **replace**, not a merge. The target key's contents and
descendants are removed before the stream's contents are written.

The whole operation — teardown and rebuild together — MUST be atomic.
There is no partial-restore mode, and a store that cannot offer
atomicity cannot be a restore target.

## 5.4.1 The target key survives

A restore is performed against a key that already exists. That key
**object** is not replaced: its GUID, its parent, its name, its
volatile flag and its symlink flag remain what they were and MUST NOT
be taken from the stream.

What the stream's root `KEY` record supplies is the mutable part — the
Security Descriptor and the last write time — which MUST be written to
the target inside the restore.

The root record's immutable flags MUST **match** the target's. A backup
of a volatile key restored onto a non-volatile one, or a symlink onto a
non-symlink, MUST be rejected.

## 5.4.2 Root remapping

`HEADER.RootGUID` is stream-local. Every reference to it — a
`PATH_ENTRY`'s `ParentGUID` or `ChildGUID`, a `VALUE` or
`BLANKET_TOMBSTONE`'s `KeyGUID` — MUST be remapped to the target key's
existing GUID **before** any validation of parent references and before
any record is applied.

The backup root GUID MUST NOT be created as a new key record.

Descendant `KEY` records keep their backup GUIDs, which are written
into the target verbatim.

## 5.4.3 GUID rules

- The stream MUST contain exactly one `KEY` record whose GUID equals
  `HEADER.RootGUID`, and it MUST be the first `KEY` record.
- A non-root GUID MUST NOT appear twice in the stream.
- A non-root GUID MUST NOT equal the restore target's GUID.
- A non-root GUID that already exists **outside** the subtree being
  replaced is a collision and the restore MUST fail. A reader is not
  required to detect this before beginning; it MAY surface during
  replay, in which case the atomicity requirement ensures nothing is
  left behind.

## 5.4.4 Parent validation

Before a path entry is applied, its `ParentGUID` — after root remapping
— MUST be either the restore target's GUID or the GUID of a non-root
`KEY` record **already processed** earlier in the stream. A parent
outside the stream's remapped key set MUST cause the restore to fail.

This is what prevents a crafted backup from injecting path entries into
arbitrary parts of the existing namespace, outside the subtree being
replaced. It is not optional.

A HIDDEN `PATH_ENTRY` is held to a stricter rule: its remapped
`ParentGUID` MUST equal the GUID of the section it appears in, not
merely some already-processed key.

## 5.4.5 Creating a key

A `KEY` record carries no name and no parent, so both come from the
section's path entries.

The **anchor** is the first GUID-bearing `PATH_ENTRY` in the section,
in stream order, whose remapped `ChildGUID` equals the `KEY` record's
GUID. Its remapped `ParentGUID` and its `ChildName` are the parent and
name the key is created with.

- If the section contains no GUID-bearing path entry targeting the
  `KEY` record's GUID, the restore MUST fail.
- If any GUID-bearing `PATH_ENTRY` in a non-root section targets a
  *different* GUID after remapping, the restore MUST fail.
- HIDDEN entries do not satisfy the anchor requirement. They are
  parent-owned records for the key being created and are replayed only
  after it exists.

The key's `LastWriteTime` MUST be written immediately after it is
created, before any of the section's other records are replayed.

Path entries for the **root** section are handled differently:
GUID-bearing ones are not restored, because the target key's existing
incoming path entries remain authoritative. HIDDEN entries in the root
section are parent-owned records for the restore root and MUST be
restored, after parent validation.

## 5.4.6 Sequence remapping

The backup's sequence numbers preserve its internal layer-resolution
ordering. A restore is a new mutation, and its entries MUST become
newer than everything already present while keeping that internal
order. A reader MUST NOT write backup sequence numbers through
unchanged.

Remapping MUST preserve streamability: it MUST NOT require a seekable
input or a pre-scan pass. Before the first layer-qualified record is
applied, the reader records an offset — the next sequence number it
would allocate — and then, for every restored layer-qualified record:

```
new_sequence = restore_sequence_offset + backup_sequence
```

That needs no lookahead: the running maximum is computed during the
single pass.

The offset is held stable for the duration of the restore, so that no
other sequence-allocating mutation can interleave. Reads are not
blocked by it. A restore containing no layer-qualified record at all
need not reserve one.

If a remapped value would reach or exceed `U64_MAX`, the restore MUST
fail. The valid remapped range is `[offset, U64_MAX)`; `U64_MAX` itself
is never a valid sequence number.

When the restore reaches any terminal state — success, abort, failure
or cancellation — the global counter MUST be advanced past the highest
number the restore dispatched, and that advance MUST NOT be rolled
back. Numbers a failed restore dispatched become unused gaps, exactly
like those of any other failed write.

Dispatch order remains structural stream order. It is the remapped
numbers, not the order they were sent in, that preserve the backup's
internal layer resolution.

## 5.4.7 Layers in a restored stream

`LAYER` manifest records define nothing (§5.3). If restored entries
reference a layer that is not in the live layer table, and the stream
does not also restore that layer's metadata subtree as ordinary
registry data, those entries become latent unknown-layer entries and
are ignored during resolution until real metadata exists. If the
metadata subtree **is** included, it is restored through the ordinary
path, and those records are what define the layer.

## 5.4.8 Privilege

A restore replaces every Security Descriptor in the subtree it covers,
so the privilege to perform one effectively confers descriptor control
over everything within its reach.

Before any key record is written, a reader MUST check the layer
manifest: if any declared layer has a precedence above 0, **or** any
existing layer with the same folded identity does, the caller MUST hold
the privilege that guards high-precedence layers, or the restore MUST
be aborted before a single byte is written.

Records in the stream that create or raise persisted layer metadata
above precedence 0 are subject to the same check as an ordinary write
would be. Neither check is redundant: the first covers what the
manifest declares, the second covers what the stream actually writes.

## 5.4.9 Validation before mutation

A reader MAY validate the entire stream — including the trailer's
record count and checksum — before applying any of it. Doing so is
stronger than this specification requires, and it means a corrupt
stream is rejected before anything is torn down rather than after. The
cost is memory rather than seeking, since the records must be retained
across the teardown.

A reader that instead validates as it goes MUST still guarantee that a
checksum failure leaves nothing applied, which the atomicity
requirement already demands.

---

# 6.1 Scope and Roles

_Peios Specifications / PSPK / Trust Store Interface_

> What the Trust Store Interface specifies, the store image the kernel reads at boot and the ktrust channel a store keeper changes the store through, and what the kernel takes on the store keeper's word.

This chapter specifies the **Trust Store Interface**: how the Peios
kernel is given the trust store of PGSS §7.10, and how that store is
changed while the system runs. The channel is called **ktrust**.

The kernel verifies signed objects (PGSS §7) for its own purposes and on
behalf of any process that asks. To do so it has to know which
top-levels are enabled, which revocations apply, and what the
administrator distrusts. It does not read the trust store's directories.
It holds the store in memory, filled from two sources that this chapter
defines.

Two roles participate.

| Role | Obligation |
|---|---|
| Kernel | Holds the store, validates everything it is given, and applies it to every verification. There is one kernel. |
| Store keeper | The store keeper of PGSS §7.1. Composes the store image and tells the kernel of every later change. Every rule on what is sent binds the store keeper. |

The store keeper role is publicly implementable. The kernel recognizes
a store keeper by privilege and by a warrant (§6.4), not by what
program it is.

This chapter covers:

- the store image, which the kernel reads before it runs any program
  (§6.3)
- the device, and how a store keeper attaches to it (§6.4)
- the operations a store keeper issues, and their results (§6.5)
- the notifications the kernel sends (§6.6)

This chapter does not cover:

- The objects the store holds, and how a chain is verified. Those are
  PGSS §7.
- The trust store's directories, and the approvals a store keeper
  obtains. Those are PGSS §7.10.
- The system call by which a process asks the kernel to verify a file,
  and what the kernel does with a result at exec. Those are the Peios
  Kernel TRM's.
- The events the kernel emits about verification. Those are documented
  by evman.

## 6.1.1 What the kernel establishes for itself

The kernel checks that every object it is given is well formed, and
verifies every signature it holds a key for. It decides for itself
whether a top-level is vouched for by a root (§6.3). It decides for
itself, at each verification, whether a revocation applies to the chain
in front of it.

## 6.1.2 What the kernel takes on trust

The kernel cannot tell whether an administrator approved anything. It
believes a store keeper on two points:

- that a top-level no root signed is one the administrator trusts
- that a distrust entry being removed is one the administrator agreed
  to remove

A store keeper is therefore inside the trusted computing base for
exactly those two decisions, and for nothing a signature can settle.
That is why attaching is restricted as §6.4 describes.

---

# 6.2 Terminology

_Peios Specifications / PSPK / Trust Store Interface_

> The terms this chapter adds, covering store, store image, generation, and seen certificate, with everything else delegated to PGSS Signed Objects.

**Store.** The trust store as the kernel holds it: a set of top-levels,
a set of revocations, and a set of distrust entries.

**Store image.** A file holding the whole store, which the kernel reads
once at boot (§6.3).

**Generation.** A number the kernel raises by one each time the store
changes. A store keeper uses it to tell whether what it last read is
still what the kernel holds.

**Seen certificate.** A certificate the kernel has verified as part of
a chain since boot, with a record of its use (§6.5).

Terms defined in PGSS §7.2 (object, root, top-level, intermediary,
leaf, bundle, warrant, trust store, enabled, revocation, distrust,
object hash, and key hash) are used with the same meaning and are not
redefined.

---

# 6.3 The Store Image

_Peios Specifications / PSPK / Trust Store Interface_

> The layout of the store image at /system/pso/store, when the kernel reads it, how it decides whether each top-level is rooted, and what happens when the image is missing or damaged.

The **store image** is one file, `/system/pso/store`, holding every
object of the store.

| Field | Type | Description |
|---|---|---|
| header | 6 bytes | The header of PGSS §7.4, with `kind` `0x06` |
| `count` | `u32` | The number of entries |
| entries | Variable | `count` entries, each a `u16` length and an object |

An entry's object is one of:

- a certificate whose role is top-level (PGSS §7.6)
- a revocation (PGSS §7.12)
- a distrust entry (PGSS §7.13)

Entries are in no required order, and an object that appears twice
counts once. The image is not signed.

## 6.3.1 When the kernel reads it

The kernel reads the image once, from the root filesystem it has when
it is about to run its first program, and before it runs that program.
On a system that boots through an initramfs, that is the initramfs, so
the image has to be in it (PSPU §5.28).

The kernel MUST NOT read the image again. Every later change arrives
through ktrust (§6.5).

## 6.3.2 How the kernel treats each top-level

For each top-level, in the image or added later, the kernel reads the
`issuer` field and does one of three things:

- **The issuer is the key hash of a root the kernel holds.** The kernel
  verifies the signature under that root. If it verifies, the top-level
  is enabled and rooted. If it does not, the kernel rejects the entry.
- **The issuer is the key hash of the certificate's own key.** The
  kernel verifies the signature under that key. If it verifies, the
  top-level is enabled and unrooted. If it does not, the kernel rejects
  the entry.
- **The issuer is anything else.** The kernel has no key to check the
  signature with. The top-level is enabled and unrooted.

A store keeper never tells the kernel which of these applies. The
kernel decides from the certificate alone.

> [!NOTE]
> A flag saying "this one is rooted" would be one more thing the
> kernel had to believe, on the one question a signature can answer
> outright.

## 6.3.3 A missing or damaged image

If the image is absent, the store starts empty.

If the image is malformed as a whole, with a bad header, a length that
runs past the end of the file, or bytes after the last entry, the kernel
MUST treat the store as empty and MUST report the failure.

If a single entry is malformed, is of a kind the image does not hold,
or is rejected as this article describes, the kernel MUST skip that
entry, keep the rest, and report it.

An empty store enables no top-level, so no chain is rooted. Where the
kernel requires a rooted chain to run its first program, a system with
a missing or damaged image does not boot, and is repaired from outside.

## 6.3.4 Writing the image

A store keeper MUST write the image whenever the store changes, and
MUST replace it in one step, so that a reader never finds a partial
file.

The image a kernel reads at boot can be older than the store on disk,
because an initramfs is built ahead of time. A store keeper MUST bring
the kernel up to date when it attaches (§6.5).

> [!NOTE]
> The image depends on the protection of the file for everything a
> signature does not cover: which unrooted top-levels are in it, and
> which distrust entries. A party able to alter boot files can alter
> those. Root-signed top-levels and revocations prove themselves and
> cannot be forged this way, only left out.

---

# 6.4 The Channel

_Peios Specifications / PSPK / Trust Store Interface_

> Attaching to /dev/pkm_trust, the privilege and the TrustStore warrant the open handler demands, the single connection, and what survives a store keeper that exits.

## 6.4.1 The device

A store keeper attaches by opening the character device
`/dev/pkm_trust`.

The `open()` handler requires both of the following, and fails `EPERM`
otherwise:

- The calling thread's effective token holds `SeTcbPrivilege`, and the
  privilege is enabled, not merely present.
- The calling process's executable verified as Rooted (PGSS §7.14), and
  its leaf holds the `TrustStore` warrant.

The device has one connection. While a store keeper has it open,
another `open()` fails `EBUSY`.

## 6.4.2 The TrustStore warrant

`TrustStore` is a warrant in the sense of PGSS §7.5.

| Name | Type | Allow Equal | `flags` | Meaning |
|---|---|---|---|---|
| `TrustStore` | Set, empty | Set | `0x80` | The holder can change the kernel's trust store |

> [!NOTE]
> Privilege alone would let any program an administrator can run with
> that privilege enable a trust anchor. The warrant ties the power to
> a program that a root vouches for, so that changing what the system
> trusts takes more than being the administrator.

## 6.4.3 Lifetime

Closing the descriptor, or the store keeper exiting, ends the
connection and nothing else. The kernel keeps the store exactly as it
is, and continues to apply it. A store keeper that attaches afterward
finds the store as the last one left it.

The kernel authenticates each store keeper by the two conditions of
this article, and keeps no record of which process held the connection
before.

---

# 6.5 Operations

_Peios Specifications / PSPK / Trust Store Interface_

> The five ktrust ioctls for adding, removing, and listing store objects and for listing and fetching seen certificates, their argument structures, their errors, and how a store keeper reconciles after attaching.

A store keeper issues every operation as an ioctl on the device
descriptor. Each takes a pointer to one structure. Reserved fields MUST
be zero, and the kernel fails `EINVAL` if one is not.

| Ioctl | Purpose |
|---|---|
| `KTRUST_ADD` | Add one object to the store |
| `KTRUST_REMOVE` | Remove one object from the store |
| `KTRUST_LIST` | List the objects of one kind |
| `KTRUST_SEEN_LIST` | List the seen certificates |
| `KTRUST_SEEN_GET` | Fetch one seen certificate |

## 6.5.1 Generation

The kernel holds a `u64` generation, which starts at 1 once the store
image is read and rises by one for each `KTRUST_ADD` or `KTRUST_REMOVE`
that changes the store. Every operation that reads or changes the
store returns the generation as it stands when the operation
completes.

## 6.5.2 KTRUST_ADD

The argument is a `ktrust_add_args`.

| Field | Type | Description |
|---|---|---|
| `object_ptr` | `u64` | Address of the object |
| `object_len` | `u32` | Length of the object |
| `_pad` | `u32` | Reserved |
| `generation` | `u64` | Out: the generation |

The object is a top-level certificate, a revocation, or a distrust
entry. The kernel treats it exactly as it treats an entry of the store
image (§6.3).

Adding an object the store already holds succeeds and changes nothing.

| Error | Meaning |
|---|---|
| `EINVAL` | The object is malformed, or is not one of the three kinds |
| `EKEYREJECTED` | A top-level's signature does not verify |
| `ENOSPC` | The store is at a limit (§6.A) |

The kernel does not require proof that a revocation applies to
anything. It keeps the revocation and applies it to a chain when
PGSS §7.12 says it applies. Showing that a revocation is worth keeping
is the store keeper's (PGSS §7.12).

## 6.5.3 KTRUST_REMOVE

The argument is a `ktrust_remove_args`.

| Field | Type | Description |
|---|---|---|
| `kind` | `u8` | `0x01` for a top-level, `0x05` for a distrust entry |
| `_pad` | `u8[7]` | Reserved |
| `hash` | `u8[64]` | The top-level's object hash, or the hash a distrust entry distrusts |
| `generation` | `u64` | Out: the generation |

| Error | Meaning |
|---|---|
| `EINVAL` | `kind` is neither value |
| `EPERM` | `kind` is `0x04`: a revocation is never removed |
| `ENOENT` | The store holds no such object |

## 6.5.4 KTRUST_LIST

The argument is a `ktrust_list_args`.

| Field | Type | Description |
|---|---|---|
| `kind` | `u8` | `0x01`, `0x04`, or `0x05` |
| `_pad` | `u8[7]` | Reserved |
| `cursor` | `u64` | In: 0 to start, or the value last returned. Out: the value to continue with |
| `buf_ptr` | `u64` | Address of a buffer for entries |
| `buf_len` | `u32` | Length of the buffer |
| `count` | `u32` | Out: the number of entries written |
| `generation` | `u64` | Out: the generation |

The kernel writes whole `ktrust_entry` structures, as many as fit. A
`count` of 0 means the list is complete.

| Field | Type | Description |
|---|---|---|
| `hash` | `u8[64]` | A top-level's or revocation's object hash, or the hash a distrust entry distrusts |
| `detail` | `u8` | For a top-level, `0x01` rooted or `0x02` unrooted. Otherwise the entry's `target_type` |
| `_pad` | `u8[7]` | Reserved |

If the generation changes between two calls of one listing, the
listing might repeat or miss an entry. A store keeper that needs a
consistent view MUST start again.

## 6.5.5 KTRUST_SEEN_LIST

The kernel records every certificate it verifies as part of a chain,
whether the certificate came from a bundle, from a directory of
intermediaries, or from the store. The record lasts until the system
restarts. Leaves are not recorded.

The argument is a `ktrust_seen_list_args`.

| Field | Type | Description |
|---|---|---|
| `cursor` | `u64` | As for `KTRUST_LIST` |
| `buf_ptr` | `u64` | Address of a buffer for entries |
| `buf_len` | `u32` | Length of the buffer |
| `count` | `u32` | Out: the number of entries written |

Each entry is a `ktrust_seen_entry`.

| Field | Type | Description |
|---|---|---|
| `hash` | `u8[64]` | The certificate's object hash |
| `issuer` | `u8[64]` | The certificate's `issuer` field |
| `top_level` | `u8[64]` | The object hash of the top-level it was last verified under |
| `use_count` | `u64` | Verifications that passed through it |
| `first_seen` | `u64` | Nanoseconds since boot at the first |
| `last_seen` | `u64` | Nanoseconds since boot at the most recent |
| `live` | `u32` | Processes running under a chain that passes through it |
| `_pad` | `u32` | Reserved |

## 6.5.6 KTRUST_SEEN_GET

The argument is a `ktrust_seen_get_args`.

| Field | Type | Description |
|---|---|---|
| `hash` | `u8[64]` | The certificate's object hash |
| `buf_ptr` | `u64` | Address of a buffer for the certificate |
| `buf_len` | `u32` | Length of the buffer |
| `object_len` | `u32` | Out: the certificate's length |

| Error | Meaning |
|---|---|
| `ENOENT` | No such certificate has been seen |
| `ERANGE` | The buffer is too small. `object_len` holds the length needed |

## 6.5.7 Reconciling after attaching

The kernel's store at the moment a store keeper attaches is whatever
the image held at boot, plus whatever earlier store keepers added. A
store keeper MUST then make it match the trust store it reads from
disk:

1. List each kind.
2. Add every top-level, revocation, and distrust entry the trust store
   holds and the kernel does not.
3. Remove every top-level and distrust entry the kernel holds and the
   trust store does not.

A store keeper MUST NOT treat a revocation the kernel holds and the
trust store does not as an error. It adds that revocation to the trust
store (PGSS §7.12).

---

# 6.6 Notifications

_Peios Specifications / PSPK / Trust Store Interface_

> The fixed-size records a store keeper reads from the device, telling it that a certificate was verified for the first time or that it has to list again.

The kernel tells a store keeper of events by records it reads from the
device descriptor.

A `read()` returns one or more whole `ktrust_notification` records and
never part of one. A blocking read waits for a record. Under
`O_NONBLOCK`, a read with nothing queued fails `EAGAIN`. The descriptor
supports `poll()`.

| Field | Type | Description |
|---|---|---|
| `type` | `u32` | What happened |
| `_pad` | `u32` | Reserved |
| `hash` | `u8[64]` | The object the record concerns, or zero |

| `type` | Name | Meaning |
|---|---|---|
| 1 | First seen | A certificate was verified for the first time since boot. `hash` is its object hash |
| 2 | Overflow | Records were dropped, or the record of seen certificates is full. `hash` is zero |

The enumeration is closed (§6.7).

The kernel queues a bounded number of records (§6.A). If the queue
fills, the kernel drops records and queues one Overflow in their place.
A store keeper that reads an Overflow MUST list the seen certificates
again to learn what it missed.

A store keeper that is not attached misses nothing it cannot recover:
the record of seen certificates is complete since boot, whenever the
store keeper attaches.

> [!NOTE]
> A notification is a hint to look, not a log. The kernel reports
> verification outcomes as events, and a store keeper that wants a
> history reads them there.

---

# 6.7 Extension

_Peios Specifications / PSPK / Trust Store Interface_

> How the Trust Store Interface grows, through new ioctls and new notification types, and why its structures and the store image do not change in place.

## 6.7.1 Additive changes

A new operation is a new ioctl. A store keeper that does not issue it
is unaffected, and a kernel that does not implement it fails `ENOTTY`,
which a store keeper MUST treat as "not supported" and not as a
failure of the connection.

## 6.7.2 Changes requiring a version

The structures of §6.5 and §6.6 do not grow. A change to one is a new
ioctl with a new structure.

The notification `type` enumeration is closed. A store keeper MUST
ignore a record whose `type` it does not recognize, and a kernel adds a
type only together with an ioctl by which a store keeper asks for it.

The store image carries the format version of PGSS §7.4 in its header.
A kernel MUST treat an image whose version it does not implement as
malformed as a whole (§6.3).

## 6.7.3 Reserved space

Every `_pad` field is reserved. A store keeper MUST write zero, and the
kernel fails `EINVAL` otherwise. The kernel writes zero in every `_pad`
field it returns.

---

# 6.8 Conformance

_Peios Specifications / PSPK / Trust Store Interface_

> The obligations of a store keeper toward the kernel, gathered in one place, with what the kernel guarantees in return and what a store keeper is free to do.

## 6.8.1 A conforming store keeper

- Writes the store image whenever the store changes, and replaces it in
  one step (§6.3).
- Puts in the image, and adds through ktrust, only top-level
  certificates, revocations, and distrust entries (§6.3, §6.5).
- Never tells the kernel whether a top-level is rooted, and relies on
  the kernel's own decision (§6.3).
- Reconciles the kernel's store with the trust store each time it
  attaches (§6.5).
- Starts a listing again if the generation changes during it, where it
  needs a consistent view (§6.5).
- Lists the seen certificates again after an Overflow (§6.6).
- Writes zero in every reserved field (§6.7).

## 6.8.2 What the kernel guarantees

- It reads the image once, before it runs its first program, and never
  again (§6.3).
- It verifies every signature it holds a key for, and rejects an object
  that fails (§6.3, §6.5).
- It never removes a revocation (§6.5).
- It keeps the store when a store keeper detaches (§6.4).
- It records every certificate it verifies, from boot, up to the limit
  of §6.A (§6.5).

## 6.8.3 What conformance does not require

Conformance does not require a store keeper to stay attached, to read
notifications, or to use the record of seen certificates at all. It
does not say how a store keeper obtains an administrator's approval,
which is PGSS §7.10, or how the image reaches the filesystem the kernel
boots from.

---

# Appendix 6.A Limits

_Peios Specifications / PSPK / Trust Store Interface_

> The size and count limits of the Trust Store Interface in one table, covering the store image, the store's three sets, the seen certificates, and the notification queue.

| Limit | Value | Defined in |
|---|---|---|
| Size of the store image | 64 MiB | §6.3 |
| Top-levels in the store | 4096 | §6.5 |
| Revocations in the store | 1,048,576 | §6.5 |
| Distrust entries in the store | 65,536 | §6.5 |
| Seen certificates recorded | 65,536 | §6.5 |
| Notifications queued | 1024 | §6.6 |

An image over its size limit is malformed as a whole (§6.3). An object
that would take a set past its limit is refused with `ENOSPC` when
added (§6.5), and skipped when it is an entry of the image (§6.3). A
certificate that would take the record of seen certificates past its
limit is not recorded, and the kernel queues an Overflow (§6.6).

---

# 1.1 Scope

_Peios Specifications / PSPU / Introduction_

> What PSPU is — the protocols and interchange formats the foundational userspace components speak to each other — and why they are specific to Peios.

This document defines the **Peios System Protocols Userspace (PSPU)**:
the protocols and interchange formats by which the foundational
userspace components of a Peios system agree with one another.

An interface belongs in this document when both of these hold:

- it is a contract between userspace parties, at least one of which is a
  component the system is built from rather than an application running
  on it; and
- the interface is public — a third party is expected to implement one
  side of it.

The parties need not exist at the same moment. A live protocol has two
processes in conversation; an interchange format has a producer and a
consumer that never meet, and the artifact between them carries the
contract. Both are in scope, because what makes something belong here is
that two independently written parties must agree on it.

## 1.1.1 These protocols are specific to Peios

The components that speak these protocols are one answer to a problem,
not the definition of the platform. A system that solves the same
problem with different components has no use for the protocols between
them. That is what separates this document from PGSS, whose standards
another system could adopt as they stand.

They are specified because they are *public* even so. A third party
writing a component to plug into one side of one of these protocols needs
the contract written down, and needs it to stay put.

For each interface, this document covers:

- for a live protocol: the channel, its direction, which party connects
  to which, message framing and encoding, the messages exchanged, and
  the shape of a conversation
- for an interchange format: the layout of the artifact, how it is
  identified and versioned, and how a consumer validates one it receives
- how a party announces itself or is identified, and how its counterpart
  establishes what it is and what it may speak for
- the rules under which the format may be extended
- what each party must declare about itself, and what its counterpart
  validates rather than believes
- the conformance requirements for each role

This document does not cover:

- Standards another system could adopt — defined in PGSS
- Protocols spoken across the kernel boundary — defined in PSPK
- The binary structures these interfaces carry — defined in PCDS
- How a component stores its data, reaches the answers it gives, or
  produces the artifacts it emits — its own design
- Which counterparts a system is configured to trust, and how that
  configuration is expressed — the consuming component's own design
- Administering a component's contents — its own design, unless the
  component publishes a protocol for other programs to administer it
  with, as the local principal store does (§10)

The fourth of those is the point of the whole document. A component is
asked a question and gives an answer, or is asked for an artifact and
produces one; how it arrives there is exactly what different components
exist to do differently.

## 1.1.2 Stability

Publication here is a commitment that the contract is written down and
will not change out from under an implementation. Each specification
states its own rules for extending its wire or file format; those rules
are the supported way for an interface to grow.

---

# 1.2 Conventions

_Peios Specifications / PSPU / Introduction_

> The normative keywords PSPU uses, and the shared conventions it inherits from the PCSA conventions book.

The key words MUST, MUST NOT, SHOULD, SHOULD NOT, and MAY in this
document are to be interpreted as described in RFC 2119. Text set off as
a note is informative, not normative.

Everything else — roles, byte order, sizes, layout tables, notation,
strings, timestamps, citation, and the external standards this anthology
depends on — is defined in the Conventions book and is not restated
here. PSPU departs from none of it.

Where a chapter needs a convention of its own, that chapter states it.

---

# 2.1 Scope and Roles

_Peios Specifications / PSPU / Principal Source Interface_

> What PSI specifies — how an authentication authority federates identity to separate processes that hold it — and its two roles.

This chapter specifies the **Principal Source Interface (PSI)**: the
protocol by which an authentication authority federates identity to
separate processes that hold it.

Two roles participate.

The **authority** is the process that mints tokens and creates logon
sessions. It is the party asking. On PSI it listens; it never dials out
(§2.3). It is also the party that speaks PGSS Logon to its clients, and
PSI exists so that it can answer them.

The **source**, in full a *principal source*, is a process that is
authoritative for some set of principals: it verifies their credentials
and says who they are. The source role is publicly implementable: any
process an authority has been configured to accept MAY register as a
source, and a third party writing one for a directory, a hardware token
service or an identity provider is the case this chapter is written for.
A conforming source is the subject of the source obligations in §2.22.

A source is not a *store*, necessarily. A local source owns its bytes; a
directory-backed source owns nothing and forwards the question. The
interface deliberately does not distinguish them, which is why the term
is "source" rather than "store".

What a source is emphatically **not** is a component of the authority.
It runs as a separate process, at lower trust, and it cannot mint
anything (§2.4).

This chapter covers:

- the channel, its direction, and why sources connect inward (§2.3,
  §2.6)
- message framing, the conversation identifier, and the rules under
  which the format may be extended (§2.7)
- registration: how a source announces itself, how the authority
  establishes what it is, and what domain it may speak for (§2.8 to
  §2.10)
- the relayed interrogation, and its relationship to PGSS Logon (§2.5,
  §2.12)
- assertion and refusal, the terminal messages of a source conversation
  (§2.13)
- querying a source outside a logon, so that an authority can serve
  PGSS Logon's identity lookup (§2.15, §2.16)
- what a source must declare about itself before an authority may cache
  its answers (§2.8, §2.17)
- scope: what a source may claim about identity, separately about
  membership, and separately again about POSIX identifiers (§2.18 to
  §2.20)
- relaying a principal's change of their own credential to the source
  that holds it (§2.21)
- the obligations binding on each role (§2.22)
- relaying a principal's addition or removal of one of their own
  credentials, such as an SSH public key, to the source that holds it
  (§2.23)

This chapter does not cover:

- The logon protocol itself, specified in PGSS.
- Tokens, SIDs, sessions and privileges — described in the Peios Kernel
  TRM, with SIDs, security descriptors and claim attributes specified
  in PCDS.
- How a source stores identity, or verifies a credential.
- Derivation — what a token ends up containing — which is the
  authority's, applying local policy (PGSS §2.1).
- Which sources a machine trusts, and how that is configured.
- Which identifier range a source is given, and how that is configured.
  The *rules* the assignment must satisfy are §2.20.
- Administering a source's contents.

The third of those is the point of the whole interface. A source is
asked a question and gives an answer; how it reaches the answer is
exactly what different sources exist to do differently.

## 2.1.1 PSI is not a generic standard

PGSS Logon is a Peios Generic System Standard: another system could
adopt it, and software written for Peios relies on it. **PSI is not.**
It is the interface an authority uses to reach the processes that know
who exists, and a system running entirely different authentication
infrastructure has no use for it.

It is specified because it is a *public* interface even so. A third
party writing a principal source needs the contract written down, and
needs it to be stable.

> [!NOTE]
> The distinction shows up in what happens when a system leaves each
> out. Without PGSS Logon, software written for Peios has no way to
> sign anyone in. Without this chapter, the system has an authority
> that federates differently, or does not federate at all, which is a
> design choice nobody will dispute.

---

# 2.2 Terminology

_Peios Specifications / PSPU / Principal Source Interface_

> Terms this chapter borrows unchanged from the Peios Kernel TRM, PCDS and PGSS Logon.

Terms defined in the Peios Kernel TRM (token, logon session, privilege),
in PCDS (SID, security descriptor, claim attribute) and in PGSS
(authority, client, principal, conversation, round, credential material,
prompt, derivation) are used here with the same meaning and are not
redefined.

**Source.** A process that is authoritative for some set of principals:
it verifies their credentials and says who they are. Called a *principal
source* in full.

**Registration.** The exchange in which a source announces itself and the
authority decides whether to accept it. Precedes any conversation.

**Domain.** The SID namespace a source is authoritative for. Every
principal a source may assert lives under it. See §2.10.

**Source conversation.** One logon's exchange between the authority and a
source, distinguished from other concurrent ones by a conversation
identifier. Not to be confused with a PGSS Logon conversation, which is
between a client and the authority; one of each exists per logon.

**Assertion.** A source's terminal message stating who a principal is.
The only successful outcome a source can produce.

**Originator.** The verified identity of the process that requested a
logon, as established by the authority from the client's connection.
Relayed to the source, which cannot learn it any other way.

**Service SID.** A SID derived from a service's name, placed in that
service's token by the init system, and unforgeable by anything else.
How a source's identity is established (§2.9).

**Membership scope.** The constraint on which groups a source may
assert. Separate from **identity scope**, which constrains whose
identity it may assert at all. Sections 2.18 to 2.20 exist because these
are different questions with different answers.

**Relative identifier.** In this chapter, a POSIX identifier as a source
states it: an offset within the range the authority assigned that
source, never an absolute number (§2.20). Where the SID sense is meant —
the last sub-authority of a SID — the text says so.

---

# 2.3 Sources Dial In

_Peios Specifications / PSPU / Principal Source Interface_

> The authority never dials a source; sources connect inward. The most consequential shape decision in the chapter, and what it buys.

**The authority listens. Sources connect to it.** The authority never
initiates a connection to a source.

This is the most consequential shape decision in this chapter, and it is
worth being explicit about what it buys.

## 2.3.1 Why the direction matters

The authority holds the privilege to mint tokens. It is the most
privileged userspace process on the system. An authority that dialled
out would need, in its configuration, a list of paths to connect to —
and a process holding that privilege having a configurable list of
things to go and talk to is a liability out of proportion to the
convenience.

Because sources connect inward, the authority's sockets are
`accept()`-only. It never opens an outbound connection to anything, for
any reason.

## 2.3.2 What follows

**Restart is the source's problem.** A source whose connection drops
reconnects. The authority does not retry, does not queue, and does not
track sources it has not heard from. A source that has gone away is
simply not registered.

**A source is not required to exist.** An authority with no registered
sources cannot authenticate anybody, and that is a coherent state rather
than an error — it means no identity has been made available to it yet.

**Ordering is the init system's problem.** The authority must be
listening before a source can register, and a service that depends on
authentication must start after a source has. Expressing that is a
service-ordering question, not a protocol one, and this chapter says
nothing about it.

> [!NOTE]
> A source SHOULD report itself ready only once its registration has
> been *acknowledged*, so that "the source is running" and "the source
> can authenticate" are the same statement to anything ordered after it.
> This is what makes the `Registered` acknowledgment load-bearing
> despite carrying almost nothing.

---

# 2.4 Assert, Never Mint

_Peios Specifications / PSPU / Principal Source Interface_

> A source says who somebody is and nothing else — the structural reason a compromised source cannot grant itself privilege.

A source says **who somebody is**. It cannot say anything else, and the
protocol is built so that this is structural rather than a rule anyone
has to remember.

## 2.4.1 The success terminal

PGSS Logon's success terminal is `AccessGranted`, carrying a session
identifier and a token descriptor. If PSI reused it, sources would be
minting sessions.

PSI's success terminal is `Assertion` (§2.13), which carries an
identity: a SID, a canonical name, and group memberships. **There is no
session identifier and no descriptor to attach a token to.** A source
could not mint one if it wanted to, because there is no message in which
to say so.

That is the whole of the mechanism. No capability check, no trust level,
no configuration flag — a source cannot mint because the protocol gives
it no way to express minting.

## 2.4.2 What the authority keeps

Everything else:

- **Derivation.** What the token actually contains — its privileges, its
  integrity level, its derived group memberships, its projected
  identifiers — is the authority's, applying local policy (PGSS §2.1).
- **Session creation.** The logon session, and the record of which
  source vouched for it.
- **Validation.** Every SID a source sends is bytes until the authority
  has checked it (§2.13).
- **Scope enforcement.** What a source is permitted to claim (§2.18 to
  §2.20).
- **Peer verification.** On every connection it accepts.
- **Rate and round limits**, and the policing of what a source may ask a
  client for (§2.12).

## 2.4.3 Why a compromised source is bounded

A source that is entirely compromised can lie about the principals in
its own domain. It cannot mint a token, cannot elevate anyone's
privileges, cannot claim identities outside its domain (§2.18), and —
unless configured otherwise — cannot assert memberships outside it
either (§2.19).

That bound is the reason for the process boundary. It is not that
sources are expected to be malicious; it is that a source is the
component parsing credentials from the outside world, and therefore the
one most likely to be wrong.

---

# 2.5 A Superset of PGSS Logon

_Peios Specifications / PSPU / Principal Source Interface_

> A source is an authority for its own slice of the world, which is why most of PSI is PGSS Logon — and where the two deliberately diverge.

A principal source *is* an authentication authority for its slice of the
world. The authority that federates is an authority over authorities.
Once that is seen, most of PSI writes itself.

## 2.5.1 The relationship

PSI's interrogation phase is **PGSS Logon's, with identical message
bodies**. `CredentialRequest` and `CredentialResponse` carry exactly the
bytes PGSS §2.8 defines, and the authority relays them nearly verbatim
in both directions.

The consequences are worth stating plainly:

- **The source decides what to ask for.** Not the authority. The
  authority does not know what credentials a source requires, and does
  not need to.
- **The authority becomes a relay** in the interrogation phase. It is a
  shorter path than synthesising its own prompts, not a longer one.
- **Adding a credential type is a change to sources**, not to the
  authority and not to clients, which already render what they are given
  (PGSS §2.3).
- **A source could be tested in isolation** by pointing a PGSS Logon
  client at it, for the interrogation phase at least.

## 2.5.2 Where they diverge, deliberately

Three differences, each for a stated reason.

**The success terminal.** `Assertion` rather than `AccessGranted`, so
that a source cannot mint. See §2.4. This is the divergence that
matters.

**Multiplexing.** PGSS Logon is one conversation per connection; the
connection *is* the conversation. PSI carries many concurrent logons
over one long-lived connection, so its header adds a conversation
identifier (§2.7). The alternative — serializing every logon behind one
connection — would make any slow logon a system-wide login stall.

**Distinct magic.** `PPSI` rather than `PGSL`. Two protocols this
similar sharing a codec is a cross-protocol hazard: a socket plugged
into the wrong daemon would *partially* work, which is far worse than
failing outright. The magic makes it a hard error on byte zero.

The full accounting of what is shared, what is added and what differs is
§2.C.

## 2.5.3 "Just relaying" is loose

The authority is a relay in the interrogation phase only, and even there
it is not passive. It polices what a source may ask a client for
(§2.12), it validates what a source asserts (§2.13), and it enforces
scope (§2.18 to §2.20). Everything before and after the interrogation is
entirely its own.

---

# 2.6 The Channel

_Peios Specifications / PSPU / Principal Source Interface_

> The PSI socket, its access control, why connections are long-lived, and what happens when one fails.

## 2.6.1 Socket

An authority that federates over PSI MUST listen on a `SOCK_STREAM` Unix
domain socket.

Unlike PGSS Logon's path, this one is **not normative**. PSI is not a
generic standard (§2.1), and an authority that offers it can put it
where it likes provided its sources are told. Mainline's is
`/run/psi.sock`.

## 2.6.2 Access control

The socket SHOULD carry a security descriptor. It is **DoS protection
and nothing more**, and an implementation MUST be written as though it
were absent.

The reason is that the socket cannot be the boundary. What establishes a
source's identity is the peer's token (§2.9), which is checked on every
connection. A descriptor that kept casual traffic away would be a
convenience; a descriptor *relied upon* would be a second, weaker access
control that someone will eventually assume is doing the work.

An authority MUST therefore bound the number of unregistered connections
it will hold open, and the time it will wait for a registration,
independently of any descriptor.

> [!NOTE]
> An unauthorized peer is refused at the identity check, which is cheap,
> and the connection cap bounds what it can occupy in the meantime. That
> is the whole of what the descriptor's absence costs.

## 2.6.3 Long-lived connections

A source's connection persists for the life of the source and carries
every logon routed to it.

An authority MUST bound the number of registered sources and the number
of concurrent conversations per source. A source MUST bound the
conversations it will track, and MUST NOT depend on the authority's
bookkeeping to do it — a source that trusted the authority's limit would
be trusting a bound it cannot verify.

## 2.6.4 Failure

A framing error is **fatal to the connection**, not to a conversation.
Once a message has failed to parse there is no way to know where the
next one starts, so both parties MUST tear the connection down rather
than attempt resynchronisation.

A failed write is likewise fatal. A partial write desynchronises the
stream just as a bad frame does, and treating it as a per-conversation
error would leave a corrupt connection in use.

Ordinary semantic failures — an unknown principal, a bad credential, a
refused logon — are **not** connection failures. They are `Refusal`
messages (§2.13) and the connection continues.

---

# 2.7 Message Framing

_Peios Specifications / PSPU / Principal Source Interface_

> The 20-byte header — the first twelve bytes are PGSS Logon's, unchanged — plus conversation identifiers, size limits and SIDs on the wire.

## 2.7.1 Header

Every message begins with a 20-byte header:

| Offset | Size | Field | Value |
|---|---|---|---|
| 0 | 4 | `magic` | `PPSI` (`50 50 53 49`) |
| 4 | 2 | `version` | `3` |
| 6 | 2 | `msg_type` | See §2.A |
| 8 | 4 | `total_len` | Header plus body, in bytes |
| 12 | 8 | `conversation` | See below |

The first twelve bytes are PGSS Logon's header, unchanged and at the
same offsets. `total_len` in particular sits where PGSS §2.6 puts it,
which is what lets one transport implementation frame either protocol
off a stream.

## 2.7.2 Magic

`PPSI`, checked on every message, fatal to the connection when wrong.

This matters more here than it would for an unrelated protocol, because
PSI and PGSS Logon **share message bodies** (§2.5). A
`CredentialRequest` from one is byte-identical to the other's. Without
distinct magic, a socket plugged into the wrong daemon would decode
several fields correctly before going wrong — which is the failure mode
hardest to diagnose and easiest to miss.

## 2.7.3 Conversation identifier

The `conversation` field distinguishes concurrent logons on one
connection.

- **Conversation `0` is reserved** for connection-level messages:
  `Register`, `Registered` and `Changed` (§2.17). It MUST NOT be used
  for a logon or a query.
- Logon and query conversations use identifiers from 1 upward, drawn
  from one space.
- The **authority allocates** them. A source MUST NOT invent one, and
  MUST reply on the identifier it was given.
- An identifier is unique among *live* conversations on one connection.
  An authority MAY reuse one after a conversation has reached a terminal
  state.

A source MUST reject a message on a conversation it does not know, and
MUST NOT treat it as opening a new one. Only `Authenticate` (§2.11),
`Query` (§2.15) and `EnumerateSource` (§2.16) open one, and an authority
MUST NOT open one with an identifier already live.

Rejecting means declining to act on it. A source MUST NOT reply on a
conversation it does not know: an authority MAY have reused the
identifier after a terminal state, so a reply could arrive as a second
terminal message for a conversation that has already ended. Discarding
it, and recording that it happened, is the whole of the obligation.

A source MUST likewise refuse an `Authenticate`, `Query` or
`EnumerateSource` arriving on conversation `0`, which is reserved.

## 2.7.4 Size limit

A message MUST NOT exceed **81920 bytes** — larger than PGSS Logon's
ceiling, because a PSI message wraps one.

## 2.7.5 Message direction

The high bit of `msg_type` marks a message sent by **the source**. This
follows PGSS Logon's convention that the bit marks the authority for the
matter at hand: on this interface the source is the authority for its
own principals, and the logon authority is the one asking.

## 2.7.6 Encoding

PSI shares its codec with PGSS Logon, and PGSS §2.6's encoding rules
apply here unchanged: little-endian multi-byte integers; UTF-8 strings,
length-prefixed and never NUL-terminated; length-framed structures and
array elements, skipped to their declared end; `u32` element counts on
arrays, with stated maxima binding on encoder and decoder alike.

### 2.7.6.1 SIDs on the wire

SIDs are carried as **opaque bytes**, in the binary self-relative form
PCDS specifies, never as text.

They are opaque *to the codec*, which has no business knowing what a SID
is. They are emphatically not opaque to the authority, which MUST
validate every SID it receives before treating it as identity (§2.13).
The obligation to check sits in the process that mints tokens, not in
the layer that moves bytes.

A SID MUST NOT exceed 68 bytes — the eight-byte prelude plus fifteen
sub-authorities, which is the most the encoding's one-byte count admits.

## 2.7.7 Body extensibility

The extensibility rules of PGSS §2.6 apply unchanged: fields are
appended only, a new field is optional with a safe default, and a new
enumeration value is a breaking change requiring a version bump. The one
exception is the capability bitmask of §2.8, for the reason given in
§2.B.

One PSI-specific application deserves stating. `Authenticate` (§2.11)
**nests** the shared `AuthenticationRequest` inside its own length frame rather than
inlining its fields. The obvious encoding — shared fields, then
PSI's — is wrong: the shared request belongs to PGSS Logon and grows on PGSS
Logon's schedule, so a field appended there would silently displace the
field after it. Nesting lets the two evolve independently.

The same reasoning applies to every shared body PSI carries, and §2.C
lists them.

## 2.7.8 Initial unpublished layout replacement

The coordinated SSH credential extension replaced the unpublished version-1
layout without retaining older codecs. Current LogonStart capability,
required-method and binding fields, Prompt parameters, and all current
Assertion fields are mandatory, including explicit empty/zero values.
Omitted mandatory fields fail decoding. The compatibility rules above apply
to future extensions of this replacement contract; they do not require
accepting the superseded development layout. See PGSS Logon §2.D.

Version 3 carries PGSS credential type 3, Mschapv2, and appends the
mandatory length-framed `mschapv2_success` field to Assertion (§2.13).
The field is empty for other methods and contains the 20-byte
AuthenticatorResponse only when the source successfully verifies an
MSCHAPv2 proof.

Version 4 carries PGSS credential type 4, Ntlmv2. It appends the
mandatory `has_presented` flag and optional `presented` proof to
Authenticate (§2.11), and the mandatory length-framed
`ntlmv2_session_key` field to Assertion (§2.13). Source and authority
MUST use this coordinated version.

---

# 2.8 Registration

_Peios Specifications / PSPU / Principal Source Interface_

> The first message on every connection — the source's name, domain, capabilities, TTL, batch limit and the identifier range it is granted.

A connection opens with registration. Nothing else may precede it.

## 2.8.1 Register

`msg_type` = `0x8001`. Source to authority, on conversation `0`.

| Field | Encoding | Limit |
|---|---|---|
| `source_name` | string | 32 bytes |
| `domain` | length-framed bytes (SID) | 68 bytes |
| `capabilities` | `u32` | §2.B |
| `entry_ttl` | `u32` | seconds |
| `max_batch` | `u32` | 64 |

### 2.8.1.1 source_name

What the source calls itself. Bounded at 32 bytes because it becomes the
authentication-package name on every session the source authenticates —
so a token's provenance answers *which source vouched for this?* rather
than merely *the authority minted it*.

The name is a **claim**. It MUST be cross-checked against the identity
the authority established for itself (§2.9), and it MUST NOT be used for
anything else. A mismatch MUST be refused rather than quietly corrected:
a service registering under another's name is worth failing on, not
normalizing.

### 2.8.1.2 domain

The SID namespace this source is authoritative for (§2.10).

### 2.8.1.3 capabilities

What the source can do beyond authenticating.

| Bit | Name | Meaning |
|---|---|---|
| 0 | `QUERIES` | Answers `Query` (§2.15). |
| 1 | `ENUMERATES` | Answers `EnumerateSource` (§2.16). |
| 2 | `MEMBERS` | Can produce a group's membership. |
| 3 | `PUSHES_CHANGES` | Sends `Changed` (§2.17). |
| 4 | `CHANGES_CREDENTIALS` | Answers `ChangeCredential` (§2.21). |
| 5 | `ENROLLS_CREDENTIALS` | Answers `EnrollCredential` (§2.23). |

An authority MUST NOT send a message a source did not declare it
answers, and MUST NOT set a field bit gating a capability the source did
not declare. A source declaring nothing authenticates and does nothing
else, which is what a source predating these fields is saying by
omission — and is the only reading that keeps such a source working.

A source that declares no `QUERIES` cannot be asked about its principals
outside a logon, so they are unresolvable through PGSS Logon's identity
channel: they can sign in and will appear as bare numbers everywhere
else. That is a coherent configuration and this chapter permits it, but
it is almost never what an administrator intended, and an authority
SHOULD report it where one will see it — as it reports a source
registering with no identifier range.

This is a declaration of capability, not of willingness. A source
declaring `QUERIES` may still answer `Refused` to any particular
question (§2.15); a source declaring `ENUMERATES` may still refuse a
cursor it can no longer honor (§2.16).

### 2.8.1.4 entry_ttl

How long, in seconds, the authority may hold an answer from this source
before asking again.

**Zero means do not cache.** A source declaring neither
`PUSHES_CHANGES` nor a non-zero `entry_ttl` has said its answers must
not be held at all, and an authority MUST honor that — see §2.17, where
the reasoning for reading silence that way is set out.

`entry_ttl` and `PUSHES_CHANGES` are not exclusive, and a source
declaring the second SHOULD declare a non-zero first as well. See §2.17:
the TTL is the backstop against a notification that was never sent.

### 2.8.1.5 max_batch

The largest number of keys the source will accept in one `Query`
(§2.15). Zero means one.

An authority MUST NOT exceed it, and MUST NOT send more than 64 keys
whatever the source declared: an encoder MUST NOT declare more, and a
decoder MUST read a larger declaration as 64.

A source MUST still validate what it receives. The field is a hint the
authority is required to respect, not a guarantee about what will
arrive.

## 2.8.2 Registered

`msg_type` = `0x0001`. Authority to source, on conversation `0`.

| Field | Encoding |
|---|---|
| `unix_id_base` | `u32` |
| `unix_id_count` | `u32` |

Load-bearing beyond its contents. A source SHOULD report itself ready
only once it has received this, so that anything ordered after the
source finds a system that can actually authenticate rather than merely
a process that exists (§2.3).

### 2.8.2.1 unix_id_base, unix_id_count

The POSIX identifier range the authority has assigned this source
(§2.20). A base of **0** means no range was assigned, and every
principal the source asserts will project as unmapped.

**Informational.** A source counts within its range and asserts relative
identifiers; the authority applies the base. A source MUST NOT apply it
— see §2.20, where the reasoning is set out in full.

It is sent so that a source's administration tools can show an operator
the identifier a principal will really project to, rather than the
relative number the source stores. Without it that arithmetic falls to
the operator.

An authority that predates these fields sends neither, and a source MUST
read their absence as *no range assigned* — which is what such an
authority means, since it has no ranges to assign.

## 2.8.3 Rules

1. A connection MUST open with `Register` on conversation `0`. An
   authority MUST refuse any connection that opens otherwise.
2. An authority MUST bound the time it waits for the opening `Register`,
   and close the connection on expiry. A peer that connects and says
   nothing MUST NOT be able to hold resources indefinitely.
3. An authority MUST NOT admit two sources under one name at the same
   time.
4. An authority MUST send `Registered` only after the source is
   routable, so that a logon racing the acknowledgment cannot find a
   source that is registered but not yet reachable.
5. A source MUST NOT send any other message before receiving
   `Registered`.
6. An authority SHOULD report, where an administrator will see it, that
   a source registered with no identifier range — its principals will
   all project as unmapped, and the cause is a configuration omission
   rather than anything the source did.

---

# 2.9 Establishing What a Source Is

_Peios Specifications / PSPU / Principal Source Interface_

> The authority establishes a connecting source's identity from the kernel, never from what the source says, and checks it against an allowlist.

The authority MUST establish a connecting source's identity **for
itself**, from the kernel, and MUST NOT take it from anything the source
sends.

## 2.9.1 A source proves nothing

The mechanism worth recommending is that a source proves nothing at all,
because the init system already did.

Where the init system places a **service SID** in each service's token —
a SID derived from the service's name, which only the init system can
mint — the authority can:

1. take its list of permitted source names from its own configuration;
2. derive the service SID each of those names implies;
3. read the connecting peer's token and ask which of those SIDs it
   carries.

The resulting identity is assembled entirely from the authority's
configuration and the kernel. **Nothing is contributed by the process on
the other end.** There is no shared secret, nothing to provision,
nothing to rotate, and nothing to steal — the derivation is a pure
function of a name that only the init system can act on.

> [!NOTE]
> Mainline derives `S-1-5-80-<SHA-1 of the uppercased UTF-16LE service
> name>`, matching what the init system places in every service token.
> The derivation exists so that platform services — all running as
> SYSTEM — remain distinguishable from one another, which is exactly
> this problem.

## 2.9.2 What is deliberately not checked

**That the peer is SYSTEM.** The service SID subsumes it: the user SID
could never distinguish one platform service from another, since they
all run as the same principal. Requiring SYSTEM as well would needlessly
forbid a future source running under a lesser account, which is a
direction worth keeping open.

## 2.9.3 The allowlist

An authority MUST NOT accept a source it has not been configured to
accept.

An empty configuration MUST mean **no source may register**, not *any
source may*. An allowlist that fails open is not an allowlist. The
visible cost is that a system configured with no sources cannot
authenticate anyone, which is the correct way for that mistake to
present — loudly, at the first logon attempt, rather than silently at
the first compromise.

> [!NOTE]
> Mainline's allowlist is a registry key whose *subkey names* are the
> permitted source names, so enumerating that key answers "what may
> assert identity on this machine?" exactly, with no second list
> anywhere to drift out of step.

---

# 2.10 The Domain Claim

_Peios Specifications / PSPU / Principal Source Interface_

> A source declares the domain it is authoritative for — how the claim is checked, why domains must be disjoint, and what it does not prove.

A source declares the domain it is authoritative for. Every principal it
may assert lives under it (§2.18).

## 2.10.1 It is a claim

A source generates or is given its own domain, so **nothing about the
SID can prove the claim is honest**. What gives it weight is entirely
what the authority does with it.

An authority MUST apply all of the following.

### 2.10.1.1 1. A domain MUST be declared

A source that declares no domain MUST be refused. There would be nothing
to confine its assertions to, which is the whole purpose of collecting
one.

> [!NOTE]
> The field is appended to a message that existed before it, so a source
> built against an older shape decodes as declaring *nothing* rather
> than as malformed. That is why the refusal is stated as its own rule:
> the diagnosis should name the real problem.

### 2.10.1.2 2. The shape MUST be checked

A domain MUST be a well-formed, locally-issued domain SID: revision 1,
the NT authority (`5`), the non-unique prefix `21`, and three further
sub-authorities — `S-1-5-21-A-B-C`, four sub-authorities in total.

The shape is the entire check, and it is enough. A source cannot claim
`S-1-5-32` (BUILTIN), or the NT authority's well-known range, or
`S-1-1-0`, because none of them has that shape. **There is no list of
forbidden domains to keep in step with the SID catalog** — the
permitted shape excludes every one of them by construction.

### 2.10.1.3 3. Domains MUST be disjoint

No two concurrently registered sources may claim the same domain. Two
authorities for one namespace means whichever answers first decides who
a name belongs to, and the other's principals become impersonable by the
first.

### 2.10.1.4 4. A source MUST NOT change domain

A source that re-registers MUST declare what it declared before. An
authority MUST refuse a change.

This is the check that survives a source restarting, and it is worth its
cost: every other check passes for a source that is killed and comes
back compromised. It still holds the right service SID, its new domain
is still a claimable shape, and with itself deregistered there is
nothing left to collide with.

An authority MAY hold this record only for its own lifetime. Persisting
it means the authority writing state, which is a larger commitment than
the guarantee justifies.

### 2.10.1.5 5. An administrator MAY pin

An authority SHOULD allow an administrator to configure the exact domain
a named source must declare, and MUST refuse a source declaring anything
else when one is configured.

A configured pin that cannot be parsed MUST NOT be treated as absent.
Absence means *no pin*; an unparseable value means an administrator
tried to apply the control and got it wrong, and silently downgrading
that to "unconstrained" removes the control at the moment it was being
applied. An authority MUST fail towards refusing the source.

## 2.10.2 What remains uncovered

With no pin configured, and another source not currently registered, a
compromised source could declare *that* source's domain and assert its
identities. Disjointness catches it only while both are registered.

This is stated rather than solved. Closing it requires someone to write
the pin down, and an authority cannot invent that authority for itself —
writing it automatically would mean the process holding the
token-minting privilege also holding a configuration write handle, which
is a worse trade than the gap it closes.

---

# 2.11 Authenticate

_Peios Specifications / PSPU / Principal Source Interface_

> A neutral authentication request routed to one source, with verified originator and optional local logon context.

`msg_type` = `0x0002`. Authority to source. **Opens a conversation.**

| Field | Encoding | Limit |
|---|---|---|
| `start` | nested `AuthenticationRequest`, length-framed | PGSS §2.24 |
| `originator` | length-framed bytes (SID) | 68 bytes |
| `has_logon_context` | u8, exactly 0 or 1 | |
| `logon` | nested length-framed local context, when present | below |
| `has_presented` | u8, exactly 0 or 1 | |
| `presented` | nested length-framed proof, when present | below |

## 2.11.1 start

The shared authentication request, nested whole (PGSS §2.24). Its fields and
meanings are unchanged — including that `identifier` is an
unverified claim and `supported_credential_types` binds what may be
prompted for.

## 2.11.2 Local logon context

Only OS Logon supplies this structure. General Authenticate supplies no
local context and MUST NOT invent a dummy logon type.

| Field | Encoding | Limit |
|---|---|---|
| logon_type | u8 | PGSS §2.B |
| tty | string | 128 bytes |
| remote_host | string | 256 bytes |

These are the local context fields of PGSS §2.7. The type is the caller's
proposal; the terminal and host remain unverified context. Sources apply
general account and credential restrictions for both operations. The
authority applies permitted_logon_types only when finalizing OS Logon.

## 2.11.3 originator

The **verified** identity of the process that requested this logon,
taken by the authority from the client's connected socket and never from
a message body.

A source cannot learn this for itself: it is not party to the client's
connection, and there is nothing it could ask. The authority relays it
because a source may legitimately refuse a logon on the strength of it —
an account restricted to console logons needs to know what asked — and
that decision needs a trustworthy input.

A source MUST treat `originator` as established fact and MUST NOT treat
any other field of this message the same way.

## 2.11.4 Presented proof

Present only for an **identity-in-answer** credential type (PGSS §2.11),
of which Ntlmv2 is the only one. The authority has already issued the
challenge and collected the answer, because the answer is what names the
principal.

| Field | Encoding | Limit |
|---|---|---|
| credential_type | u8 | MUST be 4, Ntlmv2 |
| challenge | length-framed bytes | exactly 8 bytes |
| answer | length-framed bytes | PGSS §2.11 |

`start` is the client's request unchanged, so its identifier is empty and
it requires the presented type. `answer` is the client's answer data,
unchanged. The source takes the principal's name from the answer, decoded
as the authority decoded it to route the request here, so there is only
one copy of the name to trust.

A source MUST verify the presented proof against `challenge` and answer
with Assertion or Refusal. It MUST NOT send a CredentialRequest in this
conversation: there is no client prompt left to send, and nothing it
asked could be relayed. A source that does not support the presented
type MUST refuse with `AuthenticationFailed`.

The source trusts `challenge` because it trusts the authority, as it
trusts `originator`. Single use and freshness of the challenge are the
authority's obligation (PGSS §2.11).

An authority MUST NOT present a proof for any other credential type.
Every other type is collected by the source over the relayed
interrogation (§2.12), unchanged.

## 2.11.5 Routing

Before sending `Authenticate`, an authority MUST decide **which single
source** answers.

The credential MUST NOT be offered to more than one source. Trying each
in turn *with the password* hands every source the credentials of every
other source's users, including on typos — the failure PAM stacking
exemplifies (§2.D).

Resolution therefore happens on the identifier, before any credential
exists. Asking several sources "do you own this name?" is a resolution
step with no secret in it and is permitted; offering them the answer is
not.

An authority SHOULD resolve a qualified name to its owning source and
MUST NOT fall back to another source when the owning one is unreachable.
A name that can fall through lets anyone who can break a network choose
which authority answers for a principal.

### 2.11.5.1 Identity-in-answer types

For an identity-in-answer type, the name arrives with the credential, so
resolution cannot precede it. The authority resolves the name decoded
from the answer, by the same procedure, before offering the proof to any
source, and then offers it to the owning source alone. The rule this
section protects is unchanged: no source ever receives a credential that
belongs to another source's principal. Resolution queries still carry
only the name.

This mirrors NTLM pass-through authentication on Windows, where the local
security authority issues the challenge and forwards challenge and
response to the account's domain controller for verification.

## 2.11.6 Conversation limits

An authority MUST bound the conversations it opens against one source. A
source MUST bound what it will track, and MUST refuse beyond its own
limit with `AuthorityUnavailable` (§2.13) rather than dropping the
conversation silently.

---

# 2.12 The Relayed Interrogation

_Peios Specifications / PSPU / Principal Source Interface_

> CredentialRequest and CredentialResponse carrying PGSS Logon bodies verbatim — what the authority polices on the way through, and what it never inspects.

Two messages, both carrying PGSS Logon bodies verbatim. They serve a
credential change (§2.21) exactly as they serve an authentication, and
everything below applies to both.

## 2.12.1 CredentialRequest

`msg_type` = `0x8002`. Source to authority. Body is PGSS §2.8's
`CredentialRequest`, byte-for-byte.

The source decides what to ask for, in what order, and over how many
rounds. The authority relays it to the client.

## 2.12.2 CredentialResponse

`msg_type` = `0x0003`. Authority to source. Body is PGSS §2.8's
`CredentialResponse`, byte-for-byte.

## 2.12.3 What the authority polices

The authority relays, but does not relay *anything*.

**An authority MUST refuse to relay a prompt whose credential type is
absent from the client's `supported_credential_types`.** PGSS §2.8 makes
this the authority's obligation towards the client, and it holds however
the authority reached the prompt — a prompt originating in a source is
still the authority's to police.

Relaying it would force the client to hard-fail, and a client that
guessed instead might echo a secret to the screen. The authority MUST
terminate the logon instead.

An authority MUST also enforce its own round and time limits on the
relayed exchange (PGSS §2.3), independently of any the source applies. A
source that never terminates a conversation MUST NOT be able to hold a
client's logon open indefinitely.

## 2.12.4 Credential handling

The obligations of PGSS §2.12 bind both parties on this leg as they do
on the client's. Credential material reaching a source has been decoded
and re-encoded once more than it would have been without federation, and
every buffer it passed through on the way is one the obligation covers.

## 2.12.5 What the authority does not do

It does not interpret prompts, rewrite messages, reorder anything, or
synthesise a request of its own. A source's prompt reaches the client as
the source wrote it, which is the property that makes adding a
credential type a change to sources alone.

The one exception is an identity-in-answer type (PGSS §2.11). Its
challenge must reach the client before any principal, and so any source,
is known. The authority issues that single prompt itself and presents the
answer to the owning source in Authenticate (§2.11), and no relayed
interrogation takes place. It still does not verify the answer: the
source does. Adding such a type is therefore a change to the authority
as well as to sources.

---

# 2.13 Assertion and Refusal

_Peios Specifications / PSPU / Principal Source Interface_

> The two terminal messages a source may send — and what an assertion pointedly does not contain: no session, no token, no privileges.

Exactly one terminal message ends a source conversation. An
authentication ends in `Assertion` or `Refusal`. A credential change
ends in `CredentialChanged` or `Refusal`, never in `Assertion` (§2.21).

## 2.13.1 Assertion

`msg_type` = `0x8003`. Source to authority. **The only successful
outcome a source can produce.**

| Field | Encoding | Limit |
|---|---|---|
| `user_sid` | length-framed bytes (SID) | 68 bytes |
| `canonical_name` | string | 256 bytes |
| `groups` | array of group entries | 128 |
| `unix_id` | `u32` | §2.20 |
| `primary_group` | length-framed bytes (SID) | 68 bytes |
| `profile` | length-framed structure (PGSS §2.9) | |
| `claims` | array of claim entries | 64 |
| `permitted_logon_types` | `u32` | PGSS §2.16 |
| `authenticated_credential_type` | `u8`; 0 none, 1 Password, 2 SshPublicKey, 3 Mschapv2, 4 Ntlmv2 | PGSS §2.11 |
| `mschapv2_success` | length-framed bytes | 0 or 20 bytes |
| `ntlmv2_session_key` | length-framed bytes | 0 or 16 bytes |
| `credential_binding` | optional trailing length-framed bytes | exactly 32 bytes if present |

For Mschapv2, `mschapv2_success` MUST contain the 20-byte binary
AuthenticatorResponse for the verified exchange. For Ntlmv2,
`ntlmv2_session_key` MUST contain the 16-byte NTLM `SessionBaseKey`
(PGSS §2.11). Each MUST be empty for every other method. The authority
MUST refuse missing or unexpected output and MUST NOT relay a reusable NT
hash. General authentication conveys this output through Authenticated
(PGSS §2.24) and Logon through AccessGranted (PGSS §2.9), after normal
identity validation and disclosure authorization. Neither output grants
token-creation authority.

Note what is absent: no session, no token, no privileges, no integrity
level. A source has no way to express them (§2.4).

All fields through `ntlmv2_session_key` are mandatory in the coordinated
replacement layout.
Empty arrays/strings and zero values represent absent assertions; omitted
fields are malformed. The authority checks the authenticated method against
the client's capabilities and any required method before granting a token.

The additive `credential_binding` contains a nonzero opaque reference `[16]`
followed by a nonzero opaque revision `[16]`, with the contract in PGSS §2.16.
It MUST describe the credential actually verified by this assertion and MUST
be omitted for no-credential success. The source MUST persist it before
exposure, update it atomically with replacement, and leave it unchanged for
maintenance of the same underlying credential. An older source may omit it.
Existing PSI version-4 readers skip this trailing extension; no framing or
public C layout replacement is introduced.

Authd relays it to an authorized Authenticate caller after ordinary source,
SID, method and disclosure validation. It is neither a reusable credential
nor a capability. Later current-binding queries can detect change but MUST
NOT substitute for fresh proof or update a session's proved revision.

### 2.13.1.1 canonical_name

The source's own spelling of the principal's name. A client may have
typed `JACK`; this is what the principal is actually called.

Carrying it is what makes case-insensitive matching safe: the authority
records the canonical form rather than whatever was typed, so a
session's records do not vary with a caller's shift key.

A source MUST NOT assert a name that PGSS §2.15 forbids — one carrying a
reserved character, a byte outside the printable ASCII range, or a
leading or trailing space. The authority MUST refuse one anyway (§2.22),
because a name from a source reaches a `passwd`-format record and an
audit line, and by then the damage is the reader's to do.

The obligation is on what a source **asserts**, not on what it creates.
A source that validates a name when an administrator adds it, and not
when it reads one back from storage, has enforced nothing against a
store it did not itself write.

### 2.13.1.2 permitted_logon_types

Which kinds of sign-on this principal may be used for, as the bitmask
PGSS §2.16 defines for the `LOGON_TYPES` field.

A source **states** the property and MUST NOT act on it. Deciding what
to do about a principal's restrictions is derivation, and derivation is
the authority's (§2.4) — a source that refused an authentication on
these grounds would be making an access decision it has no standing to
make, and would do it *differently* from the authority that also has to.

Zero means the source states nothing, and a source that does not hold
the property MUST send zero rather than inventing a value. In particular
it MUST NOT send "everything", which would assert that a principal may
be used for a credential-free service logon (PGSS §2.19) on no evidence
at all.

Sources that state no restriction send zero explicitly.

### 2.13.1.3 groups

Each entry is a separate length-framed structure:

| Field | Encoding | Limit |
|---|---|---|
| `sid` | length-framed bytes (SID) | 68 bytes |
| `unix_id` | `u32` | §2.20 |

**A SID and a number. No attributes.**

A source asserts *which* groups a principal belongs to. Whether a group
entry is enabled, owner-marked, or deny-only is a decision about how to
build a token, and building tokens is the authority's (§2.4). A source
saying "this principal is an administrator" is identity; a source saying
"and mark that group deny-only" would be reaching into derivation.

Both current group fields are mandatory. The per-entry framing preserves
the boundary of any future trailing extension.

A `unix_id` of **0** means the source does not number this group — the
honest answer for a group it does not own. A source naming a well-known
group is stating a membership, not claiming authority over what that
group projects to; see §2.20.

### 2.13.1.4 unix_id

The principal's POSIX identifier, **relative to the range the authority
assigned this source** (§2.20). Zero means the source has no number for
this principal.

A source MUST NOT apply its own base. It counts within its range and the
authority rebases; a source that added the base itself would have it
added twice.

### 2.13.1.5 primary_group

Which of the principal's groups projects to the POSIX group id, and
becomes the default group of objects the token creates. Empty means the
source did not say, and the authority chooses.

It need not appear in `groups`. The authority is required to place it on
the token regardless (§2.22), because a token's primary group must be a
group the token carries — so naming a group here **is** a membership
claim, and it is subject to membership scope exactly as a listed group
is (§2.19).

That applies to a primary group the **source asserted**. Where the field
is empty and the authority substitutes one of its own, the substituted
value is the authority's choice and MUST NOT be tested against the
source's membership scope. Testing it would deny every logon from a
source that declined to name a primary group, on the strength of a claim
that source never made — and an authority's own default is very unlikely
to be a sibling of the principal's domain, so the test all but always
fails.

> [!NOTE]
> A source that made this the one field escaping the scope check would
> have found a route to `BUILTIN\Administrators` that the group array
> denies it. The obligation in §2.22 to apply membership scope to the
> primary group closes that.

### 2.13.1.6 profile

PGSS Logon's profile structure (PGSS §2.9), relayed onward to the client
unchanged. It is not identity, it decides no access, and the authority
does not interpret it.

The one thing the authority does check is the one PGSS §2.9 requires of
it: `home` and `shell`, when non-empty, are absolute paths. That
obligation binds the authority towards its client whatever the value's
provenance, so a relayed profile is not exempt from it.

### 2.13.1.7 claims

Named, typed attributes fed to conditional ACE evaluation, in the claim
attribute format PCDS §5.9 specifies. Each entry is a separate
length-framed structure:

| Field | Encoding | Limit |
|---|---|---|
| `name` | string | 255 bytes |
| `flags` | `u32` | PCDS §5.9 |
| `value_type` | `u32` | PCDS §5.9 |
| `values` | array of length-framed values | 64 |

A claim is the one field here that is a **trusted input to access
decisions** rather than a statement of identity: a conditional ACE can
turn a claim into a grant. Which claim names a source may assert is
therefore the same kind of question as which groups it may assert, and
belongs with membership scope (§2.19).

An authority MUST reject an assertion carrying a claim it cannot carry
to a token — an unsupported value type, a name containing an interior
NUL, a value exceeding its limit — rather than dropping the claim. The
reasoning is rule 3 below: a dropped claim signs the principal in
against a policy nobody stated.

### 2.13.1.8 What the authority MUST do with an assertion

1. **Validate every SID** with a structural check before treating it as
   identity. Bytes from another process are bytes until checked, and the
   check belongs in the process that mints tokens rather than in the
   codec that moved them (§2.7). This includes SIDs carried *inside* a
   claim value.
2. **Enforce identity scope** (§2.18), **membership scope** (§2.19) —
   including over `primary_group` — and **numeric scope** (§2.20).
3. **Fail the logon** on a malformed group SID, an unusable claim, an
   invalid `canonical_name`, or a `unix_id` outside the source's range,
   rather than dropping it. Dropping would sign the principal in with
   authority the source did not state — a confusing way to be wrong at
   best, and for a claim, a silent change of the policy that will be
   applied to them. A source that cannot encode a SID is broken.
4. **Drop a logon SID from the asserted groups**, loudly. No source is
   authoritative for one: the kernel mints them per session, and this
   session's did not exist when the source answered. A source asserting
   one is either buggy or reaching for a *different* session's SID,
   which would forge membership of somebody else's logon.
5. **Drop duplicates**, first mention winning. A source asserting a
   group the authority also derives is redundant, not wrong.

Rules 4 and 5 drop rather than refuse because the token still ends up
correct, and refusing would punish a principal for a source's defect
without making anything safer. Rule 3 refuses because the token would
*not* end up correct.

**Rules 4 and 5 run before rule 2.** A logon SID is by construction
outside the principal's domain, so an authority that applied membership
scope first would refuse the logon that rule 4 says to survive by
dropping. Duplicates are the same shape of problem. The drops are about
what a source should never have sent; the scope tests are about what it
is permitted to claim, and only what survives the first is subject to
the second.

An authority MUST also place `primary_group` on the token even when the
source did not list it among `groups`, since a token's primary group
must be a group the token carries.

## 2.13.2 Refusal

`msg_type` = `0x8004`. Source to authority.

| Field | Encoding | Limit |
|---|---|---|
| `denial` | `u32` | PGSS §2.B |
| `reason` | string | 512 bytes |

Reuses PGSS Logon's denial vocabulary rather than inventing a parallel
one, so that relaying a refusal outward needs no lossy translation.

A source MUST NOT refuse with `NoSuchSession` (PGSS §2.B). It answers
only a request to end a logon session (PGSS §2.22), which the authority
decides alone and never puts to a source, so in a refusal it can only
be a mistake. An authority that receives it MUST NOT relay it, and
SHOULD end the conversation with `Internal` instead.

`CredentialRejected` is the same kind of code: it answers only an
enrolment (PGSS §2.23), so a source MUST NOT send it in any other
conversation, and an authority that receives it elsewhere MUST NOT relay
it (§2.23).

A source MUST NOT distinguish an unknown principal from a bad credential
— by code, by reason, or by timing (PGSS §2.10, §2.12). The obligation
is the source's here, because the source is where the distinction exists
to be leaked.

> [!NOTE]
> A principal requiring no credential is a separate matter, and cannot
> be hidden: a conversation that reaches `Assertion` with no round at
> all says that the named principal exists and needs nothing. That is
> inherent in permitting a zero-round logon rather than a defect in this
> rule, and it is the reason a passwordless principal is a
> configuration decision rather than a convenience.

An authority MAY relay `reason` to the client and MAY replace it. It
MUST NOT relay a reason that reveals a distinction the source was
required not to make.

---

# 2.14 Abandon

_Peios Specifications / PSPU / Principal Source Interface_

> Telling a source a conversation will not continue, and why the protocol would leak state without it.

`msg_type` = `0x0004`. Authority to source. No fields beyond the header.

Tells a source that a conversation will not continue: the client hung
up, a limit was reached, or the authority terminated the logon for
reasons of its own.

## 2.14.1 Why it exists

Without it, a client that disconnects mid-prompt leaves the source
holding conversation state forever. A source cannot detect this for
itself — it is not party to the client's connection — so the authority
has to say.

## 2.14.2 Rules

1. An authority MUST send `Abandon` for any conversation it opened that
   will not reach a terminal state, unless the connection itself is
   being torn down.
2. A source MUST discard all state for the conversation on receipt, and
   MUST NOT reply.
3. `Abandon` is not a terminal message *from* the source, and no
   `Assertion` or `Refusal` follows it. If one arrives anyway, the
   authority MUST ignore it — the conversation is gone, and a late
   answer to an abandoned question is at best stale.
4. A source that receives `Abandon` for a conversation it does not know
   MUST ignore it. It has already cleaned up, which is the outcome the
   message wanted.

> [!NOTE]
> The natural implementation is to send `Abandon` from whatever owns the
> conversation's lifetime, on any path that does not reach a terminal
> state — including error paths. An authority that sends it only on the
> tidy path will leak conversations exactly when things are already
> going wrong.

---

# 2.15 Query

_Peios Specifications / PSPU / Principal Source Interface_

> Asking a source about a principal outside a logon — batching, relative identifiers, and the outcomes a query can return.

An authority serving PGSS Logon's identity lookup must be able to ask a
source about a principal outside a logon: to render a name for a SID, or
a POSIX record for a number.

A query is a conversation like any other. The authority allocates the
identifier, `Query` opens it, and one terminal message closes it.

## 2.15.1 Query

`msg_type` = `0x0005`. Authority to source. Opens a conversation.

| Field | Encoding | Limit |
|---|---|---|
| `fields` | `u32` | PGSS §2.B |
| `keys` | array of key entries | 64 |

A key entry is a length-framed structure:

| Field | Encoding | Limit |
|---|---|---|
| `key_type` | `u8` | §2.B |
| `name` | string | 256 bytes |
| `sid` | length-framed bytes (SID) | 68 bytes |
| `relative_id` | `u32` | |
| `kind` | `u8` | PGSS §2.B |

Exactly one of `name`, `sid` and `relative_id` is meaningful, selected
by `key_type`. An encoder MUST leave the others empty or zero.

### 2.15.1.1 Keys are never absolute

| Value | Name |
|---|---|
| 1 | `Name` |
| 2 | `Sid` |
| 3 | `RelativeId` |

**There is no key type carrying an absolute POSIX identifier**, and this
is the load-bearing property of the message.

PGSS Logon's lookup accepts one, because that is what `getpwuid` hands a
name resolver. The authority resolves it: it locates the range
containing the number, subtracts the base, and asks the owning source by
relative identifier.

A source is therefore never asked an absolute number, exactly as it
never asserts one during a logon (§2.20).

The reason is not that an absolute number would let a source escape its
range — it could not, because the authority refuses a relative
identifier at or past the count before adding anything to it (§2.20).
The reason is that the arithmetic must exist in exactly one place. A
source asked an absolute number would have to subtract its own base to
answer, which is the operation §2.20 forbids it, and an authority that
asked would have taught it that its stored numbers and the system's are
the same numbers. Every subsequent bug in that source would be an
off-by-a-base.

> [!NOTE]
> This is also why the authority is the only party that *can* answer a
> `getpwuid`. See PGSS §2.13.

### 2.15.1.2 Batching

`keys` is an array so that an authority may ask several questions in one
exchange. An authority MAY send a single key, and one that always does
is conforming.

The array is here from the outset because adding it later would break
every source written against a single-key message. A source with a cheap
local store gains little; a source backed by a remote directory gains
the difference between one query and a hundred.

A source MUST answer every key it is sent, in order, and MUST NOT
reorder, merge or omit results. A source that cannot serve a whole batch
MUST refuse the conversation rather than answer part of it.

## 2.15.2 QueryResult

`msg_type` = `0x8005`. Source to authority. Terminal.

| Field | Encoding | Limit |
|---|---|---|
| `results` | array of result entries | 64 |

One result per key, in the order the keys were sent.

A result entry is a length-framed structure:

| Field | Encoding | Limit |
|---|---|---|
| `outcome` | `u8` | §2.B |
| `sid` | length-framed bytes (SID) | 68 bytes |
| `canonical_name` | string | 256 bytes |
| `kind` | `u8` | PGSS §2.B |
| `present` | `u32` | PGSS §2.B |
| `withheld` | array of withheld entries | 32 |
| `values` | array of length-framed values | 32 |

Everything from `present` onward is PGSS §2.16's structure, unchanged —
the same reuse of message bodies as the interrogation phase (§2.5), and
for the same reason: an authority relaying a source's answer outward
should not have to translate it.

Where `outcome` is not `Found`, everything after it MUST be empty or
zero.

### 2.15.2.1 canonical_name, not qualified

A source returns **its own spelling** of the name, as it does in an
`Assertion` (§2.13). It does not qualify it.

Qualification names which source answered, and a source cannot know what
it is called in another authority's search order. PGSS Logon requires a
qualified name on the way out (PGSS §2.15); producing it is the
authority's.

### 2.15.2.2 Identifiers are relative

Every identifier in a result — a `UNIX_ID` field, a reference's
`unix_id` — is **relative**, exactly as in an `Assertion` (§2.20). A
source MUST NOT apply a base, and the authority rebases before the
number leaves it.

### 2.15.2.3 Outcomes

A source may send only:

| Value | Name | Meaning |
|---|---|---|
| 1 | `Found` | The source holds this object. |
| 2 | `NotFound` | It does not. |
| 4 | `Refused` | It holds it and will not say so. |

A source MUST NOT send `Unavailable`: it is answering, so nothing was
unavailable to it. The authority produces that outcome when a source
does *not* answer (PGSS §2.18), and a source claiming it would let a
working source be recorded as a broken one.

A source MUST NOT send `Malformed` in a result. A message it cannot
parse is a `Refusal` for the whole conversation (§2.13).

> [!NOTE]
> `Refused` is how a source declines to expose a principal it holds —
> which §2.22 has always permitted. It is distinct from `NotFound`
> because the authority may consult another source on `NotFound`, and
> must not on `Refused`: the object was found, and the answer was no.

A `Refused` result is about the object, not about the caller, and an
authority MUST NOT relay it outward as PGSS Logon's `Refused` outcome,
which is reserved for a caller that may not make the request (PGSS
§2.18). What a source declining to expose an object means to a client is
the authority's to decide, and it is not "you lack permission".

A source that declared no `QUERIES` is a third case again. It has not
answered and cannot be asked, so an authority MUST NOT record it as
having answered `NotFound`: a source that was never consulted is not
evidence that an object does not exist, and PGSS §2.18 forbids reporting
`NotFound` on the strength of one. It contributes nothing to the search,
and §2.8 says what an authority should do about the configuration that
produced it.

## 2.15.3 Scope

An authority MUST apply identity confinement (§2.18), membership scope
(§2.19) and numeric scope (§2.20) to a `QueryResult` exactly as to an
`Assertion`, and MUST validate every SID in one structurally before
using it — including the SIDs of references inside a `PRIMARY_GROUP`,
`GROUPS` or `MEMBERS` value, not only the `sid` of the result itself.

"Exactly as to an `Assertion`" is meant literally, and it is the
sentence an implementation is most likely to satisfy by halves. An
authority that confines the object a result names, while relaying the
group references beside it unchecked, has left the whole of membership
scope unenforced on this channel — and a source with no permission to
assert a foreign membership can then report one through a name lookup
that it could not report through a logon.

A query is not a weaker channel than a logon. A source that could name a
principal outside its domain here would be able to make `ls -l` display
another source's principals as its own — and, worse, could then be
believed the next time something compared that name to a SID.

---

# 2.16 Enumeration

_Peios Specifications / PSPU / Principal Source Interface_

> Paging through a source's principals or a large group's members, with cursors that belong to the source.

`Query` asks about objects the authority can already name. Enumeration
asks a source to produce them: to fill a POSIX `passwd` or `group`
table, or to page through a group whose membership will not fit in one
answer.

**A source is never required to enumerate.** A source that declines is
fully conforming, and this section exists as much to make declining safe
as to make enumerating possible.

## 2.16.1 EnumerateSource

`msg_type` = `0x0006`. Authority to source. Opens a conversation.

| Field | Encoding | Limit |
|---|---|---|
| `kind` | `u8` | PGSS §2.B |
| `fields` | `u32` | PGSS §2.B |
| `of` | length-framed key entry (§2.15) | |
| `cursor` | length-framed bytes | 256 bytes |

`kind` MUST NOT be `Any`.

An empty `of` enumerates every object of `kind` the source holds. A
non-empty `of` MUST name a group, and enumerates that group's members.

That group is one the source holds, or a `BUILTIN` group (`S-1-5-32-…`)
named by its SID. A `BUILTIN` group is no source's object, but a source
permitted to assert memberships outside its domain records who is in it
(§2.19), and the authority asks every such source for its members (PGSS
§2.16). Such a source MUST answer with the principals it records in the
group — by a listed membership or as their primary group — and with an
empty `Found` where it records none.

`cursor` is empty on the first request, and otherwise carries the `next`
from the source's immediately preceding reply.

## 2.16.2 EnumerateResult

`msg_type` = `0x8006`. Source to authority. Terminal.

| Field | Encoding | Limit |
|---|---|---|
| `outcome` | `u8` | §2.B |
| `entries` | array of result entries (§2.15) | 256 |
| `next` | length-framed bytes | 256 bytes |

An empty `next` ends the enumeration. A non-empty `next` means there is
more, **even where `entries` is empty**.

A source MUST size a page against the smaller of this chapter's message
ceiling and PGSS Logon's, because the authority re-encodes what it
returns into the latter (§2.A). Neither the 256-entry bound nor the
message ceiling here prevents a page nobody can deliver.

A source that will not enumerate replies `Refused`, with `entries` and
`next` empty. An authority MUST record it as a source that did not
contribute, and MUST NOT retry it for the remainder of that enumeration
— across pages as well as within one (PGSS §2.17).

`Refused` and an empty `Found` are **different answers and MUST NOT be
conflated**. `Found` with `entries` and `next` both empty says *there
are none*: the group exists and has no recorded members, or the source
holds no objects of that kind. `Refused` says *this source is not
answering*. A source that returns an empty `Found` where it means the
second has told the authority a falsehood it cannot detect, and the
authority will go on asking it — the non-retry rule above has nothing to
attach to.

The cases most often got wrong, all of which are `Refused` and not an
empty `Found`: a group whose membership the source will not expose, a
key that names an object the source does not hold, a key that names a
principal where a group was required, and a cursor the source can no
longer honor.

## 2.16.3 Cursors belong to the source

A cursor is **opaque to the authority**. The authority MUST NOT
construct, parse or modify one; it relays what it was given.

A source MAY encode anything into a cursor, and MAY refuse one it no
longer honors — a store rewritten underneath a half-finished walk is
the ordinary case, not an exceptional one. A refused cursor is
`Refused`, and the authority MUST NOT restart the enumeration on the
source's behalf.

> [!NOTE]
> Restarting would turn a store edit during a `getent passwd` into an
> unbounded loop over a source that never finishes. Reporting an
> incomplete enumeration is the honest outcome, and PGSS §2.17 requires
> the authority to say so.

A source MUST NOT assume a cursor comes back on the same conversation,
or on the same connection, and MUST NOT hold per-cursor state it is
unwilling to discard.

The authority's own cursor, the one it hands its client, is its to
construct — PGSS §2.17 requires it to reject one it did not issue, which
it can only do for a cursor it made. A source's cursor travels inside
it, not as it.

## 2.16.4 Why members are here and not only in Query

`MEMBERS` is a field of `Query` (§2.15), so the common case — a small
group, whose members fit alongside the rest of the record — costs one
exchange.

A group whose membership will not fit is reported through PGSS Logon's
`TooLarge` (PGSS §2.16), and this is where the caller is sent. Paging a
membership through the mechanism that already pages is cheaper than a
third message, and considerably cheaper than the alternative of a
partial member list, which is a wrong answer rather than a smaller one.

## 2.16.5 Enumeration is not existence

An authority MUST NOT use enumeration to determine whether a principal
exists, and MUST NOT infer from a source declining to enumerate that the
source holds nothing.

A directory-backed source able to answer any single question while quite
unable to answer all of them is the expected case, not a degraded one.

---

# 2.17 Change Notification

_Peios Specifications / PSPU / Principal Source Interface_

> The unsolicited message that lets an authority cache name lookups safely, and what it deliberately does not carry.

An authority answering a name lookup for every process on the system
will cache. This is the message that lets it.

## 2.17.1 Changed

`msg_type` = `0x8007`. Source to authority, on conversation `0`.
Unsolicited, and never answered.

| Field | Encoding | Limit |
|---|---|---|
| `scope` | `u8` | §2.B |
| `sid` | length-framed bytes (SID) | 68 bytes |

| `scope` | Name | Meaning |
|---|---|---|
| 1 | `All` | Everything this source holds may have changed. |
| 2 | `Object` | The object named by `sid` may have changed. |

`sid` is meaningful only for `Object`, and MUST be within the source's
declared domain (§2.18).

`Object` scope MUST be used for a **deletion** as well as a change, and
for a **creation** — an authority may be holding a cached `NotFound` for
a name that now exists.

## 2.17.2 Obligations

A source declaring `PUSHES_CHANGES` (§2.8) MUST send `Changed` before,
or at the same time as, the altered answer becomes observable through
`Query`.

Sending it afterwards leaves a window in which the authority's cache and
the source disagree while both believe themselves current — which is
indistinguishable, from the authority's side, from the notification
never arriving.

A source MAY send `All` where it could have sent `Object`.
Over-invalidation costs a query; under-invalidation costs correctness.

An authority MUST accept `Changed` at any time after `Registered`,
including while conversations are open on the same connection, and MUST
NOT reply to it.

An authority MUST treat the loss of a source's connection as `All` for
that source. It does not know what changed while it was not listening.

A source declaring `PUSHES_CHANGES` SHOULD declare a non-zero
`entry_ttl` as well (§2.8). The two are not alternatives: the TTL is the
backstop against a notification that was never sent, or was sent and
failed to write. Declaring `PUSHES_CHANGES` with a TTL of zero means a
single lost notification leaves the authority holding a stale answer
until the connection drops — and a source that tolerated a failed
`Changed` write without tearing the connection down would have made that
outcome reachable, which is one of the reasons §2.6 makes a failed write
fatal.

## 2.17.3 Sources that do not push

A source that does not declare `PUSHES_CHANGES` is conforming, and many
cannot: a remote directory has no way to tell this machine that an
account was renamed.

Such a source declares `entry_ttl` instead (§2.8), and an authority MUST
NOT hold its answers beyond it.

A source declaring **neither** has said it cannot support caching, and
an authority MUST NOT cache its answers at all. That is the safe reading
of silence, and it is what a source predating this message says by
omission.

> [!NOTE]
> The alternative default — cache anything not explicitly forbidden —
> would make a source written against an older revision silently serve
> stale identity, which is the one class of staleness that decides
> access.

An authority that does not cache at all satisfies this section
trivially, and is conforming. The obligations here bind what an
authority may hold, not whether it must hold anything.

## 2.17.4 What this does not carry

`Changed` says that something changed. It does not say what it changed
to.

Carrying the new value would make this a second, unsolicited path by
which a source could assert identity — one arriving outside any
conversation, with no key to check it against, and no logon in progress
to refuse. An authority that believed it would have accepted an identity
assertion it never asked for.

The authority discards what it holds and asks again through `Query`,
where every scope rule in §2.18 to §2.20 applies.

---

# 2.18 Identity Confinement

_Peios Specifications / PSPU / Principal Source Interface_

> An assertion outside the source's registered domain is refused and the conversation terminated. No configuration lifts this.

**A source may assert only principals within its declared domain
(§2.10). No configuration lifts this.**

An authority MUST refuse an `Assertion` whose `user_sid` does not lie
within the domain the source registered for, and MUST terminate the
logon. It MUST apply the same test to a `QueryResult` (§2.15) and to the
`sid` of a `Changed` (§2.17).

## 2.18.1 Containment

A principal SID lies within a domain when it is the domain's SID plus
**exactly one** relative identifier.

Exactly one, deliberately. `S-1-5-21-A-B-C-1000-1` is not a principal of
`S-1-5-21-A-B-C`, and admitting it would let a source that owns one
domain mint names in a nested namespace nobody agreed it owned. A domain
SID is likewise not a principal of itself.

## 2.18.2 Why nothing lifts it

A source that could assert identities outside its domain could hand out
**another authority's principals** to anyone who satisfied *its*
credential check.

The concrete case: a local source holds no domain credential. If it were
unconfined, it could produce a domain administrator's identity for
anyone who knew a *local* password. The domain's own authority would
never be consulted and would have no way to know.

Confinement keeps a compromised source at "authority over its own
domain" — which is what it already was — rather than "authority over
everyone".

This is why identity scope and membership scope (§2.19) are separate
settings rather than one. They are different questions, and only one of
them has a legitimate exception.

---

# 2.19 Membership Scope

_Peios Specifications / PSPU / Principal Source Interface_

> Group membership is the one legitimate exception to confinement — the default, the exception, and why it never extends to identity.

Group membership is the question with a legitimate exception, and it
needs one.

## 2.19.1 The default

By default, an authority MUST refuse an `Assertion` carrying a group
outside the domain of the principal being asserted.

A directory vouches for its own users and its own groups, and nothing
else. Without this rule, a directory-backed source could declare its
users members of `BUILTIN\Administrators` — making a remote authority
the arbiter of who administers this machine.

The test is *relative*: are the group and the principal in the same
domain? It needs no configuration and no knowledge of which domain
belongs to whom, which is why membership scope is enforceable before
anything else about scope is settled.

## 2.19.2 The exception

An authority SHOULD allow a source to be configured as permitted to
assert **memberships** outside the asserted principal's domain.

A local source needs it. Local group membership of *any* principal is a
local decision: "`CORP\Domain Admins` is in `BUILTIN\Administrators`" is
a record this machine keeps, not something a domain controller asserts
at it. Without the exception, a local source could not express the one
thing it is most authoritative about.

An authority MAY grant this to more than one source. Nothing about it is
exclusive.

## 2.19.3 Memberships only, never identity

A source holding this permission **remains fully confined on identity**
(§2.18).

The two are separate because the risks are not symmetric. A source
asserting a foreign *membership* is making a claim about what a
principal may do **on this machine**, which is a local matter and is the
local source's business. A source asserting a foreign *identity* is
claiming to be the authority for somebody else's principal, which is
never anyone's business but that authority's.

> [!NOTE]
> Specifying the permission narrowly — memberships only — from the
> outset is what allowed identity confinement to be switched on later
> without changing what the setting means. A permission defined as "this
> source is trusted" would have had to be redefined, and every existing
> configuration reinterpreted, the day identity scope arrived.

## 2.19.4 The primary group is a membership

`primary_group` (§2.13) is subject to this section exactly as a listed
group is, and an authority MUST apply the test to it.

It would otherwise be a way round: the authority is required to place
the primary group on the token whether or not the source listed it, so a
source that named `BUILTIN\Administrators` there and nowhere else would
obtain a membership the group array denies it.

An authority that adds an unlisted `primary_group` to the membership set
MUST do so **before** applying this section, not after. Adding it
afterwards reintroduces exactly the route the rule closes.

This binds a primary group the **source asserted**. A default the
authority substituted for an empty field is not the source's claim and
MUST NOT be tested against the source's scope (§2.13); an authority that
tested its own default would refuse every logon from a source that
simply left the field empty.

## 2.19.5 Claims are the same question, unanswered

A claim (§2.13) is a trusted input to conditional ACE evaluation, so
asserting one can produce a grant just as asserting a membership can.
*Which claim names a source may assert* is therefore the same shape of
control as this section — and it is **not yet specified**.

The gap is stated rather than papered over. An authority federating to a
source it does not fully trust should consider claims as it considers
foreign memberships, and a future revision is expected to define the
control here.

> [!NOTE]
> Active Directory splits this in a way worth borrowing: claim *type
> definitions* are forest-level configuration while claim *values* are
> per-user attributes. The equivalent split — the machine decides which
> claims exist, the source supplies values for them — is the obvious
> shape for the control, and is why this is a gap in configuration
> rather than a flaw in the message format.

---

# 2.20 Numeric Scope

_Peios Specifications / PSPU / Principal Source Interface_

> Every unix_id a source asserts is rebased into the range it was granted, refused rather than clamped when out of range.

**A source's POSIX identifiers are relative. The authority assigns the
range and applies the base; a source is told its range but MUST NOT act
on it.**

Every `unix_id` in an `Assertion` — the principal's and each group's —
and every identifier in a `QueryResult` is an offset within a range the
authority assigned that source. The authority adds the base before the
number reaches a token or a caller.

This is the numeric counterpart of identity confinement (§2.18). That
section stops a source naming principals outside its namespace; this one
stops it *numbering* them outside its namespace.

## 2.20.1 The range

An authority MUST assign each source a range, as a **base** and a
**count**, spanning `[base, base + count)`.

> [!NOTE]
> Mainline configures both per source in the registry, as `UnixIDBase`
> and `UnixIDCount` alongside the domain pin (§2.10). How the assignment
> is expressed is the authority's own design; what it must satisfy is
> this section.

An authority MUST reserve a band below every source's base for
identifiers of its own — well-known SIDs, service SIDs, confinement SIDs
— none of which come from any directory. The band has to be generous,
because the last of those categories has no bound.

## 2.20.2 Rebasing

Given a relative identifier `r` from a source with range
`(base, count)`, the authority computes `base + r`, and MUST refuse to
produce a number at all when:

- `r` is **0**. Zero is not an identifier; it is how a source says it
  has no number for something. It MUST NOT become `base`.
- `r` is **at or past `count`**. The source has reached outside the
  range it was given.

A number the authority declines to produce projects as *unmapped*, which
the Peios Kernel TRM §3.10.1 defines.

## 2.20.3 Refuse, never clamp

An out-of-range identifier MUST be refused. It MUST NOT be clamped to
the top of the range, and it MUST NOT be reduced modulo the count.

Both alternatives look like graceful degradation and are worse than a
refusal:

- **Clamping** puts two principals on one number, so a filesystem cannot
  tell them apart.
- **Wrapping** lands inside somebody else's range, so one source's
  principal projects as another source's.

The range is a boundary, not an offset, and the count is what makes it
one.

## 2.20.4 Two numbers a source can never reach

Because the base sits above the reserved band and a relative identifier
cannot escape the count:

1. **uid 0.** It belongs to the authority's own table and is not
   reachable by adding a base to anything a source can send.
2. **Another source's numbers.** Whatever a source asserts, arithmetic
   confines it to its own range.

Neither depends on the source behaving. They hold because of what the
source is *able to express*.

## 2.20.5 Well-known SIDs are not the source's to number

An authority MUST use its own identifier for any SID in its reserved
band, and MUST ignore whatever `unix_id` a source sent alongside it.

A source asserting `BUILTIN\Administrators` is stating a membership. It
is not claiming authority over what that group projects to, and
honoring a relative identifier there would place a well-known group
*inside that source's range* — where a second source could number
something else identically.

## 2.20.6 The authority tells the source its range

A source is told its base and count at registration (§2.8). This is
informational and exists so an administration tool can show an operator
the identifier a principal will really project to, rather than the
relative number on disk.

**A source MUST NOT apply the base to what it asserts.** It is told the
range so it can explain itself, not so it can do the arithmetic. A
source that applied its own base would have it applied twice.

> [!NOTE]
> Keeping the base out of the source's stored records is what makes
> rebasing a configuration change rather than a data migration. An
> administrator moving a source's range edits two configuration values;
> nothing the source persists has to be rewritten, because nothing it
> persists was ever absolute.

Disclosure costs nothing that matters. What confines a source is not
ignorance of the base but the authority's refusal to accept a relative
identifier at or past the count — a check the authority performs on
every number it rebases, whatever the source knows.

## 2.20.7 Uniqueness within a source

SIDs are one namespace; POSIX user and group identifiers are two. A
source MUST therefore allocate from a **single counter across every kind
of object it holds**, so that a number issued to a principal is never
issued again to a group.

An authority cannot check this — it sees one assertion at a time — so it
is stated as an obligation on the source (§2.22) rather than as
something enforced.

> [!NOTE]
> The simplest way to satisfy it is to make an object's identifier its
> relative identifier within the domain, which is already unique across
> principals and groups. That has the incidental benefit that one object
> has one number rather than two unrelated ones.

---

# 2.21 Credential Change

_Peios Specifications / PSPU / Principal Source Interface_

> ChangeCredential and CredentialChanged — relaying a principal's change of their own credential to the source that holds it, and why the principal is never a claim.

A PGSS Logon credential change (PGSS §2.20) reaches the source that
holds the principal as a conversation of its own kind. It opens with
`ChangeCredential`, runs the relayed interrogation of §2.12, and ends in
`CredentialChanged` or `Refusal`.

```
  authority                              source
    |------------ ChangeCredential ---------->|   conversation N
    |<----------- CredentialRequest ----------|   the current credential
    |------------ CredentialResponse -------->|
    |<----------- CredentialRequest ----------|   the new one
    |------------ CredentialResponse -------->|
    |<------ CredentialChanged | Refusal -----|
```

It is not an `Authenticate` that ends differently. A change asserts
nobody, so it carries nothing an authority could mint from, and keeping
the two apart by message type keeps the path that mints unreachable from
this one (§2.4).

## 2.21.1 ChangeCredential

`msg_type` = `0x0007`. Authority to source. **Opens a conversation.**

| Field | Encoding | Limit |
|---|---|---|
| `start` | nested `CredentialChangeStart`, length-framed | PGSS §2.20 |
| `principal` | length-framed bytes (SID) | 68 bytes |

### 2.21.1.1 start

The client's `CredentialChangeStart`, nested whole (§2.7), for the
reason `Authenticate` nests `LogonStart` (§2.11): it grows on PGSS
Logon's schedule, and a field appended there must not displace
`principal`. Its `supported_credential_types` binds what may be prompted
for, exactly as in a logon.

### 2.21.1.2 principal

The principal whose credential changes: the user of the client's token,
established by the authority from the client's connected socket and
never from a message body.

It names both who asked and who is being changed, because PGSS Logon
gives a client no way to name anybody else. A source MUST treat it as
established fact, MUST NOT change the credential of any other principal
in this conversation, and MUST NOT take a principal from anything the
client supplies in it.

### 2.21.1.3 Routing

An authority MUST send `ChangeCredential` only to the source
authoritative for `principal`'s domain (§2.18), and MUST NOT offer the
change to any other source. The rule and its reason are those of §2.11:
a credential offered to the wrong source is a credential handed to it.

Where no registered source is authoritative for `principal` and a
configured source is absent, the authority MUST answer the client
`AuthorityUnavailable` rather than refusing the account. The absent
source may be the one that holds it, and "this account has nothing to
change" would turn an outage into a statement about the account.

An authority MUST NOT send `ChangeCredential` to a source that did not
declare `CHANGES_CREDENTIALS` (§2.8).

## 2.21.2 The interrogation

The rounds are those of §2.12, unchanged: `CredentialRequest` and
`CredentialResponse` carrying PGSS Logon's bodies, relayed and policed
by the authority as they are in a logon. The source decides what to ask
for.

A source MUST establish that the principal can present their current
credential before changing it (PGSS §2.20), and MUST refuse with
`AuthenticationFailed` where they cannot. The token the authority read
`principal` from is not that proof.

A source that proves the current credential in one round and collects
the new one in a later round MUST NOT change the credential if the
current credential has itself changed in between. Otherwise an
administrator's reset between the two rounds would be overwritten on the
strength of the credential it replaced.

## 2.21.3 CredentialChanged

`msg_type` = `0x8008`. Source to authority. **The only successful
outcome of a change conversation.** No fields.

A source MUST NOT send it until the new credential is the one it will
verify at its next `Authenticate` for this principal — until the change
is durable. The authority relays it to the client as PGSS Logon's
`CredentialChanged`, and PGSS §2.20 forbids reporting a change that a
subsequent logon would not see.

## 2.21.4 Refusal

A change that does not end in `CredentialChanged` ends in `Refusal`
(§2.13). A source MUST refuse:

- with `AccountRestricted`, a principal it holds no changeable
  credential for: one that authenticates with no credential, one
  designated only for service logons, or one that is disabled;
- with `AuthenticationFailed`, a current credential that does not
  verify;
- with `ConversationLimit`, a change it gives up on for want of an
  acceptable new credential.

## 2.21.5 Terminals out of place

An authority MUST treat an `Assertion` in a change conversation, and a
`CredentialChanged` in any other conversation, as a source fault. It
MUST end the client's conversation with `Internal`, MUST NOT mint from
the assertion, and MUST NOT report the change.

`Abandon` (§2.14) applies unchanged. A source discards everything it
held for the conversation, including what a completed round established.

---

# 2.22 Conformance

_Peios Specifications / PSPU / Principal Source Interface_

> Every requirement of this chapter collected by role, for an authority federating over PSI and for a source serving it.

A conforming implementation MUST satisfy every requirement in this
chapter. This section collects them by role.

## 2.22.1 Authority obligations

An authority federating over PSI MUST satisfy all of the following.

### 2.22.1.1 Channel

1. Listen; never dial out to a source (§2.3).
2. Never rely on the socket's descriptor as the access control, and
   bound unregistered connections and registration time independently of
   it (§2.6).
3. Bound registered sources, and conversations per source (§2.6).
4. Tear down the connection on a framing error or a failed write, rather
   than attempting resynchronisation (§2.6).

### 2.22.1.2 Registration

5. Require `Register` on conversation `0` as the first message (§2.8).
6. Establish the source's identity from the peer's token, never from
   `source_name`, and refuse a mismatch rather than correcting it
   (§2.8, §2.9).
7. Accept only configured sources, treating an empty configuration as
   *no source may register* (§2.9).
8. Refuse a source that declares no domain (§2.10).
9. Refuse a domain that is not a well-formed locally-issued domain SID
   (§2.10).
10. Refuse a domain another registered source claims (§2.10).
11. Refuse a source declaring a different domain from the one it
    declared before (§2.10).
12. Refuse a source whose declared domain contradicts a configured pin,
    and treat an unparseable pin as refusing rather than as absent
    (§2.10).
13. Send `Registered` only once the source is routable (§2.8).
14. Report, where an administrator will see it, a source registering
    with no identifier range, and a source registering without
    `QUERIES` (§2.8).

### 2.22.1.3 Conversations

15. Allocate conversation identifiers, never accepting one from a
    source, never opening one with an identifier already live, and
    reserve `0` for registration (§2.7).
16. Route each logon to exactly one source, resolved before any
    credential is collected, or for an identity-in-answer type resolved
    on the answer's name before the proof is offered to any source
    (§2.11).
17. Never fall back to another source when the owning source is
    unreachable (§2.11).
18. Relay the verified `originator`, taken from the client's socket
    (§2.11).
19. Refuse to relay a prompt for a credential type the client did not
    advertise (§2.12).
20. Enforce its own round and time limits on the relayed exchange
    (§2.12).
21. Send `Abandon` for any conversation that will not reach a terminal
    state (§2.14).

### 2.22.1.4 Assertions

22. Validate every SID structurally before treating it as identity,
    including SIDs carried inside claim values (§2.13).
23. Drop an asserted logon SID, and drop duplicates first-mention-wins,
    **before** applying any scope test (§2.13).
24. Enforce identity confinement, with no configuration lifting it, on
    an `Assertion`, on a `QueryResult`, and on the `sid` of a `Changed`
    (§2.18).
25. Enforce membership scope, subject only to a per-source permission
    covering memberships alone, and apply it to a **source-asserted**
    `primary_group` as well as to listed groups — promoting an unlisted
    one into the membership set before the test (§2.19, §2.13).
26. Never apply membership scope to a `primary_group` it substituted
    itself for an empty field (§2.13, §2.19).
27. Fail the logon on a malformed group SID, an unusable claim, a
    `canonical_name` PGSS §2.15 forbids, or an out-of-range identifier
    (§2.13).
28. Place `primary_group` on the token even when the source did not list
    it among `groups` (§2.13).
29. Perform derivation itself, and never accept privileges, integrity,
    or a token from a source (§2.4).
30. Never relay a refusal reason revealing a distinction the source was
    required not to make (§2.13).

### 2.22.1.5 Identifiers

31. Apply the source's base to every relative identifier it accepts, and
    never accept one already rebased (§2.20).
32. Refuse a relative identifier of `0` or one at or past the source's
    count, rather than clamping or wrapping it (§2.20).
33. Reserve a band of identifiers below every source's base for its own,
    and use its own value for any SID within that band regardless of
    what the source sent (§2.20).

### 2.22.1.6 Queries

34. Never send a message a source did not declare it answers, and never
    set a field bit gating a capability it did not declare (§2.8).
35. Never send more keys in one `Query` than the source's `max_batch`,
    nor more than 64 whatever it declared (§2.8).
36. Resolve an absolute POSIX identifier to a source and a relative
    identifier itself, and never send an absolute one to a source
    (§2.15).
37. Apply identity confinement, membership scope and numeric scope to a
    `QueryResult` exactly as to an `Assertion`, and validate every SID
    in one structurally — including those of references inside a value
    (§2.15).
38. Rebase every identifier in a result, under the rules of §2.20
    (§2.15).
39. Qualify a source's `canonical_name` itself; never require a source
    to (§2.15).
40. Consult no further source on a `Refused` result, treat only
    `NotFound` as leave to continue, and never relay a source's
    `Refused` outward as PGSS Logon's `Refused` outcome (§2.15).
41. Never record a source it may not ask — one that declared no
    `QUERIES` — as having answered `NotFound` (§2.15).
42. Relay cursors opaquely, never construct or modify a source's, and
    never restart an enumeration on a source's behalf (§2.16).
43. Record a source that declined or could not be reached, and not retry
    it for the remainder of that enumeration, across pages as well as
    within one (§2.16).
44. Never infer from a source declining to enumerate that it holds
    nothing (§2.16).

### 2.22.1.7 Caching

45. Not cache a source's answers at all unless it declared
    `PUSHES_CHANGES` or a non-zero `entry_ttl` (§2.8, §2.17).
46. Not hold an answer beyond a declared `entry_ttl` (§2.8).
47. Accept `Changed` at any time after `Registered`, and never reply to
    it (§2.17).
48. Re-read through `Query` after an invalidation, and never take a new
    value from `Changed` (§2.17).
49. Treat the loss of a source's connection as `All` for that source
    (§2.17).

An authority that holds nothing satisfies 45 to 49 trivially.

### 2.22.1.8 Credential change

An authority that relays PGSS Logon's credential change (PGSS §2.20)
over PSI MUST also satisfy the following. Obligations 19 to 21 bind a
change conversation as they bind an authentication.

50. Take `principal` from the client's connected socket, never from a
    message body (§2.21).
51. Send `ChangeCredential` only to the source authoritative for
    `principal`'s domain, never offer the change to another source, and
    never send it to a source that did not declare
    `CHANGES_CREDENTIALS` (§2.21, §2.8).
52. Answer the client `AuthorityUnavailable`, rather than refusing the
    account, where no registered source is authoritative for
    `principal` and a configured source is absent (§2.21).
53. End the client's conversation with `Internal` on an `Assertion` in a
    change conversation or a `CredentialChanged` in any other, minting
    nothing and reporting no change (§2.21).

### 2.22.1.9 Credential enrolment

An authority that relays PGSS Logon's enrolment (PGSS §2.23) over PSI
MUST also satisfy the following. Obligations 19 to 21 and 50 to 53 bind
an enrolment conversation as they bind a change, reading
`EnrollCredential` for `ChangeCredential`.

54. Never send `EnrollCredential` to a source that did not declare
    `ENROLLS_CREDENTIALS`, and answer the client `PermissionDenied` where
    the source holding the principal did not (§2.23, §2.8).
55. Relay `CredentialRejected` only from an enrolment conversation, and
    end any other conversation carrying it with `Internal` (§2.23,
    §2.13).

## 2.22.2 Source obligations

A principal source MUST satisfy all of the following.

### 2.22.2.1 Connection

1. Connect to the authority; never listen for it (§2.3).
2. Open with `Register` on conversation `0`, carrying its name and its
   domain (§2.8).
3. Send nothing else before receiving `Registered` (§2.8).
4. Report itself ready — to an init system or equivalent — only after
   `Registered` (§2.3).
5. Declare the same domain on every registration, for the life of the
   machine's configuration (§2.10).
6. Tear down the connection on a framing error or a failed write, on
   every path including an unsolicited `Changed` (§2.6, §2.17).

### 2.22.2.2 Conversations

7. Reply on the conversation identifier it was given, and never invent
   one (§2.7).
8. Decline to act on a message on a conversation it does not know, and
   never treat it as opening one — without replying on it, since the
   identifier may since have been reused (§2.7).
9. Refuse an `Authenticate`, `ChangeCredential`, `Query` or
   `EnumerateSource` arriving on conversation `0` (§2.7).
10. Bound the conversations it tracks itself, rather than relying on the
    authority's limit (§2.6).
11. Refuse beyond that bound with `AuthorityUnavailable`, rather than
    dropping silently (§2.11).
12. Discard conversation state on `Abandon`, and not reply (§2.14).

### 2.22.2.3 Answering

13. Send exactly one terminal message per conversation: `Assertion` or
    `Refusal` for an authentication, `CredentialChanged` or `Refusal` for
    a credential change (§2.13, §2.21).
14. Assert only principals within its declared domain (§2.18).
15. Assert group SIDs and identifiers only, never attributes (§2.13).
16. Carry the canonical spelling of the principal's name in
    `canonical_name` (§2.13), and never assert a name that PGSS §2.15
    forbids — validating what it asserts, not only what it creates.
17. Never distinguish an unknown principal from a bad credential — by
    denial code, by reason, or by timing (§2.13).

### 2.22.2.4 Identifiers

18. Assert **relative** identifiers only, and never apply its own base
    (§2.20).
19. Allocate from a single counter across every kind of object it holds,
    so that no number is issued twice (§2.20).
20. Send `0` for any object it does not number, including every group it
    does not own (§2.20).
21. Never issue an identifier at or past the count it was given (§2.20).

### 2.22.2.5 Queries

A source declaring no capabilities (§2.8) is exempt from this section
entirely.

22. Declare only capabilities it implements, and answer every message
    type it declared (§2.8).
23. Answer every key of a `Query`, in order, without reordering, merging
    or omitting — or refuse the conversation whole (§2.15).
24. Send `Found`, `NotFound` or `Refused` in a result, and never
    `Unavailable` or `Malformed` (§2.15).
25. Return its own canonical spelling of a name, unqualified (§2.15).
26. Return **relative** identifiers in a result, exactly as in an
    `Assertion` (§2.15, §2.20).
27. Answer only for principals within its declared domain, on a query as
    on a logon (§2.18).
28. Answer `Refused`, never an empty `Found`, wherever it is declining
    rather than reporting an absence — including a membership it will
    not expose, a key naming an object it does not hold, and a key of
    the wrong kind (§2.16).
29. Refuse a cursor it can no longer honor, rather than restarting or
    answering from a changed store (§2.16).
30. Hold no per-cursor state it is unwilling to discard unasked (§2.16).
31. Size a page against the smaller of PSI's message ceiling and PGSS
    Logon's, since the authority must re-encode it into the latter
    (§2.16, §2.A).
32. Send `Changed` before the altered answer becomes observable, if it
    declared `PUSHES_CHANGES` (§2.17).
33. Declare a non-zero `entry_ttl` if it does not push changes and can
    tolerate its answers being held, and SHOULD declare one even if it
    does (§2.8, §2.17).

### 2.22.2.6 Credentials

34. Store verifiers that are **not** usable as credential material —
    nothing a challenge could be recomputed from (PGSS §2.11). The one
    exception is NT material kept, as source policy, for Mschapv2 and
    Ntlmv2, which MUST never leave the source.
35. Erase credential material, and every buffer it was decoded through,
    before that memory is released (PGSS §2.12).
36. Never write credential material to a log, audit record, or
    diagnostic (PGSS §2.12).
37. Verify a presented proof against the authority's challenge without
    sending a `CredentialRequest`, and refuse with
    `AuthenticationFailed` a presented type it does not support (§2.11).

### 2.22.2.7 Logon type restrictions

38. State a principal's `permitted_logon_types` where it holds the
    property, and send zero where it does not (§2.13).
39. Never send "everything" for a principal whose restrictions it does
    not hold — zero is the honest answer, and "everything" asserts that
    the principal may be used for a credential-free service logon
    (§2.13, PGSS §2.19).
40. Never refuse an authentication on the strength of the restrictions
    it states. A source states; the authority decides (§2.4, §2.13).
41. Answer `LOGON_TYPES` from a `Query` as stored, including "not
    stated", and never substitute a default of its own — what silence
    means is the authority's reading, and two components with their own
    defaults can disagree (§2.15, PGSS §2.16).

### 2.22.2.8 Credential change

A source that declares `CHANGES_CREDENTIALS` MUST also satisfy the
following.

42. Change only the credential of `principal`, and never take a
    principal from anything the client supplied (§2.21).
43. Establish that the principal can present their current credential
    before changing it, and refuse with `AuthenticationFailed` where they
    cannot (§2.21).
44. Never change a credential on the strength of a current credential
    that has changed since it was proved (§2.21).
45. Refuse with `AccountRestricted` a principal it holds no changeable
    credential for (§2.21).
46. Send `CredentialChanged` only once the new credential is the one its
    next `Authenticate` for that principal will verify (§2.21).

### 2.22.2.9 Credential enrolment

A source that declares `ENROLLS_CREDENTIALS` MUST also satisfy the
following.

47. Add or remove credentials only of `principal`, and never take a
    principal from anything the client supplied (§2.23).
48. For both adding and removing, establish that the principal can
    present a credential they already have before changing anything,
    refuse with `AuthenticationFailed` where they cannot, and refuse with
    `AccountRestricted`, before asking, a principal it can ask for no such
    credential (§2.23).
49. Check the material again when applying the change, refuse material it
    will not accept with `CredentialRejected`, and send that code in no
    other conversation (§2.23).
50. Send `CredentialChanged` only once the change is durable, and, where
    it declares `PUSHES_CHANGES`, only after `Changed` (§2.23, §2.17).

## 2.22.3 What a source is not required to do

A source is **not** required to store anything, to be local, to be
persistent, or to know what a token is. It answers one question: given
this identifier and whatever it chose to ask for, who is this?

Nor is it required to trust the authority beyond the connection. A
source that refuses logons on the strength of `originator`, or declines
to answer for principals it holds but does not wish to expose, is
conforming.

---

# 2.23 Credential Enrolment

_Peios Specifications / PSPU / Principal Source Interface_

> EnrollCredential — relaying a principal's addition or removal of one of their own credentials to the source that holds it, the capability that gates it, and the proof the source must take first.

A PGSS Logon enrolment (PGSS §2.23) reaches the source that holds the
principal as a conversation of its own kind. It opens with
`EnrollCredential`, runs the relayed interrogation of §2.12, and ends in
`CredentialChanged` or `Refusal`.

```
  authority                              source
    |------------ EnrollCredential ---------->|   conversation N
    |<----------- CredentialRequest ----------|   the current credential
    |------------ CredentialResponse -------->|
    |<------ CredentialChanged | Refusal -----|
```

It is the sibling of the credential change (§2.21), and every rule that
section states binds here unless this section says otherwise: routing to
the source authoritative for the principal, `AuthorityUnavailable` while
a configured source is absent, the principal as established fact, the
terminals out of place, and `Abandon`.

## 2.23.1 EnrollCredential

`msg_type` = `0x0008`. Authority to source. **Opens a conversation.**

| Field | Encoding | Limit |
|---|---|---|
| `start` | nested `CredentialEnrollStart`, length-framed | PGSS §2.23 |
| `principal` | length-framed bytes (SID) | 68 bytes |

`start` is the client's `CredentialEnrollStart`, nested whole for the
reason `ChangeCredential` nests its start (§2.21). `principal` is the
user of the client's token, established by the authority from the
client's socket, exactly as in `ChangeCredential`. A source MUST NOT add
a credential to, or remove one from, any other principal in this
conversation.

## 2.23.2 The capability

An authority MUST NOT send `EnrollCredential` to a source that did not
declare `ENROLLS_CREDENTIALS` (§2.8). Where the source that holds the
principal did not declare it, the authority MUST answer the client
`PermissionDenied`: for that principal it does not offer enrolment, and
PGSS §2.23 gives that answer to an authority that does not.

`ENROLLS_CREDENTIALS` and `CHANGES_CREDENTIALS` are independent. A
source may change passwords and not enroll keys, or the reverse.

## 2.23.3 The interrogation

The source MUST establish that the principal can present a credential
they already have, other than the one being enrolled, before it adds or
removes anything, for `Add` and `Remove` alike, and MUST refuse with
`AuthenticationFailed` where they cannot. The token the authority read
`principal` from is not that proof. A source that cannot ask for such a
credential for this principal — the principal has none, or signs in only
with the kind being enrolled — MUST refuse with `AccountRestricted`
before asking anything.

The source decides which credential types it enrolls and what material it
accepts. It SHOULD check the material before asking for proof, MUST
check it again when it applies the change, and MUST refuse material it
will not accept with `CredentialRejected`. A source MUST NOT send
`CredentialRejected` in any conversation but this one, and an authority
receiving it in any other MUST end the client's conversation with
`Internal` (§2.13).

## 2.23.4 CredentialChanged

The successful terminal is `CredentialChanged` (§2.21), sent only once
the change is durable: an added key is one the source's next
`Authenticate` will accept where the principal's policy allows keys, and
a removed key is one it will not.

A source that declares `PUSHES_CHANGES` MUST send `Changed` (§2.17)
before `CredentialChanged`, as for any other change to what it holds.

Enrolment does not change which credentials the principal may sign in
with; that remains the source's administration.

---

# Appendix 2.A Message Reference

_Peios Specifications / PSPU / Principal Source Interface_

> Every PSI message by number and direction, the protocol constants, and the field limits — including the ceiling that actually binds a page.

## 2.A.1 Messages

| `msg_type` | Message | Direction | Conversation | Defined in |
|---|---|---|---|---|
| `0x8001` | `Register` | source → authority | `0` | §2.8 |
| `0x0001` | `Registered` | authority → source | `0` | §2.8 |
| `0x0002` | `Authenticate` | authority → source | 1+ (opens) | §2.11 |
| `0x8002` | `CredentialRequest` | source → authority | 1+ | §2.12 |
| `0x0003` | `CredentialResponse` | authority → source | 1+ | §2.12 |
| `0x8003` | `Assertion` | source → authority | 1+ (terminal) | §2.13 |
| `0x8004` | `Refusal` | source → authority | 1+ (terminal) | §2.13 |
| `0x0004` | `Abandon` | authority → source | 1+ (terminal) | §2.14 |
| `0x0005` | `Query` | authority → source | 1+ (opens) | §2.15 |
| `0x8005` | `QueryResult` | source → authority | 1+ (terminal) | §2.15 |
| `0x0006` | `EnumerateSource` | authority → source | 1+ (opens) | §2.16 |
| `0x8006` | `EnumerateResult` | source → authority | 1+ (terminal) | §2.16 |
| `0x8007` | `Changed` | source → authority | `0` | §2.17 |
| `0x0007` | `ChangeCredential` | authority → source | 1+ (opens) | §2.21 |
| `0x8008` | `CredentialChanged` | source → authority | 1+ (terminal) | §2.21, §2.23 |
| `0x0008` | `EnrollCredential` | authority → source | 1+ (opens) | §2.23 |

The high bit marks a message sent by **the source**, which is the
authority for its own principals (§2.7).

## 2.A.2 Protocol constants

| Constant | Value | Defined in |
|---|---|---|
| Socket path | the implementation's choice | §2.6 |
| Magic | `PPSI` (`50 50 53 49`) | §2.7 |
| Version | `2` | §2.7 |
| Header size | 20 bytes | §2.7 |
| Maximum message size | 81920 bytes | §2.7 |
| Reserved conversation | `0` | §2.7 |

## 2.A.3 Field limits

| Field | Maximum | Defined in |
|---|---|---|
| `source_name` | 32 bytes | §2.8 |
| `domain` | 68 bytes | §2.8 |
| `max_batch` | 64 | §2.8 |
| `originator` | 68 bytes | §2.11 |
| `principal` | 68 bytes | §2.21, §2.23 |
| `user_sid` | 68 bytes | §2.13 |
| `canonical_name` | 256 bytes | §2.13 |
| `groups` | 128 entries, each SID 68 bytes | §2.13 |
| `primary_group` | 68 bytes | §2.13 |
| `claims` | 64 entries | §2.13 |
| claim `name` | 255 bytes | §2.13 |
| claim `values` | 64 per claim | §2.13 |
| claim string value | 1024 bytes | §2.13 |
| claim octet value | 1024 bytes | §2.13 |
| claim SID value | 68 bytes | §2.13 |
| `reason` | 512 bytes | §2.13 |
| `keys` | 64 entries | §2.15 |
| key `name` | 256 bytes | §2.15 |
| `results` | 64 entries | §2.15 |
| `withheld` | 32 entries | §2.15 |
| `values` | 32 entries | §2.15 |
| `entries` | 256 entries | §2.16 |
| `cursor`, `next` | 256 bytes | §2.16 |

68 bytes is the largest a SID can be: an eight-byte prelude plus fifteen
sub-authorities (§2.7).

A claim name is bounded at 255 **bytes** of UTF-8 while PCDS §5.9 bounds
it at 255 UTF-16 code units. A string's UTF-16 length never exceeds its
UTF-8 byte length, so the byte bound is the stricter of the two and
satisfies PCDS without transcoding to find out.

The claim limits are otherwise tighter than PCDS §5.9 permits — it
allows 1024 values per claim. These bound the work an authority does
decoding a message it has not yet decided to believe, and nothing needs
a thousand-valued claim from a principal source.

Fields inside a nested `LogonStart`, `CredentialChangeStart`,
`CredentialRequest`, `CredentialResponse` or profile keep PGSS Logon's
limits (PGSS §2.A).

## 2.A.4 The ceiling that actually binds a page

None of the entry counts above is the constraint on how much a source
may return. **An entry that fits a PSI message need not fit the PGSS
Logon message the authority must re-encode it into**: this chapter's
ceiling is 81920 bytes and PGSS Logon's is 65536, and a `QueryResult` or
`EnumerateResult` entry travels outward inside the smaller one.

A source MUST therefore bound a reply by the **smaller** of the two
ceilings, not by this one, and MUST page rather than fill a PSI message
it knows an authority cannot forward. A page that fits here and not
there is a page nobody can deliver, and the entry-count bounds do not
prevent one — 256 entries of a few hundred bytes each exceeds both.

The margin an implementation leaves for the authority's own framing is
its own choice; leaving none is a defect.

---

# Appendix 2.B Enumerations

_Peios Specifications / PSPU / Principal Source Interface_

> The values PSI defines for itself — key types, result outcomes, change scopes, capabilities, and claim value types and flags.

Values PSI defines for itself. Everything else it carries is PGSS
Logon's — see PGSS §2.B.

Adding a value to any enumeration here is a breaking change requiring a
version bump (§2.7). The two exceptions are the capability bitmask
below, and PGSS Logon's field bitmask, which PSI carries unchanged and
which may gain bits without one.

## 2.B.1 Key types

Carried in a `Query` key entry's `key_type` (§2.15) as a `u8`.

| Value | Name | Key is in |
|---|---|---|
| 0 | *none* | The key entry is absent |
| 1 | `Name` | `name` |
| 2 | `Sid` | `sid` |
| 3 | `RelativeId` | `relative_id` |

Zero is not a key. It is how an `EnumerateSource` encodes an empty `of`
(§2.16), which is the only place it may appear; an encoder MUST NOT send
it in a `Query` key and a decoder MUST reject one that arrives there.

PGSS Logon's key types (PGSS §2.B) share the first two values and differ
in the third, where it carries an **absolute** POSIX identifier. The
values are not interchangeable and the tables are deliberately separate:
`3` means a rebased number on one side of the authority and a relative
one on the other, which is the whole of §2.20 expressed as a number.

## 2.B.2 Result outcomes

Carried in a result entry's `outcome` (§2.15) and in
`EnumerateResult.outcome` (§2.16) as a `u8`.

The values are PGSS Logon's (PGSS §2.B). A source may send only these
three:

| Value | Name |
|---|---|
| 1 | `Found` |
| 2 | `NotFound` |
| 4 | `Refused` |

`Unavailable` (`3`) and `Malformed` (`5`) are the authority's to produce
and MUST NOT be sent by a source — see §2.15. A decoder MUST reject
either arriving from a source, rather than leaving the check to a
caller.

## 2.B.3 Change scopes

Carried in `Changed.scope` (§2.17) as a `u8`.

| Value | Name |
|---|---|
| 1 | `All` |
| 2 | `Object` |

## 2.B.4 Capabilities

Carried in `Register.capabilities` (§2.8) as a `u32` bitmask.

| Bit | Name |
|---|---|
| 0 | `QUERIES` |
| 1 | `ENUMERATES` |
| 2 | `MEMBERS` |
| 3 | `PUSHES_CHANGES` |
| 4 | `CHANGES_CREDENTIALS` |
| 5 | `ENROLLS_CREDENTIALS` |

Unlike the enumerations above, a bit MAY be added here without a version
bump. A source that does not set a bit has not declared the capability,
and an authority MUST NOT send a message the source did not declare it
answers (§2.8) — so an authority that predates a bit simply never uses
it, and a source that predates one never sets it. Both are the safe
reading.

`MEMBERS` gates a *field* rather than a message: an authority MUST NOT
set the `MEMBERS` field bit of a `Query` (§2.15) against a source that
did not declare it.

## 2.B.5 Claim value types and flags

A claim's `value_type` and `flags` (§2.13) are PCDS §5.9's, and are not
restated here.

They are nonetheless **closed** on this interface: a decoder MUST reject
a value type or a flag bit it does not recognize, rather than carrying
it through to an authority that will put it on a token. Adding one is
therefore a breaking change to PSI by the rule above, even though the
values themselves belong to PCDS.

---

# Appendix 2.C What Is Shared with PGSS Logon

_Peios Specifications / PSPU / Principal Source Interface_

> A checklist of exactly what PSI shares with PGSS Logon unchanged, what it adds, and what it changes.

PSI is a superset of PGSS Logon (§2.5). This appendix consolidates
exactly what is shared, what is added, and what differs — as a checklist
for an implementer building both, and as the list to re-examine whenever
either specification changes.

## 2.C.1 Shared unchanged

| Element | PGSS | Note |
|---|---|---|
| `AuthenticationRequest` body | §2.24 | Nested whole inside `Authenticate`, without a Logon message header |
| `CredentialRequest` body | §2.8 | Byte-for-byte identical |
| `CredentialResponse` body | §2.8 | Byte-for-byte identical |
| `profile` body | §2.9 | Nested inside `Assertion`, relayed onward unchanged (§2.13) |
| Denial codes | §2.B | Reused by `Refusal` (§2.13) |
| Lookup result body, `present` onward | §2.16 | Nested inside a `QueryResult` entry (§2.15) |
| Field bitmask | §2.B | Carried unchanged by `Query` (§2.15) |
| Object kinds | §2.B | Carried unchanged by a key entry (§2.15) |
| Lookup outcomes | §2.B | A source may send three of the five (§2.B) |
| Header layout, first 12 bytes | §2.6 | Same fields at the same offsets |
| Byte order, string encoding, length framing | §2.6 | See §2.7 |
| Extensibility rules | §2.6 | Append-only; new enum value is breaking |
| Credential-handling obligations | §2.12 | Bind sources too (§2.22) |
| Name rules | §2.15 | Bind what a source asserts (§2.13) |

An implementation that reimplements any of these rather than sharing one
definition has taken on the job of keeping two copies in step. The
sharing is the point: a translation layer between two byte-identical
formats is a place for them to drift.

## 2.C.2 Added by PSI

| Element | Defined in |
|---|---|
| `conversation` header field | §2.7 |
| `Register` / `Registered` | §2.8 |
| `Authenticate`, wrapping a shared request, `originator` and optional local context | §2.11 |
| `Assertion` | §2.13 |
| `Abandon` | §2.14 |
| Domain claim and its checks | §2.10 |
| POSIX identifiers, and the ranges that confine them | §2.13, §2.20 |
| Claims carried from a source | §2.13 |
| `Query` / `QueryResult`, and batching | §2.15 |
| `EnumerateSource` / `EnumerateResult`, and cursors | §2.16 |
| `Changed`, and the cache contract | §2.17 |
| Source capabilities, TTL and batch limit | §2.8 |
| Relative key types, where PGSS Logon's are absolute | §2.15, §2.B |
| Identity, membership and numeric scope | §2.18 to §2.20 |

## 2.C.3 Differs

| | PGSS Logon | PSI |
|---|---|---|
| Magic | `PGSL` | `PPSI` |
| Header | 12 bytes | 20 bytes |
| Maximum message | 65536 | 81920 |
| Conversations per connection | one | many |
| Connection lifetime | one logon | the source's lifetime |
| High bit of `msg_type` | authority → client | source → authority |
| Success terminal | `AccessGranted` + token fd | `Assertion` — no session, no token |
| Socket path | normative | the implementation's choice |
| Key type `3` | absolute POSIX identifier | relative identifier |

The success terminal is what makes minting structurally impossible for a
source (§2.4); the socket path is normative in PGSS because it is a
conformance bar and not here because PSI is not one (§2.1).

The message ceiling is the row most likely to catch an implementer out,
because the larger number is the one that does *not* bind a reply — see
§2.A.

## 2.C.4 When either specification changes

A field appended to `AuthenticationRequest`, `CredentialRequest`,
`CredentialResponse` or `profile` in PGSS appears here automatically,
because the bodies are shared. That is the intended behavior and needs
no change to this chapter.

The profile is the one shared body that travels in the *opposite*
direction to the others: the interrogation bodies pass from the
authority outward to the client, while the profile originates at the
source and is relayed outward through the authority. It is shared for
the same reason regardless — one definition, so the value a source
states and the value a client reads cannot drift apart.

A new `Denial` value, a new `CredentialType`, or any change to the
header's first twelve bytes is a **breaking change to both** and requires a
coordinated version bump. An implementer maintaining both MUST NOT bump
one alone.

The one exception is a denial added under PGSS §2.6's rule for codes
that only newer messages draw. `NoSuchSession` is one: it answers only
requests a source is never party to, a source never sends it (§2.13),
and so no PSI peer of either age meets it.

---

# Appendix 2.D Prior Art

_Peios Specifications / PSPU / Principal Source Interface_

> The approaches PSI exists to avoid — in-process authentication packages above all — and the ones it adopts.

## 2.D.1 What this exists to avoid

The design is shaped more by rejected approaches than adopted ones.

**LSA authentication packages.** Windows loads authentication packages
as DLLs into the LSA process. A defect in any package is a defect in the
most privileged process on the system, and the packages are exactly the
components most likely to parse hostile input. PSI puts that boundary at
a process, permanently: there is no in-process extension point and no
message that could create one.

**PAM modules.** The same objection, plus stacking — offering a
credential to each module in turn until one accepts, which hands every
module the credentials of every other module's users. PSI resolves
*which* source answers before any credential is collected (§2.11).

**NSS.** Name service switch modules answer "who is this?" as a library
call in whatever process asked, with no boundary at all. PSI's answer is
a message from a process that was separately identified.

## 2.D.2 What is adopted

**RSI's shape**, specified in PSPK. A long-lived connection, sources
that dial in and register, multiplexed requests tagged with an
identifier, and the authority tearing down a connection it cannot parse.
PSI is recognizably the same family, and deliberately so — an
implementer who has written a registry source will find little
surprising here.

The differences are worth naming, because they follow from what is being
federated. A registry source is trusted with the correctness of a
subtree and the kernel validates its structure; a principal source is
trusted with identity, so the checks it faces are about *scope* — which
principals, which memberships, which numbers — rather than about
well-formedness alone. And the kernel assigns a registry source no
numeric range, because there is nothing to project.

**PGSS Logon's interrogation, wholesale.** Rather than inventing a
parallel vocabulary for prompts and answers, PSI relays PGSS Logon's
messages with identical bodies (§2.5). The gain is not brevity but
correctness: there is no translation layer to be lossy, and a source's
prompt reaches the client exactly as written.

## 2.D.3 Design influences

**Sources connect inward.** The authority never dials out. See §2.3 —
this is the single most consequential shape decision in the chapter.

**Assertion, not minting.** The success terminal deliberately cannot
express a session or a token (§2.4). The separation is structural rather
than a rule an implementer must remember.

**Domains claimed, not assumed.** A source states what it is
authoritative for and the authority confines it to that (§2.10, §2.18).
The alternative — an authority that trusts whatever a source says about
anyone — makes every source as dangerous as the most dangerous one.

**Relative numbers.** POSIX identifiers are the one thing a source
states that has no namespace of its own to be confined by, so the range
supplies one (§2.20). Nothing else in the protocol needed inventing; a
SID already carries its domain.

---

# 3.1 Scope and Roles

_Peios Specifications / PSPU / Observability Interfaces_

> The three channels by which programs deposit logs and metrics with an observability service, and the roles at each end.

This chapter specifies the **observability interfaces**: the three
channels by which the programs on a Peios system deposit logs and
metrics with an observability service, and by which anything on the
system asks that service what it holds.

There are three interfaces and they are specified together because they
are one contract from the service's side and because two of the three
share their encoding, their validation posture and their loss model:

- the **Log Ingestion Interface**, on which a producer submits log
  records (§3.6 to §3.8)
- the **Metric Ingestion Interface**, on which a producer submits
  metric samples (§3.9 to §3.13)
- the **Query Interface**, on which a client asks for stored events,
  logs and metrics and receives records (§3.14 to §3.28)

Three roles participate.

The **collector** is the process that accepts ingestion on the two
datagram channels, serves the query channel, and holds the data in
between. There is one collector. It is the party being asked, on all
three interfaces — which is why the obligations in this chapter fall
mostly on it, and why the producer and client roles are so thin.

A **producer** is a process that submits metric samples. Its KACS token
is conveyed with every datagram, and the collector verifies that it may
publish each metric name (§3.9). Service output reaches the log channel
through the service manager instead: the service manager authenticates
the service origin by the pipe it owns, then acts as the sole log broker
(§3.6).

A **client** is a process that issues a query and reads the result. A
client's identity, unlike a producer's, is established by the collector
and determines what it may see (§3.28).

One program is commonly all three at once.

This chapter covers:

- the shape of the three channels and why two are datagram and one is
  a stream (§3.3)
- the loss model, which is the load-bearing decision of the whole
  ingestion design (§3.4)
- encoding, timestamps and the timestamp domain (§3.5)
- the log record, its fields, and exactly which malformations cost the
  record and which are merely ignored (§3.6 to §3.8)
- the metric data model, the three metric types, the sample record, and
  what makes two samples the same time series (§3.9 to §3.13)
- the query channel, its framing, and the four response messages
  (§3.14 to §3.17)
- the query language: its shape, its lexis, its operators, its ordering
  and grouping semantics, and the three modes (§3.18 to §3.25)
- cross-type filtering and streaming (§3.26, §3.27)
- what a client is and is not told about data it may not read (§3.28)
- how these interfaces may be extended (§3.29)
- the obligations binding on each role (§3.30)

This chapter does not cover:

- Event *emission*. Events reach a collector through KMES, not through
  any interface here; the consumer side of that is specified in PSPK,
  and emission is a kernel interface offered to privileged callers.
- Event type vocabulary and payload schemas, which belong to whichever
  subsystem emits the event.
- How a collector stores, indexes, retains or accelerates anything —
  its own design. The mainline collector's is described in the eventd
  TRMP.
- Which principals receive publication rights for individual metric
  names, and how those rights are administered.
- Administering a collector's contents.

The third of those is the point of the whole document. A collector is
handed records and asked questions; how it gets from one to the other is
exactly what different collectors exist to do differently.

## 3.1.1 These interfaces are not a generic standard

These interfaces belong to one collector. A system that ships a
different collector, or none, is a system built from different parts
and has no use for them.

They are specified because they are *public*. Every service has its
output brokered into logs, every collection agent is a metric producer,
and every dashboard, alerting tool and command-line viewer is a query
client. All three of those are third-party positions, and all three need
a contract that stays put.

> [!NOTE]
> The Query Interface reaches *events* as well as logs and metrics, even
> though events do not arrive over any interface here. That asymmetry is
> deliberate: PSPK's ring-buffer interface is the raw transport, requires
> SeSecurityPrivilege, and applies no per-record access control. The
> query interface is how everything else reads events, and it is the only
> way to read them after the ring buffer has moved on.

---

# 3.2 Terminology

_Peios Specifications / PSPU / Observability Interfaces_

> Terms this chapter borrows unchanged from PSPK's KMES event stream and from elsewhere in the corpus.

Terms defined in PSPK for the KMES event stream — event, header,
payload, stamp, sequence number, origin class — are used here with the
same meaning and are not redefined. Terms defined in PCDS — GUID, SID,
Security Descriptor, ACL, ACE — likewise.

The following terms are specific to this chapter.

**Collector**: the process that accepts log and metric ingestion and
serves queries. The role, not the program: the mainline collector is
eventd, and this chapter never requires that it be.

**Producer**: a process that submits log records or metric samples.

**Client**: a process that issues a query.

**Log record**: one line of output from a program, with the light
metadata of §3.7 attached. A log record is text; the collector does not
parse it.

**Metric sample**: one measurement of one quantity at one moment,
belonging to a time series (§3.13).

**Time series**: the sequence of samples sharing a name, a label set,
and — for histograms — a set of bucket boundaries. Identity is defined
in §3.13.

**Boot ID**: a GUID identifying one boot of the system. Every record a
collector stores carries one, so that records from different boots are
never interleaved and per-CPU event sequence numbers, which restart each
boot, remain unambiguous. It is assigned outside this interface and is
visible to a client only as a queryable field.

**Datagram**: one message on an ingestion channel, carrying either one
record or a batch of them (§3.7, §3.11).

**Effective query range**: the half-open interval a query examines,
`[SINCE, UNTIL)`, with the bounds resolved as §3.19 defines.

**Concrete identifier**: the event type, log origin or metric name that
a stored record actually carries — as distinct from the pattern a query
or a Security Descriptor uses to match one. Access control resolves
per concrete identifier (§3.28).

---

# 3.3 Three Channels

_Peios Specifications / PSPU / Observability Interfaces_

> Two datagram sockets carrying data inward and one stream socket carrying it out — why the split, and how each is protected.

A collector listens on three `AF_UNIX` sockets. Two carry data inward,
one carries it out.

| Channel | Socket type | Direction | Section |
|---|---|---|---|
| Log ingestion | `SOCK_DGRAM` | producer to collector | §3.6 |
| Metric ingestion | `SOCK_DGRAM` | producer to collector | §3.9 |
| Query | `SOCK_STREAM` | request and response | §3.14 |

The pathnames are configuration and this chapter does not fix them. A
collector MUST serve each interface on a distinct socket; it MUST NOT
multiplex two of them onto one.

## 3.3.1 Why ingestion is datagram

Each submission is an independent message. A datagram either arrives
whole or does not arrive, so there is no framing to get wrong, no
length prefix to parse, no partial read to reassemble, and no connection
state to keep for a producer that submits one line an hour. The record
boundary is the datagram boundary.

The property that matters more is that a datagram socket **cannot exert
backpressure**. When the receive queue is full the kernel discards the
datagram and the sender proceeds. That is the behavior §3.4 requires,
and choosing a stream socket would make it unachievable: a full stream
buffer blocks the writer, which is precisely the outcome this design
forbids.

## 3.3.2 Why the query channel is a stream

A query result is arbitrarily large, is delivered in several messages,
and must not be silently truncated — the opposite requirements. It also
needs a caller identity, and a peer token can be obtained from a
connected stream socket. Both push the same way.

## 3.3.3 Separation

The three channels are separated for the same two reasons.

The first is **admission**. Each listening socket has its own receive
queue. Log volume is orders of magnitude above query volume on any
normal system, and a burst of either must not delay the other. Three
sockets means three populations of caller that cannot starve one
another, whatever load any of them is under.

The second is **access control**. The service manager alone writes the
log channel, while service processes write the metric channel under
their own conveyed identities; the set that may read either is
different again. Those want different Security Descriptors, and a
descriptor is a property of a socket.

The separation is **not** for isolation. One collector serves all three,
so a defect or a hang in any of them reaches the others regardless, and
this chapter does not pretend otherwise.

## 3.3.4 Protecting the channels

A collector MUST protect each socket with a Security Descriptor.

The log socket descriptor MUST deny `FILE_WRITE_DATA` to the Service
logon group before allowing SYSTEM. The service manager runs as SYSTEM
without the Service group; every service it launches, including a
SYSTEM service, carries that group. The ordered deny therefore makes
the service manager the log broker without making every SYSTEM service
one (§3.6).

The metric socket descriptor is coarse admission only. Every metric
datagram also carries a KACS sender token and every metric name is
authorized for `EVENTD_PUBLISH` (§3.9). A collector SHOULD let every
authenticated caller send by default, so that a publish grant to anyone
can be used; an operator MAY narrow it.

The query socket descriptor MUST let every authenticated caller connect.
What a caller may read is decided per identifier against the read policy
(§3.28), so a socket that admitted fewer callers would only make a
policy grant to anyone else impossible to use.

A collector MUST NOT rely on the socket's POSIX mode bits for this. On
Peios an access decision is routed through the object's Security
Descriptor, not through mode bits, so a mode set on a socket pathname
does not restrict anything; and an inode created without a descriptor is
denied to every caller, so a collector that binds a socket into a
directory carrying no inheritable ACEs produces a socket nothing can
reach. A collector MUST establish the descriptor on each socket before
it begins accepting on it.

---

# 3.4 Loss and Backpressure

_Peios Specifications / PSPU / Observability Interfaces_

> The decision that shapes both ingestion channels — a producer is never stalled, so data may be lost — and what a collector must not do about it.

The single decision that shapes both ingestion interfaces is this:
**a producer is never slowed down, and never told that a record was
lost.**

## 3.4.1 The obligation

A collector MUST NOT exert backpressure on a producer. A producer MUST
NOT stall, block, retry or otherwise change its behavior because a
collector is slow, busy, or absent.

The consequence is accepted openly. When a collector cannot drain an
ingestion socket as fast as producers fill it, the kernel discards
datagrams. Neither party is notified. A collector MUST NOT report the
loss to the producer, because there is no reply message on a datagram
channel and adding one would reintroduce the coupling this rule exists
to prevent.

## 3.4.2 Why loss is acceptable here

A lost log line is an inconvenience. A lost metric sample is a visible
gap in a chart. Neither is a failure of the system, and neither is worth
the cost of the alternative — which is either blocking the producer or
buffering without bound, and the second is only the first with a delay.

Events are the counter-example, and the reason the boundary between
events and logs matters. An event may be a security audit record whose
absence is itself the finding, so events do not travel on either
interface in this chapter: they travel through KMES, where loss is
detected, bounded and recorded. A program with data that must not be
lost emits an event; a program with output for a human to read writes a
log.

> [!NOTE]
> This is the practical test for producers deciding where output belongs.
> If you would want to know that a record went missing, it is not a log
> and not a metric.

## 3.4.3 What a collector must not do about it

A collector MUST NOT emit an event, write a log entry, or perform any
other work proportional to the volume of malformed or unwanted input it
receives.

Ingestion input is untrusted even though its admission is authenticated
(§3.3). A collector that reacted to bad input — by logging it, by
counting it in a way a client can observe, or by emitting a diagnostic
event — would hand an admitted process an amplification primitive: a
cheap malformed datagram producing an expensive durable record. Silence
is the defense. In-memory diagnostic counters and rate-limited standard
error output are permitted because they do not grow with durable input.

The rule binds only on responses to *input*. A collector MAY record its
own internal conditions, and the mainline collector records several,
as synthetic events and as health metrics (eventd TRMP §2.6, §5.7).

## 3.4.4 Ordering and duplication

A collector MUST NOT assume that datagrams arrive in the order they were
sent, and MUST NOT reorder or deduplicate the records inside one. A
producer MUST NOT assume that submitting two datagrams in order causes
them to be stored in that order; the timestamp field (§3.7, §3.11) is
the only ordering a producer controls.

Records are not deduplicated. A producer that submits the same record
twice has produced two records.

---

# 3.5 Encoding and Time

_Peios Specifications / PSPU / Observability Interfaces_

> MessagePack on every interface, the canonical subset producers must emit, and how timestamps are carried.

## 3.5.1 MessagePack

Every structured value on all three interfaces — log records, metric
samples, query requests, query responses — is encoded as MessagePack.
Strings are UTF-8.

The choice is inherited rather than made here: KMES event payloads are a
single MessagePack value, so a collector already carries a decoder and a
query result can carry an event payload outward without re-encoding it.

A decoder MUST accept any valid MessagePack encoding of a value it is
given. In particular a producer MAY use any length-prefix width that can
represent the value, and a collector MUST NOT require the shortest.

## 3.5.2 Canonical MessagePack

Where this chapter requires a **canonical** encoding, the value MUST be
encoded as follows:

- Nil and booleans use the fixed singleton encodings.
- Integers use the shortest encoding that preserves signedness:
  non-negative values use positive fixint, `uint8`, `uint16`, `uint32`
  or `uint64`; negative values use negative fixint, `int8`, `int16`,
  `int32` or `int64`.
- Floats are encoded as `float64`. Finite values use their IEEE-754
  binary64 representation; the infinities use the normal binary64
  encodings; **any** NaN is encoded as the single quiet NaN bit pattern
  `0x7ff8000000000000`.
- Strings, binary values, arrays and maps use the shortest length-prefix
  form capable of representing the length.
- Arrays encode each element recursively, in order.
- Maps encode keys and values recursively, with entries sorted by the
  canonical encoded key bytes; ties are broken by the canonical encoded
  value bytes.

Canonical encoding exists so that two values that are equal are also
byte-identical, which is what makes them comparable and orderable
without decoding. It is required in exactly two places: histogram
sample storage, where it makes a sample map a stable value (§3.11), and
array comparison in query ordering and grouping (§3.21).

It does **not** constrain what a producer sends. Ingestion accepts any
valid encoding.

## 3.5.3 Timestamps

A timestamp is wall-clock time in **nanoseconds since the Unix epoch,
UTC**, as a signed 64-bit value.

The **timestamp domain** is `0` to `9223372036854775807` inclusive. A
value outside it is invalid wherever it appears: as a producer-supplied
timestamp (§3.8, §3.12), as a query time literal (§3.19), or as a value
in a result record.

The domain has no negative half. A collector MUST reject a negative
timestamp rather than storing a time before 1970, and a query whose time
arithmetic lands below zero — `SINCE 100000d ago`, for example — MUST
produce an error rather than clamping.

> [!NOTE]
> The upper bound is `i64::MAX` nanoseconds, which is the year 2262. The
> domain is stated as a closed range rather than "whatever fits" because
> both parties must agree on where the edge is: a producer that clamps
> and a collector that rejects would disagree about the same sample.

Wall-clock time is not monotonic. A collector MUST store the timestamp
it is given or derives without correcting it, and MUST NOT assume that
timestamps within one time series increase (§3.13). A clock step
backwards produces records that are out of order with respect to their
arrival, and every ordering rule in this chapter is defined to remain
total and deterministic when that happens.

---

# 3.6 The Log Channel

_Peios Specifications / PSPU / Observability Interfaces_

> The log ingestion socket — its datagram ceiling, the receive queue as the only buffer, and what reachability a producer may assume.

A collector MUST expose an `AF_UNIX` `SOCK_DGRAM` socket for log
ingestion, protected by a Security Descriptor as §3.3 requires.

## 3.6.1 The datagram ceiling

A collector declares a maximum accepted datagram size, the **log
datagram ceiling**. The portable ceiling is **262144 bytes**. Every
collector MUST accept a whole datagram up to that size, and every
portable producer MUST bound its encoded datagrams to that size without
discovering collector configuration. A collector MAY accept more, but a
producer MUST NOT depend on that when implementing this interface.

A collector MUST receive log datagrams into a buffer of at least its
declared ceiling, and MUST discard a datagram the kernel reports as
truncated rather than storing the prefix that fitted.

A producer MUST NOT send a log datagram larger than the ceiling. One
that does is discarded whole, taking every record in it, and the
producer is not told (§3.4).

A sending socket's own buffer can be smaller than the ceiling. A
producer that may send a datagram longer than its socket's default send
capacity SHOULD first raise `SO_SNDBUF` enough to accommodate it.

On Linux, a Unix datagram longer than the **effective** `SO_SNDBUF`
returned by `getsockopt` minus 32 bytes is refused with `EMSGSIZE`.
Linux doubles the value requested with `setsockopt(SO_SNDBUF)` for
bookkeeping; the effective value must therefore be at least the
datagram's length plus 32 bytes. An ordinary unprivileged request is
capped at `net.core.wmem_max` before that doubling. The initial buffer
comes from `net.core.wmem_default`; neither sysctl has a universal value.

For example, with both sysctls set to 212992 bytes, the initial buffer
allows datagrams of at most 212960 bytes, below the portable ceiling.
Requesting 212992 bytes gives an effective buffer of 425984 bytes and a
datagram limit of 425952 bytes. A larger datagram needs a higher
`wmem_max` for an ordinary unprivileged sender. A collector's configured
ceiling does not itself enlarge the sender's buffer.

> [!NOTE]
> §3.A gives the mainline value and upward-adjustable range
> for this bound and every other in this chapter.

No capability exchange is needed. The 262144-byte floor is part of the
wire contract rather than a tunable assumption shared out of band.
Raising a collector's ceiling is a local extension; lowering it below
the portable ceiling is non-conforming.

## 3.6.2 The receive queue is the buffer

A collector MAY enlarge the socket receive queue, to at most four times
the datagram ceiling. It MUST NOT buffer beyond it.

That queue is the only cushion between a producer and the collector's
storage. While a collector is committing a batch it is not draining the
socket, and datagrams arriving in that window occupy the queue; when the
queue fills, they are discarded. This is the designed degradation
(§3.4), not a failure to be tuned away — a larger buffer moves the
threshold without changing what happens at it, and an unbounded one
converts data loss into memory exhaustion.

## 3.6.3 The service-manager broker

Every service produces output, including programs that know nothing
about the collector, but service processes do not write this socket.
The service manager holds each service's standard output and standard
error at fork, determines the origin from the pipe it read, and forwards
the resulting records (peinit TRM).

The log socket MUST implement the deny-Service, allow-SYSTEM descriptor
in §3.3. A collector MUST accept log origins from this broker without a
per-record KACS token or AccessCheck. A service can choose the bytes it
writes to its pipe but cannot choose another service's origin.

Direct log submission is not part of this interface. A program that
wants structured, authenticated observability data emits an event or a
metric; it does not bypass the service manager to assert a log origin.

---

# 3.7 Log Records

_Peios Specifications / PSPU / Observability Interfaces_

> The MessagePack map that carries a log record, one or batched — origin, is_error, timestamp and job_id.

A log datagram carries either **one** record, encoded as a MessagePack
map, or **several**, encoded as a MessagePack array of maps. A collector
MUST accept both forms. A producer MAY use either at any time; there is
no mode and no negotiation.

## 3.7.1 Fields

| Field | Type | Required | Meaning |
|---|---|---|---|
| `origin` | string | yes | Non-empty name of the program that produced the line. |
| `is_error` | bool | yes | True if the line came from standard error, or the producer marked it an error. False otherwise. |
| `message` | string | yes | The log text — one line of output. MAY be empty, which is a blank line. |
| `timestamp` | integer | no | When the line was produced, in the timestamp domain (§3.5). Absent means the collector uses its own clock at receipt. |
| `job_id` | binary, 16 bytes | no | A GUID in PCDS binary layout correlating this line to one execution of one program. |

A collector MUST ignore fields it does not recognize (§3.29).

## 3.7.2 `origin`

`origin` is what the producer says it is. A collector MUST NOT verify
it, because it has no way to: the channel is a datagram socket and
carries no peer identity (§3.4). Two producers MAY use the same origin,
and one producer MAY use several.

An origin is nonetheless the unit that read access is granted on
(§3.28), and a collector matches it against patterns using dot-delimited
prefix semantics: the pattern `svc` matches the origin `svc` and any
origin beginning `svc.`, and matches neither `svc_daemon` nor `svcfoo`.
It also matches every origin whose part before a slash is `svc`, such as
`svc/HealthCheck`, because matching considers only that part.

A producer therefore SHOULD choose an origin that names it stably and
distinguishably, and SHOULD use dots for hierarchy, because an
administrator writing an access rule has nothing else to write it
against.

An origin MUST match:

```text
origin    := component | component "/" producer
producer  := component | component "[" [0-9]+ "]"
component := [A-Za-z0-9_][A-Za-z0-9_.-]*
```

A collector MUST discard a record whose origin does not.

A single component is the identifier grammar of §3.19, widened only to
admit a leading digit, and names a program. The optional second
component names a **producer within** that program — a hook, a reload
command, a health check, one submitted job — and the bracketed integer
distinguishes several of the same kind. A forwarding service manager
uses it for exactly that: `jellyfin/ExecStartPre[0]` is a pre-start
hook's output, `jellyfin/HealthCheck` a health check's, `jobs/<guid>` a
submitted job's. There is at most one slash, and the index may appear
only after one.

Everything the grammar still excludes, it excludes on purpose. An
origin is not merely a label: it is matched against patterns in which
`*` is the wildcard, so an origin containing `*` could not be selected
exactly and could match a rule its producer was never meant to satisfy;
and it is the name an access rule is stored under, so an origin carrying
a backslash, a quoting character or whitespace could land somewhere
other than where the administrator who wrote the rule believes it is.
Constraining the producer is the only point at which either can be
prevented.

The slash is safe there only because it is never written into a stored
rule. A collector MUST resolve the access rule for an origin from the
part **before** the slash, so that a service's hooks, reloads, health
checks and jobs answer to the rule written against the service — and a
producer cannot reach a rule of its own by inventing a second component.

A collector MUST count discarded origins and MUST make that count
observable to an operator. An unrecognized origin means a producer's
vocabulary and a collector's have drifted apart, and every line that
producer sends is being dropped; a silent discard makes the most
complete kind of log loss the least visible one.

Quoted forms remain valid syntax everywhere an origin may be written
(§3.24). A single-component origin beginning with a letter or `_` never
needs them; every other conforming origin does, because the query
language's identifiers admit neither a slash, a bracket nor a leading
digit (§3.19). A *pattern* may need them too, and a collector holding
origins stored before this rule applied must still be able to return and
select them.

## 3.7.3 `is_error`

`is_error` is a boolean and deliberately not a severity level.

A forwarding producer can distinguish standard output from standard
error and nothing more; inventing five levels out of two file
descriptors would be a guess presented as data. A producer with real
severity levels either writes them into the message text, where they are
text and are searched as text, or emits events, which have types.

A system service SHOULD write informational messages to standard output
and warnings and errors to standard error. This keeps informational
startup and status messages out of `is_error == true` queries. Warnings
stay in them: they are diagnostics on standard error, and the collector
does not infer severity from text. Peios's own system daemons follow this
rule. A daemon's best-effort kernel-log mirror, where it has one, is
independent of the stream a line is written to.

## 3.7.4 `timestamp`

A producer SHOULD supply the timestamp it captured when the line was
produced, not when it submitted it. A producer that batches (§3.8) and
omits the field attributes every line in the batch to the moment the
collector happened to read it, which discards the timing information the
batch was accumulated over.

## 3.7.5 `job_id`

`job_id` correlates a line to a single execution rather than to a
program. A forwarding producer sets it so that the output of one run of
a service can be separated from the run before and the run after; a
producer with no such notion omits it.

A collector MUST treat it as an opaque 16-byte value. Nothing in this
chapter interprets it, and a producer MAY use it for any correlation of
its own, provided the value is a GUID.

---

# 3.8 Validating a Log Record

_Peios Specifications / PSPU / Observability Interfaces_

> The three scopes of silent failure — the whole datagram, one record, or one field — and what a collector adds on the way in.

Every failure on this channel is silent (§3.4). What differs between
failures is *how much* is lost: the whole datagram, one record, or only
one field.

## 3.8.1 The three scopes of failure

**The datagram is discarded** when it cannot be resolved into records at
all:

- it is not valid MessagePack
- it decodes to something that is neither a map nor an array of maps
- the kernel reported it truncated (§3.6)

**One record is discarded**, and the others in the same datagram are
still processed, when the record itself is unusable:

- a required field is absent
- a required field has the wrong type — `origin` an integer, say
- `origin` is the empty string
- the map contains a duplicate top-level key

**One field is ignored**, and the record is still stored, when an
optional field is unusable:

- `timestamp` is not an integer, is negative, or is outside the
  timestamp domain (§3.5)
- `job_id` is not binary, or is binary of a length other than 16

A collector MUST implement all three scopes as stated. In particular it
MUST NOT discard a record because an optional field was malformed: a
producer with a broken clock or a mangled correlation key still has a
log line worth keeping, and the field it got wrong is the field of least
value in the record.

## 3.8.2 Duplicate keys

A record map carrying the same top-level key twice MUST be discarded.

A collector MUST NOT resolve the duplicate by taking the first or the
last. MessagePack decoders differ on which they keep, and the fields
here are entirely producer-controlled, so a rule that depended on
decoder behavior would let a producer choose which of two `origin`
values a given collector saw. Discarding is the only answer that is the
same everywhere.

## 3.8.3 Batches

A batch is validated **per record**. A malformed record in a batch MUST
NOT cost the valid records beside it.

A producer SHOULD batch under sustained load. Batching amortises the
syscall over many records, and the ceiling (§3.6) is per datagram, so a
batch is also the only way to use the channel's capacity efficiently.

The encoded datagram, batched or not, MUST NOT exceed the ceiling. A
producer that batches without bounding the encoded size will eventually
build a datagram that is discarded whole — which is the one case where
batching loses more than sending singly would have.

## 3.8.4 What a collector adds

A collector supplies the boot ID (§3.2) and, when the record omitted
`timestamp`, its own clock reading at receipt. It MUST NOT alter any
other field, and MUST store `message` byte-for-byte as given.

A collector MUST NOT parse `message`. If the text happens to be JSON, or
logfmt, or anything else structured, that is the producer's business:
this interface carries lines, and a producer with structured data to
record emits an event instead (§3.4).

---

# 3.9 The Metric Channel

_Peios Specifications / PSPU / Observability Interfaces_

> The metric ingestion socket, separate from the log socket, and why the collector is a sink rather than a scraper.

A collector MUST expose an `AF_UNIX` `SOCK_DGRAM` socket for metric
ingestion, protected by a Security Descriptor as §3.3 requires,
separate from the log socket.

Before its first send, a producer MUST enable `KACS_SO_PASS_TOKEN` on
its persistent sending socket. KACS then attaches the producer's
effective token to every datagram as `KACS_SCM_TOKEN`. A collector MUST
receive with ancillary space for that token and MUST discard the whole
datagram when the token is absent or the data or control message was
truncated.

For every valid record, the collector resolves the metric name's
publication policy and runs KACS AccessCheck for `EVENTD_PUBLISH`
against the conveyed token. A denied record is discarded silently.
Records with other authorized names in the same datagram remain valid.
An implementation MAY cache a verdict by stable token identity, token
modification identity, metric name and policy generation.

The channel works exactly as the log channel does, for the reasons given
there: the 262144-byte portable datagram ceiling, truncated datagrams
discarded whole, a receive queue of at most four times the collector's
declared ceiling, no backpressure and no notification (§3.6). A
collector MUST accept at least the portable ceiling and a portable
producer MUST bound its encoded datagrams to it. A producer that may
send a datagram longer than its socket's default send capacity SHOULD
first raise `SO_SNDBUF`, as on the log channel (§3.6).

> [!NOTE]
> §3.A gives the mainline value and upward-adjustable range
> for this bound and every other in this chapter.

## 3.9.1 A sink, not a collector of its own

The collector is **pushed** to. It MUST NOT scrape an endpoint, read a
kernel interface, or poll anything to obtain metrics; every sample it
holds arrived on this socket because a producer sent it.

What gathers the measurements is a separate concern and a separate
program. A collection agent that reads system counters and submits them
is an ordinary producer here, with no privileged position and no
interface of its own.

> [!NOTE]
> The push direction follows from the loss model rather than from taste.
> A pulling collector must reach every producer on a schedule, which
> makes it responsible for their availability and makes a slow producer
> the collector's problem. Pushing keeps each producer responsible for
> its own submissions and keeps a slow or dead producer invisible to
> everything except the gap it leaves.

## 3.9.2 Batching

Batching matters more here than it does for logs. It amortizes both the
datagram and conveyed-token costs. A collection sweep
produces many samples at once — every CPU core, every disk, every
interface — and they share a moment, so a producer SHOULD submit a sweep
as one batched datagram rather than as one datagram per sample.

The rules are the log rules: one map or an array of maps, per-record
validation, and the encoded datagram bounded by the ceiling (§3.8,
§3.12).

---

# 3.10 The Metric Data Model

_Peios Specifications / PSPU / Observability Interfaces_

> What a metric is on this interface — names, labels, and the counter, gauge and histogram types, all valued as binary64.

A metric is a quantity that varies and is worth watching over time: a
utilization, a queue depth, a running total, a distribution of
latencies. Metrics are dense where events and logs are sparse — many
measurements of the same thing rather than a record of a thing that
happened — and the model reflects that.

A **sample** is one measurement, of one time series, at one moment. It
carries:

- a **name**, identifying what is measured
- a **label set**, identifying which instance of it
- a **type**, fixing how the value is to be read
- a **timestamp**
- a **value**, whose shape depends on the type

Name and labels together identify the series (§3.13). The type is a
property of the series, not of the sample.

## 3.10.1 Names

A name MUST match the identifier grammar of §3.19:

```text
[A-Za-z_][A-Za-z0-9_.-]*
```

A collector MUST discard a record whose name does not, for the same two
reasons an origin is constrained (§3.7): names are matched against
patterns in which `*` is the wildcard, and names are what read access is
granted on.

Beyond that, naming is convention and a collector MUST NOT enforce any.
The conventions in use are a dot-separated hierarchy from general to
specific, the unit as the last component, and a cumulative name for a
cumulative quantity:

```text
system.cpu.usage
disk.read.bytes
request.duration.seconds
http.requests.total
```

## 3.10.2 Labels

Labels are the dimensions of a measurement: which core, which device,
which method. `cpu.usage` with `core="0"` and `cpu.usage` with
`core="1"` are two series, not two samples of one.

Label keys and values MUST be non-empty UTF-8 strings. A key MUST match
the identifier grammar above; a value MUST NOT contain `=` (0x3D) or `,`
(0x2C), which are reserved as delimiters in the collector's canonical
representation of a label set (§3.13). A key MUST NOT be repeated within
one sample, and MUST NOT be any of the six fixed field names a metric
result carries — `timestamp`, `boot_id`, `name`, `type`, `value`,
`overflow` —
because labels and fixed fields share one flat namespace in a result
record (§3.22) and a collision would make the record ambiguous.

A record violating any of these is discarded (§3.12).

> [!NOTE]
> Label keys are constrained to the identifier grammar for the reason
> that matters most in practice: a key that cannot be written in a query
> cannot be filtered on, grouped by, or granted access to. A label you
> cannot address is storage you cannot reach.

**Label cardinality is the producer's responsibility.** Each distinct
combination of label values is a distinct series, so labels whose values
are unbounded — request identifiers, user-supplied strings, timestamps —
produce series without limit, and a collector is required neither to cap
them nor to degrade gracefully when they arrive. A producer SHOULD use
labels whose value sets are small and known. A dimension that is not
bounded belongs in an event payload, where it costs one field, not in a
label, where it costs a series.

A collector may bound its total metric storage through retention without
limiting series creation. Peios eventd does this by default: it continues
accepting new series but removes the oldest samples when the metric
store's logical live size exceeds its configured ceiling. That protects
the volume; it does not make high-cardinality labels safe, because an
active set larger than the series cache can still thrash ingestion.

## 3.10.3 Types

The type is fixed when the series is first seen and is **immutable**. A
sample that resolves to an existing series but declares a different type
is discarded (§3.12), permanently and without a response to the
producer. A producer that changes the type of a metric it already emits
has stopped emitting it. The mainline collector counts these conflicts,
retains the latest metric name and expected and received types in memory,
and may report them through its bounded operator diagnostics (§3.12).

### 3.10.3.1 Counter

A value that only increases, and resets to zero when the producer
restarts. Used for cumulative quantities: requests served, bytes
transmitted, errors encountered.

A counter value MUST be a finite, non-negative binary64 value.

The raw value is rarely what a reader wants; the rate of change is
(§3.25). A decrease is read as a restart rather than as a negative
change, which is why the type must be declared: the same number sequence
means something different for a gauge.

### 3.10.3.2 Gauge

A value that may move in either direction. Used for current state: a
utilization, an amount in use, a depth, a temperature.

A gauge value MUST be a finite binary64 value, and MAY be negative.

### 3.10.3.3 Histogram

A distribution of observations across buckets the producer chose. Used
where the shape matters more than the mean — latencies above all.

A histogram value carries:

- **boundaries**: a non-empty array of bucket upper bounds, strictly
  increasing in the order given
- **counts**: one cumulative count per boundary, each being the number
  of observations less than or equal to that boundary; non-decreasing,
  and each no greater than the total
- **total_count**: the number of observations
- **sum**: the finite sum of the observations

Boundaries are part of the series identity (§3.13). A collector MUST NOT
sort or reinterpret them; a producer that changes them has started a new
series, and SHOULD therefore keep them fixed for the life of a metric.

The final count MAY be less than the total: observations above the
highest boundary are the difference between them, and are not otherwise
represented. A total of zero is a valid empty sample, in which case
every count and the sum MUST be zero.

> [!NOTE]
> Observations above the highest boundary are counted but not located.
> A reader asking for a high percentile of a distribution whose tail
> overflows gets an explicit overflow result rather than a wrong numeric
> answer (§3.25), so a producer SHOULD choose a highest boundary above
> the values it expects to see.

## 3.10.4 Values are floating point

Numeric input MAY be a MessagePack integer or a MessagePack float; both
are converted to binary64 with round-to-nearest, ties-to-even. Every
value a collector stores and every numeric value a query returns is a
finite binary64. The null value in an explicit percentile-overflow result
is not a numeric metric value (§3.25).

Non-finite values are refused rather than stored: a record whose value
converts to NaN or to either infinity is discarded (§3.12). There is no
representation for a missing measurement — a producer with nothing to
report sends nothing, and the gap is the answer (§3.13).

---

# 3.11 Metric Records

_Peios Specifications / PSPU / Observability Interfaces_

> The MessagePack map that carries one metric sample, the histogram value shape, and why type is per record rather than per series.

A metric datagram carries one record, encoded as a MessagePack map, or
several, encoded as an array of maps. A collector MUST accept both
(§3.9). Each map is one sample of one series.

## 3.11.1 Fields

| Field | Type | Required | Meaning |
|---|---|---|---|
| `name` | string | yes | The metric name (§3.10). |
| `labels` | map | no | Key-value string pairs. Absent means the series has no labels, which is not the same as a series whose labels are empty — it is the same series. |
| `type` | string | yes | Exactly `"counter"`, `"gauge"` or `"histogram"`, lowercase. |
| `timestamp` | integer | no | When the measurement was taken, in the timestamp domain (§3.5). Absent means the collector uses its own clock at receipt. |
| `value` | varies | yes | The measurement. A number for counter and gauge; a map for histogram. |

A collector MUST ignore fields it does not recognize (§3.29).

## 3.11.2 The histogram value

For a histogram, `value` is a map:

| Field | Type | Meaning |
|---|---|---|
| `boundaries` | array of number | Non-empty, finite bucket upper bounds, strictly increasing after conversion to binary64, in the order given. |
| `counts` | array of integer | Cumulative count per boundary. Same length as `boundaries`. Non-decreasing, each no greater than `total_count`. |
| `total_count` | integer | Number of observations. |
| `sum` | number | Finite sum of the observations. |

Counts and `total_count` MUST be MessagePack unsigned integers, or
non-negative signed integers. `boundaries` and `sum` MAY be integers or
floats and are converted as §3.10 requires.

## 3.11.3 `type` is per record, not per series

Every record declares its type, including the second and every
subsequent sample of a series that already exists.

This is redundant on the wire and deliberately so. A producer holds no
state about what a collector already knows, has no way to ask, and MUST
NOT be required to establish a series before sampling it: the first
sample of a series and the millionth are the same message. The
redundancy is what makes a producer stateless, and the cost is one short
string per sample.

The collector uses the declaration only on first sight. Afterwards it is
a consistency check, and a record that fails it is discarded (§3.10).

## 3.11.4 Timestamps need not increase

A collector MUST store a valid sample whose timestamp is older than
samples it already holds for that series.

Producers batch, clocks step, and a collection sweep may be submitted
out of order or retried. A collector that refused late samples would
turn any of those into silent data loss, so it accepts them and defines
every ordering it performs over `timestamp` rather than over arrival
(§3.21, §3.25). Two samples of one series MAY share a timestamp; the
collector orders them deterministically and a client MUST NOT depend on
which comes first.

---

# 3.12 Validating a Metric Record

_Peios Specifications / PSPU / Observability Interfaces_

> What causes a metric datagram or a single record to be discarded, silently, and why the timestamp rule differs from the log channel's.

Failures on this channel are silent, exactly as on the log channel
(§3.4, §3.8). The scopes are the same, with one difference that matters:
**a metric record has no ignorable field.** Every field a metric record
carries participates either in the series identity or in the
measurement, so there is nothing whose loss leaves a usable record
behind. A malformed `timestamp` costs the log line nothing and costs the
sample everything.

## 3.12.1 The datagram is discarded

- it is not valid MessagePack
- it decodes to something that is neither a map nor an array of maps
- no KACS sender token arrived
- the kernel reported its data or ancillary data truncated (§3.9)
- the collector cannot query the sender token or resolve publication
  policy

## 3.12.2 The record is discarded

A collector MUST discard a record, leaving the rest of its batch
untouched, for any of the following.

**Structure**

- a required field is absent, or has the wrong type
- the map contains a duplicate top-level key
- `type` is not exactly `"counter"`, `"gauge"` or `"histogram"`

**Name and labels** (§3.10)

- `name` is empty or does not match the identifier grammar
- a label key or value is not a string, or is empty
- a label key does not match the identifier grammar
- a label value contains `=` or `,`
- a label key is repeated within the record
- a label key is one of `timestamp`, `boot_id`, `name`, `type`, `value`,
  `overflow`

**Timestamp**

- `timestamp` is present and is not an integer, is negative, or is
  outside the timestamp domain (§3.5)

**Counter and gauge values**

- the value is not a number
- it converts to a non-finite binary64
- it is negative and the type is counter

**Histogram values**

- the value is not a map, or its map has a duplicate key
- a field is absent or has the wrong type
- `boundaries` is empty
- a boundary or `sum` converts to a non-finite binary64
- `counts` and `boundaries` differ in length
- the converted boundaries are not strictly increasing
- a count is negative, the counts are not non-decreasing, or a count
  exceeds `total_count`
- `total_count` is zero and any count or `sum` is non-zero

**Series consistency**

- the record resolves to an existing series whose type differs (§3.10)

**Publication policy**

- the conveyed KACS token is denied `EVENTD_PUBLISH` for `name` (§3.9)

## 3.12.3 Why the timestamp rule differs from logs

On the log channel a malformed timestamp is ignored and the record
kept; here it discards the record.

The asymmetry is not an inconsistency. A log line with the wrong time is
still the line, and reading it is still worth doing. A sample is a
`(time, value)` pair and nothing else: attaching the collector's receipt
time to a measurement taken at an unknown moment does not recover the
sample, it fabricates one, and it fabricates one that will be charted
next to real ones. Discarding leaves a gap, which is honest (§3.4).

Absence is different from malformation. A record that simply omits
`timestamp` is asserting "now", and the collector's clock is the right
answer to that.

## 3.12.4 Silence, again

A collector MUST NOT emit an event, write a durable log, or increment
anything a query client can observe in response to any failure in this
article — with no exception for the series-consistency failure, which is
the one that most looks like it deserves one. Local in-memory diagnostic
counters and rate-limited standard-error output are permitted by §3.4.

A producer that changes a metric's type is misconfigured, and the
misconfiguration is permanent: every sample is discarded for as long as
the series exists, and the producer receives no response. Peios eventd
increments an in-memory total, retains the latest conflicting metric name
and expected and received types, emits at most one coalesced
standard-error warning per minute, and includes the total and latest
conflict in its `SIGQUIT` diagnostic dump. None of those signals is part
of the query interface or grows in proportion to rejected input.

---

# 3.13 Series Identity

_Peios Specifications / PSPU / Observability Interfaces_

> What makes two samples the same time series — name, labels and histogram boundaries — and what pointedly does not participate.

Two samples belong to the same time series when they agree on:

- the **name**, compared exactly, byte for byte; and
- the **label set**, compared as an unordered set of key-value pairs,
  each compared exactly; and
- for histograms, the **bucket boundaries**, compared as an ordered
  sequence of binary64 values.

Nothing else participates. Type does not: a record whose type disagrees
resolves to the series and is then discarded for disagreeing (§3.10).
Boot ID does not: a series continues across a reboot, and a client that
wants one boot's worth filters for it (§3.25). Time does not.

## 3.13.1 Order does not distinguish a label set

`{core: "0", host: "a"}` and `{host: "a", core: "0"}` are the same
series. A collector MUST compare label sets as sets.

To do so it needs a canonical form, and the form in use is the reason
label values may not contain `=` or `,` (§3.10): pairs are sorted by key
in unsigned UTF-8 byte order, each written `key=value`, and joined with
commas. Because neither delimiter can occur inside a key or a value, no
escaping is needed and no two distinct label sets can produce the same
string.

The byte form itself is the collector's business and this chapter does
not require it. What it requires is the property: **a label set has
exactly one identity, independent of the order the producer wrote it
in.** The delimiter reservation is stated normatively because it binds
the *producer*, and a producer cannot see the encoding that motivates it.

## 3.13.2 Absent labels and empty labels

A record with no `labels` field, a record with an empty `labels` map,
and a record whose labels were all discarded are the same series: the
one with no labels. There is no distinction between "unlabeled" and
"labeled with nothing".

## 3.13.3 Boundaries are identity, not metadata

Two histogram samples with different boundaries are different series
even when name and labels agree.

This is the consequence that surprises producers, and it is unavoidable:
cumulative counts against one set of bucket edges cannot be compared
with counts against another, so calling them one series would mean
computing percentiles across incommensurable distributions. A producer
that re-tunes its buckets each collection cycle creates a series each
cycle, each holding a single sample and each surviving until retention
removes it.

A collector MUST NOT defend against this. It is a producer defect, it is
indistinguishable at the interface from legitimately introducing a new
metric, and every defense available — capping series, merging near-equal
boundary sets, rejecting a second boundary set for a name — would break
a correct producer to inconvenience an incorrect one.

## 3.13.4 Series are created, never announced

A series comes into existence when its first sample arrives. There is no
registration message, no schema, and no way to declare a series in
advance or to retire one.

A collector MUST NOT require a series to be known before a sample of it
is accepted, and MUST NOT limit how many series exist. A series with no
remaining samples ceases to exist when retention removes the last of
them; nothing else removes one.

> [!NOTE]
> The absence of a cap is a deliberate and load-bearing decision, and it
> is worth being clear about what it costs. Labels are producer-supplied
> and are not part of publication authorization (§3.9), so a producer
> authorized for one metric name can create series beneath that name
> without limit. Name authorization bounds the namespace, not its label
> cardinality.
> Without a byte ceiling, each series persists until the retention window
> elapses. A collector-level ceiling may remove the oldest samples, and
> then their orphaned series, earlier; it bounds storage rather than
> admission and does not change this rule.

## 3.13.5 Gaps are preserved

A collector MUST NOT interpolate, backfill, or synthesise a sample that
a producer did not send.

A missing sample is a real fact about the system — the producer was
down, the datagram was dropped, the sweep was late — and it is a fact
the metric is often being watched for. A series with a hole in it is
returned with a hole in it, and a client that wants a value across the
hole computes one itself.

---

# 3.14 The Query Channel

_Peios Specifications / PSPU / Observability Interfaces_

> The query socket — one query per connection, the identity captured at connect, and why no credentials cross it.

A collector MUST expose an `AF_UNIX` `SOCK_STREAM` socket for queries,
protected by a Security Descriptor as §3.3 requires.

One socket serves all three data types. The mode a query runs in —
events, logs or metrics — is determined by parsing the query string
(§3.18), never by the transport, so a client needs no connection setup,
no mode selection, and no separate endpoint per data type.

## 3.14.1 One query per connection

A connection carries exactly one query. A client that wants two
concurrent queries opens two connections.

A collector MUST close the connection after the terminal message of a
non-streaming query (§3.16), and MUST treat a client disconnect as
cancellation of a streaming one.

> [!NOTE]
> This is the opposite of the identity-lookup channel in PGSS §2.14,
> which multiplexes tagged requests over one connection. The reason is
> the shape of the work rather than a difference in taste: a lookup is
> small, uniform and answered in one message, so correlating many on one
> connection saves real cost. A query may run for thirty seconds, may
> stream indefinitely, and may be canceled — and every one of those is
> expressed by the connection itself, with no correlation identifier and
> no cancellation message to specify.

## 3.14.2 Identity

A collector MUST establish the client's identity from the connected
socket, before executing anything, by obtaining the peer's token. This
is possible here and not on the ingestion channels, and it is the whole
reason the query channel is a stream (§3.3).

The token is captured **once**, at connection time, and is a snapshot. A
client whose privileges change while a query runs — and in particular
while a streaming query runs, which may be indefinitely — is evaluated
throughout against the token it connected with.

If a collector cannot obtain the peer token, it MUST refuse the query.
It MUST NOT execute a query for an unidentified caller, and MUST NOT
fall back to any other means of identifying one.

## 3.14.3 No credentials cross this channel

There is no message with which a client offers a credential and none
with which a collector asks for one. Identity is established from the
connection and from nothing else.

## 3.14.4 Concurrency

A collector MUST bound the number of queries it will execute at once,
and MUST reject a query beyond the bound with an error rather than
queueing it behind the others.

The streaming bound is the lower of the two and is enforced separately,
because a streaming query holds its resources for as long as its client
stays connected while an ordinary one holds them for at most a timeout
(§3.16).

> [!NOTE]
> §3.A gives the mainline value and adjustable range
> for this bound and every other in this chapter.

Both bounds are global. Because every authenticated caller may connect
(§3.3), a collector MUST also bound the queries one caller may have
running at once, so that one caller cannot occupy every slot. The
caller is the user SID of the token captured at connect. A collector
MAY leave SYSTEM's queries uncounted. A query beyond the caller's bound
is rejected with an error, like one beyond the global bounds.

Neither bound may affect ingestion: queries and ingestion are separate
channels precisely so that exhausting one cannot exhaust the other
(§3.3).

---

# 3.15 Query Framing

_Peios Specifications / PSPU / Observability Interfaces_

> Length-prefixed MessagePack in both directions, the inbound request ceiling, and the outbound response target.

Every message in either direction is a length-prefixed MessagePack
value:

| Offset | Size | Field | Value |
|---|---|---|---|
| 0 | 4 | `length` | Length of the payload in bytes |
| 4 | `length` | `payload` | The request or response body |

`length` is little-endian, as PSPU §1.2 requires of every integer field
in this document. It counts the payload only; the four bytes of the
prefix are not included.

There is no magic value and no version field. The channel is a Unix
socket at a configured path, so there is no possibility of reaching the
wrong service by accident in the way a shared header guards against
(PSPU §2.7), and versioning is handled as §3.29 describes.

## 3.15.1 The two size controls

A collector declares two independent sizes. The **query request
ceiling** is a hard inbound limit. The **query response target** is a
soft outbound batching target. They are separate because an untrusted
client must not be able to force an arbitrarily large allocation merely
by declaring a request length, while a record the collector has already
accepted must remain possible to return.

> [!NOTE]
> §3.A gives the mainline value and adjustable range
> for both sizes and every other bound in this chapter.

**Inbound.** A collector MUST refuse a request whose `length` exceeds
the request ceiling. It MUST do so without reading the payload — the
point of checking the prefix is to avoid allocating for a request that
a malicious or broken client has declared too large — and it MUST send
an error response (§3.16) before closing the connection. A collector
MUST NOT close on an oversized request silently: a bare close is
indistinguishable from a crash, and leaves a client unable to tell that
shortening its query is the remedy.

**Outbound.** A collector SHOULD chunk result records so an ordinary
response does not exceed the response target (§3.16). The target is not
a ceiling: when one complete record would exceed it, the collector MUST
send that record alone in one response rather than split, truncate,
skip, or reject it.

## 3.15.2 Every stored record must remain returnable

A collector MUST NOT store a record whose encoded result representation
cannot fit in the protocol's `u32` payload length. This structural
framing bound is the only outbound ceiling.

A single result record is never split across messages (§3.16). A
collector MUST therefore ensure that its accepted record encodings have
a bounded result expansion that fits one frame. It MAY establish that
statically from the protocol's record limits; it need not flatten or
encode each record on the ingestion path merely to check response size.
An implementation MAY encode a large response incrementally after
writing its known length; it need not allocate another buffer as large
as the record.

The ingestion ceilings (§3.6, §3.9) remain independent configuration.
Raising one does not require raising the response target: it merely
makes a single-record response above that target more likely. The
structural `u32` requirement is a property of the wire encodings, not a
configurable coupling between those values.

## 3.15.3 Requests

A request is a MessagePack map:

| Field | Type | Required | Meaning |
|---|---|---|---|
| `query` | string | yes | The query string (§3.18). |

A collector MUST send an error response and close the connection if the
payload is not valid MessagePack, is not a map, omits `query`, gives
`query` a non-string value, or contains a duplicate top-level key. It
MUST ignore unrecognized fields that are not duplicates (§3.29).

Unlike the ingestion channels, nothing here is silent. A query client is
identified (§3.14), is one of a bounded number, and is asking a
question, so telling it what went wrong is neither an amplification
vector nor an information leak — with the one exception §3.28 sets out.

---

# 3.16 Responses

_Peios Specifications / PSPU / Observability Interfaces_

> The four response kinds a query can receive, how records are chunked, and how errors and timeouts are reported.

A response is a MessagePack map whose `status` field names its kind.
There are four.

| `status` | Carries | Meaning |
|---|---|---|
| `"ok"` | `records` | A chunk of result records. |
| `"end"` | — | The non-streaming query is complete. |
| `"watch"` | — | The streaming query's initial result set is complete. |
| `"error"` | `error` | The query failed. |

## 3.16.1 Result messages

An `"ok"` message carries `records`, an array of flat maps (§3.22).

Records are chunked at record boundaries: a successful query sends one
or more `"ok"` messages, ordinarily at or below the response target
(§3.15). A collector MUST NOT split one record across two messages. If
one complete record exceeds the target, that record occupies an
otherwise empty `"ok"` message by itself. It MUST NOT be truncated,
partially sent, skipped, or turned into a query error merely because it
exceeds the target.

Each record is self-describing and records in one response MAY carry
different sets of keys — event payload fields vary by event type, metric
labels vary by series. A client MUST NOT assume a uniform schema across
a result set, and MUST NOT infer that a key absent from one record is
absent from the data.

A successful query with no matching records sends exactly one `"ok"`
message with an empty `records` array, then its terminal message. A
collector MUST NOT omit it: "no records" and "the query has not yet
produced records" are different states and a client must be able to tell
them apart.

## 3.16.2 The two terminal messages

`"end"` terminates a non-streaming query. `"watch"` marks the point in a
streaming query where the stored result set ends and live delivery
begins (§3.27). A query sends exactly one of them, never both.

Until one has arrived, **the query has not succeeded**. A collector that
fails partway through MUST send `"error"`, and a client that receives
`"error"` before either terminal message MUST discard every `"ok"`
message it received for that query. Partial results are not results:
they are an arbitrary prefix of an ordering that was never completed,
and a client that kept them would silently under-report.

An `"error"` *after* `"watch"` is different. It terminates the stream,
and the records already delivered remain valid — they were complete when
they were sent, and the ordering they belonged to had already closed.

## 3.16.3 Errors

An `"error"` message carries `error`, a human-readable string.

There is no error code and no machine-readable classification. This is a
deliberate limit on the interface: an error here is a parse failure, a
type mismatch, a timeout, a limit, or a refusal, and a client's response
to all of them is the same — show it to whoever wrote the query. A
client MUST NOT parse the string, and a collector MAY change the wording
of any error at any time.

A collector MUST NOT include in an error message any value the client
was not authorized to read (§3.28).

## 3.16.4 Timeouts

A collector MUST bound the time a query may take to reach its terminal
message.

> [!NOTE]
> §3.A gives the mainline value and adjustable range
> for this bound and every other in this chapter.

The clock starts once the request has been decoded and the caller's
token obtained, and it covers everything that follows: parsing, access
checks, cross-type pre-computation, execution, merging, aggregation,
pagination, projection and transmission. A collector MUST send `"end"`,
or for a streaming query `"watch"`, before it expires.

The timeout bounds the **initial result set only**. Once a streaming
query has sent `"watch"` its watch phase is not time-limited; what
bounds it instead is the streaming concurrency limit (§3.14), the
distinct-value limit (§3.27), and the client's own ability to keep up
(§3.27).

On expiry a collector MUST cancel the query and send `"error"`. Any
`"ok"` messages already sent are discarded by the client under the rule
above.

## 3.16.5 Memory

A non-aggregating query in the default order (§3.21) needs to hold
nothing while it runs: its records can be read in that order and sent
as they are read. A collector SHOULD answer it so, and MUST NOT refuse
it for the size of its result, however large. A client that wants every
record of a large store asks for exactly this.

Other queries must hold something to answer: a sort on another field
holds the records it orders, or with `TAKE` only the best `SKIP + TAKE`
of them, and an aggregation holds its groups. A collector MAY bound the
memory queries hold. When a query would exceed the bound, the collector
MUST fail it with `"error"`. It MUST NOT truncate the result, drop
groups, or answer from part of the data instead.

> [!NOTE]
> §3.A gives the mainline bound. The mainline collector applies one
> bound to every running query together, as it does for concurrency
> (§3.14), so a query can fail because others hold memory. Retrying it
> later may succeed.

---

# 3.17 Value Encoding

_Peios Specifications / PSPU / Observability Interfaces_

> How every value in a result record is encoded — including why a GUID is a string — and why missing and null are the same value.

Every value in a result record is encoded as follows.

| Value | Encoding |
|---|---|
| Integer | MessagePack integer |
| Float | MessagePack `float64` |
| Timestamp | MessagePack integer, nanoseconds since the Unix epoch (§3.5) |
| String | MessagePack string |
| GUID | MessagePack string, PCDS canonical form |
| Binary | MessagePack `bin` |
| Boolean | MessagePack boolean |
| Array | MessagePack array |
| Absent or null | MessagePack nil |

A GUID is rendered as a string rather than as sixteen bytes because a
result record is read by people as often as by programs, and a raw GUID
in a terminal is unreadable. The canonical form is lowercase
`8-4-4-4-12` hexadecimal within braces, as PCDS defines it. A query
comparing against a GUID accepts either braced or unbraced input, and
compares case-insensitively (§3.19); a result always uses the canonical
form.

## 3.17.1 Maps do not appear as values

An event payload is a MessagePack map, and result records are flat
(§3.22). A map in a stored payload is therefore a *container to be
flattened*, not a value to be emitted: its entries become top-level
keys of the record, joined by dots, and the map itself never appears.

Arrays are different. An array is emitted as an array value at its
flattened path, and a collector MUST NOT traverse into it. Maps nested
inside an array are preserved as that array's contents, unflattened and
unqueryable.

The asymmetry is deliberate. A map has keys, so its entries have names
that can be addressed, granted access to and indexed. An array has
positions, and a path like `hops.3.address` would mean something
different in every record — so an array is carried across whole and
treated as one value.

Being one value is also why `==` against an array field compares the
whole array. The question usually being asked of one — does it hold this
element — is `HAS` (§3.20).

Binary values in a payload stay binary. A collector MUST NOT render
`bin` as a string, in either direction.

## 3.17.2 Missing and null are the same value

A field absent from an event payload or from a metric's label set
encodes as nil, exactly as an explicitly null one does, and the two are
indistinguishable in a result record.

This is consistent throughout: they compare equal, they sort together,
and they group together (§3.20, §3.21). A collector MUST NOT distinguish
them anywhere in the query surface, and a client MUST NOT attempt to.

---

# 3.18 The Query Language

_Peios Specifications / PSPU / Observability Interfaces_

> One string that names a mode, narrows to some data and says what to do with it — the three modes, the clauses, and their execution order.

A query is one string. It names a mode, narrows to some data, and says
what to do with it.

```text
EVENTS kacs.* SINCE 1h ago WHERE emitter.process.guid == "550e8400-e29b-41d4-a716-446655440000" TAKE 100
LOGS FROM loregd ERROR ONLY CONTAINING "connection refused" SINCE 1d ago
METRIC cpu.usage[core="0"] SINCE 1h ago AVG_OVER 5m
```

## 3.18.1 Three modes

The first token selects the mode, and a collector MUST reject a query
whose first token is not one of them.

- **`EVENTS`** searches structured event records, primarily by event
  type (§3.23).
- **`LOGS`** searches log output, primarily by origin (§3.24).
- **`METRIC`** evaluates measurements, primarily by name and labels
  (§3.25).

Events and logs are *record-oriented*: collections you search, returning
the records that matched. Metrics are *value-oriented*: measurements you
evaluate, returning numbers computed from samples. The modes differ
because the data differs, and forcing all three through one shape would
serve none of them.

## 3.18.2 The primary selector

Immediately after the mode comes an optional **primary selector**,
specific to the mode: an event type pattern, `FROM` with one or more log
origins, or a metric name with an optional label selector. It narrows
the data before anything else runs.

A primary selector MUST NOT be repeated unless its mode defines a list
form — `LOGS FROM a, b` is one selector naming two origins, not two
selectors.

## 3.18.3 Clauses

Everything after the primary selector is a **clause**, and clauses MAY
appear in any order. `EVENTS SINCE 1h ago TAKE 10` and
`EVENTS TAKE 10 SINCE 1h ago` are the same query.

Order of appearance never affects meaning. Execution follows the fixed
sequence below regardless of how the string was written, so a collector
MUST NOT derive semantics from clause position.

These clauses work identically in all three modes:

| Clause | Meaning |
|---|---|
| `SINCE t` | Lower time bound, inclusive. |
| `UNTIL t` | Upper time bound, exclusive. Defaults to the evaluation time. |
| `WHERE p` | Filter by a predicate (§3.20). |
| `WHERE METRIC …` / `WHERE EVENT …` / `WHERE LOG …` | Filter by a condition on another data type (§3.26). |
| `SORT f [ASC\|DESC], …` | Order the results (§3.21). |
| `TAKE n` | Return at most `n`. |
| `SKIP n` | Discard the first `n` after ordering. |
| `STREAM` | Deliver matching records as they arrive (§3.27). |

## 3.18.4 Execution order

Whatever order the clauses were written in, a collector MUST evaluate
them in this sequence:

| | Phase |
|---|---|
| 1 | Cross-type conditions, producing time ranges (§3.26) |
| 2 | The primary selector |
| 3 | Access control on the primary and cross-type sources (§3.28) |
| 4 | `SINCE` and `UNTIL` |
| 5 | `WHERE`, including the ranges from phase 1 |
| 6 | `ERROR ONLY` and `CONTAINING`, as `WHERE` predicates (§3.24) |
| 7 | Metric transforms (§3.25) |
| 8 | `GROUP` |
| 9 | `COUNT BY`, `TOP N BY`, `DISTINCT`, and the aggregation functions |
| 10 | Metric window aggregations (§3.25) |
| 11 | `SORT` (§3.21) |
| 12 | `SKIP` and `TAKE` |
| 13 | `SELECT` (§3.22) |

Two positions in that list are load-bearing.

**Access control is third**, before every filter, aggregate, sort and
limit. It is part of the query's logical execution and not a filter
applied to the output (§3.28).

**`SELECT` is last.** It shapes the output and nothing else; a field it
omits is still available to every earlier phase (§3.22).

## 3.18.5 Repetition

A clause MUST appear at most once, and a collector MUST reject a repeat
as a parse error, with two exceptions:

- **`WHERE` is repeatable.** Multiple `WHERE` clauses are combined with
  `AND`, each treated as a parenthesised group: `WHERE a == 1 OR b == 2`
  followed by `WHERE c == 3` means `(a == 1 OR b == 2) AND c == 3`.
- **`SELECT` is repeatable** where it is valid at all, and is additive:
  `SELECT event.time SELECT event.type` names both fields.

Both exist so that a query can be built up in pieces — by a tool
appending a filter, or by a person adding one to a query they already
have — without rewriting what is already there.

## 3.18.6 Counts

`TAKE`, `SKIP` and the `N` of `TOP N BY` are unsigned decimal integers
that MUST fit in 64 bits. A negative, hexadecimal, floating-point or
missing count is a parse error.

`SKIP` defaults to 0. `TAKE` omitted means no limit. `TAKE 0` and
`TOP 0 BY` are valid, and return no records after every earlier phase
has run — which is not the same as not running the query, because a
`TOP 0 BY` still counts and a `TAKE 0` still enforces access control.

> [!NOTE]
> A non-aggregating query without `TAKE` has no implicit limit, and a
> broad one over a long range may match millions of records. The timeout
> (§3.16) is the only backstop.

## 3.18.7 Case

Keywords are matched case-insensitively, using ASCII case folding, in
grammar positions where a keyword is expected. This document writes them
in uppercase by convention only.

Identifiers are case-sensitive, except where the language defines a
named alias for a value (§3.23).

A word spelled like a keyword MAY be used where the grammar expects an
identifier or a value: `LOGS FROM stream` selects the origin `stream`,
while `LOGS STREAM` enables streaming. A collector MUST resolve the
ambiguity by grammar position and MUST NOT reserve keywords globally.

---

# 3.19 Lexical Rules and Literals

_Peios Specifications / PSPU / Observability Interfaces_

> The lexical layer — identifiers, strings, binary, numbers, durations and times — and what fixes the evaluation time.

A query string is UTF-8. Whitespace separates tokens outside quoted
strings and is otherwise insignificant.

## 3.19.1 Identifiers

An unquoted identifier is ASCII and matches:

```text
[A-Za-z_][A-Za-z0-9_.-]*
```

Identifiers name fields, payload paths, metric names, label keys, event
type patterns, log origins and value aliases. `.`, `_` and `-` are
permitted inside one; `/`, `:`, whitespace, quotes, brackets,
parentheses, commas and the comparison operators are not.

This grammar is the same one that constrains a metric name and a metric
label key at ingestion (§3.10), which is what makes every stored metric
identifier writable here without quoting. A log origin is the one
exception: it is constrained to a near relative of this grammar (§3.7)
that also admits a leading digit and a producer component such as
`/ExecStartPre[0]`, and an origin using either is written as a quoted
string.

A value that cannot be written as an identifier MUST be written as a
quoted string. Quoted forms are accepted anywhere an identifier is —
they are never required for a conforming identifier, but a *pattern* may
need one, and a collector holding identifiers stored under an earlier
revision must still be able to select them.

## 3.19.2 Strings

A string literal is double-quoted UTF-8. The escapes are `\"`, `\\`,
`\n`, `\r`, `\t`, and `\uXXXX` for a scalar value in `U+0000` to
`U+FFFF` written as four hexadecimal digits.

A collector MUST reject any other backslash escape as a parse error, and
MUST reject `\uXXXX` naming a surrogate code point in `U+D800` to
`U+DFFF`. Surrogate pairs are not decoded: a character outside the basic
multilingual plane is written directly as UTF-8, not as two escapes.

> [!NOTE]
> Refusing surrogates rather than pairing them means there is exactly one
> way to write every character, and no way to write a sequence that is
> not valid UTF-8. A language that accepts lone surrogates has to decide
> what they mean when compared against stored text that cannot contain
> them.

## 3.19.3 Binary

A binary literal is a lowercase `x`, a double quote, an even number of
hexadecimal digits, and a closing quote:

```text
WHERE target_sid == x"010500000000000515000000"
```

Hexadecimal digits inside are case-insensitive. `x""` is valid and is
the empty byte string. Whitespace inside the payload, an odd digit
count, and any non-hexadecimal character are parse errors.

A binary literal compares only against MessagePack `bin` values. A
collector MUST NOT coerce one to a string or a string to one: `x"6162"`
and `"ab"` are different values and never compare equal (§3.20).

## 3.19.4 Integers

An integer literal is decimal or hexadecimal.

```text
WHERE emitter.class == 2
WHERE access.granted == 0x1F01FF
```

A decimal integer MAY carry a leading `-`, in which case it MUST fit in
signed 64 bits; without one it MUST fit in unsigned 64 bits. A
hexadecimal integer is `0x` followed by one or more digits, is always
non-negative, and MUST fit in unsigned 64 bits. A leading `+` is not
valid. An out-of-range literal is a parse error.

## 3.19.5 Floats

A float literal is a finite decimal number with an optional leading `-`
and either a fractional part or an exponent: `42.0`, `0.001`, `1e6`,
`-1.25e-3`. A token that looks like an integer, such as `42`, **is** an
integer literal and not a float.

Float literals are binary64 and MUST be finite. `NaN`, `Infinity`,
`-Infinity` and any literal that overflows to infinity are parse errors.
A leading `+` is not valid.

## 3.19.6 Booleans and null

`true` and `false` are matched case-insensitively with ASCII folding.

`NULL`, likewise folded, is valid **only** in `IS NULL` and
`IS NOT NULL`. A collector MUST reject `field == NULL` and
`field != NULL` as parse errors rather than evaluating them.

> [!NOTE]
> Equality against null is refused rather than defined because every
> definition of it is a trap. Under three-valued logic it is neither
> true nor false, which no other operator here does; under two-valued
> logic it silently disagrees with SQL. `IS NULL` says what was meant
> and cannot be misread.

## 3.19.7 Durations

A duration is an unsigned decimal integer followed immediately by `s`,
`m`, `h` or `d` — seconds, minutes, hours or days. A zero duration is a
parse error.

## 3.19.8 Times

| Literal | Meaning |
|---|---|
| `<duration> ago` | That duration before the evaluation time. |
| `<duration> hence` | That duration after it. |
| `today` | Midnight of the current day, UTC. |
| `yesterday` | Midnight of the previous day, UTC. |
| `YYYY-MM-DD` | Midnight of that date, UTC. |
| `YYYY-MM-DDTHH:MM:SS` | That instant, UTC. |

Absolute literals are a fixed UTC subset. Components MUST be zero-padded
exactly as shown, the date MUST be a valid Gregorian date, hours are
`00`–`23`, minutes and seconds `00`–`59`. Leap seconds are not accepted.
Timezone suffixes and fractional seconds are not part of this revision
and MUST produce a parse error.

## 3.19.9 The evaluation time

A collector MUST capture the evaluation time **once**, before execution
begins, and MUST use that one reading for every `ago`, every `hence`,
and for an omitted `UNTIL`, throughout the query — including throughout
the watch phase of a streaming query.

A query that read the clock more than once could produce a range whose
end preceded its start, or a window that grew while it was being
scanned. One reading makes the effective query range a fixed interval
for the life of the query.

`SINCE` is inclusive, `UNTIL` is exclusive: the effective query range is
`[SINCE, UNTIL)`. If `SINCE` is greater than or equal to `UNTIL` the
query returns no records — which is a successful query with an empty
result (§3.16), not an error. A time literal that evaluates outside the
timestamp domain MUST produce an error (§3.5).

---

# 3.20 Comparison and Logic

_Peios Specifications / PSPU / Observability Interfaces_

> The operators, case-folding on strings, why types never coerce, how absent fields behave, and how predicates combine.

## 3.20.1 Operators

| Operator | Meaning | Operand types |
|---|---|---|
| `==` | Equal | any |
| `!=` | Not equal | any |
| `>` `>=` `<` `<=` | Ordering | integer, float, timestamp |
| `STARTS_WITH` | Prefix | string |
| `ENDS_WITH` | Suffix | string |
| `CONTAINS` | Substring | string |
| `HAS` | Array contains an element | array |
| `IN` | Member of a set | any |
| `NOT_IN` | Not a member | any |
| `IS NULL` | Absent or null | any |
| `IS NOT NULL` | Present and not null | any |

`IN` and `NOT_IN` take a non-empty parenthesised, comma-separated list
of literals. An empty list is a parse error.

```text
WHERE origin IN ("loregd", "peinit")
WHERE emitter.class NOT_IN (kacs, lcs)
```

`=` is not a comparison operator and MUST produce a parse error, with
one exception: inside a metric label selector, where `=` and `==` are
both equality (§3.25).

## 3.20.2 HAS asks about an array

`HAS` is true when the field holds an array one of whose elements equals
the value, compared as `==` compares it, so a binary literal matches a
binary element exactly and a string element folds case.

```text
EVENTS WHERE subject.token.groups HAS x"010200000000000520000000200200"
```

A payload field MAY hold an array — a token's group SIDs are the
canonical example — and `==` against an array is whole-value equality:
an array equals only an array of the same length whose elements are
equal in order. That is what an operand of a different type compares
against, so `==` between an array field and a single element is a type
mismatch and evaluates false, exactly as §3.20's "types do not coerce"
says. `HAS` is the operator that asks the other question.

`HAS` applied to a field that is not an array evaluates **false** for
that record, for the same reason an ordering operator applied to a
non-numeric value does: a payload field's type varies from record to
record. Elements are compared one level deep — an element that is itself
an array is compared whole, not searched.

`HAS` is not a set operator and MUST NOT be confused with `IN`. `IN`
asks whether a scalar field equals one of several literals; `HAS` asks
whether one array field holds one literal. `CONTAINS` is substring
matching on a string and has nothing to do with either.

A collector MAY evaluate `HAS` by scanning: array containment need not
be indexable, and answering correctly without an index is required where
answering quickly is not.

## 3.20.3 Strings fold case

Every string comparison — `==`, `!=`, `STARTS_WITH`, `ENDS_WITH`,
`CONTAINS`, `HAS`, `IN`, `NOT_IN` — is **case-insensitive**, using
ASCII-only folding: bytes `A`–`Z` compare equal to `a`–`z`, and every non-ASCII
byte compares exactly.

This applies uniformly: to event header fields, to payload fields, to
log messages, to metric label values, and to the pattern matching of
primary selectors. Integers, floats, GUIDs, timestamps and binary values
are unaffected.

> [!NOTE]
> Folding is ASCII-only rather than Unicode because full case folding is
> locale-dependent, version-dependent and expensive, and because the data
> it would be applied to — identifiers, service names, event types — is
> ASCII by construction (§3.19). A collector that folded Turkish dotless
> `ı` would have to fold it the same way as every other collector, for
> every Unicode version, forever.

## 3.20.4 Numbers compare mathematically

Integers and floats compare by mathematical value, not by casting both
to one storage type.

An integer equals a finite float only when the float represents exactly
that value. Ordering between an integer and a float MUST be exact,
including for integers outside the range binary64 can represent exactly.
A collector MUST NOT resolve `9007199254740993 > 9007199254740992.0` by
converting the left operand to a float, which would make it false.

### 3.20.4.1 NaN

An event payload may carry a NaN (§3.5), though a literal never can
(§3.19). Every NaN is one value: it equals every other NaN and nothing
else, so `x == 5` is false and `x != 5` is true for a record whose `x`
is a NaN.

An ordering operator with a NaN on either side evaluates **false**, as
IEEE 754 has it. `x < 5` and `x >= 5` are both false for that record.
Sorting and grouping still need a place for a NaN, and §3.21 gives it
one.

## 3.20.5 Types do not coerce

Values of different non-numeric types are never equal. The string `"1"`
is not the integer `1`, and `!=` between them is true.

An ordering operator applied to a field whose runtime value is
non-numeric evaluates **false** for that record — not an error, because
a payload field's type varies from record to record and a query cannot
know in advance.

An ordering operator applied to a *known fixed field* whose declared
type cannot be ordered is different: a collector MUST reject the query
during parsing or planning rather than executing a predicate that can
never match. `WHERE message > 5` is a mistake the collector can see, and
returning zero records for it would be a wrong answer that looks like a
right one.

Binary values compare by exact byte equality under `==`, `!=`, `HAS`,
`IN` and `NOT_IN`. Ordering is **not defined** for binary values, and a
predicate applying an ordering operator to a binary literal MUST produce
a parse error.

## 3.20.6 Absent fields

A field absent from an event payload or from a metric's label set
resolves to null (§3.17).

Every comparison against null evaluates false, except `IS NULL`, which
is true, and `IS NOT NULL`, which is false. In particular
`WHERE field != "x"` does **not** match records lacking the field: a
record with no opinion is not a record with a different opinion.

## 3.20.7 Combining predicates

Predicates within one `WHERE` combine with `AND` and `OR`. `AND` binds
tighter than `OR`. Parentheses override.

Multiple `WHERE` clauses combine with `AND`, each parenthesised as a
group (§3.18).

There is no `NOT`. Negation is written with the negative operators —
`!=`, `NOT_IN`, `IS NOT NULL` — and a collector MUST reject `NOT` as a
parse error rather than silently treating it as an identifier.

---

# 3.21 Ordering, Grouping and Distinct

_Peios Specifications / PSPU / Observability Interfaces_

> SORT, GROUP and DISTINCT — and the two rules that make paging a query safe: one query, one order.

Two rules govern this article, and both exist for the same reason.

**Ordering MUST be total and deterministic.** For a fixed set of stored
records, one query MUST produce one order. Without that, `SKIP` and
`TAKE` are meaningless: a client paging through results would see
records twice and never see others, and would have no way to tell.

**Equality here MUST be the query language's, not the storage
engine's.** A collector that grouped by whatever its database considers
equal would group differently depending on how it was built.

## 3.21.1 SORT

`SORT` orders by one or more fields. Each defaults to ascending; `ASC`
may be written, `DESC` reverses that field.

```text
SORT timestamp DESC
SORT origin ASC, timestamp DESC
```

If the named fields do not uniquely order two records, a collector MUST
append internal tiebreakers until the order is total. The tiebreakers
are not query-language fields, are never emitted in a result record, and
a client MUST NOT depend on their identity — only on their effect, which
is that the order is stable.

When no `SORT` is present:

- **Events and logs** are ordered by timestamp descending, most recent
  first — the order a person reading a log wants.
- **Metrics** are ordered by timestamp ascending, the order a chart
  wants.

## 3.21.2 Value ordering

`SORT` uses the query language's ordering, not the storage engine's.
Missing fields and explicit nulls are equivalent. Ascending order sorts
by type first, in this order:

1. Null
2. Boolean, `false` before `true`
3. Numeric, integers and floats compared mathematically (§3.20)
4. String and GUID, ASCII-folded
5. Binary, unsigned lexicographic
6. Array

`DESC` reverses the whole ordering, type order included.

A NaN is numeric and sorts **after every other number**, the infinities
included. Every NaN is one value, so NaNs tie with each other and fall
to the tiebreakers. Without a place for it the order would not be
total: a NaN is neither less than, greater than nor equal to any number
under IEEE 754, and a sort given such a comparison may produce any order
at all, or fail.

Strings and GUIDs compare with the same ASCII folding as predicates. Two
strings equal under folding are ordered by their original UTF-8 bytes,
so that folding never costs totality. Binary values compare as unsigned
bytes. Arrays compare by their canonical MessagePack encoding (§3.5).

Maps do not appear as result values (§3.17) and MUST NOT appear as sort
keys.

## 3.21.3 Grouping

`COUNT BY`, `TOP N BY`, `GROUP` and `DISTINCT` use query-language
equality:

- missing and null are one group
- integers and floats that are numerically equal are one group
- every NaN is one group
- strings and GUIDs group under ASCII folding
- binary values group by exact bytes

## 3.21.4 The canonical representative

When a group's members are equal under those rules but not
byte-identical — `"Loregd"` and `"loregd"`, or `1` and `1.0` — the value
emitted for the group MUST be its **canonical representative**:

| Group | Representative |
|---|---|
| Null | nil |
| Boolean | the boolean |
| Numeric | an integer if every contributing value was an integer; otherwise a `float64` |
| String or GUID | the smallest original UTF-8 byte sequence among the members |
| Binary | the exact value |
| Array | the member with the smallest canonical MessagePack encoding |

Choosing the smallest rather than the first makes the representative a
property of the *set*, independent of the order records were read in —
which matters because a collector may read them from several places at
once and merge (eventd TRMP §6.4).

## 3.21.5 Ordering of aggregates

`COUNT BY` and `GROUP … COUNT` results are ordered by `count`
descending. Ties are broken by the group key under the value ordering
above — for a `GROUP` of several fields, each key in turn in the order
the fields are named — then by the representative's encoded bytes.

`GROUP … SUM`, `AVG`, `MIN` and `MAX` results MUST be ordered by their
group keys ascending under the value ordering above, comparing each key
in the order the fields are named. This order applies before `SKIP` and
`TAKE`. An explicit `SORT` overrides it; groups tied under that sort
retain their group-key order.

`TOP N BY` is exactly `COUNT BY` with `TAKE N` applied after that
ordering.

`DISTINCT` results are ordered by the distinct value under the value
ordering, unless an explicit `SORT` overrides it.

---

# 3.22 Fields and Results

_Peios Specifications / PSPU / Observability Interfaces_

> Every result record is a flat map — the event, log and metric field sets, the reserved header names, and how nesting is flattened.

Every result record is a **flat** MessagePack map. There is no nesting
in a result, in any mode.

Flatness is what makes one set of rules — for access control, for
ordering, for grouping, for projection — apply uniformly to a header
field, a payload field and a metric label alike. A nested result would
need a path language, and a path language would need to be reproduced
identically by every SD author and every client.

## 3.22.1 Event fields

These names resolve to header fields, by the mapping of PGSS §6.4:

`event.time`, `event.sequence`, `event.cpu`, `event.type`,
`event.boot.guid`, `emitter.class`, `emitter.token.guid`,
`emitter.true-token.guid`, `emitter.process.guid`

Every other name resolves to a payload field.

### 3.22.1.1 Header names are reserved

Header field names are reserved in the query language and in result
maps. If a payload carries a value whose flattened path is a header
field's name, **the header wins**.

The colliding payload value is stored unchanged, and is retrievable as
part of the raw payload by whatever holds it, but it is not exposed
through field resolution, `SELECT`, `WHERE`, aggregation, access control
or result maps. If the payload carries a map at a header field's path,
the map's entire subtree is suppressed in the same way.

Only the paths themselves are reserved. A payload field beside them,
such as `emitter.process.pid`, resolves normally. An emitter MUST NOT
write a value at a header path (PGSS §6.4).

> [!NOTE]
> The header must win because header fields are the ones the kernel
> stamped and an emitter could not influence (PSPK §2). If a payload
> value could shadow `emitter.process.guid`, an emitter could choose what
> its own events appeared to come from, and every query filtering on
> identity would be answerable by the party being investigated.

### 3.22.1.2 Flattening

Payload maps are flattened recursively, path segments joined with `.`:
a payload `{source: {name: "x"}}` exposes the field `source.name`.

Each map key on a queryable path MUST be a MessagePack string matching:

```text
[A-Za-z_][A-Za-z0-9_-]*
```

Note that `.` is **not** permitted in a segment, though it is permitted
in an identifier generally (§3.19) — a key containing a dot could not be
distinguished from a path through two maps.

A key that is not a string, contains `.`, or does not match the grammar
is stored unchanged and is **not queryable**: it does not resolve, does
not appear in a result map, and has no field identity for access
control. An empty map produces no field at all.

Maps are containers; every non-map value, arrays included, is emitted at
its flattened path (§3.17).

If two payload entries flatten to the same path, the **first in
MessagePack map order wins** and later duplicates are suppressed.

## 3.22.2 Log fields

`timestamp`, `origin`, `is_error`, `message`, `boot_id`, `job_id`

The set is closed. There are no payload fields and no flattening, and a
collector MUST reject any other log field name as a parse error rather
than resolving it to null. A log record has a fixed shape, so a name
outside it is a mistake the collector can see — unlike an event payload
field, which may legitimately be absent from a given record.

`is_error` is a boolean in the query language, and compares against
`true`/`false` or against `1`/`0`.

## 3.22.3 Metric fields

`timestamp`, `boot_id`, `name`, `type`, `value`, `overflow`

Every other name resolves to a label. Ingestion refuses labels colliding
with these six (§3.10), so the flat namespace is unambiguous by
construction rather than by a precedence rule.

`type` is the series type as a string: `"counter"`, `"gauge"` or
`"histogram"`.

`overflow` is an output-only boolean marker. It is present and true only
when a histogram percentile cannot be located below the series' highest
boundary (§3.25); otherwise it is absent. Predicates and label selectors
therefore see it as null, like any other output not yet computed.

### 3.22.3.1 Types belong to the query mode

Header aliases and GUID literal forms apply only where a name is a
header in that query mode. A metric label named `emitter.class` remains
a string label: `"kacs"` is not the event-header class number. Likewise,
a metric label named `job_id` or an event payload field named `boot_id`
does not acquire the log header's GUID type. Ordinary string comparison
rules apply, including to bracket selectors and cross-type metric
selectors. The actual GUID headers still accept braced and unbraced
input (§3.17).

## 3.22.4 What a record contains

**Event records** carry the header fields plus every non-suppressed
flattened payload field, as top-level keys.

**Log records** carry the log fields.

**Raw metric sample records** carry `timestamp`, `boot_id`, `name`,
`type`, `value`, and the series' labels as top-level keys. A
percentile-overflow result additionally carries `overflow`.

**Aggregated metric results** carry `name`, `type` and `value`, plus
labels when the result belongs to one label set. They carry `boot_id`
only when the query restricted the samples to exactly one boot by a
`boot_id` equality predicate, in which case the value is that boot ID; a
result that could span boots omits it rather than picking one. An
aggregate tainted by a percentile overflow additionally carries
`overflow` (§3.25).

**Aggregation results** in event and log mode carry the group key fields
and the aggregate output, with the fixed schemas of §3.23.

## 3.22.5 SELECT

`SELECT` narrows a result record to the named fields. It is valid only
for non-aggregating event and log queries.

A collector MUST reject `SELECT` combined with `COUNT BY`, `TOP N BY`,
`DISTINCT` or `GROUP`, and MUST reject it in metric mode: all of those
have fixed output schemas, and a clause that reshapes a fixed schema is
a contradiction rather than a refinement.

`SELECT` is applied **last**, after every other phase (§3.23). It
controls the shape of the output and nothing else: a field not selected
is still available to `WHERE`, to `SORT`, and to grouping. Narrowing
what is displayed MUST NOT narrow what is filtered on.

---

# 3.23 Event Queries

_Peios Specifications / PSPU / Observability Interfaces_

> EVENTS mode — the type pattern, origin class aliases, and the aggregations available over events.

```text
EVENTS [type_pattern] [clauses…]
```

## 3.23.1 The type pattern

The primary selector is an optional event type pattern, placed
immediately after `EVENTS`.

```text
EVENTS kacs.audit.access.checked   -- exactly that type
EVENTS kacs.*                      -- every type beginning "kacs."
EVENTS *.rejected                  -- every type ending ".rejected"
EVENTS kacs.*.changed              -- kacs.audit.descriptor.changed, kacs.caap.policy.changed, …
EVENTS                             -- every type
```

`*` is the **only** metacharacter, and matches zero or more of any
character, dots included. `?`, `[` and `{` have no special meaning and a
collector MUST NOT treat them as any. Matching folds case, like every
string comparison (§3.20).

A pattern with no `*` is exactly `WHERE event.type == "…"`. A pattern
whose only `*` is trailing is exactly
`WHERE event.type STARTS_WITH "…"`. Anything else is a glob.

## 3.23.2 Origin class aliases

`emitter.class`, the origin class, accepts named aliases as well as its
integer values:

| Alias | Value |
|---|---|
| `userspace` | 0 |
| `kmes` | 1 |
| `kacs` | 2 |
| `lcs` | 3 |

```text
EVENTS WHERE emitter.class == kacs SINCE 1h ago
```

These are the only aliased values in the language. A collector MUST
accept both forms and MUST treat them as identical.

## 3.23.3 Aggregation

Grouping equality, canonical representatives and tie ordering are
defined in §3.21. Every aggregation below has a **fixed output schema**,
and rejects `SELECT` (§3.22).

### 3.23.3.1 COUNT BY

Counts records grouped by one field, ordered by count descending.

```text
EVENTS SINCE 24h ago COUNT BY event.type
```

Output: `{<field>: representative, count: <unsigned integer>}`.

### 3.23.3.2 TOP N BY

`COUNT BY` with a limit — the `N` most frequent values.

```text
EVENTS SINCE 1h ago TOP 10 BY emitter.process.guid
```

Output: the `COUNT BY` schema.

### 3.23.3.3 DISTINCT

The distinct values of one field.

```text
EVENTS SINCE 24h ago DISTINCT event.type
```

Output: `{<field>: representative}`.

### 3.23.3.4 GROUP

Groups by one or more fields, followed by an aggregation function:
`COUNT`, or `SUM`, `AVG`, `MIN`, `MAX` with a field argument.

```text
EVENTS SINCE 1h ago GROUP emitter.class COUNT
EVENTS SINCE 1h ago GROUP emitter.class, event.type COUNT
EVENTS SINCE 1h ago GROUP event.type AVG operation.duration
```

Output, for `GROUP a, b`:

| Query | Record |
|---|---|
| `COUNT` | `{a, b, count}` |
| `SUM x` | `{a, b, sum}` |
| `AVG x` | `{a, b, avg}` |
| `MIN x` | `{a, b, min}` |
| `MAX x` | `{a, b, max}` |

Group-key fields carry canonical representatives (§3.21).

### 3.23.3.5 What is aggregated

For `SUM`, `AVG`, `MIN` and `MAX`, records whose field is null or
non-numeric are **excluded** from the aggregate — not treated as zero.
`COUNT` counts every record regardless. If no record in a group
contributes a numeric value, the group's aggregate is null and the group
is still present, because `COUNT` of it is still meaningful.

### 3.23.3.6 Result types

- `COUNT` returns an unsigned integer.
- `SUM` over integers returns an integer when the exact mathematical sum
  fits in signed or unsigned 64 bits. If it does not, or if any input
  was a float, it returns a `float64`. If that would be non-finite, the
  query MUST fail with an error rather than returning an infinity.
- `AVG` returns a `float64` whenever at least one numeric value
  contributed.
- `MIN` and `MAX` return the winning value itself, under exact numeric
  comparison. When an integer and a float tie, the integer wins.

## 3.23.4 Ordering

Without `SORT`, results are ordered by `event.time` descending, ties
broken as §3.21 requires.

## 3.23.5 INDEX

```text
EVENTS INDEX target_sid
```

`INDEX` asks the collector to prioritize a field for query
acceleration immediately, rather than waiting for it to be observed
often enough to be prioritized automatically. It exists for incident
response, where the field that suddenly matters has never been queried
before.

`INDEX` is an **administrative operation**, not a query. It returns no
records. A collector MUST check the caller's token against a Security
Descriptor governing administration of the collector — one distinct from
the read-path descriptors of §3.28 — and MUST refuse a caller that does
not hold it. A collector without such a descriptor MUST refuse `INDEX`
outright.

A collector MAY treat `INDEX` as advisory and MAY decline the request,
shed the acceleration later, or do nothing at all. It is a hint about
priority; the accelerations a collector maintains are its own business,
and a conforming collector that maintains none accepts `INDEX` and has
nothing to do.

There is no command to undo it, because there is nothing to undo: a
collector reconsiders its own accelerations continuously and the hint
decays with disuse.

> [!NOTE]
> The right to issue `INDEX` MUST NOT be the read right. Accelerating a
> field costs write throughput on every record thereafter, so `INDEX` is
> a way for a caller to degrade the system for everyone, and a caller
> permitted only to read data has not been permitted to do that.

---

# 3.24 Log Queries

_Peios Specifications / PSPU / Observability Interfaces_

> LOGS mode — its three optional primary selectors, projection and aggregation, and why there are no payload fields.

```text
LOGS [FROM origin[, origin…]] [ERROR ONLY] [CONTAINING "text"] [clauses…]
```

Log mode has three primary selectors rather than one, all optional and
all combinable. Each is sugar for a `WHERE` predicate, and each exists
because it is the thing a person actually types.

## 3.24.1 FROM

Selects by origin. Several may be listed, comma-separated.

```text
LOGS FROM loregd
LOGS FROM loregd, peinit
LOGS
```

`FROM` is exactly `WHERE origin == "…"` for one origin and
`WHERE origin IN ("…", "…")` for several.

Origins are written as identifiers (§3.19) or as quoted strings. An
origin that names a producer within a service, such as
`jellyfin/HealthCheck` or `jobs/<guid>`, is not an identifier and is
written quoted (§3.7):

```text
LOGS FROM "jellyfin/ExecStartPre[0]"
```

## 3.24.2 ERROR ONLY

Selects lines that came from standard error.

```text
LOGS ERROR ONLY
LOGS FROM loregd SINCE 1h ago ERROR ONLY
```

It is exactly `WHERE is_error == true`, and like every clause it may
appear anywhere after `LOGS` without changing the meaning (§3.18).

## 3.24.3 CONTAINING

Selects lines whose message contains the given text — a substring match,
folding case like every string comparison (§3.20).

```text
LOGS CONTAINING "connection refused"
LOGS FROM loregd CONTAINING "failed to open"
```

It is exactly `WHERE message CONTAINS "…"`.

`CONTAINING` is a log-specific keyword because searching text is the
primary operation on log data, and the primary operation deserves the
shortest spelling. It is a substring scan, not an indexed text search: a
collector MUST NOT restrict what it matches, and combining it with
`SINCE` is what keeps it affordable.

## 3.24.4 Projection and aggregation

`SELECT` narrows non-aggregating results to named log fields, and is
additive across clauses (§3.22).

`COUNT BY`, `TOP N BY`, `DISTINCT` and `GROUP` work exactly as in event
mode (§3.23), with the same fixed output schemas, the same result types,
and the same prohibition on combining them with `SELECT`.

```text
LOGS SINCE 1h ago COUNT BY origin
LOGS SINCE 1h ago TOP 5 BY origin
```

## 3.24.5 Ordering

Without `SORT`, results are ordered by timestamp descending, ties broken
as §3.21 requires.

## 3.24.6 No payload fields

Log mode has a closed field set (§3.22). A collector MUST reject an
unknown log field name as a parse error, in a `WHERE`, a `SORT`, a
`SELECT` or a grouping clause alike.

This differs from event mode, where an unknown name is a payload field
that resolves to null. The difference is that a log record's shape is
fixed and known: a name outside it cannot be a field that this record
happens to lack, so treating it as null would answer a question the
client did not ask.

---

# 3.25 Metric Queries

_Peios Specifications / PSPU / Observability Interfaces_

> METRIC mode evaluates rather than searches — series selection, homogeneity, transforms, percentiles and scalar aggregations.

```text
METRIC name[label_selector] [transform] [aggregation] [clauses…]
```

Metric mode evaluates rather than searches. A collector MUST reject
`SELECT` in metric mode: the result schemas are fixed (§3.22).

## 3.25.1 Selecting series

The primary selector is a metric name, optionally followed by a label
selector in brackets. The name supports `*` with the same glob semantics
as an event type pattern (§3.23).

```text
METRIC cpu.usage
METRIC cpu.*
```

The brackets — present, absent, or present and empty — decide how
multiple matching series are handled, and this is the distinction that
governs the rest of the mode.

**No brackets — aggregate.** Every matching series is combined into one
result.

```text
METRIC cpu.usage                    -- average across all cores
METRIC cpu.usage MAX                -- maximum across all cores
```

**Empty brackets — break out.** Each series is returned separately.

```text
METRIC cpu.usage[]                  -- latest value per core
METRIC cpu.usage[] SINCE 1h ago     -- a time series per core
```

**Filled brackets — select.** Only series matching the label predicates.

```text
METRIC cpu.usage[core="0"]
METRIC cpu.usage[core="0", host="srv1"]
METRIC disk.usage[device STARTS_WITH "sd"]
```

Label predicates are comma-separated and combined with `AND`. They use
the operators of §3.20, and within a label selector `=` is accepted as
equality alongside `==`. Label keys are identifiers; values are
identifiers or quoted strings. An absent label resolves to null, so
`[device IS NULL]` selects the series that carry no `device` label.

## 3.25.2 Homogeneity

After the name, the label selector, `WHERE` predicates and access
filtering have been applied, the remaining series MUST be **of one
type**. A collector MUST reject a selection spanning more than one type
at execution time, with an error asking for a narrower name or an
explicit `WHERE type == …`.

A selection resolving to zero series returns no records — a successful
query with an empty result, not an error.

The rule exists because every function below is defined on one type. A
selection mixing counters and gauges has no meaningful rate, and a
selection mixing either with histograms has no meaningful value at all.

## 3.25.3 Function stages

Function keywords execute in fixed stages regardless of where they were
written:

1. **Transform** — `RATE`, `DELTA`, `P50`, `P95` or `P99`. Operates
   within each series independently and produces scalars. At most one
   per query.
2. **Terminal aggregation** — either a **scalar** aggregation (`AVG`,
   `MIN`, `MAX`, `SUM`) or a **window** aggregation (`AVG_OVER`,
   `MIN_OVER`, `MAX_OVER`, `SUM_OVER`). At most one per query;
   specifying both a scalar and a window aggregation is a parse error.

The pipeline ordinarily operates on scalars throughout. Counter and gauge
samples are already scalar; a histogram sample is not scalar until a
percentile function has been applied. The sole exceptional result is a
tagged percentile overflow, whose propagation is defined below. A collector
MUST therefore reject, at
execution time when the type is known, a query that resolves to a
histogram series without a percentile function, or that applies `RATE`,
`DELTA`, or any scalar or window aggregation directly to one.

Every numeric output is a **finite** binary64. If any computation would
produce NaN or an infinity, the query MUST fail with an error rather than
returning it. The null in a tagged percentile-overflow result is not a
numeric output.

## 3.25.4 Transforms

### 3.25.4.1 RATE and DELTA

`DELTA` is the change between consecutive samples; `RATE` is that change
per second. Both apply **only to counter series**, and a collector MUST
reject them on a gauge or histogram at execution time.

Both use the same pair construction. Samples of one series are taken in
ascending timestamp order, with a deterministic tiebreaker among samples
sharing a timestamp. Each consecutive pair `(s1, s2)` whose `s2` falls
inside the effective query range, and where `s2` is later than `s1`,
produces one scalar at `s2`'s timestamp. The **immediately preceding
sample before the first in-range one MUST be used as `s1`** for the
first pair, when such a sample exists — without it the first point of
every range would be missing, and a chart would show a notch at the
start of every window.

The adjusted delta is `s2 - s1` when the value rose, and `s2` alone when
it fell, because a fall means the counter restarted from zero. `RATE` is
that adjusted delta divided by the elapsed seconds. A pair with
non-positive elapsed time contributes nothing.

```text
METRIC http.requests.total SINCE 1h ago RATE
METRIC http.requests.total SINCE 1h ago DELTA
```

### 3.25.4.2 P50, P95, P99

Percentiles of **histogram series only**; a collector MUST reject them
on a counter or gauge at execution time. Each histogram sample yields
one value.

Evaluation is nearest-rank over the sample's cumulative counts: for
percentile `q`, compute `rank = ceil(q × total_count)`, and take the
first boundary whose cumulative count is at least `rank`.

A sample with `total_count == 0` yields no record. A sample whose rank
falls **above the final cumulative count** — meaning the percentile lies
in the overflow region above the highest boundary — yields a record with
`value` null and `overflow` true. The distribution proves that the
percentile exceeds the highest boundary but does not record a finite value
for it. `overflow` is absent from ordinary percentile results.

```text
METRIC request.duration P95
METRIC request.duration[origin="loregd"] SINCE 1h ago P99
```

> [!NOTE]
> The overflow marker is why a producer's highest bucket boundary still
> matters (§3.10). It prevents a `P99` above that boundary from looking like
> no data, but it cannot recover the value the histogram did not locate. An
> operator seeing `overflow: true` is seeing a mis-provisioned histogram.

## 3.25.5 Scalar aggregations

`AVG`, `MIN`, `MAX` and `SUM` reduce scalars to one value. They MUST NOT
be applied to a histogram series directly.

What they aggregate *over* depends on the brackets:

- **Bracketed**, so one result per series: over time, within each series.
- **Unbracketed without `SINCE`**: over the latest transformed value of
  each matching series. The result timestamp is the greatest of the
  contributing timestamps. A series that cannot produce a value — a
  `RATE` with fewer than two samples, say — contributes nothing.
- **Unbracketed with `SINCE`**: valid only when the selector resolves to
  zero or one series. More than one MUST be rejected with an error
  asking for a window aggregation.

```text
METRIC cpu.usage AVG
METRIC http.requests.total RATE SUM
METRIC cpu.usage[] SINCE 1d ago AVG
METRIC cpu.usage[core="0"] SINCE 1h ago MIN
```

The unbracketed default aggregation, when no `SINCE` and no explicit
function is given, is `AVG`. No implicit scalar aggregation is added
when a window aggregation is present.

If nothing contributes to an aggregation, the query returns no record
for that output group. Otherwise the output timestamp is the greatest
contributing timestamp — for `RATE` and `DELTA`, the later sample of the
contributing pair.

If any contributing percentile result has `overflow` true, a scalar
aggregation MUST conservatively return `value` null and `overflow` true.
It MUST NOT ignore the result and compute from the remaining finite values.

### 3.25.5.1 Why unbracketed plus SINCE needs a window

A collector MUST NOT synthesise a merged time series from samples that
do not share timestamps.

Two series sampled at unrelated moments cannot be averaged point by
point without inventing values between the points, and interpolation
would make the collector responsible for a number nobody measured. A
window aggregation supplies the common time grid explicitly, which is
why it is required rather than assumed.

## 3.25.6 Window aggregations

`AVG_OVER`, `MIN_OVER`, `MAX_OVER` and `SUM_OVER` take a duration and
produce one value per window. They **require `SINCE`**; a collector MUST
reject a window aggregation without one as a parse error.

Windows are fixed and aligned to Unix-epoch multiples of the duration —
not to the query's start — so that the same window boundaries fall in
the same places for every query. The output timestamp is the window
start. Windows with nothing in them are omitted rather than emitted as
null.

```text
METRIC cpu.usage SINCE 1d ago AVG_OVER 1h
METRIC cpu.usage[] SINCE 1d ago AVG_OVER 5m
METRIC http.requests.total SINCE 1h ago RATE SUM_OVER 5m
METRIC request.duration P95 SINCE 1h ago AVG_OVER 5m
```

`AVG` and `AVG_OVER` are different keywords and a collector MUST NOT
treat them as synonyms: `AVG` produces one value for the range,
`AVG_OVER` one per window.

A collector MAY cache aligned, complete window results as an implementation
optimization. Such a cache MUST be transparent: freshness must be proved from
the authoritative samples before reuse, partial windows must retain their
ordinary semantics, and a missing, stale or disabled cache MUST produce exactly
the same result as direct evaluation.

For raw and percentile-transformed values, a window contains the scalars
whose timestamps fall inside it, and the function is applied to those.
No interpolation is performed.

If a window contains a percentile result with `overflow` true, its output
MUST also carry `value` null and `overflow` true. This propagation applies
again when per-series window results are combined.

For `RATE` and `DELTA` with a window aggregation, each series first
produces **at most one scalar per window**: the window `DELTA` is the
sum of reset-adjusted deltas for pairs whose later sample is in the
window, and the window `RATE` is that divided by the elapsed seconds
those pairs covered. The preceding-sample rule applies to the first pair
of each window. The terminal aggregation then combines the per-series
window values — so `RATE SUM_OVER 5m` sums the series' five-minute
rates, and `RATE AVG_OVER 5m` averages them. Where the selector resolves
to exactly one series, all four window functions return that series'
window value.

Bracketed window queries keep labels in the result rows. Unbracketed
ones omit them, unless the selector resolved to exactly one series.

## 3.25.7 Without SINCE

With no `SINCE`, the query returns the **latest** value.

```text
METRIC cpu.usage[core="0"]
METRIC cpu.usage[]
METRIC cpu.usage
```

"Latest" is per series, by timestamp with the deterministic tiebreaker.
For `RATE` and `DELTA`, it is the latest valid consecutive pair with
positive elapsed time; a series with no such pair returns nothing.

## 3.25.8 Boot filtering

Samples carry `boot_id` but series continue across boots (§3.13). A
query MAY restrict to one boot:

```text
METRIC cpu.usage[] WHERE boot_id == "550e8400-e29b-41d4-a716-446655440000"
```

A boot-filtered metric query MUST be evaluated from raw samples. A
collector MUST NOT serve one from any pre-computed aggregate that is not
itself partitioned by boot.

## 3.25.9 Results

One record per raw sample; one per valid pair for `RATE` and `DELTA`,
timestamped at the later sample; one per non-empty histogram sample after
a percentile transform, including an explicit overflow record; one per
window for window aggregations; one for a scalar aggregation.

A finite histogram result carries only the percentile in `value`. An
overflow result carries `value` null and `overflow` true. The boundaries,
counts, total and sum are **not** returned by the query language in this
revision, in any mode.

```text
{timestamp: 1714000000000000000, boot_id: "{550e8400-…}", name: "cpu.usage", type: "gauge", core: "0", value: 42.7}
{timestamp: 1714000300000000000, name: "cpu.usage", type: "gauge", core: "0", value: 39.8}
```

Without `SORT`, metric results are ordered by timestamp **ascending**
(§3.21) — the opposite of events and logs, because a metric result is
read as a series rather than as a list of occurrences.

---

# 3.26 Cross-Type Filtering

_Peios Specifications / PSPU / Observability Interfaces_

> The only correlation mechanism in the language — narrowing one data type by a condition on another, with a lookback limit and no join.

A cross-type filter narrows one data type by a condition on another. It
is the only correlation mechanism in the language; there is no join.

```text
EVENTS kacs.* SINCE 1h ago WHERE METRIC cpu.usage[core="0"] > 80
LOGS FROM loregd SINCE 1h ago WHERE EVENT kacs.audit.access.checked EXISTS
METRIC cpu.usage[] SINCE 1h ago WHERE EVENT eventd.store.quarantined EXISTS
EVENTS kacs.* SINCE 1h ago WHERE LOG loregd CONTAINING "error" EXISTS
```

| Form | Available in |
|---|---|
| `WHERE METRIC …` | events, logs |
| `WHERE EVENT … EXISTS` | logs, metrics |
| `WHERE LOG … EXISTS` | events, metrics |

## 3.26.1 How it is evaluated

A collector MUST evaluate the cross-type condition **first**, producing
the set of time ranges over which it holds, and then apply those ranges
as additional timestamp bounds on the primary source.

The condition is evaluated against the referenced data's own resolution
— the metric's sample interval, or the density of matching events — and
**not** once per record of the primary source. It is computed once for
the query.

## 3.26.2 Metric conditions

`WHERE METRIC` operates on **raw scalar samples of counter and gauge
series only**. Transform, scalar aggregation and window aggregation
keywords are not valid in one, and a condition resolving to a histogram
series MUST be rejected.

The selector MUST resolve to **zero or one** series. Zero produces no
true ranges. More than one MUST be rejected with an error asking for a
bracketed or narrower selector.

Within the effective query range, a sample's value is treated as active
over `[sample.timestamp, next_sample.timestamp)`, clipped to the range,
and the final sample stays active through the upper bound. A collector
MUST include the **latest sample before `SINCE`** as the initial state
when one exists; without it the condition would be false from the start
of every range until the first sample inside it, which for a
fifteen-second sampling interval is fifteen seconds of wrongly excluded
records. If no earlier sample exists, the condition is false until the
first in-range sample.

Samples sharing a timestamp are ordered deterministically; the earlier
ones create zero-width intervals and the last at that timestamp is the
active value.

This is interpolation of a kind, and it should be understood as such: it
assumes the condition held continuously between two samples. A metric
that crossed a threshold and crossed back between samples is invisible.

## 3.26.3 Existence conditions

`WHERE EVENT … EXISTS` and `WHERE LOG … EXISTS` are true when at least
one matching record lies near the primary record in time. The event type
supports `*` globbing (§3.23); the log form names an origin and
optionally a `CONTAINING` text.

"Near" is a **centered half-open window** of a configured width `W`. With
`lower = floor(W / 2)` and `upper = W - lower`, the condition is true
for a primary timestamp `t` when a matching record exists with:

```text
timestamp >= t - lower
timestamp <  t + upper
```

Equivalently, a matching record at `e` contributes the true range
`[e - lower, e + upper)`. When `W` is odd the extra nanosecond falls on
the upper side, so the width is exactly `W` and never `W ± 1`.

> [!NOTE]
> §3.A gives the mainline width of the existence window and its
> adjustable range, alongside every other bound in this chapter.

## 3.26.4 The lookback limit

A collector MUST bound how far back a cross-type filter may scan.

> [!NOTE]
> §3.A gives the mainline value and adjustable range
> for this bound and every other in this chapter.

If the effective query range exceeds the limit, a collector MUST reject
the cross-type filter with an error saying the range is too large, and
the error SHOULD suggest narrowing it with `SINCE` or `UNTIL`.

**A query with a cross-type filter and no `SINCE` MUST be rejected.** An
unbounded cross-type scan is never permitted, in any mode, at any
configured limit.

The reason is that a cross-type filter reads a second store in full
before the first query begins. Its cost is set by the *referenced*
data's density, which the client did not select and cannot see, so a
query that looks cheap can scan a hundred times more than it returns.

## 3.26.5 Cost

A cross-type filter is efficient when it is selective — narrow true
ranges eliminating most of the primary source — and expensive when it is
broadly true, which is the case where it also eliminates nothing. A
condition that holds across the whole range costs the full scan of both
stores and returns exactly what the query would have returned without
it.

---

# 3.27 Streaming

_Peios Specifications / PSPU / Observability Interfaces_

> STREAM turns a query into a live watch — what may be streamed, what still applies during the watch phase, and what is rejected.

`STREAM` turns a query into a live tail. It is a flag, may appear
anywhere in the string, and takes no argument.

Streaming is available for **event and log queries only**. A collector
MUST reject `STREAM` in metric mode.

> [!NOTE]
> Metric streaming is absent because metric data is sampled on an
> interval — typically fifteen seconds — and the consumer is a dashboard
> that polls. Streaming individual samples adds a delivery path with a
> latency budget far finer than the data it carries.

## 3.27.1 The shape of a streaming query

1. The collector executes the query normally and sends the initial
   result set as `"ok"` messages.
2. It sends `"watch"` (§3.16). The query is established at this point
   and not before.
3. It stays open. As records are committed, it evaluates them against
   the query and sends those that match.
4. It continues until the client disconnects, an error terminates it, or
   the collector shuts down.

There is no `"end"` message for a streaming query, ever.

## 3.27.2 What may be streamed

Raw record queries and `DISTINCT` queries. A collector MUST reject
`STREAM` combined with `COUNT BY`, `TOP N BY` or `GROUP` as a parse
error — those produce one answer about a set, and a set that is still
growing has no answer yet.

A collector MUST reject `STREAM` combined with `UNTIL`. An upper time
bound and an unbounded live tail are contradictory requests.

`SINCE` is permitted and applies to both phases, resolved against the
evaluation time captured at query start (§3.19).

## 3.27.3 What still applies during the watch phase

Access control, the primary selector, the `SINCE` bound and every
`WHERE` predicate — cross-type conditions included — are evaluated
against each new record.

`SORT`, `TAKE` and `SKIP` apply to the **initial result set only**.
Streamed records are delivered in commit order and a collector MUST NOT
reorder, limit or skip them: there is no total order over records that
have not arrived, and applying `TAKE` to a stream would silently end it.

`SELECT` applies to streamed records as it does to initial ones.

## 3.27.4 DISTINCT streaming

```text
EVENTS kacs.* DISTINCT emitter.process.guid STREAM
LOGS DISTINCT origin STREAM
```

A `DISTINCT` stream emits a value the first time it is seen, and never
again. The output schema is `DISTINCT`'s fixed one (§3.23) in both
phases.

The initial result set is the complete distinct set visible at query
start, after access control and every filter. The collector then holds a
**seen set** initialized from it. Each newly committed record that
passes access control and the filters is reduced to its value for the
field, and emitted only if that value is not already in the seen set
under the grouping equality of §3.21; emitted values are then added.

A collector MUST bound the seen set.

> [!NOTE]
> §3.A gives the mainline value and adjustable range
> for this bound and every other in this chapter.

If initializing the set or inserting a value would exceed the bound, the
collector MUST terminate the query with an error. It MUST NOT evict:
"not seen before" is the entire meaning of the output, and a set that
forgets would re-emit values it had already reported, which is worse
than stopping.

A collector MUST reject `DISTINCT … STREAM` combined with `SORT`, `TAKE`
or `SKIP`, so that the seen set always corresponds to the complete
initial visible set. `SELECT` is already invalid with `DISTINCT`
(§3.22).

## 3.27.5 Cross-type conditions during the watch phase

The pre-computed time ranges of §3.26 describe the past. A collector
MUST NOT reuse them for streamed records.

For a **metric** condition, the selector has already been required to
resolve to exactly one series (§3.26). For each committed batch, the
collector finds that series' active sample at the batch's latest
candidate timestamp under §3.26's interval rules and evaluates the
condition against it. If no sample is active there, the condition is
false. A false condition filters out the whole batch; a true one leaves
the batch to be filtered by the remaining predicates as usual.

For an **existence** condition, the collector applies §3.26's centered
window to each candidate record's own timestamp. These are evaluated
**per record**, not per batch, because a matching record may be near
some of a batch and not the rest.

> [!NOTE]
> Evaluating the metric condition once per batch rather than once per
> record is an approximation, and an intentional one. A commit batch
> spans a fraction of a second while a metric sample spans fifteen, so
> every record in a batch normally maps to the same sample. At
> sub-second metric resolution it filters more coarsely than per-record
> evaluation would, and records near a threshold crossing are included or
> excluded as a group.

## 3.27.6 Backpressure

If a client cannot keep up, the collector MUST drop the query rather
than buffer for it.

Backpressure is detected on the socket send buffer: when a result
message cannot be sent because the buffer is full, the collector MUST
terminate the query immediately and MUST NOT block on the send. It sends
an error if the socket will still take one, and closes otherwise.

Streaming MUST NOT slow or block ingestion. A streaming client is the
lowest-priority consumer of a collector's time, and a slow one is
disconnected rather than accommodated — the same principle as §3.4,
applied on the way out.

## 3.27.7 Latency

Delivery latency is bounded below by the collector's commit interval for
the store concerned, because a record is only streamable once it is
committed. A client that needs lower latency than that is not served by
this interface: the KMES ring buffer is the lower-latency path and is
specified in PSPK.

> [!NOTE]
> Streaming is a convenience for interactive tailing and dashboards.
> Where results must be predictable — cross-type conditions evaluated per
> batch, a metric threshold sampled coarsely, a disconnect under load —
> repeated non-streaming queries with a sliding `SINCE` are more
> reliable, and for latency-critical consumption the ring buffer bypasses
> a collector entirely.

---

# 3.28 What a Client Cannot See

_Peios Specifications / PSPU / Observability Interfaces_

> Read access is enforced on every query against the token captured at connect — the unit of access, and why filtering is silent.

A collector MUST enforce read access on every query, against the token
captured when the client connected (§3.14).

How it does so is its own design, and the mechanism the mainline
collector uses is described in the eventd TRMP. What this chapter fixes
is the part a client can observe: **which results it gets, and what it
is told about the ones it does not.**

## 3.28.1 The unit of access is the concrete identifier

Access is resolved per **concrete identifier** — the event type, log
origin or metric name a stored record actually carries (§3.2) — and not
per query, per store, or per pattern the query happened to write.

A collector MUST resolve each identifier that a query's data could touch
independently. A broad selector authorizes nothing by itself: `EVENTS`
with no pattern, `EVENTS kacs.*`, `LOGS` with no `FROM`, and
`METRIC cpu.*` are all resolved identifier by identifier, and a client
permitted to read one matching identifier and not another sees only the
first.

Identifiers are matched to rules by dot-delimited prefix, most specific
first, falling back to a wildcard default: for
`kacs.audit.access.checked`, a rule for `kacs.audit.access.checked`,
then one for `kacs.audit.access`, then `kacs.audit`, then `kacs`, then
the default.

A collector MUST fail closed. If no rule resolves — including because
the default is missing — access is denied.

## 3.28.2 Filtering is silent

**Records and fields removed by access control are removed without
comment.** A collector MUST NOT indicate in a response that anything was
withheld, and a client MUST NOT assume a result set is complete.

The consequences are precise and a client needs all of them:

- A record whose identifier the client may not read is **absent**, not
  redacted.
- A field the client may not read is **absent from the record**, and is
  indistinguishable from a field the record never carried (§3.17).
- `COUNT`, `COUNT BY`, `TOP N BY`, `DISTINCT` and every aggregation
  reflect **only** authorized records. A count is a count of what the
  client may see.
- A cross-type condition referencing data the client may not read
  evaluates as though **no matching data exists** (§3.26). It does not
  fail the query.
- `TAKE` and `SKIP` page over the authorized records only.

## 3.28.3 Access control runs before everything

A collector MUST remove unauthorized records from the logical row set
**before** predicates, transforms, grouping, aggregation, sorting,
pagination and projection (§3.18).

This is not tidiness. Counting, ordering or paginating over records a
client may not read leaks them through the count, through the ordering,
and through the gaps in pagination — a client could establish how many
records of a type it cannot read exist, and roughly when, without ever
seeing one.

A collector MAY reach the result however it likes: pushing the
authorization down into its storage engine, or reading candidates and
discarding them before aggregating. What it MUST NOT do is produce a
different answer from the one filtering-first produces.

## 3.28.4 Denied fields do not fail the query

When a query references a field in a predicate, a grouping, a sort or an
aggregation, and some matching identifier does not grant that field, the
records under that identifier contribute nothing — exactly as if their
identifier had been denied outright.

A collector MUST NOT reject the query.

> [!NOTE]
> Rejecting would be the more informative behavior and that is precisely
> the objection to it. A rejection tells the client that an identifier
> exists, matches its query, and carries a field it may not read — three
> facts about data it was not permitted to see, delivered by the
> mechanism meant to withhold them. A client could enumerate restricted
> event types by watching which queries are refused. Silence costs the
> client a result that is narrower than it looks; rejection costs the
> system the property the whole model rests on.

Authorization for a field is resolved from the field **as written**,
against each concrete identifier, and does not depend on whether any
record of that identifier actually carries it. Payload fields vary
between records of the same type, so a rule that turned on presence
would be undecidable before the scan it was meant to authorize.

## 3.28.5 What is not a field

Derived aggregate outputs — `count`, `sum`, `avg`, `min`, `max` — are
**not** source fields, have no access identity of their own, and are
visible whenever the client is authorized for the records and the source
fields they were computed from.

Values internal to preserving query semantics — row identifiers, series
identifiers, ordering tiebreakers, series type checks — are likewise not
query-language fields (§3.21). A metric result's `value` **is** a source
field, because it is a raw sample or a scalar derived from raw samples.

## 3.28.6 Errors say nothing

A collector MUST NOT include a value the client is not authorized to
read in any error message (§3.16), including in errors raised by
internal consistency checks.

## 3.28.7 Streaming

Access decisions made for the initial result set are reused during the
watch phase, but a collector MUST resolve any **new** concrete
identifier that appears in a streamed batch and check it before using
the record or its distinct value — a new event type or a new log origin
appearing mid-stream has never been authorized.

If a rule changes during a streaming query, a collector MUST re-check
subsequent batches against the new rule.

The **token** does not change. It was captured at connection (§3.14), so
a client whose group memberships change mid-stream continues to be
evaluated against what it connected with, and a client whose access is
revoked keeps receiving records until it disconnects.

## 3.28.8 What write authentication proves

Log `origin` is broker-attested. The service manager chooses it from
the pipe being read, and the log socket excludes service processes
(§3.6). It proves which service context the manager associated with the
line; it does not prove that the line's text is true.

Metric `name` is publisher-authorized. KACS attests the effective token
that sent the datagram and the collector verifies `EVENTD_PUBLISH` for
that name (§3.9). Labels and values remain producer statements. A
publisher authorized for `http.requests` can report any value and any
valid label set for that name.

Read authorization is independent. Permission to publish an identifier
does not imply permission to query it, and permission to query it does
not imply permission to publish it.

---

# 3.29 Extension

_Peios Specifications / PSPU / Observability Interfaces_

> There is no version number on any of the three interfaces — so unknown fields are ignored, unknown values are refused, and only some things may change.

There is no version number on any of the three interfaces. No datagram
carries one, no query message carries one, and there is no exchange in
which either party could state or discover what the other speaks.

That is a deliberate consequence of the shapes chosen, and it is worth
being explicit about, because it means every rule below is the *only*
mechanism available.

Ingestion is one-way over a datagram socket: there is no reply in which
a collector could announce a version and no state in which a producer
could remember one. The query channel could carry a version — it is a
stream, and it has a request message — and does not, because a version
field is only useful if a party may then behave differently, and a
client cannot usefully vary: it either asks a question the collector
understands or does not.

What replaces negotiation is a set of rules under which both sides may
change without either being told.

## 3.29.1 Unknown fields are ignored

A collector MUST ignore fields it does not recognize in a log record
(§3.7), in a metric record (§3.11), and in a query request (§3.15).

This is what allows a field to be added. A producer built against a
later revision may send a field this collector has never heard of, and
the record is still stored; a producer built against an earlier one
omits a field that has since been added, and the record is still stored
because everything added is optional.

A field added to any of these three maps MUST therefore be optional, and
a collector MUST NOT require one to be present.

## 3.29.2 Unknown values are refused, not ignored

The rule does **not** extend to values.

An unrecognized `type` in a metric record discards the record (§3.12); a
first token that is not a mode fails the query (§3.18); an unrecognized
keyword is a parse error. A collector MUST NOT guess at an unrecognized
value, and MUST NOT skip a field it recognized but could not interpret.

The asymmetry is the point. An unknown field is something the sender
knows about and this collector does not, and ignoring it loses only what
was never understood. An unknown *value* in a known field is the sender
saying something specific about this record, and proceeding without
understanding it stores something other than what was sent.

## 3.29.3 Response statuses

A client MUST treat a response whose `status` it does not recognize as
an error terminating the query, and MUST discard the `"ok"` messages it
has received for that query unless `"end"` or `"watch"` had already
arrived (§3.16).

A status is the control flow of the response stream, so there is no
ignoring one: a client that skipped an unknown status would be waiting
for a terminal message that had already been sent, or treating an
incomplete result as complete. Failing is the only safe reading.

A collector MUST NOT introduce a new status for a condition that the
four existing ones can express.

## 3.29.4 What may change without notice

- **New optional fields** in a log record, a metric record or a query
  request.
- **New fields in result records.** A client MUST tolerate a key it does
  not recognize, and MUST NOT reject a record for carrying one.
- **New query keywords, clauses and functions.** A client sending one
  the collector does not know receives a parse error, which is the
  correct answer.
- **Wording of any error string** (§3.16).
- **New event types, log origins and metric names.** These are data, not
  interface; nothing enumerates the valid set of any of them.

## 3.29.5 What may not change

- **The meaning of an existing field**, in either direction. A field is
  added or it is left alone.
- **The type of an existing field.**
- **The four response statuses**, or the rule that exactly one terminal
  message ends a query.
- **The framing** of §3.15, which has no version field and therefore no
  way to change compatibly.
- **A required field becoming optional, or an optional one becoming
  required.**

## 3.29.6 Limits are not the interface

The declared bounds — the datagram ceilings above their portable floor
(§3.6, §3.9), the query request ceiling and response target (§3.15), the
concurrency and timeout bounds (§3.14, §3.16), the existence window and
lookback limit (§3.26) — are configuration, and an administrator may
change any of them within its stated range.

A collector MUST behave identically at any value in its supported range.
A producer or client MUST NOT infer a bound from having exceeded one, or
from not having exceeded one, and MUST NOT depend on the mainline
defaults quoted in this chapter.

The 262144-byte log and metric datagram floor is different: it is part
of the interface. A collector may raise its declared ceiling but MUST
NOT lower it below that floor, and a portable producer does not discover
or depend on the raised value (§3.6).

---

# 3.30 Conformance

_Peios Specifications / PSPU / Observability Interfaces_

> Every requirement of this chapter collected by role — collector, producer and client — plus what is deliberately not required.

A conforming implementation of any role MUST satisfy every requirement
in this chapter. This section collects the obligations that are not tied
to one message.

## 3.30.1 A collector

**Serve three separate channels.** Two `SOCK_DGRAM` for ingestion, one
`SOCK_STREAM` for queries, each on its own socket, each protected by a
Security Descriptor established before it accepts anything (§3.3).

**Never exert backpressure.** No producer stalls because of a collector,
under any load, in any failure state (§3.4).

**Never react to input.** No event, no log entry, no client-observable
counter, in response to a malformed, unwanted or excessive submission
(§3.4).

**Authenticate ingestion.** Admit only the service-manager broker on
the log socket; require a complete KACS token on every metric datagram
and authorize every metric name for `EVENTD_PUBLISH` (§3.3, §3.6,
§3.9).

**Validate at the stated scope.** Datagram, record, or field — as §3.8
and §3.12 set out, and no more broadly. In particular a malformed record
MUST NOT cost the valid records batched with it, and a malformed
optional field MUST NOT cost a log record.

**Store what you were given.** A log message byte-for-byte, an event
payload unmodified, a timestamp uncorrected, a histogram's boundaries in
the order sent (§3.8, §3.10, §3.5).

**Preserve gaps.** No interpolation, no backfill, no synthesised sample
(§3.13).

**Identify every query client** from the connection, before executing
anything, and refuse the query if you cannot (§3.14).

**Order totally and deterministically.** Every result, for a fixed set
of stored records, in one order — so that `SKIP` and `TAKE` mean
something (§3.21).

**Use query-language semantics, not your storage engine's**, for every
comparison, ordering, grouping and equality test the language defines
(§3.20, §3.21).

**Enforce access before you compute**, per concrete identifier, failing
closed, and silently (§3.28).

**Bound everything a client can consume**: concurrent queries, streaming
queries, message size, query time, distinct-stream values, cross-type
lookback (§3.14, §3.15, §3.16, §3.26, §3.27).

**Behave identically across your configured ranges** (§3.29).

## 3.30.2 A producer

**Send well-formed records** and accept that malformed ones vanish
without notice (§3.8, §3.12).

**Stay within the 262144-byte portable datagram ceiling**, batched or
not. Do not add discovery or depend on a collector's larger local
setting (§3.6).

**Choose a stable, conforming metric name.** It must match the identifier
grammar, name the producer distinguishably and use dots for hierarchy,
because publication and read rules are written against it and queries
select on it (§3.10).

**Convey metric identity.** Enable `KACS_SO_PASS_TOKEN` before sending
metrics and retain the sending socket so the captured-token and
authorization caches remain effective (§3.9).

**Timestamp at production**, not at submission (§3.7).

**Bound your label cardinality**, and keep histogram boundaries fixed
for the life of a metric (§3.10, §3.13).

**Never assume delivery.** No acknowledgment exists, none is coming,
and a record that mattered should have been an event (§3.4).

**Never change a metric's type.** Doing so ends the series silently and
permanently (§3.10).

## 3.30.3 A client

**Tolerate unknown keys** in result records, and unknown statuses as
errors (§3.29).

**Discard partial results.** An error before `"end"` or `"watch"` means
every `"ok"` message for that query is void (§3.16).

**Assume nothing about completeness.** Results are silently filtered by
access, counts count only what you may see, and an absent field is
indistinguishable from a denied one (§3.28).

**Interpret provenance narrowly.** A log origin is broker-attested and a
metric name is publisher-authorized; neither proves the message, value
or labels are truthful (§3.28).

**Do not parse error strings** (§3.16).

**Open one connection per query** (§3.14).

## 3.30.4 What this chapter does not require of a collector

A conforming collector need not accelerate anything, pre-compute
anything, shard anything, or retain anything for any particular period.
It need not honor `INDEX` beyond accepting it (§3.23). Its storage,
indexing, retention and query planning are entirely its own, and every
requirement above is stated about the answer rather than about how the
answer is reached.

---

# Appendix 3.A Limits

_Peios Specifications / PSPU / Observability Interfaces_

> Every bound a collector must enforce, with the mainline collector's value and adjustable range.

Every bound this chapter requires a collector to enforce, with the value
and adjustable range of the mainline collector. The mainline values are
**informative**: a conforming collector chooses its own, and a producer
or client MUST NOT depend on any of them (§3.29).

The mainline configuration key names are those of eventd, whose
configuration is cataloged in the eventd TRMP §A.

## 3.A.1 Ingestion

| Bound | Mainline value | Mainline range | Key | Section |
|---|---|---|---|---|
| Log datagram ceiling | 262144 B | 262144 – 1048576 | `MaxLogDatagramBytes` | §3.6 |
| Metric datagram ceiling | 262144 B | 262144 – 1048576 | `MaxMetricDatagramBytes` | §3.9 |
| Receive queue, either socket | ≤ 4 × the ceiling | — | — | §3.6 |

## 3.A.2 Queries

| Bound | Mainline value | Mainline range | Key | Section |
|---|---|---|---|---|
| Query request ceiling | 65536 B | 1024 – 16777216 | `MaxQueryRequestBytes` | §3.15 |
| Query response target | 65536 B | 1024 – 16777216 | `QueryResponseTargetBytes` | §3.15 |
| Query timeout | 30000 ms | 1000 – 300000 | `QueryTimeoutMs` | §3.16 |
| Concurrent queries | 128 | 1 – 4096 | `MaxConcurrentQueries` | §3.14 |
| Concurrent streaming queries | 64 | 1 – 1024 | `MaxStreamingQueries` | §3.14 |
| Concurrent queries per caller | 16 | 1 – 4096 | `MaxQueriesPerUser` | §3.14 |
| Memory all running queries hold together | 268435456 B | 16777216 – 4294967295 | `MaxQueryHeldBytes` | §3.16 |
| Values per DISTINCT stream | 100000 | 1000 – 10000000 | `MaxDistinctStreamValues` | §3.27 |

## 3.A.3 Cross-type filtering

| Bound | Mainline value | Mainline range | Key | Section |
|---|---|---|---|---|
| Existence window `W` | 15000 ms | 1000 – 300000 | `CrossTypeWindowMs` | §3.26 |
| Maximum lookback | 604800 s | 3600 – 2592000 | `CrossTypeMaxLookbackSeconds` | §3.26 |

## 3.A.4 Fixed by this chapter

These are not configuration and a collector MUST NOT vary them.

| Quantity | Value | Section |
|---|---|---|
| Timestamp domain | `0` – `9223372036854775807` ns | §3.5 |
| GUID field width | 16 bytes | §3.7, §3.11 |
| Message length prefix | 4 bytes, little-endian | §3.15 |
| Maximum response payload | `2^32 - 1` bytes | §3.15 |
| Transforms per query | at most 1 | §3.25 |
| Terminal aggregations per query | at most 1 | §3.25 |
| Queries per connection | exactly 1 | §3.14 |

The response target is not a ceiling. A complete record larger than the
target travels alone, so the configurable ingestion ceilings do not
need to be coupled to it (§3.15).

---

# Appendix 3.B Query Language Reference

_Peios Specifications / PSPU / Observability Interfaces_

> An index of the query language and where each construct is valid — shape, clause validity, rejected combinations, functions, operators and fields.

An index of the language, and of where each construct is valid. The
normative definitions are in §3.18 to §3.27; nothing here adds a rule.

## 3.B.1 Shape

```text
EVENTS [type_pattern]                             [clauses…]
LOGS   [FROM o[, o…]] [ERROR ONLY] [CONTAINING s] [clauses…]
METRIC name[label_selector] [transform] [aggregation] [clauses…]
```

## 3.B.2 Clause validity

| Clause | EVENTS | LOGS | METRIC | Section |
|---|---|---|---|---|
| `SINCE` / `UNTIL` | yes | yes | yes | §3.19 |
| `WHERE` | yes | yes | yes | §3.20 |
| `WHERE METRIC` | yes | yes | no | §3.26 |
| `WHERE EVENT … EXISTS` | no | yes | yes | §3.26 |
| `WHERE LOG … EXISTS` | yes | no | yes | §3.26 |
| `SORT` | yes | yes | yes | §3.21 |
| `TAKE` / `SKIP` | yes | yes | yes | §3.18 |
| `SELECT` | non-aggregating only | non-aggregating only | no | §3.22 |
| `COUNT BY` / `TOP N BY` | yes | yes | no | §3.23 |
| `DISTINCT` | yes | yes | no | §3.23 |
| `GROUP` + function | yes | yes | no | §3.23 |
| `STREAM` | yes | yes | no | §3.27 |
| `ERROR ONLY` / `CONTAINING` | no | yes | no | §3.24 |
| `INDEX` | yes | no | no | §3.23 |

`WHERE` and `SELECT` are the only repeatable clauses (§3.18).

## 3.B.3 Combinations that are rejected

| Combination | Rejected at | Section |
|---|---|---|
| `SELECT` with `COUNT BY`, `TOP N BY`, `DISTINCT` or `GROUP` | parse | §3.22 |
| `SELECT` in metric mode | parse | §3.22 |
| `STREAM` with `COUNT BY`, `TOP N BY` or `GROUP` | parse | §3.27 |
| `STREAM` with `UNTIL` | parse | §3.27 |
| `DISTINCT … STREAM` with `SORT`, `TAKE` or `SKIP` | parse | §3.27 |
| Window aggregation without `SINCE` | parse | §3.25 |
| Scalar and window aggregation together | parse | §3.25 |
| Two transforms | parse | §3.25 |
| Cross-type filter without `SINCE` | parse | §3.26 |
| `=` outside a label selector | parse | §3.20 |
| `== NULL` or `!= NULL` | parse | §3.19 |
| Ordering operator on a binary literal | parse | §3.20 |
| Ordering operator on a fixed field that cannot be ordered | parse or planning | §3.20 |
| Unknown log field name | parse | §3.24 |
| Effective range beyond the lookback limit | planning | §3.26 |
| Selected metric series spanning more than one type | execution | §3.25 |
| `RATE` or `DELTA` on a gauge or histogram | execution | §3.25 |
| Percentile on a counter or gauge | execution | §3.25 |
| Histogram series with no percentile function | execution | §3.25 |
| Unbracketed metric query with `SINCE` resolving to several series | execution | §3.25 |
| Cross-type metric selector resolving to several series | execution | §3.26 |
| Aggregation producing a non-finite value | execution | §3.23, §3.25 |
| A sort or aggregation needing more memory than the collector allows queries | execution | §3.16 |

"Parse" failures need no data. "Execution" failures depend on what the
store holds, so the same query string may succeed on one system and fail
on another.

## 3.B.4 Metric functions

| Keyword | Stage | Valid on | Produces |
|---|---|---|---|
| `RATE` | transform | counter | per-second change |
| `DELTA` | transform | counter | absolute change |
| `P50` `P95` `P99` | transform | histogram | one value per sample |
| `AVG` `MIN` `MAX` `SUM` | scalar aggregation | counter, gauge | one value |
| `AVG_OVER` `MIN_OVER` `MAX_OVER` `SUM_OVER` | window aggregation | counter, gauge | one value per window |

Transforms feed aggregations; a query may have at most one of each
(§3.25).

## 3.B.5 Operators

`==` `!=` `>` `>=` `<` `<=` `STARTS_WITH` `ENDS_WITH` `CONTAINS` `HAS`
`IN` `NOT_IN` `IS NULL` `IS NOT NULL`, combined with `AND` and `OR`
(§3.20).

`CONTAINS` is substring on a string; `HAS` is membership in an array.

There is no `NOT` and no `=`.

## 3.B.6 Literals

| Kind | Form | Section |
|---|---|---|
| Identifier | `[A-Za-z_][A-Za-z0-9_.-]*` | §3.19 |
| String | `"…"` with `\"` `\\` `\n` `\r` `\t` `\uXXXX` | §3.19 |
| Binary | `x"0a1b…"`, even digit count | §3.19 |
| Integer | decimal or `0x…` | §3.19 |
| Float | finite, with a fraction or exponent | §3.19 |
| Boolean | `true`, `false` | §3.19 |
| Null | `NULL`, in `IS NULL` only | §3.19 |
| Duration | `<n>s` `<n>m` `<n>h` `<n>d`, non-zero | §3.19 |
| Time | `<duration> ago`, `<duration> hence`, `today`, `yesterday`, `YYYY-MM-DD`, `YYYY-MM-DDTHH:MM:SS` | §3.19 |
| GUID | `8-4-4-4-12`, braced or not | §3.19 |

## 3.B.7 Fields

| Mode | Fixed fields | Everything else |
|---|---|---|
| EVENTS | `event.time` `event.sequence` `event.cpu` `event.type` `event.boot.guid` `emitter.class` `emitter.token.guid` `emitter.true-token.guid` `emitter.process.guid` | a flattened payload path, or null |
| LOGS | `timestamp` `origin` `is_error` `message` `boot_id` `job_id` | a parse error |
| METRIC | `timestamp` `boot_id` `name` `type` `value` `overflow` | a label, or null |

## 3.B.8 Aliases

`emitter.class` accepts `userspace` (0), `kmes` (1), `kacs` (2), `lcs`
(3). These are the only aliased values in the language (§3.23).

## 3.B.9 Default ordering

| Mode | Without `SORT` |
|---|---|
| EVENTS | `event.time` descending |
| LOGS | `timestamp` descending |
| METRIC | timestamp ascending |
| `COUNT BY`, `TOP N BY`, `GROUP … COUNT` | count descending |
| `GROUP … SUM`, `AVG`, `MIN`, `MAX` | group keys ascending in the order named |
| `DISTINCT` | by the distinct value |

All ties are broken to a total order (§3.21).

---

# Appendix 3.C Prior Art

_Peios Specifications / PSPU / Observability Interfaces_

> The well-known counterparts these three interfaces were shaped against, and where they sit relative to them.

The three interfaces here are not novel, and each has a well-known
counterpart whose shape informed it. What follows compares the
*contracts* — this appendix is about wire shapes and the obligations
they place on either side. The eventd TRMP §1.4 compares the systems.

## 3.C.1 Log ingestion

The closest relative is journald's native socket: a Unix datagram
socket, world-writable, accepting a self-describing record from any
local process, with no acknowledgment and no notification of loss. The
agreements are substantive — datagram rather than stream, silent drop
under pressure, and a forwarder bridging programs that only know
standard output. The identity model differs: this interface admits only
the service-manager broker, which assigns the origin from the pipe it
read rather than accepting a process's self-assertion.

The differences are three. The record here is MessagePack rather than a
line-oriented key-value text format, because the collector already
carries a MessagePack decoder for event payloads and a second parser
would be a second thing to get wrong. Severity is a boolean rather than
a syslog priority, because a forwarder can distinguish two file
descriptors and inventing eight levels from two would be a guess
presented as data (§3.7). And a batch is a first-class datagram shape
rather than a stream of records, which is what lets a forwarder amortise
the syscall without giving up the datagram's all-or-nothing property.

Classic syslog over `/dev/log` is the older relative, and the departure
from it is the same one journald made: a record with named fields rather
than a formatted line that every consumer re-parses with a regular
expression.

## 3.C.2 Metric ingestion

The shape is StatsD's: push, datagram, fire-and-forget, no series
registration, sender-named series. KACS sender identity and per-name
publication authorization are deliberate additions. It is the opposite
of Prometheus's, where the collector pulls from endpoints it has been
configured to know about.

The choice follows from the loss model rather than from taste (§3.9). A
pulling collector must reach every producer on a schedule, which makes
it responsible for their availability; pushing keeps a slow or dead
producer invisible except for the gap it leaves.

What is taken from the Prometheus data model rather than from StatsD is
the *identity* of a series: a name plus a set of labels, with each
distinct label combination a distinct series, and the cardinality
warning that comes with it (§3.10). The histogram is Prometheus's
cumulative-bucket form, including the property that the top bucket is an
overflow whose contents are counted but not located.

Two things are deliberately absent. There is no text exposition format,
because nothing scrapes. And there is no summary type — a producer that
has already computed its own quantiles cannot submit them, because
quantiles do not aggregate and a stored one could not be combined with
another (§3.25).

## 3.C.3 The query interface

The unusual choice here is having a query *language* at all.

journald exposes a cursor and a set of field matchers, and computation
belongs to the client. The Windows Event Log exposes XPath over an XML
representation. Prometheus exposes PromQL, a genuine language, but only
for metrics. This interface puts one language over all three data types,
with a shared clause vocabulary and per-type modes (§3.18).

The reason is access control. Filtering, grouping and aggregation must
happen on the side that knows what the caller may see, because a count
computed by a client is a count of what the client was given and a count
computed by the collector can be a count of what the client is entitled
to (§3.28). A cursor interface pushes the computation across the trust
boundary and takes the enforcement point with it.

The framing — a length-prefixed MessagePack request, a sequence of
chunked result messages, one terminal message — is unremarkable and
deliberately so. What it does not have is more interesting: no version
field (§3.29), no error codes (§3.16), no multiplexing (§3.14), and no
cursor. A query is one connection, and paging is `SKIP` and `TAKE` over
a total order (§3.21) rather than an opaque token the collector must
keep state for.

## 3.C.4 Where these interfaces sit

| Concern | Where it is specified |
|---|---|
| Event emission and the ring-buffer transport | PSPK |
| Event types and payload schemas | the emitting subsystem's own documentation |
| Tokens, SIDs and Security Descriptors | PCDS, and the Peios Kernel TRM |
| Forwarding a service's output | the peinit TRM |
| Storage, indexing, retention, query planning | the collector's own design; for the mainline one, the eventd TRMP |

---

# 4.1 Scope and Roles

_Peios Specifications / PSPU / Service Control and Notification_

> The two interfaces a Peios service manager offers — the control channel and the notification channel — and what this chapter leaves out.

This chapter defines the two interfaces a Peios service manager offers:
the **control channel**, by which a program manages services, and the
**notification channel**, by which a supervised service reports on
itself.

Both are Unix-domain sockets between userspace parties, and both have a
publicly implementable side. A monitoring tool, an orchestration agent,
a shell utility, or a privileged action broker implements the client
side of the control channel. Every supervised service that reports
readiness, sends keepalives, or preserves file descriptors across a
restart implements the producer side of the notification channel.

## 4.1.1 The roles

**The manager** is the process that supervises services. It listens on
both channels. On Peios this is peinit, running as PID 1, but nothing
here depends on that beyond the manager being a single process holding
both sockets.

**A client** connects to the control channel to issue commands and read
answers. A client is any process; it holds no special relationship with
the manager beyond the one its token establishes.

**A service** is a process the manager started, and speaks the
notification channel about itself. A service does not connect to the
control channel in that capacity — a program that does both is acting in
two roles.

**A job** the manager started on a submitter's behalf (§7) speaks the
notification channel exactly as a service does, and is observed and
stopped from the control channel by the job commands of §4.14. The
channel by which it is submitted is §7's.

Requirements are stated against the role, not the program.

## 4.1.2 What this chapter covers

- the two channels, their addressing, and how each is reached
- message framing and encoding on both
- how a client's identity is established, and how a command is
  authorized
- the command set, the response shapes, and the error vocabulary
- what a command does to a service in each of its states
- how a service's notification is authenticated, and what a service may
  say
- the file-descriptor store
- the rules under which either channel may be extended
- the conformance requirements for each role

## 4.1.3 What this chapter does not cover

- **How the manager supervises anything.** Dependency resolution,
  restart policy, timers, cgroups, the boot sequence and shutdown are
  the manager's own design. This chapter defines what a client can ask
  for and what it is told, not how the answer comes about.
- **How service definitions are expressed.** On Peios they are registry
  keys, administered like any other registry data. That is the service
  manager's own design.
- **What a service state means.** The vocabulary is fixed here
  (§4.B) because it appears on the wire; what causes a service to be in
  one of those states is not.
- **Kernel interfaces.** Establishing a peer's identity and evaluating
  an access decision are kernel operations, specified in PSPK and in
  the kernel's own reference manual.
- **Submitting a job.** The channel by which a process asks the manager
  to run a program under supervision, the identity such a job runs as,
  and the commands its submitter issues about it are §7. This chapter
  covers only what a control-channel client sees of such a job.

---

# 4.2 Terminology

_Peios Specifications / PSPU / Service Control and Notification_

> Terms this chapter defines for itself — service, job, operation and advisory — and the ones it borrows unchanged.

**Service.** A named unit of execution the manager supervises. Service
names are opaque to this chapter except for the character restriction in
§4.8.

**Job.** One process execution. A service that has been restarted has
had more than one job. A job submitted on the jobs channel (§7) has no
service; it belongs to its submitter.

**Operation.** A requested state machine action on a service, with an
identity and a lifecycle of its own. Lifecycle commands do not act
directly; they create operations, and an operation is what a client
observes and waits on.

**Activation generation.** A counter the manager increments each time a
service begins starting. It distinguishes one incarnation of a service
from the next.

**Right.** A named permission on a service or on the manager itself,
represented as a bit in an access mask and evaluated against a Security
Descriptor. §4.7.

**Dependent-satisfying state.** A service state in which the services
that depend on the service may proceed. Which states these are is the
manager's design; that a state is or is not one of them is observable
through the state vocabulary.

**Terminal state.** For an operation, one of `completed`, `failed`,
`cancelled`, `merged` or `aborted`. An operation in a terminal state
does not change again.

**Frame.** One newline-terminated line on the control channel, carrying
exactly one JSON object.

**Datagram.** One message on the notification channel, carrying zero or
more `KEY=VALUE` lines and optionally file descriptors.

---

# 4.3 The Two Channels

_Peios Specifications / PSPU / Service Control and Notification_

> Why the notification channel is a datagram socket and the control channel a stream, and how a caller reaches either.

The two channels differ in almost every respect, and the differences are
deliberate.

| | Control | Notification |
|---|---|---|
| Socket type | `SOCK_STREAM` | `SOCK_DGRAM` |
| Who connects | The client | Nobody; a service sends |
| Addressing | A fixed path | A path given to each service |
| Direction | Request and response | One-way |
| Framing | Newline-delimited JSON | `KEY=VALUE` lines |
| Identity | The peer's token, at connect | The sender's kernel-attested PID |
| Authorization | An access check per command | Membership: is the sender this service? |
| Loss | None. A stream, or an error | Possible. A datagram may be dropped |
| Ordering | Guaranteed within a connection | Not guaranteed |

## 4.3.1 Why the notification channel is a datagram socket

A service reporting on itself must not be able to block the manager, and
must not block itself. A stream socket gives both parties a queue that
fills, and a service writing into a full queue either blocks — hanging a
service on the manager's scheduling — or gets an error it has to handle
in the middle of doing something else.

A datagram socket has neither problem. A send either goes or is dropped,
and the manager can drain at whatever rate it manages. The cost is that
a notification can be lost, which is why nothing in §4.19 is a
transaction: every field is either idempotent or a statement of current
condition, and a service that needs a lost keepalive to have arrived
sends another one.

## 4.3.2 Why the control channel is a stream socket

A command has an answer, and a client waiting for one needs to know it
did not arrive rather than assuming. It also needs framing: a request
can be large, and a response certainly can.

## 4.3.3 Reaching either socket

Both sockets are protected by the Security Descriptor on the socket's
own inode, and a party that may not reach the socket is refused when it
connects or sends, before any content is exchanged.

The manager MUST NOT rely on POSIX mode bits for this. On a Peios system
access to a filesystem object is routed through its Security Descriptor,
mode bits are not consulted, and a `chmod` on either socket has no
effect whatever.

The manager MUST ensure that each socket, and each directory containing
one, carries a Security Descriptor that admits the parties intended to
use it. A socket created where nothing inheritable applies acquires no
descriptor, and an object with no descriptor is denied to every caller —
so a manager that leaves this to chance produces a socket nobody can
reach, including principals its own default policy grants access to.

> [!NOTE]
> The failure is quiet in both directions and neither direction
> announces itself. A socket in a permissive place is reachable by
> anything, and a socket in a bare one is reachable by nothing, and in
> both cases the manager binds successfully, reports itself ready, and
> serves no one it meant to.

---

# 4.4 The Control Channel

_Peios Specifications / PSPU / Service Control and Notification_

> The manager's stream socket at a well-known path, what a connection is, and the limits placed on one.

The manager MUST listen on a Unix `SOCK_STREAM` socket at a
well-known path. On Peios that path is:

```
/run/services/peinit/control.sock
```

The socket MUST exist for as long as the manager is serving, and the
manager MUST unlink it when it stops.

The manager MUST create the listening socket and every accepted
connection with close-on-exec set, so that no connection descriptor is
inherited by a process the manager starts.

## 4.4.1 A connection

A client connects, issues one or more commands, and closes. The manager
MUST NOT require a client to issue any command before another, and MUST
NOT hold state across connections: a connection carries an identity
(§4.6) and nothing else.

Requests on one connection MUST be answered in the order they were
received. The manager MAY read no further frames from a connection while
a response on it is outstanding.

## 4.4.2 Limits

The manager MUST enforce three limits, and MUST make their values
discoverable to an administrator through the same configuration surface
that sets them. The values a Peios service manager uses by default are
in §4.A.

**Concurrent connections.** A connection accepted while the manager is
already at its limit MUST be closed at the socket level, without a
response. There is no error code for this condition: the manager has
declined to enter the protocol at all, and a client MUST treat an
immediate close with no response as a refusal rather than as a protocol
error.

The limit MUST be applied to each caller, counted by the user SID of the
peer's token, as well as to the connections in all: a connection
accepted while its caller already holds its limit is closed the same
way. The manager MAY exempt the machine's own principal (SYSTEM) from
the per-caller limit. A channel that admits every authenticated
principal and bounds only the total lets any one of them fill it and
shut everyone else out, administrators included.

**Request size.** A request frame whose content exceeds the limit MUST
be answered with `REQUEST_TOO_LARGE` and the connection MUST then be
closed. The limit applies to the frame's content and MUST NOT count the
terminating newline, so a request of exactly the limit plus its newline
is within bounds.

**Idle timeout.** A connection with no request outstanding MAY be closed
once it has been idle for the configured period. The manager MUST NOT
treat a connection as idle while a request on it is outstanding — in
particular a connection blocked on a `wait=true` operation (§4.13) is
not idle, however long the operation runs, and MUST be held open until
the operation resolves. Such a connection is bounded by the operation's
own timeout, not by the idle timeout.

A connection closed for idleness MUST be closed without a response.

---

# 4.5 Framing and Encoding

_Peios Specifications / PSPU / Service Control and Notification_

> One compact JSON object per newline-terminated frame, in both directions — what counts as malformed, and when the manager closes.

## 4.5.1 Frames

Every message in both directions is one frame: a single JSON object,
serialized compactly, followed by one `0x0A` byte. This applies to
requests and to responses alike, and the manager MUST terminate every
response with a newline.

Framing is byte-oriented and is performed before any JSON is parsed. A
`0x0A` byte ends the frame wherever it appears, so a raw newline inside
what a sender intended as a JSON string does not produce one frame with
an embedded newline — it produces two malformed ones. (A raw `0x0A`
inside a JSON string is not valid JSON in any case; the `\n` escape
sequence is unaffected and is the way to carry a newline in a value.)

The manager MUST NOT emit pretty-printed JSON, and MUST NOT emit more
than one object per frame.

## 4.5.2 Encoding

Frames are UTF-8. The manager MUST reject a frame that is not
well-formed UTF-8 with `MALFORMED_REQUEST`.

## 4.5.3 What is malformed

The manager MUST answer with `MALFORMED_REQUEST` when a frame:

- is empty — a bare newline with no content;
- is not well-formed UTF-8;
- is not valid JSON;
- is valid JSON but not an **object**. An array, a string, a number,
  `true`, `false` and `null` are all malformed requests.

## 4.5.4 Closing after an error

The manager MUST distinguish two classes of failure, because they say
different things about the connection.

A **frame-level** failure means the manager cannot trust the stream's
framing any more: it does not know where the next frame begins.
`MALFORMED_REQUEST` for an empty frame and `REQUEST_TOO_LARGE` are both
frame-level. The manager MUST send the error response, discard any
buffered input, and close the connection.

A **command-level** failure means the frame was well-formed and the
command in it could not be carried out: unparseable JSON content, an
unknown command, missing arguments, a denied access check, an unknown
service. The manager MUST send the error response and MUST keep the
connection open.

A client MUST NOT assume a connection survives an error response, and
MUST be prepared for either.

## 4.5.5 Timestamps

Every timestamp field the manager emits MUST be a UTC RFC 3339 string
with exactly **nine** fractional-second digits and the literal offset
marker `Z`:

```
"2026-06-01T12:34:56.123456789Z"
```

The manager MUST NOT emit a numeric offset in place of `Z`, and MUST NOT
vary the number of fractional digits.

These are wall-clock instants, presented for a reader. The manager MUST
NOT derive elapsed-time decisions — timeouts, retries, ordering — from
wall-clock differences, and a client MUST NOT assume that two timestamps
in the same response were taken from a clock that did not move between
them.

---

# 4.6 Peer Identity

_Peios Specifications / PSPU / Service Control and Notification_

> The manager establishes every client's identity from the kernel, captured once when the connection is accepted, and a client can never assert who it is.

The manager MUST establish the identity of every client from the kernel.
There is no credential exchange in this protocol, and a client MUST NOT
be able to assert who it is.

## 4.6.1 Obtaining the identity

On accepting a connection, the manager MUST obtain the peer's token
through the kernel's peer-identity facility for connected local sockets
(the Peios Kernel TRM §3.5). The token is captured by the kernel when
the client connects; nothing in this protocol carries it, and a client
has no way to supply one.

The token reflects the identity the client was **acting under when it
connected**. A client that is impersonating another principal is
therefore captured as the principal it is impersonating, not as its own
service identity — which is the intended behavior: access decisions
reflect the identity a client is actually acting under.

## 4.6.2 When it is captured

The manager MUST capture the identity once, when the connection is
accepted, and MUST use that identity for every command on the
connection.

A client MUST NOT expect a change of identity mid-connection to affect
authorization. A client that needs to act under a different identity
MUST open a new connection.

> [!NOTE]
> One identity per connection is what keeps a command sequence coherent.
> A job started under one identity cannot be steered by a later command
> issued under another on the same connection, every command on a
> connection is attributable to a single principal, and the manager
> never has to decide which of two identities an in-flight operation
> belongs to. The rule is a property of this protocol.

## 4.6.3 Failure

If the manager cannot obtain the peer's identity, it MUST close the
connection without a response. There is no error code, because the
manager has no basis on which to decide whether this caller may be told
anything at all.

A client MUST treat an immediate close with no response as a refusal.
This is the same observable outcome as exceeding the connection limit
(§4.4), and a client cannot distinguish the two — deliberately, since
distinguishing them would tell an unauthenticated caller about the
manager's state.

## 4.6.4 The manager's identity

The kernel's facility is symmetric: a client that has connected MAY
obtain the manager's identity through the same facility and verify it
before sending a command — that the peer is the principal it expects
the manager to run as, rather than something else that bound the path.
A client MUST NOT treat the control socket's path as proof of the
manager's identity; the path is a rendezvous, and the token is what the
kernel attests.

## 4.6.5 The identity is not a UID

The manager MUST NOT use the peer's UID or GID as an authorization
input. Identity on a Peios system is a token, and the token is what the
kernel attests.

---

# 4.7 Authorizing a Command

_Peios Specifications / PSPU / Service Control and Notification_

> Every command is checked against a Security Descriptor using the peer's token — the rights, the per-command mapping, and why some results are filtered rather than denied.

Every command is authorized against a Security Descriptor, using the
peer's token. There is no command the manager performs without a check,
and no principal exempt from one.

## 4.7.1 Rights

Commands acting on a service are checked against that service's
descriptor:

| Right | Bit | Grants |
|---|---|---|
| `SERVICE_QUERY_STATUS` | 0x0001 | Query the service's state and detail. |
| `SERVICE_START` | 0x0002 | Start the service. |
| `SERVICE_STOP` | 0x0004 | Stop the service. |
| `SERVICE_INTERROGATE` | 0x0008 | Reload the service. |
| `SERVICE_ALL_ACCESS` | 0x000F | All four. |

Commands acting on a submitted job are checked against that job's own
descriptor, with the rights and generic mapping §7.8 defines:
`JOB_QUERY` (0x0001), `JOB_STOP` (0x0002), `JOB_SIGNAL` (0x0004).

Commands acting on the system are checked against the manager's own
descriptor:

| Right | Bit | Grants |
|---|---|---|
| `SYSTEM_SHUTDOWN` | 0x0001 | Initiate a shutdown. |
| `SYSTEM_RELOAD_CONFIG` | 0x0002 | Re-read the configuration. |
| `SYSTEM_QUERY_STATUS` | 0x0004 | Ask how the machine booted (`boot`). |

## 4.7.2 Generic mappings

The manager MUST use these generic mappings when evaluating a
descriptor, so that a descriptor written in generic terms means the same
thing to every implementation.

For a service descriptor:

| Generic right | Maps to |
|---|---|
| `GENERIC_READ` | `SERVICE_QUERY_STATUS` |
| `GENERIC_WRITE` | `SERVICE_START` \| `SERVICE_STOP` \| `SERVICE_INTERROGATE` |
| `GENERIC_EXECUTE` | `SERVICE_START` \| `SERVICE_STOP` \| `SERVICE_INTERROGATE` |
| `GENERIC_ALL` | `SERVICE_ALL_ACCESS` |

For the manager's descriptor:

| Generic right | Maps to |
|---|---|
| `GENERIC_READ` | `SYSTEM_QUERY_STATUS` |
| `GENERIC_WRITE` | `SYSTEM_RELOAD_CONFIG` |
| `GENERIC_EXECUTE` | `SYSTEM_SHUTDOWN` |
| `GENERIC_ALL` | `SYSTEM_SHUTDOWN` \| `SYSTEM_RELOAD_CONFIG` \| `SYSTEM_QUERY_STATUS` |

`GENERIC_READ` maps to the one right on the manager's descriptor that
changes nothing, as it maps to `SERVICE_QUERY_STATUS` on a service.

## 4.7.3 Per command

| Command | Right required |
|---|---|
| `start` | `SERVICE_START` |
| `stop` | `SERVICE_STOP` |
| `restart` | `SERVICE_START` and `SERVICE_STOP` |
| `reload` | `SERVICE_INTERROGATE` |
| `reset` | `SERVICE_STOP` |
| `status` | `SERVICE_QUERY_STATUS` |
| `list` | Evaluated per service; see below |
| `operation-status` | `SERVICE_QUERY_STATUS` on the operation's target |
| `job-status` | `JOB_QUERY` on the job |
| `job-list` | Evaluated per job; see below |
| `job-stop` | `JOB_STOP` on the job |
| `shutdown` | `SYSTEM_SHUTDOWN` |
| `reload-config` | `SYSTEM_RELOAD_CONFIG` |
| `boot` | `SYSTEM_QUERY_STATUS` |

`boot` is checked like any other command, although what it reports is
not a secret: a descriptor decides who may ask, and §4.15 asks that the
default one let every authenticated principal.

`reset` requires `SERVICE_STOP` because clearing a terminal state is the
tail of stopping something rather than the head of starting it.

## 4.7.4 The sequence

1. If the manager is shutting down, apply §4.15's restriction. The
   shutdown restriction is evaluated **before** the access check, so a
   caller who would have been denied is told the command is invalid for
   the current state. A client MUST NOT infer anything about its own
   rights from an `INVALID_STATE` received during shutdown.
2. Resolve the target. A command naming no service the manager knows of
   MUST be answered `UNKNOWN_SERVICE`. The manager MUST NOT synthesise a
   descriptor for a service that does not exist.
3. Evaluate the access check with the peer's token, the target's
   descriptor, the appropriate generic mapping, and the required right,
   naming the target in the check's audit context (PGSS §6.7).
4. On denial, answer `ACCESS_DENIED`. The attempt is recorded by the
   access check itself, under the target descriptor's SACL, with the
   caller, the target and the rights requested and granted; the manager
   MUST NOT write an access-denied event of its own (PGSS §6.7). A
   descriptor the manager supplies by default MUST carry a SACL that
   audits every refusal, so that a denial is not silent unless a
   descriptor someone wrote says so.
5. On grant, proceed.

A `status`, and each job view on this channel, also tells the caller
which of these rights it holds on the target, as `granted` (§4.14). The
manager finds them with this same check, asking for `MAXIMUM_ALLOWED`
in step 3 instead of the command's right. That check is a question
asked on the caller's behalf, not a command: a right it does not grant
is left out of `granted`, and it is not a denial for step 4.

## 4.7.5 Filtering rather than denying

`list` MUST return only the services the caller may query, and MUST
**omit** the rest rather than denying the command. A caller with no
query rights on anything receives an empty list and a successful
response.

The response does not say whether services were omitted. What the
filtering protects is each service's state, which is what
`SERVICE_QUERY_STATUS` grants, and not whether the service exists: a
command naming a service is answered `UNKNOWN_SERVICE` or by its access
check according to whether it exists (step 2 above), and §4.10 does not
hide existence either. A client MAY therefore learn from elsewhere which
services are defined and show the ones `list` left out as ones whose
state the caller may not see.

`job-list` MUST be filtered the same way, by `JOB_QUERY` on each job,
and MUST NOT reveal that jobs were omitted.

## 4.7.6 Not revealing what a caller may not see

A service's existence is not protected (above). Where a command names
an operation the caller may not query, the manager MUST NOT let the
answer distinguish "this does not exist" from "you may not see this".

For `operation-status` this means the authorization check MUST be
evaluated before the operation's existence is reported: a caller lacking
`SERVICE_QUERY_STATUS` on an operation's target MUST receive
`ACCESS_DENIED` whether or not the identifier names a real operation,
and MUST NOT receive `UNKNOWN_OPERATION` for one that exists.

Where the caller's rights cannot be established because the target
cannot be resolved, `UNKNOWN_OPERATION` is the correct answer.

For `job-status` and `job-stop` the rule is §7.10's, not this one: a
job identifier is unguessable, so a caller that names one was told it,
and the manager answers `UNKNOWN_JOB` for an identifier that names
nothing and `ACCESS_DENIED` for one that names a job the caller may not
touch.

---

# 4.8 Requests

_Peios Specifications / PSPU / Service Control and Notification_

> The fields a request JSON object carries, which apply to which commands, and the rules service names must satisfy.

A request is one JSON object.

```json
{"command": "start", "service": "jellyfin", "wait": true}
```

## 4.8.1 Fields

| Field | Type | Required | Meaning |
|---|---|---|---|
| `command` | string | always | The command to run. §4.11, §4.14, §4.15 |
| `service` | string | for service commands | The target service's name. |
| `wait` | bool | no | Whether to block until the operation resolves. §4.13 |
| `type` | string | for `shutdown` | `poweroff`, `reboot` or `halt`. |
| `operation_id` | string | for `operation-status` | The operation to report on. |
| `job_id` | string | for `job-status`, `job-stop` | The job. |
| `submitter` | string | no | For `job-list`: only jobs with this submitter SID. |
| `identity` | string | no | For `job-list`: only jobs whose identity is this SID. |
| `logon_session` | integer | no | For `job-list`: only jobs whose identity is in this logon session. |
| `state` | string | no | For `job-list`: only jobs in this state (§7.B). |

`command` MUST be present and MUST be a string naming a command the
manager implements. A request whose `command` is absent, is not a
string, or names no known command MUST be answered `INVALID_COMMAND`.

`service` MUST be present and a string for `start`, `stop`, `restart`,
`reload`, `reset` and `status`. Its absence, or a non-string value, MUST
be answered `INVALID_ARGUMENTS`.

`wait` MUST be a boolean when present. A non-boolean MUST be answered
`INVALID_ARGUMENTS`. Its default is per command (§4.13).

`type` MUST be present and MUST be exactly one of the three values for
`shutdown`. Anything else MUST be answered `INVALID_ARGUMENTS`.

`operation_id` MUST be present and a string for `operation-status`. A
value that is not a well-formed identifier MUST be answered
`INVALID_ARGUMENTS`.

`job_id` MUST be present and a string for `job-status` and `job-stop`,
under the same rule. The four `job-list` filters are each optional;
one that is present with a malformed value — a SID that does not parse,
a state outside §7.B — MUST be answered `INVALID_ARGUMENTS` rather than
matching nothing, and filters that are all present MUST all hold.

## 4.8.2 Fields that do not apply

A field the command does not use MUST be ignored, not rejected. A
`service` on a `list`, or a `wait` on a `status`, is accepted and has no
effect.

This is what makes the request shape extensible: a client written
against a later revision may send a field an earlier manager does not
know, and the earlier manager ignores it. §4.21.

## 4.8.3 Service names

A service name is 1 to 128 bytes drawn from `[A-Za-z0-9._-]`. The
manager MUST NOT accept a name outside that set, and a client MUST NOT
send one.

The restriction exists because service names are used as path
components and as configuration key names by managers that store their
definitions in a hierarchy. `/` and `:` are excluded specifically:
the first because it is a separator wherever the name is used as a path
component, and the second because it is conventionally reserved for a
manager's own synthetic naming.

---

# 4.9 Responses

_Peios Specifications / PSPU / Service Control and Notification_

> The four response shapes — acknowledgment, status, system and error — and what may be null in each.

Every response carries a `status` field, which MUST be exactly `"ok"` or
`"error"`. What else it carries depends on which of four shapes it is.

## 4.9.1 The acknowledgment shape

Returned by a lifecycle command that created, merged into, queued,
canceled, cleared or executed an operation.

```json
{"status": "ok", "operation_id": "a1b2c3d4-…", "service": "jellyfin",
 "state": "active", "cause": "explicit_start", "warnings": []}
```

| Field | Type | Meaning |
|---|---|---|
| `operation_id` | string | The operation to observe. |
| `service` | string | The target. |
| `state` | string | The service's state when the response was formed. §4.B |
| `cause` | string or null | Why the service last transitioned. §4.B |
| `warnings` | array of strings | Human-readable warnings. Often empty. |
| `mode` | string | For a `reload` only. §4.13 |

`warnings` here is an array of **strings**. The `status` response uses
the same field name for an array of objects (§4.14); a client MUST
distinguish them by which command it sent, not by inspecting the array.

## 4.9.2 The status shape

Returned by `status`, and also by a lifecycle command that had no effect
— see §4.12. §4.14 gives it in full, including `granted`, the rights
the caller holds on the service, which it carries either way.

## 4.9.3 The system shape

Returned by `shutdown`:

```json
{"status": "ok"}
```

Nothing else. A shutdown has no operation to observe and no service to
report on. `reload-config` and `boot` have shapes of their own (§4.15).

## 4.9.4 The error shape

```json
{"status": "error", "code": "ACCESS_DENIED",
 "message": "caller lacks SERVICE_START on jellyfin"}
```

`code` MUST be one of the values in §4.10. `message` is human-readable
and is not normative: a client MUST NOT parse it, match on it, or branch
on its content. Two managers answering the same request with the same
code MAY word the message differently.

## 4.9.5 Nullability

A field that does not apply to the current state MUST be present and
`null` rather than omitted, except where this chapter says otherwise.
A client MUST accept `null` for any field this chapter marks nullable,
and MUST NOT treat a `null` as an error.

The one exception is `mode`, which appears only on a reload response.
The manager's structured events are not responses and do not follow
this rule: their payloads follow PGSS §6.5, under which a value that
does not apply is absent, never null.

---

# 4.10 Errors

_Peios Specifications / PSPU / Service Control and Notification_

> The closed set of error codes a manager may emit, the distinctions a client can rely on, and why the set cannot grow without a version bump.

The `code` field of an error response MUST be one of these values. The
manager MUST NOT emit any other code, and a client MUST treat a code it
does not recognize as an unrecoverable error for that request (§4.21).

| Code | Meaning | Closes? |
|---|---|---|
| `MALFORMED_REQUEST` | The frame is not a single well-formed JSON object. §4.5 | On an empty frame |
| `REQUEST_TOO_LARGE` | The request exceeds the configured maximum. §4.4 | Yes |
| `INVALID_COMMAND` | `command` is absent, not a string, or names no known command. | No |
| `INVALID_ARGUMENTS` | A field the command requires is absent or malformed. | No |
| `UNKNOWN_SERVICE` | The named service has no definition the manager can act on. | No |
| `UNKNOWN_OPERATION` | The operation identifier names nothing the manager holds — it never existed, or its retention has elapsed. §4.14 | No |
| `UNKNOWN_JOB` | The job identifier names nothing the manager holds — it never existed, or its retention has elapsed. §7.7 | No |
| `ACCESS_DENIED` | The access check denied the requested right. §4.7 | No |
| `INVALID_STATE` | The command is not valid for the service's current state (§4.12), or the manager is shutting down (§4.15). | No |
| `OPERATION_TIMEOUT` | A `wait=true` request's operation did not reach a terminal state in time. §4.13 | No |
| `INTERNAL_ERROR` | The manager failed while executing the command. | No |

## 4.10.1 Distinctions a client can rely on

**`UNKNOWN_SERVICE` versus `ACCESS_DENIED`.** A caller that may not
query a service still receives `UNKNOWN_SERVICE` for a name that does
not exist and `ACCESS_DENIED` for one that does but which it may not
touch. This chapter does not attempt to hide the existence of services:
the `list` filtering (§4.7) keeps a service's state from a caller that
may not query it, not the fact that the service exists.

**`INVALID_STATE` versus `ACCESS_DENIED` during shutdown.** During
shutdown the state restriction is evaluated first, so a caller who would
have been denied receives `INVALID_STATE` instead. A client MUST NOT
infer that it holds a right from receiving `INVALID_STATE`.

**`OPERATION_TIMEOUT` does not cancel anything.** It reports that the
client's wait ended, not that the operation did. The operation continues
and can still be observed with `operation-status`.

## 4.10.2 Codes are not extensible without a version

The manager MUST NOT introduce a new code without the version negotiation
in §4.21. A client written against this revision will not recognize one,
and the only safe thing it can do with an unrecognized code is fail the
request — so a new code silently converts a handled condition into an
unhandled one.

---

# 4.11 Lifecycle Commands

_Peios Specifications / PSPU / Service Control and Notification_

> The five commands that move a service through its state machine — none acting directly, each creating, merging into, queuing or canceling an advisory.

Five commands move a service through its state machine. None of them
acts directly: each creates, merges into, queues or cancels an
**operation**, and the operation is what actually happens.

| Command | Effect | Default `wait` |
|---|---|---|
| `start` | Start the service. | true |
| `stop` | Stop the service, escalating if it does not exit. | true |
| `restart` | Stop then start, under one operation. | true |
| `reload` | Tell the service to re-read its configuration. | **false** |
| `reset` | Clear a terminal state, returning the service to inactive. | false |

`reload` defaults to not waiting because a reload's outcome is often
advisory, and a client usually wants the identifier rather than the
block. `reset` is synchronous and completes before the response is sent,
so waiting on it would mean nothing.

## 4.11.1 Operations

The manager MUST return an operation identifier from any lifecycle
command that created, merged into, queued, canceled, cleared or
executed an operation. The client uses it to poll (§4.14) or to
correlate.

The manager MUST NOT invent an operation solely so that it has an
identifier to return. Where a command had no effect, or the service was
already in the state asked for, the manager MUST return the status shape
instead of an acknowledgment (§4.12).

## 4.11.2 Merging

Where an operation of the same type is already in flight for the same
service, the manager MUST merge the new request into it and MUST return
the **existing** operation's identifier.

A merged caller therefore receives an identifier that may be older than
its own request, whose `requested_at` precedes the moment it sent the
command. This is correct — that is when the work being waited on began —
and a client MUST NOT treat an identifier older than its request as an
error.

The manager MUST NOT tell the caller that a merge occurred. A merge is
not a distinguishable outcome, and a client cannot do anything with the
knowledge.

## 4.11.3 What completion means

| Command | The operation completes when |
|---|---|
| `start` | The service reaches a dependent-satisfying state, or a state indicating its start-time conditions did not apply. |
| `stop` | The service is no longer running. |
| `restart` | The service reaches its normal successful start target after the restart. |
| `reload` | The reload resolves, whatever its mode. |
| `reset` | Immediately. |

## 4.11.4 Timeouts

Every queued or executing operation has a maximum lifetime, derived from
the target service's own configured timeouts; a start the service
manager is holding on an undecided dependency has none and MUST stay
Pending until the dependency is decided.

**The lifetime is measured from the operation's creation, including any
time it spent queued.** From the caller's point of view they have been
waiting since they sent the command, and an operation that sat behind
another for longer than its lifetime MUST fail rather than begin.

An operation whose lifetime expires while it is still queued MUST fail,
and MUST fail its waiters. Expiry of the operation object MUST NOT by
itself authorize the manager to act on the service — a stop operation
that timed out while waiting its turn does not license signaling the
service ahead of that turn.

---

# 4.12 Command Outcomes by State

_Peios Specifications / PSPU / Service Control and Notification_

> The defined answer for every command sent to a service in an unexpected state — the manager never silently does nothing.

A command sent to a service in an unexpected state MUST receive a
defined answer. The manager MUST NOT silently do nothing.

| | inactive | starting | active | reloading | stopping | completed | backoff | failed | abandoned | skipped |
|---|---|---|---|---|---|---|---|---|---|---|
| `start` | act | merge | already | already | queue | act | defer | act | invalid | act |
| `stop` | noop | cancel + act | act | act | merge | clear | cancel | noop | invalid | noop |
| `restart` | act | queue | act | act | queue | act | act | act | invalid | act |
| `reload` | invalid | invalid | act | merge | invalid | invalid | invalid | invalid | invalid | invalid |
| `reset` | noop | invalid | invalid | invalid | invalid | invalid | invalid | clear | clear | clear |
| `status` | ok | ok | ok | ok | ok | ok | ok | ok | ok | ok |

## 4.12.1 The outcomes

**act** — create an operation and execute it. The manager returns the
acknowledgment shape.

**merge** — an operation of this type is in flight. The command merges
into it (§4.11) and the caller receives that operation's identifier.

**queue** — the operation is created and left pending; it executes once
the operation ahead of it completes. The caller receives the new
operation's identifier.

**defer** — an automatic restart is already pending for this service.
The manager MUST create a pending start operation, or merge into a
deferred one that already exists, and MUST NOT execute it until the
existing delay has elapsed. A `start` MUST NOT shorten a pending
restart's delay.

**already** — the service is in the state the command would take it to
and no operation of this type is in flight. The manager MUST return the
**status** shape, not an error and not an acknowledgment.

**noop** — the command has no effect. The manager MUST return the status
shape.

**clear** — the service returns to inactive. This is a synchronous
outcome; the manager returns an acknowledgment.

**cancel** — abort or cancel the operation in flight, then proceed.

**invalid** — the command is not valid for this state. The manager MUST
answer `INVALID_STATE`.

**ok** — `status` is answered from any state.

## 4.12.2 The `backoff` column

A service in `backoff` is down with an automatic restart pending, and
the four lifecycle commands mean different things there:

- `start` defers, as above, and honors the remaining delay.
- `stop` cancels both the pending restart and any deferred start, and
  the service becomes inactive.
- `restart` cancels the automatic restart and performs a
  caller-initiated one.
- `reload` and `reset` are invalid: there is no process to reload and no
  terminal state to clear.

## 4.12.3 The `abandoned` column

Every lifecycle command except `reset` is invalid on an abandoned
service. `reset` clears it. Nothing else is meaningful while processes
the manager could not terminate are still present.

## 4.12.4 A service being withdrawn

A manager MAY keep supervising a service whose definition has been
removed while an instance of it is still running. In that condition the
manager MUST answer `start`, `restart` and `reload` with
`UNKNOWN_SERVICE`, MUST accept `stop`, and MUST report the condition in
the status shape (§4.14). This holds whatever the service's state.

---

# 4.13 Wait Semantics

_Peios Specifications / PSPU / Service Control and Notification_

> What ending a wait means, and how the wait flag changes when a lifecycle command responds.

`wait` decides whether a lifecycle command's response is sent
immediately or held until the operation resolves.

With `wait: false`, the manager MUST respond as soon as it has accepted
the operation, with the acknowledgment shape and the service's state at
that moment.

With `wait: true`, the manager MUST hold the connection open and respond
when the operation reaches a terminal state, with the same shape and the
service's state, cause and warnings observed at that time.

A connection blocked on a wait is not idle (§4.4). The manager MUST NOT
close it for idleness however long the operation runs.

## 4.13.1 When a wait ends

| Ending | Response |
|---|---|
| The operation reaches a terminal state | The acknowledgment shape. |
| The operation's lifetime expires | `OPERATION_TIMEOUT`. |
| The operation is no longer held by the manager | `UNKNOWN_OPERATION`. |

`OPERATION_TIMEOUT` ends the client's wait, not the operation. The
operation continues, and the client MAY still observe it with
`operation-status` using the identifier it never received — which it
does not have. A client that needs to survive a timeout SHOULD issue the
command with `wait: false`, keep the identifier, and poll.

## 4.13.2 Reload mode

A response to a `reload` command MUST carry a `mode` field saying how
the reload resolved:

| Value | Meaning |
|---|---|
| `confirmed` | The service acknowledged the reload by signaling readiness. The reload demonstrably happened. |
| `advisory` | The manager issued the reload and the service did not acknowledge it. The reload probably happened; nothing confirms it. |
| `failed` | The reload did not happen. An external reload command exited non-zero or timed out. |

`mode` MUST be present on every response to a `reload`, including one
sent with `wait: false` — in which case it MUST be `advisory`, since
nothing has been observed yet.

A client MUST treat these three as an exhaustive set and MUST NOT expect
a fourth. A manager MUST NOT introduce one without §4.21.

The distinction between `confirmed` and `advisory` is the whole value of
the field: a service that implements the reload handshake (§4.19) can be
*known* to have reloaded, and one that does not cannot. `failed` does
not mean the service stopped — a failed reload leaves a running service
running.

---

# 4.14 Query and Job Commands

_Peios Specifications / PSPU / Service Control and Notification_

> The three commands that read service state and change nothing — status, list and operation-status — the three that observe and stop submitted jobs, how a status or job view tells the caller what it may do, and how long results are retained.

Three commands read service state and change nothing. Three more
observe and stop submitted jobs (§7), and are here because a client of
this channel sees jobs alongside services.

## 4.14.1 status

Returns everything the manager knows about one service.

```json
{
    "status": "ok",
    "service": "jellyfin",
    "display_name": "Jellyfin",
    "description": "Media server for the living room.",
    "state": "active",
    "cause": "explicit_start",
    "status_text": "Listening on port 8096",
    "progress": null,
    "current_job": {
        "id": "a1b2c3d4-…",
        "type": "service_main",
        "pid": 1234,
        "started_at": "2026-06-01T12:34:56.123456789Z",
        "identity": "jellyfin-svc"
    },
    "current_operation": {
        "id": "e5f6g7h8-…",
        "type": "start",
        "source": "admin"
    },
    "health": "healthy",
    "uptime_seconds": 86400,
    "definition_removed": false,
    "warnings": [],
    "timers": [],
    "granted": ["query_status", "start", "stop"]
}
```

| Field | Type | Meaning |
|---|---|---|
| `display_name` | string or null | The definition's human-readable name. |
| `description` | string or null | The definition's human-readable description. |
| `state` | string | §4.B. |
| `cause` | string or null | Why the service last transitioned. §4.B. |
| `status_text` | string or null | The most recent status string the service sent (§4.19). |
| `progress` | object or null | The most recent progress the service sent (§4.19), in the form §7.7 gives. |
| `current_job` | object or null | The current main job, or null if none. |
| `current_operation` | object or null | The current operation, or null if none. |
| `health` | string or null | `healthy`, `unhealthy`, `unknown`, or null when the service has no health check configured. |
| `uptime_seconds` | integer or null | Whole seconds since the current job started. Null when nothing is running. |
| `definition_removed` | bool | True while the service's definition has been withdrawn and an instance is still draining (§4.12). |
| `warnings` | array of objects | Conditions worth an operator's attention. |
| `timers` | array of objects | The service's calendar timer triggers, as the manager has them armed. Empty when it has none. |
| `granted` | array of strings | The service rights the caller holds on this service. Never null. |

`current_job` carries `id`, `type` (§4.B), `pid`, `started_at` and
`identity`. `pid` and `started_at` are independently nullable.
`identity` is the identity string the manager resolved for the
execution, which is not necessarily what the resulting token contains.

`current_operation` carries `id`, `type` and `source` (§4.B).

The manager MUST clear `status_text` and `progress` to null at the
start of every activation generation. A status string or a progress
figure from a previous incarnation MUST NOT survive a restart and be
reported as though it described the current process.

### 4.14.1.1 What the caller may do

`granted` lists the service rights of §4.7 that the caller holds on the
service, each by its name lowercased and without `SERVICE_`:
`query_status`, `start`, `stop`, `interrogate`, in that order, and only
those held. It describes the caller who asked, not the service; two
callers asking about the same service may be told different things.

The manager MUST compute it with the access check it runs for a command
(§4.7) — the caller's token, the service's descriptor, the service
generic mapping — asking for `MAXIMUM_ALLOWED` rather than for one
right, and MUST report only the service rights among what that check
grants. A client can therefore offer only the commands that will be
allowed: while the caller's token and the service's descriptor stay as
they were, a command whose required rights (§4.7) all appear in
`granted` passes its access check, and one needing a right that is
absent fails it. Whether the command will then do anything is a
separate question, which the service's state answers (§4.12), and
during a shutdown §4.15's restriction comes first.

This check is a question, not a command. A right the caller lacks is
simply absent from `granted`, and the manager MUST NOT record the check
as a denial.

A status returned by a lifecycle command that had no effect (§4.12)
carries `granted` for the caller of that command.

### 4.14.1.2 Status warnings

`warnings` in the status shape is an array of **objects**, not strings:

```json
{"path": "/sys/fs/cgroup/peinit/jellyfin/health",
 "type": "health",
 "detected_at": "2026-06-01T12:34:56.123456789Z"}
```

| Field | Type | Meaning |
|---|---|---|
| `path` | string | What the warning is about. |
| `type` | string | The kind of warning. §4.B. |
| `detected_at` | string | When the manager noticed. §4.5. |

A client MUST accept a `type` it does not recognize and MUST NOT discard
the warning, since a warning it cannot classify is still one an operator
should see.

### 4.14.1.3 Status timers

`timers` has one object for each calendar timer trigger of a service
that is not disabled (for peinit, the peinit TRM §9), ordered by
schedule:

```json
{"schedule": "*-*-* 02:00:00",
 "scheduled_at": "2026-06-02T02:00:00.000000000Z",
 "fires_at": "2026-06-02T02:07:12.000000000Z",
 "last_fired_at": "2026-06-01T02:03:40.000000000Z",
 "not_armed": null}
```

| Field | Type | Meaning |
|---|---|---|
| `schedule` | string | The calendar expression, as the trigger gives it. |
| `scheduled_at` | string or null | The schedule's next occurrence. §4.5. |
| `fires_at` | string or null | When the timer will fire: that occurrence, delayed by the jitter drawn for it. Equal to `scheduled_at` without jitter. §4.5. |
| `last_fired_at` | string or null | When it last fired. Null when it has not fired since the manager started and no earlier firing is recorded. §4.5. |
| `not_armed` | string or null | Why the manager has not armed it, when it has not: its schedule does not parse, or has no occurrence within the manager's search horizon. Null when armed. |

An armed timer has `scheduled_at` and `fires_at`, and null
`not_armed`. A timer not armed has only `schedule` and `not_armed`.

These are the manager's own figures, not a calculation a client could
repeat. The jitter is drawn at random each time the timer is armed, and
only the manager knows which schedules it refused, so a client MUST
NOT compute a next firing from the definition and present it as when
the service will run.

`last_fired_at` is the firing, not the run: it is when the manager
acted on the timer (the peinit TRM §9.2), whatever came of that. For a
persistent timer that has not fired since the manager started, it is
the timestamp the manager recorded before (the peinit TRM §9.3).

## 4.14.2 list

Returns every service the caller may query, with a compact summary.

```json
{
    "status": "ok",
    "services": [
        {"service": "jellyfin", "display_name": "Jellyfin",
         "description": "Media server for the living room.",
         "state": "active", "cause": "explicit_start",
         "health": "healthy", "next_timer_at": null},
        {"service": "logrotate", "display_name": null,
         "description": null, "state": "inactive",
         "cause": "clean_exit", "health": null,
         "next_timer_at": "2026-06-02T00:03:51.000000000Z"}
    ]
}
```

Exactly seven fields per entry: the name, the definition's nullable
`display_name` and `description`, the state, cause and health of the
status shape, and `next_timer_at`, the soonest `fires_at` among the
service's armed timers, or null when it has none. Services the caller
may not query are omitted (§4.7).

A service whose definition has been withdrawn is listed, and the list
entry does not say so. A client that needs to know MUST issue a
`status`.

## 4.14.3 operation-status

Returns one operation by identifier.

```json
{
    "status": "ok",
    "operation": {
        "id": "e5f6g7h8-…",
        "type": "start",
        "service": "jellyfin",
        "source": "admin",
        "state": "completed",
        "result": "active",
        "merged_into": null,
        "error": null,
        "requested_at": "2026-06-01T12:34:56.123456789Z",
        "started_at": "2026-06-01T12:34:56.223456789Z",
        "completed_at": "2026-06-01T12:34:58.923456789Z"
    }
}
```

| Field | Meaning | Present when |
|---|---|---|
| `id` | The operation's identifier. | Always. |
| `type` | §4.B. | Always. |
| `service` | The target. | Always. |
| `source` | Why the manager created it. §4.B. | Always. |
| `state` | §4.B. | Always. |
| `result` | The resulting service state. | `completed`. |
| `error` | Why it did not complete. | `failed`, `cancelled`, `aborted`. |
| `merged_into` | The surviving operation's identifier. | `merged`. |
| `requested_at` | When it was created. | Always. |
| `started_at` | When it began executing. | Once running. |
| `completed_at` | When it reached a terminal state. | Once terminal. |

Fields that do not apply to the current state MUST be null.

`error` carries a reason for all three non-success terminal states, not
only for `failed`. A client MUST NOT read a non-null `error` as meaning
the operation failed — it MUST read `state` for that. Cancellation and
abortion have reasons worth reporting, and a separate field for each
would give a client three places to look for one fact.

## 4.14.4 job-status

Returns one submitted job by identifier, as the job view of §7.7.

```json
{"command": "job-status", "job_id": "0190a3b2-…"}
```

```json
{"status": "ok", "job": { … }}
```

The view is §7.7's, with one field added on this channel: what a
submitter sees of its job on the jobs channel is what a client sees of
it here, and the client is also told what it may do to the job.

### 4.14.4.1 What the caller may do to a job

On this channel every job view — in the response to `job-status`,
`job-list` and `job-stop` — carries one field beyond §7.7's:

| Field | Type | Meaning |
|---|---|---|
| `granted` | array of strings | The job rights the caller holds on this job. Never null. |

```json
{"id": "0190a3b2-…", "type": "submitted", "state": "running", …,
 "granted": ["query", "stop"]}
```

It lists the job rights of §7.8 the caller holds, each by its name
lowercased and without `JOB_`: `query`, `stop`, `signal`, in that
order, and only those held. The manager MUST compute it as it computes
a status's `granted`, with the access check it runs for a job command,
against the job's own descriptor and the job generic mapping (§7.8),
and the same rules follow: it is a question rather than a command, a
right the caller lacks is absent rather than denied, and a command whose
required right is listed passes its access check.

For a `job-stop` that waits, the manager MAY compute `granted` when it
accepts the command rather than when it answers. A job's descriptor is
fixed at submission (§7.8), so the two could differ only if the
caller's token had changed in between.

The jobs channel's view does not carry `granted`. A submitter is
answered there under §7.8's own rules.

## 4.14.5 job-list

Returns every submitted job the caller may query, as job views.

```json
{"command": "job-list", "identity": "S-1-5-21-…"}
```

```json
{"status": "ok", "jobs": [ { … }, { … } ]}
```

Each entry is the full job view (§7.7), with `granted` (above). Jobs
the caller may not query are omitted (§4.7). The four filters of §4.8 — `submitter`,
`identity`, `logon_session`, `state` — narrow the result before it is
filtered by right, and the manager MUST NOT let the response reveal
whether the filters or the rights removed an entry.

Terminal jobs still within their retention period are listed; a client
that wants only live ones filters by `state`.

> [!NOTE]
> `logon_session` is what an authority uses to find everything running
> under a logon it is ending: it lists the jobs in that session and
> stops each it holds `JOB_STOP` on. A user-facing view of "my jobs"
> filters by `identity`; a broker's view of "the jobs I started"
> filters by `submitter`.

## 4.14.6 job-stop

Stops one submitted job, with the semantics of the jobs channel's
`stop` (§7.8): the termination signal, the job's `stop_timeout`, then
the kill.

```json
{"command": "job-stop", "job_id": "0190a3b2-…", "wait": true}
```

`wait` defaults to true, and the response is the job view, with
`granted`, when the job is terminal; with `wait: false` it is the view
as soon as the stop has been initiated. A `job-stop` on a terminal job returns the view
unchanged, with `"status": "ok"`.

This is the one command on this channel that acts on a job, and it
creates no operation: a job has no state machine to contend for (§7.6).
There is no `job-signal` here; signaling is the submitter's business,
on its own channel.

## 4.14.7 Retention

The manager MUST hold an operation record for at least a grace period
after it reaches a terminal state, so that a client polling for the
result can retrieve it. The value a Peios service manager uses is in
§4.A.

An identifier that never existed, and one whose record has been dropped
after its grace period, MUST both be answered `UNKNOWN_OPERATION`. A
client MUST NOT distinguish them, and MUST treat `UNKNOWN_OPERATION`
after a successful acknowledgment as meaning the result is no longer
available rather than that the operation never ran.

Job records are retained under §7.7's rule, and `UNKNOWN_JOB` carries
the same two meanings.

---

# 4.15 System Commands

_Peios Specifications / PSPU / Service Control and Notification_

> shutdown, reload-config and boot — the commands that act on or ask about the manager itself, why reload is atomic but not a live update, and what boot reports.

Three commands are about the manager rather than a service. Two act on
it; the third, `boot`, asks how the machine booted.

## 4.15.1 shutdown

```json
{"command": "shutdown", "type": "reboot"}
```

`type` MUST be one of:

| Value | Meaning |
|---|---|
| `poweroff` | Stop everything and remove power. |
| `reboot` | Stop everything and restart the machine. |
| `halt` | Stop everything and halt, leaving the machine powered. |

The response is `{"status": "ok"}` and nothing else. There is no
operation to observe: a shutdown is a mode the manager enters, not an
action on a service, and by the time it has finished there is nobody
left to tell.

A client MUST NOT expect the connection to survive. The manager MAY
close it at any point after the response.

## 4.15.2 reload-config

Re-reads the configuration and rebuilds whatever the manager derives
from it.

```json
{
    "status": "ok",
    "summary": {
        "added": ["jellyfin"],
        "updated": ["sshd"],
        "restored": [],
        "marked_removed": ["old-migration"],
        "discarded": ["obsolete-timer"]
    },
    "warnings": []
}
```

| Field | Type | Meaning |
|---|---|---|
| `added` | array of strings | Services that did not exist before. |
| `updated` | array of strings | Services whose definition changed. |
| `restored` | array of strings | Services whose withdrawal was reversed. |
| `marked_removed` | array of strings | Services whose definition is gone but which are still running. |
| `discarded` | array of strings | Services removed outright. |
| `warnings` | array of strings | Human-readable warnings about the new configuration. |

Every member of `summary` MUST be present, even when empty. A client
MUST accept a member of `summary` it does not recognize, and MUST ignore
it (§4.21).

### 4.15.2.1 It is atomic

The manager MUST validate the new configuration in full before adopting
any of it, and MUST adopt it only if validation succeeds. If validation
fails, the manager MUST leave the previous configuration in force and
MUST answer `INVALID_STATE`, reporting what was wrong.

A partially applied configuration is worse than the one already running:
the running one at least booted.

### 4.15.2.2 It does not live-update

The manager MUST NOT reconfigure a running service. A changed definition
takes effect the next time that service starts.

## 4.15.3 boot

Reports how the current boot went: which mode the machine booted in and
why, how close it is to recovery, and whether this boot has counted as a
successful one yet. It takes no arguments and changes nothing.

```json
{"command": "boot"}
```

A **boot mode** is how much of the configuration a boot starts. In
`full` mode the manager starts everything configured to start at boot.
In `safe` mode it starts a reduced set: the services the boot cannot do
without, which this chapter calls **critical services**, and those
marked as wanted in Safe mode. In `recovery` mode it starts nothing and
offers a maintenance shell instead. Which services are critical, and
what each mode starts, is the manager's design.

A boot is **confirmed** once it has shown it works: every critical
service has held a dependent-satisfying state (§4.2) for a **grace
period** without a break. The manager keeps a **boot attempt count**,
the number of boots in a row that started and were never confirmed, and
enters recovery when it reaches a **threshold** rather than boot into
the same failure again. Confirming a boot puts the count back to 0.

```json
{
    "status": "ok",
    "boot": {
        "mode": "safe",
        "reason": "safe_mode_downgrade",
        "downgrade": ["critical service in dependency cycle storage -> network"],
        "attempts": 1,
        "max_attempts": 3,
        "confirmed": false,
        "grace_seconds": 30,
        "waiting_on": ["storage"],
        "confirms_at": null,
        "confirm_error": null
    }
}
```

| Field | Type | Meaning |
|---|---|---|
| `mode` | string | The mode the machine booted in, after any downgrade. §4.B |
| `reason` | string | Why it is in that mode. §4.B |
| `downgrade` | array of strings | What forced a downgrade, one human-readable finding each. Empty unless `reason` is `safe_mode_downgrade`. |
| `attempts` | integer | The boot attempt count as the manager checked it against the threshold at the start of this boot. |
| `max_attempts` | integer | The threshold. 0 means the check is off and the count never sends the machine to recovery. |
| `confirmed` | bool | This boot has been confirmed, and the count has been put back to 0. |
| `grace_seconds` | integer | The grace period, in seconds. |
| `waiting_on` | array of strings | The critical services not yet holding a dependent-satisfying state. Empty once the grace period has ended. |
| `confirms_at` | string or null | When the boot will be confirmed if every critical service keeps holding, in RFC 3339 UTC. Null while `waiting_on` is not empty, and once the grace period has ended. |
| `confirm_error` | string or null | Why the count could not be put back to 0 when the grace period ended. Human-readable. |

Every member of `boot` MUST be present. A client MUST accept a member of
`boot` it does not recognize, and MUST ignore it (§4.21).

`attempts` counts the boots before this one; this boot is not among
them. A machine reaches recovery when a boot begins with `attempts` at
or above `max_attempts`, so `max_attempts - attempts` is how many more
unconfirmed boots the machine has before recovery.

`confirmed` MUST be true only once the count has actually been put back
to 0. If the grace period ended but the manager could not write the
count, `confirmed` is false and `confirm_error` says why: the next boot
will count this one as a failed attempt, whatever its services did, and
a client MUST NOT report the boot as confirmed.

A confirmed boot stays confirmed. A critical service that fails after
confirmation is a failure of that service, not of the boot, and does not
make `confirmed` false again.

A manager in `recovery` mode does not serve the control channel, so a
client SHOULD NOT expect to read `recovery` from `boot`; the value
exists so that a manager which does serve it there has a word for it.

`boot` is checked against the manager's descriptor for
`SYSTEM_QUERY_STATUS` (§4.7). How a machine booted is not a secret, and
a manager's default descriptor SHOULD grant this right to every
authenticated principal.

## 4.15.4 During shutdown

Once the manager is shutting down, it MUST reject every command except
`status`, `list`, `operation-status`, `boot`, `job-status`, `job-list`
and `job-stop` with `INVALID_STATE`.

The first six are permitted because they change nothing and because a
client watching a shutdown proceed has a legitimate reason to keep
looking; `job-stop` because a job the shutdown will reach eventually
may be one a client has reason to end now. Everything else — including
a second `shutdown` — is refused:
the manager has committed to a course of action and a command that
would alter it arrives too late to be honored consistently.

As §4.7 says, this restriction is evaluated before the access check, so
a caller who would have been denied receives `INVALID_STATE` instead.

---

# 4.16 The Notification Channel

_Peios Specifications / PSPU / Service Control and Notification_

> The datagram socket a service reports on itself over — how it is addressed, how delivery works, and the bounds on it.

A service reports on itself over a Unix `SOCK_DGRAM` socket the manager
binds and holds for the lifetime of the system.

## 4.16.1 Addressing

The manager MUST make the socket's path available to each service it
starts, in the `NOTIFY_SOCKET` environment variable, set in the service
process's environment before exec.

The path is not part of this contract, and a service MUST NOT hardcode
one. The manager MAY bind one socket for all services or one per
service; a service cannot tell and MUST NOT depend on either.

The manager MUST set `NOTIFY_SOCKET` unconditionally, for every service
it starts, whatever readiness protocol that service uses. A service uses
this channel for keepalives, status, timeout extension and the
descriptor store as well as for readiness, and a manager that set the
variable only for services expected to signal readiness would make the
rest unreachable.

The manager MUST NOT allow `NOTIFY_SOCKET` to be overridden by any
configurable environment layer. A service that could override it would
silently disable its own supervision.

## 4.16.2 Direction and delivery

The channel is one-way. The manager does not reply, and a service MUST
NOT wait for one.

Delivery is not guaranteed. A datagram MAY be dropped, by the kernel
under load or by the manager. Every field in §4.19 is therefore either
idempotent or a statement of a current condition, and a service that
needs an effect to have taken hold sends the field again rather than
waiting for an acknowledgment that does not exist.

The manager MUST NOT let this channel exert backpressure on a service.
A service MUST NOT be able to block by sending, and the manager MUST NOT
require a service to slow down.

## 4.16.3 Bounds

The manager MUST accept a datagram of at least the size in §4.A, and
MUST accept at least the number of file descriptors in §4.A in one
datagram's control message.

The manager MUST detect a datagram that exceeded either bound and MUST
reject the whole datagram (§4.17). It MUST NOT process a truncated
datagram: a truncation can leave a tail that parses as a complete,
valid line, which would apply a field the sender did not send.

A service MUST NOT send a datagram exceeding either bound.

---

# 4.17 Datagram Framing

_Peios Specifications / PSPU / Service Control and Notification_

> Newline-separated KEY=VALUE lines — what makes a datagram malformed, the three ways one line can fail, and why rejection is recorded rather than answered.

A datagram carries zero or more lines, separated by `0x0A`. Each line is
`KEY=VALUE`.

```
READY=1
STATUS=Listening on port 8096
```

A trailing newline on the last line is permitted and is not a line of
its own. A trailing `0x0D` on any line MUST be stripped before the line
is interpreted, so a sender that emits CRLF is understood.

The datagram MUST be well-formed UTF-8.

## 4.17.1 Applying a datagram

The manager MUST parse every line before applying any of them, and MUST
apply every line of a datagram it accepts, in order.

**If any line is malformed, the manager MUST reject the entire datagram
and apply nothing from it.** Any file descriptors it carried MUST be
closed.

Partial application is the failure this rule exists to prevent. A
datagram saying `RELOADING=1` and something unintelligible has an
ambiguous meaning, and applying the half that parsed picks one reading
of it silently.

## 4.17.2 What is malformed

A **line** is malformed when it is non-empty and:

- it contains no `=`; or
- its key is empty.

An **empty line** is not malformed. It is skipped.

A datagram is malformed when it is not well-formed UTF-8, or when it
exceeded a bound in §4.16.

## 4.17.3 Three ways a line can fail to take effect

These are distinct and a service author needs the distinction:

| Situation | Effect on the datagram | Effect on the line |
|---|---|---|
| A malformed line | Rejected entirely | — |
| An **unrecognized key** | Applied normally | Ignored |
| A recognized key with an **unexpected value** | Applied normally | Ignored |

The second is what makes the field set extensible (§4.21): a service
built against a later revision may send a field an older manager does
not know, and the older manager applies the rest.

The third is the one that surprises. `READY=0` is not a malformed line
and does not reject the datagram; `READY` expects the value `1` and
anything else is silently ignored. A service MUST NOT send a recognized
key with a value the field does not define, and MUST NOT expect to be
told when it does. §4.19 gives each field's accepted values.

## 4.17.4 Rejection is recorded, not answered

The manager MUST record a rejected datagram, with at least the sender's
identity and the reason, and MUST attribute it to a service where the
sender could be identified.

It MUST NOT reply. There is nothing to reply on.

---

# 4.18 Sender Authentication

_Peios Specifications / PSPU / Service Control and Notification_

> A datagram claims to be a service talking about itself; the steps by which a manager establishes that it is, and what it must never use.

A datagram on this channel claims to be a supervised process — a
service, or a submitted job (§7) — talking about itself. The manager
MUST establish that it is.

## 4.18.1 The requirements

The manager MUST enable `SO_PASSCRED` on the socket, and MUST reject any
datagram arriving without a kernel-attested credentials control message.

It MUST then establish all of the following, and MUST drop the datagram
if any fails:

1. **The sender is a service's current main job, or a submitted job.**
   The manager MUST match the attested PID against the main jobs and
   the submitted jobs it is supervising. A hook process, a health check,
   or a child a service or a job forked MUST NOT be able to notify on
   its behalf.
2. **That job has exec'd and is running.** A job still in setup has not
   become the service yet.
3. **That job has a kernel handle on the process** — a pidfd, or an
   equivalent that refers to one specific process rather than to a
   number.
4. **The handle still refers to the attested PID.** The manager MUST
   verify the PID against the handle rather than trusting the PID alone.
5. **For a service's job, its activation generation is the service's
   current one.** A submitted job has no generation and no replacement;
   the step does not apply to it.

## 4.18.2 Why steps 3 and 4 exist

A PID identifies a process only until that process exits. Between a
service writing a datagram and the manager reading it, the service can
die and its PID be recycled onto something else — and PID matching alone
would then attribute the unrelated process's message to the service, or
attribute the service's message to whatever now holds the number.

A handle obtained atomically at fork does not have that property.
Verifying the attested PID against the handle is what turns a probable
match into a certain one.

## 4.18.3 Why step 5 exists

A datagram sent by an incarnation of a service that has since been
restarted MUST NOT be applied to its replacement. Without the generation
check, a `READY=1` written by a process moments before it crashed could
mark the process that replaced it ready — declaring a service healthy on
the strength of a message from the one that just failed.

Readiness is per activation generation, and so is everything else on
this channel.

## 4.18.4 What the manager MUST NOT use

The manager MUST NOT use the sender's UID or GID as an authorization
input, and MUST NOT accept any identity a service asserts in the
datagram's content.

Identity on this channel is *which supervised process this is*, and only
the kernel can attest that. A service does not have a name here that it
gets to state, and a job does not have an identifier.

## 4.18.5 What a job may send

A submitted job may send every field in §4.19. Those that address a
service transition it is not in — `RELOADING`, `EXTEND_TIMEOUT_USEC`
outside a readiness wait, the descriptor-store fields, which a job has
no store for — MUST be applied as §4.19 says for the case where they do
not apply: ignored, or closed and recorded. `READY=1` from a
`readiness: none` job is ignored. A job's `STATUS` and `PROGRESS` are
retained and exposed in its job view (§7.7).

---

# 4.19 Notification Fields

_Peios Specifications / PSPU / Service Control and Notification_

> Every field a service may send — lifecycle, health, reporting and descriptor-store — and the ones deliberately not supported.

Every field a service may send. A manager MUST implement all of them. A
service MUST NOT send a recognized key with a value the field does not
define (§4.17).

## 4.19.1 Lifecycle

| Field | Value | Meaning |
|---|---|---|
| `READY` | `1` | Startup is complete and the service is serving. |
| `RELOADING` | `1` | Configuration reload has begun. |
| `STOPPING` | `1` | Graceful shutdown has begun. |
| `LEVEL` | free text | A currently true readiness condition. Repeated fields publish the complete set; an empty-only set retracts it. |

**`READY=1`** is what a service using notification readiness sends when
it is genuinely able to serve, not when its process exists. Anything
depending on the service starts on the strength of it, so a service that
signals early declares its dependents' assumptions true before they are.

**`RELOADING=1`** opens a reload. The manager waits a bounded period
after issuing a reload for this field; a service that sends it MUST
follow with `READY=1` when the reload is complete, and the pair is what
lets the manager report the reload `confirmed` rather than `advisory`
(§4.13). A service that never sends either still reloads — it just
cannot be observed to have done so.

**`STOPPING=1`** tells the manager the service is already shutting down.
A manager that receives it MUST NOT send a further termination signal to
that service. It MUST NOT extend or reset the stop timeout: the service
still has to exit within it, and a service needing longer sends
`EXTEND_TIMEOUT_USEC`.

**`LEVEL`** names a condition the service currently satisfies, in the
service's own vocabulary. A service MAY repeat this field within one
datagram to publish several conditions. For example, a routed netd sends
`LEVEL=link`, `LEVEL=addressed` and `LEVEL=routed` as three lines in one
datagram.

When a datagram contains at least one `LEVEL` field, the manager MUST
atomically replace the sender's retained set with the distinct nonempty
values from all its `LEVEL` fields. Field order and duplicates MUST NOT
change the resulting set. An empty value adds no member; a datagram with
only empty `LEVEL` values MUST clear the set. A datagram without `LEVEL`
MUST leave the retained set unchanged. The entire replacement MUST be
visible before releasing dependents, including when the datagram also
contains `READY=1`.

The manager MUST discard the set whenever the service leaves a state
that satisfies dependents: these are claims made by a running process.

A level-conditioned dependency (`Requires = ["netd:routed"]`) MUST NOT
be satisfied unless the target is in a dependent-satisfying state **and**
the retained set contains the named level. Names are opaque,
case-sensitive and per-publisher; commas have no special meaning. The
manager MUST NOT assume an ordering or implication between them. A
publisher that knows several conditions hold MUST publish each one that
it promises to expose to dependents.

The value SHOULD be a single token of at most 64 printable ASCII
characters. A value outside that shape is not an error, but a dependency
condition cannot name it, so nothing can ever wait on it.

## 4.19.2 Health

| Field | Value | Meaning |
|---|---|---|
| `WATCHDOG` | `1` | A keepalive. |
| `WATCHDOG_USEC` | unsigned integer | Change the expected keepalive interval, in microseconds. |
| `EXTEND_TIMEOUT_USEC` | unsigned integer | Extend the current transition's deadline, in microseconds. |

**`WATCHDOG_USEC`** with a value above zero sets the interval and MUST
re-arm the timer from the moment the message arrives, rather than
letting the new interval apply only from the next keepalive. A value of
zero MUST disable the watchdog.

The value MUST NOT persist across a restart. A restarted service gets
the interval its definition specifies.

**`EXTEND_TIMEOUT_USEC`** sets the current transition's deadline to
expire that many microseconds from the message's arrival. It
**replaces** the deadline rather than adding to it, and MAY be sent
repeatedly.

Because it replaces, a value smaller than the time remaining shortens
the deadline, and zero expires it immediately. A service MUST NOT send a
value expecting it to be treated as a floor.

The manager MUST cap the extended deadline at four times the base
timeout of the phase being extended, and MUST **clamp** rather than
reject a value beyond the cap. During a system shutdown the manager MUST
additionally cap it at the time remaining in the shutdown, and where
both apply the stricter MUST win.

A message arriving while the service is not in a transition MUST be
ignored. There is no deadline to extend.

## 4.19.3 Reporting

| Field | Value | Meaning |
|---|---|---|
| `STATUS` | free text | A human-readable statement of what the service is doing. |
| `PROGRESS` | see below | How far the service has got. |
| `PROGRESS_UNIT` | `bytes`, `items` or `percent` | What `PROGRESS` counts. |
| `ERRNO` | free text | An errno-style error number. |
| `EXIT_STATUS` | free text | An exit status, informationally. |

All five MUST be authenticated like any other field and MUST be
recorded by the manager as structured events (PGSS §6), which, like
every event, are not written while the emission policy has their type
switched off (PGSS §6.9). They MUST NOT be forwarded
to a log sink as though they were the service's output — they are the
service speaking to the manager.

`STATUS`, `PROGRESS` and `PROGRESS_UNIT` MUST additionally be retained
and exposed — as `status_text` and `progress` in the status shape
(§4.14), and in a submitted job's view (§7.7). `ERRNO` and
`EXIT_STATUS` MUST NOT be retained.

### 4.19.3.1 Progress

`PROGRESS` takes one of three forms, each of two unsigned decimal
integers at most, separated by `/`:

| Form | Meaning | A viewer shows |
|---|---|---|
| `N` | Counting, with no end. | A rising count. |
| `N/` | Counting towards an end that exists but is not yet known. | A rising count, and expects a bound to arrive. |
| `N/T` | `N` of `T`. | A bar. |

`T` MUST be at least 1, and `N` MUST NOT exceed `T` when `T` is given.
A value outside these forms, or violating either rule, is an
**unexpected value** under §4.17: the line is ignored and the datagram
is otherwise applied. A manager MUST NOT clamp or repair a progress
value.

The manager retains the most recent accepted value and exposes it as a
`progress` object: `current` is `N`; `total` is `T` or null; `bounded`
is true for the second and third forms and false for the first; `unit`
is the most recent accepted `PROGRESS_UNIT` or null. A `PROGRESS_UNIT`
outside its three values is an unexpected value and is ignored. Each
field is replaced only by a datagram that carries it: a `STATUS` alone
leaves `progress` as it was.

`T` MAY change from one datagram to the next — a job that rescans has
learned something — and `N` MAY fall. A viewer renders the latest
value; it MUST NOT infer motion from the difference between two.

A service that sends progress with no end in sight MUST send the
first form and not a guessed `T`. A service that has not started
counting sends nothing: absence means *no progress concept*, and a
viewer shows an indeterminate indicator.

The manager MUST bound how often a change of progress becomes an event
on its event stream, so that a sender updating a thousand times a
second cannot produce a thousand events; the retained value is the
latest regardless. The bound a Peios service manager uses is §4.A.

A service MUST NOT include a newline or carriage return in a `STATUS`
value: it would frame as two lines, the second of which is almost
certainly malformed.

## 4.19.4 The descriptor store

| Field | Value | Meaning |
|---|---|---|
| `FDSTORE` | `1` | Store the descriptors attached to this datagram. |
| `FDNAME` | free text | The name to store or remove them under. |
| `FDSTOREREMOVE` | `1` | Remove the descriptors stored under `FDNAME`. |
| `FDPOLL` | `0` | Do not monitor the stored descriptors for error conditions. |

§4.20.

## 4.19.5 Fields that are not supported

| Field | Why |
|---|---|
| `MAINPID` | A manager supervises the process it forked, through a kernel handle obtained at fork. There is no mechanism for redirecting supervision to another process, and there is deliberately none: a service that could nominate its own supervision target could nominate anything. |
| `BUSERROR` | Peios has no D-Bus. |

Neither is rejected distinctly. Both are simply unrecognized keys and
are ignored like any other (§4.17). A service MUST NOT rely on being
told that it sent one.

---

# 4.20 The Descriptor Store

_Peios Specifications / PSPU / Service Control and Notification_

> Handing file descriptors to the manager and getting them back after an unchosen restart — storing, removing, returning, and when the store is emptied.

A service may hand file descriptors to the manager and get them back
after a restart it did not choose. This is what lets a stateful daemon —
one holding a listening socket, say — restart without dropping what it
already had.

The manager MUST support a per-service maximum, which MAY be zero. Zero
disables the store for that service, and a service MUST NOT assume a
store exists.

## 4.20.1 Storing

On an authenticated datagram carrying `FDSTORE=1` with descriptors
attached, the manager MUST:

1. If the store is disabled for this service, **close** the descriptors
   and record the rejection.
2. If the store already holds its maximum, **close** the descriptors and
   record the rejection. It MUST NOT evict an existing entry — a full
   store is full, and silently discarding something the service is
   relying on to survive a restart would be worse than refusing the new
   one.
3. Store them under the value of `FDNAME` if present and non-empty, and
   under the name `stored` otherwise.
4. Note `FDPOLL=0` if present.

A datagram MAY carry several descriptors. Each becomes its own entry
under the one name, and each is independently subject to the maximum —
so a datagram carrying more than will fit has some stored and the rest
closed.

Several entries MAY share a name.

`FDPOLL=0` asks the manager not to monitor the descriptors for error
conditions. A manager MAY monitor stored descriptors and remove ones
that have become invalid; a manager that does not MUST still accept the
field.

## 4.20.2 Removing

`FDSTOREREMOVE=1` with `FDNAME` MUST remove every entry of that name and
close its descriptors. A name matching nothing is a no-op and MUST NOT
be an error.

`FDSTOREREMOVE=1` **without** `FDNAME` MUST be treated as a malformed
line, rejecting the whole datagram (§4.17). A remove with no name has no
defined meaning, and the alternative readings — remove everything,
remove the default name, do nothing — are far enough apart that guessing
between them silently is worse than refusing.

## 4.20.3 Returning them

When the service starts again, the manager MUST pass the stored
descriptors to the new process:

1. Placed consecutively, starting at descriptor **3**, with close-on-exec
   cleared.
2. `LISTEN_FDS` set to the number of descriptors passed.
3. `LISTEN_FDNAMES` set to the names, **colon-separated**, in the same
   order as the descriptor numbers.
4. `LISTEN_PID` set to the new process's own PID.
5. The store cleared.

`LISTEN_PID` is what lets a service verify that the variables are
addressed to it rather than inherited from an ancestor. A conforming
client checks it against its own PID before trusting `LISTEN_FDS`, and
treats a mismatch as meaning no descriptors were passed — so a manager
that omits it hands descriptors to a service that will not take them.

All four variables MUST be absent when no descriptors are passed, and
the manager MUST NOT allow any of them to be set by a configurable
environment layer. A `LISTEN_FDS` reaching a service that was passed
nothing points its descriptor-adopting code at whatever happens to be at
descriptor 3.

Descriptors are returned to the service's main process only. A hook or a
probe MUST NOT receive them.

The store MUST be cleared once the descriptors have been passed. The
manager MUST NOT clear it when a start attempt fails before that point —
the descriptors are still the service's, and the next attempt should get
them.

A returned listening socket conveys, to every client that connects, the
identity of the process that called `listen()` on it — the previous
instance of the service. A service that receives listening sockets from
the store SHOULD restamp them with its own identity before accepting
(the Peios Kernel TRM §3.5), so that clients verifying the peer see the
instance actually serving them.

## 4.20.4 When the store is emptied

The manager MUST clear the store, closing its descriptors, when:

- the service is stopped deliberately — by a client, or as part of a
  system shutdown; or
- the service's definition is withdrawn and its entry is finally
  discarded.

The manager MUST NOT clear it on a restart the service did not ask for —
a crash, or a restart policy acting on one. That case is the entire
purpose of the mechanism: the descriptors survive exactly the restart
the service could not prepare for.

> [!NOTE]
> `LISTEN_FDS`, `LISTEN_FDNAMES` and `LISTEN_PID` are the convention
> established by systemd's `sd_listen_fds`, and are specified here in
> the same form deliberately. Software already written to adopt
> descriptors that way works against a Peios service manager without
> modification.

---

# 4.21 Extension

_Peios Specifications / PSPU / Service Control and Notification_

> Neither channel carries a version number — what may be added freely, what may not, and what a client must do with something it does not recognize.

Neither channel carries a version number. Both are extended by the rules
below, which are what allow a client and a manager built against
different revisions to interoperate.

## 4.21.1 What may be added

**A request field.** A manager MUST ignore a request field it does not
recognize (§4.8). A client MAY therefore send a field a manager may not
know, and MUST NOT depend on the field having had an effect.

**A response field.** A client MUST ignore a response field it does not
recognize, and MUST NOT treat its presence as an error. This includes an
unrecognized member of `summary` in a `reload-config` response, and an
unrecognized key in `current_job` or `current_operation`.

**A notification field.** A manager MUST ignore an unrecognized key
(§4.17). A service MAY therefore send a field a manager may not know.

**A `type` value in a status warning.** A client MUST accept a warning
whose `type` it does not recognize and MUST NOT discard it. An
unclassifiable warning is still a warning.

**A right in `granted`.** A client MUST ignore a right name it does not
recognize in a status's or a job view's `granted` (§4.14). A right it
does not know of is one it offers no command for.

**A command, together with the error codes and enumerated values that
appear only in responses to it.** A client is exposed to a command only
by sending it, so a client that does not know a command is never
exposed to anything it introduces. A manager MAY therefore add a
command without a version, provided that nothing it introduces can
reach a client through any *existing* command's response.

## 4.21.2 What may not be added without a version

Anything a client must *recognize* in order to behave correctly cannot
be added compatibly, because an older client's only options are to fail
or to misbehave.

A manager MUST NOT, without a negotiated version:

- introduce an **error code** outside §4.10 on an existing command;
- introduce a **service state**, **transition cause**, **operation
  state**, **operation type**, **operation source** or **job type**
  outside §4.B, or a job state or cause outside §7.B, where an
  existing command could return it;
- introduce a **reload mode** outside the three in §4.13;
- change what an existing **command** does;
- change the **shape** of an existing response, including changing a
  field's type or making a non-nullable field nullable.

A client encountering one of these has no correct behavior available.
Faced with an unknown `state` it cannot decide whether the service is
running; faced with an unknown error code it cannot decide whether to
retry.

## 4.21.3 What a client must do with the unknown

A client MUST treat an unrecognized **enumerated value** in a field it
depends on as an error for that request, and MUST NOT map it onto the
nearest value it does know. Guessing that an unfamiliar state is
probably like `active` is how a monitoring tool reports a broken system
as healthy.

A client MUST treat an unrecognized **error code** as unrecoverable for
that request. It MUST NOT retry, since it cannot know whether the
condition is transient.

## 4.21.4 Versioning, when it comes

A future revision introducing an incompatible change MUST do so through
an explicit negotiation, in which a client states what it understands
and the manager answers within that. Until such a mechanism exists, this
chapter's contract is fixed and the rules above are the whole of the
supported way for it to grow.

---

# 4.22 Conformance

_Peios Specifications / PSPU / Service Control and Notification_

> Every requirement of this chapter collected by role — manager, client and service — and what conformance deliberately is not.

## 4.22.1 A conforming manager

**The channels.** Listens on a Unix stream socket at a well-known path
and on a Unix datagram socket whose path it gives each service in
`NOTIFY_SOCKET`. Ensures both sockets, and the directories containing
them, carry a Security Descriptor admitting the parties intended to
reach them, and relies on no POSIX mode bits (§4.3, §4.4, §4.16).

**Framing.** Emits exactly one compact JSON object per newline-terminated
frame. Answers a malformed frame with `MALFORMED_REQUEST` and an
oversized one with `REQUEST_TOO_LARGE`, closing the connection after a
frame-level failure and holding it open after a command-level one
(§4.5).

**Identity.** Obtains every client's identity from the kernel once, at
accept, and uses no UID, GID or asserted identity (§4.6).

**Authorization.** Checks every command against the appropriate Security
Descriptor with the mappings in §4.7, naming the target in each
check's audit context and giving every default descriptor a SACL that
audits every refusal, writes no access-denied event of its own, filters
`list` rather than denying it, and does not let `operation-status`
distinguish an operation the caller may not see from one that does not
exist. Reports a status's and a job view's `granted` from that same
check asking for `MAXIMUM_ALLOWED`, and does not treat it as a denial
(§4.14).

**Commands.** Implements all fourteen, with the outcomes in §4.12 for
every command-and-state pair, the response shapes in §4.9, §4.14 and
§4.15, and only the error codes in §4.10. Reports a boot as confirmed
only once its attempt count has been put back to 0 (§4.15). Filters `job-list` by
`JOB_QUERY` as it filters `list`, and answers `job-status` and
`job-stop` against the job's own descriptor (§4.7, §4.14).

**Operations.** Returns an identifier from every lifecycle command that
produced one and none where it did not; merges same-type requests and
returns the surviving identifier; measures every operation's lifetime
from its creation including queue time; and holds a terminal record for
at least the grace period (§4.11, §4.14).

**Waiting.** Honors the per-command `wait` default, holds a waiting
connection open past the idle timeout, and carries a `mode` on every
reload response (§4.13).

**Notification.** Authenticates every datagram through all five steps of
§4.18, including verifying the attested PID against a kernel handle and
checking the activation generation for a service's job. Applies all
lines of an accepted datagram and none of a rejected one. Rejects a
truncated datagram rather than processing it. Implements every field in
§4.19, retaining `STATUS`, `PROGRESS` and `PROGRESS_UNIT` and bounding
how often a progress change becomes an event.

**The descriptor store.** Closes rather than keeps what it refuses;
returns descriptors from 3 upward with `LISTEN_FDS`, `LISTEN_FDNAMES`
and `LISTEN_PID` set; clears the store on a deliberate stop and keeps it
across a restart the service did not ask for (§4.20).

**Extension.** Ignores unrecognized request and notification fields, and
introduces nothing from §4.21's closed list without a negotiated
version.

## 4.22.2 A conforming client

Sends one compact JSON object per newline-terminated frame. Treats an
immediate close with no response as a refusal. Does not parse `message`.
Accepts `null` for every nullable field, and unrecognized fields
everywhere it is told to. Treats an unrecognized enumerated value or
error code as an error for that request rather than guessing. Reads
`state` rather than the presence of `error` to decide whether an
operation succeeded. Does not infer its own rights from an
`INVALID_STATE` received during shutdown. Opens a new connection to act
under a different identity.

## 4.22.3 A conforming service

Reads `NOTIFY_SOCKET` from its environment and hardcodes no path. Sends
`READY=1` when it can genuinely serve, not when its process exists.
Sends no recognized key with an undefined value, no newline inside a
`STATUS` value, and no `PROGRESS` outside its three forms. Sends no datagram exceeding the bounds in §4.A. Expects
no reply, and no acknowledgment that a field was applied. Treats
`EXTEND_TIMEOUT_USEC` as replacing a deadline rather than adding to one.
Checks `LISTEN_PID` against its own PID before adopting any descriptor.

## 4.22.4 What conformance is not

A system built from different components need not offer either channel
(PSPU §1.1). These are contracts for the components that do offer them.

---

# Appendix 4.A Limits and Defaults

_Peios Specifications / PSPU / Service Control and Notification_

> The limits and defaults a Peios service manager uses on both channels, and which of them are configurable.

The values a Peios service manager uses. A manager MAY use different
ones; where a value is configurable, it MUST be discoverable to an
administrator through the same surface that sets it.

## 4.A.1 Control channel

| Bound | Value | Configurable | Defined in |
|---|---|---|---|
| Socket path | `/run/services/peinit/control.sock` | No | §4.4 |
| Concurrent connections per caller | 16; SYSTEM exempt | Yes | §4.4 |
| Concurrent connections in all | 256 | Yes | §4.4 |
| Request size | 65536 bytes, excluding the terminating newline | Yes | §4.4 |
| Idle timeout | 30 seconds | Yes | §4.4 |
| Listen backlog | 32 | No | §4.4 |

## 4.A.2 Operations

| Bound | Value | Defined in |
|---|---|---|
| Terminal record retention | 60 seconds | §4.14 |
| Operation lifetime | The target service's own start or stop timeout | §4.11 |

## 4.A.3 Notification channel

| Bound | Value | Defined in |
|---|---|---|
| Maximum datagram | 65536 bytes | §4.16 |
| Descriptors per datagram | 64 | §4.16 |
| First returned descriptor | 3 | §4.20 |
| Descriptor store maximum | Per service; 0 disables | §4.20 |
| Timeout extension cap | 4 × the phase's base timeout | §4.19 |
| Progress event rate | At most one per sender per second | §4.19 |

## 4.A.4 Composing the two channels

A `STATUS` value a service sends on the notification channel is
returned as `status_text` on the control channel. The notification
datagram bound is 65536 bytes and the control response is not bounded by
the request limit, so a status string that fits in a datagram is always
returnable.

The bounds are stated at their values here rather than left to each
implementation because a producer has no other way to learn them.
Lowering either without telling anyone breaks every service that was
sizing to the old one, and the failure — a truncated datagram, or a
connection closed mid-request — does not name its cause.

---

# Appendix 4.B Wire Vocabulary

_Peios Specifications / PSPU / Service Control and Notification_

> Every enumerated value on the control channel — response status, service state, transition cause, health, job and operation types, granted rights, and boot modes and their reasons.

Every enumerated value that appears on the control channel. All are
lower snake case. Except for status warning types and granted rights,
these sets are closed: a manager MUST NOT emit a value outside them
without the version negotiation in §4.21, and a client MUST treat one it
does not recognize as an error for that request rather than mapping it
onto a value it knows. The open sets state their handling rules below.

These sets are the control channel's. The same words appear in the
manager's structured events in kebab-case, as every event value is
(PGSS §6.5): `explicit_start` on the channel is `explicit-start` in an
event.

## 4.B.1 Response status

`ok`, `error`

## 4.B.2 Service state

| Value | Process? | Satisfies dependents? |
|---|---|---|
| `inactive` | No | No |
| `starting` | Maybe | No |
| `active` | Yes | Yes |
| `reloading` | Yes | Yes |
| `stopping` | Briefly | No |
| `completed` | No | Yes |
| `backoff` | No | No |
| `failed` | No | No |
| `abandoned` | Yes, unkillably | No |
| `skipped` | No | Yes |

Exactly four states satisfy dependents: `active`, `reloading`,
`completed` and `skipped`. A client deciding whether something depending
on this service could be running MUST use that set and no other.

## 4.B.3 Transition cause

`explicit_start`, `dependency_start`, `restart_policy`,
`binds_to_recovery`, `timer`, `explicit_stop`, `explicit_reload`,
`explicit_reset`, `conflict_eviction`, `binds_to_propagation`,
`shutdown_wave`, `process_crash`, `clean_exit`, `clean_exit_restart`,
`readiness_timeout`, `watchdog_timeout`, `health_check_failure`,
`pre_hook_failure`, `parent_setup_failure`, `pre_exec_failure`,
`dependency_failure`, `restart_budget_exhausted`, `cycle_detected`,
`validation_error`, `assertion_error`, `condition_skipped`,
`tty_unavailable`, `process_unkillable`, `internal_error`

A `cause` may also be `null`, for a service that has not transitioned.

## 4.B.4 Service health

`healthy`, `unhealthy`, `unknown`

`health` is `null` when the service has no health check configured,
which is distinct from `unknown` — the latter means one is configured
and has not produced a result yet.

## 4.B.5 Job type

`service_main`, `pre_exec_hook`, `post_exec_hook`, `reload_hook`,
`health_check`, `submitted`

Only `service_main` appears in `current_job`. Only `submitted` appears
in a job view (§7.7); a job's state and cause vocabularies are §7.B's.

## 4.B.6 Operation type

`start`, `stop`, `restart`, `reload`, `reset`

## 4.B.7 Operation state

| Value | Terminal? | Meaning |
|---|---|---|
| `pending` | No | Queued, not yet executing. |
| `running` | No | Executing. |
| `completed` | Yes | Reached its goal. |
| `failed` | Yes | Did not reach its goal, or expired while queued. |
| `merged` | Yes | Merged into another operation. |
| `cancelled` | Yes | Terminated while pending. Never executed. |
| `aborted` | Yes | Terminated while running. |

## 4.B.8 Operation source

`admin`, `boot`, `shutdown`, `dependency_propagation`, `restart_policy`,
`timer`, `binds_to_recovery`, `binds_to_propagation`,
`conflict_resolution`, `on_failure`, `tty_release`

`admin` is the only source a client's own command produces. The rest
describe operations the manager created for its own reasons, and a
client observing one has learned something about what the manager is
doing rather than about anything it asked for.

## 4.B.9 Reload mode

`confirmed`, `advisory`, `failed`

## 4.B.10 Status warning type

`service_tree`, `health`, `hooks`, `helper`

These name what part of a service's process containment could not be
reclaimed, `service_tree` being the whole of it and therefore the most
serious. A client MUST accept a value outside this set and MUST NOT
discard the warning (§4.21).

## 4.B.11 Granted right

In a status's `granted`: `query_status`, `start`, `stop`, `interrogate`

In a job view's `granted`, on this channel: `query`, `stop`, `signal`

Each names a right of §4.7 or §7.8, lowercased and without its
`SERVICE_` or `JOB_` prefix, and they appear in the order given here
(§4.14). A client MUST ignore a name outside these sets rather than
treat it as an error: an unrecognized right is one it has no command
for, and the rights it does know are still correctly reported.

## 4.B.12 Shutdown type

`poweroff`, `reboot`, `halt`

Request-only; the manager does not echo it.

## 4.B.13 Boot mode

`full`, `safe`, `recovery`

The modes §4.15 defines. Only `boot` returns one, and a manager in
`recovery` does not serve this channel, so in practice a client reads
`full` or `safe`.

## 4.B.14 Boot mode reason

| Value | Meaning |
|---|---|
| `normal` | A `full` boot, which is what a boot is unless something says otherwise. |
| `requested` | The boot was asked for in this mode, on the kernel command line or its equivalent. |
| `safe_mode_downgrade` | A `full` boot that the manager downgraded to `safe` because it found a fault it could not start the full configuration past, such as a critical service in a dependency cycle. `downgrade` lists each finding. |

---

# 5.1 Scope and Roles

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> What this chapter specifies, a package, the artifact directory that stores it, the closures composed from it and the repositories that publish it, its roles, and what it leaves out.

This chapter specifies how Peios software is packaged, stored, composed and
published. A **package** is a manifest listing every path it installs, with
each file's content stored separately as a blob named by its hash. Packages
live in an **artifact directory**, are composed into **closures**, each the
contents of a `/usr`, and are published by **repositories**, artifact
directories that say what they publish and sign it.

`ppk(1)` implements this chapter. Where this chapter and ppk disagree, the
disagreement is a defect in one of them, to be resolved by changing one.

## 5.1.1 Roles

| Role | Does |
|---|---|
| **Producer** | Packs a directory into a package (§5.18) |
| **Publisher** | Makes an artifact directory a repository and signs it (§5.36) |
| **Consumer** | Fetches, verifies, resolves, and composes packages (§5.26, §5.29) |

One program commonly plays every role. Each requirement says which role it
binds; §5.38 collects them by role.

## 5.1.2 In scope

- Package names, capabilities, versions, constraints, and architectures
  (§5.3 to §5.8).
- The artifact directory, its blobs, manifests and refs (§5.10 to §5.12).
- What a package can install, and the form of its manifest (§5.13 to
  §5.23).
- Closures, their inventory, and their names (§5.24, §5.25, §5.27).
- Environment profiles and resolution (§5.28, §5.29).
- Repositories: their catalog, indexes and channels, their pointer file
  and its signature, and how a machine is configured to fetch from them
  (§5.30 to §5.36).

## 5.1.3 Out of scope

- **How an installed system boots** from a closure. The names it uses for
  its closures are reserved here (§5.27); the rest is the installer's.
- **The kernel's verification of a file's signature.** A package carries a
  file's PIP signature (§5.16); PSPK book 3 specifies the signature and its
  check.
- **Network transport other than HTTP.** A repository is a directory, which
  a static web server can serve as it is over HTTP or HTTPS (§5.34). Other
  transports are reserved for a future version.
- **Registry seeds and other system policy** that a release carries. They
  are packaged as files and applied by other components.

## 5.1.4 Relationship to other chapters

The root skeleton file a package can ship is PSPU book 11. Security
descriptors are PCDS's. File signatures are PSPK book 3's.

---

# 5.2 Terminology

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> The terms this chapter defines, package, identity, artifact directory, closure, request, repository, index and channel, used with these meanings throughout.

**Package**
: A manifest (§5.18) and the blobs it names. A package is identified by its
  name, version and architecture, and its content by its identity.

**Package ID**
: `<name>@<version>?arch=<architecture>`, as
  `dev.peios.hello@1.0-1?arch=x86_64`.
  The `?arch=` part MAY be left out where an architecture is implied.

**Identity**
: `sha256:` followed by the lowercase hexadecimal SHA-256 hash of some
  bytes. A package's identity is its manifest's (§5.11).

**Blob**
: A file's content, stored once, and named by its hash (§5.12).

**Artifact directory**
: A directory holding packages: their blobs, manifests, and refs (§5.10). A
  machine's own is its **store**, `/system/artifacts`.

**Capability**
: A name a package provides or requires, such as a soname (§5.4).

**Closure**
: A set of packages composed into one directory tree, the contents of a
  `/usr` (§5.24).

**Inventory**
: The file at the top of a closure that records its packages and what wants
  each (§5.25).

**Request**
: What is asked for: a package by name, or a capability, at the versions
  that would do, and optionally from an index (§5.29).

**Resolution**
: Choosing a version of each package that requests need (§5.29).

**Profile**
: A file of requests, with what a composed root holds outside `/usr`
  (§5.28).

**Repository**
: An artifact directory that publishes what it holds, through a signed
  pointer file (§5.30).

**Catalog**
: Every version a repository has published (§5.30).

**Index**
: One version of each package, for each architecture, that a repository
  publishes together: `leading`, the newest, or a snapshot of a release
  (§5.30).

**Channel**
: A name that follows an index or another channel, such as `stable`
  (§5.30).

---

# 5.3 Package Names

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> What a package name can contain, its reverse-DNS structure, and the conventions for related packages.

A package's name says who owns the software and what it is: the owner's
domain, backwards, then the product, as in `dev.peios.hello`,
`org.gnu.gcc-c++` and `io.github.eudev-project.eudev`.

## 5.3.1 Structure

A package name MUST consist of at least 3 labels separated by `.`, and MUST
be at most 64 characters long.

Each label MUST consist of lowercase ASCII letters `a` to `z`, digits `0` to
`9`, `+` and `-`. It MUST start with a letter or a digit, MUST NOT end with
`-`, and MUST NOT contain `--`.

The first label MUST consist of letters only, and the first two labels MUST
NOT contain `+`.

```text
dev.peios.hello
org.gnu.gcc-c++
se.curl.curl
io.github.eudev-project.eudev
```

## 5.3.2 Case

Names are case-sensitive, and since uppercase letters are not permitted,
two names are the same name exactly when they are the same bytes.

## 5.3.3 Conventions

Packages holding related but separable content SHOULD add a suffix to the
main package's name:

| Suffix | Content |
|---|---|
| `-devel` | Headers, static libraries, and other build-time files |
| `-libs` | The shared libraries of a program, alone |
| `-static` | Static libraries |

These are conventions. Nothing enforces them, and a name MAY use others.

---

# 5.4 Capabilities

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> Names that a package provides or requires besides package names, such as sonames, their grammar, and the one namespace they share with package names.

A **capability** is a name that a package provides and another requires,
such as the soname `libc.so.6`, the command `sh`, or the pkg-config module
`pkgconfig(zlib)`. A requirement names a capability (§5.21); a provide
offers one at a version, or at none. Capabilities derived from a package's
own files are §5.22's.

## 5.4.1 Grammar

A capability is 2 to 128 characters long, and is one of:

- **A plain name:** ASCII letters of either case, digits, `-`, `.`, `+` and
  `_`, starting with a letter or a digit and ending with a letter, a digit,
  or `+`. Case MUST be preserved: a dynamic loader treats `libGL.so.1` and
  `libgl.so.1` as two libraries.
- **A namespaced name**, `namespace(argument)`: the namespace is lowercase
  letters and digits starting with a letter, and the argument is not empty
  and holds what a plain name can, and `:` and `/`, as in
  `pkgconfig(gtk+-3.0)`, `perl(Foo::Bar)` and
  `elfver(libstdc++.so.6:GLIBCXX_3.4.32)`.

## 5.4.2 One namespace

Capabilities and package names share one namespace: every package provides
its own name, at its own version, as a capability. A requirement on
`dev.peios.hello` is satisfied by that package, or by any package that
provides that capability.

The namespaced form keeps capabilities from foreign naming schemes from
colliding with package names: `pkgconfig(zlib)` is the pkg-config module,
never a package.

---

# 5.5 Versions

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> The structure of a package version string — epoch, upstream version, and Peios revision — and how it is parsed.

Every package carries a version string that identifies one build of that
package. Version strings have a defined structure and a defined
comparison order (§5.6), so that "newer" and "older" are unambiguous
across every implementation.

## 5.5.1 Structure

```text
[<epoch>:]<upstream>-<peios_revision>
```

- **Epoch** — an OPTIONAL non-negative integer, separated from the rest
  by a colon. Absent means zero.
- **Upstream** — the version the upstream project assigned, or, for
  Peios-native software, the version Peios assigned as vendor.
- **Peios revision** — a REQUIRED positive integer identifying the build
  of this upstream version produced by the distributor.

```text
1.26.2-3            upstream 1.26.2, revision 3
1.26.2-rc.1-1       upstream 1.26.2-rc.1, revision 1
2:0.5.0-1           epoch 2, upstream 0.5.0, revision 1
0.22-1              upstream 0.22, revision 1 (Peios-native)
```

## 5.5.2 Epoch

The epoch MUST be encoded as ASCII decimal digits with no leading zeros,
except that zero is encoded as the single digit `0`. The separator is a
single colon.

Epoch exists solely to override the natural ordering of upstream version
strings when an upstream regression makes a later release compare as
older than an earlier one. Bumping it SHOULD be a deliberate, documented
decision; a routine version update MUST NOT bump it.

> [!NOTE]
> An upstream project releases v2.0, abandons that line, and releases
> v0.5 as its new stable branch. Without an epoch, v0.5 compares as
> older than v2.0 and nobody on v2.0 can upgrade. Bumping the epoch to 1
> says "v0.5 in this epoch is newer than anything in epoch 0".

## 5.5.3 Upstream version

The upstream version is everything between the optional epoch separator
and the final hyphen preceding the revision.

It MUST consist of ASCII characters drawn from: letters `a`–`z` and
`A`–`Z`, digits `0`–`9`, period `.`, plus sign `+`, hyphen `-`, and
tilde `~`. It MUST start with a digit or a letter, and MUST NOT contain
whitespace or any character outside that set.

> [!NOTE]
> The set is permissive because upstream projects format versions in
> every way imaginable: numeric (`1.26.2`), hyphenated pre-release
> (`1.0.0-rc.1`), concatenated pre-release (`16beta1`), build metadata
> (`1.0+build.42`), and tilde-separated pre-release (`1.0~rc.1`).

## 5.5.4 Peios revision

The peios revision MUST be a positive integer encoded as ASCII decimal
digits with no leading zeros. It is incremented when the distributor
produces a new build of the same upstream version — a backported
security patch, a build-configuration change, a dependency bump, a
packaging fix.

The first revision of any upstream version MUST be `1`. Revision `0` is
reserved and MUST NOT appear in a published package.

## 5.5.5 Parsing

A version string is parsed as follows:

1. If the string contains a colon, split at the **first** colon: what
   precedes it is the epoch, what follows is the remainder. Otherwise
   the epoch is 0 and the remainder is the whole string.
2. Split the remainder at the **last** hyphen: what follows is the peios
   revision, what precedes is the upstream version.
3. The peios revision MUST parse as a positive integer.
4. The upstream version MUST satisfy the constraints above.

A version string that does not parse is invalid, and an implementation
MUST reject it.

## 5.5.6 Stability

The comparison algorithm of §5.6 is frozen. Any two conforming
implementations MUST produce identical comparison results for every pair
of valid version strings. An implementation that disagrees with another
on any such pair is non-conformant, whichever of the two is at fault.

---

# 5.6 Comparing Versions

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> The three-stage comparison that decides which of two versions is newer, including pre-release segments and their rank.

Two version strings are compared in three stages:

1. Compare epochs as integers. If they differ, the higher epoch is
   greater.
2. If equal, compare upstream versions by the algorithm below.
3. If equal, compare peios revisions as integers. The higher revision is
   greater.
4. If all three are equal, the versions are equal.

## 5.6.1 Tokenising the upstream version

A tokeniser walks the upstream string left to right and emits segments:

1. The non-alphanumeric characters `.`, `+`, `-`, and `~` are separators
   and belong to no segment.
2. A maximal run of digits forms a **numeric** segment.
3. A maximal run of letters forms an **alphabetic** segment.
4. A transition between a digit and a letter ends the current segment
   and begins a new one.

## 5.6.2 Pre-release segments

A segment is a **pre-release segment** if it falls at or after the
earlier of:

- the first `~` separator — the tilde and every segment following it; or
- the first **recognized pre-release token**: a segment whose token
  carries a rank of 0 to 4 in the table below, that segment and every
  segment following it.

Once the pre-release tail begins it extends to the end of the upstream
version: every later segment is a pre-release segment, whatever the
separators between them. A `-` separator is an ordinary separator; it is
not itself a pre-release marker.

> [!NOTE]
> In `1.0.0-rc.1`, `rc` is recognized at rank 4, so `rc` and the
> following `1` are pre-release. In `16beta1`, `beta` is recognized at
> rank 2, so `beta` and `1` are pre-release with no separator involved.
> In `1.0-foo`, `foo` is alphabetic but not recognized: it is an
> ordinary rank-5 segment, and the `-` before it begins nothing.

| Upstream | Segments |
|---|---|
| `1.26.2` | `1`, `26`, `2` |
| `1.0.0-rc.1` | `1`, `0`, `0`, `rc` (pre), `1` (pre) |
| `1.0~rc1` | `1`, `0`, `rc` (pre), `1` (pre) |
| `16beta1` | `16`, `beta` (pre), `1` (pre) |

## 5.6.3 Pre-release rank

| Token | Rank |
|---|---|
| `dev` | 0 |
| `alpha` | 1 |
| `a` | 1 |
| `beta` | 2 |
| `b` | 2 |
| `pre` | 3 |
| `rc` | 4 |
| any other alphabetic token | 5 |

Rank 0 sorts lowest. Rank lookup MUST be case-insensitive: `Alpha`,
`ALPHA`, and `alpha` all carry rank 1.

## 5.6.4 Comparing two segments

The pre-release flag is compared first, before the kinds. If exactly one
of the two segments is a pre-release segment, **that segment is the
lesser**, whatever either segment contains. A pre-release segment sits at
or after the point where the version was marked as preceding a release,
and that is a property of position rather than of content.

When both segments carry the same flag — both pre-release, or neither —
their kinds decide:

1. **Both numeric** — compare as integers. Leading zeros are
   insignificant.
2. **Both alphabetic** — compare by pre-release rank. When the ranks are
   equal:
   - at a rank of 0 to 4, the segments are **equivalent**. The table
     assigns several tokens to one rank as aliases, so two segments at
     the same recognized rank sort equal whichever alias appears.
   - at rank 5, the segments tiebreak by ASCII byte order against other
     rank-5 tokens.
3. **One numeric, one alphabetic** — the alphabetic segment is the
   lesser if the pair is a pre-release pair, and the greater if it is
   not. (Where only one of them is a pre-release segment, the rule above
   has already decided.)

> [!NOTE]
> ```text
> 1.0~alpha-1 == 1.0~a-1       # both rank 1
> 1.0~beta-1  == 1.0~b-1       # both rank 2
> 1.0~Alpha-1 == 1.0~ALPHA-1   # case-insensitive recognition
> 1.0-foo-1   <  1.0-zzz-1     # rank-5 lexical tiebreak
> ```
> Two upstream versions that differ only in which alias they use are
> equal. An artifact directory holding both forms holds two packages at
> one version, which resolution refuses to choose between (§5.29). A
> producer SHOULD pick one form, conventionally `alpha` rather than `a`,
> and keep to it.

## 5.6.5 Unequal lengths

When the segments of one version run out and every common segment
compared equal, the next segment of the longer sequence decides. Its
pre-release flag decides it, and its kind is irrelevant:

| Next segment in the longer | Result |
|---|---|
| a pre-release segment | the shorter is **greater** |
| anything else | the shorter is less |

| Example tail | | Result |
|---|---|---|
| `~1` | numeric, pre-release | the shorter is **greater** |
| `~rc` | alphabetic, pre-release | the shorter is **greater** |
| `.1` | numeric | the shorter is less |
| `-foo` | alphabetic, rank 5 | the shorter is less |

## 5.6.6 Worked examples

| A | B | Result | Why |
|---|---|---|---|
| `1.0~2` | `1.0-2` | A < B | the pre-release flag decides before the kinds |
| `1.0~foo` | `1.0-foo` | A < B | the same, for two rank-5 tokens |
| `1.0` | `1.0` | A = B | identical |
| `1.0` | `2.0` | A < B | numeric segment differs |
| `1.10` | `1.9` | A > B | numeric, not lexical |
| `1.0` | `1.0.1` | A < B | longer continues numerically |
| `1.0` | `1.0-rc.1` | A > B | longer continues with a pre-release |
| `1.0-rc.1` | `1.0-rc.2` | A < B | numeric segment within the tail |
| `1.0-alpha` | `1.0-beta` | A < B | rank 1 < rank 2 |
| `1.0-rc` | `1.0-pre` | A > B | rank 4 > rank 3 |
| `1.0a1` | `1.0a2` | A < B | numeric within a concatenated tail |
| `1.0a1` | `1.0b1` | A < B | rank 1 < rank 2 |
| `1.0~rc1` | `1.0` | A < B | the tilde forces a pre-release |
| `1.0~1` | `1.0` | A < B | the tilde forces a pre-release, numeric or not |
| `5.2~20240101` | `5.2` | A < B | a dated snapshot precedes its release |
| `0:1.0` | `1:0.5` | A < B | epoch dominates |
| `1.0-1` | `1.0-2` | A < B | peios revision differs |
| `1.0-foo-1` | `1.0-1` | A > B | `foo` is rank 5, sorting after a number |

---

# 5.7 Version Constraints

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> How a relationship restricts which versions satisfy it — the operators, how they combine, and revision-relaxed operands.

A **version constraint** restricts which versions of a package satisfy a
relationship (§5.21).

## 5.7.1 Operators

| Operator | Meaning |
|---|---|
| `=` | exactly equal |
| `>` | strictly greater than |
| `>=` | greater than or equal |
| `<` | strictly less than |
| `<=` | less than or equal |
| `!=` | not equal |

Comparison is by §5.6 in every case.

A bare version string with no operator is equivalent to `=`.

## 5.7.2 Combining

Multiple expressions within one constraint string are separated by
commas and combined with logical AND. A version satisfies the constraint
if and only if it satisfies every expression.

```text
libssl >= 3.0
libssl >= 3.0, < 4.0
nginx = 1.26.2-3
```

Whitespace around operators and commas is optional and MUST be ignored.

A constraint string MUST parse as one or more operator-and-version
expressions separated by commas. One that does not parse is invalid, and
an implementation MUST reject it.

## 5.7.3 Revision-relaxed operands

A constraint's version operand MAY omit the `-<revision>` that a
complete version string otherwise requires.

An operand written without a revision — `>= 3.0` — constrains the epoch
and the upstream version only. A candidate satisfies it whenever its
epoch and upstream version satisfy the operator, whatever its revision.

An operand written in full constrains the revision as well.

> [!NOTE]
> This is what lets a dependency track a capability level rather than a
> packaging iteration. `libssl >= 3.0` is satisfied by `3.0-1` and by
> `3.0-7` alike; nothing about a repackaging of the same upstream
> release should change whether a dependency is met.

---

# 5.8 Architectures

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> The architecture identifier, the defined set, the triplets derived from them, and how one resolution takes one architecture.

A package's architecture identifies the instruction-set architecture its
files are for. It is part of the package ID, separate from the name and the
version.

## 5.8.1 Identifier format

An architecture identifier MUST consist of ASCII letters, digits, `.`, `_`,
`+`, `-` and `~`, and MUST start with a letter or a digit.

## 5.8.2 Defined architectures

| Identifier | Meaning |
|---|---|
| `x86_64` | 64-bit x86 (AMD64, Intel 64) |
| `aarch64` | 64-bit ARM (ARMv8-A or later) |
| `noarch` | Content that doesn't depend on the architecture |

`x86_64` is the primary target. A new identifier SHOULD be the Linux
machine name, as `uname -m` reports it, where there is one.

## 5.8.3 Triplets

Each architecture but `noarch` has a **triplet**,
`<identifier>-linux-peios`, used in the paths where architecture-specific
content is kept apart (§5.15): `x86_64-linux-peios`, `aarch64-linux-peios`.
`noarch` has none.

> [!NOTE]
> The `peios` suffix tells Peios binaries from other systems' binaries for
> the same architecture: Debian uses `gnu`, Alpine `musl`.

## 5.8.4 One architecture per resolution

A resolution (§5.29) chooses packages of one architecture: the one its
requests name, or the consumer's own. A package of another architecture,
`noarch` included, is not a candidate in it.

> [!NOTE]
> This version doesn't let a resolution for `x86_64` choose a `noarch`
> package. Content that doesn't depend on the architecture is packed for
> each architecture instead. A future version can let `noarch` packages
> join any resolution without changing the format.

---

# 5.9 Document Conventions

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> The rules every file this chapter defines obeys, its encoding, its one canonical form, its identities and its names.

## 5.9.1 Encoding

Every file this chapter defines is UTF-8 text, with LF line endings and a
newline at the end of its last line, except the signature of a pointer file
(§5.33) and the content of blobs (§5.12), which are bytes.

## 5.9.2 One form

A manifest (§5.18), an inventory (§5.25), a tree node (§5.31) and a pointer
file (§5.32) are hashed, so each has exactly one spelling. Each section
that defines one says how it is written. A consumer MUST refuse one that is
not in that form, even if it means the same: it reads the file, writes it
again, and refuses it if the bytes differ.

Manifests and profiles are TOML. A TOML string in a file this chapter
defines is a basic string, with `"` and `\` escaped by a backslash, every
ASCII control character written `\uXXXX` with uppercase hexadecimal digits,
and everything else as literal UTF-8.

The other files are line formats: one record a line, its fields separated
by single spaces, no other whitespace, and lines sorted by bytes where the
section says they are sorted.

## 5.9.3 Identities

An identity is `sha256:` and the 64 lowercase hexadecimal digits of the
SHA-256 hash of some bytes. SHA-256 is the only hash algorithm of this
version. Where a file is named by its hash, the name is the 64 digits alone.

## 5.9.4 Names of closures, indexes, channels, and repositories

A closure name (§5.27), an index or channel name (§5.30) and a repository
name (§5.35) are each 1 to 64 ASCII letters, digits, `-`, `.` and `_`, not
starting with `.`. A closure name MUST also not end with `.manifest`, and
MUST NOT be 64 hexadecimal digits, so that it can't be taken for a closure.

## 5.9.5 Keywords

The key words MUST, MUST NOT, REQUIRED, SHOULD, SHOULD NOT, RECOMMENDED,
MAY and OPTIONAL are to be read as BCP 14 describes, when they appear in
capitals.

---

# 5.10 The Artifact Directory

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> Where packages are stored, the layout of an artifact directory, its blobs, manifests, refs and closures, and why everything in it but its refs is named by its hash.

An **artifact directory** holds packages. A machine's own is its **store**,
`/system/artifacts`. A repository is an artifact directory that also
publishes what it holds (§5.30).

## 5.10.1 Layout

| Path | Holds |
|---|---|
| `blobs/sha256/<hash>` | A file's content, not executable (§5.12) |
| `blobs/sha256/<hash>.exec` | The same content, executable |
| `blobs/sha256/<hash>.<entry>` | The content of a file with security metadata, carrying it |
| `manifests/sha256/<hash>` | A manifest, named by the hash of its bytes (§5.18) |
| `refs/<name>/<version>/<arch>` | The identity of that package (§5.11) |
| `closures/<hash>/` | A closure's tree (§5.24) |
| `closures/<hash>.manifest` | The closure's manifest |
| `closures/<name>` | A closure's name (§5.27) |

A repository adds its trees, `trees/sha256/<hash>`, its pointer file,
`repository`, and its signature, `repository.pso` (§5.30).

## 5.10.2 What is named by its hash

Everything in an artifact directory but its refs, its closures' names and a
repository's pointer file is named by the hash of what it holds, and so
never changes once written. Writing one that already exists MUST leave it
as it is if its content is the same, and MUST fail if it isn't.

A file is written whole, in a temporary file beside where it goes, then
renamed into place, so that a reader never sees part of one.

## 5.10.3 Modes

Blobs and manifests are read-only: mode 0444, or 0555 for an executable
blob. A blob is a hard link of every file a closure holds with its content
(§5.24), so a change to one would change every closure that has it.

---

# 5.11 Package Identity

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> How a package is named by the hash of its manifest, what a ref records, and why a version, once stored, never changes.

## 5.11.1 Identity

A package's **identity** is the identity of its manifest's bytes (§5.9):
`sha256:` and the SHA-256 hash of the manifest. The manifest lists every
path of the package with the hash of each file's content (§5.18), so the
identity covers every byte and every piece of metadata the package has.

Two packages with the same identity are the same package.

## 5.11.2 Refs

A **ref**, `refs/<name>/<version>/<arch>`, records which package an
artifact directory holds for that package ID: its identity, then a newline,
and nothing else.

A consumer MUST refuse a ref that holds anything else, and MUST check that
the manifest it names hashes to that identity and names that package ID.

## 5.11.3 A version is never replaced

Once an artifact directory holds a package at a version, it MUST NOT come
to hold another package at that version. Packing or fetching a package
whose ID is held with another identity MUST fail, writing nothing. A change
to a package is a new revision (§5.5).

A bootstrap, whose artifact directory nothing has fetched from yet, MAY
replace a package, with an explicit request naming it. The manifest it
replaces and that manifest's blobs stay.

---

# 5.12 Blobs

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> A file's content stored once, by its hash, in one form for each mode, as a file of its own when it carries security metadata, and compressed in a repository that says so.

A **blob** is the content of a file of a package, uncompressed, in a file
of its own named by the SHA-256 hash of the content. Content that several
packages, or several paths, share is stored once.

## 5.12.1 Forms

A blob is stored in the form each entry that names it needs:

- `blobs/sha256/<hash>`, mode 0444, for a file that is not executable;
- `blobs/sha256/<hash>.exec`, mode 0555, for an executable file;
- `blobs/sha256/<hash>.<entry>`, for a file with security metadata
  (§5.16, §5.20): `<entry>` is the hash of the entry as the manifest
  writes it, after its path and ` = `. Such a blob carries the entry's
  descriptor and signature, so every hard link to it carries them too, and
  two files with the same content and different metadata are two blobs. Its
  mode is 0444, or 0555 if the entry is executable.

Content shipped both as executable and not is stored in both forms.

A file's PIP signature (§5.16) is itself a blob, named by its own hash.

## 5.12.2 Verification

A consumer copying a blob MUST check that its content hashes to its name
before the blob is used, and a blob that doesn't MUST be refused.

## 5.12.3 Compressed blobs

A repository whose pointer file has the line `blobs zstd` (§5.32) holds
every blob, in every form, as a zstd frame of its content (RFC 8878), under
the name its content gives it. Only blobs are compressed: tree nodes,
manifests, refs, the pointer file and its signature are not, and no
identity changes. Without the line, every blob is its content.

A store and every artifact directory that isn't such a repository hold
their blobs uncompressed, since a closure's files are hard links of them
(§5.24). A consumer copying a blob from a repository whose blobs are
compressed MUST decompress it, and MUST check that what it decompresses to
hashes to its name before the blob is named in the store. A blob that
doesn't, or that isn't a zstd frame, MUST be refused. A consumer MUST
refuse a blob that decompresses to more than 64 GiB, so that a small file
can't fill the store.

A repository whose blobs are compressed is usually an **export**: a copy
of a repository that stays uncompressed, written again from it after each
publication (§5.36).

---

# 5.13 Payload Paths

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> A package's paths are relative to /usr, the constraints on them, the reserved path, and why nothing is canonicalized.

Every path a package holds is relative to `/usr`: a package's `bin/hello`
is `/usr/bin/hello`. A package installs nothing outside `/usr` but the
links it claims (§5.23).

## 5.13.1 Constraints

A path MUST be relative, and MUST NOT contain an empty component, `.`,
`..` or a NUL byte. It MUST be valid UTF-8. It is compared byte for byte:
nothing is canonicalized, so two paths that differ in case or in Unicode
normalization are two paths.

## 5.13.2 The reserved path

The top-level path `inventory`, that is `/usr/inventory`, is the closure's
inventory (§5.25). A package MUST NOT hold it, or anything beneath it,
whether as a file, a directory or a link, and MUST NOT claim it.

## 5.13.3 An empty package

A package with no paths is valid. It installs nothing, and exists for what
it depends on and provides.

---

# 5.14 Install Destinations

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> The /usr layout a package installs into, why package storage under /usr is kept apart from the root-level views, and where the boot paths are.

Peios separates package storage under `/usr` from the root-level views,
such as `/bin`, `/lib` and `/etc`, that software reads. The views are
assembled by the boot and base-filesystem layers from `/usr` and the
machine's own trees; they are not package storage. A package holds paths
under `/usr` only (§5.13), and the views show them at their usual places.

## 5.14.1 The layout

A package SHOULD install into these destinations, and only these:

| Path | Purpose |
|---|---|
| `/usr/bin/` | Programs a person runs, administrative ones included |
| `/usr/sbin/` | System programs: daemons, init, boot, and service executables |
| `/usr/lib/<triplet>/` | Architecture-specific libraries and data (§5.15) |
| `/usr/lib/debug/` | Separated debug information, at the paths of the files it describes |
| `/usr/lib/modules/` | The closure's kernel, `vmlinuz`, and its modules, one kernel per closure |
| `/usr/lib/firmware/` | Device firmware, by device |
| `/usr/lib/earlyirf/<segment>/` | What the kernel reads from the initramfs before the rest (below) |
| `/usr/lib/os-release` | The operating system's identity |
| `/usr/libexec/` | Programs other programs run |
| `/usr/libexec/prelude/hooks.d/` | Initramfs boot hooks |
| `/usr/share/` | Architecture-independent data |
| `/usr/include/` | Headers |
| `/usr/src/debug/` | Debugger source, as the build's source tree |
| `/usr/src/dist/` | Corresponding source |
| `/usr/etc/` | Default configuration for software that reads `/etc` |
| `/usr/conf/` | Defaults for native software's supplementary configuration |

This version doesn't enforce the layout: a consumer composes whatever paths
a package holds.

## 5.14.2 Notes on individual destinations

`/usr/etc/` is the bottom layer of the `/etc` view, which also merges the
machine's reconciled `/system/retc` and its own `/lcl/etc`, in that order. A
package never writes `/etc` itself. `/usr/conf/` is the bottom layer of
`/conf`, beneath `/lcl/conf`.

`/usr/lib/modules/` holds one kernel, `vmlinuz`, and its modules, directly:
there is no directory for each kernel release, because a closure holds one
kernel.

`/usr/lib/earlyirf/` matters only in an initramfs. Each directory in it is
a segment, whose contents map onto the root of the uncompressed archive the
kernel reads first, such as
`/usr/lib/earlyirf/intel-ucode/kernel/x86/microcode/GenuineIntel.bin`. An
administrator's segment of the same name in `/lcl/lib/earlyirf/` replaces
it. `/usr/libexec/prelude/hooks.d/` is likewise read by the initramfs
builder, with `/lcl/libexec/prelude/hooks.d/` before it.

What a root holds outside `/usr`, its mountpoints and links, is its root
skeleton file's (PSPU book 11), which a package such as the base filesystem
ships at `/usr/share/skeleton`.

> [!NOTE]
> What a package doesn't install into, and why:
>
> - `/bin`, `/sbin`, `/lib`, `/libexec`, `/share`, `/include`, `/etc` and
>   `/conf` are **views**, computed from the trees beneath them.
> - `/lcl` is the **machine's own** tree, which survives reinstalling.
>   `/lcl/policy` holds inputs that grant authority.
> - `/system` is **derived**: from the image, the registry or the platform.
> - `/var` is state a running system makes; a package's service makes its
>   own state directories.
> - `/opt`, `/srv`, `/home`, `/media` and `/mnt` belong to the operator and
>   users, and `/dev`, `/proc`, `/sys`, `/run` and `/tmp` to the running
>   system.
> - `/usr/local` doesn't exist: `/usr` is never written by anything but
>   packages, and `/lcl` is the machine's.

---

# 5.15 The Architecture Triplet

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> What an architecture-specific package must install under /usr/lib/<triplet>/, the exemptions, and where architecture-independent data goes.

These rules bind a producer. A consumer doesn't check them: it composes
whatever paths a package holds (§5.14).

A package whose architecture is not `noarch` MUST install all of the
following under `/usr/lib/<triplet>/`, where `<triplet>` is the
architecture triplet of §5.8:

- shared libraries (`.so`, `.so.*`)
- static libraries (`.a`)
- loadable modules — plugin shared objects, and kernel modules outside
  `/usr/lib/modules/`
- architecture-*dependent* helper binaries not on the user's search path
- any other arch-dependent file that is not a user-facing binary

Architecture-*independent* helper executables — a shell script run by
another program, say — go under `/usr/libexec/` instead, which carries
no triplet rule because the rule is scoped to `/usr/lib/`.

A package whose architecture is `noarch` MUST NOT install any file under
`/usr/lib/<triplet>/`. A `noarch` package containing any of the
categories above is invalid.

## 5.15.1 Exemptions

Three arch-dependent payload categories are exempt from the triplet
path, because each is addressed by something other than the host
triplet:

| Category | Path | Addressed by |
|---|---|---|
| Kernel content | `/usr/lib/modules/<release>/` | kernel release |
| Device firmware | `/usr/lib/firmware/` | device |
| Separated debug information | `/usr/lib/debug/` | the install path of the file it describes |

A `noarch` package MUST NOT install under `/usr/lib/modules/` or under
`/usr/lib/debug/`: kernel content and debug information are both
arch-dependent. `/usr/lib/firmware/` carries no such restriction,
firmware being opaque data rather than host-architecture content.

Debug files mirror the full install path of what they describe. The
debug information for `/usr/bin/foo` is
`/usr/lib/debug/usr/bin/foo.debug`; for `/usr/lib/<triplet>/libfoo.so.1`
it is `/usr/lib/debug/usr/lib/<triplet>/libfoo.so.1.debug`. Debug files
MAY additionally be indexed by build ID under
`/usr/lib/debug/.build-id/`.

The freedesktop `os-release` file is a fourth exemption of a different
kind: it installs at exactly `/usr/lib/os-release`, a fixed external
contract path the ecosystem hard-codes. Unlike debug information it is
arch-*independent*, so a `noarch` package — the OS-identity package —
MAY ship it. It is conventionally paired with a `/usr/etc/os-release`
symlink, which the `/etc` merge projects to `/etc/os-release`.

## 5.15.2 Source

The debugger *source* files that debug information references install
under `/usr/src/debug/`, not under `/usr/lib/`. Source is
architecture-independent, so `/usr/src/debug/` carries neither a triplet
rule nor the `noarch` restriction: it is a plain permitted destination
that both arch-specific and `noarch` packages MAY use. The same applies
to `/usr/src/dist/`, the home of corresponding-source packages.

Files retained inside `/usr/src/dist/` are reconstruction inputs rather than
installed library providers. Captured upstream or vendored inputs MAY include
library-shaped test fixtures or import archives for other target platforms
(such as Cargo's Windows crates), including in a `noarch` source package.
Their
`.so` or `.a` suffix does not make that reserved source-data tree a runtime
library installation. The normal library-placement rule still applies outside
this subtree; source data remains subject to path and symlink containment.
Automatic ELF and pkg-config capability derivation MUST ignore `/usr/src/`
inputs: their libraries and `.pc` fixtures do not provide installed interfaces
or create runtime dependencies of a source package.

> [!NOTE]
> A corresponding-source package conventionally lays out
> `/usr/src/dist/<name>-<version>/` with `upstream/` — the pristine
> source artifact, byte-identical to the producer's pinned input —
> `patches/` for the applied patch series, and `recipe/` for the
> build-controlling recipe files including the source lock that makes
> the shipped upstream artifact verifiable. This is a producer
> convention, not a format rule.

## 5.15.3 Architecture-independent data

`/usr/share/` holds architecture-independent files shared across every
architecture of a system: documentation, man pages, locales,
configuration templates, and static data such as icons, images, and
fonts.

Both `noarch` and arch-specific packages MAY install under
`/usr/share/`. A file installed there by an arch-specific package MUST
be byte-identical across every architecture build of the same upstream
version.

---

# 5.16 Payload Entries

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> The three kinds of entry a manifest lists, files, symbolic links and directories, what a file records of its mode, and a file's detached PIP signature.

A manifest's `[files]` table lists every path of the package with an
**entry**: a file, a symbolic link, or a directory.

## 5.16.1 Files

A file's entry names its content's blob (§5.12) by identity, and records
whether it is executable: whether any execute bit was set on the file it
was packed from. That is all a package records of a file's mode. Owner,
group, the other permission bits and timestamps are not part of a package:
access is governed by security descriptors (§5.20).

A producer MUST refuse to pack a file with its set-user-ID or set-group-ID
bit set, and anything that is not a regular file, a symbolic link or a
directory, such as a socket or a device.

## 5.16.2 Symbolic links

A link's entry records its target exactly as `readlink` returns it
(§5.17).

## 5.16.3 Directories

A directory is implied by the paths beneath it. A directory with nothing
beneath it is listed, so that it is created, and so is a directory with a
security descriptor (§5.20), whatever is beneath it. Every other directory
is left out of the manifest, so each tree has one manifest.

## 5.16.4 One package per path

Within a closure, a path belongs to one package. Two packages MAY both list
a path only if their entries for it are identical, security metadata
included; §5.24 says what is refused.

## 5.16.5 Detached signatures

A file the kernel loads as firmware is checked against its PIP signature,
which the kernel reads from the file's `security.peios.sig` extended
attribute (PSPK book 3). A package carries it as part of the file's entry:
the entry's `signature` names a blob holding the signature, which is 3310
bytes, starting with the version byte 1. A consumer that places the file
MUST give it that signature as its `security.peios.sig` attribute.

A producer takes a file's signature from the file beside it in the tree it
packs, named with `.peios.sig` added, which is not packed as a file of its
own. The file it signs MUST be a regular file that is not ELF: an ELF file
carries its signature in its own `.peios.sig` section. No other path MAY end
in `.peios.sig`.

## 5.16.6 Forward compatibility

An entry has one of the three forms of §5.18, with exactly the keys that
section gives. A consumer MUST refuse an entry with any other key: this
version leaves no room for an entry it doesn't understand, since a closure
built without it would not be the package.

---

# 5.17 Symbolic Links

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> Symbolic links as entries of their own, their targets, links that cross into other packages, and why a link has no security descriptor.

A symbolic link is an entry of its own (§5.16): it is never followed when a
package is packed or composed.

## 5.17.1 Targets

A link's target is recorded exactly as `readlink` returns it, and MUST be
valid UTF-8. A relative target resolves from the link's own directory. An
absolute target resolves from the root of the system, not from `/usr`, where
the package's own paths are: a package's `bin/sh` linking to `dash`
resolves to `/usr/bin/dash`, and one linking to `/usr/bin/dash` does too.

## 5.17.2 Across packages

A link MAY point into another package, or at nothing. The format doesn't
check that a target exists, since what is there depends on the closure the
link is composed into.

## 5.17.3 Integrity

A link's target is part of its entry, so the manifest's identity covers it.

## 5.17.4 No descriptor

A link has no security descriptor of its own: access to what it reaches is
the target's. A link MUST NOT be given one (§5.20). A link created when a
closure is built takes what its directory gives it.

---

# 5.18 The Manifest

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> The canonical TOML that lists a package's paths and says what else is known about it, its fields, its tables, its entries, and the one form it is written in.

A package's **manifest** says what the package is: its ID, its metadata,
and every path it holds with that path's entry. It is TOML, in exactly one
form, and its identity is the package's (§5.11).

## 5.18.1 Form

```toml
name = "se.curl.curl"
version = "8.22.0-1"
arch = "x86_64"
description = "Command line tool for transferring data with URLs"
homepage = "https://curl.se/"
license = "curl"
license_class = "free"

[dependencies]
"se.curl.libcurl" = "= 8.22.0-1"

[requires]
"libc.so.6" = ">= 2.34"

[files]
"bin/curl" = { blob = "sha256:3b1f…", exec = true }
"share/man/man1/curl.1" = { blob = "sha256:9a0c…" }
```

A manifest is, in this order:

1. `name`, `version` and `arch`, one line each: the package's ID (§5.3,
   §5.5, §5.8).
2. The descriptive fields that are present (§5.19), one line each, sorted
   by key: `description`, `homepage`, `license`, `license_class`,
   `source`, `source_license`.
3. The tables that are not empty, each after an empty line, in this order:
   `[claims]` (§5.23), `[dependencies]`, `[provides]` and `[requires]`
   (§5.21). Each table's keys are sorted by bytes, one `"key" = "value"`
   line each.
4. An empty line, then `[files]`, then one line for each path, sorted by
   the bytes of the path: the path as a TOML string, ` = `, and its entry.

Every key and string is written as §5.9 writes TOML strings. A constraint
is written as §5.7 writes it, with a single space between an operator and
its version and `, ` between expressions, and an empty string for any
version. A provided capability's version is written as its version, or as
an empty string for none.

An absent field and an empty table are left out, so a package with no
metadata has a manifest of its ID and its files alone.

## 5.18.2 Entries

An entry is an inline table, with single spaces inside its braces and around
each `=`, and its keys in this order:

| Kind | Entry |
|---|---|
| File | `{ blob = "sha256:<hash>" }`, then `, exec = true` if it is executable, then `, descriptor = "<hex>"` and `, signature = "sha256:<hash>"` if present |
| Symbolic link | `{ symlink = "<target>" }` |
| Directory | `{ dir = true }`, then `, descriptor = "<hex>"` if present |

`exec` is written only when true. A descriptor is lowercase hexadecimal
(§5.20); a signature names the blob holding the file's PIP signature
(§5.16).

## 5.18.3 Reading a manifest

A consumer MUST read a manifest as untrusted input. It MUST check that the
manifest's bytes hash to the identity it was asked for, that every path
meets §5.13, and that every field meets its section. It then writes the
manifest it read in this form and MUST refuse it if the bytes differ: that
one comparison refuses unknown keys, unsorted entries and every other
spelling.

---

# 5.19 Descriptive Metadata

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> The fields that describe a package, its one-line description, its homepage, its license, the kind of terms that license is, and the package holding its corresponding source.

A package MAY carry descriptive fields. None affects how it resolves or
composes; each is covered by the package's identity.

| Field | Holds |
|---|---|
| `description` | A one-line description, in printable ASCII |
| `homepage` | The upstream project's `http` or `https` URL |
| `license` | The package's license, conventionally an SPDX expression |
| `license_class` | Which kind of terms the license is (below) |
| `source` | The package holding the corresponding source it was built from (below) |
| `source_license` | The license of the source it was built from, where it isn't the package's own |

None MAY be empty: an absent field is how a manifest says there is nothing.
`license` and `source_license` MUST NOT hold control characters. A
`homepage` MUST name a host.

## 5.19.1 Corresponding source

`source` is a package ID in its string form (§5.2), with its `?arch=`
part, naming the package
that holds the complete source the package was built from: the upstream
source, the patches applied to it, and the files that controlled the
build. It SHOULD name a `noarch` package, since source is the same for
every architecture, such as `org.gnu.bash-source@5.3.20-1?arch=noarch`.

A source package holds its source under `/usr/src/dist/` (§5.14). Several
packages built from one source name the same source package. A package
whose upstream artifact is itself what ships, such as device firmware,
has no source to name and leaves `source` out.

A repository that publishes a package naming a source SHOULD publish that
source package beside it, so that the source can be found from the
package alone.

## 5.19.2 License classes

| Class | Meaning |
|---|---|
| `free` | Free software or open-source terms |
| `firmware` | Terms for device firmware, redistributable but not modifiable |
| `proprietary` | Other terms |
| `unknown` | Not recorded |

`unknown` is the default, and is recorded by leaving `license_class` out:
saying nothing and saying `unknown` mean the same.

---

# 5.20 Security Descriptor Overrides

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> A file or directory takes the descriptor its directory gives it unless its entry gives one, the form of one, and the consumer's obligation when it does.

A file or directory of a package takes the security descriptor that
inheritance from its directory gives it, unless its entry gives one. An
entry's `descriptor` replaces it.

## 5.20.1 Form

A descriptor is a self-relative security descriptor (PCDS) with an owner, a
group and a DACL, written in the manifest as the lowercase hexadecimal of
its bytes. Its bytes are kept as given: two layouts of one descriptor are two
descriptors. A producer MUST check that its parts lie within it; what it
grants is the kernel's to judge.

A symbolic link MUST NOT have one (§5.17). A directory with one is listed in
the manifest even if it has contents (§5.16).

## 5.20.2 The consumer's obligation

A consumer that stores a file or directory with a descriptor MUST give it
that descriptor before anything else can reach it: on Peios, as it creates
it. A file with a descriptor is stored as a blob of its own that carries it
(§5.12), so every hard link to it carries it too.

Where the system won't let the consumer give a descriptor, as on a host that
isn't Peios, it MAY leave it out, and MUST then say how many files and
directories lack theirs. The manifest still records them, and a file stored
without its descriptor MUST NOT be linked into a tree on Peios as if it had
it.

---

# 5.21 Relationships

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> What a package needs and offers, its dependencies, requirements and provides, with their constraints, and what satisfies each.

A manifest's `[dependencies]`, `[requires]`, and `[provides]` tables say what
the package needs and what it offers.

## 5.21.1 Dependencies

A **dependency** is on another package, by name (§5.3), with a constraint
(§5.7):

```toml
[dependencies]
"se.curl.libcurl" = "= 8.22.0-1"
"dev.peios.base" = ""
```

A package that has the name, at a version the constraint holds for,
satisfies it. The empty constraint holds for any version.

## 5.21.2 Requirements

A **requirement** is on a capability (§5.4), with a constraint:

```toml
[requires]
"libc.so.6" = ">= 2.34"
"sh" = ""
```

A package satisfies it if it provides the capability at a version the
constraint holds for, or provides it with no version, which holds for any
constraint; or if the capability is the package's own name and the
constraint holds for the package's version.

## 5.21.3 Provides

A **provide** offers a capability, at a version or at none:

```toml
[provides]
"libcurl.so.4" = ""
"curl" = "8.22.0"
```

A provided version MAY leave out its revision (§5.7). A package provides its
own name at its own version without saying so.

## 5.21.4 What ppk doesn't have

This version has no conflicts, replacements, or optional dependencies.
Packages that can't be composed together are refused when they are
(§5.24); one package taking over from another is a new version of a
package, or a new name that the old one's dependents are moved to.

---

# 5.22 Derived Capabilities

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> The requirements and provides a producer derives from a package's ELF objects, sonames and symbol-version floors, and how they join what it was told.

A producer reads each ELF object among a package's files and adds to the
manifest what it needs and provides. Derivation is the producer's job, done
once when the package is packed: a consumer doesn't read a package's files
to find what it needs.

## 5.22.1 Sonames

An object's `DT_NEEDED` sonames become requirements, for any version, and
its `DT_SONAME` becomes a capability the package provides. A soname the
package provides is not also required.

Files under `src/`, which hold source rather than installed objects, are not
read, nor are symbolic links, which alias an object packed at its own path.
Files that are not ELF are passed over.

## 5.22.2 Symbol-version floors

For the glibc libraries, `ld-linux-x86-64.so.2`, `libanl.so.1`,
`libc.so.6`, `libdl.so.2`, `libm.so.6`, `libmvec.so.1`, `libnsl.so.1`,
`libpthread.so.0`, `libresolv.so.2`, `librt.so.1` and `libutil.so.1`, and
for `libgcc_s.so.1`, whose symbol versions are numbered as their package
is, the highest symbol version an object needs is a floor: an object
needing `GLIBC_2.34` of `libc.so.6` gives the requirement
`libc.so.6 >= 2.34`. A package that provides one of these libraries provides
it at its own version.

The versions of `libstdc++.so.6` are not numbered as gcc is, so each is an
exact capability instead, `elfver(libstdc++.so.6:<version>)`. A package
providing `libstdc++.so.6` provides each version it defines, and an object
needing a version requires it, unless the need is weak.

## 5.22.3 Joining what the producer was told

What derivation finds joins what the producer was given. Where both name one
capability, the given entry is kept, unless it gives no version or holds for
any version, when the derived one is. A given requirement on one of the
floor libraries for anything but any version MUST be refused, because its
floor comes only from the payload, and so MUST a given provide of one at a
version other than the package's.

An object that can't be read, or whose version tables are inconsistent, is
an error, and so is a package providing `libstdc++.so.6` that needs a
version of it that it doesn't define. The same files MUST give the same
requirements and provides.

---

# 5.23 Claim Declarations

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> Links a package provides besides its files, under /usr or outside it, and why only one package in an environment can claim a path.

A **claim** is a link that a package provides besides its files, at an
absolute path, with its target:

```toml
[claims]
"/init" = "usr/sbin/prelude"
"/usr/bin/sh" = "dash"
```

A claim says which package provides a name that several packages could:
the shell at `/usr/bin/sh`, or the initramfs's `/init`. Composing creates
the link.

## 5.23.1 Rules

A claim's path MUST be absolute and normal, with no empty, `.` or `..`
component and no trailing `/`. Its target MUST NOT be empty. Neither MAY
hold a NUL byte.

A claim under `/usr` is a symbolic link in the closure. A claim elsewhere is
made only when a closure is composed into a root, since a closure is only a
`/usr` (§5.24).

## 5.23.2 One claimant

When packages are composed together, a consumer MUST refuse:

- two packages claiming one path, even with one target, since a claim says
  who provides a name;
- a claim at a path one of the packages holds, or beneath one of its files,
  links or claims;
- a claim of `/usr` itself, or of `/usr/inventory` or beneath it (§5.13).

---

# 5.24 Closures

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> Packages composed into one tree of hard links, the contents of a /usr, the conflicts that stop one being built, how one is named, and why an existing one is reused.

A **closure** is a set of packages composed into one directory tree: the
contents of a `/usr`. Mounted at `/usr`, each package's files are at their
ordinary paths.

## 5.24.1 The tree

Every file of a closure is a hard link to its blob in the form its entry
needs (§5.12), which carries the entry's security metadata. Symbolic links
and directories are created in the tree, each directory with its
descriptor, and so is each link a package claims under `/usr` (§5.23). A
closure is only `/usr`, so links claimed elsewhere are left out of it.

A closure MUST be on the same filesystem as the artifact directory its
blobs are in. A consumer MAY copy each file from its blob instead, checking
it against its hash as it does, and giving it the entry's security metadata;
it MUST NOT fall back to copying without being asked.

The tree's root has a protected DACL granting Everyone read and execute,
and SYSTEM and Administrators full control, which what is created in it
inherits. Its files have the access their blobs grant.

The closure's inventory (§5.25) is at the top of the tree, as `inventory`.

## 5.24.2 Conflicts

Every package's paths are merged before anything is written, and a consumer
MUST refuse to build the closure, writing nothing, if:

- two packages give one path different entries, even entries that differ
  only in their security metadata;
- a path lies beneath a file or link of another package, or beneath a
  claimed link;
- a claim breaks §5.23's rules;
- a package holds or claims `/usr/inventory` (§5.13).

The result doesn't depend on the order the packages are given in.

## 5.24.3 Name

A closure is named by the identity of its inventory without the inventory's
first line (§5.25): its packages and what wants each. The same packages
asked for the same way are always the same closure; the same packages asked
for differently are another. A closure's tree is `closures/<hash>/` in the
artifact directory, and its manifest, those same lines, is
`closures/<hash>.manifest`.

## 5.24.4 Reuse

Because a closure's name is known before it is built, a consumer MUST reuse
one that exists rather than build it again, after checking that its
manifest is the one its name hashes to. A closure is built in a temporary
directory beside where it goes and renamed into place when complete, so one
that exists is never half-built. Reusing one only reads it.

---

# 5.25 The Inventory

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> The line format at the top of a closure that records its packages and what wants each, its brackets, its order, and how a closure's identity comes from it.

A closure's **inventory**, `/usr/inventory` when it is mounted, records the
closure's identity and its packages, and why each is there.

## 5.25.1 Form

```text
closure sha256:9c41…
org.openssl.libssl@3.5.8-1?arch=x86_64 sha256:… [se.curl.curl libssl.so.3]
se.curl.curl@8.22.0-1?arch=x86_64 sha256:… [* #stable >=8.22]
```

The first line is `closure`, a space, and the closure's identity. Each other
line is one package: its full ID, a space, its identity, then a space and a
**bracket** for each thing that wants it.

A bracket is `[`, then tokens separated by single spaces, then `]`:

1. **Who wants it:** `*` for a request of the closure itself, or the name of
   a package in the closure.
2. **What it asked for**, if it asked for a capability rather than the
   package by name: the capability (§5.4).
3. **Where from**, for a request that named an index or channel: `#` and its
   name (§5.29). Only a `*` request names one.
4. **Which versions would do:** one token for each expression of the
   constraint, its operator and its version with no space between, such as
   `>=8.22`; none for any version.

A capability never starts with an operator, and a constraint token always
does, so the two can't be confused. No package can be named `*`.

## 5.25.2 What wants a package

A package is wanted by every request it satisfies, and by every dependency
and requirement of another package in the closure that it satisfies (§5.21).
So the brackets are worked out from the packages and the requests alone,
however the closure was reached. A requirement's bracket always names its
capability, even where the capability is the package's own name.

Every package of a closure MUST be wanted by something, and every request
MUST be satisfied by a package of it. A dependency or requirement need not
be satisfied: a closure of exactly the packages given doesn't check what
they need.

## 5.25.3 Order

Lines are sorted by the bytes of the full ID. Brackets are sorted by who
wants the package, `*` first and then by name, then by capability, none
first, then by index, none first, then by the constraint's tokens. A bracket
that would be written twice is written once.

## 5.25.4 Identity

The closure's identity is the identity (§5.9) of every line after the first.
A consumer MUST refuse an inventory whose first line doesn't name that
identity, or that isn't in this form.

---

# 5.26 Verifying a Package

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> What a consumer checks before it stores a package, the order of the checks, and what they prove and don't.

A consumer copying a package from one artifact directory to another trusts
nothing it reads from the source. Before it stores the package, it MUST
check, in this order:

1. **The ref** holds exactly one identity and a newline (§5.11).
2. **The manifest** hashes to that identity, is in the one form §5.18
   gives, names the package ID asked for, and holds only paths that meet
   §5.13.
3. **Each blob** copied hashes to the name the manifest gives it (§5.12).

From a repository served over HTTP, the identity is the one its catalog
gives, and there is no ref to check (§5.34).

A stored file takes only its content from the source: it is given the
security metadata its entry records (§5.20, §5.16).

If a check fails, the consumer MUST stop without writing the manifest or the
ref. Blobs copied before the failure are named by their content, and MAY be
kept. Only a package whose manifest and ref are written is stored.

## 5.26.1 Already present

If the package is already stored with the same identity, the consumer copies
only the blobs that are missing. If it is stored with another identity, the
consumer MUST refuse it (§5.11).

## 5.26.2 What this proves

These checks prove that the package is the one the source's ref names. They
don't prove who published it. A package fetched through a machine's
configuration of a repository that gives an identity is proved published by
it
too: it MUST be in the catalog that the signed pointer file leads to, at the
identity the catalog gives (§5.29, §5.33). A package fetched from a
directory named directly is not.

---

# 5.27 Named Closures

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> A name in a closure directory that points at one of its closures, how it is changed, and the two names an installed system uses.

A closure can be given a **name** of its own, so that what a system runs can
be chosen, and changed, by name.

## 5.27.1 Form

A name is a symbolic link in the closure directory, `closures/<name>`, whose
target is the closure's hash: the name of its tree beside it. A name follows
§5.9's rules for closure names.

A consumer MUST change a name by creating a new link elsewhere in the
closure directory and renaming it over the old one, so that the name always
names one closure or another, never neither. A name MUST NOT be set to a
closure that doesn't exist.

Removing a name leaves its closure. A consumer that lists a closure
directory MUST tell names, which are symbolic links, from closures, which
are directories.

## 5.27.2 Reserved names

| Name | Names |
|---|---|
| `SYSTEM` | The closure that is an installed system's `/usr` |
| `INITRAMFS` | The closure an installed system's initramfs is built from |

How an installed system boots from them is outside this chapter.

---

# 5.28 Environment Profiles

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> A TOML file of the packages an environment asks for and what its root holds outside /usr, fragments it includes, and why it holds requests rather than their answer.

An **environment profile** describes an environment: the packages it asks
for, and what a root composed for it holds outside `/usr`.

```toml
arch = "x86_64"
include = ["layout.toml"]
dirs = ["proc", "sys", "tmp"]

[packages]
"net.busybox.busybox" = "1.37.0-1"
"dev.peios.prelude" = ">= 0.0.7"
"se.curl.curl" = "#stable"

[symlinks]
"init" = ":sbin/prelude"

[files]
"system/pso/store" = "/system/pso/store"
```

## 5.28.1 Keys

| Key | Holds |
|---|---|
| `arch` | The architecture of its packages, the consumer's own by default |
| `include` | Profiles whose contents it holds too, relative to its directory |
| `packages` | Each package asked for, with the versions that will do |
| `symlinks` | Links a composed root holds, each path with its target |
| `dirs` | Empty directories a composed root holds |
| `files` | Files a composed root holds that no package ships, each path with its source |
| `include_artifacts` | `true` to give a composed root its packages in an artifact directory of its own |

Every key is OPTIONAL, and a consumer MUST refuse any other.

A value in `packages` is a constraint (§5.7), or `""` for any version; a
bare version asks for exactly that version. `#` and an index or channel,
optionally followed by a constraint, as in `"#stable"` or
`"#stable >= 1.36"`, asks for what that index holds (§5.29).

A link's target is written as given, unless it starts with `:`, which
stands for `usr`: `":sbin/prelude"` is `usr/sbin/prelude`, relative to the
root.

## 5.28.2 Files from the machine

A profile's `files` gives a composed root files that belong to the
machine and not to any package, such as state a boot image has to carry.
Each key is a path in the composed root, relative to it, and each value
is the absolute path of the source.

A source is resolved against the root of the system the profile is
composed for, which is not always the system the consumer runs on. A
consumer MUST copy the source's content as it is when the root is
composed, and MUST refuse:

- a source that is absent, or is anything but a regular file;
- a path that is `usr` or beneath it, since `/usr` is the closure's;
- a path that is not relative and normal, with no empty, `.` or `..`
  component.

A file a profile names is not part of the closure and does not change
its identity (§5.24). Composing the same profile on two machines gives
the same closure and, where the sources differ, different roots.

> [!NOTE]
> A missing source is refused, not skipped. A root composed without a
> file its profile asked for is a boot image that starts and then fails
> for want of it, which is worse than no image.

## 5.28.3 Requests, not answers

A profile holds requests. Composing it resolves them, with what they need
(§5.29), and the closure's inventory records what was chosen (§5.25). The
inventory is the exact answer; the profile is what was asked. A profile that
asks for exact versions of everything always composes the same environment.

## 5.28.4 Fragments

A profile's `include` names other profiles, which it holds as well. Each
file's `arch` is for its own packages. A consumer MUST refuse:

- two files asking for one package differently;
- packages for two architectures;
- two links at one path with different targets, or a link where another
  file makes a directory;
- two files at one path with different sources, or a file at a path
  where a link or a directory is made;
- a file that includes itself, directly or not.

A file included twice by different routes changes nothing the second time.

---

# 5.29 Resolution

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> Choosing a version of each package that requests need, the order needs are settled in, index requests, yanked and deleted versions, and what makes an error.

**Resolution** chooses one version of each package that a set of requests
needs, from one or more artifact directories, for one architecture (§5.8).

## 5.29.1 Requests

A request asks for a package by name, or for a capability (§5.4), with a
constraint (§5.7). It MAY also name an index or channel of a repository
(§5.30), written after the name with `#`:

```text
se.curl.curl
se.curl.curl >= 8.20
se.curl.curl#stable
se.curl.curl#stable >= 8
libc.so.6 >= 2.34
```

An exact package ID, `name@version`, asks for exactly that version and its
spelling, and is settled before any other request. It can't name an index.

## 5.29.2 Order

Each need, a request or a dependency or requirement of a package chosen, is
settled once, in order:

1. Needs for packages by name are settled before needs for capabilities, at
   every step: first the requests, then the dependencies of what they chose,
   and only when no dependency is left, the first capability waiting.
2. Within each kind, needs are settled in the order of the requests, then
   in the order of each manifest's tables.

A package not chosen yet is chosen at the newest version that satisfies the
need (§5.6). A capability that a chosen package provides at a satisfying
version needs nothing more. Otherwise the one package name that provides it
is chosen, at its newest satisfying version.

Nothing chosen is reconsidered. The same requests against the same packages
MUST always give the same choice.

## 5.29.3 Errors

A consumer MUST refuse a resolution, naming the need and what it met, when:

- nothing satisfies a need;
- a package already chosen doesn't satisfy a later need, which is a
  conflict: the error says what was chosen and why, and whether another
  version would have satisfied both;
- several package names provide a capability that none chosen does, since
  the request must choose one by name;
- the version chosen is spelt two ways, such as `1.0~a-1` and
  `1.0~alpha-1`, which no constraint can tell apart.

## 5.29.4 Index requests

A need from an index is satisfied only by a version that index holds, for
the resolution's architecture. A package chosen for it passes the index on:
its dependencies and requirements are settled from the same index too. A
request for an exact version, or for another index, is an exception, and
MUST still satisfy every need on its package.

A request naming an index that no artifact directory among those given
publishes MUST be refused.

The closure's inventory records the index of each request that names one,
but not the index a dependency or requirement inherited (§5.25).

## 5.29.5 Yanked and deleted versions

A version a repository has yanked (§5.36) satisfies only a need for exactly
that version. A request that only a deleted version would have satisfied
MUST be refused, giving the deletion's reason from the repository's
catalog.

## 5.29.6 Signed repositories

When a repository's identity is configured (§5.35), its packages are
candidates
only if its catalog, reached from its signed pointer file (§5.33), lists
them, and only at the identity the catalog gives. A ref that names another
identity MUST be refused. The refs of a repository without a configured
identity are taken as they are.

A repository served over HTTP has no refs a consumer can list. Its packages
are those its catalog lists, at the identity the catalog gives, with or
without a configured identity (§5.34).

## 5.29.7 Resolving from summaries

A consumer resolving from a repository served over HTTP MUST NOT read a
manifest to do so. It reads only what resolution reaches: for a package
name, its node in the catalog and the summary of each of its versions
(§5.31); for a capability, its node in the provides tree, and each package
name there in the same way. What a summary says replaces what the manifest
would. A version a name's node gives as yanked or deleted is treated as
§5.36 says, whatever the provides tree lists. The manifests are read when
the packages chosen are fetched, and each is checked against the summary
it was chosen by.

The packages chosen are the same as resolving from the manifests would
choose.

---

# 5.30 Repositories

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> An artifact directory that publishes what it holds, its catalog of every version, its indexes of one version of each package, its channels, and the one file that says what each is.

A **repository** is an artifact directory (§5.10) that publishes what it
holds. Besides its packages it has:

- a **catalog**, every version it has published, with how each stands;
- **indexes**, each one version of each package for each architecture: the
  index `leading`, the newest, and **snapshots**, each a release's,
  unchanged for ever;
- **channels**, each following an index or another channel, such as
  `stable` or `2026.10`;
- a **pointer file**, the one file of it that changes, which says what the
  catalog, each index and each channel are, and its **signature**.

## 5.30.1 Layout

| Path | Holds |
|---|---|
| `repository` | The pointer file (§5.32) |
| `repository.pso` | Its signature (§5.33) |
| `trees/sha256/<hash>` | The nodes of the catalog's and the indexes' trees (§5.31) |
| `blobs/`, `manifests/`, `refs/` | Its packages, as any artifact directory's (§5.10) |

An artifact directory without a pointer file is not a repository, but is
still a valid artifact directory, and its packages can be fetched and
resolved as any other's.

Everything below the pointer file is named by its hash, and is reached from
the pointer file through hashes. A signature over the pointer file therefore
vouches for every tree node, every manifest a tree names and every blob a
manifest names.

## 5.30.2 Indexes and channels

Indexes and channels share one namespace, and each name follows §5.9. A
channel's target is an index or another channel, and following channels MUST
reach an index, without a loop.

A release usually has three levels: a snapshot of each patch release, such
as `2026.10.0` and `2026.10.1`; a channel for the release, `2026.10`,
following its latest snapshot; and a channel such as `stable` following the
newest release's channel. A machine tracking `stable` follows every release,
one tracking `2026.10` gets only its fixes, and one tracking `2026.10.0`
changes only when told to.

## 5.30.3 Package names belong to one repository

A machine that fetches from several repositories (§5.35) MUST take each
package name from only one of them. A name that two of them publish is an
error, for a request or anything it needs, until the machine is told which.

---

# 5.31 Tree Nodes

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> The catalog and each index as a tree of small files named by their hash, the three kinds of node, the bucket of a name, each version's summary, the catalog's provides tree, and why a lookup reads three files.

A repository's catalog and each of its indexes is a **tree**: three levels
of small text files, each named by the hash of its content and stored at
`trees/sha256/<hash>`.

## 5.31.1 Package nodes

A package's node has a line for each of its versions in the tree:

```text
8.21.0-1 x86_64 sha256:<manifest> sha256:<summary> yanked
8.22.0-1 x86_64 sha256:<manifest> sha256:<summary>
```

Each line is the version, the architecture, the manifest's identity and
the identity of the version's summary, then, for a version taken back,
` yanked`, or ` deleted ` and a reason (§5.36). A reason is one line, not
empty. The two identities are told from what follows them by their
`sha256:` prefix. A deleted version's line MAY lack its summary; every
other line MUST have one.

This form replaces the one without summaries: a consumer MUST refuse a
line of a version not deleted that lacks one. A publisher reading a catalog
or an index written without them, to publish again, writes it with them
(§5.36).

## 5.31.2 Summaries

A version's **summary** is its manifest's head: every byte of the manifest
before the blank line that comes before `[files]` (§5.18). It holds the
package's ID and all of its metadata, and so everything resolution needs,
but not its files. A summary is stored as a node of its own, at
`trees/sha256/<hash>`, named by the hash of its bytes.

A consumer MUST refuse a summary that doesn't hash to its name, or that
isn't a manifest's head in the one form (§5.18), or that names another
version than the line that gives it. A consumer that reads a manifest
whose summary it resolved from MUST refuse it unless the manifest begins
with that summary, followed by a blank line and `[files]`.

In the catalog, a package's node holds every version published. In an index,
it holds one version for each architecture.

## 5.31.3 Bucket nodes

A name falls in the **bucket** of the first two hexadecimal digits of the
SHA-256 hash of the name's bytes. A bucket's node has a line for each package
in the tree whose name falls in it: the name, a space, and the identity of
the package's node.

## 5.31.4 The top node

The top node has a line for each bucket that holds a package: the bucket's
two digits, a space, and the identity of its node. The tree is named by the
identity of its top node.

## 5.31.5 Form

Every node's lines are sorted by their bytes, with no line twice, and each
ends in a newline. A consumer MUST refuse a node whose bytes don't hash to
its name, or that isn't in this form, and a bucket's node that lists a name
from another bucket.

## 5.31.6 The provides tree

A catalog has a **provides tree**, whose top the pointer file names
(§5.32). It has the same three levels, but its leaves are capabilities
(§5.4), not packages: a capability falls in the bucket of the first two
hexadecimal digits of the SHA-256 hash of its name, and a capability's node
has a line for each version, of any package, that provides it:

```text
org.gnu.glibc 2.44-1 x86_64 2.44
org.git.kernel.dash 0.5.13.5-1 x86_64 -
```

Each line is the package's name, its version and architecture, and the
version it provides the capability at, or `-` for none. Every version the
catalog lists and hasn't deleted is in it, yanked or not, for every
capability it provides: each its `provides` table lists, and its own name
at its own version unless the table lists that too (§5.21). A version's
standing is in the catalog's package node, not here.

## 5.31.7 Why a tree

Looking up a name reads three nodes, the top, a bucket and a package,
however many versions the tree holds, and finding what provides a
capability reads three more. Publishing one package changes its
node, its bucket's and the top: every other node stays byte for byte as it
was, and a snapshot shares every node it can with `leading` and with other
snapshots.

---

# 5.32 The Pointer File

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> The one file of a repository that changes, its lines, its order, its sequence that only goes up, when it was signed, and whether its blobs are compressed.

A repository's **pointer file**, `repository`, says what its catalog, its
indexes and its channels are:

```text
sequence 1042
signed 2026-11-13T11:30:00Z
blobs zstd
catalog sha256:…
provides sha256:…
index 2026.10.0 sha256:…
index leading sha256:…
channel 2026.09 2026.09.3 ended
channel stable 2026.10
```

## 5.32.1 Lines

In this order:

1. `sequence` and a decimal number: how many times the repository has been
   published. Each publication MUST be one higher than the last.
2. `signed` and the time it was signed, in UTC, as
   `YYYY-MM-DDTHH:MM:SSZ`.
3. `blobs zstd`, if the repository's blobs are compressed (§5.12). Without
   it, they aren't.
4. `catalog` and the identity of the catalog's top node, once there is one.
5. `provides` and the identity of the top node of the catalog's provides
   tree (§5.31), once there is a catalog.
6. A line for each index, sorted by the bytes of its name: `index`, its
   name, and the identity of its top node.
7. A line for each channel, sorted by the bytes of its name: `channel`, its
   name, and the index or channel it follows, then ` ended` if it won't
   move again.

A consumer MUST refuse a pointer file that isn't in this form, that names
something twice, that has a name both an index and a channel, or whose
channels don't each reach an index (§5.30).

## 5.32.2 Writing it

The pointer file is written whole and renamed into place, after its
signature (§5.33). A reader that finds the two don't match has read between
them, and SHOULD read both again.

---

# 5.33 Repository Keys and Signatures

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> How a repository's pointer file is signed with a PSO bundle, the Repository warrant, the identity a repository signs as, what a machine requires of the result, and what a signature vouches for.

A repository is signed as PGSS Signed Objects defines (PGSS §7).
Publishing a repository MUST sign its pointer file.

## 5.33.1 The signature

`repository.pso` is a detached bundle (PGSS §7.9) over the pointer file's
bytes. Its leaf:

- has the whole-file hash form;
- is issued under the repository's **identity**, a name in the form of
  PGSS §7.7, such as `pkgs.peios.org`;
- holds the `Repository` warrant.

A publisher SHOULD publish a bundle that carries every intermediary of its
chain. A machine reading a repository for the first time has none of the
publisher's packages, and so none of the intermediaries they would install.

A publisher MUST check the signature it made before writing it.

## 5.33.2 The warrant a signer needs

`Repository` is a warrant in the sense of PGSS §7.5.

| Name | Type | Allow Equal | `flags` | Meaning |
|---|---|---|---|---|
| `Repository` | Set, empty | Set | `0x80` | The holder can sign a repository's pointer file |

The warrant carries no value. Which repository a leaf signs for is the
leaf's name, which the chain already bounds through the `Name` warrant
(PGSS §7.5).

> [!NOTE]
> The warrant separates signing a repository from signing anything else.
> A certificate issued to sign programs can't sign a pointer file unless
> its issuer gave it `Repository` as well, so a key taken from a build
> machine doesn't hand over the repository with it.

## 5.33.3 Keys

A publisher's keys and certificates are an authority's (PGSS §7.1), and
are issued and kept as that chapter says. A private key MUST NOT be kept
in the repository, or anywhere it is published.

A publisher replaces its signing certificate without any machine's
configuration changing: a machine names the repository's identity
(§5.35), not a key.

## 5.33.4 What a machine requires

A machine checks a repository's signature only if its configuration of the
repository gives an identity (§5.35), and only when it fetches through that
configuration. It verifies `repository.pso` against the pointer file (PGSS
§7.14) and MUST refuse the repository unless all of these hold:

- the result is Rooted, or is Unrooted and the configuration says
  `unrooted = true`;
- the leaf holds `Repository`;
- the leaf's name is the configured identity, byte for byte;
- if the configuration gives an anchor, the chain's top-level is the one
  it names.

A consumer MUST NOT accept a Consistent result, whatever the configuration
says.

> [!NOTE]
> Rooted is the default so that the configuration a system ships for its
> own repository can't be satisfied by a top-level an administrator
> enabled for something else. An Unrooted top-level is trusted for the
> names its `Name` warrant states, which the administrator saw when
> enabling it (PGSS §7.10), so a repository that opts in needs no pin. An
> anchor is a second line of defense against a top-level enabled with a
> wider `Name` than a repository's operator expected.

## 5.33.5 What it vouches for

When the signature is accepted, a package is taken from the repository
only if the catalog the pointer file names lists it, at the identity the
catalog gives (§5.29). Every tree node, manifest and blob is reached
through hashes from the pointer file, so for a repository used that way the
signature vouches for all of them.

Reading the same directory as a plain artifact directory, without its
configuration, checks none of this: its refs are taken as they are (§5.26).

A repository without an identity in the machine's configuration, such as a
medium's store or a local directory, is trusted because whoever configured
it supplied it. A repository served over HTTP without one is trusted for
whatever its server sends, so a machine's configuration of one SHOULD give
its identity.

---

# 5.34 Freshness and Mirrors

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> What a mirror is trusted for and what it isn't, why a sequence can't go backwards, why nothing expires, how a repository is served over HTTP, and how a consumer tries several base URLs in order.

## 5.34.1 Mirrors

A **mirror** serves a copy of a repository. It is never trusted for
authenticity: everything it serves is signed or named by its hash. It is
trusted for freshness: a mirror MAY hold back a newer publication, as a
company testing updates before it rolls them out might want to.

## 5.34.2 Going backwards

A consumer MUST keep, for each repository it fetches from, the highest
sequence (§5.32) it has seen, and MUST refuse a pointer file with a lower
one. Holding back never moves backwards; serving an older publication after
a newer one does, and only a broken or hostile mirror does that.

## 5.34.3 Nothing expires

A snapshot is valid for ever: using one from years ago is valid, if not
wise. A pointer file carries the time it was signed so that a consumer can
show it, such as `signed 2026-11-01`, and a machine on a stale mirror can be
seen to be behind. A consumer MUST NOT refuse a pointer file for its age.

## 5.34.4 Serving a repository

Every file of a repository but `repository` and `repository.pso` is named by
its hash and never changes, so a static web server can serve a repository as
it is, and a cache can keep every file but those two for ever.

## 5.34.5 Serving over HTTP

A repository served over HTTP is named by a **base URL**: an `http` or
`https` URL with a host and no query or fragment. A consumer treats a base
URL that doesn't end in `/` as if it did. Each file of the repository is at
the base URL followed by the file's path in the repository's directory
(§5.30), such as `https://pkgs.peios.org/trees/sha256/<hash>`. A server
MUST serve a file's bytes unchanged as the body of a `200` response, and
need not list directories or answer range requests.

A repository served over HTTP MUST have a pointer file. Its directories
can't be listed, so a consumer takes its packages from its catalog, at the
identities the catalog gives, whether or not an identity is configured
(§5.29),
and doesn't read its refs.

A consumer reads the pointer file and its signature from one base URL, so
that a publication between the two reads can't give it a signature over
another pointer file. It MUST check the pointer file as §5.33 orders, and
every tree node, manifest and blob against its hash before it uses it. It
MUST check a blob before the blob is named in the store, so that a blob
that fails its check is never stored. Where the pointer file says the
blobs are compressed, a blob's hash is that of what it decompresses to
(§5.12).

## 5.34.6 Base URLs tried in order

A machine can give a repository several base URLs (§5.35), each serving a
copy of the repository, such as a cache on its own network and then the
repository's own server. Each is a mirror of the repository. A consumer
reads each file from the first base URL that serves it:

- A base URL that can't be reached, or that answers with anything but the
  file, such as `404 Not Found` or a server error, is passed over for the
  next. The pointer file and its signature are passed over together.
- A file that fails its check, of its signature or its hash, MUST be
  refused, and the consumer MUST NOT read it from another base URL. A
  mirror that serves the wrong file is broken or hostile, and the error
  is reported, not hidden.
- If no base URL serves the file, the consumer fails, saying why each
  didn't. If every base URL answers `404 Not Found` for the pointer file,
  the repository has none.

## 5.34.7 Keeping what was read

A consumer MAY keep the tree nodes and manifests it reads from a repository
served over HTTP, under the paths the repository gives them, and read them
again from there. It MUST check one against its hash each time it reads
it. The pointer file and its signature are read from the repository each
time; what the consumer keeps of them is the sequence (§5.35).

---

# 5.35 Machine Repository Configuration

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> The repositories a machine fetches from, the file for each, the identity it requires, whether an unrooted chain is accepted, the channel it tracks, and what the machine records of each.

A machine fetches from the repositories its configuration names.

## 5.35.1 Files

Each repository is a file of its own, `/conf/ppk/repositories/<name>.toml`,
where `<name>` follows §5.9:

```toml
path = "/mnt/peios-repo"
identity = "pkgs.peios.org"
track = "stable"
```

A repository served over HTTP (§5.34) is given by its base URLs, tried in
order:

```toml
urls = ["http://cache.lan/peios/", "https://pkgs.peios.org/"]
identity = "pkgs.peios.org"
track = "stable"
```

| Key | Holds |
|---|---|
| `path` | Where the repository is, as a directory |
| `urls` | The base URLs the repository is served at, at least one, tried in order (§5.34) |
| `identity` | The name its pointer file is signed under (§5.33); with it, the signature is checked |
| `unrooted` | `true` to accept an Unrooted chain as well as a Rooted one; `false` by default |
| `anchor` | The object hash of the top-level its chain has to end at, in lowercase hexadecimal |
| `track` | The index or channel a request for a bare name follows |

A file MUST have exactly one of `path` and `urls`. `unrooted` and `anchor`
are given only with `identity`. A consumer MUST refuse any other key.
`/conf` merges what the system ships, under `/usr/conf`, with the
machine's own, under `/lcl/conf`: a consumer reads `/conf/ppk` and writes
what the machine adds under `/lcl/conf/ppk`.

## 5.35.2 Tracking

A request for a package by a bare name or a constraint, naming no index and
not one exact version, follows the index or channel its repository tracks,
if it tracks one. The closure's inventory records the index (§5.25), so its
meaning doesn't depend on the configuration that chose it.

## 5.35.3 State

What the machine has seen of each repository is state, not configuration: a
consumer keeps the highest sequence it has seen of each in
`/var/state/ppk/sequences/<name>`, as a decimal number and a newline
(§5.34).

---

# 5.36 Publishing

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> What publishing a repository writes, leading and what it leaves out, snapshots that never change, taking a version back by yanking or deleting it, and exporting a copy with compressed blobs.

**Publishing** writes a repository's catalog, its provides tree and
`leading` from what it holds, and signs a new pointer file one higher in
sequence. It writes each version's summary (§5.31) for the catalog to
give, and writes again, with summaries, any snapshot written without them;
a snapshot holds the same versions as before.

## 5.36.1 The catalog

The catalog lists every version the repository's refs hold, each current or
yanked as the previous catalog had it, and every version a previous catalog
recorded as deleted.

## 5.36.2 Leading

`leading` holds, for each package name and architecture, the newest current
version. A package whose dependencies or requirements `leading` can't
satisfy MUST be left out of it, and so MUST anything left needing it,
repeating until what is left can all be installed from it. A publisher MUST
say what it left out and why, and MAY refuse to publish instead.

## 5.36.3 Snapshots

A snapshot is a new index holding what an index or channel holds,
`leading` by default. A snapshot never changes: its name MUST be new. To fix
a release, publish a new snapshot and move the release's channel to it.

## 5.36.4 Yanking

Yanking a version marks it `yanked` in the catalog: new resolutions don't
choose it, but a request for exactly it still does (§5.29). Republishing
keeps the mark, and unyanking removes it. `leading` doesn't hold a yanked
version.

## 5.36.5 Deleting

Deleting a version removes its ref, its manifest, and every blob of it that
no other manifest names, and records it in the catalog as `deleted` with a
reason. A resolution it would have satisfied fails with that reason
(§5.29), so that a missing package is never mistaken for a broken mirror.

A snapshot that holds a deleted version isn't changed. To keep a release
installable, publish a new snapshot without it. Deletion reaches the
repository, not machines: a machine that holds the package keeps it until a
closure without it replaces the one that has it.

## 5.36.6 Exporting

An **export** is a copy of a repository, to serve, whose blobs are
compressed (§5.12). It holds what the repository held when it was last
published: its tree nodes, manifests and refs as they are, every blob
compressed, and a pointer file with the repository's sequence, the line
`blobs zstd`, and its signature (§5.33). The pointer file
MUST be written after everything it names, and what the repository doesn't
hold, such as a version deleted, removed from the export after it.

An export is written again after each publication. A publisher need not
compress again a blob the export holds already. A publisher MUST NOT write
an export from a publication with a lower sequence than the export has.

---

# 5.37 Extension

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> What this version leaves room for, and why every format in it refuses what it doesn't understand.

Every format of this chapter has one form (§5.9), and a consumer refuses a
file that isn't in it. A later version that adds a field, a line kind or an
entry kind is therefore a new format: a consumer of this version refuses
what it adds rather than ignoring it, since ignoring part of a hashed file
would let two consumers take one identity for different things.

This version reserves:

- **Network transports other than HTTP** (§5.34).
- **Certificate chains** for signing a pointer file (§5.33).
- **`noarch` in other architectures' resolutions** (§5.8).
- **Index requests by a package:** only a request of the closure itself
  names an index in this version (§5.25).

---

# 5.38 Conformance

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> The requirements of this chapter collected by role, producer, publisher and consumer.

## 5.38.1 Producer

- Packs only regular files, symbolic links and directories, refusing
  set-user-ID and set-group-ID files and every other kind (§5.16).
- Writes the manifest in its one form (§5.18), with paths that meet §5.13
  and metadata that meets §5.19 to §5.23.
- Derives what ELF objects need and provide (§5.22).
- Never replaces a stored version with other content (§5.11).

## 5.38.2 Publisher

- Signs every pointer file under the repository's identity, with a leaf
  that holds `Repository`, one higher in sequence (§5.32, §5.33).
- Writes tree nodes in their one form (§5.31), with each version's summary
  and the catalog's provides tree.
- Leaves out of `leading` what it can't satisfy, and says so (§5.36).
- Never changes a snapshot, and keeps yanks and tombstones (§5.36).
- Writes an export's pointer file after everything it names, and never
  from an older publication than the export has (§5.36).
- Keeps its private key out of the repository (§5.33).

## 5.38.3 Consumer

- Refuses anything not in its one form, and anything that doesn't hash to
  its name (§5.9).
- Checks a package as §5.26 orders before storing it, decompressing the
  blobs of a repository that compresses them and refusing one that
  decompresses to more than 64 GiB (§5.12).
- Gives each file and directory its security metadata before anything
  else can reach it, or says how many lack it (§5.20).
- Refuses the conflicts of §5.24, and reuses a closure that exists.
- Records what wants each package in the inventory (§5.25).
- Resolves as §5.29 specifies, deterministically, from summaries and not
  manifests for a repository served over HTTP, and checks each manifest it
  fetches against its summary (§5.31).
- Checks a configured repository's signature when it has an identity,
  requires what §5.33 lists of the result, takes its packages from its
  catalog, and refuses a lower sequence than it has seen (§5.29, §5.33,
  §5.34).
- Takes each package name from one repository (§5.30).
- Reads a repository served over HTTP from its catalog, takes the pointer
  file and its signature from one base URL, tries the next base URL when
  one doesn't serve a file, and never when a file fails its check (§5.34).

Conformance doesn't require a consumer to give security metadata on a
system that won't let it, nor to fetch over a network.

---

# Appendix 5.A Limits and Defaults

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> Every limit and default of this chapter in one place.

## 5.A.1 Limits

| Limit | Value |
|---|---|
| Package name | At most 64 characters, at least 3 labels (§5.3) |
| Capability | 2 to 128 characters (§5.4) |
| Closure, index, channel, or repository name | 1 to 64 characters (§5.9) |
| PIP signature | 3310 bytes, version byte 1 (§5.16) |
| Bucket | The first 2 hexadecimal digits of SHA-256 of the name (§5.31) |
| What a compressed blob decompresses to | At most 64 GiB (§5.12) |

## 5.A.2 Defaults

| Default | Value |
|---|---|
| Store | `/system/artifacts` |
| Closures | `closures/` in the artifact directory |
| Repository configuration | `/conf/ppk/repositories/`, written under `/lcl/conf/ppk/` |
| Repository state | `/var/state/ppk/` |
| What is kept of repositories served over HTTP | `/var/cache/ppk/` |
| Architecture | The consumer's own |
| License class | `unknown` |

---

# Appendix 5.B Enumerated Values

_Peios Specifications / PSPU / Package Format and Repository Protocol_

> Every closed set of this chapter, architectures, pre-release tokens, constraint operators, entry kinds, license classes, standings and pointer-file lines.

## 5.B.1 Architectures (§5.8)

`x86_64`, `aarch64`, `noarch`.

## 5.B.2 Pre-release tokens (§5.6)

In rank order: `dev`; `alpha`, `a`; `beta`, `b`; `pre`; `rc`. A `~` begins a
pre-release too.

## 5.B.3 Constraint operators (§5.7)

`=`, `>`, `>=`, `<`, `<=`, `!=`.

## 5.B.4 Hash algorithms (§5.9)

`sha256`.

## 5.B.5 Entry kinds (§5.16, §5.18)

`blob`, with `exec`, `descriptor` and `signature`; `symlink`; `dir`, with
`descriptor`.

## 5.B.6 Manifest tables (§5.18)

`[claims]`, `[dependencies]`, `[provides]`, `[requires]`, `[files]`.

## 5.B.7 Descriptive fields (§5.19)

`description`, `homepage`, `license`, `license_class`, `source`,
`source_license`.

## 5.B.8 License classes (§5.19)

`free`, `firmware`, `proprietary`, `unknown`.

## 5.B.9 Standings of a version in a catalog (§5.31)

Current (nothing written), `yanked`, `deleted` and a reason.

## 5.B.10 Pointer-file lines (§5.32)

`sequence`, `signed`, `blobs`, with `zstd`, `catalog`, `provides`, `index`,
`channel`, with `ended`.

## 5.B.11 Reserved closure names (§5.27)

`SYSTEM`, `INITRAMFS`.

## 5.B.12 Profile keys (§5.28)

`arch`, `include`, `packages`, `symlinks`, `dirs`, `files`,
`include_artifacts`.

## 5.B.13 Repository configuration keys (§5.35)

`path`, `urls`, `identity`, `unrooted`, `anchor`, `track`.

---

# 6.1 Scope and Roles

_Peios Specifications / PSPU / Name Resolution Interface_

> What NRI specifies — how programs on a Peios machine resolve names through one resolver, and how the network manager feeds it — and its three roles.

This chapter specifies the **Name Resolution Interface (NRI)**: the
protocol by which a program asks the machine's resolver for the records
behind a name, the protocol by which the network manager tells the
resolver what each interface contributes, and the obligations of the
resolver that stands between them.

Three roles participate.

The **resolver** is the one process on a machine that answers names. It
is a *stub* resolver — a DNS client — not a recursive or authoritative
server: it answers synthetically, from the registry, from its cache, or
by forwarding to an upstream server chosen by policy. It listens on a
Unix socket (§6.4) and on the loopback DNS port (§6.8); it never dials
a client. Peios' resolver is `resolvd`; another implementation MAY stand
in its place, and the obligations in §6.11 are what "stand in its place"
means.

A **client** is any process that asks. Most clients never see this
protocol: they call `getaddrinfo`, and the NSS shim (§6.10) speaks it
for them. Peios-native tools, the operator command and the network
manager speak it directly. A client is not trusted by the resolver
beyond what the control object grants it (§6.4).

The **network manager** is the process that knows what each interface
contributes — servers, search domains, addresses, whether it carries the
default route. It publishes that to the resolver over the manager's own
control socket (§6.9); the resolver subscribes. Nothing about the live
network is ever written to the registry to get from one to the other.

This chapter covers:

- the three doors and the one function behind them (§6.3)
- the native channel: socket, framing, access (§6.4)
- the requests and their replies (§6.5)
- what an outcome and a validation state mean (§6.6)
- the resolution model: scopes, routing, expansion, synthetic names,
  the cache (§6.7)
- the stub door (§6.8)
- the network manager channel (§6.9)
- what the hosts shim must and must not do (§6.10)
- conformance, by role (§6.11)
- a message reference and the limits (§6.A, §6.B)

What this chapter does not specify: DNSSEC validation and encrypted
transports (reserved; a resolver reports `unvalidated` until it does
them), multicast DNS, and per-caller resolution policy. Each has a
place held for it in the wire format so that adding it is additive.

---

# 6.2 Terminology

_Peios Specifications / PSPU / Name Resolution Interface_

> The terms this chapter uses — name, question, record, scope, outcome, door — and the sense in which each is used.

**Name.** A DNS domain name: a sequence of labels. Names compare
case-insensitively (RFC 4343). A **single-label** name has one label;
every other name is **multi-label**. The distinction governs search
expansion (§6.7).

**Question.** A name and a record type (and class, always `IN`). What a
client asks, and the unit the cache is keyed on.

**Record.** A resource record: name, type, TTL, and data. The protocol
is **record-level**: an answer is records, not addresses shaped for a
particular libc structure. `lookup` (§6.5) is the one convenience that
returns addresses, because that is the question every `getaddrinfo`
asks.

**Scope.** What one interface contributes to resolution: its servers,
its search domains, its addresses, whether it claims unmatched names,
whether it is exclusive. Scopes come from the network manager (§6.9).
The **fallback scope** is the registry's server list, used only when no
interface contributes servers.

**Up.** A scope is up while its interface's level is `link` or better
(§6.9). Whether it has servers is a separate matter and does not decide
it: a scope that is up with no servers still takes every routing step
it qualifies for, and a question routed to it is `unavailable` without a
query (§6.7).

**Route.** The scope a question goes to. Every question goes to exactly
one scope (§6.7).

**Outcome.** How a question ended: `found`, `notfound`, or
`unavailable` (§6.6). The three are not interchangeable and no door may
collapse two into one.

**Source.** Where an answer came from: `synthetic`, `hosts`, `cache`,
`dns`, or `local` (an answer that needed no lookup at all).

**Door.** A way in: the native socket, the stub listener, or the NSS
shim. The doors differ in who can use them and what they can carry; the
function behind them does not (§6.3).

**Synthetic answer.** An answer the resolver gives from what it knows
about the machine, before any network: loopback, the machine's own name,
static names from the registry, and their reverses.

**Control object.** The resolver's access-control object, a security
descriptor against which every native request is checked (§6.4).

**Stub door.** DNS itself, on the loopback address `127.0.0.53`, for
programs that speak DNS directly (§6.8).

---

# 6.3 Three Doors, One Function

_Peios Specifications / PSPU / Name Resolution Interface_

> The native socket, the stub listener and the NSS shim — what each carries, who uses it, and the rule that every one of them runs the same resolution.

A resolver MUST offer three doors [*nri-doors.offers-three-doors] and MUST answer every question
through the same resolution function (§6.7) whichever door it arrived
by. [*nri-doors.one-resolution-function-behind-every-door]

| Door | Callers | Carries |
|---|---|---|
| Native socket (§6.4) | Peios tools, the network manager, the NSS shim | Records with TTL, source, validation state; the caller's identity |
| Stub listener (§6.8) | Anything that speaks DNS itself — Go's `netgo`, musl, hickory | DNS; no caller identity |
| NSS shim (§6.10) | Everything via glibc `getaddrinfo` and `gethostbyname` | `struct hostent` / `gaih_addrtuple`, rendered from the native door |

The rule that matters is the second sentence. A bare `printer` arriving
at the stub door is expanded with the same search domains, routed to
the same scope and answered from the same cache as `printer` arriving on
the native socket. A static name from the registry is answered at every
door, so a program that never touches libc sees the same `printer` as
one that does. [*nri-doors.static-names-answered-at-every-door] There is no configuration a door reads that another does
not, and no file behind any of them.

This is why there is no `/etc/hosts`: the stub answers static names
synthetically, so a direct-DNS resolver gets them without a file. And it
is why `/etc/resolv.conf` is a constant — `nameserver 127.0.0.53`,
`options edns0` — shipped by the resolver's package as
`/usr/etc/resolv.conf`, the bottom layer of the `/etc` merge, and never
regenerated: it is a pointer to the answerer, not a copy of the answer. [*nri-doors.resolv-conf-is-constant]
A search list in it would be a second expansion policy the resolver
could not see; there is none.

A resolver MUST NOT offer a fourth policy path — an in-process fallback
in the shim, a `files` source, a direct-DNS retry — behind any door. [*nri-doors.no-fourth-policy-path]
Before the resolver is running, the shim answers `localhost` itself and
nothing else (§6.10).

---

# 6.4 The Native Channel

_Peios Specifications / PSPU / Name Resolution Interface_

> The Unix socket, the observability query framing it reuses, one request per connection, and the control object every request is checked against.

The native door is a `SOCK_STREAM` Unix socket at a configured path —
`/run/resolvd/resolv.sock` on Peios. [*nri-native.stream-socket-at-configured-path] Every process MAY connect; what a
connection may ask is decided by the control object, not by reaching the
socket. [*nri-native.every-process-may-connect]

## 6.4.1 Framing

Messages in both directions are length-prefixed MessagePack values in
the observability query framing (§3.15): [*nri-native.length-prefixed-messagepack-framing]

| Offset | Size | Field | Value |
|---|---|---|---|
| 0 | 4 | `length` | Length of the payload in bytes, little-endian [*nri-native.length-is-little-endian] |
| 4 | `length` | `payload` | A MessagePack map |

A request is a map with a required `query` string naming the request
(§6.5). [*nri-native.request-carries-query-string] A reply is a map with a required `ok` boolean; when `ok` is
`false` it carries `error`, a string for a person, and nothing else. [*nri-native.error-reply-carries-only-error]
When `ok` is `true` it carries `kind` — `answer`, `addresses`, `status`
— or nothing, for a request with no body to return. [*nri-native.success-reply-carries-kind]

A receiver MUST ignore keys it does not know [*nri-native.unknown-keys-ignored] and MUST reject a message
that repeats a key. [*nri-native.duplicate-keys-rejected] A resolver MUST refuse a request whose `length`
exceeds the message ceiling (§6.B) without reading the payload, [*nri-native.oversized-request-refused-unread] and
MUST reply with an error rather than closing silently. [*nri-native.oversized-request-answered-with-error]

## 6.4.2 One request per connection

A connection carries exactly one request and one reply. [*nri-native.one-request-per-connection] The client
sends, the resolver answers, and either side closes. There is no
pipelining and no conversation identifier: the shim that generates most
of the traffic is loaded into processes that fork, and a connection
held across a fork is how a resolver hands back somebody else's answer.
Connecting to a Unix socket is cheap; the cache that would make it
cheaper lives in the resolver, where every caller shares it.

A resolver MUST bound how long a connection may take to deliver its
request, and MUST drop one that exceeds the bound. [*nri-native.request-delivery-bounded] A client with a
half-sent request holds a few bytes of buffer, never the resolver.

## 6.4.3 The control object

Every request names a right (§6.5). Before acting, a resolver MUST
perform an access check of that right against its **control object**
using the token of the connecting peer — the peer's real token, as the
kernel would judge it, never a numeric credential read from the socket. [*nri-native.access-check-with-peer-token]

The control object's descriptor is `Machine\System\Network\Dns
ControlSecurity` when that value holds a valid self-relative descriptor,
else the resolver's compiled default. [*nri-native.control-descriptor-from-registry-else-default] The default MUST grant
`RESOLVER_QUERY` to Everyone and `RESOLVER_ALL_ACCESS` to SYSTEM and
Administrators. [*nri-native.default-descriptor-grants]

| Right | Value | Governs |
|---|---|---|
| `RESOLVER_QUERY` | `0x0001` | `resolve`, `lookup`, `reverse`, `status` [*nri-native.resolver-query-right] |
| `RESOLVER_CONTROL` | `0x0002` | `flush` [*nri-native.resolver-control-right] |
| `RESOLVER_ALL_ACCESS` | `0x000F0003` | Both, with the standard rights [*nri-native.resolver-all-access] |

A denied request is answered with an error reply, not a closed
connection. [*nri-native.denied-request-answered-with-error]

The peer's identity is what identity-aware resolution policy will key
on. This version defines no such policy; a resolver MUST NOT invent one. [*nri-native.no-identity-aware-policy]

---

# 6.5 Requests

_Peios Specifications / PSPU / Name Resolution Interface_

> The five requests on the native channel — resolve, lookup, reverse, status, flush — their fields, their replies, and the right each needs.

Each request is a map whose `query` key names it. Field types are the
MessagePack types named; an address is a string in its usual textual
form; a name is a string in presentation form, with or without a
trailing dot. [*nri-requests.field-encodings]

## 6.5.1 `resolve` — `RESOLVER_QUERY`

One question.

| Key | Type | Meaning |
|---|---|---|
| `name` | string | The name |
| `type` | uint | The record type number (`1` A, `28` AAAA, `12` PTR, …) [*nri-requests.resolve-type-is-record-type-number] |
| `no_cache` | bool | Bypass the cache for this question; default `false` [*nri-requests.resolve-no-cache-bypasses-cache] |

Reply `kind: answer`:

| Key | Type | Meaning |
|---|---|---|
| `outcome` | string | `found`, `notfound`, `unavailable` (§6.6) |
| `records` | array of map | Each: `name` (string), `type` (uint), `ttl` (uint), `data` (bin, uncompressed wire rdata), `text` (string, presentation form) [*nri-requests.answer-records-shape] |
| `source` | string | `synthetic`, `hosts`, `cache`, `dns`, `local` [*nri-requests.answer-source-values] |
| `server` | string or nil | The upstream that answered, for `dns`; for `cache`, the upstream whose answer was cached; nil otherwise [*nri-requests.answer-server-for-dns] |
| `interface` | string or nil | The interface whose scope answered [*nri-requests.answer-interface] |
| `validation` | string | §6.6 |
| `rcode` | uint | The DNS response code, for `dns`; for `cache`, the code of the response that was cached; `0` otherwise [*nri-requests.answer-rcode-for-dns] |

`records` is the answer section only. [*nri-requests.records-are-answer-section-only] When the name was expanded
(§6.7) the records are at the expanded name, and `name` on each record
says so. [*nri-requests.expanded-records-carry-expanded-name]

## 6.5.2 `lookup` — `RESOLVER_QUERY`

The addresses of a name: what `getaddrinfo` asks. The resolver asks for
`A` and/or `AAAA`, applies search expansion, follows the CNAME chain and
returns what it ends at. [*nri-requests.lookup-follows-cname-chain]

| Key | Type | Meaning |
|---|---|---|
| `name` | string | The name |
| `family` | string | `any` (default), `inet`, `inet6` [*nri-requests.lookup-family-default-any] |

Reply `kind: addresses`:

| Key | Type | Meaning |
|---|---|---|
| `outcome` | string | `found` when at least one family answered; `unavailable` when none did and one could not; else `notfound` [*nri-requests.lookup-outcome-rule] |
| `canonical` | string | The name the addresses belong to after expansion and CNAME chasing; the name asked, when neither applied [*nri-requests.lookup-canonical-name] |
| `addresses` | array of map | Each: `address` (string), `ttl` (uint) [*nri-requests.lookup-addresses-shape] |
| `source` | string | As for `resolve` |
| `validation` | string | §6.6 |

## 6.5.3 `reverse` — `RESOLVER_QUERY`

| Key | Type | Meaning |
|---|---|---|
| `address` | string | An IPv4 or IPv6 address |

Equivalent to `resolve` of the address's reverse-mapping name with type
`PTR`; the reply is `kind: answer`. [*nri-requests.reverse-is-ptr-resolve]

## 6.5.4 `status` — `RESOLVER_QUERY`

No fields. Reply `kind: status`:

| Key | Type | Meaning |
|---|---|---|
| `hostname` | string | The machine's name as the resolver knows it [*nri-requests.status-hostname] |
| `netd` | bool | Whether the network manager channel is connected [*nri-requests.status-netd-connected] |
| `scopes` | array of map | Each: `interface`, `servers` (array of string), `domains` (array of string), `default_route` (bool), `exclusive` (bool), `metric` (uint), `subnets` (array of string: the interface's addresses, each as `address/prefix`, which name the subnets routing step 3 matches against), `demoted` (array of string) [*nri-requests.status-scopes] |
| `fallback_servers` | array of string | The registry's server list [*nri-requests.status-fallback-servers] |
| `cache_entries` | uint | [*nri-requests.status-cache-entries] |
| `counters` | map | `queries`, `synthetic`, `cache_hits`, `upstream_sent`, `upstream_answered`, `upstream_failed`, `refused`, each uint [*nri-requests.status-counters] |

## 6.5.5 `flush` — `RESOLVER_CONTROL`

No fields. Drops every cached answer. Reply `ok: true` with no `kind`. [*nri-requests.flush-drops-every-cached-answer]

## 6.5.6 Unknown requests

A resolver MUST answer a `query` it does not know with an error reply. [*nri-requests.unknown-query-answered-with-error]
A client MUST treat an error reply as "not answered", never as
`notfound`. [*nri-requests.client-treats-error-as-not-answered]

---

# 6.6 Outcomes and Validation

_Peios Specifications / PSPU / Name Resolution Interface_

> The three outcomes and why no door may merge two of them; the validation state every answer carries from the first version.

## 6.6.1 Outcomes

| Outcome | Meaning | Cached |
|---|---|---|
| `found` | An answer. Includes a name that exists with no records of the asked type — an empty `records` with `found` is NODATA, and is not absence. [*nri-outcomes.nodata-is-found] | Yes, by TTL |
| `notfound` | The name does not exist, authoritatively (NXDOMAIN, or a single label with no domain to apply, or `.local`). [*nri-outcomes.notfound-is-authoritative-absence] | Yes, briefly (§6.7) |
| `unavailable` | Nothing that could have answered did: every server timed out, refused, or failed; or no server exists to ask. | Never |

The third row is the one that carries the weight. A resolver MUST NOT
report `unavailable` as `notfound`, at any door, [*nri-outcomes.unavailable-never-reported-as-notfound] and MUST NOT cache it: [*nri-outcomes.unavailable-never-cached]
a source that could have answered and did not is not the same as a name
that does not exist, and recording it as one would let an outage be
remembered as a fact. Each door renders the distinction in its own
terms (§6.8, §6.10).

A resolver MUST answer `notfound` locally, without a query, for a
single-label name with no applicable search domain and for any name
under `.local` (§6.7).

## 6.6.2 Validation

Every `answer` and `addresses` reply carries `validation`: [*nri-outcomes.every-answer-carries-validation]

| Value | Meaning |
|---|---|
| `unvalidated` | The resolver did not attempt DNSSEC validation. |
| `secure` | Validated, with a chain of trust to a configured anchor. |
| `insecure` | Validated as provably unsigned. |
| `bogus` | Validation failed. |

This version of the interface defines no validating resolver, and a
resolver that does not validate MUST report `unvalidated` for every
answer from the network. [*nri-outcomes.unvalidated-until-validating] The field exists now so that a client is
written against it from the start: when validation arrives, the change
is a value, not a field, and a client that wanted only `secure` answers
needs nothing new.

A resolver MUST NOT set the `AD` bit on a stub-door reply (§6.8) unless
its own validation produced `secure`. [*nri-outcomes.ad-bit-only-when-secure] An upstream's `AD` is an assertion
by a plaintext peer and MUST NOT be forwarded as one. [*nri-outcomes.upstream-ad-not-forwarded]

---

# 6.7 The Resolution Model

_Peios Specifications / PSPU / Name Resolution Interface_

> Scopes, the routing order that sends every question to exactly one of them, search expansion without leaks, synthetic answers, the scoped cache and server health.

This is the function behind every door.

## 6.7.1 Scopes

Every interface with a link contributes a **scope**: servers in the
order to try them, search domains, the interface's addresses, whether it
claims unmatched names (`default_route`), whether it is exclusive, and
its metric. Scopes arrive from the network manager (§6.9); the resolver
holds them and nothing else about the network. The **fallback scope** is
`Machine\System\Network\Dns FallbackServers` and `ExtraSearchDomains`. [*nri-resolution.fallback-scope-from-registry]

## 6.7.2 Routing

A question goes to **exactly one** scope. A resolver MUST NOT send a
question to several scopes' servers and take the first answer — parallel
fan-out is the mechanism of the classic VPN name leak, and it also lets
a hostile network win a race for a name it has no claim to. [*nri-resolution.exactly-one-scope-no-fan-out]

The order:

1. **An exclusive scope**, if any interface at `addressed` or better is
   exclusive: it takes every question. [*nri-resolution.route-exclusive-takes-every-question] Several exclusive scopes: the
   lowest metric. [*nri-resolution.route-several-exclusive-lowest-metric] While an exclusive interface is up no other
   interface's servers are consulted for anything. [*nri-resolution.exclusive-excludes-every-other-server]
2. **The longest matching search domain.** The scope with the longest
   domain the name ends with; ties by metric. [*nri-resolution.route-longest-search-domain]
3. **The subnet**, for a reverse-mapping name: the scope whose interface
   has an address in the same subnet as the address named. [*nri-resolution.route-reverse-by-subnet]
4. **The default-route claimant** with the lowest metric. [*nri-resolution.route-default-route-claimant]
5. **The lowest-metric scope with servers**, when no interface claims
   the default route. [*nri-resolution.route-lowest-metric-with-servers]
6. **The fallback scope**, only when no interface contributes servers. [*nri-resolution.route-fallback-only-without-interface-servers]

When none of these yields a scope with servers, the question is
`unavailable` without a query. [*nri-resolution.no-scope-is-unavailable-without-query]

This is DNS routing only. Which interface a *packet* leaves by is the
network manager's and the firewall's.

## 6.7.3 Search expansion

A **single-label** name is never sent upstream as it is. [*nri-resolution.single-label-never-sent-bare] It is expanded
with the applicable search domains, in order, and each candidate is
asked in turn until one is not `notfound`. [*nri-resolution.candidates-asked-in-turn] The applicable domains are
the exclusive scope's when one is up; otherwise every up scope's, in
metric order, followed by the fallback scope's. [*nri-resolution.applicable-search-domains] With no applicable
domain the name is `notfound` without a query. [*nri-resolution.no-domain-is-notfound-without-query]

A **multi-label** name is never expanded. There is no `ndots` setting:
the rule is fixed at one, because every other value is a leak of local
names to the public tree or of public names to the local one. [*nri-resolution.multi-label-never-expanded]

An answer at an expanded name reports the expanded name (`resolved`
records on the native channel; a `CNAME` from the bare name at the
stub door, §6.8).

## 6.7.4 Synthetic answers

Before any network, a resolver MUST answer: [*nri-resolution.synthetic-before-network]

- `localhost` and any name under it: `127.0.0.1` and `::1`; [*nri-resolution.synthetic-localhost]
- the machine's hostname: every unicast address of every interface at
  `addressed` or better, or loopback when there are none; [*nri-resolution.synthetic-hostname]
- every name under `Machine\System\Network\Dns\Hosts`, exactly and
  case-insensitively: its addresses. [*nri-resolution.synthetic-static-names] A static name wins over DNS; [*nri-resolution.static-name-wins-over-dns]
- the reverse of loopback (`localhost`), of a static name's address
  (the name whose ASCII-lowercased presentation form sorts first in byte
  order when several names share it), and of the machine's own addresses
  (the hostname); [*nri-resolution.synthetic-reverses]
- any name under `.local`: `notfound`. [*nri-resolution.local-is-notfound] mDNS is a separate transport
  (RFC 6762) and a `.local` question MUST NOT reach a DNS server. [*nri-resolution.local-never-reaches-dns]
  LLMNR MUST NOT be spoken. [*nri-resolution.no-llmnr]

A synthetic answer has `source` `synthetic` (or `hosts`) and TTL `0`. [*nri-resolution.synthetic-source-and-ttl-zero]

## 6.7.5 The cache

The cache is keyed by `(name, type, scope)`, the name folded to lower
case. [*nri-resolution.cache-keyed-by-name-type-scope] The scope is part of the key because the same name may have
different answers on different interfaces (split horizon), and because
when an interface's servers change or the interface goes away, every
answer learned through it MUST be discarded: what a VPN's servers said
dies with the VPN. [*nri-resolution.cache-discarded-with-scope]

Positive answers live for their least TTL, capped (§6.B). [*nri-resolution.positive-ttl-least-capped] Negative
answers — `notfound`, and `found` with no records — live for the lesser
of the authority section's SOA record TTL and its MINIMUM field (RFC 2308
§5), capped lower. [*nri-resolution.negative-ttl-soa-minimum-capped] `unavailable`
is never cached. A hit reports TTLs reduced by the time spent in cache. [*nri-resolution.cache-hit-ttl-reduced]

## 6.7.6 Upstream behavior

A resolver MUST send each query from a fresh source port, [*nri-resolution.fresh-source-port] MUST use a
random message identifier, [*nri-resolution.random-message-id] and MUST randomise the case of the question
name and require the reply to echo it exactly (0x20 encoding). Both the
identifier and the case bits MUST come from a cryptographically secure
generator: a predictable one hands a spoofer back the entropy these
measures exist to add. [*nri-resolution.case-randomised-and-echo-required] A reply
whose identifier, question or case pattern does not match MUST be
ignored, not treated as a failure. [*nri-resolution.mismatched-reply-ignored]

Queries are UDP with EDNS0 advertising the buffer size in §6.B; [*nri-resolution.udp-with-edns0] a
truncated reply is retried over TCP to the same server. [*nri-resolution.truncated-retried-over-tcp-same-server] A server that
does not answer within the per-server timeout, or answers `SERVFAIL`,
`REFUSED` or a format error, is **demoted** — tried after its peers —
for the demotion period; [*nri-resolution.failing-server-demoted] the question moves to the next server. [*nri-resolution.question-moves-to-next-server] After
the attempt limit the question is `unavailable`. [*nri-resolution.attempt-limit-unavailable] Servers within a scope
are tried in the scope's order, healthy ones first; never in parallel. [*nri-resolution.servers-in-order-healthy-first]

---

# 6.8 The Stub Door

_Peios Specifications / PSPU / Name Resolution Interface_

> DNS on 127.0.0.53 — for programs that resolve without libc — and how outcomes, expansion and validation are rendered in DNS's terms.

A resolver MUST listen for DNS over UDP and TCP on `127.0.0.53` port 53 [*nri-stub.dns-over-udp-and-tcp]
and MUST NOT listen on any other address: not `::1`, which a local DNS
server may legitimately want, and never a routable one. [*nri-stub.listens-on-127-0-0-53-only] It MUST ignore
a datagram or connection whose source is not a loopback address. [*nri-stub.non-loopback-source-ignored]

The stub door exists for software that does not go through libc — a Go
binary built with `netgo`, a musl program, a Rust resolver library — and
it is non-optional: the constant `/etc/resolv.conf` points at it. It is
also anonymous: DNS carries no caller identity, and the door is not
governed by the control object. Everything on the machine may ask. [*nri-stub.anonymous-not-governed-by-control-object]

## 6.8.1 Rendering

A query is answered by the same function as every other door (§6.7),
including search expansion of a single-label question. The reply is
rendered as:

| Outcome | Reply |
|---|---|
| `found` | `NOERROR`, the records in the answer section [*nri-stub.found-is-noerror] |
| `notfound` | `NXDOMAIN` [*nri-stub.notfound-is-nxdomain] |
| `unavailable` | `SERVFAIL` [*nri-stub.unavailable-is-servfail] |

When the answer is at an expanded name, the reply's answer section
MUST begin with a `CNAME` from the question name to the expanded name,
so that a client checking names sees a well-formed chain. [*nri-stub.expanded-answer-begins-with-cname] `RA` is set; [*nri-stub.ra-set]
`AA` is not; [*nri-stub.aa-clear] `AD` is not, per §6.6.

A query with an opcode other than `QUERY` is answered `NOTIMP`; [*nri-stub.non-query-opcode-is-notimp] one
with other than exactly one question, or that cannot be decoded, is
answered `FORMERR` when there is enough of a header to echo. [*nri-stub.bad-question-count-or-undecodable-is-formerr] A reply
larger than the client's advertised buffer (or 512 bytes without EDNS)
is truncated with `TC` set; [*nri-stub.oversized-udp-reply-truncated] TCP carries the whole answer. [*nri-stub.tcp-carries-whole-answer]

## 6.8.2 Binding the port

Port 53 is below the privileged floor. On Peios the resolver's service
SID holds a port reservation for `tcp,udp:53`, shipped as a registry
seed by the resolver's package; [*nri-stub.port-reservation-seed] the resolver needs no privilege to bind
it. A resolver MUST NOT require `SeTcbPrivilege` or any capability for
its listeners. [*nri-stub.binds-without-privilege]

---

# 6.9 The Network Manager Channel

_Peios Specifications / PSPU / Name Resolution Interface_

> How scopes reach the resolver — a subscribe request on the manager's control socket that streams a whole snapshot on every change — and why the registry is not the path.

The live facts of the network — which interface has which servers,
which carries the default route — never reach the resolver through the
registry, whatever the manager also records there. [*nri-manager.live-facts-never-in-registry] They
go from the network manager to the resolver directly, over the
manager's own control socket, and they are gone when the manager is.

## 6.9.1 `subscribe`

The resolver connects to the manager's control socket
(`/run/netd/control.sock` on Peios; framing as §6.4) and sends
`{"query": "subscribe"}`, [*nri-manager.subscribe-request] which requires the manager's query right
(`NETWORK_QUERY`). [*nri-manager.subscribe-requires-network-query] The manager replies at once with a **snapshot** and
then keeps the connection open, sending a fresh snapshot every time the
picture changes, until either side closes. [*nri-manager.snapshot-at-once-then-on-every-change] This is the one request on
that socket that holds a connection. [*nri-manager.only-subscribe-holds-a-connection]

A snapshot is `ok: true`, `kind: snapshot`:

| Key | Type | Meaning |
|---|---|---|
| `hostname` | string | The machine's name as set by the manager; empty when unset [*nri-manager.snapshot-hostname] |
| `scopes` | array of map | One per managed interface with a link, in metric order [*nri-manager.snapshot-scopes-in-metric-order] |

Each scope:

| Key | Type | Meaning |
|---|---|---|
| `ifid` | string | The interface's stable identity; the cache scope key [*nri-manager.scope-ifid-is-cache-key] |
| `name` | string | The interface name |
| `servers` | array of string | The profile's static servers, then the lease's when the profile takes them [*nri-manager.scope-servers-order] |
| `domains` | array of string | The profile's search domains, then the lease's search list or domain [*nri-manager.scope-domains-order] |
| `addresses` | array of string | Every unicast address, CIDR form [*nri-manager.scope-addresses-cidr] |
| `default_route` | bool | The profile's `Dns.Default`; unset, whether the interface carries a default route [*nri-manager.scope-default-route] |
| `exclusive` | bool | The profile's `Dns.Exclusive` [*nri-manager.scope-exclusive] |
| `metric` | uint | The route metric [*nri-manager.scope-metric] |
| `level` | string | `link`, `addressed`, `routed` [*nri-manager.scope-level] |

A snapshot is the **whole** picture, not a delta. [*nri-manager.snapshot-is-whole-picture] It is a few hundred
bytes, and a whole picture cannot be misapplied out of order. The
resolver MUST replace its scopes with each snapshot; [*nri-manager.resolver-replaces-scopes] a scope whose
servers differ from before loses its cached answers (§6.7).

## 6.9.2 Failure and reconnection

The manager MAY drop a subscriber it cannot write to. [*nri-manager.manager-drops-unwritable-subscriber] The resolver MUST
reconnect with backoff whenever the connection is lost or the manager
is absent, [*nri-manager.reconnect-with-backoff] and MUST keep answering meanwhile: synthetic names need no
scope, and the scopes it holds remain valid until replaced. [*nri-manager.keeps-answering-while-disconnected] A resolver
MUST NOT treat the manager's absence as a reason to refuse questions.

The manager merges the profile's static DNS keys with the lease itself;
the resolver reads `Profiles\` for nothing. [*nri-manager.resolver-never-reads-profiles] The registry keys the
resolver reads are exactly `Machine\System\Network\Dns` and its
subkeys; [*nri-manager.resolver-reads-only-dns-key] it MAY watch the parent `Machine\System\Network` so that the
key's creation is seen. When the manager reports no hostname the
resolver uses the kernel's. [*nri-manager.empty-hostname-uses-kernel]

---

# 6.10 The Hosts Shim

_Peios Specifications / PSPU / Name Resolution Interface_

> What libnss_peios_net.so.2 must do — one request per libc call, localhost on its own, no files and no DNS — and how outcomes map to NSS statuses.

The shim is the NSS module glibc's `hosts` database reaches, and on
Peios the only one it can reach: glibc is patched so that `hosts`, like
the identity databases, is not configurable and names `peios_net`
whatever `nsswitch.conf` says. [*nri-shim.hosts-database-fixed-to-peios-net] There is no `files` source behind it and
no `/etc/hosts` for one to read.

## 6.10.1 Obligations

A shim MUST:

1. Forward every question to the native channel (§6.4) as `lookup` or
   `reverse`, one connection per libc call, and render the reply. [*nri-shim.one-connection-per-call] It
   MUST NOT hold a connection across calls. [*nri-shim.no-connection-across-calls]
2. Answer `localhost`, and any name under it, and the reverse of a
   loopback address, itself — with no socket. [*nri-shim.answers-localhost-itself] It is the one name a
   machine can never be without, and the only one the shim knows.
3. Answer `NSS_STATUS_UNAVAIL` for everything else when the resolver
   cannot be reached. [*nri-shim.unreachable-resolver-is-unavail] There is nothing behind it.
4. Report an over-full caller buffer as `NSS_STATUS_TRYAGAIN`, with
   `*errnop = ERANGE` and `*h_errnop = NETDB_INTERNAL` (`-1`), so glibc
   retries with a larger one. [*nri-shim.over-full-buffer-is-tryagain-erange]

A shim MUST NOT read `/etc/hosts`, `/etc/resolv.conf` or any file; [*nri-shim.reads-no-file]
MUST NOT speak DNS itself; [*nri-shim.speaks-no-dns] and MUST NOT cache. [*nri-shim.does-not-cache] Each would be a second
policy path the resolver cannot see.

The complete buffer-exhaustion triple is required by the
[glibc NSS interface](https://sourceware.org/glibc/manual/2.42/html_node/NSS-Modules-Interface.html):
`NETDB_INTERNAL` tells the caller to examine `errnop`, including its
`ERANGE` buffer-size indication.

## 6.10.2 Status mapping

| Resolver outcome | NSS status | `h_errno` |
|---|---|---|
| `found`, with addresses of the asked family | `SUCCESS` | — [*nri-shim.found-is-success] |
| `found`, none of that family | `NOTFOUND` | `NO_DATA` [*nri-shim.found-without-family-is-no-data] |
| `notfound` | `NOTFOUND` | `HOST_NOT_FOUND` [*nri-shim.notfound-is-host-not-found] |
| `unavailable` | `TRYAGAIN` (`EAGAIN`) | `TRY_AGAIN` [*nri-shim.unavailable-is-tryagain] |
| Resolver unreachable, or an error reply | `UNAVAIL` | `NO_RECOVERY` [*nri-shim.unreachable-or-error-is-no-recovery] |

The `unavailable` row is the one that matters: a shim MUST NOT render it
as `NOTFOUND`. A caller that retries gets its answer when the network
comes back; a caller told "no such host" may remember that.

> [!NOTE]
> glibc's `getaddrinfo` reports a module's `UNAVAIL` to its caller as
> `EAI_NONAME`, the same code as a name that does not exist, so through
> that interface an unreachable resolver still looks like an absent
> name. That mapping is glibc's; the shim reports `UNAVAIL` faithfully,
> and the native channel and `resolv` keep the distinction.

`h_name` is the reply's `canonical` name. [*nri-shim.h-name-is-canonical] TTLs are reported through
`ttlp` where glibc offers it, as the least TTL among the addresses. [*nri-shim.ttl-is-least-address-ttl]

## 6.10.3 Entry points

`_nss_peios_net_gethostbyname4_r`, `gethostbyname3_r`,
`gethostbyname2_r`, `gethostbyname_r`, `gethostbyaddr2_r`,
`gethostbyaddr_r`. [*nri-shim.entry-points] The module's SONAME is `libnss_peios_net.so.2` and
it is installed in glibc's configured library directory; [*nri-shim.soname-and-location] it links
against libc and the wire codec and nothing else, since it is loaded
into every process that resolves a host. [*nri-shim.links-libc-and-codec-only]

---

# 6.11 Conformance

_Peios Specifications / PSPU / Name Resolution Interface_

> Every requirement of this chapter collected by role — resolver, client, network manager, shim.

A conforming implementation MUST satisfy every requirement in this
chapter. This section collects them by role.

## 6.11.1 Resolver obligations

### 6.11.1.1 Doors

1. Offer the native socket, the stub listener and answer the shim, and
   run one resolution function behind all three (§6.3).
2. Offer no other policy path: no files, no in-shim DNS, no fallback
   (§6.3).

### 6.11.1.2 Native channel

3. Frame as §6.4; refuse an oversized request without reading it, with
   an error reply (§6.4).
4. Ignore unknown keys; reject duplicate keys (§6.4).
5. One request per connection; bound the time a request may take to
   arrive (§6.4).
6. Access-check every request against the control object with the
   peer's real token; default Everyone `RESOLVER_QUERY`, SYSTEM and
   Administrators all (§6.4).
7. Answer unknown requests and denied requests with error replies
   (§6.4, §6.5).

### 6.11.1.3 Outcomes

8. Never report `unavailable` as `notfound`; never cache `unavailable`
   (§6.6).
9. Report `unvalidated` until validating; never forward an upstream's
   `AD` (§6.6).

### 6.11.1.4 Resolution

10. Route every question to exactly one scope, in the order of §6.7;
    never fan out.
11. Honor an exclusive scope absolutely while it is up (§6.7).
12. Expand single labels with applicable domains only; never send one
    bare; never expand a multi-label name; no `ndots` (§6.7).
13. Answer the synthetic names of §6.7 before any network; never
    forward `.local`; never speak LLMNR.
14. Key the cache by scope; flush a scope whose servers change or that
    goes away; cap TTLs as §6.B (§6.7).
15. Fresh source port, random identifier, 0x20 case with exact echo;
    ignore mismatched replies (§6.7).
16. EDNS0 with the §6.B buffer; TCP on truncation; demote failing
    servers; bounded attempts (§6.7).

### 6.11.1.5 Stub door

17. Listen on `127.0.0.53` only, UDP and TCP; ignore non-loopback
    sources (§6.8).
18. Render outcomes as §6.8; CNAME from a bare question to its expanded
    name; `NOTIMP` and `FORMERR` as §6.8; truncate over the buffer.
19. Bind without privilege (§6.8).

### 6.11.1.6 Network manager channel

20. Subscribe; replace scopes on every snapshot; reconnect with backoff;
    keep answering while disconnected (§6.9).
21. Read only `Machine\System\Network\Dns` from the registry (§6.9).

## 6.11.2 Network manager obligations

22. Answer `subscribe` with a snapshot and stream one on every change on
    the same connection (§6.9).
23. Send whole snapshots, never deltas; merge profile and lease facts
    itself (§6.9).

## 6.11.3 Client obligations

24. Treat an error reply as "not answered", never as `notfound` (§6.5).
25. Be written against `validation` (§6.6).

## 6.11.4 Shim obligations

26. One connection per libc call; answer `localhost` alone; `UNAVAIL`
    when the resolver is unreachable; `ERANGE` retry (§6.10).
27. No files, no DNS, no cache (§6.10).
28. Map outcomes as §6.10; never render `unavailable` as `NOTFOUND`.

---

# Appendix 6.A Message Reference

_Peios Specifications / PSPU / Name Resolution Interface_

> Every NRI request and reply by name, the rights and values, and the constants.

## 6.A.1 Native channel requests

| `query` | Right | Reply `kind` | Defined in |
|---|---|---|---|
| `resolve` | `RESOLVER_QUERY` | `answer` | §6.5 |
| `lookup` | `RESOLVER_QUERY` | `addresses` | §6.5 |
| `reverse` | `RESOLVER_QUERY` | `answer` | §6.5 |
| `status` | `RESOLVER_QUERY` | `status` | §6.5 |
| `flush` | `RESOLVER_CONTROL` | (none) | §6.5 |

## 6.A.2 Network manager channel

| `query` | Right | Reply `kind` | Defined in |
|---|---|---|---|
| `subscribe` | `NETWORK_QUERY` | `snapshot`, streamed | §6.9 |

## 6.A.3 Rights

| Constant | Value | Defined in |
|---|---|---|
| `RESOLVER_QUERY` | `0x00000001` | §6.4 |
| `RESOLVER_CONTROL` | `0x00000002` | §6.4 |
| `RESOLVER_ALL_ACCESS` | `0x000F0003` | §6.4 |

## 6.A.4 Enumerations

| Field | Values | Defined in |
|---|---|---|
| `outcome` | `found`, `notfound`, `unavailable` | §6.6 |
| `validation` | `unvalidated`, `secure`, `insecure`, `bogus` | §6.6 |
| `source` | `local`, `synthetic`, `hosts`, `cache`, `dns` | §6.2 |
| `family` | `any`, `inet`, `inet6` | §6.5 |
| `level` | `link`, `addressed`, `routed`; never `absent` in a snapshot, since an absent interface contributes no scope | §6.9 |

## 6.A.5 Paths and addresses (Peios)

| Item | Value |
|---|---|
| Native socket | `/run/resolvd/resolv.sock` |
| Stub listener | `127.0.0.53:53`, UDP and TCP |
| Network manager socket | `/run/netd/control.sock` |
| Registry key | `Machine\System\Network\Dns` |
| Shim | `libnss_peios_net.so.2` |
| Compat file | `/usr/etc/resolv.conf`, constant |

---

# Appendix 6.B Limits

_Peios Specifications / PSPU / Name Resolution Interface_

> The mainline values for every bound in this chapter.

| Bound | Mainline | Defined in |
|---|---|---|
| Message ceiling, native channel | 65 536 bytes [*nri-limits.native-message-ceiling] | §6.4 |
| Request delivery bound, native channel | 5 s [*nri-limits.native-request-delivery-bound] | §6.4 |
| Per-server timeout | 2 s [*nri-limits.per-server-timeout] | §6.7 |
| Attempts per question | 3 [*nri-limits.attempts-per-question] | §6.7 |
| Demotion period | 30 s [*nri-limits.demotion-period] | §6.7 |
| Positive TTL cap | 86 400 s [*nri-limits.positive-ttl-cap] | §6.7 |
| Negative TTL cap | 300 s [*nri-limits.negative-ttl-cap] | §6.7 |
| EDNS0 buffer advertised | 1 232 bytes [*nri-limits.edns0-buffer] | §6.7 |
| Upstream transactions in flight (synthetic and cached answers are never refused) | 4 096 [*nri-limits.upstream-in-flight] | §6.7 |
| Native connections delivering a request or awaiting resolution | 256 [*nri-limits.native-pending-connections] | §6.4 |
| Stub TCP clients delivering a query or awaiting resolution | 256 [*nri-limits.stub-tcp-clients] | §6.8 |
| Stub UDP queries awaiting resolution | 256 total; 16 per source address and port [*nri-limits.stub-udp-pending] | §6.8 |
| Cache entries | 8 192 [*nri-limits.cache-entries] | §6.7 |
| Stub TCP client bound | 10 s [*nri-limits.stub-tcp-client-bound] | §6.8 |
| Manager reconnect backoff | 0.5 s doubling to 10 s [*nri-limits.manager-reconnect-backoff] | §6.9 |

The upstream ceiling leaves synthetic and cached answers unaffected once
a query has passed its door's admission limits. Native and stub TCP reply
writers have separate 256-frame queues and one-second write deadlines.

An implementation MAY adjust these; it MUST document the values it
uses. The relations that must hold: the shim's own timeout exceeds
attempts × per-server timeout, so a slow upstream is reported by the
resolver as `unavailable` rather than by the shim as a timeout. [*nri-limits.shim-timeout-exceeds-attempts-times-server-timeout]

---

# 7.1 Scope and Roles

_Peios Specifications / PSPU / Job Submission_

> The interface by which any process asks the service manager to run and supervise a process on its behalf — the submitter's side of a job, and what this chapter leaves to §4.

This chapter defines the **jobs channel**: the interface by which a
process asks a Peios service manager to run an arbitrary program under
its supervision, with an identity the requester is entitled to confer,
and to manage that program afterwards.

A job submitted this way is a **job** in the sense of §4.2 — one
process execution, supervised by the manager — whose parent is the
process that asked for it rather than a service definition. The
manager forks it, installs its token, contains it, records it and
reaps it exactly as it does a service's process. What differs is where
the definition came from and who is entitled to manage the result.

Two shapes of use are intended, and the chapter is written so that one
primitive serves both:

- A **task**: a program that runs to completion and reports progress
  on the way — a backup, a transfer, a migration — submitted by a
  broker on behalf of the principal it is acting for.
- A **session**: a long-lived program managed from outside — a
  per-logon host process for an interactive session — submitted with a
  freshly issued logon token and one end of a channel back to its
  submitter.

Nothing in the protocol distinguishes the two. They are the same
message with different field values.

## 7.1.1 The roles

**The manager** is the process that supervises services and listens on
the control and notification channels of §4. It listens on the jobs
channel too. On Peios this is peinit.

**A submitter** connects to the jobs channel, submits a job, and MAY
manage the jobs it submitted. A submitter is any process the socket's
descriptor admits; it holds no relationship with the manager beyond
the one its token establishes.

**A job** is the process the manager started on a submitter's behalf.
It speaks the notification channel of §4 about itself, in the same way
a service does, and this chapter adds nothing to that role beyond the
progress fields defined in §4.19.

**A client** of the control channel (§4) MAY observe and stop jobs it
is entitled to, alongside services. That role is unchanged here;
§4.14 defines the commands.

Requirements are stated against the role, not the program. A service
that submits jobs is a submitter when it does so; a job that submits
jobs of its own is a submitter too.

## 7.1.2 What this chapter covers

- the jobs socket, how it is reached, and who may reach it
- message framing on it, and how a message carries a token and
  descriptors alongside its content
- how the identity a job runs as is established, and the rule that
  the manager never installs an identity the submitter could not
  already act as
- the job definition a submitter sends, and what the manager validates
- the job view the manager reports, its states and its causes
- the commands a submitter may issue about its own jobs, and the
  Security Descriptor that decides who else may
- passing descriptors into a job, and receiving its output
- the error vocabulary, the extension rules and the conformance
  requirements

## 7.1.3 What this chapter does not cover

- **The notification channel**, including the progress fields a job
  sends. A job reports on itself exactly as a service does. §4.16–§4.19.
- **Observing and stopping jobs from the control channel.** The
  `job-list`, `job-status` and `job-stop` commands are part of the
  control channel's command set and are defined in §4.14, using the
  job view this chapter defines.
- **How the manager supervises the job** once it is running — cgroup
  containment, output capture, reaping, the child setup sequence. That
  is the manager's own design, documented in its reference manual.
- **How a token is conveyed on a socket, and what the kernel checks
  when it is.** Peer-token capture, `KACS_SCM_TOKEN`, the impersonation
  gates and the impersonation-level ratchet are kernel operations,
  documented in the Peios Kernel TRM §3.5.
- **How a submitter obtained the token it attaches.** From a peer it is
  serving, from a logon it originated (PGSS §2), or from anywhere else
  — the manager does not ask, because the kernel has already decided
  whether the submitter may convey it.

---

# 7.2 Terminology

_Peios Specifications / PSPU / Job Submission_

> Terms this chapter defines for itself — submitter, submitted job, job identity, attached token, message — and the ones it borrows from §4 and the kernel manual.

Terms defined in §4.2 — service, job, activation generation, right,
terminal state, datagram — are used here with the same meaning and are
not redefined.

**Submitted job.** A job whose definition arrived on the jobs channel
rather than from a service definition. It has no service, no
operation, and no activation generation; it belongs to a submitter.

**Submitter.** The principal that submitted a job: the identity the
connection carried when the `submit` message was read. It is recorded
on the job and is the owner of the job's Security Descriptor.

**Job identity.** The identity a submitted job's process runs as. It
is either the submitter's own primary identity or one the submitter
attached to the `submit` message; it is never named by a field.

**Attached token.** A token conveyed with a message through the
kernel's per-message identity facility (`KACS_SCM_TOKEN`; the Peios
Kernel TRM §3.5). The kernel has verified, at the moment of sending,
that the sender could act as that identity at the level recorded on
the token.

**Attached descriptor.** A file descriptor conveyed with a message
through `SCM_RIGHTS`, to be given to the job or used as its output
sink.

**Message.** One `SOCK_SEQPACKET` record on the jobs channel, carrying
exactly one JSON object and, optionally, one attached token and any
number of attached descriptors. The jobs channel has no frames in the
sense of §4.2: the transport delimits messages.

**Job view.** The JSON object by which the manager reports a job, on
either channel. §7.7.

**Live job.** A submitted job in a non-terminal state. Quotas count
live jobs.

---

# 7.3 The Jobs Socket

_Peios Specifications / PSPU / Job Submission_

> The manager's sequenced-packet socket at a well-known path, why reaching it is the whole of the submission permission, and the limits placed on a connection.

The manager MUST listen on a Unix `SOCK_SEQPACKET` socket at a
well-known path. On Peios that path is:

```
/run/services/peinit/jobs.sock
```

The socket MUST exist for as long as the manager is serving, and the
manager MUST unlink it when it stops. The manager MUST create the
listening socket and every accepted connection with close-on-exec set,
so that no connection descriptor is inherited by a job it starts.

## 7.3.1 Why a second socket

The control channel (§4.4) is an administrator's door: its commands
change the state of the system's services, and the descriptor on its
socket admits the principals entitled to do that. Submitting a job is
a different permission held by a different population. Any principal
may reasonably be allowed to run a program under supervision, subject
to a quota, without being allowed to stop `registryd`.

Putting the two on one socket would force one descriptor to serve both
populations. Two sockets let the filesystem say who may submit and who
may administer, separately, with no policy inside the manager.

## 7.3.2 Why a sequenced-packet socket

A message on this channel carries more than bytes. It carries the
token a job is to run as, and the descriptors a job is to be given,
as ancillary data. The kernel associates ancillary data with the
record it was sent with, and on a stream that association is only as
precise as the reader's record boundaries. `SOCK_SEQPACKET` makes one
`send` one message and one identity (the Peios Kernel TRM §3.5), so
the manager never has to decide which request an attached token or
descriptor belongs to.

The cost is that a message has a maximum size (§7.A) and cannot be
split. A definition is small; nothing here needs to be large.

## 7.3.3 Who may submit

**Being able to connect is the submission permission.** The manager
MUST NOT perform an access check of its own before accepting a
`submit`; the check is the one the kernel performs against the
socket's inode descriptor when the submitter connects, and the manager
relies on it entirely.

The manager MUST therefore ensure the socket, and each directory
containing it, carries a Security Descriptor admitting exactly the
principals it intends to let submit. The default a Peios service
manager applies is in §7.A. §4.3's warning applies with full force: a
socket that inherits nothing is reachable by nobody, and one in a
permissive place is reachable by anything.

What a submitter may do *to a job* is a separate question, answered by
the job's own descriptor (§7.8). Reaching the socket confers the right
to submit, and nothing else.

## 7.3.4 A connection

A submitter connects, issues one or more messages, and closes. The
manager MUST NOT require a submitter to issue any message before
another, and MUST NOT hold state across connections beyond the jobs
themselves: a connection carries an identity (§7.5) and nothing else.

Messages on one connection MUST be answered in the order they were
received. The manager MAY read no further messages from a connection
while a response on it is outstanding.

Closing a connection MUST NOT affect any job submitted on it. A job
belongs to its submitter's identity, not to the connection that
submitted it; a submitter that reconnects — after a restart, say —
finds its jobs where it left them.

## 7.3.5 Limits

The manager MUST enforce three limits on the channel and one on the
submitter, and MUST make their values discoverable to an administrator
through the same surface that sets them. The values a Peios service
manager uses by default are in §7.A.

**Concurrent connections.** A connection accepted while the manager is
already at its limit MUST be closed at the socket level, without a
response, and a submitter MUST treat an immediate close with no
response as a refusal rather than a protocol error.

**Message size.** A message whose content exceeds the limit MUST be
answered with `REQUEST_TOO_LARGE`. The manager MUST detect a message
the kernel truncated to fit its receive buffer (`MSG_TRUNC`) and MUST
NOT interpret the truncated content: a truncated JSON object is
malformed by construction, but a truncated attachment list is not,
and the manager MUST NOT act on a request whose attachments it did
not fully receive.

**Idle timeout.** A connection with no message outstanding MAY be
closed once it has been idle for the configured period, without a
response. A connection blocked on a `wait` (§7.8), or on a `submit`
whose job has not yet confirmed exec, is not idle and MUST NOT be
closed for idleness.

**Live jobs per submitter.** The manager MUST bound the number of live
jobs one submitter may hold, counted by the submitter's user SID, and
MUST answer a `submit` that would exceed the bound with
`QUOTA_EXCEEDED`, creating nothing. The manager MAY exempt the SYSTEM
principal (`S-1-5-18`). A job that reaches a terminal state stops
counting at once, not when its record is dropped (§7.7).

---

# 7.4 Messages

_Peios Specifications / PSPU / Job Submission_

> One compact JSON object per sequenced-packet message, in both directions, with a token and descriptors carried as ancillary data — and what is malformed.

## 7.4.1 Content

Every message in both directions carries exactly one JSON object,
serialized compactly, as the whole of the record's content. There is
no terminator: the transport delimits messages, and the manager MUST
NOT require or emit a trailing newline.

Content is UTF-8. The manager MUST reject content that is not
well-formed UTF-8 with `MALFORMED_REQUEST`.

The rules of §4.5 for what is malformed apply unchanged: an empty
message, content that is not valid JSON, and valid JSON that is not an
object are all `MALFORMED_REQUEST`. The manager MUST NOT emit
pretty-printed JSON. Timestamps follow §4.5.

## 7.4.2 Attachments

A request MAY carry ancillary data. Two kinds are defined:

| Level | Type | Meaning | Applies to |
|---|---|---|---|
| `SOL_KACS` | `KACS_SCM_TOKEN` | The token the job is to run as. At most one. | `submit` |
| `SOL_SOCKET` | `SCM_RIGHTS` | Descriptors for the job, or an output sink. | `submit` |

The manager MUST receive every message with room for both kinds and
for the number of descriptors in §7.A. It MUST detect ancillary data
the kernel could not fit (`MSG_CTRUNC`) and MUST answer the message
`INVALID_ARGUMENTS` without acting on it: a request whose attachments
were partly lost does not describe the job the submitter meant.

Attachments on a message whose command does not use them MUST be
closed and ignored. A stray descriptor on a `status` is not an error,
in the same spirit as §4.8's rule for fields that do not apply — but
it is closed, because nothing else could own it.

The manager MUST close every attached descriptor it does not hand to a
job or adopt as an output sink, on every path including error paths.
A submitter MUST assume the manager has taken ownership of everything
it attached to a `submit`, whatever the outcome, and MUST NOT rely on
the manager leaving a descriptor open.

A response MAY carry ancillary data. One kind is defined:

| Level | Type | Meaning | Carried by |
|---|---|---|---|
| `SOL_SOCKET` | `SCM_RIGHTS` | The job's process handle. Exactly one. | A `submit` response for a running job. §7.6 |

A submitter that receives a response without room for its ancillary
data does not receive the handle, and MUST NOT treat that as an error:
the response content is complete without it.

## 7.4.3 Requests

A request is one JSON object.

```json
{"command": "submit", "image_path": "/usr/bin/peios-backup",
 "arguments": ["sync", "/home/u/docs"], "description": "Backup of docs"}
```

| Field | Type | Required | Meaning |
|---|---|---|---|
| `command` | string | always | `submit`, `status`, `wait`, `stop` or `signal`. |
| `job_id` | string | all but `submit` | The job. |
| `wait` | bool | no | For `stop`: block until the job is terminal. §7.8 |
| `for` | string | no | For `wait`: `ready` or `terminal`. §7.8 |
| `signal` | integer | for `signal` | The signal number. §7.8 |

The `submit` definition fields are in §7.6.

`command` MUST be present and MUST be a string naming one of the five
commands. Otherwise the manager MUST answer `INVALID_COMMAND`.

`job_id` MUST be present and a string for every command but `submit`.
Its absence, a non-string value, or a value that is not a well-formed
identifier MUST be answered `INVALID_ARGUMENTS`.

A field the command does not use MUST be ignored, not rejected. A
field the manager does not recognize MUST be ignored (§7.11).

## 7.4.4 Responses

Every response carries a `status` field, exactly `"ok"` or `"error"`.

The success shape for every command is the **job view** (§7.7):

```json
{"status": "ok", "job": { … }}
```

The error shape is §4.9's:

```json
{"status": "error", "code": "QUOTA_EXCEEDED",
 "message": "submitter S-1-5-21-… holds 64 live jobs"}
```

`code` MUST be one of the values in §7.10. `message` is not
normative; a submitter MUST NOT parse or branch on it.

## 7.4.5 Closing after an error

§4.5's distinction applies. On a sequenced-packet socket a
frame-level failure is narrower — the transport cannot lose
synchronization — so only `REQUEST_TOO_LARGE` and a truncated message
close the connection. Every other error is command-level: the manager
MUST send the error and keep the connection open.

A submitter MUST NOT assume a connection survives an error response.

---

# 7.5 Identity

_Peios Specifications / PSPU / Job Submission_

> Two identities per submission — the submitter's, captured from the kernel, and the job's, which is either the submitter's own primary or a token the kernel verified it could convey. Never a name.

Every submission involves two identities, and the protocol keeps them
apart.

The **submitter** is who asked. The **job identity** is who the job
runs as. They are the same principal in the simplest case and
different ones in the case the channel exists for — a broker running a
program as the client it is serving.

## 7.5.1 The submitter

The manager MUST establish the submitter's identity from the kernel,
as §4.6 requires of the control channel: the peer's token, captured
when the connection was accepted, used for every message on the
connection. A submitter MUST NOT be able to assert who it is, and a
change of identity mid-connection has no effect on it.

The submitter's identity is what the manager records on the job as
its submitter, what it counts quotas against, and what it names as the
owner of the job's descriptor (§7.8). It MUST be the identity the peer
thread was acting under when it connected — so a submitter that
connects while impersonating is recorded as the principal it was
impersonating. A submitter that intends to *own* the jobs it submits,
as itself, connects as itself and conveys any other identity per
message.

## 7.5.2 The job identity

The job identity is established in exactly one of two ways, and the
manager MUST NOT provide a third.

**No token attached — the submitter's own primary.** The manager MUST
open the primary token of the connecting *process* — identified by
the kernel through the peer's process handle (`SO_PEERPIDFD`), never
by a PID the submitter names — duplicate it, and install the duplicate
on the job.

The job then has the identity a child of the submitter would have
had: its primary token, with no impersonation inherited (the Peios
Kernel TRM §3.2). A submitter that was impersonating when it
connected therefore produces a job running as its *own* identity, not
the impersonated one, while being recorded as a submitter under the
impersonated one. The two differ deliberately, and a submitter that
wants the impersonated identity on the job attaches it.

**A token attached — the identity conveyed with the message.** The
manager MUST use the token the kernel delivered with the `submit`
message, duplicate it to a primary token, and install the duplicate on
the job.

The kernel gated the attach: it ran the impersonation gates with the
submitter as installer and recorded on the token the lower of the
socket's level and the source's own (the Peios Kernel TRM §3.5). The
attached token is therefore a kernel-verified statement that *the
submitter could have acted as this identity, at this level, when it
sent this message*. The manager MUST rely on that statement and MUST
NOT re-derive it.

## 7.5.3 What the manager checks

The manager MUST refuse, with `BAD_TOKEN`:

- more than one attached token on a message;
- an attached token whose impersonation level is below Impersonation.
  An Identification-level token cannot pass an access check and an
  Anonymous one is not an identity to run a process as; neither can
  become a primary (the Peios Kernel TRM §3.2.4);
- an attached token the manager cannot duplicate.

The manager MUST NOT refuse a token because of *who* it names. Whether
the submitter may run a job as that identity was decided by the kernel
when the token was conveyed, and a second decision inside the manager
would be a second copy of the same policy, able only to disagree with
the first.

## 7.5.4 The level carries through

The duplicated primary carries the attached token's impersonation
level, and everything the job does inherits it (the Peios Kernel TRM
§3.5.1). A submitter that needs the job to convey Delegation — to a
session that will authenticate to remote services on its user's
behalf — MUST set its own jobs connection to Delegation before
attaching, because the default level on a socket is Impersonation and
the attach is clamped to it. A job started at Impersonation cannot be
raised afterwards, by anyone.

## 7.5.5 What the manager never does

The manager MUST NOT accept a *primary* token passed as a plain
descriptor (`SCM_RIGHTS`) as a job identity. A descriptor passed that
way is not gated by the kernel: whoever holds an fd can pass it, and
the recipient learns nothing about whether the sender could act as the
identity it names. Every job identity on this channel is one the
kernel verified the submitter could act as, and a path that skips the
verification would be the only one worth attacking.

The manager MUST NOT install on a job any token it obtained by a route
other than the two above. In particular it MUST NOT open a token
through a submitter-supplied PID or descriptor, and MUST NOT let a
`submit` field name an identity. There is no identity field, and a
manager MUST NOT add one (§7.11).

> [!NOTE]
> The consequence for a service that runs programs as its clients is
> that it needs `SeImpersonatePrivilege` — to be allowed to convey a
> client's identity at all — and nothing more. It never holds a
> primary token for the client, never needs
> `SeAssignPrimaryTokenPrivilege`, and never installs anything. The
> one process that installs primary tokens on other people's behalf is
> the one that supervises the result.

---

# 7.6 Submitting a Job

_Peios Specifications / PSPU / Job Submission_

> The definition a submitter sends — every field, its default and its validation — what the manager does with it, and when and with what the submit is answered.

A `submit` carries the whole definition of the job in the request
object. There is no persistent definition, no name, and no policy: a
submitted job runs once, as described, and is then gone.

## 7.6.1 The definition

| Field | Type | Required | Default | Meaning |
|---|---|---|---|---|
| `image_path` | string | yes | — | The program to execute. An absolute path. |
| `arguments` | array of strings | no | `[]` | Its arguments, after the program name. |
| `environment` | object of string → string | no | `{}` | Variables to set. §7.6 below. |
| `working_directory` | string | no | `/` | The working directory. An absolute path. |
| `description` | string | no | `""` | A human-readable label, for views and records. |
| `timeout` | integer | no | `0` | Seconds the job may run before it is stopped. `0` is no limit. |
| `stop_timeout` | integer | no | §7.A | Seconds between the termination signal and the kill. |
| `readiness` | string | no | `none` | `none`, or `notify` to wait for `READY=1`. |
| `readiness_timeout` | integer | no | §7.A | Seconds a `notify` job has to become ready. |
| `success_exit_codes` | array of integers | no | `[]` | Non-zero exit codes that count as success. |
| `descriptors` | array of strings | no | `[]` | Names for the descriptors to inject. §7.9 |
| `output` | bool | no | `false` | Whether the last attached descriptor is an output sink. §7.9 |
| `security_descriptor` | string | no | §7.8 | The job's descriptor, in SDDL. §7.8 |

Nothing here restarts, depends, probes, or schedules. A program that
needs a restart policy, dependencies, a health check or a trigger is a
service, and its definition belongs in the registry (§4.1). The
manager MUST NOT accept a policy field on a `submit`, and MUST NOT add
one (§7.11).

### 7.6.1.1 Validation

The manager MUST answer `INVALID_ARGUMENTS`, creating nothing, when:

- `image_path` is absent, not a string, empty, not absolute, or
  contains a NUL byte;
- `working_directory` is present and not an absolute string, or
  contains a NUL byte;
- any element of `arguments` is not a string or contains a NUL byte;
- any key of `environment` is empty, contains `=`, or contains a NUL
  byte; or any value contains a NUL byte;
- any of `timeout`, `stop_timeout`, `readiness_timeout` is present and
  not a non-negative integer, or `stop_timeout` is `0`;
- `readiness` is present and not one of the two values;
- any element of `success_exit_codes` is not an integer in 0–255;
- `descriptors` does not match the attached descriptors (§7.9);
- `security_descriptor` is present and is not a valid descriptor with
  an owner and a DACL (§7.8);
- the total size of the resulting `argv` and environment exceeds what
  the manager can pass to `execve`.

The manager MUST NOT validate that `image_path` exists or is
executable. That is decided at `execve`, by the job's own token
against the file's descriptor, and a job whose program cannot be run
becomes a failed job (§7.7) rather than a refused submission. Checking
in advance would either check with the wrong identity or duplicate the
kernel's decision.

### 7.6.1.2 The environment

The manager MUST build the job's environment as it builds a service's,
with `environment` in the place a service definition's own variables
occupy: above any manager-wide layer an administrator configures, and
below the protocol variables the manager sets last. A submitter MUST
NOT be able to override `NOTIFY_SOCKET`, `LISTEN_FDS`,
`LISTEN_FDNAMES` or `LISTEN_PID`.

The manager sets no `HOME`, `USER`, `LOGNAME` or `SHELL` — it knows
nothing about the job identity beyond its token, and a submitter that
knows the principal's home directory supplies it. A submitter that
originated a logon has these from the logon's profile (PGSS §2.9).

## 7.6.2 What the manager does

On an accepted `submit` the manager MUST, in order:

1. Establish the job identity (§7.5) and refuse with `BAD_TOKEN` if
   it cannot.
2. Check the submitter's quota and refuse with `QUOTA_EXCEEDED` if the
   job would exceed it.
3. Create the job record, with its identifier, in the `created` state,
   owned by the submitter with the descriptor of §7.8.
4. Start the process — install the identity, set up its streams,
   inject descriptors, execute — as it starts a service's main process.
5. Answer the `submit`.

Steps 1 and 2 MUST both precede step 3: a refused submission MUST
leave no record, emit no lifecycle event, and consume no quota.

## 7.6.3 When the submit is answered

The manager MUST answer a `submit` when the job has **left the
`created` state**: when the process has confirmed a successful
`execve`, or when starting it has failed.

It MUST NOT answer earlier. A submitter holding a response holds a job
that either exists as a running process or has definitively failed to
— never one whose fate is still being decided in the setup between
fork and exec.

It MUST NOT answer later. In particular a `readiness: notify` job is
answered when it is running, not when it is ready; a submitter that
wants to block until readiness follows with a `wait` (§7.8).

## 7.6.4 The response

The response is the job view (§7.7).

If the job is `running`, the response MUST carry the job's process
handle — a pidfd referring to the job's main process — as an attached
descriptor. The handle lets the submitter observe the process's exit
with `poll` or `waitid`, and signal it, with no further protocol; the
kernel applies its ordinary process access rules to whatever the
submitter does with it. A submitter that declined to receive ancillary
data simply does not get the handle (§7.4).

If the job is `failed`, the response carries no descriptor, and the
view's `cause` says why (§7.7). The submission itself succeeded — a
job was created, recorded and reported — so the response is
`"status": "ok"`. Only a submission the manager refused outright, at
steps 1–3, is an error response.

> [!NOTE]
> A submitter that needs the process handle as a *child* would have
> — to `waitpid` on it, or to be its parent for `PR_SET_PDEATHSIG` —
> does not get that, because the job is the manager's child, not the
> submitter's. Exit status reaches the submitter through the job view,
> through `wait`, or through the manager's event stream; the pidfd is
> for polling, signaling, and passing to something else.

---

# 7.7 The Job View

_Peios Specifications / PSPU / Job Submission_

> The one JSON object by which a submitted job is reported on either channel — its fields, its five states and what each nullable field means in each, its causes, and how long it is retained.

The job view is the shape every successful response on this channel
carries, and the shape `job-status`, `job-list` and `job-stop` return
on the control channel (§4.14), which adds one field to it. It is
defined once, here.

```json
{
    "id": "0190a3b2-…",
    "type": "submitted",
    "state": "running",
    "cause": null,
    "submitter": "S-1-5-80-…",
    "identity": "S-1-5-21-…",
    "logon_session": 1042,
    "description": "Backup of docs",
    "image_path": "/usr/bin/peios-backup",
    "pid": 4521,
    "ready": null,
    "exit_code": null,
    "exit_signal": null,
    "status_text": "Backing up /home/u/docs (3/5)",
    "progress": {"current": 812, "total": 2048, "bounded": true,
                 "unit": "items"},
    "created_at": "2026-06-01T12:34:56.123456789Z",
    "started_at": "2026-06-01T12:34:56.223456789Z",
    "ended_at": null
}
```

| Field | Type | Meaning |
|---|---|---|
| `id` | string | The job's identifier. |
| `type` | string | Always `submitted` on this channel. §4.B |
| `state` | string | §7.B. |
| `cause` | string or null | Why the job ended, where the manager decided it. §7.B |
| `submitter` | string | The submitter's user SID. |
| `identity` | string | The job identity's user SID. |
| `logon_session` | integer | The job identity's logon session identifier. |
| `description` | string | As submitted. |
| `image_path` | string | As submitted. |
| `pid` | integer or null | The process identifier, while there is a process. |
| `ready` | bool or null | For a `notify` job: whether `READY=1` has arrived. Null for a `none` job. |
| `exit_code` | integer or null | The exit code, when the process exited. |
| `exit_signal` | integer or null | The signal, when the process was killed. |
| `status_text` | string or null | The most recent `STATUS` the job sent (§4.19). |
| `progress` | object or null | The most recent progress the job sent (§4.19). |
| `created_at` | string | When the record was created. §4.5 |
| `started_at` | string or null | When exec was confirmed. |
| `ended_at` | string or null | When the job became terminal. |

A field that does not apply MUST be present and null, never omitted.

These are all the view's fields on this channel. On the control
channel each view carries one more, `granted`: the job rights the
caller holds on the job (§4.14). It describes the caller rather than
the job, and a submitter on this channel is not given it.

`identity` and `submitter` are user SIDs. A client that needs the
identity's groups, privileges or integrity does not get them here;
they are the job's, not the view's.

`progress` carries `current` (integer), `total` (integer or null),
`bounded` (bool) and `unit` (string or null), in the representation
§4.19 defines. A progress object whose `total` is null is either
unbounded or not yet bounded, and `bounded` distinguishes them.

## 7.7.1 States

| State | Process? | Terminal? | Meaning |
|---|---|---|---|
| `created` | Not yet | No | The record exists; exec has not been confirmed. Never visible on this channel — a `submit` is answered only after leaving it. |
| `running` | Yes | No | Exec succeeded and the process is alive. |
| `completed` | No | Yes | The process exited with `0` or a code in `success_exit_codes`. |
| `failed` | No | Yes | The process exited otherwise, was killed by a signal, or never ran because setup failed. |
| `abandoned` | Yes, unkillably | Yes | The process survived the kill. The manager has stopped supervising it. |

These are the states of every job the manager runs, not a set
invented for this channel; a client that understands them for a
service's main job understands them here. A stopped job whose
process died to the termination signal is `failed` with
`exit_signal` set, and `cause` says the stop was asked for.

Which fields are populated is a function of state, and a client MAY
rely on it:

| State | `pid` | `started_at` | `ended_at` | `exit_code` / `exit_signal` |
|---|---|---|---|---|
| `running` | set | set | null | null |
| `completed` | null | set | set | exactly one set |
| `failed`, process ran | null | set | set | exactly one set |
| `failed`, setup failed | null | null | set | both null |
| `abandoned` | set | set | set | both null |

`exit_code` and `exit_signal` are never both set: a process exits or
is killed. For `abandoned`, `ended_at` records when supervision
stopped; nothing exited.

## 7.7.2 Causes

`cause` is set when the manager itself brought the job to its end, or
decided it could not start, and null when the process ended of its own
accord — a clean exit, a crash, a signal from elsewhere.

| Value | State | Meaning |
|---|---|---|
| `parent_setup_failure` | `failed` | The manager could not prepare the launch: no token, no cgroup, no fork. No process existed. |
| `pre_exec_failure` | `failed` | The child's setup between fork and exec failed, or exec itself did. |
| `readiness_timeout` | `failed` | A `notify` job did not send `READY=1` within `readiness_timeout`. The manager stopped it. |
| `timeout` | `failed` | The job ran longer than `timeout`. The manager stopped it. |
| `explicit_stop` | `failed` | A `stop` or `job-stop` was issued and the process died to it. |
| `shutdown` | `failed` | The system was shutting down and the manager stopped it. |
| `process_unkillable` | `abandoned` | The process survived the kill. |

A `stop` whose process handled the termination signal and exited `0`
produces `completed` with cause `explicit_stop`: the manager asked, the
process agreed, and both facts are recorded.

## 7.7.3 Retention

The manager MUST hold a terminal job's record for at least a grace
period after it reaches a terminal state, so that a submitter polling
for the outcome can retrieve it. The value a Peios service manager
uses is in §7.A.

An identifier that never existed and one whose record has been dropped
MUST both be answered `UNKNOWN_JOB`, and a submitter MUST NOT
distinguish them (§4.14's rule for operations, applied to jobs).

A job that is terminal stops counting against its submitter's quota at
once; its record's retention is for the submitter's benefit, not a
cost to it.

---

# 7.8 Managing a Job

_Peios Specifications / PSPU / Job Submission_

> The four commands a submitter issues about a job — status, wait, stop, signal — the Security Descriptor every job carries, the rights on it, and who holds them by default.

Four commands act on an existing job. Every one is authorized against
the job's own Security Descriptor, using the connection's token, with
the rights and mapping below. There is no command the manager performs
on a job without a check, and no principal exempt from one — the
submitter included.

## 7.8.1 Rights

| Right | Bit | Grants |
|---|---|---|
| `JOB_QUERY` | 0x0001 | Read the job view; wait on the job. |
| `JOB_STOP` | 0x0002 | Stop the job. |
| `JOB_SIGNAL` | 0x0004 | Send a signal to the job's process. |
| `JOB_ALL_ACCESS` | 0x0007 | All three. |

| Generic right | Maps to |
|---|---|
| `GENERIC_READ` | `JOB_QUERY` |
| `GENERIC_WRITE` | `JOB_STOP \| JOB_SIGNAL` |
| `GENERIC_EXECUTE` | `JOB_STOP \| JOB_SIGNAL` |
| `GENERIC_ALL` | `JOB_ALL_ACCESS` |

The same rights and mapping govern the control channel's job commands
(§4.7).

## 7.8.2 The job's descriptor

Every job carries a Security Descriptor from the moment its record
exists. Unless the `submit` supplied one, the manager MUST construct:

- owner and group: the submitter's user SID;
- a DACL granting `JOB_ALL_ACCESS` to the submitter, to SYSTEM
  (`S-1-5-18`) and to Administrators (`S-1-5-32-544`);
- a SACL with one failure-audit ACE for Everyone (`S-1-1-0`) over
  `JOB_ALL_ACCESS`, so that a refused command on the job is recorded by
  the access check (§4.7);
- nothing else. In particular **the job identity is granted nothing**:
  a process cannot, by virtue of running as U, see or stop a job that
  runs as U. A submitter that wants the principal to see its own
  session says so.

A `submit` MAY supply `security_descriptor`, in SDDL, and the manager
MUST use it as given — it MUST NOT add its default entries to it. The
supplied descriptor MUST carry an owner and a DACL, or the `submit` is
`INVALID_ARGUMENTS`. A submitter that omits itself from the DACL it
supplies has locked itself out of its own job, and the manager MUST
NOT prevent that: the descriptor is the policy, and a policy the
manager second-guessed would not be one.

The descriptor is fixed at submission. This chapter defines no command
to change it.

## 7.8.3 status

Returns the job view. Requires `JOB_QUERY`.

## 7.8.4 wait

Blocks until a condition holds, then returns the job view. Requires
`JOB_QUERY`.

| `for` | Returns when |
|---|---|
| `terminal` (default) | The job reaches a terminal state. |
| `ready` | The job has sent `READY=1`, **or** reaches a terminal state, whichever first. |

`for: ready` on a `readiness: none` job MUST be answered
`INVALID_STATE`: there is nothing to wait for. On a job that is
already ready, or already terminal, the manager MUST answer at once.

A connection blocked on a `wait` is not idle (§7.3). The wait is
bounded by nothing but the job: a `wait` on a session job with no
`timeout` blocks until something stops it. A submitter that needs a
bounded wait polls `status` instead, or waits on the process handle it
was given.

If the job's record is dropped while a wait is blocked on it — which
can only happen after it became terminal and its grace period elapsed,
so only if the manager was unable to answer in time — the wait MUST
be answered `UNKNOWN_JOB`.

## 7.8.5 stop

Asks the manager to end the job. Requires `JOB_STOP`.

The manager MUST send the termination signal to the job's process,
wait `stop_timeout`, and then kill everything remaining in the job's
containment. A job that has sent `STOPPING=1` MUST NOT receive the
termination signal (§4.19); the deadline still applies.

`wait` defaults to **true**: the response is sent when the job is
terminal. With `wait: false` the manager MUST respond as soon as the
stop has been initiated, with the job view as it then is.

A `stop` on a job that is already terminal MUST return the job view
unchanged, with `"status": "ok"`. It is not an error to stop something
that has stopped; it is a no-op, and the view is the honest answer. A
second `stop` on a job already being stopped MUST NOT restart the
deadline.

## 7.8.6 signal

Sends one signal to the job's main process, and nothing else. Requires
`JOB_SIGNAL`.

`signal` MUST be an integer naming a signal the platform defines, or
the request is `INVALID_ARGUMENTS`. The manager MUST deliver it to
the process through the handle it obtained at fork, so that a recycled
PID can never be signaled by mistake, and MUST answer with the job
view.

A `signal` on a job that is not `running` MUST be answered
`INVALID_STATE`.

This is the raw mechanism, deliberately: `SIGKILL` through `signal`
kills the main process and leaves whatever it spawned, and produces a
`failed` job with `exit_signal` set and a null `cause`. A submitter
that wants the job *ended* uses `stop`.

## 7.8.7 What none of them do

None of these commands moves a job backwards or starts it again. A
terminal job stays terminal, its record is dropped after the grace
period, and a submitter that wants the program to run again submits
it again.

---

# 7.9 Descriptors and Output

_Peios Specifications / PSPU / Job Submission_

> Handing descriptors to a job at submission, in the form a conforming program already adopts; and receiving a copy of the job's output while the manager keeps the record.

## 7.9.1 Descriptors into the job

A `submit` MAY attach descriptors with `SCM_RIGHTS`. The manager MUST
give them to the job's process, in the order they were attached, in
exactly the form §4.20 gives stored descriptors back to a service:

1. Placed consecutively from descriptor **3**, with close-on-exec
   cleared.
2. `LISTEN_FDS` set to the count.
3. `LISTEN_FDNAMES` set to the names from `descriptors`,
   colon-separated, in the same order.
4. `LISTEN_PID` set to the job process's own PID.

All four MUST be absent when nothing is passed.

`descriptors` names them. It MUST have exactly one entry per
descriptor to be injected — the attached descriptors, less the output
sink if `output` is true — or the `submit` is `INVALID_ARGUMENTS`. A
name MUST be non-empty and MUST NOT contain `:`, since `:` is the
separator in `LISTEN_FDNAMES`.

A submitter MAY attach nothing and send an empty `descriptors`; that
is the common case.

> [!NOTE]
> This is what makes a session job possible without inventing a
> channel: the submitter creates a `socketpair`, keeps one end, and
> attaches the other, and the session process finds it at descriptor 3
> under whatever name the submitter chose. It is also what makes a
> terminal possible — attach the pseudo-terminal's slave — and every
> other case where the program needs a handle its submitter already
> holds. The convention is `sd_listen_fds`'s, so a program written to
> adopt descriptors from a service manager adopts them from a
> submitter unchanged.

The manager MUST NOT inspect, validate or restrict what an attached
descriptor refers to. What a job may do with a descriptor is decided
by the rights cached on it, which the submitter established when it
opened it.

## 7.9.2 The job's output

A job's standard output and standard error MUST be captured by the
manager and recorded exactly as a service's are — the manager's own
design says where, and on Peios that is eventd, tagged with the job's
identifier. This is unconditional: a submitter cannot turn it off, and
cannot redirect the job's streams somewhere the manager does not see.

A submitter MAY additionally ask for a copy. With `output: true`, the
**last** attached descriptor is not injected into the job; the manager
adopts it as an **output sink** and writes to it every line it reads
from the job's streams, as it reads them.

The copy is best-effort, and the record is not:

- The manager MUST NOT block on the sink, and MUST NOT let a sink that
  is not being drained slow the job or the manager. It MUST put the
  sink in non-blocking mode.
- When a write to the sink would block, the manager MUST drop the line
  **for the sink only**, MUST still record it, and MUST count the drop.
  It MUST report that drops occurred — at least once per job, through
  its event stream — so a submitter that sees a gap can learn it
  caused one.
- The manager MUST close the sink when the job is terminal, after the
  last line has been written or dropped, and MUST close it at once if
  writing to it fails with anything other than a would-block
  condition.

What the manager writes to the sink is each line the job produced,
followed by a newline, with no tagging: the submitter attached the
sink knowing which job it was for. Lines from the two streams are
interleaved in the order the manager read them. A submitter that needs
to tell them apart, or needs every line, reads the record instead.

`output: true` with no attached descriptor is `INVALID_ARGUMENTS`.

---

# 7.10 Errors

_Peios Specifications / PSPU / Job Submission_

> The closed set of error codes the jobs channel may emit — §4.10's, less those that cannot arise here, plus three of its own.

The `code` field of an error response MUST be one of these values. The
manager MUST NOT emit any other code on this channel, and a submitter
MUST treat a code it does not recognize as an unrecoverable error for
that request (§7.11).

| Code | Meaning | Closes? |
|---|---|---|
| `MALFORMED_REQUEST` | The message is not a single well-formed JSON object. §7.4 | No |
| `REQUEST_TOO_LARGE` | The message exceeds the configured maximum, or was truncated. §7.3 | Yes |
| `INVALID_COMMAND` | `command` is absent, not a string, or names no command. | No |
| `INVALID_ARGUMENTS` | A field is absent, malformed, or inconsistent with the attachments. §7.6, §7.9 | No |
| `UNKNOWN_JOB` | `job_id` names nothing the manager holds — it never existed, or its retention has elapsed. §7.7 | No |
| `ACCESS_DENIED` | The access check against the job's descriptor denied the right. §7.8 | No |
| `INVALID_STATE` | The command is not valid for the job's state, or the manager is shutting down. | No |
| `QUOTA_EXCEEDED` | The submitter already holds its maximum of live jobs. §7.3 | No |
| `BAD_TOKEN` | The attached token cannot be a job identity. §7.5 | No |
| `INTERNAL_ERROR` | The manager failed while executing the command. | No |

`UNKNOWN_SERVICE`, `UNKNOWN_OPERATION` and `OPERATION_TIMEOUT` are
not emitted here: nothing on this channel names a service or an
operation, and a `wait` has no timeout of its own to expire.

## 7.10.1 Distinctions a submitter can rely on

**`UNKNOWN_JOB` versus `ACCESS_DENIED`.** A caller that may not query a
job receives `ACCESS_DENIED` for an identifier that exists, and
`UNKNOWN_JOB` for one that does not. This channel does not hide the
existence of a job from a caller that can name it: identifiers are
unguessable, and a caller that holds one was told it by something that
had it.

**`BAD_TOKEN` is about the token, never about the identity.** It says
the attached token is unusable — its level, its count, its rights —
and never that the submitter may not act as the principal it names.
That decision was the kernel's, made before the message arrived, and a
submitter that could not convey an identity never reaches the manager
with it.

**`QUOTA_EXCEEDED` created nothing.** No record, no event, no
consumption. A submitter MAY retry once one of its live jobs ends.

**`INVALID_STATE` during shutdown.** Once the manager is shutting
down it MUST reject `submit` with `INVALID_STATE` and MUST continue to
answer `status`, `wait`, `stop` and `signal`; a submitter watching its
jobs be stopped has a legitimate reason to keep looking, and a
submitter that wants a job stopped sooner than the shutdown will
manage has a legitimate reason to ask.

## 7.10.2 Codes are not extensible without a version

The manager MUST NOT introduce a new code without the negotiation in
§4.21, for the reason §4.10 gives: an unrecognized code silently turns
a handled condition into an unhandled one.

---

# 7.11 Extension

_Peios Specifications / PSPU / Job Submission_

> The jobs channel is extended under §4.21's rules — what may be added freely, what may not, and the two things that may never be added at all.

The jobs channel carries no version number, and is extended under the
rules of §4.21. They are not repeated; what follows is how they apply
here and what this chapter adds.

## 7.11.1 What may be added

A **request field**, including a new definition field on `submit`. A
manager MUST ignore a field it does not recognize, so a submitter MAY
send one and MUST NOT depend on its effect.

A **job view field**. A client MUST ignore a field it does not
recognize.

A **command**, and the error codes and enumerated values that appear
only in responses to it, on the terms §4.21 gives: a client that never
sends the command is never exposed to them.

## 7.11.2 What may not be added without a version

A **state**, a **cause**, a **progress unit**, or a **`for` value**
outside §7.B. A **command** changing what an existing command does. A
change to the **shape** of the job view. A new **error code** on an
existing command.

## 7.11.3 What may never be added

Two things are excluded from extension by any means, because their
absence is a security property of the channel rather than a gap in
it:

- **An identity field.** A `submit` MUST NOT be able to name the
  principal the job runs as. Every job identity is one the kernel
  verified the submitter could convey (§7.5), and a field that named
  one would be a path around that verification.
- **A policy field.** A `submit` MUST NOT be able to ask for a
  restart, a dependency, a health check or a trigger. A job that needs
  policy is a service, and a service is defined where an administrator
  controls it.

A revision that wanted either would not be a revision of this channel.

---

# 7.12 Conformance

_Peios Specifications / PSPU / Job Submission_

> Every requirement of this chapter collected by role — manager and submitter — and what a job owes, which is nothing this chapter did not already ask of a service.

## 7.12.1 A conforming manager

**The socket.** Listens on a Unix sequenced-packet socket at the
well-known path, close-on-exec on the listener and every accepted
connection, and ensures the socket and each directory containing it
carry a Security Descriptor admitting exactly the principals meant to
submit. Performs no access check of its own before a `submit` (§7.3).

**Messages.** Emits and accepts exactly one compact JSON object per
record, with no terminator. Receives every message with room for one
token and the maximum number of descriptors, answers a truncated
message or attachment list without acting on it, and closes every
attached descriptor it does not hand on or adopt, on every path (§7.4).

**Identity.** Establishes the submitter from the kernel once, at
accept. Installs on a job exactly one of: the connecting process's own
primary token, opened through the kernel's peer process handle; or
the token the kernel attached to the `submit`, duplicated to a
primary. Refuses a token below Impersonation level, more than one
token, or one it cannot duplicate, with `BAD_TOKEN`. Accepts no
identity by name and no primary token by plain descriptor (§7.5).

**Submission.** Validates the definition as §7.6 lists and refuses with
`INVALID_ARGUMENTS`; does not check that the program exists. Checks
identity and quota before creating any record. Answers a `submit` when
the job has left `created` and not before or after, with the job view,
attaching the process handle when the job is running (§7.6).

**The job view.** Reports every job in the one shape of §7.7, with
every inapplicable field present and null, the state-dependent
population rules honored, and the cause set only where the manager
decided the outcome. Holds a terminal record for the grace period and
answers a dropped or never-existent identifier `UNKNOWN_JOB` alike.

**Management.** Gives every job a descriptor — the default of §7.8 or
the one supplied — and checks every command against it with the
rights and mapping there, including commands from the submitter.
Implements `status`, `wait`, `stop` and `signal` with the semantics of
§7.8: a `wait` bounded only by the job, a `stop` that is a no-op on a
terminal job and does not restart a running deadline, a `signal`
delivered through the fork-time handle.

**Descriptors and output.** Injects attached descriptors from 3 upward
with `LISTEN_FDS`, `LISTEN_FDNAMES` and `LISTEN_PID` set; records the
job's output unconditionally; and, when asked, copies it to a
non-blocking sink, dropping for the sink only, counting and reporting
the drops, and closing the sink when the job ends (§7.9).

**Errors and extension.** Emits only the codes in §7.10, ignores
unrecognized request fields, and adds nothing from §7.11's closed
list — and never an identity or policy field — without a negotiated
version.

## 7.12.2 A conforming submitter

Connects as the identity it wants to own its jobs, and conveys any
other identity per message rather than by impersonating at connect.
Attaches at most one token, and sets its connection's level to
Delegation before attaching when the job needs it. Sends one compact
JSON object per record. Supplies every `LISTEN_FDNAMES` name it
attaches a descriptor for, and none containing `:`. Assumes the
manager owns every descriptor it attached. Treats an immediate close
with no response as a refusal. Does not parse `message`. Accepts null
for every nullable field and unrecognized fields in the job view.
Treats an unrecognized state, cause, unit or error code as an error
for that request rather than guessing. Reads `state` rather than
`cause` to decide whether a job succeeded. Uses `stop` to end a job
and `signal` only to signal it. Does not depend on a job's record
surviving its grace period.

## 7.12.3 A conforming job

Nothing beyond §4.22's requirements of a service on the notification
channel. A job that sends progress does so in the form §4.19 defines.
A job that adopts descriptors checks `LISTEN_PID` first.

## 7.12.4 What conformance is not

A manager that offers the control channel and not this one is still a
conforming manager under §4. This chapter is the contract for one that
offers both.

---

# Appendix 7.A Limits and Defaults

_Peios Specifications / PSPU / Job Submission_

> The limits and defaults a Peios service manager uses on the jobs channel, and which of them are configurable.

The values a Peios service manager uses. A manager MAY use different
ones; where a value is configurable, it MUST be discoverable to an
administrator through the same surface that sets it.

## 7.A.1 The socket

| Bound | Value | Configurable | Defined in |
|---|---|---|---|
| Socket path | `/run/services/peinit/jobs.sock` | No | §7.3 |
| Socket descriptor, default | Connect for Authenticated Users (`S-1-5-11`); full control for SYSTEM and Administrators | Yes | §7.3 |
| Concurrent connections | 64 | Yes | §7.3 |
| Message size | 65536 bytes | Yes | §7.3 |
| Idle timeout | 30 seconds | Yes | §7.3 |
| Listen backlog | 32 | No | §7.3 |
| Live jobs per submitter | 64; SYSTEM exempt | Yes | §7.3 |

## 7.A.2 Attachments

| Bound | Value | Defined in |
|---|---|---|
| Tokens per message | 1 | §7.4 |
| Descriptors per message | 64, including an output sink | §7.4 |
| First injected descriptor | 3 | §7.9 |

## 7.A.3 The definition

| Field | Default | Defined in |
|---|---|---|
| `stop_timeout` | 10 seconds | §7.6 |
| `readiness_timeout` | 30 seconds | §7.6 |
| `timeout` | 0, no limit | §7.6 |
| `working_directory` | `/` | §7.6 |

## 7.A.4 Records

| Bound | Value | Defined in |
|---|---|---|
| Terminal record retention | 60 seconds | §7.7 |

The retention value is the control channel's operation retention
(§4.A), for the same reason: a client polling once a second must never
find the outcome gone.

## 7.A.5 Composing with the control channel

A job's `status_text` and `progress` come from datagrams on the
notification channel, whose bound is §4.A's 65536 bytes; the job view
is not bounded by the jobs channel's message size on the way out, so
a status a job can send is always one the manager can return.

The message-size bound applies to a `submit` and therefore to the sum
of its definition: a program with a very large `environment` or
`arguments` list is bounded here before it is bounded by `execve`.

---

# Appendix 7.B Wire Vocabulary

_Peios Specifications / PSPU / Job Submission_

> Every enumerated value on the jobs channel — commands, job state, cause, readiness, wait condition and progress unit.

Every enumerated value that appears on the jobs channel. All are lower
snake case. A manager MUST NOT emit a value outside these sets without
the negotiation in §4.21, and a submitter MUST treat one it does not
recognize as an error for that request rather than mapping it onto a
value it knows.

Values shared with the control channel — response status, job type —
are §4.B's and are not restated.

## 7.B.1 Command

`submit`, `status`, `wait`, `stop`, `signal`

## 7.B.2 Job state

| Value | Process? | Terminal? |
|---|---|---|
| `created` | Not yet | No |
| `running` | Yes | No |
| `completed` | No | Yes |
| `failed` | No | Yes |
| `abandoned` | Yes, unkillably | Yes |

`created` is never reported on this channel (§7.6). It appears here
because the control channel's `job-list` may show it for a job whose
submit is still in flight.

## 7.B.3 Cause

`parent_setup_failure`, `pre_exec_failure`, `readiness_timeout`,
`timeout`, `explicit_stop`, `shutdown`, `process_unkillable`

`cause` is null when the process ended of its own accord.

## 7.B.4 Readiness

`none`, `notify`

Request-only, on `submit`. The job view reports readiness through
`ready`, not by echoing this.

## 7.B.5 Wait condition

`terminal`, `ready`

Request-only, the `for` field of `wait`.

## 7.B.6 Progress unit

`bytes`, `items`, `percent`

The vocabulary of `PROGRESS_UNIT` (§4.19), reported in the job view's
`progress.unit`. Null when the job sent none.

---

# 8.1 Scope and Roles

_Peios Specifications / PSPU / Security Descriptor Editing_

> The interface by which a program has a person edit the Security Descriptor of an object it holds, in an editor that is a program of its own and never touches the object.

This chapter defines the **editing channel**: the interface by which a
program has a person edit the Security Descriptor of an object the
program holds, in a dialog drawn by another program, the **editor**.

The object may be of any kind that has a Security Descriptor — a file,
a registry key, a service. The editor knows none of them. What it is
told is what a person needs in order to edit the descriptor: what the
object is called, what kind of thing it is, what its rights are called,
and the descriptor itself. What it answers with is a descriptor.

## 8.1.1 Roles

**The requester** is the program whose object it is. It starts the
editor, reads the object's descriptor, tells the editor about it, and
applies each descriptor the editor sends back. It holds the object, and
whatever right changing the descriptor takes, throughout.

**The editor** draws the descriptor for a person to change, on the
desktop the requester is on, and sends back what they apply. It holds
no handle to the object and needs no right over it. It changes nothing
itself.

The split is deliberate. The party that can change the object is the
one that already holds it, and it applies exactly what it is sent, so
an editor serves every kind of object without ever being trusted with
one. A requester gains a full editor without containing one.

> [!NOTE]
> The arrangement is the one Windows' security editor uses, where the
> caller implements the object's side (`ISecurityInformation`: the
> descriptor, the rights' names, applying) and the editor draws. Here
> the editor is a separate process rather than a library, so that it
> serves a requester in any language, and a fault in it is its own.

## 8.1.2 What this chapter leaves to others

How the editor draws its dialog, and on which desktop, is the editor's
own design and that desktop's. On a GXWI desktop the editor is an app
like any other, found by the environment it inherits from the
requester.

The layout of a Security Descriptor, of the access masks it carries
and of its entries is PCDS §5's. This chapter carries descriptors and
says nothing about their contents beyond which components are applied.

How a requester reads and applies a descriptor is its own concern, and
depends on the kind of object. A requester SHOULD apply through the
same handle it read through, so that what is applied reaches the object
that was shown, wherever it has gone in the meantime.

---

# 8.2 Terminology

_Peios Specifications / PSPU / Security Descriptor Editing_

> Terms this chapter defines for itself — requester, editor, line, request, component, general right — and the ones it takes from PCDS.

Security Descriptor, access mask, ACE, DACL, SACL, owner, group, and
generic right are used with PCDS §5's meanings and are not redefined.

**Requester.** The program whose object's descriptor is being edited,
and which started the editor. §8.1

**Editor.** The program that shows the descriptor to a person and
sends back what they apply. §8.1

**Line.** One message on the editing channel: a single compact JSON
object, encoded as UTF-8, followed by a line feed (U+000A). §8.3

**Request.** The first line the requester sends: everything the editor
is told about the object. §8.4

**Component.** One of the five separately applicable parts of a
Security Descriptor: the owner, the group, the DACL, the SACL and the
label. The label is the SACL's mandatory integrity label alone, which
KACS applies apart from the rest of the SACL and with a different right
(KACS set-security). On the channel they are named `owner`, `group`,
`dacl`, `sacl` and `label`.

**General right.** A right the requester names for a person to grant
or deny in one step, such as "Read" or "Full control", standing for an
access mask that may have many bits. The requester decides which rights
are general and what each stands for. §8.4

**Applying.** The requester writing components of a descriptor the
editor sent onto the object. §8.5

---

# 8.3 The Channel

_Peios Specifications / PSPU / Security Descriptor Editing_

> The editor's standard input and output, one JSON object a line; who starts whom; and how either end knows the other has gone.

## 8.3.1 Starting the editor

The requester MUST start the editor as a child process of its own, with
the editor's standard input and standard output connected to it. It
SHOULD start the editor with its own environment, which is how the
editor finds the desktop to draw on.

The editor's standard error is not part of the channel. The editor MAY
write diagnostics there for an administrator, and the requester MUST
NOT read meaning into them.

## 8.3.2 Lines

Each direction is a sequence of lines (§8.2): one compact JSON object,
UTF-8, then a line feed. A line MUST NOT contain a line feed before its
end; compact JSON never needs one.

- Requester to editor, on the editor's standard input: the request
  (§8.4), first and exactly once, then one answer for each `apply`
  (§8.5), and `raise` (below) whenever the person asks for the object
  again.
- Editor to requester, on the editor's standard output: `apply`
  messages (§8.5), and nothing else in this revision.

Every line carries a `type` member naming what it is, except the
request, which is identified by being first.

A party MUST ignore a line whose `type` it does not recognize, and a
member of an object it does not recognize (§8.7). A party MAY refuse a
line longer than 1 MiB; a request carrying a descriptor of the largest
size PCDS §5.1 permits is well inside it.

## 8.3.3 Asked for again

A requester that the person asks to edit an object it already has an
editor open on SHOULD NOT start a second editor for it: two dialogs on
one object would each apply over the other. It SHOULD instead send

```
{"type":"raise"}
```

which needs no answer. An editor that receives it SHOULD bring its
dialog to the front and give it the keyboard, as far as the desktop
lets it. An editor that does not recognize it ignores it, as any line,
so a requester MUST NOT depend on the dialog coming forward. A requester
whose write of `raise` fails has learned the editor has gone, and MAY
start a new one.

## 8.3.4 Ending

The channel ends when either party closes its end, and either party can
tell when the other has.

**The editor ends** when the person closes or cancels the dialog, and
after the person confirms once what it sent has been applied (§8.5). It
ends by exiting, which closes its standard output; the requester reading
end-of-file there is how it knows. An editor that ends sends nothing
more and applies nothing, since it never could.

**The requester ends**, or gives up on the editor, by closing the
editor's standard input. The editor MUST end promptly when it reads
end-of-file there, whatever it is doing, and MUST NOT ask the person
anything first: the requester can no longer apply what they would say.
A requester that exits closes the editor's input whether it means to or
not, so the editor goes with it.

The editor SHOULD also arrange to be signaled when its parent exits
(on Linux, `PR_SET_PDEATHSIG`), and end then. A process whose parent
exits is not ended by that, and an editor left showing a dialog for an
object nobody can apply to is worse than none.

The editor's exit status says nothing about what was applied. The
requester knows that from its own answers (§8.5), and MUST NOT infer it
from the status.

---

# 8.4 The Request

_Peios Specifications / PSPU / Security Descriptor Editing_

> The first line the requester sends — the object, its descriptor, what its rights are called, what its generic rights mean, and which components it can change.

The request is the first line on the editor's standard input, and the
only one that has no `type`. It is one JSON object:

| Member | Type | Required | Meaning |
|---|---|---|---|
| `object` | object | Yes | What the descriptor is the descriptor of. |
| `object.name` | string | Yes | What the object is called where the person found it: `notes.txt`, not a full path, unless a path is how they know it. |
| `object.kind` | string | Yes | What kind of thing it is, in words for the person: `File`, `Folder`, `Service`. |
| `object.container` | boolean | No, `false` | Whether other objects inherit from it (PCDS §5.6). |
| `object.children` | string | No, `"all"` | What a container holds, which is what the entries made for it are passed on to: `all` or `containers` (see [Containers](#containers)). Ignored unless `container` is true. |
| `object.parent` | object | No | What the object is in, which its inherited entries come from (see [The parent](#the-parent)). |
| `object.parent.name` | string | Yes, in `parent` | What the parent is called where the person knows it: `/srv`. |
| `object.parent.sd` | string | No | The parent's descriptor, self-relative and in base64 as `sd` is. |
| `object.parts` | array | No, empty | The object's parts that rules can be made for one at a time: object types (see [Parts and kinds](#parts-and-kinds)). |
| `object.parts[].guid` | string | Yes | The object type, as a GUID in its usual text form: `bf967aba-0de6-11d0-a285-00aa003049e2`. |
| `object.parts[].name` | string | Yes | What the part is called, for the person. |
| `object.parts[].kind` | string | Yes | `set`, a set of properties; `property`; or `right`, an action. |
| `object.parts[].set` | string | No | For a property, the GUID of the set it is in. |
| `object.kinds` | array | No, empty | On a container of typed things, the kinds of thing it holds: inherited object types. |
| `object.kinds[].guid`, `.name` | string | Yes | The inherited object type, and what that kind of thing is called. |
| `object.part_rights` | array | No, empty | The rights a rule for a part can give, as `rights` gives the object's (see [Parts and kinds](#parts-and-kinds)). |
| `object.part_rights[].name`, `.mask` | string, number | Yes | What the right is called, and its access mask. |
| `object.naming` | object | No | How a part not listed is named (see [Parts named by the person](#parts-named-by-the-person)). |
| `object.naming.namespace` | string | Yes, in `naming` | The UUID v5 namespace a part's object type is derived in, as a GUID in its usual text form. |
| `object.naming.noun` | string | Yes, in `naming` | What one such part is called, for the person: `field`. |
| `object.naming.example` | string | No | A name the person might give, to show how one is written: `source.name`. |
| `sd` | string | Yes | The descriptor as it is now: a self-relative Security Descriptor (PCDS §5.1), in base64 with padding (RFC 4648 §4). |
| `read` | array of strings | No | The components `sd` holds as they are on the object: some of `owner`, `group`, `dacl`, `sacl` and `label` (see [The descriptor](#the-descriptor)). Left out, every component `sd` has. |
| `rights` | array | Yes | The object's rights by name, in the order a person should see them. |
| `rights[].name` | string | Yes | What the right is called. |
| `rights[].mask` | number | Yes | The access mask the right stands for, as an unsigned 32-bit integer. |
| `rights[].general` | boolean | No, `false` | Whether it is a general right (§8.2). |
| `generic` | object | Yes | What each generic right stands for on this kind of object (PCDS §5.3). |
| `generic.read`, `.write`, `.execute`, `.all` | number | Yes | The access mask each generic right maps to. |
| `can` | object | No | Which components the requester is able to change. |
| `can.dacl` | boolean | No, `true` | Whether it can change the DACL. It is true when left out because, before this member, a requester always could. |
| `can.owner` | boolean | No, `false` | Whether it can change the owner. |
| `can.audit` | boolean | No, `false` | Whether it can change the SACL. |
| `can.label` | boolean | No, `false` | Whether it can apply the label by itself (§8.5). |
| `can.propagate` | boolean | No, `false` | Whether, on a container, it can push what was applied into what is already inside (§8.5, Pushing into what is inside). |
| `can.why` | string | No | Why the requester cannot change what `can` says it cannot, as text for the person. |

## 8.4.1 The descriptor

The requester SHOULD include the owner, the group and the DACL. It MAY
leave out the SACL: reading a SACL takes ACCESS_SYSTEM_SECURITY, which
a requester need not have. It SHOULD include the label where it can
read it, which takes only READ_CONTROL. A requester that could read the
label and not the rest of the SACL sends a SACL holding the label
alone, and MUST then say so in `read`, naming `label` and not `sacl`.

The editor MUST NOT take a SACL for the whole SACL unless `read` names
`sacl` or is left out. Where it is only the label, the editor MUST NOT
show it as an object with no auditing, claims or policies, since those
are not known.

A descriptor with no DACL component means one with no access list,
which PCDS §5.1 treats as granting everyone everything. The editor MUST
show it as such and not as an empty list, which grants nobody anything.

## 8.4.2 The parent

`object.parent` names what the object's inherited entries come from,
for the person: "Inherited from /srv". An editor that offers to stop
inheriting MAY offer to inherit again, but KACS does not pass a
parent's entries down again by itself when protection is turned off
(PCDS §5.6): the editor works out what is passed down from
`object.parent.sd`, and SHOULD NOT offer to inherit again without it.
A requester SHOULD send the parent's descriptor where it can read it.

## 8.4.3 Parts and kinds

`object.parts` lists the object types (PCDS §5.4) a rule can be made
for, as an account's sign-in details or the action of resetting its
password. `object.kinds` lists, for a container of typed things, the
kinds of thing it holds, which an entry can be passed on to alone. An
editor MAY offer rules for parts and kinds only where they are listed,
and MUST keep as it found it an entry naming a GUID it is not told of.

`object.part_rights` names what a rule for a part can give. Left out,
an editor offers what a directory's parts take: reading and writing a
property, and using an action. A requester whose parts take other rights
MUST send them. eventd's fields, for example, take only its Read.

### 8.4.3.1 Parts named by the person

Some objects have more parts than can be listed, each one's object type
derived from its name. eventd's fields are an example: a payload field
needs no registration, and its GUID is derived from its name (eventd TRM
§7.3). `object.naming` tells the editor how such a part is named. Its
object type is the UUID v5 (RFC 9562 §5.5) of the name, as UTF-8, in
`naming.namespace`, and it is a property.

An editor MAY then let the person name a part beside those listed. It
MUST derive the object type exactly so, and SHOULD show the part by the
name given for as long as the dialog is open. A requester SHOULD still
list in `parts` the ones it knows, so that an existing rule for one is
shown by name.

## 8.4.4 The rights

`rights` names every right the requester wants a person to see.
General rights SHOULD come first, from the one granting the most to the
one granting the least, so that a right that includes another is above
it. The masks of two rights MAY overlap, and typically do: "Modify"
includes "Read".

An editor that shows general rights as boxes to tick SHOULD show as a
whole what a mask it cannot express in them — a mask with bits outside
every general right it contains, an entry of a type it does not edit,
or inheritance flags other than its own — rather than leave it unshown,
and SHOULD keep such an entry as it found it.

`generic` lets the editor read an entry that grants generic rights
(PCDS §5.3) as the rights they stand for. The requester MUST give the
mapping its kind of object actually uses.

## 8.4.5 Containers

On a container, the entries an editor makes apply to the container and
are passed on to what it holds. `object.children` says what that is,
and so which inheritance flags (PCDS §5.6) those entries carry:

| Value | Holds | Flags of an entry made here |
|---|---|---|
| `all` | Containers and other objects, as a folder holds folders and files. | Object inherit and container inherit. |
| `containers` | Containers alone, as a registry key holds keys and nothing else. | Container inherit. |

An entry with other inheritance flags is one the editor cannot express
in its general rights (above), and is shown as a whole and kept.

## 8.4.6 What the requester can change

`can` says what the requester is able to change. It MUST NOT say it
can change a component it cannot. `can.label` is true only where it can
apply the label by itself, which takes WRITE_OWNER and, for a level
above the caller's own, SeRelabelPrivilege (KACS set-security). It SHOULD find out by asking the
system, for example by an AccessCheck of the person's token against the
descriptor, or by opening the object for the rights that changing it
takes. It SHOULD NOT infer it from the person's group memberships.

`can.propagate` is true only on a container whose requester holds what
is inside it and can walk it: a file explorer for a folder, a registry
editor for a key. It says nothing about whether each item inside can be
changed, which is found out item by item as the walk goes (§8.5).

A requester that cannot change the DACL still sends it, so that the
person can read it. The editor MUST then show the DACL without offering
to change it, and SHOULD say why, with `can.why` if it was given. An
editor whose requester can change nothing SHOULD offer only to close.

## 8.4.7 Validation

An editor that cannot use the request — one that is not a JSON object,
lacks a required member, or carries an `sd` that is not a Security
Descriptor — MUST NOT show a dialog. It SHOULD write why to its
standard error, and MUST end (§8.3).

---

# 8.5 Applying

_Peios Specifications / PSPU / Security Descriptor Editing_

> The editor sends the whole descriptor and which components changed, only when the person says to; the requester applies exactly those, and answers once.

## 8.5.1 `apply`

When the person asks for what they have done to take effect — Apply,
or OK — the editor sends:

| Member | Type | Meaning |
|---|---|---|
| `type` | `"apply"` | |
| `sd` | string | The whole descriptor as the person now has it, self-relative and in base64 as in the request (§8.4). |
| `parts` | array of strings | The components of `sd` that changed since the request, or since the last `apply` the requester answered `applied`: some of `owner`, `group`, `dacl`, `sacl`, `label`. |
| `propagate` | boolean | Optional, `false` when left out. Once `parts` is applied, push what the object now passes down into what is already inside it (see [Pushing into what is inside](#pushing-into-what-is-inside)). |

The editor MUST NOT send an `apply` as the person changes things, only
when they ask for it. A descriptor applied part way through a change
can take away the access the person needs to finish it: denying
Everyone before granting oneself, say.

The editor MUST NOT name `dacl` in `parts` unless the request's
`can.dacl` was true or left out, nor `owner` or `group` unless
`can.owner` was true, nor `sacl` unless `can.audit` was and the request
held the whole SACL, nor `label` unless `can.label` was. It MUST NOT
send `propagate` true unless `can.propagate` was, nor without the
person having chosen it for this `apply`. It MUST NOT send an `apply`
while one is unanswered, and SHOULD NOT send one whose `parts` is
empty. It MAY send one whose `parts` names components that have not
changed since they were applied, with `propagate` true, to push them
into what is inside again (after a walk was stopped or some of it
failed): applying them again changes nothing.

## 8.5.2 The label

The label is in the SACL, and `sacl` carries it: a changed label goes
with a changed SACL. `parts` MUST NOT name both `sacl` and `label`,
which KACS refuses to apply together (KACS set-security). `label` names
the label alone, where the rest of the SACL has not changed or cannot
be applied: the SACL of `sd` then holds the label that is to be the
object's, or none to remove it, and the requester applies it as a label
(LABEL_SECURITY_INFORMATION), which keeps the rest of the object's SACL
as it is. A requester that keeps a descriptor whole, as a registry value,
puts the label into the SACL it has, in place of the label there.

## 8.5.3 The answer

The requester MUST answer every `apply` with exactly one line, in the
order they came:

| Line | Meaning |
|---|---|
| `{"type":"applied"}` | Every component in `parts` was applied. Where `propagate` was true, it carries how pushing into what is inside went (below). |
| `{"type":"failed","why":"…"}` | None was, or not all, and `why` says why, as text for the person. Nothing was pushed into what is inside. |

The requester MUST apply the components named in `parts`, and MUST NOT
apply any other component of `sd`. The rest is as the requester sent
it, or as the editor could not read it, and writing it back would at
best change nothing and at worst write over what changed meanwhile.

The requester SHOULD apply the named components in one operation where
the kind of object allows it. Where it cannot, and some were applied
and some were not, it MUST answer `failed` and SHOULD say which were
applied.

`why` is shown to the person as it stands. It SHOULD say what was in
the way in words they can act on — "you are not allowed to" — rather
than an error code.

## 8.5.4 Pushing into what is inside

Inheritance is eager (PCDS §5.6): what a container passes down reaches
the things made inside it afterwards, and the things already there keep
what they were given. Where the person changes what a container passes
down, the editor SHOULD ask whether to update what is already inside
too, and, where they say yes, sends the `apply` with `propagate` true.

A requester sent `propagate` true first applies `parts` as above. If it
answers `failed`, it pushes nothing. Otherwise, before it answers, it
re-propagates everything inside the object as PCDS §5.6 sets out
(Re-propagation), for the lists `parts` names: the DACL for `dacl`, the
SACL for `sacl`, and for `label` the SACL as far as it holds labels,
read and applied as labels. In particular it MUST:

- go parents first, re-propagating each item from its parent as just
  rewritten;
- leave a list an item protects exactly as it is, and still re-propagate
  what is inside that item from it as it is;
- resolve CREATOR OWNER and CREATOR GROUP against each item's own owner
  and group, and map generic rights through the generic mapping of the
  kind of thing it holds;
- change no component of an item but the lists it re-propagates;
- follow no link out of the tree;
- carry on past an item it cannot read or change, noting it, and leave
  what is inside that item as it is.

The editor sends nothing for the items inside: what each gets is worked
out by the requester, from the object as it now is.

While it walks, the requester MAY send:

| Line | Meaning |
|---|---|
| `{"type":"progress","done":n,"at":"…"}` | `done` items have been re-propagated, the last being `at`, by what the person knows it as. |

It needs no answer. A requester SHOULD send one now and then on a long
walk, and SHOULD NOT send them more often than a person can read.

The editor MAY send, while it waits for the answer to an `apply` with
`propagate` true:

| Line | Meaning |
|---|---|
| `{"type":"stop"}` | Stop the walk after the item in hand. |

It needs no answer of its own: the requester stops, and answers the
`apply` as it would have at the end. What was re-propagated stays so.
End-of-file on the requester's input from the editor means the same.

The `applied` answer to an `apply` with `propagate` true carries:

| Member | Type | Meaning |
|---|---|---|
| `done` | number | How many items inside were re-propagated, those that protect every list included. Left out, none. |
| `failed` | array | The items that could not be, each `{"name":"…","why":"…"}`: what the person knows it as, and why, as text for the person. Left out, none. |
| `stopped` | boolean | Whether the walk was stopped before the end. Left out, it was not. |

Each of these concerns the items inside, not the object: `applied`
still means the object's `parts` were all applied. The editor SHOULD
show how far the walk got, a way to stop it, and afterwards what could
not be done, and SHOULD NOT end on an apply-and-close whose walk failed
for some items or was stopped, so that the person sees it.

## 8.5.5 After the answer

On `applied`, the editor takes what it sent as the descriptor it is
editing from then on: a later `apply` names only what changed after.
If the person had asked to apply and close, the editor ends (§8.3).

On `failed`, the editor MUST show the person `why` and MUST NOT end
because of it: what they did is still there to be put right or
abandoned. What it has not had answered `applied` it still counts as
changed.

---

# 8.6 Extension

_Peios Specifications / PSPU / Security Descriptor Editing_

> The editing channel carries no version number; what may be added to it, what may not without one, and the one thing that may never be.

The editing channel carries no version number. It grows by addition,
under these rules.

## 8.6.1 What may be added

A **member** of the request, or of any line. A party MUST ignore a
member it does not recognize, so a requester MAY send one and MUST NOT
depend on its effect.

A **line type**, in either direction, that the other party may ignore
and still conform: a party MUST ignore a `type` it does not recognize
(§8.3). A line that needs an answer MUST NOT be added this way, since
an editor waiting on an answer from a requester that ignored the
question would wait for ever.

## 8.6.2 What may not be added without a version

A change to the meaning of an existing member or line. A component name
beyond the five of §8.2. An answer to `apply` other than the two of
§8.5.

The fifth, `label`, was added without a version because nothing can
send it to a requester that does not know it: an editor names it only
for a requester that said `can.label`, which an older requester never
says.

Pushing into what is inside was added the same way. An editor sends
`propagate` only to a requester that said `can.propagate`. `progress`
and `stop` are lines that need no answer. What `applied` carries about
the walk is members of it, and `applied` still means only that the
object's `parts` were applied.

`object.part_rights` and `object.naming` were added as optional members
of the request. An editor that does not know `naming` offers only the
parts listed. An editor that does not know `part_rights` offers a
directory's rights for a part, which may not be rights the object's
parts take. For eventd's fields they aren't, so such a rule gives
nothing.

`raise` (§8.3) was added as a line that needs no answer. An older
editor ignores it, and its dialog stays where it is.

## 8.6.3 What may never be added

**A way for the editor to apply.** Nothing on the channel may let the
editor change the object itself, or ask the requester to apply anything
but a descriptor the person asked to apply. That the editor holds
nothing and is trusted with nothing is what lets a requester open it on
any object, and the requester applying exactly what it is sent is the
whole of the contract between them.

Pushing into what is inside keeps to this. The editor sends no
descriptor for anything but the object, and `propagate` asks only for
what PCDS §5.6 says re-propagation of the object's descriptor is, which
the requester works out itself from the object as it applied it. The
editor cannot choose what any item inside gets.

---

# 8.7 Conformance

_Peios Specifications / PSPU / Security Descriptor Editing_

> Every requirement of this chapter collected by role — the requester and the editor.

## 8.7.1 A conforming requester

**Starting.** Starts the editor as its own child with the editor's
standard input and output connected to it, and sends the request as the
first line (§8.3).

**The request.** Sends every required member, a self-relative
descriptor in padded base64, the general rights from the most to the
least, and the generic mapping its kind of object actually uses. On a
container, says in `object.children` what it holds. Says in `can` only
what it can in fact change, having asked the system. Says in `read`
which components it sent where that is not everything `sd` has, as a
SACL holding only the label (§8.4).

**Applying.** Answers every `apply` with exactly one line, in order.
Applies the components `parts` names and no others, and the label as a
label, keeping the rest of the SACL. Answers `applied` only when all of
them were, and otherwise `failed`, with a reason for the person (§8.5).

**Pushing into what is inside.** Says `can.propagate` only on a
container it can walk. Asked to, after applying, re-propagates
everything inside as PCDS §5.6 sets out, for the lists `parts` names:
parents first, protected lists left, nothing changed but those lists, no
link followed, past an item it cannot change. Stops after the item in
hand on `stop` or end-of-file, and answers `applied` with how many were
done, which could not be and why, and whether it was stopped (§8.5).

**Lines.** Ignores a line type and a member it does not recognize
(§8.3). Infers nothing from the editor's exit status or standard error
(§8.3).

## 8.7.2 A conforming editor

**Starting.** Shows no dialog for a request it cannot use, and ends
(§8.4).

**Showing.** Shows a descriptor without a DACL as granting everyone
everything, never as an empty list. Shows what it cannot express in the
general rights as a whole, and keeps such entries as it found them.
Gives the entries it makes on a container the inheritance flags of what
the container holds. Shows a DACL the requester cannot change without
offering to change it. Takes a SACL for the whole SACL only where
`read` says it is (§8.4).

**Applying.** Sends an `apply` only when the person asks, with the
whole descriptor and the components that changed, never `dacl`,
`owner`, `group`, `sacl` or `label` it was not told it could, never
`sacl` and `label` together, and never while one is unanswered.
Shows a `failed` answer's reason and stays (§8.5). Sends `propagate`
only to a requester that said `can.propagate`, and only where the person
chose it (§8.5).

**Changing nothing.** Holds no handle to the object and changes nothing
itself (§8.1, §8.6).

**Ending.** Ends when the person closes or cancels, after an `applied`
answer to an apply-and-close, and promptly on end-of-file on its
standard input, without asking the person anything. SHOULD also end
when its parent exits (§8.3).

---

# Appendix 8.A Message Reference

_Peios Specifications / PSPU / Security Descriptor Editing_

> Every line on the editing channel, in order, with an example conversation.

| Direction | Line | Defined in |
|---|---|---|
| Requester → editor | The request (first line, no `type`) | §8.4 |
| Editor → requester | `{"type":"apply","sd":…,"parts":[…],"propagate":…}` | §8.5 |
| Requester → editor | `{"type":"progress","done":…,"at":…}` (while pushing into what is inside; no answer) | §8.5 |
| Editor → requester | `{"type":"stop"}` (while pushing into what is inside; no answer) | §8.5 |
| Requester → editor | `{"type":"applied","done":…,"failed":[…],"stopped":…}` (the last three only after pushing) | §8.5 |
| Requester → editor | `{"type":"failed","why":…}` | §8.5 |
| Requester → editor | `{"type":"raise"}` (the object asked for again; no answer) | §8.3 |

## 8.A.1 An example

A file explorer opens the permissions of a file. The person adds
Everyone with Read and presses Apply, which fails, then changes their
mind and closes the dialog. Lines are shown on several lines here for
reading. On the channel each is one line, and the descriptors are
shortened.

```
→ {"object":{"name":"notes.txt","kind":"File","container":false,
             "parent":{"name":"/home/dana","sd":"AQAEgBQAAAAkAAAA…"}},
   "sd":"AQAEgBQAAAAkAAAAAAAAADQAAAAB…",
   "read":["owner","group","dacl","label"],
   "rights":[{"name":"Full control","mask":2032127,"general":true},
             {"name":"Read","mask":1179785,"general":true}],
   "generic":{"read":1179785,"write":1179926,"execute":1179808,"all":2032127},
   "can":{"owner":true,"audit":false,"label":true}}
← {"type":"apply","sd":"AQAEgBQAAAAkAAAAAAAAADQAAAAC…","parts":["dacl"]}
→ {"type":"failed","why":"you are not allowed to"}
```

The editor shows why and stays open. The person closes it, and the
requester reads end-of-file on the editor's output.

The requester could read the label but not the rest of the SACL, so
`read` names `label` and not `sacl`, and the SACL in `sd` holds the
label alone. Had the person raised the label, the editor would have
sent `"parts":["label"]`.

## 8.A.2 Pushing into what is inside

The same explorer opens a folder's permissions, saying it can push into
what is inside. The person gives Finance Modify on the folder and
everything in it, presses OK, says yes to updating what is already
inside, and stops partway.

```
→ {"object":{"name":"finance","kind":"Folder","container":true}, …,
   "can":{"owner":true,"audit":true,"label":true,"propagate":true}}
← {"type":"apply","sd":"AQAEnBQAAAAkAAAA…","parts":["dacl"],"propagate":true}
→ {"type":"progress","done":120,"at":"/srv/finance/2025/q3.xlsx"}
→ {"type":"progress","done":480,"at":"/srv/finance/2026/budget"}
← {"type":"stop"}
→ {"type":"applied","done":512,
   "failed":[{"name":"/srv/finance/archive","why":"you are not allowed to"}],
   "stopped":true}
```

The folder's DACL was applied, and 512 items inside were updated before
the walk stopped. The editor shows that, and what could not be done, and
stays open though OK was pressed. The person can push the rest with
another `apply` of the same `parts`.

---

# 9.1 Scope and Roles

_Peios Specifications / PSPU / File Choosing_

> The interface by which a program has a person choose a file to open, a place and a name to save to, or a folder, in a dialog that is a program of its own and never opens the file.

This chapter defines the **choosing channel**: the interface by which a
program has a person choose a file, either an existing one to read or a
place and a name to write to, or an existing folder, in a dialog drawn by
another program, the **chooser**.

The chooser knows nothing of what the file is for. It is told what to
call the dialog, what the file is for in words, where to start, and what
kinds of file to offer. What it answers with is a path, or that the
person chose nothing.

## 9.1.1 Roles

**The requester** is the program that wants a file. It starts the
chooser, says what it wants, and, given a path, opens, reads, creates or
writes the file itself.

**The chooser** shows the person's folders and lets them pick a file or
type a name, and answers with the path. It runs as the same person as
the requester, and, as a small file manager, lets them make a folder and
rename and delete as themselves. It never opens the chosen file, and
hands the requester nothing but a path.

The split mirrors §8's. The party that will use the file is the one that
opens it, with its own token, so the chooser is trusted with nothing it
could misuse, and serves any requester without knowing what files are
for.

## 9.1.2 What this chapter leaves to others

How the chooser draws its dialog, and on which desktop, is the chooser's
own design and that desktop's. On a GXWI desktop the chooser is an app
like any other, found by the environment it inherits from the requester.

What the person may do with files and folders is KACS's to decide, as it
is for any program of theirs. This chapter says only that the chooser
asks the system rather than guessing (§9.6).

What a requester does with the file, and in what format, is its own
concern.

---

# 9.2 Terminology

_Peios Specifications / PSPU / File Choosing_

> Terms this chapter defines for itself — requester, chooser, line, request, answer, mode, filter.

**Requester.** The program that wants a file chosen, and which started
the chooser. §9.1

**Chooser.** The program that shows the person's folders and answers
with the file they choose. §9.1

**Line.** One message on the choosing channel: a single compact JSON
object, encoded as UTF-8, followed by a line feed (U+000A). §9.3

**Request.** The first line the requester sends: everything the chooser
is told about what is wanted. §9.4

**Answer.** The one line the chooser sends: the path chosen, or that
nothing was. §9.5

**Mode.** Whether an existing file is to be opened (`open`) or a place
and a name to be saved to (`save`). §9.4

**Filter.** A kind of file the requester offers, named for the person
and given as a list of extensions. §9.4

---

# 9.3 The Channel

_Peios Specifications / PSPU / File Choosing_

> The chooser's standard input and output, one JSON object a line; who starts whom; and how either end knows the other has gone.

## 9.3.1 Starting the chooser

The requester MUST start the chooser as a child process of its own, with
the chooser's standard input and standard output connected to it. It
SHOULD start the chooser with its own environment, which is how the
chooser finds the desktop to draw on, and the person's home folder.

The chooser's standard error is not part of the channel. The chooser MAY
write diagnostics there for an administrator, and the requester MUST
NOT read meaning into them.

## 9.3.2 Lines

Each direction is a sequence of lines (§9.2): one compact JSON object,
UTF-8, then a line feed. A line MUST NOT contain a line feed before its
end.

- Requester to chooser, on the chooser's standard input: the request
  (§9.4), first and exactly once, and nothing else in this revision.
- Chooser to requester, on the chooser's standard output: the answer
  (§9.5), at most once, and nothing else in this revision.

The answer carries a `type` member naming what it is. The request is
identified by being first.

A party MUST ignore a line whose `type` it does not recognize, and a
member of an object it does not recognize (§9.7). A party MAY refuse a
line longer than 1 MiB.

## 9.3.3 Ending

**The chooser ends** once it has answered, and when the person closes or
cancels the dialog, which it answers as `cancelled` first. It ends by
exiting, which closes its standard output.

**The requester ends**, or gives up on the chooser, by closing the
chooser's standard input. The chooser MUST end promptly when it reads
end-of-file there, without answering and without asking the person
anything: nobody is left to use the answer. A requester that exits
closes the chooser's input whether it means to or not, so the chooser
goes with it. The chooser SHOULD also arrange to be signaled when its
parent exits (on Linux, `PR_SET_PDEATHSIG`), and end then.

A requester that reads end-of-file on the chooser's output with no
answer MUST treat it as `cancelled`. It MUST NOT infer anything from the
chooser's exit status.

---

# 9.4 The Request

_Peios Specifications / PSPU / File Choosing_

> The first line — whether to open, save or choose a folder, what the dialog is called and what the choice is for, where to start, the name to suggest, and the kinds of file to offer.

The request is a JSON object, sent once, as the first line.

| Member | Type | Required | Meaning |
|---|---|---|---|
| `mode` | string | yes | `open` for an existing file to read; `save` for a place and a name to write to; `folder` for an existing folder (revision 2) |
| `title` | string | yes | What the dialog is called, for the person: "Export a key" |
| `purpose` | string | no | What the file is for, in a sentence, for the person to read |
| `folder` | string | no | An absolute path to the folder to start in |
| `name` | string | no | The name to suggest, in `save` mode: "Services.json" |
| `filters` | array | no | The kinds of file to offer, in order, each an object below; not in `folder` mode |

Each filter is an object with:

| Member | Type | Meaning |
|---|---|---|
| `name` | string | What the kind is called, for the person: "Registry documents" |
| `extensions` | array of strings | The extensions it covers, without the dot: `["json"]` |

## 9.4.1 What the chooser does with it

The chooser MUST start in `folder` if it is given, absolute, and a folder
the person may list, and otherwise in the person's home folder.

If `filters` is given, the chooser MUST offer them in the order given,
with the first chosen at first, and MAY offer every file as well. In
`open` mode it SHOULD show only folders and the files of the kind
chosen. A filter matches a file by its extension, without regard to
case.

In `save` mode the chooser MUST offer `name`, if given, as the name to
save as, and the person MAY change it. If the person types a name
without an extension while a filter is chosen, the chooser SHOULD add
the filter's first extension.

In `folder` mode the chooser MUST NOT show files, and does not use
`name` or `filters`. A requester asks for a folder only when it can use
one: it is the only mode whose answer can be a folder (§9.5).

The requester MUST NOT rely on the person choosing a file of a kind it
offered: the person may choose any file. A requester that needs a kind
checks what it opens.

A chooser that receives a request it cannot use, because a required
member is missing or `mode` is unknown, MUST NOT show a dialog, and ends
without answering.

---

# 9.5 The Answer

_Peios Specifications / PSPU / File Choosing_

> The one line the chooser sends — the path chosen, or that nothing was — and what a path in each mode promises.

The chooser sends at most one answer, and ends after sending it.

| Line | Meaning |
|---|---|
| `{"type":"chosen","path":…}` | The person chose the file, or in `folder` mode the folder, at `path`, an absolute path |
| `{"type":"cancelled"}` | The person chose nothing: they canceled or closed the dialog |

## 9.5.1 What a path promises

In `open` mode, the path names a file that existed when the person chose
it. The requester opens it, and MUST handle its having gone, or changed,
since.

In `save` mode, the path names a place the person chose to write to, in
a folder that existed when they chose it. If a file was there, the
person has already said to save over it: the chooser MUST ask before it
answers with the path of a file that exists. The requester creates or
replaces the file, and MUST handle being refused, since what the person
may do can change, and the chooser could not open the file to find out.

In `folder` mode, the path names a folder that existed when the person
chose it: the folder they picked or, with none picked, the folder shown.
The chooser MUST make clear which folder choosing will answer with
before the person chooses, and MUST NOT answer with a path that is not a
folder. The requester MUST handle the folder's having gone, or what it
can do there having changed, since.

Only in `folder` mode does the chooser answer with a folder. In `open`
and `save` modes, choosing a folder MUST go into it rather than answer
with it, so that a requester that asked for a file is never handed a
folder.

The chooser MUST NOT open, create or change the chosen file to choose
it, and MUST NOT answer with a path it has not shown or the person has
not typed. In neither mode does a path grant anything: the requester
uses it as the person, with its own token.

---

# 9.6 The Chooser

_Peios Specifications / PSPU / File Choosing_

> What a chooser shows and lets the person do — folders as they may see them, and making, renaming and deleting as themselves — and what it must ask before offering.

The chooser shows one folder at a time, and lets the person move among
folders. Beyond choosing, it MAY let them make a folder, and rename and
delete files and folders: a small file manager, so that a person saving
a file can make somewhere to put it.

## 9.6.1 As the person

The chooser runs as the same person as the requester, started as its
child. Everything it does to files and folders is that person's act,
which KACS checks as for any program of theirs. The chooser MUST NOT
hold or use any authority beyond theirs.

## 9.6.2 Asking before offering

The chooser MUST NOT guess what the person may do from who they are.
Before it offers an act, it SHOULD find out whether the person may do
it, by asking the system: an AccessCheck of the person's token against
the descriptor of the folder or the file. What the person may not do it
SHOULD show disabled, with the reason in words, rather than hide it or
offer it to fail. Where the descriptor cannot be read, it MAY offer the
act and let the system decide.

A folder the person may not list MUST be shown as such, with the
reason, and not as an empty folder.

## 9.6.3 Deleting

The chooser MUST ask the person before it deletes anything, and say
when a folder will be deleted with everything in it.

---

# 9.7 Extension

_Peios Specifications / PSPU / File Choosing_

> The choosing channel carries no version number; what may be added to it, what may not without a new revision, the revisions so far, and the one thing that may never be.

The choosing channel carries no version number. It grows by addition,
under these rules.

## 9.7.1 What may be added

A **member** of the request or of the answer. A party MUST ignore a
member it does not recognize, so a requester MAY send one and MUST NOT
depend on its effect.

A **line type** from the chooser that the requester may ignore and
still conform: a requester MUST ignore a `type` it does not recognize
(§9.3), and goes on waiting for the answer.

## 9.7.2 What may not be added without a new revision

A change to the meaning of an existing member or line. A `mode` beyond
those of the current revision. A second answer, or a line from the
requester after the request.

## 9.7.3 Revisions

**Revision 1** defined the `open` and `save` modes.

**Revision 2** adds the `folder` mode (§9.4, §9.5). It adds no member
and changes nothing in revision 1. A revision-1 chooser receiving a
`folder` request cannot use it: it shows no dialog and ends without
answering (§9.4), which the requester treats as `cancelled` (§9.3).
Nothing is chosen, and no folder reaches a requester that cannot handle
one. A requester that asks for a folder MUST be prepared for that
outcome as for any `cancelled`.

## 9.7.4 What may never be added

**A way for the chooser to hand over a file.** Nothing on the channel
may carry an open file, its contents, or anything but a path from the
chooser to the requester. The requester opening what it is pointed at,
as the person, is what lets any program use a chooser it does not
trust.

---

# 9.8 Conformance

_Peios Specifications / PSPU / File Choosing_

> Every requirement of this chapter collected by role — the requester and the chooser.

## 9.8.1 A conforming requester

**Starting.** Starts the chooser as its own child with the chooser's
standard input and output connected to it, and sends the request as the
first line (§9.3).

**The request.** Sends `mode` and `title`, a `folder` that is absolute
if any, and filters with extensions without the dot (§9.4). Asks for
`folder` mode only when it can use a folder, and is prepared for a
chooser of revision 1 to end without answering it (§9.7).

**The answer.** Uses a `chosen` path as the person, opening the file
itself, and handles its having gone or the act being refused. Treats
end-of-file without an answer as `cancelled` (§9.3, §9.5). Infers
nothing from the chooser's exit status or standard error, and does not
rely on the person choosing a file of a kind offered (§9.4).

**Lines.** Ignores a line type and a member it does not recognize (§9.3).

## 9.8.2 A conforming chooser

**Starting.** Shows no dialog for a request it cannot use, and ends
(§9.4). Starts in the folder given, or the person's home (§9.4).

**Choosing.** Offers the filters in order, the first chosen (§9.4). In
`save` mode, asks before answering with a file that exists (§9.5).
Never opens, creates or changes the chosen file to choose it (§9.5).

**Folders.** Answers with a folder only in `folder` mode, and goes into
a folder chosen in `open` or `save` mode instead. In `folder` mode,
shows no files, makes clear which folder choosing will answer with, and
answers only with a folder that exists (§9.4, §9.5).

**The answer.** Sends at most one, a `chosen` with an absolute path or a
`cancelled`, and ends. Answers `cancelled` when the person closes or
cancels the dialog (§9.3, §9.5).

**Ending.** Ends promptly, without answering or asking, when its
standard input closes (§9.3).

**As the person.** Acts on files and folders only as the person, and
holds nothing beyond their authority. Asks the system what they may do
before offering it, and shows what they may not, with the reason. Shows
a folder they may not list as such. Asks before deleting (§9.6).

**Lines.** Ignores a member it does not recognize (§9.3).

---

# Appendix 9.A Message Reference

_Peios Specifications / PSPU / File Choosing_

> Every line on the choosing channel, in order, with an example conversation.

| Direction | Line | Defined in |
|---|---|---|
| Requester → chooser | The request (first line, no `type`) | §9.4 |
| Chooser → requester | `{"type":"chosen","path":…}` | §9.5 |
| Chooser → requester | `{"type":"cancelled"}` | §9.5 |

## 9.A.1 An example

A registry editor exports a key. The person goes into a folder, makes a
folder called Backups inside it, opens it, keeps the suggested name and
saves. Lines are shown on several lines here for reading. On the channel
each is one line.

```
→ {"mode":"save","title":"Export Services",
   "purpose":"The key and everything under it is written to a registry document.",
   "folder":"/home/dana","name":"Services.json",
   "filters":[{"name":"Registry documents","extensions":["json"]}]}
← {"type":"chosen","path":"/home/dana/Backups/Services.json"}
```

The chooser ends, and the registry editor writes the file.

## 9.A.2 Choosing a folder

A file server's settings ask where a new share is (revision 2). The
person goes into `/srv`, picks `photos`, and chooses it.

```text
→ {"mode":"folder","title":"Choose a folder to share","folder":"/srv"}
← {"type":"chosen","path":"/srv/photos"}
```

The settings check the folder and share it, as the person.

---

# 10.1 Scope and Roles

_Peios Specifications / PSPU / Local Principal Administration_

> What PLPS specifies — how a program administers a local principal store through the daemon that owns it — and its two roles.

This chapter specifies **PLPS**, the protocol on which a program
administers a **local principal store**: the users and groups a machine
holds for itself, their memberships, their credentials and their claims.
It is spoken to the daemon that owns the store, never to the store's
file.

Two roles participate.

The **store daemon** owns the store. It is the store's only reader and
only writer, it decides who may administer it, and it applies each
request or refuses it. On Peios it is `lpsd`, which is also the machine's
local principal source on PSI (§2): the store it administers here is the
one it answers for there.

The **administrator client** is a program that asks: a command-line tool
such as `lps`, a desktop app such as Principals Manager, or a
provisioning tool. It holds no state of its own and no privilege of its
own; everything it does is a request the store daemon decides whether to
honor. Any program MAY be an administrator client, and a third party
writing one is the case this chapter is written for.

## 10.1.1 Why a daemon, and not the file

The store holds every local principal's credential verifier, so its
descriptor admits the store daemon and nothing else. A tool that edited
the file would need that descriptor widened to whatever it runs as,
undoing the one thing it exists to do. Going through the daemon keeps one
writer, makes "an administrator may do this" a check on the caller's
token rather than a file permission, and lets the daemon validate every
change before anything is written.

This chapter covers:

- the channel: where it is, who may connect, and the one exchange each
  connection carries (§10.3)
- message framing, shared with PGSS Logon (§10.4)
- the requests: principals (§10.5), groups and membership (§10.6),
  claims (§10.7), and SSH keys and credential policy (§10.8)
- the replies, and how a request is refused (§10.9)
- the obligations binding on each role (§10.10)
- the self socket, on which any principal reads their own account and
  sets their own display name (§10.11)

This chapter does not cover:

- How the store is kept on disk, or how a credential verifier is
  derived — the store daemon's own design.
- Signing in, and a principal changing their own password or adding or
  removing their own SSH keys. Those are PGSS Logon (PGSS §2.20 and
  PGSS §2.23), and reach the store through PSI (§2.21, §2.23).
- Looking other principals up. Anyone may ask who a name or a SID is,
  and who is in a group, on the authority's identity socket (PGSS
  §2.14); a client that only reads about principals in general SHOULD
  read there rather than on the admin socket, since that socket answers
  everyone. A principal reading their *own* account, including what
  the identity socket does not carry — their credential policy and SSH
  keys — reads it on the self socket (§10.11).
- What policy applies to a principal at sign-in, such as its privileges.
  That is the authority's (PGSS §2.13).

---

# 10.2 Terminology

_Peios Specifications / PSPU / Local Principal Administration_

> The words this chapter uses for the store, its principals and groups, and the names a request may give a group.

**Store.** The set of local principals and local groups one store daemon
holds, with their memberships, credentials, claims and SSH keys.

**Principal.** A user or service account the store holds. It has a
**name**, unique in the store and matched without regard to case, and a
**RID** (relative identifier): the last sub-authority of its SID. A RID
is never reissued, so a deleted principal's SID never names anyone else.

**Domain SID.** The SID every principal and local group of the store is
under, `S-1-5-21-A-B-C`. A principal's SID is the domain SID followed by
its RID.

**Local group.** A group the store holds, named and numbered as a
principal is, from the same RID space.

**Well-known group.** A group whose SID is fixed by the system rather
than issued by any store: `Everyone`, `Authenticated Users`, and the
`BUILTIN` groups such as `Administrators`. The store holds none of them as
objects, but it records memberships of the `BUILTIN` groups (§2.19).

**Group name, as written.** Where a request names a group (§10.6), the
store daemon resolves it, never the client: a well-known group by its
name (`Administrators`, with or without `BUILTIN\`), a local group by its
name, or any group by its SID written out (`S-1-5-32-544`). A client
MUST pass what the person wrote, and MUST NOT resolve it itself; a client
with its own table of well-known names would be a second implementation
of the machine's identity scheme, free to disagree with the first.

**Effective Unix ID.** The POSIX identifier a principal or group projects
to: the authority's base for the store's range plus the store's relative
number (§2.20). Replies here carry the effective number, so that what an
administrator is shown is what the principal will appear as. Zero means
the store daemon cannot say.

**Credential policy.** Which credentials a principal may sign in with
(§10.8): a password, an SSH public key, either, none required, or none
accepted.

---

# 10.3 The Channel

_Peios Specifications / PSPU / Local Principal Administration_

> The admin socket, who may connect to it, and why each connection carries exactly one request.

## 10.3.1 The socket

The store daemon listens on a Unix stream socket. On Peios it is
`/run/lpsd/admin.sock`.

The socket's descriptor SHOULD admit exactly those the store daemon
would (§10.3, *Who may administer*), so that a caller it would refuse is
refused at `connect` rather than after sending a request. That descriptor
is load-bearing rather than a convenience: the store daemon reads the
caller's token from the connection, and a socket open to everyone would
let anyone hold a connection open against its timeouts.

A client MUST treat a `connect` refused for permission as the store
daemon refusing it, exactly as `Denied` (§10.9).

## 10.3.2 One request a connection

Each connection carries **one exchange**: the client sends one request,
the store daemon sends one reply, and the connection is finished. There
is no pipelining, no conversation identifier and nothing to
demultiplex. The store daemon MUST close the connection after replying,
and MUST NOT read a second request from it.

A client MUST open a connection for each request. It MUST NOT hold one
open waiting to use it later: the store daemon closes a connection that
sends nothing (below).

Every request is answered **exactly once**, with its own reply
(§10.A) or with `Failed` (§10.9). A client MUST treat a connection closed
without a reply as the request's outcome being unknown: a change MAY
have been applied. It SHOULD read the store again before telling a person
the change failed.

## 10.3.3 Who may administer

The store daemon decides who may administer the store from the caller's
token, read from the connection, and it MUST decide before reading the
request. On Peios a caller may administer the store if its token's user
is `SYSTEM`, or if it carries `BUILTIN\Administrators` **enabled**. A
group present but deny-only grants nothing, and MUST NOT be treated as
membership.

`SYSTEM` is admitted because a machine's first account is created by a
boot-time service, before any person exists to be an administrator.

There is nothing finer. A caller that may administer the store may make
every request on this socket; one that may not, may make none. In
particular a principal may not change their own profile here. What a
principal may do about their own account is served elsewhere: their
display name and a view of their account on the self socket (§10.11),
and their password and SSH keys through PGSS Logon (PGSS §2.20 and PGSS §2.23).

A store daemon refusing a caller MUST reply `Failed` with `Denied` and
then close the connection.

## 10.3.4 Timeouts

A store daemon SHOULD bound how long it waits for the request and how
long it spends sending the reply. On Peios each is five seconds.

A client SHOULD wait for a reply far longer than that. A request that
sets a password makes the store daemon derive a verifier, and a store
daemon that also answers PSI may serve a sign-in first; on Peios `lps`
waits thirty seconds.

## 10.3.5 Credentials on the wire

`Add` and `SetPassword` (§10.5) carry a password in the clear. On a
kernel-mediated local socket, anything able to read those bytes could as
well read the memory of the process that typed them; what must never
travel is anything a verifier could be recomputed from, and nothing here
does. Both parties SHOULD wipe a buffer that held a password once they
are finished with it.

---

# 10.4 Message Framing

_Peios Specifications / PSPU / Local Principal Administration_

> PGSS Logon's header and encoding with PLPS's own magic, and a larger size limit for a whole store's listing.

## 10.4.1 Header

Every message begins with PGSS Logon's 12-byte header (PGSS §2.6),
unchanged, with this chapter's magic:

| Offset | Size | Field | Value |
|---|---|---|---|
| 0 | 4 | `magic` | `PLPS` (`50 4c 50 53`) |
| 4 | 2 | `version` | `1` |
| 6 | 2 | `msg_type` | See §10.A |
| 8 | 4 | `total_len` | Header plus body, in bytes |

The magic MUST be checked on every message, and MUST end the exchange
when wrong. PLPS shares PGSS Logon's codec and some of its structures,
so a socket plugged into the wrong daemon would otherwise decode several
fields before going wrong.

The high bit of `msg_type` marks a message sent by the **store daemon**,
which is the authority for its own store. A party MUST check the type it
received against the one it expected, not only against that bit.

## 10.4.2 Size limit

A message MUST NOT exceed **2 MiB** (2,097,152 bytes) in total, larger
than PGSS Logon's limit so that `Principals` can carry a whole store's
listing (§10.5). A party MUST reject a header declaring more without
reading the body.

## 10.4.3 Encoding

Integers, strings, byte strings, arrays and length-framed structures are
encoded exactly as PGSS §2.6 specifies, and a body is one length-framed
structure. The two length mechanisms are the ones that section warns
against confusing: a string or byte string is a `u32` byte count and its
bytes; a structure or array element is a `u32` byte count of the whole
structure, and a decoder skips to that end after the fields it knows.

**Booleans** are a `u8`: zero is false, anything else is true.

**SIDs** are byte strings carrying the binary SID (PCDS §4), at most 68
bytes.

**An optional string** is a `u8` presence flag followed by a string: the
string is meaningful only where the flag is non-zero. It exists where
"leave this alone" and "set this to empty" are both requests a client
makes, and PGSS's empty-means-absent rule could not tell them apart.

**A claim** is encoded as PSI encodes one (§2.13): a length-framed
structure of `name`, `flags`, `value_type` and `values`. Its value types
and flags are PCDS §5.9's, and are closed here as they are on PSI
(§2.A).

## 10.4.4 Extending

The rules of PGSS §2.6 bind this chapter: fields are appended only, an
appended field is optional with a stated default, and a new value in an
enumeration is a breaking change requiring a version bump.

A decoder that reaches the end of a structure where an appended field
would have been MUST substitute that field's default. This chapter states
each default where the field is defined; a client and a store daemon of
different ages then degrade rather than fail.

---

# 10.5 Principals

_Peios Specifications / PSPU / Local Principal Administration_

> Listing the store's principals, one in full, the store's domain, and creating, deleting, renaming, enabling, disabling and changing a principal.

Every request naming a principal names it by `name`, a string of at most
256 bytes, matched without regard to case. A store daemon MUST answer
`NotFound` (§10.9) for a name it holds no principal by.

## 10.5.1 List

`msg_type` = `0x0001`. Empty body. Answered with `Principals`.

## 10.5.2 Principals

`msg_type` = `0x8001`. Every principal in the store, as an array of at
most 4096 length-framed entries:

| Field | Encoding | Default if absent |
|---|---|---|
| `name` | string, 256 bytes | |
| `rid` | `u32` | |
| `enabled` | boolean | |
| `groups` | `u32`: how many groups it is listed in | |
| `unix_id` | `u32`: its effective Unix ID (§10.2) | `0` |

`groups` counts listed memberships only, not the primary group.

## 10.5.3 Show

`msg_type` = `0x0002`. Body: `name`. Answered with `Principal`.

## 10.5.4 Principal

`msg_type` = `0x8002`. One principal in full:

| Field | Encoding | Default if absent |
|---|---|---|
| `name` | string, 256 bytes | |
| `rid` | `u32` | |
| `enabled` | boolean | |
| `sid` | SID | |
| `groups` | array of at most 128 group references | |
| `unix_id` | `u32`: effective | `0` |
| `primary_group` | one length-framed group reference | an empty reference |
| `home` | string, 4096 bytes | empty |
| `shell` | string, 4096 bytes | empty |
| `display_name` | string, 256 bytes | empty |
| `claims` | array of at most 64 claims (§10.4) | none |
| `permitted_logon_types` | `u32`, as on `Add` | `0`, not stated |
| `credential_policy` | `u8` (§10.8) | not said |
| `nt_hash_present` | `u8`: 0 not said, 1 absent, 2 present | not said |

`credential_policy` is closed, as §10.8 says: a client MUST treat a
value it does not know as a reply it cannot read. A client given no
`credential_policy` MUST NOT show one; the store daemon did not say.

`nt_hash_present` is administrative status, not credential material or
permission to use a password method. It follows `credential_policy` when
that field is present. An unknown status value MUST be rejected. The
daemon MUST NOT return the hash itself through this reply.

A **group reference** is a length-framed structure:

| Field | Encoding | Default if absent |
|---|---|---|
| `sid` | SID | |
| `name` | string, 256 bytes: what this machine calls the group | empty |
| `unix_id` | `u32`: its effective Unix ID, or zero | `0` |

The store daemon names each group, a well-known one included, and gives
its number where it knows it, so a client never builds a SID or resolves
a name itself. An empty `name` means the store daemon knows no name for
the SID; zero means it cannot say the number.

## 10.5.5 Domain

`msg_type` = `0x0003`. Empty body. Answered with `DomainIs`.

## 10.5.6 DomainIs

`msg_type` = `0x8003`. Body: `sid`, the store's domain SID (§10.2).

`Domain` is the smallest request there is, changes nothing, and is
refused to anyone who may not administer the store (§10.3). A client MAY
send it to find out whether its caller may administer the store, before
offering to change anything.

## 10.5.7 Add

`msg_type` = `0x0004`. Creates a principal. Answered with `Created`
carrying its RID.

| Field | Encoding | Default if absent |
|---|---|---|
| `name` | string, 256 bytes | |
| `credential_kind` | `u8`: `0` none, `1` a password | |
| `secret` | byte string, 4096 bytes | |
| `enabled` | boolean | |
| `groups` | array of at most 128 length-framed strings: groups as written (§10.2) | |
| `permitted_logon_types` | `u32` | `0`, not stated |
| `primary_group` | optional string (§10.4), 256 bytes: a group as written | absent |
| `home` | optional string, 4096 bytes | absent |
| `shell` | optional string, 4096 bytes | absent |
| `display_name` | optional string, 256 bytes | absent |

`credential_kind` says plainly whether the principal has a password,
rather than an empty `secret` meaning none, so that a client cannot make
a principal that needs no credential by accident. `secret` is present
either way, and empty for `0`. A store daemon MUST refuse an empty
`secret` with kind `1` as `Invalid`, and MUST refuse a kind it does not
know.

A principal made with kind `0` has the credential policy `NoCredential`
(§10.8): it signs in with nothing collected. One made with kind `1` has
the policy `Password`.

`permitted_logon_types` is the set of PGSS §2.16's, as PSI carries it
(§2.13). Zero is *not stated*, which the authority reads as its default:
every kind of sign-in a person could use, and never a service sign-in.

The principal gets the store's next RID. Where `primary_group`, `home`,
`shell` or `display_name` is absent, it gets what the store daemon
chooses (on Peios, `Authenticated Users`, `/home/<name>`, `/bin/sh` and
no display name). A present field is checked as `SetProfile` and
`SetPrimaryGroup` check it, and a store daemon MUST refuse the whole
request if it refuses any field, creating nothing: a principal is made
whole or not at all.

A store daemon that predates the last four fields ignores them, and
makes the principal with its own choices. A client cannot tell that
from the reply; one that must know reads the principal back with `Show`.

A store daemon MUST refuse a name it already holds, a principal's or a
local group's, as `Exists`, and a name it will not accept as `Invalid`
with the reason. Which names it accepts is its own. On Peios a name is 1
to 256 bytes of printable ASCII, may not contain `@ \ / : ,`, and may
not be a well-known group's name.

## 10.5.8 Remove

`msg_type` = `0x0005`. Body: `name`. Deletes the principal. Answered with
`Done`.

Its RID is not reissued, so its SID keeps appearing in the descriptors of
whatever it owned, naming nobody. A client SHOULD say so before removing
one, and SHOULD offer disabling instead.

## 10.5.9 SetEnabled

`msg_type` = `0x0006`. Body: `name`, then `enabled`, a boolean. Answered
with `Done`. A disabled principal keeps everything, and cannot sign in.

## 10.5.10 SetPassword

`msg_type` = `0x0007`. Body: `name`, then `secret`, a byte string of at
most 4096 bytes, never empty. Sets the principal's password. Answered
with `Done`.

It does not change the principal's credential policy (§10.8). A
principal whose policy accepts no password is not given one by this
request: a client that means the password to be used MUST also send
`CredentialPolicy`.

## 10.5.11 SetProfile

`msg_type` = `0x000d`. Changes part of a principal's profile, leaving the
rest alone. Answered with `Done`.

| Field | Encoding |
|---|---|
| `name` | string, 256 bytes |
| `home` | optional string (§10.4), 4096 bytes |
| `shell` | optional string, 4096 bytes |
| `display_name` | optional string, 256 bytes |

An absent field is left as it is. A present empty `display_name` clears
it. A store daemon MAY refuse a value it will not accept as `Invalid`;
on Peios `home` and `shell` must be absolute paths.

## 10.5.12 Rename

`msg_type` = `0x0015`. Changes what a principal is called. Answered with
`Done`.

| Field | Encoding |
|---|---|
| `name` | string, 256 bytes: the principal |
| `new_name` | string, 256 bytes: what it is to be called |

Its SID, RID and Unix ID stay, so everything that names it by SID, every
descriptor and every token already minted, still does. Its home directory
stays too: a store daemon MUST NOT change `home` on a rename. A client
that means the home directory to follow sends `SetProfile` as well.

A store daemon MUST refuse a `new_name` another principal or a local
group holds as `Exists`, and applies the rules for a name as `Add` does.
A `new_name` differing from the principal's name only in case is a
rename; one equal to it is `Done` and changes nothing.

## 10.5.13 SetLogonTypes

`msg_type` = `0x0016`. Sets which kinds of sign-in a principal may be
used for. Answered with `Done`.

| Field | Encoding |
|---|---|
| `name` | string, 256 bytes |
| `permitted_logon_types` | `u32`, as on `Add` |

Zero returns the principal to *not stated*, the authority's default.
There is no value meaning "no sign-in at all"; a client disables the
principal for that. A store daemon MUST keep bits for logon types it
does not know as they are given, as it does on `Add`: the authority
checks the types it knows.

## 10.5.14 Last administrator

A store daemon MUST refuse, as `Invalid`, a request that would leave the
store with no enabled principal in `BUILTIN\Administrators` who can sign
in: removing or disabling the last one, removing the last one from that
group (§10.6), setting the last one's `permitted_logon_types` to a
set that permits none of interactive, remote interactive or network
sign-in, or leaving the last one nothing to sign in with (§10.8): a
`CredentialPolicy` it would not have something to sign in with under,
or a `KeyRemove` of the last key it signs in with. A machine left so
has nobody to administer it.

---

# 10.6 Groups and Membership

_Peios Specifications / PSPU / Local Principal Administration_

> Listing, creating, renaming, describing and deleting local groups, and putting principals in groups — local, BUILTIN or any other — and setting a principal's primary group.

## 10.6.1 GroupList

`msg_type` = `0x000a`. Empty body. Answered with `Groups`.

## 10.6.2 Groups

`msg_type` = `0x8007`. Every **local** group in the store, as an array of
at most 4096 length-framed entries:

| Field | Encoding | Default if absent |
|---|---|---|
| `name` | string, 256 bytes | |
| `rid` | `u32` | |
| `unix_id` | `u32`: its effective Unix ID (§10.2) | |
| `sid` | SID | |
| `members` | `u32`: how many principals list it | |
| `description` | string, 1024 bytes | empty |

The well-known groups are not in it: the store holds none of them as
objects (§10.2). `members` counts listed memberships, not principals
whose primary group it is; the identity socket's `MEMBERS` counts both
(PGSS §2.16).

A group's **description** says what it is for, on one line, for a person
to read; empty is none. Anyone may read it, on the identity socket's
`DESCRIPTION` (PGSS §2.16), where a store daemon that is a principal
source answers it.

## 10.6.3 GroupCreate

`msg_type` = `0x000b`. Creates a local group, with the store's next RID.
Answered with `Created` carrying it.

| Field | Encoding | Default if absent |
|---|---|---|
| `name` | string, 256 bytes | |
| `description` | string, 1024 bytes | empty |

A store daemon MUST refuse a name it already holds, a principal's or a
group's, as `Exists`, and applies the same rules to a group's name as to
a principal's (§10.5). It MAY refuse a description it will not keep as
`Invalid`; on Peios one may hold no control characters, and is kept with
the spaces at its ends removed.

A store daemon that predates `description` ignores it, and makes the
group with none, as `Add` describes (§10.5).

## 10.6.4 GroupRename

`msg_type` = `0x0017`. Body: `name`, a local group's, then `new_name`,
as `Rename` (§10.5). Changes what the group is called. Answered with
`Done`.

Its SID, RID and Unix ID stay, and so does every membership of it, since
a membership names the group by SID. A store daemon MUST answer
`NotFound` where it holds no local group by `name`, and refuses
`new_name` as `Rename` does.

## 10.6.5 GroupDescribe

`msg_type` = `0x0018`. Sets a local group's description. Answered with
`Done`.

| Field | Encoding |
|---|---|
| `name` | string, 256 bytes: a local group's |
| `description` | string, 1024 bytes; empty clears it |

A store daemon MUST answer `NotFound` where it holds no local group by
`name`. The well-known groups' descriptions are the authority's, and
cannot be set here.

## 10.6.6 GroupDelete

`msg_type` = `0x000c`. Body: `name`, a local group's. Deletes it.
Answered with `Done`.

A store daemon MUST refuse, as `Invalid`, deleting a group any principal
lists or has as its primary group: a principal would be left in a group
that no longer exists. A client removes the members first.

A store daemon MUST answer `NotFound` where it holds no local group by
`name`, a well-known group's name included.

## 10.6.7 GroupAdd and GroupRemove

`GroupAdd`, `msg_type` = `0x0008`, puts a principal in a group;
`GroupRemove`, `msg_type` = `0x0009`, takes it out. Both are answered
with `Done`.

| Field | Encoding |
|---|---|
| `name` | string, 256 bytes: the principal |
| `group` | string, 256 bytes: the group as written (§10.2) |

`name` MUST name a principal: groups do not nest, and a store daemon MUST
answer `NotFound` for a group's name there.

`group` MAY name a local group, a `BUILTIN` group, or any group by its
SID. A membership of a `BUILTIN` group is recorded here on the machine's
behalf, and asserted at sign-in under PSI's membership-scope exception
(§2.19); it is how a principal becomes an administrator. A membership of
a group in another domain is recorded as given.

Both are idempotent: adding a membership already held, or removing one
not held, is `Done` and changes nothing. A principal MAY be listed in at
most 128 groups; a store daemon MUST refuse a 129th as `Invalid`.

Removing a principal from `BUILTIN\Administrators` is refused if it is
the last enabled one there (§10.5).

A store daemon MUST answer `NotFound` for a `group` that names nothing it
can resolve.

## 10.6.8 SetPrimaryGroup

`msg_type` = `0x000e`. Body: as `GroupAdd`. Makes `group` the principal's
primary group: the one it projects to as its POSIX group ID. Answered
with `Done`.

A primary group is a membership (§2.13): the principal is in it whether
or not it is also listed.

---

# 10.7 Claims

_Peios Specifications / PSPU / Local Principal Administration_

> Setting and removing a principal's claims — the typed attributes conditional ACEs are evaluated against.

A principal's **claims** are named, typed attributes that the authority
puts on the tokens it mints for them, and that conditional ACEs are
evaluated against (PCDS §5.9). `Principal` carries them (§10.5).

## 10.7.1 SetClaim

`msg_type` = `0x000f`. Sets a claim, replacing one of the same name.
Answered with `Done`.

| Field | Encoding |
|---|---|
| `name` | string, 256 bytes: the principal |
| `claim` | one claim (§10.4) |

Claim names match without regard to case. A store daemon MUST refuse, as
`Invalid`, a claim PSI could not carry to the authority (§2.13): a name
empty or longer than 255 bytes or containing a NUL, a flag or value type
it does not recognize, more than 64 values, or a string or octet value
longer than 1024 bytes. It MUST refuse a 65th claim on one principal.

## 10.7.2 RemoveClaim

`msg_type` = `0x0010`. Removes a claim. Answered with `Done`.

| Field | Encoding |
|---|---|
| `name` | string, 256 bytes: the principal |
| `claim_name` | string, 255 bytes |

Removing a claim the principal does not hold is `Done` and changes
nothing.

---

# 10.8 Keys and Credential Policy

_Peios Specifications / PSPU / Local Principal Administration_

> A principal's SSH public keys, and its credential policy — which credentials it may sign in with.

A principal's **credential policy** says which credentials it may sign
in with. Its **SSH public keys** are what it may sign in with by key
(PGSS §2.D). The two are separate on purpose: adding a key does not let
anyone sign in with it until the policy says keys are accepted, so
enrolling a key and allowing key sign-in are two decisions, and neither
happens as a side effect of the other.

## 10.8.1 Credential policies

| Value | Policy | Signs in with |
|---|---|---|
| `0` | `Denied` | nothing: every sign-in is refused |
| `1` | `Password` | its password |
| `2` | `SshPublicKey` | one of its SSH keys |
| `3` | `PasswordOrKey` | either |
| `4` | `NoCredential` | nothing collected (§10.5, `Add`) |

The enumeration is closed (§10.4). A store daemon MUST refuse a value it
does not know.

## 10.8.2 KeyList

`msg_type` = `0x0011`. Body: `name`. Answered with `Keys`.

## 10.8.3 Keys

`msg_type` = `0x8008`. The principal's credential policy and keys:

| Field | Encoding |
|---|---|
| `policy` | `u8` |
| `keys` | array of at most 32 length-framed keys |

A key:

| Field | Encoding |
|---|---|
| `id` | byte string, 16 bytes: the store daemon's, never all zero |
| `fingerprint` | string, 128 bytes: as `ssh-keygen -l` writes one |
| `label` | string, 128 bytes |
| `created` | `u64`: seconds since the Unix epoch |

`Detail` (§10.5) answers the credential policy too, as a trailing
optional field; `KeyList` answers it from every store daemon.

## 10.8.4 KeyAdd

`msg_type` = `0x0012`. Enrolls an SSH public key. Answered with `Done`.

| Field | Encoding |
|---|---|
| `name` | string, 256 bytes |
| `public_key` | string, 16384 bytes: one line of an OpenSSH `authorized_keys` file |
| `label` | string, 128 bytes, no control characters |

A store daemon MUST refuse, as `Invalid`, a key it cannot read or does
not support, a key the principal already has, a 33rd key, and a label
too long or carrying a control character. It does not change the policy.

## 10.8.5 KeyRemove

`msg_type` = `0x0013`. Body: `name`, then `id`, a byte string of 16
bytes. Removes the key. Answered with `Done`, or `NotFound` for an `id`
the principal has no key by. It is refused as the last-administrator
rule says (§10.5).

## 10.8.6 CredentialPolicy

`msg_type` = `0x0014`. Body: `name`, then `policy`, a `u8`. Sets the
principal's credential policy. Answered with `Done`. It is refused as
the last-administrator rule says (§10.5).

A principal **has something to sign in with** when its policy is
`NoCredential`; `Password` and it has a password; `SshPublicKey` and it
has a key; or `PasswordOrKey` and it has either. `Denied` never does.

---

# 10.9 Replies and Refusal

_Peios Specifications / PSPU / Local Principal Administration_

> Created, Done and Failed; the five reasons a request is refused; and what a change must have done before it is acknowledged.

Every request has exactly one successful reply, listed in §10.A, and any
request may instead be answered with `Failed`.

## 10.9.1 Created

`msg_type` = `0x8004`. Body: `rid`, a `u32`. Answers `Add` and
`GroupCreate`: the two requests that allocate a RID, and so have
something to report.

## 10.9.2 Done

`msg_type` = `0x8005`. Empty body. Answers every other request that
changes the store.

## 10.9.3 Failed

`msg_type` = `0x8006`. The request was refused.

| Field | Encoding |
|---|---|
| `failure` | `u32`: why, from the table below |
| `reason` | string, 512 bytes: why, in words |

| Value | Failure | Means |
|---|---|---|
| `1` | `Denied` | The caller may not administer the store (§10.3). |
| `2` | `NotFound` | Nothing in the store by the name, or the key, given. |
| `3` | `Exists` | The name asked for is already held. |
| `4` | `Invalid` | Well-formed, and asking for something the store will not do. |
| `5` | `Internal` | The store could not be read or written. |

The enumeration is closed (§10.4). `failure` is for a client that
branches on it; `reason` is for a person, and a client SHOULD show it as
it is rather than interpret it.

A store daemon MUST answer a request it cannot decode, or whose
`msg_type` this chapter does not define, with `Invalid`.

There is no failure for "you may not see that". Administering is not
authenticating, and a caller already allowed to administer the store
has nothing to learn from a refusal that it could not learn by listing.

## 10.9.4 A change is applied whole, or not at all

A store daemon MUST NOT acknowledge a change, with `Created` or `Done`,
before it has been made durable. A change that cannot be saved MUST be
undone and answered `Internal`; a refused request MUST leave the store as
it was.

Every change acknowledged is also announced to the authority, as PSI's
`Changed` (§2.17), so that what it answers next reflects it. A client
here is told nothing when somebody else changes the store: one that shows
the store SHOULD read it again after its own changes and from time to
time.

---

# 10.10 Conformance

_Peios Specifications / PSPU / Local Principal Administration_

> Every requirement of this chapter collected by role — the store daemon and the administrator client.

## 10.10.1 A conforming store daemon

**The channel.** Decides from the caller's token, before reading the
request, whether the caller may administer the store, admitting `SYSTEM`
and a token carrying `BUILTIN\Administrators` enabled, and treating a
deny-only group as no membership; refuses anyone else with `Denied`
(§10.3). Serves one request a connection, answers it exactly once, and
closes (§10.3).

**Framing.** Checks the magic and the version of every message, refuses
one over 2 MiB unread, and substitutes the stated default for an
appended field a peer did not send (§10.4).

**Requests.** Answers each with its own reply (§10.A) or `Failed`, and a
request it cannot decode or does not define with `Invalid` (§10.9).
Resolves a group as written itself (§10.2). Answers `NotFound` for a
principal, group or key it does not hold, `Exists` for a name already
held, and `Invalid`, with the reason, for anything it will not do
(§10.5 to §10.9).

**Its rules.** Refuses to leave the store with no enabled administrator
who can sign in (§10.5); to delete a group anyone is in or has as their
primary group (§10.6); a claim PSI could not carry (§10.7); and a key it
cannot read, or holds already (§10.8). Gives a principal made without a
password the policy `NoCredential`, and one made with one `Password`
(§10.5). Makes a principal whole or not at all, refusing an `Add` if it
refuses any field of it (§10.5). Keeps a renamed principal's SID, RID,
Unix ID and home directory (§10.5), and a renamed group's SID, RID, Unix
ID and memberships (§10.6). Holds one name for one principal or
local group, matched without regard to case (§10.5, §10.6). Never
reissues a RID (§10.2).

**Changes.** Acknowledges a change only once it is durable, undoes one
it cannot save, leaves the store untouched on a refusal, and announces
every change to the authority (§10.9).

## 10.10.2 A conforming administrator client

**The channel.** Opens a connection for each request and holds none
open (§10.3). Treats a connection refused for permission as `Denied`,
and a connection closed without a reply as an outcome unknown, reading
the store again before saying the change failed (§10.3).

**Requests.** Passes a group as the person wrote it, resolving nothing
itself (§10.2). Sends `credential_kind` `0` only where a principal is
meant to need no credential (§10.5). Sends `CredentialPolicy` alongside
`SetPassword` where the password is meant to be used (§10.5). Reads a
principal back with `Show` where it must know that an `Add`'s profile
was applied (§10.5). Shows no credential policy where the store daemon
gave none (§10.5).

**Refusals.** Shows a refusal's `reason` as it is (§10.9).

**Reading.** Reads principals for display on the identity socket where
it need not administer them (§10.1), and reads the store again after its
own changes, since nothing tells it of anyone else's (§10.9).

## 10.10.3 The self socket

The obligations of a store daemon serving the self socket, and of its
clients, are collected in §10.11.

---

# 10.11 The Self Socket

_Peios Specifications / PSPU / Local Principal Administration_

> How any principal reads their own account from the store daemon and sets their own display name — a second socket whose requests never name anybody, and how the daemon serves it without letting a caller stall it.

The admin socket (§10.3) is for administrators, and every request on it
names the principal it is about. A principal also needs to see their own
account — what they are called, what they sign in with, which SSH keys
they have — and to set what they are called, without being an
administrator. The **self socket** serves that: any authenticated
principal may connect to it, and no request on it names anybody.

Changing a credential is not here. A display name is not a credential,
so setting it asks for no proof; a password or an SSH key is one, so
changing either goes through PGSS Logon, where the principal's current
password is asked for (PGSS §2.20 and PGSS §2.23).

## 10.11.1 The socket

The store daemon listens on a second Unix stream socket. On Peios it is
`/run/lpsd/self.sock`.

Its descriptor MUST admit every authenticated principal to connect. On
Peios it is `D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;0x100082;;;AU)`: SYSTEM and
Administrators with full access, and Authenticated Users with exactly
what a connect needs (`FILE_WRITE_DATA`, `READ_ATTRIBUTES` and
`SYNCHRONIZE`), the mask Peios grants them on `/run/logon.sock`.
The store daemon sets it when it creates the socket and reads it back;
the socket's directory admits nobody the socket is for, so a socket that
inherited it would be closed to everyone it exists to serve.

## 10.11.2 The subject is the peer

The subject of every request is the **user of the connected peer's
token**, read by the store daemon from the connection when it accepts
it. No request carries a name, a SID or any other way to point at a
principal, and the store daemon MUST NOT answer about, or change, any
principal but that one.

A peer whose user the store does not hold — `SYSTEM`, a service
identity, a principal another source holds — is refused with `NotFound`
and a reason saying so. It is never shown, or allowed to change,
somebody else's account.

## 10.11.3 Framing

Messages are PLPS's (§10.4): the same header, magic, encoding and
`Failed` and `Done` replies (§10.9). The requests are in a range of
their own, `0x0040` upward, with their reply at `0x8040`. Each socket
MUST refuse the other's requests with `Invalid`: the self socket is not
a second way to administer the store, and the admin socket does not
answer about its caller.

A request on the self socket MUST NOT exceed **4096 bytes**. The store
daemon MUST refuse, from its header and without reading the body, one
that declares more, answering `Invalid`. Replies are bounded by PLPS's
ceiling as on the admin socket.

## 10.11.4 One request a connection, never served blocking

Each connection carries one exchange, as on the admin socket (§10.3).

The admin socket admits only administrators, so a store daemon MAY
serve it a connection at a time. The self socket admits everyone, and a
store daemon that also answers PSI (§2) MUST NOT let a connection on it
delay anything else: a principal who connected and sent nothing would
otherwise stall every sign-in behind them. A store daemon MUST serve the
self socket without blocking on any one connection, MUST bound how long
a connection may remain open from accept to the last byte of its reply,
and MUST bound the connections open at once and the connections any one
user, by the token's user SID, holds. A caller over a bound is refused,
with `Failed` where that will not block, and the connection closed.

On Peios lpsd holds each connection non-blocking in a table its poll
loop drives, and drops one at **5 seconds** after accept. It holds at
most **32** at once and **4** from any one user.

## 10.11.5 ShowSelf

`msg_type` = `0x0040`. Empty body. Answered with `Self`.

## 10.11.6 Self

`msg_type` = `0x8040`. The caller's own account.

| Field | Encoding |
|---|---|
| `name` | string, 256 bytes |
| `sid` | byte string, 68 bytes |
| `display_name` | string, 256 bytes; empty when unset |
| `enabled` | boolean |
| `policy` | `u8`: the credential policy (§10.8) |
| `has_password` | boolean: whether the account has a password at all |
| `keys` | array of at most 32 length-framed keys |

A key:

| Field | Encoding |
|---|---|
| `id` | byte string, 16 bytes: as `Keys` gives it (§10.8) |
| `fingerprint` | string, 128 bytes: as `ssh-keygen -l` writes one |
| `algorithm` | string, 64 bytes: the key's type, such as `ssh-ed25519` |
| `label` | string, 128 bytes |
| `created` | `u64`: seconds since the Unix epoch |

`has_password` is separate from `policy` because a policy can name a
password the account has not got, and a principal adding or removing a
key must prove a password (PGSS §2.23). A client SHOULD offer key
changes only where the account has one.

This is what `Show` and `KeyList` give an administrator about the same
principal, less what is the administrator's to manage. Nothing in it is
a verifier, a key's private half or anything a credential could be
recomputed from.

## 10.11.7 SetDisplayName

`msg_type` = `0x0041`. Answered with `Done`.

| Field | Encoding |
|---|---|
| `display_name` | string, 256 bytes; empty clears it |

The store daemon MUST validate it exactly as it validates `SetProfile`'s
`display_name` (§10.5), refusing what that refuses with `Invalid`. It
MUST refuse with `Denied` a principal that is disabled: a session that
outlived its account's disabling is not a way to change the account.

The change is applied as any other (§10.9): made durable before `Done`,
undone and answered `Internal` if it cannot be saved, and announced to
the authority as PSI's `Changed` (§2.17) so that its identity channel
answers with the new name at once. A request that changes nothing — the
name is already that — MAY be answered `Done` without writing.

## 10.11.8 Conformance

**A store daemon serving the self socket** admits every authenticated
principal to connect to it; answers every request about the peer's
token's user and nobody else, and refuses a peer it does not hold with
`NotFound`; refuses the admin socket's requests with `Invalid`, and a
request over 4096 bytes from its header; never blocks on one connection,
and bounds each connection's time, the connections open, and each user's
connections; validates `SetDisplayName` as `SetProfile`, refuses it for
a disabled principal, and makes, undoes and announces it as §10.9
requires.

**A client of the self socket** names nobody, since there is no field
to; opens a connection for each request; treats a `connect` refused for
permission as `Denied`; and changes credentials through PGSS Logon, not
here.

---

# Appendix 10.A Message Reference

_Peios Specifications / PSPU / Local Principal Administration_

> Every PLPS message by number, which reply answers which request, the protocol constants and the field limits.

## 10.A.1 Messages

| `msg_type` | Message | Direction | Answered with | Defined in |
|---|---|---|---|---|
| `0x0001` | `List` | client → store daemon | `Principals` | §10.5 |
| `0x0002` | `Show` | client → store daemon | `Principal` | §10.5 |
| `0x0003` | `Domain` | client → store daemon | `DomainIs` | §10.5 |
| `0x0004` | `Add` | client → store daemon | `Created` | §10.5 |
| `0x0005` | `Remove` | client → store daemon | `Done` | §10.5 |
| `0x0006` | `SetEnabled` | client → store daemon | `Done` | §10.5 |
| `0x0007` | `SetPassword` | client → store daemon | `Done` | §10.5 |
| `0x0008` | `GroupAdd` | client → store daemon | `Done` | §10.6 |
| `0x0009` | `GroupRemove` | client → store daemon | `Done` | §10.6 |
| `0x000a` | `GroupList` | client → store daemon | `Groups` | §10.6 |
| `0x000b` | `GroupCreate` | client → store daemon | `Created` | §10.6 |
| `0x000c` | `GroupDelete` | client → store daemon | `Done` | §10.6 |
| `0x000d` | `SetProfile` | client → store daemon | `Done` | §10.5 |
| `0x000e` | `SetPrimaryGroup` | client → store daemon | `Done` | §10.6 |
| `0x000f` | `SetClaim` | client → store daemon | `Done` | §10.7 |
| `0x0010` | `RemoveClaim` | client → store daemon | `Done` | §10.7 |
| `0x0011` | `KeyList` | client → store daemon | `Keys` | §10.8 |
| `0x0012` | `KeyAdd` | client → store daemon | `Done` | §10.8 |
| `0x0013` | `KeyRemove` | client → store daemon | `Done` | §10.8 |
| `0x0014` | `CredentialPolicy` | client → store daemon | `Done` | §10.8 |
| `0x0015` | `Rename` | client → store daemon | `Done` | §10.5 |
| `0x0016` | `SetLogonTypes` | client → store daemon | `Done` | §10.5 |
| `0x0017` | `GroupRename` | client → store daemon | `Done` | §10.6 |
| `0x0018` | `GroupDescribe` | client → store daemon | `Done` | §10.6 |
| `0x8001` | `Principals` | store daemon → client | | §10.5 |
| `0x8002` | `Principal` | store daemon → client | | §10.5 |
| `0x8003` | `DomainIs` | store daemon → client | | §10.5 |
| `0x8004` | `Created` | store daemon → client | | §10.9 |
| `0x8005` | `Done` | store daemon → client | | §10.9 |
| `0x8006` | `Failed` | store daemon → client | | §10.9 |
| `0x8007` | `Groups` | store daemon → client | | §10.6 |
| `0x8008` | `Keys` | store daemon → client | | §10.8 |

Any request may be answered with `Failed` instead.

### 10.A.1.1 On the self socket

| `msg_type` | Message | Direction | Answered with | Defined in |
|---|---|---|---|---|
| `0x0040` | `ShowSelf` | client → store daemon | `Self` | §10.11 |
| `0x0041` | `SetDisplayName` | client → store daemon | `Done` | §10.11 |
| `0x8040` | `Self` | store daemon → client | | §10.11 |

`Done` and `Failed` (§10.9) answer here too. Each socket refuses the
other's requests with `Invalid`.

## 10.A.2 Protocol constants

| Constant | Value | Defined in |
|---|---|---|
| Socket path | `/run/lpsd/admin.sock` on Peios | §10.3 |
| Self socket path | `/run/lpsd/self.sock` on Peios | §10.11 |
| Largest self-socket request | 4096 bytes | §10.11 |
| Magic | `PLPS` (`50 4c 50 53`) | §10.4 |
| Version | `1` | §10.4 |
| Header size | 12 bytes | §10.4 |
| Maximum message size | 2,097,152 bytes | §10.4 |
| Requests a connection | 1 | §10.3 |

## 10.A.3 Field limits

| Field | Limit |
|---|---|
| A principal's or group's name | 256 bytes |
| A password | 4096 bytes, never empty |
| `home`, `shell` | 4096 bytes |
| `display_name` | 256 bytes |
| A group's `description` | 1024 bytes |
| A principal's listed groups | 128 |
| Principals in `Principals` | 4096 |
| Groups in `Groups` | 4096 |
| A SID | 68 bytes |
| Claims on a principal | 64 |
| A claim's name | 255 bytes |
| A claim's values | 64 |
| A string or octet claim value | 1024 bytes |
| SSH keys on a principal | 32 |
| An SSH public key | 16384 bytes |
| A key's label | 128 bytes |
| A key's fingerprint | 128 bytes |
| A key's algorithm | 64 bytes |
| A refusal's `reason` | 512 bytes |

## 10.A.4 Enumerations

| Enumeration | Defined in |
|---|---|
| Failure | §10.9 |
| Credential policy | §10.8 |
| Logon types | PGSS §2.16, carried as PSI carries them (§2.13) |
| Claim value types and flags | PCDS §5.9, closed as on PSI (§2.A) |

---

# 11.1 Scope and Roles

_Peios Specifications / PSPU / Root Skeleton_

> The file that says what a root needs outside /usr, which no package can ship, and the parties that write and apply it.

This chapter defines the **root skeleton file**: a list of the directories
and symbolic links a root needs outside `/usr`, with a security descriptor
for any directory that needs one.

A package installs only under `/usr` (§5.14). A root still needs `/var`,
`/lcl`, `/tmp` and the other directories outside `/usr` before its first
program runs. It also needs `/lib64`, the link through which the x86-64
psABI finds the dynamic loader. Nothing that runs in the root can make
these, because the loader itself needs one of them. Whatever builds the
root makes them, from the skeleton file the root's own `/usr` holds.

## 11.1.1 Roles

**The provider** is the package that ships the skeleton file in its
payload, as an ordinary file under `/usr`. On Mainline this is
`dev.peios.fsbase`, and `dev.peios.fsbase-irf` for an initramfs.

**The applier** is whatever builds a root: a live-boot hook that composes
the root at boot, an image builder that composes an initramfs, an
installer, or an upgrade tool. It installs the root's packages, then
reads the skeleton file in that root and makes what it lists.

The provider decides what a root holds outside `/usr`. The applier
decides when to apply the file and against which root, but not what the
file contains. A root's packages, and so its provider, are chosen when
its closure is chosen. Nothing else selects a skeleton.

## 11.1.2 What this chapter leaves to others

What goes in `/usr` is the package format's (§5). Policy outside `/usr`
that differs from one image or machine to another, such as registry seeds
or an operator's local files, is not skeleton content. It belongs to the
image, the installer or the operator.

Mounting filesystems at the skeleton's directories is the boot process's
concern. The skeleton makes only the directories and links.

---

# 11.2 Terminology

_Peios Specifications / PSPU / Root Skeleton_

> Terms this chapter defines for itself — root, skeleton file, provider, applier, entry.

**Root.** A directory tree that a system, or an initramfs, runs with as
its `/`. Paths in a skeleton file are relative to it. §11.1

**Skeleton file.** The file at `/usr/share/skeleton` in a root, which
lists what that root needs outside `/usr`. §11.3

**Provider.** The package whose payload holds a root's skeleton file.
§11.1

**Applier.** The program that builds a root and applies its skeleton
file to it. §11.1

**Entry.** One line of a skeleton file that names a directory or a
symbolic link. §11.3

**Descriptor.** A security descriptor (PCDS 5), written in SDDL, that a
directory entry gives for the directory it names. §11.3

---

# 11.3 The File

_Peios Specifications / PSPU / Root Skeleton_

> Where the skeleton file is, how its lines are read, the two kinds of entry, and the rules every path, link target and descriptor follows.

The skeleton file is at `/usr/share/skeleton` in the root it describes.
A root has at most one, because one path in a closure belongs to one
package. It is UTF-8 text, with lines separated by a line feed (U+000A).

```text
# Directories outside /usr, each after its parent.
/var
/var/state
/var/state/secrets O:SYG:SYD:P(A;OICI;GA;;;SY)
/lib64 -> usr/lib/x86_64-linux-peios
```

## 11.3.1 Lines

A line is read after removing leading and trailing spaces (U+0020) and
tabs (U+0009). A line that is then empty, or that begins with `#`, is
ignored. A comment occupies a whole line; `#` later in a line is not a
comment.

Every other line is an entry. Its fields are separated by one or more
spaces or tabs, and it has one of three shapes:

| Shape | Entry |
|---|---|
| `path` | A directory with no descriptor. |
| `path descriptor` | A directory created with `descriptor`. |
| `path -> target` | A symbolic link at `path` whose content is `target`. |

A line of any other shape makes the file invalid.

## 11.3.2 Paths

Each `path` MUST:

- begin with `/` and name something under the root, not the root itself;
- be in canonical form, with no empty, `.` or `..` component and no
  trailing `/`;
- be outside `/usr`, neither `/usr` nor anything under it.

No two entries may have the same `path`.

## 11.3.3 Order

Entries are applied in the order the file gives them. The parent of each
entry's `path` MUST be the root, or a directory entry earlier in the file.
A file that lists a child before its parent, or under a link, is invalid.
A provider can list paths in byte order to satisfy this, because a
parent's path is a prefix of its children's.

## 11.3.4 Link targets

A `target` is the link's content, exactly as written. It MUST be
relative: it is resolved from the directory holding the link, so the link
works wherever the root is mounted, including while it is being built.
It MUST NOT have an empty component, and following its `..` components
from the link's directory MUST NOT go above the root.

## 11.3.5 Descriptors

A `descriptor` is a security descriptor in SDDL. It has no spaces or
tabs. It SHOULD name principals only by well-known SIDs or absolute SID
aliases, such as `SY` or `BA`. The file is applied before any domain or
machine exists to resolve anything else.

A directory without a descriptor inherits one from its parent, as any
new directory does.

A descriptor MUST grant whoever applies the file a right to read the
directory. Root builders run as SYSTEM, so a descriptor that grants
SYSTEM full control is enough.

---

# 11.4 Applying

_Peios Specifications / PSPU / Root Skeleton_

> When an applier applies the file, what it makes, what it leaves alone, and how it creates a directory with a descriptor.

An applier applies a root's skeleton file after installing the root's
packages, and before running anything from the root. It reads the file
from the root it is building, never from the system it is running on.

## 11.4.1 Check first

An applier MUST read the whole file before it changes the root. It
checks every line against §11.3 and every descriptor it will apply. A
file with any error is rejected whole, and nothing is made.

## 11.4.2 Make what is missing

The applier then takes each entry in order:

| What is at `path` | Directory entry | Link entry |
|---|---|---|
| Nothing | Create the directory | Create the link |
| A directory | Leave it | Fail |
| A link | Fail | Leave it if its content is `target`, otherwise fail |
| Anything else | Fail | Fail |

The applier MUST NOT follow a link at an entry's path, and MUST NOT make
an entry by way of a link. The order rule (§11.3) means each entry's
parent is the root or a directory the applier has already found or made.

An applier MUST NOT delete anything, and MUST NOT change anything it
finds, including an existing directory's descriptor. Applying the same
file twice makes nothing the second time.

On a failure, the applier stops and reports the entry and the reason.
What it made before the failure stays. Applying the file again, once
the obstacle is removed, continues from where it stopped.

## 11.4.3 Descriptors at creation

An applier MUST create a directory that has a descriptor with that
descriptor, in the same operation that creates it. On Peios this is the
kernel's native create, `kacs_open`, with the descriptor supplied as the
new directory's. It MUST NOT create the directory and then set its
descriptor, because the directory would have an inherited descriptor in
between.

An applier building a tree whose format holds no descriptors, such as an
initramfs archive, creates each directory without one. The descriptors
then have no effect in that tree. It still checks every descriptor's
syntax where it can, but it MUST NOT reject the file only because it
cannot apply the descriptors.

## 11.4.4 A root without a file

A root whose closure holds no skeleton file gets nothing from this
chapter. An applier SHOULD warn that the root has no skeleton file, and
MAY continue.

---

# 11.5 Extension

_Peios Specifications / PSPU / Root Skeleton_

> The skeleton file carries no version number; what may change in it, and what may not without a new path.

The skeleton file carries no version number. A provider changes what a
root holds by changing the file's entries, which needs no change to this
chapter.

## 11.5.1 What may not be added without a new file

A new kind of entry, such as a regular file or a device node. A new field
on an existing entry. A change to the meaning of an existing shape.

An applier that met such a line would reject the whole file (§11.4).
Such a change therefore needs a new file at a new path, which old
appliers do not read, and which the provider ships beside this one for
as long as old appliers remain.

## 11.5.2 What may never be added

**Anything under `/usr`, or anything that removes or changes what a root
holds.** Packages own `/usr`. A skeleton only adds what is missing, so
applying it to a running system or an upgraded root is always safe.

---

# 11.6 Conformance

_Peios Specifications / PSPU / Root Skeleton_

> Every requirement of this chapter collected by role — the provider and the applier.

## 11.6.1 A conforming provider

**The file.** Ships it at `/usr/share/skeleton` as an ordinary payload
file, in UTF-8 text (§11.3).

**Entries.** Writes only the three entry shapes, with absolute,
canonical paths outside `/usr`, each path once (§11.3).

**Order.** Lists each entry after its parent, which is the root or an
earlier directory entry (§11.3).

**Links.** Gives each link a relative target that stays inside the root
(§11.3).

**Descriptors.** Writes descriptors in SDDL without spaces, naming
principals by well-known SIDs or absolute aliases, and granting SYSTEM a
right to read each directory (§11.3).

## 11.6.2 A conforming applier

**When.** Applies the root's own file, after installing the root's
packages and before running anything from it (§11.4).

**Checking.** Rejects the whole file on any error, before making
anything (§11.4).

**Making.** Makes each missing entry in order. Leaves an existing
directory, or an existing link with the same target, as it is. Fails
on anything else at an entry's path, and reports the entry. Never
follows a link, deletes anything, or changes what it finds (§11.4).

**Descriptors.** Creates a directory that has a descriptor with that
descriptor in the same operation, never afterwards. Where the tree
cannot hold descriptors, creates the directory without one (§11.4).

**No file.** Warns when the root has no skeleton file (§11.4).
