trusty-code 0.5.0

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
Documentation
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
//! Unit tests for the prompt-assembly layer (parity-spec §2, §4, §6).
//!
//! Why: The parity guarantee is only as strong as the assembler's determinism
//! and section discipline; these tests pin the stable order, idempotence,
//! separator collapse, and fallback-last placement the spec mandates.
//! What: Exercises [`assemble_system_prompt`] and [`PromptAssembler`] over the
//! full matrix of present/absent sections, plus shape checks on
//! [`BASE_PREAMBLE`] and [`BASE_PREAMBLE_VERSION`].
//! Test: this file.

use crate::agents::AgentConfig;
use crate::mode::HarnessMode;
use crate::prompt::{
    BASE_PREAMBLE, BASE_PREAMBLE_VERSION, DISCOVERY_GUIDANCE, PromptAssembler,
    assemble_system_prompt, assemble_system_prompt_for_mode,
};

/// Build an `AgentConfig` whose `system_prompt.content` is the given string.
///
/// Why: Tests need a minimal config that varies only by prompt content.
/// What: Returns a defaulted `AgentConfig` with `system_prompt.content` set.
/// Test: Used by the tests below (no assertions of its own).
fn config_with_prompt(content: &str) -> AgentConfig {
    let mut cfg = AgentConfig::default();
    cfg.system_prompt.content = content.to_string();
    cfg
}

/// With all four sections present, the assembled order is 1→2→3→4 (spec §2).
///
/// Why: A stable, fixed section order is the backbone of the parity guarantee.
/// What: Asserts the `str::find` positions of BASE, agent prompt, project
/// context, and fallback guidance are strictly increasing.
/// Test: this test.
#[test]
fn assembled_order_is_stable() {
    let cfg = config_with_prompt("AGENT_PROMPT_MARKER");
    let out = assemble_system_prompt(
        &cfg,
        Some("PROJECT_CONTEXT_MARKER"),
        Some("FALLBACK_GUIDANCE_MARKER"),
    );

    let base = out.find(BASE_PREAMBLE).expect("base present");
    let agent = out.find("AGENT_PROMPT_MARKER").expect("agent present");
    let project = out.find("PROJECT_CONTEXT_MARKER").expect("project present");
    let fallback = out
        .find("FALLBACK_GUIDANCE_MARKER")
        .expect("fallback present");

    assert!(base < agent, "BASE must precede agent prompt");
    assert!(agent < project, "agent prompt must precede project context");
    assert!(
        project < fallback,
        "project context must precede fallback guidance"
    );
}

/// Identical inputs produce byte-identical output across calls (spec §1).
///
/// Why: Parity requires determinism; assembly must never reorder or vary.
/// What: Calls the assembler twice with the same inputs and asserts equality.
/// Test: this test.
#[test]
fn base_identical_across_calls() {
    let cfg = config_with_prompt("You are an engineer.");
    let first = assemble_system_prompt(&cfg, Some("# Project\nrules"), None);
    let second = assemble_system_prompt(&cfg, Some("# Project\nrules"), None);
    assert_eq!(first, second);
}

/// Omitted optional sections never produce a doubled separator (spec §2c).
///
/// Why: A collapsed separator (`---\n\n\n\n---`) would be a malformed prompt and
/// signal a section-skipping bug.
/// What: Assembles with no project context and no fallback, then asserts the
/// output contains neither a doubled separator nor a trailing separator.
/// Test: this test.
#[test]
fn omitted_sections_produce_no_double_separator() {
    let cfg = config_with_prompt("Solo agent prompt.");
    let out = assemble_system_prompt(&cfg, None, None);

    assert!(
        !out.contains("\n\n---\n\n\n\n---\n\n"),
        "must not contain a doubled separator: {out:?}"
    );
    assert!(
        !out.ends_with("\n\n---\n\n"),
        "must not end with a dangling separator: {out:?}"
    );
    // Exactly one separator joins BASE and the single agent section.
    assert_eq!(out.matches("\n\n---\n\n").count(), 1);
}

