# MD-LD — Core Specification (Minimal)

**Markdown-Linked Data**

A deterministic, streaming-friendly semantic annotation layer for CommonMark Markdown that emits RDF quads **only** from explicit `{...}` annotations.

---

## 1. Core Guarantees

1. **Markdown-preserving** - Removing `{...}` yields valid Markdown
2. **No implicit semantics** - Everything must be explicit
3. **Explicit origin** - All quads come from `{...}` blocks
4. **Single-pass streaming** - No backtracking required
5. **No blank nodes** - Every entity has an IRI
6. **No inference** - No guessing or structural heuristics
7. **Traceable** - Every quad traces to source span

---

## 2. Graph Model

MD-LD creates facts: **Subject → Predicate → Object**

**Building blocks:**
- **IRIs** - Unique identifiers (subjects and objects)
- **Literals** - Data values (objects only)

**Rules:**
- IRIs can be subjects or objects
- Literals are always objects
- Creates a directed labeled multigraph

---

## 3. Available Nodes (S, O, L)

When parsing `{...}`, MD-LD knows:

- **S** - Current subject (IRI, from `{=IRI}` or `{=#fragment}`)
- **O** - Object resource (IRI, from links/images or `{=IRI}`)  
- **L** - Literal value (text from value carrier)

---

## 4. Value Carriers

`{...}` attaches to exactly one value carrier:

### Inline
- `[text] {...}` - Link text
- `*text* {...}`, `_text_ {...}` - Emphasis
- `**text** {...}`, `__text__ {...}` - Strong
- `` `text` {...}`` - Code

### Block
- `# Heading {...}` - Heading text
- `- item {...}` - List item text
- `> quote {...}` - Quote text
- ````lang {...}`` - Code block content

### Links/Media
- `<URL> {...}` - URL (IRI)
- `[label](URL) {...}` - Link (text + URL)
- `![alt](URL) {...}` - Image (alt + URL)

**Rule:** `{...}` must immediately follow the carrier.

---

## 5. Semantic Block Attachment

`{...}` blocks attach by:

1. **Nearest preceding value carrier**, OR
2. **Stand alone** - applies to current subject or following list

**Ambiguous attachment = no output**

---

## 6. Subjects

### Full IRI
```
{=IRI}
```
Sets current subject. Persists until changed.

### Fragment
```
{=#fragment}
```
Creates `currentSubjectBase#fragment`. Requires existing subject.

### Soft Object IRI (Temporary)

```
{+iri}
```

Declares a temporary object for use with `?` and `!` predicates, without changing the current subject.

### Soft Fragment (Temporary)

```
{+#fragment}
```

Creates a temporary fragment relative to the current subject base.

**Use cases:**
- `[Related Item] {+ex:related ?schema:isRelatedTo}` - Links to a local fragment
- `[Parent] {+ex:parent !schema:hasPart}` - Reverse relationship
- `[Section] {+#section1 name ?hasPart}` - Object property with fragment

The soft IRI only exists within the current annotation block.

### Primary Metadata

MD-LD tracks three primary metadata fields during single-pass parsing:

| Field | Source | Purpose |
|-------|--------|---------|
| **primarySubject** | First non-fragment `{=subject}` | Document identity |
| **primaryType** | First `.Class` declaration | Document category |
| **primaryLabel** | First `{label}` literal | Human-readable name |
| **primaryComment** | First `{comment}` literal | Human-readable description |

**Selection rules:**
- First occurrence only (fixed once detected)
- Never cleared on `{=}` reset
- Returns `null` if not declared

**API returns:**
- `parse()`: `{ quads, remove, statements, origin, context, primarySubject, primary, md }`
  - `primary`: `{ subject, type, label, comment }` (semantic surface descriptor)
- `merge()`: `{ quads, remove, statements, origin, context, primarySubjects, primary }`
  - `primarySubjects`: ordered array of canonical identities
  - `primary`: array of semantic surface descriptors
- `generate({ quads, context, primarySubject })`: Places primary subject first for round-trip safety

**Use cases:** Document identity, stream addressing, merge tracking, UI navigation, query optimization, content classification, search indexing.

---

## 7. Elevated Statements

MD-LD automatically detects `rdf:Statement` patterns during parsing to create a "golden graph" of important statements.

**Detection:** Subject typed as `rdf:Statement` with `rdf:subject`, `rdf:predicate`, `rdf:object` properties.

**Elevated quad:** Creates direct SPO quad from the statement's subject/predicate/object values.

**API access:** `result.statements` array contains all elevated quads.

**Benefits:** Golden graph access, full provenance retention, single-pass detection, memory efficient.

---

## 8. Types

```
.Class
```
Declares type: `S rdf:type schema:Class`

Multiple types allowed: `.Person .Astronaut`

---

## 8. Predicate Forms

| Syntax | Direction | Use |
|--------|-----------|-----|
| `p`    | S → L     | Literal properties |
| `?p`   | S → O     | Object properties |
| `!p`   | O → S     | Reverse properties |

**Emission rule:** Create quad only if all nodes exist and roles are valid.

