github-issue-tower-defence-management 1.140.2 → 1.142.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.
- package/CHANGELOG.md +20 -0
- package/README.md +13 -6
- package/bin/adapter/entry-points/console/dashboardComposeService.js +23 -4
- package/bin/adapter/entry-points/console/dashboardComposeService.js.map +1 -1
- package/bin/adapter/entry-points/handlers/HandleScheduledEventUseCaseHandler.js +43 -2
- package/bin/adapter/entry-points/handlers/HandleScheduledEventUseCaseHandler.js.map +1 -1
- package/bin/adapter/entry-points/handlers/resetDegeneratedTmuxSessions.js +32 -0
- package/bin/adapter/entry-points/handlers/resetDegeneratedTmuxSessions.js.map +1 -0
- package/bin/adapter/entry-points/handlers/tokenStatusWriter.js +1 -0
- package/bin/adapter/entry-points/handlers/tokenStatusWriter.js.map +1 -1
- package/bin/adapter/repositories/FileSystemSessionAssistantTurnsRepository.js +135 -0
- package/bin/adapter/repositories/FileSystemSessionAssistantTurnsRepository.js.map +1 -0
- package/bin/adapter/repositories/FileSystemSessionDegenerationCooldownStateRepository.js +120 -0
- package/bin/adapter/repositories/FileSystemSessionDegenerationCooldownStateRepository.js.map +1 -0
- package/bin/adapter/repositories/FileSystemSubAgentLivenessResolver.js +3 -3
- package/bin/adapter/repositories/FileSystemSubAgentLivenessResolver.js.map +1 -1
- package/bin/adapter/repositories/TranscriptOwnerCallStatusProvider.js +23 -9
- package/bin/adapter/repositories/TranscriptOwnerCallStatusProvider.js.map +1 -1
- package/bin/domain/entities/OutputDegeneration.js +3 -0
- package/bin/domain/entities/OutputDegeneration.js.map +1 -0
- package/bin/domain/usecases/OutputDegenerationDetector.js +150 -0
- package/bin/domain/usecases/OutputDegenerationDetector.js.map +1 -0
- package/bin/domain/usecases/SessionOutputDegenerationRecoveryUseCase.js +84 -0
- package/bin/domain/usecases/SessionOutputDegenerationRecoveryUseCase.js.map +1 -0
- package/bin/domain/usecases/adapter-interfaces/SessionAssistantTurnsRepository.js +3 -0
- package/bin/domain/usecases/adapter-interfaces/SessionAssistantTurnsRepository.js.map +1 -0
- package/bin/domain/usecases/adapter-interfaces/SessionDegenerationCooldownStateRepository.js +3 -0
- package/bin/domain/usecases/adapter-interfaces/SessionDegenerationCooldownStateRepository.js.map +1 -0
- package/bin/domain/usecases/dashboard/ComposeDashboardUseCase.js +41 -5
- package/bin/domain/usecases/dashboard/ComposeDashboardUseCase.js.map +1 -1
- package/bin/domain/usecases/dashboard/GenerateTokenStatusUseCase.js +16 -1
- package/bin/domain/usecases/dashboard/GenerateTokenStatusUseCase.js.map +1 -1
- package/package.json +1 -1
- package/src/adapter/entry-points/console/dashboardComposeService.test.ts +82 -0
- package/src/adapter/entry-points/console/dashboardComposeService.ts +38 -4
- package/src/adapter/entry-points/handlers/HandleScheduledEventUseCaseHandler.ts +44 -0
- package/src/adapter/entry-points/handlers/resetDegeneratedTmuxSessions.test.ts +69 -0
- package/src/adapter/entry-points/handlers/resetDegeneratedTmuxSessions.ts +71 -0
- package/src/adapter/entry-points/handlers/tokenStatusWriter.test.ts +6 -0
- package/src/adapter/entry-points/handlers/tokenStatusWriter.ts +4 -0
- package/src/adapter/repositories/FileSystemSessionAssistantTurnsRepository.test.ts +138 -0
- package/src/adapter/repositories/FileSystemSessionAssistantTurnsRepository.ts +113 -0
- package/src/adapter/repositories/FileSystemSessionDegenerationCooldownStateRepository.test.ts +85 -0
- package/src/adapter/repositories/FileSystemSessionDegenerationCooldownStateRepository.ts +105 -0
- package/src/adapter/repositories/FileSystemSubAgentLivenessResolver.test.ts +94 -0
- package/src/adapter/repositories/FileSystemSubAgentLivenessResolver.ts +3 -3
- package/src/adapter/repositories/TranscriptOwnerCallStatusProvider.test.ts +368 -1
- package/src/adapter/repositories/TranscriptOwnerCallStatusProvider.ts +28 -10
- package/src/adapter/repositories/issue/ApiV3CheerioRestIssueRepository.test.ts +31 -0
- package/src/domain/entities/OutputDegeneration.ts +10 -0
- package/src/domain/usecases/OutputDegenerationDetector.test.ts +167 -0
- package/src/domain/usecases/OutputDegenerationDetector.ts +169 -0
- package/src/domain/usecases/SessionOutputDegenerationRecoveryUseCase.test.ts +224 -0
- package/src/domain/usecases/SessionOutputDegenerationRecoveryUseCase.ts +142 -0
- package/src/domain/usecases/adapter-interfaces/SessionAssistantTurnsRepository.ts +6 -0
- package/src/domain/usecases/adapter-interfaces/SessionDegenerationCooldownStateRepository.ts +4 -0
- package/src/domain/usecases/dashboard/ComposeDashboardUseCase.test.ts +164 -0
- package/src/domain/usecases/dashboard/ComposeDashboardUseCase.ts +63 -5
- package/src/domain/usecases/dashboard/GenerateTokenStatusUseCase.test.ts +73 -0
- package/src/domain/usecases/dashboard/GenerateTokenStatusUseCase.ts +23 -0
- package/types/adapter/entry-points/console/dashboardComposeService.d.ts.map +1 -1
- package/types/adapter/entry-points/handlers/HandleScheduledEventUseCaseHandler.d.ts.map +1 -1
- package/types/adapter/entry-points/handlers/resetDegeneratedTmuxSessions.d.ts +19 -0
- package/types/adapter/entry-points/handlers/resetDegeneratedTmuxSessions.d.ts.map +1 -0
- package/types/adapter/entry-points/handlers/tokenStatusWriter.d.ts +2 -1
- package/types/adapter/entry-points/handlers/tokenStatusWriter.d.ts.map +1 -1
- package/types/adapter/repositories/FileSystemSessionAssistantTurnsRepository.d.ts +10 -0
- package/types/adapter/repositories/FileSystemSessionAssistantTurnsRepository.d.ts.map +1 -0
- package/types/adapter/repositories/FileSystemSessionDegenerationCooldownStateRepository.d.ts +15 -0
- package/types/adapter/repositories/FileSystemSessionDegenerationCooldownStateRepository.d.ts.map +1 -0
- package/types/adapter/repositories/TranscriptOwnerCallStatusProvider.d.ts +2 -1
- package/types/adapter/repositories/TranscriptOwnerCallStatusProvider.d.ts.map +1 -1
- package/types/domain/entities/OutputDegeneration.d.ts +10 -0
- package/types/domain/entities/OutputDegeneration.d.ts.map +1 -0
- package/types/domain/usecases/OutputDegenerationDetector.d.ts +32 -0
- package/types/domain/usecases/OutputDegenerationDetector.d.ts.map +1 -0
- package/types/domain/usecases/SessionOutputDegenerationRecoveryUseCase.d.ts +31 -0
- package/types/domain/usecases/SessionOutputDegenerationRecoveryUseCase.d.ts.map +1 -0
- package/types/domain/usecases/adapter-interfaces/SessionAssistantTurnsRepository.d.ts +4 -0
- package/types/domain/usecases/adapter-interfaces/SessionAssistantTurnsRepository.d.ts.map +1 -0
- package/types/domain/usecases/adapter-interfaces/SessionDegenerationCooldownStateRepository.d.ts +8 -0
- package/types/domain/usecases/adapter-interfaces/SessionDegenerationCooldownStateRepository.d.ts.map +1 -0
- package/types/domain/usecases/dashboard/ComposeDashboardUseCase.d.ts +3 -1
- package/types/domain/usecases/dashboard/ComposeDashboardUseCase.d.ts.map +1 -1
- package/types/domain/usecases/dashboard/GenerateTokenStatusUseCase.d.ts +6 -0
- package/types/domain/usecases/dashboard/GenerateTokenStatusUseCase.d.ts.map +1 -1
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { CrossTurnDegeneration } from '../entities/OutputDegeneration';
|
|
2
|
+
|
|
3
|
+
export const OUTPUT_DEGENERATION_REPEAT_THRESHOLD = 5;
|
|
4
|
+
export const OUTPUT_DEGENERATION_DOMINATION_FRACTION = 0.8;
|
|
5
|
+
export const OUTPUT_DEGENERATION_MAX_TOKEN_LENGTH = 32;
|
|
6
|
+
export const OUTPUT_DEGENERATION_ABSOLUTE_RUN_THRESHOLD = 15;
|
|
7
|
+
export const OUTPUT_DEGENERATION_REP4_THRESHOLD = 0.3;
|
|
8
|
+
export const OUTPUT_DEGENERATION_REP4_MIN_TOKENS = 40;
|
|
9
|
+
export const OUTPUT_DEGENERATION_CROSS_TURN_WINDOW = 10;
|
|
10
|
+
export const OUTPUT_DEGENERATION_CROSS_TURN_MIN_TURNS = 4;
|
|
11
|
+
|
|
12
|
+
export type ShortTokenRun = {
|
|
13
|
+
token: string | null;
|
|
14
|
+
run: number;
|
|
15
|
+
total: number;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
const LIST_ITEM_LINE_PATTERN = /^\s*(?:[-*+]\s|\d+[.)]\s)/;
|
|
19
|
+
const TRAILING_ALPHA_TOKEN_PATTERN = /^[A-Za-z]+$/;
|
|
20
|
+
|
|
21
|
+
const splitTokens = (text: string): string[] =>
|
|
22
|
+
text.split(/\s+/).filter((token) => token.length > 0);
|
|
23
|
+
|
|
24
|
+
const splitLines = (text: string): string[] => text.split(/\r\n|\r|\n/);
|
|
25
|
+
|
|
26
|
+
export class OutputDegenerationDetector {
|
|
27
|
+
constructor(
|
|
28
|
+
private readonly repeatThreshold: number = OUTPUT_DEGENERATION_REPEAT_THRESHOLD,
|
|
29
|
+
private readonly dominationFraction: number = OUTPUT_DEGENERATION_DOMINATION_FRACTION,
|
|
30
|
+
private readonly maxTokenLength: number = OUTPUT_DEGENERATION_MAX_TOKEN_LENGTH,
|
|
31
|
+
private readonly absoluteRunThreshold: number = OUTPUT_DEGENERATION_ABSOLUTE_RUN_THRESHOLD,
|
|
32
|
+
private readonly rep4Threshold: number = OUTPUT_DEGENERATION_REP4_THRESHOLD,
|
|
33
|
+
private readonly rep4MinTokens: number = OUTPUT_DEGENERATION_REP4_MIN_TOKENS,
|
|
34
|
+
private readonly crossTurnWindow: number = OUTPUT_DEGENERATION_CROSS_TURN_WINDOW,
|
|
35
|
+
private readonly crossTurnMinTurns: number = OUTPUT_DEGENERATION_CROSS_TURN_MIN_TURNS,
|
|
36
|
+
) {}
|
|
37
|
+
|
|
38
|
+
maxConsecutiveShortTokenRun = (text: string): ShortTokenRun => {
|
|
39
|
+
let bestToken: string | null = null;
|
|
40
|
+
let bestRun = 0;
|
|
41
|
+
let totalTokens = 0;
|
|
42
|
+
let currentToken: string | null = null;
|
|
43
|
+
let currentRun = 0;
|
|
44
|
+
for (const token of splitTokens(text)) {
|
|
45
|
+
totalTokens += 1;
|
|
46
|
+
if (token.length > this.maxTokenLength) {
|
|
47
|
+
currentToken = null;
|
|
48
|
+
currentRun = 0;
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
if (token === currentToken) {
|
|
52
|
+
currentRun += 1;
|
|
53
|
+
} else {
|
|
54
|
+
currentToken = token;
|
|
55
|
+
currentRun = 1;
|
|
56
|
+
}
|
|
57
|
+
if (currentRun > bestRun) {
|
|
58
|
+
bestRun = currentRun;
|
|
59
|
+
bestToken = currentToken;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return { token: bestToken, run: bestRun, total: totalTokens };
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
isIntraTurnDegeneration = (text: string): boolean => {
|
|
66
|
+
const { run, total } = this.maxConsecutiveShortTokenRun(text);
|
|
67
|
+
if (total === 0) {
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
if (run >= this.repeatThreshold && run >= this.dominationFraction * total) {
|
|
71
|
+
return true;
|
|
72
|
+
}
|
|
73
|
+
const filtered = this.stripRepetitionExemptSpans(text);
|
|
74
|
+
const filteredRun = this.maxConsecutiveShortTokenRun(filtered);
|
|
75
|
+
if (filteredRun.run >= this.absoluteRunThreshold) {
|
|
76
|
+
return true;
|
|
77
|
+
}
|
|
78
|
+
if (
|
|
79
|
+
filteredRun.total >= this.rep4MinTokens &&
|
|
80
|
+
this.duplicateNgramFraction(filtered, 4) >= this.rep4Threshold
|
|
81
|
+
) {
|
|
82
|
+
return true;
|
|
83
|
+
}
|
|
84
|
+
return false;
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
detectCrossTurnDegeneration = (
|
|
88
|
+
texts: string[],
|
|
89
|
+
): CrossTurnDegeneration | null => {
|
|
90
|
+
const counts = new Map<string, number>();
|
|
91
|
+
for (const text of texts.slice(0, this.crossTurnWindow)) {
|
|
92
|
+
const token = this.trailingSpuriousToken(text);
|
|
93
|
+
if (token === null) {
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
counts.set(token, (counts.get(token) ?? 0) + 1);
|
|
97
|
+
}
|
|
98
|
+
let bestToken: string | null = null;
|
|
99
|
+
let bestCount = 0;
|
|
100
|
+
for (const [token, count] of counts) {
|
|
101
|
+
if (count > bestCount) {
|
|
102
|
+
bestCount = count;
|
|
103
|
+
bestToken = token;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
if (bestToken !== null && bestCount >= this.crossTurnMinTurns) {
|
|
107
|
+
return { token: bestToken, turnCount: bestCount };
|
|
108
|
+
}
|
|
109
|
+
return null;
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
private stripRepetitionExemptSpans = (text: string): string => {
|
|
113
|
+
const keptLines: string[] = [];
|
|
114
|
+
let inFence = false;
|
|
115
|
+
for (const line of splitLines(text)) {
|
|
116
|
+
const stripped = line.trim();
|
|
117
|
+
if (stripped.startsWith('```') || stripped.startsWith('~~~')) {
|
|
118
|
+
inFence = !inFence;
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
if (inFence) {
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
if (line.includes('|')) {
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
if (LIST_ITEM_LINE_PATTERN.test(line)) {
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
keptLines.push(line);
|
|
131
|
+
}
|
|
132
|
+
return keptLines.join('\n');
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
private duplicateNgramFraction = (text: string, n: number): number => {
|
|
136
|
+
const tokens = splitTokens(text).filter(
|
|
137
|
+
(token) => token.length <= this.maxTokenLength,
|
|
138
|
+
);
|
|
139
|
+
if (tokens.length < n + 1) {
|
|
140
|
+
return 0;
|
|
141
|
+
}
|
|
142
|
+
const ngrams: string[] = [];
|
|
143
|
+
for (let index = 0; index <= tokens.length - n; index += 1) {
|
|
144
|
+
ngrams.push(tokens.slice(index, index + n).join('\u0000'));
|
|
145
|
+
}
|
|
146
|
+
const total = ngrams.length;
|
|
147
|
+
if (total < 2) {
|
|
148
|
+
return 0;
|
|
149
|
+
}
|
|
150
|
+
const unique = new Set(ngrams).size;
|
|
151
|
+
return 1 - unique / total;
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
private trailingSpuriousToken = (text: string): string | null => {
|
|
155
|
+
const stripped = text.replace(/\s+$/, '');
|
|
156
|
+
if (stripped.length === 0) {
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
const lines = splitLines(stripped);
|
|
160
|
+
const lastLine = lines[lines.length - 1].trim();
|
|
161
|
+
if (lastLine.length === 0 || lastLine.length > this.maxTokenLength) {
|
|
162
|
+
return null;
|
|
163
|
+
}
|
|
164
|
+
if (!TRAILING_ALPHA_TOKEN_PATTERN.test(lastLine)) {
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
return lastLine;
|
|
168
|
+
};
|
|
169
|
+
}
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import { SessionOutputDegenerationRecoveryUseCase } from './SessionOutputDegenerationRecoveryUseCase';
|
|
2
|
+
import { LiveSessionProcessSnapshotProvider } from './adapter-interfaces/LiveSessionProcessSnapshotProvider';
|
|
3
|
+
import { InteractiveLiveSessionTranscriptResolver } from './adapter-interfaces/InteractiveLiveSessionTranscriptResolver';
|
|
4
|
+
import { SessionAssistantTurnsRepository } from './adapter-interfaces/SessionAssistantTurnsRepository';
|
|
5
|
+
import { SessionDegenerationCooldownStateRepository } from './adapter-interfaces/SessionDegenerationCooldownStateRepository';
|
|
6
|
+
import { SilentSessionNotificationRepository } from './adapter-interfaces/SilentSessionNotificationRepository';
|
|
7
|
+
import { TmuxSessionRepository } from './adapter-interfaces/TmuxSessionRepository';
|
|
8
|
+
import { Sleeper } from './adapter-interfaces/Sleeper';
|
|
9
|
+
import { LiveSessionProcessSnapshot } from '../entities/LiveSessionProcessSnapshot';
|
|
10
|
+
|
|
11
|
+
const SESSION_NAME = 'https://github.com/HiromiShikata/secretary/issues/2824';
|
|
12
|
+
|
|
13
|
+
const buildSnapshot = (sessionName: string): LiveSessionProcessSnapshot => ({
|
|
14
|
+
sessions: [{ sessionName, panePids: [100] }],
|
|
15
|
+
processes: [
|
|
16
|
+
{
|
|
17
|
+
pid: 100,
|
|
18
|
+
ppid: 1,
|
|
19
|
+
commandLine: 'claude --resume',
|
|
20
|
+
sessionId: 'session-1',
|
|
21
|
+
currentSessionId: 'session-1',
|
|
22
|
+
configDir: '/home/user/.claude',
|
|
23
|
+
},
|
|
24
|
+
],
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
const repeat = (token: string, count: number): string =>
|
|
28
|
+
Array.from({ length: count }, () => token).join(' ');
|
|
29
|
+
|
|
30
|
+
type Mocked<T> = jest.Mocked<T> & jest.MockedObject<T>;
|
|
31
|
+
|
|
32
|
+
describe('SessionOutputDegenerationRecoveryUseCase', () => {
|
|
33
|
+
let snapshotProvider: Mocked<LiveSessionProcessSnapshotProvider>;
|
|
34
|
+
let transcriptResolver: Mocked<InteractiveLiveSessionTranscriptResolver>;
|
|
35
|
+
let assistantTurnsRepository: Mocked<SessionAssistantTurnsRepository>;
|
|
36
|
+
let notificationRepository: Mocked<SilentSessionNotificationRepository>;
|
|
37
|
+
let tmuxSessionRepository: Mocked<Pick<TmuxSessionRepository, 'killSession'>>;
|
|
38
|
+
let cooldownStateRepository: Mocked<SessionDegenerationCooldownStateRepository>;
|
|
39
|
+
let sleeper: Mocked<Sleeper>;
|
|
40
|
+
let useCase: SessionOutputDegenerationRecoveryUseCase;
|
|
41
|
+
|
|
42
|
+
const now = new Date('2026-07-26T00:00:00Z');
|
|
43
|
+
const nowEpochSeconds = Math.floor(now.getTime() / 1000);
|
|
44
|
+
|
|
45
|
+
const runWith = (params: {
|
|
46
|
+
enabled: boolean;
|
|
47
|
+
turns: string[];
|
|
48
|
+
lastResetEpochSeconds?: number;
|
|
49
|
+
}): Promise<void> => {
|
|
50
|
+
snapshotProvider.getSnapshot.mockResolvedValue(buildSnapshot(SESSION_NAME));
|
|
51
|
+
transcriptResolver.resolveTranscriptPaths.mockReturnValue(
|
|
52
|
+
new Map([[SESSION_NAME, '/fake/transcript.jsonl']]),
|
|
53
|
+
);
|
|
54
|
+
assistantTurnsRepository.listRecentAssistantTurnsBySessionName.mockResolvedValue(
|
|
55
|
+
new Map([[SESSION_NAME, params.turns]]),
|
|
56
|
+
);
|
|
57
|
+
cooldownStateRepository.loadLastResetEpochSecondsBySessionName.mockResolvedValue(
|
|
58
|
+
params.lastResetEpochSeconds === undefined
|
|
59
|
+
? new Map()
|
|
60
|
+
: new Map([[SESSION_NAME, params.lastResetEpochSeconds]]),
|
|
61
|
+
);
|
|
62
|
+
return useCase.run({
|
|
63
|
+
enabled: params.enabled,
|
|
64
|
+
warningMessage: 'WARNING',
|
|
65
|
+
graceSeconds: 5,
|
|
66
|
+
cooldownSeconds: 300,
|
|
67
|
+
now,
|
|
68
|
+
});
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
beforeEach(() => {
|
|
72
|
+
snapshotProvider = {
|
|
73
|
+
getSnapshot: jest.fn(),
|
|
74
|
+
};
|
|
75
|
+
transcriptResolver = {
|
|
76
|
+
resolveTranscriptPaths: jest.fn(),
|
|
77
|
+
};
|
|
78
|
+
assistantTurnsRepository = {
|
|
79
|
+
listRecentAssistantTurnsBySessionName: jest.fn(),
|
|
80
|
+
};
|
|
81
|
+
notificationRepository = {
|
|
82
|
+
sendSelfCheckNotification: jest.fn().mockResolvedValue(undefined),
|
|
83
|
+
};
|
|
84
|
+
tmuxSessionRepository = {
|
|
85
|
+
killSession: jest.fn().mockResolvedValue(undefined),
|
|
86
|
+
};
|
|
87
|
+
cooldownStateRepository = {
|
|
88
|
+
loadLastResetEpochSecondsBySessionName: jest.fn(),
|
|
89
|
+
recordReset: jest.fn().mockResolvedValue(undefined),
|
|
90
|
+
};
|
|
91
|
+
sleeper = {
|
|
92
|
+
sleep: jest.fn().mockResolvedValue(undefined),
|
|
93
|
+
};
|
|
94
|
+
useCase = new SessionOutputDegenerationRecoveryUseCase(
|
|
95
|
+
snapshotProvider,
|
|
96
|
+
transcriptResolver,
|
|
97
|
+
assistantTurnsRepository,
|
|
98
|
+
notificationRepository,
|
|
99
|
+
tmuxSessionRepository,
|
|
100
|
+
cooldownStateRepository,
|
|
101
|
+
sleeper,
|
|
102
|
+
);
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it('warns, waits the grace period, kills, and records the reset when enabled and degenerated (intra-turn)', async () => {
|
|
106
|
+
await runWith({ enabled: true, turns: [repeat('court', 40)] });
|
|
107
|
+
|
|
108
|
+
expect(
|
|
109
|
+
notificationRepository.sendSelfCheckNotification,
|
|
110
|
+
).toHaveBeenCalledWith(SESSION_NAME, 'WARNING');
|
|
111
|
+
expect(sleeper.sleep).toHaveBeenCalledWith(5000);
|
|
112
|
+
expect(tmuxSessionRepository.killSession).toHaveBeenCalledWith(
|
|
113
|
+
SESSION_NAME,
|
|
114
|
+
);
|
|
115
|
+
expect(cooldownStateRepository.recordReset).toHaveBeenCalledWith({
|
|
116
|
+
sessionName: SESSION_NAME,
|
|
117
|
+
now,
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it('does not warn or kill in dry-run but still records the reset for cooldown', async () => {
|
|
122
|
+
await runWith({ enabled: false, turns: [repeat('court', 40)] });
|
|
123
|
+
|
|
124
|
+
expect(
|
|
125
|
+
notificationRepository.sendSelfCheckNotification,
|
|
126
|
+
).not.toHaveBeenCalled();
|
|
127
|
+
expect(sleeper.sleep).not.toHaveBeenCalled();
|
|
128
|
+
expect(tmuxSessionRepository.killSession).not.toHaveBeenCalled();
|
|
129
|
+
expect(cooldownStateRepository.recordReset).toHaveBeenCalledWith({
|
|
130
|
+
sessionName: SESSION_NAME,
|
|
131
|
+
now,
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it('skips a session that was reset within the cooldown window', async () => {
|
|
136
|
+
await runWith({
|
|
137
|
+
enabled: true,
|
|
138
|
+
turns: [repeat('court', 40)],
|
|
139
|
+
lastResetEpochSeconds: nowEpochSeconds - 100,
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
expect(
|
|
143
|
+
notificationRepository.sendSelfCheckNotification,
|
|
144
|
+
).not.toHaveBeenCalled();
|
|
145
|
+
expect(tmuxSessionRepository.killSession).not.toHaveBeenCalled();
|
|
146
|
+
expect(cooldownStateRepository.recordReset).not.toHaveBeenCalled();
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
it('acts again once the cooldown window has elapsed', async () => {
|
|
150
|
+
await runWith({
|
|
151
|
+
enabled: true,
|
|
152
|
+
turns: [repeat('court', 40)],
|
|
153
|
+
lastResetEpochSeconds: nowEpochSeconds - 301,
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
expect(tmuxSessionRepository.killSession).toHaveBeenCalledWith(
|
|
157
|
+
SESSION_NAME,
|
|
158
|
+
);
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
it('does not act on a healthy session', async () => {
|
|
162
|
+
await runWith({
|
|
163
|
+
enabled: true,
|
|
164
|
+
turns: [
|
|
165
|
+
'I finished the migration, verified the seed data, and uploaded the report.',
|
|
166
|
+
],
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
expect(
|
|
170
|
+
notificationRepository.sendSelfCheckNotification,
|
|
171
|
+
).not.toHaveBeenCalled();
|
|
172
|
+
expect(tmuxSessionRepository.killSession).not.toHaveBeenCalled();
|
|
173
|
+
expect(cooldownStateRepository.recordReset).not.toHaveBeenCalled();
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
it('resets a session detected only by the cross-turn signature', async () => {
|
|
177
|
+
const clean = (index: number): string =>
|
|
178
|
+
`Turn ${index}: completed and reported.`;
|
|
179
|
+
const trailing = (index: number): string =>
|
|
180
|
+
`Turn ${index}: real message.\n\ncourt`;
|
|
181
|
+
const turns = [
|
|
182
|
+
trailing(1),
|
|
183
|
+
clean(2),
|
|
184
|
+
trailing(3),
|
|
185
|
+
clean(4),
|
|
186
|
+
trailing(5),
|
|
187
|
+
clean(6),
|
|
188
|
+
trailing(7),
|
|
189
|
+
clean(8),
|
|
190
|
+
clean(9),
|
|
191
|
+
clean(10),
|
|
192
|
+
];
|
|
193
|
+
|
|
194
|
+
await runWith({ enabled: true, turns });
|
|
195
|
+
|
|
196
|
+
expect(tmuxSessionRepository.killSession).toHaveBeenCalledWith(
|
|
197
|
+
SESSION_NAME,
|
|
198
|
+
);
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
it('does not act on a non-github-named interactive session', async () => {
|
|
202
|
+
snapshotProvider.getSnapshot.mockResolvedValue(buildSnapshot('app'));
|
|
203
|
+
transcriptResolver.resolveTranscriptPaths.mockReturnValue(new Map());
|
|
204
|
+
assistantTurnsRepository.listRecentAssistantTurnsBySessionName.mockResolvedValue(
|
|
205
|
+
new Map(),
|
|
206
|
+
);
|
|
207
|
+
cooldownStateRepository.loadLastResetEpochSecondsBySessionName.mockResolvedValue(
|
|
208
|
+
new Map(),
|
|
209
|
+
);
|
|
210
|
+
|
|
211
|
+
await useCase.run({
|
|
212
|
+
enabled: true,
|
|
213
|
+
warningMessage: 'WARNING',
|
|
214
|
+
graceSeconds: 5,
|
|
215
|
+
cooldownSeconds: 300,
|
|
216
|
+
now,
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
expect(
|
|
220
|
+
assistantTurnsRepository.listRecentAssistantTurnsBySessionName,
|
|
221
|
+
).toHaveBeenCalledWith(new Map(), 10);
|
|
222
|
+
expect(tmuxSessionRepository.killSession).not.toHaveBeenCalled();
|
|
223
|
+
});
|
|
224
|
+
});
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { LiveSessionProcessSnapshotProvider } from './adapter-interfaces/LiveSessionProcessSnapshotProvider';
|
|
2
|
+
import { InteractiveLiveSessionTranscriptResolver } from './adapter-interfaces/InteractiveLiveSessionTranscriptResolver';
|
|
3
|
+
import { SessionAssistantTurnsRepository } from './adapter-interfaces/SessionAssistantTurnsRepository';
|
|
4
|
+
import { SessionDegenerationCooldownStateRepository } from './adapter-interfaces/SessionDegenerationCooldownStateRepository';
|
|
5
|
+
import { SilentSessionNotificationRepository } from './adapter-interfaces/SilentSessionNotificationRepository';
|
|
6
|
+
import { TmuxSessionRepository } from './adapter-interfaces/TmuxSessionRepository';
|
|
7
|
+
import { Sleeper } from './adapter-interfaces/Sleeper';
|
|
8
|
+
import {
|
|
9
|
+
OutputDegenerationDetector,
|
|
10
|
+
OUTPUT_DEGENERATION_CROSS_TURN_WINDOW,
|
|
11
|
+
} from './OutputDegenerationDetector';
|
|
12
|
+
import { ResolveInteractiveLiveSessionsUseCase } from './ResolveInteractiveLiveSessionsUseCase';
|
|
13
|
+
import { isGitHubIssueOrPullRequestSessionName } from './NotifySilentLiveSessionsUseCase';
|
|
14
|
+
|
|
15
|
+
export const DEFAULT_OUTPUT_DEGENERATION_GRACE_SECONDS = 5;
|
|
16
|
+
export const DEFAULT_OUTPUT_DEGENERATION_COOLDOWN_SECONDS = 300;
|
|
17
|
+
export const DEFAULT_OUTPUT_DEGENERATION_WARNING_MESSAGE =
|
|
18
|
+
'OUTPUT DEGENERATION DETECTED: your session is about to be reset. Immediately write a checkpoint to your assigned task issue (single concrete next action to resume, working directory and branch, in-flight sub-agent branch/PR URLs).';
|
|
19
|
+
|
|
20
|
+
export class SessionOutputDegenerationRecoveryUseCase {
|
|
21
|
+
private readonly resolveInteractiveLiveSessions =
|
|
22
|
+
new ResolveInteractiveLiveSessionsUseCase();
|
|
23
|
+
|
|
24
|
+
constructor(
|
|
25
|
+
private readonly liveSessionProcessSnapshotProvider: LiveSessionProcessSnapshotProvider,
|
|
26
|
+
private readonly interactiveLiveSessionTranscriptResolver: InteractiveLiveSessionTranscriptResolver,
|
|
27
|
+
private readonly assistantTurnsRepository: SessionAssistantTurnsRepository,
|
|
28
|
+
private readonly notificationRepository: SilentSessionNotificationRepository,
|
|
29
|
+
private readonly tmuxSessionRepository: Pick<
|
|
30
|
+
TmuxSessionRepository,
|
|
31
|
+
'killSession'
|
|
32
|
+
>,
|
|
33
|
+
private readonly cooldownStateRepository: SessionDegenerationCooldownStateRepository,
|
|
34
|
+
private readonly sleeper: Sleeper,
|
|
35
|
+
private readonly detector: OutputDegenerationDetector = new OutputDegenerationDetector(),
|
|
36
|
+
) {}
|
|
37
|
+
|
|
38
|
+
run = async (params: {
|
|
39
|
+
enabled: boolean;
|
|
40
|
+
warningMessage: string;
|
|
41
|
+
graceSeconds: number;
|
|
42
|
+
cooldownSeconds: number;
|
|
43
|
+
now: Date;
|
|
44
|
+
}): Promise<void> => {
|
|
45
|
+
const snapshot =
|
|
46
|
+
await this.liveSessionProcessSnapshotProvider.getSnapshot();
|
|
47
|
+
const allInteractiveSessions =
|
|
48
|
+
this.resolveInteractiveLiveSessions.resolve(snapshot);
|
|
49
|
+
const interactiveSessions = allInteractiveSessions.filter((session) =>
|
|
50
|
+
isGitHubIssueOrPullRequestSessionName(session.sessionName),
|
|
51
|
+
);
|
|
52
|
+
|
|
53
|
+
const transcriptPathBySessionName =
|
|
54
|
+
this.interactiveLiveSessionTranscriptResolver.resolveTranscriptPaths(
|
|
55
|
+
interactiveSessions,
|
|
56
|
+
);
|
|
57
|
+
const turnsBySessionName =
|
|
58
|
+
await this.assistantTurnsRepository.listRecentAssistantTurnsBySessionName(
|
|
59
|
+
transcriptPathBySessionName,
|
|
60
|
+
OUTPUT_DEGENERATION_CROSS_TURN_WINDOW,
|
|
61
|
+
);
|
|
62
|
+
const lastResetBySessionName =
|
|
63
|
+
await this.cooldownStateRepository.loadLastResetEpochSecondsBySessionName();
|
|
64
|
+
|
|
65
|
+
const nowEpochSeconds = Math.floor(params.now.getTime() / 1000);
|
|
66
|
+
let detectedCount = 0;
|
|
67
|
+
let resetCount = 0;
|
|
68
|
+
let dryRunCount = 0;
|
|
69
|
+
let cooldownSkippedCount = 0;
|
|
70
|
+
|
|
71
|
+
for (const session of interactiveSessions) {
|
|
72
|
+
const sessionName = session.sessionName;
|
|
73
|
+
const lastResetEpochSeconds = lastResetBySessionName.get(sessionName);
|
|
74
|
+
if (
|
|
75
|
+
lastResetEpochSeconds !== undefined &&
|
|
76
|
+
nowEpochSeconds - lastResetEpochSeconds < params.cooldownSeconds
|
|
77
|
+
) {
|
|
78
|
+
cooldownSkippedCount += 1;
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const turns = turnsBySessionName.get(sessionName) ?? [];
|
|
83
|
+
const newestTurn = turns.length > 0 ? turns[0] : null;
|
|
84
|
+
const intraTurn =
|
|
85
|
+
newestTurn !== null &&
|
|
86
|
+
this.detector.isIntraTurnDegeneration(newestTurn);
|
|
87
|
+
const crossTurn = this.detector.detectCrossTurnDegeneration(turns);
|
|
88
|
+
if (!intraTurn && crossTurn === null) {
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
detectedCount += 1;
|
|
92
|
+
|
|
93
|
+
if (intraTurn && newestTurn !== null) {
|
|
94
|
+
const { token, run, total } =
|
|
95
|
+
this.detector.maxConsecutiveShortTokenRun(newestTurn);
|
|
96
|
+
console.log(
|
|
97
|
+
`Output degeneration detected (intra-turn) session=${sessionName} token=${JSON.stringify(token)} run=${run} turnTokens=${total} enabled=${params.enabled}`,
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
if (crossTurn !== null) {
|
|
101
|
+
console.log(
|
|
102
|
+
`Output degeneration detected (cross-turn) session=${sessionName} token=${JSON.stringify(crossTurn.token)} turns=${crossTurn.turnCount}/${Math.min(turns.length, OUTPUT_DEGENERATION_CROSS_TURN_WINDOW)} enabled=${params.enabled}`,
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
if (params.enabled) {
|
|
107
|
+
try {
|
|
108
|
+
await this.notificationRepository.sendSelfCheckNotification(
|
|
109
|
+
sessionName,
|
|
110
|
+
params.warningMessage,
|
|
111
|
+
);
|
|
112
|
+
await this.sleeper.sleep(params.graceSeconds * 1000);
|
|
113
|
+
await this.tmuxSessionRepository.killSession(sessionName);
|
|
114
|
+
resetCount += 1;
|
|
115
|
+
console.log(
|
|
116
|
+
`Output degeneration reset session=${sessionName} graceSeconds=${params.graceSeconds}`,
|
|
117
|
+
);
|
|
118
|
+
} catch (error) {
|
|
119
|
+
console.error(
|
|
120
|
+
`Failed to reset degenerated session ${sessionName}: ${
|
|
121
|
+
error instanceof Error ? error.message : String(error)
|
|
122
|
+
}`,
|
|
123
|
+
);
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
} else {
|
|
127
|
+
dryRunCount += 1;
|
|
128
|
+
console.log(
|
|
129
|
+
`Output degeneration dry-run: would warn and reset session=${sessionName}`,
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
await this.cooldownStateRepository.recordReset({
|
|
133
|
+
sessionName,
|
|
134
|
+
now: params.now,
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
console.log(
|
|
139
|
+
`Output degeneration recovery: detected ${detectedCount} degenerated session(s) of ${interactiveSessions.length} interactive session(s); reset ${resetCount}, dry-run would-reset ${dryRunCount}, cooldown-skipped ${cooldownSkippedCount}.`,
|
|
140
|
+
);
|
|
141
|
+
};
|
|
142
|
+
}
|