minicode-ai 0.27.0 → 0.30.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 (145) hide show
  1. package/README.md +1 -1
  2. package/cli/args.ts +184 -57
  3. package/cli/bootstrap/presentation-bridge.ts +383 -0
  4. package/cli/commands/acp.ts +45 -29
  5. package/cli/commands/auth.ts +17 -17
  6. package/cli/commands/config.ts +65 -66
  7. package/cli/commands/daemon.ts +44 -16
  8. package/cli/commands/doctor.ts +18 -15
  9. package/cli/commands/exec.ts +41 -89
  10. package/cli/commands/mcp.ts +25 -8
  11. package/cli/commands/memory.ts +16 -24
  12. package/cli/commands/openwork.ts +6 -2
  13. package/cli/commands/pricing.ts +14 -12
  14. package/cli/commands/providers.ts +36 -57
  15. package/cli/commands/sessions.ts +24 -18
  16. package/cli/commands/skills.ts +33 -18
  17. package/cli/commands/stats.ts +15 -30
  18. package/cli/commands.ts +73 -44
  19. package/cli/context-command-run.ts +30 -18
  20. package/cli/index.ts +51 -100
  21. package/cli/model-manager.ts +7 -2
  22. package/cli/provider-manager.ts +33 -18
  23. package/cli/router.ts +41 -12
  24. package/cli/setup.ts +241 -485
  25. package/cli/tui.ts +303 -100
  26. package/docs/TERMINAL_CONTRACT.md +258 -73
  27. package/docs/UI_RENDER_PIPELINE.md +9 -1
  28. package/docs/agents.md +2 -2
  29. package/docs/architecture.md +17 -32
  30. package/docs/choosing-mode.md +7 -9
  31. package/docs/cli.md +3 -5
  32. package/docs/environment.md +1 -2
  33. package/docs/policy-sandbox.md +3 -3
  34. package/docs/repl.md +2 -2
  35. package/docs/tools.md +1 -1
  36. package/package.json +1 -1
  37. package/src/app/mentions.ts +60 -13
  38. package/src/app/rag-layer.ts +17 -20
  39. package/src/app/session.ts +144 -68
  40. package/src/app/tool-layer.ts +38 -16
  41. package/src/config.ts +64 -104
  42. package/src/constants.ts +4 -6
  43. package/src/daemon/capability.ts +8 -1
  44. package/src/daemon/control.ts +3 -2
  45. package/src/daemon/server.ts +57 -0
  46. package/src/hooks/run.ts +73 -41
  47. package/src/lib/atomic-write.ts +31 -59
  48. package/src/lib/db-path.ts +47 -0
  49. package/src/lib/process-tree.ts +62 -0
  50. package/src/lib/public-http.ts +88 -23
  51. package/src/lib/trusted-exec.ts +48 -1
  52. package/src/lsp/client.ts +62 -17
  53. package/src/mcp/client.ts +85 -38
  54. package/src/mcp/http-transport.ts +28 -16
  55. package/src/mcp/transport.ts +42 -6
  56. package/src/memory/files.ts +164 -134
  57. package/src/memory/vector.ts +371 -420
  58. package/src/policy/approval-binding.ts +122 -45
  59. package/src/policy/bash-guard.ts +18 -7
  60. package/src/policy/compaction.ts +51 -18
  61. package/src/policy/context-window.ts +31 -8
  62. package/src/policy/context.ts +62 -36
  63. package/src/policy/executor.ts +17 -7
  64. package/src/policy/jail.ts +6 -8
  65. package/src/policy/microcompact.ts +4 -3
  66. package/src/policy/no-progress.ts +103 -22
  67. package/src/policy/permission.ts +36 -12
  68. package/src/policy/tool-contract.ts +74 -416
  69. package/src/policy/usage.ts +24 -2
  70. package/src/policy/verifier.ts +50 -2
  71. package/src/policy/work-mode.ts +28 -54
  72. package/src/presentation/adapter.ts +24 -16
  73. package/src/providers/anthropic.ts +16 -5
  74. package/src/providers/provision.ts +6 -56
  75. package/src/providers/responses.ts +38 -7
  76. package/src/providers/sse-bounds.ts +6 -4
  77. package/src/runtime/execution-journal.ts +4 -29
  78. package/src/sandbox/docker.ts +58 -34
  79. package/src/sandbox/mask.ts +157 -0
  80. package/src/sandbox/os.ts +107 -73
  81. package/src/session/authority.ts +29 -10
  82. package/src/session/context-projection.ts +6 -5
  83. package/src/session/db/runs.ts +397 -0
  84. package/src/session/db/schema.ts +358 -0
  85. package/src/session/open-work.ts +26 -3
  86. package/src/session/persistence.ts +74 -998
  87. package/src/session/verification.ts +170 -20
  88. package/src/skills/loader.ts +31 -16
  89. package/src/task/db/schema.ts +325 -0
  90. package/src/task/db/types.ts +269 -0
  91. package/src/task/production-scheduler.ts +13 -1
  92. package/src/task/store.ts +92 -1021
  93. package/src/telemetry/trace.ts +27 -0
  94. package/src/tools/ask_user.ts +1 -13
  95. package/src/tools/bash.ts +27 -92
  96. package/src/tools/code_run.ts +1 -1
  97. package/src/tools/context.ts +133 -0
  98. package/src/tools/delete_file.ts +3 -2
  99. package/src/tools/edit.ts +37 -72
  100. package/src/tools/git.ts +86 -9
  101. package/src/tools/glob.ts +26 -51
  102. package/src/tools/grep.ts +67 -57
  103. package/src/tools/hashline.ts +4 -0
  104. package/src/tools/lsp.ts +11 -8
  105. package/src/tools/mcp_call.ts +9 -6
  106. package/src/tools/memory.ts +56 -33
  107. package/src/tools/move_file.ts +36 -10
  108. package/src/tools/patch.ts +13 -21
  109. package/src/tools/read_file.ts +18 -25
  110. package/src/tools/read_image.ts +35 -33
  111. package/src/tools/submit_result.ts +29 -8
  112. package/src/tools/task.ts +74 -17
  113. package/src/tools/todo.ts +181 -74
  114. package/src/tools/web_fetch.ts +42 -2
  115. package/src/tools/web_search.ts +47 -8
  116. package/src/ui/approval/prompt.ts +206 -47
  117. package/src/ui/assistant/turn-status.ts +14 -5
  118. package/src/ui/footer.ts +4 -4
  119. package/src/ui/i18n/en.ts +47 -23
  120. package/src/ui/i18n/id.ts +76 -51
  121. package/src/ui/input/input.ts +4 -3
  122. package/src/ui/input/prompt-engine.ts +35 -5
  123. package/src/ui/render/activity-panel.ts +4 -2
  124. package/src/ui/render/hint.ts +7 -4
  125. package/src/ui/render/list.ts +32 -0
  126. package/src/ui/render/markdown.ts +6 -3
  127. package/src/ui/render/notice.ts +19 -0
  128. package/src/ui/render/table-grid.ts +7 -8
  129. package/src/ui/render/theme.ts +113 -39
  130. package/src/ui/runtime/screen.ts +74 -10
  131. package/src/ui/runtime/spinner.ts +19 -6
  132. package/src/ui/screens/dialog.ts +19 -1
  133. package/src/ui/screens/form.ts +80 -35
  134. package/src/ui/screens/model-manager.ts +82 -61
  135. package/src/ui/screens/output-window.ts +263 -0
  136. package/src/ui/screens/picker.ts +94 -81
  137. package/src/ui/screens/provider-manager.ts +100 -69
  138. package/src/ui/screens/wizard.ts +117 -28
  139. package/src/ui/tui/app.ts +196 -33
  140. package/src/ui/tui/transcript.ts +158 -25
  141. package/vendor/minicore/src/core/executor.ts +2 -0
  142. package/vendor/minicore/src/core/loop.ts +17 -6
  143. package/vendor/minicore/src/core/session.ts +3 -0
  144. package/vendor/minicore/src/core/tool.ts +1 -0
  145. package/vendor/minicore/src/providers/openai-compat.ts +35 -19