/// An empty agent prompt is skipped, leaving BASE first with no extra rule.
///
/// Why: A blank `system_prompt.content` must not inject an empty section or a
/// dangling separator.
/// What: With an empty agent prompt and no other sections, the output equals
/// `BASE_PREAMBLE` exactly.
/// Test: this test.
#[test]
fn empty_agent_prompt_skipped() {
    let cfg = config_with_prompt("");
    let out = assemble_system_prompt(&cfg, None, None);

    assert!(out.starts_with(BASE_PREAMBLE), "must start with BASE");
    assert_eq!(out, BASE_PREAMBLE, "BASE only — no separators added");
    assert!(
        !out.contains("\n\n---\n\n"),
        "no separator with one section"
    );
}

/// Whitespace-only optional sections are treated as empty.
///
/// Why: A `CLAUDE.md` that is only whitespace (or a fallback string that is)
/// must not inject a meaningless section or a dangling separator.
/// What: Passes whitespace for both optional sections; output equals BASE only.
/// Test: this test.
#[test]
fn whitespace_only_sections_are_skipped() {
    let cfg = config_with_prompt("   \n  ");
    let out = assemble_system_prompt(&cfg, Some("\n\t  \n"), Some("   "));
    assert_eq!(out, BASE_PREAMBLE);
}

/// When supplied, fallback guidance is the final section (spec §4, D4).
///
/// Why: Placing fallback last makes a strong model's prompt a strict prefix of
/// a weak model's, yielding clean diffs and easy disclosure.
/// What: With all sections present, asserts the output ends with the fallback
/// text and that fallback follows the project context.
/// Test: this test.
#[test]
fn fallback_guidance_is_last() {
    let cfg = config_with_prompt("Agent prompt.");
    let out = assemble_system_prompt(&cfg, Some("Project context."), Some("FALLBACK_LAST"));

    assert!(
        out.ends_with("FALLBACK_LAST"),
        "fallback must be last: {out:?}"
    );
    let project = out.find("Project context.").expect("project present");
    let fallback = out.find("FALLBACK_LAST").expect("fallback present");
    assert!(project < fallback);
}

/// Native-tier models (no fallback) get exactly sections 1→2→3 (spec D4).
///
/// Why: Confirms the prefix-compatibility design: the common case omits §4.
/// What: With a project context but no fallback, asserts the output does not
/// contain the fallback and ends with the project context.
/// Test: this test.
#[test]
fn native_tier_omits_fallback_section() {
    let cfg = config_with_prompt("Agent prompt.");
    let out = assemble_system_prompt(&cfg, Some("PROJECT_END"), None);
    assert!(out.ends_with("PROJECT_END"));
    assert_eq!(out.matches("\n\n---\n\n").count(), 2);
}

/// `BASE_PREAMBLE` contains every load-bearing block of spec §2a.
///
/// Why: The preamble is a machine-readable contract; a missing block would
/// silently weaken every agent's instructions.
/// What: Asserts the presence of the tool-use, filesystem, output, and finish
/// signals via their key phrases.
/// Test: this test.
#[test]
fn base_preamble_contains_required_blocks() {
    assert!(
        BASE_PREAMBLE.contains("tool call"),
        "tool-use protocol block missing"
    );
    assert!(
        BASE_PREAMBLE.contains("project root"),
        "filesystem-safety block missing"
    );
    assert!(
        BASE_PREAMBLE.contains("## Summary"),
        "output-convention block missing"
    );
    assert!(
        BASE_PREAMBLE.contains("contains no tool call"),
        "finish-convention block missing"
    );
    assert!(
        BASE_PREAMBLE.contains("trusty-code harness"),
        "identity/role block missing"
    );
}

