File size: 12,073 Bytes
19aab86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4eef289
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19aab86
 
4eef289
 
 
 
 
 
 
 
19aab86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4eef289
 
 
 
 
 
 
19aab86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d69eb01
 
 
 
 
 
 
 
19aab86
 
 
 
 
 
 
 
 
 
 
 
 
 
4eef289
 
 
 
 
 
 
 
 
 
 
 
 
19aab86
 
 
 
 
 
 
 
4eef289
 
 
19aab86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4eef289
 
 
 
 
 
 
 
 
 
 
19aab86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4eef289
 
 
 
 
19aab86
 
 
4eef289
19aab86
 
 
 
 
 
 
4eef289
 
 
 
 
 
 
 
19aab86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
from __future__ import annotations

import argparse
import io
import json
import os
import re
import tarfile
import tempfile
from dataclasses import dataclass
from pathlib import Path, PurePosixPath

from ctx.core.wiki.wiki_packs import load_merged_wiki_pages, write_wiki_base_pack

_WINDOWS_DRIVE_RE = re.compile(r"^[A-Za-z]:")
_PATH_CHAR = r"[^`\"'<>|\s\r\n)]"
_PATH_TOKEN = rf"{_PATH_CHAR}+"
_PATH_TERMINAL_WORD = r"[A-Z0-9][^`\"'<>|/\\\s\r\n)]*"
_PATH_LOWER_PROSE_WORDS = (
    r"(?:a|an|and|are|as|at|by|for|from|in|is|of|on|or|the|to|was|were|with|without)"
)
_PATH_LOWER_TERMINAL_WORD = (
    rf"(?!(?:{_PATH_LOWER_PROSE_WORDS})(?=$|[\s),.;:!?]))"
    r"[a-z][^`\"'<>|/\\\s\r\n),.;:!?]*"
)
_PATH_TERMINAL_END = r"(?=$|[\r\n`\"'),.;:!?>\]])"
_PATH_SPACED_COMPONENT = (
    rf"(?: {_PATH_CHAR}*[\\/]{_PATH_CHAR}*| {_PATH_CHAR}*\.{_PATH_CHAR}+"
    rf"|(?: {_PATH_TERMINAL_WORD})+"
    rf"|(?: {_PATH_LOWER_TERMINAL_WORD}){{1,2}}{_PATH_TERMINAL_END})"
)
_PATH_BOUNDARY = r"(?:^|(?<=[`\"'(<\[\s=,:]))"
_QUOTED_PATH_BOUNDARY = r"(?<=[`\"'(<\[])"
_QUOTED_PATH_TOKEN = r"[^`\"'<>|\r\n)]+"
_QUOTED_PATH_END = r"(?=[`\"')>\]])"
_QUOTED_WINDOWS_USER_PATH_RE = re.compile(
    rf"(?i){_QUOTED_PATH_BOUNDARY}[A-Z]:[\\/]+Users[\\/]+{_QUOTED_PATH_TOKEN}{_QUOTED_PATH_END}"
)
_QUOTED_POSIX_USER_PATH_RE = re.compile(
    rf"{_QUOTED_PATH_BOUNDARY}(?:(?i:file:///)|/)(?:Users|home)/"
    rf"{_QUOTED_PATH_TOKEN}{_QUOTED_PATH_END}"
)
_WINDOWS_USER_PATH_RE = re.compile(
    rf"(?i)\b[A-Z]:[\\/]+Users[\\/]+{_PATH_TOKEN}(?:{_PATH_SPACED_COMPONENT})*"
)
_POSIX_USER_PATH_RE = re.compile(
    rf"{_PATH_BOUNDARY}(?:(?i:file:///)|/)(?:Users|home)/{_PATH_TOKEN}"
    rf"(?:{_PATH_SPACED_COMPONENT})*"
)
_POSIX_USER_PATH_PREFIX_RE = re.compile(rf"{_PATH_BOUNDARY}(?:(?i:file:///)|/)(?:Users|home)/")
_GRAPH_MANIFEST = "graphify-out/graph-export-manifest.json"
_REQUIRED_EXPANDED_MARKDOWN = frozenset({"graphify-out/graph-report.md"})
_LOCAL_GENERATED_MARKDOWN = frozenset(
    {
        "catalog.md",
        "converted-index.md",
        "log.md",
        "versions-catalog.md",
    }
)


@dataclass(frozen=True)
class RepackStats:
    export_id: str
    packed_pages: int
    removed_expanded_markdown_pages: int
    target: Path


