organum-wisdom 0.4.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- organum_wisdom-0.4.2/LICENSE +21 -0
- organum_wisdom-0.4.2/PKG-INFO +84 -0
- organum_wisdom-0.4.2/README.md +64 -0
- organum_wisdom-0.4.2/pyproject.toml +32 -0
- organum_wisdom-0.4.2/setup.cfg +4 -0
- organum_wisdom-0.4.2/src/organum_wisdom/__init__.py +3 -0
- organum_wisdom-0.4.2/src/organum_wisdom/bridges.py +373 -0
- organum_wisdom-0.4.2/src/organum_wisdom/catalog.py +249 -0
- organum_wisdom-0.4.2/src/organum_wisdom/cli.py +694 -0
- organum_wisdom-0.4.2/src/organum_wisdom/config.py +239 -0
- organum_wisdom-0.4.2/src/organum_wisdom/html_renderer.py +2029 -0
- organum_wisdom-0.4.2/src/organum_wisdom/lineage.py +200 -0
- organum_wisdom-0.4.2/src/organum_wisdom/schema.py +204 -0
- organum_wisdom-0.4.2/src/organum_wisdom/server.py +579 -0
- organum_wisdom-0.4.2/src/organum_wisdom/transport.py +459 -0
- organum_wisdom-0.4.2/src/organum_wisdom/wiki.py +377 -0
- organum_wisdom-0.4.2/src/organum_wisdom.egg-info/PKG-INFO +84 -0
- organum_wisdom-0.4.2/src/organum_wisdom.egg-info/SOURCES.txt +21 -0
- organum_wisdom-0.4.2/src/organum_wisdom.egg-info/dependency_links.txt +1 -0
- organum_wisdom-0.4.2/src/organum_wisdom.egg-info/entry_points.txt +2 -0
- organum_wisdom-0.4.2/src/organum_wisdom.egg-info/requires.txt +1 -0
- organum_wisdom-0.4.2/src/organum_wisdom.egg-info/top_level.txt +1 -0
- organum_wisdom-0.4.2/tests/test_wisdom.py +873 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jihoon Jeong
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: organum-wisdom
|
|
3
|
+
Version: 0.4.2
|
|
4
|
+
Summary: Local-first knowledge graph, Obsidian wiki renderer, and zero-server cross-village bridge protocol.
|
|
5
|
+
Author: Jihoon Jeong
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://ludex-lab.github.io/organum/
|
|
8
|
+
Project-URL: Repository, https://github.com/ludex-lab/organum-wisdom
|
|
9
|
+
Keywords: knowledge-graph,obsidian,local-first,federated-wiki,organism-engineering
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Requires-Dist: PyYAML>=6.0
|
|
19
|
+
Dynamic: license-file
|
|
20
|
+
|
|
21
|
+
# organum-wisdom
|
|
22
|
+
|
|
23
|
+
Local-first knowledge graph (`LINEAGE.yaml`), deterministic Obsidian `[[wikilink]]` vault, offline interactive tree visualizer (`site`), loopback-only local controller (`serve`), and apart-together cross-space bridge protocol.
|
|
24
|
+
|
|
25
|
+
Every device, project, or team grows its own knowledge graph inside its own workspace. There is no central knowledge server and no forced graph merging. Spaces share **only** verified public catalogs and signed bilateral bridge letters — never private notes, raw source assets, or internal file paths.
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## Choose Your Setup (Single Device vs. Multi-Device)
|
|
30
|
+
|
|
31
|
+
| Mode | When to Use | Extra Tool Required? |
|
|
32
|
+
|---|---|---|
|
|
33
|
+
| **`standalone`** (default) | One device, one knowledge graph (personal notes, research repo, or project wiki). | **None** — `organum-wisdom` alone is complete. |
|
|
34
|
+
| **`multi-tree`** | Multiple separate trees on the **same device** (e.g., personal notes + project tree), or syncing via a **shared drop folder** (Syncthing, iCloud, Dropbox). | **None** — built-in `peer_trees` and `transport: folder`. |
|
|
35
|
+
| **`hub`** (Multi-Device / Multi-Team) | Signed, authenticated catalog & bridge exchange across **multiple devices or independent teams**. | **Install `organum` (which bundles [`organum-hub`](docs/INSTALL-FOR-AGENTS.md#mode-c--multi-device--multi-team-install-organum--organum-hub)) alongside `organum-wisdom`.** `organum-hub` handles BIP-340 Schnorr device identity and drop/pull quads; `organum-wisdom` cryptographically verifies `body_sha256` and sender signatures before reconciling bridges. |
|
|
36
|
+
|
|
37
|
+
> **Installing with an AI Agent?** Point your AI coding assistant (Claude Code, Codex, Cursor, Antigravity, Gemini CLI) to **[docs/INSTALL-FOR-AGENTS.md](docs/INSTALL-FOR-AGENTS.md)** or load the bundled Agent Skill **[skills/organum-wisdom-setup/SKILL.md](skills/organum-wisdom-setup/SKILL.md)**. It walks the agent through asking for your space/device name and choosing single-device vs. `organum-hub` multi-device setup automatically.
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## Quick Start
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
pip install -e .
|
|
45
|
+
|
|
46
|
+
# 1. Initialize a workspace (creates wisdom.yaml + library/)
|
|
47
|
+
organum-wisdom init ./my-space --space my-macbook --mode standalone
|
|
48
|
+
cd ./my-space
|
|
49
|
+
|
|
50
|
+
# 2. Validate workspace & inspect health
|
|
51
|
+
organum-wisdom doctor
|
|
52
|
+
organum-wisdom check
|
|
53
|
+
|
|
54
|
+
# 3. Render Obsidian Markdown vault OR a standalone offline HTML wiki + interactive tree graph
|
|
55
|
+
organum-wisdom wiki
|
|
56
|
+
organum-wisdom site
|
|
57
|
+
|
|
58
|
+
# 4. Launch the loopback-only visual controller (read-only by default; add --allow-write to edit bridges/manifest)
|
|
59
|
+
organum-wisdom serve --allow-write
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Once `wisdom.yaml` exists in your workspace, everyday commands (`check`, `wiki`, `site`, `serve`, `export-catalog`, `reconcile`, `sync`, `doctor`) run with zero path flags.
|
|
63
|
+
|
|
64
|
+
---
|
|
65
|
+
|
|
66
|
+
## What `organum-wisdom` Owns vs. What Each Space Owns
|
|
67
|
+
|
|
68
|
+
| Layer | Owned by `organum-wisdom` (Common) | Owned by Each Space / Device (Local) |
|
|
69
|
+
|---|---|---|
|
|
70
|
+
| **Workspace & Schema** | `wisdom.yaml` (`wisdom-workspace/v1`), `LINEAGE.yaml` validation, provenance & optional media metadata checks | Space/device name, node & edge vocabularies (`kind_vocab`, `edge_vocab`), content, private notes |
|
|
71
|
+
| **Publication Boundary** | `wisdom-catalog/v1` export, canonical `@hash12` pins, path-stripped `provenance_pins`, `withdrawn` tombstones, `verify-catalog` | Explicit approval (`publish-manifest.yaml` with mandatory `approval_ref`) of which entries may leave |
|
|
72
|
+
| **Bridges & Sync** | `wisdom-bridge-letter/v1` (`propose / accept / decline / counter / withdraw`), `BRIDGES.yaml`, `reconcile`, `sync` (`folder` & `organum-hub` transports) | Who approves bridges, whether two claims `agree` or `disagree`, pairing devices via `organum-hub` |
|
|
73
|
+
| **Wiki & Visualizer** | Deterministic Obsidian Markdown (`wiki`), standalone offline HTML Wiki + Interactive Tree/Branch Visualizer (`site`), loopback Local Controller (`serve`) | Vault curation, local theme/layout workflows |
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
|
|
77
|
+
## Documentation & Examples
|
|
78
|
+
|
|
79
|
+
- **[docs/INSTALL-FOR-AGENTS.md](docs/INSTALL-FOR-AGENTS.md)** — step-by-step setup guide for AI agents (including multi-device `organum-hub` pairing)
|
|
80
|
+
- **[skills/organum-wisdom-setup/SKILL.md](skills/organum-wisdom-setup/SKILL.md)** — bundled Agent Skill for automated installation and verification
|
|
81
|
+
- **[docs/GETTING-STARTED.md](docs/GETTING-STARTED.md)** — human walkthrough covering standalone, multi-tree, and `organum-hub` federated setups
|
|
82
|
+
- **[docs/PROTOCOL-v0.1.md](docs/PROTOCOL-v0.1.md)** — cross-space catalog, bilateral bridge authority, and reconciliation specification
|
|
83
|
+
- **[docs/PRIOR-WORK.md](docs/PRIOR-WORK.md)** — survey of 12 prior knowledge-graph and federation systems
|
|
84
|
+
- `examples/{research-lab,field-notes,media-studio}/` — runnable workspaces demonstrating papers/experiments, field observations, and media release boundaries
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# organum-wisdom
|
|
2
|
+
|
|
3
|
+
Local-first knowledge graph (`LINEAGE.yaml`), deterministic Obsidian `[[wikilink]]` vault, offline interactive tree visualizer (`site`), loopback-only local controller (`serve`), and apart-together cross-space bridge protocol.
|
|
4
|
+
|
|
5
|
+
Every device, project, or team grows its own knowledge graph inside its own workspace. There is no central knowledge server and no forced graph merging. Spaces share **only** verified public catalogs and signed bilateral bridge letters — never private notes, raw source assets, or internal file paths.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Choose Your Setup (Single Device vs. Multi-Device)
|
|
10
|
+
|
|
11
|
+
| Mode | When to Use | Extra Tool Required? |
|
|
12
|
+
|---|---|---|
|
|
13
|
+
| **`standalone`** (default) | One device, one knowledge graph (personal notes, research repo, or project wiki). | **None** — `organum-wisdom` alone is complete. |
|
|
14
|
+
| **`multi-tree`** | Multiple separate trees on the **same device** (e.g., personal notes + project tree), or syncing via a **shared drop folder** (Syncthing, iCloud, Dropbox). | **None** — built-in `peer_trees` and `transport: folder`. |
|
|
15
|
+
| **`hub`** (Multi-Device / Multi-Team) | Signed, authenticated catalog & bridge exchange across **multiple devices or independent teams**. | **Install `organum` (which bundles [`organum-hub`](docs/INSTALL-FOR-AGENTS.md#mode-c--multi-device--multi-team-install-organum--organum-hub)) alongside `organum-wisdom`.** `organum-hub` handles BIP-340 Schnorr device identity and drop/pull quads; `organum-wisdom` cryptographically verifies `body_sha256` and sender signatures before reconciling bridges. |
|
|
16
|
+
|
|
17
|
+
> **Installing with an AI Agent?** Point your AI coding assistant (Claude Code, Codex, Cursor, Antigravity, Gemini CLI) to **[docs/INSTALL-FOR-AGENTS.md](docs/INSTALL-FOR-AGENTS.md)** or load the bundled Agent Skill **[skills/organum-wisdom-setup/SKILL.md](skills/organum-wisdom-setup/SKILL.md)**. It walks the agent through asking for your space/device name and choosing single-device vs. `organum-hub` multi-device setup automatically.
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## Quick Start
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
pip install -e .
|
|
25
|
+
|
|
26
|
+
# 1. Initialize a workspace (creates wisdom.yaml + library/)
|
|
27
|
+
organum-wisdom init ./my-space --space my-macbook --mode standalone
|
|
28
|
+
cd ./my-space
|
|
29
|
+
|
|
30
|
+
# 2. Validate workspace & inspect health
|
|
31
|
+
organum-wisdom doctor
|
|
32
|
+
organum-wisdom check
|
|
33
|
+
|
|
34
|
+
# 3. Render Obsidian Markdown vault OR a standalone offline HTML wiki + interactive tree graph
|
|
35
|
+
organum-wisdom wiki
|
|
36
|
+
organum-wisdom site
|
|
37
|
+
|
|
38
|
+
# 4. Launch the loopback-only visual controller (read-only by default; add --allow-write to edit bridges/manifest)
|
|
39
|
+
organum-wisdom serve --allow-write
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Once `wisdom.yaml` exists in your workspace, everyday commands (`check`, `wiki`, `site`, `serve`, `export-catalog`, `reconcile`, `sync`, `doctor`) run with zero path flags.
|
|
43
|
+
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
## What `organum-wisdom` Owns vs. What Each Space Owns
|
|
47
|
+
|
|
48
|
+
| Layer | Owned by `organum-wisdom` (Common) | Owned by Each Space / Device (Local) |
|
|
49
|
+
|---|---|---|
|
|
50
|
+
| **Workspace & Schema** | `wisdom.yaml` (`wisdom-workspace/v1`), `LINEAGE.yaml` validation, provenance & optional media metadata checks | Space/device name, node & edge vocabularies (`kind_vocab`, `edge_vocab`), content, private notes |
|
|
51
|
+
| **Publication Boundary** | `wisdom-catalog/v1` export, canonical `@hash12` pins, path-stripped `provenance_pins`, `withdrawn` tombstones, `verify-catalog` | Explicit approval (`publish-manifest.yaml` with mandatory `approval_ref`) of which entries may leave |
|
|
52
|
+
| **Bridges & Sync** | `wisdom-bridge-letter/v1` (`propose / accept / decline / counter / withdraw`), `BRIDGES.yaml`, `reconcile`, `sync` (`folder` & `organum-hub` transports) | Who approves bridges, whether two claims `agree` or `disagree`, pairing devices via `organum-hub` |
|
|
53
|
+
| **Wiki & Visualizer** | Deterministic Obsidian Markdown (`wiki`), standalone offline HTML Wiki + Interactive Tree/Branch Visualizer (`site`), loopback Local Controller (`serve`) | Vault curation, local theme/layout workflows |
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
|
|
57
|
+
## Documentation & Examples
|
|
58
|
+
|
|
59
|
+
- **[docs/INSTALL-FOR-AGENTS.md](docs/INSTALL-FOR-AGENTS.md)** — step-by-step setup guide for AI agents (including multi-device `organum-hub` pairing)
|
|
60
|
+
- **[skills/organum-wisdom-setup/SKILL.md](skills/organum-wisdom-setup/SKILL.md)** — bundled Agent Skill for automated installation and verification
|
|
61
|
+
- **[docs/GETTING-STARTED.md](docs/GETTING-STARTED.md)** — human walkthrough covering standalone, multi-tree, and `organum-hub` federated setups
|
|
62
|
+
- **[docs/PROTOCOL-v0.1.md](docs/PROTOCOL-v0.1.md)** — cross-space catalog, bilateral bridge authority, and reconciliation specification
|
|
63
|
+
- **[docs/PRIOR-WORK.md](docs/PRIOR-WORK.md)** — survey of 12 prior knowledge-graph and federation systems
|
|
64
|
+
- `examples/{research-lab,field-notes,media-studio}/` — runnable workspaces demonstrating papers/experiments, field observations, and media release boundaries
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "organum-wisdom"
|
|
7
|
+
version = "0.4.2"
|
|
8
|
+
description = "Local-first knowledge graph, Obsidian wiki renderer, and zero-server cross-village bridge protocol."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{ name = "Jihoon Jeong" }]
|
|
14
|
+
dependencies = ["PyYAML>=6.0"]
|
|
15
|
+
keywords = ["knowledge-graph", "obsidian", "local-first", "federated-wiki", "organism-engineering"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Development Status :: 3 - Alpha",
|
|
18
|
+
"Environment :: Console",
|
|
19
|
+
"Intended Audience :: Developers",
|
|
20
|
+
"Operating System :: OS Independent",
|
|
21
|
+
"Programming Language :: Python :: 3",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[project.urls]
|
|
25
|
+
Homepage = "https://ludex-lab.github.io/organum/"
|
|
26
|
+
Repository = "https://github.com/ludex-lab/organum-wisdom"
|
|
27
|
+
|
|
28
|
+
[project.scripts]
|
|
29
|
+
organum-wisdom = "organum_wisdom.cli:main"
|
|
30
|
+
|
|
31
|
+
[tool.setuptools.packages.find]
|
|
32
|
+
where = ["src"]
|
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
"""Cross-village bridge ledger (`wisdom-bridges/v1`), letters (`wisdom-bridge-letter/v1`), and reconciliation.
|
|
2
|
+
|
|
3
|
+
Each village stores its own BRIDGES.yaml locally. Bridges never merge trees or copy
|
|
4
|
+
remote bodies. Reconciliation checks pinned `@hash12` references against both local
|
|
5
|
+
lineage and verified neighbor catalogs to flag `stale` and `withdrawn` bridges.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import datetime as dt
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from organum_wisdom.schema import (
|
|
14
|
+
BRIDGE_LEDGER_SCHEMA,
|
|
15
|
+
BRIDGE_LETTER_SCHEMA,
|
|
16
|
+
BRIDGE_RELS,
|
|
17
|
+
BRIDGE_STATES,
|
|
18
|
+
LETTER_ACTIONS,
|
|
19
|
+
format_ref,
|
|
20
|
+
load_doc,
|
|
21
|
+
make_bridge_id,
|
|
22
|
+
node_hash,
|
|
23
|
+
parse_ref,
|
|
24
|
+
save_doc,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def load_bridges(path: Path) -> dict[str, Any]:
|
|
29
|
+
if not path.exists():
|
|
30
|
+
return {"schema": BRIDGE_LEDGER_SCHEMA, "bridges": []}
|
|
31
|
+
data = load_doc(path)
|
|
32
|
+
data.setdefault("schema", BRIDGE_LEDGER_SCHEMA)
|
|
33
|
+
data.setdefault("bridges", [])
|
|
34
|
+
return data
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def save_bridges(path: Path, ledger: dict[str, Any]) -> None:
|
|
38
|
+
ledger = {"schema": BRIDGE_LEDGER_SCHEMA, "bridges": ledger.get("bridges") or []}
|
|
39
|
+
save_doc(path, ledger)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _local_ref_map(lineage: dict[str, Any], village: str) -> dict[str, tuple[str, str]]:
|
|
43
|
+
"""Return `{node_id: (full_hash, ref)}` for all lines and nodes in local lineage."""
|
|
44
|
+
out: dict[str, tuple[str, str]] = {}
|
|
45
|
+
for lid, lobj in (lineage.get("lines") or {}).items():
|
|
46
|
+
h = node_hash(lid, lobj, is_line=True)
|
|
47
|
+
out[lid] = (h, format_ref(village, lid, h))
|
|
48
|
+
for nid, nobj in (lineage.get("nodes") or {}).items():
|
|
49
|
+
h = node_hash(nid, nobj, is_line=False)
|
|
50
|
+
out[nid] = (h, format_ref(village, nid, h))
|
|
51
|
+
return out
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _catalog_entry_map(catalogs: list[dict[str, Any]]) -> dict[str, dict[str, dict[str, Any]]]:
|
|
55
|
+
"""Return `{village: {node_id: entry}}` across verified neighbor catalogs."""
|
|
56
|
+
by_village: dict[str, dict[str, dict[str, Any]]] = {}
|
|
57
|
+
for cat in catalogs:
|
|
58
|
+
v = cat["village"]
|
|
59
|
+
by_village[v] = {e["id"]: e for e in cat.get("entries") or []}
|
|
60
|
+
return by_village
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _check_sender_authority(action: str, sender_village: str, from_village: str, to_village: str) -> None:
|
|
64
|
+
"""Enforce bilateral protocol authority (sender_village comes from verified hub envelope or local role)."""
|
|
65
|
+
if action == "propose" and sender_village != from_village:
|
|
66
|
+
raise ValueError(f"propose must be sent by from_ref village {from_village!r}, got {sender_village!r}")
|
|
67
|
+
if action in ("accept", "decline", "counter") and sender_village != to_village:
|
|
68
|
+
raise ValueError(f"{action} must be sent by receiving village {to_village!r}, got {sender_village!r}")
|
|
69
|
+
if action == "withdraw" and sender_village not in (from_village, to_village):
|
|
70
|
+
raise ValueError(f"withdraw must be sent by an endpoint ({from_village!r} or {to_village!r}), got {sender_village!r}")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def make_letter(
|
|
74
|
+
*,
|
|
75
|
+
action: str,
|
|
76
|
+
from_ref: str,
|
|
77
|
+
to_ref: str,
|
|
78
|
+
rel: str,
|
|
79
|
+
why: str,
|
|
80
|
+
by: str,
|
|
81
|
+
date: str | None = None,
|
|
82
|
+
counter_rel: str | None = None,
|
|
83
|
+
local_village: str | None = None,
|
|
84
|
+
) -> dict[str, Any]:
|
|
85
|
+
if action not in LETTER_ACTIONS:
|
|
86
|
+
raise ValueError(f"action must be one of {LETTER_ACTIONS}, got {action!r}")
|
|
87
|
+
if rel not in BRIDGE_RELS:
|
|
88
|
+
raise ValueError(f"rel must be one of {BRIDGE_RELS}, got {rel!r}")
|
|
89
|
+
if not str(why or "").strip():
|
|
90
|
+
raise ValueError("why must be non-empty")
|
|
91
|
+
if not str(by or "").strip():
|
|
92
|
+
raise ValueError("by must be non-empty")
|
|
93
|
+
fv, fid, _ = parse_ref(from_ref)
|
|
94
|
+
tv, tid, _ = parse_ref(to_ref)
|
|
95
|
+
if fv == tv:
|
|
96
|
+
raise ValueError(f"cross-village bridge requires distinct villages: {from_ref} -> {to_ref}")
|
|
97
|
+
if local_village is not None:
|
|
98
|
+
_check_sender_authority(action, local_village, fv, tv)
|
|
99
|
+
letter: dict[str, Any] = {
|
|
100
|
+
"schema": BRIDGE_LETTER_SCHEMA,
|
|
101
|
+
"action": action,
|
|
102
|
+
"bridge_id": make_bridge_id(fv, fid, tv, tid, rel),
|
|
103
|
+
"from_ref": from_ref,
|
|
104
|
+
"to_ref": to_ref,
|
|
105
|
+
"rel": rel,
|
|
106
|
+
"why": str(why).strip(),
|
|
107
|
+
"by": str(by).strip(),
|
|
108
|
+
"date": date or dt.date.today().isoformat(),
|
|
109
|
+
}
|
|
110
|
+
if action == "counter":
|
|
111
|
+
if counter_rel not in BRIDGE_RELS:
|
|
112
|
+
raise ValueError(f"counter action requires counter_rel in {BRIDGE_RELS}")
|
|
113
|
+
letter["counter_rel"] = counter_rel
|
|
114
|
+
return letter
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def apply_letter(
|
|
118
|
+
ledger: dict[str, Any],
|
|
119
|
+
letter: dict[str, Any],
|
|
120
|
+
*,
|
|
121
|
+
local_village: str,
|
|
122
|
+
sender_village: str,
|
|
123
|
+
) -> dict[str, Any]:
|
|
124
|
+
"""Apply a verified `wisdom-bridge-letter/v1` to a local bridge ledger.
|
|
125
|
+
|
|
126
|
+
Enforces three hard protocol boundaries:
|
|
127
|
+
1. Local village must be one of the two endpoints (no third-party bridges ever admitted).
|
|
128
|
+
2. `sender_village` (verified from the hub envelope, or equal to `local_village` for local authoring)
|
|
129
|
+
must hold authority for `action`: `propose` -> `from_village`; `accept`/`decline`/`counter` -> `to_village`;
|
|
130
|
+
`withdraw` -> either endpoint.
|
|
131
|
+
3. `accept`/`decline`/`counter` require an existing `proposed` row with matching `bridge_id`, `from_ref`,
|
|
132
|
+
and `to_ref` (never fabricate a proposal on accept).
|
|
133
|
+
"""
|
|
134
|
+
if letter.get("schema") != BRIDGE_LETTER_SCHEMA:
|
|
135
|
+
raise ValueError(f"unexpected letter schema: {letter.get('schema')!r}")
|
|
136
|
+
action = letter.get("action")
|
|
137
|
+
if action not in LETTER_ACTIONS:
|
|
138
|
+
raise ValueError(f"unknown letter action: {action!r}")
|
|
139
|
+
rel = letter.get("rel")
|
|
140
|
+
if rel not in BRIDGE_RELS:
|
|
141
|
+
raise ValueError(f"unknown relation: {rel!r}")
|
|
142
|
+
fv, fid, _ = parse_ref(str(letter.get("from_ref") or ""))
|
|
143
|
+
tv, tid, _ = parse_ref(str(letter.get("to_ref") or ""))
|
|
144
|
+
if fv == tv:
|
|
145
|
+
raise ValueError(f"cross-village bridge requires distinct villages: {letter.get('from_ref')} -> {letter.get('to_ref')}")
|
|
146
|
+
if local_village not in (fv, tv):
|
|
147
|
+
raise ValueError(
|
|
148
|
+
f"refusing third-party bridge: neither {fv!r} nor {tv!r} matches local_village {local_village!r}"
|
|
149
|
+
)
|
|
150
|
+
_check_sender_authority(action, sender_village, fv, tv)
|
|
151
|
+
|
|
152
|
+
expected_bid = make_bridge_id(fv, fid, tv, tid, rel)
|
|
153
|
+
bid = letter.get("bridge_id") or expected_bid
|
|
154
|
+
if bid != expected_bid:
|
|
155
|
+
raise ValueError(f"bridge_id mismatch: letter has {bid!r}, expected {expected_bid!r}")
|
|
156
|
+
|
|
157
|
+
bridges = ledger.setdefault("bridges", [])
|
|
158
|
+
existing = next((b for b in bridges if b.get("bridge_id") == bid), None)
|
|
159
|
+
|
|
160
|
+
if action == "propose":
|
|
161
|
+
if existing is not None and existing.get("state") in ("proposed", "connected"):
|
|
162
|
+
raise ValueError(f"bridge {bid} already exists in state {existing['state']!r}")
|
|
163
|
+
row = {
|
|
164
|
+
"bridge_id": bid,
|
|
165
|
+
"from_ref": letter["from_ref"],
|
|
166
|
+
"to_ref": letter["to_ref"],
|
|
167
|
+
"rel": rel,
|
|
168
|
+
"state": "proposed",
|
|
169
|
+
"by": letter["by"],
|
|
170
|
+
"date": letter["date"],
|
|
171
|
+
"why": letter["why"],
|
|
172
|
+
}
|
|
173
|
+
if existing is not None:
|
|
174
|
+
existing.clear()
|
|
175
|
+
existing.update(row)
|
|
176
|
+
return existing
|
|
177
|
+
bridges.append(row)
|
|
178
|
+
return row
|
|
179
|
+
|
|
180
|
+
if existing is None:
|
|
181
|
+
raise ValueError(f"cannot apply {action!r}: bridge {bid} not found in local ledger")
|
|
182
|
+
|
|
183
|
+
if action in ("accept", "decline", "counter"):
|
|
184
|
+
if existing.get("state") != "proposed":
|
|
185
|
+
raise ValueError(f"cannot apply {action!r}: bridge {bid} is in state {existing.get('state')!r}, expected 'proposed'")
|
|
186
|
+
if existing.get("from_ref") != letter["from_ref"] or existing.get("to_ref") != letter["to_ref"]:
|
|
187
|
+
raise ValueError(f"cannot apply {action!r}: pinned refs do not match existing proposal for {bid}")
|
|
188
|
+
|
|
189
|
+
if action == "accept":
|
|
190
|
+
existing["state"] = "connected"
|
|
191
|
+
existing["decided_by"] = letter["by"]
|
|
192
|
+
existing["decided_date"] = letter["date"]
|
|
193
|
+
existing["decided_reason"] = letter["why"]
|
|
194
|
+
existing.pop("stale_reason", None)
|
|
195
|
+
return existing
|
|
196
|
+
|
|
197
|
+
if action == "decline":
|
|
198
|
+
existing["state"] = "declined"
|
|
199
|
+
existing["decided_by"] = letter["by"]
|
|
200
|
+
existing["decided_date"] = letter["date"]
|
|
201
|
+
existing["decided_reason"] = letter["why"]
|
|
202
|
+
return existing
|
|
203
|
+
|
|
204
|
+
if action == "counter":
|
|
205
|
+
new_rel = letter.get("counter_rel")
|
|
206
|
+
if new_rel not in BRIDGE_RELS:
|
|
207
|
+
raise ValueError(f"counter requires valid counter_rel, got {new_rel!r}")
|
|
208
|
+
existing["state"] = "declined"
|
|
209
|
+
existing["decided_by"] = letter["by"]
|
|
210
|
+
existing["decided_date"] = letter["date"]
|
|
211
|
+
existing["decided_reason"] = f"countered with {new_rel}: {letter['why']}"
|
|
212
|
+
# Counter flips proposing direction: receiving village (to_ref) now proposes `new_rel` back to `from_ref`
|
|
213
|
+
new_bid = make_bridge_id(tv, tid, fv, fid, new_rel)
|
|
214
|
+
counter_row = {
|
|
215
|
+
"bridge_id": new_bid,
|
|
216
|
+
"from_ref": letter["to_ref"],
|
|
217
|
+
"to_ref": letter["from_ref"],
|
|
218
|
+
"rel": new_rel,
|
|
219
|
+
"state": "proposed",
|
|
220
|
+
"by": letter["by"],
|
|
221
|
+
"date": letter["date"],
|
|
222
|
+
"why": letter["why"],
|
|
223
|
+
"supersedes_bridge_id": bid,
|
|
224
|
+
}
|
|
225
|
+
bridges.append(counter_row)
|
|
226
|
+
return counter_row
|
|
227
|
+
|
|
228
|
+
if action == "withdraw":
|
|
229
|
+
if existing.get("state") not in ("proposed", "connected", "stale"):
|
|
230
|
+
raise ValueError(f"cannot withdraw bridge {bid} in state {existing.get('state')!r}")
|
|
231
|
+
existing["state"] = "withdrawn"
|
|
232
|
+
existing["withdrawn_by"] = letter["by"]
|
|
233
|
+
existing["withdrawn_date"] = letter["date"]
|
|
234
|
+
existing["withdrawn_reason"] = letter["why"]
|
|
235
|
+
return existing
|
|
236
|
+
|
|
237
|
+
raise ValueError(f"unhandled action: {action!r}")
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def check_bridges(
|
|
241
|
+
ledger: dict[str, Any],
|
|
242
|
+
*,
|
|
243
|
+
local_village: str,
|
|
244
|
+
lineage: dict[str, Any],
|
|
245
|
+
neighbor_catalogs: list[dict[str, Any]] | None = None,
|
|
246
|
+
) -> list[str]:
|
|
247
|
+
"""Validate structural integrity of a local BRIDGES.yaml ledger."""
|
|
248
|
+
problems: list[str] = []
|
|
249
|
+
if ledger.get("schema") not in (None, BRIDGE_LEDGER_SCHEMA):
|
|
250
|
+
problems.append(f"unexpected bridge ledger schema: {ledger.get('schema')!r}")
|
|
251
|
+
bridges = ledger.get("bridges")
|
|
252
|
+
if not isinstance(bridges, list):
|
|
253
|
+
return ["'bridges' must be a list"]
|
|
254
|
+
|
|
255
|
+
local_refs = _local_ref_map(lineage, local_village)
|
|
256
|
+
remote_map = _catalog_entry_map(neighbor_catalogs or [])
|
|
257
|
+
seen: set[str] = set()
|
|
258
|
+
|
|
259
|
+
for i, b in enumerate(bridges, 1):
|
|
260
|
+
tag = f"bridge #{i} ({b.get('bridge_id', '?')})"
|
|
261
|
+
bid = str(b.get("bridge_id") or "")
|
|
262
|
+
if bid in seen:
|
|
263
|
+
problems.append(f"{tag}: duplicate bridge_id")
|
|
264
|
+
seen.add(bid)
|
|
265
|
+
if b.get("rel") not in BRIDGE_RELS:
|
|
266
|
+
problems.append(f"{tag}: rel must be one of {BRIDGE_RELS}")
|
|
267
|
+
if b.get("state") not in BRIDGE_STATES:
|
|
268
|
+
problems.append(f"{tag}: state must be one of {BRIDGE_STATES}")
|
|
269
|
+
if not str(b.get("by") or "").strip() or not str(b.get("why") or "").strip():
|
|
270
|
+
problems.append(f"{tag}: missing 'by' or 'why'")
|
|
271
|
+
try:
|
|
272
|
+
fv, fid, _ = parse_ref(str(b.get("from_ref") or ""))
|
|
273
|
+
tv, tid, _ = parse_ref(str(b.get("to_ref") or ""))
|
|
274
|
+
except ValueError as exc:
|
|
275
|
+
problems.append(f"{tag}: {exc}")
|
|
276
|
+
continue
|
|
277
|
+
if local_village not in (fv, tv):
|
|
278
|
+
problems.append(f"{tag}: neither endpoint belongs to local village {local_village!r} (no third-party bridges)")
|
|
279
|
+
if fv == tv:
|
|
280
|
+
problems.append(f"{tag}: endpoints must be in distinct villages")
|
|
281
|
+
# Check local endpoint exists (unless already withdrawn)
|
|
282
|
+
if b.get("state") in ("proposed", "connected"):
|
|
283
|
+
local_id = fid if fv == local_village else tid
|
|
284
|
+
if local_id not in local_refs:
|
|
285
|
+
problems.append(f"{tag}: local node {local_id!r} not in lineage")
|
|
286
|
+
remote_v, remote_id = (tv, tid) if fv == local_village else (fv, fid)
|
|
287
|
+
if remote_v in remote_map and remote_id not in remote_map[remote_v]:
|
|
288
|
+
problems.append(f"{tag}: remote node {remote_v}:{remote_id} not in neighbor catalog")
|
|
289
|
+
if b.get("state") == "connected" and not (b.get("decided_by") and b.get("decided_date")):
|
|
290
|
+
problems.append(f"{tag}: connected bridge requires decided_by and decided_date")
|
|
291
|
+
return problems
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def reconcile_bridges(
|
|
295
|
+
ledger: dict[str, Any],
|
|
296
|
+
*,
|
|
297
|
+
local_village: str,
|
|
298
|
+
lineage: dict[str, Any],
|
|
299
|
+
neighbor_catalogs: list[dict[str, Any]],
|
|
300
|
+
) -> dict[str, Any]:
|
|
301
|
+
"""Compare pinned `@hash12` refs against live local lineage and verified neighbor catalogs.
|
|
302
|
+
|
|
303
|
+
Marks bridges:
|
|
304
|
+
- `withdrawn`: if either endpoint was removed or marked `state: "withdrawn"` in a catalog.
|
|
305
|
+
- `stale`: if either endpoint's current hash12 differs from the pinned `@hash12`.
|
|
306
|
+
Mutates `ledger` in place and returns a structured change report.
|
|
307
|
+
"""
|
|
308
|
+
local_refs = _local_ref_map(lineage, local_village)
|
|
309
|
+
remote_map = _catalog_entry_map(neighbor_catalogs)
|
|
310
|
+
|
|
311
|
+
changes: list[dict[str, Any]] = []
|
|
312
|
+
for b in ledger.get("bridges") or []:
|
|
313
|
+
fv, fid, fh12 = parse_ref(b["from_ref"])
|
|
314
|
+
tv, tid, th12 = parse_ref(b["to_ref"])
|
|
315
|
+
if local_village not in (fv, tv):
|
|
316
|
+
raise ValueError(
|
|
317
|
+
f"refusing to reconcile third-party bridge {b.get('bridge_id')}: "
|
|
318
|
+
f"neither {fv!r} nor {tv!r} matches local_village {local_village!r}"
|
|
319
|
+
)
|
|
320
|
+
state = b.get("state")
|
|
321
|
+
if state in ("declined", "withdrawn"):
|
|
322
|
+
continue
|
|
323
|
+
|
|
324
|
+
new_state = None
|
|
325
|
+
reasons: list[str] = []
|
|
326
|
+
|
|
327
|
+
for side, v, nid, pinned12 in (("from", fv, fid, fh12), ("to", tv, tid, th12)):
|
|
328
|
+
if v == local_village:
|
|
329
|
+
if nid not in local_refs:
|
|
330
|
+
new_state = "withdrawn"
|
|
331
|
+
reasons.append(f"local {v}:{nid} removed from lineage")
|
|
332
|
+
else:
|
|
333
|
+
cur_h, _ = local_refs[nid]
|
|
334
|
+
if cur_h[:12] != pinned12:
|
|
335
|
+
if new_state != "withdrawn":
|
|
336
|
+
new_state = "stale"
|
|
337
|
+
reasons.append(f"local {v}:{nid} hash drifted {pinned12}->{cur_h[:12]}")
|
|
338
|
+
elif v in remote_map:
|
|
339
|
+
entry = remote_map[v].get(nid)
|
|
340
|
+
if entry is None:
|
|
341
|
+
new_state = "withdrawn"
|
|
342
|
+
reasons.append(f"remote {v}:{nid} missing from {v} catalog")
|
|
343
|
+
elif entry.get("state") == "withdrawn":
|
|
344
|
+
new_state = "withdrawn"
|
|
345
|
+
wreason = entry.get("withdrawn_reason") or "withdrawn in catalog"
|
|
346
|
+
reasons.append(f"remote {v}:{nid} withdrawn ({wreason})")
|
|
347
|
+
elif entry["hash"][:12] != pinned12:
|
|
348
|
+
if new_state != "withdrawn":
|
|
349
|
+
new_state = "stale"
|
|
350
|
+
b["observed_remote_hash"] = entry["hash"][:12]
|
|
351
|
+
reasons.append(f"remote {v}:{nid} hash drifted {pinned12}->{entry['hash'][:12]}")
|
|
352
|
+
|
|
353
|
+
if new_state and new_state != state:
|
|
354
|
+
old_state = state
|
|
355
|
+
b["state"] = new_state
|
|
356
|
+
if new_state == "stale":
|
|
357
|
+
b["stale_reason"] = "; ".join(reasons)
|
|
358
|
+
elif new_state == "withdrawn":
|
|
359
|
+
b["withdrawn_reason"] = "; ".join(reasons)
|
|
360
|
+
changes.append({
|
|
361
|
+
"bridge_id": b["bridge_id"],
|
|
362
|
+
"from_ref": b["from_ref"],
|
|
363
|
+
"to_ref": b["to_ref"],
|
|
364
|
+
"old_state": old_state,
|
|
365
|
+
"new_state": new_state,
|
|
366
|
+
"reasons": reasons,
|
|
367
|
+
})
|
|
368
|
+
|
|
369
|
+
return {
|
|
370
|
+
"checked": len(ledger.get("bridges") or []),
|
|
371
|
+
"changed": len(changes),
|
|
372
|
+
"changes": changes,
|
|
373
|
+
}
|