context-loader 1.3.10__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: context-loader
3
- Version: 1.3.10
3
+ Version: 1.4.0
4
4
  Summary: Render deterministic local Git context for any executor
5
5
  License-Expression: Apache-2.0
6
6
  License-File: LICENSE
@@ -19,14 +19,14 @@ Python standard library.
19
19
 
20
20
  ## Open-source quick start
21
21
 
22
- Current stable release: **1.3.10**. Local CLI for coding-agent workflows; renders deterministic Markdown or JSON.
22
+ Current stable release: **1.4.0**. Local CLI for coding-agent workflows; renders deterministic Markdown or JSON.
23
23
 
24
24
  ```bash
25
- uv tool install 'context-loader==1.3.10'
25
+ uv tool install 'context-loader==1.4.0'
26
26
  ```
27
27
 
28
28
  ```bash
29
- pip install 'context-loader==1.3.10'
29
+ pip install 'context-loader==1.4.0'
30
30
  ```
31
31
 
32
32
  ```bash
@@ -39,21 +39,21 @@ project-context --repo /path/to/repo --format json
39
39
 
40
40
  ## Install
41
41
 
42
- Source version: `1.3.10`. Install its matching published release or an exact source commit.
42
+ Source version: `1.4.0`. Install its matching published release or an exact source commit.
43
43
 
44
44
  Install via `uv`:
45
45
 
46
46
  ```bash
47
- uv tool install 'context-loader==1.3.10'
47
+ uv tool install 'context-loader==1.4.0'
48
48
  ```
49
49
 
50
50
  Install via `pip`:
51
51
 
52
52
  ```bash
53
- pip install 'context-loader==1.3.10'
53
+ pip install 'context-loader==1.4.0'
54
54
  ```
55
55
 
56
- For development or source-based installs tracking current repository (`1.3.10`):
56
+ For development or source-based installs tracking current repository (`1.4.0`):
57
57
 
58
58
  ```bash
59
59
  uv tool install git+https://github.com/xuanheng-tech/context-loader.git
@@ -80,10 +80,10 @@ part of either distribution; run them from a checkout of the matching tag.
80
80
  ## Platform and Runtime Requirements
81
81
 
82
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 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.
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
87
  - **Operating System**: supported and locally tested on Ubuntu 24.04 LTS; CI also tests the
88
88
  GitHub-hosted Ubuntu runner. Other Linux/POSIX systems are unverified, not a portability promise.
89
89
  Windows is not supported.
@@ -103,6 +103,7 @@ automatic redaction**. Inspect the output before sharing it with a person or ext
103
103
  project-context --version
104
104
  project-context --repo /home/user/projects/example
105
105
  project-context --repo /home/user/projects/example --format markdown
106
+ project-context --repo /home/user/projects/example --format markdown --layout cache-friendly
106
107
  project-context --repo /home/user/projects/example --format json
107
108
  project-context --repo /home/user/projects/example --format json-compact
108
109
  project-context --repo /home/user/projects/example \
@@ -110,17 +111,21 @@ project-context --repo /home/user/projects/example \
110
111
  --path auth/session.py
111
112
  ```
112
113
 
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.
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.
118
123
 
119
124
  `--focus` and `--path` are optional, bounded selection signals for the root `AGENTS.md`. `--path`
120
125
  must be repository-relative. The collector does not retain either input in output or audit data.
121
126
  Calls that omit both options remain valid and use the conservative fallback described in
122
127
  [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;
128
+ Each value option (`--repo`, `--focus`, `--path`, `--format`, `--layout`) may be supplied once;
124
129
  duplicates are rejected before collection rather than silently overriding an earlier value.
125
130
 
126
131
  ## Markdown Output
@@ -150,8 +155,9 @@ the machine formats; this does not change Markdown content or its byte budgets.
150
155
  ## Authority Boundary
151
156
 
152
157
  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.
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.
155
161
 
156
162
  Resolving an instruction hierarchy stays with the calling agent harness. That includes any
157
163
  shared or user-level instruction file outside the repository, nested or scoped `AGENTS.md` files
@@ -180,7 +186,7 @@ or candidate-file content.
180
186
 
181
187
  ## Not Included
182
188
 
183
- Version 1.3.10 does not provide AI summaries, project-type detection, loading or transport of
189
+ Version 1.4.0 does not provide AI summaries, project-type detection, loading or transport of
184
190
  nested `AGENTS.md` contents (the JSON `nested_context` field reports bounded existence only),
185
191
  Memory retrieval, semantic ranking, ignore-rule parsing, plugins, profiles, caches, databases,
186
192
  network services, MCP, daemons, GUIs, CI/CD, telemetry, or automatic updates.
@@ -8,14 +8,14 @@ Python standard library.
8
8
 
9
9
  ## Open-source quick start
10
10
 
11
- Current stable release: **1.3.10**. Local CLI for coding-agent workflows; renders deterministic Markdown or JSON.
11
+ Current stable release: **1.4.0**. Local CLI for coding-agent workflows; renders deterministic Markdown or JSON.
12
12
 
13
13
  ```bash
