File size: 7,501 Bytes
f0634fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { produce } from 'immer';
import { describe, expect, it } from 'vitest';

import {
  ContextAppendLoopEvent,
  ContextApplyCompaction,
  ContextClear,
  ContextUndo,
} from '#/agent/contextMemory/contextEvents';
import type { Event2, Event2Class } from '#/app/event/event2';
import type { FoldContext } from '#/state/state';
import {
  TurnCancel,
  TurnEnded,
  turnKey,
  TurnPrompt,
  type TurnModelState,
} from '#/agent/loop/turnOps';

const foldContext: FoldContext = {
  silent: false,
  checkpoint: () => {},
  clearCheckpoints: () => {},
  undoToCheckpoint: () => {},
  emit: () => {},
};

function fold(s: TurnModelState, event: Event2): TurnModelState {
  const entry = turnKey.replayable.folds.get(event.constructor as Event2Class);
  if (entry === undefined) throw new Error(`turn model fold not registered for '${event.type}'`);
  return produce(s, (draft) => entry(draft, event, foldContext) as void);
}

function foldLoopEvent(s: TurnModelState, turnId: string): TurnModelState {
  return fold(s, new ContextAppendLoopEvent({ agentId: 'main', event: { type: 'step.begin', uuid: 'step-0', turnId } }));
}

describe('turnKey lastEnded', () => {
  it('keeps the stored outcome across prompts and queued cancels', () => {
    let s = turnKey.initial();
    s = fold(s, new TurnPrompt({ agentId: 'main', input: [], origin: { kind: 'user' } }));
    s = fold(s, new TurnEnded({ agentId: 'main', turnId: 0, reason: 'failed', durationMs: 10 }));
    expect(s.lastEnded).toMatchObject({ turnId: 0, reason: 'failed' });
    s = fold(s, new TurnPrompt({ agentId: 'main', input: [], origin: { kind: 'user' } }));
    expect(s.lastEnded?.reason).toBe('failed');
    s = fold(s, new TurnCancel({ agentId: 'main', turnId: 1, target: 'queued' }));
    expect(s.lastEnded?.reason).toBe('failed');
    s = fold(s, new TurnEnded({ agentId: 'main', turnId: 1, reason: 'completed' }));
    expect(s.lastEnded).toMatchObject({ turnId: 1, reason: 'completed' });
  });

  it('clears the stored outcome once a newer turn starts producing', () => {
    let s = turnKey.initial();
    s = fold(s, new TurnPrompt({ agentId: 'main', input: [], origin: { kind: 'user' } }));
    s = fold(s, new TurnEnded({ agentId: 'main', turnId: 0, reason: 'failed' }));
    s = fold(s, new TurnPrompt({ agentId: 'main', input: [], origin: { kind: 'user' } }));
    s = foldLoopEvent(s, '1');
    expect(s.lastEnded).toBeUndefined();
  });

  it('keeps the stored outcome on the same turn’s own events', () => {
    let s = turnKey.initial();
    s = fold(s, new TurnPrompt({ agentId: 'main', input: [], origin: { kind: 'user' } }));
    s = foldLoopEvent(s, '0');
    s = fold(s, new TurnEnded({ agentId: 'main', turnId: 0, reason: 'completed' }));
    s = foldLoopEvent(s, '0');
    expect(s.lastEnded?.reason).toBe('completed');
  });

  it('clears the stored outcome when an undo rewinds the turn it describes', () => {
    let s = turnKey.initial();
    s = fold(s, new TurnPrompt({ agentId: 'main', input: [], origin: { kind: 'user' } }));
    s = fold(s, new TurnEnded({ agentId: 'main', turnId: 0, reason: 'completed', durationMs: 10 }));
    s = fold(s, new TurnPrompt({ agentId: 'main', input: [], origin: { kind: 'user' } }));
    s = fold(s, new TurnEnded({ agentId: 'main', turnId: 1, reason: 'cancelled', durationMs: 10 }));
    expect(s.lastEnded?.reason).toBe('cancelled');
    s = fold(s, new ContextUndo({ agentId: 'main', count: 1 }));
    expect(s.anchorTurnIds).toEqual([0]);
    expect(s.lastEnded).toBeUndefined();
  });

  it('keeps the stored outcome when an undo rewinds only later turns', () => {
    let s = turnKey.initial();
    s = fold(s, new TurnPrompt({ agentId: 'main', input: [], origin: { kind: 'user' } }));
    s = fold(s, new TurnEnded({ agentId: 'main', turnId: 0, reason: 'completed', durationMs: 10 }));
    s = fold(s, new TurnPrompt({ agentId: 'main', input: [], origin: { kind: 'user' } }));
    s = fold(s, new ContextUndo({ agentId: 'main', count: 1 }));
    expect(s.lastEnded).toMatchObject({ turnId: 0, reason: 'completed' });
  });

  it('clears the stored outcome when the undo count exceeds the tracked anchors', () => {
    let s = turnKey.initial();
    s = fold(s, new TurnPrompt({ agentId: 'main', input: [], origin: { kind: 'user' } }));
    s = fold(s, new TurnEnded({ agentId: 'main', turnId: 0, reason: 'cancelled', durationMs: 10 }));
    s = fold(s, new ContextUndo({ agentId: 'main', count: 2 }));
    expect(s.anchorTurnIds).toEqual([]);
    expect(s.lastEnded).toBeUndefined();
  });

  it('starts without a stored outcome', () => {
    expect(turnKey.initial().lastEnded).toBeUndefined();
  });
});