/// `BASE_PREAMBLE` requires running the project's OWN test suite before
/// finishing, not just self-authored tests (bake-off L1 diagnosis: a
/// delegated engineer's self-reported "my tests pass" previously let a
/// missing feature ship unnoticed).
///
/// Why: This is the default finish-gate strengthening — it must apply to
/// every agent (PM and delegated sub-agents alike), not just a benchmark
/// harness, so it belongs in the model-agnostic BASE preamble every prompt
/// assembles.
/// What: Asserts the preamble instructs discovering/running the project's
/// existing suite and explicitly rejects self-authored tests as a substitute.
/// Test: this test.
#[test]
fn base_preamble_requires_running_project_test_suite_before_finishing() {
    assert!(
        BASE_PREAMBLE.contains("run it, then report the")
            || BASE_PREAMBLE.to_lowercase().contains("run it"),
        "must instruct running the project's own test suite before finishing"
    );
    assert!(
        BASE_PREAMBLE.contains("not a substitute for the"),
        "must reject self-authored tests as a substitute for the project's own suite"
    );
    assert!(
        BASE_PREAMBLE.contains("Never claim tests passed without"),
        "must forbid claiming unverified test results"
    );
}

/// `BASE_PREAMBLE` tells the model that ONE clean run after the last code
/// change is sufficient and to NOT repeat identical confirmation runs over
/// unchanged code (#2682 bake-off L1 diagnosis: the engineer re-ran the full
/// suite 7-14x per run as repeated "one final run to confirm" passes,
/// inflating turn counts far above claude-code's).
///
/// Why: This is the prompt-side half of #2682 (the structural half is
/// `redundant_run`) — a general turn-efficiency nudge that applies to every
/// agent's assembled prompt, so it belongs in the model-agnostic BASE preamble
/// beside the neighbouring verification instructions.
/// What: Asserts the preamble states one clean run is sufficient and forbids a
/// redundant re-run over unchanged code.
/// Test: this test.
#[test]
fn base_preamble_discourages_redundant_test_reruns() {
    assert!(
        BASE_PREAMBLE.contains(
            "ONE clean run of the suite after your LAST code change is \
sufficient"
        ),
        "must state one clean post-change run is sufficient verification"
    );
    assert!(
        BASE_PREAMBLE.contains("do NOT re-run the same suite again"),
        "must forbid repeating an identical confirmation run over unchanged code"
    );
}

/// `BASE_PREAMBLE` nudges toward pure, unit-testable core functions with I/O
/// kept in thin wrappers (#2279 improvement 2, bake-off L2 diagnosis: tcode
/// fused `git` invocation directly into `parse_git_log`, making it untestable
/// against the visible text-fixture suite the challenge instructed it to
/// run).
///
/// Why: This is a general product-quality nudge, not a benchmark-specific
/// patch — it must apply to every agent's assembled prompt, so it belongs in
/// the model-agnostic BASE preamble like the neighbouring verification block.
/// What: Asserts the preamble names both halves of the principle: pure core
/// functions, and I/O kept separate in thin wrappers.
/// Test: this test.
#[test]
fn base_preamble_nudges_testable_design() {
    assert!(
        BASE_PREAMBLE.contains("pure, unit-testable core functions"),
        "must nudge toward pure, unit-testable core functions"
    );
    assert!(
        BASE_PREAMBLE.contains("thin wrapper functions"),
        "must instruct keeping I/O in thin wrapper functions separate from core logic"
    );
}