def repack_full_wiki_tar(source: Path, target: Path | None = None) -> RepackStats:
    """Write a full wiki tarball that carries entity pages in wiki-packs."""
    source = Path(source)
    target = source if target is None else Path(target)
    if not source.is_file():
        raise FileNotFoundError(source)
    target.parent.mkdir(parents=True, exist_ok=True)

    with tempfile.TemporaryDirectory(prefix="ctx-wiki-pack-") as tmp_name:
        tmp_root = Path(tmp_name)
        existing_pack_root = tmp_root / "existing-wiki-packs"
        pages: dict[str, str] = {}
        export_id: str | None = None
        with tarfile.open(source, "r:gz") as src:
            for member in src:
                name = _safe_tar_name(member.name)
                if name.startswith("wiki-packs/"):
                    _copy_existing_wiki_pack_member(src, member, name, existing_pack_root)
                    continue
                if not member.isfile():
                    continue
                if name == _GRAPH_MANIFEST:
                    export_id = _read_export_id(src, member)
                if not _should_pack_markdown_page(name):
                    continue
                extracted = src.extractfile(member)
                if extracted is None:
                    raise ValueError(f"archive file is unreadable: {member.name}")
                with extracted:
                    pages[name] = _normalise_page_text(
                        extracted.read().decode("utf-8", errors="replace")
                    )
        if not export_id:
            raise ValueError(f"{source} is missing graph export id")
        if existing_pack_root.exists():
            pages.update(
                {
                    name: _normalise_page_text(text)
                    for name, text in load_merged_wiki_pages(existing_pack_root).items()
                    if _should_pack_markdown_page(name)
                }
            )

        pack_root = tmp_root / "wiki-packs"
        write_wiki_base_pack(
            pack_dir=pack_root / f"base-{export_id}",
            pack_id=f"base-{export_id}",
            base_export_id=export_id,
            pages=pages,
        )
        _validate_pack_payload(pack_root, pages)
        removed = _rewrite_tar_with_pack(source, target, pack_root, pages)
    return RepackStats(
        export_id=export_id,
        packed_pages=len(pages),
        removed_expanded_markdown_pages=removed,
        target=target,
    )


def _rewrite_tar_with_pack(
    source: Path,
    target: Path,
    pack_root: Path,
    pages: dict[str, str],
) -> int:
    tmp_target = target.with_name(f".{target.name}.tmp")
    tmp_target.unlink(missing_ok=True)
    removed = 0
    written_names: set[str] = set()
    try:
        with (
            tarfile.open(source, "r:gz") as src,
            tarfile.open(
                tmp_target,
                "w:gz",
                compresslevel=9,
            ) as dst,
        ):
            for member in src:
                name = _safe_tar_name(member.name)
                if name.startswith("wiki-packs/"):
                    continue
                if _is_transient_member(name):
                    continue
                if _should_skip_expanded_markdown_member(name):
                    removed += 1
                    continue
                if member.isfile():
                    extracted = src.extractfile(member)
                    if extracted is None:
                        raise ValueError(f"archive file is unreadable: {member.name}")
                    with extracted:
                        if name.endswith(".md"):
                            text = _normalise_page_text(
                                extracted.read().decode("utf-8", errors="replace")
                            )
                            _add_text(dst, name=name, text=text)
                        elif _should_redact_text_member(name):
                            text = _redact_host_user_paths(
                                extracted.read().decode("utf-8", errors="replace")
                            )
                            _add_text(dst, name=name, text=text)
                        else:
                            member.name = name
                            dst.addfile(member, extracted)
                    written_names.add(name)
                elif member.isdir():
                    member.name = name
                    dst.addfile(member)
                    written_names.add(name)
                else:
                    raise ValueError(f"unsupported archive member: {member.name}")
            for name in sorted(_REQUIRED_EXPANDED_MARKDOWN - written_names):
                required_text = pages.get(name)
                if required_text is not None:
                    _add_text(dst, name=name, text=required_text)
            for path in sorted(pack_root.rglob("*")):
                if path.is_file():
                    dst.add(path, arcname=path.relative_to(pack_root.parent).as_posix())
        os.replace(tmp_target, target)
    finally:
        tmp_target.unlink(missing_ok=True)
    return removed


def _copy_existing_wiki_pack_member(
    tf: tarfile.TarFile,
    member: tarfile.TarInfo,
    name: str,
    packs_dir: Path,
) -> None:
    if not member.isfile():
        return
    relpath = name.removeprefix("wiki-packs/")
    if not relpath:
        return
    target = packs_dir.joinpath(*PurePosixPath(relpath).parts)
    target.parent.mkdir(parents=True, exist_ok=True)
    extracted = tf.extractfile(member)
    if extracted is None:
        raise ValueError(f"archive file is unreadable: {member.name}")
    with extracted, target.open("wb") as out:
        out.write(extracted.read())


