context-loader 1.3.9__tar.gz → 1.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,227 @@
1
+ Metadata-Version: 2.4
2
+ Name: context-loader
3
+ Version: 1.4.0
4
+ Summary: Render deterministic local Git context for any executor
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.12, <3.15
8
+ Project-URL: Repository, https://github.com/xuanheng-tech/context-loader
9
+ Project-URL: Issues, https://github.com/xuanheng-tech/context-loader/issues
10
+ Description-Content-Type: text/markdown
11
+
12
+ # Context Loader
13
+
14
+ Context Loader renders deterministic, bounded context for one local Git working tree.
15
+ The default CLI output remains Markdown; a stable JSON interface is also available for machine
16
+ callers. The tool reads repository state and a fixed set of root files without fetching, executing
17
+ repository code, network access, or writes to the target repository. Runtime code uses only the
18
+ Python standard library.
19
+
20
+ ## Open-source quick start
21
+
22
+ Current stable release: **1.4.0**. Local CLI for coding-agent workflows; renders deterministic Markdown or JSON.
23
+
24
+ ```bash
25
+ uv tool install 'context-loader==1.4.0'
26
+ ```
27
+
28
+ ```bash
29
+ pip install 'context-loader==1.4.0'
30
+ ```
31
+
32
+ ```bash
33
+ project-context --repo /path/to/repo
34
+ ```
35
+
36
+ ```bash
37
+ project-context --repo /path/to/repo --format json
38
+ ```
39
+
40
+ ## Install
41
+
42
+ Source version: `1.4.0`. Install its matching published release or an exact source commit.
43
+
44
+ Install via `uv`:
45
+
46
+ ```bash
47
+ uv tool install 'context-loader==1.4.0'
48
+ ```
49
+
50
+ Install via `pip`:
51
+
52
+ ```bash
53
+ pip install 'context-loader==1.4.0'
54
+ ```
55
+
56
+ For development or source-based installs tracking current repository (`1.4.0`):
57
+
58
+ ```bash
59
+ uv tool install git+https://github.com/xuanheng-tech/context-loader.git
60
+ ```
61
+
62
+ The repository also retains `./project-context` as a direct development entry point.
63
+
64
+ ### Distributions
65
+
66
+ The sole distribution is **`context-loader`**, containing the `context_loader` runtime
67
+ and the `project-context` console script. Version `1.0.0` broke the CLI name and Markdown
68
+ heading contract while leaving the then-current JSON schema unchanged. Terminal and any executor call this same
69
+ entry point with explicit repository and focus arguments; no provider adapter or private
70
+ session state is involved.
71
+
72
+ Previously published packages and historical release records remain unchanged. The new
73
+ release publishes no compatibility distribution or legacy executable alias.
74
+
75
+ The wheel installs the runtime package only. The source distribution additionally carries
76
+ `tool_cli_contract.json`, so a package-only consumer can pin the declared public CLI contract
77
+ without cloning. The test suite, `justfile` and lockfile stay in the Git repository and are not
78
+ part of either distribution; run them from a checkout of the matching tag.
79
+
80
+ ## Platform and Runtime Requirements
81
+
82
+ - **Python**: Python 3.12–3.14 (`>=3.12,<3.15`). Runtime code uses only the Python standard library with zero runtime dependencies.
83
+ - **Git**: Requires the standard `git` CLI at `/usr/bin/git` (with fallback to `/opt/homebrew/bin/git`
84
+ or `/usr/local/bin/git` when `/usr/bin/git` is absent). The executable is never resolved through
85
+ ambient `PATH`. Git runs with a sanitized environment that ignores system, global and per-command
86
+ configuration, attributes, and hooks.
87
+ - **Operating System**: supported and locally tested on Ubuntu 24.04 LTS; CI also tests the
88
+ GitHub-hosted Ubuntu runner. Other Linux/POSIX systems are unverified, not a portability promise.
89
+ Windows is not supported.
90
+
91
+ Deterministic means byte-identical output for the same tool version, CLI arguments, canonical
92
+ repository path, readable file contents, directory entries, Git state/local refs, and relevant Git
93
+ configuration, with no concurrent changes. Different checkout paths, permissions, Git versions or
94
+ working-tree contents can change the output. The tool does not freeze a repository snapshot.
95
+
96
+ Output can contain sensitive information from the repository itself: README/instructions, declared
97
+ commands, paths, branch names and commit subjects. Fixed file selection and size limits are **not
98
+ automatic redaction**. Inspect the output before sharing it with a person or external service.
99
+
100
+ ## Usage
101
+
102
+ ```bash
103
+ project-context --version
104
+ project-context --repo /home/user/projects/example
105
+ project-context --repo /home/user/projects/example --format markdown
106
+ project-context --repo /home/user/projects/example --format markdown --layout cache-friendly
107
+ project-context --repo /home/user/projects/example --format json
108
+ project-context --repo /home/user/projects/example --format json-compact
109
+ project-context --repo /home/user/projects/example \
110
+ --focus "Authentication and session management" \
111
+ --path auth/session.py
112
+ ```
113
+
114
+ `--format` defaults to `markdown`. `--layout` defaults to `default` (fixed section order starting
115
+ with `Git State`); `--layout cache-friendly` places stable static sections (`Development
116
+ Instructions`, `Project Overview`, `Declared Commands`, `Project Entry Files`, `Directory Tree`)
117
+ before dynamic `Git State` and `Recent Commits` to preserve prompt prefix caching across edits.
118
+ In Markdown mode, `--repo` retains the 0.1.1 contract: it must be the absolute, canonical root of
119
+ a non-bare Git working tree. In the `json` and `json-compact` modes, an absolute existing directory
120
+ inside the working tree is accepted (enforcing worktree-root containment against `core.worktree`
121
+ escapes); symlinks are normalized and the discovered root is reported as `canonical_root`. Relative
122
+ paths, non-Git directories, regular files, and bare repositories are rejected in every mode.
123
+
124
+ `--focus` and `--path` are optional, bounded selection signals for the root `AGENTS.md`. `--path`
125
+ must be repository-relative. The collector does not retain either input in output or audit data.
126
+ Calls that omit both options remain valid and use the conservative fallback described in
127
+ [Supported Root Files](https://github.com/xuanheng-tech/context-loader/blob/HEAD/docs/reference.md#supported-root-files).
128
+ Each value option (`--repo`, `--focus`, `--path`, `--format`, `--layout`) may be supplied once;
129
+ duplicates are rejected before collection rather than silently overriding an earlier value.
130
+
131
+ ## Markdown Output
132
+
133
+ Successful repository collection uses schema `context-loader/v0.1` and emits these sections in
134
+ order:
135
+
136
+ 1. `Git State`, including bounded working-tree changes
137
+ 2. `Development Instructions`
138
+ 3. `Project Overview`
139
+ 4. `Declared Commands`
140
+ 5. `Project Entry Files`
141
+ 6. `Recent Commits`
142
+ 7. `Directory Tree`
143
+
144
+ The output has no generated timestamp, AI summary, architecture inference, or diff body.
145
+ The Markdown CLI skips the nested-instruction presence scan, which contributes only to
146
+ the machine formats; this does not change Markdown content or its byte budgets.
147
+
148
+ ## JSON Output
149
+
150
+ `--format json` writes one sorted, separator-compact UTF-8 JSON document (`schema_version` 3);
151
+ `--format json-compact` writes the same document without `sources[*].content` (`schema_version`
152
+ 4). Field definitions, compact-consumption guidance and schema-version rules are in
153
+ [docs/reference.md](https://github.com/xuanheng-tech/context-loader/blob/HEAD/docs/reference.md#json-output).
154
+
155
+ ## Authority Boundary
156
+
157
+ Context Loader is a bounded transport for repository-root context, not the authority for a
158
+ repository's instruction hierarchy. It reads the fixed root candidates listed in
159
+ [Supported Root Files](https://github.com/xuanheng-tech/context-loader/blob/HEAD/docs/reference.md#supported-root-files),
160
+ renders them under explicit limits, and stops there.
161
+
162
+ Resolving an instruction hierarchy stays with the calling agent harness. That includes any
163
+ shared or user-level instruction file outside the repository, nested or scoped `AGENTS.md` files
164
+ under subdirectories, and any include or import directive written inside an instruction file:
165
+ such a directive is transported as literal text and is never followed. `--path` selects sections
166
+ of the repository-root `AGENTS.md` only; it never changes which files are read. The JSON-only
167
+ `nested_context` field reports the existence of nested `AGENTS.md` paths without reading them;
168
+ deciding whether any of them applies stays with the calling agent harness exactly as before.
169
+
170
+ A successful run therefore proves that the bounded root context was collected and rendered. It
171
+ does not prove that every instruction applicable to a task has been loaded.
172
+
173
+ ## Inputs, limits and Git semantics
174
+
175
+ The exact root files read, every output and capture bound, and how Git state is derived are
176
+ documented in [docs/reference.md](https://github.com/xuanheng-tech/context-loader/blob/HEAD/docs/reference.md).
177
+
178
+ ## Exit Codes
179
+
180
+ - `0`: context or version output completed successfully
181
+ - `1`: required Git collection or an internal operation failed
182
+ - `2`: command arguments or the repository path do not satisfy the contract
183
+
184
+ On nonzero exit, stdout is empty and a bounded diagnostic is written to stderr without a traceback
185
+ or candidate-file content.
186
+
187
+ ## Not Included
188
+
189
+ Version 1.4.0 does not provide AI summaries, project-type detection, loading or transport of
190
+ nested `AGENTS.md` contents (the JSON `nested_context` field reports bounded existence only),
191
+ Memory retrieval, semantic ranking, ignore-rule parsing, plugins, profiles, caches, databases,
192
+ network services, MCP, daemons, GUIs, CI/CD, telemetry, or automatic updates.
193
+
194
+ ## Development
195
+
196
+ Run the complete local check:
197
+
198
+ ```bash
199
+ just check
200
+ ```
201
+
202
+ The shared check also builds a wheel and installs it into a fresh virtual environment. Package
203
+ acceptance runs the installed CLI outside the source checkout, checking deterministic agreement
204
+ between all three formats, linked worktrees, long multi-module instructions with focus/path selection,
205
+ explicit truncation and nested-instruction presence, and safe failures. Build and installation run offline
206
+ using the backend cache populated by `uv run --frozen`; the tests use only disposable repositories.
207
+ Git deadline regressions verify that silent, streaming, and stdout-closed child processes are
208
+ terminated and reaped, that successful commands cannot reset the shared budget, and that process
209
+ creation consumes it. A timeout leaves CLI stdout empty in every output format.
210
+
211
+ The lockfile uses public PyPI artifact URLs; no organization mirror or local Renovate preset
212
+ is needed. Renovate keeps scheduled, rate-limited updates and manual merges using a public
213
+ recommended preset plus the repository's explicit settings. The GitHub quality gate runs on
214
+ Python 3.12.13, 3.13.13 and 3.14.5; the Gitea root-runner gate and release builds use 3.12.13.
215
+ Other interpreter/platform combinations require validation before widening the supported range.
216
+
217
+ Git test fixtures discard inherited `GIT_*` routing/configuration before creating repositories.
218
+ Permission-sensitive tests must run as a non-root user. Gitea uses `just ci-check`, which installs
219
+ Python 3.12.13 without user-level executable links and keeps its interpreter/cache under
220
+ `$RUNNER_TEMP/context-loader-ci` (or ignored `.ci-runtime/context-loader-ci` locally).
221
+ Non-root runners execute directly; root containers transfer ownership of that runtime and the
222
+ checkout, then use `runuser` with an existing account named by `CONTEXT_LOADER_CI_USER` (default
223
+ `ubuntu`). That account must be able to execute the installed `uv` and `just`; it does not need
224
+ access to `/root` or a root-owned Python/cache. No `sudo` dependency is required for this CI step.
225
+
226
+ Performance baselines, version maintenance and release closure/recovery procedures are in
227
+ [docs/reference.md](https://github.com/xuanheng-tech/context-loader/blob/HEAD/docs/reference.md).
@@ -0,0 +1,216 @@
1
+ # Context Loader
2
+
3
+ Context Loader renders deterministic, bounded context for one local Git working tree.
4
+ The default CLI output remains Markdown; a stable JSON interface is also available for machine
5
+ callers. The tool reads repository state and a fixed set of root files without fetching, executing
6
+ repository code, network access, or writes to the target repository. Runtime code uses only the
7
+ Python standard library.
8
+
9
+ ## Open-source quick start
10
+
11
+ Current stable release: **1.4.0**. Local CLI for coding-agent workflows; renders deterministic Markdown or JSON.
12
+
13
+ ```bash
14
+ uv tool install 'context-loader==1.4.0'
15
+ ```
16
+
17
+ ```bash
18
+ pip install 'context-loader==1.4.0'
19
+ ```
20
+
21
+ ```bash
22
+ project-context --repo /path/to/repo
23
+ ```
24
+
25
+ ```bash
26
+ project-context --repo /path/to/repo --format json
27
+ ```
28
+
29
+ ## Install
30
+
31
+ Source version: `1.4.0`. Install its matching published release or an exact source commit.
32
+
33
+ Install via `uv`:
34
+
35
+ ```bash
36
+ uv tool install 'context-loader==1.4.0'
37
+ ```
38
+
39
+ Install via `pip`:
40
+
41
+ ```bash
42
+ pip install 'context-loader==1.4.0'
43
+ ```
44
+
45
+ For development or source-based installs tracking current repository (`1.4.0`):
46
+
47
+ ```bash
48
+ uv tool install git+https://github.com/xuanheng-tech/context-loader.git
49
+ ```
50
+
51
+ The repository also retains `./project-context` as a direct development entry point.
52
+
53
+ ### Distributions
54
+
55
+ The sole distribution is **`context-loader`**, containing the `context_loader` runtime
56
+ and the `project-context` console script. Version `1.0.0` broke the CLI name and Markdown
57
+ heading contract while leaving the then-current JSON schema unchanged. Terminal and any executor call this same
58
+ entry point with explicit repository and focus arguments; no provider adapter or private
59
+ session state is involved.
60
+
61
+ Previously published packages and historical release records remain unchanged. The new
62
+ release publishes no compatibility distribution or legacy executable alias.
63
+
64
+ The wheel installs the runtime package only. The source distribution additionally carries
65
+ `tool_cli_contract.json`, so a package-only consumer can pin the declared public CLI contract
66
+ without cloning. The test suite, `justfile` and lockfile stay in the Git repository and are not
67
+ part of either distribution; run them from a checkout of the matching tag.
68
+
69
+ ## Platform and Runtime Requirements
70
+
71
+ - **Python**: Python 3.12–3.14 (`>=3.12,<3.15`). Runtime code uses only the Python standard library with zero runtime dependencies.
72
+ - **Git**: Requires the standard `git` CLI at `/usr/bin/git` (with fallback to `/opt/homebrew/bin/git`
73
+ or `/usr/local/bin/git` when `/usr/bin/git` is absent). The executable is never resolved through
74
+ ambient `PATH`. Git runs with a sanitized environment that ignores system, global and per-command
75
+ configuration, attributes, and hooks.
76
+ - **Operating System**: supported and locally tested on Ubuntu 24.04 LTS; CI also tests the
77
+ GitHub-hosted Ubuntu runner. Other Linux/POSIX systems are unverified, not a portability promise.
78
+ Windows is not supported.
79
+
80
+ Deterministic means byte-identical output for the same tool version, CLI arguments, canonical
81
+ repository path, readable file contents, directory entries, Git state/local refs, and relevant Git
82
+ configuration, with no concurrent changes. Different checkout paths, permissions, Git versions or
83
+ working-tree contents can change the output. The tool does not freeze a repository snapshot.
84
+
85
+ Output can contain sensitive information from the repository itself: README/instructions, declared
86
+ commands, paths, branch names and commit subjects. Fixed file selection and size limits are **not
87
+ automatic redaction**. Inspect the output before sharing it with a person or external service.
88
+
89
+ ## Usage
90
+
91
+ ```bash
92
+ project-context --version
93
+ project-context --repo /home/user/projects/example
94
+ project-context --repo /home/user/projects/example --format markdown
95
+ project-context --repo /home/user/projects/example --format markdown --layout cache-friendly
96
+ project-context --repo /home/user/projects/example --format json
97
+ project-context --repo /home/user/projects/example --format json-compact
98
+ project-context --repo /home/user/projects/example \
99
+ --focus "Authentication and session management" \
100
+ --path auth/session.py
101
+ ```
102
+
103
+ `--format` defaults to `markdown`. `--layout` defaults to `default` (fixed section order starting
104
+ with `Git State`); `--layout cache-friendly` places stable static sections (`Development
105
+ Instructions`, `Project Overview`, `Declared Commands`, `Project Entry Files`, `Directory Tree`)
106
+ before dynamic `Git State` and `Recent Commits` to preserve prompt prefix caching across edits.
107
+ In Markdown mode, `--repo` retains the 0.1.1 contract: it must be the absolute, canonical root of
108
+ a non-bare Git working tree. In the `json` and `json-compact` modes, an absolute existing directory
109
+ inside the working tree is accepted (enforcing worktree-root containment against `core.worktree`
110
+ escapes); symlinks are normalized and the discovered root is reported as `canonical_root`. Relative
111
+ paths, non-Git directories, regular files, and bare repositories are rejected in every mode.
112
+
113
+ `--focus` and `--path` are optional, bounded selection signals for the root `AGENTS.md`. `--path`
114
+ must be repository-relative. The collector does not retain either input in output or audit data.
115
+ Calls that omit both options remain valid and use the conservative fallback described in
116
+ [Supported Root Files](https://github.com/xuanheng-tech/context-loader/blob/HEAD/docs/reference.md#supported-root-files).
117
+ Each value option (`--repo`, `--focus`, `--path`, `--format`, `--layout`) may be supplied once;
118
+ duplicates are rejected before collection rather than silently overriding an earlier value.
119
+
120
+ ## Markdown Output
121
+
122
+ Successful repository collection uses schema `context-loader/v0.1` and emits these sections in
123
+ order:
124
+
125
+ 1. `Git State`, including bounded working-tree changes
126
+ 2. `Development Instructions`
127
+ 3. `Project Overview`
128
+ 4. `Declared Commands`
129
+ 5. `Project Entry Files`
130
+ 6. `Recent Commits`
131
+ 7. `Directory Tree`
132
+
133
+ The output has no generated timestamp, AI summary, architecture inference, or diff body.
134
+ The Markdown CLI skips the nested-instruction presence scan, which contributes only to
135
+ the machine formats; this does not change Markdown content or its byte budgets.
136
+
137
+ ## JSON Output
138
+
139
+ `--format json` writes one sorted, separator-compact UTF-8 JSON document (`schema_version` 3);
140
+ `--format json-compact` writes the same document without `sources[*].content` (`schema_version`
141
+ 4). Field definitions, compact-consumption guidance and schema-version rules are in
142
+ [docs/reference.md](https://github.com/xuanheng-tech/context-loader/blob/HEAD/docs/reference.md#json-output).
143
+
144
+ ## Authority Boundary
145
+
146
+ Context Loader is a bounded transport for repository-root context, not the authority for a
147
+ repository's instruction hierarchy. It reads the fixed root candidates listed in
148
+ [Supported Root Files](https://github.com/xuanheng-tech/context-loader/blob/HEAD/docs/reference.md#supported-root-files),
149
+ renders them under explicit limits, and stops there.
150
+
151
+ Resolving an instruction hierarchy stays with the calling agent harness. That includes any
152
+ shared or user-level instruction file outside the repository, nested or scoped `AGENTS.md` files
153
+ under subdirectories, and any include or import directive written inside an instruction file:
154
+ such a directive is transported as literal text and is never followed. `--path` selects sections
155
+ of the repository-root `AGENTS.md` only; it never changes which files are read. The JSON-only
156
+ `nested_context` field reports the existence of nested `AGENTS.md` paths without reading them;
157
+ deciding whether any of them applies stays with the calling agent harness exactly as before.
158
+
159
+ A successful run therefore proves that the bounded root context was collected and rendered. It
160
+ does not prove that every instruction applicable to a task has been loaded.
161
+
162
+ ## Inputs, limits and Git semantics
163
+
164
+ The exact root files read, every output and capture bound, and how Git state is derived are
165
+ documented in [docs/reference.md](https://github.com/xuanheng-tech/context-loader/blob/HEAD/docs/reference.md).
166
+
167
+ ## Exit Codes
168
+
169
+ - `0`: context or version output completed successfully
170
+ - `1`: required Git collection or an internal operation failed
171
+ - `2`: command arguments or the repository path do not satisfy the contract
172
+
173
+ On nonzero exit, stdout is empty and a bounded diagnostic is written to stderr without a traceback
174
+ or candidate-file content.
175
+
176
+ ## Not Included
177
+
178
+ Version 1.4.0 does not provide AI summaries, project-type detection, loading or transport of
179
+ nested `AGENTS.md` contents (the JSON `nested_context` field reports bounded existence only),
180
+ Memory retrieval, semantic ranking, ignore-rule parsing, plugins, profiles, caches, databases,
181
+ network services, MCP, daemons, GUIs, CI/CD, telemetry, or automatic updates.
182
+
183
+ ## Development
184
+
185
+ Run the complete local check:
186
+
187
+ ```bash
188
+ just check
189
+ ```
190
+
191
+ The shared check also builds a wheel and installs it into a fresh virtual environment. Package
192
+ acceptance runs the installed CLI outside the source checkout, checking deterministic agreement
193
+ between all three formats, linked worktrees, long multi-module instructions with focus/path selection,
194
+ explicit truncation and nested-instruction presence, and safe failures. Build and installation run offline
195
+ using the backend cache populated by `uv run --frozen`; the tests use only disposable repositories.
196
+ Git deadline regressions verify that silent, streaming, and stdout-closed child processes are
197
+ terminated and reaped, that successful commands cannot reset the shared budget, and that process
198
+ creation consumes it. A timeout leaves CLI stdout empty in every output format.
199
+
200
+ The lockfile uses public PyPI artifact URLs; no organization mirror or local Renovate preset
201
+ is needed. Renovate keeps scheduled, rate-limited updates and manual merges using a public
202
+ recommended preset plus the repository's explicit settings. The GitHub quality gate runs on
203
+ Python 3.12.13, 3.13.13 and 3.14.5; the Gitea root-runner gate and release builds use 3.12.13.
204
+ Other interpreter/platform combinations require validation before widening the supported range.
205
+
206
+ Git test fixtures discard inherited `GIT_*` routing/configuration before creating repositories.
207
+ Permission-sensitive tests must run as a non-root user. Gitea uses `just ci-check`, which installs
208
+ Python 3.12.13 without user-level executable links and keeps its interpreter/cache under
209
+ `$RUNNER_TEMP/context-loader-ci` (or ignored `.ci-runtime/context-loader-ci` locally).
210
+ Non-root runners execute directly; root containers transfer ownership of that runtime and the
211
+ checkout, then use `runuser` with an existing account named by `CONTEXT_LOADER_CI_USER` (default
212
+ `ubuntu`). That account must be able to execute the installed `uv` and `just`; it does not need
213
+ access to `/root` or a root-owned Python/cache. No `sudo` dependency is required for this CI step.
214
+
215
+ Performance baselines, version maintenance and release closure/recovery procedures are in
216
+ [docs/reference.md](https://github.com/xuanheng-tech/context-loader/blob/HEAD/docs/reference.md).
@@ -1,3 +1,3 @@
1
1
  """Project Context Loader."""
2
2
 
3
- __version__ = "1.3.9"
3
+ __version__ = "1.4.0"
@@ -8,6 +8,7 @@ from bisect import bisect_right
8
8
  from dataclasses import dataclass, replace
9
9
  from pathlib import PurePosixPath
10
10
 
11
+ from .filesystem import display_text
11
12
  from .model import (
12
13
  AGENTS_FOCUS_LIMIT_BYTES,
13
14
  AGENTS_HEAD_LIMIT_BYTES,
@@ -64,16 +65,11 @@ _PATH_TOKEN_STOPWORDS = _MATCH_TOKEN_STOPWORDS | {
64
65
  "data",
65
66
  "doc",
66
67
  "frontend",
67
- "ingestion",
68
68
  "lib",
69
69
  "package",
70
70
  "packages",
71
- "platform",
72
- "provider",
73
- "providers",
74
71
  "py",
75
72
  "python",
76
- "quant",
77
73
  "research",
78
74
  "scripts",
79
75
  "src",
@@ -175,7 +171,7 @@ _AUDIT_NO_INDEX_LINE = "- Omitted content has no available heading index; read t
175
171
 
176
172
 
177
173
  def _audit_heading(heading: str) -> str:
178
- safe = heading.replace("`", r"\x60").strip()
174
+ safe = display_text(heading).strip()
179
175
  if len(safe) <= 160:
180
176
  return safe
181
177
  return f"{safe[:159]}…"
@@ -240,7 +236,9 @@ def _fence_marker(line: str) -> tuple[str, int, str] | None:
240
236
  return character, length, stripped[length:]
241
237
 
242
238
 
243
- def _parse_markdown_sections(content: str) -> tuple[MarkdownSection, ...]:
239
+ def _parse_markdown_sections(
240
+ content: str, *, allow_unclosed_eof_fence: bool = False
241
+ ) -> tuple[MarkdownSection, ...]:
244
242
  headings: list[tuple[str, int, int]] = []
245
243
  offset = 0
246
244
  open_fence: tuple[str, int] | None = None
@@ -255,17 +253,19 @@ def _parse_markdown_sections(content: str) -> tuple[MarkdownSection, ...]:
255
253
  offset += len(line)
256
254
  continue
257
255
  if marker is not None:
258
- character, length, _remainder = marker
259
- open_fence = (character, length)
260
- offset += len(line)
261
- continue
256
+ character, length, remainder = marker
257
+ # CommonMark §4.5: backtick code fences cannot have backticks in their info string.
258
+ if character == "~" or "`" not in remainder:
259
+ open_fence = (character, length)
260
+ offset += len(line)
261
+ continue
262
262
  match = _ATX_HEADING_RE.fullmatch(visible)
263
263
  if match is not None:
264
264
  heading = (match.group(2) or "").rstrip()
265
265
  heading = re.sub(r"[ \t]+#+[ \t]*$", "", heading).strip()
266
266
  headings.append((heading, len(match.group(1)), offset))
267
267
  offset += len(line)
268
- if open_fence is not None:
268
+ if open_fence is not None and not allow_unclosed_eof_fence:
269
269
  raise MarkdownSectionParseError("unclosed fenced code block")
270
270
 
271
271
  sections: list[MarkdownSection] = []
@@ -378,6 +378,7 @@ def _selection_state(
378
378
  reasons: dict[int, set[str]],
379
379
  budget_fallback: frozenset[int],
380
380
  *,
381
+ partial_head_index: int | None = None,
381
382
  parse_fallback: bool,
382
383
  source_scan_truncated: bool,
383
384
  source_characters: int,
@@ -398,7 +399,7 @@ def _selection_state(
398
399
  for index, section in enumerate(sections):
399
400
  if _interval_is_covered(section.start, section.end, merged, merged_starts):
400
401
  entry_reasons = set(reasons.get(index, set()))
401
- if section.end <= head_end:
402
+ if section.end <= head_end or index == partial_head_index:
402
403
  entry_reasons.add("head")
403
404
  selected_entries.append(
404
405
  AgentsSectionAuditEntry(
@@ -407,6 +408,16 @@ def _selection_state(
407
408
  _ordered_reasons(entry_reasons),
408
409
  )
409
410
  )
411
+ elif index == partial_head_index and section.start < head_end:
412
+ # The small head loaded a prefix of sections[0] because sections[0].start == 0
413
+ # exceeded 4 KiB; record it as loaded by head rather than indexed-only.
414
+ selected_entries.append(
415
+ AgentsSectionAuditEntry(
416
+ section.heading,
417
+ section.heading_level,
418
+ ("head",),
419
+ )
420
+ )
410
421
  else:
411
422
  indexed_entries.append(
412
423
  AgentsSectionAuditEntry(
@@ -449,6 +460,8 @@ def _fit_agents_index(content: str, audit: AgentsSelectionAudit) -> AgentsSelect
449
460
  if _aggregate_agents_bytes(content, audit) <= AGENTS_LIMIT_BYTES:
450
461
  return audit
451
462
  entries = audit.indexed_only_sections
463
+ if not entries:
464
+ raise RuntimeError("AGENTS head and selection audit exceed the AGENTS budget")
452
465
  without_index = replace(audit, indexed_only_sections=(), index_truncated=True)
453
466
  without_index_bytes = _aggregate_agents_bytes(content, without_index)
454
467
  fixed_bytes = without_index_bytes - len(_AUDIT_EMPTY_LIST_LINE.encode("utf-8")) - 1
@@ -511,12 +524,17 @@ def _select_agents_content(source: CollectedFile, signals: _SelectionSignals) ->
511
524
  return source
512
525
  source = _without_byte_order_mark(source)
513
526
  try:
514
- sections = _parse_markdown_sections(source.content)
527
+ sections = _parse_markdown_sections(
528
+ source.content, allow_unclosed_eof_fence=source.truncated
529
+ )
515
530
  except MarkdownSectionParseError:
516
531
  return _bounded_head_fallback(source, parse_fallback=True)
517
532
 
518
533
  head_end = _small_head_end(source.content, sections)
519
534
  selected_indices = {index for index, section in enumerate(sections) if section.end <= head_end}
535
+ partial_head_index = (
536
+ 0 if (sections and 0 not in selected_indices and sections[0].start < head_end) else None
537
+ )
520
538
  reasons: dict[int, set[str]] = {index: {"head"} for index in selected_indices}
521
539
  ranked: list[tuple[int, int, frozenset[str]]] = []
522
540
  for index, section in enumerate(sections):
@@ -544,6 +562,9 @@ def _select_agents_content(source: CollectedFile, signals: _SelectionSignals) ->
544
562
  + 1
545
563
  for s in sections
546
564
  ]
565
+ initially_listed = set(selected_indices)
566
+ if partial_head_index is not None:
567
+ initially_listed.add(partial_head_index)
547
568
  selected_sizes = {
548
569
  index: len(
549
570
  _audit_selected_line(
@@ -553,7 +574,7 @@ def _select_agents_content(source: CollectedFile, signals: _SelectionSignals) ->
553
574
  ).encode("utf-8")
554
575
  )
555
576
  + 1
556
- for index in selected_indices
577
+ for index in initially_listed
557
578
  }
558
579
  selected_lines = sum(selected_sizes.values())
559
580
  document_head_end = sections[0].start if sections else len(source.content)
@@ -568,11 +589,13 @@ def _select_agents_content(source: CollectedFile, signals: _SelectionSignals) ->
568
589
  )
569
590
  content_bytes = len(source.content[:head_end].encode("utf-8"))
570
591
  chars_selected = head_end
571
- index_count = len(sections) - len(selected_indices)
592
+ index_count = len(sections) - len(initially_listed)
572
593
  index_lines = sum(
573
- size for index, size in enumerate(index_sizes) if index not in selected_indices
594
+ size for index, size in enumerate(index_sizes) if index not in initially_listed
574
595
  )
575
- first_index = len(selected_indices)
596
+ first_index = 0
597
+ while first_index < len(sections) and first_index in initially_listed:
598
+ first_index += 1
576
599
  placeholder_bytes = len(_AUDIT_EMPTY_LIST_LINE.encode("utf-8")) + 1
577
600
  no_index_bytes = len(_AUDIT_NO_INDEX_LINE.encode("utf-8")) + 1
578
601
  empty_sizes = {
@@ -608,10 +631,11 @@ def _select_agents_content(source: CollectedFile, signals: _SelectionSignals) ->
608
631
  if selected_line_bytes:
609
632
  common += selected_line_bytes - placeholder_bytes
610
633
  full = common + empty_sizes[truncated, False]
611
- if remaining_count:
612
- full += remaining_lines - placeholder_bytes
613
- if truncated:
614
- full -= no_index_bytes
634
+ if not remaining_count:
635
+ return full
636
+ full += remaining_lines - placeholder_bytes
637
+ if truncated:
638
+ full -= no_index_bytes
615
639
  fitted = common + empty_sizes[truncated, True]
616
640
  if remaining_count > 1:
617
641
  # A very short first index line can cost less than the empty placeholder.
@@ -625,7 +649,10 @@ def _select_agents_content(source: CollectedFile, signals: _SelectionSignals) ->
625
649
  while parent is not None:
626
650
  trial_reasons[parent] = reasons.get(parent, set()) | {"parent_context"}
627
651
  parent = sections[parent].parent_index
652
+ if partial_head_index is not None and partial_head_index in trial_reasons:
653
+ trial_reasons[partial_head_index].add("head")
628
654
  new_indices = trial_reasons.keys() - selected_indices
655
+ newly_removed_from_index = {item for item in new_indices if item != partial_head_index}
629
656
  trial_bytes = content_bytes + sum(extra_bytes[item] for item in new_indices)
630
657
  trial_chars = chars_selected + sum(
631
658
  sections[item].end - max(head_end, sections[item].start) for item in new_indices
@@ -646,11 +673,15 @@ def _select_agents_content(source: CollectedFile, signals: _SelectionSignals) ->
646
673
  trial_selected_lines = selected_lines + sum(
647
674
  size - selected_sizes.get(item, 0) for item, size in trial_sizes.items()
648
675
  )
649
- trial_index_count = index_count - len(new_indices)
650
- trial_index_lines = index_lines - sum(index_sizes[item] for item in new_indices)
676
+ trial_index_count = index_count - len(newly_removed_from_index)
677
+ trial_index_lines = index_lines - sum(
678
+ index_sizes[item] for item in newly_removed_from_index
679
+ )
651
680
  trial_first = first_index
652
681
  while trial_first < len(sections) and (
653
- trial_first in selected_indices or trial_first in new_indices
682
+ trial_first in selected_indices
683
+ or trial_first in new_indices
684
+ or trial_first == partial_head_index
654
685
  ):
655
686
  trial_first += 1
656
687
  if (
@@ -684,6 +715,7 @@ def _select_agents_content(source: CollectedFile, signals: _SelectionSignals) ->
684
715
  frozenset(selected_indices),
685
716
  reasons,
686
717
  frozenset(budget_fallback),
718
+ partial_head_index=partial_head_index,
687
719
  parse_fallback=False,
688
720
  source_scan_truncated=source.truncated,
689
721
  source_characters=source.source_characters,