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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
//! Multi-contributor commit attribution ledger (#1707/#1709 family, "the
//! contract").
//!
//! A single interactive session can hand material work to more than one
//! model, harness, or crew delegate between commits — a `/model` switch, a
//! `/backend` repoint, a loadout swap, a crew leaf landing its own edits.
//! Each of those is a genuine contributor to the work the NEXT commit
//! represents, and none of them may silently displace an earlier one.
//!
//! [`AttributionLedger`] is the pending-contributor set for one commit: an
//! ordered, deduplicated collection of [`Attribution`] identities, `add`ed to
//! as work lands and `clear`ed only once a commit built from it actually
//! succeeds. It is deliberately NOT `Option<Attribution>` — there is no
//! maximum contributor count, and a later contributor never overwrites an
//! earlier one.
//!
//! Identity is `(model, harness, email)` — never self-reported by the model.
//! Callers resolve `model`/`harness` from authoritative runtime state (the
//! active backend/loadout, the actual execution harness) and pass them to
//! [`AttributionLedger::record`]; `email` comes from the ledger's configured
//! default (ordinarily [`crate::agent_identity::AgentIdentity::email`]).
use std::collections::HashSet;
/// One AI collaborator credited on a commit: the model that did the work,
/// the harness it ran under, and the email the credit is attributed to.
///
/// Renders as a single `Co-authored-by:` trailer — see [`Attribution::trailer`].
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Attribution {
/// The resolved model identifier (e.g. `"claude-opus-4-8"`,
/// `"ornith_35b"`, `"gpt-5.6-sol"`). Never a model's self-report — the
/// caller resolves this from the session's active backend/loadout.
pub model: String,
/// The execution harness the model ran under (e.g. `"newt-agent"`,
/// `"newt-agent crew"`). Never a model's self-report.
pub harness: String,
/// The harness **version** the model ran under, captured at contribution
/// time (e.g. [`crate::build_info::PACKAGE_VERSION`]). Pairs with
/// [`Attribution::harness`] so a contributor is always credited under the
/// *actual* harness build that ran its work — the same model under
/// `v0.7.6` and `v0.8.0` is two distinct contributors, not one ambiguous
/// identity (audit Q9). Renders inside the trailer's `(<harness> v<ver>)`
/// qualifier, matching [`CommitAttribution::model_trailer`].
pub harness_version: String,
/// The email the credit is attributed to. It names the **harness**, not
/// the model: a co-author line credits a real account, so a harness signs
/// its own address and never another's. Newt's own contributions carry
/// [`crate::agent_identity::DEFAULT_AGENT_EMAIL`] (or the configured
/// override); a contributor that ran under a foreign harness carries that
/// harness's address — which is why this is a per-contributor field and
/// not one value hung off the ledger.
pub email: String,
/// The harness **build** the model ran under — for newt,
/// [`crate::build_info::SOURCE_ID`]: the git commit it was compiled from,
/// `-dirty`-suffixed when the worktree was modified. `None` for a harness
/// that reports no build revision.
///
/// A package version alone does not identify a build; every dev build
/// between two releases claims the same semver. Part of the identity for
/// the same reason [`Attribution::harness_version`] is: a different build
/// is a different thing that ran the work.
pub harness_build: Option<String>,
}
/// The GitHub noreply account a `<id>+<login>@users.noreply.github.com`
/// address names, e.g. `newt-agent`. `None` for any other address shape — a
/// generic mailbox like `codex@openai.com` names a provider, not an account,
/// and must not be treated as naming a harness.
fn noreply_login(email: &str) -> Option<&str> {
let local = email.strip_suffix("@users.noreply.github.com")?;
let (_id, login) = local.split_once('+')?;
(!login.is_empty()).then_some(login)
}
/// The parenthesized qualifier in a co-author trailer: what ran the work,
/// beyond what the address already says.
///
/// The ONE place the qualifier is rendered — [`Attribution::trailer`] and
/// [`CommitAttribution::model_trailer`] both call it, so the two can never
/// drift into different shapes.
///
/// The harness NAME is dropped when the email already carries it: against
/// `<…+newt-agent@…>` the harness `newt-agent` is pure repetition, and
/// `newt-agent crew` reduces to the part the address does not tell you,
/// `crew`. A foreign harness keeps its full name, because its address does
/// not spell it out — which is what keeps `Model A (newt-agent)` and
/// `Model A (Codex CLI)` two visibly distinct contributors on one commit.
fn qualifier(harness: &str, version: &str, build: Option<&str>) -> String {
let mut out = String::new();
if !harness.is_empty() {
out.push_str(harness);
out.push(' ');
}
out.push('v');
out.push_str(version);
if let Some(build) = build.filter(|b| !b.is_empty()) {
out.push(' ');
out.push_str(build);
}
out
}
/// The harness name as it should appear in a qualifier next to `email` —
/// emptied when the address already names it. See [`qualifier`].
fn harness_beyond_email(harness: &str, email: &str) -> String {
let Some(login) = noreply_login(email) else {
return harness.to_string();
};
match harness.strip_prefix(login) {
// Exactly the account name: the address says it all.
Some("") => String::new(),
// `newt-agent crew` -> `crew`. The space guard keeps a harness that
// merely *starts with* the login (`newt-agentic`) fully spelled out.
Some(rest) => rest.strip_prefix(' ').unwrap_or(harness).to_string(),
None => harness.to_string(),
}
}
impl Attribution {
#[must_use]
pub fn new(
model: impl Into<String>,
harness: impl Into<String>,
harness_version: impl Into<String>,
email: impl Into<String>,
) -> Self {
Self {
model: model.into(),
harness: harness.into(),
harness_version: harness_version.into(),
email: email.into(),
harness_build: None,
}
}
/// Pin the harness build revision this contribution ran under (for newt,
/// [`crate::build_info::SOURCE_ID`]). Chainable on [`Attribution::new`].
#[must_use]
pub fn with_build(mut self, build: impl Into<String>) -> Self {
self.harness_build = Some(build.into());
self
}
/// The single `Co-authored-by:` trailer line for this contributor:
/// `Co-authored-by: <model> (<harness> v<harness_version>) <email>` —
/// the SAME canonical shape [`CommitAttribution::model_trailer`] renders,
/// so a ledger contributor and the active-at-commit model can never
/// format attribution differently.
///
/// [`CommitAttribution::model_trailer`]: CommitAttribution::model_trailer
#[must_use]
pub fn trailer(&self) -> String {
format!(
"Co-authored-by: {} ({}) <{}>",
self.model,
qualifier(
&harness_beyond_email(&self.harness, &self.email),
&self.harness_version,
self.harness_build.as_deref(),
),
self.email
)
}
}
/// The complete provenance of ONE commit: the model that drove it, the
/// harness build that ran it, and the operator + agent identities the
/// commit is attributed to. A snapshot of **authoritative runtime state**
/// at the moment a commit is about to be signed — never model-generated
/// text, never a session-startup cache.
///
/// Distinct from [`Attribution`] / [`AttributionLedger`], which are the
/// *multi-contributor AI-credit* set for a commit. [`CommitAttribution`] is
/// the single envelope around that set: the *active* model (one value, the
/// one driving this commit), the *harness build* (name + version + revision
/// + dirty state), and the *human operator* + *agent account* emails.
///
/// Every field is resolved from an existing authoritative source — see the
/// field docs and [`CommitAttribution::from_runtime`]. Construction is
/// **tool-less and deterministic** (no subprocess): harness fields come from
/// compile-time [`crate::build_info`] (plus the `NEWT_BRAND_NAME` env read),
/// and `model` / `operator` / `agent_email` are passed in from their live
/// sources, so a fresh [`CommitAttribution::from_runtime`] call always
/// reflects the *current* active model — a `/model` switch between commits
/// shows up in the next value, not the one captured at session boot.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommitAttribution {
/// The active model that drove this commit — the **live** resolved model
/// (the same `&str` threaded as the agent loop's `ChatCtx::model`), not a
/// session-startup snapshot and not the model's prompt/system text. The
/// caller passes the *current* value per commit, so a `/model` (or
/// `/backend` / loadout) switch is reflected in the next construction.
pub model: String,
/// The execution harness name — [`crate::build_info::harness_name()`]:
/// the `NEWT_BRAND_NAME` env override else the compiled-in
/// [`crate::build_info::DEFAULT_BRAND_NAME`] (`"newt-agent"`). The single
/// authoritative "which harness is this" source (no duplicate constant).
pub harness_name: String,
/// Harness SemVer version — [`crate::build_info::PACKAGE_VERSION`], from
/// `CARGO_PKG_VERSION` at compile time.
pub harness_version: String,
/// Harness build revision + dirty state — [`crate::build_info::SOURCE_ID`]:
/// the checked-out git commit captured at build time, with a `-dirty`
/// suffix when the worktree had tracked or untracked changes.
pub harness_build_revision: String,
/// The human operator running the agent, when known. Reuses the
/// configured [`crate::agent_identity::AgentIdentity::operator`] field.
/// The host-git fallback ([`crate::agent_identity::AgentIdentity::operator_name`])
/// shells out to `git config` and is therefore the *caller's*
/// responsibility — kept out of this tool-less constructor.
pub operator_name: Option<String>,
/// The human operator's email. [`None`] **explicitly** when no operator
/// email is configured — never invented. No operator-email source exists
/// in `agent-identity.toml` today; the field is `Option` so a future
/// source can populate it without reshaping the type.
pub operator_email: Option<String>,
/// The agent account's attribution email — the canonical Newt Agent
/// GitHub noreply address
/// ([`crate::agent_identity::DEFAULT_AGENT_EMAIL`]), overridable via a
/// resolved [`crate::agent_identity::AgentIdentity::email`].
pub agent_email: String,
/// #1707/#1709 semantic B — the accumulated multi-contributor set for
/// this commit: every model/harness/version that materially contributed
/// to the committed work, NOT just the active-at-commit model. A snapshot
/// of the session [`AttributionLedger`] captured at the latest practical
/// point before the turn that may commit (see the session loop); empty
/// (`Vec::new()`) is the single-active-model floor (semantic A).
/// [`CommitAttribution::finalize_message`] merges this with the active
/// model and renders one `Co-authored-by:` trailer per contributor.
pub contributors: Vec<Attribution>,
}
impl CommitAttribution {
/// Build a commit attribution from already-resolved runtime state.
///
/// Tool-less and deterministic — no subprocess: `harness_name` /
/// `harness_version` / `harness_build_revision` come from
/// [`crate::build_info`] (compile-time constants plus the `NEWT_BRAND_NAME`
/// env read), and `model` / `operator_name` / `agent_email` are passed in
/// from their live sources. A fresh call therefore always reflects the
/// *current* active model, not a session-boot snapshot.
///
/// `operator_email` has no source today and is left [`None`] (see the
/// field doc); set it directly on the returned value if a source is added.
#[must_use]
pub fn from_runtime(
model: impl Into<String>,
operator_name: Option<String>,
agent_email: impl Into<String>,
) -> Self {
Self {
model: model.into(),
harness_name: crate::build_info::harness_name(),
harness_version: crate::build_info::PACKAGE_VERSION.to_string(),
harness_build_revision: crate::build_info::SOURCE_ID.to_string(),
operator_name,
operator_email: None,
agent_email: agent_email.into(),
contributors: Vec::new(),
}
}
/// Convenience: pull `agent_email` and `operator_name` from a resolved
/// [`crate::agent_identity::AgentIdentity`]. Uses the configured
/// `operator` field directly (no host-git subprocess fallback) to keep
/// construction tool-less; a caller that wants the `git config user.name`
/// fallback should apply [`crate::agent_identity::AgentIdentity::operator_name`]
/// itself and pass the result through [`CommitAttribution::from_runtime`].
#[must_use]
pub fn from_identity(
model: impl Into<String>,
identity: &crate::agent_identity::AgentIdentity,
) -> Self {
Self::from_runtime(model, identity.operator.clone(), identity.email.clone())
}
// ---- deterministic commit-message finalization (#1709 family) ----
//
// The model is allowed to provide only a commit subject + body. The
// harness owns attribution. [`CommitAttribution::finalize_message`] takes
// the model-provided message and this typed provenance value, and renders
// ONE canonical, idempotent commit message from them — replacing any
// stale Newt-owned attribution a previous run left, preserving legitimate
// third-party trailers, and never hard-coding a model or package version
// (both come from this single typed value).
/// The canonical Newt-managed model attribution trailer, rendered from
/// this typed value:
/// `Co-authored-by: <model> (<harness> v<version>) <agent-email>`.
///
/// `model`, `harness_name`, `harness_version`, and `agent_email` are all
/// fields of this one [`CommitAttribution`] (requirements 1, 3, 4) — no
/// current-model or current-package-version constant is hard-coded.
#[must_use]
pub fn model_trailer(&self) -> String {
self.active_attribution().trailer()
}
/// The active-at-commit model as a contributor identity — the same typed
/// value the ledger holds, so the active model and an accumulated
/// contributor can never render differently. Used by
/// [`CommitAttribution::model_trailer`] and by the merge in
/// [`CommitAttribution::finalize_message_with`].
#[must_use]
pub fn active_attribution(&self) -> Attribution {
Attribution::new(
&self.model,
&self.harness_name,
&self.harness_version,
&self.agent_email,
)
.with_build(&self.harness_build_revision)
}
/// The canonical operator co-author trailer, rendered from this value's
/// operator identity: `Co-authored-by: <operator> <operator-email>`.
/// Returns `None` when no real operator email is known — never invented
/// (requirement 4: never invent an operator email). Distinct from
/// [`CommitAttribution::model_trailer`] (requirement 8: Newt model
/// attribution is independent from operator attribution): the operator is
/// a human co-author, credited to their OWN email, separate from the
/// accumulated model contributors.
#[must_use]
pub fn operator_trailer(&self) -> Option<String> {
self.operator_email.as_ref().map(|email| {
format!(
"Co-authored-by: {} <{}>",
self.operator_name.as_deref().unwrap_or("unknown"),
email
)
})
}
/// The trailer block a commit finalized RIGHT NOW would carry: every
/// accumulated contributor, the active-at-commit model, the operator
/// by-line when a real operator email is known, and the provenance line —
/// in the order a commit gets them.
///
/// This is what `/byline` shows the operator (and the model). It runs the
/// REAL finalizer over an empty message rather than re-rendering the
/// pieces itself, so a preview can never show something the commit would
/// not actually receive — the failure mode a hand-rolled preview invites.
#[must_use]
pub fn byline(&self, contributors: &[Attribution]) -> Vec<String> {
self.finalize_message_with("", contributors)
.lines()
.filter(|line| !line.trim().is_empty())
.map(str::to_string)
.collect()
}
/// The canonical provenance line, rendered from this same typed value
/// (requirement 2):
/// `Harness: <harness> v<version> (<revision>) | Model: <model> | Operator: <operator>`.
///
/// `operator` is [`CommitAttribution::operator_name`] when known, else the
/// deterministic sentinel `"unknown"`. No operator *email* is ever
/// manufactured (requirement 12) — this line carries the operator *name*,
/// and [`CommitAttribution::operator_email`] is intentionally absent from
/// the rendered output.
#[must_use]
pub fn provenance_line(&self) -> String {
format!(
"Harness: {} v{} ({}) | Model: {} | Operator: {}",
self.harness_name,
self.harness_version,
self.harness_build_revision,
self.model,
self.operator_name.as_deref().unwrap_or("unknown"),
)
}
/// Finalize a commit message from a model-provided subject/body plus this
/// typed provenance value — rendering **semantic B** (accumulated
/// contributors) when [`CommitAttribution::contributors`] is non-empty,
/// and the single-active-model floor (semantic A) when it is empty.
///
/// Delegates to [`CommitAttribution::finalize_message_with`] with this
/// value's `contributors` snapshot: the active-at-commit model is always
/// merged in (it drove the commit), and every prior contributor in the
/// snapshot gets its own `Co-authored-by:` trailer — so a `/model` switch
/// mid-session credits BOTH models on the one commit (the contract),
/// while an empty snapshot yields exactly the single active-model
/// trailer (bit-for-bit the floor).
#[must_use]
pub fn finalize_message(&self, message: &str) -> String {
self.finalize_message_with(message, &self.contributors)
}
/// Finalize a commit message from a model-provided subject/body plus this
/// typed provenance value AND an accumulated contributor set — semantic B
/// (#1707/#1709 "accumulated contributors").
///
/// The model may provide any subject + body text; the harness owns the
/// attribution. This:
///
/// 1. Merges `contributors` with the active-at-commit model (this value):
/// the active model drove the commit, so it is always a contributor
/// even if the ledger is empty (the floor). Deduplicates on the full
/// `(model, harness, harness_version, email)` identity, preserving
/// first-contribution order with the active model appended if new — so
/// a `/model` switch mid-session ADDS a contributor and never discards
/// an earlier one (the contract), while an empty ledger yields exactly
/// the single active-model trailer (bit-for-bit the floor).
/// 2. Splits the message into body + a trailing trailer block (git's
/// "blank line before trailers" convention).
/// 3. Partitions the existing trailers into Newt-owned vs third-party.
/// Newt-owned = ANY `Co-authored-by:` line attributed to this value's
/// `agent_email` (there may be several from a prior multi-contributor
/// run — all are stale and replaced, not just one) and the provenance
/// line (any `Harness:` line).
/// 4. Drops stale Newt-owned model attribution and stale provenance,
/// preserving legitimate third-party `Co-authored-by:` /
/// `Signed-off-by:` / … trailers verbatim and in order.
/// 5. Appends a blank line, the preserved third-party trailers, then ONE
/// `Co-authored-by:` trailer per merged contributor (canonical
/// `<model> (<harness> v<version>) <email>` shape), then the single
/// provenance line rendered from this value.
///
/// The provenance line stays single (one harness build drives the commit);
/// the multi-contributor history lives in the per-contributor trailers,
/// each paired with its own harness/version — matching the contract's
/// "many `Co-authored-by:`, one `Harness:` provenance" shape.
///
/// Repeated finalization is idempotent: running it on its own output
/// yields the same bytes, because the freshly-rendered Newt trailers are
/// recognized as Newt-owned on the next pass and replaced rather than
/// duplicated.
///
/// Rendering is deterministic: given the same typed value, the same
/// contributor set, and the same input message, the output is
/// byte-identical — no wall clock, no subprocess, no model text beyond
/// what the caller passed.
#[must_use]
pub fn finalize_message_with(&self, message: &str, contributors: &[Attribution]) -> String {
let (body, existing) = split_message(message);
let agent_email_tag = format!("<{}>", self.agent_email);
// Operator co-author attribution — INDEPENDENT from model attribution
// (requirement 8). Emitted ONLY when a REAL operator email is known
// (requirement 3 + 4: never invented) AND the operator is not already
// the commit's primary author. The git commit author is this value's
// `agent_email`; when the operator's email equals it, the operator IS
// the primary author and a duplicate `Co-authored-by:` is both wrong
// and ignored by GitHub (requirement: avoid emitting an operator
// co-author identical to the primary author).
let operator_email_tag = self.operator_email.as_ref().map(|e| format!("<{e}>"));
// Merge accumulated contributors with the active-at-commit model.
// Dedup on the full identity; first-contribution order, active model
// appended only if it is not already present.
let mut merged: Vec<Attribution> = Vec::with_capacity(contributors.len() + 1);
let mut seen: HashSet<Attribution> = HashSet::with_capacity(contributors.len() + 1);
for c in contributors {
if seen.insert(c.clone()) {
merged.push(c.clone());
}
}
let active = self.active_attribution();
if seen.insert(active.clone()) {
merged.push(active);
}
let mut third_party: Vec<String> = Vec::new();
for trailer in existing {
if is_newt_model_trailer(&trailer, &agent_email_tag) || is_newt_provenance(&trailer) {
continue; // stale Newt-owned model attribution / provenance — drop, re-render below
}
// A stale Newt-managed OPERATOR trailer (credited to the known
// operator email) is also dropped + re-rendered, so
// re-finalization is idempotent and never duplicates it
// (requirement 5: avoid duplicate operator co-author trailers;
// requirement 11: keep finalization idempotent). Independent from
// model attribution — matched on the OPERATOR email, not the
// agent email.
if let Some(tag) = &operator_email_tag {
if is_newt_operator_trailer(&trailer, tag) {
continue;
}
}
third_party.push(trailer);
}
// Emit the operator co-author trailer only when a real operator email
// is known AND it differs from the primary author's email.
let emit_operator = operator_email_tag
.as_ref()
.is_some_and(|tag| tag.as_str() != agent_email_tag.as_str());
let mut trailers = third_party;
for c in &merged {
trailers.push(c.trailer());
}
// Operator co-author trailer — separate from the model contributors,
// rendered after them. Omitted when no real operator email is known
// OR the operator is already the primary author. Never duplicates
// (stale ones were dropped above).
if emit_operator {
trailers.push(
self.operator_trailer()
.expect("operator email known and distinct"),
);
}
trailers.push(self.provenance_line());
let mut out = body;
out.push_str("\n\n");
out.push_str(&trailers.join("\n"));
out.push('\n');
out
}
}
// ---- message-splitting + Newt-owned-trailer recognition helpers ----
//
// Free functions (not methods): they take no `&self`, so they are pure
// functions of their arguments and trivially unit-testable in isolation.
/// A line is trailer-shaped if it is `Key: value` with an alphanumeric /
/// `-` / `_` key — the shape git's trailer parser recognizes. Continuation
/// lines and blank lines are NOT recognized (the canonical Newt trailers are
/// single-line); a multi-line trailer block therefore falls back to "no
/// trailers" and is preserved as body, which is safe (we never drop user
/// text).
fn looks_like_trailer(line: &str) -> bool {
if line.starts_with(char::is_whitespace) || line.is_empty() {
return false;
}
match line.find(": ") {
Some(idx) => {
let key = &line[..idx];
!key.is_empty()
&& key
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}
None => false,
}
}
/// Split a commit message into `(body, trailers)` on the last blank line.
/// The trailers are the maximal run of trailer-shaped lines after the final
/// blank line; if that run is empty or contains a non-trailer line, the whole
/// message is treated as body (no trailer block). Trailing blank lines are
/// stripped from the body; internal blank lines are preserved.
fn split_message(message: &str) -> (String, Vec<String>) {
let lines: Vec<&str> = message.lines().collect();
let last_blank = lines.iter().rposition(|l| l.trim().is_empty());
let tail_start = match last_blank {
Some(idx) => idx + 1,
None => return (body_of(&lines), Vec::new()),
};
let tail = &lines[tail_start..];
if tail.is_empty() || !tail.iter().all(|l| looks_like_trailer(l)) {
return (body_of(&lines), Vec::new());
}
let body = body_of(&lines[..tail_start]);
let trailers = tail.iter().map(|s| s.to_string()).collect();
(body, trailers)
}
/// Join message lines into a body string with trailing blank lines stripped
/// (internal blank lines preserved).
fn body_of(lines: &[&str]) -> String {
let mut end = lines.len();
while end > 0 && lines[end - 1].trim().is_empty() {
end -= 1;
}
lines[..end].join("\n")
}
/// A Newt-owned model attribution trailer: a `Co-authored-by:` line credited
/// to this value's agent account email. The model and harness version in a
/// stale trailer may differ from the current value — matching on the
/// (stable) agent email is what lets us recognize and *replace* it rather
/// than duplicate (requirement 8).
fn is_newt_model_trailer(line: &str, agent_email_tag: &str) -> bool {
line.starts_with("Co-authored-by: ") && line.ends_with(agent_email_tag)
}
/// A Newt-managed operator co-author trailer: a `Co-authored-by:` line credited
/// to the known operator email. Distinct from [`is_newt_model_trailer`] (which
/// matches the agent email) — operator attribution is independent from model
/// attribution (requirement 8). Recognized so a stale operator trailer is
/// dropped + re-rendered on re-finalization (idempotent, no duplicate).
fn is_newt_operator_trailer(line: &str, operator_email_tag: &str) -> bool {
line.starts_with("Co-authored-by: ") && line.ends_with(operator_email_tag)
}
/// A Newt-owned provenance line: the canonical shape
/// `Harness: <harness> v<version> (<rev>) | Model: <model> | Operator: <op>`
/// — matched by its unique ` | Model: ` + ` | Operator: ` markers, NOT merely
/// by the `Harness:` prefix. A user's unrelated `Harness: built with Rust`
/// trailer therefore survives finalization as third-party (requirement 6:
/// tighten Newt-owned `Harness:` detection so unrelated user `Harness:`
/// trailers are preserved). Replaced wholesale on re-finalization so a stale
/// revision/version does not linger (requirement 9).
fn is_newt_provenance(line: &str) -> bool {
line.starts_with("Harness: ") && line.contains(" | Model: ") && line.contains(" | Operator: ")
}
/// The pending multi-contributor set for one not-yet-committed unit of work.
///
/// Ordered (first-contribution order) and deduplicated on the full
/// `(model, harness, email)` identity — the same model through two different
/// harnesses, or the same model+harness under two different configured
/// emails, are distinct contributors. There is no maximum size.
#[derive(Debug, Clone)]
pub struct AttributionLedger {
default_email: String,
default_build: Option<String>,
contributors: Vec<Attribution>,
seen: HashSet<Attribution>,
}
impl AttributionLedger {
/// A fresh, empty ledger. `default_email` is the email
/// [`AttributionLedger::record`] stamps on every entry — resolve it once
/// (ordinarily from [`crate::agent_identity::AgentIdentity::email`]) and
/// reuse the same ledger for the life of the session; construct a new
/// ledger only if the configured attribution email itself changes.
#[must_use]
pub fn new(default_email: impl Into<String>) -> Self {
Self {
default_email: default_email.into(),
// THIS build, not `None`. `record` credits the harness that owns
// the ledger, and that harness is this one — the same source
// [`CommitAttribution::from_runtime`] reads. Defaulting to `None`
// made a forgotten `with_build` silently double-credit the active
// model at commit time (its build set, the ledger's not, so the
// dedup in `finalize_message_with` saw two identities). Correct by
// construction instead: a caller must go out of its way to be
// inconsistent.
default_build: Some(crate::build_info::SOURCE_ID.to_string()),
contributors: Vec::new(),
seen: HashSet::new(),
}
}
/// Pin the harness build revision [`AttributionLedger::record`] stamps on
/// its entries (for newt, [`crate::build_info::SOURCE_ID`]).
///
/// `record` is for the harness that OWNS this ledger, so one default
/// build is right for it — exactly as one default email is. A contributor
/// that ran under a foreign harness carries its own build and its own
/// address, and goes in through [`AttributionLedger::add`].
#[must_use]
pub fn with_build(mut self, build: impl Into<String>) -> Self {
self.default_build = Some(build.into());
self
}
/// Record a material contribution from `model` running under `harness` at
/// `harness_version`, attributed to this ledger's configured default email.
/// `harness_version` is captured at contribution time (ordinarily
/// [`crate::build_info::PACKAGE_VERSION`]) so the contributor stays paired
/// with the harness build that actually ran its work (audit Q9). A no-op if
/// this exact `(model, harness, harness_version, default_email)` identity
/// is already pending — first-contribution order is preserved, not bumped
/// to the end.
pub fn record(
&mut self,
model: impl Into<String>,
harness: impl Into<String>,
harness_version: impl Into<String>,
) {
let mut attribution =
Attribution::new(model, harness, harness_version, self.default_email.clone());
attribution.harness_build = self.default_build.clone();
self.add(attribution);
}
/// Record a fully-specified [`Attribution`] (an explicit email, e.g. for
/// a contributor attributed under a different configured identity than
/// this ledger's default). Deduplicates and preserves order exactly like
/// [`AttributionLedger::record`].
pub fn add(&mut self, attribution: Attribution) {
if self.seen.insert(attribution.clone()) {
self.contributors.push(attribution);
}
}
/// True iff no contributor has been recorded since the last
/// [`AttributionLedger::clear`].
#[must_use]
pub fn is_empty(&self) -> bool {
self.contributors.is_empty()
}
/// The pending contributors, in first-contribution order.
#[must_use]
pub fn contributors(&self) -> &[Attribution] {
&self.contributors
}
/// One `Co-authored-by:` trailer line per pending contributor, in
/// first-contribution order. Empty when the ledger is empty.
#[must_use]
pub fn trailers(&self) -> Vec<String> {
self.contributors.iter().map(Attribution::trailer).collect()
}
/// [`AttributionLedger::trailers`] joined with newlines — the block a
/// commit-message signer appends verbatim. Empty string when the ledger
/// has no pending contributors (callers should treat that as "no
/// attribution to stamp", not as a literal empty trailer line).
#[must_use]
pub fn render(&self) -> String {
self.trailers().join("\n")
}
/// Discard every pending contributor. Call only after a commit built
/// from [`AttributionLedger::render`] actually succeeded — a failed
/// commit attempt must leave the ledger untouched so the same
/// contributors are credited on the next attempt.
pub fn clear(&mut self) {
self.contributors.clear();
self.seen.clear();
}
}
#[cfg(test)]
mod tests {
use super::*;
const DEFAULT_EMAIL: &str = crate::agent_identity::DEFAULT_AGENT_EMAIL;
/// Deterministic harness version for ledger tests — the version is part
/// of the contributor identity now (audit Q9), so tests pin it rather
/// than reading the live `PACKAGE_VERSION` (which would make assertions
/// drift on every release).
const TEST_VER: &str = "0.0.0-test";
/// The build revision `AttributionLedger::record` stamps by default —
/// this harness's own, the same source `CommitAttribution::from_runtime`
/// reads. Referenced rather than hard-coded so the assertions stay true
/// on every build.
const SOURCE_ID: &str = crate::build_info::SOURCE_ID;
/// A foreign harness's own address — the Claude Code row of the harness
/// table. Never newt's.
const ANTHROPIC: &str = "noreply@anthropic.com";
/// Contract test 1: one contributor produces exactly one trailer.
#[test]
fn one_contributor_produces_exactly_one_trailer() {
let mut ledger = AttributionLedger::new(DEFAULT_EMAIL);
ledger.record("GPT-5.6 Sol", "newt-agent", TEST_VER);
assert_eq!(ledger.contributors().len(), 1);
assert_eq!(
ledger.trailers(),
vec![format!(
"Co-authored-by: GPT-5.6 Sol (v{TEST_VER} {SOURCE_ID}) <{DEFAULT_EMAIL}>"
)]
);
}
/// Contract test 2: a model switch, both contributing, produces TWO
/// trailers — not only the later model.
#[test]
fn model_switch_with_both_contributing_produces_two_trailers() {
let mut ledger = AttributionLedger::new(DEFAULT_EMAIL);
ledger.record("Model A", "newt-agent", TEST_VER);
ledger.record("Model B", "newt-agent", TEST_VER);
assert_eq!(ledger.contributors().len(), 2);
assert_eq!(
ledger.trailers(),
vec![
format!("Co-authored-by: Model A (v{TEST_VER} {SOURCE_ID}) <{DEFAULT_EMAIL}>"),
format!("Co-authored-by: Model B (v{TEST_VER} {SOURCE_ID}) <{DEFAULT_EMAIL}>"),
],
"the earlier contributor must not be discarded by the later one"
);
}
/// Contract test 3: a harness switch (same model) produces TWO trailers
/// — the same model through two harnesses is two distinct identities.
#[test]
fn harness_switch_with_same_model_produces_two_trailers() {
let mut ledger = AttributionLedger::new(DEFAULT_EMAIL);
ledger.record("Model A", "newt-agent", TEST_VER);
ledger.record("Model A", "Codex", TEST_VER);
assert_eq!(ledger.contributors().len(), 2);
assert_eq!(
ledger.trailers(),
vec![
format!("Co-authored-by: Model A (v{TEST_VER} {SOURCE_ID}) <{DEFAULT_EMAIL}>"),
format!(
"Co-authored-by: Model A (Codex v{TEST_VER} {SOURCE_ID}) <{DEFAULT_EMAIL}>"
),
]
);
}
/// Contract test 4: repeated identical contribution produces ONE
/// trailer, not three.
#[test]
fn duplicate_contribution_produces_one_trailer() {
let mut ledger = AttributionLedger::new(DEFAULT_EMAIL);
ledger.record("Model A", "newt-agent", TEST_VER);
ledger.record("Model A", "newt-agent", TEST_VER);
ledger.record("Model A", "newt-agent", TEST_VER);
assert_eq!(ledger.contributors().len(), 1);
}
/// Contract test 4b: the same model+harness under TWO different versions
/// is TWO contributors — version is part of the identity (audit Q9), so
/// a harness bump mid-session credits the work under the build that
/// actually ran it rather than silently merging it into the old one.
#[test]
fn version_switch_with_same_model_and_harness_produces_two_trailers() {
let mut ledger = AttributionLedger::new(DEFAULT_EMAIL);
ledger.record("Model A", "newt-agent", "0.7.6");
ledger.record("Model A", "newt-agent", "0.8.0");
assert_eq!(ledger.contributors().len(), 2);
assert_eq!(
ledger.trailers(),
vec![
format!("Co-authored-by: Model A (v0.7.6 {SOURCE_ID}) <{DEFAULT_EMAIL}>"),
format!("Co-authored-by: Model A (v0.8.0 {SOURCE_ID}) <{DEFAULT_EMAIL}>"),
]
);
}
// ---- the qualifier: what the address does not already say ----
/// The harness name is REDUNDANT against an address that already names
/// it, so it is dropped: `<…+newt-agent@…>` says `newt-agent` once, and
/// the qualifier carries only the build that address cannot tell you.
#[test]
fn newt_harness_name_is_not_repeated_against_its_own_address() {
let a = Attribution::new("m", "newt-agent", "0.8.0", DEFAULT_EMAIL).with_build("abc123");
assert_eq!(
a.trailer(),
format!("Co-authored-by: m (v0.8.0 abc123) <{DEFAULT_EMAIL}>")
);
assert!(
!a.trailer().contains("(newt-agent"),
"the account name appears once, in the address: {}",
a.trailer()
);
}
/// Only the part the address does NOT carry survives: `newt-agent crew`
/// reduces to `crew`, so a crew-landed commit stays distinguishable from
/// a session one — the crew marker is the whole reason that harness
/// string exists (newt-cli's `crew_coauthor_trailer`).
#[test]
fn crew_keeps_the_half_of_the_harness_the_address_omits() {
let a =
Attribution::new("m", "newt-agent crew", "0.8.0", DEFAULT_EMAIL).with_build("abc123");
assert_eq!(
a.trailer(),
format!("Co-authored-by: m (crew v0.8.0 abc123) <{DEFAULT_EMAIL}>")
);
}
/// A FOREIGN harness keeps its full name, because its address does not
/// spell it out. This is what stops the omission from collapsing two
/// genuinely different contributors into one identical line — the
/// `Model A (newt-agent)` vs `Model A (Codex)` contract.
#[test]
fn a_foreign_harness_keeps_its_name_so_contributors_stay_distinct() {
let newt = Attribution::new("Model A", "newt-agent", "0.8.0", DEFAULT_EMAIL);
let codex = Attribution::new("Model A", "Codex CLI", "0.8.0", "codex@openai.com");
assert_eq!(
codex.trailer(),
"Co-authored-by: Model A (Codex CLI v0.8.0) <codex@openai.com>"
);
assert_ne!(
newt.trailer(),
codex.trailer(),
"same model, two harnesses — two visibly distinct trailers"
);
}
/// A generic provider mailbox names a PROVIDER, not an account, so it
/// never licenses dropping the harness name. `codex@openai.com` must not
/// strip `Codex` off `Codex CLI`.
#[test]
fn a_non_account_address_never_strips_the_harness_name() {
let a = Attribution::new("m", "Codex CLI", "1.0", "codex@openai.com");
assert!(a.trailer().contains("(Codex CLI v1.0)"), "{}", a.trailer());
let anthropic = Attribution::new("Claude Opus 5", "Claude Code", "2.1.239", ANTHROPIC);
assert_eq!(
anthropic.trailer(),
format!("Co-authored-by: Claude Opus 5 (Claude Code v2.1.239) <{ANTHROPIC}>")
);
}
/// A harness that merely STARTS WITH the account name is not the account:
/// `newt-agentic` keeps its full name, because the space guard means only
/// `newt-agent` itself and `newt-agent <suffix>` are treated as the
/// account speaking.
#[test]
fn a_lookalike_harness_name_is_not_treated_as_the_account() {
let a = Attribution::new("m", "newt-agentic", "0.8.0", DEFAULT_EMAIL);
assert!(
a.trailer().contains("(newt-agentic v0.8.0)"),
"{}",
a.trailer()
);
}
/// The build revision is part of the IDENTITY, not just the rendering:
/// the same model+harness+version from two different builds is two
/// contributors, because what ran the work differs.
#[test]
fn a_build_switch_with_everything_else_equal_produces_two_trailers() {
let mut ledger = AttributionLedger::new(DEFAULT_EMAIL);
ledger.add(
Attribution::new("Model A", "newt-agent", "0.8.0", DEFAULT_EMAIL)
.with_build("aaaa1111"),
);
ledger.add(
Attribution::new("Model A", "newt-agent", "0.8.0", DEFAULT_EMAIL)
.with_build("bbbb2222"),
);
assert_eq!(ledger.contributors().len(), 2);
assert_eq!(
ledger.trailers(),
vec![
format!("Co-authored-by: Model A (v0.8.0 aaaa1111) <{DEFAULT_EMAIL}>"),
format!("Co-authored-by: Model A (v0.8.0 bbbb2222) <{DEFAULT_EMAIL}>"),
]
);
}
/// A dirty build is credited as dirty — an honest signal that the harness
/// that ran the work is not any committed revision.
#[test]
fn a_dirty_build_says_so_in_the_trailer() {
let a = Attribution::new("m", "newt-agent", "0.8.0", DEFAULT_EMAIL)
.with_build("ba56944bd262-dirty");
assert!(a.trailer().ends_with(&format!("<{DEFAULT_EMAIL}>")));
assert!(
a.trailer().contains("(v0.8.0 ba56944bd262-dirty)"),
"{}",
a.trailer()
);
}
/// `record` credits the harness that OWNS the ledger, so it stamps THIS
/// build by default — the same source `CommitAttribution::from_runtime`
/// reads. Without that default a caller who forgot `with_build` would
/// silently double-credit the active model at commit time.
#[test]
fn record_stamps_this_build_so_the_active_model_dedupes() {
let mut ledger = AttributionLedger::new(DEFAULT_EMAIL);
ledger.record("m", "newt-agent", "0.8.0");
assert_eq!(
ledger.contributors()[0].harness_build.as_deref(),
Some(crate::build_info::SOURCE_ID)
);
}
/// The active-at-commit model and a ledger contributor render through the
/// SAME code path, so the two can never drift into different shapes.
#[test]
fn the_active_model_renders_exactly_like_a_ledger_contributor() {
let ca = sample_ca();
let same = Attribution::new(
&ca.model,
&ca.harness_name,
&ca.harness_version,
&ca.agent_email,
)
.with_build(&ca.harness_build_revision);
assert_eq!(ca.model_trailer(), same.trailer());
}
// ---- `/byline`: the preview cannot lie about the commit ----
/// The preview is EXACTLY the trailer block the commit gets — same lines,
/// same order — because it runs the same finalizer. Pinned against a real
/// finalized message rather than against a hand-written expectation, so
/// the two cannot drift.
#[test]
fn byline_is_exactly_what_the_commit_would_receive() {
let ca = CommitAttribution {
operator_email: Some("shawn@example.com".to_string()),
..sample_ca()
};
let mut ledger = AttributionLedger::new(DEFAULT_EMAIL);
ledger.record("Model A", "newt-agent", "0.7.6");
let preview = ca.byline(ledger.contributors());
let committed: Vec<String> = ca
.finalize_message_with("fix the parser", ledger.contributors())
.lines()
.filter(|l| !l.trim().is_empty() && *l != "fix the parser")
.map(str::to_string)
.collect();
assert_eq!(preview, committed);
}
/// The preview credits the human operator and every accumulated model,
/// not just the active one — the whole point of asking before committing.
#[test]
fn byline_shows_operator_contributors_and_provenance() {
let ca = CommitAttribution {
operator_email: Some("shawn@example.com".to_string()),
..sample_ca()
};
let mut ledger = AttributionLedger::new(DEFAULT_EMAIL);
ledger.record("Model A", "newt-agent", "0.7.6");
let out = ca.byline(ledger.contributors());
assert_eq!(
out,
vec![
format!("Co-authored-by: Model A (v0.7.6 {SOURCE_ID}) <{DEFAULT_EMAIL}>"),
format!(
"Co-authored-by: glm-5.2 (v0.8.0 ba56944bd262-dirty) <{DEFAULT_EMAIL}>"
),
"Co-authored-by: shawn <shawn@example.com>".to_string(),
"Harness: newt-agent v0.8.0 (ba56944bd262-dirty) | Model: glm-5.2 | Operator: shawn"
.to_string(),
]
);
}
/// With no operator email known, the preview omits the operator by-line
/// rather than inventing an address — the same never-invent rule the
/// commit path obeys.
#[test]
fn byline_omits_the_operator_when_no_real_email_is_known() {
let out = sample_ca().byline(&[]);
assert!(
!out.iter().any(|l| l.contains("shawn@")),
"no operator email is manufactured: {out:?}"
);
assert_eq!(out.len(), 2, "active model + provenance only: {out:?}");
}
/// Contract test 5: many contributors (10+) — none truncated, no hidden
/// cap.
#[test]
fn many_contributors_are_not_truncated() {
let mut ledger = AttributionLedger::new(DEFAULT_EMAIL);
for i in 0..25 {
ledger.record(format!("Model-{i}"), format!("Harness-{i}"), TEST_VER);
}
assert_eq!(ledger.contributors().len(), 25);
assert_eq!(ledger.trailers().len(), 25);
// First-contribution order preserved end to end.
assert!(ledger.trailers()[0].contains("Model-0"));
assert!(ledger.trailers()[24].contains("Model-24"));
}
/// Contract test 6: with no explicit email configuration, every
/// generated attribution uses the default Newt Agent noreply address.
#[test]
fn default_email_is_the_newt_agent_noreply_address() {
let mut ledger =
AttributionLedger::new(crate::agent_identity::AgentIdentity::default().email);
ledger.record("Model A", "newt-agent", TEST_VER);
assert!(ledger.trailers()[0].ends_with("<309460085+newt-agent@users.noreply.github.com>"));
}
/// Contract test 7: an explicitly configured attribution email still
/// works — no provider-specific email is required.
#[test]
fn configured_email_override_is_used_for_every_contributor() {
let mut ledger = AttributionLedger::new("custom-agent@example.com");
ledger.record("Model A", "newt-agent", TEST_VER);
ledger.record("Model B", "Codex", TEST_VER);
for trailer in ledger.trailers() {
assert!(trailer.ends_with("<custom-agent@example.com>"), "{trailer}");
}
}
/// Contract test 8: after a successful commit, pending contributors are
/// cleared.
#[test]
fn clear_empties_the_ledger_for_the_next_commit() {
let mut ledger = AttributionLedger::new(DEFAULT_EMAIL);
ledger.record("Model A", "newt-agent", TEST_VER);
assert!(!ledger.is_empty());
ledger.clear();
assert!(ledger.is_empty());
assert!(ledger.trailers().is_empty());
assert_eq!(ledger.render(), "");
}
/// Contract test 9: on a failed commit, pending contributors remain —
/// callers must not clear before a commit is known to have succeeded.
#[test]
fn failed_commit_leaves_pending_contributors_untouched() {
let mut ledger = AttributionLedger::new(DEFAULT_EMAIL);
ledger.record("Model A", "newt-agent", TEST_VER);
// Simulated commit failure: the caller simply never calls `clear`.
let commit_result: Result<(), &str> = Err("commit rejected");
if commit_result.is_ok() {
ledger.clear();
}
assert_eq!(ledger.contributors().len(), 1);
}
/// A harness switch under an otherwise-identical model+email is not
/// silently merged with a same-named different-harness contributor from
/// a DIFFERENT default email either — full triple identity.
#[test]
fn full_triple_identity_distinguishes_same_model_and_harness_different_email() {
let mut ledger = AttributionLedger::new(DEFAULT_EMAIL);
ledger.record("Model A", "newt-agent", TEST_VER);
ledger.add(Attribution::new(
"Model A",
"newt-agent",
TEST_VER,
"someone-else@example.com",
));
assert_eq!(
ledger.contributors().len(),
2,
"a different email is a different provenance identity"
);
}
#[test]
fn render_joins_trailers_with_newlines() {
let mut ledger = AttributionLedger::new(DEFAULT_EMAIL);
ledger.record("Model A", "newt-agent", TEST_VER);
ledger.record("Model B", "Codex", TEST_VER);
let rendered = ledger.render();
let lines: Vec<&str> = rendered.lines().collect();
assert_eq!(lines.len(), 2);
assert!(lines[0].starts_with("Co-authored-by: Model A"));
assert!(lines[1].starts_with("Co-authored-by: Model B"));
}
// ---- CommitAttribution: constructing the value from runtime state ----
use super::CommitAttribution;
/// Every field of `from_runtime` is sourced from the existing
/// authoritative runtime/compile-time state, not invented: harness fields
/// mirror `build_info`, the agent email is the caller-passed canonical
/// noreply address, and the model is the live value the caller threaded
/// in. Comparing against the same source functions (not hard-coded
/// literals) keeps this independent of the build environment.
#[test]
fn from_runtime_sources_every_field_from_existing_state() {
let ca = CommitAttribution::from_runtime("ornith-1.0-35b", None, DEFAULT_EMAIL);
assert_eq!(ca.model, "ornith-1.0-35b");
assert_eq!(ca.harness_name, crate::build_info::harness_name());
assert_eq!(ca.harness_version, crate::build_info::PACKAGE_VERSION);
assert_eq!(ca.harness_build_revision, crate::build_info::SOURCE_ID);
assert_eq!(ca.agent_email, DEFAULT_EMAIL);
assert!(ca.operator_name.is_none());
assert!(
ca.operator_email.is_none(),
"no operator-email source today"
);
}
/// Harness name + version + build revision come from `build_info`
/// verbatim — no duplicate constants for version/name/revision state
/// (decision 12). The version is a prefix of the build-revision-bearing
/// version string the footer already uses, so they cannot drift.
#[test]
fn harness_fields_reuse_build_info_with_no_duplicate_constants() {
let ca = CommitAttribution::from_runtime("m", None, DEFAULT_EMAIL);
// PACKAGE_VERSION is a compile-time const from CARGO_PKG_VERSION.
assert_eq!(ca.harness_version, env!("CARGO_PKG_VERSION"));
// SOURCE_ID is the git commit (+ -dirty); it must start with the
// captured commit, proving revision + dirty-state reuse (decision 6).
assert!(
ca.harness_build_revision
.starts_with(crate::build_info::GIT_COMMIT),
"build revision must carry the captured git commit"
);
}
/// A `/model` switch between two commits is reflected when constructing a
/// FRESH value (decision 14): the second `from_runtime` call sees the
/// *current* model, not one cached at session startup. Only `model`
/// differs; harness provenance is stable across the two constructions.
#[test]
fn fresh_construction_reflects_a_model_switch() {
let before = CommitAttribution::from_runtime("model-a", None, DEFAULT_EMAIL);
// Simulate the operator running `/model model-b` between commits.
let after = CommitAttribution::from_runtime("model-b", None, DEFAULT_EMAIL);
assert_ne!(before.model, after.model, "the switch must be visible");
assert_eq!(after.model, "model-b");
// Harness provenance is build-derived, not model-derived: unchanged.
assert_eq!(before.harness_name, after.harness_name);
assert_eq!(before.harness_version, after.harness_version);
assert_eq!(before.harness_build_revision, after.harness_build_revision);
assert_eq!(before.agent_email, after.agent_email);
}
/// The active model comes from the live resolved source threaded into the
/// constructor — never from model prompt/system text (decision 11). The
/// type carries no prompt field and is independent of the prompt pipeline.
#[test]
fn model_is_a_runtime_parameter_independent_of_prompt_text() {
// Two commits under the same model but with arbitrary prompt text
// the type never sees — the attribution is identical, proving the
// type does not depend on prompt content.
let a = CommitAttribution::from_runtime("shared-model", None, DEFAULT_EMAIL);
let b = CommitAttribution::from_runtime("shared-model", None, DEFAULT_EMAIL);
assert_eq!(a, b);
}
/// `from_identity` reuses a resolved `AgentIdentity`: the agent email and
/// the configured operator name flow through, and the default identity
/// yields the canonical Newt Agent noreply address (decision 7) with no
/// operator (decision 9: explicit `None`, never an invented name).
#[test]
fn from_identity_reuses_resolved_agent_identity() {
let id = crate::agent_identity::AgentIdentity::default();
let ca = CommitAttribution::from_identity("ornith", &id);
assert_eq!(
ca.agent_email,
crate::agent_identity::DEFAULT_AGENT_EMAIL,
"default identity → canonical newt-agent noreply"
);
assert!(ca.operator_name.is_none());
assert!(ca.operator_email.is_none());
// Harness fields are still sourced from build_info, not the identity.
assert_eq!(ca.harness_name, crate::build_info::harness_name());
}
/// A configured operator name flows through `from_identity`; a configured
/// agent-email override is used verbatim (decision 7: reuse the canonical
/// email via the identity, overrideable). Construction stays tool-less —
/// no `git config` subprocess is spawned (decision 10).
#[test]
fn from_identity_carries_configured_operator_and_email_override() {
let id = crate::agent_identity::AgentIdentity {
operator: Some("shawn".to_string()),
email: "custom-agent@example.com".to_string(),
..Default::default()
};
let ca = CommitAttribution::from_identity("m", &id);
assert_eq!(ca.operator_name.as_deref(), Some("shawn"));
assert_eq!(ca.agent_email, "custom-agent@example.com");
// operator_email stays explicitly None — never invented.
assert!(ca.operator_email.is_none());
}
// ---- finalize_message: the deterministic commit-message finalizer ----
/// A fixed typed value the finalizer tests build against. Every field is
/// explicit so the assertions are independent of the real build
/// environment (no real git revision / package version in the test
/// expectations — those are *rendered from the value*, proving
/// requirements 1, 2, 3, 4).
fn sample_ca() -> CommitAttribution {
CommitAttribution {
model: "glm-5.2".to_string(),
harness_name: "newt-agent".to_string(),
harness_version: "0.8.0".to_string(),
harness_build_revision: "ba56944bd262-dirty".to_string(),
operator_name: Some("shawn".to_string()),
operator_email: None,
agent_email: DEFAULT_EMAIL.to_string(),
contributors: Vec::new(),
}
}
/// Requirement 1 + 3 + 4: the model trailer renders model + harness +
/// harness version all from the SAME typed value, with no hard-coded
/// current-model or current-package-version constant.
#[test]
fn model_trailer_renders_model_harness_version_from_the_value() {
let ca = sample_ca();
assert_eq!(
ca.model_trailer(),
format!("Co-authored-by: glm-5.2 (v0.8.0 ba56944bd262-dirty) <{DEFAULT_EMAIL}>")
);
}
/// Requirement 2: the provenance line is rendered from the same value —
/// harness, version, revision, model, and operator all flow from the one
/// typed value. No operator email appears (requirement 12).
#[test]
fn provenance_line_renders_from_the_same_value() {
let ca = sample_ca();
assert_eq!(
ca.provenance_line(),
"Harness: newt-agent v0.8.0 (ba56944bd262-dirty) | Model: glm-5.2 | Operator: shawn"
);
}
/// Requirement 12: when no operator name is known, the provenance line
/// uses the deterministic `"unknown"` sentinel — and never an invented
/// operator email.
#[test]
fn provenance_line_uses_unknown_when_no_operator_and_never_an_email() {
let ca = CommitAttribution {
operator_name: None,
..sample_ca()
};
assert_eq!(
ca.provenance_line(),
"Harness: newt-agent v0.8.0 (ba56944bd262-dirty) | Model: glm-5.2 | Operator: unknown"
);
assert!(
!ca.provenance_line().contains('@'),
"no operator email is ever manufactured"
);
}
/// Requirement 5: arbitrary user subject + body text is preserved
/// verbatim, and a blank line separates body from trailers (req 11).
#[test]
fn finalize_preserves_arbitrary_subject_and_body() {
let ca = sample_ca();
let input = "fix(parser): handle trailing whitespace\n\nBody para one.\n\nBody para two with `code`.\n";
let out = ca.finalize_message(input);
assert!(
out.starts_with("fix(parser): handle trailing whitespace\n\nBody para one.\n\nBody para two with `code`.\n\n"),
"subject + body must be preserved verbatim, then a blank line"
);
// The canonical trailers are appended after the body.
assert!(out.contains(&ca.model_trailer()));
assert!(out.contains(&ca.provenance_line()));
}
/// Requirement 6: a legitimate third-party `Co-authored-by:` trailer (a
/// real person, different email) is preserved through finalization.
#[test]
fn finalize_preserves_third_party_co_authored_by() {
let ca = sample_ca();
let input = "feat: thing\n\nBody.\n\nCo-authored-by: Alice <alice@example.com>\nSigned-off-by: Bob <bob@example.com>\n";
let out = ca.finalize_message(input);
assert!(
out.contains("Co-authored-by: Alice <alice@example.com>"),
"third-party Co-authored-by must be preserved"
);
assert!(
out.contains("Signed-off-by: Bob <bob@example.com>"),
"other third-party trailers must be preserved"
);
}
/// Requirement 8: a STALE Newt-owned model attribution trailer (old model
/// / old harness version, but same agent email) is REPLACED, not
/// duplicated.
#[test]
fn finalize_replaces_stale_newt_owned_model_trailer() {
let ca = sample_ca();
let input = format!(
"feat: thing\n\nBody.\n\nCo-authored-by: old-model (newt-agent v0.7.5) <{DEFAULT_EMAIL}>\n"
);
let out = ca.finalize_message(&input);
assert!(
!out.contains("old-model"),
"stale model trailer must be gone"
);
assert!(
!out.contains("v0.7.5"),
"stale harness version must be gone"
);
// Exactly one model trailer in the output — the fresh one.
let model_trailers: Vec<&str> = out
.lines()
.filter(|l| {
l.starts_with("Co-authored-by: ") && l.ends_with(&format!("<{DEFAULT_EMAIL}>"))
})
.collect();
assert_eq!(model_trailers.len(), 1, "no duplicate model trailer");
assert_eq!(model_trailers[0], ca.model_trailer());
}
/// Requirement 9: a STALE Newt-owned provenance line (old revision) is
/// replaced, not duplicated.
#[test]
fn finalize_replaces_stale_newt_owned_provenance() {
let ca = sample_ca();
let input = "feat: thing\n\nBody.\n\nHarness: newt-agent v0.7.5 (deadbeef) | Model: old | Operator: old\n";
let out = ca.finalize_message(input);
assert!(
!out.contains("deadbeef"),
"stale provenance revision must be gone"
);
let provenance: Vec<&str> = out.lines().filter(|l| l.starts_with("Harness: ")).collect();
assert_eq!(provenance.len(), 1, "exactly one provenance line");
assert_eq!(provenance[0], ca.provenance_line());
}
/// Requirement 10: repeated finalization is idempotent — running the
/// finalizer on its own output yields byte-identical bytes.
#[test]
fn finalize_is_idempotent() {
let ca = sample_ca();
let input = "feat: thing\n\nBody.\n\nCo-authored-by: Alice <alice@example.com>\n";
let once = ca.finalize_message(input);
let twice = ca.finalize_message(&once);
assert_eq!(once, twice, "re-finalization must be a no-op");
let thrice = ca.finalize_message(&twice);
assert_eq!(twice, thrice, "idempotent across repeated calls");
}
/// Requirement 10 (negative): idempotence survives a model switch
/// between finalizations only if the value is the same; with a DIFFERENT
/// value the stale trailer is replaced — proving the idempotence above is
/// genuine recognition, not "output already matched by luck".
#[test]
fn a_model_switch_replaces_the_stale_trailer() {
let before = sample_ca();
let msg = "feat: thing\n\nBody.\n";
let once = before.finalize_message(msg);
let after = CommitAttribution {
model: "glm-5.3".to_string(),
harness_version: "0.8.1".to_string(),
harness_build_revision: "cef01234-clean".to_string(),
..sample_ca()
};
let twice = after.finalize_message(&once);
assert!(twice.contains("glm-5.3 (v0.8.1 cef01234-clean)"));
assert!(twice.contains("Harness: newt-agent v0.8.1 (cef01234-clean)"));
assert!(
!twice.contains("glm-5.2 (v0.8.0 ba56944bd262-dirty)"),
"old model trailer replaced"
);
}
/// Requirement 11: the blank line before the trailer block is present,
/// and there is exactly one (not two, not zero).
#[test]
fn finalize_emits_exactly_one_blank_line_before_trailers() {
let ca = sample_ca();
let out = ca.finalize_message("feat: thing\n\nBody.\n");
// The body ends, then exactly one blank line, then the trailer block.
let body_end = out.find("\n\nCo-authored-by: ").unwrap();
let _ = body_end; // present
// No doubled blank line right before the trailer block.
assert!(
!out.contains("\n\n\nCo-authored-by: "),
"exactly one blank line before trailers"
);
// The trailer block is the last paragraph: a line after the trailers
// would break git's trailer parsing.
let mut lines = out.lines();
let mut seen_trailer = false;
for l in lines.by_ref() {
if l.starts_with("Co-authored-by: ") || l.starts_with("Harness: ") {
seen_trailer = true;
} else if seen_trailer {
panic!("non-trailer line after trailer block: {l:?}");
}
}
}
/// Requirement 13: rendering is deterministic — the same value + input
/// always produce byte-identical output.
#[test]
fn finalize_is_deterministic() {
let ca = sample_ca();
let input = "feat: thing\n\nBody.\n\nCo-authored-by: Alice <alice@example.com>\n";
let a = ca.finalize_message(input);
let b = ca.finalize_message(input);
assert_eq!(a, b);
}
/// Representative before/after, asserted as a single golden snapshot so a
/// future change to the format is loudly visible. This is the
/// "representative before/after" deliverable expressed as a test.
#[test]
fn finalize_before_after_snapshot() {
let ca = sample_ca();
let before = "feat(attribution): finalizer\n\nDrives the commit.\n\nCo-authored-by: glm-4.7 (v0.7.6 aabbccdd) <309460085+newt-agent@users.noreply.github.com>\nHarness: newt-agent v0.7.6 (aabbccdd) | Model: glm-4.7 | Operator: shawn\nCo-authored-by: Reviewer <reviewer@example.com>\n";
let after = ca.finalize_message(before);
let expected = format!(
"feat(attribution): finalizer\n\nDrives the commit.\n\n\
Co-authored-by: Reviewer <reviewer@example.com>\n\
Co-authored-by: glm-5.2 (v0.8.0 ba56944bd262-dirty) <{DEFAULT_EMAIL}>\n\
Harness: newt-agent v0.8.0 (ba56944bd262-dirty) | Model: glm-5.2 | Operator: shawn\n"
);
assert_eq!(after, expected);
}
// ---- semantic B: accumulated multi-contributor finalization ----
//
// `finalize_message_with` merges an AttributionLedger's accumulated
// contributors with the active-at-commit model, so a `/model` switch
// mid-session credits BOTH models on the one commit — the contract —
// rather than only the model driving the commit (semantic A, the floor).
/// Two accumulated contributors + the active model = THREE trailers, in
/// first-contribution order with the active model appended. The
/// provenance line stays single (one harness build drives the commit).
#[test]
fn finalize_with_ledger_credits_every_accumulated_contributor() {
let ca = sample_ca(); // active model = glm-5.2 under newt-agent v0.8.0
let mut ledger = AttributionLedger::new(DEFAULT_EMAIL);
ledger.record("Model A", "newt-agent", "0.7.6");
ledger.record("Model B", "Codex", "0.8.0");
let out = ca.finalize_message_with("fix the parser", ledger.contributors());
let lines: Vec<&str> = out.lines().collect();
// body, blank, then trailers: Model A, Model B, active glm-5.2, provenance.
assert_eq!(lines[0], "fix the parser");
assert_eq!(lines[1], "");
assert_eq!(
lines[2],
format!("Co-authored-by: Model A (v0.7.6 {SOURCE_ID}) <{DEFAULT_EMAIL}>")
);
assert_eq!(
lines[3],
format!("Co-authored-by: Model B (Codex v0.8.0 {SOURCE_ID}) <{DEFAULT_EMAIL}>")
);
assert_eq!(
lines[4],
format!("Co-authored-by: glm-5.2 (v0.8.0 ba56944bd262-dirty) <{DEFAULT_EMAIL}>")
);
assert!(lines[5].starts_with("Harness: "));
assert_eq!(lines.len(), 6);
}
/// The active model is merged and DEDUPED against the ledger: if it
/// already contributed (same model+harness+version+email), it is not
/// stamped twice. This is the `/model` switch back to a previous model —
/// credit it once.
#[test]
fn finalize_with_ledger_dedupes_active_model_already_present() {
// The build revision is part of the identity, so the active model and
// the ledger entry must agree on it to be ONE contributor. They do in
// production — `AttributionLedger::new` and
// `CommitAttribution::from_runtime` both read `build_info::SOURCE_ID`
// — so the fixture reads it too rather than pinning a literal that
// would make this dedupe pass for the wrong reason.
let ca = CommitAttribution {
harness_build_revision: SOURCE_ID.to_string(),
..sample_ca()
};
let mut ledger = AttributionLedger::new(DEFAULT_EMAIL);
ledger.record("glm-5.2", "newt-agent", "0.8.0"); // identical to active
ledger.record("Model A", "newt-agent", "0.7.6");
let out = ca.finalize_message_with("fix the parser", ledger.contributors());
let coauth: Vec<&str> = out
.lines()
.filter(|l| l.starts_with("Co-authored-by: "))
.collect();
assert_eq!(
coauth.len(),
2,
"active model dedupes against the ledger — no double trailer"
);
// First-contribution order: Model A was NOT in the ledger before the
// active identity, so the active identity (recorded first into the
// ledger) leads, then Model A.
assert!(coauth[0].contains("glm-5.2"));
assert!(coauth[1].contains("Model A"));
}
/// An empty contributor set is the floor: `finalize_message_with(&[])`
/// is byte-identical to `finalize_message` — the single active-model
/// trailer + provenance. B never regresses the A floor.
#[test]
fn finalize_with_empty_ledger_matches_the_single_model_floor() {
let ca = sample_ca();
let msg = "feat(x): y\n\nbody text\n";
assert_eq!(ca.finalize_message(msg), ca.finalize_message_with(msg, &[]));
}
/// Re-finalization is idempotent under B: running `finalize_message_with`
/// on its own output with the SAME contributors yields the same bytes —
/// the freshly-rendered Newt trailers are recognized as Newt-owned
/// (agent-email-tagged) on the next pass and replaced, not duplicated.
#[test]
fn finalize_with_ledger_is_idempotent() {
let ca = sample_ca();
let mut ledger = AttributionLedger::new(DEFAULT_EMAIL);
ledger.record("Model A", "newt-agent", "0.7.6");
let contributors = ledger.contributors().to_vec();
let once = ca.finalize_message_with("fix the parser\n\nbody", &contributors);
let twice = ca.finalize_message_with(&once, &contributors);
assert_eq!(
once, twice,
"re-finalization must not duplicate contributors"
);
}
/// Stale multi-contributor Newt trailers from a prior run are ALL
/// replaced, not just one: a previous B finalization may have left
/// several `Co-authored-by:` lines tagged with the agent email, and
/// re-finalizing with a fresh contributor set drops every one rather
/// than appending duplicates alongside them.
#[test]
fn finalize_with_ledger_replaces_every_stale_newt_model_trailer() {
let ca = sample_ca();
// A prior run left TWO stale Newt model trailers (both agent-email-
// tagged) plus a third-party one.
let stale = format!(
"fix the parser\n\n\
Co-authored-by: Old Model (newt-agent v0.1.0) <{DEFAULT_EMAIL}>\n\
Co-authored-by: Older Model (newt-agent v0.0.1) <{DEFAULT_EMAIL}>\n\
Co-authored-by: Reviewer <reviewer@example.com>\n\
Harness: newt-agent v0.1.0 (deadbeef) | Model: old | Operator: shawn\n"
);
let mut ledger = AttributionLedger::new(DEFAULT_EMAIL);
ledger.record("Model A", "newt-agent", "0.7.6");
let out = ca.finalize_message_with(&stale, ledger.contributors());
let coauth: Vec<&str> = out
.lines()
.filter(|l| l.starts_with("Co-authored-by: "))
.collect();
// Third-party Reviewer preserved; stale Newt ones gone; fresh set =
// Model A + active glm-5.2 = 3 total.
assert_eq!(coauth.len(), 3);
assert!(coauth.iter().any(|l| l.contains("Reviewer")));
assert!(
!coauth
.iter()
.any(|l| l.contains("Old Model") || l.contains("Older Model")),
"stale Newt trailers must all be dropped"
);
// Stale provenance replaced with the fresh single line.
assert!(
out.contains("Harness: newt-agent v0.8.0 (ba56944bd262-dirty)"),
"stale provenance replaced"
);
assert!(!out.contains("deadbeef"));
}
/// Representative B before/after as a golden snapshot: a model-switch
/// session (Model A → Model B) committing under Model B yields TWO
/// `Co-authored-by:` trailers — the contract's "ADD a contributor, never
/// discard" — plus the single Harness provenance, with third-party
/// trailers preserved.
#[test]
fn finalize_with_ledger_before_after_snapshot() {
let ca = sample_ca(); // active at commit = glm-5.2 / newt-agent v0.8.0
let mut ledger = AttributionLedger::new(DEFAULT_EMAIL);
// Model A did earlier work; the active glm-5.2 drives the commit.
ledger.record("Model A", "newt-agent", "0.7.6");
let before = "fix the parser";
let after = ca.finalize_message_with(before, ledger.contributors());
let expected = format!(
"fix the parser\n\n\
Co-authored-by: Model A (v0.7.6 {SOURCE_ID}) <{DEFAULT_EMAIL}>\n\
Co-authored-by: glm-5.2 (v0.8.0 ba56944bd262-dirty) <{DEFAULT_EMAIL}>\n\
Harness: newt-agent v0.8.0 (ba56944bd262-dirty) | Model: glm-5.2 | Operator: shawn\n"
);
assert_eq!(after, expected);
}
// ---- operator attribution (requirement 2/3/4/5/6/8) ----
/// A known real operator email emits an operator `Co-authored-by:` trailer,
/// credited to the OPERATOR email (not the agent email), separate from the
/// model contributor trailers (requirement 3 + 8: independent from model
/// attribution). The operator name is preserved in the trailer.
#[test]
fn operator_with_known_email_emits_operator_co_author_trailer() {
let ca = CommitAttribution {
operator_email: Some("shawn@example.com".to_string()),
..sample_ca()
};
let out = ca.finalize_message("fix the parser\n\nbody");
assert!(
out.contains("Co-authored-by: shawn <shawn@example.com>"),
"operator trailer emitted with the operator's own email + name"
);
// The model trailer is still present and credited to the agent email.
assert!(out.contains(&ca.model_trailer()));
// Operator trailer is credited to the operator email, NOT the agent one.
assert_ne!(ca.operator_trailer().unwrap(), ca.model_trailer());
}
/// Requirement 4: when NO operator email is known, NO operator trailer is
/// emitted — never invented. The model trailer + provenance still render.
#[test]
fn operator_with_missing_email_emits_no_operator_trailer() {
let ca = sample_ca(); // operator_email: None
assert!(ca.operator_trailer().is_none());
let out = ca.finalize_message("fix the parser\n\nbody");
assert!(
!out.contains("@example.com"),
"no operator email is ever manufactured"
);
// Model attribution + provenance still present.
assert!(out.contains(&ca.model_trailer()));
assert!(out.contains(&ca.provenance_line()));
}
/// Requirement: avoid emitting an operator co-author identical to the
/// primary Git author. The commit author is the `agent_email`; when the
/// operator's email equals it, the operator IS the primary author and no
/// duplicate operator trailer is emitted.
#[test]
fn operator_who_is_the_primary_author_gets_no_duplicate_trailer() {
let ca = CommitAttribution {
operator_email: Some(DEFAULT_EMAIL.to_string()), // == agent_email
..sample_ca()
};
let out = ca.finalize_message("fix the parser\n\nbody");
let coauth: Vec<&str> = out
.lines()
.filter(|l| l.starts_with("Co-authored-by: "))
.collect();
// Exactly one Co-authored-by: the model trailer (credited to the agent
// email). No second one for the operator, who is already the author.
assert_eq!(
coauth.len(),
1,
"no duplicate trailer for the primary author"
);
assert_eq!(coauth[0], ca.model_trailer());
}
/// Requirement 7 + 10: an existing third-party human co-author PLUS the
/// operator PLUS the Newt model all survive on one commit — third-party
/// trailers are preserved verbatim, the operator trailer is added, and the
/// Newt model attribution is independent from both.
#[test]
fn third_party_plus_operator_plus_newt_model_all_survive() {
let ca = CommitAttribution {
operator_email: Some("shawn@example.com".to_string()),
..sample_ca()
};
let input = "feat: thing\n\nBody.\n\nCo-authored-by: Alice <alice@example.com>\n";
let out = ca.finalize_message(input);
assert!(out.contains("Co-authored-by: Alice <alice@example.com>"));
assert!(out.contains("Co-authored-by: shawn <shawn@example.com>"));
assert!(out.contains(&ca.model_trailer()));
let coauth: Vec<&str> = out
.lines()
.filter(|l| l.starts_with("Co-authored-by: "))
.collect();
assert_eq!(coauth.len(), 3, "Alice + operator + newt model");
}
/// Requirement 5 + 11: a stale operator trailer from a prior finalization
/// is dropped + re-rendered (idempotent), never duplicated.
#[test]
fn finalize_replaces_stale_operator_trailer_idempotently() {
let ca = CommitAttribution {
operator_email: Some("shawn@example.com".to_string()),
..sample_ca()
};
let once = ca.finalize_message("fix the parser\n\nbody");
let twice = ca.finalize_message(&once);
assert_eq!(once, twice, "re-finalization is a no-op");
let op_trailers: Vec<&str> = out_operator_trailers(&once, "shawn@example.com");
assert_eq!(op_trailers.len(), 1, "exactly one operator trailer");
}
/// Requirement 6: an UNRELATED user `Harness:` trailer (not the canonical
/// Newt provenance shape) is PRESERVED as third-party, not dropped as stale
/// Newt provenance.
#[test]
fn unrelated_user_harness_trailer_is_preserved() {
let ca = sample_ca();
let input = "feat: thing\n\nBody.\n\nHarness: built with Rust 1.80\n";
let out = ca.finalize_message(input);
assert!(
out.contains("Harness: built with Rust 1.80"),
"unrelated user Harness: trailer must be preserved"
);
// The canonical Newt provenance is ALSO present (one of each).
let harness_lines: Vec<&str> = out.lines().filter(|l| l.starts_with("Harness: ")).collect();
assert_eq!(harness_lines.len(), 2, "user Harness + Newt provenance");
assert!(out.contains(&ca.provenance_line()));
}
/// Requirement 11: finalization with an operator is idempotent end-to-end
/// (operator trailer included), and the provenance line still carries the
/// operator name even when email is unavailable (requirement 5: preserve
/// operator name in provenance when email is unavailable).
#[test]
fn finalize_with_operator_is_idempotent_and_provenance_keeps_name() {
let ca = CommitAttribution {
operator_email: Some("shawn@example.com".to_string()),
..sample_ca()
};
let once = ca.finalize_message("fix the parser\n\nbody");
let twice = ca.finalize_message(&once);
assert_eq!(once, twice);
// Provenance carries the operator NAME regardless of email.
assert!(ca.provenance_line().contains("Operator: shawn"));
}
/// Helper: collect operator `Co-authored-by:` lines credited to `email`.
fn out_operator_trailers<'a>(message: &'a str, email: &str) -> Vec<&'a str> {
let tag = format!("<{email}>");
message
.lines()
.filter(|l| l.starts_with("Co-authored-by: ") && l.ends_with(&tag))
.collect()
}
}