context-loader 1.3.10__tar.gz → 1.4.1__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: context-loader
3
- Version: 1.3.10
3
+ Version: 1.4.1
4
4
  Summary: Render deterministic local Git context for any executor
5
5
  License-Expression: Apache-2.0
6
6
  License-File: LICENSE
@@ -11,6 +11,8 @@ Description-Content-Type: text/markdown
11
11
 
12
12
  # Context Loader
13
13
 
14
+ > **Maintenance freeze (2026-11-21):** Active feature development on `context-loader` is frozen following the November 2026 agent toolchain ROI audit. The existing `v1.4.0` release remains available as-is, and no new features or routine workflow integrations are planned.
15
+
14
16
  Context Loader renders deterministic, bounded context for one local Git working tree.
15
17
  The default CLI output remains Markdown; a stable JSON interface is also available for machine
16
18
  callers. The tool reads repository state and a fixed set of root files without fetching, executing
@@ -19,14 +21,14 @@ Python standard library.
19
21
 
20
22
  ## Open-source quick start
21
23
 
22
- Current stable release: **1.3.10**. Local CLI for coding-agent workflows; renders deterministic Markdown or JSON.
24
+ Current stable release: **1.4.1**. Local CLI for coding-agent workflows; renders deterministic Markdown or JSON.
23
25
 
24
26
  ```bash
25
- uv tool install 'context-loader==1.3.10'
27
+ uv tool install 'context-loader==1.4.1'
26
28
  ```
27
29
 
28
30
  ```bash
29
- pip install 'context-loader==1.3.10'
31
+ pip install 'context-loader==1.4.1'
30
32
  ```
31
33
 
32
34
  ```bash
@@ -39,21 +41,21 @@ project-context --repo /path/to/repo --format json
39
41
 
40
42
  ## Install
41
43
 
42
- Source version: `1.3.10`. Install its matching published release or an exact source commit.
44
+ Source version: `1.4.1`. Install its matching published release or an exact source commit.
43
45
 
44
46
  Install via `uv`:
45
47
 
46
48
  ```bash
47
- uv tool install 'context-loader==1.3.10'
49
+ uv tool install 'context-loader==1.4.1'
48
50
  ```
49
51
 
50
52
  Install via `pip`:
51
53
 
52
54
  ```bash
53
- pip install 'context-loader==1.3.10'
55
+ pip install 'context-loader==1.4.1'
54
56
  ```
55
57
 
56
- For development or source-based installs tracking current repository (`1.3.10`):
58
+ For development or source-based installs tracking current repository (`1.4.1`):
57
59
 
58
60
  ```bash
59
61
  uv tool install git+https://github.com/xuanheng-tech/context-loader.git
@@ -80,10 +82,10 @@ part of either distribution; run them from a checkout of the matching tag.
80
82
  ## Platform and Runtime Requirements
81
83
 
82
84
  - **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 the fixed absolute path `/usr/bin/git`. The
84
- executable is never resolved through `PATH`, so an installation elsewhere is not used and
85
- every invocation fails with exit `1`. Git runs with a sanitized environment that ignores
86
- system, global and per-command configuration, attributes, and hooks.
85
+ - **Git**: Requires the standard `git` CLI at `/usr/bin/git` (with fallback to `/opt/homebrew/bin/git`
86
+ or `/usr/local/bin/git` when `/usr/bin/git` is absent). The executable is never resolved through
87
+ ambient `PATH`. Git runs with a sanitized environment that ignores system, global and per-command
88
+ configuration, attributes, and hooks.
87
89
  - **Operating System**: supported and locally tested on Ubuntu 24.04 LTS; CI also tests the
88
90
  GitHub-hosted Ubuntu runner. Other Linux/POSIX systems are unverified, not a portability promise.
89
91
  Windows is not supported.
@@ -103,6 +105,7 @@ automatic redaction**. Inspect the output before sharing it with a person or ext
103
105
  project-context --version
104
106
  project-context --repo /home/user/projects/example
105
107
  project-context --repo /home/user/projects/example --format markdown
108
+ project-context --repo /home/user/projects/example --format markdown --layout cache-friendly
106
109
  project-context --repo /home/user/projects/example --format json
107
110
  project-context --repo /home/user/projects/example --format json-compact
108
111
  project-context --repo /home/user/projects/example \
@@ -110,17 +113,21 @@ project-context --repo /home/user/projects/example \
110
113
  --path auth/session.py
