minicode-ai 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/AGENTS.md +45 -0
  2. package/CHANGELOG.md +59 -4
  3. package/PLAN.md +491 -0
  4. package/README.md +2 -2
  5. package/cli/commands/acp.ts +485 -0
  6. package/cli/commands/auth.ts +7 -4
  7. package/cli/commands/config.ts +41 -27
  8. package/cli/commands/exec.ts +33 -12
  9. package/cli/commands/mcp.ts +3 -2
  10. package/cli/commands/memory.ts +1 -1
  11. package/cli/commands/pricing.ts +6 -4
  12. package/cli/commands/providers.ts +18 -8
  13. package/cli/commands/sessions.ts +11 -4
  14. package/cli/commands/skills.ts +3 -3
  15. package/cli/commands/stats.ts +3 -1
  16. package/cli/commands.ts +6 -0
  17. package/cli/index.ts +82 -57
  18. package/cli/model-manager.ts +6 -1
  19. package/cli/router.ts +7 -0
  20. package/cli/setup.ts +341 -5
  21. package/cli/tui.ts +54 -18
  22. package/docs/ARCHITECTURE.html +29 -22
  23. package/docs/CONTROL-PLANE-MAP.md +139 -0
  24. package/docs/HARNESS.md +150 -0
  25. package/docs/PLAN_UIUX_V6.md +209 -0
  26. package/docs/README.md +1 -1
  27. package/docs/SUMMARY.md +52 -0
  28. package/docs/TERMINAL_CONTRACT.md +367 -0
  29. package/docs/UI_RENDER_PIPELINE.md +165 -0
  30. package/docs/USAGE.md +11 -0
  31. package/docs/agents.md +31 -0
  32. package/docs/architecture.md +3 -3
  33. package/docs/choosing-mode.md +34 -0
  34. package/docs/cli.md +130 -0
  35. package/docs/concepts.md +53 -0
  36. package/docs/config-providers.md +87 -0
  37. package/docs/config.md +63 -0
  38. package/docs/contributing.md +79 -0
  39. package/docs/environment.md +95 -0
  40. package/docs/exec.md +73 -0
  41. package/docs/getting-started.md +102 -0
  42. package/docs/glossary.md +37 -0
  43. package/docs/mcp-lsp.md +54 -0
  44. package/docs/memory-sessions.md +63 -0
  45. package/docs/policy-sandbox.md +72 -0
  46. package/docs/pricing-budget.md +49 -0
  47. package/docs/quickstart.md +60 -0
  48. package/docs/repl.md +67 -0
  49. package/docs/security-model.md +95 -0
  50. package/docs/security.md +91 -0
  51. package/docs/skills.md +48 -0
  52. package/docs/terminal.md +79 -0
  53. package/docs/tools.md +123 -0
  54. package/docs/troubleshooting.md +40 -0
  55. package/docs/verify-benchmark.md +58 -0
  56. package/package.json +8 -5
  57. package/src/app/provider-layer.ts +12 -4
  58. package/src/app/session.ts +6 -0
  59. package/src/app/tool-layer.ts +2 -1
  60. package/src/constants.ts +35 -0
  61. package/src/lib/net.ts +6 -1
  62. package/src/lsp/client.ts +41 -8
  63. package/src/mcp/http-transport.ts +52 -15
  64. package/src/mcp/transport.ts +32 -1
  65. package/src/memory/files.ts +6 -5
  66. package/src/policy/allowlist.ts +1 -1
  67. package/src/policy/bash-guard.ts +154 -14
  68. package/src/policy/compaction.ts +57 -3
  69. package/src/policy/context.ts +4 -0
  70. package/src/policy/jail.ts +49 -4
  71. package/src/policy/permission.ts +152 -12
  72. package/src/policy/pricing.ts +12 -9
  73. package/src/presentation/adapter.ts +721 -0
  74. package/src/presentation/events.ts +324 -0
  75. package/src/presentation/label.ts +140 -0
  76. package/src/presentation/model.ts +172 -0
  77. package/src/presentation/reducer.ts +486 -0
  78. package/src/presentation/store.ts +256 -0
  79. package/src/providers/anthropic.ts +22 -4
  80. package/src/providers/detect.ts +2 -1
  81. package/src/providers/router.ts +13 -0
  82. package/src/repo/repomap.ts +2 -29
  83. package/src/session/checkpoint.ts +27 -9
  84. package/src/session/journal.ts +27 -5
  85. package/src/skills/loader.ts +88 -5
  86. package/src/telemetry/trace.ts +36 -15
  87. package/src/tools/ask_user.ts +73 -4
  88. package/src/tools/bash.ts +15 -17
  89. package/src/tools/glob.ts +10 -11
  90. package/src/tools/lsp.ts +3 -56
  91. package/src/tools/memory.ts +13 -12
  92. package/src/tools/task.ts +1 -0
  93. package/src/ui/approval/prompt.ts +14 -6
  94. package/src/ui/assistant/simple.ts +137 -26
  95. package/src/ui/assistant/turn-status.ts +16 -3
  96. package/src/ui/contract.ts +119 -0
  97. package/src/ui/footer.ts +21 -2
  98. package/src/ui/i18n/en.ts +34 -6
  99. package/src/ui/i18n/id.ts +34 -6
  100. package/src/ui/i18n/locale.ts +3 -1
  101. package/src/ui/input/input.ts +51 -4
  102. package/src/ui/input/prompt-engine.ts +46 -4
  103. package/src/ui/render/collapse.ts +13 -13
  104. package/src/ui/render/diff.ts +7 -2
  105. package/src/ui/render/format.ts +16 -8
  106. package/src/ui/render/highlight.ts +7 -3
  107. package/src/ui/render/markdown.ts +5 -1
  108. package/src/ui/render/sanitize.ts +29 -2
  109. package/src/ui/render/table.ts +8 -5
  110. package/src/ui/render/theme.ts +18 -4
  111. package/src/ui/render/width.ts +89 -10
  112. package/src/ui/runtime/motion.ts +16 -0
  113. package/src/ui/runtime/screen.ts +45 -0
  114. package/src/ui/runtime/spinner.ts +50 -4
  115. package/src/ui/runtime/statusline.ts +50 -1
  116. package/src/ui/screens/form.ts +42 -15
  117. package/src/ui/screens/model-manager.ts +26 -18
  118. package/src/ui/screens/picker.ts +47 -23
  119. package/src/ui/screens/provider-manager.ts +18 -12
  120. package/src/ui/screens/wizard.ts +24 -8
  121. package/src/ui/tui/app.ts +233 -27
  122. package/src/ui/tui/transcript.ts +269 -65
  123. package/vendor/minicore/LICENSE +21 -0
  124. package/vendor/minicore/VENDOR.md +6 -3
  125. package/vendor/minicore/package.json +6 -3
  126. package/vendor/minicore/src/core/loop.ts +12 -2
  127. package/vendor/minicore/src/core/snapshot.ts +4 -0
  128. package/vendor/minicore/src/providers/openai-compat.ts +76 -25
