minicode-ai 0.27.0 → 0.28.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.
- package/cli/args.ts +120 -16
- package/cli/commands/acp.ts +38 -28
- package/cli/commands/auth.ts +17 -17
- package/cli/commands/config.ts +65 -66
- package/cli/commands/daemon.ts +44 -16
- package/cli/commands/doctor.ts +11 -12
- package/cli/commands/exec.ts +35 -73
- package/cli/commands/mcp.ts +25 -8
- package/cli/commands/memory.ts +16 -24
- package/cli/commands/openwork.ts +6 -2
- package/cli/commands/pricing.ts +14 -12
- package/cli/commands/providers.ts +36 -57
- package/cli/commands/sessions.ts +24 -18
- package/cli/commands/skills.ts +33 -18
- package/cli/commands/stats.ts +15 -30
- package/cli/commands.ts +73 -44
- package/cli/context-command-run.ts +30 -18
- package/cli/index.ts +48 -98
- package/cli/model-manager.ts +7 -2
- package/cli/provider-manager.ts +33 -18
- package/cli/router.ts +41 -12
- package/cli/setup.ts +246 -123
- package/cli/tui.ts +303 -100
- package/docs/TERMINAL_CONTRACT.md +254 -69
- package/docs/UI_RENDER_PIPELINE.md +9 -1
- package/docs/agents.md +2 -2
- package/docs/architecture.md +3 -3
- package/docs/choosing-mode.md +7 -9
- package/docs/cli.md +3 -5
- package/docs/environment.md +1 -2
- package/docs/policy-sandbox.md +3 -3
- package/docs/repl.md +2 -2
- package/docs/tools.md +1 -1
- package/package.json +1 -1
- package/src/app/mentions.ts +60 -13
- package/src/app/rag-layer.ts +17 -20
- package/src/app/session.ts +119 -66
- package/src/app/tool-layer.ts +12 -17
- package/src/config.ts +64 -104
- package/src/constants.ts +4 -6
- package/src/daemon/capability.ts +8 -1
- package/src/daemon/control.ts +3 -2
- package/src/daemon/server.ts +57 -0
- package/src/hooks/run.ts +73 -41
- package/src/lib/db-path.ts +47 -0
- package/src/lib/process-tree.ts +62 -0
- package/src/lib/public-http.ts +88 -23
- package/src/lib/trusted-exec.ts +48 -1
- package/src/lsp/client.ts +62 -17
- package/src/mcp/client.ts +85 -38
- package/src/mcp/http-transport.ts +28 -16
- package/src/mcp/transport.ts +42 -6
- package/src/memory/files.ts +164 -134
- package/src/memory/vector.ts +371 -420
- package/src/policy/approval-binding.ts +122 -45
- package/src/policy/bash-guard.ts +18 -7
- package/src/policy/compaction.ts +51 -18
- package/src/policy/context-window.ts +31 -8
- package/src/policy/context.ts +62 -36
- package/src/policy/executor.ts +17 -7
- package/src/policy/microcompact.ts +4 -3
- package/src/policy/no-progress.ts +103 -22
- package/src/policy/permission.ts +36 -12
- package/src/policy/tool-contract.ts +74 -416
- package/src/policy/usage.ts +24 -2
- package/src/policy/verifier.ts +50 -2
- package/src/policy/work-mode.ts +28 -54
- package/src/presentation/adapter.ts +24 -16
- package/src/providers/provision.ts +6 -56
- package/src/providers/responses.ts +1 -0
- package/src/runtime/execution-journal.ts +4 -29
- package/src/sandbox/docker.ts +58 -34
- package/src/sandbox/mask.ts +157 -0
- package/src/sandbox/os.ts +107 -73
- package/src/session/authority.ts +29 -10
- package/src/session/context-projection.ts +6 -5
- package/src/session/open-work.ts +26 -3
- package/src/session/persistence.ts +25 -58
- package/src/session/verification.ts +170 -20
- package/src/skills/loader.ts +31 -16
- package/src/task/production-scheduler.ts +13 -1
- package/src/task/store.ts +20 -37
- package/src/telemetry/trace.ts +27 -0
- package/src/tools/ask_user.ts +1 -13
- package/src/tools/bash.ts +27 -92
- package/src/tools/code_run.ts +1 -1
- package/src/tools/context.ts +133 -0
- package/src/tools/delete_file.ts +3 -2
- package/src/tools/edit.ts +37 -72
- package/src/tools/git.ts +86 -9
- package/src/tools/glob.ts +26 -51
- package/src/tools/grep.ts +67 -57
- package/src/tools/hashline.ts +4 -0
- package/src/tools/lsp.ts +11 -8
- package/src/tools/mcp_call.ts +9 -6
- package/src/tools/memory.ts +56 -33
- package/src/tools/move_file.ts +36 -10
- package/src/tools/patch.ts +13 -21
- package/src/tools/read_file.ts +18 -25
- package/src/tools/read_image.ts +35 -33
- package/src/tools/submit_result.ts +29 -8
- package/src/tools/task.ts +74 -17
- package/src/tools/todo.ts +181 -74
- package/src/tools/web_fetch.ts +42 -2
- package/src/tools/web_search.ts +47 -8
- package/src/ui/approval/prompt.ts +206 -47
- package/src/ui/assistant/turn-status.ts +14 -5
- package/src/ui/footer.ts +4 -4
- package/src/ui/i18n/en.ts +47 -23
- package/src/ui/i18n/id.ts +76 -51
- package/src/ui/input/input.ts +4 -3
- package/src/ui/input/prompt-engine.ts +35 -5
- package/src/ui/render/activity-panel.ts +4 -2
- package/src/ui/render/hint.ts +7 -4
- package/src/ui/render/list.ts +32 -0
- package/src/ui/render/markdown.ts +6 -3
- package/src/ui/render/notice.ts +19 -0
- package/src/ui/render/table-grid.ts +7 -8
- package/src/ui/render/theme.ts +113 -39
- package/src/ui/runtime/screen.ts +74 -10
- package/src/ui/runtime/spinner.ts +19 -6
- package/src/ui/screens/dialog.ts +19 -1
- package/src/ui/screens/form.ts +80 -35
- package/src/ui/screens/model-manager.ts +82 -61
- package/src/ui/screens/output-window.ts +263 -0
- package/src/ui/screens/picker.ts +94 -81
- package/src/ui/screens/provider-manager.ts +100 -69
- package/src/ui/screens/wizard.ts +117 -28
- package/src/ui/tui/app.ts +196 -33
- package/src/ui/tui/transcript.ts +154 -25
- package/vendor/minicore/src/core/executor.ts +2 -0
- package/vendor/minicore/src/core/loop.ts +17 -6
- package/vendor/minicore/src/core/session.ts +3 -0
- package/vendor/minicore/src/core/tool.ts +1 -0
- package/vendor/minicore/src/providers/openai-compat.ts +28 -19
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
|
|
21
21
|
import { LIMITS } from "../constants.ts"
|
|
22
22
|
import { isPrivateHostWithDns } from "../lib/net.ts"
|
|
23
|
+
import { publicHttp } from "../lib/public-http.ts"
|
|
23
24
|
|
|
24
25
|
/**
|
|
25
26
|
* Kemampuan transport yang dipakai `McpConnection` setelah koneksi terbuka.
|
|
@@ -160,17 +161,21 @@ export class McpHttpTransport implements McpTransportLike {
|
|
|
160
161
|
else signal?.addEventListener("abort", onAbort, { once: true })
|
|
161
162
|
let res: Response
|
|
162
163
|
try {
|
|
163
|
-
res = await
|
|
164
|
+
res = await publicHttp.request(this.url, {
|
|
164
165
|
method: "POST",
|
|
165
166
|
headers: this.headers("application/json, text/event-stream"),
|
|
166
167
|
body,
|
|
167
168
|
signal: controller.signal,
|
|
168
|
-
|
|
169
|
+
allowPrivateHost: this.allowPrivate,
|
|
169
170
|
})
|
|
170
171
|
} catch (e) {
|
|
171
172
|
clearTimeout(timer)
|
|
172
173
|
signal?.removeEventListener("abort", onAbort)
|
|
173
174
|
const msg = (e as Error).message
|
|
175
|
+
if (msg.startsWith("blocked private host:")) {
|
|
176
|
+
this.blockedPrivate = true
|
|
177
|
+
throw new Error(`MCP http: private host rejected: ${this.url.hostname}`)
|
|
178
|
+
}
|
|
174
179
|
throw new Error(
|
|
175
180
|
`MCP http: ${method} failed: ${msg === "timeout" ? `timeout ${timeoutMs}ms` : msg}`,
|
|
176
181
|
)
|
|
@@ -222,13 +227,16 @@ export class McpHttpTransport implements McpTransportLike {
|
|
|
222
227
|
// request()/connect()) alih-alih mengirim lalu diam.
|
|
223
228
|
void (async () => {
|
|
224
229
|
if (!(await this.checkHost())) return
|
|
225
|
-
await
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
230
|
+
await publicHttp
|
|
231
|
+
.request(this.url, {
|
|
232
|
+
method: "POST",
|
|
233
|
+
headers: this.headers("application/json, text/event-stream"),
|
|
234
|
+
body: JSON.stringify({ jsonrpc: "2.0", method, params }),
|
|
235
|
+
allowPrivateHost: this.allowPrivate,
|
|
236
|
+
signal: AbortSignal.timeout(Math.min(LIMITS.MCP_HANDSHAKE_TIMEOUT_MS, 3_000)),
|
|
237
|
+
})
|
|
238
|
+
.then((r) => r.body?.cancel())
|
|
239
|
+
.catch(() => {})
|
|
232
240
|
})()
|
|
233
241
|
}
|
|
234
242
|
|
|
@@ -239,11 +247,15 @@ export class McpHttpTransport implements McpTransportLike {
|
|
|
239
247
|
// itu bukan kegagalan bagi kita. Audit F7: cleanup TIDAK boleh jadi jalur
|
|
240
248
|
// egress tanpa validasi host (blockedPrivate = host terbukti privat).
|
|
241
249
|
if (this.sessionId && !this.blockedPrivate && (await this.checkHost())) {
|
|
242
|
-
await
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
250
|
+
await publicHttp
|
|
251
|
+
.request(this.url, {
|
|
252
|
+
method: "DELETE",
|
|
253
|
+
headers: this.headers("application/json"),
|
|
254
|
+
allowPrivateHost: this.allowPrivate,
|
|
255
|
+
signal: AbortSignal.timeout(Math.min(LIMITS.MCP_HANDSHAKE_TIMEOUT_MS, 3_000)),
|
|
256
|
+
})
|
|
257
|
+
.then((r) => r.body?.cancel())
|
|
258
|
+
.catch(() => {})
|
|
247
259
|
}
|
|
248
260
|
}
|
|
249
261
|
}
|
|
@@ -299,7 +311,7 @@ export async function readSseResponse(
|
|
|
299
311
|
const { done, value } = await reader.read()
|
|
300
312
|
if (done) break
|
|
301
313
|
total += value.byteLength
|
|
302
|
-
if (total > LIMITS.
|
|
314
|
+
if (total > LIMITS.MCP_HTTP_BODY_MAX_BYTES) {
|
|
303
315
|
throw new Error("MCP http: aliran SSE melewati batas ukuran")
|
|
304
316
|
}
|
|
305
317
|
buffer += decoder.decode(value, { stream: true })
|
|
@@ -377,7 +389,7 @@ async function readCapped(res: Response): Promise<string> {
|
|
|
377
389
|
const { done, value } = await reader.read()
|
|
378
390
|
if (done) break
|
|
379
391
|
out += decoder.decode(value, { stream: true })
|
|
380
|
-
if (out.length > LIMITS.
|
|
392
|
+
if (out.length > LIMITS.MCP_HTTP_BODY_MAX_BYTES) {
|
|
381
393
|
throw new Error("MCP http: balasan melewati batas ukuran")
|
|
382
394
|
}
|
|
383
395
|
}
|
package/src/mcp/transport.ts
CHANGED
|
@@ -1,9 +1,15 @@
|
|
|
1
|
-
import { type ChildProcess, spawn } from "node:child_process"
|
|
1
|
+
import { type ChildProcess, spawn, spawnSync } from "node:child_process"
|
|
2
2
|
import { LIMITS } from "../constants.ts"
|
|
3
|
+
import { resolveSpawnTarget, resolveTrustedExecutable } from "../lib/trusted-exec.ts"
|
|
3
4
|
import { sanitizeSpawnEnv } from "../policy/scrub.ts"
|
|
4
5
|
|
|
5
6
|
export class McpTransport {
|
|
7
|
+
private readonly maxFrameBytes: number
|
|
8
|
+
constructor(opts: { maxFrameBytes?: number } = {}) {
|
|
9
|
+
this.maxFrameBytes = opts.maxFrameBytes ?? LIMITS.MCP_STDIO_FRAME_MAX_BYTES
|
|
10
|
+
}
|
|
6
11
|
private proc: ChildProcess | null = null
|
|
12
|
+
private winCmdTree = false
|
|
7
13
|
private stdoutFrame = Buffer.alloc(0)
|
|
8
14
|
private pending = new Map<
|
|
9
15
|
string | number,
|
|
@@ -28,11 +34,14 @@ export class McpTransport {
|
|
|
28
34
|
async connect(command: string, args: string[], env: Record<string, string> = {}): Promise<void> {
|
|
29
35
|
if (this.proc) throw new Error("transport already connected")
|
|
30
36
|
|
|
31
|
-
|
|
37
|
+
const target = resolveSpawnTarget(command, args)
|
|
38
|
+
this.winCmdTree = target.windowsVerbatimArguments === true
|
|
39
|
+
this.proc = spawn(target.command, target.args, {
|
|
32
40
|
stdio: ["pipe", "pipe", "pipe"],
|
|
33
41
|
// env kredensial di-strip; env eksplisit config server menang setelahnya
|
|
34
42
|
env: sanitizeSpawnEnv(process.env, env),
|
|
35
43
|
signal: this.killSignal.signal,
|
|
44
|
+
...(target.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
|
|
36
45
|
})
|
|
37
46
|
|
|
38
47
|
this.proc.on("error", (err) => this.failAll(err))
|
|
@@ -101,6 +110,22 @@ export class McpTransport {
|
|
|
101
110
|
try {
|
|
102
111
|
this.proc?.stdin?.end()
|
|
103
112
|
} catch {}
|
|
113
|
+
// Untuk shim .cmd/.bat di Windows, bunuh seluruh subtree SEBELUM killSignal.abort()
|
|
114
|
+
// karena abort() hanya menghentikan wrapper cmd.exe dan meninggalkan anak (node/Chromium).
|
|
115
|
+
if (
|
|
116
|
+
this.winCmdTree &&
|
|
117
|
+
process.platform === "win32" &&
|
|
118
|
+
this.proc?.pid !== undefined &&
|
|
119
|
+
this.proc.exitCode === null
|
|
120
|
+
) {
|
|
121
|
+
try {
|
|
122
|
+
spawnSync(
|
|
123
|
+
resolveTrustedExecutable("taskkill"),
|
|
124
|
+
["/pid", String(this.proc.pid), "/T", "/F"],
|
|
125
|
+
{ stdio: "ignore", env: sanitizeSpawnEnv(process.env) },
|
|
126
|
+
)
|
|
127
|
+
} catch {}
|
|
128
|
+
}
|
|
104
129
|
this.killSignal.abort()
|
|
105
130
|
if (this.proc) {
|
|
106
131
|
const p = this.proc
|
|
@@ -108,7 +133,18 @@ export class McpTransport {
|
|
|
108
133
|
await new Promise<void>((r) => {
|
|
109
134
|
const t = setTimeout(() => {
|
|
110
135
|
try {
|
|
111
|
-
|
|
136
|
+
if (process.platform === "win32" && p.pid !== undefined) {
|
|
137
|
+
spawnSync(
|
|
138
|
+
resolveTrustedExecutable("taskkill"),
|
|
139
|
+
["/pid", String(p.pid), "/T", "/F"],
|
|
140
|
+
{
|
|
141
|
+
stdio: "ignore",
|
|
142
|
+
env: sanitizeSpawnEnv(process.env),
|
|
143
|
+
},
|
|
144
|
+
)
|
|
145
|
+
} else {
|
|
146
|
+
p.kill("SIGKILL")
|
|
147
|
+
}
|
|
112
148
|
} catch {}
|
|
113
149
|
r()
|
|
114
150
|
}, 2_000)
|
|
@@ -172,7 +208,7 @@ export class McpTransport {
|
|
|
172
208
|
for (let i = 0; i < chunk.length; i++) {
|
|
173
209
|
if (chunk[i] !== 0x0a) continue
|
|
174
210
|
const part = chunk.subarray(start, i)
|
|
175
|
-
if (this.stdoutFrame.length + part.length >
|
|
211
|
+
if (this.stdoutFrame.length + part.length > this.maxFrameBytes) {
|
|
176
212
|
this.rejectOversizedFrame(this.stdoutFrame.length + part.length)
|
|
177
213
|
return
|
|
178
214
|
}
|
|
@@ -184,7 +220,7 @@ export class McpTransport {
|
|
|
184
220
|
}
|
|
185
221
|
if (start < chunk.length) {
|
|
186
222
|
const remainder = chunk.subarray(start)
|
|
187
|
-
if (this.stdoutFrame.length + remainder.length >
|
|
223
|
+
if (this.stdoutFrame.length + remainder.length > this.maxFrameBytes) {
|
|
188
224
|
this.rejectOversizedFrame(this.stdoutFrame.length + remainder.length)
|
|
189
225
|
return
|
|
190
226
|
}
|
|
@@ -214,7 +250,7 @@ export class McpTransport {
|
|
|
214
250
|
|
|
215
251
|
private rejectOversizedFrame(size: number): void {
|
|
216
252
|
const error = new Error(
|
|
217
|
-
`MCP stdio frame exceeds ${
|
|
253
|
+
`MCP stdio frame exceeds ${this.maxFrameBytes} bytes (at least ${size})`,
|
|
218
254
|
)
|
|
219
255
|
this.closed = true
|
|
220
256
|
this.stdoutFrame = Buffer.alloc(0)
|
package/src/memory/files.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { appendFile, mkdir, readFile
|
|
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(
|
|
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
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
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
|
-
//
|
|
84
|
-
//
|
|
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
|
-
|
|
93
|
-
|
|
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) ===
|
|
104
|
+
if (memLocks.get(path) === tail) memLocks.delete(path)
|
|
102
105
|
}
|
|
103
106
|
}
|
|
104
107
|
|
|
105
|
-
|
|
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
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
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
|
-
|
|
153
|
-
|
|
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
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
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
|
|
201
|
+
return {
|
|
202
|
+
text: (tagMatch ? body.slice(0, tagMatch.index!) : body).trim(),
|
|
203
|
+
tags: [],
|
|
204
|
+
}
|
|
166
205
|
}
|
|
167
206
|
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
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
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
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
|
-
|
|
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
|
|
255
|
+
txt = await safeReadMemoryFile(path, root)
|
|
226
256
|
} catch {
|
|
227
257
|
return 0
|
|
228
258
|
}
|
|
229
|
-
const
|
|
230
|
-
const
|
|
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
|
-
|
|
233
|
-
await atomicWriteText(path, kept.join("\n"))
|
|
263
|
+
await safeAtomicWriteMemory(path, root, kept.join("\n"))
|
|
234
264
|
return deleted
|
|
235
265
|
})
|
|
236
266
|
}
|