@@ -1,9 +1,9 @@
1
- import { appendFile, mkdir, readFile, stat } from "node:fs/promises"
1
+ import { appendFile, lstat, mkdir, readFile } from "node:fs/promises"
2
2
  import { homedir } from "node:os"
3
3
  import { dirname, join, resolve } from "node:path"
4
4
  import { LIMITS } from "../constants.ts"
5
5
  import { homeDir } from "../lib/db-path.ts"
6
- import { safeReadFileCapped } from "../lib/safe-open.ts"
6
+ import { assertSafeWriteTarget, safeReadFileCapped } from "../lib/safe-open.ts"
7
7
  import { isRealPathOutsideRoot } from "../policy/jail.ts"
8
8
  import { scrubSecrets } from "../policy/scrub.ts"
9
9
 
@@ -21,7 +21,10 @@ const ROOT_MEM = "MEMORY.md"
21
21
  // Claude-like hierarchy extensions
22
22
  const CLAUDE_MEM = "CLAUDE.md"
23
23
 
24
- export async function loadMemoryFiles(cwd = process.cwd()): Promise<string> {
24
+ export async function loadMemoryFiles(
25
+ cwd = process.cwd(),
26
+ opts: { allowLocalRules?: boolean } = {},
27
+ ): Promise<string> {
25
28
  const parts: string[] = []
26
29
  const globalMem = globalMemPath()
27
30
  // Hierarchy: global → local → root → CLAUDE compat → rules/
@@ -48,31 +51,34 @@ export async function loadMemoryFiles(cwd = process.cwd()): Promise<string> {
48
51
  )
49
52
  } catch {}
50
53
  }