111
114
  ```
112
115
 
113
- `--format` defaults to `markdown`. In Markdown mode, `--repo` retains the 0.1.1 contract: it must be
114
- the absolute, canonical root of a non-bare Git working tree. In the `json` and `json-compact` modes,
115
- an absolute existing directory inside the working tree is accepted; symlinks are normalized and the
116
- discovered root is reported as `canonical_root`. Relative paths, non-Git directories, regular files,
117
- and bare repositories are rejected in every mode.
116
+ `--format` defaults to `markdown`. `--layout` defaults to `default` (fixed section order starting
117
+ with `Git State`); `--layout cache-friendly` places stable static sections (`Development
118
+ Instructions`, `Project Overview`, `Declared Commands`, `Project Entry Files`, `Directory Tree`)
119
+ before dynamic `Git State` and `Recent Commits` to preserve prompt prefix caching across edits.
120
+ In Markdown mode, `--repo` retains the 0.1.1 contract: it must be the absolute, canonical root of
121
+ a non-bare Git working tree. In the `json` and `json-compact` modes, an absolute existing directory
122
+ inside the working tree is accepted (enforcing worktree-root containment against `core.worktree`
123
+ escapes); symlinks are normalized and the discovered root is reported as `canonical_root`. Relative
124
+ paths, non-Git directories, regular files, and bare repositories are rejected in every mode.
118
125
 
119
126
  `--focus` and `--path` are optional, bounded selection signals for the root `AGENTS.md`. `--path`
120
127
  must be repository-relative. The collector does not retain either input in output or audit data.
121
128
  Calls that omit both options remain valid and use the conservative fallback described in
122
129
  [Supported Root Files](https://github.com/xuanheng-tech/context-loader/blob/HEAD/docs/reference.md#supported-root-files).
123
- Each value option (`--repo`, `--focus`, `--path`, `--format`) may be supplied once;
130
+ Each value option (`--repo`, `--focus`, `--path`, `--format`, `--layout`) may be supplied once;
124
131
  duplicates are rejected before collection rather than silently overriding an earlier value.
125
132
 
126
133
  ## Markdown Output
@@ -150,8 +157,9 @@ the machine formats; this does not change Markdown content or its byte budgets.
150
157
  ## Authority Boundary
151
158
 
152
159
  Context Loader is a bounded transport for repository-root context, not the authority for a
153
- repository's instruction hierarchy. It reads the fixed root candidates listed below, renders them
154
- under explicit limits, and stops there.
160
+ repository's instruction hierarchy. It reads the fixed root candidates listed in
161
+ [Supported Root Files](https://github.com/xuanheng-tech/context-loader/blob/HEAD/docs/reference.md#supported-root-files),
162
+ renders them under explicit limits, and stops there.
155
163
 
156
164
  Resolving an instruction hierarchy stays with the calling agent harness. That includes any
157
165
  shared or user-level instruction file outside the repository, nested or scoped `AGENTS.md` files
@@ -180,7 +188,7 @@ or candidate-file content.
180
188
 
181
189
  ## Not Included
182
190
 
183
- Version 1.3.10 does not provide AI summaries, project-type detection, loading or transport of
191
+ Version 1.4.1 does not provide AI summaries, project-type detection, loading or transport of
184
192
  nested `AGENTS.md` contents (the JSON `nested_context` field reports bounded existence only),
185
193
  Memory retrieval, semantic ranking, ignore-rule parsing, plugins, profiles, caches, databases,
186
194
  network services, MCP, daemons, GUIs, CI/CD, telemetry, or automatic updates.
@@ -1,5 +1,7 @@
1
1
  # Context Loader
2
2
 
3
+ > **Maintenance freeze (2026-11-21):** Active feature development on `context-loader` is frozen following the November 2026 agent toolchain ROI audit. The existing `v1.4.0` release remains available as-is, and no new features or routine workflow integrations are planned.
4
+
3
5
  Context Loader renders deterministic, bounded context for one local Git working tree.
4
6
  The default CLI output remains Markdown; a stable JSON interface is also available for machine
5
7
  callers. The tool reads repository state and a fixed set of root files without fetching, executing
@@ -8,14 +10,14 @@ Python standard library.
8
10
 
9
11
  ## Open-source quick start
10
12
 
11
- Current stable release: **1.3.10**. Local CLI for coding-agent workflows; renders deterministic Markdown or JSON.
13
+ Current stable release: **1.4.1**. Local CLI for coding-agent workflows; renders deterministic Markdown or JSON.
12
14
 
13
15
  ```bash
14
- uv tool install 'context-loader==1.3.10'
16
+ uv tool install 'context-loader==1.4.1'
15
17
  ```
16
18
 
17
19
  ```bash
18
- pip install 'context-loader==1.3.10'
20
+ pip install 'context-loader==1.4.1'
19
21
  ```
20
22
 
21
23
  ```bash
@@ -28,21 +30,21 @@ project-context --repo /path/to/repo --format json
28
30
 
29
31
  ## Install
30
32
 
