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.
Files changed (162) hide show
  1. package/CHANGELOG.md +935 -0
  2. package/LICENSE +21 -0
  3. package/README.md +200 -0
  4. package/cli/args.ts +195 -0
  5. package/cli/auto-update.ts +108 -0
  6. package/cli/commands/auth.ts +166 -0
  7. package/cli/commands/config.ts +382 -0
  8. package/cli/commands/doctor.ts +128 -0
  9. package/cli/commands/exec.ts +179 -0
  10. package/cli/commands/mcp.ts +35 -0
  11. package/cli/commands/memory.ts +107 -0
  12. package/cli/commands/pricing.ts +100 -0
  13. package/cli/commands/providers.ts +162 -0
  14. package/cli/commands/sessions.ts +128 -0
  15. package/cli/commands/skills.ts +61 -0
  16. package/cli/commands/stats.ts +82 -0
  17. package/cli/commands.ts +317 -0
  18. package/cli/index.ts +539 -0
  19. package/cli/model-manager.ts +112 -0
  20. package/cli/provider-manager.ts +111 -0
  21. package/cli/repl.ts +734 -0
  22. package/cli/router.ts +124 -0
  23. package/cli/setup.ts +780 -0
  24. package/cli/wizard.ts +21 -0
  25. package/docs/ARCHITECTURE.html +1222 -0
  26. package/docs/README.md +109 -0
  27. package/docs/architecture.md +44 -0
  28. package/docs/changelog.md +3 -0
  29. package/package.json +91 -0
  30. package/src/agents/pool.ts +43 -0
  31. package/src/app/mentions.ts +50 -0
  32. package/src/app/provider-layer.ts +118 -0
  33. package/src/app/rag-layer.ts +105 -0
  34. package/src/app/session.ts +154 -0
  35. package/src/app/tool-layer.ts +56 -0
  36. package/src/config.ts +372 -0
  37. package/src/constants.ts +119 -0
  38. package/src/hooks/run.ts +89 -0
  39. package/src/lib/atomic-write.ts +88 -0
  40. package/src/lib/db-path.ts +36 -0
  41. package/src/lib/git-hardening.ts +91 -0
  42. package/src/lib/ignore.ts +58 -0
  43. package/src/lib/keystore.ts +202 -0
  44. package/src/lib/net.ts +70 -0
  45. package/src/lib/safe-open.ts +138 -0
  46. package/src/lib/session-id.ts +23 -0
  47. package/src/lib/trash.ts +38 -0
  48. package/src/lib/trusted-exec.ts +81 -0
  49. package/src/lsp/client.ts +395 -0
  50. package/src/mcp/client.ts +400 -0
  51. package/src/mcp/http-transport.ts +344 -0
  52. package/src/mcp/server.ts +538 -0
  53. package/src/mcp/transport.ts +150 -0
  54. package/src/memory/files.ts +159 -0
  55. package/src/memory/vector.ts +775 -0
  56. package/src/policy/allowlist.ts +67 -0
  57. package/src/policy/bash-guard.ts +465 -0
  58. package/src/policy/compaction.ts +271 -0
  59. package/src/policy/context.ts +161 -0
  60. package/src/policy/executor.ts +199 -0
  61. package/src/policy/jail.ts +127 -0
  62. package/src/policy/permission.ts +517 -0
  63. package/src/policy/pricing.ts +336 -0
  64. package/src/policy/ratelimit.ts +54 -0
  65. package/src/policy/sandbox-policy.ts +157 -0
  66. package/src/policy/scrub.ts +138 -0
  67. package/src/policy/update-check.ts +200 -0
  68. package/src/policy/usage.ts +292 -0
  69. package/src/policy/verifier.ts +181 -0
  70. package/src/providers/anthropic.ts +401 -0
  71. package/src/providers/auth-store.ts +139 -0
  72. package/src/providers/build.ts +136 -0
  73. package/src/providers/detect.ts +126 -0
  74. package/src/providers/effort.ts +165 -0
  75. package/src/providers/guards.ts +107 -0
  76. package/src/providers/oauth.ts +326 -0
  77. package/src/providers/presets.ts +122 -0
  78. package/src/providers/provision.ts +298 -0
  79. package/src/providers/responses.ts +371 -0
  80. package/src/providers/router.ts +247 -0
  81. package/src/repo/repomap.ts +470 -0
  82. package/src/sandbox/docker.ts +129 -0
  83. package/src/sandbox/os.ts +193 -0
  84. package/src/session/checkpoint.ts +543 -0
  85. package/src/session/journal.ts +1347 -0
  86. package/src/session/persistence.ts +446 -0
  87. package/src/session/shadow-git.ts +351 -0
  88. package/src/session/turn-marker.ts +118 -0
  89. package/src/skills/loader.ts +117 -0
  90. package/src/telemetry/trace.ts +283 -0
  91. package/src/tools/ask_user.ts +54 -0
  92. package/src/tools/bash.ts +400 -0
  93. package/src/tools/code_run.ts +96 -0
  94. package/src/tools/delete_file.ts +31 -0
  95. package/src/tools/edit.ts +204 -0
  96. package/src/tools/git.ts +301 -0
  97. package/src/tools/glob.ts +90 -0
  98. package/src/tools/grep.ts +281 -0
  99. package/src/tools/hashline.ts +66 -0
  100. package/src/tools/index.ts +103 -0
  101. package/src/tools/lsp.ts +346 -0
  102. package/src/tools/mcp_call.ts +163 -0
  103. package/src/tools/memory.ts +144 -0
  104. package/src/tools/move_file.ts +47 -0
  105. package/src/tools/patch.ts +86 -0
  106. package/src/tools/read_file.ts +130 -0
  107. package/src/tools/read_image.ts +80 -0
  108. package/src/tools/submit_result.ts +49 -0
  109. package/src/tools/task.ts +346 -0
  110. package/src/tools/todo.ts +201 -0
  111. package/src/tools/web_fetch.ts +161 -0
  112. package/src/tools/web_search.ts +156 -0
  113. package/src/tools/write_file.ts +42 -0
  114. package/src/ui/approval/prompt.ts +76 -0
  115. package/src/ui/assistant/simple.ts +568 -0
  116. package/src/ui/assistant/turn-status.ts +303 -0
  117. package/src/ui/contract.ts +55 -0
  118. package/src/ui/footer.ts +105 -0
  119. package/src/ui/input/input.ts +805 -0
  120. package/src/ui/input/prompt-engine.ts +606 -0
  121. package/src/ui/render/collapse.ts +84 -0
  122. package/src/ui/render/detail.ts +24 -0
  123. package/src/ui/render/diff.ts +181 -0
  124. package/src/ui/render/errors.ts +239 -0
  125. package/src/ui/render/format.ts +54 -0
  126. package/src/ui/render/highlight.ts +294 -0
  127. package/src/ui/render/markdown.ts +120 -0
  128. package/src/ui/render/money.ts +12 -0
  129. package/src/ui/render/reasoning.ts +20 -0
  130. package/src/ui/render/sanitize.ts +80 -0
  131. package/src/ui/render/table.ts +88 -0
  132. package/src/ui/render/theme.ts +339 -0
  133. package/src/ui/render/width.ts +256 -0
  134. package/src/ui/render/wrap.ts +120 -0
  135. package/src/ui/runtime/bus-debug.ts +83 -0
  136. package/src/ui/runtime/chrome.ts +301 -0
  137. package/src/ui/runtime/spinner.ts +77 -0
  138. package/src/ui/runtime/statusline.ts +227 -0
  139. package/src/ui/screens/model-manager.ts +434 -0
  140. package/src/ui/screens/overlay.ts +61 -0
  141. package/src/ui/screens/picker.ts +307 -0
  142. package/src/ui/screens/provider-manager.ts +450 -0
  143. package/src/ui/screens/wizard.ts +132 -0
  144. package/vendor/minicore/VENDOR.md +29 -0
  145. package/vendor/minicore/package.json +21 -0
  146. package/vendor/minicore/src/core/budget.ts +26 -0
  147. package/vendor/minicore/src/core/compact.ts +76 -0
  148. package/vendor/minicore/src/core/errors.ts +60 -0
  149. package/vendor/minicore/src/core/events.ts +74 -0
  150. package/vendor/minicore/src/core/executor.ts +139 -0
  151. package/vendor/minicore/src/core/history.ts +32 -0
  152. package/vendor/minicore/src/core/index.ts +42 -0
  153. package/vendor/minicore/src/core/loop.ts +344 -0
  154. package/vendor/minicore/src/core/permission.ts +24 -0
  155. package/vendor/minicore/src/core/provider.ts +39 -0
  156. package/vendor/minicore/src/core/recovery.ts +34 -0
  157. package/vendor/minicore/src/core/session.ts +327 -0
  158. package/vendor/minicore/src/core/snapshot.ts +142 -0
  159. package/vendor/minicore/src/core/tokens.ts +111 -0
  160. package/vendor/minicore/src/core/tool.ts +118 -0
  161. package/vendor/minicore/src/core/types.ts +50 -0
  162. package/vendor/minicore/src/providers/openai-compat.ts +366 -0