51
- // Load .minicode/rules/*.md (Kiro steering style)
52
- try {
53
- const { readdir } = await import("node:fs/promises")
54
- const rulesDir = resolve(cwd, ".minicode/rules")
55
- const entries = await readdir(rulesDir).catch(() => [] as string[])
56
- // entries may be string[] or Dirent — handle both
57
- const files: string[] =
58
- Array.isArray(entries) && typeof entries[0] === "string"
59
- ? (entries as string[]).filter((f) => f.endsWith(".md")).slice(0, 10)
60
- : (entries as unknown as import("node:fs").Dirent[])
61
- .filter((e) => e.isFile() && e.name.endsWith(".md"))
62
- .map((e) => e.name)
63
- .slice(0, 10)
64
- for (const f of files) {
65
- try {
66
- const full = join(rulesDir, f as string)
67
- if (isRealPathOutsideRoot(full, cwd)) continue
68
- const { text, truncated } = await safeReadFileCapped(full, cwd, 3000)
69
- if (text.trim())
70
- parts.push(
71
- `# rules/${f}\n${scrubSecrets(text)}${truncated ? "\n… [truncated: showing first 3000 bytes]" : ""}`,
72
- )
73
- } catch {}
74
- }
75
- } catch {}
54
+ // Load .minicode/rules/*.md (Kiro steering style) — hanya aktif bila
55
+ // local config diizinkan (`--allow-local-config`), selaras dengan .minicode/skills/.
56
+ if (opts.allowLocalRules === true) {
57
+ try {
58
+ const { readdir } = await import("node:fs/promises")
59
+ const rulesDir = resolve(cwd, ".minicode/rules")
60
+ const entries = await readdir(rulesDir).catch(() => [] as string[])
61
+ // entries may be string[] or Dirent — handle both
62
+ const files: string[] =
63
+ Array.isArray(entries) && typeof entries[0] === "string"
64
+ ? (entries as string[]).filter((f) => f.endsWith(".md")).slice(0, 10)
65
+ : (entries as unknown as import("node:fs").Dirent[])
66
+ .filter((e) => e.isFile() && e.name.endsWith(".md"))
67
+ .map((e) => e.name)
68
+ .slice(0, 10)
69
+ for (const f of files) {
70
+ try {
71
+ const full = join(rulesDir, f as string)
72
+ if (isRealPathOutsideRoot(full, cwd)) continue
73
+ const { text, truncated } = await safeReadFileCapped(full, cwd, 3000)
74
+ if (text.trim())
75
+ parts.push(
76
+ `# rules/${f}\n${scrubSecrets(text)}${truncated ? "\n… [truncated: showing first 3000 bytes]" : ""}`,
77
+ )
78
+ } catch {}
79
+ }
80
+ } catch {}
81
+ }
76
82
  return parts.join("\n\n")