31
- Source version: `1.3.10`. Install its matching published release or an exact source commit.
33
+ Source version: `1.4.1`. Install its matching published release or an exact source commit.
32
34
 
33
35
  Install via `uv`:
34
36
 
35
37
  ```bash
36
- uv tool install 'context-loader==1.3.10'
38
+ uv tool install 'context-loader==1.4.1'
37
39
  ```
38
40
 
39
41
  Install via `pip`:
40
42
 
41
43
  ```bash
42
- pip install 'context-loader==1.3.10'
44
+ pip install 'context-loader==1.4.1'
43
45
  ```
44
46
 
45
- For development or source-based installs tracking current repository (`1.3.10`):
47
+ For development or source-based installs tracking current repository (`1.4.1`):
46
48
 
47
49
  ```bash
48
50
  uv tool install git+https://github.com/xuanheng-tech/context-loader.git
@@ -69,10 +71,10 @@ part of either distribution; run them from a checkout of the matching tag.
69
71
  ## Platform and Runtime Requirements
70
72
 
71
73
  - **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 the fixed absolute path `/usr/bin/git`. The
73
- executable is never resolved through `PATH`, so an installation elsewhere is not used and
74
- every invocation fails with exit `1`. Git runs with a sanitized environment that ignores
75
- system, global and per-command configuration, attributes, and hooks.
74
+ - **Git**: Requires the standard `git` CLI at `/usr/bin/git` (with fallback to `/opt/homebrew/bin/git`
75
+ or `/usr/local/bin/git` when `/usr/bin/git` is absent). The executable is never resolved through
76
+ ambient `PATH`. Git runs with a sanitized environment that ignores system, global and per-command
77
+ configuration, attributes, and hooks.
76
78
  - **Operating System**: supported and locally tested on Ubuntu 24.04 LTS; CI also tests the
77
79
  GitHub-hosted Ubuntu runner. Other Linux/POSIX systems are unverified, not a portability promise.
78
80
  Windows is not supported.
@@ -92,6 +94,7 @@ automatic redaction**. Inspect the output before sharing it with a person or ext
92
94
  project-context --version
93
95
  project-context --repo /home/user/projects/example
94
96
  project-context --repo /home/user/projects/example --format markdown
97
+ project-context --repo /home/user/projects/example --format markdown --layout cache-friendly
95
98
  project-context --repo /home/user/projects/example --format json
96
99
  project-context --repo /home/user/projects/example --format json-compact
97
100
  project-context --repo /home/user/projects/example \
@@ -99,17 +102,21 @@ project-context --repo /home/user/projects/example \
99
102
  --path auth/session.py
100
103
  ```
101
104
 
102
- `--format` defaults to `markdown`. In Markdown mode, `--repo` retains the 0.1.1 contract: it must be
103
- the absolute, canonical root of a non-bare Git working tree. In the `json` and `json-compact` modes,
104
- an absolute existing directory inside the working tree is accepted; symlinks are normalized and the
105
- discovered root is reported as `canonical_root`. Relative paths, non-Git directories, regular files,
106
- and bare repositories are rejected in every mode.
105
+ `--format` defaults to `markdown`. `--layout` defaults to `default` (fixed section order starting
106
+ with `Git State`); `--layout cache-friendly` places stable static sections (`Development
107
+ Instructions`, `Project Overview`, `Declared Commands`, `Project Entry Files`, `Directory Tree`)
108
+ before dynamic `Git State` and `Recent Commits` to preserve prompt prefix caching across edits.
109
+ In Markdown mode, `--repo` retains the 0.1.1 contract: it must be the absolute, canonical root of
110
+ a non-bare Git working tree. In the `json` and `json-compact` modes, an absolute existing directory
111
+ inside the working tree is accepted (enforcing worktree-root containment against `core.worktree`
112
+ escapes); symlinks are normalized and the discovered root is reported as `canonical_root`. Relative
113
+ paths, non-Git directories, regular files, and bare repositories are rejected in every mode.
107
114
 
108
115
  `--focus` and `--path` are optional, bounded selection signals for the root `AGENTS.md`. `--path`
109
116
  must be repository-relative. The collector does not retain either input in output or audit data.
110
117
  Calls that omit both options remain valid and use the conservative fallback described in
