swarm repositories / source
aboutsummaryrefslogtreecommitdiff
path: root/assemble-pro-review-package/scripts/inline_section.py
blob: 23daaf0dad2326cecfefea49d2998e399cb99307 (plain)
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
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = "==3.13.*"
# dependencies = ["tiktoken==0.12.0"]
# ///

from __future__ import annotations

import argparse
import sys
from pathlib import Path

import tiktoken


LANGUAGE_BY_SUFFIX = {
    ".c": "c",
    ".cc": "cpp",
    ".conf": "text",
    ".cpp": "cpp",
    ".css": "css",
    ".csv": "csv",
    ".go": "go",
    ".h": "c",
    ".hpp": "cpp",
    ".html": "html",
    ".java": "java",
    ".js": "javascript",
    ".json": "json",
    ".jsonl": "json",
    ".kt": "kotlin",
    ".log": "text",
    ".lua": "lua",
    ".md": "markdown",
    ".patch": "diff",
    ".proto": "proto",
    ".py": "python",
    ".rb": "ruby",
    ".rs": "rust",
    ".sh": "bash",
    ".sql": "sql",
    ".toml": "toml",
    ".ts": "typescript",
    ".tsx": "tsx",
    ".txt": "text",
    ".xml": "xml",
    ".yaml": "yaml",
    ".yml": "yaml",
}

HARD_MAX_TOKENS = 100_000


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description=(
            "Append a labeled markdown section containing a file or excerpt to a "
            "target document, while enforcing the skill's fixed 100k-token hard budget."
        )
    )
    parser.add_argument("source", type=Path, help="Source file to inline.")
    parser.add_argument("target", type=Path, help="Markdown file to append into.")
    parser.add_argument(
        "--label",
        help="Section label. Defaults to the source path as provided.",
    )
    parser.add_argument(
        "--start",
        type=int,
        default=1,
        help="One-indexed start line, inclusive. Defaults to 1.",
    )
    parser.add_argument(
        "--end",
        type=int,
        help="One-indexed end line, inclusive. Defaults to EOF.",
    )
    parser.add_argument(
        "--heading-level",
        type=int,
        default=2,
        help="Markdown heading level for the section. Defaults to 2.",
    )
    parser.add_argument(
        "--encoding",
        default="o200k_base",
        help="Tiktoken encoding name used for the hard budget. Defaults to o200k_base.",
    )
    parser.add_argument(
        "--model",
        help=(
            "Optional model name for encoding lookup. If unavailable, the script falls "
            "back to --encoding."
        ),
    )
    return parser.parse_args()


def fail(message: str) -> "NoReturn":
    print(f"error: {message}", file=sys.stderr)
    raise SystemExit(2)


def normalize_span(start: int, end: int | None, total_lines: int) -> tuple[int, int]:
    if start < 1:
        fail("--start must be at least 1")
    resolved_end = total_lines if end is None else end
    if resolved_end < start:
        fail("--end must be greater than or equal to --start")
    if start > total_lines:
        fail(
            f"--start {start} exceeds the source length of {total_lines} line"
            f"{'' if total_lines == 1 else 's'}"
        )
    if resolved_end > total_lines:
        fail(
            f"--end {resolved_end} exceeds the source length of {total_lines} line"
            f"{'' if total_lines == 1 else 's'}"
        )
    return start, resolved_end


def resolve_language(path: Path) -> str:
    return LANGUAGE_BY_SUFFIX.get(path.suffix.lower(), "text")


def load_encoding(model: str | None, encoding_name: str) -> tuple[tiktoken.Encoding, str]:
    if model is not None:
        try:
            encoding = tiktoken.encoding_for_model(model)
            return encoding, f"model:{model}->{encoding.name}"
        except KeyError:
            pass
    return tiktoken.get_encoding(encoding_name), f"encoding:{encoding_name}"


def choose_fence(body: str) -> str:
    longest_run = 0
    current_run = 0
    for char in body:
        if char == "`":
            current_run += 1
            longest_run = max(longest_run, current_run)
        else:
            current_run = 0
    return "`" * max(3, longest_run + 1)


def render_section(
    *,
    label: str,
    source_name: str,
    start: int,
    end: int,
    body: str,
    language: str,
    heading_level: int,
) -> str:
    if heading_level < 1:
        fail("--heading-level must be at least 1")
    heading = "#" * heading_level
    lines_label = f"{start}" if start == end else f"{start}-{end}"
    fence = choose_fence(body)
    if body and not body.endswith("\n"):
        body = f"{body}\n"
    return (
        f"{heading} {label}\n\n"
        f"Source: `{source_name}`\n"
        f"Lines: `{lines_label}`\n\n"
        f"{fence}{language}\n"
        f"{body}"
        f"{fence}\n"
    )


def main() -> None:
    args = parse_args()
    source = args.source
    target = args.target

    if not source.is_file():
        fail(f"source file not found: {source}")

    source_text = source.read_text(encoding="utf-8", errors="replace")
    source_lines = source_text.splitlines(keepends=True)
    if not source_lines:
        fail("source file is empty")

    start, end = normalize_span(args.start, args.end, len(source_lines))
    excerpt = "".join(source_lines[start - 1 : end])
    label = args.label or str(source)
    section = render_section(
        label=label,
        source_name=str(source),
        start=start,
        end=end,
        body=excerpt,
        language=resolve_language(source),
        heading_level=args.heading_level,
    )

    existing = ""
    if target.exists():
        if target.is_dir():
            fail(f"target is a directory: {target}")
        existing = target.read_text(encoding="utf-8", errors="replace")

    separator = "\n\n" if existing else ""
    rendered = f"{existing}{separator}{section}"

    encoding, encoding_label = load_encoding(args.model, args.encoding)
    total_tokens = len(encoding.encode(rendered))
    section_tokens = len(encoding.encode(section))
    existing_tokens = len(encoding.encode(existing))

    if total_tokens > HARD_MAX_TOKENS:
        fail(
            "refusing append because the projected document would exceed the hard budget: "
            f"{total_tokens} > {HARD_MAX_TOKENS} ({encoding_label}; existing={existing_tokens}; "
            f"section={section_tokens})"
        )

    target.parent.mkdir(parents=True, exist_ok=True)
    target.write_text(rendered, encoding="utf-8")

    print(f"appended: {label}")
    print(f"source: {source}")
    print(f"target: {target}")
    print(f"lines: {start}-{end}")
    print(f"encoding: {encoding_label}")
    print(f"section_tokens: {section_tokens}")
    print(f"total_tokens: {total_tokens}")


if __name__ == "__main__":
    main()