@@ -0,0 +1,256 @@
1
+ // Content Store V2.1 (§16 plan / §21 architecture) — sibling model, non-otoritatif.
2
+ //
3
+ // Kenapa terpisah: PresentationState hanya menyimpan ContentRef (pointer);
4
+ // isi besar (output tool, diff, reasoning) hidup di sini dengan retensi FIFO
5
+ // yang adil untuk sesi panjang. Reducer TIDAK PERNAH membaca store untuk
6
+ // keputusan (I-A04) — store hanya dilayani expand/proyeksi.
7
+ //
8
+ // Basar angka = collapse.ts:24-25 (200K per-entry / 500K total) — dipertahankan
9
+ // sebagai awal, bukan angka magis baru. Evict = FIFO tertua + tandai dead
10
+ // (bukan hapus diam-diam): proyeksi menampilkan penanda retensi, bukan string
11
+ // kosong yang menyesatkan.
12
+ //
13
+ // Durable fallback: resolve miss → loader inject (sqlite messages, tool result
14
+ // full) bila kind=output; reasoning di luar retensi = hilang dengan penanda
15
+ // (jujur). Restart: store kosong; expandRef lama → fallback durable.
16
+ //
17
+ // Pola potong (surrogate-safe + splitTrailingEscape) DIUlang di sini (bukan
18
+ // impor src/ui — boundary src/** non-ui dilarang impor src/ui). Pola sama
19
+ // dengan collapse.ts:66-71; trigonometri escape disederhanakan untuk kasus
20
+ // tail yang mungkin terpotong.
21
+
22
+ import type { ContentRef } from "./events.ts"
23
+
24
+ /** Cap per-entry — baseline collapse.ts MAX_SECTION_CHARS. */
25
+ export const MAX_SECTION_CHARS = 200_000
26
+ /** Cap total store — baseline collapse.ts MAX_BUFFER_TOTAL. */
27
+ export const MAX_BUFFER_TOTAL = 500_000
28
+
29
+ export type ContentKind = "output" | "diff" | "reasoning" | "diagnostic"
30
+
31
+ export interface ContentMeta {
32
+ kind: ContentKind
33
+ /** Stream asal (kontrak Unix dipertahankan saat /expand mencetak). */
34
+ stream: "stdout" | "stderr"
35
+ truncated: boolean
36
+ /** Sumber konten saat resolve: store in-memory | durable sqlite | penanda retensi. */
37
+ source?: "store" | "durable" | "retention"
38
+ }
39
+
40
+ export interface ContentEntry {
41
+ ref?: ContentRef
42
+ text: string
43
+ meta: ContentMeta
44
+ }
45
+
46
+ export interface ContentStore {
47
+ put(ref: ContentRef, text: string, meta: ContentMeta): void
48
+ get(ref: ContentRef): ContentEntry | undefined
49
+ /** Tandai ref ter-evict (dipanggil otomatis saat FIFO melepas entry). */
50
+ markDead(ref: ContentRef): void
51
+ isDead(ref: ContentRef): boolean
52
+ /**
53
+ * Ambil konten: hit store → miss + kind output → durable loader → miss →
54
+ * penanda retensi (bila pernah dead) / undefined (tak pernah ada).
55
+ */
56
+ resolve(
57
+ ref: ContentRef,
58
+ durable?: (toolCallId: string) => string | undefined,
59
+ ): ContentEntry | undefined
60
+ /** Semua idx untuk satu toolCallId (urut idx), sudah di-resolve. */
61
+ expand(toolCallId: string, durable?: (toolCallId: string) => string | undefined): ContentEntry[]
62
+ /** Semua entry store yang masih hidup, insertion order (query /expand tanpa id). */
63
+ expandAll(): ContentEntry[]
64
+ clear(): void
65
+ stats(): { entries: number; totalChars: number; dead: number }
66
+ }
67
+
68
+ export function contentKey(ref: ContentRef): string {
69
+ return `${ref.toolCallId}#${ref.idx}`
70
+ }
71
+
72
+ /** Potong aman: jangan belah surrogate pair, jangan sisakan ekor escape parsial. */
73
+ function trimToCap(text: string): string {
74
+ if (text.length <= MAX_SECTION_CHARS) return splitTrailingEscape(text).head
75
+ let cut = text.slice(0, MAX_SECTION_CHARS)
76
+ const last = cut.charCodeAt(cut.length - 1)
77
+ if (cut.length > 0 && last >= 0xd800 && last <= 0xdbff) cut = cut.slice(0, -1)
78
+ return splitTrailingEscape(cut).head
79
+ }
80
+
81
+ /** Pola sanitize.ts splitTrailingEscape — lokal (boundary presentation). */
82
+ function splitTrailingEscape(s: string): { head: string; tail: string } {
83
+ const idx = s.lastIndexOf("\x1b")
84
+ if (idx === -1) return { head: s, tail: "" }
85
+ const next = s[idx + 1]
86
+ if (next === undefined) return { head: s.slice(0, idx), tail: s.slice(idx) }
87
+ if (next === "[") {
88
+ let j = idx + 2
89
+ while (j < s.length) {
90
+ const code = s.charCodeAt(j)
91
+ const ok = (code >= 0x30 && code <= 0x3f) || (code >= 0x21 && code <= 0x2f)
92
+ if (!ok) break
93
+ j++
94
+ }
95
+ // CSI diakhiri byte final 0x40–0x7E; bila string habis sebelum itu → tahan.
96
+ if (j >= s.length) return { head: s.slice(0, idx), tail: s.slice(idx) }
97
+ return { head: s, tail: "" }
98
+ }
99
+ if (next === "]" || next === "P" || next === "_" || next === "^" || next === "X") {
100
+ // OSC/DCS/APC/PM/SOS: lengkap bila ada terminator BEL atau ESC \.
101
+ const rest = s.slice(idx + 2)
102
+ const bel = String.fromCharCode(7)
103
+ if (!rest.includes(bel) && !rest.includes("\x1b\\")) {
104
+ return { head: s.slice(0, idx), tail: s.slice(idx) }
105
+ }
106
+ return { head: s, tail: "" }
107
+ }
108
+ return { head: s, tail: "" }
109
+ }
110
+
111
+ /**
112
+ * Content store in-memory FIFO. Satu instance per sesi (composition root);
113
+ * kosong saat restart (durability = sqlite, bukan store).
114
+ */
115
+ export function createContentStore(): ContentStore {
116
+ // Map = insertion order = urutan FIFO untuk evict tertua.
117
+ const entries = new Map<string, ContentEntry>()
118
+ const dead = new Set<string>()
119
+ let totalChars = 0
120
+
121
+ const evictIfNeeded = (): void => {
122
+ // Buang tertua sampai total dalam budget — terbaru selalu dipertahankan.
123
+ while (totalChars > MAX_BUFFER_TOTAL && entries.size > 0) {
124
+ const oldestKey = entries.keys().next().value
125
+ if (oldestKey === undefined) break
126
+ const old = entries.get(oldestKey)
127
+ entries.delete(oldestKey)
128
+ if (old) totalChars -= old.text.length
129
+ dead.add(oldestKey)
130
+ }
131
+ }
132
+
133
+ return {
134
+ put(ref, text, meta) {
135
+ if (!text) return
136
+ const key = contentKey(ref)
137
+ const prev = entries.get(key)
138
+ if (prev) totalChars -= prev.text.length
139
+ const cut = trimToCap(text)
140
+ entries.set(key, {
141
+ ref: { toolCallId: ref.toolCallId, idx: ref.idx },
142
+ text: cut,
143
+ meta: { ...meta, truncated: meta.truncated || cut.length < text.length },
144
+ })
145
+ totalChars += cut.length
146
+ dead.delete(key)
147
+ evictIfNeeded()
148
+ },
149
+ get(ref) {
150
+ const hit = entries.get(contentKey(ref))
151
+ if (hit) return { ref: hit.ref, text: hit.text, meta: { ...hit.meta, source: "store" } }
152
+ return undefined
153
+ },
154
+ markDead(ref) {
155
+ const key = contentKey(ref)
156
+ const hit = entries.get(key)
157
+ if (hit) {
158
+ entries.delete(key)
159
+ totalChars -= hit.text.length
160
+ }
161
+ dead.add(key)
162
+ },
163
+ isDead(ref) {
164
+ return dead.has(contentKey(ref))
165
+ },
166
+ resolve(ref, durable) {
167
+ const local = entries.get(contentKey(ref))
168
+ if (local)
169
+ return { ref: local.ref, text: local.text, meta: { ...local.meta, source: "store" } }
170
+ // Fallback durable HANYA untuk output (reasoning di luar retensi = hilang).
171
+ if (durable) {
172
+ const text = durable(ref.toolCallId)
173
+ if (text != null && text !== "") {
174
+ return {
175
+ text,
176
+ meta: {
177
+ kind: "output",
178
+ stream: "stderr",
179
+ truncated: false,
180
+ source: "durable",
181
+ },
182
+ }
183
+ }
184
+ }
185
+ if (dead.has(contentKey(ref))) {
186
+ return {
187
+ text: "",
188
+ meta: {
189
+ kind: "output",
190
+ stream: "stderr",
191
+ truncated: false,
192
+ source: "retention",
193
+ },
194
+ }
195
+ }
196
+ return undefined
197
+ },
198
+ expand(toolCallId, durable) {
199
+ const prefix = `${toolCallId}#`
200
+ const keys = [...entries.keys()].filter((k) => k.startsWith(prefix)).sort()
201
+ const out: ContentEntry[] = []
202
+ for (const k of keys) {
203
+ const hit = entries.get(k)
204
+ if (hit) out.push({ ref: hit.ref, text: hit.text, meta: { ...hit.meta, source: "store" } })
205
+ }
206
+ if (out.length > 0) return out
207
+ // Miss total: durable → retention (bila pernah ada & ter-evict).
208
+ if (durable) {
209
+ const text = durable(toolCallId)
210
+ if (text != null && text !== "") {
211
+ return [
212
+ {
213
+ text,
214
+ meta: {
215
+ kind: "output",
216
+ stream: "stderr",
217
+ truncated: false,
218
+ source: "durable",
219
+ },
220
+ },
221
+ ]
222
+ }
223
+ }
224
+ const anyDead = [...dead].some((k) => k.startsWith(prefix))
225
+ if (anyDead) {
226
+ return [
227
+ {
228
+ text: "",
229
+ meta: {
230
+ kind: "output",
231
+ stream: "stderr",
232
+ truncated: false,
233
+ source: "retention",
234
+ },
235
+ },
236
+ ]
237
+ }
238
+ return []
239
+ },
240
+ expandAll() {
241
+ return [...entries.values()].map((entry) => ({
242
+ ref: entry.ref,
243
+ text: entry.text,
244
+ meta: { ...entry.meta, source: "store" as const },
245
+ }))
246
+ },
247
+ clear() {
248
+ entries.clear()
249
+ dead.clear()
250
+ totalChars = 0
251
+ },
252
+ stats() {
253
+ return { entries: entries.size, totalChars, dead: dead.size }
254
+ },
255
+ }
256
+ }
@@ -244,14 +244,32 @@ function sniffImageMime(b: Uint8Array): string | null {
244
244
  return null
245
245
  }
