@mmnto/cli 1.56.0 → 1.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1205,4 +1205,476 @@ describe('runOrchestrator artifact emission (#2100)', { timeout: 15_000 }, () =>
1205
1205
  expect(artifact.output.content).toBe('fallback result');
1206
1206
  });
1207
1207
  });
1208
+ // ─── runOrchestrator admission contract (mmnto-ai/totem#2102) ──
1209
+ describe('runOrchestrator admission contract (#2102)', { timeout: 15_000 }, () => {
1210
+ let tmpDir;
1211
+ const GROUNDING_HASH = 'b'.repeat(64);
1212
+ function artifactRequest(onEmitted) {
1213
+ return {
1214
+ groundingHash: GROUNDING_HASH,
1215
+ provenanceSummary: 'similarity-only',
1216
+ ...(onEmitted !== undefined ? { onEmitted } : {}),
1217
+ };
1218
+ }
1219
+ /** Orchestrator config WITHOUT a declared capability (today's default). */
1220
+ function plainConfig(overrides) {
1221
+ return {
1222
+ targets: [{ glob: '**/*.ts', type: 'code', strategy: 'typescript-ast' }],
1223
+ orchestrator: {
1224
+ provider: 'gemini',
1225
+ defaultModel: 'gemini-3-flash-preview',
1226
+ },
1227
+ totemDir: '.totem',
1228
+ lanceDir: '.lancedb',
1229
+ ignorePatterns: [],
1230
+ contextWarningThreshold: 40_000,
1231
+ ...overrides,
1232
+ };
1233
+ }
1234
+ /** Orchestrator config that DECLARES self_grounding_agent capability. */
1235
+ function declaredConfig(orchestratorOverrides) {
1236
+ const base = plainConfig();
1237
+ return {
1238
+ ...base,
1239
+ orchestrator: {
1240
+ ...base.orchestrator,
1241
+ capabilities: { admissionClasses: ['self_grounding_agent'] },
1242
+ ...orchestratorOverrides,
1243
+ },
1244
+ };
1245
+ }
1246
+ function runsDirPath() {
1247
+ return path.join(tmpDir, '.totem', 'artifacts', 'runs');
1248
+ }
1249
+ function readArtifact(hash) {
1250
+ const file = path.join(runsDirPath(), `${hash}.json`);
1251
+ return RunArtifactSchema.parse(JSON.parse(fs.readFileSync(file, 'utf-8')));
1252
+ }
1253
+ beforeEach(() => {
1254
+ vi.clearAllMocks();
1255
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'totem-admission-'));
1256
+ vi.spyOn(process, 'cwd').mockReturnValue(tmpDir);
1257
+ const mockInvoke = vi.fn().mockResolvedValue({
1258
+ content: 'mock result',
1259
+ inputTokens: 100,
1260
+ outputTokens: 50,
1261
+ durationMs: 500,
1262
+ });
1263
+ mockedCreateOrchestrator.mockReturnValue(mockInvoke);
1264
+ });
1265
+ afterEach(() => {
1266
+ vi.restoreAllMocks();
1267
+ cleanTmpDir(tmpDir);
1268
+ });
1269
+ it('omitting every new field yields a byte-identical invoke payload and identical artifact backend (invariant 1)', async () => {
1270
+ const emitted = [];
1271
+ await runOrchestrator({
1272
+ prompt: 'test prompt',
1273
+ tag: 'Spec',
1274
+ options: { fresh: true },
1275
+ config: plainConfig(),
1276
+ cwd: tmpDir,
1277
+ artifact: artifactRequest((hash) => emitted.push(hash)),
1278
+ });
1279
+ // Byte-identical provider payload: the EXACT pre-#2102 key set, no
1280
+ // admission transport keys of any kind.
1281
+ const invoke = mockedCreateOrchestrator.mock.results[0].value;
1282
+ expect(invoke.mock.calls[0][0]).toStrictEqual({
1283
+ prompt: 'test prompt',
1284
+ model: 'gemini-3-flash-preview',
1285
+ cwd: tmpDir,
1286
+ tag: 'Spec',
1287
+ totemDir: '.totem',
1288
+ temperature: undefined,
1289
+ });
1290
+ // Identical artifact backend — decided by DEFAULT now, not constant.
1291
+ const artifact = readArtifact(emitted[0]);
1292
+ expect(artifact.backend.admissionClass).toBe('completion_only');
1293
+ expect(artifact.backend.taskProfile).toBe('Spec');
1294
+ expect(artifact.admission).toBeUndefined();
1295
+ });
1296
+ it('a requested-but-undeclared admission class fails loud before any invoke — no tokens, no artifact (invariant 2)', async () => {
1297
+ await expect(runOrchestrator({
1298
+ prompt: 'elevated request',
1299
+ tag: 'Spec',
1300
+ options: { fresh: true },
1301
+ config: plainConfig(), // no capabilities declared
1302
+ cwd: tmpDir,
1303
+ backendAdmissionClass: 'self_grounding_agent',
1304
+ artifact: artifactRequest(),
1305
+ })).rejects.toThrow(/self_grounding_agent/);
1306
+ const invoke = mockedCreateOrchestrator.mock.results[0]?.value;
1307
+ if (invoke !== undefined) {
1308
+ expect(invoke).not.toHaveBeenCalled();
1309
+ }
1310
+ expect(fs.existsSync(path.join(tmpDir, '.totem', 'artifacts'))).toBe(false);
1311
+ });
1312
+ it('the admitted class lands in backend.admissionClass verbatim; taskProfile records task ?? tag (invariant 3)', async () => {
1313
+ const emitted = [];
1314
+ await runOrchestrator({
1315
+ prompt: 'admitted run',
1316
+ tag: 'Spec',
1317
+ options: { fresh: true },
1318
+ config: declaredConfig(),
1319
+ cwd: tmpDir,
1320
+ backendAdmissionClass: 'self_grounding_agent',
1321
+ task: 'eval-fixture',
1322
+ artifact: artifactRequest((hash) => emitted.push(hash)),
1323
+ });
1324
+ const artifact = readArtifact(emitted[0]);
1325
+ expect(artifact.backend.admissionClass).toBe('self_grounding_agent');
1326
+ expect(artifact.backend.taskProfile).toBe('eval-fixture');
1327
+ });
1328
+ it('inputHash is unaffected by every new contract field (invariant 4)', async () => {
1329
+ const emitted = [];
1330
+ const shared = {
1331
+ prompt: 'identical prompt',
1332
+ tag: 'Spec',
1333
+ options: { fresh: true },
1334
+ config: declaredConfig(),
1335
+ cwd: tmpDir,
1336
+ };
1337
+ await runOrchestrator({
1338
+ ...shared,
1339
+ artifact: artifactRequest((hash) => emitted.push(hash)),
1340
+ });
1341
+ await runOrchestrator({
1342
+ ...shared,
1343
+ task: 'eval-fixture',
1344
+ backendAdmissionClass: 'self_grounding_agent',
1345
+ contextPolicy: { budget: 8000 },
1346
+ outputContract: { citationsRequired: true },
1347
+ runMetadata: { caller: 'test' },
1348
+ artifact: artifactRequest((hash) => emitted.push(hash)),
1349
+ });
1350
+ const bare = readArtifact(emitted[0]);
1351
+ const hydrated = readArtifact(emitted[1]);
1352
+ expect(hydrated.inputHash).toBe(bare.inputHash);
1353
+ });
1354
+ it('a provider-qualified PRIMARY that resolves cross-provider under an elevated class is denied BEFORE the invoke', async () => {
1355
+ // #2148 round-1 (CR major + Greptile P2): the capability declaration is
1356
+ // config-level (base-provider scoped), but `resolveOrchestrator` can route
1357
+ // a provider-qualified primary model to a DIFFERENT provider — the gate
1358
+ // must hold per RESOLVED backend on the primary path too, not just the
1359
+ // quota-fallback path.
1360
+ const onEmitted = vi.fn();
1361
+ await expect(runOrchestrator({
1362
+ prompt: 'cross-provider elevated primary',
1363
+ tag: 'Spec',
1364
+ options: { fresh: true, model: 'anthropic:claude-sonnet-4-6' },
1365
+ config: declaredConfig(), // gemini base config WITH self_grounding_agent declared
1366
+ cwd: tmpDir,
1367
+ backendAdmissionClass: 'self_grounding_agent',
1368
+ artifact: { ...artifactRequest(), onEmitted },
1369
+ })).rejects.toThrow(/cross-provider routing is not admitted/i);
1370
+ // ZERO invokes: every orchestrator the mocked factory handed out stayed idle.
1371
+ for (const created of mockedCreateOrchestrator.mock.results) {
1372
+ expect(created.value).not.toHaveBeenCalled();
1373
+ }
1374
+ expect(onEmitted).not.toHaveBeenCalled();
1375
+ expect(fs.existsSync(path.join(tmpDir, '.totem', 'artifacts'))).toBe(false);
1376
+ });
1377
+ it('a declared self_grounding_agent run whose quota fallback resolves cross-provider fails BEFORE the fallback invoke (invariant 5)', async () => {
1378
+ const quotaErr = new Error('429 quota exhausted');
1379
+ quotaErr.name = 'QuotaError';
1380
+ const mockInvoke = vi.fn().mockRejectedValueOnce(quotaErr).mockResolvedValue({
1381
+ content: 'fallback result',
1382
+ durationMs: 300,
1383
+ });
1384
+ mockedCreateOrchestrator.mockReturnValue(mockInvoke);
1385
+ const onEmitted = vi.fn();
1386
+ await expect(runOrchestrator({
1387
+ prompt: 'elevated quota-bound run',
1388
+ tag: 'Spec',
1389
+ options: { fresh: true },
1390
+ config: declaredConfig({ fallbackModel: 'anthropic:claude-sonnet-4-6' }),
1391
+ cwd: tmpDir,
1392
+ backendAdmissionClass: 'self_grounding_agent',
1393
+ artifact: { ...artifactRequest(), onEmitted },
1394
+ })).rejects.toThrow(/429 quota exhausted[\s\S]*self_grounding_agent/);
1395
+ // Exactly ONE invoke: the primary. The cross-provider fallback was never invoked.
1396
+ expect(mockInvoke).toHaveBeenCalledTimes(1);
1397
+ expect(onEmitted).not.toHaveBeenCalled();
1398
+ });
1399
+ it('a same-provider quota fallback under an elevated class is admitted', async () => {
1400
+ const quotaErr = new Error('429 quota exhausted');
1401
+ quotaErr.name = 'QuotaError';
1402
+ const mockInvoke = vi.fn().mockRejectedValueOnce(quotaErr).mockResolvedValue({
1403
+ content: 'fallback result',
1404
+ durationMs: 300,
1405
+ });
1406
+ mockedCreateOrchestrator.mockReturnValue(mockInvoke);
1407
+ const emitted = [];
1408
+ const result = await runOrchestrator({
1409
+ prompt: 'elevated quota-bound run',
1410
+ tag: 'Spec',
1411
+ options: { fresh: true },
1412
+ config: declaredConfig({
1413
+ defaultModel: 'gemini-3.1-pro-preview',
1414
+ fallbackModel: 'gemini-3-flash-preview',
1415
+ }),
1416
+ cwd: tmpDir,
1417
+ backendAdmissionClass: 'self_grounding_agent',
1418
+ artifact: artifactRequest((hash) => emitted.push(hash)),
1419
+ });
1420
+ expect(result).toBe('fallback result');
1421
+ const artifact = readArtifact(emitted[0]);
1422
+ expect(artifact.backend.admissionClass).toBe('self_grounding_agent');
1423
+ expect(artifact.backend.qualifiedModel).toBe('gemini-3-flash-preview');
1424
+ });
1425
+ it('records the admission group only when at least one member is supplied', async () => {
1426
+ const emitted = [];
1427
+ const admission = {
1428
+ outputContract: { citationsRequired: true, verifyFallback: true },
1429
+ contextPolicy: { budget: 16_000 },
1430
+ runMetadata: { caller: 'test', command: 'spec' },
1431
+ };
1432
+ await runOrchestrator({
1433
+ prompt: 'contract run',
1434
+ tag: 'Spec',
1435
+ options: { fresh: true },
1436
+ config: plainConfig(),
1437
+ cwd: tmpDir,
1438
+ ...admission,
1439
+ artifact: artifactRequest((hash) => emitted.push(hash)),
1440
+ });
1441
+ // Class-only run: backendAdmissionClass is recorded in backend, NOT the group.
1442
+ await runOrchestrator({
1443
+ prompt: 'class-only run',
1444
+ tag: 'Spec',
1445
+ options: { fresh: true },
1446
+ config: declaredConfig(),
1447
+ cwd: tmpDir,
1448
+ backendAdmissionClass: 'self_grounding_agent',
1449
+ artifact: artifactRequest((hash) => emitted.push(hash)),
1450
+ });
1451
+ const withGroup = readArtifact(emitted[0]);
1452
+ expect(withGroup.admission).toEqual(admission);
1453
+ const classOnlyRaw = fs.readFileSync(path.join(runsDirPath(), `${emitted[1]}.json`), 'utf-8');
1454
+ expect(JSON.parse(classOnlyRaw)).not.toHaveProperty('admission');
1455
+ });
1456
+ it('threads the supplied transport fields to the provider invoke verbatim', async () => {
1457
+ await runOrchestrator({
1458
+ prompt: 'threaded run',
1459
+ tag: 'Spec',
1460
+ options: { fresh: true },
1461
+ config: declaredConfig(),
1462
+ cwd: tmpDir,
1463
+ task: 'eval-fixture',
1464
+ backendAdmissionClass: 'self_grounding_agent',
1465
+ contextPolicy: { budget: 8000 },
1466
+ outputContract: { citationsRequired: true },
1467
+ runMetadata: { caller: 'test' },
1468
+ });
1469
+ const invoke = mockedCreateOrchestrator.mock.results[0].value;
1470
+ expect(invoke).toHaveBeenCalledWith(expect.objectContaining({
1471
+ task: 'eval-fixture',
1472
+ backendAdmissionClass: 'self_grounding_agent',
1473
+ contextPolicy: { budget: 8000 },
1474
+ outputContract: { citationsRequired: true },
1475
+ runMetadata: { caller: 'test' },
1476
+ }));
1477
+ });
1478
+ it('mismatched groundingBundle and artifact.bundle is an ambiguous grounding identity — hard error before invoke', async () => {
1479
+ const bundleA = {
1480
+ items: [
1481
+ {
1482
+ provenance: 'similarity-only',
1483
+ contentHash: 'c'.repeat(64),
1484
+ sourceType: 'code',
1485
+ filePath: 'src/a.ts',
1486
+ },
1487
+ ],
1488
+ };
1489
+ const bundleB = {
1490
+ items: [
1491
+ {
1492
+ provenance: 'similarity-only',
1493
+ contentHash: 'd'.repeat(64),
1494
+ sourceType: 'code',
1495
+ filePath: 'src/b.ts',
1496
+ },
1497
+ ],
1498
+ };
1499
+ await expect(runOrchestrator({
1500
+ prompt: 'ambiguous run',
1501
+ tag: 'Spec',
1502
+ options: { fresh: true },
1503
+ config: plainConfig(),
1504
+ cwd: tmpDir,
1505
+ groundingBundle: bundleA,
1506
+ artifact: {
1507
+ groundingHash: calculateDeterministicHash(bundleB),
1508
+ provenanceSummary: summarizeProvenance(bundleB),
1509
+ bundle: bundleB,
1510
+ },
1511
+ })).rejects.toThrow(/ambiguous grounding identity/i);
1512
+ const invoke = mockedCreateOrchestrator.mock.results[0]?.value;
1513
+ if (invoke !== undefined) {
1514
+ expect(invoke).not.toHaveBeenCalled();
1515
+ }
1516
+ });
1517
+ it('a supplied groundingBundle flows into the artifact bundle role when artifact.bundle is absent', async () => {
1518
+ const bundle = {
1519
+ items: [
1520
+ {
1521
+ provenance: 'similarity-only',
1522
+ contentHash: 'c'.repeat(64),
1523
+ sourceType: 'code',
1524
+ filePath: 'src/x.ts',
1525
+ },
1526
+ ],
1527
+ };
1528
+ const emitted = [];
1529
+ await runOrchestrator({
1530
+ prompt: 'bundle-flow run',
1531
+ tag: 'Spec',
1532
+ options: { fresh: true },
1533
+ config: plainConfig(),
1534
+ cwd: tmpDir,
1535
+ groundingBundle: bundle,
1536
+ artifact: {
1537
+ groundingHash: calculateDeterministicHash(bundle),
1538
+ provenanceSummary: summarizeProvenance(bundle),
1539
+ onEmitted: (hash) => emitted.push(hash),
1540
+ },
1541
+ });
1542
+ const artifact = readArtifact(emitted[0]);
1543
+ expect(artifact.grounding.bundle).toEqual(bundle);
1544
+ // #2148 round-1: the recorded hash must recompute from the recorded
1545
+ // bundle — the adopted-bundle path verifies the attested hash (never
1546
+ // recomputes it) before recording.
1547
+ expect(artifact.grounding.hash).toBe(calculateDeterministicHash(artifact.grounding.bundle));
1548
+ });
1549
+ it('an adopted groundingBundle whose hash mismatches artifact.groundingHash is rejected before invoke (verify-and-reject)', async () => {
1550
+ // #2148 round-1: with `artifact.bundle` omitted, the artifact records the
1551
+ // ADOPTED `opts.groundingBundle` but used to trust `artifact.groundingHash`
1552
+ // verbatim — persisting a record whose grounding.hash does not match its
1553
+ // grounding.bundle. The seam records, never re-derives, so the fix is
1554
+ // verify-and-reject, not recompute.
1555
+ const bundle = {
1556
+ items: [
1557
+ {
1558
+ provenance: 'similarity-only',
1559
+ contentHash: 'c'.repeat(64),
1560
+ sourceType: 'code',
1561
+ filePath: 'src/x.ts',
1562
+ },
1563
+ ],
1564
+ };
1565
+ await expect(runOrchestrator({
1566
+ prompt: 'forged grounding hash',
1567
+ tag: 'Spec',
1568
+ options: { fresh: true },
1569
+ config: plainConfig(),
1570
+ cwd: tmpDir,
1571
+ groundingBundle: bundle,
1572
+ artifact: {
1573
+ groundingHash: 'e'.repeat(64), // does NOT recompute from the adopted bundle
1574
+ provenanceSummary: 'similarity-only:1',
1575
+ },
1576
+ })).rejects.toThrow(/ambiguous grounding identity/i);
1577
+ const invoke = mockedCreateOrchestrator.mock.results[0]?.value;
1578
+ if (invoke !== undefined) {
1579
+ expect(invoke).not.toHaveBeenCalled();
1580
+ }
1581
+ expect(fs.existsSync(path.join(tmpDir, '.totem', 'artifacts'))).toBe(false);
1582
+ });
1583
+ it('a supplied artifact.bundle flows into the invoke-seam groundingBundle role', async () => {
1584
+ const bundle = {
1585
+ items: [
1586
+ {
1587
+ provenance: 'similarity-only',
1588
+ contentHash: 'c'.repeat(64),
1589
+ sourceType: 'code',
1590
+ filePath: 'src/x.ts',
1591
+ },
1592
+ ],
1593
+ };
1594
+ await runOrchestrator({
1595
+ prompt: 'bundle-flow run',
1596
+ tag: 'Spec',
1597
+ options: { fresh: true },
1598
+ config: plainConfig(),
1599
+ cwd: tmpDir,
1600
+ artifact: {
1601
+ groundingHash: calculateDeterministicHash(bundle),
1602
+ provenanceSummary: summarizeProvenance(bundle),
1603
+ bundle,
1604
+ },
1605
+ });
1606
+ const invoke = mockedCreateOrchestrator.mock.results[0].value;
1607
+ expect(invoke).toHaveBeenCalledWith(expect.objectContaining({ groundingBundle: bundle }));
1608
+ });
1609
+ it('matching groundingBundle and artifact.bundle reconcile cleanly (no false ambiguity)', async () => {
1610
+ const bundle = {
1611
+ items: [
1612
+ {
1613
+ provenance: 'similarity-only',
1614
+ contentHash: 'c'.repeat(64),
1615
+ sourceType: 'code',
1616
+ filePath: 'src/x.ts',
1617
+ },
1618
+ ],
1619
+ };
1620
+ const emitted = [];
1621
+ const result = await runOrchestrator({
1622
+ prompt: 'reconciled run',
1623
+ tag: 'Spec',
1624
+ options: { fresh: true },
1625
+ config: plainConfig(),
1626
+ cwd: tmpDir,
1627
+ groundingBundle: bundle,
1628
+ artifact: {
1629
+ groundingHash: calculateDeterministicHash(bundle),
1630
+ provenanceSummary: summarizeProvenance(bundle),
1631
+ bundle,
1632
+ onEmitted: (hash) => emitted.push(hash),
1633
+ },
1634
+ });
1635
+ expect(result).toBe('mock result');
1636
+ expect(readArtifact(emitted[0]).grounding.bundle).toEqual(bundle);
1637
+ });
1638
+ // ─── Response-cache key carries the contract (#2148 round-1) ──
1639
+ it('absent contract fields leave the response-cache key byte-identical to the legacy shape (invariant 1 — legacy keys stay warm)', async () => {
1640
+ await runOrchestrator({
1641
+ prompt: 'cache key probe',
1642
+ tag: 'Spec', // Spec carries a default response-cache TTL
1643
+ options: {},
1644
+ config: plainConfig(),
1645
+ cwd: tmpDir,
1646
+ });
1647
+ // The exact legacy construction (see the null-byte delimiter test above):
1648
+ // prompt, systemPrompt, qualifiedModel — and NOTHING else when every
1649
+ // contract field is absent.
1650
+ const legacyHash = crypto
1651
+ .createHash('sha256')
1652
+ .update('cache key probe')
1653
+ .update('\0')
1654
+ .update('')
1655
+ .update('\0')
1656
+ .update('gemini-3-flash-preview')
1657
+ .digest('hex')
1658
+ .slice(0, 16);
1659
+ expect(fs.existsSync(path.join(tmpDir, '.totem', 'cache', `spec-${legacyHash}.json`))).toBe(true);
1660
+ });
1661
+ it('contract fields produce a distinct response-cache key, and differing in ONE contract field differs again (no aliasing)', async () => {
1662
+ const shared = {
1663
+ prompt: 'aliasing probe',
1664
+ tag: 'Spec', // Spec carries a default response-cache TTL
1665
+ options: {},
1666
+ config: plainConfig(),
1667
+ cwd: tmpDir,
1668
+ };
1669
+ await runOrchestrator(shared); // legacy-shaped
1670
+ await runOrchestrator({ ...shared, contextPolicy: { budget: 8000 } });
1671
+ await runOrchestrator({ ...shared, contextPolicy: { budget: 16_000 } });
1672
+ // Three ACTUAL invokes — a contract-bearing call must never be served the
1673
+ // legacy call's cached payload (or another contract's) as a replay.
1674
+ const invoke = mockedCreateOrchestrator.mock.results[0].value;
1675
+ expect(invoke).toHaveBeenCalledTimes(3);
1676
+ // …and three distinct cache keys on disk.
1677
+ expect(fs.readdirSync(path.join(tmpDir, '.totem', 'cache'))).toHaveLength(3);
1678
+ });
1679
+ });
1208
1680
  //# sourceMappingURL=utils.test.js.map