@gooftoken/dsh-rewind 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +29 -2
- package/assets/icon.svg +6 -0
- package/client.js +1549 -0
- package/cordis.patch.yml +4 -0
- package/docs/DETAIL.md +153 -0
- package/lib/command.d.ts +48 -0
- package/lib/compaction.d.ts +105 -0
- package/lib/config.d.ts +22 -0
- package/lib/git/provider.d.ts +26 -0
- package/lib/git/runner.d.ts +45 -0
- package/lib/git/snapshot.d.ts +60 -0
- package/lib/git/workspace.d.ts +54 -0
- package/lib/index.d.ts +18 -0
- package/lib/index.js +2631 -0
- package/lib/paths.d.ts +16 -0
- package/lib/recorder.d.ts +50 -0
- package/lib/replay.d.ts +72 -0
- package/lib/store.d.ts +34 -0
- package/lib/surface.d.ts +74 -0
- package/lib/types.d.ts +120 -0
- package/lib/undo.d.ts +38 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +92 -4
package/lib/index.js
ADDED
|
@@ -0,0 +1,2631 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { copyFile, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
|
|
3
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import z from "@deepseek-ai/schemastery";
|
|
6
|
+
// src/types.ts
|
|
7
|
+
/** A stable, rewind-specific error with a machine-readable code. */
|
|
8
|
+
var RewindError = class extends Error {
|
|
9
|
+
/** Stable failure identity used by command result copy. */
|
|
10
|
+
code;
|
|
11
|
+
/**
|
|
12
|
+
* @param code - stable failure identity.
|
|
13
|
+
* @param message - user-facing reason.
|
|
14
|
+
*/
|
|
15
|
+
constructor(code, message) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.name = "RewindError";
|
|
18
|
+
this.code = code;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
// src/surface.ts
|
|
22
|
+
/** Read one session event's surface operation without importing runtime helpers. */
|
|
23
|
+
function surfaceOpOf$1(event) {
|
|
24
|
+
return event.surfaceOp;
|
|
25
|
+
}
|
|
26
|
+
/** Whether one event entered the surface at its own log position. */
|
|
27
|
+
function isAppend(event) {
|
|
28
|
+
return surfaceOpOf$1(event) === "append";
|
|
29
|
+
}
|
|
30
|
+
/** First log position one surface node covers: its own seq, or a replacement range start. */
|
|
31
|
+
function coverStart$1(event) {
|
|
32
|
+
const op = surfaceOpOf$1(event);
|
|
33
|
+
if (typeof op === "object" && op !== null && op.op === "replace") return Number(op.startSeq);
|
|
34
|
+
return event.seq;
|
|
35
|
+
}
|
|
36
|
+
/** Whether one surface node is a replacement whose covered range includes a log position. */
|
|
37
|
+
function covers$1(event, seq) {
|
|
38
|
+
const op = surfaceOpOf$1(event);
|
|
39
|
+
if (typeof op !== "object" || op === null || op.op !== "replace") return false;
|
|
40
|
+
const range = op;
|
|
41
|
+
return Number(range.startSeq) <= seq && seq <= Number(range.endSeq);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Every user rewind marker in the log, oldest first.
|
|
45
|
+
* @param events - complete session log.
|
|
46
|
+
* @returns markers written by earlier rewinds or replays.
|
|
47
|
+
*/
|
|
48
|
+
function rewindMarkers(events) {
|
|
49
|
+
const markers = [];
|
|
50
|
+
for (const event of events) {
|
|
51
|
+
const op = surfaceOpOf$1(event);
|
|
52
|
+
const replaces = typeof op === "object" && op !== null && op.op === "replace";
|
|
53
|
+
if (op !== "append" && !replaces) continue;
|
|
54
|
+
const data = event.data;
|
|
55
|
+
let source;
|
|
56
|
+
if (event.type === "user/message") source = data.source;
|
|
57
|
+
else if (event.type === "developer/message") source = data.message?.source;
|
|
58
|
+
else continue;
|
|
59
|
+
if (source === void 0) continue;
|
|
60
|
+
if (source.kind === "rewind-undo") {
|
|
61
|
+
markers.pop();
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (source.kind === "rewind-replay" && event.type === "user/message") {} else if (source.kind === "rewind-cut" && event.type === "developer/message") {} else if (source.kind === "rewind-checkpoint" && event.type === "user/message") {} else continue;
|
|
65
|
+
const turn = Number(source.turn);
|
|
66
|
+
if (!Number.isSafeInteger(turn) || turn < 0) continue;
|
|
67
|
+
const cut = Number(source.cut);
|
|
68
|
+
markers.push({
|
|
69
|
+
turn,
|
|
70
|
+
seq: event.seq,
|
|
71
|
+
...Number.isSafeInteger(cut) && cut >= 0 ? { cut } : {}
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
return markers;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Whether an earlier rewind already hid a turn's start. A turn stays hidden
|
|
78
|
+
* when a marker returned to that turn or an earlier one after the turn began;
|
|
79
|
+
* turns created after a marker are visible again.
|
|
80
|
+
* @param events - complete session log.
|
|
81
|
+
* @param turn - host-assigned turn to test.
|
|
82
|
+
* @returns true when the turn is no longer part of the visible conversation.
|
|
83
|
+
*/
|
|
84
|
+
function hiddenByRewind(events, turn) {
|
|
85
|
+
const markers = rewindMarkers(events);
|
|
86
|
+
if (markers.length === 0) return false;
|
|
87
|
+
const start = events.find((event) => event.type === "turn/start" && event.data.turn === turn);
|
|
88
|
+
if (start === void 0) return false;
|
|
89
|
+
const startSeq = start.seq;
|
|
90
|
+
return markers.some((marker) => turn >= marker.turn && startSeq < marker.seq);
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Whether the log ends inside an open compaction bracket. A rewind must not
|
|
94
|
+
* replace the surface while compaction owns it.
|
|
95
|
+
* @param events - complete session log.
|
|
96
|
+
* @returns true when the newest bracket has no close.
|
|
97
|
+
*/
|
|
98
|
+
function compactionOpen(events) {
|
|
99
|
+
let boundary = 0;
|
|
100
|
+
for (let index = events.length - 1; index >= 0; index -= 1) if (events[index].type === "session/end-seed") {
|
|
101
|
+
boundary = index + 1;
|
|
102
|
+
break;
|
|
103
|
+
}
|
|
104
|
+
for (let index = events.length - 1; index >= boundary; index -= 1) {
|
|
105
|
+
const type = events[index].type;
|
|
106
|
+
if (type === "compaction/end") return false;
|
|
107
|
+
if (type === "compaction/start") return true;
|
|
108
|
+
}
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Compute the surface suffix a rewind to the start of one turn must replace.
|
|
113
|
+
* The cut is the turn's first appended human message; when a previous
|
|
114
|
+
* compaction or rewind already shadowed it, the cut is the replacement node
|
|
115
|
+
* covering it. System prompt nodes are never the cut.
|
|
116
|
+
* @param session - live session whose current surface is used.
|
|
117
|
+
* @param events - complete session log at the same cut.
|
|
118
|
+
* @param turn - host-assigned target turn.
|
|
119
|
+
* @returns the cut, or null when the surface already ends before that turn.
|
|
120
|
+
*/
|
|
121
|
+
function computeSurfaceCut(session, events, turn) {
|
|
122
|
+
const turnStart = events.find((event) => event.type === "turn/start" && event.data.turn === turn);
|
|
123
|
+
if (turnStart === void 0) throw new RewindError("no-turn", `Turn ${String(turn)} does not exist in this conversation.`);
|
|
124
|
+
if (!events.some((event) => event.type === "turn/end" && event.data.turn === turn)) throw new RewindError("busy", `Turn ${String(turn)} has not finished yet. Stop it before rewinding.`);
|
|
125
|
+
if (compactionOpen(events)) throw new RewindError("busy", "A context compaction is in progress. Wait for it to finish before rewinding.");
|
|
126
|
+
const nodes = session.surface.nodes;
|
|
127
|
+
if (nodes.length === 0) return null;
|
|
128
|
+
const bySeq = /* @__PURE__ */ new Map();
|
|
129
|
+
for (const event of events) bySeq.set(event.seq, event);
|
|
130
|
+
const eventAt = (seq) => {
|
|
131
|
+
const event = bySeq.get(seq);
|
|
132
|
+
if (event === void 0) throw new Error(`surface seq ${String(seq)} has no loaded event`);
|
|
133
|
+
return event;
|
|
134
|
+
};
|
|
135
|
+
const targetSeq = turnStart.seq;
|
|
136
|
+
const nextStartSeq = events.find((event) => event.type === "turn/start" && event.data.turn > turn)?.seq;
|
|
137
|
+
let index = -1;
|
|
138
|
+
for (let position = 0; position < nodes.length; position += 1) {
|
|
139
|
+
const event = eventAt(nodes[position]);
|
|
140
|
+
const seq = event.seq;
|
|
141
|
+
if (event.type === "user/message" && isAppend(event) && seq >= targetSeq && (nextStartSeq === void 0 || seq < nextStartSeq)) {
|
|
142
|
+
index = position;
|
|
143
|
+
break;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
if (index < 0) for (let position = 0; position < nodes.length; position += 1) {
|
|
147
|
+
const event = eventAt(nodes[position]);
|
|
148
|
+
if (covers$1(event, targetSeq) || coverStart$1(event) >= targetSeq) {
|
|
149
|
+
index = position;
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
if (index < 0) return null;
|
|
154
|
+
while (index < nodes.length && eventAt(nodes[index]).type === "system/message") index += 1;
|
|
155
|
+
if (index >= nodes.length) return null;
|
|
156
|
+
return {
|
|
157
|
+
startSeq: nodes[index],
|
|
158
|
+
endSeq: nodes[nodes.length - 1],
|
|
159
|
+
shadowed: nodes.slice(index),
|
|
160
|
+
turn
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
// src/compaction.ts
|
|
164
|
+
/**
|
|
165
|
+
* Idle-range context compaction: summarize one turn-bounded surface span with
|
|
166
|
+
* the agent's routed model and land it as a standard DSH compaction checkpoint
|
|
167
|
+
* inside a standalone `turn: null` bracket. The compaction backend's
|
|
168
|
+
* `compactRegion` only runs inside an open turn, so a human command between
|
|
169
|
+
* turns performs the same transaction here.
|
|
170
|
+
*/
|
|
171
|
+
/** Max output tokens requested from the summarization call. */
|
|
172
|
+
const SUMMARY_MAX_TOKENS = 8192;
|
|
173
|
+
/** Tags wrapping the structured summary inside the landed checkpoint node. */
|
|
174
|
+
const SUMMARY_OPEN_TAG = "<compacted-summary>";
|
|
175
|
+
const SUMMARY_CLOSE_TAG = "</compacted-summary>";
|
|
176
|
+
/** Instruction appended after the replayed conversation, matching the DSH backend. */
|
|
177
|
+
const COMPACTION_INSTRUCTION = [
|
|
178
|
+
"You are now acting as a compaction engine for this AI coding assistant. Condense the conversation ABOVE into a structured checkpoint that lets another model resume the work with no loss of essential context.",
|
|
179
|
+
"",
|
|
180
|
+
"Output EXACTLY the Markdown structure below: keep every section, in order. Use terse bullets, not prose paragraphs. Write \"(none)\" for an empty section — never drop a section.",
|
|
181
|
+
"",
|
|
182
|
+
"## Primary Request and Intent",
|
|
183
|
+
"- [the user's original and evolving goals; quote verbatim where the exact wording matters]",
|
|
184
|
+
"",
|
|
185
|
+
"## Key Technical Concepts",
|
|
186
|
+
"- [technologies, frameworks, patterns, and conventions in play]",
|
|
187
|
+
"",
|
|
188
|
+
"## Files and Code",
|
|
189
|
+
"- [exact path: why it matters, key changes or snippets]",
|
|
190
|
+
"",
|
|
191
|
+
"## Errors and Fixes",
|
|
192
|
+
"- [error: how it was resolved, plus any related user feedback]",
|
|
193
|
+
"",
|
|
194
|
+
"## Pending Jobs",
|
|
195
|
+
"- [explicitly requested work not yet completed]",
|
|
196
|
+
"",
|
|
197
|
+
"## Current Work",
|
|
198
|
+
"- [precisely what was in progress at this checkpoint]",
|
|
199
|
+
"",
|
|
200
|
+
"## Next Step",
|
|
201
|
+
"- [the single next action, directly in line with the most recent request, or \"(none)\"]",
|
|
202
|
+
"",
|
|
203
|
+
"## Critical Context",
|
|
204
|
+
"- [decisions and their rationale, constraints, user preferences, open questions, data needed to continue]",
|
|
205
|
+
"",
|
|
206
|
+
"Rules:",
|
|
207
|
+
"- Write concise English engineering prose. Preserve exact file paths, commands, error strings, identifiers, numeric values, function signatures, and syntax fragments.",
|
|
208
|
+
"- Capture user feedback and explicit instructions faithfully, especially corrections.",
|
|
209
|
+
"- Do NOT mention this summarization request or that the context was compacted.",
|
|
210
|
+
"- Output only the checkpoint text: do not call any tool or take any other action.",
|
|
211
|
+
`- If the conversation already contains a ${SUMMARY_OPEN_TAG} block, it is a PRIOR checkpoint. Do not copy it forward verbatim: preserve still-true facts, drop stale ones, and merge newer information into a single consolidated summary under the same structure.`
|
|
212
|
+
].join("\n");
|
|
213
|
+
/** Framing that makes the replacement user message established context. */
|
|
214
|
+
const CHECKPOINT_PREAMBLE = "This is an automatically generated checkpoint condensing an earlier span of the conversation to free up context. Treat the captured context as established background and build on it without restating it. Continue the task directly from the messages that follow, without acknowledging this checkpoint.";
|
|
215
|
+
/** First log position one surface node covers. */
|
|
216
|
+
function coverStart(event) {
|
|
217
|
+
const op = event.surfaceOp;
|
|
218
|
+
if (typeof op === "object" && op !== null && op.op === "replace") return Number(op.startSeq);
|
|
219
|
+
return event.seq;
|
|
220
|
+
}
|
|
221
|
+
/** Whether one surface node is a replacement covering a log position. */
|
|
222
|
+
function covers(event, seq) {
|
|
223
|
+
const op = event.surfaceOp;
|
|
224
|
+
if (typeof op !== "object" || op === null || op.op !== "replace") return false;
|
|
225
|
+
const range = op;
|
|
226
|
+
return Number(range.startSeq) <= seq && seq <= Number(range.endSeq);
|
|
227
|
+
}
|
|
228
|
+
/** Collect every shadowed seq and replacement range written by compactions. */
|
|
229
|
+
function compactionState(events) {
|
|
230
|
+
const shadowed = /* @__PURE__ */ new Set();
|
|
231
|
+
const ranges = [];
|
|
232
|
+
for (const event of events) {
|
|
233
|
+
const type = event.type;
|
|
234
|
+
if (type === "compaction/summary") {
|
|
235
|
+
const seqs = event.data.shadowedSeqs;
|
|
236
|
+
if (Array.isArray(seqs)) {
|
|
237
|
+
for (const seq of seqs) if (Number.isSafeInteger(seq) && seq >= 0) shadowed.add(Number(seq));
|
|
238
|
+
}
|
|
239
|
+
} else if (type === "user/message") {
|
|
240
|
+
const op = event.surfaceOp;
|
|
241
|
+
if (typeof op !== "object" || op === null || op.op !== "replace") continue;
|
|
242
|
+
if (event.data.source?.kind !== "compact-checkpoint") continue;
|
|
243
|
+
ranges.push({
|
|
244
|
+
start: Number(op.startSeq),
|
|
245
|
+
end: Number(op.endSeq)
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return {
|
|
250
|
+
shadowed,
|
|
251
|
+
ranges
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
/** First human prompt event of one turn, when the log still records one. */
|
|
255
|
+
function turnPrompt(events, turn) {
|
|
256
|
+
const start = events.find((event) => event.type === "turn/start" && event.data.turn === turn);
|
|
257
|
+
if (start === void 0) return void 0;
|
|
258
|
+
const limit = events.find((event) => event.type === "turn/start" && event.data.turn > turn)?.seq;
|
|
259
|
+
return events.find((event) => event.type === "user/message" && event.seq >= start.seq && (limit === void 0 || event.seq < limit) && event.data.source?.kind === "user");
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Whether an earlier compaction already shadowed a turn's prompt.
|
|
263
|
+
* @param events - complete session log.
|
|
264
|
+
* @param turn - host-assigned turn to test.
|
|
265
|
+
* @returns true when the turn is no longer part of the visible surface.
|
|
266
|
+
*/
|
|
267
|
+
function hiddenByCompaction(events, turn) {
|
|
268
|
+
const prompt = turnPrompt(events, turn);
|
|
269
|
+
if (prompt === void 0) return false;
|
|
270
|
+
const seq = prompt.seq;
|
|
271
|
+
const state = compactionState(events);
|
|
272
|
+
if (state.shadowed.has(seq)) return true;
|
|
273
|
+
return state.ranges.some((range) => range.start <= seq && seq <= range.end);
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Turn-level summary markers: newest compaction per turn boundary. Used by the
|
|
277
|
+
* list command to omit turns an earlier compaction already condensed.
|
|
278
|
+
* @param events - complete session log.
|
|
279
|
+
* @returns set of turns whose first prompt is shadowed.
|
|
280
|
+
*/
|
|
281
|
+
function compactedTurns(events) {
|
|
282
|
+
const state = compactionState(events);
|
|
283
|
+
const turns = /* @__PURE__ */ new Set();
|
|
284
|
+
const seen = /* @__PURE__ */ new Set();
|
|
285
|
+
let current;
|
|
286
|
+
for (const event of events) {
|
|
287
|
+
if (event.type === "turn/start") {
|
|
288
|
+
current = event.data.turn;
|
|
289
|
+
continue;
|
|
290
|
+
}
|
|
291
|
+
if (event.type === "turn/end") {
|
|
292
|
+
current = void 0;
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
if (event.type !== "user/message" || current === void 0 || seen.has(current)) continue;
|
|
296
|
+
if (event.data.source?.kind !== "user") continue;
|
|
297
|
+
seen.add(current);
|
|
298
|
+
const seq = event.seq;
|
|
299
|
+
if (state.shadowed.has(seq) || state.ranges.some((range) => seq >= range.start && seq <= range.end)) turns.add(current);
|
|
300
|
+
}
|
|
301
|
+
return turns;
|
|
302
|
+
}
|
|
303
|
+
/** Resolve one surface node's event from the loaded log. */
|
|
304
|
+
function eventAt(bySeq, seq) {
|
|
305
|
+
const event = bySeq.get(seq);
|
|
306
|
+
if (event === void 0) throw new Error(`surface seq ${String(seq)} has no loaded event`);
|
|
307
|
+
return event;
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* Plan the surface span one compaction mode replaces.
|
|
311
|
+
* @param session - live session whose current surface is read.
|
|
312
|
+
* @param events - complete session log at the same cut.
|
|
313
|
+
* @param turn - target turn.
|
|
314
|
+
* @param direction - summarize before or after the turn.
|
|
315
|
+
* @returns the span, or null when the selected side is empty.
|
|
316
|
+
*/
|
|
317
|
+
function planCompaction(session, events, turn, direction) {
|
|
318
|
+
const startEvent = events.find((event) => event.type === "turn/start" && event.data.turn === turn);
|
|
319
|
+
if (startEvent === void 0) throw new RewindError("no-turn", `Turn ${String(turn)} does not exist in this conversation.`);
|
|
320
|
+
const bySeq = /* @__PURE__ */ new Map();
|
|
321
|
+
for (const event of events) bySeq.set(event.seq, event);
|
|
322
|
+
const nodes = session.surface.nodes;
|
|
323
|
+
if (nodes.length === 0) return null;
|
|
324
|
+
const firstIndex = eventAt(bySeq, nodes[0]).type === "system/message" ? 1 : 0;
|
|
325
|
+
if (firstIndex >= nodes.length) return null;
|
|
326
|
+
const limit = events.find((event) => event.type === "turn/start" && event.data.turn > turn)?.seq;
|
|
327
|
+
let promptIndex = -1;
|
|
328
|
+
for (let index = firstIndex; index < nodes.length; index += 1) {
|
|
329
|
+
const event = eventAt(bySeq, nodes[index]);
|
|
330
|
+
if (event.type === "user/message" && event.surfaceOp === "append" && event.data.source?.kind === "user" && event.seq >= startEvent.seq && (limit === void 0 || event.seq < limit)) {
|
|
331
|
+
promptIndex = index;
|
|
332
|
+
break;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
if (promptIndex < 0) {
|
|
336
|
+
for (let index = firstIndex; index < nodes.length; index += 1) {
|
|
337
|
+
if (covers(eventAt(bySeq, nodes[index]), startEvent.seq)) return null;
|
|
338
|
+
if (coverStart(eventAt(bySeq, nodes[index])) >= startEvent.seq) return null;
|
|
339
|
+
}
|
|
340
|
+
return null;
|
|
341
|
+
}
|
|
342
|
+
if (direction === "before") {
|
|
343
|
+
if (promptIndex <= firstIndex) return null;
|
|
344
|
+
const shadowed = nodes.slice(firstIndex, promptIndex);
|
|
345
|
+
if (!shadowed.some((seq) => {
|
|
346
|
+
const event = eventAt(bySeq, seq);
|
|
347
|
+
return event.type === "user/message" && event.data.source?.kind === "user";
|
|
348
|
+
})) return null;
|
|
349
|
+
return {
|
|
350
|
+
turn,
|
|
351
|
+
direction,
|
|
352
|
+
start: shadowed[0],
|
|
353
|
+
end: shadowed[shadowed.length - 1],
|
|
354
|
+
shadowed
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
const shadowed = nodes.slice(promptIndex);
|
|
358
|
+
return {
|
|
359
|
+
turn,
|
|
360
|
+
direction,
|
|
361
|
+
start: shadowed[0],
|
|
362
|
+
end: shadowed[shadowed.length - 1],
|
|
363
|
+
shadowed
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
/** Frame the model summary as the durable checkpoint body. */
|
|
367
|
+
function frameSummary(summary) {
|
|
368
|
+
return [
|
|
369
|
+
{
|
|
370
|
+
type: "text",
|
|
371
|
+
text: `${CHECKPOINT_PREAMBLE}\n\n${SUMMARY_OPEN_TAG}`
|
|
372
|
+
},
|
|
373
|
+
...summary,
|
|
374
|
+
{
|
|
375
|
+
type: "text",
|
|
376
|
+
text: SUMMARY_CLOSE_TAG
|
|
377
|
+
}
|
|
378
|
+
];
|
|
379
|
+
}
|
|
380
|
+
/** Build the replay prefix (system head + shadowed messages) and instruction. */
|
|
381
|
+
function summarizationMessages(session, bySeq, shadowed) {
|
|
382
|
+
const nodes = session.surface.nodes;
|
|
383
|
+
const head = nodes.length === 0 ? void 0 : bySeq.get(nodes[0]);
|
|
384
|
+
const system = head === void 0 ? void 0 : session.deriveEventMessage(head);
|
|
385
|
+
const messages = [];
|
|
386
|
+
if (system !== null && system !== void 0) messages.push(system);
|
|
387
|
+
for (const seq of shadowed) {
|
|
388
|
+
const message = session.deriveEventMessage(eventAt(bySeq, seq));
|
|
389
|
+
if (message !== null) messages.push(message);
|
|
390
|
+
}
|
|
391
|
+
messages.push({
|
|
392
|
+
role: "user",
|
|
393
|
+
content: [{
|
|
394
|
+
type: "text",
|
|
395
|
+
text: COMPACTION_INSTRUCTION
|
|
396
|
+
}]
|
|
397
|
+
});
|
|
398
|
+
return messages;
|
|
399
|
+
}
|
|
400
|
+
/** Route the summary through the agent's latest routed model. */
|
|
401
|
+
function summarizeTarget(agent, session) {
|
|
402
|
+
const latest = session.requestHeader()?.config;
|
|
403
|
+
if (latest !== void 0 && latest.provider.length > 0 && latest.model.length > 0) return {
|
|
404
|
+
provider: latest.provider,
|
|
405
|
+
model: latest.model
|
|
406
|
+
};
|
|
407
|
+
const configured = agent.options;
|
|
408
|
+
if (configured?.provider !== void 0 && configured.provider.length > 0 && configured.model !== void 0 && configured.model.length > 0) return {
|
|
409
|
+
provider: configured.provider,
|
|
410
|
+
model: configured.model
|
|
411
|
+
};
|
|
412
|
+
throw new RewindError("compaction-unavailable", "No provider/model is available for summarization yet. Send one normal turn first.");
|
|
413
|
+
}
|
|
414
|
+
/** Run the routed summarization call and collect its text output. */
|
|
415
|
+
async function callSummary(llm, session, messages, provider, model, signal) {
|
|
416
|
+
const header = session.requestHeader();
|
|
417
|
+
const options = {
|
|
418
|
+
provider,
|
|
419
|
+
model,
|
|
420
|
+
messages: [...messages],
|
|
421
|
+
toolHistory: session.toolHistory(),
|
|
422
|
+
...header?.tools === void 0 ? {} : { tools: [...header.tools] },
|
|
423
|
+
maxTokens: SUMMARY_MAX_TOKENS,
|
|
424
|
+
sessionId: session.id,
|
|
425
|
+
purpose: "compaction",
|
|
426
|
+
signal
|
|
427
|
+
};
|
|
428
|
+
const closed = /* @__PURE__ */ new Map();
|
|
429
|
+
let delta = "";
|
|
430
|
+
let usage;
|
|
431
|
+
let finish;
|
|
432
|
+
for await (const chunk of llm.stream(options)) if (chunk.type === "text-delta") delta += chunk.text;
|
|
433
|
+
else if (chunk.type === "block-end") {
|
|
434
|
+
if (chunk.block.type === "text") closed.set(chunk.index, chunk.block);
|
|
435
|
+
} else if (chunk.type === "usage") usage = chunk.usage;
|
|
436
|
+
else if (chunk.type === "finish") finish = chunk.reason;
|
|
437
|
+
return {
|
|
438
|
+
blocks: closed.size > 0 ? [...closed.entries()].sort((left, right) => left[0] - right[0]).map((entry) => entry[1]) : delta.trim() === "" ? [] : [{
|
|
439
|
+
type: "text",
|
|
440
|
+
text: delta
|
|
441
|
+
}],
|
|
442
|
+
provider,
|
|
443
|
+
model,
|
|
444
|
+
...usage === void 0 ? {} : { usage },
|
|
445
|
+
finish
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
/** Reject a terminal summarization failure. */
|
|
449
|
+
function summaryFailure(finish, blocks) {
|
|
450
|
+
if (finish === void 0) return /* @__PURE__ */ new Error("summarization ended without a finish reason");
|
|
451
|
+
switch (finish.kind) {
|
|
452
|
+
case "error":
|
|
453
|
+
case "aborted": return /* @__PURE__ */ new Error("summarization request failed");
|
|
454
|
+
case "max-tokens": return /* @__PURE__ */ new Error("summarization was truncated at the token cap; try compacting a smaller range");
|
|
455
|
+
}
|
|
456
|
+
if (!blocks.some((block) => block.type === "text" && block.text.trim() !== "")) return /* @__PURE__ */ new Error("summarization produced no text summary content");
|
|
457
|
+
}
|
|
458
|
+
/** Throw when the selected span is no longer the same replacement target. */
|
|
459
|
+
function assertSpanStable(session, plan) {
|
|
460
|
+
const nodes = session.surface.nodes;
|
|
461
|
+
const start = nodes.indexOf(plan.start);
|
|
462
|
+
if (start < 0 || start + plan.shadowed.length > nodes.length) throw new RewindError("compaction-changed", "The selected history changed while the summary was running. Nothing was replaced; try again.");
|
|
463
|
+
for (let offset = 0; offset < plan.shadowed.length; offset += 1) if (nodes[start + offset] !== plan.shadowed[offset]) throw new RewindError("compaction-changed", "The selected history changed while the summary was running. Nothing was replaced; try again.");
|
|
464
|
+
}
|
|
465
|
+
/**
|
|
466
|
+
* Run one idle-range compaction transaction.
|
|
467
|
+
* @param deps - LLM and token-meter seams resolved from the Host composition.
|
|
468
|
+
* @param session - live session whose surface is replaced.
|
|
469
|
+
* @param events - log used to build the summarization prefix.
|
|
470
|
+
* @param plan - validated span to replace.
|
|
471
|
+
* @param agent - routing options and session owner.
|
|
472
|
+
* @param signal - cancellation for the request.
|
|
473
|
+
* @returns committed compaction facts.
|
|
474
|
+
*/
|
|
475
|
+
async function compactPlan(deps, session, events, plan, agent, signal) {
|
|
476
|
+
if (compactionOpen(events)) throw new RewindError("compaction-busy", "A context compaction is already running. Wait for it to finish.");
|
|
477
|
+
const bySeq = /* @__PURE__ */ new Map();
|
|
478
|
+
for (const event of events) bySeq.set(event.seq, event);
|
|
479
|
+
const messages = summarizationMessages(session, bySeq, plan.shadowed);
|
|
480
|
+
const target = summarizeTarget(agent, session);
|
|
481
|
+
const measured = new Map(deps.meter.measure(session).nodes.map((node) => [node.seq, node]));
|
|
482
|
+
const shadowedTokenCount = plan.shadowed.reduce((total, seq) => {
|
|
483
|
+
const node = measured.get(seq);
|
|
484
|
+
return total + (node === void 0 ? 0 : node.heuristicTokens);
|
|
485
|
+
}, 0);
|
|
486
|
+
const compactionId = randomUUID();
|
|
487
|
+
const lifecycle = {
|
|
488
|
+
compactionId,
|
|
489
|
+
turn: null
|
|
490
|
+
};
|
|
491
|
+
session.append("compaction/start", lifecycle);
|
|
492
|
+
let closed = false;
|
|
493
|
+
try {
|
|
494
|
+
const call = await callSummary(deps.llm, session, messages, target.provider, target.model, signal);
|
|
495
|
+
const failure = summaryFailure(call.finish, call.blocks);
|
|
496
|
+
if (failure !== void 0) throw failure;
|
|
497
|
+
assertSpanStable(session, plan);
|
|
498
|
+
const summary = call.blocks.filter((block) => block.type === "text");
|
|
499
|
+
const checkpoint = Object.freeze({
|
|
500
|
+
id: randomUUID(),
|
|
501
|
+
role: "user",
|
|
502
|
+
content: frameSummary(summary),
|
|
503
|
+
source: Object.freeze({
|
|
504
|
+
kind: "compact-checkpoint",
|
|
505
|
+
compactionId
|
|
506
|
+
})
|
|
507
|
+
});
|
|
508
|
+
session.append("compaction/summary", {
|
|
509
|
+
compactionId,
|
|
510
|
+
summary,
|
|
511
|
+
shadowedRange: {
|
|
512
|
+
start: plan.start,
|
|
513
|
+
end: plan.end
|
|
514
|
+
},
|
|
515
|
+
shadowedSeqs: [...plan.shadowed],
|
|
516
|
+
shadowedTokenCount,
|
|
517
|
+
provider: call.provider,
|
|
518
|
+
model: call.model,
|
|
519
|
+
maxTokens: SUMMARY_MAX_TOKENS,
|
|
520
|
+
...call.usage === void 0 ? {} : { usage: call.usage },
|
|
521
|
+
rawOutput: summary,
|
|
522
|
+
llmStreamCall: true
|
|
523
|
+
});
|
|
524
|
+
const appended = session.append("user/message", checkpoint, {
|
|
525
|
+
surfaceOp: {
|
|
526
|
+
op: "replace",
|
|
527
|
+
startSeq: plan.start,
|
|
528
|
+
endSeq: plan.end
|
|
529
|
+
},
|
|
530
|
+
sourceEventSeqs: [...plan.shadowed]
|
|
531
|
+
});
|
|
532
|
+
session.append("compaction/end", lifecycle);
|
|
533
|
+
closed = true;
|
|
534
|
+
return {
|
|
535
|
+
compactionId,
|
|
536
|
+
summarySeq: appended.seq,
|
|
537
|
+
shadowedItemCount: plan.shadowed.length,
|
|
538
|
+
shadowedTokenCount,
|
|
539
|
+
summaryTokenCount: deps.meter.estimateMessage(checkpoint)
|
|
540
|
+
};
|
|
541
|
+
} catch (error) {
|
|
542
|
+
if (!closed) try {
|
|
543
|
+
session.append("compaction/end", {
|
|
544
|
+
...lifecycle,
|
|
545
|
+
error: error instanceof Error ? error.message : String(error)
|
|
546
|
+
});
|
|
547
|
+
} catch {}
|
|
548
|
+
if (error instanceof RewindError) throw error;
|
|
549
|
+
if (signal.aborted) throw new RewindError("cancelled", "Compaction was cancelled.");
|
|
550
|
+
throw new RewindError("compaction-failed", `Context compaction failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
// src/paths.ts
|
|
554
|
+
/** Small path and file helpers shared by the Git store and the command. */
|
|
555
|
+
/** Convert a native path to slash-separated form for Git pathspecs. */
|
|
556
|
+
function toPosix(path) {
|
|
557
|
+
return path.split(sep).join("/");
|
|
558
|
+
}
|
|
559
|
+
/** Whether a path is the same as, or strictly inside, a root. */
|
|
560
|
+
function isInside(root, path) {
|
|
561
|
+
const rel = relative(root, path);
|
|
562
|
+
return rel !== "" && !isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`);
|
|
563
|
+
}
|
|
564
|
+
/** Canonical absolute path, resolving symlinks of the nearest existing ancestor. */
|
|
565
|
+
async function canonicalPath(path) {
|
|
566
|
+
try {
|
|
567
|
+
return await realpath(path);
|
|
568
|
+
} catch {
|
|
569
|
+
const parent = dirname(path);
|
|
570
|
+
if (parent === path) return path;
|
|
571
|
+
return join(await canonicalPath(parent), path.slice(parent.length + 1));
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
/** Lowercase hexadecimal SHA-256 of one string. */
|
|
575
|
+
function sha256(text) {
|
|
576
|
+
return createHash("sha256").update(text).digest("hex");
|
|
577
|
+
}
|
|
578
|
+
/** Read a UTF-8 JSON file, returning undefined for a missing or unreadable file. */
|
|
579
|
+
async function readJsonFile(path) {
|
|
580
|
+
try {
|
|
581
|
+
return JSON.parse(await readFile(path, "utf8"));
|
|
582
|
+
} catch {
|
|
583
|
+
return;
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
/** Atomically replace one UTF-8 file through a sibling temporary file. */
|
|
587
|
+
async function writeJsonAtomic(path, value) {
|
|
588
|
+
await mkdir(dirname(path), { recursive: true });
|
|
589
|
+
const temporary = `${path}.${process.pid}.${Date.now()}.tmp`;
|
|
590
|
+
await writeFile(temporary, `${JSON.stringify(value)}\n`, { mode: 384 });
|
|
591
|
+
await rename(temporary, path);
|
|
592
|
+
}
|
|
593
|
+
/** Remove one path and, when requested, its descendants; missing paths are ignored. */
|
|
594
|
+
async function removePath(path) {
|
|
595
|
+
await rm(path, {
|
|
596
|
+
recursive: true,
|
|
597
|
+
force: true
|
|
598
|
+
});
|
|
599
|
+
}
|
|
600
|
+
/** Directory under `<storageDir>/workspaces` that owns one repository's objects. */
|
|
601
|
+
function workspaceKey(repoRoot) {
|
|
602
|
+
return sha256(repoRoot).slice(0, 24);
|
|
603
|
+
}
|
|
604
|
+
// src/git/runner.ts
|
|
605
|
+
/** Reject a failed command with its stderr. */
|
|
606
|
+
function assertGit(result, what) {
|
|
607
|
+
if (result.exitCode !== 0) throw new Error(`${what} failed: ${result.stderr.trim()}`);
|
|
608
|
+
return result;
|
|
609
|
+
}
|
|
610
|
+
/** Milliseconds a terminated git child gets to exit. */
|
|
611
|
+
const TERMINATE_GRACE_MS = 2e3;
|
|
612
|
+
/** Retained stderr tail for diagnostics. */
|
|
613
|
+
const STDERR_TAIL_BYTES = 16384;
|
|
614
|
+
/** Resolve the git executable once; the macOS developer-tools stub counts as absent. */
|
|
615
|
+
async function resolveGit(subprocess, signal) {
|
|
616
|
+
let executable;
|
|
617
|
+
try {
|
|
618
|
+
executable = await subprocess.resolveExecutable("git", void 0, signal);
|
|
619
|
+
} catch {
|
|
620
|
+
return null;
|
|
621
|
+
}
|
|
622
|
+
if (process.platform !== "darwin" || executable !== "/usr/bin/git") return executable;
|
|
623
|
+
return (await subprocess.spawn({
|
|
624
|
+
argv: ["/usr/bin/xcode-select", "-p"],
|
|
625
|
+
cwd: process.env.HOME ?? "/",
|
|
626
|
+
stdio: {
|
|
627
|
+
stdin: "ignore",
|
|
628
|
+
stdout: { maxBytes: 4096 },
|
|
629
|
+
stderr: { maxBytes: 4096 }
|
|
630
|
+
},
|
|
631
|
+
graceMs: 1e3,
|
|
632
|
+
signal
|
|
633
|
+
}).done.catch(() => ({ exitCode: null }))).exitCode === 0 ? executable : null;
|
|
634
|
+
}
|
|
635
|
+
/** Git runner over the Host subprocess capability. */
|
|
636
|
+
var SubprocessGit = class {
|
|
637
|
+
subprocess;
|
|
638
|
+
executable;
|
|
639
|
+
limits;
|
|
640
|
+
constructor(subprocess, executable, limits) {
|
|
641
|
+
this.subprocess = subprocess;
|
|
642
|
+
this.executable = executable;
|
|
643
|
+
this.limits = limits;
|
|
644
|
+
}
|
|
645
|
+
async run(args, options) {
|
|
646
|
+
const timeout = AbortSignal.timeout(this.limits.timeoutMs);
|
|
647
|
+
const signal = AbortSignal.any([options.signal, timeout]);
|
|
648
|
+
const handle = this.subprocess.spawn({
|
|
649
|
+
argv: [this.executable, ...args],
|
|
650
|
+
cwd: options.cwd,
|
|
651
|
+
stdio: {
|
|
652
|
+
stdin: options.stdin === void 0 ? "ignore" : { data: options.stdin },
|
|
653
|
+
stdout: { maxBytes: options.maxBytes ?? this.limits.outputMaxBytes },
|
|
654
|
+
stderr: { maxBytes: STDERR_TAIL_BYTES }
|
|
655
|
+
},
|
|
656
|
+
graceMs: TERMINATE_GRACE_MS,
|
|
657
|
+
signal,
|
|
658
|
+
env: {
|
|
659
|
+
GIT_CONFIG_COUNT: "0",
|
|
660
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
661
|
+
GIT_OPTIONAL_LOCKS: "0",
|
|
662
|
+
LC_ALL: "C",
|
|
663
|
+
...options.env
|
|
664
|
+
}
|
|
665
|
+
});
|
|
666
|
+
const outcome = await handle.done;
|
|
667
|
+
if (signal.aborted) throw new Error(`git ${args.join(" ")} ${timeout.aborted ? `timed out after ${this.limits.timeoutMs}ms` : "was aborted"}`);
|
|
668
|
+
const stdout = handle.collected.stdout?.readFrom(0) ?? {
|
|
669
|
+
text: "",
|
|
670
|
+
lossy: false
|
|
671
|
+
};
|
|
672
|
+
const stderr = handle.collected.stderr?.readFrom(0).text ?? "";
|
|
673
|
+
return {
|
|
674
|
+
exitCode: outcome.exitCode,
|
|
675
|
+
stdout: stdout.text,
|
|
676
|
+
stderr,
|
|
677
|
+
truncated: stdout.lossy
|
|
678
|
+
};
|
|
679
|
+
}
|
|
680
|
+
};
|
|
681
|
+
// src/git/snapshot.ts
|
|
682
|
+
/**
|
|
683
|
+
* Git working-tree snapshots through a private object store: capture a tree,
|
|
684
|
+
* diff two trees, and restore selected paths without touching the repository's
|
|
685
|
+
* own index, objects, refs, or work-tree history.
|
|
686
|
+
*/
|
|
687
|
+
/** Paths per `checkout-index --stdin` invocation; keeps argv and stdin bounded. */
|
|
688
|
+
const RESTORE_CHUNK = 200;
|
|
689
|
+
/** Whether a filesystem error names a missing path. */
|
|
690
|
+
function isMissing(error) {
|
|
691
|
+
return typeof error === "object" && error !== null && error.code === "ENOENT";
|
|
692
|
+
}
|
|
693
|
+
/**
|
|
694
|
+
* Write the complete work tree, including untracked and modified files but not
|
|
695
|
+
* ignored ones, as a tree object through a private index seeded from the
|
|
696
|
+
* repository's index. New blobs and the tree land in the private object store.
|
|
697
|
+
* @param git - command runner.
|
|
698
|
+
* @param workspace - addressed repository with its private object store.
|
|
699
|
+
* @param signal - cancellation.
|
|
700
|
+
* @returns the tree object id.
|
|
701
|
+
*/
|
|
702
|
+
async function snapshotTree(git, workspace, signal) {
|
|
703
|
+
await mkdir(workspace.scratch, {
|
|
704
|
+
recursive: true,
|
|
705
|
+
mode: 448
|
|
706
|
+
});
|
|
707
|
+
const scratch = await mkdtemp(join(workspace.scratch, "index-"));
|
|
708
|
+
try {
|
|
709
|
+
const index = join(scratch, "index");
|
|
710
|
+
await copyFile(join(workspace.gitDir, "index"), index).catch((error) => {
|
|
711
|
+
if (!isMissing(error)) throw error;
|
|
712
|
+
});
|
|
713
|
+
const env = {
|
|
714
|
+
...workspace.env,
|
|
715
|
+
GIT_INDEX_FILE: index
|
|
716
|
+
};
|
|
717
|
+
const pathspec = workspace.excludes.length === 0 ? [] : [
|
|
718
|
+
"--",
|
|
719
|
+
".",
|
|
720
|
+
...workspace.excludes.map((path) => `:(exclude)${path}`)
|
|
721
|
+
];
|
|
722
|
+
const added = await git.run([
|
|
723
|
+
"add",
|
|
724
|
+
"--all",
|
|
725
|
+
"--ignore-errors",
|
|
726
|
+
...pathspec
|
|
727
|
+
], {
|
|
728
|
+
cwd: workspace.root,
|
|
729
|
+
env,
|
|
730
|
+
signal
|
|
731
|
+
});
|
|
732
|
+
if (added.exitCode !== 1) assertGit(added, `git add in ${workspace.root}`);
|
|
733
|
+
const tree = assertGit(await git.run(["write-tree"], {
|
|
734
|
+
cwd: workspace.root,
|
|
735
|
+
env,
|
|
736
|
+
signal
|
|
737
|
+
}), "git write-tree").stdout.trim();
|
|
738
|
+
if (!/^[0-9a-f]{40,64}$/.test(tree)) throw new Error("git write-tree returned an unexpected object id");
|
|
739
|
+
return tree;
|
|
740
|
+
} finally {
|
|
741
|
+
await rm(scratch, {
|
|
742
|
+
recursive: true,
|
|
743
|
+
force: true
|
|
744
|
+
});
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
/**
|
|
748
|
+
* List the work-tree paths that differ between two snapshot trees without
|
|
749
|
+
* rename detection, so both ends of a rename appear as a deletion and an add.
|
|
750
|
+
* @param git - command runner.
|
|
751
|
+
* @param workspace - addressed repository.
|
|
752
|
+
* @param before - checkpoint tree id.
|
|
753
|
+
* @param after - current tree id.
|
|
754
|
+
* @param signal - cancellation.
|
|
755
|
+
* @returns changed paths relative to the repository root.
|
|
756
|
+
*/
|
|
757
|
+
async function changedPaths(git, workspace, before, after, signal) {
|
|
758
|
+
if (before === after) return [];
|
|
759
|
+
const result = assertGit(await git.run([
|
|
760
|
+
"diff-tree",
|
|
761
|
+
"-r",
|
|
762
|
+
"-z",
|
|
763
|
+
"--no-renames",
|
|
764
|
+
"--name-status",
|
|
765
|
+
before,
|
|
766
|
+
after
|
|
767
|
+
], {
|
|
768
|
+
cwd: workspace.root,
|
|
769
|
+
env: workspace.env,
|
|
770
|
+
signal
|
|
771
|
+
}), "git diff-tree");
|
|
772
|
+
if (result.truncated) throw new Error("git diff-tree output exceeded the configured cap");
|
|
773
|
+
const tokens = result.stdout.split("\0");
|
|
774
|
+
const changes = [];
|
|
775
|
+
for (let index = 0; index + 1 < tokens.length; index += 2) {
|
|
776
|
+
const status = tokens[index];
|
|
777
|
+
const path = tokens[index + 1];
|
|
778
|
+
if (status === "" && path === "") break;
|
|
779
|
+
if (status === "" || path === "") throw new Error("git diff-tree returned an unexpected record");
|
|
780
|
+
if (status !== "M" && status !== "T" && status !== "A" && status !== "D") throw new Error(`git diff-tree returned unsupported status ${JSON.stringify(status)}`);
|
|
781
|
+
changes.push({
|
|
782
|
+
status,
|
|
783
|
+
path
|
|
784
|
+
});
|
|
785
|
+
}
|
|
786
|
+
return changes;
|
|
787
|
+
}
|
|
788
|
+
/**
|
|
789
|
+
* Work-tree paths one snapshot tree records as gitlinks (nested repositories
|
|
790
|
+
* and submodules), whose contents snapshots never descend into.
|
|
791
|
+
* @param git - command runner.
|
|
792
|
+
* @param workspace - addressed repository.
|
|
793
|
+
* @param tree - snapshot tree id.
|
|
794
|
+
* @param maxBytes - stdout cap for the tree listing.
|
|
795
|
+
* @param signal - cancellation.
|
|
796
|
+
* @returns repo-relative gitlink paths.
|
|
797
|
+
*/
|
|
798
|
+
async function gitlinkPaths(git, workspace, tree, maxBytes, signal) {
|
|
799
|
+
const result = assertGit(await git.run([
|
|
800
|
+
"ls-tree",
|
|
801
|
+
"-r",
|
|
802
|
+
"-z",
|
|
803
|
+
"--full-tree",
|
|
804
|
+
tree
|
|
805
|
+
], {
|
|
806
|
+
cwd: workspace.root,
|
|
807
|
+
env: workspace.env,
|
|
808
|
+
maxBytes,
|
|
809
|
+
signal
|
|
810
|
+
}), "git ls-tree");
|
|
811
|
+
if (result.truncated) throw new Error("git ls-tree output exceeded the configured cap");
|
|
812
|
+
const links = /* @__PURE__ */ new Set();
|
|
813
|
+
for (const record of result.stdout.split("\0")) {
|
|
814
|
+
if (!record.startsWith("160000 ")) continue;
|
|
815
|
+
const tab = record.indexOf(" ");
|
|
816
|
+
if (tab !== -1) links.add(record.slice(tab + 1));
|
|
817
|
+
}
|
|
818
|
+
return links;
|
|
819
|
+
}
|
|
820
|
+
/**
|
|
821
|
+
* Materialize selected paths from one snapshot tree into the work tree. File
|
|
822
|
+
* modes, executable bits, and symbolic links follow the tree.
|
|
823
|
+
* @param git - command runner.
|
|
824
|
+
* @param workspace - addressed repository.
|
|
825
|
+
* @param tree - tree whose entries are written.
|
|
826
|
+
* @param paths - repo-relative paths to write.
|
|
827
|
+
* @param signal - cancellation.
|
|
828
|
+
* @returns per-path failures; an empty array means every path was written.
|
|
829
|
+
*/
|
|
830
|
+
async function restoreTreePaths(git, workspace, tree, paths, signal) {
|
|
831
|
+
if (paths.length === 0) return [];
|
|
832
|
+
await mkdir(workspace.scratch, {
|
|
833
|
+
recursive: true,
|
|
834
|
+
mode: 448
|
|
835
|
+
});
|
|
836
|
+
const scratch = await mkdtemp(join(workspace.scratch, "restore-"));
|
|
837
|
+
try {
|
|
838
|
+
const index = join(scratch, "index");
|
|
839
|
+
const env = {
|
|
840
|
+
...workspace.env,
|
|
841
|
+
GIT_INDEX_FILE: index
|
|
842
|
+
};
|
|
843
|
+
assertGit(await git.run(["read-tree", tree], {
|
|
844
|
+
cwd: workspace.root,
|
|
845
|
+
env,
|
|
846
|
+
signal
|
|
847
|
+
}), "git read-tree");
|
|
848
|
+
const checkoutEnv = {
|
|
849
|
+
...env,
|
|
850
|
+
GIT_WORK_TREE: workspace.root,
|
|
851
|
+
GIT_LITERAL_PATHSPECS: "1"
|
|
852
|
+
};
|
|
853
|
+
const failures = [];
|
|
854
|
+
for (let offset = 0; offset < paths.length; offset += RESTORE_CHUNK) {
|
|
855
|
+
const chunk = paths.slice(offset, offset + RESTORE_CHUNK);
|
|
856
|
+
if ((await git.run([
|
|
857
|
+
"checkout-index",
|
|
858
|
+
"-f",
|
|
859
|
+
"-z",
|
|
860
|
+
"--stdin"
|
|
861
|
+
], {
|
|
862
|
+
cwd: workspace.root,
|
|
863
|
+
env: checkoutEnv,
|
|
864
|
+
stdin: `${chunk.join("\0")}\0`,
|
|
865
|
+
signal
|
|
866
|
+
})).exitCode === 0) continue;
|
|
867
|
+
for (const path of chunk) {
|
|
868
|
+
const single = await git.run([
|
|
869
|
+
"checkout-index",
|
|
870
|
+
"-f",
|
|
871
|
+
"-z",
|
|
872
|
+
"--stdin"
|
|
873
|
+
], {
|
|
874
|
+
cwd: workspace.root,
|
|
875
|
+
env: checkoutEnv,
|
|
876
|
+
stdin: `${path}\0`,
|
|
877
|
+
signal
|
|
878
|
+
});
|
|
879
|
+
if (single.exitCode !== 0) failures.push({
|
|
880
|
+
path,
|
|
881
|
+
reason: single.stderr.trim() || `git checkout-index exited ${String(single.exitCode)}`
|
|
882
|
+
});
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
return failures;
|
|
886
|
+
} finally {
|
|
887
|
+
await rm(scratch, {
|
|
888
|
+
recursive: true,
|
|
889
|
+
force: true
|
|
890
|
+
});
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
/**
|
|
894
|
+
* Remove work-tree paths that the checkpoint tree does not hold.
|
|
895
|
+
* @param root - repository top-level directory.
|
|
896
|
+
* @param paths - repo-relative paths to remove.
|
|
897
|
+
* @returns per-path failures; a missing path is not a failure.
|
|
898
|
+
*/
|
|
899
|
+
async function removeWorktreePaths(root, paths) {
|
|
900
|
+
const failures = [];
|
|
901
|
+
for (const path of paths) {
|
|
902
|
+
const absolute = resolve(root, path);
|
|
903
|
+
if (absolute !== root && !isInside(root, absolute)) {
|
|
904
|
+
failures.push({
|
|
905
|
+
path,
|
|
906
|
+
reason: "path escapes the repository root"
|
|
907
|
+
});
|
|
908
|
+
continue;
|
|
909
|
+
}
|
|
910
|
+
try {
|
|
911
|
+
if ((await lstat(absolute)).isDirectory()) {
|
|
912
|
+
failures.push({
|
|
913
|
+
path,
|
|
914
|
+
reason: "path is a directory now; inspect it manually"
|
|
915
|
+
});
|
|
916
|
+
continue;
|
|
917
|
+
}
|
|
918
|
+
await unlink(absolute);
|
|
919
|
+
} catch (error) {
|
|
920
|
+
if (isMissing(error)) continue;
|
|
921
|
+
failures.push({
|
|
922
|
+
path,
|
|
923
|
+
reason: error instanceof Error ? error.message : String(error)
|
|
924
|
+
});
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
return failures;
|
|
928
|
+
}
|
|
929
|
+
// src/replay.ts
|
|
930
|
+
/** Read one event's surface operation without importing runtime helpers. */
|
|
931
|
+
function surfaceOpOf(event) {
|
|
932
|
+
return event.surfaceOp;
|
|
933
|
+
}
|
|
934
|
+
/**
|
|
935
|
+
* Fold the surface node list of one event window. This mirrors the core fold
|
|
936
|
+
* for node membership only; message projections never change nodes.
|
|
937
|
+
* @param events - contiguous log events starting at seq 0.
|
|
938
|
+
* @returns surface event seqs in model-visible order.
|
|
939
|
+
*/
|
|
940
|
+
function foldSurfaceNodes(events) {
|
|
941
|
+
const nodes = [];
|
|
942
|
+
for (const event of events) {
|
|
943
|
+
const op = surfaceOpOf(event);
|
|
944
|
+
if (op === void 0) continue;
|
|
945
|
+
if (op === "append") {
|
|
946
|
+
nodes.push(event.seq);
|
|
947
|
+
continue;
|
|
948
|
+
}
|
|
949
|
+
if (typeof op !== "object" || op === null || op.op !== "replace") throw new RewindError("conversation-unavailable", `Unknown surface operation on event ${String(event.seq)}.`);
|
|
950
|
+
const range = op;
|
|
951
|
+
const startSeq = Number(range.startSeq);
|
|
952
|
+
const endSeq = Number(range.endSeq);
|
|
953
|
+
const start = nodes.indexOf(startSeq);
|
|
954
|
+
const end = nodes.indexOf(endSeq);
|
|
955
|
+
if (!Number.isSafeInteger(startSeq) || !Number.isSafeInteger(endSeq) || start < 0 || end < 0 || start > end) throw new RewindError("conversation-unavailable", `The log's surface history around event ${String(event.seq)} cannot be replayed safely.`);
|
|
956
|
+
nodes.splice(start, end - start + 1, event.seq);
|
|
957
|
+
}
|
|
958
|
+
return nodes;
|
|
959
|
+
}
|
|
960
|
+
/**
|
|
961
|
+
* Plan one same-session replay to the state before a turn whose surface was
|
|
962
|
+
* condensed by a compaction.
|
|
963
|
+
* @param session - live session whose current surface is authoritative.
|
|
964
|
+
* @param events - complete session log at the same cut.
|
|
965
|
+
* @param turn - host-assigned target turn.
|
|
966
|
+
* @param cut - seq of the target turn's `turn/start`.
|
|
967
|
+
* @returns the replay plan.
|
|
968
|
+
* @throws RewindError when the desired prefix cannot be reconstructed.
|
|
969
|
+
*/
|
|
970
|
+
function planReplay(session, events, turn, cut) {
|
|
971
|
+
if (events.length === 0 || events[0].seq !== 0) throw new RewindError("conversation-unavailable", "The conversation log is not fully loaded for a replay.");
|
|
972
|
+
if (openTurn(events) !== void 0) throw new RewindError("busy", "The conversation still has an open turn; wait for it to settle before rewinding.");
|
|
973
|
+
if (!Number.isSafeInteger(cut) || cut < 0 || cut > events.length) throw new RewindError("conversation-unavailable", `Turn ${String(turn)} has no usable replay boundary.`);
|
|
974
|
+
const current = foldSurfaceNodes(events);
|
|
975
|
+
const live = session.surface.nodes;
|
|
976
|
+
if (current.length !== live.length || current.some((seq, index) => seq !== live[index])) throw new RewindError("conversation-unavailable", "The live conversation surface does not match the loaded log; retry after the session settles.");
|
|
977
|
+
const bySeq = /* @__PURE__ */ new Map();
|
|
978
|
+
for (const event of events) bySeq.set(event.seq, event);
|
|
979
|
+
const lookup = (seq) => {
|
|
980
|
+
const event = bySeq.get(seq);
|
|
981
|
+
if (event === void 0) throw new RewindError("conversation-unavailable", `Replay source event ${String(seq)} is not loaded.`);
|
|
982
|
+
return event;
|
|
983
|
+
};
|
|
984
|
+
let systemEnd = 0;
|
|
985
|
+
while (systemEnd < current.length && lookup(current[systemEnd]).type === "system/message") systemEnd += 1;
|
|
986
|
+
const currentConversation = current.slice(systemEnd);
|
|
987
|
+
const desiredConversation = foldSurfaceNodes(events.slice(0, cut)).filter((seq) => {
|
|
988
|
+
const event = lookup(seq);
|
|
989
|
+
if (event.type === "system/message") return false;
|
|
990
|
+
if (event.type !== "user/message") return true;
|
|
991
|
+
return event.data.source?.kind !== "rewind-checkpoint";
|
|
992
|
+
});
|
|
993
|
+
let common = 0;
|
|
994
|
+
while (common < desiredConversation.length && common < currentConversation.length && desiredConversation[common] === currentConversation[common]) common += 1;
|
|
995
|
+
const desiredTail = desiredConversation.slice(common);
|
|
996
|
+
const currentTail = currentConversation.slice(common);
|
|
997
|
+
const first = desiredTail.length === 0 ? void 0 : lookup(desiredTail[0]);
|
|
998
|
+
const pivot = first?.type === "user/message" ? first : null;
|
|
999
|
+
return {
|
|
1000
|
+
turn,
|
|
1001
|
+
cut,
|
|
1002
|
+
pivot,
|
|
1003
|
+
copies: (pivot === null ? desiredTail : desiredTail.slice(1)).map(lookup),
|
|
1004
|
+
shadowed: currentTail
|
|
1005
|
+
};
|
|
1006
|
+
}
|
|
1007
|
+
/** Give a copied message a fresh identity so it cannot collide with its source. */
|
|
1008
|
+
function replayMessageId(original, seq) {
|
|
1009
|
+
return `rewind-replay-${String(seq)}-${String(original)}`;
|
|
1010
|
+
}
|
|
1011
|
+
/** Clone one projected message with a fresh identity and optional source override. */
|
|
1012
|
+
function copyMessage(message, seq, source) {
|
|
1013
|
+
const copy = structuredClone(message);
|
|
1014
|
+
copy["id"] = replayMessageId(copy["id"], seq);
|
|
1015
|
+
if (source !== void 0) copy["source"] = source;
|
|
1016
|
+
return copy;
|
|
1017
|
+
}
|
|
1018
|
+
/** Clone one surface event (with its projected message) into an append input. */
|
|
1019
|
+
function copyInput(event, projected) {
|
|
1020
|
+
if (event.type === "user/message") return [
|
|
1021
|
+
"user/message",
|
|
1022
|
+
copyMessage(projected, event.seq, { kind: "user" }),
|
|
1023
|
+
{ surfaceOp: "append" }
|
|
1024
|
+
];
|
|
1025
|
+
const data = structuredClone(event.data);
|
|
1026
|
+
data["message"] = copyMessage(projected, event.seq);
|
|
1027
|
+
if (event.type === "assistant/message") {
|
|
1028
|
+
data["stream"] = [];
|
|
1029
|
+
delete data["usage"];
|
|
1030
|
+
}
|
|
1031
|
+
return [
|
|
1032
|
+
event.type,
|
|
1033
|
+
data,
|
|
1034
|
+
{ surfaceOp: "append" }
|
|
1035
|
+
];
|
|
1036
|
+
}
|
|
1037
|
+
/** Advertised tool calls of one projected assistant message. */
|
|
1038
|
+
function advertisedCalls(message) {
|
|
1039
|
+
const calls = [];
|
|
1040
|
+
for (const block of message.content) {
|
|
1041
|
+
if (block.type !== "tool-call") continue;
|
|
1042
|
+
calls.push({
|
|
1043
|
+
id: block.id,
|
|
1044
|
+
name: block.name,
|
|
1045
|
+
arguments: block.arguments
|
|
1046
|
+
});
|
|
1047
|
+
}
|
|
1048
|
+
return calls;
|
|
1049
|
+
}
|
|
1050
|
+
/** Whether the log ends with an open turn the synthetic envelope would conflict with. */
|
|
1051
|
+
function openTurn(events) {
|
|
1052
|
+
let current;
|
|
1053
|
+
for (const event of events) if (event.type === "turn/start") current = event.data.turn;
|
|
1054
|
+
else if (event.type === "turn/end" && event.data.turn === current) current = void 0;
|
|
1055
|
+
return current;
|
|
1056
|
+
}
|
|
1057
|
+
/** Next host turn number, used only for the internal replay envelope. */
|
|
1058
|
+
function nextTurn(events) {
|
|
1059
|
+
let last = 0;
|
|
1060
|
+
for (const event of events) if (event.type === "turn/start") last = Math.max(last, event.data.turn);
|
|
1061
|
+
return last + 1;
|
|
1062
|
+
}
|
|
1063
|
+
/** One replay append member with the internal turn tag ignored by the picker. */
|
|
1064
|
+
function envelopeInput(type, data) {
|
|
1065
|
+
return [type, data];
|
|
1066
|
+
}
|
|
1067
|
+
/** The call id of one projected tool message. */
|
|
1068
|
+
function toolCallId(message) {
|
|
1069
|
+
return message.role === "tool" ? String(message.toolCallId) : void 0;
|
|
1070
|
+
}
|
|
1071
|
+
/**
|
|
1072
|
+
* Append one replay: the first rebuilt user message replaces the compacted
|
|
1073
|
+
* tail and the remaining rebuilt messages are appended after it; an empty
|
|
1074
|
+
* developer cut node is used when the pivot cannot be the replacement. No
|
|
1075
|
+
* separate surface marker is written.
|
|
1076
|
+
*
|
|
1077
|
+
* Assistant messages and the cut node require an open turn and step, so a
|
|
1078
|
+
* replay with either writes a tagged internal turn around the copies. The
|
|
1079
|
+
* tag keeps that turn out of the picker and its assistant messages carry the
|
|
1080
|
+
* matching tool/call events, so a reload accepts the log.
|
|
1081
|
+
* @param session - live session to append to.
|
|
1082
|
+
* @param plan - validated replay plan.
|
|
1083
|
+
* @param at - epoch milliseconds of the target turn start.
|
|
1084
|
+
* @param headKind - source kind of the fallback cut head; `rewind-undo` marks
|
|
1085
|
+
* an undo of the previous rewind instead of a new rewind.
|
|
1086
|
+
* @returns the replacement message's seq and the synthetic envelope turn.
|
|
1087
|
+
*/
|
|
1088
|
+
function appendReplay(session, plan, at, headKind = "rewind-cut") {
|
|
1089
|
+
const events = session.snapshotEvents();
|
|
1090
|
+
if (openTurn(events) !== void 0) throw new RewindError("busy", "The conversation still has an open turn; wait for it to settle before rewinding.");
|
|
1091
|
+
const copies = [];
|
|
1092
|
+
for (const event of plan.copies) {
|
|
1093
|
+
const projected = session.deriveEventMessage(event);
|
|
1094
|
+
if (projected !== null) copies.push({
|
|
1095
|
+
event,
|
|
1096
|
+
projected
|
|
1097
|
+
});
|
|
1098
|
+
}
|
|
1099
|
+
const needsEnvelope = plan.pivot === null || copies.some((entry) => entry.event.type !== "user/message");
|
|
1100
|
+
const syntheticTurn = needsEnvelope ? nextTurn(events) : plan.turn;
|
|
1101
|
+
const step = needsEnvelope ? 1 : 0;
|
|
1102
|
+
const inputs = [];
|
|
1103
|
+
if (needsEnvelope) {
|
|
1104
|
+
inputs.push(envelopeInput("turn/start", {
|
|
1105
|
+
turn: syntheticTurn,
|
|
1106
|
+
rewindReplay: true
|
|
1107
|
+
}));
|
|
1108
|
+
inputs.push(envelopeInput("step/start", {
|
|
1109
|
+
turn: syntheticTurn,
|
|
1110
|
+
step
|
|
1111
|
+
}));
|
|
1112
|
+
}
|
|
1113
|
+
let head;
|
|
1114
|
+
if (plan.pivot !== null) {
|
|
1115
|
+
const projected = session.deriveEventMessage(plan.pivot);
|
|
1116
|
+
if (projected === null) throw new RewindError("conversation-unavailable", `The first message before turn ${String(plan.turn)} projects to no model message.`);
|
|
1117
|
+
head = copyMessage(projected, plan.pivot.seq, {
|
|
1118
|
+
kind: "rewind-replay",
|
|
1119
|
+
turn: plan.turn,
|
|
1120
|
+
cut: plan.cut,
|
|
1121
|
+
at
|
|
1122
|
+
});
|
|
1123
|
+
} else head = {
|
|
1124
|
+
turn: syntheticTurn,
|
|
1125
|
+
step,
|
|
1126
|
+
message: {
|
|
1127
|
+
id: `rewind-replay-cut-${randomUUID()}`,
|
|
1128
|
+
role: "developer",
|
|
1129
|
+
content: [],
|
|
1130
|
+
source: {
|
|
1131
|
+
kind: headKind,
|
|
1132
|
+
turn: plan.turn,
|
|
1133
|
+
cut: plan.cut,
|
|
1134
|
+
at
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
};
|
|
1138
|
+
const headType = plan.pivot !== null ? "user/message" : "developer/message";
|
|
1139
|
+
const intent = plan.shadowed.length === 0 ? { surfaceOp: "append" } : {
|
|
1140
|
+
surfaceOp: {
|
|
1141
|
+
op: "replace",
|
|
1142
|
+
startSeq: plan.shadowed[0],
|
|
1143
|
+
endSeq: plan.shadowed[plan.shadowed.length - 1]
|
|
1144
|
+
},
|
|
1145
|
+
sourceEventSeqs: [...plan.shadowed]
|
|
1146
|
+
};
|
|
1147
|
+
const headIndex = inputs.length;
|
|
1148
|
+
inputs.push([
|
|
1149
|
+
headType,
|
|
1150
|
+
head,
|
|
1151
|
+
intent
|
|
1152
|
+
]);
|
|
1153
|
+
const resultIds = /* @__PURE__ */ new Set();
|
|
1154
|
+
for (const { event, projected } of copies) {
|
|
1155
|
+
if (event.type !== "tool/result") continue;
|
|
1156
|
+
const callId = toolCallId(projected);
|
|
1157
|
+
if (callId !== void 0) resultIds.add(callId);
|
|
1158
|
+
}
|
|
1159
|
+
const advertised = /* @__PURE__ */ new Set();
|
|
1160
|
+
for (const { event, projected } of copies) {
|
|
1161
|
+
if (event.type === "user/message") {
|
|
1162
|
+
inputs.push(copyInput(event, projected));
|
|
1163
|
+
continue;
|
|
1164
|
+
}
|
|
1165
|
+
if (event.type === "assistant/message") {
|
|
1166
|
+
const message = copyMessage(projected, event.seq);
|
|
1167
|
+
const calls = advertisedCalls(message);
|
|
1168
|
+
const kept = calls.filter((call) => resultIds.has(call.id));
|
|
1169
|
+
let copy = message;
|
|
1170
|
+
if (kept.length !== calls.length) {
|
|
1171
|
+
const keep = new Set(kept.map((call) => call.id));
|
|
1172
|
+
copy = {
|
|
1173
|
+
...message,
|
|
1174
|
+
content: message.content.filter((block) => block.type !== "tool-call" || keep.has(block.id))
|
|
1175
|
+
};
|
|
1176
|
+
}
|
|
1177
|
+
const data = structuredClone(event.data);
|
|
1178
|
+
data["message"] = copy;
|
|
1179
|
+
data["stream"] = [];
|
|
1180
|
+
delete data["usage"];
|
|
1181
|
+
if (needsEnvelope) {
|
|
1182
|
+
data["turn"] = syntheticTurn;
|
|
1183
|
+
data["step"] = step;
|
|
1184
|
+
}
|
|
1185
|
+
inputs.push([
|
|
1186
|
+
event.type,
|
|
1187
|
+
data,
|
|
1188
|
+
{ surfaceOp: "append" }
|
|
1189
|
+
]);
|
|
1190
|
+
if (!needsEnvelope) continue;
|
|
1191
|
+
for (const call of kept) {
|
|
1192
|
+
advertised.add(call.id);
|
|
1193
|
+
inputs.push(["tool/call", {
|
|
1194
|
+
turn: syntheticTurn,
|
|
1195
|
+
step,
|
|
1196
|
+
callId: call.id,
|
|
1197
|
+
name: call.name,
|
|
1198
|
+
arguments: call.arguments
|
|
1199
|
+
}]);
|
|
1200
|
+
}
|
|
1201
|
+
continue;
|
|
1202
|
+
}
|
|
1203
|
+
if (event.type === "tool/result") {
|
|
1204
|
+
const callId = toolCallId(projected);
|
|
1205
|
+
if (needsEnvelope && (callId === void 0 || !advertised.has(callId))) continue;
|
|
1206
|
+
const data = structuredClone(event.data);
|
|
1207
|
+
data["message"] = copyMessage(projected, event.seq);
|
|
1208
|
+
if (needsEnvelope) {
|
|
1209
|
+
data["turn"] = syntheticTurn;
|
|
1210
|
+
data["step"] = step;
|
|
1211
|
+
}
|
|
1212
|
+
inputs.push([
|
|
1213
|
+
event.type,
|
|
1214
|
+
data,
|
|
1215
|
+
{ surfaceOp: "append" }
|
|
1216
|
+
]);
|
|
1217
|
+
continue;
|
|
1218
|
+
}
|
|
1219
|
+
if (event.type === "developer/message") {
|
|
1220
|
+
const data = structuredClone(event.data);
|
|
1221
|
+
data["message"] = copyMessage(projected, event.seq);
|
|
1222
|
+
if (needsEnvelope) {
|
|
1223
|
+
data["turn"] = syntheticTurn;
|
|
1224
|
+
data["step"] = step;
|
|
1225
|
+
}
|
|
1226
|
+
inputs.push([
|
|
1227
|
+
event.type,
|
|
1228
|
+
data,
|
|
1229
|
+
{ surfaceOp: "append" }
|
|
1230
|
+
]);
|
|
1231
|
+
continue;
|
|
1232
|
+
}
|
|
1233
|
+
inputs.push(copyInput(event, projected));
|
|
1234
|
+
}
|
|
1235
|
+
if (needsEnvelope) {
|
|
1236
|
+
inputs.push(envelopeInput("step/end", {
|
|
1237
|
+
turn: syntheticTurn,
|
|
1238
|
+
step
|
|
1239
|
+
}));
|
|
1240
|
+
inputs.push(envelopeInput("turn/end", {
|
|
1241
|
+
turn: syntheticTurn,
|
|
1242
|
+
reason: { kind: "completed" }
|
|
1243
|
+
}));
|
|
1244
|
+
}
|
|
1245
|
+
return {
|
|
1246
|
+
head: session.append(inputs)[headIndex].seq,
|
|
1247
|
+
...needsEnvelope ? { turn: syntheticTurn } : {}
|
|
1248
|
+
};
|
|
1249
|
+
}
|
|
1250
|
+
// src/undo.ts
|
|
1251
|
+
/** Validate and plan an undo of the last applied rewind. */
|
|
1252
|
+
/** Stable fingerprint of one model surface's node order. */
|
|
1253
|
+
function surfaceHash(nodes) {
|
|
1254
|
+
return createHash("sha256").update(nodes.join(",")).digest("hex");
|
|
1255
|
+
}
|
|
1256
|
+
/**
|
|
1257
|
+
* Plan the rebuild that restores the surface a rewind replaced: an empty
|
|
1258
|
+
* developer cut replaces the rewind's suffix, and the shadowed messages are
|
|
1259
|
+
* copied back after it.
|
|
1260
|
+
* @param session - live session whose surface is undoed.
|
|
1261
|
+
* @param events - complete session log.
|
|
1262
|
+
* @param record - undo record written by the rewind.
|
|
1263
|
+
* @returns the replay plan, with a cut head and every shadowed message as a copy.
|
|
1264
|
+
* @throws RewindError when the conversation moved on since the rewind.
|
|
1265
|
+
*/
|
|
1266
|
+
function planUndo(session, events, record) {
|
|
1267
|
+
const conversation = record.conversation;
|
|
1268
|
+
if (conversation === void 0) throw new RewindError("no-undo", "The last rewind did not change the conversation.");
|
|
1269
|
+
if (openTurn(events) !== void 0) throw new RewindError("busy", "The conversation still has an open turn; wait for it to settle before undoing.");
|
|
1270
|
+
const nodes = session.surface.nodes;
|
|
1271
|
+
if (surfaceHash(nodes) !== conversation.surfaceHash) throw new RewindError("undo-stale", "The conversation changed after the last rewind; undo is no longer available.");
|
|
1272
|
+
const index = nodes.findIndex((seq) => seq === conversation.head);
|
|
1273
|
+
if (index < 0) throw new RewindError("undo-stale", "The rewind head is no longer on the conversation surface; undo is no longer available.");
|
|
1274
|
+
const bySeq = /* @__PURE__ */ new Map();
|
|
1275
|
+
for (const event of events) bySeq.set(event.seq, event);
|
|
1276
|
+
const copies = [];
|
|
1277
|
+
for (const seq of conversation.shadowed) {
|
|
1278
|
+
const event = bySeq.get(seq);
|
|
1279
|
+
if (event === void 0) throw new RewindError("undo-stale", `The restored message ${String(seq)} is no longer in the session log; undo is no longer available.`);
|
|
1280
|
+
copies.push(event);
|
|
1281
|
+
}
|
|
1282
|
+
return {
|
|
1283
|
+
turn: record.turn,
|
|
1284
|
+
cut: conversation.shadowed[0] ?? conversation.head,
|
|
1285
|
+
pivot: null,
|
|
1286
|
+
copies,
|
|
1287
|
+
shadowed: nodes.slice(index)
|
|
1288
|
+
};
|
|
1289
|
+
}
|
|
1290
|
+
/**
|
|
1291
|
+
* Cheap availability check for the list command and picker. File drift is
|
|
1292
|
+
* checked by the undo itself, which needs a work-tree snapshot.
|
|
1293
|
+
* @param session - live session.
|
|
1294
|
+
* @param events - complete session log.
|
|
1295
|
+
* @param record - stored undo record, if any.
|
|
1296
|
+
* @returns the undo summary, or undefined when nothing was recorded.
|
|
1297
|
+
*/
|
|
1298
|
+
function undoAvailability(session, events, record) {
|
|
1299
|
+
if (record === void 0) return void 0;
|
|
1300
|
+
const conversation = record.conversation;
|
|
1301
|
+
let available = true;
|
|
1302
|
+
if (conversation !== void 0) available = openTurn(events) === void 0 && surfaceHash(session.surface.nodes) === conversation.surfaceHash && session.surface.nodes.some((seq) => seq === conversation.head);
|
|
1303
|
+
return {
|
|
1304
|
+
turn: record.turn,
|
|
1305
|
+
at: record.at,
|
|
1306
|
+
files: record.files !== void 0,
|
|
1307
|
+
conversation: conversation !== void 0,
|
|
1308
|
+
available
|
|
1309
|
+
};
|
|
1310
|
+
}
|
|
1311
|
+
// src/command.ts
|
|
1312
|
+
/** Prompt preview length used by the checkpoint list. */
|
|
1313
|
+
const PROMPT_PREVIEW_LIMIT = 80;
|
|
1314
|
+
/** Path samples printed in one command result. */
|
|
1315
|
+
const PATH_SAMPLE_LIMIT = 8;
|
|
1316
|
+
const USAGE = [
|
|
1317
|
+
"Usage:",
|
|
1318
|
+
" /rewind list [--json] [--brief]",
|
|
1319
|
+
" /rewind apply <turn> [--files] [--conversation] [--compact-before|--compact-after] [--dry-run] [--json]",
|
|
1320
|
+
" /rewind undo [--dry-run] [--json]"
|
|
1321
|
+
].join("\n");
|
|
1322
|
+
/** Whether one command failure is expected and safe to render. */
|
|
1323
|
+
function errorResult(text) {
|
|
1324
|
+
return {
|
|
1325
|
+
kind: "error",
|
|
1326
|
+
text
|
|
1327
|
+
};
|
|
1328
|
+
}
|
|
1329
|
+
/** Collapse a message's text blocks into one bounded preview line. */
|
|
1330
|
+
function preview(content, limit) {
|
|
1331
|
+
let text = "";
|
|
1332
|
+
for (const block of content) {
|
|
1333
|
+
if (block.type !== "text") continue;
|
|
1334
|
+
text += text === "" ? block.text : ` ${block.text}`;
|
|
1335
|
+
if (text.length >= limit * 2) break;
|
|
1336
|
+
}
|
|
1337
|
+
const normalized = text.replace(/\s+/g, " ").trim();
|
|
1338
|
+
return normalized.length > limit - 1 ? `${normalized.slice(0, limit - 1).trimEnd()}…` : normalized;
|
|
1339
|
+
}
|
|
1340
|
+
/**
|
|
1341
|
+
* Fold turn boundaries, start times, and first human prompt previews.
|
|
1342
|
+
* @param events - complete session log.
|
|
1343
|
+
* @returns turns in ascending order.
|
|
1344
|
+
*/
|
|
1345
|
+
function deriveTurns(events) {
|
|
1346
|
+
const turns = [];
|
|
1347
|
+
let current;
|
|
1348
|
+
/** Internal replay turn opened by this plugin; it is not a user-visible turn. */
|
|
1349
|
+
let internal;
|
|
1350
|
+
for (const event of events) {
|
|
1351
|
+
if (event.type === "turn/start") {
|
|
1352
|
+
if (event.data.rewindReplay === true) {
|
|
1353
|
+
internal = event.data.turn;
|
|
1354
|
+
current = void 0;
|
|
1355
|
+
continue;
|
|
1356
|
+
}
|
|
1357
|
+
internal = void 0;
|
|
1358
|
+
current = {
|
|
1359
|
+
turn: event.data.turn,
|
|
1360
|
+
startSeq: event.seq,
|
|
1361
|
+
at: event.time,
|
|
1362
|
+
prompt: "",
|
|
1363
|
+
ended: false
|
|
1364
|
+
};
|
|
1365
|
+
turns.push(current);
|
|
1366
|
+
continue;
|
|
1367
|
+
}
|
|
1368
|
+
if (event.type === "turn/end") {
|
|
1369
|
+
if (internal === event.data.turn) {
|
|
1370
|
+
internal = void 0;
|
|
1371
|
+
current = void 0;
|
|
1372
|
+
continue;
|
|
1373
|
+
}
|
|
1374
|
+
const fact = turns.find((entry) => entry.turn === event.data.turn);
|
|
1375
|
+
if (fact !== void 0) fact.ended = true;
|
|
1376
|
+
if (current?.turn === event.data.turn) current = void 0;
|
|
1377
|
+
continue;
|
|
1378
|
+
}
|
|
1379
|
+
if (event.type !== "user/message") continue;
|
|
1380
|
+
if (internal !== void 0) continue;
|
|
1381
|
+
if (event.data.source.kind !== "user") continue;
|
|
1382
|
+
const target = current ?? turns.at(-1);
|
|
1383
|
+
if (target === void 0 || target.prompt !== "") continue;
|
|
1384
|
+
target.prompt = preview(event.data.content, PROMPT_PREVIEW_LIMIT);
|
|
1385
|
+
}
|
|
1386
|
+
return turns;
|
|
1387
|
+
}
|
|
1388
|
+
/** Whether a session is a subagent conversation the command refuses to rewind. */
|
|
1389
|
+
function isSubagent(session) {
|
|
1390
|
+
return session.header.origin === "subagent" || (session.header.delegationDepth ?? 0) > 0;
|
|
1391
|
+
}
|
|
1392
|
+
/** Parse the command's own grammar. */
|
|
1393
|
+
function parse(rawInput) {
|
|
1394
|
+
const tokens = rawInput.trim().split(/\s+/).filter((token) => token !== "");
|
|
1395
|
+
if (tokens.length === 0) return { kind: "help" };
|
|
1396
|
+
const subcommand = tokens[0];
|
|
1397
|
+
if (subcommand === "list") {
|
|
1398
|
+
const flags = new Set(tokens.slice(1));
|
|
1399
|
+
if ([...flags].some((flag) => flag !== "--json" && flag !== "--brief")) return {
|
|
1400
|
+
kind: "invalid",
|
|
1401
|
+
message: USAGE
|
|
1402
|
+
};
|
|
1403
|
+
return {
|
|
1404
|
+
kind: "list",
|
|
1405
|
+
json: flags.has("--json"),
|
|
1406
|
+
brief: flags.has("--brief")
|
|
1407
|
+
};
|
|
1408
|
+
}
|
|
1409
|
+
if (subcommand === "undo") {
|
|
1410
|
+
const flags = new Set(tokens.slice(1));
|
|
1411
|
+
if ([...flags].some((flag) => flag !== "--dry-run" && flag !== "--json")) return {
|
|
1412
|
+
kind: "invalid",
|
|
1413
|
+
message: USAGE
|
|
1414
|
+
};
|
|
1415
|
+
return {
|
|
1416
|
+
kind: "undo",
|
|
1417
|
+
dryRun: flags.has("--dry-run"),
|
|
1418
|
+
json: flags.has("--json")
|
|
1419
|
+
};
|
|
1420
|
+
}
|
|
1421
|
+
if (subcommand === "apply") {
|
|
1422
|
+
const turnToken = tokens[1];
|
|
1423
|
+
if (turnToken === void 0 || !/^\d+$/.test(turnToken)) return {
|
|
1424
|
+
kind: "invalid",
|
|
1425
|
+
message: USAGE
|
|
1426
|
+
};
|
|
1427
|
+
const turn = Number(turnToken);
|
|
1428
|
+
if (!Number.isSafeInteger(turn)) return {
|
|
1429
|
+
kind: "invalid",
|
|
1430
|
+
message: USAGE
|
|
1431
|
+
};
|
|
1432
|
+
const flags = new Set(tokens.slice(2));
|
|
1433
|
+
const allowed = /* @__PURE__ */ new Set([
|
|
1434
|
+
"--files",
|
|
1435
|
+
"--conversation",
|
|
1436
|
+
"--compact-before",
|
|
1437
|
+
"--compact-after",
|
|
1438
|
+
"--dry-run",
|
|
1439
|
+
"--json"
|
|
1440
|
+
]);
|
|
1441
|
+
for (const flag of flags) if (!allowed.has(flag)) return {
|
|
1442
|
+
kind: "invalid",
|
|
1443
|
+
message: USAGE
|
|
1444
|
+
};
|
|
1445
|
+
const compactBefore = flags.has("--compact-before");
|
|
1446
|
+
const compactAfter = flags.has("--compact-after");
|
|
1447
|
+
const files = flags.has("--files");
|
|
1448
|
+
const conversation = flags.has("--conversation");
|
|
1449
|
+
if (compactBefore && compactAfter || (compactBefore || compactAfter) && (files || conversation)) return {
|
|
1450
|
+
kind: "invalid",
|
|
1451
|
+
message: USAGE
|
|
1452
|
+
};
|
|
1453
|
+
return {
|
|
1454
|
+
kind: "apply",
|
|
1455
|
+
turn,
|
|
1456
|
+
mode: compactBefore ? "compact-before" : compactAfter ? "compact-after" : files && conversation ? "both" : files ? "files" : conversation ? "conversation" : "both",
|
|
1457
|
+
dryRun: flags.has("--dry-run"),
|
|
1458
|
+
json: flags.has("--json")
|
|
1459
|
+
};
|
|
1460
|
+
}
|
|
1461
|
+
return {
|
|
1462
|
+
kind: "invalid",
|
|
1463
|
+
message: USAGE
|
|
1464
|
+
};
|
|
1465
|
+
}
|
|
1466
|
+
/** Bounded path sample for one human-readable result. */
|
|
1467
|
+
function pathSample(paths) {
|
|
1468
|
+
if (paths.length === 0) return "";
|
|
1469
|
+
const sample = paths.slice(0, PATH_SAMPLE_LIMIT).join(", ");
|
|
1470
|
+
return paths.length > PATH_SAMPLE_LIMIT ? `${sample} (+${String(paths.length - PATH_SAMPLE_LIMIT)} more)` : sample;
|
|
1471
|
+
}
|
|
1472
|
+
/** Human-readable failure list. */
|
|
1473
|
+
function failureText(failures) {
|
|
1474
|
+
return failures.slice(0, PATH_SAMPLE_LIMIT).map((failure) => `${failure.path}: ${failure.reason}`).join("; ");
|
|
1475
|
+
}
|
|
1476
|
+
/**
|
|
1477
|
+
* Compare the current work tree with every recorded checkpoint tree.
|
|
1478
|
+
* Turns without a usable checkpoint report why files cannot be restored.
|
|
1479
|
+
* @param deps - host dependencies.
|
|
1480
|
+
* @param sessionId - session whose index is read.
|
|
1481
|
+
* @param signal - cancellation for the Git calls.
|
|
1482
|
+
* @returns per-turn file state; unknown when it could not be measured.
|
|
1483
|
+
*/
|
|
1484
|
+
async function fileStates(deps, sessionId, signal) {
|
|
1485
|
+
const record = await deps.store.load(sessionId);
|
|
1486
|
+
const states = /* @__PURE__ */ new Map();
|
|
1487
|
+
const groups = /* @__PURE__ */ new Map();
|
|
1488
|
+
for (const checkpoint of record.checkpoints) {
|
|
1489
|
+
if (!checkpoint.complete) {
|
|
1490
|
+
states.set(checkpoint.turn, "unavailable");
|
|
1491
|
+
continue;
|
|
1492
|
+
}
|
|
1493
|
+
states.set(checkpoint.turn, "unknown");
|
|
1494
|
+
const group = groups.get(checkpoint.repoRoot);
|
|
1495
|
+
if (group === void 0) groups.set(checkpoint.repoRoot, [{
|
|
1496
|
+
turn: checkpoint.turn,
|
|
1497
|
+
beforeTree: checkpoint.beforeTree
|
|
1498
|
+
}]);
|
|
1499
|
+
else group.push({
|
|
1500
|
+
turn: checkpoint.turn,
|
|
1501
|
+
beforeTree: checkpoint.beforeTree
|
|
1502
|
+
});
|
|
1503
|
+
}
|
|
1504
|
+
if (groups.size === 0) return states;
|
|
1505
|
+
const git = await deps.git();
|
|
1506
|
+
if (git === null) return states;
|
|
1507
|
+
for (const [root, checkpoints] of groups) try {
|
|
1508
|
+
const workspace = await deps.workspaces.forRoot(root, signal);
|
|
1509
|
+
if (workspace === null) continue;
|
|
1510
|
+
const current = await snapshotTree(git, workspace, signal);
|
|
1511
|
+
for (const checkpoint of checkpoints) states.set(checkpoint.turn, checkpoint.beforeTree === current ? "none" : "changed");
|
|
1512
|
+
} catch {}
|
|
1513
|
+
return states;
|
|
1514
|
+
}
|
|
1515
|
+
/** List rewindable turns, file-change state, and whether a turn is still visible. */
|
|
1516
|
+
async function listCheckpoints(deps, invocation, json, brief) {
|
|
1517
|
+
const sessionId = invocation.agent.session.id;
|
|
1518
|
+
const observation = await deps.observe(sessionId);
|
|
1519
|
+
try {
|
|
1520
|
+
const events = observation.events;
|
|
1521
|
+
const turns = deriveTurns(events).filter((turn) => turn.prompt !== "");
|
|
1522
|
+
const record = await deps.store.load(sessionId);
|
|
1523
|
+
const checkpoints = new Map(record.checkpoints.map((checkpoint) => [checkpoint.turn, checkpoint]));
|
|
1524
|
+
let files = /* @__PURE__ */ new Map();
|
|
1525
|
+
if (turns.length > 0) try {
|
|
1526
|
+
files = await fileStates(deps, sessionId, invocation.signal);
|
|
1527
|
+
} catch (error) {
|
|
1528
|
+
deps.logger.warn(`rewind: could not inspect checkpoint file state: ${error instanceof Error ? error.message : String(error)}`);
|
|
1529
|
+
}
|
|
1530
|
+
const condensed = compactedTurns(events);
|
|
1531
|
+
const undo = undoAvailability(invocation.agent.session, events, record.undo);
|
|
1532
|
+
const rows = turns.map((turn) => {
|
|
1533
|
+
const checkpoint = checkpoints.get(turn.turn);
|
|
1534
|
+
const state = checkpoint === void 0 ? "missing" : checkpoint.complete ? "ready" : "unavailable";
|
|
1535
|
+
return {
|
|
1536
|
+
turn: turn.turn,
|
|
1537
|
+
at: turn.at,
|
|
1538
|
+
prompt: turn.prompt,
|
|
1539
|
+
checkpoint: state,
|
|
1540
|
+
files: files.get(turn.turn) ?? (checkpoint === void 0 ? "missing" : "unknown"),
|
|
1541
|
+
hidden: hiddenByRewind(events, turn.turn),
|
|
1542
|
+
compacted: condensed.has(turn.turn)
|
|
1543
|
+
};
|
|
1544
|
+
});
|
|
1545
|
+
if (json) {
|
|
1546
|
+
const turns = brief ? rows.map((row) => ({
|
|
1547
|
+
turn: row.turn,
|
|
1548
|
+
files: row.files,
|
|
1549
|
+
hidden: row.hidden,
|
|
1550
|
+
compacted: row.compacted
|
|
1551
|
+
})) : rows;
|
|
1552
|
+
return {
|
|
1553
|
+
kind: "success",
|
|
1554
|
+
text: JSON.stringify({
|
|
1555
|
+
sessionId,
|
|
1556
|
+
turns,
|
|
1557
|
+
...undo === void 0 ? {} : { undo }
|
|
1558
|
+
})
|
|
1559
|
+
};
|
|
1560
|
+
}
|
|
1561
|
+
if (rows.length === 0) return {
|
|
1562
|
+
kind: "success",
|
|
1563
|
+
text: "No rewindable turns yet."
|
|
1564
|
+
};
|
|
1565
|
+
const lines = ["Rewind checkpoints:"];
|
|
1566
|
+
for (const row of rows) {
|
|
1567
|
+
const markers = `${row.hidden ? " [hidden]" : ""}${row.compacted ? " [compacted]" : ""}`;
|
|
1568
|
+
const changes = row.files === "changed" ? ", changes" : row.files === "none" ? ", clean" : "";
|
|
1569
|
+
lines.push(` turn ${String(row.turn)} ${new Date(row.at).toISOString()} "${row.prompt}" [files: ${row.checkpoint}${changes}]${markers}`);
|
|
1570
|
+
}
|
|
1571
|
+
lines.push("Use /rewind apply <turn> [--files] [--conversation] [--compact-before|--compact-after] to rewind.");
|
|
1572
|
+
if (undo?.available) {
|
|
1573
|
+
const halves = [undo.files ? "files" : "", undo.conversation ? "conversation" : ""].filter((part) => part !== "");
|
|
1574
|
+
lines.push(`Undo available: last rewind to before turn ${String(undo.turn)} (${halves.join(", ")}). Use /rewind undo.`);
|
|
1575
|
+
}
|
|
1576
|
+
return {
|
|
1577
|
+
kind: "success",
|
|
1578
|
+
text: lines.join("\n")
|
|
1579
|
+
};
|
|
1580
|
+
} finally {
|
|
1581
|
+
observation.dispose();
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
1584
|
+
/** Snapshot the current tree, diff it against the target, and prepare the writes. */
|
|
1585
|
+
async function prepareTreeRestore(deps, repoRoot, tree, expectedTree, signal) {
|
|
1586
|
+
const git = await deps.git();
|
|
1587
|
+
if (git === null) throw new RewindError("no-git", "File rewind requires a usable git on the Host.");
|
|
1588
|
+
const workspace = await deps.workspaces.forRoot(repoRoot, signal);
|
|
1589
|
+
if (workspace === null) throw new RewindError("no-repository", `The recorded repository (${repoRoot}) is no longer available.`);
|
|
1590
|
+
let currentTree;
|
|
1591
|
+
let changes;
|
|
1592
|
+
try {
|
|
1593
|
+
currentTree = await snapshotTree(git, workspace, signal);
|
|
1594
|
+
if (expectedTree !== void 0 && currentTree !== expectedTree) throw new RewindError("undo-stale", "The work tree changed after the last rewind; undo would discard those changes.");
|
|
1595
|
+
changes = await changedPaths(git, workspace, tree, currentTree, signal);
|
|
1596
|
+
} catch (error) {
|
|
1597
|
+
if (error instanceof RewindError) throw error;
|
|
1598
|
+
throw new RewindError("restore-failed", `Could not read the current work tree: ${error instanceof Error ? error.message : String(error)}`);
|
|
1599
|
+
}
|
|
1600
|
+
if (changes.length === 0) return {
|
|
1601
|
+
git,
|
|
1602
|
+
workspace,
|
|
1603
|
+
tree,
|
|
1604
|
+
currentTree,
|
|
1605
|
+
write: [],
|
|
1606
|
+
remove: [],
|
|
1607
|
+
skipped: []
|
|
1608
|
+
};
|
|
1609
|
+
if (changes.length > deps.config.maxPathsPerRestore) throw new RewindError("too-many-paths", `${String(changes.length)} paths differ from the restore target, above the limit of ${String(deps.config.maxPathsPerRestore)}. Rewind the conversation only, or raise maxPathsPerRestore.`);
|
|
1610
|
+
let links;
|
|
1611
|
+
try {
|
|
1612
|
+
links = {
|
|
1613
|
+
before: await gitlinkPaths(git, workspace, tree, deps.config.outputMaxBytes, signal),
|
|
1614
|
+
current: await gitlinkPaths(git, workspace, currentTree, deps.config.outputMaxBytes, signal)
|
|
1615
|
+
};
|
|
1616
|
+
} catch (error) {
|
|
1617
|
+
throw new RewindError("restore-failed", `Could not inspect the restore trees: ${error instanceof Error ? error.message : String(error)}`);
|
|
1618
|
+
}
|
|
1619
|
+
const skipped = [];
|
|
1620
|
+
const write = [];
|
|
1621
|
+
const remove = [];
|
|
1622
|
+
for (const change of changes) {
|
|
1623
|
+
if (links.before.has(change.path) || links.current.has(change.path)) {
|
|
1624
|
+
skipped.push(change.path);
|
|
1625
|
+
continue;
|
|
1626
|
+
}
|
|
1627
|
+
if (change.status === "A") remove.push(change.path);
|
|
1628
|
+
else write.push(change.path);
|
|
1629
|
+
}
|
|
1630
|
+
return {
|
|
1631
|
+
git,
|
|
1632
|
+
workspace,
|
|
1633
|
+
tree,
|
|
1634
|
+
currentTree,
|
|
1635
|
+
write,
|
|
1636
|
+
remove,
|
|
1637
|
+
skipped
|
|
1638
|
+
};
|
|
1639
|
+
}
|
|
1640
|
+
/** Write or delete the prepared paths, unless this is a dry run. */
|
|
1641
|
+
async function applyTreeRestore(plan, dryRun, signal) {
|
|
1642
|
+
if (!dryRun && (plan.write.length > 0 || plan.remove.length > 0)) {
|
|
1643
|
+
let failures;
|
|
1644
|
+
try {
|
|
1645
|
+
failures = [...await restoreTreePaths(plan.git, plan.workspace, plan.tree, plan.write, signal), ...await removeWorktreePaths(plan.workspace.root, plan.remove)];
|
|
1646
|
+
} catch (error) {
|
|
1647
|
+
throw new RewindError("restore-failed", `File restore failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1648
|
+
}
|
|
1649
|
+
if (failures.length > 0) {
|
|
1650
|
+
const applied = plan.write.length + plan.remove.length - failures.length;
|
|
1651
|
+
throw new RewindError("restore-failed", `${String(failures.length)} path(s) could not be restored (${failureText(failures)}); ${String(applied)} path(s) may already have changed. The conversation was not changed; retry after resolving them.`);
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
return {
|
|
1655
|
+
restored: plan.write.length,
|
|
1656
|
+
deleted: plan.remove.length,
|
|
1657
|
+
skipped: plan.skipped,
|
|
1658
|
+
paths: [...plan.write, ...plan.remove]
|
|
1659
|
+
};
|
|
1660
|
+
}
|
|
1661
|
+
/** Take the current tree, diff it against the checkpoint, and apply the file half. */
|
|
1662
|
+
async function applyFiles(deps, sessionId, turn, dryRun, signal) {
|
|
1663
|
+
const checkpoint = await deps.store.checkpoint(sessionId, turn);
|
|
1664
|
+
if (checkpoint === void 0) throw new RewindError("no-checkpoint", `No file checkpoint was recorded for turn ${String(turn)}.`);
|
|
1665
|
+
if (!checkpoint.complete) {
|
|
1666
|
+
const reason = checkpoint.reason === void 0 ? "" : `: ${checkpoint.reason}`;
|
|
1667
|
+
throw new RewindError("no-checkpoint", `The file checkpoint for turn ${String(turn)} is unavailable${reason}.`);
|
|
1668
|
+
}
|
|
1669
|
+
const plan = await prepareTreeRestore(deps, checkpoint.repoRoot, checkpoint.beforeTree, void 0, signal);
|
|
1670
|
+
const outcome = await applyTreeRestore(plan, dryRun, signal);
|
|
1671
|
+
if (!(outcome.restored + outcome.deleted > 0)) return {
|
|
1672
|
+
outcome,
|
|
1673
|
+
repoRoot: checkpoint.repoRoot
|
|
1674
|
+
};
|
|
1675
|
+
let afterTree = checkpoint.beforeTree;
|
|
1676
|
+
if (!dryRun && plan.skipped.length > 0) try {
|
|
1677
|
+
afterTree = await snapshotTree(plan.git, plan.workspace, signal);
|
|
1678
|
+
} catch (error) {
|
|
1679
|
+
deps.logger.warn(`rewind: could not snapshot the restored work tree: ${error instanceof Error ? error.message : String(error)}`);
|
|
1680
|
+
}
|
|
1681
|
+
return {
|
|
1682
|
+
outcome,
|
|
1683
|
+
repoRoot: checkpoint.repoRoot,
|
|
1684
|
+
currentTree: plan.currentTree,
|
|
1685
|
+
afterTree
|
|
1686
|
+
};
|
|
1687
|
+
}
|
|
1688
|
+
/** Estimate the shadowed span's heuristic token price, when a meter is mounted. */
|
|
1689
|
+
function spanTokens(meter, session, shadowed) {
|
|
1690
|
+
if (meter === void 0) return void 0;
|
|
1691
|
+
try {
|
|
1692
|
+
const nodes = new Map(meter.measure(session).nodes.map((node) => [node.seq, node.heuristicTokens]));
|
|
1693
|
+
return shadowed.reduce((total, seq) => total + (nodes.get(seq) ?? 0), 0);
|
|
1694
|
+
} catch {
|
|
1695
|
+
return;
|
|
1696
|
+
}
|
|
1697
|
+
}
|
|
1698
|
+
/** Run one compaction mode after the shared guards. */
|
|
1699
|
+
async function applyCompaction(deps, invocation, parsed, events, signal) {
|
|
1700
|
+
const session = invocation.agent.session;
|
|
1701
|
+
const direction = parsed.mode === "compact-before" ? "before" : "after";
|
|
1702
|
+
if (deriveTurns(events).some((turn) => !turn.ended)) throw new RewindError("busy", "A turn has not finished yet. Stop it before compacting.");
|
|
1703
|
+
const plan = planCompaction(session, events, parsed.turn, direction);
|
|
1704
|
+
if (plan === null) throw new RewindError("no-range", direction === "before" ? `There is no earlier conversation to compact before turn ${String(parsed.turn)}.` : `There is no conversation to compact from turn ${String(parsed.turn)} onward.`);
|
|
1705
|
+
const meter = deps.tokenMeter();
|
|
1706
|
+
const preview = {
|
|
1707
|
+
direction,
|
|
1708
|
+
items: plan.shadowed.length,
|
|
1709
|
+
tokens: spanTokens(meter, session, plan.shadowed)
|
|
1710
|
+
};
|
|
1711
|
+
if (parsed.dryRun) return compactionResult(parsed, preview);
|
|
1712
|
+
const llm = deps.llm();
|
|
1713
|
+
if (llm === void 0 || meter === void 0) throw new RewindError("compaction-unavailable", "Context compaction is unavailable because this profile mounts no LLM or token-meter service.");
|
|
1714
|
+
const agent = {
|
|
1715
|
+
session,
|
|
1716
|
+
options: invocation.agent.options
|
|
1717
|
+
};
|
|
1718
|
+
const outcome = await compactPlan({
|
|
1719
|
+
llm,
|
|
1720
|
+
meter
|
|
1721
|
+
}, session, events, plan, agent, signal);
|
|
1722
|
+
return compactionResult(parsed, {
|
|
1723
|
+
direction,
|
|
1724
|
+
items: outcome.shadowedItemCount,
|
|
1725
|
+
tokens: outcome.shadowedTokenCount,
|
|
1726
|
+
summaryTokens: outcome.summaryTokenCount
|
|
1727
|
+
});
|
|
1728
|
+
}
|
|
1729
|
+
/** Build the human or JSON result of one compaction. */
|
|
1730
|
+
function compactionResult(parsed, preview) {
|
|
1731
|
+
const where = preview.direction === "before" ? `before turn ${String(parsed.turn)}` : `from turn ${String(parsed.turn)} onward`;
|
|
1732
|
+
if (parsed.json) return {
|
|
1733
|
+
kind: "success",
|
|
1734
|
+
text: JSON.stringify({
|
|
1735
|
+
turn: parsed.turn,
|
|
1736
|
+
dryRun: parsed.dryRun,
|
|
1737
|
+
compact: {
|
|
1738
|
+
direction: preview.direction,
|
|
1739
|
+
items: preview.items,
|
|
1740
|
+
tokens: preview.tokens,
|
|
1741
|
+
...preview.summaryTokens === void 0 ? {} : { summaryTokens: preview.summaryTokens }
|
|
1742
|
+
}
|
|
1743
|
+
})
|
|
1744
|
+
};
|
|
1745
|
+
const tokens = preview.tokens === void 0 ? "" : ` (~${String(preview.tokens)} tokens)`;
|
|
1746
|
+
return {
|
|
1747
|
+
kind: "success",
|
|
1748
|
+
text: parsed.dryRun ? `Dry run for turn ${String(parsed.turn)}: would compact ${String(preview.items)} item(s)${tokens} ${where}.` : `Compacted ${String(preview.items)} item(s)${tokens} ${where}.`
|
|
1749
|
+
};
|
|
1750
|
+
}
|
|
1751
|
+
/** Extract the text of one user message, or undefined when it has no text. */
|
|
1752
|
+
function userText(event) {
|
|
1753
|
+
if (event.type !== "user/message") return void 0;
|
|
1754
|
+
const text = (event.data.content ?? []).filter((block) => block.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n").trim();
|
|
1755
|
+
return text === "" ? void 0 : text;
|
|
1756
|
+
}
|
|
1757
|
+
/**
|
|
1758
|
+
* The user's original prompt for one turn, used to repopulate the composer
|
|
1759
|
+
* after a conversation rewind. Markers, compaction summaries, and agent
|
|
1760
|
+
* instructions are not prompts.
|
|
1761
|
+
* @param events - complete session log.
|
|
1762
|
+
* @param turn - host-assigned target turn.
|
|
1763
|
+
* @returns the prompt text, or undefined when the turn has none.
|
|
1764
|
+
*/
|
|
1765
|
+
function targetPrompt(events, turn) {
|
|
1766
|
+
const start = events.find((event) => event.type === "turn/start" && event.data.turn === turn);
|
|
1767
|
+
if (start === void 0) return void 0;
|
|
1768
|
+
const end = events.find((event) => event.type === "turn/end" && event.data.turn === turn);
|
|
1769
|
+
let fallback;
|
|
1770
|
+
for (const event of events) {
|
|
1771
|
+
if (event.seq < start.seq) continue;
|
|
1772
|
+
if (end !== void 0 && event.seq > end.seq) break;
|
|
1773
|
+
const text = userText(event);
|
|
1774
|
+
if (text === void 0) continue;
|
|
1775
|
+
const kind = event.data.source?.kind;
|
|
1776
|
+
if (kind === "user" || kind === "user-question-reply") return text;
|
|
1777
|
+
if (fallback === void 0 && kind !== "compact-checkpoint" && kind !== "rewind-checkpoint" && kind !== "agent-instructions") fallback = text;
|
|
1778
|
+
}
|
|
1779
|
+
return fallback;
|
|
1780
|
+
}
|
|
1781
|
+
/** Build the human or JSON success result of a file/conversation rewind. */
|
|
1782
|
+
function successResult(parsed, files, conversation, prompt) {
|
|
1783
|
+
if (parsed.json) return {
|
|
1784
|
+
kind: "success",
|
|
1785
|
+
text: JSON.stringify({
|
|
1786
|
+
turn: parsed.turn,
|
|
1787
|
+
dryRun: parsed.dryRun,
|
|
1788
|
+
...files === void 0 ? {} : { files: {
|
|
1789
|
+
restored: files.restored,
|
|
1790
|
+
deleted: files.deleted,
|
|
1791
|
+
skipped: files.skipped,
|
|
1792
|
+
paths: files.paths
|
|
1793
|
+
} },
|
|
1794
|
+
conversation: {
|
|
1795
|
+
changed: conversation.changed,
|
|
1796
|
+
replaced: conversation.replaced,
|
|
1797
|
+
...conversation.replayed === void 0 ? {} : { replayed: conversation.replayed }
|
|
1798
|
+
},
|
|
1799
|
+
...prompt === void 0 ? {} : { prompt }
|
|
1800
|
+
})
|
|
1801
|
+
};
|
|
1802
|
+
const parts = [];
|
|
1803
|
+
if (files !== void 0) {
|
|
1804
|
+
const fileParts = [`${String(files.restored)} file(s) restored`];
|
|
1805
|
+
if (files.deleted > 0) fileParts.push(`${String(files.deleted)} removed`);
|
|
1806
|
+
if (files.skipped.length > 0) fileParts.push(`${String(files.skipped.length)} skipped`);
|
|
1807
|
+
parts.push(fileParts.join(", "));
|
|
1808
|
+
if (files.paths.length > 0) parts.push(`Files: ${pathSample(files.paths)}`);
|
|
1809
|
+
}
|
|
1810
|
+
if (conversation.replayed !== void 0) parts.push(parsed.dryRun ? `would replay ${String(conversation.replayed)} messages in place` : `conversation context replayed (${String(conversation.replayed)} messages)`);
|
|
1811
|
+
else if (conversation.changed) parts.push(`conversation context truncated (${String(conversation.replaced)} nodes)`);
|
|
1812
|
+
else if (parsed.mode === "both" || parsed.mode === "conversation") parts.push("conversation already ends before that point");
|
|
1813
|
+
const prefix = parsed.dryRun ? `Dry run for turn ${String(parsed.turn)}` : `Rewound to before turn ${String(parsed.turn)}`;
|
|
1814
|
+
return {
|
|
1815
|
+
kind: "success",
|
|
1816
|
+
text: parts.length === 0 ? `${prefix}: nothing to change.` : `${prefix}: ${parts.join("; ")}.`
|
|
1817
|
+
};
|
|
1818
|
+
}
|
|
1819
|
+
/**
|
|
1820
|
+
* Move the live agent's turn cursor past a synthetic replay envelope.
|
|
1821
|
+
* The loop computes its next turn from this cursor rather than from the raw
|
|
1822
|
+
* log, so an unsynced envelope leaves the next real turn with the same number
|
|
1823
|
+
* and makes the stored log fail its reload check.
|
|
1824
|
+
* @param agent - live agent that owns the session.
|
|
1825
|
+
* @param turn - synthetic turn just appended.
|
|
1826
|
+
*/
|
|
1827
|
+
function advanceReplayTurn(agent, turn) {
|
|
1828
|
+
const phase = agent.phase;
|
|
1829
|
+
if (phase === void 0) return;
|
|
1830
|
+
if (typeof phase.lastTurn === "number") phase.lastTurn = Math.max(phase.lastTurn, turn);
|
|
1831
|
+
if (typeof phase.turn === "number") phase.turn = Math.max(phase.turn, turn);
|
|
1832
|
+
}
|
|
1833
|
+
/** Apply one mode inside the already-owned maintenance phase. */
|
|
1834
|
+
async function applyLocked(deps, invocation, parsed, signal) {
|
|
1835
|
+
const session = invocation.agent.session;
|
|
1836
|
+
const sessionId = session.id;
|
|
1837
|
+
const observation = await deps.observe(sessionId);
|
|
1838
|
+
try {
|
|
1839
|
+
const events = observation.events;
|
|
1840
|
+
const facts = deriveTurns(events).find((turn) => turn.turn === parsed.turn);
|
|
1841
|
+
if (facts === void 0) throw new RewindError("no-turn", `Turn ${String(parsed.turn)} does not exist in this conversation.`);
|
|
1842
|
+
if (!facts.ended) throw new RewindError("busy", `Turn ${String(parsed.turn)} has not finished yet. Stop it before rewinding.`);
|
|
1843
|
+
const compaction = parsed.mode === "compact-before" || parsed.mode === "compact-after";
|
|
1844
|
+
const conversation = parsed.mode === "both" || parsed.mode === "conversation";
|
|
1845
|
+
const compacted = hiddenByCompaction(events, parsed.turn);
|
|
1846
|
+
if (compaction || conversation) {
|
|
1847
|
+
if (hiddenByRewind(events, parsed.turn)) throw new RewindError("already-rewound", `Turn ${String(parsed.turn)} was already hidden by an earlier rewind. Choose a later turn; --files still works on a hidden turn.`);
|
|
1848
|
+
if (compaction && compacted) throw new RewindError("compacted", `Turn ${String(parsed.turn)} was already condensed by an earlier compaction. Choose a later turn; --files still works on a condensed turn.`);
|
|
1849
|
+
}
|
|
1850
|
+
if (compaction) return await applyCompaction(deps, invocation, parsed, events, signal);
|
|
1851
|
+
const replay = conversation ? planReplay(session, session.snapshotEvents(), parsed.turn, facts.startSeq) : null;
|
|
1852
|
+
if (conversation) computeSurfaceCut(session, events, parsed.turn);
|
|
1853
|
+
let fileRestore;
|
|
1854
|
+
if (parsed.mode === "both" || parsed.mode === "files") fileRestore = await applyFiles(deps, sessionId, parsed.turn, parsed.dryRun, signal);
|
|
1855
|
+
const files = fileRestore?.outcome;
|
|
1856
|
+
let outcome = {
|
|
1857
|
+
changed: false,
|
|
1858
|
+
replaced: 0
|
|
1859
|
+
};
|
|
1860
|
+
let conversationUndo;
|
|
1861
|
+
if (replay !== null) {
|
|
1862
|
+
const noop = replay.pivot === null && replay.copies.length === 0 && replay.shadowed.length === 0;
|
|
1863
|
+
if (!parsed.dryRun && !noop) try {
|
|
1864
|
+
const appended = appendReplay(session, replay, facts.at);
|
|
1865
|
+
if (appended.turn !== void 0) advanceReplayTurn(invocation.agent, appended.turn);
|
|
1866
|
+
conversationUndo = {
|
|
1867
|
+
shadowed: replay.shadowed.map((seq) => Number(seq)),
|
|
1868
|
+
head: Number(appended.head),
|
|
1869
|
+
surfaceHash: surfaceHash(session.surface.nodes)
|
|
1870
|
+
};
|
|
1871
|
+
} catch (error) {
|
|
1872
|
+
throw new RewindError("conversation-unavailable", `The conversation could not be replayed after the file restore: ${error instanceof Error ? error.message : String(error)}`);
|
|
1873
|
+
}
|
|
1874
|
+
const rebuilt = (replay.pivot === null ? 0 : 1) + replay.copies.length;
|
|
1875
|
+
outcome = noop ? {
|
|
1876
|
+
changed: false,
|
|
1877
|
+
replaced: 0
|
|
1878
|
+
} : {
|
|
1879
|
+
changed: true,
|
|
1880
|
+
replaced: replay.shadowed.length,
|
|
1881
|
+
...rebuilt > 0 ? { replayed: rebuilt } : {}
|
|
1882
|
+
};
|
|
1883
|
+
}
|
|
1884
|
+
if (!parsed.dryRun) {
|
|
1885
|
+
const undoFiles = fileRestore === void 0 || fileRestore.currentTree === void 0 || fileRestore.afterTree === void 0 ? void 0 : {
|
|
1886
|
+
repoRoot: fileRestore.repoRoot,
|
|
1887
|
+
tree: fileRestore.currentTree,
|
|
1888
|
+
afterTree: fileRestore.afterTree
|
|
1889
|
+
};
|
|
1890
|
+
if (undoFiles !== void 0 || conversationUndo !== void 0) {
|
|
1891
|
+
const undo = {
|
|
1892
|
+
turn: parsed.turn,
|
|
1893
|
+
at: Date.now(),
|
|
1894
|
+
...undoFiles === void 0 ? {} : { files: undoFiles },
|
|
1895
|
+
...conversationUndo === void 0 ? {} : { conversation: conversationUndo }
|
|
1896
|
+
};
|
|
1897
|
+
try {
|
|
1898
|
+
await deps.store.saveUndo(sessionId, undo);
|
|
1899
|
+
} catch (error) {
|
|
1900
|
+
deps.logger.warn(`rewind: could not save the undo record: ${error instanceof Error ? error.message : String(error)}`);
|
|
1901
|
+
}
|
|
1902
|
+
}
|
|
1903
|
+
}
|
|
1904
|
+
return successResult(parsed, files, outcome, conversation ? targetPrompt(events, parsed.turn) : void 0);
|
|
1905
|
+
} finally {
|
|
1906
|
+
observation.dispose();
|
|
1907
|
+
}
|
|
1908
|
+
}
|
|
1909
|
+
/** Build the human or JSON result of one undo. */
|
|
1910
|
+
function undoResult(parsed, record, files, conversation) {
|
|
1911
|
+
if (parsed.json) return {
|
|
1912
|
+
kind: "success",
|
|
1913
|
+
text: JSON.stringify({
|
|
1914
|
+
undo: true,
|
|
1915
|
+
turn: record.turn,
|
|
1916
|
+
dryRun: parsed.dryRun,
|
|
1917
|
+
...files === void 0 ? {} : { files: {
|
|
1918
|
+
restored: files.restored,
|
|
1919
|
+
deleted: files.deleted,
|
|
1920
|
+
skipped: files.skipped,
|
|
1921
|
+
paths: files.paths
|
|
1922
|
+
} },
|
|
1923
|
+
...conversation === void 0 ? {} : { conversation }
|
|
1924
|
+
})
|
|
1925
|
+
};
|
|
1926
|
+
const parts = [];
|
|
1927
|
+
if (files !== void 0) {
|
|
1928
|
+
const fileParts = [`${String(files.restored)} file(s) restored`];
|
|
1929
|
+
if (files.deleted > 0) fileParts.push(`${String(files.deleted)} removed`);
|
|
1930
|
+
if (files.skipped.length > 0) fileParts.push(`${String(files.skipped.length)} skipped`);
|
|
1931
|
+
parts.push(fileParts.join(", "));
|
|
1932
|
+
if (files.paths.length > 0) parts.push(`Files: ${pathSample(files.paths)}`);
|
|
1933
|
+
}
|
|
1934
|
+
if (conversation !== void 0) parts.push(`${parsed.dryRun ? "would restore" : "restored"} ${String(conversation.replayed)} conversation message(s)`);
|
|
1935
|
+
const prefix = parsed.dryRun ? `Dry run for undoing the rewind to turn ${String(record.turn)}` : `Undid the rewind to turn ${String(record.turn)}`;
|
|
1936
|
+
return {
|
|
1937
|
+
kind: "success",
|
|
1938
|
+
text: parts.length === 0 ? `${prefix}: nothing to change.` : `${prefix}: ${parts.join("; ")}.`
|
|
1939
|
+
};
|
|
1940
|
+
}
|
|
1941
|
+
/** Undo the last applied rewind inside the already-owned maintenance phase. */
|
|
1942
|
+
async function applyUndo(deps, invocation, parsed, signal) {
|
|
1943
|
+
const session = invocation.agent.session;
|
|
1944
|
+
const sessionId = session.id;
|
|
1945
|
+
const observation = await deps.observe(sessionId);
|
|
1946
|
+
try {
|
|
1947
|
+
const events = observation.events;
|
|
1948
|
+
const record = await deps.store.loadUndo(sessionId);
|
|
1949
|
+
if (record === void 0) throw new RewindError("no-undo", "Nothing to undo: no rewind was applied in this session.");
|
|
1950
|
+
if (openTurn(events) !== void 0) throw new RewindError("busy", "The conversation still has an open turn; wait for it to settle before undoing.");
|
|
1951
|
+
const replay = record.conversation === void 0 ? null : planUndo(session, events, record);
|
|
1952
|
+
const restore = record.files === void 0 ? void 0 : await prepareTreeRestore(deps, record.files.repoRoot, record.files.tree, record.files.afterTree, signal);
|
|
1953
|
+
let files = restore === void 0 ? void 0 : {
|
|
1954
|
+
restored: restore.write.length,
|
|
1955
|
+
deleted: restore.remove.length,
|
|
1956
|
+
skipped: restore.skipped,
|
|
1957
|
+
paths: [...restore.write, ...restore.remove]
|
|
1958
|
+
};
|
|
1959
|
+
const conversation = replay === null ? void 0 : {
|
|
1960
|
+
replayed: replay.copies.length,
|
|
1961
|
+
replaced: replay.shadowed.length
|
|
1962
|
+
};
|
|
1963
|
+
if (parsed.dryRun) return undoResult(parsed, record, files, conversation);
|
|
1964
|
+
if (restore !== void 0) files = await applyTreeRestore(restore, false, signal);
|
|
1965
|
+
if (replay !== null) try {
|
|
1966
|
+
const appended = appendReplay(session, replay, record.at, "rewind-undo");
|
|
1967
|
+
if (appended.turn !== void 0) advanceReplayTurn(invocation.agent, appended.turn);
|
|
1968
|
+
} catch (error) {
|
|
1969
|
+
throw new RewindError("conversation-unavailable", `The rewind could not be undone: ${error instanceof Error ? error.message : String(error)}`);
|
|
1970
|
+
}
|
|
1971
|
+
try {
|
|
1972
|
+
await deps.store.clearUndo(sessionId);
|
|
1973
|
+
} catch (error) {
|
|
1974
|
+
deps.logger.warn(`rewind: could not clear the undo record: ${error instanceof Error ? error.message : String(error)}`);
|
|
1975
|
+
}
|
|
1976
|
+
return undoResult(parsed, record, files, conversation);
|
|
1977
|
+
} finally {
|
|
1978
|
+
observation.dispose();
|
|
1979
|
+
}
|
|
1980
|
+
}
|
|
1981
|
+
/**
|
|
1982
|
+
* Execute one `/rewind` invocation. Expected failures settle as error results;
|
|
1983
|
+
* an occupied agent is refused without cancelling the running turn.
|
|
1984
|
+
* @param deps - host dependencies.
|
|
1985
|
+
* @param invocation - command invocation from the registry.
|
|
1986
|
+
* @returns settled human or machine-readable result.
|
|
1987
|
+
*/
|
|
1988
|
+
async function runRewindCommand(deps, invocation) {
|
|
1989
|
+
const parsed = parse(invocation.rawInput);
|
|
1990
|
+
if (parsed.kind === "help") return {
|
|
1991
|
+
kind: "success",
|
|
1992
|
+
text: USAGE
|
|
1993
|
+
};
|
|
1994
|
+
if (parsed.kind === "invalid") return errorResult(parsed.message);
|
|
1995
|
+
if (!deps.config.enabled) return errorResult("Rewind is disabled in this profile.");
|
|
1996
|
+
if (isSubagent(invocation.agent.session)) return errorResult("Rewind is only available in a top-level conversation.");
|
|
1997
|
+
if (parsed.kind === "list") return listCheckpoints(deps, invocation, parsed.json, parsed.brief);
|
|
1998
|
+
if (invocation.agent.status === "running") return errorResult("Rewind is unavailable while this turn is running. Stop it and try again; background jobs are not affected.");
|
|
1999
|
+
try {
|
|
2000
|
+
return await invocation.agent.runMaintenance((maintenanceSignal) => {
|
|
2001
|
+
const signal = AbortSignal.any([maintenanceSignal, invocation.signal]);
|
|
2002
|
+
return parsed.kind === "undo" ? applyUndo(deps, invocation, parsed, signal) : applyLocked(deps, invocation, parsed, signal);
|
|
2003
|
+
});
|
|
2004
|
+
} catch (error) {
|
|
2005
|
+
if (error instanceof RewindError) return errorResult(error.message);
|
|
2006
|
+
return errorResult(`Rewind failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
2007
|
+
}
|
|
2008
|
+
}
|
|
2009
|
+
// src/config.ts
|
|
2010
|
+
/** Plugin configuration and the local storage defaults. */
|
|
2011
|
+
/**
|
|
2012
|
+
* Resolve the harness home the same way DSH does for user data: an explicit
|
|
2013
|
+
* `DSH_HOME`, else `~/.dsh`. An explicit configured home cannot be read from a
|
|
2014
|
+
* plugin, so `storageDir` stays overridable in the profile patch.
|
|
2015
|
+
* @returns absolute harness home.
|
|
2016
|
+
*/
|
|
2017
|
+
function resolveDshHome() {
|
|
2018
|
+
const configured = process.env.DSH_HOME?.trim();
|
|
2019
|
+
const base = configured !== void 0 && configured.length > 0 ? configured : join(homedir(), ".dsh");
|
|
2020
|
+
return resolve(base.replace(/^~(?=$|[\\/])/, homedir()));
|
|
2021
|
+
}
|
|
2022
|
+
/** Default directory holding session checkpoint indexes and Git object stores. */
|
|
2023
|
+
const DEFAULT_STORAGE_DIR = join(resolveDshHome(), "rewind");
|
|
2024
|
+
/** Schemastery validation for {@link Config}. */
|
|
2025
|
+
const Config = z.object({
|
|
2026
|
+
enabled: z.boolean().description("Register /rewind and snapshot turns.").default(true),
|
|
2027
|
+
storageDir: z.string().description("Directory for session indexes and private Git object stores.").default(DEFAULT_STORAGE_DIR),
|
|
2028
|
+
timeoutMs: z.number().description("Milliseconds one git command may run.").default(3e4),
|
|
2029
|
+
outputMaxBytes: z.number().description("Bytes of git stdout retained per command.").default(8388608),
|
|
2030
|
+
maxPathsPerRestore: z.number().description("Maximum changed paths one file rewind may apply.").default(1e3),
|
|
2031
|
+
retentionDays: z.number().description("Days a session checkpoint index is retained.").default(30)
|
|
2032
|
+
});
|
|
2033
|
+
/** Defaults used by a direct caller or a config-less Loader row. */
|
|
2034
|
+
const DEFAULT_CONFIG = {
|
|
2035
|
+
enabled: true,
|
|
2036
|
+
storageDir: DEFAULT_STORAGE_DIR,
|
|
2037
|
+
timeoutMs: 3e4,
|
|
2038
|
+
outputMaxBytes: 8388608,
|
|
2039
|
+
maxPathsPerRestore: 1e3,
|
|
2040
|
+
retentionDays: 30
|
|
2041
|
+
};
|
|
2042
|
+
// src/git/provider.ts
|
|
2043
|
+
/** One process-wide Git runtime, resolved on first use. */
|
|
2044
|
+
var GitProvider = class {
|
|
2045
|
+
subprocess;
|
|
2046
|
+
signal;
|
|
2047
|
+
limits;
|
|
2048
|
+
logger;
|
|
2049
|
+
runtime;
|
|
2050
|
+
warned = false;
|
|
2051
|
+
/**
|
|
2052
|
+
* @param subprocess - Host subprocess capability.
|
|
2053
|
+
* @param signal - plugin lifetime; aborts executable resolution.
|
|
2054
|
+
* @param limits - per-command timeout and stdout cap.
|
|
2055
|
+
* @param logger - warning sink.
|
|
2056
|
+
*/
|
|
2057
|
+
constructor(subprocess, signal, limits, logger) {
|
|
2058
|
+
this.subprocess = subprocess;
|
|
2059
|
+
this.signal = signal;
|
|
2060
|
+
this.limits = limits;
|
|
2061
|
+
this.logger = logger;
|
|
2062
|
+
}
|
|
2063
|
+
/** Resolve the git runtime, or null when the Host has no usable git. */
|
|
2064
|
+
get() {
|
|
2065
|
+
this.runtime ??= this.resolve();
|
|
2066
|
+
return this.runtime;
|
|
2067
|
+
}
|
|
2068
|
+
async resolve() {
|
|
2069
|
+
const executable = await resolveGit(this.subprocess, this.signal).catch(() => null);
|
|
2070
|
+
if (executable === null) {
|
|
2071
|
+
if (!this.warned) {
|
|
2072
|
+
this.warned = true;
|
|
2073
|
+
this.logger.warn("rewind: git is unavailable; file checkpoints will not be recorded");
|
|
2074
|
+
}
|
|
2075
|
+
return null;
|
|
2076
|
+
}
|
|
2077
|
+
return new SubprocessGit(this.subprocess, executable, this.limits);
|
|
2078
|
+
}
|
|
2079
|
+
};
|
|
2080
|
+
// src/git/workspace.ts
|
|
2081
|
+
/** Locate the repository enclosing one working directory and prepare its private object store. */
|
|
2082
|
+
/**
|
|
2083
|
+
* Locate the repository enclosing `cwd`. The repository's own index, objects,
|
|
2084
|
+
* refs, and work tree stay untouched: writes go to the private object store,
|
|
2085
|
+
* and the repository's object store is attached read-only as an alternate.
|
|
2086
|
+
* @param git - command runner.
|
|
2087
|
+
* @param cwd - absolute working directory.
|
|
2088
|
+
* @param scratchFor - yields the private object-store directory for the located root.
|
|
2089
|
+
* @param signal - cancellation.
|
|
2090
|
+
* @param storageRoot - plugin storage root to exclude when it lies inside the work tree.
|
|
2091
|
+
* @returns the workspace, or null when the directory is outside any repository.
|
|
2092
|
+
*/
|
|
2093
|
+
async function locateWorkspace(git, cwd, scratchFor, signal, storageRoot) {
|
|
2094
|
+
const found = await git.run([
|
|
2095
|
+
"rev-parse",
|
|
2096
|
+
"--show-toplevel",
|
|
2097
|
+
"--absolute-git-dir",
|
|
2098
|
+
"--git-path",
|
|
2099
|
+
"objects"
|
|
2100
|
+
], {
|
|
2101
|
+
cwd,
|
|
2102
|
+
signal
|
|
2103
|
+
});
|
|
2104
|
+
if (found.exitCode === 128 && /not a git repository/i.test(found.stderr)) return null;
|
|
2105
|
+
const lines = assertGit(found, "git rev-parse").stdout.split("\n").filter((line) => line !== "");
|
|
2106
|
+
if (lines.length < 3) throw new Error("git rev-parse returned an unexpected shape");
|
|
2107
|
+
const [rootLine, gitDirLine, objectsLine] = lines;
|
|
2108
|
+
const root = await canonicalPath(resolve(cwd, rootLine));
|
|
2109
|
+
const gitDir = resolve(cwd, gitDirLine);
|
|
2110
|
+
const repositoryObjects = resolve(cwd, objectsLine);
|
|
2111
|
+
const directory = await canonicalPath(await scratchFor(root));
|
|
2112
|
+
const objects = join(directory, "objects");
|
|
2113
|
+
await mkdir(objects, {
|
|
2114
|
+
recursive: true,
|
|
2115
|
+
mode: 448
|
|
2116
|
+
});
|
|
2117
|
+
const excluded = storageRoot !== void 0 && isInside(root, storageRoot) ? storageRoot : isInside(root, directory) ? directory : void 0;
|
|
2118
|
+
const excludes = excluded === void 0 ? [] : [toPosix(relative(root, excluded))];
|
|
2119
|
+
return {
|
|
2120
|
+
root,
|
|
2121
|
+
gitDir,
|
|
2122
|
+
scratch: directory,
|
|
2123
|
+
env: {
|
|
2124
|
+
GIT_OBJECT_DIRECTORY: objects,
|
|
2125
|
+
GIT_ALTERNATE_OBJECT_DIRECTORIES: repositoryObjects
|
|
2126
|
+
},
|
|
2127
|
+
excludes
|
|
2128
|
+
};
|
|
2129
|
+
}
|
|
2130
|
+
/** Workspace resolution shared by the turn recorder and the restore command. */
|
|
2131
|
+
var WorkspaceResolver = class {
|
|
2132
|
+
storageDir;
|
|
2133
|
+
git;
|
|
2134
|
+
/**
|
|
2135
|
+
* @param storageDir - plugin storage root holding `workspaces/`.
|
|
2136
|
+
* @param git - lazy git runtime, or null when git is unavailable.
|
|
2137
|
+
*/
|
|
2138
|
+
constructor(storageDir, git) {
|
|
2139
|
+
this.storageDir = storageDir;
|
|
2140
|
+
this.git = git;
|
|
2141
|
+
}
|
|
2142
|
+
/**
|
|
2143
|
+
* Resolve the workspace enclosing one working directory.
|
|
2144
|
+
* @param cwd - absolute session working directory.
|
|
2145
|
+
* @param signal - cancellation.
|
|
2146
|
+
* @returns the workspace, or null outside a repository.
|
|
2147
|
+
*/
|
|
2148
|
+
async forCwd(cwd, signal) {
|
|
2149
|
+
const git = await this.git();
|
|
2150
|
+
if (git === null) return null;
|
|
2151
|
+
return locateWorkspace(git, cwd, (root) => this.scratchFor(root), signal, this.storageDir);
|
|
2152
|
+
}
|
|
2153
|
+
/**
|
|
2154
|
+
* Resolve one recorded repository root again at restore time.
|
|
2155
|
+
* @param root - recorded repository top-level directory.
|
|
2156
|
+
* @param signal - cancellation.
|
|
2157
|
+
* @returns the workspace, or null when the directory is no longer a repository.
|
|
2158
|
+
*/
|
|
2159
|
+
async forRoot(root, signal) {
|
|
2160
|
+
return this.forCwd(root, signal);
|
|
2161
|
+
}
|
|
2162
|
+
/** Private object-store directory for one canonical repository root. */
|
|
2163
|
+
async scratchFor(root) {
|
|
2164
|
+
const directory = join(this.storageDir, "workspaces", workspaceKey(root));
|
|
2165
|
+
await mkdir(directory, {
|
|
2166
|
+
recursive: true,
|
|
2167
|
+
mode: 448
|
|
2168
|
+
});
|
|
2169
|
+
return directory;
|
|
2170
|
+
}
|
|
2171
|
+
};
|
|
2172
|
+
// src/recorder.ts
|
|
2173
|
+
/** Whether a session is a top-level conversation the recorder snapshots. */
|
|
2174
|
+
function isTopLevel(session) {
|
|
2175
|
+
return session.header.origin !== "subagent" && (session.header.delegationDepth ?? 0) === 0;
|
|
2176
|
+
}
|
|
2177
|
+
/** Incomplete checkpoint facts for a turn whose baseline could not be taken. */
|
|
2178
|
+
function incomplete(turn, at, cwd, repoRoot, reason) {
|
|
2179
|
+
return {
|
|
2180
|
+
turn,
|
|
2181
|
+
at,
|
|
2182
|
+
cwd,
|
|
2183
|
+
repoRoot,
|
|
2184
|
+
workspaceKey: workspaceKey(repoRoot),
|
|
2185
|
+
beforeTree: "",
|
|
2186
|
+
complete: false,
|
|
2187
|
+
reason
|
|
2188
|
+
};
|
|
2189
|
+
}
|
|
2190
|
+
/** Git checkpoint recorder for live sessions. */
|
|
2191
|
+
var SnapshotRecorder = class {
|
|
2192
|
+
options;
|
|
2193
|
+
states = /* @__PURE__ */ new Map();
|
|
2194
|
+
sessions = /* @__PURE__ */ new Map();
|
|
2195
|
+
constructor(options) {
|
|
2196
|
+
this.options = options;
|
|
2197
|
+
}
|
|
2198
|
+
/** Observe one committed session event; `turn/start` queues a snapshot. */
|
|
2199
|
+
observe(session, event) {
|
|
2200
|
+
if (isTopLevel(session)) this.sessions.set(session.id, session);
|
|
2201
|
+
if (event.type === "turn/start") this.startTurn(session, event.data.turn, event.time);
|
|
2202
|
+
}
|
|
2203
|
+
/** Wait for the pending baseline of the session behind one tool execution. */
|
|
2204
|
+
async settleFor(execution) {
|
|
2205
|
+
const session = execution.agent?.session;
|
|
2206
|
+
if (session === void 0) return;
|
|
2207
|
+
await this.stateBehind(session)?.current?.catch(() => {});
|
|
2208
|
+
}
|
|
2209
|
+
/** Abort and forget one disposed session. */
|
|
2210
|
+
forget(session) {
|
|
2211
|
+
const state = this.states.get(session.id);
|
|
2212
|
+
this.states.delete(session.id);
|
|
2213
|
+
this.sessions.delete(session.id);
|
|
2214
|
+
state?.abort.abort();
|
|
2215
|
+
}
|
|
2216
|
+
/** Abort every pending baseline and wait for settlement. */
|
|
2217
|
+
async dispose() {
|
|
2218
|
+
const pending = [];
|
|
2219
|
+
for (const state of this.states.values()) {
|
|
2220
|
+
state.abort.abort();
|
|
2221
|
+
if (state.current !== void 0) pending.push(state.current.catch(() => {}));
|
|
2222
|
+
}
|
|
2223
|
+
this.states.clear();
|
|
2224
|
+
this.sessions.clear();
|
|
2225
|
+
await Promise.all(pending);
|
|
2226
|
+
}
|
|
2227
|
+
/** Find the tracked top-level state behind a session, walking subagent ancestry. */
|
|
2228
|
+
stateBehind(session) {
|
|
2229
|
+
let current = session;
|
|
2230
|
+
for (let depth = 0; depth < 8 && current !== void 0; depth += 1) {
|
|
2231
|
+
const state = this.states.get(current.id);
|
|
2232
|
+
if (state !== void 0) return state;
|
|
2233
|
+
const parent = current.header.parentSession;
|
|
2234
|
+
current = parent === void 0 ? void 0 : this.sessions.get(parent);
|
|
2235
|
+
}
|
|
2236
|
+
}
|
|
2237
|
+
/** Queue the baseline of one top-level turn. */
|
|
2238
|
+
startTurn(session, turn, at) {
|
|
2239
|
+
if (!isTopLevel(session)) return;
|
|
2240
|
+
const cwd = this.options.workingDirectory?.get(session) ?? session.header.cwd;
|
|
2241
|
+
if (cwd === void 0 || cwd === "") return;
|
|
2242
|
+
let state = this.states.get(session.id);
|
|
2243
|
+
if (state === void 0) {
|
|
2244
|
+
state = {
|
|
2245
|
+
turn: -1,
|
|
2246
|
+
chain: Promise.resolve(),
|
|
2247
|
+
current: void 0,
|
|
2248
|
+
abort: new AbortController()
|
|
2249
|
+
};
|
|
2250
|
+
this.states.set(session.id, state);
|
|
2251
|
+
}
|
|
2252
|
+
if (turn <= state.turn) return;
|
|
2253
|
+
state.turn = turn;
|
|
2254
|
+
const signal = AbortSignal.any([state.abort.signal, this.options.lifetime]);
|
|
2255
|
+
const task = state.chain.then(() => this.capture(session.id, turn, at, cwd, signal));
|
|
2256
|
+
state.current = task;
|
|
2257
|
+
state.chain = task.catch(() => {});
|
|
2258
|
+
}
|
|
2259
|
+
/** Take and store one turn's baseline tree, recording an incomplete checkpoint on failure. */
|
|
2260
|
+
async capture(sessionId, turn, at, cwd, signal) {
|
|
2261
|
+
let repoRoot = cwd;
|
|
2262
|
+
try {
|
|
2263
|
+
const git = await this.options.git();
|
|
2264
|
+
if (git === null) {
|
|
2265
|
+
await this.options.store.saveCheckpoint(sessionId, incomplete(turn, at, cwd, cwd, "git is unavailable"));
|
|
2266
|
+
return;
|
|
2267
|
+
}
|
|
2268
|
+
const workspace = await this.options.workspaces.forCwd(cwd, signal);
|
|
2269
|
+
if (workspace === null) {
|
|
2270
|
+
await this.options.store.saveCheckpoint(sessionId, incomplete(turn, at, cwd, cwd, "not inside a git repository"));
|
|
2271
|
+
return;
|
|
2272
|
+
}
|
|
2273
|
+
repoRoot = workspace.root;
|
|
2274
|
+
const tree = await (this.options.snapshot ?? snapshotTree)(git, workspace, signal);
|
|
2275
|
+
if (signal.aborted) return;
|
|
2276
|
+
await this.options.store.saveCheckpoint(sessionId, {
|
|
2277
|
+
turn,
|
|
2278
|
+
at,
|
|
2279
|
+
cwd,
|
|
2280
|
+
repoRoot: workspace.root,
|
|
2281
|
+
workspaceKey: workspaceKey(workspace.root),
|
|
2282
|
+
beforeTree: tree,
|
|
2283
|
+
complete: true
|
|
2284
|
+
});
|
|
2285
|
+
} catch (error) {
|
|
2286
|
+
if (signal.aborted) return;
|
|
2287
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
2288
|
+
this.options.logger.warn(`rewind: turn ${String(turn)} checkpoint was not recorded: ${reason}`);
|
|
2289
|
+
await this.options.store.saveCheckpoint(sessionId, incomplete(turn, at, cwd, repoRoot, reason)).catch(() => {});
|
|
2290
|
+
}
|
|
2291
|
+
}
|
|
2292
|
+
};
|
|
2293
|
+
// src/store.ts
|
|
2294
|
+
/** Durable per-session checkpoint index under the plugin storage directory. */
|
|
2295
|
+
/** Milliseconds in one day. */
|
|
2296
|
+
const DAY_MS = 864e5;
|
|
2297
|
+
/** File-name-safe spelling of one session id. */
|
|
2298
|
+
function sessionFileName(sessionId) {
|
|
2299
|
+
return /^[A-Za-z0-9][A-Za-z0-9._-]{0,120}$/.test(sessionId) ? sessionId : sha256(sessionId).slice(0, 40);
|
|
2300
|
+
}
|
|
2301
|
+
/** Validate one stored checkpoint; unknown or malformed entries are dropped. */
|
|
2302
|
+
function parseCheckpoint(value) {
|
|
2303
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
2304
|
+
const record = value;
|
|
2305
|
+
const turn = record["turn"];
|
|
2306
|
+
const at = record["at"];
|
|
2307
|
+
const cwd = record["cwd"];
|
|
2308
|
+
const repoRoot = record["repoRoot"];
|
|
2309
|
+
const workspaceKey = record["workspaceKey"];
|
|
2310
|
+
const beforeTree = record["beforeTree"];
|
|
2311
|
+
const complete = record["complete"];
|
|
2312
|
+
if (typeof turn !== "number" || !Number.isSafeInteger(turn) || turn < 0) return void 0;
|
|
2313
|
+
if (typeof at !== "number" || !Number.isFinite(at)) return void 0;
|
|
2314
|
+
if (typeof cwd !== "string" || cwd === "") return void 0;
|
|
2315
|
+
if (typeof repoRoot !== "string" || repoRoot === "") return void 0;
|
|
2316
|
+
if (typeof workspaceKey !== "string" || workspaceKey === "") return void 0;
|
|
2317
|
+
if (typeof beforeTree !== "string") return void 0;
|
|
2318
|
+
if (typeof complete !== "boolean") return void 0;
|
|
2319
|
+
const reason = record["reason"];
|
|
2320
|
+
return {
|
|
2321
|
+
turn,
|
|
2322
|
+
at,
|
|
2323
|
+
cwd,
|
|
2324
|
+
repoRoot,
|
|
2325
|
+
workspaceKey,
|
|
2326
|
+
beforeTree,
|
|
2327
|
+
complete,
|
|
2328
|
+
...typeof reason === "string" && reason !== "" ? { reason } : {}
|
|
2329
|
+
};
|
|
2330
|
+
}
|
|
2331
|
+
/** Whether a JSON value is a non-negative safe integer. */
|
|
2332
|
+
function isCount(value) {
|
|
2333
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
2334
|
+
}
|
|
2335
|
+
/** Validate one stored undo record; malformed records are dropped. */
|
|
2336
|
+
function parseUndo(value) {
|
|
2337
|
+
if (typeof value !== "object" || value === null) return void 0;
|
|
2338
|
+
const record = value;
|
|
2339
|
+
const turn = record["turn"];
|
|
2340
|
+
const at = record["at"];
|
|
2341
|
+
if (!isCount(turn) || typeof at !== "number" || !Number.isFinite(at)) return void 0;
|
|
2342
|
+
let files;
|
|
2343
|
+
const rawFiles = record["files"];
|
|
2344
|
+
if (rawFiles !== void 0) {
|
|
2345
|
+
if (typeof rawFiles !== "object" || rawFiles === null) return void 0;
|
|
2346
|
+
const entry = rawFiles;
|
|
2347
|
+
const repoRoot = entry["repoRoot"];
|
|
2348
|
+
const tree = entry["tree"];
|
|
2349
|
+
const afterTree = entry["afterTree"];
|
|
2350
|
+
if (typeof repoRoot !== "string" || repoRoot === "") return void 0;
|
|
2351
|
+
if (typeof tree !== "string" || tree === "") return void 0;
|
|
2352
|
+
if (typeof afterTree !== "string" || afterTree === "") return void 0;
|
|
2353
|
+
files = {
|
|
2354
|
+
repoRoot,
|
|
2355
|
+
tree,
|
|
2356
|
+
afterTree
|
|
2357
|
+
};
|
|
2358
|
+
}
|
|
2359
|
+
let conversation;
|
|
2360
|
+
const rawConversation = record["conversation"];
|
|
2361
|
+
if (rawConversation !== void 0) {
|
|
2362
|
+
if (typeof rawConversation !== "object" || rawConversation === null) return void 0;
|
|
2363
|
+
const entry = rawConversation;
|
|
2364
|
+
const head = entry["head"];
|
|
2365
|
+
const surfaceHash = entry["surfaceHash"];
|
|
2366
|
+
const shadowed = entry["shadowed"];
|
|
2367
|
+
if (!isCount(head)) return void 0;
|
|
2368
|
+
if (typeof surfaceHash !== "string" || surfaceHash === "") return void 0;
|
|
2369
|
+
if (!Array.isArray(shadowed)) return void 0;
|
|
2370
|
+
const seqs = [];
|
|
2371
|
+
for (const seq of shadowed) {
|
|
2372
|
+
if (!isCount(seq)) return void 0;
|
|
2373
|
+
seqs.push(seq);
|
|
2374
|
+
}
|
|
2375
|
+
conversation = {
|
|
2376
|
+
shadowed: seqs,
|
|
2377
|
+
head,
|
|
2378
|
+
surfaceHash
|
|
2379
|
+
};
|
|
2380
|
+
}
|
|
2381
|
+
if (files === void 0 && conversation === void 0) return void 0;
|
|
2382
|
+
return {
|
|
2383
|
+
turn,
|
|
2384
|
+
at,
|
|
2385
|
+
...files === void 0 ? {} : { files },
|
|
2386
|
+
...conversation === void 0 ? {} : { conversation }
|
|
2387
|
+
};
|
|
2388
|
+
}
|
|
2389
|
+
/** Load-and-validate one stored session record. */
|
|
2390
|
+
function parseSessionRecord(value, sessionId) {
|
|
2391
|
+
const empty = {
|
|
2392
|
+
version: 1,
|
|
2393
|
+
sessionId,
|
|
2394
|
+
checkpoints: []
|
|
2395
|
+
};
|
|
2396
|
+
if (typeof value !== "object" || value === null) return empty;
|
|
2397
|
+
const record = value;
|
|
2398
|
+
if (record["version"] !== 1 || record["sessionId"] !== sessionId) return empty;
|
|
2399
|
+
const raw = record["checkpoints"];
|
|
2400
|
+
if (!Array.isArray(raw)) return empty;
|
|
2401
|
+
const checkpoints = [];
|
|
2402
|
+
for (const entry of raw) {
|
|
2403
|
+
const checkpoint = parseCheckpoint(entry);
|
|
2404
|
+
if (checkpoint !== void 0) checkpoints.push(checkpoint);
|
|
2405
|
+
}
|
|
2406
|
+
checkpoints.sort((left, right) => left.turn - right.turn);
|
|
2407
|
+
const undo = parseUndo(record["undo"]);
|
|
2408
|
+
return {
|
|
2409
|
+
version: 1,
|
|
2410
|
+
sessionId,
|
|
2411
|
+
checkpoints,
|
|
2412
|
+
...undo === void 0 ? {} : { undo }
|
|
2413
|
+
};
|
|
2414
|
+
}
|
|
2415
|
+
/** Checkpoint index for one plugin storage directory. */
|
|
2416
|
+
var CheckpointStore = class {
|
|
2417
|
+
retentionDays;
|
|
2418
|
+
logger;
|
|
2419
|
+
sessionsDir;
|
|
2420
|
+
workspacesDir;
|
|
2421
|
+
/**
|
|
2422
|
+
* @param root - plugin storage directory.
|
|
2423
|
+
* @param retentionDays - days a session index is retained.
|
|
2424
|
+
* @param logger - warning sink.
|
|
2425
|
+
*/
|
|
2426
|
+
constructor(root, retentionDays, logger) {
|
|
2427
|
+
this.retentionDays = retentionDays;
|
|
2428
|
+
this.logger = logger;
|
|
2429
|
+
this.sessionsDir = join(root, "sessions");
|
|
2430
|
+
this.workspacesDir = join(root, "workspaces");
|
|
2431
|
+
}
|
|
2432
|
+
/** Read one session record, or an empty record when absent or malformed. */
|
|
2433
|
+
async load(sessionId) {
|
|
2434
|
+
const value = await readJsonFile(this.fileOf(sessionId));
|
|
2435
|
+
if (value === void 0) return {
|
|
2436
|
+
version: 1,
|
|
2437
|
+
sessionId,
|
|
2438
|
+
checkpoints: []
|
|
2439
|
+
};
|
|
2440
|
+
return parseSessionRecord(value, sessionId);
|
|
2441
|
+
}
|
|
2442
|
+
/** Read one turn's checkpoint. */
|
|
2443
|
+
async checkpoint(sessionId, turn) {
|
|
2444
|
+
return (await this.load(sessionId)).checkpoints.find((checkpoint) => checkpoint.turn === turn);
|
|
2445
|
+
}
|
|
2446
|
+
/** Insert or replace one turn's checkpoint. Callers serialize per session. */
|
|
2447
|
+
async saveCheckpoint(sessionId, checkpoint) {
|
|
2448
|
+
const record = await this.load(sessionId);
|
|
2449
|
+
const checkpoints = record.checkpoints.filter((entry) => entry.turn !== checkpoint.turn);
|
|
2450
|
+
checkpoints.push(checkpoint);
|
|
2451
|
+
checkpoints.sort((left, right) => left.turn - right.turn);
|
|
2452
|
+
await writeJsonAtomic(this.fileOf(sessionId), {
|
|
2453
|
+
version: 1,
|
|
2454
|
+
sessionId,
|
|
2455
|
+
checkpoints,
|
|
2456
|
+
...record.undo === void 0 ? {} : { undo: record.undo }
|
|
2457
|
+
});
|
|
2458
|
+
}
|
|
2459
|
+
/** Read the last undoable rewind, when one was recorded. */
|
|
2460
|
+
async loadUndo(sessionId) {
|
|
2461
|
+
return (await this.load(sessionId)).undo;
|
|
2462
|
+
}
|
|
2463
|
+
/** Replace the undo record. Callers serialize per session. */
|
|
2464
|
+
async saveUndo(sessionId, undo) {
|
|
2465
|
+
const record = await this.load(sessionId);
|
|
2466
|
+
await writeJsonAtomic(this.fileOf(sessionId), {
|
|
2467
|
+
version: 1,
|
|
2468
|
+
sessionId,
|
|
2469
|
+
checkpoints: record.checkpoints,
|
|
2470
|
+
undo
|
|
2471
|
+
});
|
|
2472
|
+
}
|
|
2473
|
+
/** Drop the undo record after a successful undo. */
|
|
2474
|
+
async clearUndo(sessionId) {
|
|
2475
|
+
const record = await this.load(sessionId);
|
|
2476
|
+
if (record.undo === void 0) return;
|
|
2477
|
+
await writeJsonAtomic(this.fileOf(sessionId), {
|
|
2478
|
+
version: 1,
|
|
2479
|
+
sessionId,
|
|
2480
|
+
checkpoints: record.checkpoints
|
|
2481
|
+
});
|
|
2482
|
+
}
|
|
2483
|
+
/**
|
|
2484
|
+
* Drop indexes older than the retention window, then remove object stores
|
|
2485
|
+
* that no surviving index references.
|
|
2486
|
+
* @param now - epoch milliseconds used as the cutoff.
|
|
2487
|
+
*/
|
|
2488
|
+
async prune(now = Date.now()) {
|
|
2489
|
+
const cutoff = now - this.retentionDays * DAY_MS;
|
|
2490
|
+
const referenced = /* @__PURE__ */ new Set();
|
|
2491
|
+
let entries;
|
|
2492
|
+
try {
|
|
2493
|
+
entries = await readdir(this.sessionsDir);
|
|
2494
|
+
} catch {
|
|
2495
|
+
return;
|
|
2496
|
+
}
|
|
2497
|
+
for (const entry of entries) {
|
|
2498
|
+
if (!entry.endsWith(".json")) continue;
|
|
2499
|
+
const path = join(this.sessionsDir, entry);
|
|
2500
|
+
let mtime;
|
|
2501
|
+
try {
|
|
2502
|
+
mtime = (await stat(path)).mtimeMs;
|
|
2503
|
+
} catch {
|
|
2504
|
+
continue;
|
|
2505
|
+
}
|
|
2506
|
+
if (mtime < cutoff) {
|
|
2507
|
+
await unlink(path).catch(() => {});
|
|
2508
|
+
continue;
|
|
2509
|
+
}
|
|
2510
|
+
const value = await readJsonFile(path);
|
|
2511
|
+
const record = parseSessionRecord(value, typeof value === "object" && value !== null && typeof value.sessionId === "string" ? value.sessionId : "");
|
|
2512
|
+
for (const checkpoint of record.checkpoints) referenced.add(checkpoint.workspaceKey);
|
|
2513
|
+
if (record.undo?.files !== void 0) referenced.add(workspaceKey(record.undo.files.repoRoot));
|
|
2514
|
+
}
|
|
2515
|
+
let workspaces;
|
|
2516
|
+
try {
|
|
2517
|
+
workspaces = await readdir(this.workspacesDir);
|
|
2518
|
+
} catch {
|
|
2519
|
+
return;
|
|
2520
|
+
}
|
|
2521
|
+
for (const entry of workspaces) {
|
|
2522
|
+
if (referenced.has(entry)) continue;
|
|
2523
|
+
const path = join(this.workspacesDir, entry);
|
|
2524
|
+
try {
|
|
2525
|
+
if ((await stat(path)).mtimeMs >= cutoff) continue;
|
|
2526
|
+
} catch {
|
|
2527
|
+
continue;
|
|
2528
|
+
}
|
|
2529
|
+
await removePath(path).catch((error) => {
|
|
2530
|
+
this.logger.warn(`rewind: could not remove unused object store ${path}: ${error instanceof Error ? error.message : String(error)}`);
|
|
2531
|
+
});
|
|
2532
|
+
}
|
|
2533
|
+
}
|
|
2534
|
+
/** Absolute index file for one session. */
|
|
2535
|
+
fileOf(sessionId) {
|
|
2536
|
+
return join(this.sessionsDir, `${sessionFileName(sessionId)}.json`);
|
|
2537
|
+
}
|
|
2538
|
+
};
|
|
2539
|
+
// src/index.ts
|
|
2540
|
+
/** Stable Loader identity. */
|
|
2541
|
+
const name = "rewind";
|
|
2542
|
+
/** Services the plugin composes with. */
|
|
2543
|
+
const inject = [
|
|
2544
|
+
"commands",
|
|
2545
|
+
"sessionQuery",
|
|
2546
|
+
"workingDirectory",
|
|
2547
|
+
"subprocess"
|
|
2548
|
+
];
|
|
2549
|
+
/** Reject invalid numeric bounds loudly at activation. */
|
|
2550
|
+
function validate(config) {
|
|
2551
|
+
for (const [field, value] of [
|
|
2552
|
+
["timeoutMs", config.timeoutMs],
|
|
2553
|
+
["outputMaxBytes", config.outputMaxBytes],
|
|
2554
|
+
["maxPathsPerRestore", config.maxPathsPerRestore],
|
|
2555
|
+
["retentionDays", config.retentionDays]
|
|
2556
|
+
]) if (!Number.isSafeInteger(value) || value < 1) throw new Error(`rewind requires a positive integer ${field}`);
|
|
2557
|
+
if (config.storageDir.trim() === "") throw new Error("rewind requires a non-empty storageDir");
|
|
2558
|
+
}
|
|
2559
|
+
/**
|
|
2560
|
+
* Register `/rewind`, the checkpoint recorder, and the Git runtime.
|
|
2561
|
+
* @param ctx - plugin context with commands, session query, working directory, and subprocess.
|
|
2562
|
+
* @param config - plugin configuration; defaults apply when omitted.
|
|
2563
|
+
*/
|
|
2564
|
+
function apply(ctx, config = DEFAULT_CONFIG) {
|
|
2565
|
+
if (!(config?.enabled ?? DEFAULT_CONFIG.enabled)) return;
|
|
2566
|
+
validate(config);
|
|
2567
|
+
const logger = {
|
|
2568
|
+
info: (message) => {
|
|
2569
|
+
ctx.logger.info(message);
|
|
2570
|
+
},
|
|
2571
|
+
warn: (message) => {
|
|
2572
|
+
ctx.logger.warn(message);
|
|
2573
|
+
}
|
|
2574
|
+
};
|
|
2575
|
+
const lifetime = new AbortController();
|
|
2576
|
+
const store = new CheckpointStore(config.storageDir, config.retentionDays, logger);
|
|
2577
|
+
const provider = new GitProvider(ctx.subprocess, lifetime.signal, {
|
|
2578
|
+
timeoutMs: config.timeoutMs,
|
|
2579
|
+
outputMaxBytes: config.outputMaxBytes
|
|
2580
|
+
}, logger);
|
|
2581
|
+
const workspaces = new WorkspaceResolver(config.storageDir, () => provider.get());
|
|
2582
|
+
const recorder = new SnapshotRecorder({
|
|
2583
|
+
store,
|
|
2584
|
+
workspaces,
|
|
2585
|
+
git: () => provider.get(),
|
|
2586
|
+
workingDirectory: ctx.workingDirectory,
|
|
2587
|
+
logger,
|
|
2588
|
+
lifetime: lifetime.signal
|
|
2589
|
+
});
|
|
2590
|
+
const deps = {
|
|
2591
|
+
config,
|
|
2592
|
+
store,
|
|
2593
|
+
workspaces,
|
|
2594
|
+
git: () => provider.get(),
|
|
2595
|
+
llm: () => ctx.get("llm"),
|
|
2596
|
+
tokenMeter: () => ctx.get("tokenMeter"),
|
|
2597
|
+
observe: async (sessionId) => {
|
|
2598
|
+
const observation = await ctx.sessionQuery.observeSession(sessionId, { projectionMode: "none" });
|
|
2599
|
+
return {
|
|
2600
|
+
events: observation.events,
|
|
2601
|
+
dispose: () => {
|
|
2602
|
+
observation[Symbol.dispose]?.();
|
|
2603
|
+
}
|
|
2604
|
+
};
|
|
2605
|
+
},
|
|
2606
|
+
logger
|
|
2607
|
+
};
|
|
2608
|
+
ctx.effect(() => ctx.commands.register({
|
|
2609
|
+
name: "rewind",
|
|
2610
|
+
description: "Rewind files and conversation to an earlier turn.",
|
|
2611
|
+
handler: (invocation) => runRewindCommand(deps, invocation)
|
|
2612
|
+
}), "rewind command");
|
|
2613
|
+
ctx.on("session/event", (session, event) => {
|
|
2614
|
+
recorder.observe(session, event);
|
|
2615
|
+
});
|
|
2616
|
+
ctx.on("session/disposed", (session) => {
|
|
2617
|
+
recorder.forget(session);
|
|
2618
|
+
});
|
|
2619
|
+
ctx.on("tools/pre-execute", async (execution, next) => {
|
|
2620
|
+
await recorder.settleFor(execution);
|
|
2621
|
+
return next();
|
|
2622
|
+
});
|
|
2623
|
+
ctx.effect(() => async () => {
|
|
2624
|
+
lifetime.abort();
|
|
2625
|
+
await recorder.dispose();
|
|
2626
|
+
}, "rewind lifetime");
|
|
2627
|
+
store.prune().catch((error) => {
|
|
2628
|
+
logger.warn(`rewind: could not prune old checkpoints: ${error instanceof Error ? error.message : String(error)}`);
|
|
2629
|
+
});
|
|
2630
|
+
}
|
|
2631
|
+
export { Config, apply, inject, name };
|