describe('turnKey anchorTurnIds', () => {
  const cronOrigin = {
    kind: 'cron_job',
    jobId: 'j1',
    cron: '0 9 * * *',
    recurring: true,
    coalescedCount: 0,
    stale: false,
  } as const;

  it('records undo-anchor prompt turns and skips non-anchor turns', () => {
    let s = turnKey.initial();
    s = fold(s, new TurnPrompt({ agentId: 'main', input: [], origin: { kind: 'user' } }));
    s = fold(s, new TurnPrompt({ agentId: 'main', input: [], origin: cronOrigin }));
    s = fold(
      s,
      new TurnPrompt({
        agentId: 'main',
        input: [],
        origin: {
          kind: 'plugin_command',
          activationId: 'a1',
          pluginId: 'p',
          commandName: 'c',
          trigger: 'user-slash',
        },
      }),
    );
    expect(s.anchorTurnIds).toEqual([0, 2]);
  });

  it('assigns the consumed id before cancelled-queued skips', () => {
    let s = turnKey.initial();
    s = fold(s, new TurnPrompt({ agentId: 'main', input: [], origin: { kind: 'user' } }));
    s = fold(s, new TurnCancel({ agentId: 'main', turnId: 1, target: 'queued' }));
    s = fold(s, new TurnPrompt({ agentId: 'main', input: [], origin: { kind: 'user' } }));
    expect(s.anchorTurnIds).toEqual([0, 2]);
  });

  it('drops trailing anchors on context.undo and resets on compaction and clear', () => {
    let s = turnKey.initial();
    s = fold(s, new TurnPrompt({ agentId: 'main', input: [], origin: { kind: 'user' } }));
    s = fold(s, new TurnPrompt({ agentId: 'main', input: [], origin: { kind: 'user' } }));
    s = fold(s, new ContextUndo({ agentId: 'main', count: 1 }));
    expect(s.anchorTurnIds).toEqual([0]);

    s = fold(
      s,
      new ContextApplyCompaction({ agentId: 'main', summary: 'summary', compactedCount: 2 }),
    );
    expect(s.anchorTurnIds).toEqual([]);

    s = fold(s, new TurnPrompt({ agentId: 'main', input: [], origin: { kind: 'user' } }));
    s = fold(s, new ContextClear({ agentId: 'main' }));
    expect(s.anchorTurnIds).toEqual([]);
  });
});

describe('TurnEnded serialization', () => {
  it('emits the op record shape without the bus-only interruptReason', () => {
    const event = new TurnEnded(
      {
        agentId: 'main',
        turnId: 3,
        reason: 'cancelled',
        durationMs: 12,
        interruptReason: 'user_cancelled',
      },
      42,
    );
    expect(event.serialize()).toEqual({
      type: 'turn.ended',
      agentId: 'main',
      turnId: 3,
      reason: 'cancelled',
      durationMs: 12,
      time: 42,
    });
  });

  it('omits absent optional fields from the record', () => {
    const event = new TurnEnded({ agentId: 'main', turnId: 0, reason: 'completed' }, 7);
    expect(event.serialize()).toEqual({
      type: 'turn.ended',
      agentId: 'main',
      turnId: 0,
      reason: 'completed',
      time: 7,
    });
  });
});