wikidelta 0.1.0__py3-none-any.whl
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.
- wikidelta/__init__.py +1 -0
- wikidelta/cli.py +132 -0
- wikidelta/document.py +100 -0
- wikidelta/models.py +33 -0
- wikidelta/repository.py +50 -0
- wikidelta/service.py +171 -0
- wikidelta/sources.py +159 -0
- wikidelta-0.1.0.dist-info/METADATA +375 -0
- wikidelta-0.1.0.dist-info/RECORD +13 -0
- wikidelta-0.1.0.dist-info/WHEEL +5 -0
- wikidelta-0.1.0.dist-info/entry_points.txt +2 -0
- wikidelta-0.1.0.dist-info/licenses/LICENSE +201 -0
- wikidelta-0.1.0.dist-info/top_level.txt +1 -0
wikidelta/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
wikidelta/cli.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import typer
|
|
7
|
+
|
|
8
|
+
from wikidelta.repository import Repository
|
|
9
|
+
from wikidelta.service import add_source, apply_review, extract_effective, status_items, update_document, write_review
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
app = typer.Typer(no_args_is_help=True)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@app.callback()
|
|
16
|
+
def main() -> None:
|
|
17
|
+
"""Manage WikiDelta .wd lifecycle files."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def emit(payload: dict, *, as_json: bool) -> None:
|
|
21
|
+
if as_json:
|
|
22
|
+
typer.echo(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
23
|
+
else:
|
|
24
|
+
typer.echo(payload.get("message", json.dumps(payload, ensure_ascii=False)))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@app.command()
|
|
28
|
+
def init(
|
|
29
|
+
workspace: Path = typer.Option(Path.cwd(), "--workspace", help="Workspace root."),
|
|
30
|
+
mode: str = typer.Option("llmwiki_project", "--mode", help="Repository mode."),
|
|
31
|
+
json_output: bool = typer.Option(False, "--json", help="Emit JSON output."),
|
|
32
|
+
) -> None:
|
|
33
|
+
repo = Repository(workspace)
|
|
34
|
+
repo.ensure_layout(mode=mode)
|
|
35
|
+
emit(
|
|
36
|
+
{
|
|
37
|
+
"ok": True,
|
|
38
|
+
"workspace": str(repo.root),
|
|
39
|
+
"mode": mode,
|
|
40
|
+
"config": str(repo.config_path),
|
|
41
|
+
"message": f"Initialized WikiDelta workspace at {repo.root}",
|
|
42
|
+
},
|
|
43
|
+
as_json=json_output,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@app.command()
|
|
48
|
+
def add(
|
|
49
|
+
target: str = typer.Argument(..., help="Local file path or URL to wrap as a .wd source."),
|
|
50
|
+
into: Path | None = typer.Option(None, "--into", help="Directory where the .wd file is written."),
|
|
51
|
+
workspace: Path = typer.Option(Path.cwd(), "--workspace", help="Workspace root."),
|
|
52
|
+
title: str | None = typer.Option(None, "--title", help="Knowledge title."),
|
|
53
|
+
json_output: bool = typer.Option(False, "--json", help="Emit JSON output."),
|
|
54
|
+
) -> None:
|
|
55
|
+
wd_path = add_source(target, workspace=workspace, into=into, title=title)
|
|
56
|
+
emit(
|
|
57
|
+
{
|
|
58
|
+
"ok": True,
|
|
59
|
+
"path": str(wd_path),
|
|
60
|
+
"message": f"Created {wd_path}",
|
|
61
|
+
},
|
|
62
|
+
as_json=json_output,
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@app.command()
|
|
67
|
+
def update(
|
|
68
|
+
path: Path | None = typer.Argument(None, help=".wd file to update. Omit to update all .wd files in the workspace."),
|
|
69
|
+
workspace: Path = typer.Option(Path.cwd(), "--workspace", help="Workspace root."),
|
|
70
|
+
json_output: bool = typer.Option(False, "--json", help="Emit JSON output."),
|
|
71
|
+
) -> None:
|
|
72
|
+
if path is None:
|
|
73
|
+
repo = Repository(workspace)
|
|
74
|
+
items = [update_document(wd_path, workspace=repo.root) for wd_path in repo.iter_wd_files()]
|
|
75
|
+
emit({"ok": True, "workspace": str(repo.root), "items": items}, as_json=json_output)
|
|
76
|
+
return
|
|
77
|
+
if path.suffix != ".wd":
|
|
78
|
+
payload = {
|
|
79
|
+
"ok": False,
|
|
80
|
+
"error": {
|
|
81
|
+
"code": "INVALID_UPDATE_TARGET",
|
|
82
|
+
"message": "wd update only accepts .wd files. Run wd update path/to/file.wd, not the original source file.",
|
|
83
|
+
},
|
|
84
|
+
}
|
|
85
|
+
emit(payload, as_json=json_output)
|
|
86
|
+
raise typer.Exit(1)
|
|
87
|
+
emit(update_document(path, workspace=workspace), as_json=json_output)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@app.command()
|
|
91
|
+
def status(
|
|
92
|
+
workspace: Path = typer.Option(Path.cwd(), "--workspace", help="Workspace root."),
|
|
93
|
+
json_output: bool = typer.Option(False, "--json", help="Emit JSON output."),
|
|
94
|
+
) -> None:
|
|
95
|
+
items = status_items(workspace=workspace)
|
|
96
|
+
payload = {"ok": True, "workspace": str(workspace), "items": items}
|
|
97
|
+
emit(payload, as_json=json_output)
|
|
98
|
+
if any(item.get("state") in {"pending_review", "effective_changed"} for item in items):
|
|
99
|
+
raise typer.Exit(3)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@app.command()
|
|
103
|
+
def review(
|
|
104
|
+
path: Path = typer.Argument(..., help=".wd file to review."),
|
|
105
|
+
workspace: Path = typer.Option(Path.cwd(), "--workspace", help="Workspace root."),
|
|
106
|
+
json_output: bool = typer.Option(False, "--json", help="Emit JSON output."),
|
|
107
|
+
) -> None:
|
|
108
|
+
emit({"ok": True, "review": write_review(path, workspace=workspace)}, as_json=json_output)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@app.command("apply")
|
|
112
|
+
def apply_cmd(
|
|
113
|
+
path: Path = typer.Argument(..., help=".wd file to apply."),
|
|
114
|
+
workspace: Path = typer.Option(Path.cwd(), "--workspace", help="Workspace root."),
|
|
115
|
+
strategy: str = typer.Option("replace", "--strategy", help="Apply strategy."),
|
|
116
|
+
yes: bool = typer.Option(False, "--yes", help="Confirm lifecycle mutation."),
|
|
117
|
+
json_output: bool = typer.Option(False, "--json", help="Emit JSON output."),
|
|
118
|
+
) -> None:
|
|
119
|
+
emit(apply_review(path, workspace=workspace, strategy=strategy, yes=yes), as_json=json_output)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@app.command()
|
|
123
|
+
def ingest(
|
|
124
|
+
path: Path = typer.Argument(..., help=".wd file to extract for llmwiki."),
|
|
125
|
+
workspace: Path = typer.Option(Path.cwd(), "--workspace", help="Workspace root."),
|
|
126
|
+
json_output: bool = typer.Option(False, "--json", help="Emit JSON output."),
|
|
127
|
+
) -> None:
|
|
128
|
+
emit(extract_effective(path, workspace=workspace), as_json=json_output)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
if __name__ == "__main__":
|
|
132
|
+
app()
|
wikidelta/document.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import re
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import yaml
|
|
9
|
+
|
|
10
|
+
from wikidelta.models import WdMeta
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
FRONT_MATTER_RE = re.compile(r"\A---\n(.*?)\n---\n?", re.DOTALL)
|
|
14
|
+
SECTION_RE = re.compile(r"<!-- wd:([a-z_]+) -->\n?(.*?)\n?<!-- /wd:\1 -->", re.DOTALL)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class WdParseError(ValueError):
|
|
18
|
+
pass
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def content_hash(content: str) -> str:
|
|
22
|
+
return "sha256:" + hashlib.sha256(content.encode("utf-8")).hexdigest()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass
|
|
26
|
+
class WdDocument:
|
|
27
|
+
meta: WdMeta
|
|
28
|
+
sections: dict[str, str]
|
|
29
|
+
|
|
30
|
+
@classmethod
|
|
31
|
+
def parse(cls, text: str) -> "WdDocument":
|
|
32
|
+
match = FRONT_MATTER_RE.match(text)
|
|
33
|
+
if not match:
|
|
34
|
+
raise WdParseError("Missing YAML front matter")
|
|
35
|
+
|
|
36
|
+
raw_meta = yaml.safe_load(match.group(1)) or {}
|
|
37
|
+
meta = WdMeta.model_validate(raw_meta)
|
|
38
|
+
body = text[match.end() :]
|
|
39
|
+
sections = {name: content.strip("\n") for name, content in SECTION_RE.findall(body)}
|
|
40
|
+
|
|
41
|
+
if "effective" not in sections:
|
|
42
|
+
raise WdParseError("Missing wd:effective section")
|
|
43
|
+
|
|
44
|
+
return cls(meta=meta, sections=sections)
|
|
45
|
+
|
|
46
|
+
def section(self, name: str, default: str | None = None) -> str | None:
|
|
47
|
+
return self.sections.get(name, default)
|
|
48
|
+
|
|
49
|
+
def set_section(self, name: str, content: str) -> None:
|
|
50
|
+
self.sections[name] = content.strip("\n")
|
|
51
|
+
|
|
52
|
+
def remove_section(self, name: str) -> None:
|
|
53
|
+
self.sections.pop(name, None)
|
|
54
|
+
|
|
55
|
+
def to_text(self) -> str:
|
|
56
|
+
meta_dict = self.meta.model_dump(mode="json", exclude_none=True)
|
|
57
|
+
front_matter = yaml.safe_dump(meta_dict, sort_keys=False, allow_unicode=True).strip()
|
|
58
|
+
section_names = ["effective"]
|
|
59
|
+
if "source_snapshot" in self.sections:
|
|
60
|
+
section_names.append("source_snapshot")
|
|
61
|
+
if "notes" in self.sections:
|
|
62
|
+
section_names.append("notes")
|
|
63
|
+
section_names.extend(name for name in self.sections if name not in section_names)
|
|
64
|
+
|
|
65
|
+
body_parts = []
|
|
66
|
+
for name in section_names:
|
|
67
|
+
body_parts.append(f"<!-- wd:{name} -->\n{self.sections[name].strip()}\n<!-- /wd:{name} -->")
|
|
68
|
+
return f"---\n{front_matter}\n---\n\n" + "\n\n".join(body_parts) + "\n"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def render_wd(*, wd_id: str, title: str, source: dict[str, Any], content: str) -> str:
|
|
72
|
+
body = content.strip("\n")
|
|
73
|
+
hash_value = content_hash(body)
|
|
74
|
+
meta = WdMeta.model_validate(
|
|
75
|
+
{
|
|
76
|
+
"wd_version": 1,
|
|
77
|
+
"id": wd_id,
|
|
78
|
+
"title": title,
|
|
79
|
+
"status": "active",
|
|
80
|
+
"content_type": "markdown",
|
|
81
|
+
"tags": [],
|
|
82
|
+
"source": source,
|
|
83
|
+
"sync": {
|
|
84
|
+
"strategy": "review_before_apply",
|
|
85
|
+
"state": "up_to_date",
|
|
86
|
+
"source_hash": hash_value,
|
|
87
|
+
"snapshot_hash": None,
|
|
88
|
+
"effective_hash": hash_value,
|
|
89
|
+
"last_ingested_at": None,
|
|
90
|
+
},
|
|
91
|
+
}
|
|
92
|
+
)
|
|
93
|
+
doc = WdDocument(
|
|
94
|
+
meta=meta,
|
|
95
|
+
sections={
|
|
96
|
+
"effective": body,
|
|
97
|
+
"notes": "",
|
|
98
|
+
},
|
|
99
|
+
)
|
|
100
|
+
return doc.to_text()
|
wikidelta/models.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel, Field
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class SourceConfig(BaseModel):
|
|
9
|
+
fetcher: str
|
|
10
|
+
fetch: dict[str, Any] = Field(default_factory=dict)
|
|
11
|
+
transformer: str
|
|
12
|
+
transform: dict[str, Any] = Field(default_factory=dict)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class SyncState(BaseModel):
|
|
16
|
+
state: str = "up_to_date"
|
|
17
|
+
strategy: str = "review_before_apply"
|
|
18
|
+
last_refreshed_at: str | None = None
|
|
19
|
+
source_hash: str | None = None
|
|
20
|
+
snapshot_hash: str | None = None
|
|
21
|
+
effective_hash: str | None = None
|
|
22
|
+
last_ingested_at: str | None = None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class WdMeta(BaseModel):
|
|
26
|
+
wd_version: int = 1
|
|
27
|
+
id: str
|
|
28
|
+
title: str
|
|
29
|
+
status: str = "active"
|
|
30
|
+
content_type: str = "markdown"
|
|
31
|
+
tags: list[str] = Field(default_factory=list)
|
|
32
|
+
source: SourceConfig
|
|
33
|
+
sync: SyncState = Field(default_factory=SyncState)
|
wikidelta/repository.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import yaml
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
STATE_DIRS = ("cache", "reviews", "errors", "ingest")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def find_workspace(start: Path | str) -> Path | None:
|
|
13
|
+
current = Path(start).resolve()
|
|
14
|
+
if current.is_file():
|
|
15
|
+
current = current.parent
|
|
16
|
+
for candidate in (current, *current.parents):
|
|
17
|
+
if (candidate / ".wikidelta").is_dir():
|
|
18
|
+
return candidate
|
|
19
|
+
return None
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class Repository:
|
|
24
|
+
root: Path
|
|
25
|
+
|
|
26
|
+
def __post_init__(self) -> None:
|
|
27
|
+
object.__setattr__(self, "root", Path(self.root).resolve())
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def state_dir(self) -> Path:
|
|
31
|
+
return self.root / ".wikidelta"
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def config_path(self) -> Path:
|
|
35
|
+
return self.state_dir / "config.yaml"
|
|
36
|
+
|
|
37
|
+
def ensure_layout(self, *, mode: str = "llmwiki_project") -> None:
|
|
38
|
+
self.state_dir.mkdir(parents=True, exist_ok=True)
|
|
39
|
+
for dirname in STATE_DIRS:
|
|
40
|
+
(self.state_dir / dirname).mkdir(parents=True, exist_ok=True)
|
|
41
|
+
if not self.config_path.exists():
|
|
42
|
+
self.config_path.write_text(yaml.safe_dump({"mode": mode}, sort_keys=False), encoding="utf-8")
|
|
43
|
+
|
|
44
|
+
def iter_wd_files(self) -> list[Path]:
|
|
45
|
+
files: list[Path] = []
|
|
46
|
+
for path in self.root.rglob("*.wd"):
|
|
47
|
+
if ".wikidelta" in path.relative_to(self.root).parts:
|
|
48
|
+
continue
|
|
49
|
+
files.append(path)
|
|
50
|
+
return sorted(files)
|
wikidelta/service.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import json
|
|
5
|
+
import difflib
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from wikidelta.document import WdDocument, content_hash, render_wd
|
|
9
|
+
from wikidelta.repository import Repository
|
|
10
|
+
from wikidelta.sources import fetch_source, infer_source_config, transform_content
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def slugify(value: str) -> str:
|
|
14
|
+
slug = re.sub(r"[^a-zA-Z0-9]+", "-", value).strip("-").lower()
|
|
15
|
+
return slug or "document"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def add_source(target: str, *, workspace: Path, into: Path | None = None, title: str | None = None) -> Path:
|
|
19
|
+
repo = Repository(workspace)
|
|
20
|
+
repo.ensure_layout()
|
|
21
|
+
source_config = infer_source_config(target)
|
|
22
|
+
raw = fetch_source(source_config["fetcher"], source_config["fetch"], workspace=repo.root, wd_id="new")
|
|
23
|
+
transformed = transform_content(source_config["transformer"], source_config.get("transform", {}), raw)
|
|
24
|
+
|
|
25
|
+
parsed_target = Path(target)
|
|
26
|
+
stem = parsed_target.stem if parsed_target.suffix else slugify(target.rstrip("/"))
|
|
27
|
+
wd_id = slugify(stem)
|
|
28
|
+
output_dir = into if into is not None else repo.root / "raw_source"
|
|
29
|
+
if not output_dir.is_absolute():
|
|
30
|
+
output_dir = repo.root / output_dir
|
|
31
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
32
|
+
wd_path = output_dir / f"{wd_id}.wd"
|
|
33
|
+
wd_path.write_text(
|
|
34
|
+
render_wd(
|
|
35
|
+
wd_id=wd_id,
|
|
36
|
+
title=title or stem.replace("-", " ").replace("_", " ").title(),
|
|
37
|
+
source=source_config,
|
|
38
|
+
content=transformed.content,
|
|
39
|
+
),
|
|
40
|
+
encoding="utf-8",
|
|
41
|
+
)
|
|
42
|
+
return wd_path
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def update_document(path: Path, *, workspace: Path) -> dict:
|
|
46
|
+
repo = Repository(workspace)
|
|
47
|
+
doc = WdDocument.parse(path.read_text(encoding="utf-8"))
|
|
48
|
+
source = doc.meta.source
|
|
49
|
+
raw = fetch_source(source.fetcher, source.fetch, workspace=repo.root, wd_id=doc.meta.id)
|
|
50
|
+
transformed = transform_content(source.transformer, source.transform, raw)
|
|
51
|
+
snapshot = transformed.content.strip("\n")
|
|
52
|
+
effective = doc.section("effective", default="").strip("\n")
|
|
53
|
+
doc.meta.sync.source_hash = content_hash(raw.content)
|
|
54
|
+
doc.meta.sync.effective_hash = content_hash(effective)
|
|
55
|
+
if snapshot == effective:
|
|
56
|
+
doc.remove_section("source_snapshot")
|
|
57
|
+
doc.meta.sync.state = "up_to_date"
|
|
58
|
+
doc.meta.sync.snapshot_hash = None
|
|
59
|
+
else:
|
|
60
|
+
doc.set_section("source_snapshot", snapshot)
|
|
61
|
+
doc.meta.sync.state = "pending_review"
|
|
62
|
+
doc.meta.sync.snapshot_hash = content_hash(snapshot)
|
|
63
|
+
path.write_text(doc.to_text(), encoding="utf-8")
|
|
64
|
+
return {"ok": True, "path": str(path), "id": doc.meta.id, "snapshotHash": doc.meta.sync.snapshot_hash}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def status_items(*, workspace: Path) -> list[dict]:
|
|
68
|
+
repo = Repository(workspace)
|
|
69
|
+
items: list[dict] = []
|
|
70
|
+
for path in repo.iter_wd_files():
|
|
71
|
+
try:
|
|
72
|
+
doc = WdDocument.parse(path.read_text(encoding="utf-8"))
|
|
73
|
+
effective_hash = content_hash(doc.section("effective", default="").strip("\n"))
|
|
74
|
+
snapshot = doc.section("source_snapshot", default=None)
|
|
75
|
+
snapshot_hash = content_hash(snapshot.strip("\n")) if snapshot is not None else None
|
|
76
|
+
state = "pending_review" if snapshot_hash is not None and effective_hash != snapshot_hash else "clean"
|
|
77
|
+
items.append(
|
|
78
|
+
{
|
|
79
|
+
"path": str(path.relative_to(repo.root)),
|
|
80
|
+
"id": doc.meta.id,
|
|
81
|
+
"state": state,
|
|
82
|
+
"effectiveChanged": effective_hash != doc.meta.sync.effective_hash,
|
|
83
|
+
"sourceChanged": snapshot_hash is not None and effective_hash != snapshot_hash,
|
|
84
|
+
"lastError": None,
|
|
85
|
+
}
|
|
86
|
+
)
|
|
87
|
+
except Exception as exc: # noqa: BLE001 - status must report invalid files.
|
|
88
|
+
items.append({"path": str(path.relative_to(repo.root)), "id": None, "state": "invalid", "lastError": str(exc)})
|
|
89
|
+
return items
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def write_review(path: Path, *, workspace: Path) -> dict:
|
|
93
|
+
repo = Repository(workspace)
|
|
94
|
+
repo.ensure_layout()
|
|
95
|
+
doc = WdDocument.parse(path.read_text(encoding="utf-8"))
|
|
96
|
+
effective = doc.section("effective", default="").strip("\n")
|
|
97
|
+
maybe_snapshot = doc.section("source_snapshot", default=None)
|
|
98
|
+
if maybe_snapshot is None:
|
|
99
|
+
return {
|
|
100
|
+
"wdId": doc.meta.id,
|
|
101
|
+
"path": str(path.relative_to(repo.root) if path.is_relative_to(repo.root) else path),
|
|
102
|
+
"state": "clean",
|
|
103
|
+
"effectiveHash": content_hash(effective),
|
|
104
|
+
"snapshotHash": None,
|
|
105
|
+
"summary": {"addedLines": 0, "removedLines": 0},
|
|
106
|
+
"actions": [{"name": "update", "command": f"wd update {path}"}],
|
|
107
|
+
}
|
|
108
|
+
snapshot = maybe_snapshot.strip("\n")
|
|
109
|
+
patch = "".join(
|
|
110
|
+
difflib.unified_diff(
|
|
111
|
+
effective.splitlines(keepends=True),
|
|
112
|
+
snapshot.splitlines(keepends=True),
|
|
113
|
+
fromfile="effective",
|
|
114
|
+
tofile="source_snapshot",
|
|
115
|
+
)
|
|
116
|
+
)
|
|
117
|
+
review = {
|
|
118
|
+
"wdId": doc.meta.id,
|
|
119
|
+
"path": str(path.relative_to(repo.root) if path.is_relative_to(repo.root) else path),
|
|
120
|
+
"state": "pending_review" if effective != snapshot else "clean",
|
|
121
|
+
"effectiveHash": content_hash(effective),
|
|
122
|
+
"snapshotHash": content_hash(snapshot),
|
|
123
|
+
"summary": {
|
|
124
|
+
"addedLines": sum(1 for line in patch.splitlines() if line.startswith("+") and not line.startswith("+++")),
|
|
125
|
+
"removedLines": sum(1 for line in patch.splitlines() if line.startswith("-") and not line.startswith("---")),
|
|
126
|
+
},
|
|
127
|
+
"actions": [{"name": "replace_effective", "command": f"wd apply {path} --strategy replace --yes"}],
|
|
128
|
+
}
|
|
129
|
+
(repo.state_dir / "reviews" / f"{doc.meta.id}.json").write_text(json.dumps(review, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
130
|
+
(repo.state_dir / "reviews" / f"{doc.meta.id}.patch").write_text(patch, encoding="utf-8")
|
|
131
|
+
return review
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def apply_review(path: Path, *, workspace: Path, strategy: str, yes: bool) -> dict:
|
|
135
|
+
if strategy != "replace":
|
|
136
|
+
raise ValueError("Only replace strategy is supported")
|
|
137
|
+
if not yes:
|
|
138
|
+
raise ValueError("--yes is required to apply changes")
|
|
139
|
+
doc = WdDocument.parse(path.read_text(encoding="utf-8"))
|
|
140
|
+
maybe_snapshot = doc.section("source_snapshot", default=None)
|
|
141
|
+
if maybe_snapshot is None:
|
|
142
|
+
raise ValueError("No source_snapshot to apply")
|
|
143
|
+
snapshot = maybe_snapshot.strip("\n")
|
|
144
|
+
doc.set_section("effective", snapshot)
|
|
145
|
+
doc.remove_section("source_snapshot")
|
|
146
|
+
doc.meta.sync.state = "up_to_date"
|
|
147
|
+
doc.meta.sync.effective_hash = content_hash(snapshot)
|
|
148
|
+
doc.meta.sync.snapshot_hash = None
|
|
149
|
+
path.write_text(doc.to_text(), encoding="utf-8")
|
|
150
|
+
return {"ok": True, "path": str(path), "id": doc.meta.id, "strategy": strategy}
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def extract_effective(path: Path, *, workspace: Path) -> dict:
|
|
154
|
+
repo = Repository(workspace)
|
|
155
|
+
doc = WdDocument.parse(path.read_text(encoding="utf-8"))
|
|
156
|
+
relative_path = str(path.relative_to(repo.root) if path.is_relative_to(repo.root) else path)
|
|
157
|
+
return {
|
|
158
|
+
"ok": True,
|
|
159
|
+
"items": [
|
|
160
|
+
{
|
|
161
|
+
"external_id": f"wd:{doc.meta.id}",
|
|
162
|
+
"id": doc.meta.id,
|
|
163
|
+
"title": doc.meta.title,
|
|
164
|
+
"path": relative_path,
|
|
165
|
+
"content_type": doc.meta.content_type,
|
|
166
|
+
"tags": doc.meta.tags,
|
|
167
|
+
"effective_hash": content_hash(doc.section("effective", default="").strip("\n")),
|
|
168
|
+
"content": doc.section("effective", default="").strip("\n"),
|
|
169
|
+
}
|
|
170
|
+
],
|
|
171
|
+
}
|
wikidelta/sources.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import subprocess
|
|
5
|
+
import sys
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from urllib.parse import urlparse
|
|
9
|
+
|
|
10
|
+
import requests
|
|
11
|
+
from bs4 import BeautifulSoup
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class Artifact:
|
|
16
|
+
content: str
|
|
17
|
+
content_type: str
|
|
18
|
+
metadata: dict = field(default_factory=dict)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def infer_source_config(target: str) -> dict:
|
|
22
|
+
parsed = urlparse(target)
|
|
23
|
+
if parsed.scheme in {"http", "https"}:
|
|
24
|
+
return {
|
|
25
|
+
"fetcher": "builtin.http",
|
|
26
|
+
"fetch": {"url": target},
|
|
27
|
+
"transformer": "builtin.html_to_markdown",
|
|
28
|
+
"transform": {},
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
suffix = Path(target).suffix.lower()
|
|
32
|
+
transformer = {
|
|
33
|
+
".md": "builtin.markdown",
|
|
34
|
+
".markdown": "builtin.markdown",
|
|
35
|
+
".txt": "builtin.text",
|
|
36
|
+
".html": "builtin.text",
|
|
37
|
+
".htm": "builtin.text",
|
|
38
|
+
".json": "builtin.json_to_markdown",
|
|
39
|
+
".pdf": "builtin.pdf_to_markdown",
|
|
40
|
+
}.get(suffix, "builtin.text")
|
|
41
|
+
return {
|
|
42
|
+
"fetcher": "builtin.file",
|
|
43
|
+
"fetch": {"path": target},
|
|
44
|
+
"transformer": transformer,
|
|
45
|
+
"transform": {},
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def fetch_source(fetcher: str, config: dict, *, workspace: Path, wd_id: str) -> Artifact:
|
|
50
|
+
if fetcher == "builtin.file":
|
|
51
|
+
path = Path(config["path"])
|
|
52
|
+
if not path.is_absolute():
|
|
53
|
+
path = workspace / path
|
|
54
|
+
content = path.read_text(encoding="utf-8")
|
|
55
|
+
return Artifact(content=content, content_type=_content_type_for_path(path), metadata={"path": str(path)})
|
|
56
|
+
|
|
57
|
+
if fetcher == "builtin.http":
|
|
58
|
+
response = requests.get(config["url"], timeout=float(config.get("timeout", 20)))
|
|
59
|
+
response.raise_for_status()
|
|
60
|
+
return Artifact(
|
|
61
|
+
content=response.text,
|
|
62
|
+
content_type=response.headers.get("content-type", "text/html").split(";")[0],
|
|
63
|
+
metadata={"url": config["url"]},
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
if fetcher == "script.python":
|
|
67
|
+
payload = {
|
|
68
|
+
"kind": "fetch",
|
|
69
|
+
"wdId": wd_id,
|
|
70
|
+
"workspace": str(workspace),
|
|
71
|
+
"config": config.get("args", {}),
|
|
72
|
+
}
|
|
73
|
+
result = _run_python_script(config, payload, workspace=workspace)
|
|
74
|
+
return Artifact(
|
|
75
|
+
content=result["content"],
|
|
76
|
+
content_type=result.get("contentType", "text/plain"),
|
|
77
|
+
metadata=result.get("metadata", {}),
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
raise ValueError(f"Unsupported fetcher: {fetcher}")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def transform_content(transformer: str, config: dict, raw: Artifact) -> Artifact:
|
|
84
|
+
if transformer == "builtin.markdown":
|
|
85
|
+
return Artifact(content=raw.content.strip(), content_type="text/markdown", metadata=raw.metadata)
|
|
86
|
+
if transformer == "builtin.text":
|
|
87
|
+
return Artifact(content=raw.content.strip(), content_type="text/markdown", metadata=raw.metadata)
|
|
88
|
+
if transformer == "builtin.html_to_markdown":
|
|
89
|
+
html = raw.content
|
|
90
|
+
selector = config.get("selector")
|
|
91
|
+
if selector:
|
|
92
|
+
soup = BeautifulSoup(html, "html.parser")
|
|
93
|
+
selected = soup.select_one(selector)
|
|
94
|
+
html = str(selected) if selected else ""
|
|
95
|
+
soup = BeautifulSoup(html, "html.parser")
|
|
96
|
+
for tag in soup(["script", "style"]):
|
|
97
|
+
tag.decompose()
|
|
98
|
+
return Artifact(content=soup.get_text("\n", strip=True), content_type="text/markdown", metadata=raw.metadata)
|
|
99
|
+
if transformer == "builtin.json_to_markdown":
|
|
100
|
+
parsed = json.loads(raw.content)
|
|
101
|
+
pretty = json.dumps(parsed, ensure_ascii=False, indent=2)
|
|
102
|
+
return Artifact(content=f"```json\n{pretty}\n```", content_type="text/markdown", metadata=raw.metadata)
|
|
103
|
+
if transformer == "builtin.pdf_to_markdown":
|
|
104
|
+
return Artifact(content=raw.content.strip(), content_type="text/markdown", metadata=raw.metadata)
|
|
105
|
+
if transformer == "script.python":
|
|
106
|
+
payload = {
|
|
107
|
+
"kind": "transform",
|
|
108
|
+
"wdId": config.get("wd_id", ""),
|
|
109
|
+
"workspace": config.get("workspace", ""),
|
|
110
|
+
"contentType": raw.content_type,
|
|
111
|
+
"content": raw.content,
|
|
112
|
+
"metadata": raw.metadata,
|
|
113
|
+
"config": config.get("args", {}),
|
|
114
|
+
}
|
|
115
|
+
workspace = Path(config.get("workspace") or ".").resolve()
|
|
116
|
+
result = _run_python_script(config, payload, workspace=workspace)
|
|
117
|
+
return Artifact(
|
|
118
|
+
content=result["content"],
|
|
119
|
+
content_type=result.get("contentType", "text/markdown"),
|
|
120
|
+
metadata=result.get("metadata", {}),
|
|
121
|
+
)
|
|
122
|
+
raise ValueError(f"Unsupported transformer: {transformer}")
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _run_python_script(config: dict, payload: dict, *, workspace: Path) -> dict:
|
|
126
|
+
entry = Path(config["entry"])
|
|
127
|
+
if not entry.is_absolute():
|
|
128
|
+
entry = workspace / entry
|
|
129
|
+
completed = subprocess.run(
|
|
130
|
+
[sys.executable, str(entry)],
|
|
131
|
+
input=json.dumps(payload),
|
|
132
|
+
text=True,
|
|
133
|
+
capture_output=True,
|
|
134
|
+
timeout=float(config.get("timeout", 30)),
|
|
135
|
+
cwd=str(workspace),
|
|
136
|
+
check=False,
|
|
137
|
+
)
|
|
138
|
+
if completed.returncode != 0:
|
|
139
|
+
raise RuntimeError(completed.stderr.strip() or f"script exited with {completed.returncode}")
|
|
140
|
+
try:
|
|
141
|
+
result = json.loads(completed.stdout)
|
|
142
|
+
except json.JSONDecodeError as exc:
|
|
143
|
+
raise RuntimeError("script did not return JSON") from exc
|
|
144
|
+
if not result.get("ok"):
|
|
145
|
+
error = result.get("error", {})
|
|
146
|
+
raise RuntimeError(f"{error.get('code', 'SCRIPT_FAILED')}: {error.get('message', 'script failed')}")
|
|
147
|
+
return result
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _content_type_for_path(path: Path) -> str:
|
|
151
|
+
return {
|
|
152
|
+
".md": "text/markdown",
|
|
153
|
+
".markdown": "text/markdown",
|
|
154
|
+
".txt": "text/plain",
|
|
155
|
+
".html": "text/html",
|
|
156
|
+
".htm": "text/html",
|
|
157
|
+
".json": "application/json",
|
|
158
|
+
".pdf": "application/pdf",
|
|
159
|
+
}.get(path.suffix.lower(), "text/plain")
|
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: wikidelta
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Lifecycle CLI for .wd llmwiki source files
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Project-URL: Homepage, https://github.com/jcb850/WikiDelta
|
|
7
|
+
Project-URL: Repository, https://github.com/jcb850/WikiDelta
|
|
8
|
+
Project-URL: Issues, https://github.com/jcb850/WikiDelta/issues
|
|
9
|
+
Requires-Python: >=3.11
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: beautifulsoup4>=4.12
|
|
13
|
+
Requires-Dist: pydantic>=2.7
|
|
14
|
+
Requires-Dist: pypdf>=4.2
|
|
15
|
+
Requires-Dist: PyYAML>=6.0
|
|
16
|
+
Requires-Dist: requests>=2.32
|
|
17
|
+
Requires-Dist: typer>=0.12
|
|
18
|
+
Provides-Extra: dev
|
|
19
|
+
Requires-Dist: pytest>=8.2; extra == "dev"
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
<p align="center">
|
|
23
|
+
<img src="./assets/wikidelta-icon.png" alt="WikiDelta icon" width="160">
|
|
24
|
+
</p>
|
|
25
|
+
|
|
26
|
+
# WikiDelta
|
|
27
|
+
|
|
28
|
+
[中文说明](./README.zh-CN.md) | English
|
|
29
|
+
|
|
30
|
+
WikiDelta is built for the llmwiki raw source layer. It introduces the `.wd` file format so raw sources can be managed as reviewable, agent-friendly knowledge units instead of loose files that are refreshed and ingested directly.
|
|
31
|
+
|
|
32
|
+
A `.wd` file keeps the content llmwiki should ingest, the source configuration used to refresh it, and an optional candidate snapshot when upstream source content changes. This gives llmwiki raw source maintenance a clear lifecycle: fetch, compare, review, apply, and ingest.
|
|
33
|
+
|
|
34
|
+
The first version follows one clear constraint:
|
|
35
|
+
|
|
36
|
+
```text
|
|
37
|
+
1 .wd file = 1 knowledge unit = 1 source = 1 effective content section
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Use Cases
|
|
41
|
+
|
|
42
|
+
- The llmwiki raw source directory needs a durable source-file format that can be maintained continuously by people and agents.
|
|
43
|
+
- Raw sources may originate from Markdown, text, HTML, JSON, PDF, local files, or web pages, but llmwiki should ingest only reviewed effective content.
|
|
44
|
+
- You want an explicit "currently effective content" layer so source refreshes cannot directly pollute the knowledge base.
|
|
45
|
+
- Agents need stable CLI commands and JSON output to inspect source state, generate diffs, and apply reviewed updates.
|
|
46
|
+
|
|
47
|
+
## `.wd` File Structure
|
|
48
|
+
|
|
49
|
+
A `.wd` file is essentially a Markdown file composed of YAML front matter and named content sections:
|
|
50
|
+
|
|
51
|
+
```markdown
|
|
52
|
+
---
|
|
53
|
+
wd_version: 1
|
|
54
|
+
id: pricing-policy
|
|
55
|
+
title: Pricing Rules
|
|
56
|
+
status: active
|
|
57
|
+
content_type: markdown
|
|
58
|
+
tags:
|
|
59
|
+
- pricing
|
|
60
|
+
- policy
|
|
61
|
+
source:
|
|
62
|
+
fetcher: builtin.file
|
|
63
|
+
fetch:
|
|
64
|
+
path: ./pricing.md
|
|
65
|
+
transformer: builtin.markdown
|
|
66
|
+
transform: {}
|
|
67
|
+
sync:
|
|
68
|
+
strategy: review_before_apply
|
|
69
|
+
---
|
|
70
|
+
|
|
71
|
+
<!-- wd:effective -->
|
|
72
|
+
# Pricing Rules
|
|
73
|
+
|
|
74
|
+
This is the currently effective content and will be imported into llmwiki.
|
|
75
|
+
<!-- /wd:effective -->
|
|
76
|
+
|
|
77
|
+
<!-- wd:notes -->
|
|
78
|
+
Maintenance notes, review decisions, and why certain source changes were accepted or rejected.
|
|
79
|
+
<!-- /wd:notes -->
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
When `wd update` finds source content that differs from `wd:effective`, WikiDelta adds a temporary candidate section:
|
|
83
|
+
|
|
84
|
+
```markdown
|
|
85
|
+
<!-- wd:source_snapshot -->
|
|
86
|
+
# Pricing Rules
|
|
87
|
+
|
|
88
|
+
This is the latest candidate content fetched and transformed from the source.
|
|
89
|
+
<!-- /wd:source_snapshot -->
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Core rules:
|
|
93
|
+
|
|
94
|
+
- `wd:effective` is the only content imported into the knowledge base by default.
|
|
95
|
+
- `wd:source_snapshot` is optional candidate content for review and diffing, and is not imported directly.
|
|
96
|
+
- `wd:notes` contains maintenance notes and is not imported into llmwiki by default.
|
|
97
|
+
- `id` is the stable identity of the knowledge unit, used for status, caching, review, and future upsert operations.
|
|
98
|
+
- The first `wd add` writes only `effective`; later `wd update` creates `source_snapshot` only when source content differs.
|
|
99
|
+
|
|
100
|
+
## Installation and Running
|
|
101
|
+
|
|
102
|
+
This project is currently a Python CLI package. In a development environment, you can run it directly with `PYTHONPATH`:
|
|
103
|
+
|
|
104
|
+
```bash
|
|
105
|
+
PYTHONPATH=src python3 -m wikidelta.cli --help
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Install it as a local executable command:
|
|
109
|
+
|
|
110
|
+
```bash
|
|
111
|
+
pip install -e .
|
|
112
|
+
wd --help
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## Quick Start
|
|
116
|
+
|
|
117
|
+
Initialize a workspace:
|
|
118
|
+
|
|
119
|
+
```bash
|
|
120
|
+
wd init --mode llmwiki_project
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Wrap a local Markdown file into a `.wd` file:
|
|
124
|
+
|
|
125
|
+
```bash
|
|
126
|
+
wd add ./policy.md --into raw_sources/policy
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Refresh candidate snapshots after source files change. Without a path, WikiDelta updates every `.wd` file in the workspace:
|
|
130
|
+
|
|
131
|
+
```bash
|
|
132
|
+
wd update
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
Pass a path when you only want to update one `.wd` file:
|
|
136
|
+
|
|
137
|
+
```bash
|
|
138
|
+
wd update raw_sources/policy/policy.wd
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
Check status:
|
|
142
|
+
|
|
143
|
+
```bash
|
|
144
|
+
wd status --json
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
Generate review materials:
|
|
148
|
+
|
|
149
|
+
```bash
|
|
150
|
+
wd review raw_sources/policy/policy.wd --json
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
Accept the candidate content as the effective content:
|
|
154
|
+
|
|
155
|
+
```bash
|
|
156
|
+
wd apply raw_sources/policy/policy.wd --strategy replace --yes
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Extract only `wd:effective` as an llmwiki-compatible bridge:
|
|
160
|
+
|
|
161
|
+
```bash
|
|
162
|
+
wd ingest raw_sources/policy/policy.wd --json
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
## Daily Workflow Example
|
|
166
|
+
|
|
167
|
+
This is the workflow for maintaining an llmwiki raw source directory with `.wd` files.
|
|
168
|
+
|
|
169
|
+
Start in the knowledge project directory:
|
|
170
|
+
|
|
171
|
+
```bash
|
|
172
|
+
cd /path/to/llmwiki-project
|
|
173
|
+
wd init --mode llmwiki_project
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
Add source files. If `--into` is omitted, WikiDelta writes `.wd` files under `raw_source/` by default:
|
|
177
|
+
|
|
178
|
+
```bash
|
|
179
|
+
wd add ./policy.md
|
|
180
|
+
wd add ./dashboard.html
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Local HTML files are preserved as raw source text. That means the generated `.wd` keeps the original `<!doctype html>`, `<style>`, and other HTML text in `wd:effective`. Web URLs still use `builtin.html_to_markdown` by default.
|
|
184
|
+
|
|
185
|
+
After source files change, update all `.wd` files:
|
|
186
|
+
|
|
187
|
+
```bash
|
|
188
|
+
wd update --json
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
If you only want to update one knowledge unit, pass the `.wd` path:
|
|
192
|
+
|
|
193
|
+
```bash
|
|
194
|
+
wd update raw_source/dashboard.wd --json
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
`wd update` intentionally accepts `.wd` files only. Do not pass the original source file:
|
|
198
|
+
|
|
199
|
+
```bash
|
|
200
|
+
# Wrong: this is the original source file
|
|
201
|
+
wd update ./dashboard.html
|
|
202
|
+
|
|
203
|
+
# Right: this is the lifecycle wrapper
|
|
204
|
+
wd update raw_source/dashboard.wd
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
Check what needs review:
|
|
208
|
+
|
|
209
|
+
```bash
|
|
210
|
+
wd status --json
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
For every item with `state: pending_review`, generate review files:
|
|
214
|
+
|
|
215
|
+
```bash
|
|
216
|
+
wd review raw_source/dashboard.wd --json
|
|
217
|
+
less .wikidelta/reviews/dashboard.patch
|
|
218
|
+
cat .wikidelta/reviews/dashboard.json
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
If the candidate snapshot should become the new effective content:
|
|
222
|
+
|
|
223
|
+
```bash
|
|
224
|
+
wd apply raw_source/dashboard.wd --strategy replace --yes --json
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
After apply, confirm the workspace is clean:
|
|
228
|
+
|
|
229
|
+
```bash
|
|
230
|
+
wd status --json
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
Finally, inspect the content llmwiki should ingest:
|
|
234
|
+
|
|
235
|
+
```bash
|
|
236
|
+
wd ingest raw_source/dashboard.wd --json
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
`wd ingest` outputs only `wd:effective`; it does not include source config, `source_snapshot`, or `notes`.
|
|
240
|
+
|
|
241
|
+
## CLI Commands
|
|
242
|
+
|
|
243
|
+
```text
|
|
244
|
+
wd init Initialize the .wikidelta state directory
|
|
245
|
+
wd add Create a .wd file from a local file or URL
|
|
246
|
+
wd update Refresh all .wd files, or one .wd file when a path is provided
|
|
247
|
+
wd status Scan .wd status
|
|
248
|
+
wd review Generate review JSON and patch files
|
|
249
|
+
wd apply Apply candidate content to effective
|
|
250
|
+
wd ingest Extract effective as an llmwiki-compatible bridge
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
When `wd status` succeeds but pending review content exists, it returns exit code `3`. This is not an execution failure; it tells agents or scripts that pending review needs to be handled.
|
|
254
|
+
|
|
255
|
+
## Built-in Sources and Transforms
|
|
256
|
+
|
|
257
|
+
`wd add` automatically infers common source pipelines from the input:
|
|
258
|
+
|
|
259
|
+
```text
|
|
260
|
+
*.md builtin.file + builtin.markdown
|
|
261
|
+
*.txt builtin.file + builtin.text
|
|
262
|
+
*.html builtin.file + builtin.text
|
|
263
|
+
*.json builtin.file + builtin.json_to_markdown
|
|
264
|
+
*.pdf builtin.file + builtin.pdf_to_markdown
|
|
265
|
+
http(s):// builtin.http + builtin.html_to_markdown
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
You can also maintain the source configuration manually in a `.wd` file:
|
|
269
|
+
|
|
270
|
+
```yaml
|
|
271
|
+
source:
|
|
272
|
+
fetcher: builtin.http
|
|
273
|
+
fetch:
|
|
274
|
+
url: https://example.com/policy
|
|
275
|
+
transformer: builtin.html_to_markdown
|
|
276
|
+
transform:
|
|
277
|
+
selector: main
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
## llmwiki Project Mode
|
|
281
|
+
|
|
282
|
+
The recommended layout is to place `.wd` files directly inside the raw source file structure of an llmwiki project:
|
|
283
|
+
|
|
284
|
+
```text
|
|
285
|
+
llmwiki-project/
|
|
286
|
+
raw_sources/
|
|
287
|
+
pricing/pricing-policy.wd
|
|
288
|
+
policy/refund-policy.wd
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
In this mode, the project a `.wd` file belongs to is determined by directory context. You do not need to configure llmwiki `base_url` or `project` for every `.wd` file.
|
|
292
|
+
|
|
293
|
+
The import rule is: llmwiki or a compatible bridge may only read `wd:effective`; it must not import the entire `.wd` file as ordinary Markdown, otherwise the source configuration, candidate snapshot, and notes will pollute the knowledge base.
|
|
294
|
+
|
|
295
|
+
## Agent-Friendly Conventions
|
|
296
|
+
|
|
297
|
+
Main commands support JSON output and an explicit workspace:
|
|
298
|
+
|
|
299
|
+
```bash
|
|
300
|
+
wd status --workspace /path/to/repo --json
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
Lifecycle operations that affect `effective` require explicit confirmation:
|
|
304
|
+
|
|
305
|
+
```bash
|
|
306
|
+
wd apply path/to/file.wd --strategy replace --yes
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
Recommended agent workflow:
|
|
310
|
+
|
|
311
|
+
```text
|
|
312
|
+
1. wd status --json
|
|
313
|
+
2. Run wd review --json for files in pending_review
|
|
314
|
+
3. Read .wikidelta/reviews/<id>.json and .patch
|
|
315
|
+
4. Decide whether to accept the changes
|
|
316
|
+
5. wd apply <file.wd> --strategy replace --yes
|
|
317
|
+
6. wd ingest <file.wd> --json
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
## Script Extensions
|
|
321
|
+
|
|
322
|
+
Complex sources can use `script.python`. The script reads JSON from stdin and writes JSON to stdout.
|
|
323
|
+
|
|
324
|
+
`.wd` example:
|
|
325
|
+
|
|
326
|
+
```yaml
|
|
327
|
+
source:
|
|
328
|
+
fetcher: script.python
|
|
329
|
+
fetch:
|
|
330
|
+
entry: ./fetchers/feishu_doc.py
|
|
331
|
+
args:
|
|
332
|
+
doc_id: abc123
|
|
333
|
+
transformer: builtin.markdown
|
|
334
|
+
transform: {}
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
Successful output:
|
|
338
|
+
|
|
339
|
+
```json
|
|
340
|
+
{
|
|
341
|
+
"ok": true,
|
|
342
|
+
"contentType": "text/plain",
|
|
343
|
+
"content": "Fetched content",
|
|
344
|
+
"metadata": {}
|
|
345
|
+
}
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
Failed output:
|
|
349
|
+
|
|
350
|
+
```json
|
|
351
|
+
{
|
|
352
|
+
"ok": false,
|
|
353
|
+
"error": {
|
|
354
|
+
"code": "AUTH_FAILED",
|
|
355
|
+
"message": "Missing token",
|
|
356
|
+
"retryable": false
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
Credentials should be passed to scripts through environment variables and should not be written into `.wd` files.
|
|
362
|
+
|
|
363
|
+
## Testing
|
|
364
|
+
|
|
365
|
+
Run the full test suite:
|
|
366
|
+
|
|
367
|
+
```bash
|
|
368
|
+
pytest -v
|
|
369
|
+
```
|
|
370
|
+
|
|
371
|
+
Current tests cover `.wd` parsing, repository initialization, source inference, `wd add/update/status/review/apply/ingest`, the script protocol, and the end-to-end lifecycle.
|
|
372
|
+
|
|
373
|
+
## License
|
|
374
|
+
|
|
375
|
+
WikiDelta is licensed under the [Apache License 2.0](./LICENSE).
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
wikidelta/__init__.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
|
|
2
|
+
wikidelta/cli.py,sha256=goScExr_VbBTEb4o-wwmknFXPEmPghRCVL3zTZNHTUI,4814
|
|
3
|
+
wikidelta/document.py,sha256=PSKdoeCRJTACEkseITD8srDcRbEpFZKvCeB0-GOppOQ,3087
|
|
4
|
+
wikidelta/models.py,sha256=tCawLDOASrwoxaNiIENly9vJcbgCw9eHxx0uDyPNKGY,848
|
|
5
|
+
wikidelta/repository.py,sha256=mLTBWHFsDDsk6T2anD4-cYEz0K1p-acKUSWV0EcJYSg,1466
|
|
6
|
+
wikidelta/service.py,sha256=3ueNx8PPmeaqxm6bVDdfSwjrjUZ4NVasCfbEJn3k4tY,7519
|
|
7
|
+
wikidelta/sources.py,sha256=8gLhyb67IUt2Yy1u15rz8V4cjoZAhvORiSR3_R_4YRU,5821
|
|
8
|
+
wikidelta-0.1.0.dist-info/licenses/LICENSE,sha256=wbnfEnXnafPbqwANHkV6LUsPKOtdpsd-SNw37rogLtc,11359
|
|
9
|
+
wikidelta-0.1.0.dist-info/METADATA,sha256=mdiiQP3pCUkvJjiz76wO76EXrrqGXLKsJPJ-JPJXxl0,9885
|
|
10
|
+
wikidelta-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
11
|
+
wikidelta-0.1.0.dist-info/entry_points.txt,sha256=TrVQBheCCPR0OGvMvLvYEeBGB7oQfpwfyKx5A-z099s,41
|
|
12
|
+
wikidelta-0.1.0.dist-info/top_level.txt,sha256=glAayfAUZq3Kq_rdzFkuwOPN1mjD7y9S0MeNMAyazR8,10
|
|
13
|
+
wikidelta-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
https://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
https://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
wikidelta
|