surf-cli 0.7.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.
surf/orchestrator.py ADDED
@@ -0,0 +1,300 @@
1
+ # orchestrator.py
2
+ """Laminate models, logic, and adapters. No heading regex."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import sys
8
+ from collections.abc import Sequence
9
+ from pathlib import Path
10
+
11
+ from surf import __version__
12
+ from surf.adapters import (
13
+ PdfIngestError,
14
+ document_byte_count,
15
+ read_document,
16
+ read_pdf_catalog,
17
+ read_pdf_pages,
18
+ resolve_file,
19
+ resolve_tex_include,
20
+ write_output,
21
+ )
22
+ from surf.logic import (
23
+ exclusive_page_end,
24
+ extract_section,
25
+ format_empty_index,
26
+ format_empty_pdf_index,
27
+ format_file_index,
28
+ format_heading_list,
29
+ format_outline_list,
30
+ match_outline_span,
31
+ parse_heading_path,
32
+ parse_headings,
33
+ parse_link,
34
+ parse_tex_headings,
35
+ split_frontmatter,
36
+ tex_include_path,
37
+ )
38
+ from surf.models import (
39
+ CliFailure,
40
+ CliOptions,
41
+ CliSuccess,
42
+ CliTarget,
43
+ DocumentLines,
44
+ ErrorMessage,
45
+ ExitCode,
46
+ FileRef,
47
+ HeadingLevel,
48
+ HeadingPath,
49
+ HeadingPathRemainder,
50
+ HeadingText,
51
+ LineCount,
52
+ OutlineLevel,
53
+ RenderedBody,
54
+ )
55
+
56
+ type CliResult = CliSuccess | CliFailure
57
+
58
+
59
+ def build_parser() -> argparse.ArgumentParser:
60
+ parser = argparse.ArgumentParser(
61
+ prog="surf",
62
+ description="Extract markdown, TeX, or PDF outline sections with Obsidian link support.",
63
+ )
64
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
65
+ parser.add_argument(
66
+ "target",
67
+ nargs="?",
68
+ help="Link or file path: [[path#Heading]], [Text](path#Heading), or file path",
69
+ )
70
+ parser.add_argument(
71
+ "heading",
72
+ nargs="?",
73
+ help="Heading or outline title (when target is a plain file path)",
74
+ )
75
+ mode = parser.add_mutually_exclusive_group()
76
+ mode.add_argument("--full", action="store_true", help="Output frontmatter + section content")
77
+ mode.add_argument(
78
+ "--content-only",
79
+ "--body-only",
80
+ action="store_true",
81
+ dest="content_only",
82
+ help="Section content without frontmatter (default)",
83
+ )
84
+ mode.add_argument(
85
+ "--frontmatter-only",
86
+ "-f",
87
+ action="store_true",
88
+ dest="frontmatter_only",
89
+ help="Output only the YAML frontmatter",
90
+ )
91
+ mode.add_argument(
92
+ "--list",
93
+ "-l",
94
+ action="store_true",
95
+ dest="list_headings",
96
+ help="List headings or PDF outline titles",
97
+ )
98
+ parser.add_argument(
99
+ "--level",
100
+ type=int,
101
+ default=None,
102
+ help="Max heading level when listing (1..N); exact level when extracting",
103
+ )
104
+ parser.add_argument(
105
+ "--no-heading", action="store_true", help="Exclude the heading line from output"
106
+ )
107
+ parser.add_argument(
108
+ "--output", "-o", type=str, default=None, help="Write output to file instead of stdout"
109
+ )
110
+ return parser
111
+
112
+
113
+ def options_from_namespace(args: argparse.Namespace) -> CliOptions | CliFailure:
114
+ if args.target is None:
115
+ return CliFailure(
116
+ message=ErrorMessage("no target specified. Use surf --help for usage."),
117
+ exit_code=ExitCode(2),
118
+ )
119
+ parsed = parse_link(CliTarget(args.target))
120
+ heading_path = parsed.heading_path
121
+ if heading_path is None and args.heading is not None:
122
+ heading_path = parse_heading_path(HeadingPathRemainder(args.heading))
123
+ if heading_path is None:
124
+ heading_path = HeadingPath(segments=(HeadingText(args.heading),))
125
+ output_ref = FileRef(args.output) if args.output else None
126
+ return CliOptions(
127
+ file_ref=parsed.file_ref,
128
+ heading_path=heading_path,
129
+ list_headings=bool(args.list_headings),
130
+ frontmatter_only=bool(args.frontmatter_only),
131
+ full=bool(args.full),
132
+ no_heading=bool(args.no_heading),
133
+ level_filter=args.level,
134
+ output_ref=output_ref,
135
+ )
136
+
137
+
138
+ def _run_pdf(path: Path, options: CliOptions) -> CliResult:
139
+ try:
140
+ catalog = read_pdf_catalog(path)
141
+ except PdfIngestError as exc:
142
+ return CliFailure(message=ErrorMessage(str(exc)), exit_code=ExitCode(1))
143
+ outline_level = OutlineLevel(options.level_filter) if options.level_filter is not None else None
144
+ if options.frontmatter_only:
145
+ return CliSuccess(body=RenderedBody(""))
146
+ if options.list_headings or options.heading_path is None:
147
+ if not catalog.outline:
148
+ return CliSuccess(
149
+ body=format_empty_pdf_index(
150
+ page_count=catalog.page_count, byte_count=catalog.byte_count
151
+ )
152
+ )
153
+ return CliSuccess(body=format_outline_list(catalog.outline, level_filter=outline_level))
154
+ span = match_outline_span(catalog.outline, options.heading_path, level_filter=outline_level)
155
+ if span is None:
156
+ remainder = "#".join(str(seg) for seg in options.heading_path.segments)
157
+ return CliFailure(
158
+ message=ErrorMessage(f'heading "{remainder}" not found in {path}.'),
159
+ exit_code=ExitCode(1),
160
+ )
161
+ if span.start_page is None:
162
+ return CliSuccess(body=RenderedBody(""))
163
+ try:
164
+ pages = read_pdf_pages(path, span.start_page, exclusive_page_end(span))
165
+ except PdfIngestError as exc:
166
+ return CliFailure(message=ErrorMessage(str(exc)), exit_code=ExitCode(1))
167
+ return CliSuccess(body=RenderedBody("\n".join(pages).rstrip()))
168
+
169
+
170
+ def run(options: CliOptions) -> CliResult:
171
+ if options.file_ref is None:
172
+ return CliFailure(
173
+ message=ErrorMessage("could not parse file path from target."),
174
+ exit_code=ExitCode(2),
175
+ )
176
+ try:
177
+ path = resolve_file(options.file_ref)
178
+ except FileNotFoundError as exc:
179
+ return CliFailure(message=ErrorMessage(str(exc)), exit_code=ExitCode(2))
180
+ if path.suffix.lower() == ".pdf":
181
+ return _run_pdf(path, options)
182
+ try:
183
+ lines = read_document(path)
184
+ except UnicodeDecodeError:
185
+ return CliFailure(
186
+ message=ErrorMessage(f"could not decode {path} as UTF-8."),
187
+ exit_code=ExitCode(1),
188
+ )
189
+ line_count = LineCount(len(lines))
190
+ byte_count = document_byte_count(path)
191
+ if path.suffix.lower() == ".tex":
192
+ lines = _expand_tex_inputs(
193
+ lines,
194
+ root_dir=path.parent,
195
+ current=path,
196
+ seen=frozenset(),
197
+ )
198
+ split = split_frontmatter(lines)
199
+ headings = (
200
+ parse_tex_headings(split.body)
201
+ if path.suffix.lower() == ".tex"
202
+ else parse_headings(split.body)
203
+ )
204
+ empty_index = format_empty_index(line_count=line_count, byte_count=byte_count)
205
+ heading_level = HeadingLevel(options.level_filter) if options.level_filter is not None else None
206
+
207
+ if options.list_headings:
208
+ if not headings:
209
+ return CliSuccess(body=empty_index)
210
+ return CliSuccess(
211
+ body=format_heading_list(split.body, headings=headings, level_filter=heading_level)
212
+ )
213
+ if options.frontmatter_only:
214
+ if split.frontmatter is None:
215
+ return CliSuccess(body=RenderedBody(""))
216
+ return CliSuccess(body=RenderedBody("\n".join(split.frontmatter)))
217
+
218
+ if options.heading_path is None:
219
+ if not headings and split.frontmatter is None:
220
+ return CliSuccess(body=empty_index)
221
+ return CliSuccess(
222
+ body=format_file_index(split, headings=headings, level_filter=heading_level)
223
+ )
224
+
225
+ extracted = extract_section(
226
+ split.body,
227
+ options.heading_path,
228
+ level_filter=heading_level,
229
+ headings=headings,
230
+ )
231
+ if extracted is None:
232
+ remainder = "#".join(str(seg) for seg in options.heading_path.segments)
233
+ return CliFailure(
234
+ message=ErrorMessage(f'heading "{remainder}" not found in {path}.'),
235
+ exit_code=ExitCode(1),
236
+ )
237
+
238
+ section_lines = extracted.lines
239
+ if options.no_heading and section_lines:
240
+ section_lines = section_lines[int(extracted.heading_line_count) :]
241
+ parts: list[str] = []
242
+ if options.full and split.frontmatter is not None:
243
+ parts.append("\n".join(split.frontmatter))
244
+ parts.append("\n".join(section_lines))
245
+ return CliSuccess(body=RenderedBody("\n".join(parts).rstrip()))
246
+
247
+
248
+ def _expand_tex_inputs(
249
+ lines: DocumentLines,
250
+ *,
251
+ root_dir: Path,
252
+ current: Path,
253
+ seen: frozenset[Path],
254
+ ) -> DocumentLines:
255
+ resolved = current.resolve()
256
+ if resolved in seen:
257
+ return ()
258
+ loaded = seen | {resolved}
259
+ out: list[str] = []
260
+ for line in lines:
261
+ rel = tex_include_path(line)
262
+ if rel is None:
263
+ out.append(line)
264
+ continue
265
+ child = resolve_tex_include(root_dir, rel)
266
+ if child is None:
267
+ out.append(line)
268
+ continue
269
+ out.extend(
270
+ _expand_tex_inputs(
271
+ read_document(child),
272
+ root_dir=root_dir,
273
+ current=child,
274
+ seen=loaded,
275
+ )
276
+ )
277
+ return tuple(out)
278
+
279
+
280
+ def run_argv(argv: Sequence[str] | None = None) -> CliResult:
281
+ parser = build_parser()
282
+ args = parser.parse_args(argv)
283
+ converted = options_from_namespace(args)
284
+ if isinstance(converted, CliFailure):
285
+ return converted
286
+ return run(converted)
287
+
288
+
289
+ def main() -> None:
290
+ parser = build_parser()
291
+ args = parser.parse_args()
292
+ converted = options_from_namespace(args)
293
+ if isinstance(converted, CliFailure):
294
+ print(f"Error: {converted.message}", file=sys.stderr)
295
+ raise SystemExit(converted.exit_code)
296
+ result = run(converted)
297
+ if isinstance(result, CliFailure):
298
+ print(f"Error: {result.message}", file=sys.stderr)
299
+ raise SystemExit(result.exit_code)
300
+ write_output(result.body, converted.output_ref)
@@ -0,0 +1,177 @@
1
+ Metadata-Version: 2.5
2
+ Name: surf-cli
3
+ Version: 0.7.0
4
+ Summary: Extract markdown, TeX, or PDF outline sections by heading with Obsidian link support
5
+ Project-URL: Homepage, https://github.com/saintx/surf-cli
6
+ Project-URL: Repository, https://github.com/saintx/surf-cli
7
+ Project-URL: Issues, https://github.com/saintx/surf-cli/issues
8
+ Project-URL: Author, https://github.com/saintx
9
+ Author-email: "Alexander R. Saint Croix" <alex@saintx.us>
10
+ License: MIT License
11
+
12
+ Copyright (c) 2026 Alexander R. Saint Croix
13
+
14
+ Permission is hereby granted, free of charge, to any person obtaining a copy
15
+ of this software and associated documentation files (the "Software"), to deal
16
+ in the Software without restriction, including without limitation the rights
17
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18
+ copies of the Software, and to permit persons to whom the Software is
19
+ furnished to do so, subject to the following conditions:
20
+
21
+ The above copyright notice and this permission notice shall be included in all
22
+ copies or substantial portions of the Software.
23
+
24
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30
+ SOFTWARE.
31
+ License-File: LICENSE
32
+ Requires-Python: >=3.12
33
+ Requires-Dist: pypdf>=6.17.0
34
+ Description-Content-Type: text/markdown
35
+
36
+ # surf
37
+
38
+ Extract one section of a markdown, TeX, or PDF file by its heading. The rest of the file never loads.
39
+
40
+ ```bash
41
+ uv tool install surf-cli
42
+ cd plugins/surf/skills/surf/references
43
+ ```
44
+
45
+ A file with no heading named returns the map, frontmatter and then headings, and none of the body:
46
+
47
+ ```
48
+ $ surf about.md
49
+ ---
50
+ metadata:
51
+ author:
52
+ name: Alexander R. Saint Croix
53
+ github_username: saintx
54
+ email: alex@saintx.us
55
+ twitter: alexsaintx
56
+ surf-version: "0.7.0"
57
+ ---
58
+
59
+ - Surf — About
60
+ - Overview
61
+ - When to use
62
+ ```
63
+
64
+ A heading returns that section and stops at the next heading of the same or higher level:
65
+
66
+ ```
67
+ $ surf about.md "When to use"
68
+ ## When to use
69
+
70
+ Invoke when skimming markdown, TeX, or PDF files, checking what a file contains,
71
+ listing structure, extracting a named address, or batch-scanning metadata across
72
+ a directory. See `surf --help` for CLI flags. Skip when the full body is already
73
+ needed. ...
74
+ ```
75
+
76
+ The same two commands work on TeX, addressed by sectioning commands and the `abstract` environment, and on PDF, addressed by outline bookmarks. The whitepaper in this directory ships in both forms and lists the same tree from either:
77
+
78
+ ```
79
+ $ surf surf.tex --list
80
+ - abstract
81
+ - Background
82
+ - A Thin Index Shaped by Intent
83
+ - Agentic Context Composition
84
+ - Skills You Can Check
85
+ - Indexes over Indexes
86
+ - Markdown, TeX, and PDF
87
+ - This Paper
88
+
89
+ $ surf surf.pdf "Skills You Can Check"
90
+ ```
91
+
92
+ surf exists so that agent skills can be thin. The `SKILL.md` beside these files is a table of intents, each resolving to `surf path "Heading"`, over reference material the agent never reads whole. `surf.pdf` explains why the tool was built and what that pattern makes possible.
93
+
94
+ ## Addressing
95
+
96
+ `surf --list file.md` is the heading tree without YAML. `surf -f file.md` is YAML only. Nested paths (`Overview#Usage`) select a child when the same name appears under different parents.
97
+
98
+ A heading is an address: ATX display text on markdown, brace title on TeX, the TeX `abstract` environment (addressed as `abstract`), or an outline bookmark title on PDF. On markdown and TeX the return value is that section through the next heading of the same or higher level. On PDF it is dest-to-next-dest page text; when the next dest is on the same page, that dest page is included.
99
+
100
+ `--level` is 1 at the top of the heading tree. On markdown that is `#`. On TeX it is the shallowest command in the file, so `--level 1` is `\section` in an article. On PDF it is the outline's native rank. Listing with `--level N` includes ranks 1 through N. Named extract uses N as an exact match.
101
+
102
+ TeX `\input` and `\include` of `.tex` files are expanded relative to the file you name. Graphics, comments, shell pipes, and macro-constructed paths are not.
103
+
104
+ If the file has no headings, or a PDF has no outline, surf prints that it has no structural index, with line and byte counts on markdown and TeX, or page and byte counts on PDF. It does not dump the body.
105
+
106
+ Python 3.12+. pypdf is the runtime dependency for PDF outline addressing.
107
+
108
+ ## Agent skill
109
+
110
+ `plugins/surf` packages the skill for agents. It carries a Claude Code manifest, an Agent Plugins 1.0.0 manifest, and the skill itself at `plugins/surf/skills/surf`, in the Agent Skills format that Claude Code, Codex, Gemini CLI, Cursor, and Grok Build read.
111
+
112
+ Claude Code installs it from the marketplace in this repo:
113
+
114
+ ```bash
115
+ claude plugin marketplace add saintx/surf-cli
116
+ claude plugin install surf@surf-cli
117
+ ```
118
+
119
+ Any harness that reads a skills directory takes a copy of the skill:
120
+
121
+ ```bash
122
+ cp -R plugins/surf/skills/surf ~/.agents/skills/surf
123
+ ```
124
+
125
+ The repo also carries `.agents/skills/surf`, `.claude/skills/surf`, and `.grok/skills/surf` as symlinks into the plugin, so an agent working in this checkout has the skill available.
126
+
127
+ ## Install
128
+
129
+ The distribution name is `surf-cli`. The command is `surf`. Python 3.12+.
130
+
131
+ ```bash
132
+ uv tool install surf-cli
133
+ surf --version
134
+ ```
135
+
136
+ ```bash
137
+ pipx install surf-cli
138
+ surf --version
139
+ ```
140
+
141
+ ```bash
142
+ pip install surf-cli
143
+ ```
144
+
145
+ ### Nix
146
+
147
+ From a local clone, install the flake into the nix profile:
148
+
149
+ ```bash
150
+ nix profile install "git+file://${PWD}"
151
+ surf --version
152
+ ```
153
+
154
+ Pin a tagged release with `?ref=X.Y.Z`. If `surf` is already in the profile under a different flake URL, remove it first:
155
+
156
+ ```bash
157
+ nix profile remove surf
158
+ nix profile install "git+file://${PWD}?ref=X.Y.Z"
159
+ ```
160
+
161
+ `scripts/deploy.sh` syncs, tests, and retargets the profile at the latest local semver tag.
162
+
163
+ ## Releasing
164
+
165
+ Version locations, the bump checklist, tagging, and nix profile deployment are in [RELEASING.md](RELEASING.md).
166
+
167
+ ## Development
168
+
169
+ ```bash
170
+ nix develop
171
+ ```
172
+
173
+ ## Tests
174
+
175
+ ```bash
176
+ scripts/test.sh # uv run pytest src/surf
177
+ ```
@@ -0,0 +1,11 @@
1
+ surf/__init__.py,sha256=1pXaPX_VAHeJdvB-x89tLLKyRjvp77XDIa7BjgvOdYE,144
2
+ surf/__main__.py,sha256=ANlz65xgS_gLYkFY7rNicUva_NffRRumsnLQZJjPp1M,117
3
+ surf/adapters.py,sha256=I0A_B85ABh-IaXCni3rfXMfPzRIdIOSe-6bZnrNQZnY,5007
4
+ surf/logic.py,sha256=bZyRCT7SyEnzeFKik0nMb1OVQJRGcw6HHqPyXVilj2o,18540
5
+ surf/models.py,sha256=_Cr4vJBaq_At4yCYKj2QggYvpLo-g4g4NvkXZhsqCvE,3421
6
+ surf/orchestrator.py,sha256=zFkXukKHmk_rg5jqOAWMSyUPL3XOGu5jAgc6SaKQsOI,9726
7
+ surf_cli-0.7.0.dist-info/METADATA,sha256=oO6IMBWRNBdNGF5H9tYRfSyLJE5JxkDFWvuJFMyftss,6460
8
+ surf_cli-0.7.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
9
+ surf_cli-0.7.0.dist-info/entry_points.txt,sha256=vU3KRWN9HFa83zwz9ozp2pb6eaPIfnyAdjPhf64Xtdo,48
10
+ surf_cli-0.7.0.dist-info/licenses/LICENSE,sha256=zMyNx4S0Dmu2So_ND8lf2NICO0jVbRNZeEjaGP_qgAk,1081
11
+ surf_cli-0.7.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ surf = surf.orchestrator:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alexander R. Saint Croix
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.