File size: 97,473 Bytes
4e23b01 | 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 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 | import { describe, expect, it } from 'vitest';
import { filterOpsForGrade, isAppendOnly, redactSnapshotForGrade } from '#/granularity/filterOps';
import { detachGrades, gradeFor, needsResetOnTransition } from '#/granularity/grade';
import { paginateTurns } from '#/pagination/paginate';
import { ViewRegistry } from '#/view/registry';
import { projectTranscriptUserOrigin } from '#/contract/origin';
import { groupMessagesIntoSnapshot, type HistoryContentPart } from '#/history/groupTurns';
import { foldWireRecordFacts, type HistoryWireRecord } from '#/history/foldFacts';
import {
transcriptOperationSchema,
transcriptQuerySchema,
transcriptResponseSchema,
transcriptGradeSpecSchema,
transcriptUserOriginSchema,
} from '#/contract/schema';
import type { TranscriptItem } from '#/model/item';
import type { AgentTranscriptSnapshot, TranscriptOperation } from '#/ops/operation';
const idLabel = (i: TranscriptItem): string =>
i.kind === 'turn' ? i.turnId : i.kind === 'marker' ? i.markerId : i.refId;
describe('client metadata in transcript user origins', () => {
it('retains user-invoked single skill frame metadata without exposing model-triggered activations as user input', () => {
const origin = { kind: 'skill_activation', trigger: 'user-slash', skillName: 'example-skill', skillArgs: 'args', clientMetadata: [{ display_text: 'Save button' }] };
expect(transcriptUserOriginSchema.parse(projectTranscriptUserOrigin(origin))).toEqual(origin);
expect(projectTranscriptUserOrigin({ ...origin, trigger: 'model-tool' })).toBeUndefined();
});
it('rebuilds a user turn payload without server-local paths', () => {
const clientMetadata = [{ display_text: 'Visible prompt' }];
const origin = {
kind: 'user',
clientMetadata,
skillActivations: [{ activationId: 'a1', skillName: 'deploy', skillArgs: 'now', skillPath: '/private/deploy/SKILL.md' }],
attachments: [{ name: 'notes.pdf', mediaType: 'application/pdf', size: 42, path: '/private/notes.pdf' }],
};
const snapshot = groupMessagesIntoSnapshot([
{ role: 'user', content: [{ type: 'text', text: 'rendered skill' }, { type: 'text', text: 'visible prompt' }], toolCalls: [], origin },
{ role: 'assistant', content: [{ type: 'text', text: 'reply' }], toolCalls: [] },
]);
const turn = snapshot.items.find((item) => item.kind === 'turn');
expect(turn?.origin).toEqual({ kind: 'user', payload: { kind: 'user', clientMetadata, skillActivations: [{ skillName: 'deploy', skillArgs: 'now' }] } });
expect(JSON.stringify(turn)).not.toContain('/private/');
expect(JSON.stringify(snapshot.attachments)).not.toContain('/private/');
});
it('keeps opening prompt metadata when rebuilding history turns', () => {
const clientMetadata = [{ kimi_code_composer: { version: 1, doc: { type: 'doc' } } }];
const origin = { kind: 'user', clientMetadata };
const snapshot = groupMessagesIntoSnapshot([
{ role: 'user', content: [{ type: 'text', text: 'visible prompt' }], toolCalls: [], origin },
{ role: 'assistant', content: [{ type: 'text', text: 'reply' }], toolCalls: [] },
]);
const turn = snapshot.items.find((item) => item.kind === 'turn');
expect(turn?.origin).toEqual({ kind: 'user', payload: { kind: 'user', clientMetadata } });
expect(turn?.prompt).toBe('visible prompt');
});
it('projects and validates independent document snapshots without losing their nested fields', () => {
const clientMetadata = [
{ kimi_code_composer: { version: 1, doc: { type: 'doc', content: [{ type: 'paragraph' }] }, captureIds: ['capture-a'] } },
{ kimi_code_composer: { version: 1, captureIds: ['capture-b'] } },
];
const projected = projectTranscriptUserOrigin({ kind: 'user', clientMetadata });
expect(transcriptUserOriginSchema.parse(projected)).toEqual({ kind: 'user', clientMetadata });
expect(projectTranscriptUserOrigin({ kind: 'user' })).toStrictEqual({ kind: 'user' });
expect(projectTranscriptUserOrigin({ kind: 'injection', clientMetadata })).toBeUndefined();
});
});
describe('user slash skill activations as transcript origins', () => {
it('projects a user-invoked activation and rejects a model-triggered one', () => {
const origin = { kind: 'skill_activation', trigger: 'user-slash', skillName: 'example-skill', skillArgs: 'args' };
expect(transcriptUserOriginSchema.parse(projectTranscriptUserOrigin(origin))).toEqual(origin);
expect(projectTranscriptUserOrigin({ ...origin, trigger: 'model-tool' })).toBeUndefined();
expect(projectTranscriptUserOrigin({ ...origin, skillName: '' })).toBeUndefined();
expect(projectTranscriptUserOrigin({ kind: 'user' })).toStrictEqual({ kind: 'user' });
});
});
const turnOp = (n: number): TranscriptOperation => ({
op: 'turn.upsert',
turn: { kind: 'turn', turnId: `t${n}`, ordinal: n, state: 'running', origin: { kind: 'user' } },
});
const stepOp: TranscriptOperation = {
op: 'step.upsert',
turnId: 't1',
step: { kind: 'step', stepId: 't1.1', turnId: 't1', ordinal: 1, state: 'running' },
};
const frameOp: TranscriptOperation = {
op: 'frame.upsert',
turnId: 't1',
stepId: 't1.1',
frame: { kind: 'text', frameId: 't1.1.f1', role: 'assistant', text: 'full' },
};
const appendOp: TranscriptOperation = {
op: 'append',
target: { type: 'frame', turnId: 't1', stepId: 't1.1', frameId: 't1.1.f1' },
offset: 0,
text: 'chunk',
};
const promptOp: TranscriptOperation = {
op: 'prompt.upsert',
prompt: { promptId: 'p1', status: 'queued', createdAt: '2026-07-22T00:00:00.000Z' },
};
describe('granularity', () => {
const ops: TranscriptOperation[] = [
turnOp(1),
stepOp,
frameOp,
appendOp,
promptOp,
{ op: 'meta.merge', meta: { activity: 'turn' } },
];
it('off admits nothing', () => {
expect(filterOpsForGrade('off', ops)).toEqual([]);
});
it('turn admits headers and global state only', () => {
expect(filterOpsForGrade('turn', ops).map((op) => op.op)).toEqual([
'turn.upsert',
'prompt.upsert',
'meta.merge',
]);
});
it('block admits step/frame upserts but no appends', () => {
expect(filterOpsForGrade('block', ops).map((op) => op.op)).toEqual([
'turn.upsert',
'step.upsert',
'frame.upsert',
'prompt.upsert',
'meta.merge',
]);
});
it('delta admits everything', () => {
expect(filterOpsForGrade('delta', ops)).toHaveLength(ops.length);
});
it('gradeFor resolves agent override over wildcard default', () => {
const spec = { '*': 'turn', main: 'delta' } as const;
expect(gradeFor(spec, 'main')).toBe('delta');
expect(gradeFor(spec, 'sub-1')).toBe('turn');
expect(gradeFor(undefined, 'main')).toBe('off');
});
it('upgrade needs reset, downgrade does not', () => {
expect(needsResetOnTransition('turn', 'delta')).toBe(true);
expect(needsResetOnTransition('delta', 'turn')).toBe(false);
});
it('detachGrades writes explicit off so a wildcard default cannot resurrect the agent', () => {
expect(detachGrades({ '*': 'delta' }, ['main'])).toEqual({ '*': 'delta', main: 'off' });
expect(detachGrades({ '*': 'delta', main: 'turn' }, ['main'])).toEqual({
'*': 'delta',
main: 'off',
});
});
it('detachGrades deletes a listed wildcard entry', () => {
expect(detachGrades({ '*': 'delta', main: 'turn' }, ['*'])).toEqual({ main: 'turn' });
});
it('detachGrades collapses an all-off spec to undefined', () => {
expect(detachGrades({ main: 'delta' }, ['main'])).toBeUndefined();
expect(detachGrades({ '*': 'delta', main: 'off' }, ['*'])).toBeUndefined();
expect(detachGrades(undefined, ['main'])).toBeUndefined();
});
it('append-only batches are volatile-safe', () => {
expect(isAppendOnly([appendOp])).toBe(true);
expect(isAppendOnly([appendOp, frameOp])).toBe(false);
});
it('redactSnapshotForGrade strips step detail below block, keeps it at block+', () => {
const snapshot: AgentTranscriptSnapshot = {
items: [
{
kind: 'turn',
turnId: 't1',
ordinal: 1,
state: 'completed',
origin: { kind: 'user' },
prompt: 'hi',
steps: [
{
kind: 'step',
stepId: 't1.1',
turnId: 't1',
ordinal: 1,
state: 'completed',
frames: [{ kind: 'text', frameId: 't1.1.f1', role: 'assistant', text: 'body' }],
},
],
},
{ kind: 'marker', markerId: 'm1', marker: 'skill' },
],
tasks: [],
interactions: [
{
interactionId: 'appr-1',
interactionKind: 'approval' as const,
toolCallId: 'c1',
state: 'pending' as const,
},
],
attachments: [
{ attachmentId: 'att_1', mediaType: 'image/png', source: { kind: 'url' as const, url: 'https://example.com/a.png' } },
],
todos: [{ todoId: 'todo', items: [{ title: 'write tests', status: 'in_progress' as const }] }],
prompts: [{ promptId: 'p1', status: 'running' as const, createdAt: '2026-07-22T00:00:00.000Z' }],
meta: {},
};
const turnGrade = redactSnapshotForGrade('turn', snapshot);
expect(turnGrade.interactions).toHaveLength(1);
expect(turnGrade.attachments).toHaveLength(1);
expect(turnGrade.todos).toHaveLength(1);
expect(turnGrade.prompts).toHaveLength(1);
const turn = turnGrade.items[0];
expect(turn?.kind === 'turn' && turn.steps).toEqual([]);
expect(turn?.kind === 'turn' && turn.prompt).toBe('hi');
expect(turnGrade.items[1]?.kind).toBe('marker');
expect(redactSnapshotForGrade('block', snapshot)).toBe(snapshot);
expect(redactSnapshotForGrade('delta', snapshot)).toBe(snapshot);
});
});
describe('paginateTurns', () => {
const items: TranscriptItem[] = [
{ kind: 'marker', markerId: 'm0', marker: 'goal' },
...[1, 2, 3, 4, 5].flatMap((n): TranscriptItem[] => [
{
kind: 'turn',
turnId: `t${n}`,
ordinal: n,
state: 'completed',
origin: { kind: 'user' },
steps: [],
},
{ kind: 'marker', markerId: `m${n}`, marker: 'skill' },
]),
];
it('default page is the newest N turns with trailing segment items', () => {
const page = paginateTurns(items, { pageSize: 2 });
expect(page.items.map(idLabel)).toEqual(['t4', 'm4', 't5', 'm5']);
expect(page.hasMore).toBe(true);
});
it('before_turn pages toward older turns; head marker rides the oldest segment', () => {
const page = paginateTurns(items, { beforeTurn: 't4', pageSize: 2 });
expect(page.items.map(idLabel)).toEqual(['t2', 'm2', 't3', 'm3']);
expect(page.hasMore).toBe(true);
const oldest = paginateTurns(items, { beforeTurn: 't2', pageSize: 5 });
expect(oldest.items[0]).toEqual({ kind: 'marker', markerId: 'm0', marker: 'goal' });
expect(oldest.hasMore).toBe(false);
});
it('after_turn pages toward newer turns without the head unit', () => {
const page = paginateTurns(items, { afterTurn: 't3', pageSize: 2 });
expect(page.items.map(idLabel)).toEqual(['t4', 'm4', 't5', 'm5']);
expect(page.hasMore).toBe(false);
});
it('keeps head non-turn items with the newest page when turns exactly fill it', () => {
const page = paginateTurns(items, { pageSize: 5 });
expect(page.items[0]).toEqual({ kind: 'marker', markerId: 'm0', marker: 'goal' });
expect(page.items.map(idLabel)).toEqual(['m0', 't1', 'm1', 't2', 'm2', 't3', 'm3', 't4', 'm4', 't5', 'm5']);
expect(page.hasMore).toBe(false);
});
it('returns a marker-only timeline as one page with nothing older', () => {
const only = paginateTurns([{ kind: 'marker', markerId: 'm0', marker: 'goal' }], { pageSize: 3 });
expect(only.items.map(idLabel)).toEqual(['m0']);
expect(only.hasMore).toBe(false);
});
});
describe('ViewRegistry', () => {
it('dispatches on view ?? name, origin.kind and marker keys', () => {
const registry = new ViewRegistry<string>({ fallbackTool: 'generic' });
registry.registerTool('read', 'readRenderer');
registry.registerTool('swarm', 'swarmRenderer');
registry.registerInput('cron', 'cronInput');
registry.registerMarker('goal', 'goalMarker');
expect(
registry.resolveTool({ kind: 'tool', frameId: 'f', toolCallId: 'c1', name: 'Read', state: 'done' }),
).toBe('readRenderer');
expect(
registry.resolveTool({ kind: 'tool', frameId: 'f', toolCallId: 'c2', name: 'AgentSwarm', view: 'swarm', state: 'running' }),
).toBe('swarmRenderer');
expect(
registry.resolveTool({ kind: 'tool', frameId: 'f', toolCallId: 'c3', name: 'Bash', state: 'running' }),
).toBe('generic');
expect(registry.resolveInput({ kind: 'cron' })).toBe('cronInput');
expect(registry.resolveInput({ kind: 'user' })).toBeUndefined();
expect(registry.resolveMarker('goal')).toBe('goalMarker');
});
});
describe('contract schemas', () => {
it('roundtrips every op kind', () => {
const ops: TranscriptOperation[] = [
{ op: 'reset', agentId: 'main', snapshot: { items: [], tasks: [], interactions: [], attachments: [], todos: [], prompts: [], meta: {}, hasMoreOlder: true } },
turnOp(1),
stepOp,
frameOp,
appendOp,
{ op: 'marker.upsert', item: { kind: 'marker', markerId: 'm1', marker: 'goal' } },
{ op: 'taskref.upsert', item: { kind: 'taskref', refId: 'r1', taskId: 'task1' } },
{ op: 'task.upsert', task: { taskId: 'task1', kind: 'shell', state: 'running', detached: false, outputTail: '' } },
{
op: 'interaction.upsert',
interaction: { interactionId: 'appr-1', interactionKind: 'approval', toolCallId: 'c1', state: 'pending' },
},
{
op: 'attachment.upsert',
attachment: { attachmentId: 'att_1', mediaType: 'image/png', source: { kind: 'file', fileId: 'f1' } },
},
{ op: 'todo.upsert', todo: { todoId: 'todo', items: [{ title: 'x', status: 'done' }] } },
promptOp,
{ op: 'meta.merge', meta: { goal: { objective: 'x', status: 'active' } } },
{ op: 'items.remove', ids: ['t1'] },
];
for (const op of ops) {
expect(transcriptOperationSchema.parse(op)).toBeDefined();
}
});
it('roundtrips ops carrying the extended wire detail', () => {
const usage = { inputOther: 10, output: 5, inputCacheRead: 3, inputCacheCreation: 2 };
const ops: TranscriptOperation[] = [
{
op: 'reset',
agentId: 'main',
snapshot: {
items: [],
tasks: [],
interactions: [],
attachments: [],
todos: [],
prompts: [
{
promptId: 'p1',
status: 'completed',
userMessageId: 'u1',
content: [{ type: 'text', text: 'hi' }],
createdAt: '2026-07-22T00:00:00.000Z',
finishedAt: '2026-07-22T00:01:00.000Z',
steeredAt: '2026-07-22T00:00:30.000Z',
},
],
meta: {
agent: {
model: 'k2',
thinkingEffort: 'high',
usage: { byModel: { k2: usage }, currentTurn: usage, total: usage },
contextTokens: 1234,
maxContextTokens: 128000,
contextUsage: 0.01,
permission: 'auto',
phase: { kind: 'retrying', turnId: 1, step: 1, stepId: 't1.1', failedAttempt: 1, nextAttempt: 2, maxAttempts: 3, delayMs: 500, since: 1000 },
},
},
},
},
{
op: 'turn.upsert',
turn: {
kind: 'turn', turnId: 't1', triggerPromptId: 'prompt-1', ordinal: 1, state: 'failed', origin: { kind: 'user' },
usage: { inputTokens: 12, outputTokens: 5, cachedTokens: 3 },
durationMs: 1500,
error: 'boom',
},
},
{
op: 'step.upsert',
turnId: 't1',
step: {
kind: 'step', stepId: 't1.1', turnId: 't1', ordinal: 1, state: 'interrupted',
usage,
finishReason: 'stop',
timing: {
llmFirstTokenLatencyMs: 120,
llmStreamDurationMs: 900,
llmRequestBuildMs: 5,
llmServerFirstTokenMs: 110,
llmServerDecodeMs: 700,
llmClientConsumeMs: 950,
llmClientBlockedMs: 25,
},
retry: { failedAttempt: 1, nextAttempt: 2, maxAttempts: 3, delayMs: 500, errorName: 'RateLimit', errorMessage: 'slow down', statusCode: 429 },
endReason: 'aborted',
endMessage: 'user pressed escape',
},
},
{
op: 'frame.upsert',
turnId: 't1',
stepId: 't1.1',
frame: {
kind: 'tool', frameId: 't1.1.c1', toolCallId: 'c1', name: 'Bash', state: 'running',
inputText: '{"command":"ls',
progress: { kind: 'progress', text: 'half', percent: 50, customKind: 'bar', customData: { x: 1 } },
},
},
{
op: 'task.upsert',
task: {
taskId: 'task1', kind: 'subagent', state: 'completed', detached: false, outputTail: '',
resultSummary: 'scanned 12 files',
error: 'partial failure',
stateReason: 'waiting for input',
usage,
},
},
{
op: 'meta.merge',
meta: { agent: { model: 'k2', phase: { kind: 'ended', turnId: 1, reason: 'completed', durationMs: 1500, at: 2000 } } },
},
];
for (const op of ops) {
expect(transcriptOperationSchema.parse(op)).toEqual(op);
}
});
it('accepts provenance only on user text frames', () => {
const base = {
op: 'frame.upsert',
turnId: 't1',
stepId: 't1.1',
} as const;
expect(transcriptOperationSchema.safeParse({
...base,
frame: {
kind: 'text',
frameId: 't1.1.f1',
role: 'user',
text: 'steered in',
origin: { kind: 'user', skillActivations: [{ skillName: 'review', skillArgs: 'strict' }] },
},
}).success).toBe(true);
expect(transcriptOperationSchema.safeParse({
...base,
frame: {
kind: 'text',
frameId: 't1.1.f2',
role: 'assistant',
text: 'reply',
origin: { kind: 'user' },
},
}).success).toBe(false);
});
it('rejects mutually exclusive cursors and bad grades', () => {
expect(() => transcriptGradeSpecSchema.parse({ '*': 'stream' })).toThrow();
const ok = transcriptResponseSchema.safeParse({
agent_id: 'main',
items: [],
has_more: false,
tasks: [],
interactions: [],
attachments: [],
todos: [],
meta: {},
agents: [{ agentId: 'main', type: 'main' }],
pending_interactions: [],
});
expect(ok.success).toBe(true);
});
it('rejects path-hostile agent ids in the transcript query', () => {
const base = { agent_id: 'main', before_turn: undefined, after_turn: undefined, page_size: undefined };
expect(transcriptQuerySchema.safeParse({ ...base, agent_id: 'sub-1' }).success).toBe(true);
expect(transcriptQuerySchema.safeParse({ ...base, agent_id: '01HF7YAT31J7SMRT1QXGJWKR8D' }).success).toBe(true);
for (const hostile of ['../main', '..\\main', '..', 'a/b', 'a\\b', '.', 'a\0b', 'x'.repeat(200)]) {
expect(transcriptQuerySchema.safeParse({ ...base, agent_id: hostile }).success).toBe(false);
}
});
});
describe('groupMessagesIntoSnapshot (cold path)', () => {
const snapshotOf = (...parts: HistoryContentPart[]): AgentTranscriptSnapshot =>
groupMessagesIntoSnapshot([
{ role: 'user', content: parts, toolCalls: [], origin: { kind: 'user' } },
]);
it('groups flat messages into turns with folded tool results', () => {
const snapshot = groupMessagesIntoSnapshot([
{ role: 'system', content: [{ type: 'text', text: 'sys' }] },
{ role: 'user', content: [{ type: 'text', text: 'hello' }], toolCalls: [], origin: { kind: 'user' } },
{
role: 'assistant',
content: [{ type: 'think', think: 'hmm' }, { type: 'text', text: 'checking' }],
toolCalls: [{ id: 'c1', name: 'Read', arguments: '{"path":"/a"}' }],
},
{ role: 'tool', content: [{ type: 'text', text: 'file body' }], toolCallId: 'c1', toolCalls: [] },
{
role: 'assistant',
content: [{ type: 'text', text: 'done' }],
toolCalls: [],
},
{ role: 'user', content: [{ type: 'text', text: 'next' }], toolCalls: [], origin: { kind: 'user' } },
{
role: 'user',
content: [{ type: 'text', text: 'summary of old' }],
toolCalls: [],
origin: { kind: 'compaction_summary' },
},
{ role: 'user', content: [{ type: 'text', text: 'after' }], toolCalls: [], origin: { kind: 'user' } },
]);
const kinds = snapshot.items.map((i) => i.kind);
expect(kinds).toEqual(['turn', 'turn', 'marker', 'turn']);
const firstTurn = snapshot.items[0];
if (firstTurn?.kind !== 'turn') throw new Error('expected turn');
expect(firstTurn.prompt).toBe('hello');
expect(firstTurn.steps).toHaveLength(2);
const tool = firstTurn.steps[0]?.frames.find((f) => f.kind === 'tool');
expect(tool?.kind === 'tool' && tool.output).toBe('file body');
expect(tool?.kind === 'tool' && tool.input).toEqual({ path: '/a' });
const marker = snapshot.items[2];
expect(marker?.kind === 'marker' && marker.marker).toBe('compaction');
});
it('folds task-notification user messages into the current turn instead of opening their own', () => {
const snapshot = groupMessagesIntoSnapshot(
[
{ role: 'user', content: [{ type: 'text', text: 'run it' }], toolCalls: [], origin: { kind: 'user' } },
{
role: 'assistant',
content: [{ type: 'text', text: 'starting' }],
toolCalls: [{ id: 'c1', name: 'Bash', arguments: '{"command":"ls"}' }],
},
{
role: 'user',
content: [{
type: 'text',
text: '<notification id="task:task-9:completed" category="task" type="task.completed" source_kind="background_task" source_id="task-9">\nTitle: Background agent completed\nSeverity: info\ninspect done.\n</notification>',
}],
toolCalls: [],
origin: { kind: 'task', taskId: 'task-9' } as { kind: string },
},
{
role: 'user',
content: [{ type: 'text', text: '<notification id="task:task-8:completed"></notification>' }],
toolCalls: [],
origin: { kind: 'task', taskId: 'task-8' } as { kind: string },
},
{
role: 'assistant',
content: [{ type: 'text', text: 'continuing' }],
toolCalls: [],
},
],
{ taskOriginTurnTaskIds: new Set() },
);
const turns = snapshot.items.filter((i) => i.kind === 'turn');
expect(turns).toHaveLength(1);
const turn = turns[0];
if (turn?.kind !== 'turn') throw new Error('expected turn');
const userFrames = turn.steps
.flatMap((step) => step.frames)
.filter((f) => f.kind === 'text' && f.role === 'user');
expect(userFrames.map((f) => f.kind === 'text' && f.taskId)).toEqual(['task-9', 'task-8']);
expect(userFrames[0]).toMatchObject({ text: 'Background agent completed\ninspect done.' });
const assistantTexts = turn.steps
.flatMap((step) => step.frames)
.filter((f) => f.kind === 'text' && f.role === 'assistant')
.map((f) => f.kind === 'text' && f.text);
expect(assistantTexts).toEqual(['starting', 'continuing']);
expect(turn.steps).toHaveLength(2);
expect(turn.steps[1]?.frames.map((f) => f.kind === 'text' && f.role)).toEqual([
'user',
'user',
'assistant',
]);
});
it('folds a user message whose content matches a turn.steer record into the current turn as a user frame', () => {
const snapshot = groupMessagesIntoSnapshot(
[
{ role: 'user', content: [{ type: 'text', text: 'active' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'working' }], toolCalls: [] },
{ role: 'user', content: [{ type: 'text', text: 'steered in' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'noted' }], toolCalls: [] },
],
{ steeredContents: new Map([[JSON.stringify([{ type: 'text', text: 'steered in' }]), new Map([['user', 1]])]]) },
);
expect(snapshot.items.map((i) => i.kind)).toEqual(['turn']);
const turn = snapshot.items[0];
if (turn?.kind !== 'turn') throw new Error('expected turn');
expect(turn.steps).toHaveLength(2);
expect(turn.steps[1]?.frames[0]).toMatchObject({
kind: 'text',
role: 'user',
text: 'steered in',
});
});
it('keeps a trailing steered message visible by appending it to the last step', () => {
const snapshot = groupMessagesIntoSnapshot(
[
{ role: 'user', content: [{ type: 'text', text: 'active' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'working' }], toolCalls: [] },
{ role: 'user', content: [{ type: 'text', text: 'steered in' }], toolCalls: [], origin: { kind: 'user' } },
],
{ steeredContents: new Map([[JSON.stringify([{ type: 'text', text: 'steered in' }]), new Map([['user', 1]])]]) },
);
expect(snapshot.items.map((i) => i.kind)).toEqual(['turn']);
const turn = snapshot.items[0];
if (turn?.kind !== 'turn') throw new Error('expected turn');
const lastStep = turn.steps.at(-1);
expect(lastStep?.frames.at(-1)).toMatchObject({
kind: 'text',
role: 'user',
text: 'steered in',
});
});
it('flushes a pending steer into the closing turn when a new turn opens before any reply', () => {
const snapshot = groupMessagesIntoSnapshot(
[
{ role: 'user', content: [{ type: 'text', text: 'active' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'working' }], toolCalls: [] },
{ role: 'user', content: [{ type: 'text', text: 'steered in' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'user', content: [{ type: 'text', text: 'next question' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'answer' }], toolCalls: [] },
],
{ steeredContents: new Map([[JSON.stringify([{ type: 'text', text: 'steered in' }]), new Map([['user', 1]])]]) },
);
const turns = snapshot.items.filter((i) => i.kind === 'turn');
expect(turns).toHaveLength(2);
const first = turns[0];
if (first?.kind !== 'turn') throw new Error('expected turn');
expect(first.steps.at(-1)?.frames.at(-1)).toMatchObject({
kind: 'text',
role: 'user',
text: 'steered in',
});
const second = turns[1];
if (second?.kind !== 'turn') throw new Error('expected turn');
expect(second.prompt).toBe('next question');
});
it('still opens its own turn for a mid-conversation user message unknown to the steer map', () => {
const snapshot = groupMessagesIntoSnapshot(
[
{ role: 'user', content: [{ type: 'text', text: 'active' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'working' }], toolCalls: [] },
{ role: 'user', content: [{ type: 'text', text: 'plain follow-up' }], toolCalls: [], origin: { kind: 'user' } },
],
{ steeredContents: new Map([[JSON.stringify([{ type: 'text', text: 'steered in' }]), new Map([['user', 1]])]]) },
);
expect(snapshot.items.map((i) => i.kind)).toEqual(['turn', 'turn']);
});
it('stops folded notification text before child output blocks', () => {
const xml = [
'<notification id="task:task-9:completed" category="task" type="task.completed" source_kind="background_task" source_id="task-9">',
'Title: Background agent completed',
'Severity: info',
'inspect done.',
'<output-file>/tmp/out.log</output-file>',
'/tmp/out.log',
'full output here',
'</notification>',
].join('\n');
const snapshot = groupMessagesIntoSnapshot(
[
{ role: 'user', content: [{ type: 'text', text: 'run' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'go' }], toolCalls: [] },
{ role: 'user', content: [{ type: 'text', text: xml }], toolCalls: [], origin: { kind: 'task', taskId: 'task-9' } as { kind: string } },
{ role: 'assistant', content: [{ type: 'text', text: 'done' }], toolCalls: [] },
],
{ taskOriginTurnTaskIds: new Set() },
);
const turn = snapshot.items[0];
if (turn?.kind !== 'turn') throw new Error('expected turn');
const frame = turn.steps.flatMap((step) => step.frames).find((f) => f.kind === 'text' && f.role === 'user');
expect(frame).toMatchObject({ text: 'Background agent completed\ninspect done.' });
});
it('stops folded notification text before an inline answer block', () => {
const xml = [
'<notification id="task:question-1:completed" category="task" type="task.completed" source_kind="background_task" source_id="question-1">',
'Title: Background question answered',
'Severity: info',
'The user answered "Which database?".',
'<answer>',
'{"answers":{"Which database?":"Postgres"}}',
'</answer>',
'</notification>',
].join('\n');
const snapshot = groupMessagesIntoSnapshot(
[
{ role: 'user', content: [{ type: 'text', text: 'run' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'go' }], toolCalls: [] },
{ role: 'user', content: [{ type: 'text', text: xml }], toolCalls: [], origin: { kind: 'task', taskId: 'question-1' } as { kind: string } },
{ role: 'assistant', content: [{ type: 'text', text: 'done' }], toolCalls: [] },
],
{ taskOriginTurnTaskIds: new Set() },
);
const turn = snapshot.items[0];
if (turn?.kind !== 'turn') throw new Error('expected turn');
const frame = turn.steps.flatMap((step) => step.frames).find((f) => f.kind === 'text' && f.role === 'user');
expect(frame).toMatchObject({ text: 'Background question answered\nThe user answered "Which database?".' });
});
it('buffers a folded notification that arrives before the first step into that step', () => {
const xml = [
'<notification id="task:task-9:completed" category="task" type="task.completed" source_kind="background_task" source_id="task-9">',
'Title: Background agent completed',
'Severity: info',
'early done.',
'</notification>',
].join('\n');
const snapshot = groupMessagesIntoSnapshot(
[
{ role: 'user', content: [{ type: 'text', text: 'run' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'user', content: [{ type: 'text', text: xml }], toolCalls: [], origin: { kind: 'task', taskId: 'task-9' } as { kind: string } },
{ role: 'assistant', content: [{ type: 'text', text: 'go' }], toolCalls: [] },
],
{ taskOriginTurnTaskIds: new Set() },
);
const turn = snapshot.items[0];
if (turn?.kind !== 'turn') throw new Error('expected turn');
expect(turn.steps).toHaveLength(1);
expect(turn.steps[0]?.frames.map((f) => f.kind === 'text' && f.role)).toEqual([
'user',
'assistant',
]);
expect(turn.steps[0]?.frames[0]).toMatchObject({
text: 'Background agent completed\nearly done.',
taskId: 'task-9',
});
});
it('drops a folded notification when no turn is open yet', () => {
const snapshot = groupMessagesIntoSnapshot(
[
{
role: 'user',
content: [{ type: 'text', text: '<notification id="n1"></notification>' }],
toolCalls: [],
origin: { kind: 'task', taskId: 'task-9' } as { kind: string },
},
],
{ taskOriginTurnTaskIds: new Set() },
);
expect(snapshot.items).toHaveLength(0);
});
it('keeps body lines that start with an angle bracket but are not output blocks', () => {
const xml = [
'<notification id="task:task-9:completed" category="task" type="task.completed" source_kind="background_task" source_id="task-9">',
'Title: Background agent completed',
'Severity: info',
'first line.',
'<div>pasted markup</div>',
'last line.',
'</notification>',
].join('\n');
const snapshot = groupMessagesIntoSnapshot(
[
{ role: 'user', content: [{ type: 'text', text: 'run' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'go' }], toolCalls: [] },
{ role: 'user', content: [{ type: 'text', text: xml }], toolCalls: [], origin: { kind: 'task', taskId: 'task-9' } as { kind: string } },
{ role: 'assistant', content: [{ type: 'text', text: 'done' }], toolCalls: [] },
],
{ taskOriginTurnTaskIds: new Set() },
);
const turn = snapshot.items[0];
if (turn?.kind !== 'turn') throw new Error('expected turn');
const frame = turn.steps.flatMap((step) => step.frames).find((f) => f.kind === 'text' && f.role === 'user');
expect(frame).toMatchObject({
text: 'Background agent completed\nfirst line.\n<div>pasted markup</div>\nlast line.',
});
});
it('parses only the leading header lines, keeping later Title-like lines as body', () => {
const xml = [
'<notification id="task:task-9:completed" category="task" type="task.completed" source_kind="background_task" source_id="task-9">',
'Title: Background agent completed',
'Severity: info',
'first line.',
'Title: details',
'last line.',
'</notification>',
].join('\n');
const snapshot = groupMessagesIntoSnapshot(
[
{ role: 'user', content: [{ type: 'text', text: 'run' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'go' }], toolCalls: [] },
{ role: 'user', content: [{ type: 'text', text: xml }], toolCalls: [], origin: { kind: 'task', taskId: 'task-9' } as { kind: string } },
{ role: 'assistant', content: [{ type: 'text', text: 'done' }], toolCalls: [] },
],
{ taskOriginTurnTaskIds: new Set() },
);
const turn = snapshot.items[0];
if (turn?.kind !== 'turn') throw new Error('expected turn');
const frame = turn.steps.flatMap((step) => step.frames).find((f) => f.kind === 'text' && f.role === 'user');
expect(frame).toMatchObject({
text: 'Background agent completed\nfirst line.\nTitle: details\nlast line.',
});
});
it('keeps a body whose first line starts with Severity:', () => {
const xml = [
'<notification id="task:task-9:completed" category="task" type="task.completed" source_kind="background_task" source_id="task-9">',
'Title: Background agent completed',
'Severity: info',
'Severity: this line is the task description, not a header',
'last line.',
'</notification>',
].join('\n');
const snapshot = groupMessagesIntoSnapshot(
[
{ role: 'user', content: [{ type: 'text', text: 'run' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'go' }], toolCalls: [] },
{ role: 'user', content: [{ type: 'text', text: xml }], toolCalls: [], origin: { kind: 'task', taskId: 'task-9' } as { kind: string } },
{ role: 'assistant', content: [{ type: 'text', text: 'done' }], toolCalls: [] },
],
{ taskOriginTurnTaskIds: new Set() },
);
const turn = snapshot.items[0];
if (turn?.kind !== 'turn') throw new Error('expected turn');
const frame = turn.steps.flatMap((step) => step.frames).find((f) => f.kind === 'text' && f.role === 'user');
expect(frame).toMatchObject({
text: 'Background agent completed\nSeverity: this line is the task description, not a header\nlast line.',
});
});
it('expands a bundled prompt into per-skill markers and a caller-text turn', () => {
const snapshot = groupMessagesIntoSnapshot([
{
role: 'user',
content: [
{ type: 'text', text: 'rendered review block' },
{ type: 'text', text: 'rendered security block' },
{ type: 'text', text: 'please /skill:review and /skill:security' },
],
toolCalls: [],
origin: {
kind: 'user',
skillActivations: [
{ activationId: 'act-1', skillName: 'review' },
{ activationId: 'act-2', skillName: 'security', skillArgs: 'src/app.ts' },
],
} as { kind: string },
},
{ role: 'assistant', content: [{ type: 'text', text: 'done' }], toolCalls: [] },
]);
expect(snapshot.items.map((item) => item.kind)).toEqual(['marker', 'marker', 'turn']);
const first = snapshot.items[0];
expect(first?.kind === 'marker' && first.marker).toBe('skill');
expect(first?.kind === 'marker' && first.payload).toMatchObject({
text: 'rendered review block',
origin: { kind: 'skill_activation', trigger: 'user-slash', skillName: 'review' },
});
const second = snapshot.items[1];
expect(second?.kind === 'marker' && second.payload).toMatchObject({
text: 'rendered security block',
origin: { skillName: 'security', skillArgs: 'src/app.ts' },
});
const turn = snapshot.items[2];
if (turn?.kind !== 'turn') throw new Error('expected turn');
expect(turn.prompt).toBe('please /skill:review and /skill:security');
expect(turn.steps).toHaveLength(1);
});
it('maps media parts on the opening user message to attachment entities, dropping base64 bytes', () => {
const snapshot = groupMessagesIntoSnapshot([
{
role: 'user',
content: [
{ type: 'text', text: 'what is this? [Image #1]' },
{ type: 'image', source: { kind: 'base64', media_type: 'image/png', data: 'aGVsbG8=' }, name: 'inline.png' },
{ type: 'image', source: { kind: 'url', url: 'https://example.com/pic.png' }, name: 'remote.png' },
{ type: 'image', source: { kind: 'file', file_id: 'file_8' }, name: 'stored.png' },
{ type: 'file', file_id: 'file_9', name: 'notes.txt', media_type: 'text/plain', size: 128 },
],
toolCalls: [],
origin: { kind: 'user' },
},
{ role: 'assistant', content: [{ type: 'text', text: 'a screenshot' }], toolCalls: [] },
]);
expect(snapshot.attachments).toHaveLength(4);
expect(snapshot.attachments[0]).toMatchObject({
attachmentId: 'att_1',
mediaType: 'image/png',
name: 'inline.png',
source: undefined,
});
expect(snapshot.attachments[1]).toMatchObject({
attachmentId: 'att_2',
name: 'remote.png',
source: { kind: 'url', url: 'https://example.com/pic.png' },
});
expect(snapshot.attachments[2]).toMatchObject({
attachmentId: 'att_3',
name: 'stored.png',
source: { kind: 'file', fileId: 'file_8' },
});
expect(snapshot.attachments[3]).toMatchObject({
attachmentId: 'att_4',
mediaType: 'text/plain',
name: 'notes.txt',
source: { kind: 'file', fileId: 'file_9' },
});
const firstTurn = snapshot.items[0];
if (firstTurn?.kind !== 'turn') throw new Error('expected turn');
expect(firstTurn.attachmentIds).toEqual(['att_1', 'att_2', 'att_3', 'att_4']);
});
it('folds origin file attachments on the opening user message into path-sourced entities', () => {
const snapshot = groupMessagesIntoSnapshot([
{
role: 'user',
content: [
{
type: 'text',
text: 'Attached file "report.pdf" (application/pdf, 128 bytes): /data/report.pdf — open it with the Read tool',
},
],
toolCalls: [],
origin: {
kind: 'user',
attachments: [
{ name: 'report.pdf', mediaType: 'application/pdf', size: 128, path: '/data/report.pdf' },
],
} as { kind: string },
},
{ role: 'assistant', content: [{ type: 'text', text: 'done' }], toolCalls: [] },
]);
expect(snapshot.attachments).toEqual([
{
attachmentId: 'att_1',
mediaType: 'application/pdf',
name: 'report.pdf',
size: 128,
},
]);
const turn = snapshot.items[0];
if (turn?.kind !== 'turn') throw new Error('expected turn');
expect(turn.attachmentIds).toEqual(['att_1']);
});
it('folds origin file attachments on a skill activation message into path-sourced entities', () => {
const snapshot = groupMessagesIntoSnapshot([
{
role: 'user',
content: [
{
type: 'text',
text: 'User activated the skill "update-config".',
},
],
toolCalls: [],
origin: {
kind: 'skill_activation',
activationId: 'act_1',
skillName: 'update-config',
trigger: 'user-slash',
attachments: [
{ name: 'note.txt', mediaType: 'text/plain', size: 21, path: '/data/note.txt' },
],
} as { kind: string },
},
{ role: 'assistant', content: [{ type: 'text', text: 'done' }], toolCalls: [] },
]);
expect(snapshot.attachments).toEqual([
{
attachmentId: 'att_1',
mediaType: 'text/plain',
name: 'note.txt',
size: 21,
},
]);
const turn = snapshot.items[1];
if (turn?.kind !== 'turn') throw new Error('expected turn');
expect(turn.attachmentIds).toEqual(['att_1']);
});
it('maps persisted kimi-file media refs to attachments', () => {
const snapshot = groupMessagesIntoSnapshot([
{
role: 'user',
content: [
{
type: 'video_url',
videoUrl: { url: 'kimi-file://file_1', name: 'clip.mp4' },
} as HistoryContentPart,
],
toolCalls: [],
origin: { kind: 'user' },
},
{
role: 'user',
content: [
{ type: 'text', text: 'what is this?' },
{
type: 'image_url',
imageUrl: { url: 'kimi-file://file_2?path=%2Fcache%2Fshot.png', name: 'shot.png' },
} as HistoryContentPart,
],
toolCalls: [],
origin: { kind: 'user' },
},
]);
expect(snapshot.attachments).toEqual([
{
attachmentId: 'att_1',
mediaType: 'video/*',
name: 'clip.mp4',
source: { kind: 'session_media', fileId: 'file_1' },
},
{
attachmentId: 'att_2',
mediaType: 'image/*',
name: 'shot.png',
source: { kind: 'session_media', fileId: 'file_2' },
},
]);
const videoTurn = snapshot.items[0];
const imageTurn = snapshot.items[1];
if (videoTurn?.kind !== 'turn' || imageTurn?.kind !== 'turn') {
throw new Error('expected turns');
}
expect(videoTurn.attachmentIds).toEqual(['att_1']);
expect(imageTurn.attachmentIds).toEqual(['att_2']);
expect(videoTurn.prompt).toBe('');
expect(imageTurn.prompt).toBe('what is this?');
});
it('projects a daemon ref in a user-slash turn-opening input like a plain user turn', () => {
const snapshot = groupMessagesIntoSnapshot([
{
role: 'user',
content: [
{ type: 'text', text: '/gen-docs ' },
{
type: 'image_url',
imageUrl: { url: 'kimi-file://file_4?path=%2Fcache%2Fshot.png' },
} as HistoryContentPart,
],
toolCalls: [],
origin: { kind: 'skill_activation', trigger: 'user-slash', skillName: 'gen-docs' } as {
kind: string;
},
},
]);
expect(snapshot.attachments).toEqual([
{
attachmentId: 'att_1',
mediaType: 'image/*',
source: { kind: 'session_media', fileId: 'file_4' },
},
]);
expect(snapshot.items.map((item) => item.kind)).toEqual(['marker', 'turn']);
const marker = snapshot.items[0];
if (marker?.kind !== 'marker') throw new Error('expected marker');
expect((marker.payload as { text: string }).text).toBe('/gen-docs ');
const turn = snapshot.items[1];
if (turn?.kind !== 'turn') throw new Error('expected turn');
expect(turn.prompt).toBe('/gen-docs ');
expect(turn.attachmentIds).toEqual(['att_1']);
});
it('keeps a kimi-file ref as a nameless attachment and inline tags as user text', () => {
const snapshot = snapshotOf(
{ type: 'text', text: 'open <image path="/tmp/other.png"></image> please' },
{
type: 'image_url',
imageUrl: { url: 'kimi-file://file_3' },
} as HistoryContentPart,
);
expect(snapshot.attachments).toEqual([
{
attachmentId: 'att_1',
mediaType: 'image/*',
source: { kind: 'session_media', fileId: 'file_3' },
},
]);
const turn = snapshot.items[0];
if (turn?.kind !== 'turn') throw new Error('expected turn');
expect(turn.attachmentIds).toEqual(['att_1']);
expect(turn.prompt).toBe('open <image path="/tmp/other.png"></image> please');
});
it('keeps a legacy tag+ref pair as prompt text plus the ref-derived attachment', () => {
const snapshot = snapshotOf(
{ type: 'text', text: '<image path="/cache/shot.png"></image>' },
{
type: 'image_url',
imageUrl: { url: 'kimi-file://file_5?path=%2Fcache%2Fshot.png' },
} as HistoryContentPart,
);
expect(snapshot.attachments).toEqual([
{
attachmentId: 'att_1',
mediaType: 'image/*',
source: { kind: 'session_media', fileId: 'file_5' },
},
]);
const turn = snapshot.items[0];
if (turn?.kind !== 'turn') throw new Error('expected turn');
expect(turn.prompt).toBe('<image path="/cache/shot.png"></image>');
expect(turn.attachmentIds).toEqual(['att_1']);
});
it('keeps standalone <media path> tags as prompt text', () => {
const snapshot = snapshotOf(
{ type: 'text', text: '<image path="/cache/shot.png">' },
{ type: 'text', text: '<image path="/cache/shot.png" content_type="image/png"></image>' },
{ type: 'text', text: '<video path="/cache/clip.mp4">' },
);
const turn = snapshot.items[0];
if (turn?.kind !== 'turn') throw new Error('expected turn');
expect(turn.prompt).toBe(
'<image path="/cache/shot.png"><image path="/cache/shot.png" content_type="image/png"></image><video path="/cache/clip.mp4">',
);
expect(turn.attachmentIds).toBeUndefined();
expect(snapshot.attachments).toEqual([]);
});
it('keeps cold tool calls running until a result is persisted', () => {
const pending = groupMessagesIntoSnapshot([
{ role: 'user', content: [{ type: 'text', text: 'run it' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [], toolCalls: [{ id: 'c1', name: 'Bash', arguments: '{}' }] },
]);
const pendingTurn = pending.items[0];
if (pendingTurn?.kind !== 'turn') throw new Error('expected turn');
const pendingTool = pendingTurn.steps[0]?.frames.find((f) => f.kind === 'tool');
expect(pendingTool?.kind === 'tool' && pendingTool.state).toBe('running');
const done = groupMessagesIntoSnapshot([
{ role: 'user', content: [{ type: 'text', text: 'run it' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [], toolCalls: [{ id: 'c1', name: 'Bash', arguments: '{}' }] },
{ role: 'tool', content: [{ type: 'text', text: 'done.txt' }], toolCallId: 'c1', toolCalls: [] },
]);
const doneTurn = done.items[0];
if (doneTurn?.kind !== 'turn') throw new Error('expected turn');
const doneTool = doneTurn.steps[0]?.frames.find((f) => f.kind === 'tool');
expect(doneTool?.kind === 'tool' && doneTool.state).toBe('done');
expect(doneTool?.kind === 'tool' && doneTool.output).toBe('done.txt');
});
it('opens a turn for subagent run prompts recorded as system triggers', () => {
const snapshot = groupMessagesIntoSnapshot([
{ role: 'user', content: [{ type: 'text', text: 'hi' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'answer' }], toolCalls: [] },
{
role: 'user',
content: [{ type: 'text', text: 'scan the repo' }],
toolCalls: [],
origin: { kind: 'system_trigger', name: 'subagent' } as { kind: string },
},
{ role: 'assistant', content: [{ type: 'text', text: 'scanning' }], toolCalls: [] },
]);
expect(snapshot.items.map((item) => item.kind)).toEqual(['turn', 'turn']);
const subTurn = snapshot.items[1];
if (subTurn?.kind !== 'turn') throw new Error('expected turn');
expect(subTurn.ordinal).toBe(1);
expect(subTurn.origin.kind).toBe('other');
expect(subTurn.prompt).toBe('scan the repo');
expect(subTurn.steps).toHaveLength(1);
});
it('starts a new turn for user-slash skill activations, keeps other triggers as markers only', () => {
const snapshot = groupMessagesIntoSnapshot([
{ role: 'user', content: [{ type: 'text', text: 'hi' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'answer' }], toolCalls: [] },
{
role: 'user',
content: [{ type: 'text', text: 'skill body' }],
toolCalls: [],
origin: { kind: 'skill_activation', trigger: 'user-slash', skillName: 'gen-docs' } as {
kind: string;
},
},
{ role: 'assistant', content: [{ type: 'text', text: 'docs done' }], toolCalls: [] },
{
role: 'user',
content: [{ type: 'text', text: 'nested skill body' }],
toolCalls: [],
origin: { kind: 'skill_activation', trigger: 'model-tool', skillName: 'x' } as {
kind: string;
},
},
{ role: 'assistant', content: [{ type: 'text', text: 'still same turn' }], toolCalls: [] },
]);
expect(snapshot.items.map((item) => item.kind)).toEqual(['turn', 'marker', 'turn', 'marker']);
const slashTurn = snapshot.items[2];
if (slashTurn?.kind !== 'turn') throw new Error('expected turn');
expect(slashTurn.ordinal).toBe(1);
expect(slashTurn.origin.kind).toBe('other');
expect(slashTurn.prompt).toBe('skill body');
expect(slashTurn.steps).toHaveLength(2);
});
it('keeps model-tool skill activations as markers even when their content matches a steer record', () => {
const skillContent = [{ type: 'text', text: 'skill body' }];
const snapshot = groupMessagesIntoSnapshot(
[
{ role: 'user', content: [{ type: 'text', text: 'hi' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'answer' }], toolCalls: [] },
{
role: 'user',
content: skillContent,
toolCalls: [],
origin: { kind: 'skill_activation', trigger: 'model-tool', skillName: 'write-tui' } as {
kind: string;
},
},
{ role: 'assistant', content: [{ type: 'text', text: 'used the skill' }], toolCalls: [] },
],
{ steeredContents: new Map([[JSON.stringify(skillContent), new Map([['skill_activation', 1]])]]) },
);
expect(snapshot.items.map((item) => item.kind)).toEqual(['turn', 'marker']);
const marker = snapshot.items[1];
if (marker?.kind !== 'marker') throw new Error('expected marker');
expect(marker.marker).toBe('skill');
});
it('still folds cron-origin steers into the running turn by content match', () => {
const cronContent = [{ type: 'text', text: 'cron tick' }];
const snapshot = groupMessagesIntoSnapshot(
[
{ role: 'user', content: [{ type: 'text', text: 'active' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'working' }], toolCalls: [] },
{
role: 'user',
content: cronContent,
toolCalls: [],
origin: { kind: 'cron_job', jobId: 'job1' } as { kind: string },
},
{ role: 'assistant', content: [{ type: 'text', text: 'noted' }], toolCalls: [] },
],
{ steeredContents: new Map([[JSON.stringify(cronContent), new Map([['cron_job', 1]])]]) },
);
expect(snapshot.items.map((item) => item.kind)).toEqual(['turn']);
const turn = snapshot.items[0];
if (turn?.kind !== 'turn') throw new Error('expected turn');
expect(turn.steps).toHaveLength(2);
expect(turn.steps[1]?.frames[0]).toMatchObject({
kind: 'text',
role: 'user',
text: 'cron tick',
});
});
it('still folds user-slash skill activations into the running turn by content match', () => {
const slashContent = [{ type: 'text', text: 'slash skill body' }];
const snapshot = groupMessagesIntoSnapshot(
[
{ role: 'user', content: [{ type: 'text', text: 'active' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'working' }], toolCalls: [] },
{
role: 'user',
content: slashContent,
toolCalls: [],
origin: { kind: 'skill_activation', trigger: 'user-slash', skillName: 'gen-docs' } as {
kind: string;
},
},
{ role: 'assistant', content: [{ type: 'text', text: 'noted' }], toolCalls: [] },
],
{ steeredContents: new Map([[JSON.stringify(slashContent), new Map([['skill_activation', 1]])]]) },
);
expect(snapshot.items.map((item) => item.kind)).toEqual(['turn']);
const turn = snapshot.items[0];
if (turn?.kind !== 'turn') throw new Error('expected turn');
expect(turn.steps).toHaveLength(2);
expect(turn.steps[1]?.frames[0]).toMatchObject({
kind: 'text',
role: 'user',
text: 'slash skill body',
});
});
it('consumes the steer count for marker-only activations so a later identical prompt opens its own turn', () => {
const shared = [{ type: 'text', text: 'same text' }];
const snapshot = groupMessagesIntoSnapshot(
[
{ role: 'user', content: [{ type: 'text', text: 'active' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'working' }], toolCalls: [] },
{
role: 'user',
content: shared,
toolCalls: [],
origin: { kind: 'skill_activation', trigger: 'model-tool', skillName: 'x' } as {
kind: string;
},
},
{ role: 'user', content: shared, toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'noted' }], toolCalls: [] },
],
{ steeredContents: new Map([[JSON.stringify(shared), new Map([['skill_activation', 1]])]]) },
);
expect(snapshot.items.map((item) => item.kind)).toEqual(['turn', 'marker', 'turn']);
});
it('does not consume a user steer count for a compaction summary with identical content', () => {
const shared = [{ type: 'text', text: 'same text' }];
const snapshot = groupMessagesIntoSnapshot(
[
{ role: 'user', content: [{ type: 'text', text: 'active' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'working' }], toolCalls: [] },
{
role: 'user',
content: shared,
toolCalls: [],
origin: { kind: 'compaction_summary' } as { kind: string },
},
{ role: 'user', content: shared, toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'noted' }], toolCalls: [] },
],
{ steeredContents: new Map([[JSON.stringify(shared), new Map([['user', 1]])]]) },
);
expect(snapshot.items.map((item) => item.kind)).toEqual(['turn', 'marker']);
const turn = snapshot.items[0];
if (turn?.kind !== 'turn') throw new Error('expected turn');
const steered = turn.steps
.flatMap((step) => step.frames)
.filter((frame) => frame.kind === 'text' && frame.role === 'user');
expect(steered).toHaveLength(1);
});
it('starts a promptless turn for turn-opening system triggers (goal continuation)', () => {
const snapshot = groupMessagesIntoSnapshot([
{ role: 'user', content: [{ type: 'text', text: 'hi' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'answer' }], toolCalls: [] },
{
role: 'user',
content: [{ type: 'text', text: 'continue the goal' }],
toolCalls: [],
origin: { kind: 'system_trigger', name: 'goal_continuation' } as { kind: string },
},
{ role: 'assistant', content: [{ type: 'text', text: 'continued' }], toolCalls: [] },
{
role: 'user',
content: [{ type: 'text', text: 'mode reminder' }],
toolCalls: [],
origin: { kind: 'injection', variant: 'permission_mode' } as { kind: string },
},
{ role: 'assistant', content: [{ type: 'text', text: 'still same turn' }], toolCalls: [] },
]);
expect(snapshot.items.map((item) => item.kind)).toEqual(['turn', 'turn']);
const [first, second] = snapshot.items;
if (first?.kind !== 'turn' || second?.kind !== 'turn') throw new Error('expected turns');
expect(first.ordinal).toBe(0);
expect(first.steps.map((step) => step.frames.map((frame) => frame.kind))).toEqual([['text']]);
expect(second.ordinal).toBe(1);
expect(second.origin.kind).toBe('other');
expect(second.prompt).toBeUndefined();
expect(second.steps).toHaveLength(2);
});
it('hides injected user messages and maps cron origins', () => {
const snapshot = groupMessagesIntoSnapshot([
{
role: 'user',
content: [{ type: 'text', text: 'secret context' }],
toolCalls: [],
origin: { kind: 'injection' },
},
{ role: 'user', content: [{ type: 'text', text: 'hi' }], toolCalls: [], origin: { kind: 'user' } },
{
role: 'user',
content: [{ type: 'text', text: 'run report' }],
toolCalls: [],
origin: { kind: 'cron_job', jobId: 'job1' } as { kind: string },
},
]);
expect(snapshot.items).toHaveLength(2);
const cronTurn = snapshot.items[1];
expect(cronTurn?.kind === 'turn' && cronTurn.origin.kind).toBe('cron');
});
it('opens a task turn for a notification with a task-origin turn.started in the wire', () => {
const snapshot = groupMessagesIntoSnapshot(
[
{ role: 'user', content: [{ type: 'text', text: 'hi' }], toolCalls: [], origin: { kind: 'user' } },
{
role: 'assistant',
content: [{ type: 'text', text: 'answer' }],
toolCalls: [],
},
{
role: 'user',
content: [{ type: 'text', text: 'task done' }],
toolCalls: [],
origin: { kind: 'task', taskId: 'task-9' } as { kind: string },
},
],
{ taskOriginTurnTaskIds: new Set(['task-9']) },
);
const taskTurn = snapshot.items[1];
if (taskTurn?.kind !== 'turn') throw new Error('expected turn');
expect(taskTurn.origin).toMatchObject({ kind: 'task', taskId: 'task-9' });
});
it('maps legacy background_task origins to task turns, preserving the taskId', () => {
const snapshot = groupMessagesIntoSnapshot([
{ role: 'user', content: [{ type: 'text', text: 'hi' }], toolCalls: [], origin: { kind: 'user' } },
{
role: 'user',
content: [{ type: 'text', text: 'task done' }],
toolCalls: [],
origin: { kind: 'background_task', taskId: 'b83rhswvs' } as { kind: string },
},
]);
const taskTurn = snapshot.items[1];
if (taskTurn?.kind !== 'turn') throw new Error('expected turn');
expect(taskTurn.origin).toMatchObject({ kind: 'task', taskId: 'b83rhswvs' });
});
});
describe('foldWireRecordFacts (cold facts)', () => {
const baseWithMarker = (): AgentTranscriptSnapshot =>
groupMessagesIntoSnapshot([
{ role: 'user', content: [{ type: 'text', text: 'hi' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'answer' }], toolCalls: [] },
{
role: 'user',
content: [{ type: 'text', text: 'summary of old' }],
toolCalls: [],
origin: { kind: 'compaction_summary' },
},
]);
it('returns the base snapshot unchanged when no fact records exist (old sessions)', () => {
const base = baseWithMarker();
const folded = foldWireRecordFacts(
[
{ type: 'metadata', protocol_version: '1.5', created_at: 1 },
{ type: 'context.append_message', message: { role: 'user' }, time: 1 },
],
base,
);
expect(folded).toEqual(base);
expect(folded.items).toBe(base.items);
});
it('folds todo records into the global todo document, last write wins', () => {
const base = baseWithMarker();
const folded = foldWireRecordFacts(
[
{ type: 'tools.update_store', key: 'todo', value: [{ title: 'old', status: 'pending' }], time: 1000 },
{ type: 'tools.update_store', key: 'other', value: [{ title: 'ignored', status: 'done' }], time: 2000 },
{
type: 'tools.update_store',
key: 'todo',
value: [
{ title: 'write tests', status: 'in_progress' },
{ title: 'ship', status: 'pending' },
{ title: 'malformed' },
],
time: 3000,
},
],
base,
);
expect(folded.todos).toEqual([
{
todoId: 'todo',
items: [
{ title: 'write tests', status: 'in_progress' },
{ title: 'ship', status: 'pending' },
],
updatedAt: new Date(3000).toISOString(),
},
]);
expect(folded.items).toBe(base.items);
});
it('folds goal create/update/clear into meta.goal with markers, last write wins', () => {
const base = baseWithMarker();
expect(base.items.some((item) => item.kind === 'marker' && item.markerId === 'm1')).toBe(true);
const folded = foldWireRecordFacts(
[
{
type: 'goal.create',
goalId: 'g1',
objective: 'fix the bug',
completionCriterion: 'tests pass',
time: 1000,
},
{ type: 'goal.update', status: 'blocked', reason: 'stuck', tokensUsed: 1200, time: 2000 },
{ type: 'goal.update', budgetLimits: { tokenBudget: 50000 }, time: 3000 },
],
base,
);
expect(folded.meta.goal).toEqual({
objective: 'fix the bug',
status: 'blocked',
completionCriterion: 'tests pass',
budgetUsed: 1200,
budgetLimit: 50000,
});
const goalMarkers = folded.items.filter(
(item) => item.kind === 'marker' && item.marker === 'goal',
);
expect(goalMarkers.map((item) => item.kind === 'marker' && item.markerId)).toEqual([
'm2',
'm3',
'm4',
]);
expect(goalMarkers[0]).toMatchObject({ at: new Date(1000).toISOString() });
expect(folded.items.slice(0, base.items.length)).toEqual(base.items);
const cleared = foldWireRecordFacts(
[
{ type: 'goal.create', goalId: 'g1', objective: 'fix the bug', time: 1000 },
{ type: 'goal.clear', time: 2000 },
],
base,
);
expect(cleared.meta.goal).toBeUndefined();
});
it('marks user-cancelled turns with interruption markers, skipping unattributable cancels', () => {
const base = baseWithMarker();
const folded = foldWireRecordFacts(
[
{ type: 'turn.cancel', turnId: 0, target: 'active', reason: 'user_cancelled', time: 1000 },
{ type: 'turn.cancel', turnId: 0, target: 'active', reason: 'user_cancelled', time: 1500 },
{ type: 'turn.cancel', turnId: 1, target: 'queued', reason: 'user_cancelled', time: 2000 },
{ type: 'turn.cancel', turnId: 2, target: 'active', reason: 'aborted', time: 3000 },
{ type: 'turn.cancel', turnId: 4, target: 'active', reason: 'aborted', time: 3500 },
{ type: 'turn.cancel', turnId: 4, target: 'active', reason: 'user_cancelled', time: 3600 },
{ type: 'turn.cancel', turnId: 3, target: 'active', time: 4000 },
],
base,
);
expect(
folded.items.filter((item) => item.kind === 'marker' && item.marker === 'interruption'),
).toEqual([
{
kind: 'marker',
markerId: 'm2',
marker: 'interruption',
payload: { turnId: 0, target: 'active', reason: 'user_cancelled' },
at: new Date(1000).toISOString(),
},
]);
});
it('folds plan/swarm mode records into meta.modes with enter/exit markers', () => {
const base = baseWithMarker();
const folded = foldWireRecordFacts(
[
{ type: 'plan_mode.enter', id: 'plan-1', time: 1000 },
{ type: 'swarm_mode.enter', trigger: { kind: 'task' }, time: 2000 },
{ type: 'plan_mode.exit', id: 'plan-1', time: 3000 },
],
base,
);
expect(folded.meta.modes).toEqual({ swarm: {} });
const markers = folded.items
.filter((item) => item.kind === 'marker')
.map((item) => item.kind === 'marker' && item.marker);
expect(markers).toEqual(['compaction', 'plan.enter', 'swarm.enter', 'plan.exit']);
const cancelled = foldWireRecordFacts(
[
{ type: 'plan_mode.enter', id: 'plan-1', time: 1000 },
{ type: 'plan_mode.cancel', time: 2000 },
{ type: 'swarm_mode.enter', trigger: { kind: 'tool' }, time: 3000 },
{ type: 'swarm_mode.exit', time: 4000 },
],
base,
);
expect(cancelled.meta.modes).toEqual({});
const stillPlanning = foldWireRecordFacts(
[{ type: 'plan_mode.enter', id: 'plan-1', time: 1000 }],
base,
);
expect(stillPlanning.meta.modes).toEqual({ plan: {} });
});
it('folds tower mode records into meta.modes without markers', () => {
const base = baseWithMarker();
const folded = foldWireRecordFacts(
[
{ type: 'tower_mode.enter', time: 1000 },
{ type: 'tower_mode.exit', time: 2000 },
{ type: 'tower_mode.enter', time: 3000 },
],
base,
);
expect(folded.meta.modes).toEqual({ tower: {} });
const exited = foldWireRecordFacts(
[
{ type: 'tower_mode.enter', time: 1000 },
{ type: 'tower_mode.exit', time: 2000 },
],
base,
);
expect(exited.meta.modes).toEqual({});
});
it('folds plan.revision records into the plan badge and a timeline marker', () => {
const base = baseWithMarker();
const revision = {
type: 'plan.revision',
id: 'plan-1',
version: 2,
key: 'plan/plan-1/v2.md',
sha256: 'deadbeef',
bytes: 512,
time: 2000,
};
const folded = foldWireRecordFacts(
[{ type: 'plan_mode.enter', id: 'plan-1', time: 1000 }, revision],
base,
{ resolvePlanRevisionKey: (key) => `sessions/w/s/agents/main/${key}` },
);
expect(folded.meta.modes).toEqual({
plan: { reviewPath: 'sessions/w/s/agents/main/plan/plan-1/v2.md', version: 2 },
});
const revisionMarkers = folded.items.filter(
(item) => item.kind === 'marker' && item.marker === 'plan.revision',
);
expect(revisionMarkers).toEqual([
{
kind: 'marker',
markerId: 'm3',
marker: 'plan.revision',
payload: {
id: 'plan-1',
version: 2,
path: 'sessions/w/s/agents/main/plan/plan-1/v2.md',
sha256: 'deadbeef',
bytes: 512,
},
at: new Date(2000).toISOString(),
},
]);
const exited = foldWireRecordFacts(
[
{ type: 'plan_mode.enter', id: 'plan-1', time: 1000 },
revision,
{ type: 'plan_mode.exit', id: 'plan-1', time: 3000 },
],
base,
);
expect(exited.meta.modes?.plan).toBeUndefined();
expect(
exited.items.filter((item) => item.kind === 'marker' && item.marker === 'plan.revision'),
).toHaveLength(1);
const reentered = foldWireRecordFacts(
[
{ type: 'plan_mode.enter', id: 'plan-1', time: 1000 },
revision,
{ type: 'plan_mode.exit', id: 'plan-1', time: 3000 },
{ type: 'plan_mode.enter', id: 'plan-2', time: 4000 },
],
base,
);
expect(reentered.meta.modes).toEqual({ plan: {} });
});
it('folds legacy plan.revision path records without a key', () => {
const base = baseWithMarker();
const legacy = {
type: 'plan.revision',
id: 'plan-1',
version: 1,
path: 'sessions/w/s/agents/main/plan/plan-1/v1.md',
sha256: 'deadbeef',
bytes: 256,
time: 2000,
};
const folded = foldWireRecordFacts(
[{ type: 'plan_mode.enter', id: 'plan-1', time: 1000 }, legacy],
base,
);
expect(folded.meta.modes).toEqual({
plan: { reviewPath: 'sessions/w/s/agents/main/plan/plan-1/v1.md', version: 1 },
});
const revisionMarkers = folded.items.filter(
(item) => item.kind === 'marker' && item.marker === 'plan.revision',
);
expect(revisionMarkers).toEqual([
{
kind: 'marker',
markerId: 'm3',
marker: 'plan.revision',
payload: {
id: 'plan-1',
version: 1,
path: 'sessions/w/s/agents/main/plan/plan-1/v1.md',
sha256: 'deadbeef',
bytes: 256,
},
at: new Date(2000).toISOString(),
},
]);
});
it('folds task records into task entities and timeline taskrefs', () => {
const base = baseWithMarker();
const folded = foldWireRecordFacts(
[
{
type: 'task.started',
info: {
taskId: 'task_1',
kind: 'process',
description: 'pnpm test',
status: 'running',
startedAt: 1000,
endedAt: null,
},
time: 1000,
},
{
type: 'task.started',
info: {
taskId: 'task_2',
kind: 'agent',
description: 'scan the repo',
status: 'running',
detached: false,
agentId: 'sub-1',
startedAt: 2000,
endedAt: null,
},
time: 2000,
},
{
type: 'task.terminated',
info: {
taskId: 'task_1',
kind: 'process',
description: 'pnpm test',
status: 'completed',
startedAt: 1000,
endedAt: 5000,
},
outputTail: '42 passed',
time: 5000,
},
],
base,
);
expect(folded.tasks).toEqual([
{
taskId: 'task_1',
kind: 'shell',
state: 'completed',
detached: true,
description: 'pnpm test',
agentId: undefined,
outputTail: '42 passed',
startedAt: new Date(1000).toISOString(),
endedAt: new Date(5000).toISOString(),
},
{
taskId: 'task_2',
kind: 'subagent',
state: 'running',
detached: false,
description: 'scan the repo',
agentId: 'sub-1',
outputTail: '',
startedAt: new Date(2000).toISOString(),
endedAt: undefined,
},
]);
const refs = folded.items.filter((item) => item.kind === 'taskref');
expect(refs).toEqual([
{ kind: 'taskref', refId: 'ref-task_1', taskId: 'task_1', at: new Date(1000).toISOString() },
{ kind: 'taskref', refId: 'ref-task_2', taskId: 'task_2', at: new Date(2000).toISOString() },
]);
});
it('maps unknown task kinds to other and survives malformed task records', () => {
const base = baseWithMarker();
const folded = foldWireRecordFacts(
[
{
type: 'task.started',
info: { taskId: 'task_q', kind: 'question', status: 'running', startedAt: 1000, endedAt: null },
time: 1000,
},
{ type: 'task.started', time: 2000 },
{ type: 'task.terminated', info: { kind: 'process' }, time: 3000 },
],
base,
);
expect(folded.tasks).toHaveLength(1);
expect(folded.tasks[0]).toMatchObject({ taskId: 'task_q', kind: 'other', state: 'running' });
});
it('folds interaction request/resolved into entities with terminal states', () => {
const base = baseWithMarker();
const folded = foldWireRecordFacts(
[
{
type: 'interaction.request',
id: 'apr-1',
kind: 'approval',
toolCallId: 'call_1',
request: { toolName: 'Bash' },
time: 1000,
},
{
type: 'interaction.request',
id: 'q-1',
kind: 'question',
request: { questions: [] },
time: 2000,
},
{
type: 'interaction.resolved',
id: 'apr-1',
response: { decision: 'approved', scope: 'session' },
time: 3000,
},
{ type: 'interaction.resolved', id: 'q-1', response: null, time: 4000 },
],
base,
);
expect(folded.interactions).toEqual([
{
interactionId: 'apr-1',
interactionKind: 'approval',
toolCallId: 'call_1',
state: 'approved',
request: { toolName: 'Bash' },
response: { decision: 'approved', scope: 'session' },
},
{
interactionId: 'q-1',
interactionKind: 'question',
toolCallId: undefined,
state: 'dismissed',
request: { questions: [] },
response: null,
},
]);
});
it('cancels interactions still pending at the end of the scan (crash == cancelled)', () => {
const base = baseWithMarker();
const folded = foldWireRecordFacts(
[
{
type: 'interaction.request',
id: 'apr-9',
kind: 'approval',
request: { toolCallId: 'call_9', toolName: 'Write' },
time: 1000,
},
],
base,
);
expect(folded.interactions).toHaveLength(1);
expect(folded.interactions[0]).toMatchObject({
interactionId: 'apr-9',
state: 'cancelled',
toolCallId: 'call_9',
});
expect(folded.interactions.every((entity) => entity.state !== 'pending')).toBe(true);
});
it('skips user_tool interactions like the live path', () => {
const base = baseWithMarker();
const folded = foldWireRecordFacts(
[
{ type: 'interaction.request', id: 'ut-1', kind: 'user_tool', request: {}, time: 1000 },
{ type: 'interaction.resolved', id: 'ut-1', response: {}, time: 2000 },
] satisfies HistoryWireRecord[],
base,
);
expect(folded.interactions).toEqual([]);
});
it('folds turn.ended records into the matching turn items', () => {
const base = baseWithMarker();
const folded = foldWireRecordFacts(
[
{
type: 'turn.ended',
turnId: 0,
reason: 'failed',
error: { code: 'provider.overloaded', message: 'Overloaded', name: 'APIStatusError', retryable: true },
durationMs: 1234,
time: 5000,
},
],
base,
);
const turn = folded.items[0];
if (turn?.kind !== 'turn') throw new Error('expected turn');
expect(turn.state).toBe('failed');
expect(turn.error).toBe('Overloaded');
expect(turn.durationMs).toBe(1234);
expect(turn.endedAt).toBe(new Date(5000).toISOString());
expect(folded.items).toHaveLength(base.items.length);
});
it('applies turn.ended records last-wins per turn and folds blocked into failed', () => {
const base = baseWithMarker();
const folded = foldWireRecordFacts(
[
{ type: 'turn.ended', turnId: 0, reason: 'failed', error: { message: 'boom' }, time: 1000 },
{ type: 'turn.ended', turnId: 0, reason: 'cancelled', durationMs: 10, time: 2000 },
],
base,
);
const turn = folded.items[0];
if (turn?.kind !== 'turn') throw new Error('expected turn');
expect(turn.state).toBe('cancelled');
expect(turn.error).toBeUndefined();
expect(turn.durationMs).toBe(10);
expect(turn.endedAt).toBe(new Date(2000).toISOString());
const blocked = foldWireRecordFacts(
[{ type: 'turn.ended', turnId: 0, reason: 'blocked', time: 3000 }],
base,
);
const blockedTurn = blocked.items[0];
if (blockedTurn?.kind !== 'turn') throw new Error('expected turn');
expect(blockedTurn.state).toBe('failed');
});
it('ignores turn.ended records with unknown turn ids or malformed payloads', () => {
const base = baseWithMarker();
const folded = foldWireRecordFacts(
[
{ type: 'turn.ended', turnId: 9, reason: 'cancelled', time: 1000 },
{ type: 'turn.ended', reason: 'completed', time: 2000 },
{ type: 'turn.ended', turnId: 0, reason: 'not-a-reason', time: 3000 },
],
base,
);
const turn = folded.items[0];
if (turn?.kind !== 'turn') throw new Error('expected turn');
expect(turn.state).toBe('completed');
expect(turn.endedAt).toBe(new Date(3000).toISOString());
expect(folded.items).toHaveLength(base.items.length);
});
const baseWithSteps = (): AgentTranscriptSnapshot =>
groupMessagesIntoSnapshot([
{ role: 'user', content: [{ type: 'text', text: 'hi' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'first' }], toolCalls: [] },
{ role: 'assistant', content: [{ type: 'text', text: 'second' }], toolCalls: [] },
]);
it('folds turn.step.interrupted records into the matching step of the matching turn', () => {
const base = baseWithSteps();
const folded = foldWireRecordFacts(
[
{
type: 'turn.step.interrupted',
turnId: 0,
step: 2,
reason: 'user_cancelled',
message: 'stopped by user',
time: 4000,
},
{ type: 'turn.ended', turnId: 0, reason: 'cancelled', time: 5000 },
],
base,
);
const turn = folded.items[0];
if (turn?.kind !== 'turn') throw new Error('expected turn');
expect(turn.steps).toHaveLength(2);
expect(turn.steps[0]).toMatchObject({ ordinal: 1, state: 'completed' });
expect(turn.steps[0]?.endReason).toBeUndefined();
expect(turn.steps[1]).toMatchObject({
ordinal: 2,
state: 'interrupted',
endReason: 'user_cancelled',
endMessage: 'stopped by user',
endedAt: new Date(4000).toISOString(),
});
expect(turn.state).toBe('cancelled');
expect(folded.items).toHaveLength(base.items.length);
});
it('applies turn.step.interrupted last-wins per step and tolerates a missing message', () => {
const base = baseWithSteps();
const folded = foldWireRecordFacts(
[
{ type: 'turn.step.interrupted', turnId: 0, step: 1, reason: 'aborted', message: 'first', time: 1000 },
{ type: 'turn.step.interrupted', turnId: 0, step: 1, reason: 'max_steps', time: 2000 },
],
base,
);
const turn = folded.items[0];
if (turn?.kind !== 'turn') throw new Error('expected turn');
expect(turn.steps[0]).toMatchObject({
ordinal: 1,
state: 'interrupted',
endReason: 'max_steps',
endedAt: new Date(2000).toISOString(),
});
expect(turn.steps[0]?.endMessage).toBeUndefined();
expect(turn.steps[1]?.state).toBe('completed');
});
it('skips turn.step.interrupted records with unknown turn ids or missing reason', () => {
const base = baseWithSteps();
const folded = foldWireRecordFacts(
[
{ type: 'turn.step.interrupted', turnId: 9, step: 1, reason: 'error', time: 1000 },
{ type: 'turn.step.interrupted', turnId: 0, step: 1, time: 3000 },
],
base,
);
const turn = folded.items[0];
if (turn?.kind !== 'turn') throw new Error('expected turn');
expect(turn.steps.map((step) => step.state)).toEqual(['completed', 'completed']);
expect(turn.steps.every((step) => step.endReason === undefined)).toBe(true);
});
it('creates the interrupted step when the cold tree has no step with that ordinal', () => {
const base = baseWithSteps();
const folded = foldWireRecordFacts(
[
{
type: 'turn.step.interrupted',
turnId: 0,
step: 3,
reason: 'error',
message: 'all retries exhausted',
time: 2000,
},
{ type: 'turn.ended', turnId: 0, reason: 'failed', time: 3000 },
],
base,
);
const turn = folded.items[0];
if (turn?.kind !== 'turn') throw new Error('expected turn');
expect(turn.steps.map((step) => step.ordinal)).toEqual([1, 2, 3]);
expect(turn.steps[2]).toEqual({
kind: 'step',
stepId: 't0.3',
turnId: 't0',
ordinal: 3,
state: 'interrupted',
frames: [],
endedAt: new Date(2000).toISOString(),
endReason: 'error',
endMessage: 'all retries exhausted',
});
});
it('creates the interrupted step for a turn that produced no steps at all', () => {
const base = groupMessagesIntoSnapshot([
{ role: 'user', content: [{ type: 'text', text: 'hi' }], toolCalls: [], origin: { kind: 'user' } },
]);
const folded = foldWireRecordFacts(
[
{ type: 'turn.step.interrupted', turnId: 0, step: 1, reason: 'user_cancelled', time: 1000 },
{ type: 'turn.ended', turnId: 0, reason: 'cancelled', time: 2000 },
],
base,
);
const turn = folded.items[0];
if (turn?.kind !== 'turn') throw new Error('expected turn');
expect(turn.steps).toHaveLength(1);
expect(turn.steps[0]).toMatchObject({
stepId: 't0.1',
ordinal: 1,
state: 'interrupted',
endReason: 'user_cancelled',
endedAt: new Date(1000).toISOString(),
});
expect(turn.steps[0]?.endMessage).toBeUndefined();
});
it('ignores turn.step.retrying records in the cold fold', () => {
const base = baseWithSteps();
const folded = foldWireRecordFacts(
[
{
type: 'turn.step.retrying',
turnId: 0,
step: 1,
failedAttempt: 1,
nextAttempt: 2,
maxAttempts: 10,
delayMs: 500,
errorName: 'APIStatusError',
errorMessage: 'Overloaded',
statusCode: 429,
time: 1000,
},
],
base,
);
expect(folded).toEqual(base);
expect(folded.items).toBe(base.items);
});
it('matches durable turns by prompt identity after a context-only blocked prompt', () => {
const base = groupMessagesIntoSnapshot([
{ id: 'prompt-blocked', role: 'user', content: [{ type: 'text', text: 'blocked' }], toolCalls: [], origin: { kind: 'user' } },
{ id: 'prompt-live', role: 'user', content: [{ type: 'text', text: 'run' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'failed later' }], toolCalls: [] },
]);
const folded = foldWireRecordFacts(
[
{ type: 'turn.prompt', turnId: 2, input: [{ type: 'text', text: 'run' }], origin: { kind: 'user' }, promptId: 'prompt-live', time: 1 },
{ type: 'turn.ended', turnId: 2, reason: 'failed', error: { message: 'later failure' }, time: 2 },
],
base,
);
expect(folded.items).toHaveLength(2);
const blocked = folded.items[0];
const live = folded.items[1];
if (blocked?.kind !== 'turn' || live?.kind !== 'turn') throw new Error('expected turns');
expect(blocked.triggerPromptId).toBe('prompt-blocked');
expect(blocked.error).toBeUndefined();
expect(live.triggerPromptId).toBe('prompt-live');
expect(live.state).toBe('failed');
expect(live.error).toBe('later failure');
});
it('recovers legacy boundary identity past a context-only blocked prompt', () => {
const base = groupMessagesIntoSnapshot([
{ id: 'prompt-blocked', role: 'user', content: [{ type: 'text', text: 'blocked' }], toolCalls: [], origin: { kind: 'user' } },
{ id: 'prompt-real', role: 'user', content: [{ type: 'text', text: 'run' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'failed later' }], toolCalls: [] },
]);
const folded = foldWireRecordFacts(
[
{ type: 'context.append_message', message: { id: 'prompt-blocked', role: 'user', origin: { kind: 'user' } }, time: 1 },
{ type: 'turn.prompt', input: [{ type: 'text', text: 'run' }], origin: { kind: 'user' }, time: 2 },
{ type: 'context.append_message', message: { id: 'prompt-real', role: 'user', origin: { kind: 'user' } }, time: 3 },
{ type: 'turn.ended', turnId: 0, reason: 'failed', error: { message: 'legacy failure' }, time: 4 },
],
base,
);
const blocked = folded.items[0];
const real = folded.items[1];
if (blocked?.kind !== 'turn' || real?.kind !== 'turn') throw new Error('expected turns');
expect(blocked.error).toBeUndefined();
expect(real.triggerPromptId).toBe('prompt-real');
expect(real.state).toBe('failed');
expect(real.error).toBe('legacy failure');
});
it('retires an unmatched legacy empty boundary before a later blocked prompt', () => {
const base = groupMessagesIntoSnapshot([
{ role: 'assistant', content: [{ type: 'text', text: 'partial' }], toolCalls: [] },
{ id: 'prompt-blocked', role: 'user', content: [{ type: 'text', text: 'blocked' }], toolCalls: [], origin: { kind: 'user' } },
]);
const folded = foldWireRecordFacts(
[
{ type: 'turn.prompt', input: [], origin: { kind: 'user' }, time: 1 },
{ type: 'turn.ended', turnId: 0, reason: 'failed', error: { message: 'empty failure' }, time: 2 },
{ type: 'context.append_message', message: { id: 'prompt-blocked', role: 'user', origin: { kind: 'user' } }, time: 3 },
],
base,
);
const empty = folded.items[0];
const blocked = folded.items[1];
if (empty?.kind !== 'turn' || blocked?.kind !== 'turn') throw new Error('expected turns');
expect(empty.state).toBe('failed');
expect(empty.error).toBe('empty failure');
expect(blocked.triggerPromptId).toBe('prompt-blocked');
expect(blocked.error).toBeUndefined();
});
it('folds terminal facts for an empty prompt turn without a context identity', () => {
const base = groupMessagesIntoSnapshot([
{ role: 'assistant', content: [{ type: 'text', text: 'partial' }], toolCalls: [] },
]);
const folded = foldWireRecordFacts(
[
{ type: 'turn.prompt', input: [], origin: { kind: 'user' }, promptId: 'prompt-empty', time: 1 },
{ type: 'turn.ended', turnId: 0, reason: 'failed', error: { message: 'empty failure' }, time: 2 },
],
base,
);
const turn = folded.items[0];
if (turn?.kind !== 'turn') throw new Error('expected turn');
expect(turn.triggerPromptId).toBeUndefined();
expect(turn.state).toBe('failed');
expect(turn.error).toBe('empty failure');
});
it('does not let an empty prompt claim a later system continuation turn', () => {
const base = groupMessagesIntoSnapshot([
{ id: 'internal-prompt', role: 'user', content: [{ type: 'text', text: 'continue' }], toolCalls: [], origin: { kind: 'system_trigger', name: 'goal_continuation' } as { kind: string } },
{ role: 'assistant', content: [{ type: 'text', text: 'stopped' }], toolCalls: [] },
]);
const folded = foldWireRecordFacts(
[
{ type: 'turn.prompt', input: [], origin: { kind: 'user' }, promptId: 'prompt-empty', time: 1 },
{ type: 'turn.ended', turnId: 0, reason: 'failed', error: { message: 'empty failure' }, time: 2 },
{ type: 'turn.prompt', input: [{ type: 'text', text: 'continue' }], origin: { kind: 'system_trigger', name: 'goal_continuation' }, promptId: 'internal-prompt', time: 3 },
{ type: 'turn.ended', turnId: 1, reason: 'cancelled', durationMs: 10, time: 4 },
],
base,
);
const system = folded.items[0];
if (system?.kind !== 'turn') throw new Error('expected turn');
expect(system.triggerPromptId).toBeUndefined();
expect(system.state).toBe('cancelled');
expect(system.durationMs).toBe(10);
expect(system.error).toBeUndefined();
});
it('matches a system turn with internal prompt identity past a context-only blocked prompt', () => {
const base = groupMessagesIntoSnapshot([
{ id: 'prompt-blocked', role: 'user', content: [{ type: 'text', text: 'blocked' }], toolCalls: [], origin: { kind: 'user' } },
{ id: 'internal-prompt', role: 'user', content: [{ type: 'text', text: 'continue' }], toolCalls: [], origin: { kind: 'system_trigger', name: 'goal_continuation' } as { kind: string } },
{ role: 'assistant', content: [{ type: 'text', text: 'continuation failed' }], toolCalls: [] },
]);
const folded = foldWireRecordFacts(
[
{ type: 'turn.prompt', input: [{ type: 'text', text: 'continue' }], origin: { kind: 'system_trigger', name: 'goal_continuation' }, promptId: 'internal-prompt', time: 1 },
{ type: 'turn.ended', turnId: 0, reason: 'failed', error: { message: 'system failure' }, time: 2 },
],
base,
);
const blocked = folded.items[0];
const system = folded.items[1];
if (blocked?.kind !== 'turn' || system?.kind !== 'turn') throw new Error('expected turns');
expect(blocked.triggerPromptId).toBe('prompt-blocked');
expect(blocked.error).toBeUndefined();
expect(system.triggerPromptId).toBeUndefined();
expect(system.state).toBe('failed');
expect(system.error).toBe('system failure');
});
it('maps turn.ended around hidden retry turns replayed from the turn-clock records', () => {
const base = groupMessagesIntoSnapshot([
{ id: 'prompt-1', role: 'user', content: [{ type: 'text', text: 'one' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'a1' }], toolCalls: [] },
{ id: 'prompt-2', role: 'user', content: [{ type: 'text', text: 'two' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'a2' }], toolCalls: [] },
]);
const folded = foldWireRecordFacts(
[
{ type: 'turn.prompt', input: [{ type: 'text', text: 'one' }], origin: { kind: 'user' }, promptId: 'prompt-1', time: 1 },
{ type: 'turn.ended', turnId: 0, reason: 'completed', time: 2 },
{ type: 'turn.prompt', input: [], origin: { kind: 'retry' }, time: 3 },
{ type: 'turn.ended', turnId: 1, reason: 'failed', error: { message: 'retry boom' }, time: 4 },
{ type: 'turn.prompt', input: [{ type: 'text', text: 'two' }], origin: { kind: 'user' }, promptId: 'prompt-2', time: 5 },
{ type: 'turn.ended', turnId: 2, reason: 'cancelled', durationMs: 20, time: 6 },
],
base,
);
const first = folded.items[0];
if (first?.kind !== 'turn') throw new Error('expected turn');
expect(first.state).toBe('completed');
expect(first.triggerPromptId).toBe('prompt-1');
const second = folded.items[1];
if (second?.kind !== 'turn') throw new Error('expected turn');
expect(second.state).toBe('cancelled');
expect(second.triggerPromptId).toBe('prompt-2');
expect(second.error).toBeUndefined();
expect(second.durationMs).toBe(20);
});
it('maps turn.ended across queued-then-cancelled turn reservations', () => {
const base = groupMessagesIntoSnapshot([
{ id: 'prompt-1', role: 'user', content: [{ type: 'text', text: 'one' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'a1' }], toolCalls: [] },
{ id: 'prompt-2', role: 'user', content: [{ type: 'text', text: 'two' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'a2' }], toolCalls: [] },
]);
const folded = foldWireRecordFacts(
[
{ type: 'turn.prompt', input: [{ type: 'text', text: 'one' }], origin: { kind: 'user' }, time: 1 },
{ type: 'turn.ended', turnId: 0, reason: 'completed', time: 2 },
{ type: 'turn.cancel', turnId: 1, target: 'queued', time: 3 },
{ type: 'turn.prompt', input: [{ type: 'text', text: 'two' }], origin: { kind: 'user' }, promptId: 'prompt-2', time: 4 },
{ type: 'turn.ended', turnId: 2, reason: 'failed', error: { message: 'boom' }, time: 5 },
],
base,
);
const second = folded.items[1];
if (second?.kind !== 'turn') throw new Error('expected turn');
expect(second.state).toBe('failed');
expect(second.error).toBe('boom');
expect(second.triggerPromptId).toBe('prompt-2');
});
it('skips undone turn boundaries when mapping prompt ids and turn endings', () => {
const base = groupMessagesIntoSnapshot([
{ id: 'prompt-1', role: 'user', content: [{ type: 'text', text: 'one' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'a1' }], toolCalls: [] },
{ id: 'prompt-3', role: 'user', content: [{ type: 'text', text: 'replacement' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'a3' }], toolCalls: [] },
]);
const folded = foldWireRecordFacts(
[
{ type: 'turn.prompt', input: [{ type: 'text', text: 'one' }], origin: { kind: 'user' }, promptId: 'prompt-1', time: 1 },
{ type: 'context.append_message', message: { id: 'prompt-1', role: 'user', origin: { kind: 'user' } }, time: 1.5 },
{ type: 'turn.ended', turnId: 0, reason: 'completed', time: 2 },
{ type: 'turn.prompt', input: [{ type: 'text', text: 'undone' }], origin: { kind: 'user' }, promptId: 'prompt-2', time: 3 },
{ type: 'context.append_message', message: { id: 'prompt-2', role: 'user', origin: { kind: 'user' } }, time: 3.5 },
{ type: 'turn.ended', turnId: 1, reason: 'completed', time: 4 },
{ type: 'turn.prompt', input: [{ type: 'text', text: 'continue' }], origin: { kind: 'system_trigger', name: 'goal_continuation' }, time: 5 },
{ type: 'turn.ended', turnId: 2, reason: 'completed', time: 6 },
{ type: 'context.undo', count: 1, time: 7 },
{ type: 'turn.prompt', input: [{ type: 'text', text: 'replacement' }], origin: { kind: 'user' }, promptId: 'prompt-3', time: 8 },
{ type: 'turn.ended', turnId: 3, reason: 'failed', error: { message: 'replacement failed' }, time: 9 },
],
base,
);
const replacement = folded.items[1];
if (replacement?.kind !== 'turn') throw new Error('expected turn');
expect(replacement.triggerPromptId).toBe('prompt-3');
expect(replacement.state).toBe('failed');
expect(replacement.error).toBe('replacement failed');
});
it('counts context-only blocked prompts as undo anchors', () => {
const base = groupMessagesIntoSnapshot([
{ id: 'prompt-real', role: 'user', content: [{ type: 'text', text: 'real' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'failed' }], toolCalls: [] },
]);
const folded = foldWireRecordFacts(
[
{ type: 'turn.prompt', input: [{ type: 'text', text: 'real' }], origin: { kind: 'user' }, promptId: 'prompt-real', time: 1 },
{ type: 'context.append_message', message: { id: 'prompt-real', role: 'user', origin: { kind: 'user' } }, time: 2 },
{ type: 'turn.ended', turnId: 0, reason: 'failed', error: { message: 'real failure' }, time: 3 },
{ type: 'context.append_message', message: { id: 'prompt-blocked', role: 'user', origin: { kind: 'user' } }, time: 4 },
{ type: 'context.undo', count: 1, time: 5 },
],
base,
);
const real = folded.items[0];
if (real?.kind !== 'turn') throw new Error('expected turn');
expect(real.triggerPromptId).toBe('prompt-real');
expect(real.state).toBe('failed');
expect(real.error).toBe('real failure');
});
it('does not consume a pending identity boundary for a different context-only anchor', () => {
const base = groupMessagesIntoSnapshot([
{ id: 'prompt-real', role: 'user', content: [{ type: 'text', text: 'real' }], toolCalls: [], origin: { kind: 'user' } },
{ role: 'assistant', content: [{ type: 'text', text: 'failed' }], toolCalls: [] },
]);
const folded = foldWireRecordFacts(
[
{ type: 'turn.prompt', input: [{ type: 'text', text: 'real' }], origin: { kind: 'user' }, promptId: 'prompt-real', time: 1 },
{ type: 'context.append_message', message: { id: 'prompt-blocked', role: 'user', origin: { kind: 'user' } }, time: 2 },
{ type: 'context.undo', count: 1, time: 3 },
{ type: 'context.append_message', message: { id: 'prompt-real', role: 'user', origin: { kind: 'user' } }, time: 4 },
{ type: 'turn.ended', turnId: 0, reason: 'failed', error: { message: 'real failure' }, time: 5 },
],
base,
);
const real = folded.items[0];
if (real?.kind !== 'turn') throw new Error('expected turn');
expect(real.state).toBe('failed');
expect(real.error).toBe('real failure');
});
});
|