/// `BASE_PREAMBLE` makes eager schema initialization at application
/// construction the PRIMARY, required mechanism, and explicitly warns that a
/// startup/lifecycle hook alone is insufficient because an in-process test
/// client may construct the app without firing those hooks (#2622 bake-off L3
/// diagnosis, strengthened: the first 1.3.0 fix offered eager init only as an
/// "OR" alternative, so a generated service picked the hook-only branch and the
/// first CRUD request still hit a missing table under the bare test client).
///
/// Why: This is a general product-quality nudge for any service backed by a
/// database or persistent store, not a benchmark- or provider-specific patch —
/// it must apply to every agent's assembled prompt, so it belongs in the
/// model-agnostic BASE preamble alongside the neighbouring design nudges. The
/// eager-at-construction directive must be unambiguously primary so the model
/// cannot satisfy it with a fragile hook-only initialization.
/// What: Asserts the preamble (a) requires creating the schema as part of
/// constructing the application object before the first request, names that the
/// required/primary mechanism, and (b) warns that a startup/lifecycle hook alone
/// is not sufficient because an in-process test client may construct the app
/// without triggering those hooks.
/// Test: this test.
#[test]
fn base_preamble_requires_persistent_store_init() {
    assert!(
        BASE_PREAMBLE.contains("persistent store"),
        "must address services backed by a database or other persistent store"
    );
    assert!(
        BASE_PREAMBLE.contains("BEFORE the service handles its first request"),
        "must instruct initializing the schema before the first request"
    );
    // (a) Eager init at application construction is the PRIMARY, required
    // mechanism — not merely one alternative among several.
    assert!(
        BASE_PREAMBLE.contains("as part of constructing the application object"),
        "must require creating the schema as part of constructing the application object"
    );
    assert!(
        BASE_PREAMBLE.contains("required, primary mechanism"),
        "must name eager construction-time initialization as the required, primary mechanism"
    );
    // (b) A startup/lifecycle hook alone is insufficient because an in-process
    // test client may construct the app without firing those hooks.
    assert!(
        BASE_PREAMBLE.contains("lifecycle event hook alone is NOT sufficient"),
        "must warn that a startup or lifecycle hook alone is not sufficient"
    );
    assert!(
        BASE_PREAMBLE
            .contains("in-process test client may construct the application WITHOUT triggering"),
        "must warn that an in-process test client may construct the app without firing its hooks"
    );
}

/// `BASE_PREAMBLE` makes the task's required-artifact SET a tracked deliverable
/// rather than an epilogue (#2824).
///
/// Why: On the bake-off L4 task the engineer's completion was nondeterministic:
/// with an identical prompt and model, run-2's engineer consumed its full
/// 40-turn `InProcessRunnerConfig` budget (transcript turns 9..=48) and its
/// FINAL turn opened with "Now let me create the README and ARCHITECTURE
/// files" — so `ARCHITECTURE.md` was never written, while run-3 finished the
/// same task in 29 turns. Both runs shipped ~130 self-authored tests; the only
/// difference was that run-2 had less turn margin left when it reached the docs
/// it had queued LAST. Documentation being last in the queue makes it the only
/// deliverable exposed to turn-budget variance, so the preamble must (a) order
/// required docs ahead of discretionary self-authored tests and (b) make the
/// required set explicitly tracked.
/// What: Asserts the load-bearing phrases of the deliverable-completeness block
/// are present — the up-front checklist, the docs-are-deliverables rule, the
/// required-before-discretionary ordering, and the final checklist sweep.
/// Test: this test.
#[test]
fn base_preamble_requires_tracking_the_deliverable_set() {
    assert!(
        BASE_PREAMBLE.contains("## Deliverable completeness"),
        "BASE_PREAMBLE must carry the deliverable-completeness block (#2824)"
    );
    assert!(
        BASE_PREAMBLE.contains("enumerate that set"),
        "must instruct enumerating the required-artifact set up front"
    );
    assert!(
        BASE_PREAMBLE.contains("which items remain outstanding"),
        "must instruct tracking the outstanding items as work proceeds"
    );
    assert!(
        BASE_PREAMBLE.contains("it is not an epilogue"),
        "must state required documentation is not an epilogue"
    );
    assert!(
        BASE_PREAMBLE.contains("the design is settled: write the required documents THEN"),
        "must order required docs at the point the design settles"
    );
    assert!(
        BASE_PREAMBLE.contains("Do the REQUIRED work before any discretionary work"),
        "must order required work ahead of discretionary work"
    );
    assert!(
        BASE_PREAMBLE.contains("while a required artifact is still \nmissing from disk")
            || BASE_PREAMBLE.contains("while a required artifact is still missing from disk"),
        "must forbid starting discretionary work while a required artifact is missing"
    );
    assert!(
        BASE_PREAMBLE.contains("Scale the tests you author yourself to the requirements"),
        "must scale self-authored tests to the requirements (run-2 shipped ~130)"
    );
    assert!(
        BASE_PREAMBLE.contains("walk your checklist one final time"),
        "must require a final completeness sweep before finishing"
    );
}