def _read_export_id(tf: tarfile.TarFile, member: tarfile.TarInfo) -> str:
    extracted = tf.extractfile(member)
    if extracted is None:
        raise ValueError(f"archive file is unreadable: {member.name}")
    with extracted:
        payload = json.loads(extracted.read().decode("utf-8"))
    if not isinstance(payload, dict):
        raise ValueError(f"{_GRAPH_MANIFEST} must contain a JSON object")
    export_id = payload.get("export_id")
    if not isinstance(export_id, str) or not export_id.strip():
        raise ValueError(f"{_GRAPH_MANIFEST} is missing export_id")
    return export_id.strip()


def _validate_pack_payload(pack_root: Path, expected_pages: dict[str, str]) -> None:
    pages = load_merged_wiki_pages(pack_root)
    if pages != expected_pages:
        raise ValueError("wiki pack payload does not match source markdown pages")


def _normalise_page_text(text: str) -> str:
    if not text.strip():
        return "<!-- empty markdown page -->\n"
    return _redact_host_user_paths(text)


def _redact_host_user_paths(text: str) -> str:
    redacted = _QUOTED_WINDOWS_USER_PATH_RE.sub("<host-user-path>", text)
    redacted = _QUOTED_POSIX_USER_PATH_RE.sub("<host-user-path>", redacted)
    redacted = _WINDOWS_USER_PATH_RE.sub("<host-user-path>", redacted)
    redacted = _POSIX_USER_PATH_RE.sub("<host-user-path>", redacted)
    return _POSIX_USER_PATH_PREFIX_RE.sub("<host-user-path>", redacted)


def _safe_tar_name(raw_name: str) -> str:
    name = raw_name.replace("\\", "/")
    while name.startswith("./"):
        name = name[2:]
    path = PurePosixPath(name)
    if (
        not name
        or name.startswith("/")
        or _WINDOWS_DRIVE_RE.match(name)
        or any(part in {"", ".", ".."} for part in path.parts)
    ):
        raise ValueError(f"unsafe archive member path: {raw_name}")
    return path.as_posix()


def _is_transient_member(name: str) -> bool:
    return (
        name.endswith(".original")
        or name.endswith(".lock")
        or name == ".ctx"
        or name.startswith(".ctx/")
    )


def _is_high_fanout_entity_page(name: str) -> bool:
    prefixes = (
        "entities/skills/",
        "entities/agents/",
        "entities/mcp-servers/",
    )
    return name.startswith(prefixes) and name.endswith(".md")


def _should_pack_markdown_page(name: str) -> bool:
    return (
        name.endswith(".md")
        and name not in _LOCAL_GENERATED_MARKDOWN
        and not name.startswith("wiki-packs/")
    )


def _should_skip_expanded_markdown_member(name: str) -> bool:
    return name in _LOCAL_GENERATED_MARKDOWN or (
        name.endswith(".md")
        and name not in _REQUIRED_EXPANDED_MARKDOWN
        and "/" in name
        and not name.startswith("entities/harnesses/")
    )


def _should_redact_text_member(name: str) -> bool:
    return (
        name.startswith("graphify-out/")
        and not name.startswith("graphify-out/packs/")
        and name.endswith((".json", ".jsonl"))
    )


def _add_text(tf: tarfile.TarFile, *, name: str, text: str) -> None:
    payload = text.encode("utf-8")
    info = tarfile.TarInfo(name)
    info.size = len(payload)
    info.mode = 0o644
    info.mtime = 0
    tf.addfile(info, io.BytesIO(payload))


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(
        description="Repack ctx full wiki tarball with markdown pages in wiki-packs.",
    )
    parser.add_argument(
        "--source",
        type=Path,
        default=Path("graph/wiki-graph.tar.gz"),
        help="Existing full wiki tarball.",
    )
    parser.add_argument(
        "--target",
        type=Path,
        help="Destination tarball. Defaults to rewriting --source atomically.",
    )
    args = parser.parse_args(argv)
    stats = repack_full_wiki_tar(args.source, args.target)
    print(
        "packed "
        f"{stats.packed_pages:,} markdown pages for {stats.export_id}; "
        f"removed {stats.removed_expanded_markdown_pages:,} expanded markdown pages; "
        f"wrote {stats.target}"
    )
    return 0


if __name__ == "__main__":
    raise SystemExit(main())