14
- uv tool install 'context-loader==1.3.10'
14
+ uv tool install 'context-loader==1.4.0'
15
15
  ```
16
16
 
17
17
  ```bash
18
- pip install 'context-loader==1.3.10'
18
+ pip install 'context-loader==1.4.0'
19
19
  ```
20
20
 
21
21
  ```bash
@@ -28,21 +28,21 @@ project-context --repo /path/to/repo --format json
28
28
 
29
29
  ## Install
30
30
 
31
- Source version: `1.3.10`. Install its matching published release or an exact source commit.
31
+ Source version: `1.4.0`. Install its matching published release or an exact source commit.
32
32
 
33
33
  Install via `uv`:
34
34
 
35
35
  ```bash
36
- uv tool install 'context-loader==1.3.10'
36
+ uv tool install 'context-loader==1.4.0'
37
37
  ```
38
38
 
39
39
  Install via `pip`:
40
40
 
41
41
  ```bash
42
- pip install 'context-loader==1.3.10'
42
+ pip install 'context-loader==1.4.0'
43
43
  ```
44
44
 
45
- For development or source-based installs tracking current repository (`1.3.10`):
45
+ For development or source-based installs tracking current repository (`1.4.0`):
46
46
 
47
47
  ```bash
48
48
  uv tool install git+https://github.com/xuanheng-tech/context-loader.git
@@ -69,10 +69,10 @@ part of either distribution; run them from a checkout of the matching tag.
69
69
  ## Platform and Runtime Requirements
70
70
 
71
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 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.
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
76
  - **Operating System**: supported and locally tested on Ubuntu 24.04 LTS; CI also tests the
77
77
  GitHub-hosted Ubuntu runner. Other Linux/POSIX systems are unverified, not a portability promise.
78
78
  Windows is not supported.
@@ -92,6 +92,7 @@ automatic redaction**. Inspect the output before sharing it with a person or ext
92
92
  project-context --version
93
93
  project-context --repo /home/user/projects/example
94
94
  project-context --repo /home/user/projects/example --format markdown
95
+ project-context --repo /home/user/projects/example --format markdown --layout cache-friendly
95
96
  project-context --repo /home/user/projects/example --format json
96
97
  project-context --repo /home/user/projects/example --format json-compact
97
98
  project-context --repo /home/user/projects/example \
@@ -99,17 +100,21 @@ project-context --repo /home/user/projects/example \
99
100
  --path auth/session.py
100
101
  ```
101
102
 
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.
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.
107
112
 
108
113
  `--focus` and `--path` are optional, bounded selection signals for the root `AGENTS.md`. `--path`
109
114
  must be repository-relative. The collector does not retain either input in output or audit data.
110
115
  Calls that omit both options remain valid and use the conservative fallback described in
111
116
  [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;
117
+ Each value option (`--repo`, `--focus`, `--path`, `--format`, `--layout`) may be supplied once;
113
118
  duplicates are rejected before collection rather than silently overriding an earlier value.
114
119
 
115
120
  ## Markdown Output
@@ -139,8 +144,9 @@ the machine formats; this does not change Markdown content or its byte budgets.
139
144
  ## Authority Boundary
140
145
 
141
146
  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.
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.
144
150
 
145
151
  Resolving an instruction hierarchy stays with the calling agent harness. That includes any
146
152
  shared or user-level instruction file outside the repository, nested or scoped `AGENTS.md` files
@@ -169,7 +175,7 @@ or candidate-file content.
169
175
 
170
176
  ## Not Included
171
177
 
172
- Version 1.3.10 does not provide AI summaries, project-type detection, loading or transport of
178
+ Version 1.4.0 does not provide AI summaries, project-type detection, loading or transport of
173
179
  nested `AGENTS.md` contents (the JSON `nested_context` field reports bounded existence only),
174
180
  Memory retrieval, semantic ranking, ignore-rule parsing, plugins, profiles, caches, databases,
175
181
  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.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,
@@ -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")