/// The deliverable-completeness block points at the batch-write tool so a
/// multi-document tail costs one turn, not one per file (#2824).
///
/// Why: Run-2's engineer spent 19 of its 40 turns on single-file `write_file`
/// calls and used the `write_files` batch tool exactly ONCE, despite the
/// tool-use block already recommending batching. Repeating the pointer at the
/// point of use — the doc tail, which is where the budget actually ran out —
/// targets the specific waste the transcript shows.
/// What: Asserts the block names `write_files` and the one-call framing.
/// Test: this test.
#[test]
fn base_preamble_batches_remaining_deliverables() {
    let block = BASE_PREAMBLE
        .split("## Deliverable completeness")
        .nth(1)
        .expect("deliverable-completeness block present");
    let block = block
        .split("## Verification before finishing")
        .next()
        .expect("block is delimited by the following section");
    assert!(
        block.contains("ONE `write_files` call"),
        "the deliverable block must point at the batch-write tool"
    );
    assert!(
        block.contains("rather than one per turn"),
        "must contrast batching against one-file-per-turn writes"
    );
}

/// `BASE_PREAMBLE` carries no host- or model-specific tokens (spec §2a/§3).
///
/// Why: Any model name, provider name, or host path in the BASE preamble would
/// break the byte-identical guarantee.
/// What: Asserts the preamble does not mention common provider/model slugs.
/// Test: this test.
#[test]
fn base_preamble_is_model_agnostic() {
    for forbidden in ["claude", "openai", "gpt", "anthropic", "qwen", "deepseek"] {
        assert!(
            !BASE_PREAMBLE.to_lowercase().contains(forbidden),
            "BASE_PREAMBLE must not mention provider/model token {forbidden:?}"
        );
    }
}

/// `BASE_PREAMBLE_VERSION` is a three-component semver-shaped string (spec D5).
///
/// Why: The parity report records this token; a malformed version would make
/// the report ambiguous.
/// What: Splits on `.` and asserts three numeric components.
/// Test: this test.
#[test]
fn base_preamble_version_is_semver_shaped() {
    let parts: Vec<&str> = BASE_PREAMBLE_VERSION.split('.').collect();
    assert_eq!(parts.len(), 3, "expected MAJOR.MINOR.PATCH");
    for part in parts {
        assert!(
            part.chars().all(|c| c.is_ascii_digit()),
            "non-numeric version component: {part:?}"
        );
    }
}

/// Expected FNV-1a-style fold of [`BASE_PREAMBLE`]'s bytes, folded with its
/// byte length. Regenerate this whenever the preamble legitimately changes
/// (see [`base_preamble_hash_tripwire`] for the contributor instructions).
const EXPECTED_PREAMBLE_HASH: u64 = 0x7518_5b12_b59f_2f94;

/// Test-time guard coupling `BASE_PREAMBLE` *content* to its version constant.
///
/// Why: `BASE_PREAMBLE_VERSION` (in `prompt/version.rs`) is hand-maintained and
/// otherwise decoupled from the preamble text — a contributor can edit the
/// preamble and forget to bump the version, silently making the parity report's
/// version token (spec D5 disclosure) stale. This tripwire fails the build the
/// moment the preamble bytes change without the expected hash being refreshed,
/// forcing the version bump into the same review.
///
/// What: Folds `BASE_PREAMBLE`'s bytes with an inline FNV-1a-style hash (mixed
/// with the byte length) and asserts it equals [`EXPECTED_PREAMBLE_HASH`].
///
/// Note: This is a *tripwire*, not a security or cryptographic hash — collision
/// resistance is irrelevant; we only need a deterministic fingerprint that
/// trips on edits. We deliberately compute the fold inline (FNV-1a over the
/// bytes plus a length mix) rather than using `std::collections::hash_map::
/// DefaultHasher`, whose output is only guaranteed stable *within* a Rust
/// release; the inline fold is byte-stable across every toolchain, so the
/// stored constant never needs a cross-compiler caveat.
///
/// Test: this test (self-checking against the stored constant).
#[test]
fn base_preamble_hash_tripwire() {
    // FNV-1a 64-bit constants (public-domain reference values).
    const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
    const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;

    let mut hash = FNV_OFFSET_BASIS;
    for &byte in BASE_PREAMBLE.as_bytes() {
        hash ^= u64::from(byte);
        hash = hash.wrapping_mul(FNV_PRIME);
    }
    // Mix the byte length so a pure-truncation edit can't preserve the hash.
    hash ^= BASE_PREAMBLE.len() as u64;
    hash = hash.wrapping_mul(FNV_PRIME);

    assert_eq!(
        hash, EXPECTED_PREAMBLE_HASH,
        "BASE_PREAMBLE changed — update EXPECTED_PREAMBLE_HASH and bump \
         BASE_PREAMBLE_VERSION in prompt/version.rs (actual hash: {hash:#018x})"
    );
}

