Files
encyclopedia-knowledge-graph/docs/archive/ASSESSMENT-IPLD-DAG-JSON-CODEC-INTEGRATION.md
T

104 lines
8.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Technical Assessment: Integrating the IPLD `dag-json` Codec (`0x0129`) Across the `hyperstitionstud.io` JSON Data Ecosystem
- **Document ID:** `ASSESSMENT-IPLD-DAG-JSON-CODEC-INTEGRATION` (`v2.0.0`)
- **Codec Specification:** IPLD `dag-json` (`multicodec 0x0129`) + `sha2-256` (`multihash 0x12`) + `CIDv1` Base32 (`baguqeera...`)
- **Evaluated Scope:** All 8 JSON registries in `technocapital-singularity-zoology`, `encyclopedia-graph.json` and `graph-data.js` in `encyclopedia-knowledge-graph`, `db.json` and `db_lite.json` in `haiperdohp-jemaytreeah`, and `ReadOnlyIsolationGuard` in `hyperstitionstudio-core` (`hyperstitionstud_io.*`).
---
## 1. Executive Summary
Integrating the **IPLD `dag-json` codec** (`multicodec 0x0129`, paired with `SHA-256` `multihash 0x12` and `CIDv1` `{"/": "baguqeera..."}` content-addressed links) aligns directly with the `hyperstitionstud.io` architecture. Because the workspace already enforces `SHA-256` immutability gates, offline-first `URN:` identifiers (`urn:io:hyperstitionstud:*`), and a multi-repository directed acyclic graph (`DAG`) of dependencies, adopting `dag-json` upgrades existing JSON artifacts into a cryptographically linked **Merkle DAG** while remaining `100%` valid RFC 8259 JSON readable by standard browser `JSON.parse()`, Python `json.loads()`, and `jq`.
---
## 2. Five Core Architectural Benefits
### 2.1 Deterministic Canonical Serialization (Eliminating Formatting-Induced Hash Drift)
- **Current Limitation:**
`ReadOnlyIsolationGuard` hashes raw file bytes (`hashlib.sha256(path.read_bytes())`). A non-semantic change in indentation (`indent=2` vs. minified), key ordering, or trailing newline alters the file's SHA-256 digest even when the underlying data model is identical (which previously required a separate normalized-JSON forensic audit).
- **How `dag-json` Solves It:**
The `dag-json` specification mandates a single deterministic byte representation for any IPLD Data Model object:
1. Map/object keys are sorted deterministically by UTF-8 byte sequence (RFC 8949 / IPLD canonical ordering),
2. All insignificant whitespace is omitted (`separators=(",", ":")`),
3. Non-portable IEEE-754 tokens (`NaN`, `Infinity`, `-Infinity`, `-0.0`) are rejected, and
4. Strings are encoded in canonical UTF-8 without arbitrary `\uXXXX` escape variations.
- **Result:** Any two runtimes (Python `hyperstitionstud_io` and browser JavaScript `window.HyperstitionStudio`) serializing the same in-memory structure always produce the **exact same byte stream, the exact same `SHA-256` digest, and the exact same `CIDv1`**.
### 2.2 First-Class Merkle-DAG Provenance Links (`{"/": "<CIDv1>"}`) Across Repositories
- **Current Limitation:**
`encyclopedia-graph.json` records upstream provenance via custom string fields (`"glossary_registry_sha256_pre": "7564ef40fb3e..."` and `"encyclopedia_manifest_sha256_pre": "0d7ce833bb0a..."`).
- **How `dag-json` Upgrades Provenance:**
In `dag-json`, cross-artifact references are represented as native **IPLD Links**:
```json
{
"upstream_glossary": {"/": "baguqeera..."},
"upstream_encyclopedia": {"/": "baguqeera..."}
}
```
Because a `dag-json` `CIDv1` consists of the 4-byte multicodec/multihash prefix (`0x01` `CIDv1` + `0x8002`/`0x0129` `dag-json` varint + `0x12` `sha2-256` + `0x20` 32-byte length) followed immediately by the raw **32-byte SHA-256 digest** (encoded in lowercase RFC 4648 Base32 with multibase prefix `b` -> `baguqeera...`), every `CIDv1` is **100% mathematically reversible to and from our existing SHA-256 baseline locks** while turning all 8 JSON registries and `encyclopedia-graph.json` into a verifiable Merkle DAG.
### 2.3 Constant-Time `O(1)` Sub-Graph Diffing for `M7+` Two-Run (`Run N -> Run N+1`) Nucleation
- **Current Limitation:**
In `technocapital-singularity-zoology`, detecting whether an emergent `M7_candidate` or an `S1–S6` equivalence ring changed between daily `00:00 GMT` wire harvests requires traversing nested dictionaries and lists.
- **How `dag-json` Solves It:**
When each assemblage build (`build:S1..Q0`), AQ coordinate hub (`aq:71..777`), and lexical specimen (`spec:*`) is canonicalized as a `dag-json` block with its own `CIDv1`, any unchanged node or equivalence ring retains the exact same CID across runs. Cross-run persistence checking (`Run N -> Run N+1`) and incremental graph rebuilds reduce to `O(1)` CID comparisons.
### 2.4 100% Standard RFC 8259 JSON Compatibility in Browser (`file://`) and CLI (`jq`)
- Unlike binary `dag-cbor` (`multicodec 0x71`), which requires a CBOR decoder library in the browser and cannot be inspected directly with standard text tools, `dag-json` is **strictly valid UTF-8 JSON**.
- Consequently:
- `<script src="graph-data.js">` and `JSON.parse()` in `index.html` work with zero external JS libraries,
- `json.loads()` in Python 3.10+ standard library parses it natively, and
- `jq` in the terminal queries it directly, preserving 100% offline `file://` portability.
### 2.5 Transport-Agnostic Content Addressing (Local Disk, Static HTTP/3, `.car` Archives & IPFS)
- Just as replacing `https://` schema URLs with `urn:io:hyperstitionstud:*` eliminated outbound DNS/HTTPS dependencies for offline users, `CIDv1` links (`{"/": "baguqeera..."}`) address data purely by cryptographic content rather than server hostname.
- The exact same `dag-json` blocks can be resolved from local disk (`/workspace/...`), from RAM-backed Caddy HTTP/3 routes (`https://hyperstitionstud.io/...`), from a single-file Content-Addressable Archive (`.car`), or from IPFS/Helia/Iroh gateways without modifying a single byte of data.
---
## 3. Zero-Dependency Implementation Footprint in `hyperstitionstud_io`
Implementing `dag-json` canonical encoding and `CIDv1` (`baguqeera...`) generation inside `hyperstitionstudio-core` (`src/hyperstitionstud_io/ipld/__init__.py`) requires **zero third-party Python packages** (`100%` Python standard library: `hashlib`, `base64`, `json`):
```python
import base64
import hashlib
import json
from typing import Any
# Multicodec varint header for CIDv1 (0x01) + dag-json (0x0129 -> varint 0xa9 0x02)
# + sha2-256 (0x12) + 32-byte digest length (0x20)
_CIDV1_DAG_JSON_SHA256_PREFIX = bytes([0x01, 0xA9, 0x02, 0x12, 0x20])
def encode_dag_json(obj: Any) -> bytes:
"""Serialize a Python object to canonical UTF-8 dag-json bytes."""
return json.dumps(
obj,
sort_keys=True,
separators=(",", ":"),
ensure_ascii=False,
allow_nan=False,
).encode("utf-8")
def compute_dag_json_cidv1(obj: Any) -> str:
"""Compute the multibase Base32lower CIDv1 ('baguqeera...') for a dag-json object."""
raw_bytes = encode_dag_json(obj)
digest = hashlib.sha256(raw_bytes).digest()
cid_bytes = _CIDV1_DAG_JSON_SHA256_PREFIX + digest
b32 = base64.b32encode(cid_bytes).decode("ascii").lower().rstrip("=")
return "b" + b32
```
- **Zero Schema Collisions:** In `dag-json`, single-key maps of the form `{"/": "..."}` are reserved for IPLD Links and Bytes. None of the 8 JSON schemas in the workspace use `"/"` as a property key, so all existing registries are 100% compatible with the `dag-json` data model.
---
## 4. Trade-Off Analysis & Recommended Hybrid Adoption Strategy
| Dimension | Pure On-Disk `dag-json` Everywhere | Recommended Hybrid `dag-json` Strategy |
| :--- | :--- | :--- |
| **Human-Edited Source Registries (`glossary-registry.json`, `quantitative-economic-anchors.json`)** | Minified single-line JSON makes line-by-line `git diff` harder to read during manual review. | Keep pretty-printed (`indent=2`) on disk for readable Git diffs, while computing and verifying their canonical `dag-json` `CIDv1` (`baguqeera...`) in `ReadOnlyIsolationGuard` and `hs-doctor` (alongside raw file SHA-256). |
| **Compiled Machine Bundles (`encyclopedia-graph.json`, `graph-data.js`, `db_lite.json`, `db.json`)** | Ideal: minified canonical `dag-json` reduces uncompressed payload size by `~18–25%` before Brotli-11 compression. | Emit strict canonical `dag-json` with embedded `{"/": "baguqeera..."}` IPLD Links pointing to the upstream source registries and node sub-blocks. |
| **Existing Raw SHA-256 Locks (`7564ef40fb3e...` & `0d7ce833bb0a...`)** | Replacing raw file SHA-256 outright would change gate receipt format. | Preserve raw file `SHA-256` gates (`Gate 1` & `Gate 2`) unchanged while adding `dag_json_cidv1` (`{"/": "baguqeera..."}`) alongside them for zero-regression backwards compatibility. |