111
118
  [Supported Root Files](https://github.com/xuanheng-tech/context-loader/blob/HEAD/docs/reference.md#supported-root-files).
112
- Each value option (`--repo`, `--focus`, `--path`, `--format`) may be supplied once;
119
+ Each value option (`--repo`, `--focus`, `--path`, `--format`, `--layout`) may be supplied once;
113
120
  duplicates are rejected before collection rather than silently overriding an earlier value.
114
121
 
115
122
  ## Markdown Output
@@ -139,8 +146,9 @@ the machine formats; this does not change Markdown content or its byte budgets.
139
146
  ## Authority Boundary
140
147
 
141
148
  Context Loader is a bounded transport for repository-root context, not the authority for a
142
- repository's instruction hierarchy. It reads the fixed root candidates listed below, renders them
143
- under explicit limits, and stops there.
149
+ repository's instruction hierarchy. It reads the fixed root candidates listed in
150
+ [Supported Root Files](https://github.com/xuanheng-tech/context-loader/blob/HEAD/docs/reference.md#supported-root-files),
151
+ renders them under explicit limits, and stops there.
144
152
 
145
153
  Resolving an instruction hierarchy stays with the calling agent harness. That includes any
146
154
  shared or user-level instruction file outside the repository, nested or scoped `AGENTS.md` files
@@ -169,7 +177,7 @@ or candidate-file content.
169
177
 
170
178
  ## Not Included
171
179
 
172
- Version 1.3.10 does not provide AI summaries, project-type detection, loading or transport of
180
+ Version 1.4.1 does not provide AI summaries, project-type detection, loading or transport of
173
181
  nested `AGENTS.md` contents (the JSON `nested_context` field reports bounded existence only),
174
182
  Memory retrieval, semantic ranking, ignore-rule parsing, plugins, profiles, caches, databases,
175
183
  network services, MCP, daemons, GUIs, CI/CD, telemetry, or automatic updates.
@@ -1,3 +1,3 @@
1
1
  """Project Context Loader."""
2
2
 
3
- __version__ = "1.3.10"
3
+ __version__ = "1.4.1"
@@ -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,
@@ -252,6 +252,7 @@ def load_project_context(
252
252
  focus: str | None = None,
253
253
  path: str | None = None,
254
254
  include_nested_context: bool = True,
255
+ layout: str = "default",
255
256
  ) -> ProjectContextResult:
256
257
  """Collect one repository once and return its deterministic machine-readable result.
257
258
 
@@ -271,7 +272,7 @@ def load_project_context(
271
272
  )
272
273
  except AgentsSelectionInputError as exc:
273
274
  raise ContextLoaderError(str(exc), exit_code=2) from None
274
- rendered = render_markdown_with_details(state, project)
275
+ rendered = render_markdown_with_details(state, project, layout=layout)
275
276
  context = rendered.output.decode("utf-8")
276
277
  rendered_bodies = rendered.source_bodies
277
278
  sources = _sources(state.repository, rendered_bodies)
@@ -13,8 +13,21 @@ from .git import ContextLoaderError
13
13
 
14
14
  class SafeArgumentParser(argparse.ArgumentParser):
15
15
  def error(self, message: str) -> None:
16
- del message
17
- raise ContextLoaderError("invalid command-line arguments", exit_code=2)
16
+ # Categorize failures using static messages without echoing caller tokens or paths.
17
+ lowered = message.lower()
18
+ if "option supplied more than once" in lowered:
19
+ reason = "invalid command-line arguments: option supplied more than once"
20
+ elif "the following arguments are required" in lowered:
21
+ reason = "invalid command-line arguments: missing required option"
22
+ elif "unrecognized arguments" in lowered:
23
+ reason = "invalid command-line arguments: unrecognized argument"
24
+ elif "invalid choice" in lowered:
25
+ reason = "invalid command-line arguments: invalid option value"
26
+ elif "expected one argument" in lowered:
27
+ reason = "invalid command-line arguments: option requires a value"
28
+ else:
29
+ reason = "invalid command-line arguments"
30
+ raise ContextLoaderError(reason, exit_code=2)
18
31
 
19
32
 
20
33
  class _OnceAction(argparse.Action):
@@ -60,7 +73,17 @@ def _parser() -> argparse.ArgumentParser:
60
73
  action=_OnceAction,
61
74
  help=(
62
75
  "output format (default: markdown); json-compact omits the "
63
- "duplicated source bodies (see README, Compact model consumption)"
76
+ "duplicated source bodies (see docs/reference.md, Compact model consumption)"
77
+ ),
78
+ )
79
+ parser.add_argument(
80
+ "--layout",
81
+ choices=("default", "cache-friendly"),
82
+ default="default",
83
+ action=_OnceAction,
84
+ help=(
85
+ "section order in rendered context (default: default); "
86
+ "cache-friendly places stable static sections before dynamic Git state"
64
87
  ),
65
88
  )
66
89
  return parser
@@ -75,6 +98,7 @@ def main(argv: Sequence[str] | None = None) -> int:
75
98
  focus=arguments.focus,
76
99
  path=arguments.target_path,
77
100
  include_nested_context=arguments.format != "markdown",
101
+ layout=arguments.layout,
78
102
  )
79
103
  if arguments.format == "markdown":
80
104
  output = result.context.encode("utf-8")