1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
//! Write-side owner of a project's `CLAUDE.md` — named-section override blocks
//! and the compiled-instructions pointer (issue #4754).
//!
//! Why: [`crate::core::claude_md_sections`] is explicitly reader-only ("Scope:
//! reader only"), so every write to `CLAUDE.md` has so far been performed by
//! hand — by an LLM following prose in the `tm-init` skill — against a grammar
//! only the reader actually knows. That is the pairing that fails: prose cannot
//! be idempotent, and the repeat-application bug it invites is not hypothetical
//! in this repo. The shared `## [Unreleased]` changelog section was edited the
//! same hand-merged way and five concurrent PRs stacked five copies into it
//! (#4463–#4475, #4399 burned three rebase rounds), which is exactly why
//! changelog entries moved to per-PR fragment files. A section override stacked
//! twice is worse than a changelog stacked twice: the reader's block parser keeps the
//! FIRST well-formed block and reports the rest as
//! [`crate::core::claude_md_sections::REASON_DUPLICATE`], so the second copy is the one the
//! author just wrote and the one silently ignored.
//!
//! What: [`write_section_override`] — the single entry point that creates,
//! replaces, or leaves alone one section's marker block — and
//! [`ensure_compiled_pointer`], which records where the composed system prompt
//! actually lands. Both are idempotent by construction and both preserve every
//! byte outside the region they own.
//!
//! THE GRAMMAR LIVES IN THE READER, NOT HERE. This module never parses a marker
//! itself: it locates existing blocks with
//! [`locate_blocks`], screens bodies with
//! [`contains_marker_line`], stamps
//! [`SUPPORTED_VERSION`], and spells the token with
//! [`section_token`]. A second grammar here would drift, and
//! the first divergence would be a block this crate writes and this crate then
//! declines to read — an override that is advertised and unread, issue #381
//! verbatim.
//!
//! WHO DECIDES WHAT MAY BE WRITTEN — the package, and only the package, exactly
//! as on the read side. [`section_is_writable`] asks
//! [`CustomizationTier::permits`] for the section as the shipped package
//! declares it. `core` is refused because the package declares it `fixed`, not
//! because this module carries a list naming it; a hardcoded list here would be
//! a second source of truth, and the first time the two disagreed the protected
//! section would become writable in the one surface that must never write it.
//!
//! NEVER FAIL OPEN. Every refusal in this module leaves MORE framework
//! instruction in force, never less, and never a damaged file: a protected
//! section, an empty body, a body carrying its own marker line, a host whose
//! markers are unpaired, and an unavailable package all decline the write and
//! leave `CLAUDE.md` byte-identical. A customization mistake must never be able
//! to delete the PM's instructions — the writer's version of the reader's
//! standing rule.
//!
//! Test: `claude_md_writer_tests.rs`.
use ;
use crateatomic_write;
use crate;
use crateFrameworkContent;
use crate;
/// Where the composed PM system prompt is written, as named in a project's
/// `CLAUDE.md`.
///
/// Why: `CLAUDE.md` and the compiled prompt are read by two different readers
/// (the reader-side module's "CLAUDE.md is read twice" section), and nothing in
/// the project's own file says where the composed half ends up. A reader of
/// `CLAUDE.md` could see marker blocks with no way to find what they compile
/// into. The pointer runs one way only — `CLAUDE.md` → compiled file — so this
/// module records the path without owning, creating, or reading it.
/// What: the path RELATIVE TO THE PROJECT ROOT — which is where the `CLAUDE.md`
/// holding the pointer lives, so a reader can follow it directly. Written
/// verbatim into the pointer block. Producing the file at this path belongs to
/// the instruction pipeline, not here.
///
/// #4752: this was the global `~/.trusty-mpm/framework/INSTRUCTIONS-COMPILED.md`
/// until the compiled prompt became project-local. Nothing writes the global
/// path any more, so a pointer naming it would have sent every reader to a file
/// that never exists.
///
/// #4832 made the file per-SESSION, so the pointer names the DIRECTORY the
/// per-session files live in rather than one file: a pointer written into a
/// project's `CLAUDE.md` outlives any single session, and hard-coding one
/// session's id would send every later reader to a stale path. Kept in step
/// with [`crate::core::instruction_pipeline::compiled_prompt_path`] by
/// `pointer_path_matches_the_instruction_pipeline`, which fails if either side
/// moves.
/// Test: `pointer_block_names_the_compiled_instructions_path`,
/// `pointer_path_matches_the_instruction_pipeline`.
pub const COMPILED_INSTRUCTIONS_PATH: &str =
".trusty-mpm/sessions/<session-id>/INSTRUCTIONS-COMPILED.md";
/// First line of the managed compiled-instructions pointer block.
///
/// Why: the pointer is NOT a section override and must never be parsed as one.
/// These delimiters deliberately fail [`crate::core::claude_md_sections`]'s namespace test —
/// `trusty-mpm ` is not `TRUSTY-MPM:` — so the reader treats the whole block as
/// ordinary prose and raises no `unknown section token` diagnostic for it.
/// What: the begin marker; its presence is how a repeat call finds the block.
/// Test: `pointer_block_is_invisible_to_the_section_reader`.
pub const POINTER_BEGIN: &str = "<!-- trusty-mpm compiled-instructions pointer >>> -->";
/// Last line of the managed compiled-instructions pointer block.
///
/// Test: `pointer_block_is_invisible_to_the_section_reader`.
pub const POINTER_END: &str = "<!-- <<< trusty-mpm compiled-instructions pointer -->";
/// What a write did to the host file.
///
/// Why: `Unchanged` is reported separately from `Replaced` so idempotency is an
/// observable outcome rather than an inference from an unchanged mtime — a
/// second identical call is provably a no-op, not merely a rewrite that
/// happened to produce the same bytes.
/// What: one variant per terminal state of a write.
/// Test: `applying_the_same_override_twice_reports_unchanged`.
/// Why a write was declined, leaving the host untouched.
///
/// Why: every variant is a case where the bundled section stays in force and
/// `CLAUDE.md` keeps its exact prior bytes. Returning them as data rather than
/// only logging keeps "the writer refused" an assertable fact, matching the
/// reader's [`crate::core::claude_md_sections::Rejection`] treatment.
/// What: one variant per rule in the write contract.
/// Test: one test per variant in `claude_md_writer_tests.rs`.
/// The project-relative host every write targets.
///
/// Why: taken from the reader's [`HOST_FILES`] rather than spelled again here,
/// so the writer cannot target a file the reader does not scan.
/// What: the sole host path, joined onto a project root by [`host_path`].
/// Test: `writes_target_the_readers_only_host`.
/// Confirm the shipped package permits a project-tier write of `section`.
///
/// Why: the single decision point for "may this be written?", asking the package
/// exactly as `InstructionPackage::with_overrides` does on
/// the read side. Keeping both sides on one authority is what makes the
/// protected section unwritable rather than merely undocumented.
/// What: `Ok(())` when the declared tier admits [`OverrideTier::Project`];
/// otherwise a rejection, logged at `warn` because a declined customization the
/// author never hears about is the #381 failure mode.
/// Test: `core_is_declined_and_logged`, `every_other_section_is_writable`.
/// The line ending the host predominantly uses.
///
/// Why: a rendered block always spells `\n` internally, so splicing one into a
/// CRLF host would leave a file with mixed endings — a user-visible defect in a
/// file the project owns, and the kind of diff noise that makes a `CLAUDE.md`
/// change unreviewable. Matching the host's dominant ending keeps the writer
/// invisible in the diff.
/// What: `"\r\n"` when more than half the newlines in `text` are CRLF, else
/// `"\n"`. An empty or newline-free host yields `"\n"`.
/// Test: `matches_the_hosts_crlf_line_endings`,
/// `a_mixed_ending_host_takes_the_dominant_ending`.
/// Re-spell a rendered block's `\n` endings as `eol`.
///
/// Why: rendering stays single-spelling (`\n`) so the templates remain readable;
/// the host-specific ending is applied once, at the boundary.
/// What: identity for `"\n"`; otherwise every `\n` becomes `\r\n`. Safe against
/// double-conversion because rendered blocks never contain a `\r`.
/// Test: `matches_the_hosts_crlf_line_endings`.
/// Render one section override block, terminator included.
///
/// Why: the emitted text has to be something the reader accepts unchanged, so
/// every variable part comes from the reader — the token from
/// [`section_token`], the version from [`SUPPORTED_VERSION`].
/// What: `START` line, trimmed body, `END` line, each `\n`-terminated; the
/// caller re-spells the endings via [`normalize_eol`] to match the host.
/// Test: `written_block_declares_the_readers_supported_version`,
/// `round_trips_through_the_reader`.
/// Render the managed compiled-instructions pointer block, terminator included.
///
/// Why: the body is visible Markdown rather than an HTML comment, because the
/// point is that a HUMAN reading `CLAUDE.md` can find the compiled prompt. Only
/// the delimiters are comments.
/// What: begin marker, a blockquote naming [`COMPILED_INSTRUCTIONS_PATH`], end
/// marker.
/// Test: `pointer_block_names_the_compiled_instructions_path`.
/// Splice `replacement` over the line spans `spans`, keeping the first and
/// dropping the rest.
///
/// Why: replacing the first span and DELETING any later duplicate is what makes
/// the post-condition "exactly one block for this section" hold. It is also
/// semantically free: the reader already keeps the first block and reports the
/// others as [`crate::core::claude_md_sections::REASON_DUPLICATE`], so removing them changes
/// which bytes are on disk but not which override is in force. Leaving them
/// would mean a caller could read back its own freshly written value and get a
/// stale one — the stacking failure this module exists to prevent.
///
/// Line indices come from the reader's parse of the same string, and
/// `split_inclusive` yields one segment per `lines()` item while retaining each
/// terminator, so untouched regions survive byte-for-byte including `\r\n` and
/// trailing whitespace.
/// What: concatenates the segments outside every span, emitting `replacement` at
/// the first. Restores a missing final newline when the original lacked one and
/// the last span reached end-of-file.
/// Test: `preserves_surrounding_content_byte_for_byte`,
/// `replacing_collapses_duplicate_blocks_to_one`,
/// `preserves_crlf_line_endings`.
/// Append `block` to `text`, separated by one blank line.
///
/// Why: a project's own prose and a managed block must stay visually distinct,
/// and an existing file that lacks a final newline would otherwise have its last
/// line swallowed into the marker line.
/// What: returns `block` alone for empty input; otherwise `text`, a normalising
/// line ending when absent, a blank line, then `block` — both separators spelled
/// with the host's own `eol`.
/// Test: `appends_after_existing_prose`,
/// `appends_newline_when_existing_file_lacks_trailing_newline`,
/// `matches_the_hosts_crlf_line_endings`.
/// Read the host, treating absence as empty content.
///
/// Why: "no `CLAUDE.md` yet" is the ordinary first-write case, not an error, and
/// must not be distinguishable from an empty one by anything but the outcome.
/// What: `Ok((contents, existed))`; a genuine IO error is surfaced rather than
/// swallowed, because writing over a file that could not be read risks
/// destroying content this module promised to preserve.
/// Test: `creates_the_host_when_absent`, `unreadable_host_is_reported_not_clobbered`.
/// Persist `contents` to `path` unless it already matches.
///
/// Why: routed through the shared [`atomic_write`] entry point (the common
/// entry-point rule) so a crash mid-write cannot leave a half-written
/// `CLAUDE.md` — the file whose corruption would cost a project its
/// instructions.
/// What: writes via temp-file rename; returns `chosen` unchanged for the caller
/// to report.
/// Test: covered by every write test's on-disk assertion.
/// Create, replace, or confirm one named-section override block in a project's
/// `CLAUDE.md`.
///
/// Why: the single owner of section-override writes. Every caller routes here so
/// that idempotency, the protected-section refusal, and byte preservation are
/// properties of the system rather than of whoever wrote the calling prose.
///
/// What, in order: the package must permit the section; the body must be
/// non-empty once trimmed and must not contain a marker line; the host's markers
/// must all be paired. Only then does it splice. An existing block for the
/// section is replaced in place and any duplicate of it removed, so exactly one
/// block for that section survives; with no existing block, one is appended.
/// Re-running with an identical body writes nothing and reports
/// [`WriteOutcome::Unchanged`].
///
/// Every refusal leaves the file byte-identical and the bundled section in
/// force.
///
/// Test: `writes_a_new_block_a_reader_accepts`,
/// `applying_the_same_override_twice_reports_unchanged`,
/// `applying_twice_leaves_exactly_one_block`, `core_is_declined_and_logged`,
/// `preserves_surrounding_content_byte_for_byte`,
/// `an_unclosed_marker_blocks_the_write`.
/// Ensure the project's `CLAUDE.md` names where its compiled prompt lands.
///
/// Why: behaviour 6 of #4754 — a reader of `CLAUDE.md` should be able to find
/// the composed system prompt actually in force. The pointer is one-directional
/// and inert: this module writes the path and never reads, creates, or validates
/// the file it names, which stays the instruction pipeline's to produce.
/// What: appends the managed pointer block, or replaces it when its content has
/// changed; reports [`WriteOutcome::Unchanged`] when already correct. The block
/// is delimited by comments the section reader does not recognise, so it
/// contributes no override and no diagnostic.
/// Test: `pointer_block_names_the_compiled_instructions_path`,
/// `pointer_write_is_idempotent`, `pointer_block_is_invisible_to_the_section_reader`.
/// Locate the managed pointer block's line span, if present.
///
/// Why: the pointer is deliberately outside the marker grammar, so
/// [`locate_blocks`] cannot find it and this small paired scan is required. It
/// stays conservative in the same direction as the reader: an unpaired begin
/// marker yields no span, so the block is appended rather than the file being
/// rewritten around a delimiter whose extent is unknown.
/// It also returns EVERY paired block, not just the first, so [`splice`]
/// collapses duplicates here exactly as it does for sections. The argument is
/// the same one that justified collapsing there: a caller must be able to read
/// back what it wrote, and a second pointer block left behind is a stale copy a
/// reader can find first.
/// What: one `(start, end)` span per paired delimiter, in file order, matching
/// trimmed delimiter lines.
/// Test: `pointer_write_is_idempotent`,
/// `an_unpaired_pointer_marker_does_not_consume_the_file`,
/// `pointer_write_collapses_duplicate_pointer_blocks`.
// A `remove_section_override` counterpart is deliberately absent. Removing a
// block means reverting to the bundled section, which the reader already does
// for an ABSENT block — so deletion has a safe spelling a caller can reach
// without a code path whose bug mode is "deleted more of CLAUDE.md than asked".
// Add it only with a caller that needs it, per issue #4754's minimalism note.