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,1347 @@
|
|
|
1
|
+
// Mutation intent journal — application-layer commitment truth.
|
|
2
|
+
//
|
|
3
|
+
// Masalah yang ditutup (AUDIT #01 P0-1/P0-2): filesystem dapat berubah
|
|
4
|
+
// sebelum turn commit/persist, sementara SQLite dan checkpoint ditulis dua
|
|
5
|
+
// penulis tak tersinkron. Setelah crash, tak ada artefak yang tahu apakah
|
|
6
|
+
// mutasi terakhir committed, belum, atau ambigu.
|
|
7
|
+
//
|
|
8
|
+
// Modul ini menjawab SATU pertanyaan: "status komitmen mutasi X?"
|
|
9
|
+
// - intent = execution:started (terbit SETELAH permission+validate, SEBELUM
|
|
10
|
+
// execute — titik D audit #01C; denied/invalid tak pernah tercatat).
|
|
11
|
+
// - terminal = execution:completed (!isError → committed, isError → failed).
|
|
12
|
+
// - finalize = turn durable di SQLite (hanya ini yang boleh di-cleanup).
|
|
13
|
+
//
|
|
14
|
+
// BUKAN transaksi lintas FS+DB (tak tersedia). BUKAN checkpoint (tak restore
|
|
15
|
+
// file). BUKAN penentu redo (tak pernah auto-redo; resume = verify-first).
|
|
16
|
+
// Kernel vendor tak tersentuh: semua lewat langganan event + API eksplisit.
|
|
17
|
+
//
|
|
18
|
+
// Model kegagalan tulis: kegagalan append/fsync TAK PERNAH menggagalkan turn
|
|
19
|
+
// (fail-open eksekusi) tetapi menandai sesi degraded + warn keras — resume
|
|
20
|
+
// lalu memperlakukan sesi itu via jalur advisory. Paling aman yang tersedia:
|
|
21
|
+
// menghentikan turn karena log gagal akan merusak lebih banyak daripada gap.
|
|
22
|
+
|
|
23
|
+
import { createHash } from "node:crypto"
|
|
24
|
+
import { mkdir, open, readFile } from "node:fs/promises"
|
|
25
|
+
import { dirname, isAbsolute, join, relative, resolve } from "node:path"
|
|
26
|
+
import { atomicWriteText } from "../lib/atomic-write.ts"
|
|
27
|
+
import { sanitizeSessionPart } from "../lib/session-id.ts"
|
|
28
|
+
|
|
29
|
+
export type JournalState = "pending" | "committed" | "failed"
|
|
30
|
+
|
|
31
|
+
export interface JournalRecord {
|
|
32
|
+
v: 1
|
|
33
|
+
/** Identity utama: `${session}:${seq}` (seq monotonik per jurnal). */
|
|
34
|
+
id: string
|
|
35
|
+
session: string
|
|
36
|
+
/** Rantai delegasi: id sesi parent (diisi wiring factory-site). */
|
|
37
|
+
childOf?: string
|
|
38
|
+
/** Nomor turn kernel saat intent (narrative; boleh null). */
|
|
39
|
+
turn?: number | null
|
|
40
|
+
seq: number
|
|
41
|
+
tool: string
|
|
42
|
+
/** mutation (default) | undo | redo | finalize. Marker bukan intent. */
|
|
43
|
+
kind?: "mutation" | "undo" | "redo" | "finalize"
|
|
44
|
+
/** true = klaim sukses berasal dari pihak remote (MCP), bukan komit lokal. */
|
|
45
|
+
remote?: true
|
|
46
|
+
/** Backend code_run ("docker"|"os"|...) — alat interpretasi, bukan kontrol. */
|
|
47
|
+
backend?: string
|
|
48
|
+
/** Workspace root saat record ditulis (deteksi resume-beda-cwd). */
|
|
49
|
+
cwd: string
|
|
50
|
+
/** Path relatif-workspace untuk verification (allowlist per kelas-tool). */
|
|
51
|
+
paths?: string[]
|
|
52
|
+
/** SHA-256 JSON kanonisal argumen — identitas, BUKAN replay (tanpa raw args). */
|
|
53
|
+
argsHash?: string
|
|
54
|
+
/** Tautan delegasi: id sesi anak (parent-side record). */
|
|
55
|
+
childSessionId?: string
|
|
56
|
+
/** Marker finalize: semua seq ≤ ini durable. */
|
|
57
|
+
uptoSeq?: number
|
|
58
|
+
/** Marker undo/redo: turn target manifest. */
|
|
59
|
+
targetTurn?: number
|
|
60
|
+
/**
|
|
61
|
+
* Marker undo/redo: nilai pointer manifest (currentIndex) SETELAH operasi.
|
|
62
|
+
* Ditulis SETELAH apply files, SEBELUM save manifest — crash di antaranya
|
|
63
|
+
* meninggalkan bukti durable untuk rekonsiliasi pointer (P0-3).
|
|
64
|
+
*/
|
|
65
|
+
newIndex?: number
|
|
66
|
+
/** Marker undo/redo: jumlah file yang berhasil di-apply (info, bukan janji). */
|
|
67
|
+
files?: number
|
|
68
|
+
/** Hanya untuk kind mutation. Terminal immutable (lihat consolidate). */
|
|
69
|
+
state?: JournalState
|
|
70
|
+
outcome?: { code?: number | null; note?: string }
|
|
71
|
+
/**
|
|
72
|
+
* Bukti dedup idempotency (audit #08 P0): terminal yang ditandai ini
|
|
73
|
+
* dipertahankan sweep (lihat sweepInner) agar retry id-sama pasca-restart
|
|
74
|
+
* tetap terdeteksi. Dipakai server MCP: note = `req:<id>:<argsHash>`.
|
|
75
|
+
* Tanpa ini finalize+sweep rutin menghapus bukti id dan retry berikutnya
|
|
76
|
+
* dieksekusi ulang buta — padahal client tak bisa tahu server restart.
|
|
77
|
+
*/
|
|
78
|
+
dedup?: true
|
|
79
|
+
ts: number
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// ── Klasifikasi closed-set berbasis efek aktual (AUDIT #01C §2) ──
|
|
83
|
+
//
|
|
84
|
+
// MUTATION = execute() dapat menimbulkan efek eksternal durable.
|
|
85
|
+
// "none" = terbukti tanpa efek durable (read, kontrol, full-replace
|
|
86
|
+
// idempoten seperti todo_write, memori-proses seperti submit_result).
|
|
87
|
+
// Nama bertitik (server.tool runtime MCP) = kelas mcp_call.
|
|
88
|
+
const MUTATION_TOOLS: ReadonlySet<string> = new Set([
|
|
89
|
+
"write_file",
|
|
90
|
+
"edit",
|
|
91
|
+
"apply_patch",
|
|
92
|
+
"move_file",
|
|
93
|
+
"delete_file",
|
|
94
|
+
"bash",
|
|
95
|
+
"git_commit",
|
|
96
|
+
"mcp_call",
|
|
97
|
+
"code_run",
|
|
98
|
+
"delegate_task",
|
|
99
|
+
"write_memory",
|
|
100
|
+
"forget_memory",
|
|
101
|
+
])
|
|
102
|
+
|
|
103
|
+
const NON_MUTATION_TOOLS: ReadonlySet<string> = new Set([
|
|
104
|
+
"read_file",
|
|
105
|
+
"glob",
|
|
106
|
+
"grep",
|
|
107
|
+
"read_image",
|
|
108
|
+
"bash_output",
|
|
109
|
+
"bash_kill",
|
|
110
|
+
"git_status",
|
|
111
|
+
"git_diff",
|
|
112
|
+
"git_log",
|
|
113
|
+
"lsp_diagnostics",
|
|
114
|
+
"lsp_definition",
|
|
115
|
+
"lsp_references",
|
|
116
|
+
"lsp_hover",
|
|
117
|
+
"lsp_symbols",
|
|
118
|
+
"lsp_workspace_symbols",
|
|
119
|
+
"mcp_list",
|
|
120
|
+
"mcp_read",
|
|
121
|
+
"mcp_prompt",
|
|
122
|
+
"read_memory",
|
|
123
|
+
"todo_write",
|
|
124
|
+
"todo_read",
|
|
125
|
+
"submit_result",
|
|
126
|
+
"ask_user",
|
|
127
|
+
"web_fetch",
|
|
128
|
+
"web_search",
|
|
129
|
+
])
|
|
130
|
+
|
|
131
|
+
export function classifyTool(name: string): "mutation" | "none" | "unknown" {
|
|
132
|
+
// Tool runtime MCP (server.tool) mewarisi kelas mcp_call: efek arbitrer.
|
|
133
|
+
const base = name.includes(".") ? "mcp_call" : name
|
|
134
|
+
if (MUTATION_TOOLS.has(base)) return "mutation"
|
|
135
|
+
if (NON_MUTATION_TOOLS.has(base)) return "none"
|
|
136
|
+
return "unknown"
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function isMutationTool(name: string): boolean {
|
|
140
|
+
// F-14: unknown = mutasi (fail-closed). Tool baru yang lupa didaftarkan di
|
|
141
|
+
// MUTATION_TOOLS/NON_MUTATION_TOOLS tetap terjurnal + ter-recovery, bukan
|
|
142
|
+
// buta. Biaya salah-klasifikasi hanya baris jurnal ekstra untuk tool baca
|
|
143
|
+
// yang terlupa — jauh lebih murah daripada efek tulis yang tak tercatat.
|
|
144
|
+
// classifyTool tetap mengembalikan "unknown" (taksonomi untuk test-time
|
|
145
|
+
// guard `tool belum diklasifikasikan` di journal.test.ts).
|
|
146
|
+
return classifyTool(name) !== "none"
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// delegate_task dicatat eksplisit oleh tool-nya sendiri (butuh childSessionId
|
|
150
|
+
// yang hanya diketahui di sana) — wiring generik melewatinya agar tak ganda.
|
|
151
|
+
const NO_AUTO_JOURNAL: ReadonlySet<string> = new Set(["delegate_task"])
|
|
152
|
+
|
|
153
|
+
// ── Hash & paths (tanpa rahasia di jurnal) ──
|
|
154
|
+
|
|
155
|
+
function canonicalize(value: unknown): string {
|
|
156
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null"
|
|
157
|
+
if (Array.isArray(value)) return `[${value.map(canonicalize).join(",")}]`
|
|
158
|
+
const keys = Object.keys(value as Record<string, unknown>).sort()
|
|
159
|
+
return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalize((value as Record<string, unknown>)[k])}`).join(",")}}`
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function hashArgs(args: unknown): string {
|
|
163
|
+
return createHash("sha256")
|
|
164
|
+
.update(canonicalize(args ?? {}))
|
|
165
|
+
.digest("hex")
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Ambil path verifikasi (relatif, di dalam root) sesuai kelas tool. */
|
|
169
|
+
export function verifyPaths(tool: string, args: unknown, cwd: string): string[] {
|
|
170
|
+
const a = (args ?? {}) as Record<string, unknown>
|
|
171
|
+
const pick = (p: unknown): string | null => {
|
|
172
|
+
if (typeof p !== "string" || !p) return null
|
|
173
|
+
const rel = relative(cwd, resolve(cwd, p)).replace(/\\/g, "/")
|
|
174
|
+
if (!rel || rel.startsWith("..") || isAbsolute(rel)) return null
|
|
175
|
+
return rel
|
|
176
|
+
}
|
|
177
|
+
const many = (v: unknown): string[] =>
|
|
178
|
+
(Array.isArray(v) ? v : [])
|
|
179
|
+
.map(pick)
|
|
180
|
+
.filter((x): x is string => x !== null)
|
|
181
|
+
.slice(0, 20)
|
|
182
|
+
switch (tool) {
|
|
183
|
+
case "write_file":
|
|
184
|
+
case "edit":
|
|
185
|
+
case "apply_patch":
|
|
186
|
+
case "delete_file": {
|
|
187
|
+
const p = pick(a.path)
|
|
188
|
+
return p ? [p] : []
|
|
189
|
+
}
|
|
190
|
+
case "move_file": {
|
|
191
|
+
const out = [pick(a.from), pick(a.to)].filter((x): x is string => x !== null)
|
|
192
|
+
return out
|
|
193
|
+
}
|
|
194
|
+
case "git_commit":
|
|
195
|
+
return many(a.paths)
|
|
196
|
+
default:
|
|
197
|
+
return []
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// ── Lokasi & state penulis ──
|
|
202
|
+
|
|
203
|
+
function sanitizeId(s: string): string {
|
|
204
|
+
// F-17: delegasi ke sanitizer bersama (dulu duplikasi 3 baris dengan
|
|
205
|
+
// pemetaan sedikit berbeda dari checkpoint/shadow).
|
|
206
|
+
return sanitizeSessionPart(s)
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export function journalPath(sessionId: string, cwd?: string): string {
|
|
210
|
+
return resolve(cwd ?? process.cwd(), ".minicode", `journal-${sanitizeId(sessionId)}.jsonl`)
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export function deleteJournalFile(sessionId: string, cwd?: string): void {
|
|
214
|
+
// Lifecycle: ikut hapus sesi/TTL (best-effort, sinkron agar materai).
|
|
215
|
+
void import("node:fs").then(({ unlinkSync }) => {
|
|
216
|
+
try {
|
|
217
|
+
unlinkSync(journalPath(sessionId, cwd))
|
|
218
|
+
} catch {}
|
|
219
|
+
})
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Temukan jurnal yatim untuk purge TTL (AUDIT #01E §6): file milik sesi yang
|
|
224
|
+
* tak ada di tabel sessions DAN tak dirujuk delegasi hidup mana pun DAN
|
|
225
|
+
* lebih tua dari TTL. Unreadable dilewati (tak bisa dibuktikan yatim —
|
|
226
|
+
* menghapus yang tak terbaca adalah heuristik berbahaya).
|
|
227
|
+
*/
|
|
228
|
+
export async function findOrphanJournals(
|
|
229
|
+
journalDir: string,
|
|
230
|
+
knownSessionIds: Set<string>,
|
|
231
|
+
ttlDays: number,
|
|
232
|
+
nowMs = Date.now(),
|
|
233
|
+
): Promise<string[]> {
|
|
234
|
+
const { readdir, readFile: readF, stat } = await import("node:fs/promises")
|
|
235
|
+
let entries: string[]
|
|
236
|
+
try {
|
|
237
|
+
entries = await readdir(journalDir)
|
|
238
|
+
} catch {
|
|
239
|
+
return []
|
|
240
|
+
}
|
|
241
|
+
const files = entries.filter((f) => f.startsWith("journal-") && f.endsWith(".jsonl"))
|
|
242
|
+
// Pass 1: kumpulkan referensi anak dari semua file terbaca (parent yang
|
|
243
|
+
// masih hidup melindungi jurnal anaknya walau id anak asing bagi DB).
|
|
244
|
+
const referenced = new Set<string>()
|
|
245
|
+
const owners = new Map<string, string>() // file → owner session
|
|
246
|
+
for (const f of files) {
|
|
247
|
+
const full = join(journalDir, f)
|
|
248
|
+
let raw: string
|
|
249
|
+
try {
|
|
250
|
+
raw = await readF(full, "utf8")
|
|
251
|
+
} catch {
|
|
252
|
+
continue // unreadable → jangan sentuh (lihat kontrak di atas)
|
|
253
|
+
}
|
|
254
|
+
for (const line of raw.split("\n")) {
|
|
255
|
+
if (!line.trim()) continue
|
|
256
|
+
try {
|
|
257
|
+
const r = JSON.parse(line) as { session?: unknown; childSessionId?: unknown }
|
|
258
|
+
if (typeof r.session === "string" && !owners.has(f)) owners.set(f, r.session)
|
|
259
|
+
if (typeof r.childSessionId === "string") referenced.add(r.childSessionId)
|
|
260
|
+
} catch {
|
|
261
|
+
break // baris korup: pemilik dari record valid sebelumnya (atau tak ada)
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
if (!owners.has(f)) {
|
|
265
|
+
// File kosong/penuh-sampah-terbaca: fallback stem nama (best-effort).
|
|
266
|
+
owners.set(f, f.slice("journal-".length, -".jsonl".length))
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
// Pass 2: yatim = pemilik asing + tak dirujuk + tua.
|
|
270
|
+
const cutoff = nowMs - ttlDays * 24 * 60 * 60 * 1000
|
|
271
|
+
const orphans: string[] = []
|
|
272
|
+
for (const f of files) {
|
|
273
|
+
const owner = owners.get(f)
|
|
274
|
+
if (!owner || knownSessionIds.has(owner) || referenced.has(owner)) continue
|
|
275
|
+
try {
|
|
276
|
+
const st = await stat(join(journalDir, f))
|
|
277
|
+
if (st.mtimeMs < cutoff) orphans.push(join(journalDir, f))
|
|
278
|
+
} catch {}
|
|
279
|
+
}
|
|
280
|
+
return orphans.sort()
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
interface WriterState {
|
|
284
|
+
nextSeq: number
|
|
285
|
+
healthy: boolean
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const writers = new Map<string, WriterState>()
|
|
289
|
+
/** File yang gagal dibuat/ditulis (di luar map writers agar tak merusak seq). */
|
|
290
|
+
const degradedFiles = new Set<string>()
|
|
291
|
+
|
|
292
|
+
function writerKey(session: string, cwd: string): string {
|
|
293
|
+
return `${resolve(cwd)}::${session}`
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// ── Serialisasi per-file (§F16): alokasi seq + append harus atomik terhadap
|
|
297
|
+
// sesama penulis. Tanpa ini dua intent konkuren membaca nextSeq sama →
|
|
298
|
+
// tabrakan id → konsolidasi/keputusan runtuh. Rantai janji per file; deadlock
|
|
299
|
+
// mustahil selama callback tak memanggil API terkunci lain (dipatuhi).
|
|
300
|
+
const fileLocks = new Map<string, Promise<void>>()
|
|
301
|
+
|
|
302
|
+
async function withFileLock<T>(key: string, fn: () => Promise<T>): Promise<T> {
|
|
303
|
+
const prev = fileLocks.get(key)
|
|
304
|
+
let release!: () => void
|
|
305
|
+
const gate = new Promise<void>((res) => {
|
|
306
|
+
release = res
|
|
307
|
+
})
|
|
308
|
+
fileLocks.set(key, gate)
|
|
309
|
+
if (prev) {
|
|
310
|
+
try {
|
|
311
|
+
await prev
|
|
312
|
+
} catch {}
|
|
313
|
+
}
|
|
314
|
+
try {
|
|
315
|
+
return await fn()
|
|
316
|
+
} finally {
|
|
317
|
+
release()
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
export function isJournalHealthy(sessionId: string, cwd?: string): boolean {
|
|
322
|
+
const root = resolve(cwd ?? process.cwd())
|
|
323
|
+
if (degradedFiles.has(journalPath(sessionId, root))) return false
|
|
324
|
+
return writers.get(writerKey(sessionId, root))?.healthy ?? true
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function markDegraded(sessionId: string, cwd: string, why: string): void {
|
|
328
|
+
degradedFiles.add(journalPath(sessionId, cwd))
|
|
329
|
+
const st = writers.get(writerKey(sessionId, cwd))
|
|
330
|
+
if (st) st.healthy = false
|
|
331
|
+
process.stderr.write(`[warn] journal degraded (${why})\n`)
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// ── Tulis durabel: append → flush/fsync (§10) ──
|
|
335
|
+
|
|
336
|
+
async function appendLine(path: string, obj: JournalRecord): Promise<boolean> {
|
|
337
|
+
const line = `${JSON.stringify(obj)}\n`
|
|
338
|
+
// Baris kecil + O_APPEND = tulis atomik antar proses (POSIX); cukup untuk
|
|
339
|
+
// satu penulis per sesi + penulis sesekali (sweep memakai file lain).
|
|
340
|
+
try {
|
|
341
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 }).catch(() => {})
|
|
342
|
+
const h = await open(path, "a")
|
|
343
|
+
try {
|
|
344
|
+
await h.appendFile(line, "utf8")
|
|
345
|
+
await h.sync()
|
|
346
|
+
} finally {
|
|
347
|
+
await h.close().catch(() => {})
|
|
348
|
+
}
|
|
349
|
+
return true
|
|
350
|
+
} catch (e) {
|
|
351
|
+
process.stderr.write(`[warn] journal: write failed (${path}): ${(e as Error).message}\n`)
|
|
352
|
+
return false
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
async function stateFor(path: string, key: string): Promise<WriterState> {
|
|
357
|
+
let st = writers.get(key)
|
|
358
|
+
if (!st) {
|
|
359
|
+
st = { nextSeq: 0, healthy: true }
|
|
360
|
+
// Lanjutkan seq lintas restart proses (anti tabrakan id).
|
|
361
|
+
try {
|
|
362
|
+
const raw = await readFile(path, "utf8")
|
|
363
|
+
for (const line of raw.split("\n")) {
|
|
364
|
+
if (!line.trim()) continue
|
|
365
|
+
try {
|
|
366
|
+
const r = JSON.parse(line) as { seq?: unknown }
|
|
367
|
+
if (typeof r.seq === "number" && Number.isFinite(r.seq)) {
|
|
368
|
+
st.nextSeq = Math.max(st.nextSeq, Math.floor(r.seq) + 1)
|
|
369
|
+
}
|
|
370
|
+
} catch {}
|
|
371
|
+
}
|
|
372
|
+
} catch {}
|
|
373
|
+
writers.set(key, st)
|
|
374
|
+
}
|
|
375
|
+
return st
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
export interface IntentInput {
|
|
379
|
+
session: string
|
|
380
|
+
childOf?: string
|
|
381
|
+
turn?: number | null
|
|
382
|
+
tool: string
|
|
383
|
+
remote?: true
|
|
384
|
+
backend?: string
|
|
385
|
+
cwd?: string
|
|
386
|
+
paths?: string[]
|
|
387
|
+
argsHash?: string
|
|
388
|
+
childSessionId?: string
|
|
389
|
+
/**
|
|
390
|
+
* Kunci idempotency (audit #08): ditulis ke outcome.note SEJAK intent agar
|
|
391
|
+
* crash di tengah eksekusi tetap meninggalkan bukti yang dapat dicocokkan
|
|
392
|
+
* (sebelumnya note hanya ada di terminal → bukti pending tak terlihat →
|
|
393
|
+
* retry id-sama pasca-crash dieksekusi ulang buta).
|
|
394
|
+
*/
|
|
395
|
+
note?: string
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/** Tulis intent pending. Tak pernah throw (degraded-loud, lihat header). */
|
|
399
|
+
export async function appendMutationIntent(input: IntentInput): Promise<JournalRecord> {
|
|
400
|
+
const root = resolve(input.cwd ?? process.cwd())
|
|
401
|
+
const path = journalPath(input.session, root)
|
|
402
|
+
const key = writerKey(input.session, root)
|
|
403
|
+
return withFileLock(key, async () => {
|
|
404
|
+
const st = await stateFor(path, key)
|
|
405
|
+
// Alokasi seq SYNCHRONOUS di dalam lock: tanpa ini dua pemanggil konkuren
|
|
406
|
+
// mendapat seq sama (tabrakan id — P0, ditemukan AUDIT #01D).
|
|
407
|
+
const seq = st.nextSeq
|
|
408
|
+
const rec: JournalRecord = {
|
|
409
|
+
v: 1,
|
|
410
|
+
id: `${input.session}:${seq}`,
|
|
411
|
+
session: input.session,
|
|
412
|
+
...(input.childOf ? { childOf: input.childOf } : {}),
|
|
413
|
+
turn: input.turn ?? null,
|
|
414
|
+
seq,
|
|
415
|
+
tool: input.tool,
|
|
416
|
+
...(input.remote ? { remote: true as const } : {}),
|
|
417
|
+
...(input.backend ? { backend: input.backend } : {}),
|
|
418
|
+
cwd: root,
|
|
419
|
+
...(input.paths?.length ? { paths: input.paths } : {}),
|
|
420
|
+
...(input.argsHash ? { argsHash: input.argsHash } : {}),
|
|
421
|
+
...(input.childSessionId ? { childSessionId: input.childSessionId } : {}),
|
|
422
|
+
// Kunci idempotency sejak intent (lihat IntentInput.note).
|
|
423
|
+
...(input.note ? { outcome: { note: input.note } } : {}),
|
|
424
|
+
state: "pending",
|
|
425
|
+
ts: Date.now(),
|
|
426
|
+
}
|
|
427
|
+
// Tak-pernah-throw disengaja: kegagalan jurnal tak boleh menggagalkan turn.
|
|
428
|
+
// Resume memperlakukan sesi degraded via jalur advisory + warn ini.
|
|
429
|
+
if (await appendLine(path, rec)) {
|
|
430
|
+
st.nextSeq = seq + 1
|
|
431
|
+
} else {
|
|
432
|
+
markDegraded(input.session, root, "intent append gagal")
|
|
433
|
+
}
|
|
434
|
+
return rec
|
|
435
|
+
})
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/** Tulis terminal (committed/failed) untuk id intent. Append-only. */
|
|
439
|
+
export async function appendMutationTerminal(
|
|
440
|
+
session: string,
|
|
441
|
+
cwd: string | undefined,
|
|
442
|
+
id: string,
|
|
443
|
+
seq: number,
|
|
444
|
+
tool: string,
|
|
445
|
+
state: "committed" | "failed",
|
|
446
|
+
outcome?: { code?: number | null; note?: string },
|
|
447
|
+
childSessionId?: string,
|
|
448
|
+
opts: { dedup?: boolean } = {},
|
|
449
|
+
): Promise<void> {
|
|
450
|
+
const root = resolve(cwd ?? process.cwd())
|
|
451
|
+
const path = journalPath(session, root)
|
|
452
|
+
const key = writerKey(session, root)
|
|
453
|
+
return withFileLock(key, async () => {
|
|
454
|
+
await stateFor(path, key)
|
|
455
|
+
const rec: JournalRecord = {
|
|
456
|
+
v: 1,
|
|
457
|
+
id,
|
|
458
|
+
session,
|
|
459
|
+
seq,
|
|
460
|
+
tool,
|
|
461
|
+
state,
|
|
462
|
+
cwd: root,
|
|
463
|
+
...(outcome ? { outcome } : {}),
|
|
464
|
+
// Tautan delegasi diwariskan ke terminal agar pembaca tak perlu
|
|
465
|
+
// join intent-terminal untuk mengetahui anak mana yang dirujuk.
|
|
466
|
+
...(childSessionId ? { childSessionId } : {}),
|
|
467
|
+
// Bukti dedup idempotency (mis. MCP request id): dipertahankan sweep.
|
|
468
|
+
...(opts.dedup ? { dedup: true as const } : {}),
|
|
469
|
+
ts: Date.now(),
|
|
470
|
+
}
|
|
471
|
+
const st = writers.get(key)
|
|
472
|
+
if (!(await appendLine(path, rec)) && st) markDegraded(session, root, "terminal append gagal")
|
|
473
|
+
})
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/** Marker finalize: semua seq ≤ uptoSeq durable (post-persistCurrent). */
|
|
477
|
+
export async function appendFinalize(
|
|
478
|
+
session: string,
|
|
479
|
+
cwd: string | undefined,
|
|
480
|
+
uptoSeq: number,
|
|
481
|
+
): Promise<void> {
|
|
482
|
+
const root = resolve(cwd ?? process.cwd())
|
|
483
|
+
const path = journalPath(session, root)
|
|
484
|
+
const key = writerKey(session, root)
|
|
485
|
+
return withFileLock(key, async () => {
|
|
486
|
+
const st = await stateFor(path, key)
|
|
487
|
+
const seq = st.nextSeq
|
|
488
|
+
const rec: JournalRecord = {
|
|
489
|
+
v: 1,
|
|
490
|
+
id: `${session}:f${seq}`,
|
|
491
|
+
session,
|
|
492
|
+
seq,
|
|
493
|
+
tool: "",
|
|
494
|
+
kind: "finalize",
|
|
495
|
+
uptoSeq,
|
|
496
|
+
cwd: root,
|
|
497
|
+
ts: Date.now(),
|
|
498
|
+
}
|
|
499
|
+
if (await appendLine(path, rec)) st.nextSeq = seq + 1
|
|
500
|
+
else markDegraded(session, root, "finalize append gagal")
|
|
501
|
+
})
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/** Marker undo/redo: posisi workspace pasca-operasi (DB tak ikut). */
|
|
505
|
+
export async function appendUndoMarker(
|
|
506
|
+
session: string,
|
|
507
|
+
cwd: string | undefined,
|
|
508
|
+
kind: "undo" | "redo",
|
|
509
|
+
targetTurn: number,
|
|
510
|
+
extra?: { newIndex?: number; files?: number },
|
|
511
|
+
): Promise<void> {
|
|
512
|
+
const root = resolve(cwd ?? process.cwd())
|
|
513
|
+
const path = journalPath(session, root)
|
|
514
|
+
const key = writerKey(session, root)
|
|
515
|
+
return withFileLock(key, async () => {
|
|
516
|
+
const st = await stateFor(path, key)
|
|
517
|
+
const seq = st.nextSeq
|
|
518
|
+
const rec: JournalRecord = {
|
|
519
|
+
v: 1,
|
|
520
|
+
id: `${session}:m${seq}`,
|
|
521
|
+
session,
|
|
522
|
+
seq,
|
|
523
|
+
tool: "",
|
|
524
|
+
kind,
|
|
525
|
+
targetTurn,
|
|
526
|
+
cwd: root,
|
|
527
|
+
...(extra?.newIndex !== undefined ? { newIndex: extra.newIndex } : {}),
|
|
528
|
+
...(extra?.files !== undefined ? { files: extra.files } : {}),
|
|
529
|
+
ts: Date.now(),
|
|
530
|
+
}
|
|
531
|
+
if (await appendLine(path, rec)) st.nextSeq = seq + 1
|
|
532
|
+
else markDegraded(session, root, "marker append gagal")
|
|
533
|
+
})
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
/** Finalize + sweep: dipanggil setelah persistCurrent sukses. */
|
|
537
|
+
export async function finalizeJournal(sessionId: string, cwd?: string): Promise<void> {
|
|
538
|
+
const root = resolve(cwd ?? process.cwd())
|
|
539
|
+
const path = journalPath(sessionId, root)
|
|
540
|
+
const key = writerKey(sessionId, root)
|
|
541
|
+
const st = await stateFor(path, key)
|
|
542
|
+
const maxMutation = st.nextSeq - 1
|
|
543
|
+
if (maxMutation < 0) return
|
|
544
|
+
await appendFinalize(sessionId, root, maxMutation)
|
|
545
|
+
await sweepJournal(sessionId, root).catch((e) => {
|
|
546
|
+
process.stderr.write(`[warn] journal: sweep failed: ${(e as Error).message}\n`)
|
|
547
|
+
})
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/**
|
|
551
|
+
* Hapus HANYA yang finalized + marker lama. Atomic: tulis tmp → rename.
|
|
552
|
+
* - committed/failed dengan seq ≤ maxUpto → finalized → buang.
|
|
553
|
+
* - pending TAK PERNAH dibuang karena finalize (finalize menandai persist,
|
|
554
|
+
* bukan status mutasi) — KECUALI superseded: mutasi sama (tool+paths)
|
|
555
|
+
* berhasil di-commit belakangan = bukti operator verifikasi + jalan terus.
|
|
556
|
+
* Pending tanpa paths (bash/MCP) tak bisa disupersede — ambiguitasnya
|
|
557
|
+
* genuinely berbahaya, jadi bertahan sampai resolvePending eksplisit.
|
|
558
|
+
*/
|
|
559
|
+
export async function sweepJournal(sessionId: string, cwd?: string): Promise<number> {
|
|
560
|
+
const root = resolve(cwd ?? process.cwd())
|
|
561
|
+
const key = writerKey(sessionId, root)
|
|
562
|
+
// Sweep vs append konkuren = lost-record: serialkan dengan penulis.
|
|
563
|
+
return withFileLock(key, () => sweepInner(sessionId, root))
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
async function sweepInner(sessionId: string, root: string): Promise<number> {
|
|
567
|
+
const path = journalPath(sessionId, root)
|
|
568
|
+
const loaded = await loadJournal(sessionId, root)
|
|
569
|
+
if (loaded.records.length === 0) return 0
|
|
570
|
+
let maxUpto = -1
|
|
571
|
+
for (const r of loaded.records) {
|
|
572
|
+
if (r.kind === "finalize" && typeof r.uptoSeq === "number")
|
|
573
|
+
maxUpto = Math.max(maxUpto, r.uptoSeq)
|
|
574
|
+
}
|
|
575
|
+
if (maxUpto < 0) return 0
|
|
576
|
+
// Pasangan selesai: pending yang sudah punya terminal (id sama) ikut
|
|
577
|
+
// dibuang — statusnya hidup di record terminal (satu semantik mutasi).
|
|
578
|
+
const paired = new Set<string>()
|
|
579
|
+
for (const r of loaded.records) {
|
|
580
|
+
if ((!r.kind || r.kind === "mutation") && (r.state === "committed" || r.state === "failed")) {
|
|
581
|
+
paired.add(r.id)
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
const committedKeys = committedPathsKeys(loaded.records)
|
|
585
|
+
const keep = loaded.records.filter((r) => {
|
|
586
|
+
if (r.kind === "finalize") return r.seq === maxFinalizeSeq(loaded.records)
|
|
587
|
+
if (r.kind === "undo" || r.kind === "redo") return r.seq > maxUpto
|
|
588
|
+
if (r.state === "pending" && paired.has(r.id)) return false
|
|
589
|
+
if (r.state === "pending") return !isSuperseded(r, committedKeys)
|
|
590
|
+
// Bukti dedup idempotency (dedup: true, mis. MCP request id) BUKAN sampah
|
|
591
|
+
// finalize: menghapusnya membuat retry id-sama pasca-restart dieksekusi
|
|
592
|
+
// ulang buta (audit #08 P0 — reproducer: note hilang setelah sweep).
|
|
593
|
+
// Intent pasangannya tetap dibuang (aturan paired di atas); terminal ini
|
|
594
|
+
// yang menjadi bukti. Batas pertumbuhan: file per sesi + purge yatim TTL.
|
|
595
|
+
if (
|
|
596
|
+
(!r.kind || r.kind === "mutation") &&
|
|
597
|
+
(r.state === "committed" || r.state === "failed") &&
|
|
598
|
+
r.dedup === true
|
|
599
|
+
)
|
|
600
|
+
return true
|
|
601
|
+
return (r.seq ?? 0) > maxUpto // committed/failed muda bertahan
|
|
602
|
+
})
|
|
603
|
+
if (keep.length === loaded.records.length) return 0
|
|
604
|
+
const data = keep.map((r) => JSON.stringify(r)).join("\n") + (keep.length ? "\n" : "")
|
|
605
|
+
await atomicWriteText(path, data)
|
|
606
|
+
// Sinkronkan counter in-memory dengan file hasil sweep.
|
|
607
|
+
const key = writerKey(sessionId, root)
|
|
608
|
+
const st = writers.get(key)
|
|
609
|
+
if (st) {
|
|
610
|
+
let mx = -1
|
|
611
|
+
for (const r of keep) if (typeof r.seq === "number") mx = Math.max(mx, r.seq)
|
|
612
|
+
st.nextSeq = mx + 1
|
|
613
|
+
}
|
|
614
|
+
return loaded.records.length - keep.length
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/** Kunci supersede: tool + paths non-kosong (bash/MCP tanpa path tak ikut). */
|
|
618
|
+
function pathsKey(tool: string, paths?: string[]): string | null {
|
|
619
|
+
if (!paths || paths.length === 0) return null
|
|
620
|
+
return `${tool}|${[...paths].sort().join(",")}`
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
function committedPathsKeys(records: JournalRecord[]): Set<string> {
|
|
624
|
+
const out = new Set<string>()
|
|
625
|
+
// Terminal committed per id (duplikat: terminal pertama menang — sama
|
|
626
|
+
// seperti consolidate di decideRecovery).
|
|
627
|
+
const seen = new Set<string>()
|
|
628
|
+
for (const r of records) {
|
|
629
|
+
if (r.kind && r.kind !== "mutation") continue
|
|
630
|
+
if (r.state !== "committed" || seen.has(r.id)) continue
|
|
631
|
+
seen.add(r.id)
|
|
632
|
+
const k = pathsKey(r.tool, r.paths)
|
|
633
|
+
if (k) out.add(`${k}@${r.seq}`)
|
|
634
|
+
}
|
|
635
|
+
return out
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
function isSuperseded(r: JournalRecord, committedKeys: Set<string>): boolean {
|
|
639
|
+
const k = pathsKey(r.tool, r.paths)
|
|
640
|
+
if (!k) return false
|
|
641
|
+
for (const entry of committedKeys) {
|
|
642
|
+
const at = entry.lastIndexOf("@")
|
|
643
|
+
if (entry.slice(0, at) === k && Number(entry.slice(at + 1)) > r.seq) return true
|
|
644
|
+
}
|
|
645
|
+
return false
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
/**
|
|
649
|
+
* Resolusi manual pending → terminal berdasar verifikasi manusia (calon
|
|
650
|
+
* pemanggil: perintah /verify-ack masa depan). applied = efek ada (jangan
|
|
651
|
+
* ulang); absent = efek tak ada (boleh coba lagi via gate normal).
|
|
652
|
+
*/
|
|
653
|
+
export async function resolvePending(
|
|
654
|
+
sessionId: string,
|
|
655
|
+
cwd: string | undefined,
|
|
656
|
+
seq: number,
|
|
657
|
+
verdict: "applied" | "absent",
|
|
658
|
+
note?: string,
|
|
659
|
+
): Promise<boolean> {
|
|
660
|
+
const root = resolve(cwd ?? process.cwd())
|
|
661
|
+
const loaded = await loadJournal(sessionId, root)
|
|
662
|
+
const mine = loaded.records.filter(
|
|
663
|
+
(r) => (!r.kind || r.kind === "mutation") && r.session === sessionId && r.seq === seq,
|
|
664
|
+
)
|
|
665
|
+
if (mine.length === 0) return false
|
|
666
|
+
if (mine.some((r) => r.state === "committed" || r.state === "failed")) return false
|
|
667
|
+
const first = mine[0]!
|
|
668
|
+
await appendMutationTerminal(
|
|
669
|
+
sessionId,
|
|
670
|
+
root,
|
|
671
|
+
first.id,
|
|
672
|
+
seq,
|
|
673
|
+
first.tool,
|
|
674
|
+
verdict === "applied" ? "committed" : "failed",
|
|
675
|
+
{ note: `human-verified:${verdict}${note ? ` ${note}` : ""}` },
|
|
676
|
+
)
|
|
677
|
+
return true
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
function maxFinalizeSeq(records: JournalRecord[]): number {
|
|
681
|
+
let mx = -1
|
|
682
|
+
for (const r of records) {
|
|
683
|
+
if (r.kind === "finalize" && typeof r.seq === "number") mx = Math.max(mx, r.seq)
|
|
684
|
+
}
|
|
685
|
+
return mx
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
// ── Baca + korupsi (§9) ──
|
|
689
|
+
|
|
690
|
+
export interface JournalLoad {
|
|
691
|
+
records: JournalRecord[]
|
|
692
|
+
warnings: string[]
|
|
693
|
+
/** Ekor terpotong (fail-closed keputusan, fail-open sesi). */
|
|
694
|
+
truncatedTail: boolean
|
|
695
|
+
quarantined: boolean
|
|
696
|
+
/**
|
|
697
|
+
* Status file — TIDAK disamakan:
|
|
698
|
+
* absent = tak pernah ada (bukan bukti apa pun);
|
|
699
|
+
* empty = ada tetapi nol record (sesi terpasang, belum bermutasi);
|
|
700
|
+
* valid = ≥1 record utuh; corrupt = dikarantina / ekor-rusak tanpa isi;
|
|
701
|
+
* unreadable = ada tetapi tak terbaca (bukan bukti kosong).
|
|
702
|
+
*/
|
|
703
|
+
status: "absent" | "empty" | "valid" | "corrupt" | "unreadable"
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
function isRecordShape(r: unknown): r is JournalRecord {
|
|
707
|
+
if (!r || typeof r !== "object") return false
|
|
708
|
+
const o = r as Record<string, unknown>
|
|
709
|
+
if (o.v !== 1 || typeof o.id !== "string" || typeof o.session !== "string") return false
|
|
710
|
+
if (typeof o.seq !== "number" || !Number.isFinite(o.seq)) return false
|
|
711
|
+
if (o.kind === "finalize" || o.kind === "undo" || o.kind === "redo") return true
|
|
712
|
+
if (typeof o.tool !== "string" || !o.tool) return false
|
|
713
|
+
return o.state === "pending" || o.state === "committed" || o.state === "failed"
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
export async function loadJournal(sessionId: string, cwd?: string): Promise<JournalLoad> {
|
|
717
|
+
const root = resolve(cwd ?? process.cwd())
|
|
718
|
+
const path = journalPath(sessionId, root)
|
|
719
|
+
const warnings: string[] = []
|
|
720
|
+
let raw: string
|
|
721
|
+
try {
|
|
722
|
+
raw = await readFile(path, "utf8")
|
|
723
|
+
} catch (e) {
|
|
724
|
+
// ENOENT = memang tak ada (bukan bukti kosong). Sisanya = unreadable,
|
|
725
|
+
// BUKAN empty — file yang tak terbaca tak boleh disamakan dengan bersih.
|
|
726
|
+
if ((e as NodeJS.ErrnoException)?.code === "ENOENT") {
|
|
727
|
+
return { records: [], warnings, truncatedTail: false, quarantined: false, status: "absent" }
|
|
728
|
+
}
|
|
729
|
+
warnings.push(`journal tak terbaca (${path}): ${(e as Error).message}`)
|
|
730
|
+
return { records: [], warnings, truncatedTail: false, quarantined: false, status: "unreadable" }
|
|
731
|
+
}
|
|
732
|
+
const lines = raw.split("\n")
|
|
733
|
+
// Baris akhir kosong = terminator normal, bukan truncasi.
|
|
734
|
+
if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop()
|
|
735
|
+
const records: JournalRecord[] = []
|
|
736
|
+
for (let i = 0; i < lines.length; i++) {
|
|
737
|
+
const line = lines[i]!
|
|
738
|
+
if (!line.trim()) continue
|
|
739
|
+
let parsed: unknown
|
|
740
|
+
try {
|
|
741
|
+
parsed = JSON.parse(line)
|
|
742
|
+
} catch {
|
|
743
|
+
const r = await handleCorrupt(
|
|
744
|
+
path,
|
|
745
|
+
lines,
|
|
746
|
+
i,
|
|
747
|
+
records,
|
|
748
|
+
warnings,
|
|
749
|
+
`baris ${i + 1} bukan JSON valid`,
|
|
750
|
+
)
|
|
751
|
+
return { ...r, status: "corrupt" }
|
|
752
|
+
}
|
|
753
|
+
if (!isRecordShape(parsed)) {
|
|
754
|
+
const r = await handleCorrupt(
|
|
755
|
+
path,
|
|
756
|
+
lines,
|
|
757
|
+
i,
|
|
758
|
+
records,
|
|
759
|
+
warnings,
|
|
760
|
+
`baris ${i + 1} bentuk record invalid`,
|
|
761
|
+
)
|
|
762
|
+
return { ...r, status: "corrupt" }
|
|
763
|
+
}
|
|
764
|
+
records.push(parsed)
|
|
765
|
+
}
|
|
766
|
+
return {
|
|
767
|
+
records,
|
|
768
|
+
warnings,
|
|
769
|
+
truncatedTail: false,
|
|
770
|
+
quarantined: false,
|
|
771
|
+
status: records.length > 0 ? "valid" : "empty",
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
async function handleCorrupt(
|
|
776
|
+
path: string,
|
|
777
|
+
lines: string[],
|
|
778
|
+
at: number,
|
|
779
|
+
prefix: JournalRecord[],
|
|
780
|
+
warnings: string[],
|
|
781
|
+
reason: string,
|
|
782
|
+
): Promise<JournalLoad> {
|
|
783
|
+
const isTail = at === lines.length - 1
|
|
784
|
+
if (isTail) {
|
|
785
|
+
// Ekor terpotong (crash mid-append): buang baris, pakai prefix.
|
|
786
|
+
warnings.push(
|
|
787
|
+
`journal korup di ekor (${reason}) — baris dibuang, prefix (${prefix.length} record) tetap otoritatif`,
|
|
788
|
+
)
|
|
789
|
+
try {
|
|
790
|
+
await atomicWriteText(
|
|
791
|
+
path,
|
|
792
|
+
prefix.map((r) => JSON.stringify(r)).join("\n") + (prefix.length ? "\n" : ""),
|
|
793
|
+
)
|
|
794
|
+
} catch {}
|
|
795
|
+
return { records: prefix, warnings, truncatedTail: true, quarantined: false, status: "corrupt" }
|
|
796
|
+
}
|
|
797
|
+
// Tengah korup: quarantine + pertahankan prefix sebagai live.
|
|
798
|
+
const qpath = `${path}.corrupt.${Date.now()}`
|
|
799
|
+
warnings.push(
|
|
800
|
+
`journal KORUP di tengah (${reason}) — file dikarantina ke ${qpath}; prefix (${prefix.length} record) dipakai, suffix dianggap pending/ambigu`,
|
|
801
|
+
)
|
|
802
|
+
try {
|
|
803
|
+
await atomicWriteText(qpath, lines.join("\n"))
|
|
804
|
+
await atomicWriteText(
|
|
805
|
+
path,
|
|
806
|
+
prefix.map((r) => JSON.stringify(r)).join("\n") + (prefix.length ? "\n" : ""),
|
|
807
|
+
)
|
|
808
|
+
} catch {}
|
|
809
|
+
return { records: prefix, warnings, truncatedTail: false, quarantined: true, status: "corrupt" }
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
// ── Keputusan resume murni: decideRecovery (tanpa I/O) ──
|
|
813
|
+
|
|
814
|
+
export interface AttentionItem {
|
|
815
|
+
id: string
|
|
816
|
+
seq: number
|
|
817
|
+
tool: string
|
|
818
|
+
state: "pending" | "committed" | "failed"
|
|
819
|
+
remote: boolean
|
|
820
|
+
paths: string[]
|
|
821
|
+
childSessionId?: string
|
|
822
|
+
turn?: number | null
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
export interface RecoveryPlan {
|
|
826
|
+
clean: boolean
|
|
827
|
+
/** SATU blok SYSTEM (blocking + stitch + remote). null bila clean. */
|
|
828
|
+
directive: string | null
|
|
829
|
+
warnings: string[]
|
|
830
|
+
attention: AttentionItem[]
|
|
831
|
+
stitched: { id: string; tool: string; turn?: number | null }[]
|
|
832
|
+
stats: { pending: number; failed: number; committed: number; finalized: number; markers: number }
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
const MAX_DIRECTIVE_ITEMS = 10
|
|
836
|
+
|
|
837
|
+
export function decideRecovery(
|
|
838
|
+
records: JournalRecord[],
|
|
839
|
+
persistedTurns: number[],
|
|
840
|
+
opts: { maxItems?: number } = {},
|
|
841
|
+
): RecoveryPlan {
|
|
842
|
+
const warnings: string[] = []
|
|
843
|
+
const maxItems = opts.maxItems ?? MAX_DIRECTIVE_ITEMS
|
|
844
|
+
// Konsolidasi per id (append-only boleh punya pasangan pending→terminal).
|
|
845
|
+
// Aturan: terminal pertama menang; terminal ganda / terminal→pending =
|
|
846
|
+
// anomali → warn + abaikan tulisan basi.
|
|
847
|
+
const byId = new Map<string, JournalRecord[]>()
|
|
848
|
+
for (const r of records) {
|
|
849
|
+
if (r.kind && r.kind !== "mutation") continue
|
|
850
|
+
const list = byId.get(r.id) ?? []
|
|
851
|
+
list.push(r)
|
|
852
|
+
byId.set(r.id, list)
|
|
853
|
+
}
|
|
854
|
+
// Finalize scope = PER SESSION FILE (seq spaces tak sebanding antar file).
|
|
855
|
+
// Global maxUpto akan mencampur namespace parent/child secara salah.
|
|
856
|
+
const uptoBySession = new Map<string, number>()
|
|
857
|
+
let undoRedoCount = 0
|
|
858
|
+
// Marker undo/redo untuk aturan stitch (P0-3): redo mengembalikan efek
|
|
859
|
+
// (stitch moot), undo mencabut efek (stitch salah → warning khusus).
|
|
860
|
+
// Hanya untuk record sesi-sendiri (tanpa childOf) — namespace terisolasi.
|
|
861
|
+
const redoMarks: { targetTurn: number; seq: number }[] = []
|
|
862
|
+
const undoMarks: { targetTurn: number; seq: number }[] = []
|
|
863
|
+
for (const r of records) {
|
|
864
|
+
if (r.kind === "finalize" && typeof r.uptoSeq === "number") {
|
|
865
|
+
uptoBySession.set(r.session, Math.max(uptoBySession.get(r.session) ?? -1, r.uptoSeq))
|
|
866
|
+
}
|
|
867
|
+
if (r.kind === "undo" || r.kind === "redo") {
|
|
868
|
+
undoRedoCount += 1
|
|
869
|
+
if (typeof r.targetTurn === "number" && typeof r.seq === "number") {
|
|
870
|
+
;(r.kind === "redo" ? redoMarks : undoMarks).push({ targetTurn: r.targetTurn, seq: r.seq })
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
const covered = (r: JournalRecord): boolean => r.seq <= (uptoBySession.get(r.session) ?? -1)
|
|
875
|
+
// Cakupan transitif delegasi: anak ter-cover bila record delegasi parent-nya
|
|
876
|
+
// terminal committed DAN finalized (skop sesi parent). Tanpa ini committed
|
|
877
|
+
// anak selalu stitch karena turn anak tak ada di DB parent (false positive).
|
|
878
|
+
const coveredChild = new Set<string>()
|
|
879
|
+
for (const [, list] of byId) {
|
|
880
|
+
const first = list[0]!
|
|
881
|
+
if (first.tool !== "delegate_task" || !first.childSessionId) continue
|
|
882
|
+
const term = list.find((r) => r.state === "committed" || r.state === "failed")
|
|
883
|
+
if (term?.state === "committed" && covered(term)) coveredChild.add(first.childSessionId)
|
|
884
|
+
}
|
|
885
|
+
// Gap seq = kemungkinan penulis ganda/hilang (peringatan, bukan blokir).
|
|
886
|
+
const seqs = [...byId.values()].map((l) => l[0]!.seq).sort((a, b) => a - b)
|
|
887
|
+
for (let i = 1; i < seqs.length; i++) {
|
|
888
|
+
if (seqs[i]! - seqs[i - 1]! > 1) {
|
|
889
|
+
warnings.push(
|
|
890
|
+
`journal seq gap ${seqs[i - 1]} → ${seqs[i]} (kemungkinan tulis hilang/penulis ganda)`,
|
|
891
|
+
)
|
|
892
|
+
break
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
const stats = { pending: 0, failed: 0, committed: 0, finalized: 0, markers: undoRedoCount }
|
|
896
|
+
const attention: AttentionItem[] = []
|
|
897
|
+
const stitched: { id: string; tool: string; turn?: number | null }[] = []
|
|
898
|
+
const remoteVerify: AttentionItem[] = []
|
|
899
|
+
const supersedeKeys = committedPathsKeys(records)
|
|
900
|
+
for (const [, list] of [...byId.entries()].sort((a, b) => a[1][0]!.seq - b[1][0]!.seq)) {
|
|
901
|
+
const first = list[0]!
|
|
902
|
+
if (list.length > 1) {
|
|
903
|
+
const terminals = list.filter((r) => r.state === "committed" || r.state === "failed")
|
|
904
|
+
if (terminals.length > 1) {
|
|
905
|
+
warnings.push(
|
|
906
|
+
`journal id duplikat ${first.id} (${terminals.length} terminal) — pakai yang pertama`,
|
|
907
|
+
)
|
|
908
|
+
}
|
|
909
|
+
const stalePending = list.findIndex((r, i) => i > 0 && r.state === "pending")
|
|
910
|
+
if (stalePending !== -1 || (terminals.length === 0 && list.length > 1)) {
|
|
911
|
+
warnings.push(`journal id duplikat ${first.id} — abaikan tulisan basi`)
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
const eff = list.find((r) => r.state === "committed" || r.state === "failed") ?? first
|
|
915
|
+
if (!eff.state || eff.state === "pending") {
|
|
916
|
+
// Superseded = mutasi sama berhasil belakangan = bukti verifikasi
|
|
917
|
+
// implisit (sweep akan membuangnya). Jangan nagih yang sudah terjawab.
|
|
918
|
+
if (isSuperseded(first, supersedeKeys)) continue
|
|
919
|
+
stats.pending += 1
|
|
920
|
+
if (covered(first)) {
|
|
921
|
+
// Tertutup finalize tetapi tanpa terminal: finalize menandai cakupan
|
|
922
|
+
// persist, BUKAN status mutasi — tetap ambigu (konservatif benar).
|
|
923
|
+
warnings.push(
|
|
924
|
+
`journal ${first.id} pending tetapi ter-cover finalize — tetap diperlakukan ambigu`,
|
|
925
|
+
)
|
|
926
|
+
}
|
|
927
|
+
attention.push(toItem(first, "pending"))
|
|
928
|
+
continue
|
|
929
|
+
}
|
|
930
|
+
if (eff.state === "failed") {
|
|
931
|
+
stats.failed += 1
|
|
932
|
+
if (covered(first)) {
|
|
933
|
+
stats.finalized += 1
|
|
934
|
+
continue
|
|
935
|
+
}
|
|
936
|
+
attention.push(toItem(first, "failed"))
|
|
937
|
+
continue
|
|
938
|
+
}
|
|
939
|
+
// committed
|
|
940
|
+
if (covered(first)) {
|
|
941
|
+
stats.committed += 1
|
|
942
|
+
stats.finalized += 1
|
|
943
|
+
continue
|
|
944
|
+
}
|
|
945
|
+
// Anak ter-cover transitif: delegasi parent-nya committed + finalized
|
|
946
|
+
// (skop sesi parent). Tanpa ini setiap committed anak stitch spurios.
|
|
947
|
+
if (first.childOf && coveredChild.has(first.session)) {
|
|
948
|
+
stats.committed += 1
|
|
949
|
+
continue
|
|
950
|
+
}
|
|
951
|
+
stats.committed += 1
|
|
952
|
+
if (first.remote) {
|
|
953
|
+
remoteVerify.push(toItem(first, "committed"))
|
|
954
|
+
continue
|
|
955
|
+
}
|
|
956
|
+
// Redo yang lebih baru dan mencakup turn ini mengembalikan efeknya —
|
|
957
|
+
// stitch moot. BUKAN auto-redo: redo sudah terjadi dan tercatat.
|
|
958
|
+
// (Remote dikecualikan di atas: redo file tak memulihkan efek server.)
|
|
959
|
+
if (!first.childOf && first.turn != null) {
|
|
960
|
+
const redone = redoMarks.some((mk) => mk.seq > first.seq && mk.targetTurn >= first.turn!)
|
|
961
|
+
if (redone) continue
|
|
962
|
+
// Undo yang lebih baru dan mencakup turn ini MENCABUT efeknya: stitch
|
|
963
|
+
// "anggap efek ada" menjadi salah — ganti warning jujur, tanpa redo.
|
|
964
|
+
const undone = undoMarks.some((mk) => mk.seq > first.seq && first.turn! >= mk.targetTurn)
|
|
965
|
+
if (undone) {
|
|
966
|
+
warnings.push(
|
|
967
|
+
`efek turn ${first.turn} (${first.tool}) di-undo sesudah commit — transkrip lebih baru dari file; JANGAN ulangi otomatis, JANGAN percaya penuh`,
|
|
968
|
+
)
|
|
969
|
+
continue
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
// ISOLASI NAMESPACE TURN: turn anak tak pernah dibandingkan dengan turns
|
|
973
|
+
// parent (ruang turn berbeda). Anak uncovered selalu stitch — aman dan
|
|
974
|
+
// tak pernah cross-match kebetulan.
|
|
975
|
+
if (!first.childOf) {
|
|
976
|
+
const turn = first.turn ?? null
|
|
977
|
+
if (turn !== null && persistedTurns.includes(turn)) continue // normal
|
|
978
|
+
}
|
|
979
|
+
stitched.push({ id: first.id, tool: first.tool, turn: first.turn ?? null })
|
|
980
|
+
}
|
|
981
|
+
const blocks: string[] = []
|
|
982
|
+
const shown = attention.slice(0, maxItems)
|
|
983
|
+
if (shown.length > 0) {
|
|
984
|
+
blocks.push(
|
|
985
|
+
"MUTASI TAK-PASTI (pending/failed) — verifikasi SEBELUM mengulang; DILARANG redo buta:",
|
|
986
|
+
...shown.map(
|
|
987
|
+
(a) =>
|
|
988
|
+
`- [seq ${a.seq}] ${a.tool} (${a.state})${a.paths.length ? ` paths: ${a.paths.join(", ")}` : " (tanpa path — diff workspace vs checkpoint)"}${a.childSessionId ? ` child: ${a.childSessionId}` : ""}`,
|
|
989
|
+
),
|
|
990
|
+
)
|
|
991
|
+
if (attention.length > shown.length) {
|
|
992
|
+
blocks.push(
|
|
993
|
+
`- ... +${attention.length - shown.length} lagi — minta keputusan user sebelum lanjut.`,
|
|
994
|
+
)
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
if (remoteVerify.length > 0) {
|
|
998
|
+
const rshown = remoteVerify.slice(0, maxItems)
|
|
999
|
+
blocks.push(
|
|
1000
|
+
"MUTASI REMOTE (external-acknowledged, BUKAN komit lokal) — wajib baca-balik sebelum membangun state di atasnya:",
|
|
1001
|
+
...rshown.map((a) => `- [seq ${a.seq}] ${a.tool}`),
|
|
1002
|
+
)
|
|
1003
|
+
}
|
|
1004
|
+
if (stitched.length > 0) {
|
|
1005
|
+
blocks.push(
|
|
1006
|
+
"CATATAN NARASI (bukan blokir): mutasi berikut tercatat committed tetapi turn-nya tidak durable — JANGAN dieksekusi ulang; anggap efeknya ada:",
|
|
1007
|
+
...stitched.map((s) => `- [${s.id}] ${s.tool}${s.turn != null ? ` (turn ${s.turn})` : ""}`),
|
|
1008
|
+
)
|
|
1009
|
+
}
|
|
1010
|
+
const clean = blocks.length === 0
|
|
1011
|
+
return {
|
|
1012
|
+
clean,
|
|
1013
|
+
directive: clean
|
|
1014
|
+
? null
|
|
1015
|
+
: `[recovery] Sesi sebelumnya berhenti tak-sempurna. Ikuti aturan ini:\n${blocks.join("\n")}`,
|
|
1016
|
+
warnings,
|
|
1017
|
+
attention,
|
|
1018
|
+
stitched,
|
|
1019
|
+
stats,
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
function toItem(first: JournalRecord, state: "pending" | "committed" | "failed"): AttentionItem {
|
|
1024
|
+
return {
|
|
1025
|
+
id: first.id,
|
|
1026
|
+
seq: first.seq,
|
|
1027
|
+
tool: first.tool,
|
|
1028
|
+
state,
|
|
1029
|
+
remote: first.remote === true,
|
|
1030
|
+
paths: first.paths ?? [],
|
|
1031
|
+
...(first.childSessionId ? { childSessionId: first.childSessionId } : {}),
|
|
1032
|
+
turn: first.turn ?? null,
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
// ── Wiring event (titik D: execution:started/completed) ──
|
|
1037
|
+
|
|
1038
|
+
interface EventBusLike {
|
|
1039
|
+
on(type: string, handler: (event: never) => void): () => void
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
interface SessionLike {
|
|
1043
|
+
events: EventBusLike
|
|
1044
|
+
state?: { turnCount?: number }
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
interface ExecutionEvent {
|
|
1048
|
+
execution?: {
|
|
1049
|
+
call?: { name?: unknown; args?: unknown; id?: unknown }
|
|
1050
|
+
result?: { isError?: unknown }
|
|
1051
|
+
}
|
|
1052
|
+
/** Ditandai task.ts saat event child di-forward ke bus parent: catat di
|
|
1053
|
+
* jurnal ANAK saja (bus asal), bukan ganda di parent. Checkpoint, trace,
|
|
1054
|
+
* dan UI tetap mengonsumsi event forward seperti biasa. */
|
|
1055
|
+
forwardedChild?: unknown
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
/**
|
|
1059
|
+
* Pasang jurnal pada sesi apa pun (parent maupun anak). Total: kegagalan
|
|
1060
|
+
* I/O jurnal tak pernah melempar ke bus turn (degraded-loud).
|
|
1061
|
+
*/
|
|
1062
|
+
export function attachMutationJournal(
|
|
1063
|
+
session: SessionLike,
|
|
1064
|
+
opts: { sessionId: string; cwd?: string; childOf?: string },
|
|
1065
|
+
): void {
|
|
1066
|
+
const root = resolve(opts.cwd ?? process.cwd())
|
|
1067
|
+
// Eager creation (AUDIT #01E §1): file jurnal dibuat saat wiring dipasang
|
|
1068
|
+
// — SEBELUM mutasi pertama — agar ABSENT vs EMPTY dapat dibedakan saat
|
|
1069
|
+
// resume (absent = bukti hilang; empty = sesi ada, belum bermutasi).
|
|
1070
|
+
// Create-if-absent ("wx"): tak menimpa file existing, tak menulis record
|
|
1071
|
+
// palsu; balapan dengan append pertama aman dari dua arah (append memakai
|
|
1072
|
+
// "a" yang juga membuat bila belum ada).
|
|
1073
|
+
// Fire-and-forget disengaja: attach sinkron; kegagalan → degraded-loud,
|
|
1074
|
+
// BUKAN sesi gagal start.
|
|
1075
|
+
void (async () => {
|
|
1076
|
+
const path = journalPath(opts.sessionId, root)
|
|
1077
|
+
try {
|
|
1078
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 }).catch(() => {})
|
|
1079
|
+
const h = await open(path, "wx", 0o600)
|
|
1080
|
+
try {
|
|
1081
|
+
await h.sync().catch(() => {})
|
|
1082
|
+
} finally {
|
|
1083
|
+
await h.close().catch(() => {})
|
|
1084
|
+
}
|
|
1085
|
+
} catch (e) {
|
|
1086
|
+
// EEXIST = file sudah ada (normal). Sisanya = degraded (bukan empty!).
|
|
1087
|
+
if ((e as NodeJS.ErrnoException)?.code !== "EEXIST") {
|
|
1088
|
+
markDegraded(opts.sessionId, root, `eager create gagal: ${(e as Error).message}`)
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
})()
|
|
1092
|
+
// toolCallId → ANTRE intent (FIFO). Started ganda id sama (retry/duplikat)
|
|
1093
|
+
// tak boleh saling menimpa: completed mengambil pasangan TERTUA yang belum
|
|
1094
|
+
// berpasangan. Map-overwrite = terminal salah pasangan = pending hantu.
|
|
1095
|
+
const inflight = new Map<string, Promise<JournalRecord>[]>()
|
|
1096
|
+
const turnOf = (): number | null => {
|
|
1097
|
+
try {
|
|
1098
|
+
const n = session.state?.turnCount
|
|
1099
|
+
return typeof n === "number" ? n : null
|
|
1100
|
+
} catch {
|
|
1101
|
+
return null
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
session.events.on("execution:started", (e) => {
|
|
1105
|
+
const ev = e as unknown as ExecutionEvent
|
|
1106
|
+
// Forward dari child: ground truth ada di jurnal anak (bus asal).
|
|
1107
|
+
// Mencatatnya juga di sini = bukti ganda (satu efek, dua id/sesi).
|
|
1108
|
+
if (ev.forwardedChild != null) return
|
|
1109
|
+
const name = typeof ev.execution?.call?.name === "string" ? ev.execution.call.name : ""
|
|
1110
|
+
if (!name || NO_AUTO_JOURNAL.has(name) || !isMutationTool(name)) return
|
|
1111
|
+
const callId =
|
|
1112
|
+
typeof ev.execution?.call?.id === "string" ? (ev.execution.call.id as string) : ""
|
|
1113
|
+
const base = name.includes(".") ? "mcp_call" : name
|
|
1114
|
+
const args = (ev.execution?.call?.args ?? {}) as Record<string, unknown>
|
|
1115
|
+
// Daftarkan promise SEBELUM await: completed dijamin datang sesudah
|
|
1116
|
+
// started, dan kini pasti menunggu intent selesai dulu.
|
|
1117
|
+
const intentP = appendMutationIntent({
|
|
1118
|
+
session: opts.sessionId,
|
|
1119
|
+
...(opts.childOf ? { childOf: opts.childOf } : {}),
|
|
1120
|
+
turn: turnOf(),
|
|
1121
|
+
tool: name,
|
|
1122
|
+
...(base === "mcp_call" ? { remote: true as const } : {}),
|
|
1123
|
+
...(base === "code_run" ? { backend: process.env.MINICODE_SANDBOX || "none" } : {}),
|
|
1124
|
+
cwd: root,
|
|
1125
|
+
paths: verifyPaths(base, args, root),
|
|
1126
|
+
argsHash: hashArgs(args),
|
|
1127
|
+
})
|
|
1128
|
+
if (callId) {
|
|
1129
|
+
const q = inflight.get(callId) ?? []
|
|
1130
|
+
q.push(
|
|
1131
|
+
intentP.catch((err) => {
|
|
1132
|
+
process.stderr.write(`[warn] journal: intent failed: ${(err as Error).message}\n`)
|
|
1133
|
+
throw err
|
|
1134
|
+
}),
|
|
1135
|
+
)
|
|
1136
|
+
inflight.set(callId, q)
|
|
1137
|
+
}
|
|
1138
|
+
void intentP.catch((err) => {
|
|
1139
|
+
process.stderr.write(`[warn] journal: intent failed: ${(err as Error).message}\n`)
|
|
1140
|
+
})
|
|
1141
|
+
})
|
|
1142
|
+
session.events.on("execution:completed", (e) => {
|
|
1143
|
+
void (async () => {
|
|
1144
|
+
try {
|
|
1145
|
+
const ev = e as unknown as ExecutionEvent
|
|
1146
|
+
if (ev.forwardedChild != null) return
|
|
1147
|
+
const name = typeof ev.execution?.call?.name === "string" ? ev.execution.call.name : ""
|
|
1148
|
+
if (!name || NO_AUTO_JOURNAL.has(name) || !isMutationTool(name)) return
|
|
1149
|
+
const callId =
|
|
1150
|
+
typeof ev.execution?.call?.id === "string" ? (ev.execution.call.id as string) : ""
|
|
1151
|
+
const q = callId ? (inflight.get(callId) ?? []) : []
|
|
1152
|
+
const found = q.length > 0 ? await q.shift()!.catch(() => undefined) : undefined
|
|
1153
|
+
if (callId && q.length === 0) inflight.delete(callId)
|
|
1154
|
+
// Tanpa pasangan intent (mis. intent gagal tulis / degraded): jangan
|
|
1155
|
+
// karang terminal yatim — biarkan absen (jalur advisory + warn).
|
|
1156
|
+
if (!found) return
|
|
1157
|
+
const failed = ev.execution?.result?.isError === true
|
|
1158
|
+
let note: string | undefined
|
|
1159
|
+
if (base_of(name) === "mcp_call") {
|
|
1160
|
+
const a = (ev.execution?.call?.args ?? {}) as Record<string, unknown>
|
|
1161
|
+
const srv = typeof a.server === "string" ? a.server : ""
|
|
1162
|
+
const t =
|
|
1163
|
+
typeof a.tool === "string"
|
|
1164
|
+
? a.tool
|
|
1165
|
+
: name.includes(".")
|
|
1166
|
+
? name.split(".").slice(1).join(".")
|
|
1167
|
+
: ""
|
|
1168
|
+
if (srv || t) note = `${srv ? `${srv}.` : ""}${t}`
|
|
1169
|
+
}
|
|
1170
|
+
await appendMutationTerminal(
|
|
1171
|
+
opts.sessionId,
|
|
1172
|
+
root,
|
|
1173
|
+
found.id,
|
|
1174
|
+
found.seq,
|
|
1175
|
+
found.tool,
|
|
1176
|
+
failed ? "failed" : "committed",
|
|
1177
|
+
note ? { note } : undefined,
|
|
1178
|
+
)
|
|
1179
|
+
} catch (err) {
|
|
1180
|
+
process.stderr.write(`[warn] journal: terminal failed: ${(err as Error).message}\n`)
|
|
1181
|
+
}
|
|
1182
|
+
})()
|
|
1183
|
+
})
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
function base_of(name: string): string {
|
|
1187
|
+
return name.includes(".") ? "mcp_call" : name
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
// ── Resume: muat jurnal (+anak) → putuskan ──
|
|
1191
|
+
|
|
1192
|
+
export interface RecoveryInput {
|
|
1193
|
+
directive: string | null
|
|
1194
|
+
warnings: string[]
|
|
1195
|
+
clean: boolean
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
/**
|
|
1199
|
+
* Delegasi committed sejak timestamp: dipakai peringatan turn-gagal ("efek
|
|
1200
|
+
* anak tetap ada walau riwayat bersih"). Kembalikan childSessionId + seq + ts.
|
|
1201
|
+
* Murni baca; tak pernah melempar (gagal baca = [] + warn stderr).
|
|
1202
|
+
*/
|
|
1203
|
+
export async function committedDelegatesSince(
|
|
1204
|
+
sessionId: string,
|
|
1205
|
+
cwd: string | undefined,
|
|
1206
|
+
sinceTs: number,
|
|
1207
|
+
): Promise<{ childSessionId: string; seq: number; ts: number }[]> {
|
|
1208
|
+
try {
|
|
1209
|
+
const { records } = await loadJournal(sessionId, cwd)
|
|
1210
|
+
// Tautan dari terminal, fallback ke intent se-id (jurnal lama).
|
|
1211
|
+
const intentChild = new Map<string, string>()
|
|
1212
|
+
for (const r of records) {
|
|
1213
|
+
if (r.tool === "delegate_task" && r.childSessionId && r.state === "pending") {
|
|
1214
|
+
intentChild.set(r.id, r.childSessionId)
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
const out: { childSessionId: string; seq: number; ts: number }[] = []
|
|
1218
|
+
for (const r of records) {
|
|
1219
|
+
if (r.tool !== "delegate_task" || r.state !== "committed") continue
|
|
1220
|
+
const cid = r.childSessionId ?? intentChild.get(r.id)
|
|
1221
|
+
if (!cid) continue
|
|
1222
|
+
if (typeof r.ts !== "number" || r.ts < sinceTs) continue
|
|
1223
|
+
out.push({ childSessionId: cid, seq: r.seq, ts: r.ts })
|
|
1224
|
+
}
|
|
1225
|
+
return out.sort((a, b) => a.seq - b.seq)
|
|
1226
|
+
} catch (e) {
|
|
1227
|
+
process.stderr.write(
|
|
1228
|
+
`[warn] journal: committedDelegatesSince failed: ${(e as Error).message}\n`,
|
|
1229
|
+
)
|
|
1230
|
+
return []
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
|
|
1234
|
+
/**
|
|
1235
|
+
* Rencana recovery untuk satu sesi: jurnal sendiri + jurnal anak yang dirujuk
|
|
1236
|
+
* record delegasi. Murni baca; keputusan via decideRecovery (tanpa I/O).
|
|
1237
|
+
*/
|
|
1238
|
+
export async function planRecoveryForSession(
|
|
1239
|
+
sessionId: string,
|
|
1240
|
+
cwd?: string,
|
|
1241
|
+
opts: { includeChildren?: boolean; maxItems?: number; persistedTurns?: number[] } = {},
|
|
1242
|
+
): Promise<RecoveryInput & { stats: RecoveryPlan["stats"] }> {
|
|
1243
|
+
const warnings: string[] = []
|
|
1244
|
+
try {
|
|
1245
|
+
const root = resolve(cwd ?? process.cwd())
|
|
1246
|
+
const main = await loadJournal(sessionId, root)
|
|
1247
|
+
warnings.push(...main.warnings)
|
|
1248
|
+
let records = [...main.records]
|
|
1249
|
+
if (main.quarantined) {
|
|
1250
|
+
warnings.push("journal utama dikarantina — keputusan dari prefix valid + advisory")
|
|
1251
|
+
}
|
|
1252
|
+
if (opts.includeChildren !== false) {
|
|
1253
|
+
const childIds = [
|
|
1254
|
+
...new Set(
|
|
1255
|
+
main.records
|
|
1256
|
+
.filter((r) => r.tool === "delegate_task" && r.childSessionId)
|
|
1257
|
+
.map((r) => r.childSessionId as string),
|
|
1258
|
+
),
|
|
1259
|
+
].slice(0, 10)
|
|
1260
|
+
// Status terminal delegasi parent per anak: hanya committed yang
|
|
1261
|
+
// menjadi bukti anak "seharusnya ada" (failed/pending = anak boleh
|
|
1262
|
+
// tak lahir → absen adalah normal, bukan anomali). Tautan diambil
|
|
1263
|
+
// dari terminal, fallback ke intent se-id (jurnal lama).
|
|
1264
|
+
const intentChild = new Map<string, string>()
|
|
1265
|
+
for (const r of main.records) {
|
|
1266
|
+
if (r.tool === "delegate_task" && r.childSessionId && r.state === "pending") {
|
|
1267
|
+
intentChild.set(r.id, r.childSessionId)
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
const delegateDone = new Set<string>()
|
|
1271
|
+
for (const r of main.records) {
|
|
1272
|
+
if (r.tool !== "delegate_task" || r.state !== "committed") continue
|
|
1273
|
+
const cid = r.childSessionId ?? intentChild.get(r.id)
|
|
1274
|
+
if (cid) delegateDone.add(cid)
|
|
1275
|
+
}
|
|
1276
|
+
const degraded: string[] = []
|
|
1277
|
+
for (const cid of childIds) {
|
|
1278
|
+
const child = await loadJournal(cid, root).catch(
|
|
1279
|
+
(e): JournalLoad => ({
|
|
1280
|
+
records: [],
|
|
1281
|
+
warnings: [`jurnal anak ${cid} gagal dimuat: ${(e as Error).message}`],
|
|
1282
|
+
truncatedTail: false,
|
|
1283
|
+
quarantined: false,
|
|
1284
|
+
status: "unreadable",
|
|
1285
|
+
}),
|
|
1286
|
+
)
|
|
1287
|
+
warnings.push(...child.warnings.map((w) => `child ${cid}: ${w}`))
|
|
1288
|
+
switch (child.status) {
|
|
1289
|
+
case "absent":
|
|
1290
|
+
// Bukti parent committed + file tak ada = bukti HILANG (degraded).
|
|
1291
|
+
// Parent failed/pending = anak boleh tak lahir → sunyi (normal).
|
|
1292
|
+
if (delegateDone.has(cid)) {
|
|
1293
|
+
degraded.push(
|
|
1294
|
+
`jurnal anak ${cid} SEHARUSNYA ADA (delegasi committed) tetapi file tak ditemukan — bukti tak-lengkap, jangan asumsikan efek anak ada/tidak-ada`,
|
|
1295
|
+
)
|
|
1296
|
+
}
|
|
1297
|
+
break
|
|
1298
|
+
case "unreadable":
|
|
1299
|
+
// File ada tetapi tak terbaca = anomali dalam kondisi apa pun.
|
|
1300
|
+
degraded.push(
|
|
1301
|
+
`jurnal anak ${cid} TAK TERBACA — bukti tak-lengkap, jangan asumsikan efek anak ada/tidak-ada`,
|
|
1302
|
+
)
|
|
1303
|
+
break
|
|
1304
|
+
case "empty":
|
|
1305
|
+
// Anak terpasang tetapi nol mutasi = normal, bukan anomali.
|
|
1306
|
+
break
|
|
1307
|
+
default:
|
|
1308
|
+
records = records.concat(child.records)
|
|
1309
|
+
break
|
|
1310
|
+
}
|
|
1311
|
+
if (child.quarantined) {
|
|
1312
|
+
warnings.push(
|
|
1313
|
+
`child ${cid}: journal dikarantina — keputusan dari prefix valid + advisory`,
|
|
1314
|
+
)
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
// Degraded evidence = bagian direktif (non-blocking, informatif) agar
|
|
1318
|
+
// model tak membangun di atas ketiadaan bukti + warnings user-visible.
|
|
1319
|
+
if (degraded.length > 0) {
|
|
1320
|
+
const extra = `[recovery] BUKTI TAK-LENGKAP (degraded, bukan blokir):\n${degraded.map((d) => `- ${d}`).join("\n")}`
|
|
1321
|
+
warnings.push(...degraded)
|
|
1322
|
+
const base = decideRecovery(records, opts.persistedTurns ?? [], { maxItems: opts.maxItems })
|
|
1323
|
+
warnings.push(...base.warnings)
|
|
1324
|
+
const directive = base.directive ? `${base.directive}\n${extra}` : extra
|
|
1325
|
+
if (!isJournalHealthy(sessionId, root)) {
|
|
1326
|
+
warnings.push("journal degraded (tulis gagal sebelumnya) — anggap catatan tak-lengkap")
|
|
1327
|
+
}
|
|
1328
|
+
return { directive, warnings, clean: false, stats: base.stats }
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
// Turn durable dipasok pemanggil (persistence.listPersistedTurns) agar
|
|
1332
|
+
// modul ini tak bergantung modul persistence (anti cycle-import).
|
|
1333
|
+
const plan = decideRecovery(records, opts.persistedTurns ?? [], { maxItems: opts.maxItems })
|
|
1334
|
+
warnings.push(...plan.warnings)
|
|
1335
|
+
if (!isJournalHealthy(sessionId, root)) {
|
|
1336
|
+
warnings.push("journal degraded (tulis gagal sebelumnya) — anggap catatan tak-lengkap")
|
|
1337
|
+
}
|
|
1338
|
+
return { directive: plan.directive, warnings, clean: plan.clean, stats: plan.stats }
|
|
1339
|
+
} catch (e) {
|
|
1340
|
+
return {
|
|
1341
|
+
directive: null,
|
|
1342
|
+
warnings: [`recovery journal gagal dimuat: ${(e as Error).message} — lanjut jalur advisory`],
|
|
1343
|
+
clean: false,
|
|
1344
|
+
stats: { pending: 0, failed: 0, committed: 0, finalized: 0, markers: 0 },
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
}
|