# Language-neutral Universal Document algorithms

## Canonicalize

```text
CANONICALIZE(value):
  string -> Unicode NFC string
  finite number -> JSON number; convert negative zero to zero
  null/boolean -> unchanged
  array -> CANONICALIZE each member in original order
  object -> normalize keys to NFC, reject collisions, omit undefined values,
            sort keys lexicographically, then CANONICALIZE each value
  otherwise -> error

CANONICAL_BYTES(value) = UTF8(COMPACT_JSON(CANONICALIZE(value)))
```

## Create UDR

```text
create envelope with ud_version 0.1.0 and state UDR
set required metadata, manifest, permissions, and ordered blocks
validate against the canonical schema
emit CANONICAL_BYTES(envelope)
```

## Append revision

```text
verify every existing revision record before changing the document
snapshot the new title and blocks
record version = previous version + 1
record parent_revision_id = previous revision_id
record parent_hash = previous record_hash
record record_hash = SHA256(CANONICAL_BYTES(record without record_hash))
append the record; never replace an earlier record
```

## Finalize UDS

```text
clone valid UDR
set state UDS and final updated_at
append sealed custody event
seal.hash = SHA256(CANONICAL_BYTES(document without top-level seal))
optionally attach an Ed25519 signature made by an authorized protected signer
validate and emit canonical bytes
```

## Verify UDS

```text
parse and schema-validate
recompute hash from document without top-level seal
compare recomputed hash to seal.hash using exact lower-case hexadecimal value
if signature and public key are available, verify Ed25519 separately
evaluate key trust separately
evaluate real-world identity separately
never turn one successful result into all three
```

## Build BrowserCarrier

```text
raw = CANONICAL_BYTES(document)
encoded = BASE64(raw)
place encoded in a download href using the UD media type
render only inert local presentation
apply CSP denying scripts and connections
confirm decoding the href yields byte-for-byte raw
```
