minicode-ai 0.9.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +935 -0
- package/LICENSE +21 -0
- package/README.md +200 -0
- package/cli/args.ts +195 -0
- package/cli/auto-update.ts +108 -0
- package/cli/commands/auth.ts +166 -0
- package/cli/commands/config.ts +382 -0
- package/cli/commands/doctor.ts +128 -0
- package/cli/commands/exec.ts +179 -0
- package/cli/commands/mcp.ts +35 -0
- package/cli/commands/memory.ts +107 -0
- package/cli/commands/pricing.ts +100 -0
- package/cli/commands/providers.ts +162 -0
- package/cli/commands/sessions.ts +128 -0
- package/cli/commands/skills.ts +61 -0
- package/cli/commands/stats.ts +82 -0
- package/cli/commands.ts +317 -0
- package/cli/index.ts +539 -0
- package/cli/model-manager.ts +112 -0
- package/cli/provider-manager.ts +111 -0
- package/cli/repl.ts +734 -0
- package/cli/router.ts +124 -0
- package/cli/setup.ts +780 -0
- package/cli/wizard.ts +21 -0
- package/docs/ARCHITECTURE.html +1222 -0
- package/docs/README.md +109 -0
- package/docs/architecture.md +44 -0
- package/docs/changelog.md +3 -0
- package/package.json +91 -0
- package/src/agents/pool.ts +43 -0
- package/src/app/mentions.ts +50 -0
- package/src/app/provider-layer.ts +118 -0
- package/src/app/rag-layer.ts +105 -0
- package/src/app/session.ts +154 -0
- package/src/app/tool-layer.ts +56 -0
- package/src/config.ts +372 -0
- package/src/constants.ts +119 -0
- package/src/hooks/run.ts +89 -0
- package/src/lib/atomic-write.ts +88 -0
- package/src/lib/db-path.ts +36 -0
- package/src/lib/git-hardening.ts +91 -0
- package/src/lib/ignore.ts +58 -0
- package/src/lib/keystore.ts +202 -0
- package/src/lib/net.ts +70 -0
- package/src/lib/safe-open.ts +138 -0
- package/src/lib/session-id.ts +23 -0
- package/src/lib/trash.ts +38 -0
- package/src/lib/trusted-exec.ts +81 -0
- package/src/lsp/client.ts +395 -0
- package/src/mcp/client.ts +400 -0
- package/src/mcp/http-transport.ts +344 -0
- package/src/mcp/server.ts +538 -0
- package/src/mcp/transport.ts +150 -0
- package/src/memory/files.ts +159 -0
- package/src/memory/vector.ts +775 -0
- package/src/policy/allowlist.ts +67 -0
- package/src/policy/bash-guard.ts +465 -0
- package/src/policy/compaction.ts +271 -0
- package/src/policy/context.ts +161 -0
- package/src/policy/executor.ts +199 -0
- package/src/policy/jail.ts +127 -0
- package/src/policy/permission.ts +517 -0
- package/src/policy/pricing.ts +336 -0
- package/src/policy/ratelimit.ts +54 -0
- package/src/policy/sandbox-policy.ts +157 -0
- package/src/policy/scrub.ts +138 -0
- package/src/policy/update-check.ts +200 -0
- package/src/policy/usage.ts +292 -0
- package/src/policy/verifier.ts +181 -0
- package/src/providers/anthropic.ts +401 -0
- package/src/providers/auth-store.ts +139 -0
- package/src/providers/build.ts +136 -0
- package/src/providers/detect.ts +126 -0
- package/src/providers/effort.ts +165 -0
- package/src/providers/guards.ts +107 -0
- package/src/providers/oauth.ts +326 -0
- package/src/providers/presets.ts +122 -0
- package/src/providers/provision.ts +298 -0
- package/src/providers/responses.ts +371 -0
- package/src/providers/router.ts +247 -0
- package/src/repo/repomap.ts +470 -0
- package/src/sandbox/docker.ts +129 -0
- package/src/sandbox/os.ts +193 -0
- package/src/session/checkpoint.ts +543 -0
- package/src/session/journal.ts +1347 -0
- package/src/session/persistence.ts +446 -0
- package/src/session/shadow-git.ts +351 -0
- package/src/session/turn-marker.ts +118 -0
- package/src/skills/loader.ts +117 -0
- package/src/telemetry/trace.ts +283 -0
- package/src/tools/ask_user.ts +54 -0
- package/src/tools/bash.ts +400 -0
- package/src/tools/code_run.ts +96 -0
- package/src/tools/delete_file.ts +31 -0
- package/src/tools/edit.ts +204 -0
- package/src/tools/git.ts +301 -0
- package/src/tools/glob.ts +90 -0
- package/src/tools/grep.ts +281 -0
- package/src/tools/hashline.ts +66 -0
- package/src/tools/index.ts +103 -0
- package/src/tools/lsp.ts +346 -0
- package/src/tools/mcp_call.ts +163 -0
- package/src/tools/memory.ts +144 -0
- package/src/tools/move_file.ts +47 -0
- package/src/tools/patch.ts +86 -0
- package/src/tools/read_file.ts +130 -0
- package/src/tools/read_image.ts +80 -0
- package/src/tools/submit_result.ts +49 -0
- package/src/tools/task.ts +346 -0
- package/src/tools/todo.ts +201 -0
- package/src/tools/web_fetch.ts +161 -0
- package/src/tools/web_search.ts +156 -0
- package/src/tools/write_file.ts +42 -0
- package/src/ui/approval/prompt.ts +76 -0
- package/src/ui/assistant/simple.ts +568 -0
- package/src/ui/assistant/turn-status.ts +303 -0
- package/src/ui/contract.ts +55 -0
- package/src/ui/footer.ts +105 -0
- package/src/ui/input/input.ts +805 -0
- package/src/ui/input/prompt-engine.ts +606 -0
- package/src/ui/render/collapse.ts +84 -0
- package/src/ui/render/detail.ts +24 -0
- package/src/ui/render/diff.ts +181 -0
- package/src/ui/render/errors.ts +239 -0
- package/src/ui/render/format.ts +54 -0
- package/src/ui/render/highlight.ts +294 -0
- package/src/ui/render/markdown.ts +120 -0
- package/src/ui/render/money.ts +12 -0
- package/src/ui/render/reasoning.ts +20 -0
- package/src/ui/render/sanitize.ts +80 -0
- package/src/ui/render/table.ts +88 -0
- package/src/ui/render/theme.ts +339 -0
- package/src/ui/render/width.ts +256 -0
- package/src/ui/render/wrap.ts +120 -0
- package/src/ui/runtime/bus-debug.ts +83 -0
- package/src/ui/runtime/chrome.ts +301 -0
- package/src/ui/runtime/spinner.ts +77 -0
- package/src/ui/runtime/statusline.ts +227 -0
- package/src/ui/screens/model-manager.ts +434 -0
- package/src/ui/screens/overlay.ts +61 -0
- package/src/ui/screens/picker.ts +307 -0
- package/src/ui/screens/provider-manager.ts +450 -0
- package/src/ui/screens/wizard.ts +132 -0
- package/vendor/minicore/VENDOR.md +29 -0
- package/vendor/minicore/package.json +21 -0
- package/vendor/minicore/src/core/budget.ts +26 -0
- package/vendor/minicore/src/core/compact.ts +76 -0
- package/vendor/minicore/src/core/errors.ts +60 -0
- package/vendor/minicore/src/core/events.ts +74 -0
- package/vendor/minicore/src/core/executor.ts +139 -0
- package/vendor/minicore/src/core/history.ts +32 -0
- package/vendor/minicore/src/core/index.ts +42 -0
- package/vendor/minicore/src/core/loop.ts +344 -0
- package/vendor/minicore/src/core/permission.ts +24 -0
- package/vendor/minicore/src/core/provider.ts +39 -0
- package/vendor/minicore/src/core/recovery.ts +34 -0
- package/vendor/minicore/src/core/session.ts +327 -0
- package/vendor/minicore/src/core/snapshot.ts +142 -0
- package/vendor/minicore/src/core/tokens.ts +111 -0
- package/vendor/minicore/src/core/tool.ts +118 -0
- package/vendor/minicore/src/core/types.ts +50 -0
- package/vendor/minicore/src/providers/openai-compat.ts +366 -0
|
@@ -0,0 +1,543 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto"
|
|
2
|
+
import { existsSync } from "node:fs"
|
|
3
|
+
import { mkdir, readdir, readFile, rm } from "node:fs/promises"
|
|
4
|
+
import { join, relative, resolve } from "node:path"
|
|
5
|
+
import { LIMITS } from "../constants.ts"
|
|
6
|
+
import { atomicWriteText } from "../lib/atomic-write.ts"
|
|
7
|
+
import { GIT_SAFE_BASE } from "../lib/git-hardening.ts"
|
|
8
|
+
import { sanitizeSessionPart } from "../lib/session-id.ts"
|
|
9
|
+
import { isPathOutsideRoot } from "../policy/jail.ts"
|
|
10
|
+
import { appendUndoMarker, loadJournal } from "./journal.ts"
|
|
11
|
+
import { diffTrees, ephemeralTree, restoreTree, snapshotTree } from "./shadow-git.ts"
|
|
12
|
+
|
|
13
|
+
/** Alias back-compat: satu-satunya sanitizer kini di lib/session-id.ts (F-17). */
|
|
14
|
+
export function sanitizeSessionId(id: string): string {
|
|
15
|
+
return sanitizeSessionPart(id)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// In-process lock per manifest path untuk mencegah lost-update checkpoint
|
|
19
|
+
// saat turn paralel (mis. Pool(3) sub-agent).
|
|
20
|
+
const checkpointLocks = new Map<string, Promise<void>>()
|
|
21
|
+
|
|
22
|
+
async function withCheckpointLock<T>(path: string, fn: () => Promise<T>): Promise<T> {
|
|
23
|
+
const prev = checkpointLocks.get(path) ?? Promise.resolve()
|
|
24
|
+
let release!: () => void
|
|
25
|
+
const next = new Promise<void>((res) => (release = res))
|
|
26
|
+
checkpointLocks.set(
|
|
27
|
+
path,
|
|
28
|
+
prev.then(() => next),
|
|
29
|
+
)
|
|
30
|
+
await prev
|
|
31
|
+
try {
|
|
32
|
+
return await fn()
|
|
33
|
+
} finally {
|
|
34
|
+
release()
|
|
35
|
+
if (checkpointLocks.get(path) === next) checkpointLocks.delete(path)
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const MAX_CHECKPOINTS = 20
|
|
40
|
+
|
|
41
|
+
export interface FileSnapshot {
|
|
42
|
+
path: string // relative path
|
|
43
|
+
content: string | null // null means file was deleted/didn't exist
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface Checkpoint {
|
|
47
|
+
id: string
|
|
48
|
+
turn: number
|
|
49
|
+
timestamp: string
|
|
50
|
+
description: string
|
|
51
|
+
snapshots: FileSnapshot[] // pre-edit state (untuk /undo)
|
|
52
|
+
redoSnapshots?: FileSnapshot[] // post-edit state (untuk /redo)
|
|
53
|
+
/** Tree git pre-turn (mode shadow-git). Bila ada, snapshots dibiarkan kosong. */
|
|
54
|
+
treeBefore?: string
|
|
55
|
+
/** Tree git post-turn (mode shadow-git) untuk /redo. */
|
|
56
|
+
treeAfter?: string
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface CheckpointManifest {
|
|
60
|
+
sessionId: string
|
|
61
|
+
currentIndex: number // pointer in history
|
|
62
|
+
checkpoints: Checkpoint[]
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function getCheckpointDir(sessionId: string, cwd: string = process.cwd()): string {
|
|
66
|
+
return resolve(cwd, ".minicode", "checkpoints", sanitizeSessionId(sessionId))
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function getManifestPath(sessionId: string, cwd: string = process.cwd()): string {
|
|
70
|
+
return join(getCheckpointDir(sessionId, cwd), "manifest.json")
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export async function loadCheckpointManifest(
|
|
74
|
+
sessionId: string,
|
|
75
|
+
cwd?: string,
|
|
76
|
+
): Promise<CheckpointManifest> {
|
|
77
|
+
const path = getManifestPath(sessionId, cwd)
|
|
78
|
+
try {
|
|
79
|
+
const raw = await readFile(path, "utf8")
|
|
80
|
+
try {
|
|
81
|
+
return JSON.parse(raw) as CheckpointManifest
|
|
82
|
+
} catch (e) {
|
|
83
|
+
if (e instanceof SyntaxError) {
|
|
84
|
+
const backup = `${path}.corrupt.${Date.now()}`
|
|
85
|
+
await atomicWriteText(backup, raw).catch(() => {})
|
|
86
|
+
process.stderr.write(
|
|
87
|
+
`[warn] checkpoint: manifest corrupt — backup to ${backup}: ${(e as Error).message} — starting empty\n`,
|
|
88
|
+
)
|
|
89
|
+
}
|
|
90
|
+
throw e
|
|
91
|
+
}
|
|
92
|
+
} catch (e) {
|
|
93
|
+
// manifest hilang = kondisi normal utk sesi baru; manifest KORUP sudah di-backup di atas
|
|
94
|
+
// lalu akan jatuh ke sini sebagai SyntaxError — tetap return empty tapi sudah backup
|
|
95
|
+
const code = (e as NodeJS.ErrnoException).code
|
|
96
|
+
if (code !== "ENOENT" && !(e instanceof SyntaxError)) {
|
|
97
|
+
process.stderr.write(
|
|
98
|
+
`[warn] checkpoint: manifest unreadable (${(e as Error).message}) — starting empty\n`,
|
|
99
|
+
)
|
|
100
|
+
}
|
|
101
|
+
if (e instanceof SyntaxError) {
|
|
102
|
+
// already backed up, return empty
|
|
103
|
+
}
|
|
104
|
+
return { sessionId: sanitizeSessionId(sessionId), currentIndex: -1, checkpoints: [] }
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export async function saveCheckpointManifest(
|
|
109
|
+
manifest: CheckpointManifest,
|
|
110
|
+
cwd?: string,
|
|
111
|
+
): Promise<void> {
|
|
112
|
+
const dir = getCheckpointDir(manifest.sessionId, cwd)
|
|
113
|
+
await mkdir(dir, { recursive: true }).catch(() => {})
|
|
114
|
+
const path = getManifestPath(manifest.sessionId, cwd)
|
|
115
|
+
await atomicWriteText(path, JSON.stringify(manifest, null, 2))
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// P3 — validasi resume: workspace berubah sejak checkpoint terakhir?
|
|
119
|
+
// Bukan replay buta: mode git bandingkan treeAfter terakhir vs tree sekarang
|
|
120
|
+
// (tanpa pin ref baru); mode files bandingkan snapshot post (redo) vs isi
|
|
121
|
+
// sekarang. Best-effort: null bila tak bisa dipastikan — resume tetap jalan.
|
|
122
|
+
export async function validateResumeWorkspace(
|
|
123
|
+
cwd: string,
|
|
124
|
+
sessionId: string,
|
|
125
|
+
): Promise<{ mode: "git" | "files" | "none"; diverged: number } | null> {
|
|
126
|
+
try {
|
|
127
|
+
const manifest = await loadCheckpointManifest(sessionId, cwd)
|
|
128
|
+
if (manifest.checkpoints.length === 0) return { mode: "none", diverged: 0 }
|
|
129
|
+
const last =
|
|
130
|
+
manifest.checkpoints[manifest.currentIndex] ??
|
|
131
|
+
manifest.checkpoints[manifest.checkpoints.length - 1]!
|
|
132
|
+
if (last.treeAfter) {
|
|
133
|
+
const now = await ephemeralTree(cwd)
|
|
134
|
+
if (!now) return null
|
|
135
|
+
if (now === last.treeAfter) return { mode: "git", diverged: 0 }
|
|
136
|
+
const changes = await diffTrees(cwd, last.treeAfter, now)
|
|
137
|
+
// Pembukuan harness sendiri (.minicode/: manifest, trace, todos berubah
|
|
138
|
+
// tiap run) bukan divergensi user — keluarkan agar resume di repo tanpa
|
|
139
|
+
// gitignore .minicode tidak selalu kuning.
|
|
140
|
+
const userChanges = changes.filter(
|
|
141
|
+
(ch) => ch.path !== ".minicode" && !ch.path.startsWith(".minicode/"),
|
|
142
|
+
)
|
|
143
|
+
return { mode: "git", diverged: userChanges.length }
|
|
144
|
+
}
|
|
145
|
+
const refs = last.redoSnapshots?.length ? last.redoSnapshots : last.snapshots
|
|
146
|
+
if (refs.length === 0) return { mode: "none", diverged: 0 }
|
|
147
|
+
let diverged = 0
|
|
148
|
+
for (const s of refs.slice(0, LIMITS.WORKSPACE_SNAPSHOT_LIMIT)) {
|
|
149
|
+
// Jail: manifest bisa usang/rusak — jangan baca di luar workspace.
|
|
150
|
+
if (isPathOutsideRoot(s.path, cwd)) {
|
|
151
|
+
diverged++
|
|
152
|
+
continue
|
|
153
|
+
}
|
|
154
|
+
let cur: string | null
|
|
155
|
+
try {
|
|
156
|
+
cur = await readFile(resolve(cwd, s.path), "utf8")
|
|
157
|
+
} catch {
|
|
158
|
+
cur = null
|
|
159
|
+
}
|
|
160
|
+
if (cur !== s.content) diverged++
|
|
161
|
+
}
|
|
162
|
+
return { mode: "files", diverged }
|
|
163
|
+
} catch {
|
|
164
|
+
return null
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export async function captureFileSnapshot(
|
|
169
|
+
filePath: string,
|
|
170
|
+
cwd: string = process.cwd(),
|
|
171
|
+
): Promise<FileSnapshot> {
|
|
172
|
+
const rel = relative(cwd, filePath).replace(/\\/g, "/")
|
|
173
|
+
const abs = resolve(cwd, filePath)
|
|
174
|
+
try {
|
|
175
|
+
const content = await readFile(abs, "utf8")
|
|
176
|
+
return { path: rel, content }
|
|
177
|
+
} catch {
|
|
178
|
+
return { path: rel, content: null }
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// Snapshot seluruh workspace (maks `limit` file) — menangkap perubahan apa pun
|
|
183
|
+
// termasuk bash/git (bukan cuma edit/write_file). Dipakai /undo per turn.
|
|
184
|
+
async function walkFiles(root: string, rel: string, out: string[], limit: number): Promise<void> {
|
|
185
|
+
if (out.length >= limit) return
|
|
186
|
+
const dir = rel ? join(root, rel) : root
|
|
187
|
+
const entries = await readdir(dir, { withFileTypes: true }).catch(() => [])
|
|
188
|
+
for (const e of entries) {
|
|
189
|
+
if (out.length >= limit) break
|
|
190
|
+
if (e.name.startsWith(".") || e.name === "node_modules" || e.name === ".git") continue
|
|
191
|
+
const r = rel ? `${rel}/${e.name}` : e.name
|
|
192
|
+
if (e.isDirectory()) await walkFiles(root, r, out, limit)
|
|
193
|
+
else out.push(r)
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export async function snapshotWorkspace(
|
|
198
|
+
cwd: string = process.cwd(),
|
|
199
|
+
limit = 200,
|
|
200
|
+
): Promise<FileSnapshot[]> {
|
|
201
|
+
// Try git dirty files first for efficiency on large workspaces.
|
|
202
|
+
// Audit #10: status menjalankan fsmonitor repo tanpa netralisasi; git
|
|
203
|
+
// di-resolve absolut agar `git.bat` repo tak dieksekusi dari cwd (Windows).
|
|
204
|
+
try {
|
|
205
|
+
const { spawnSync } = await import("node:child_process")
|
|
206
|
+
const { resolveTrustedExecutable } = await import("../lib/trusted-exec.ts")
|
|
207
|
+
const r = spawnSync(
|
|
208
|
+
resolveTrustedExecutable("git"),
|
|
209
|
+
[...GIT_SAFE_BASE, "status", "--porcelain"],
|
|
210
|
+
{
|
|
211
|
+
cwd,
|
|
212
|
+
timeout: 2000,
|
|
213
|
+
encoding: "utf8",
|
|
214
|
+
},
|
|
215
|
+
)
|
|
216
|
+
if (r.status === 0 && r.stdout) {
|
|
217
|
+
const dirty = r.stdout
|
|
218
|
+
.split("\n")
|
|
219
|
+
.map((l: string) => l.slice(3).trim())
|
|
220
|
+
.filter(Boolean)
|
|
221
|
+
.slice(0, limit)
|
|
222
|
+
if (dirty.length > 0) {
|
|
223
|
+
const snaps: FileSnapshot[] = []
|
|
224
|
+
for (const f of dirty) snaps.push(await captureFileSnapshot(resolve(cwd, f), cwd))
|
|
225
|
+
return snaps
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
} catch {}
|
|
229
|
+
const files: string[] = []
|
|
230
|
+
await walkFiles(cwd, "", files, limit)
|
|
231
|
+
const snaps: FileSnapshot[] = []
|
|
232
|
+
for (const f of files) {
|
|
233
|
+
snaps.push(await captureFileSnapshot(resolve(cwd, f), cwd))
|
|
234
|
+
}
|
|
235
|
+
return snaps
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// ── Shadow-git: jalur utama bila cwd adalah repo git ──
|
|
239
|
+
//
|
|
240
|
+
// Menyimpan SHA tree alih-alih isi file. Biayanya O(delta) bukan
|
|
241
|
+
// O(ukuran workspace), tanpa cap jumlah file, dan tidak menyentuh index/HEAD
|
|
242
|
+
// user. Fallback ke snapshot manual di bawah tetap ada untuk non-repo.
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Ambil snapshot pre-turn. Return penanda mode yang dipakai supaya pemanggil
|
|
246
|
+
* tahu apakah perlu mengumpulkan snapshot file manual.
|
|
247
|
+
*/
|
|
248
|
+
export async function beginTurnSnapshot(
|
|
249
|
+
sessionId: string,
|
|
250
|
+
cwd: string = process.cwd(),
|
|
251
|
+
): Promise<{ mode: "git"; tree: string } | { mode: "files"; snapshots: FileSnapshot[] }> {
|
|
252
|
+
const shadow = await snapshotTree(cwd, sessionId, "pre")
|
|
253
|
+
if (shadow) return { mode: "git", tree: shadow.tree }
|
|
254
|
+
return { mode: "files", snapshots: await snapshotWorkspace(cwd, LIMITS.WORKSPACE_SNAPSHOT_LIMIT) }
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Rekam checkpoint dari tree git pre/post turn. */
|
|
258
|
+
export async function recordCheckpointFromTrees(
|
|
259
|
+
sessionId: string,
|
|
260
|
+
turn: number,
|
|
261
|
+
treeBefore: string,
|
|
262
|
+
treeAfter: string | undefined,
|
|
263
|
+
description: string,
|
|
264
|
+
cwd: string = process.cwd(),
|
|
265
|
+
): Promise<Checkpoint | null> {
|
|
266
|
+
// Tak ada perubahan → tak ada yang perlu di-undo. Ini juga mencegah manifest
|
|
267
|
+
// dipenuhi checkpoint kosong dari turn yang hanya membaca.
|
|
268
|
+
if (treeAfter && treeAfter === treeBefore) return null
|
|
269
|
+
const manifestPath = getManifestPath(sessionId, cwd)
|
|
270
|
+
return withCheckpointLock(manifestPath, async () => {
|
|
271
|
+
const manifest = await loadCheckpointManifest(sessionId, cwd)
|
|
272
|
+
const cp: Checkpoint = {
|
|
273
|
+
id: `cp_${Date.now()}_${randomUUID().slice(0, 6)}`,
|
|
274
|
+
turn,
|
|
275
|
+
timestamp: new Date().toISOString(),
|
|
276
|
+
description,
|
|
277
|
+
snapshots: [],
|
|
278
|
+
treeBefore,
|
|
279
|
+
...(treeAfter ? { treeAfter } : {}),
|
|
280
|
+
}
|
|
281
|
+
if (manifest.currentIndex < manifest.checkpoints.length - 1) {
|
|
282
|
+
manifest.checkpoints = manifest.checkpoints.slice(0, manifest.currentIndex + 1)
|
|
283
|
+
}
|
|
284
|
+
manifest.checkpoints.push(cp)
|
|
285
|
+
if (manifest.checkpoints.length > MAX_CHECKPOINTS) {
|
|
286
|
+
manifest.checkpoints = manifest.checkpoints.slice(-MAX_CHECKPOINTS)
|
|
287
|
+
}
|
|
288
|
+
manifest.currentIndex = manifest.checkpoints.length - 1
|
|
289
|
+
await saveCheckpointManifest(manifest, cwd)
|
|
290
|
+
return cp
|
|
291
|
+
})
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
export async function recordCheckpoint(
|
|
295
|
+
sessionId: string,
|
|
296
|
+
turn: number,
|
|
297
|
+
filePaths: string[],
|
|
298
|
+
description: string = "",
|
|
299
|
+
cwd: string = process.cwd(),
|
|
300
|
+
): Promise<Checkpoint> {
|
|
301
|
+
const snapshots: FileSnapshot[] = []
|
|
302
|
+
for (const fp of filePaths) {
|
|
303
|
+
snapshots.push(await captureFileSnapshot(fp, cwd))
|
|
304
|
+
}
|
|
305
|
+
const cp = await recordCheckpointFromSnapshots(sessionId, turn, snapshots, description, cwd)
|
|
306
|
+
if (!cp) throw new Error("no files to checkpoint")
|
|
307
|
+
return cp
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// Rekam checkpoint dari snapshot yang SUDAH ditangkap. `snapshots` = pre-edit
|
|
311
|
+
// (untuk /undo); `redoSnapshots` opsional = post-edit (untuk /redo).
|
|
312
|
+
export async function recordCheckpointFromSnapshots(
|
|
313
|
+
sessionId: string,
|
|
314
|
+
turn: number,
|
|
315
|
+
snapshots: FileSnapshot[],
|
|
316
|
+
description: string = "",
|
|
317
|
+
cwd: string = process.cwd(),
|
|
318
|
+
redoSnapshots?: FileSnapshot[],
|
|
319
|
+
): Promise<Checkpoint | null> {
|
|
320
|
+
if (snapshots.length === 0) return null
|
|
321
|
+
const manifestPath = getManifestPath(sessionId, cwd)
|
|
322
|
+
return withCheckpointLock(manifestPath, async () => {
|
|
323
|
+
const manifest = await loadCheckpointManifest(sessionId, cwd)
|
|
324
|
+
const cp: Checkpoint = {
|
|
325
|
+
id: `cp_${Date.now()}_${randomUUID().slice(0, 6)}`,
|
|
326
|
+
turn,
|
|
327
|
+
timestamp: new Date().toISOString(),
|
|
328
|
+
description,
|
|
329
|
+
snapshots,
|
|
330
|
+
...(redoSnapshots?.length ? { redoSnapshots } : {}),
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// Truncate any redo branches if new action is taken
|
|
334
|
+
if (manifest.currentIndex < manifest.checkpoints.length - 1) {
|
|
335
|
+
manifest.checkpoints = manifest.checkpoints.slice(0, manifest.currentIndex + 1)
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
manifest.checkpoints.push(cp)
|
|
339
|
+
// Cap manifest agar tidak membengkak tanpa batas (keep N terakhir)
|
|
340
|
+
if (manifest.checkpoints.length > MAX_CHECKPOINTS) {
|
|
341
|
+
manifest.checkpoints = manifest.checkpoints.slice(-MAX_CHECKPOINTS)
|
|
342
|
+
}
|
|
343
|
+
manifest.currentIndex = manifest.checkpoints.length - 1
|
|
344
|
+
|
|
345
|
+
await saveCheckpointManifest(manifest, cwd)
|
|
346
|
+
return cp
|
|
347
|
+
})
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// Terapkan snapshot dengan jail path: path di luar workspace dilewati.
|
|
351
|
+
async function applySnapshots(snapshots: FileSnapshot[], cwd: string): Promise<string[]> {
|
|
352
|
+
const root = resolve(cwd)
|
|
353
|
+
const applied: string[] = []
|
|
354
|
+
for (const snap of snapshots) {
|
|
355
|
+
const absPath = resolve(root, snap.path)
|
|
356
|
+
if (isPathOutsideRoot(absPath, root)) {
|
|
357
|
+
applied.push(`${snap.path} (skipped: outside workspace)`)
|
|
358
|
+
continue
|
|
359
|
+
}
|
|
360
|
+
if (snap.content === null) {
|
|
361
|
+
if (existsSync(absPath)) {
|
|
362
|
+
await rm(absPath, { force: true }).catch(() => {})
|
|
363
|
+
applied.push(`${snap.path} (removed)`)
|
|
364
|
+
}
|
|
365
|
+
} else {
|
|
366
|
+
await atomicWriteText(absPath, snap.content)
|
|
367
|
+
applied.push(`${snap.path} (restored)`)
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
return applied
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/** Terapkan satu checkpoint: tree git bila ada, else snapshot file. */
|
|
374
|
+
async function applyCheckpoint(
|
|
375
|
+
cp: Checkpoint,
|
|
376
|
+
direction: "undo" | "redo",
|
|
377
|
+
cwd: string,
|
|
378
|
+
): Promise<string[]> {
|
|
379
|
+
const tree = direction === "undo" ? cp.treeBefore : (cp.treeAfter ?? cp.treeBefore)
|
|
380
|
+
if (tree) {
|
|
381
|
+
const res = await restoreTree(cwd, tree)
|
|
382
|
+
return [...res.applied, ...res.skipped.map((s) => `${s} (skipped)`)]
|
|
383
|
+
}
|
|
384
|
+
const snaps = direction === "undo" ? cp.snapshots : (cp.redoSnapshots ?? cp.snapshots)
|
|
385
|
+
return applySnapshots(snaps, cwd)
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
export async function undoLastCheckpoint(
|
|
389
|
+
sessionId: string,
|
|
390
|
+
cwd: string = process.cwd(),
|
|
391
|
+
): Promise<{ success: boolean; restoredFiles: string[]; message: string }> {
|
|
392
|
+
const manifestPath = getManifestPath(sessionId, cwd)
|
|
393
|
+
return withCheckpointLock(manifestPath, async () => {
|
|
394
|
+
const manifest = await loadCheckpointManifest(sessionId, cwd)
|
|
395
|
+
if (manifest.currentIndex < 0 || manifest.checkpoints.length === 0) {
|
|
396
|
+
return { success: false, restoredFiles: [], message: "no checkpoints to undo" }
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
const targetCp = manifest.checkpoints[manifest.currentIndex]!
|
|
400
|
+
const restoredFiles = await applyCheckpoint(targetCp, "undo", cwd)
|
|
401
|
+
|
|
402
|
+
// Urutan: marker DULU (bukti durable niat+hasil apply), pointer-disk
|
|
403
|
+
// TERAKHIR. Crash apply→save: marker + pointer basi → rekonsiliasi
|
|
404
|
+
// mengadopsi pointer (P0-3). Marker gagal ≠ save batal (lanjut save).
|
|
405
|
+
const newIndex = manifest.currentIndex - 1
|
|
406
|
+
await appendUndoMarker(sessionId, cwd, "undo", targetCp.turn, {
|
|
407
|
+
newIndex,
|
|
408
|
+
files: restoredFiles.length,
|
|
409
|
+
}).catch((e) => {
|
|
410
|
+
process.stderr.write(`[warn] journal: undo marker failed: ${(e as Error).message}\n`)
|
|
411
|
+
})
|
|
412
|
+
manifest.currentIndex = newIndex
|
|
413
|
+
await saveCheckpointManifest(manifest, cwd)
|
|
414
|
+
|
|
415
|
+
return {
|
|
416
|
+
success: true,
|
|
417
|
+
restoredFiles,
|
|
418
|
+
message: `undid checkpoint ${targetCp.id} (turn ${targetCp.turn})`,
|
|
419
|
+
}
|
|
420
|
+
})
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
export async function redoLastCheckpoint(
|
|
424
|
+
sessionId: string,
|
|
425
|
+
cwd: string = process.cwd(),
|
|
426
|
+
): Promise<{ success: boolean; reappliedFiles: string[]; message: string }> {
|
|
427
|
+
const manifestPath = getManifestPath(sessionId, cwd)
|
|
428
|
+
return withCheckpointLock(manifestPath, async () => {
|
|
429
|
+
const manifest = await loadCheckpointManifest(sessionId, cwd)
|
|
430
|
+
if (manifest.currentIndex >= manifest.checkpoints.length - 1) {
|
|
431
|
+
return { success: false, reappliedFiles: [], message: "no undone checkpoints to redo" }
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// Protokol UNIFORM dengan undo (P0-3): hitung target DULU tanpa mutasi
|
|
435
|
+
// pointer, apply files, tulis marker, BARU persist pointer. Versi lama
|
|
436
|
+
// increment pointer di memori sebelum apply — hilang saat crash dan
|
|
437
|
+
// mengaburkan jendela crash (pointer-memory vs pointer-disk berbeda).
|
|
438
|
+
const targetIndex = manifest.currentIndex + 1
|
|
439
|
+
const targetCp = manifest.checkpoints[targetIndex]!
|
|
440
|
+
const reappliedFiles = await applyCheckpoint(targetCp, "redo", cwd)
|
|
441
|
+
|
|
442
|
+
await appendUndoMarker(sessionId, cwd, "redo", targetCp.turn, {
|
|
443
|
+
newIndex: targetIndex,
|
|
444
|
+
files: reappliedFiles.length,
|
|
445
|
+
}).catch((e) => {
|
|
446
|
+
process.stderr.write(`[warn] journal: redo marker failed: ${(e as Error).message}\n`)
|
|
447
|
+
})
|
|
448
|
+
manifest.currentIndex = targetIndex
|
|
449
|
+
await saveCheckpointManifest(manifest, cwd)
|
|
450
|
+
|
|
451
|
+
return {
|
|
452
|
+
success: true,
|
|
453
|
+
reappliedFiles,
|
|
454
|
+
message: `redid checkpoint ${targetCp.id} (turn ${targetCp.turn})`,
|
|
455
|
+
}
|
|
456
|
+
})
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* Rekonsiliasi pointer undo/redo pasca-crash (P0-3).
|
|
461
|
+
*
|
|
462
|
+
* Protokol apply → marker → save menyisakan satu jendela: marker durable,
|
|
463
|
+
* pointer-disk basi. Crash di sana membuat resume melihat pointer yang
|
|
464
|
+
* menunjuk TERLALU TUA sementara file sudah di-apply. Fungsi ini menutupnya
|
|
465
|
+
* secara deterministik: marker undo/redo TERBARU yang valid (indeks dalam
|
|
466
|
+
* batas + turn cocok dengan checkpoint pada indeks itu) diadopsi sebagai
|
|
467
|
+
* pointer — metadata-only, tanpa menyentuh file (file sudah benar).
|
|
468
|
+
*
|
|
469
|
+
* Tanpa marker / marker cocok pointer / marker invalid → null (no-op).
|
|
470
|
+
* Idempoten: pemanggilan ulang menghasilkan null setelah adopsi pertama.
|
|
471
|
+
*/
|
|
472
|
+
export async function reconcileUndoRedoPointer(
|
|
473
|
+
sessionId: string,
|
|
474
|
+
cwd: string = process.cwd(),
|
|
475
|
+
): Promise<{
|
|
476
|
+
repaired: boolean
|
|
477
|
+
from: number
|
|
478
|
+
to: number
|
|
479
|
+
kind: "undo" | "redo"
|
|
480
|
+
files: number
|
|
481
|
+
} | null> {
|
|
482
|
+
const manifestPath = getManifestPath(sessionId, cwd)
|
|
483
|
+
return withCheckpointLock(manifestPath, async () => {
|
|
484
|
+
const manifest = await loadCheckpointManifest(sessionId, cwd)
|
|
485
|
+
if (manifest.checkpoints.length === 0) return null
|
|
486
|
+
let markers: {
|
|
487
|
+
kind: "undo" | "redo"
|
|
488
|
+
targetTurn?: number
|
|
489
|
+
newIndex?: number
|
|
490
|
+
files?: number
|
|
491
|
+
seq: number
|
|
492
|
+
}[]
|
|
493
|
+
try {
|
|
494
|
+
const loaded = await loadJournal(sessionId, cwd)
|
|
495
|
+
markers = loaded.records
|
|
496
|
+
.filter((r) => (r.kind === "undo" || r.kind === "redo") && typeof r.seq === "number")
|
|
497
|
+
.map((r) => ({
|
|
498
|
+
kind: r.kind as "undo" | "redo",
|
|
499
|
+
targetTurn: r.targetTurn,
|
|
500
|
+
newIndex: r.newIndex,
|
|
501
|
+
files: r.files,
|
|
502
|
+
seq: r.seq as number,
|
|
503
|
+
}))
|
|
504
|
+
} catch {
|
|
505
|
+
return null
|
|
506
|
+
}
|
|
507
|
+
if (markers.length === 0) return null
|
|
508
|
+
const latest = markers.sort((a, b) => a.seq - b.seq)[markers.length - 1]!
|
|
509
|
+
if (latest.newIndex === undefined) return null // marker lama tanpa pointer
|
|
510
|
+
if (latest.newIndex === manifest.currentIndex) return null // konvergen
|
|
511
|
+
if (latest.newIndex < -1 || latest.newIndex > manifest.checkpoints.length - 1) {
|
|
512
|
+
process.stderr.write(
|
|
513
|
+
`[warn] checkpoint: undo/redo marker menunjuk indeks invalid (${latest.newIndex}) — diabaikan, pointer dipertahankan\n`,
|
|
514
|
+
)
|
|
515
|
+
return null
|
|
516
|
+
}
|
|
517
|
+
// Turn harus cocok: marker untuk susunan checkpoints yang berbeda
|
|
518
|
+
// (eviksi/cabang lain) tak boleh diadopsi buta. newIndex -1 = "mundur
|
|
519
|
+
// sebelum checkpoint pertama": cocokkan dengan checkpoint pertama
|
|
520
|
+
// (tanpa ini marker basi turn-asing selalu diadopsi — audit #08 §15).
|
|
521
|
+
const pointed =
|
|
522
|
+
latest.newIndex === -1 ? manifest.checkpoints[0] : manifest.checkpoints[latest.newIndex]
|
|
523
|
+
if (latest.targetTurn !== undefined && pointed && pointed.turn !== latest.targetTurn) {
|
|
524
|
+
process.stderr.write(
|
|
525
|
+
`[warn] checkpoint: undo/redo marker turn ${latest.targetTurn} tak cocok checkpoint idx ${latest.newIndex} (turn ${pointed.turn}) — diabaikan\n`,
|
|
526
|
+
)
|
|
527
|
+
return null
|
|
528
|
+
}
|
|
529
|
+
const from = manifest.currentIndex
|
|
530
|
+
manifest.currentIndex = latest.newIndex
|
|
531
|
+
await saveCheckpointManifest(manifest, cwd)
|
|
532
|
+
process.stderr.write(
|
|
533
|
+
`[recovery] checkpoint pointer dipulihkan ${from} → ${latest.newIndex} (${latest.kind} turn ${latest.targetTurn ?? "?"}, ${latest.files ?? 0} file)\n`,
|
|
534
|
+
)
|
|
535
|
+
return {
|
|
536
|
+
repaired: true,
|
|
537
|
+
from,
|
|
538
|
+
to: latest.newIndex,
|
|
539
|
+
kind: latest.kind,
|
|
540
|
+
files: latest.files ?? 0,
|
|
541
|
+
}
|
|
542
|
+
})
|
|
543
|
+
}
|