### 8.1 Diff Polarity (Remove Tokens)

Prefix `-` to any predicate for remove polarity:

| Syntax | Effect |
|--------|--------|
| `-p`   | Remove S→L fact |
| `-?p`  | Remove S→O fact |
| `-!p`  | Remove O→S fact |
| `-.C`  | Remove rdf:type fact |

**Live state routing:** Cancel if quad exists in buffer, else add to remove array.

**Parse result:** `{ quads, remove, origin, context }`

**Invariant:** `quads ∩ remove = ∅`

---

## 9. Literals

Extracted **only** from attached value carrier.

### Datatypes/Languages
```
^^datatypeIRI  # Typed data
@lang          # Language tag
```

Mutually exclusive. Common types: `xsd:string`, `xsd:integer`, `xsd:gYear`, `xsd:date`, `xsd:boolean`.

---

## 10. Object Resources

Available from:
- Link URLs: `[text](URL)`
- Image URLs: `![alt](URL)`  
- Explicit IRIs: `{=IRI}`

**Example:**
```md
## References {=ex:references}
[Example image](https://example.com/image.jpg) {?image name}
[W3C RDF](https://www.w3.org/RDF) {?dct:references name}
[Alice] {=urn:person:alice ?author name}
```

**Result:**
```turtle
ex:references schema:image <https://example.com/image.jpg> .
<https://example.com/image.jpg> schema:name "Example image" .
ex:references dct:references <https://www.w3.org/RDF> .
<https://www.w3.org/RDF> schema:name "W3C RDF" .
ex:references schema:author <urn:person:alice> .
<urn:person:alice> schema:name "Alice" .
```

---

## 11. Lists

Lists are pure Markdown structure with **no semantic scope**. Each list item requires explicit annotations.

### Explicit List Annotations

```md
[@vocab] <http://www.w3.org/2000/01/rdf-schema#>

## Research Team {=prj:team .Container label}
Team members:

- **Lead researcher** {+prj:lead ?member .Person label}
- **Data analyst** {+prj:analyst ?member .Person label}
```

**Key Rules:**
- No semantic propagation from list scope
- Each item must have explicit annotations
- Use `+IRI` to maintain subject chaining for repeated object properties
- Nested lists have no inheritance

**Ordered lists** require explicit rdf:List construction:
```md
[ex] <http://example.org/>

# Manual list construction {=ex:manualList label}
[head] {=ex:l1 ?sh:in .rdf:List}
[a] {+ex:A ?rdf:first}
[list2] {=ex:l2 ?rdf:rest}
[b] {+ex:B ?rdf:first}
[nil] {+rdf:nil ?rdf:rest}
{=}
```

---

## 12. Reverse Relationships

`!p` flips direction only, not meaning.

**Example:**
```md
Used in: {!hasPart}
- Bread {=ex:bread}
```
Creates: `ex:bread schema:hasPart S`

---

## 13. Code Blocks

`{...}` on opening fence makes code block a value carrier.

**Example:**
```md
```js {=ex:code .SoftwareSourceCode text}
console.log("hi")
```
```

**Result:**
```turtle
ex:code a schema:SoftwareSourceCode ;
  schema:text "console.log(\"hi\")" .
```

---

## 14. Context

### Default Context
```json
{
    "@vocab": "http://www.w3.org/2000/01/rdf-schema#",
    "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
    "rdfs": "http://www.w3.org/2000/01/rdf-schema#",
    "xsd": "http://www.w3.org/2001/XMLSchema#",
    "sh": "http://www.w3.org/ns/shacl#",
    "prov": "http://www.w3.org/ns/prov#"
}
```

### Prefix Declaration
```
[prefix] <IRI>
```

### Prefix Folding: Hierarchical IRI Authoring

Build namespace hierarchies by referencing previously declared prefixes:

```
[my] <tag:mymail@domain.com,2026:>
[j] <my:journal:>
[p] <my:property:>
[org] <https://org.example.com/>
[person] <org:person/>
[emp] <person:employee/>
```

**Resolution Rules:**
- Prefixes must be declared before they can be referenced (forward-reference only)
- References are resolved immediately during declaration
- Circular references are treated as literal strings
- Later declarations override earlier ones

### Vocabulary Setting
```
[@vocab] <IRI>
```

**Rules:** Apply forward, later overrides earlier, single-pass resolution.

---

## 15. Forbidden Constructs

- Implicit labels
- Structural inference  
- Auto-subjects
- Literal lists
- Blank nodes
- key=value syntax
- Predicate guessing
- Backtracking parses
- CURIE in Markdown links
- **Semantic list propagation**

These ensure predictability, traceability, and single-pass processing.

---

## 16. Conformance

A conformant MD-LD processor must:

1. Follow predicate routing rules (§8)
2. Emit quads only from `{...}` blocks
3. Implement single-pass streaming parsing
4. Provide deterministic output
5. Maintain traceable origins
6. Support all three predicate forms (`p`, `?p`, `!p`)

No guessing, no blank nodes, no backtracking. Round-trip MD → RDF → MD preserves quads and origins.