/// The `PromptAssembler` struct produces the same output as the free function.
///
/// Why: The two entry points must never diverge.
/// What: Compares `PromptAssembler::assemble` to `assemble_system_prompt` for
/// identical inputs.
/// Test: this test.
#[test]
fn assembler_struct_matches_free_function() {
    let cfg = config_with_prompt("Agent prompt.");
    let via_struct = PromptAssembler.assemble(&cfg, Some("ctx"), Some("fb"));
    let via_fn = assemble_system_prompt(&cfg, Some("ctx"), Some("fb"));
    assert_eq!(via_struct, via_fn);
}

/// All four sections are present in the fully-populated assembled prompt.
///
/// Why: Acceptance criterion — "all sections present in assembled prompt".
/// What: Asserts BASE, agent, project, and fallback markers all appear.
/// Test: this test.
#[test]
fn all_sections_present_when_supplied() {
    let cfg = config_with_prompt("AGENT");
    let out = assemble_system_prompt(&cfg, Some("PROJECT"), Some("FALLBACK"));
    assert!(out.contains(BASE_PREAMBLE));
    assert!(out.contains("AGENT"));
    assert!(out.contains("PROJECT"));
    assert!(out.contains("FALLBACK"));
}

/// With no skills catalog, #2059's mode-aware branch point must produce
/// IDENTICAL output for both modes — this is the pre-#2069 M1 contract,
/// preserved for any project with no `.claude/skills/` catalog (or when the
/// catalog happens to be empty).
///
/// Why: pins the "byte-identical when there is nothing to progressively
/// disclose" contract so a future change to the `DailyDriver` arm cannot
/// silently regress projects with no skills.
/// What: asserts `Parity` with `skills_catalog: None` returns the exact same
/// string as `assemble_system_prompt`, and `DailyDriver` differs only by the
/// always-present [`DISCOVERY_GUIDANCE`] trailing section (PR A, #2689).
/// Test: this test.
#[test]
fn assemble_system_prompt_for_mode_identical_when_no_skills() {
    let cfg = config_with_prompt("AGENT");
    let baseline = assemble_system_prompt(&cfg, Some("PROJECT"), Some("FALLBACK"));

    let parity = assemble_system_prompt_for_mode(
        HarnessMode::Parity,
        &cfg,
        Some("PROJECT"),
        Some("FALLBACK"),
        None,
    );
    assert_eq!(parity, baseline, "Parity must match baseline byte-for-byte");

    let daily = assemble_system_prompt_for_mode(
        HarnessMode::DailyDriver,
        &cfg,
        Some("PROJECT"),
        Some("FALLBACK"),
        None,
    );
    assert_eq!(
        daily,
        format!("{baseline}\n\n---\n\n{DISCOVERY_GUIDANCE}"),
        "DailyDriver with no skills = baseline + discovery guidance"
    );
}