246
246
 
247
- function toAnthropicMessages(messages: readonly Message[]): unknown[] {
248
- const out: unknown[] = []
247
+ export function toAnthropicMessages(messages: readonly Message[]): unknown[] {
248
+ const out: { role: string; content: unknown }[] = []
249
249
  let toolGroup:
250
250
  | { type: "tool_result"; tool_use_id: string; content: unknown; is_error?: boolean }[]
251
251
  | null = null
252
+
253
+ const pushUser = (content: unknown) => {
254
+ const last = out.length > 0 ? out[out.length - 1] : undefined
255
+ if (last && last.role === "user") {
256
+ // Invarian peran Anthropic: peran user↔assistant wajib bergantian.
257
+ // Bila turn sebelumnya sudah user (mis. prompt steering atau tool-result),
258
+ // satukan blok kontennya alih-alih melempar dua entri user berturut-turut.
259
+ const toBlocks = (val: unknown): unknown[] => {
260
+ if (Array.isArray(val)) return val
261
+ if (typeof val === "string") return [{ type: "text", text: val }]
262
+ return [{ type: "text", text: String(val) }]
263
+ }
264
+ last.content = [...toBlocks(last.content), ...toBlocks(content)]
265
+ } else {
266
+ out.push({ role: "user", content })
267
+ }
268
+ }
269
+
252
270
  const flushToolGroup = () => {
253
271
  if (toolGroup) {
254
- out.push({ role: "user", content: toolGroup })
272
+ pushUser(toolGroup)
255
273
  toolGroup = null
256
274
  }
257
275
  }
@@ -259,7 +277,7 @@ function toAnthropicMessages(messages: readonly Message[]): unknown[] {
259
277
  for (const m of messages) {
260
278
  if (m.role === "user") {
261
279
  flushToolGroup()
262
- out.push({ role: "user", content: toContent(m.content) })
280
+ pushUser(toContent(m.content))
263
281
  } else if (m.role === "assistant") {
264
282
  flushToolGroup()
265
283
  const content: unknown[] = []
@@ -109,8 +109,9 @@ export async function detectModels(
109
109
  : path.includes("anthropic")
110
110
  ? "anthropic"
111
111
  : "openai"
112
+ const uniqueModels = Array.from(new Set(models))
112
113
  const result = {
113
- models,
114
+ models: uniqueModels,
114
115
  providerHint: hint as DetectResult["providerHint"],
115
116
  authFailed: everAuthFailed,
116
117
  }
@@ -141,6 +141,7 @@ export function createRouterProvider(config: RouterConfig): ModelProvider {
141
141
  let current: ModelProvider | undefined = target
142
142
  while (current) {
143
143
  tried.add(current.id)
144
+ let hasYieldedContent = false
144
145
  try {
145
146
  // rate limit: tunggu token bucket sebelum tiap request
146
147
  if (config.limiter) await config.limiter.acquire()
@@ -169,11 +170,23 @@ export function createRouterProvider(config: RouterConfig): ModelProvider {
169
170
  }
170
171
  }
171
172
  for await (const ev of current.stream(req, signal)) {
173
+ // Tandai bila konten substantif sudah keluar ke caller: sekali konten
174
+ // keluar, stream tak bisa lagi di-fallback diam-diam ke provider lain
175
+ // karena akan menduplikasi respons dari awal di sisi user.
176
+ if (
177
+ ev.type === "text" ||
178
+ ev.type === "tool_call" ||
179
+ (ev.type === "extension" && ev.kind === "reasoning")
180
+ ) {
181
+ hasYieldedContent = true
182
+ }
172
183
  yield ev
173
184
  }
174
185
  return
175
186
  } catch (e) {
176
187
  if (e instanceof ProviderError) {
188
+ // Stream yang sudah separuh terkirim ke klien tidak boleh di-restart dari awal
189
+ if (hasYieldedContent) throw e
177
190
  // cap retryAfter without mutating original
178
191
  let err: ProviderError = e
179
192
  if (e.retryAfterMs != null && e.retryAfterMs > maxRetry) {
@@ -5,7 +5,7 @@ import { readdir, readFile, stat } from "node:fs/promises"
5
5
  import { join, relative, resolve } from "node:path"
6
6
  import { fileURLToPath } from "node:url"
7
7
  import { promisify } from "node:util"
8
- import { LIMITS } from "../constants.ts"
8
+ import { LIMITS, LSP_SYMBOL_KINDS } from "../constants.ts"
9
9
  import { homeDir } from "../lib/db-path.ts"
10
10
  import { GIT_SAFE_BASE } from "../lib/git-hardening.ts"
11
11
  import { resolveTrustedExecutable } from "../lib/trusted-exec.ts"
@@ -380,34 +380,7 @@ async function buildRepoMapLsp(cwd: string): Promise<string | null> {
380
380
  if (getConfiguredExts().length === 0) return null
381
381
  const symbols = await workspaceSymbols("", 4000, cwd)
382
382
  if (!symbols.length) return null
383
- const KIND = [
384
- "File",
385
- "Module",
386
- "Namespace",
387
- "Package",
388
- "Class",
389
- "Method",
390
- "Property",
391
- "Field",
392
- "Constructor",
393
- "Enum",
394
- "Interface",
395
- "Function",
396
- "Variable",
397
- "Constant",
398
- "String",
399
- "Number",
400
- "Boolean",
401
- "Array",
402
- "Object",
403
- "Key",
404
- "Null",
405
- "EnumMember",
406
- "Struct",
407
- "Event",
408
- "Operator",
409
- "TypeParameter",
410
- ]
383
+ const KIND = LSP_SYMBOL_KINDS
411
384
  const byFile = new Map<string, string[]>()
412
385
  for (const s of symbols.slice(0, 200)) {
413
386
  let file: string
@@ -376,12 +376,13 @@ async function applyCheckpoint(
376
376
  direction: "undo" | "redo",
377
377
  cwd: string,
378
378
  ): Promise<string[]> {
379
- const tree = direction === "undo" ? cp.treeBefore : (cp.treeAfter ?? cp.treeBefore)
379
+ const tree = direction === "undo" ? cp.treeBefore : cp.treeAfter
380
380
  if (tree) {
381
381
  const res = await restoreTree(cwd, tree)
382
382
  return [...res.applied, ...res.skipped.map((s) => `${s} (skipped)`)]
383
383
  }
384
- const snaps = direction === "undo" ? cp.snapshots : (cp.redoSnapshots ?? cp.snapshots)
384
+ const snaps = direction === "undo" ? cp.snapshots : cp.redoSnapshots
385
+ if (!snaps) throw new Error(`checkpoint ${cp.id} does not have ${direction} data`)
385
386
  return applySnapshots(snaps, cwd)
386
387
  }
387
388
 
@@ -397,6 +398,15 @@ export async function undoLastCheckpoint(
397
398
  }
398
399
 
399
400
  const targetCp = manifest.checkpoints[manifest.currentIndex]!
401
+ if (!targetCp.redoSnapshots && !targetCp.treeAfter && targetCp.snapshots) {
402
+ try {
403
+ const redoSnaps: FileSnapshot[] = []
404
+ for (const snap of targetCp.snapshots) {
405
+ redoSnaps.push(await captureFileSnapshot(resolve(cwd, snap.path), cwd))
406
+ }
407
+ targetCp.redoSnapshots = redoSnaps
408
+ } catch {}
409
+ }
400
410
  const restoredFiles = await applyCheckpoint(targetCp, "undo", cwd)
401
411
 
402
412
  // Urutan: marker DULU (bukti durable niat+hasil apply), pointer-disk
@@ -437,6 +447,13 @@ export async function redoLastCheckpoint(
437
447
  // mengaburkan jendela crash (pointer-memory vs pointer-disk berbeda).
438
448
  const targetIndex = manifest.currentIndex + 1
439
449
  const targetCp = manifest.checkpoints[targetIndex]!
450
+ if (!targetCp.treeAfter && !targetCp.redoSnapshots) {
451
+ return {
452
+ success: false,
453
+ reappliedFiles: [],
454
+ message: `checkpoint ${targetCp.id} (turn ${targetCp.turn}) does not have redo data`,
455
+ }
456
+ }
440
457
  const reappliedFiles = await applyCheckpoint(targetCp, "redo", cwd)
441
458
 
442
459
  await appendUndoMarker(sessionId, cwd, "redo", targetCp.turn, {
@@ -515,14 +532,15 @@ export async function reconcileUndoRedoPointer(
515
532
  return null
516
533
  }
517
534
  // Turn harus cocok: marker untuk susunan checkpoints yang berbeda
518
- // (eviksi/cabang lain) tak boleh diadopsi buta. newIndex -1 = "mundur
519
- // sebelum checkpoint pertama": cocokkan dengan checkpoint pertama
520
- // (tanpa ini marker basi turn-asing selalu diadopsi — audit #08 §15).
521
- const pointed =
522
- latest.newIndex === -1 ? manifest.checkpoints[0] : manifest.checkpoints[latest.newIndex]
523
- if (latest.targetTurn !== undefined && pointed && pointed.turn !== latest.targetTurn) {
535
+ // (eviksi/cabang lain) tak boleh diadopsi buta.
536
+ // Pada undo: targetCp yang dibatalkan berada di indeks newIndex + 1 (newIndex -1 → checkpoint 0).
537
+ // Pada redo: targetCp yang diaplikasikan kembali berada tepat di latest.newIndex.
538
+ const targetIdx = latest.kind === "undo" ? latest.newIndex + 1 : latest.newIndex
539
+ const pointed = manifest.checkpoints[targetIdx]
540
+ if (!pointed || (latest.targetTurn !== undefined && pointed.turn !== latest.targetTurn)) {
541
+ const actualTurn = pointed ? ` (turn ${pointed.turn})` : " (absen)"
524
542
  process.stderr.write(
525
- `[warn] checkpoint: undo/redo marker turn ${latest.targetTurn} tak cocok checkpoint idx ${latest.newIndex} (turn ${pointed.turn}) — diabaikan\n`,
543
+ `[warn] checkpoint: ${latest.kind} marker turn ${latest.targetTurn} tak cocok checkpoint idx ${targetIdx}${actualTurn} — diabaikan\n`,
526
544
  )
527
545
  return null
528
546
  }
@@ -25,6 +25,7 @@ import { mkdir, open, readFile } from "node:fs/promises"
25
25
  import { dirname, isAbsolute, join, relative, resolve } from "node:path"
26
26
  import { atomicWriteText } from "../lib/atomic-write.ts"
27
27
  import { sanitizeSessionPart } from "../lib/session-id.ts"
28
+ import { isMcpToolName } from "../presentation/label.ts"
28
29
 
29
30
  export type JournalState = "pending" | "committed" | "failed"
30
31
 
@@ -130,7 +131,7 @@ const NON_MUTATION_TOOLS: ReadonlySet<string> = new Set([
130
131
 
131
132
  export function classifyTool(name: string): "mutation" | "none" | "unknown" {
132
133
  // Tool runtime MCP (server.tool) mewarisi kelas mcp_call: efek arbitrer.
133
- const base = name.includes(".") ? "mcp_call" : name
134
+ const base = isMcpToolName(name) ? "mcp_call" : name
134
135
  if (MUTATION_TOOLS.has(base)) return "mutation"
135
136
  if (NON_MUTATION_TOOLS.has(base)) return "none"
136
137
  return "unknown"
@@ -1061,7 +1062,17 @@ interface ExecutionEvent {
1061
1062
  */
1062
1063
  export function attachMutationJournal(
1063
1064
  session: SessionLike,
1064
- opts: { sessionId: string; cwd?: string; childOf?: string },
1065
+ opts: {
1066
+ sessionId: string
1067
+ cwd?: string
1068
+ childOf?: string
1069
+ /**
1070
+ * Fase 4 V2.1: kabar terminal committed (paths+journalSeq) → composition
1071
+ * root memancarkan file.changed (receipt). Opsional — tanpa hook, jurnal
1072
+ * tetap berjalan seperti dulu.
1073
+ */
1074
+ onCommitted?: (info: { toolCallId: string; paths: string[]; journalSeq: number }) => void
1075
+ },
1065
1076
  ): void {
1066
1077
  const root = resolve(opts.cwd ?? process.cwd())
1067
1078
  // Eager creation (AUDIT #01E §1): file jurnal dibuat saat wiring dipasang
@@ -1110,7 +1121,7 @@ export function attachMutationJournal(
1110
1121
  if (!name || NO_AUTO_JOURNAL.has(name) || !isMutationTool(name)) return
1111
1122
  const callId =
1112
1123
  typeof ev.execution?.call?.id === "string" ? (ev.execution.call.id as string) : ""
1113
- const base = name.includes(".") ? "mcp_call" : name
1124
+ const base = isMcpToolName(name) ? "mcp_call" : name
1114
1125
  const args = (ev.execution?.call?.args ?? {}) as Record<string, unknown>
1115
1126
  // Daftarkan promise SEBELUM await: completed dijamin datang sesudah
1116
1127
  // started, dan kini pasti menunggu intent selesai dulu.
@@ -1162,7 +1173,7 @@ export function attachMutationJournal(
1162
1173
  const t =
1163
1174
  typeof a.tool === "string"
1164
1175
  ? a.tool
1165
- : name.includes(".")
1176
+ : isMcpToolName(name)
1166
1177
  ? name.split(".").slice(1).join(".")
1167
1178
  : ""
1168
1179
  if (srv || t) note = `${srv ? `${srv}.` : ""}${t}`
@@ -1176,6 +1187,17 @@ export function attachMutationJournal(
1176
1187
  failed ? "failed" : "committed",
1177
1188
  note ? { note } : undefined,
1178
1189
  )
1190
+ // Fase 4: kabar committed ke composition root (file.changed/receipt).
1191
+ // Gagal hook tak boleh menggagalkan jurnal (degraded-loud).
1192
+ if (!failed && opts.onCommitted && callId) {
1193
+ try {
1194
+ opts.onCommitted({
1195
+ toolCallId: callId,
1196
+ paths: found.paths ?? [],
1197
+ journalSeq: found.seq,
1198
+ })
1199
+ } catch {}
1200
+ }
1179
1201
  } catch (err) {
1180
1202
  process.stderr.write(`[warn] journal: terminal failed: ${(err as Error).message}\n`)
1181
1203
  }
@@ -1184,7 +1206,7 @@ export function attachMutationJournal(
1184
1206
  }
1185
1207
 
1186
1208
  function base_of(name: string): string {
1187
- return name.includes(".") ? "mcp_call" : name
1209
+ return isMcpToolName(name) ? "mcp_call" : name
1188
1210
  }
1189
1211
 
1190
1212
  // ── Resume: muat jurnal (+anak) → putuskan ──
@@ -1,6 +1,7 @@
1
- import { readdir, readFile } from "node:fs/promises"
1
+ import type { Dirent } from "node:fs"
2
+ import { readdir, readFile, stat } from "node:fs/promises"
2
3
  import { homedir } from "node:os"
3
- import { join, resolve } from "node:path"
4
+ import { basename, dirname, join, resolve } from "node:path"
4
5
  import { isRealPathOutsideRoot } from "../policy/jail.ts"
5
6
 
6
7
  export interface Skill {
@@ -8,6 +9,14 @@ export interface Skill {
8
9
  description: string
9
10
  body: string // prompt template
10
11
  path: string
12
+ /** F4.1: frontmatter `disable-model-invocation: true` — skill HANYA via
13
+ * `/nama` eksplisit, tak masuk katalog auto-pick system prompt. Untuk
14
+ * workflow yang tak boleh dipicu model sendiri (deploy/rilis). */
15
+ manualOnly: boolean
16
+ /** F4.1: aset opsional gaya Zed — folder sibling `<nama>/` berisi
17
+ * `scripts/` dan `references/` (daftar nama berkas, hanya info agar model
18
+ * bisa membacanya via read_file; TIDAK dieksekusi otomatis). */
19
+ assets: { scripts: string[]; references: string[] }
11
20
  }
12
21
 
13
22
  const GLOBAL_SKILLS = join(homedir(), ".minicode", "skills")
@@ -54,6 +63,10 @@ async function loadDir(dir: string, out: Skill[], root: string = dir) {
54
63
  // realpath-nya di luar root kepercayaannya (global vs proyek).
55
64
  if (isRealPathOutsideRoot(full, root)) continue
56
65
  if (e.isDirectory()) {
66
+ // F4.1: folder aset sibling (<skill>/scripts|references) BUKAN wadah
67
+ // skill — tanpa ini references/guide.md ikut dimuat sebagai skill
68
+ // "guide" dan mengotori katalog. Terdeteksi via <skill>.md di parent.
69
+ if ((e.name === "scripts" || e.name === "references") && (await isAssetDir(dir))) continue
57
70
  // recursive 1-level deep for nested skills
58
71
  await loadDir(full, out, root)
59
72
  continue
@@ -69,15 +82,65 @@ async function loadDir(dir: string, out: Skill[], root: string = dir) {
69
82
  .replace(/[^a-z0-9-]/g, "-")
70
83
  .replace(/-+/g, "-")
71
84
  .replace(/^-|-$/g, "")
85
+ // F4.1: nilai truthy longgar ("true"/"1"/"yes", case-insensitive) —
86
+ // frontmatter YAML-ish ditulis manusia, bukan mesin.
87
+ const manualOnly = /^(true|1|yes)$/i.test((meta["disable-model-invocation"] ?? "").trim())
72
88
  out.push({
73
89
  name: name || rawName,
74
90
  description: meta.description ?? body.split("\n")[0]?.slice(0, 100) ?? "",
75
91
  body,
76
92
  path: full,
93
+ manualOnly,
94
+ assets: await loadSkillAssets(dir, e.name.replace(/\.md$/, ""), root),
77
95
  })
78
96
  }
79
97
  }
80
98
 
99
+ /** F4.1: true bila `dir` adalah folder aset skill — yaitu `<base>/scripts`
100
+ * atau `<base>/references` dengan `<base>.md` di parent-nya. Hanya dua nama
101
+ * itu yang istimewa; folder skill biasa (mis. `deploy/`) tetap direkursi. */
102
+ async function isAssetDir(dir: string): Promise<boolean> {
103
+ const base = basename(dir)
104
+ try {
105
+ await stat(join(dirname(dir), `${base}.md`))
106
+ return true
107
+ } catch {
108
+ return false
109
+ }
110
+ }
111
+ async function loadSkillAssets(
112
+ dir: string,
113
+ base: string,
114
+ root: string,
115
+ ): Promise<{ scripts: string[]; references: string[] }> {
116
+ const empty = { scripts: [], references: [] }
117
+ // base dari nama berkas .md sendiri (sudah lewat slug) — tanpa separator
118
+ // path, jadi join aman; tetap lewat guard realpath per entri di bawah.
119
+ if (base.includes("/") || base.includes("\\") || base === "" || base === "." || base === "..")
120
+ return empty
121
+ const out: { scripts: string[]; references: string[] } = { scripts: [], references: [] }
122
+ for (const [key, sub] of [
123
+ ["scripts", "scripts"],
124
+ ["references", "references"],
125
+ ] as const) {
126
+ const subdir = join(dir, base, sub)
127
+ let entries: Dirent[]
128
+ try {
129
+ entries = await readdir(subdir, { withFileTypes: true })
130
+ } catch {
131
+ continue
132
+ }
133
+ for (const en of entries) {
134
+ if (out[key].length >= 20) break
135
+ if (!en.isFile() || en.name.startsWith(".")) continue
136
+ const full = join(subdir, en.name)
137
+ if (isRealPathOutsideRoot(full, root)) continue
138
+ out[key].push(en.name)
139
+ }
140
+ }
141
+ return out
142
+ }
143
+
81
144
  let skillsCache: { cwd: string; at: number; skills: Skill[] } | undefined
82
145
  const SKILLS_CACHE_TTL_MS = 5 * 60 * 1000
83
146
 
@@ -90,7 +153,16 @@ export async function loadSkills(cwd = process.cwd()): Promise<Skill[]> {
90
153
  }
91
154
  const skills: Skill[] = []
92
155
  await loadDir(GLOBAL_SKILLS, skills)
93
- await loadDir(resolve(cwd, LOCAL_SKILLS), skills)
156
+ const localSkills: Skill[] = []
157
+ await loadDir(resolve(cwd, LOCAL_SKILLS), localSkills, resolve(cwd, LOCAL_SKILLS))
158
+ if (localSkills.length > 0) {
159
+ try {
160
+ process.stderr.write(
161
+ `[warn] skills: loaded ${localSkills.length} project skill(s) from ${LOCAL_SKILLS} (untrusted repo instructions)\n`,
162
+ )
163
+ } catch {}
164
+ skills.push(...localSkills)
165
+ }
94
166
  // local overrides global by name
95
167
  const map = new Map<string, Skill>()
96
168
  for (const s of skills) map.set(s.name, s)
@@ -112,6 +184,17 @@ export async function findSkill(name: string, cwd = process.cwd()): Promise<Skil
112
184
  }
113
185
 
114
186
  export function skillsToSystemPrompt(skills: Skill[]): string {
115
- if (skills.length === 0) return ""
116
- return `\n# Available skills (use via /name or ask)\n${skills.map((s) => `- /${s.name}: ${s.description}`).join("\n")}`
187
+ // F4.1: manualOnly TAK masuk katalog auto-pick — model tak boleh memicu
188
+ // workflow berbahaya sendiri; user memanggil eksplisit via /nama (findSkill
189
+ // tetap menemukannya). Aset dicantumkan sebagai petunjuk baca, bukan
190
+ // eksekusi: model memakai read_file bila perlu.
191
+ const auto = skills.filter((s) => !s.manualOnly)
192
+ if (auto.length === 0) return ""
193
+ const line = (s: Skill): string => {
194
+ const hints: string[] = []
195
+ if (s.assets.scripts.length > 0) hints.push(`scripts: ${s.assets.scripts.join(", ")}`)
196
+ if (s.assets.references.length > 0) hints.push(`refs: ${s.assets.references.join(", ")}`)
197
+ return `- /${s.name}: ${s.description}${hints.length ? ` (${hints.join("; ")})` : ""}`
198
+ }
199
+ return `\n# Available skills (use via /name or ask)\n${auto.map(line).join("\n")}`
117
200
  }