77
83
  }
78
84
 
@@ -80,157 +86,181 @@ const MAX_MEMORY_FILE_BYTES = LIMITS.MEMORY_FILE_MAX_BYTES
80
86
 
81
87
  // Kunci in-process per berkas (audit #09 P1): appendMemory (append +
82
88
  // truncate-guard read-modify-write) dan deleteMemoryLines (read-filter-write)
83
- // tanpa ini saling menelan — reproducer: forget vs 20 append konkuren →
84
- // 0/20 selamat. Baca (loadMemoryFiles) sengaja tanpa lock: append O_APPEND
85
- // atomik sehingga baca basi/robek sesaat tak berbahaya untuk retrieval.
89
+ // serta reconcileMemoryStores/revokeByProvenance berbagi lock ini agar tak
90
+ // saling menelan.
86
91
  const memLocks = new Map<string, Promise<void>>()
87
92
 
88
- async function withMemLock<T>(path: string, fn: () => Promise<T>): Promise<T> {
93
+ export async function withMemLock<T>(path: string, fn: () => Promise<T>): Promise<T> {
89
94
  const prev = memLocks.get(path) ?? Promise.resolve()
90
95
  let release!: () => void
91
96
  const next = new Promise<void>((res) => (release = res))
92
- memLocks.set(
93
- path,
94
- prev.then(() => next),
95
- )
97
+ const tail = prev.then(() => next)
98
+ memLocks.set(path, tail)
96
99
  await prev
97
100
  try {
98
101
  return await fn()
99
102
  } finally {
100
103
  release()
101
- if (memLocks.get(path) === next) memLocks.delete(path)
104
+ if (memLocks.get(path) === tail) memLocks.delete(path)
102
105
  }
103
106
  }
104
107
 
105
- export async function appendMemory(
108
+ /** Cegah symlink/hardlink escape sebelum baca/tulis MEMORY.md. */
109
+ export async function assertSafeMemoryPath(path: string, root: string): Promise<void> {
110
+ await assertSafeWriteTarget(path, root)
111
+ try {
112
+ const st = await lstat(path)
113
+ if (st.isSymbolicLink() || st.nlink > 1) {
114
+ throw new Error(`unsafe memory target (symlink or hardlink): ${path}`)
115
+ }
116
+ } catch (e) {
117
+ if ((e as NodeJS.ErrnoException)?.code !== "ENOENT") throw e
118
+ }
119
+ }
120
+
121
+ export async function safeReadMemoryFile(path: string, root: string): Promise<string> {
122
+ await assertSafeMemoryPath(path, root)
123
+ return await readFile(path, "utf8")
124
+ }
125
+
126
+ async function safeAtomicWriteMemory(path: string, root: string, content: string): Promise<void> {
127
+ const { atomicWriteText } = await import("../lib/atomic-write.ts")
128
+ await assertSafeMemoryPath(path, root)
129
+ await atomicWriteText(path, content)
130
+ }
131
+
132
+ function sanitizeMemoryTags(tags?: readonly string[]): string[] | undefined {
133
+ if (!tags?.length) return undefined
134
+ return tags.map((tg) => scrubSecrets(String(tg)).replace(/[\r\n]+/g, " "))
135
+ }
136
+
137
+ export async function appendMemoryUnlocked(
106
138
  text: string,
107
139
  cwd = process.cwd(),
108
140
  tags?: readonly string[],
109
141
  ): Promise<string> {
110
142
  const path = resolve(cwd, LOCAL_MEM)
111
- return withMemLock(path, async () => {
112
- await mkdir(dirname(path), { recursive: true, mode: 0o700 }).catch(() => {})
113
- // [Area E / D5] JANGAN potong per-entri di sini. Batas 1000 karakter lama
114
- // membuat MEMORY.md lebih pendek daripada chunk vektor (2000) sehingga
115
- // reconcile menganggap chunk ekor "vector-only" dan menghapusnya. Batas
116
- // ukuran total berkas tetap dijaga MAX_MEMORY_FILE_BYTES di bawah.
117
- const clean = scrubSecrets(text.trim())
118
- // [Area E / D2] Provenance (MEM-01) benar-benar ditulis ke berkas — tanpa
119
- // tag ini jalur revoke-by-provenance tidak punya bukti di sisi file dan
120
- // gagal-closed (atau, pada versi lama, menghapus SEMUA baris tanpa tag).
121
- const meta = tags && tags.length > 0 ? ` [tags: ${JSON.stringify(tags)}]` : ""
122
- const entry = `- ${new Date().toISOString().slice(0, 10)} ${clean}${meta}\n`
123
- // atomic append — no read+write race
124
- await appendFile(path, entry, "utf8").catch(async () => {
125
- // fallback if file not exists
126
- await mkdir(dirname(path), { recursive: true })
127
- await appendFile(path, entry, "utf8")
128
- })
129
- // size guard: truncate oldest if too large (keep last 150k)
130
- try {
131
- const st = await stat(path)
132
- if (st.size > MAX_MEMORY_FILE_BYTES) {
133
- const txt = await readFile(path, "utf8")
134
- const rawKeep = txt.slice(-LIMITS.MEMORY_TRUNCATE_KEEP_BYTES)
135
- // Cari batas entri utuh berikutnya (diawali \n- ) agar entri pertama tak terpotong buntung
136
- const entryBoundary = rawKeep.indexOf("\n- ")
137
- const cut = entryBoundary >= 0 ? entryBoundary + 1 : rawKeep.indexOf("\n")
138
- const trimmed = cut >= 0 ? rawKeep.slice(cut + (entryBoundary >= 0 ? 0 : 1)) : rawKeep
139
- const { atomicWriteText } = await import("../lib/atomic-write.ts")
140
- await atomicWriteText(path, trimmed)
141
- }
142
- } catch {}
143
- return path
143
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 }).catch(() => {})
144
+ await assertSafeMemoryPath(path, cwd)
145
+ // Ratakan newline agar satu entri tetap satu baris & tidak memecah parser.
146
+ const clean = scrubSecrets(text.trim()).replace(/[\r\n]+/g, " ")
147
+ const safeTags = sanitizeMemoryTags(tags)
148
+ const meta = safeTags?.length ? ` [tags: ${JSON.stringify(safeTags)}]` : ""
149
+ const entry = `- ${new Date().toISOString().slice(0, 10)} ${clean}${meta}\n`
150
+ await appendFile(path, entry, "utf8").catch(async () => {
151
+ await mkdir(dirname(path), { recursive: true })
152
+ await assertSafeMemoryPath(path, cwd)
153
+ await appendFile(path, entry, "utf8")
144
154
  })
155
+ try {
156
+ const txt = await safeReadMemoryFile(path, cwd)
157
+ const buf = Buffer.from(txt, "utf8")
158
+ if (buf.byteLength > MAX_MEMORY_FILE_BYTES) {
159
+ const rawKeep = buf.subarray(-LIMITS.MEMORY_TRUNCATE_KEEP_BYTES).toString("utf8")
160
+ const entryBoundary = rawKeep.indexOf("\n- ")
161
+ const cut = entryBoundary >= 0 ? entryBoundary + 1 : rawKeep.indexOf("\n")
162
+ const trimmed = cut >= 0 ? rawKeep.slice(cut + (entryBoundary >= 0 ? 0 : 1)) : rawKeep
163
+ await safeAtomicWriteMemory(path, cwd, trimmed)
164
+ }
165
+ } catch {}
166
+ return path
167
+ }
168
+
169
+ export async function appendMemory(
170
+ text: string,
171
+ cwd = process.cwd(),
172
+ tags?: readonly string[],
173
+ ): Promise<string> {
174
+ const path = resolve(cwd, LOCAL_MEM)
175
+ return withMemLock(path, () => appendMemoryUnlocked(text, cwd, tags))
145
176
  }
146
177
 
147
178
  export async function readMemoryFile(cwd = process.cwd()): Promise<string> {
148
179
  return await loadMemoryFiles(cwd)
149
180
  }
150
181
 
151
- /**
152
- * [Area E / D6] Ambil teks entri dari satu baris MEMORY.md — buang prefix
153
- * tanggal dan metadata `[tags: ...]`. Dipakai supersession untuk mencocokkan
154
- * baris lama tanpa bergantung pada posisi/urutan.
155
- */
156
- export function memoryLineText(line: string): string {
182
+ /** Parser baris MEMORY.md terpusat (dipakai files.ts & vector.ts). */
183
+ export function parseMemoryLine(line: string): { text: string; tags: string[] } | null {
184
+ if (!line.startsWith("- ")) return null
157
185
  const match = line.match(/^-\s+\d{4}-\d{2}-\d{2}(?:T\S+)?\s+(.+)$/)
158
- const body = match
159
- ? match[1]!
160
- : line
161
- .trim()
162
- .replace(/^-\s+\S+\s+/, "")
163
- .trim()
186
+ const body = (match ? match[1]! : line.trim().replace(/^-\s+\S+\s+/, "")).trim()
187
+ if (!body) return null
188
+ const jsonTagMatch = body.match(/\s*\[tags:\s*(\[.*\])\]\s*$/)
189
+ if (jsonTagMatch) {
190
+ try {
191
+ const parsed = JSON.parse(jsonTagMatch[1]!)
192
+ if (Array.isArray(parsed)) {
193
+ return {
194
+ text: body.slice(0, jsonTagMatch.index!).trim(),
195
+ tags: parsed.map((item) => String(item)),
196
+ }
197
+ }
198
+ } catch {}
199
+ }
164
200
  const tagMatch = body.match(/\[tags:\s*[^\]]+\]/)
165
- return (tagMatch ? body.slice(0, tagMatch.index!) : body).trim()
201
+ return {
202
+ text: (tagMatch ? body.slice(0, tagMatch.index!) : body).trim(),
203
+ tags: [],
204
+ }
166
205
  }
167
206
 
168
- /**
169
- * [Area E / D6] Hapus SATU entri MEMORY.md lokal berdasarkan teksnya.
170
- *
171
- * `target` boleh berupa teks utuh (entri pendek) atau prefix chunk pertama
172
- * (entri multi-chunk yang tersimpan utuh di berkas). `startsWith` diperlukan
173
- * karena baris lama yang panjang tidak lagi dipotong saat append.
174
- *
175
- * Fail-closed: berkas tak ada / tak ada baris yang cocok → `false`, bukan
176
- * menulis ulang berkas tanpa perubahan.
177
- */
178
- export async function deleteMemoryEntry(target: string, cwd = process.cwd()): Promise<boolean> {
179
- const needle = target.trim()
207
+ export function memoryLineText(line: string): string {
208
+ return parseMemoryLine(line)?.text ?? ""
209
+ }
210
+
211
+ export async function deleteMemoryEntryUnlocked(
212
+ target: string,
213
+ cwd = process.cwd(),
214
+ ): Promise<boolean> {
215
+ const needle = target.trim().replace(/[\r\n]+/g, " ")
180
216
  if (!needle) return false
181
217
  const path = resolve(cwd, LOCAL_MEM)
182
- return withMemLock(path, async () => {
183
- let txt: string
184
- try {
185
- txt = await readFile(path, "utf8")
186
- } catch {
187
- return false
188
- }
189
- const lines = txt.split("\n")
190
- let removed = 0
191
- const kept = lines.filter((line) => {
192
- if (!line.startsWith("- ")) return true
193
- const text = memoryLineText(line)
194
- const hit = text === needle || text.startsWith(needle)
195
- if (hit) removed++
196
- return !hit
197
- })
198
- if (removed === 0) return false
199
- const { atomicWriteText } = await import("../lib/atomic-write.ts")
200
- await atomicWriteText(path, kept.join("\n"))
201
- return true
218
+ let txt: string
219
+ try {
220
+ txt = await safeReadMemoryFile(path, cwd)
221
+ } catch {
222
+ return false
223
+ }
224
+ const lines = txt.split("\n")
225
+ let removed = 0
226
+ const kept = lines.filter((line) => {
227
+ if (!line.startsWith("- ")) return true
228
+ const text = memoryLineText(line)
229
+ const hit = text === needle || (needle.length >= 200 && text.startsWith(needle))
230
+ if (hit) removed++
231
+ return !hit
202
232
  })
233
+ if (removed === 0) return false
234
+ await safeAtomicWriteMemory(path, cwd, kept.join("\n"))
235
+ return true
236
+ }
237
+
238
+ export async function deleteMemoryEntry(target: string, cwd = process.cwd()): Promise<boolean> {
239
+ const needle = target.trim().replace(/[\r\n]+/g, " ")
240
+ if (!needle) return false
241
+ const path = resolve(cwd, LOCAL_MEM)
242
+ return withMemLock(path, () => deleteMemoryEntryUnlocked(needle, cwd))
203
243
  }
204
244
 
205
- /**
206
- * Hapus baris MEMORY.md lokal + global yang cocok query (temuan audit #06,
207
- * diperluas audit 2026-09-16 M4).
208
- *
209
- * forget_memory sebelumnya hanya menghapus baris vector — entri file
210
- * (sumber `file hits:` di read_memory) bertahan selamanya sehingga "lupa"
211
- * tidak pernah benar-benar terjadi di jalur file. Perluasan M4: read_memory
212
- * membaca hierarki lokal DAN global (loadMemoryFiles), jadi hapus lokal saja
213
- * tak tuntas — baris global yang cocok ikut dihapus. Pencocokan sama persis
214
- * dengan jalur baca (substring case-insensitive) agar hapus-menemukan apa
215
- * yang baca-temukan.
216
- */
217
245
  export async function deleteMemoryLines(query: string, cwd = process.cwd()): Promise<number> {
218
246
  const q = query.trim().toLowerCase()
219
247
  if (!q) return 0
220
248
  let total = 0
221
- for (const path of [resolve(cwd, LOCAL_MEM), globalMemPath()]) {
249
+ const globalMem = globalMemPath()
250
+ for (const path of [resolve(cwd, LOCAL_MEM), globalMem]) {
251
+ const root = path === globalMem ? dirname(path) : cwd
222
252
  total += await withMemLock(path, async () => {
223
253
  let txt: string
224
254
  try {
225
- txt = await readFile(path, "utf8")
255
+ txt = await safeReadMemoryFile(path, root)
226
256
  } catch {
227
257
  return 0
228
258
  }
229
- const kept = txt.split("\n").filter((l) => !l.toLowerCase().includes(q))
230
- const deleted = txt.split("\n").length - kept.length
259
+ const lines = txt.split("\n")
260
+ const kept = lines.filter((l) => !l.toLowerCase().includes(q))
261
+ const deleted = lines.length - kept.length
231
262
  if (deleted === 0) return 0
232
- const { atomicWriteText } = await import("../lib/atomic-write.ts")
233
- await atomicWriteText(path, kept.join("\n"))
263
+ await safeAtomicWriteMemory(path, root, kept.join("\n"))
234
264
  return deleted
235
265
  })
236
266
  }