gestalt-mobile 0.56.0 → 0.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.
Files changed (39) hide show
  1. package/README.md +2 -1
  2. package/dist/client/assets/index-Cp-JfcNd.css +1 -0
  3. package/dist/client/assets/index-DeNYHfGR.js +123 -0
  4. package/dist/client/index.html +2 -2
  5. package/dist/server/client/features/chat/chat-projection.js +11 -0
  6. package/dist/server/server/cli.js +1 -1
  7. package/dist/server/server/composition.contracts.js +219 -1
  8. package/dist/server/server/composition.js +26 -1
  9. package/dist/server/server/config.js +1 -1
  10. package/dist/server/server/features/agent-activity/tool-efficiency-projection.js +179 -0
  11. package/dist/server/server/features/agent-activity/tool-efficiency.js +13 -0
  12. package/dist/server/server/features/catalog/get-xerj-status/endpoint.js +3 -1
  13. package/dist/server/server/features/control-plane-trace/export-trace.js +18 -3
  14. package/dist/server/server/features/sessions/get-history/endpoint.js +3 -0
  15. package/dist/server/server/features/sessions/get-retrieval-readiness/endpoint.js +19 -0
  16. package/dist/server/server/features/sessions/get-session/endpoint.js +3 -1
  17. package/dist/server/server/features/sessions/register-routes.js +7 -1
  18. package/dist/server/server/platform/codex/activity-facts.js +2 -0
  19. package/dist/server/server/platform/codex/codex-capabilities.js +4 -0
  20. package/dist/server/server/platform/codex/codex-serena.js +16 -3
  21. package/dist/server/server/platform/codex/mcp-startup-failure.js +96 -0
  22. package/dist/server/server/platform/codex/normalizer.js +69 -0
  23. package/dist/server/server/platform/codex/session-runtime.js +101 -4
  24. package/dist/server/server/platform/codex/tool-efficiency-facts.js +178 -0
  25. package/dist/server/server/platform/persistence/migrate.js +1 -0
  26. package/dist/server/server/platform/persistence/sqlite-event-journal.js +16 -0
  27. package/dist/server/server/platform/persistence/sqlite-tool-efficiency-store.js +23 -0
  28. package/dist/server/server/platform/retrieval/codex-xerj.js +17 -3
  29. package/dist/server/server/platform/retrieval/read-authority.js +55 -0
  30. package/dist/server/server/platform/retrieval/readiness-evidence.js +92 -0
  31. package/dist/server/server/platform/retrieval/repository-readiness.js +464 -0
  32. package/dist/server/server/platform/retrieval/xerj-indexer.js +19 -1
  33. package/dist/server/shared/contracts/mcp-startup-failure.js +158 -0
  34. package/dist/server/shared/contracts/retrieval-readiness.js +47 -0
  35. package/dist/server/shared/contracts/tool-efficiency.js +125 -0
  36. package/dist/server/shared/contracts/tool-efficiency.test-fixture.js +77 -0
  37. package/package.json +1 -1
  38. package/dist/client/assets/index-BIDTmI1d.css +0 -1
  39. package/dist/client/assets/index-UlRqhCZk.js +0 -116
@@ -16,8 +16,8 @@ SPDX-License-Identifier: AGPL-3.0-or-later
16
16
  <link rel="icon" href="/icons/gestalt-mobile-192.png" />
17
17
  <link rel="apple-touch-icon" href="/icons/gestalt-mobile-180.png" />
18
18
  <title>Gestalt Mobile</title>
19
- <script type="module" crossorigin src="/assets/index-UlRqhCZk.js"></script>
20
- <link rel="stylesheet" crossorigin href="/assets/index-BIDTmI1d.css">
19
+ <script type="module" crossorigin src="/assets/index-DeNYHfGR.js"></script>
20
+ <link rel="stylesheet" crossorigin href="/assets/index-Cp-JfcNd.css">
21
21
  </head>
22
22
  <body>
23
23
  <div id="app"></div>
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { autopilotAuditLabel, autopilotAuditAttention, } from '../../../shared/contracts/autopilot-audit.js';
7
7
  import { toActivity } from './activity-summary.js';
8
+ import { parseMcpStartupStatus } from '../../../shared/contracts/mcp-startup-failure.js';
8
9
  const empty = () => ({
9
10
  sessionId: null,
10
11
  cursor: 0,
@@ -328,6 +329,11 @@ export function hydrateCache(sessionId, cached) {
328
329
  value.deletions >= 0);
329
330
  }))) &&
330
331
  (activity.turnId === undefined || typeof activity.turnId === 'string')))
332
+ .map((activity) => {
333
+ const { mcpStartup, ...safe } = activity;
334
+ const status = parseMcpStartupStatus(mcpStartup);
335
+ return { ...safe, ...(status ? { mcpStartup: status } : {}) };
336
+ })
331
337
  .slice(-200)
332
338
  : [],
333
339
  prompts: candidate.prompts