/// `HarnessMode::DailyDriver` always appends [`DISCOVERY_GUIDANCE`] as a
/// trailing section, before any skills catalog (PR A, #2689).
///
/// Why: the engineer's `search_code` tool needs the model steered toward it;
/// the guidance is static (not project-dependent) so it is always present in
/// DailyDriver.
/// What: asserts the guidance appears after FALLBACK and, when a catalog is
/// present, before the catalog.
/// Test: this test.
#[test]
fn daily_driver_appends_discovery_guidance() {
    let cfg = config_with_prompt("AGENT");
    let catalog = "Available skills:\n- demo-skill: Does demo things";
    let out = assemble_system_prompt_for_mode(
        HarnessMode::DailyDriver,
        &cfg,
        Some("PROJECT"),
        Some("FALLBACK"),
        Some(catalog),
    );
    assert!(out.contains(DISCOVERY_GUIDANCE));
    assert!(out.contains("search_code"));
    let guidance_at = out.find("## Code discovery").expect("guidance present");
    assert!(
        out.find("FALLBACK").unwrap() < guidance_at,
        "guidance after fallback"
    );
    assert!(
        guidance_at < out.find(catalog).unwrap(),
        "guidance before catalog"
    );
}

/// `HarnessMode::Parity` never appends the discovery guidance — the parity
/// spec forbids MCP/tool catalogs in the shared prompt.
///
/// Why: benchmark fairness (D2) requires a byte-identical prompt across models.
/// What: asserts Parity output equals the plain baseline and omits the guidance.
/// Test: this test.
#[test]
fn parity_omits_discovery_guidance() {
    let cfg = config_with_prompt("AGENT");
    let baseline = assemble_system_prompt(&cfg, Some("PROJECT"), Some("FALLBACK"));
    let out = assemble_system_prompt_for_mode(
        HarnessMode::Parity,
        &cfg,
        Some("PROJECT"),
        Some("FALLBACK"),
        Some("Available skills:\n- demo"),
    );
    assert_eq!(out, baseline);
    assert!(!out.contains("## Code discovery"));
}

/// `HarnessMode::DailyDriver` appends a non-empty skills catalog as a
/// trailing section (#2069).
///
/// Why: This is the actual token-efficiency payoff — the DailyDriver prompt
/// gains the cheap metadata-only catalog, never a skill's full body.
/// What: Asserts the DailyDriver output contains both the baseline (BASE +
/// agent + project + fallback) and the catalog text, with the catalog
/// appearing after the baseline.
/// Test: this test.
#[test]
fn daily_driver_appends_skills_catalog() {
    let cfg = config_with_prompt("AGENT");
    let catalog = "Available skills:\n- demo-skill: Does demo things";

    let out = assemble_system_prompt_for_mode(
        HarnessMode::DailyDriver,
        &cfg,
        Some("PROJECT"),
        Some("FALLBACK"),
        Some(catalog),
    );

    assert!(out.contains("AGENT"));
    assert!(out.contains(catalog));
    assert!(
        out.find("FALLBACK").unwrap() < out.find(catalog).unwrap(),
        "the skills catalog must be the trailing section"
    );
}

/// `HarnessMode::Parity` ignores `skills_catalog` entirely, even when given
/// one (#2069's scope note: "Parity mode should NOT progressively
/// disclose").
///
/// Why: The parity spec's byte-identical-schema guarantee (D2) must never
/// depend on which project's `.claude/skills/` catalog happens to be
/// present.
/// What: Asserts `Parity` output with `Some(catalog)` equals the plain
/// `assemble_system_prompt` baseline and does not contain the catalog text.
/// Test: this test.
#[test]
fn parity_ignores_skills_catalog() {
    let cfg = config_with_prompt("AGENT");
    let baseline = assemble_system_prompt(&cfg, Some("PROJECT"), Some("FALLBACK"));
    let catalog = "Available skills:\n- demo-skill: Does demo things";

    let out = assemble_system_prompt_for_mode(
        HarnessMode::Parity,
        &cfg,
        Some("PROJECT"),
        Some("FALLBACK"),
        Some(catalog),
    );

    assert_eq!(out, baseline);
    assert!(!out.contains("demo-skill"));
}