@@ -0,0 +1,446 @@
1
+ import { Database } from "bun:sqlite"
2
+ import { LIMITS } from "../constants.ts"
3
+ import { resolveDbPath } from "../lib/db-path.ts"
4
+
5
+ const dbPath = (cwd?: string) => resolveDbPath("sessions.db", cwd)
6
+
7
+ const initializedSessionPaths = new Set<string>()
8
+
9
+ function open(cwd?: string): Database {
10
+ const p = dbPath(cwd)
11
+ const db = new Database(p)
12
+ // busy_timeout DULU, sebelum statement apa pun yang butuh lock (audit #09
13
+ // P1 §27: dua proses membuka DB bersamaan → PRAGMA journal_mode balapan →
14
+ // SQLITE_BUSY padahal timeout 3000ms belum aktif — reproducer: 2×
15
+ // loadSession konkuren lintas proses, satu gagal). Set pragma tak butuh
16
+ // lock data sehingga aman duluan.
17
+ try {
18
+ db.exec(`PRAGMA busy_timeout=${LIMITS.SQLITE_BUSY_TIMEOUT_MS}`)
19
+ } catch {}
20
+ if (!initializedSessionPaths.has(p)) {
21
+ // journal_size_limit + wal_autocheckpoint: WAL tidak tumbuh tak terbatas.
22
+ // Bungkus try/catch DENGAN retry-next-open (audit 2026-09-16): di Windows,
23
+ // lock AV/file sesaat saat dua proses membuka bersamaan membuat setup WAL
24
+ // gagal SQLITE_IOERR_TRUNCATE — crash di sini mematikan SELURUH operasi
25
+ // sesi padahal mode rollback-journal tetap bisa baca. Jangan tandai
26
+ // initialized bila gagal agar open berikutnya mencoba lagi (mode WAL
27
+ // persisten di berkas DB, jadi sekali sukses berlaku untuk semua handle).
28
+ try {
29
+ db.exec(
30
+ `PRAGMA journal_mode=WAL; PRAGMA busy_timeout=${LIMITS.SQLITE_BUSY_TIMEOUT_MS}; PRAGMA synchronous=NORMAL; PRAGMA journal_size_limit=${LIMITS.SQLITE_WAL_SIZE_LIMIT_BYTES}; PRAGMA wal_autocheckpoint=${LIMITS.SQLITE_WAL_AUTOCHECKPOINT_PAGES};`,
31
+ )
32
+ initializedSessionPaths.add(p)
33
+ } catch (e) {
34
+ process.stderr.write(
35
+ `[warn] persistence: wal setup deferred, retry next open: ${(e as Error).message}\n`,
36
+ )
37
+ }
38
+ // File DB dibuat dengan 644 default; ubah ke 600 agar history tidak world-readable
39
+ try {
40
+ const { chmodSync } = require("node:fs") as typeof import("node:fs")
41
+ chmodSync(p, 0o600)
42
+ // WAL/SHM akan dibuat dengan mode yang sama pada checkpoint berikutnya
43
+ } catch {}
44
+ }
45
+ db.exec(`
46
+ CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, created_at INTEGER, cwd TEXT, system TEXT);
47
+ CREATE TABLE IF NOT EXISTS messages (session_id TEXT, seq INTEGER, role TEXT, content TEXT, toolCalls TEXT, toolCallId TEXT, name TEXT, ts INTEGER, PRIMARY KEY(session_id, seq));
48
+ CREATE TABLE IF NOT EXISTS turns (session_id TEXT, turn_idx INTEGER, usage TEXT, ts INTEGER, PRIMARY KEY(session_id, turn_idx));
49
+ CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_id, seq);
50
+ `)
51
+ // migration: add updated_at, toolCallId, name jika kolom lama (backward-compat)
52
+ try {
53
+ const cols = db.prepare("PRAGMA table_info(sessions)").all() as { name: string }[]
54
+ if (!cols.some((c) => c.name === "updated_at")) {
55
+ db.exec("ALTER TABLE sessions ADD COLUMN updated_at INTEGER")
56
+ db.exec("UPDATE sessions SET updated_at = created_at WHERE updated_at IS NULL")
57
+ }
58
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_sessions_updated ON sessions(updated_at DESC)`)
59
+ } catch (e) {
60
+ process.stderr.write(
61
+ `[warn] persistence: sessions migration skipped: ${(e as Error).message}\n`,
62
+ )
63
+ }
64
+ try {
65
+ const msgCols = db.prepare("PRAGMA table_info(messages)").all() as { name: string }[]
66
+ if (!msgCols.some((c) => c.name === "toolCallId")) {
67
+ db.exec("ALTER TABLE messages ADD COLUMN toolCallId TEXT")
68
+ db.exec("ALTER TABLE messages ADD COLUMN name TEXT")
69
+ }
70
+ } catch (e) {
71
+ process.stderr.write(
72
+ `[warn] persistence: messages migration skipped: ${(e as Error).message}\n`,
73
+ )
74
+ }
75
+ return db
76
+ }
77
+
78
+ // JSON-safe serialization: konten binary (Uint8Array) jangan di-stringify jadi
79
+ // array ribuan angka — cukup placeholder agar DB tidak menggembung.
80
+ function safeContent(value: unknown): string {
81
+ if (value instanceof Uint8Array) return `[binary: ${value.length} bytes]`
82
+ if (Array.isArray(value)) {
83
+ for (const p of value) {
84
+ if (p instanceof Uint8Array) return `[binary: ${value.length} parts]`
85
+ if (p && typeof p === "object" && (p as { data?: unknown }).data instanceof Uint8Array) {
86
+ return `[binary: ${value.length} parts (image)]`
87
+ }
88
+ }
89
+ }
90
+ try {
91
+ return JSON.stringify(value)
92
+ } catch {
93
+ return String(value)
94
+ }
95
+ }
96
+
97
+ // SQLITE_BUSY / database-is-locked bisa muncul saat Pool(3) sub-agent menulis
98
+ // bersamaan meski WAL+busy_timeout aktif (terutama Windows). Retry singkat
99
+ // P0.2: async + Bun.sleep agar tidak block event-loop (sebelumnya Atomics.wait freeze 175ms).
100
+ async function withBusyRetry<T>(fn: () => T, attempts = 3): Promise<T> {
101
+ let last: unknown
102
+ for (let i = 0; i < attempts; i++) {
103
+ try {
104
+ return fn()
105
+ } catch (e) {
106
+ const msg = String((e as Error).message ?? e)
107
+ if (!msg.includes("SQLITE_BUSY") && !msg.includes("database is locked")) throw e
108
+ last = e
109
+ await Bun.sleep(25 * 2 ** i)
110
+ }
111
+ }
112
+ throw last
113
+ }
114
+
115
+ export async function saveSession(
116
+ id: string,
117
+ cwd: string | undefined,
118
+ system: string | undefined,
119
+ messages: readonly unknown[],
120
+ usage: unknown,
121
+ ) {
122
+ const db = open(cwd)
123
+ const now = Date.now()
124
+ const txn = db.transaction(() => {
125
+ const existing = db
126
+ .prepare("SELECT created_at, updated_at FROM sessions WHERE id = ?")
127
+ .get(id) as { created_at: number; updated_at: number | null } | null
128
+ const createdAt = existing?.created_at ?? now
129
+ db.prepare(
130
+ "INSERT OR REPLACE INTO sessions (id, created_at, updated_at, cwd, system) VALUES (?, ?, ?, ?, ?)",
131
+ ).run(id, createdAt, now, cwd ?? "", system ?? "")
132
+ const ins = db.prepare(
133
+ "INSERT INTO messages (session_id, seq, role, content, toolCalls, toolCallId, name, ts) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
134
+ )
135
+ type StoredMsg = {
136
+ role: string
137
+ content: unknown
138
+ toolCalls?: unknown
139
+ toolCallId?: string
140
+ name?: string
141
+ }
142
+ const norm = (m: StoredMsg): [string, string, string, string | null, string | null] => [
143
+ m.role,
144
+ safeContent(m.content),
145
+ safeContent(m.toolCalls ?? null),
146
+ (m.toolCallId ?? null) as string | null,
147
+ (m.name ?? null) as string | null,
148
+ ]
149
+ // F-05: JANGAN pakai messages.length sebagai proksi perubahan. Kompaksi
150
+ // (atau replace apa pun) bisa mengganti N pesan dengan N pesan BERBEDA —
151
+ // panjang sama, isi beda. Tanpa verifikasi prefix, tulis dilewat dan
152
+ // resume memuat sejarah basi. Bandingkan prefix tersimpan dengan incoming:
153
+ // sama persis = re-save (bukan turn baru, jaga guard anti turn-hantu);
154
+ // prefix sama + tumbuh = append; selain itu = rewrite penuh.
155
+ const stored = db
156
+ .prepare(
157
+ "SELECT seq, role, content, toolCalls, toolCallId, name FROM messages WHERE session_id = ? ORDER BY seq",
158
+ )
159
+ .all(id) as {
160
+ seq: number
161
+ role: string
162
+ content: string
163
+ toolCalls: string
164
+ toolCallId: string | null
165
+ name: string | null
166
+ }[]
167
+ const known = stored.length
168
+ let prefixSame = stored.length <= messages.length
169
+ if (prefixSame) {
170
+ for (let i = 0; i < stored.length; i++) {
171
+ const want = norm(messages[i] as StoredMsg)
172
+ const got = stored[i]!
173
+ if (
174
+ got.seq !== i ||
175
+ got.role !== want[0] ||
176
+ got.content !== want[1] ||
177
+ got.toolCalls !== want[2] ||
178
+ (got.toolCallId ?? null) !== want[3] ||
179
+ (got.name ?? null) !== want[4]
180
+ ) {
181
+ prefixSame = false
182
+ break
183
+ }
184
+ }
185
+ }
186
+ const changed = !prefixSame || stored.length !== messages.length
187
+ if (changed && prefixSame) {
188
+ // incremental append-only: cukup insert pesan baru (umumnya 1 turn)
189
+ for (let i = known; i < messages.length; i++) {
190
+ const m = messages[i] as StoredMsg
191
+ const w = norm(m)
192
+ ins.run(id, i, w[0], w[1], w[2], w[3], w[4], now)
193
+ }
194
+ } else if (changed) {
195
+ // history menyusut (compaction/reset) ATAU prefix berubah dengan panjang
196
+ // sama (kompaksi N→N) → tulis ulang penuh agar tidak ada pesan basi
197
+ // yang tertinggal untuk resume
198
+ db.prepare("DELETE FROM messages WHERE session_id = ?").run(id)
199
+ for (let i = 0; i < messages.length; i++) {
200
+ const m = messages[i] as StoredMsg
201
+ const w = norm(m)
202
+ ins.run(id, i, w[0], w[1], w[2], w[3], w[4], now)
203
+ }
204
+ }
205
+ if (usage) {
206
+ // Audit #08 P1 (§16): baris turns = turn SELESAI, bukan panggilan save.
207
+ // Menyimpan ulang riwayat yang sama (retry/crash antara save dan
208
+ // finalize) sebelumnya menambah turn_idx hantu — suppressor stitch
209
+ // palsu di decideRecovery (turn yang tak pernah durable dikira ada).
210
+ // Aturan: tumbuh (pesan baru), susut, atau isi berubah (rewrite
211
+ // pasca-kompaksi) = turn terjadi; sama persis = re-save, bukan turn baru.
212
+ if (changed) {
213
+ const maxRow = db
214
+ .prepare("SELECT MAX(turn_idx) as m FROM turns WHERE session_id = ?")
215
+ .get(id) as { m: number | null } | null
216
+ const nextIdx = (maxRow?.m ?? -1) + 1
217
+ db.prepare("INSERT INTO turns (session_id, turn_idx, usage, ts) VALUES (?, ?, ?, ?)").run(
218
+ id,
219
+ nextIdx,
220
+ JSON.stringify(usage),
221
+ now,
222
+ )
223
+ }
224
+ }
225
+ // TTL: hapus sesi basi + orphan rows (best-effort; 0 = forever)
226
+ try {
227
+ purgeExpired(db, now)
228
+ } catch (e) {
229
+ process.stderr.write(`[warn] persistence: TTL purge failed: ${(e as Error).message}\n`)
230
+ }
231
+ })
232
+ try {
233
+ await withBusyRetry(() => txn())
234
+ } finally {
235
+ db.close()
236
+ }
237
+ }
238
+
239
+ // TTL default 30 hari; MINICODE_SESSION_TTL_DAYS=0 = simpan selamanya.
240
+ export function getSessionTtlDays(): number {
241
+ const raw = process.env.MINICODE_SESSION_TTL_DAYS
242
+ if (raw == null || raw === "") return 30
243
+ const n = Number(raw)
244
+ return Number.isFinite(n) && n >= 0 ? n : 30
245
+ }
246
+
247
+ export function purgeExpired(db: Database, now = Date.now()): number {
248
+ const days = getSessionTtlDays()
249
+ if (days <= 0) return 0
250
+ const ttlMs = days * 24 * 60 * 60 * 1000
251
+ const cutoff = now - ttlMs
252
+ const gone = db
253
+ .prepare("DELETE FROM sessions WHERE COALESCE(updated_at, created_at) < ?")
254
+ .run(cutoff)
255
+ db.prepare("DELETE FROM messages WHERE session_id NOT IN (SELECT id FROM sessions)").run()
256
+ db.prepare("DELETE FROM turns WHERE session_id NOT IN (SELECT id FROM sessions)").run()
257
+ return gone.changes
258
+ }
259
+
260
+ function parseContent(s: string): unknown {
261
+ try {
262
+ return JSON.parse(s)
263
+ } catch {
264
+ return s // placeholder "[binary: N bytes]" atau data yang bukan JSON
265
+ }
266
+ }
267
+
268
+ export function loadSession(
269
+ id: string,
270
+ cwd?: string,
271
+ ): { messages: unknown[]; system?: string; cwd?: string; turnCount?: number } | null {
272
+ const db = open(cwd)
273
+ try {
274
+ const sess = db.prepare("SELECT * FROM sessions WHERE id = ?").get(id) as {
275
+ system: string
276
+ cwd: string
277
+ } | null
278
+ if (!sess) {
279
+ return null
280
+ }
281
+ const rows = db.prepare("SELECT * FROM messages WHERE session_id = ? ORDER BY seq").all(id) as {
282
+ role: string
283
+ content: string
284
+ toolCalls: string
285
+ toolCallId: string | null
286
+ name: string | null
287
+ }[]
288
+ const messages = rows.map((r) => ({
289
+ role: r.role,
290
+ content: parseContent(r.content),
291
+ ...(r.toolCalls && r.toolCalls !== "null" ? { toolCalls: parseContent(r.toolCalls) } : {}),
292
+ ...(r.toolCallId ? { toolCallId: r.toolCallId } : {}),
293
+ ...(r.name ? { name: r.name } : {}),
294
+ }))
295
+ const turnRow = db
296
+ .prepare("SELECT MAX(turn_idx) as m FROM turns WHERE session_id = ?")
297
+ .get(id) as { m: number | null } | null
298
+ const turnCount = turnRow?.m != null ? turnRow.m + 1 : 0
299
+ return { messages, system: sess.system, cwd: sess.cwd, turnCount }
300
+ } finally {
301
+ db.close()
302
+ }
303
+ }
304
+
305
+ export function listPersistedTurns(id: string, cwd?: string): number[] {
306
+ // Turn durable untuk keputusan recovery journal (baca-saja, tanpa schema).
307
+ const db = open(cwd)
308
+ try {
309
+ const rows = db
310
+ .prepare("SELECT turn_idx as t FROM turns WHERE session_id = ? ORDER BY turn_idx")
311
+ .all(id) as { t: number }[]
312
+ return rows.map((r) => r.t)
313
+ } finally {
314
+ db.close()
315
+ }
316
+ }
317
+
318
+ export function listSessions(
319
+ cwd?: string,
320
+ ): { id: string; created_at: number; updated_at?: number; cwd: string }[] {
321
+ const db = open(cwd)
322
+ try {
323
+ const rows = db
324
+ .prepare(
325
+ "SELECT id, created_at, updated_at, cwd FROM sessions ORDER BY COALESCE(updated_at, created_at) DESC LIMIT 50",
326
+ )
327
+ .all() as { id: string; created_at: number; updated_at: number | null; cwd: string }[]
328
+ return rows.map((r) => ({ ...r, updated_at: r.updated_at ?? r.created_at }))
329
+ } finally {
330
+ db.close()
331
+ }
332
+ }
333
+
334
+ export async function deleteSession(id: string, cwd?: string) {
335
+ const db = open(cwd)
336
+ const txn = db.transaction(() => {
337
+ db.prepare("DELETE FROM messages WHERE session_id = ?").run(id)
338
+ db.prepare("DELETE FROM turns WHERE session_id = ?").run(id)
339
+ db.prepare("DELETE FROM sessions WHERE id = ?").run(id)
340
+ })
341
+ try {
342
+ await withBusyRetry(() => txn())
343
+ } finally {
344
+ db.close()
345
+ }
346
+ // Lifecycle: jurnal ikut hapus sesi (best-effort; tak boleh gagalkan hapus).
347
+ try {
348
+ const { deleteJournalFile } = await import("./journal.ts")
349
+ deleteJournalFile(id, cwd)
350
+ } catch {}
351
+ // P0-3 #10: manifes checkpoint ikut hapus sesi — sesi yang dihapus lalu
352
+ // dibuat ulang dengan id sama tak boleh mewarisi pointer basi. Best-effort.
353
+ try {
354
+ const { sanitizeSessionId } = await import("./checkpoint.ts")
355
+ const { rm } = await import("node:fs/promises")
356
+ const { resolve: resolvePath, join: joinPath } = await import("node:path")
357
+ await rm(
358
+ joinPath(
359
+ resolvePath(cwd ?? process.cwd()),
360
+ ".minicode",
361
+ "checkpoints",
362
+ sanitizeSessionId(id),
363
+ ),
364
+ {
365
+ recursive: true,
366
+ force: true,
367
+ },
368
+ ).catch(() => {})
369
+ } catch {}
370
+ // Audit #10 §17: ref shadow-git (`refs/minicode/<sesi>/*`) menunjuk tree
371
+ // berisi ISI file saat snapshot — tanpa prune, konten sesi yang dihapus
372
+ // tetap reachable via `git cat-file`. pruneSessionRefs sudah ada & teruji,
373
+ // tetapi tak pernah dipanggil dari sini (jalur cleanup mati). Best-effort.
374
+ try {
375
+ const { pruneSessionRefs } = await import("./shadow-git.ts")
376
+ await pruneSessionRefs(cwd ?? process.cwd(), id).catch(() => {})
377
+ } catch {}
378
+ // Audit #10 §17: traces.jsonl/step-traces.jsonl adalah berkas bersama
379
+ // per-workspace — baris sesi yang dihapus bertahan sebagai residual
380
+ // (prompt/args/error mentah masih terbaca pasca-delete). Purge baris milik
381
+ // sesi ini saja; sesi lain tak tersentuh. Best-effort.
382
+ try {
383
+ const { purgeSessionTraces } = await import("../telemetry/trace.ts")
384
+ await purgeSessionTraces(id, cwd).catch(() => {})
385
+ } catch {}
386
+ // Audit #13 chain 28: daftar todo + snapshot rencana adalah state milik
387
+ // sesi — tanpa purge, isi rencana (bisa memuat secret/path kerja) bertahan
388
+ // sebagai residual reachable pasca-delete. Best-effort.
389
+ try {
390
+ const { deleteTodoFiles } = await import("../tools/todo.ts")
391
+ await deleteTodoFiles(id, cwd ?? process.cwd()).catch(() => {})
392
+ } catch {}
393
+ }
394
+
395
+ // P13 P1 — branch: fork sesi (history + turns) ke id baru tanpa menyentuh
396
+ // sumber. Butuh untuk "coba dua arah dari titik yang sama" — tanpa ini user
397
+ // harus mengulang seluruh percakapan untuk eksplorasi alternatif.
398
+ export async function branchSession(srcId: string, dstId: string, cwd?: string): Promise<number> {
399
+ if (!dstId || !/^[\w.-]{1,64}$/.test(dstId)) throw new Error("invalid branch session id")
400
+ const db = open(cwd)
401
+ const now = Date.now()
402
+ let copied = 0
403
+ const txn = db.transaction(() => {
404
+ const src = db.prepare("SELECT cwd, system FROM sessions WHERE id = ?").get(srcId) as {
405
+ cwd: string
406
+ system: string
407
+ } | null
408
+ if (!src) throw new Error(`session not found: ${srcId}`)
409
+ db.prepare(
410
+ "INSERT OR REPLACE INTO sessions (id, created_at, updated_at, cwd, system) VALUES (?, ?, ?, ?, ?)",
411
+ ).run(dstId, now, now, src.cwd, src.system)
412
+ const rows = db
413
+ .prepare(
414
+ "SELECT seq, role, content, toolCalls, toolCallId, name, ts FROM messages WHERE session_id = ? ORDER BY seq",
415
+ )
416
+ .all(srcId) as {
417
+ seq: number
418
+ role: string
419
+ content: string
420
+ toolCalls: string
421
+ toolCallId: string | null
422
+ name: string | null
423
+ ts: number
424
+ }[]
425
+ const ins = db.prepare(
426
+ "INSERT INTO messages (session_id, seq, role, content, toolCalls, toolCallId, name, ts) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
427
+ )
428
+ for (const r of rows) {
429
+ ins.run(dstId, r.seq, r.role, r.content, r.toolCalls, r.toolCallId, r.name, r.ts)
430
+ }
431
+ copied = rows.length
432
+ const turns = db
433
+ .prepare("SELECT turn_idx, usage, ts FROM turns WHERE session_id = ? ORDER BY turn_idx")
434
+ .all(srcId) as { turn_idx: number; usage: string; ts: number }[]
435
+ const insT = db.prepare(
436
+ "INSERT INTO turns (session_id, turn_idx, usage, ts) VALUES (?, ?, ?, ?)",
437
+ )
438
+ for (const t of turns) insT.run(dstId, t.turn_idx, t.usage, t.ts)
439
+ })
440
+ try {
441
+ await withBusyRetry(() => txn())
442
+ } finally {
443
+ db.close()
444
+ }
445
+ return copied
446
+ }