@@ -406,6 +412,9 @@ export function acceptSnapshot(current, snapshot) {
406
412
  ...(item.actorTurnId ? { actorTurnId: item.actorTurnId } : {}),
407
413
  ...(item.occurredAt !== undefined ? { occurredAt: item.occurredAt } : {}),
408
414
  ...(item.changes ? { changes: item.changes } : {}),
415
+ ...(parseMcpStartupStatus(item.mcpStartup)
416
+ ? { mcpStartup: parseMcpStartupStatus(item.mcpStartup) }
417
+ : {}),
409
418
  }));
410
419
  const activities = canonicalActivities.reduce(upsertActivity, [...current.activities]);
411
420
  const turnTimes = new Map(snapshot.turns.map((turn) => [turn.id, turn]));
@@ -664,6 +673,7 @@ export function applyProjectionEvent(current, event) {
664
673
  typeof payload.label === 'string' &&
665
674
  typeof payload.detail === 'string') {
666
675
  const changes = safeFileChanges(payload.changes);
676
+ const mcpStartup = parseMcpStartupStatus(payload.mcpStartup);
667
677
  next = {
668
678
  ...next,
669
679
  activities: upsertActivity(next.activities, {
@@ -672,6 +682,7 @@ export function applyProjectionEvent(current, event) {
672
682
  detail: payload.detail,
673
683
  ...(occurredAt !== undefined ? { occurredAt } : {}),
674
684
  ...(changes.length ? { changes } : {}),
685
+ ...(mcpStartup ? { mcpStartup } : {}),
675
686
  ...(typeof payload.turnId === 'string'
676
687
  ? { turnId: payload.turnId }
677
688
  : next.activeTurnId
@@ -29,7 +29,7 @@ Options:
29
29
  --disable-passkey-auth Disable passkey access control (unsafe on shared or network hosts)
30
30
  --data-dir <path> Directory for persistent application data
31
31
  --icon <path> SVG or PNG used as the installed PWA application icon
32
- --xerj <mode> Source discovery: manual (default, no indexing), auto, off
32
+ --xerj <mode> Source discovery: auto (default, index and watch), manual, off
33
33
  --skills <profile> Use a global skill profile for every session
34
34
  --skills list List saved global skill profiles without starting the server
35
35
  --help Show this help
@@ -20,13 +20,14 @@ import { CodexJsonRpcError } from './platform/codex/json-rpc-client.js';
20
20
  import { CodexSessionRuntime } from './platform/codex/session-runtime.js';
21
21
  import { SqliteAuthorizationStore } from './platform/auth/sqlite-authorization-store.js';
22
22
  import { SqliteEventJournal } from './platform/persistence/sqlite-event-journal.js';
23
+ import { exportControlPlaneTrace } from './features/control-plane-trace/export-trace.js';
23
24
  import { authorizationSessionId, authorizedDeviceId, localOwnerId, webAuthnCredentialId, } from './features/auth/domain/identifiers.js';
24
25
  import { deviceNickname } from './features/auth/domain/device-nickname.js';
25
26
  import { workspaceId } from './platform/catalog/workspace-id.js';
26
27
  import { planStatusDirectoryPath, planStatusFilePath, } from './platform/plans/filesystem-plan-status-source.js';
27
28
  import { toOrgPlanAttentionAcknowledgement, toOrgPlanAttentionToolResponse, } from '../shared/contracts/org-plan-attention.js';
28
29
  import { toOrgPlanCheckpointToolResponse } from '../shared/contracts/org-plan-checkpoint.js';
29
- import { applyProjectionEvent, createChatProjection, } from '../client/features/chat/chat-projection.js';
30
+ import { applyProjectionEvent, createChatProjection, acceptSnapshot, } from '../client/features/chat/chat-projection.js';
30
31
  function fakeAppServer(calls) {
31
32
  return {
32
33
  rpc: {
@@ -5139,6 +5140,18 @@ describe('production composition', () => {
5139
5140
  ['GET', '/api/sessions/:id/plan', '/api/sessions/session-1/plan', 'protected'],
5140
5141
  ['HEAD', '/api/sessions/:id/plan', '/api/sessions/session-1/plan', 'protected'],
5141
5142
  ['DELETE', '/api/sessions/:id/plan', '/api/sessions/session-1/plan', 'protected'],
5143
+ [
5144
+ 'GET',
5145
+ '/api/sessions/:id/retrieval-readiness',
5146
+ '/api/sessions/session-1/retrieval-readiness',
5147
+ 'protected',
5148
+ ],
5149
+ [
5150
+ 'HEAD',
5151
+ '/api/sessions/:id/retrieval-readiness',
5152
+ '/api/sessions/session-1/retrieval-readiness',
5153
+ 'protected',
5154
+ ],
5142
5155
  [
5143
5156
  'POST',
5144
5157
  '/api/workspaces/:workspaceId/files/references',
@@ -5470,6 +5483,211 @@ describe('production composition', () => {
5470
5483
  });
5471
5484
  });
5472
5485
  describeCompositionConcern('sessions', () => {
5486
+ it('persists replay-stable tool groups from runtime notifications without charging provider tokens', async () => {
5487
+ const homeDirectory = await mkdtemp(join(tmpdir(), 'gestalt-efficiency-home-'));
5488
+ ownTemporaryPaths(homeDirectory);
5489
+ const { app, sessionId, handles, dataDir, root } = await createProductionAutopilotFixture({
5490
+ homeDirectory,
5491
+ });
5492
+ onTestFinished(() => app.close());
5493
+ await app.inject({
5494
+ method: 'PUT',
5495
+ url: `/api/sessions/${sessionId}/autopilot`,
5496
+ payload: { enabled: false },
5497
+ });
5498
+ const database = new DatabaseSync(join(dataDir, 'relay.sqlite'));
5499
+ onTestFinished(() => database.close());
5500
+ const journal = new SqliteEventJournal(database);
5501
+ const before = journal.currentSequence(sessionId);
5502
+ const handle = handles.findLast((candidate) => candidate.calls.includes('thread/start'));
5503
+ const threadId = (await app.inject(`/api/sessions/${sessionId}`)).json().threadId;
5504
+ const notify = (item, phase = 'item/completed', owner = threadId, turnId = 'turn') => handle.notify({
5505
+ method: phase,
5506
+ params: { ...(owner ? { threadId: owner } : {}), turnId, item },
5507
+ });
5508
+ notify({
5509
+ id: 'spawn',
5510
+ type: 'collabAgentToolCall',
5511
+ tool: 'spawnAgent',
5512
+ status: 'completed',
5513
+ senderThreadId: threadId,
5514
+ receiverThreadIds: ['child'],
5515
+ agentsStates: { child: { status: 'running' } },
5516
+ });
5517
+ const wrapper = {
5518
+ id: 'wrapper',
5519
+ type: 'dynamicToolCall',
5520
+ namespace: 'functions',
5521
+ tool: 'exec',
5522
+ status: 'completed',
5523
+ durationMs: 10,
5524
+ arguments: {
5525
+ code: 'await tools.exec_command({cmd:"secret nested"});\nawait tools.other()',
5526
+ },
5527
+ contentItems: [],
5528
+ };
5529
+ notify(wrapper);
5530
+ notify(wrapper);
5531
+ const command = {
5532
+ id: 'nested',
5533
+ type: 'commandExecution',
5534
+ status: 'completed',
5535
+ durationMs: 0,
5536
+ aggregatedOutput: '',
5537
+ command: 'synthetic command',
5538
+ };
5539
+ notify(command, 'item/started', 'child');
5540
+ notify(command, 'item/completed', 'child');
5541
+ notify(command, 'item/completed', 'child');
5542
+ notify(command, 'item/started', 'child');
5543
+ notify({ ...command, id: 'resumed', durationMs: null, aggregatedOutput: null }, 'item/completed', 'child', 'resumed-turn');
5544
+ notify({ ...wrapper, id: 'uncorrelated' }, 'item/completed', null, 'unknown-turn');
5545
+ handle.notify({
5546
+ method: 'thread/tokenUsage/updated',
5547
+ params: {
5548
+ threadId,
5549
+ tokenUsage: { last: { totalTokens: 500 }, total: { totalTokens: 1000 } },
5550
+ },
5551
+ });
5552
+ const snapshot = (await app.inject(`/api/sessions/${sessionId}`)).json()
5553
+ .toolEfficiency;
5554
+ expect(snapshot).toMatchObject({
5555
+ scope: 'observedCallsOnly',
5556
+ coverage: 'partial',
5557
+ missingCorrelation: true,
5558
+ retentionLimited: false,
5559
+ });
5560
+ expect(snapshot.groups).toHaveLength(3);
5561
+ expect(snapshot.groups.find((group) => group.layer === 'wrapper')).toMatchObject({
5562
+ actor: 'root',
5563
+ calls: 1,
5564
+ durationMs: { value: 10 },
5565
+ });
5566
+ expect(snapshot.groups.find((group) => group.threadId === 'child')).toMatchObject({
5567
+ actor: 'child',
5568
+ calls: 2,
5569
+ durationMs: { value: 0, measuredCalls: 1, coverage: 'partial' },
5570
+ });
5571
+ const replay = journal.replay(sessionId, before);
5572
+ if (replay.kind !== 'replay')
5573
+ throw new Error('Expected focused replay');
5574
+ const analytics = replay.events.filter((event) => event.type === 'tool.efficiency.updated');
5575
+ expect(analytics).toHaveLength(6);
5576
+ expect(analytics.at(-1)?.payload).toEqual(snapshot);
5577
+ expect(JSON.stringify(analytics)).not.toMatch(/secret|synthetic command|500|1000|nested/);
5578
+ const sameEvents = journal.currentSequence(sessionId);
5579
+ notify(wrapper);
5580
+ expect((await app.inject(`/api/sessions/${sessionId}`)).json().toolEfficiency).toEqual(snapshot);
5581
+ // Raw activity may publish independently; efficiency duplicates never publish another snapshot.
5582
+ const duplicateReplay = journal.replay(sessionId, sameEvents);
5583
+ if (duplicateReplay.kind !== 'replay')
5584
+ throw new Error('Expected bounded duplicate replay');
5585
+ expect(duplicateReplay.events.filter((event) => event.type === 'tool.efficiency.updated')).toEqual([]);
5586
+ await app.close();
5587
+ const reopened = await composeAuthorizedApp({
5588
+ root,
5589
+ dataDir,
5590
+ homeDirectory,
5591
+ relyingParty,
5592
+ installedCodexVersion: null,
5593
+ profiles: {
5594
+ list: async () => [],
5595
+ require: async () => ({ name: 'default', state: 'ok', status: 'ready' }),
5596
+ },
5597
+ });
5598
+ onTestFinished(() => reopened.close());
5599
+ expect((await reopened.inject(`/api/sessions/${sessionId}`)).json().toolEfficiency).toEqual(snapshot);
5600
+ });
5601
+ it('retains child MCP startup attempts through trace, activity, snapshot and reconnect without changing manual Off', async () => {
5602
+ const fixture = await createProductionAutopilotFixture();
5603
+ const { app, sessionId, handles, dataDir } = fixture;
5604
+ onTestFinished(() => app.close());
5605
+ expect((await app.inject({
5606
+ method: 'PUT',
5607
+ url: `/api/sessions/${sessionId}/autopilot`,
5608
+ payload: { enabled: false },
5609
+ })).statusCode).toBe(200);
5610
+ const databasePath = join(dataDir, 'relay.sqlite');
5611
+ const database = new DatabaseSync(databasePath);
5612
+ onTestFinished(() => database.close());
5613
+ const journal = new SqliteEventJournal(database);
5614
+ const before = journal.currentSequence(sessionId);
5615
+ const handle = handles.findLast((candidate) => candidate.calls.includes('thread/start'));
5616
+ const callsBefore = [...handle.calls];
5617
+ const notify = (status, name = 'context-mode', threadId = 'child-1') => handle.notify({
5618
+ method: 'mcpServer/startupStatus/updated',
5619
+ params: {
5620
+ name,
5621
+ status,
5622
+ threadId,
5623
+ error: 'TOKEN=secret prompt model output stderr',
5624
+ exitCode: 1,
5625
+ signal: 'SIGKILL',
5626
+ },
5627
+ });
5628
+ notify('starting');
5629
+ notify('failed');
5630
+ notify('failed');
5631
+ notify('failed', 'gestalt-serena');
5632
+ notify('failed', 'context-mode', 'child-2');
5633
+ notify('starting');
5634
+ notify('failed');
5635
+ const failureCut = journal.currentSequence(sessionId);
5636
+ const failureHistory = (await app.inject(`/api/sessions/${sessionId}/history`)).json();
5637
+ const beforeRecovery = failureHistory.activities.find((row) => row.mcpStartup?.threadId === 'child-1' && row.mcpStartup.serverName === 'context-mode');
5638
+ expect(beforeRecovery.mcpStartup).toMatchObject({
5639
+ status: 'failed',
5640
+ failure: { exitCode: null, signal: null },
5641
+ });
5642
+ notify('ready');
5643
+ notify('ready', 'context-mode', 'secret\nthread');
5644
+ const trace = exportControlPlaneTrace(databasePath, sessionId);
5645
+ const transitions = trace.events.filter((event) => event.type === 'agent.activity.mcp-startup');
5646
+ const statuses = transitions.map((event) => event.payload);
5647
+ const failures = statuses.filter((status) => status.failure);
5648
+ expect(failures).toHaveLength(4);
5649
+ const childFailures = failures.filter((status) => status.threadId === 'child-1' && status.serverName === 'context-mode');
5650
+ expect(childFailures).toHaveLength(2);
5651
+ expect(new Set(childFailures.map((status) => status.attemptId)).size).toBe(2);
5652
+ expect(new Set(statuses.map((status) => status.runtimeId)).size).toBe(1);
5653
+ expect(transitions
5654
+ .filter((event) => event.payload.failure)
5655
+ .map((event) => event.traceId)).toEqual(failures.map((status) => status.failure.failureId));
5656
+ expect(JSON.stringify(trace)).not.toMatch(/TOKEN|secret|prompt|stderr/);
5657
+ const history = (await app.inject(`/api/sessions/${sessionId}/history`)).json();
5658
+ const current = history.activities.filter((row) => row.mcpStartup);
5659
+ expect(current).toHaveLength(3);
5660
+ expect(current.find((row) => row.id === beforeRecovery.id).mcpStartup).toMatchObject({ status: 'ready', failure: null });
5661
+ expect(current.filter((row) => row.mcpStartup.status === 'failed')).toHaveLength(2);
5662
+ const hydrated = acceptSnapshot(createChatProjection(sessionId), history);
5663
+ expect(hydrated.activities.filter((row) => row.mcpStartup?.status === 'failed')).toHaveLength(2);
5664
+ expect(journal.replay(sessionId, before)).toMatchObject({ kind: 'replay' });
5665
+ const replay = journal.replay(sessionId, failureCut);
5666
+ if (replay.kind !== 'replay')
5667
+ throw new Error('Expected bounded replay');
5668
+ const recovered = replay.events.reduce((projection, event) => applyProjectionEvent(projection, event), acceptSnapshot(createChatProjection(sessionId), failureHistory));
5669
+ expect(recovered.activities.find((row) => row.id === beforeRecovery.id)?.mcpStartup).toMatchObject({ status: 'ready', failure: null });
5670
+ expect(handle.calls.filter((method) => method !== 'thread/read')).toEqual(callsBefore.filter((method) => method !== 'thread/read'));
5671
+ expect((await app.inject(`/api/sessions/${sessionId}`)).json()).toMatchObject({
5672
+ autopilot: { enabled: false },
5673
+ });
5674
+ await app.listen({ host: '127.0.0.1', port: 0 });
5675
+ const address = app.server.address();
5676
+ if (!address || typeof address === 'string')
5677
+ throw new Error('Expected TCP listener');
5678
+ const socket = new WebSocket(`ws://127.0.0.1:${address.port}/api/sessions/${sessionId}/events?after=${failureCut}`, {
5679
+ headers: {
5680
+ origin: relyingParty.publicOrigin,
5681
+ cookie: 'gestalt_mobile_session=test-session',
5682
+ },
5683
+ });
5684
+ onTestFinished(() => socket.close());
5685
+ const messages = [];
5686
+ socket.on('message', (data) => messages.push(JSON.parse(String(data))));
5687
+ await vi.waitFor(() => expect(messages.some((message) => message.event?.type === 'agent.activity.mcp-startup' &&
5688
+ message.event.payload?.status === 'ready')).toBe(true));
5689
+ expect(JSON.stringify(messages)).not.toMatch(/TOKEN|secret|stderr/);
5690
+ });
5473
5691
  it('hydrates chat and resyncs a large replay without materializing the journal', async () => {
5474
5692
  const fixture = await createProductionAutopilotFixture();
5475
5693
  const { app, sessionId } = fixture;
@@ -27,6 +27,7 @@ import { createRecentThreadLister } from './platform/codex/recent-thread-lister.
27
27
  import { CodexSessionRuntime } from './platform/codex/session-runtime.js';
28
28
  import { normalizeCodexNotification } from './platform/codex/normalizer.js';
29
29
  import { decodeCodexFailure } from './platform/codex/codex-failure.js';
30
+ import { parseMcpStartupStatus } from '../shared/contracts/mcp-startup-failure.js';
30
31
  import { KimiSessionRuntime } from './platform/kimi/kimi-session-runtime.js';
31
32
  import { KimiWebServerManager } from './platform/kimi/kimi-web-server-manager.js';
32
33
  import { KimiModelCatalog } from './platform/kimi/kimi-model-catalog.js';
@@ -55,7 +56,9 @@ import { mapWithConcurrency } from './platform/runtime/concurrency.js';
55
56
  import { RelaySession, } from './features/sessions/model/relay-session.js';
56
57
  import { AgentActivityRegistry } from './features/agent-activity/registry.js';
57
58
  import { toAgentActivityDto } from './features/agent-activity/activity-dto.js';
58
- import { decodeAgentActivityFacts } from './platform/codex/activity-facts.js';
59
+ import { decodeAgentActivityFacts, decodeToolEfficiencyFacts, } from './platform/codex/activity-facts.js';
60
+ import { ToolEfficiencyProjection } from './features/agent-activity/tool-efficiency-projection.js';
61
+ import { SqliteToolEfficiencyStore } from './platform/persistence/sqlite-tool-efficiency-store.js';
59
62
  import { completedCommandId, compactOrgPlanCheckpointKind, isAgentCapacityRecoveryCall, isAutopilotWaitLeaseCall, resolvedServerRequestId, toPendingInteraction, } from './platform/codex/server-request.js';
60
63
  import { parseOrgPlanCheckpoint, toOrgPlanCheckpointToolResponse, } from '../shared/contracts/org-plan-checkpoint.js';
61
64
  import { hasActiveL1Writer, resolveOrgPlanCheckpointSignal, validateOrgPlanCheckpoint, } from './features/org-plan-checkpoint/application/validate.js';
@@ -123,6 +126,7 @@ export async function composeRelayApp(options) {
123
126
  // reconciliation race their own owner.
124
127
  const persistedSessionIds = new Set(sessions.list().map((session) => session.id));
125
128
  const journal = new SqliteEventJournal(database);
129
+ const toolEfficiency = new ToolEfficiencyProjection(new SqliteToolEfficiencyStore(database));
126
130
  const interactions = new SqlitePendingInteractionStore(database);
127
131
  const idempotency = new SqliteIdempotencyStore(database);
128
132
  const autopilotStore = new SqliteAutopilotStore(database);
@@ -810,6 +814,12 @@ export async function composeRelayApp(options) {
810
814
  runtime = options.startAppServers
811
815
  ? new CodexSessionRuntime(options.launchAppServer ?? launchCodexAppServer, undefined, (sessionId, notification, origin) => {
812
816
  const occurredAt = new Date().toISOString();
817
+ if (notification.method === 'gestalt/mcpStartup') {
818
+ const status = parseMcpStartupStatus(notification.params);
819
+ if (!status)
820
+ return;
821
+ events.publish(journal.append(sessionId, 'agent.activity.mcp-startup', status, status.observedAt));
822
+ }
813
823
  const activityFacts = decodeAgentActivityFacts(sessionId, occurredAt, notification);
814
824
  const resolvedRequestId = resolvedServerRequestId(notification);
815
825
  if (resolvedRequestId) {
@@ -826,6 +836,19 @@ export async function composeRelayApp(options) {
826
836
  }
827
837
  }
828
838
  const currentSession = sessions.find(sessionId);
839
+ if (currentSession) {
840
+ for (const fact of decodeToolEfficiencyFacts(sessionId, occurredAt, notification, {
841
+ runtimeId: origin.runtimeId,
842
+ rootThreadId: currentSession.threadId ?? undefined,
843
+ physicalThreadId: origin.physicalThreadId,
844
+ physicalTurnId: origin.physicalTurnId,
845
+ actor: origin.kind,
846
+ })) {
847
+ const snapshot = toolEfficiency.observe(fact);
848
+ if (snapshot)
849
+ events.publish(journal.append(sessionId, 'tool.efficiency.updated', snapshot, occurredAt));
850
+ }
851
+ }
829
852
  const completionTurnId = notification.method === 'turn/completed' &&
830
853
  notification.params &&
831
854
  typeof notification.params === 'object' &&
@@ -1621,6 +1644,8 @@ export async function composeRelayApp(options) {
1621
1644
  planMeasurementRefresh?.refreshNow(session.id);
1622
1645
  },
1623
1646
  agentActivity: (id) => activity.snapshot(id, new Date().toISOString()),
1647
+ toolEfficiency: (id) => toolEfficiency.snapshot(id),
1648
+ retrievalReadiness: (id) => runtime?.readRetrievalReadiness(id) ?? Promise.resolve(null),
1624
1649
  autopilotSnapshot: (id) => autopilot.snapshot(id),
1625
1650
  autopilotControlTurns: (id) => autopilot.acceptedControlTurns(id),
1626
1651
  autopilotAudit: (id, limit) => journal.autopilotAuditTail(id, limit),
@@ -42,7 +42,7 @@ export function parseConfig(args, cwd = process.cwd()) {
42
42
  values.set(option, value);
43
43
  index += 1;
44
44
  }
45
- const xerj = values.get('--xerj') ?? 'manual';
45
+ const xerj = values.get('--xerj') ?? 'auto';
46
46
  if (xerj !== 'auto' && xerj !== 'manual' && xerj !== 'off')
47
47
  throw new CliUsageError('--xerj must be auto, manual, or off');
48
48
  const portValue = values.get('--port') ?? '3000';
@@ -0,0 +1,179 @@
1
+ /*
2
+ * Copyright (C) 2026 Dyne.org foundation
3
+ * Designed by Denis Roio <jaromil@dyne.org>
4
+ * SPDX-License-Identifier: AGPL-3.0-or-later
5
+ */
6
+ const empty = () => ({
7
+ calls: [],
8
+ observedAt: null,
9
+ missingCorrelation: false,
10
+ retentionLimited: false,
11
+ });
12
+ const callKey = (fact) => JSON.stringify([fact.identity.runtimeId, fact.identity.threadId, fact.itemId]);
13
+ const groupKey = (fact) => JSON.stringify([
14
+ fact.identity.runtimeId,
15
+ fact.identity.threadId,
16
+ fact.identity.actor,
17
+ fact.family,
18
+ ]);
19
+ const semantic = (fact) => JSON.stringify({ ...fact, occurredAt: undefined });
20
+ const retainKnown = (before, next) => (next.value === null ? before : next);
21
+ function mergeCall(before, next) {
22
+ return {
23
+ ...next,
24
+ duration: retainKnown(before.duration, next.duration),
25
+ retries: retainKnown(before.retries, next.retries),
26
+ reuse: retainKnown(before.reuse, next.reuse),
27
+ truncated: retainKnown(before.truncated, next.truncated),
28
+ bytes: {
29
+ raw: retainKnown(before.bytes.raw, next.bytes.raw),
30
+ processed: retainKnown(before.bytes.processed, next.bytes.processed),
31
+ delivered: retainKnown(before.bytes.delivered, next.bytes.delivered),
32
+ deliveredScope: next.bytes.delivered.value === null
33
+ ? before.bytes.deliveredScope
34
+ : next.bytes.deliveredScope,
35
+ },
36
+ completeness: {
37
+ capture: retainKnown(before.completeness.capture, next.completeness.capture),
38
+ display: retainKnown(before.completeness.display, next.completeness.display),
39
+ evidence: retainKnown(before.completeness.evidence, next.completeness.evidence),
40
+ },
41
+ coverage: before.coverage === 'partial' || next.coverage === 'partial' ? 'partial' : 'unknown',
42
+ };
43
+ }
44
+ /** Bounded content-free projection. Persistence is a port; no provider usage enters tool totals. */
45
+ export class ToolEfficiencyProjection {
46
+ store;
47
+ limits;
48
+ constructor(store, limits = { calls: 1024, groups: 64 }) {
49
+ this.store = store;
50
+ this.limits = limits;
51
+ }
52
+ observe(observation) {
53
+ if (observation.kind !== 'tool')
54
+ return null;
55
+ const { sessionId, runtimeId, threadId } = observation.identity;
56
+ const current = this.store.load(sessionId) ?? empty();
57
+ let next;
58
+ if (!runtimeId ||
59
+ !threadId ||
60
+ !observation.eventKey ||
61
+ observation.identity.actor === 'unknown') {
62
+ if (current.missingCorrelation)
63
+ return null;
64
+ next = {
65
+ ...current,
66
+ missingCorrelation: true,
67
+ observedAt: !current.observedAt || Date.parse(observation.occurredAt) > Date.parse(current.observedAt)
68
+ ? observation.occurredAt
69
+ : current.observedAt,
70
+ };
71
+ }
72
+ else {
73
+ const index = current.calls.findIndex((fact) => callKey(fact) === callKey(observation));
74
+ const before = current.calls[index];
75
+ if (before) {
76
+ if (before.phase === 'completed' && observation.phase === 'started')
77
+ return null;
78
+ if (before.phase === observation.phase &&
79
+ Date.parse(before.occurredAt) > Date.parse(observation.occurredAt))
80
+ return null;
81
+ const merged = mergeCall(before, observation);
82
+ if (semantic(before) === semantic(merged))
83
+ return null;
84
+ const calls = [...current.calls];
85
+ calls[index] = merged;
86
+ next = { ...current, calls };
87
+ }
88
+ else {
89
+ const groups = new Set(current.calls.map(groupKey));
90
+ if (current.calls.length >= this.limits.calls ||
91
+ (!groups.has(groupKey(observation)) && groups.size >= this.limits.groups)) {
92
+ if (current.retentionLimited)
93
+ return null;
94
+ next = { ...current, retentionLimited: true };
95
+ }
96
+ else
97
+ next = { ...current, calls: [...current.calls, observation] };
98
+ }
99
+ next = {
100
+ ...next,
101
+ observedAt: !current.observedAt || Date.parse(observation.occurredAt) > Date.parse(current.observedAt)
102
+ ? observation.occurredAt
103
+ : current.observedAt,
104
+ };
105
+ }
106
+ next = { ...next, revision: (current.revision ?? 0) + 1 };
107
+ this.store.save(sessionId, next);
108
+ return summarizeToolEfficiency(sessionId, next);
109
+ }
110
+ snapshot(sessionId) {
111
+ return summarizeToolEfficiency(sessionId, this.store.load(sessionId) ?? empty());
112
+ }
113
+ }
114
+ export function summarizeToolEfficiency(sessionId, state) {
115
+ const groups = new Map();
116
+ for (const fact of state.calls) {
117
+ const key = groupKey(fact);
118
+ groups.set(key, [...(groups.get(key) ?? []), fact]);
119
+ }
120
+ return {
121
+ sessionId,
122
+ revision: state.revision ?? 0,
123
+ observedAt: state.observedAt,
124
+ scope: 'observedCallsOnly',
125
+ coverage: state.calls.length || state.missingCorrelation || state.retentionLimited
126
+ ? 'partial'
127
+ : 'unknown',
128
+ missingCorrelation: state.missingCorrelation,
129
+ retentionLimited: state.retentionLimited,
130
+ groups: [...groups.entries()]
131
+ .sort(([a], [b]) => a.localeCompare(b))
132
+ .map(([, calls]) => summarizeGroup(calls)),
133
+ };
134
+ }
135
+ function summarizeGroup(calls) {
136
+ const first = calls[0];
137
+ const total = (read) => {
138
+ const known = calls.map(read).filter((value) => value !== null);
139
+ const sum = known.reduce((value, next) => value + Number(next), 0);
140
+ return {
141
+ value: known.length && Number.isSafeInteger(sum) ? sum : null,
142
+ measuredCalls: known.length,
143
+ coverage: !known.length
144
+ ? 'unknown'
145
+ : known.length === calls.length && Number.isSafeInteger(sum)
146
+ ? 'complete'
147
+ : 'partial',
148
+ };
149
+ };
150
+ const completeness = (scope) => {
151
+ const result = { complete: 0, partial: 0, unknown: 0, missing: 0 };
152
+ for (const fact of calls)
153
+ result[fact.completeness[scope].value ?? 'missing']++;
154
+ return result;
155
+ };
156
+ return {
157
+ runtimeId: first.identity.runtimeId,
158
+ threadId: first.identity.threadId,
159
+ actor: first.identity.actor,
160
+ family: first.family,
161
+ layer: first.family === 'executionWrapper' ? 'wrapper' : 'tool',
162
+ calls: calls.length,
163
+ completedCalls: calls.filter((fact) => fact.phase === 'completed').length,
164
+ failedCalls: calls.filter((fact) => fact.status === 'failed').length,
165
+ durationMs: total((fact) => fact.duration.value),
166
+ deliveredBytes: total((fact) => fact.bytes.delivered.value),
167
+ deliveredScope: calls.find((fact) => fact.bytes.deliveredScope !== null)?.bytes.deliveredScope ?? null,
168
+ rawBytes: total((fact) => fact.bytes.raw.value),
169
+ processedBytes: total((fact) => fact.bytes.processed.value),
170
+ retries: total((fact) => fact.retries.value),
171
+ reusedCalls: total((fact) => fact.reuse.value),
172
+ truncatedCalls: total((fact) => fact.truncated.value),
173
+ completeness: {
174
+ capture: completeness('capture'),
175
+ display: completeness('display'),
176
+ evidence: completeness('evidence'),
177
+ },
178
+ };
179
+ }
@@ -0,0 +1,13 @@
1
+ /*
2
+ * Copyright (C) 2026 Dyne.org foundation
3
+ * Designed by Denis Roio <jaromil@dyne.org>
4
+ * SPDX-License-Identifier: AGPL-3.0-or-later
5
+ */
6
+ export const providerTokenFields = [
7
+ 'totalTokens',
8
+ 'inputTokens',
9
+ 'cachedInputTokens',
10
+ 'cacheWriteInputTokens',
11
+ 'outputTokens',
12
+ 'reasoningOutputTokens',
13
+ ];
@@ -3,9 +3,11 @@
3
3
  * Designed by Denis Roio <jaromil@dyne.org>
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
+ import { unknownReadiness } from '../../../../shared/contracts/retrieval-readiness.js';
6
7
  export function registerXerjStatus(app, status) {
7
8
  app.get('/api/xerj', async (_request, reply) => {
8
9
  reply.header('Cache-Control', 'no-store');
9
- return status();
10
+ const current = status();
11
+ return { ...current, readiness: current.readiness ?? unknownReadiness() };
10
12
  });
11
13
  }
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { readTransportDiagnostics } from '../../platform/persistence/sqlite-transport-diagnostics.js';
7
7
  import { DatabaseSync } from 'node:sqlite';
8
+ import { parseMcpStartupStatus } from '../../../shared/contracts/mcp-startup-failure.js';
8
9
  const relevant = /^(?:org-plan\.|autopilot\.|agent\.activity\.|session\.status\.)/;
9
10
  const statusTypes = ['autopilot.updated', 'agent.activity.updated', 'session.status.updated'];
10
11
  // Export structural telemetry only. Event types alone do not imply payload safety.
@@ -143,13 +144,19 @@ export function exportControlPlaneTrace(databasePath, sessionId, generatedAt = n
143
144
  .reverse()
144
145
  .filter((row) => relevant.test(row.type))
145
146
  .map((row) => {
146
- const payload = redactDiagnosticPayload(objectPayload(row.payload_json));
147
+ const raw = objectPayload(row.payload_json);
148
+ const payload = (row.type === 'agent.activity.mcp-startup'
149
+ ? (parseMcpStartupStatus(raw) ?? {})
150
+ : redactDiagnosticPayload(raw));
147
151
  return {
148
152
  sequence: row.sequence,
149
153
  occurredAt: row.occurred_at,
150
154
  type: row.type,
151
155
  payload,
152
- traceId: correlation(payload),
156
+ traceId: row.type === 'agent.activity.mcp-startup'
157
+ ? (payload.failure?.failureId ??
158
+ (typeof payload.attemptId === 'string' ? payload.attemptId : null))
159
+ : correlation(payload),
153
160
  };
154
161
  });
155
162
  return {
@@ -181,7 +188,15 @@ export function formatControlPlaneTrace(trace) {
181
188
  ];
182
189
  for (const event of trace.events) {
183
190
  const correlationLabel = event.traceId ? ` trace=${event.traceId}` : '';
184
- lines.push(`${String(event.sequence).padStart(6)} ${event.occurredAt} ${event.type}${correlationLabel}`);
191
+ const startup = event.type === 'agent.activity.mcp-startup'
192
+ ? parseMcpStartupStatus(event.payload)
193
+ : undefined;
194
+ const startupLabel = startup
195
+ ? ` server=${startup.serverName} thread=${startup.threadId ?? 'unavailable'} runtime=${startup.runtimeId} attempt=${startup.attemptId} status=${startup.status}${startup.failure
196
+ ? ` phase=${startup.failure.phase} code=${startup.failure.code} exit=${startup.failure.exitCode ?? 'unavailable'} signal=${startup.failure.signal ?? 'unavailable'} artifact=${startup.failure.artifactDigest ?? 'unavailable'}`
197
+ : ''}`
198
+ : '';
199
+ lines.push(`${String(event.sequence).padStart(6)} ${event.occurredAt} ${event.type}${correlationLabel}${startupLabel}`);
185
200
  }
186
201
  lines.push('', 'Diagnosis:');
187
202
  if (!trace.diagnoses.length)