minicode-ai 0.14.0 → 0.14.2

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 (88) hide show
  1. package/README.md +1 -1
  2. package/cli/args.ts +16 -3
  3. package/cli/auto-update.ts +32 -2
  4. package/cli/commands/exec.ts +9 -0
  5. package/cli/index.ts +31 -13
  6. package/cli/setup.ts +31 -19
  7. package/cli/tui.ts +63 -40
  8. package/docs/OUTPUT_PROTOCOL_SPEC.md +6 -0
  9. package/docs/OUTPUT_RENDERING_SPEC.md +28 -4
  10. package/docs/README.md +2 -2
  11. package/docs/TERMINAL_CONTRACT.md +52 -26
  12. package/docs/agents.md +2 -2
  13. package/docs/choosing-mode.md +20 -13
  14. package/docs/cli.md +11 -11
  15. package/docs/environment.md +3 -3
  16. package/docs/getting-started.md +14 -12
  17. package/docs/glossary.md +1 -1
  18. package/docs/mcp-lsp.md +1 -1
  19. package/docs/policy-sandbox.md +7 -1
  20. package/docs/security-model.md +2 -2
  21. package/docs/security.md +7 -1
  22. package/docs/tools.md +4 -4
  23. package/docs/verify-benchmark.md +16 -0
  24. package/package.json +1 -3
  25. package/src/app/mentions.ts +4 -3
  26. package/src/app/session.ts +19 -9
  27. package/src/app/tool-layer.ts +10 -3
  28. package/src/constants.ts +17 -0
  29. package/src/lib/git-hardening.ts +27 -22
  30. package/src/lib/safe-open.ts +73 -19
  31. package/src/lib/trusted-exec.ts +7 -4
  32. package/src/mcp/client.ts +34 -9
  33. package/src/mcp/transport.ts +96 -42
  34. package/src/memory/files.ts +15 -4
  35. package/src/memory/vector.ts +5 -1
  36. package/src/policy/context.ts +21 -13
  37. package/src/policy/permission.ts +75 -16
  38. package/src/policy/tool-contract.ts +21 -10
  39. package/src/policy/update-check.ts +83 -6
  40. package/src/policy/usage.ts +17 -7
  41. package/src/policy/work-mode.ts +51 -17
  42. package/src/presentation/adapter.ts +64 -2
  43. package/src/presentation/events.ts +6 -0
  44. package/src/presentation/model.ts +1 -0
  45. package/src/presentation/projection.ts +2 -0
  46. package/src/presentation/reducer.ts +1 -0
  47. package/src/providers/anthropic.ts +52 -19
  48. package/src/providers/guards.ts +98 -13
  49. package/src/providers/responses.ts +61 -23
  50. package/src/providers/sse-bounds.ts +170 -0
  51. package/src/repo/repomap.ts +10 -11
  52. package/src/runtime/execution-backend.ts +7 -8
  53. package/src/sandbox/docker.ts +113 -9
  54. package/src/session/checkpoint.ts +9 -2
  55. package/src/session/persistence.ts +5 -2
  56. package/src/session/verification.ts +55 -16
  57. package/src/skills/loader.ts +16 -3
  58. package/src/tools/bash.ts +6 -3
  59. package/src/tools/code_run.ts +6 -5
  60. package/src/tools/context.ts +8 -0
  61. package/src/tools/delete_file.ts +2 -1
  62. package/src/tools/edit.ts +2 -1
  63. package/src/tools/git.ts +128 -54
  64. package/src/tools/glob.ts +2 -1
  65. package/src/tools/grep.ts +31 -6
  66. package/src/tools/lsp.ts +5 -4
  67. package/src/tools/mcp_call.ts +3 -1
  68. package/src/tools/memory.ts +175 -180
  69. package/src/tools/move_file.ts +2 -1
  70. package/src/tools/patch.ts +2 -1
  71. package/src/tools/read_file.ts +94 -1
  72. package/src/tools/read_image.ts +2 -1
  73. package/src/tools/task.ts +2 -1
  74. package/src/tools/todo.ts +4 -5
  75. package/src/tools/web_fetch.ts +28 -12
  76. package/src/tools/web_search.ts +28 -9
  77. package/src/tools/write_file.ts +2 -1
  78. package/src/ui/assistant/simple.ts +72 -3
  79. package/src/ui/footer.ts +17 -12
  80. package/src/ui/i18n/en.ts +6 -3
  81. package/src/ui/i18n/id.ts +6 -3
  82. package/src/ui/render/width.ts +107 -79
  83. package/src/ui/runtime/screen.ts +49 -37
  84. package/src/ui/tui/app.ts +261 -209
  85. package/src/ui/tui/transcript.ts +39 -0
  86. package/CHANGELOG.md +0 -1167
  87. package/docs/PLAN_UIUX_V6.md +0 -209
  88. package/docs/changelog.md +0 -3
@@ -5,6 +5,7 @@ import {
5
5
  extractMcpText,
6
6
  getMcpPrompt,
7
7
  getMcpServerIds,
8
+ McpCallOutcomeUnknownError,
8
9
  mcpInventory,
9
10
  readMcpResource,
10
11
  } from "../mcp/client.ts"
@@ -50,7 +51,7 @@ export const mcpCallTool: Tool = {
50
51
  description:
51
52
  "Call a tool on a connected MCP server. Parameters: server id, tool name, and arguments. " +
52
53
  "The server runs OUTSIDE minicode policy: a call may read/write files, network, or processes " +
53
- "on the server side — one approval covers one server+tool+args call only.",
54
+ "on the server side — one approval covers one server+tool+args call only. If transport aborts after dispatch, the outcome is unknown; inspect remote state before retrying.",
54
55
  parameters: {
55
56
  type: "object",
56
57
  properties: {
@@ -91,6 +92,7 @@ export const mcpCallTool: Tool = {
91
92
  ? capped
92
93
  : fenceUntrustedToolOutput(`mcp_call:${sid}.${tn}`, capped)
93
94
  } catch (e) {
95
+ if (e instanceof McpCallOutcomeUnknownError) throw e
94
96
  return `[mcp] error: ${scrubSecrets((e as Error).message)}`
95
97
  }
96
98
  },
@@ -14,6 +14,7 @@ import {
14
14
  recordCandidateLesson,
15
15
  searchHybrid,
16
16
  } from "../memory/vector.ts"
17
+ import { requireToolCwd } from "./context.ts"
17
18
  import { subAgentWorkMode } from "./task.ts"
18
19
 
19
20
  export const readMemoryTool: Tool = {
@@ -31,7 +32,7 @@ export const readMemoryTool: Tool = {
31
32
  },
32
33
  async execute({ query, topK }, ctx) {
33
34
  ctx.signal.throwIfAborted()
34
- const cwd = ctx.cwd ?? process.cwd()
35
+ const cwd = requireToolCwd(ctx)
35
36
  // Mode readonly/plan: retrieval tidak boleh menulis access_count/WAL —
36
37
  // permissionMode diteruskan kernel per turn (lihat task.ts).
37
38
  const pm = (ctx as unknown as { permissionMode?: string }).permissionMode
@@ -100,198 +101,192 @@ export const readMemoryTool: Tool = {
100
101
  },
101
102
  }
102
103
 
103
- export const writeMemoryTool: Tool = {
104
- name: "write_memory",
105
- description:
106
- "Write a concise fact to project memory (MEMORY.md + vector store). Use for lasting facts, decisions, preferences, and verified snippets. Keep to 1-2 sentences.",
107
- parameters: {
108
- type: "object",
109
- properties: {
110
- text: { type: "string", description: "new memory, 1-2 concise sentences" },
111
- category: {
112
- type: "string",
113
- enum: ["fact", "decision", "preference", "snippet", "summary"],
114
- description:
115
- "retrieval category: fact/decision/preference are durable, snippet is short-lived, summary for session summaries",
116
- },
117
- tags: { type: "array", items: { type: "string" } },
118
- // MEM-01 / Fase 5A: provenance metadata untuk forensik & revokasi selektif
119
- sessionId: {
120
- type: "string",
121
- description: "session ID if this memory originates from a session",
122
- },
123
- turnId: {
124
- type: "string",
125
- description: "turn ID if this memory originates from a specific turn",
126
- },
127
- sourceKind: {
128
- type: "string",
129
- enum: ["user", "tool", "agent", "compaction", "manual", "legacy"],
130
- description: "source category: user/manual input vs tool/agent auto-memory vs compaction",
131
- },
132
- sourceRef: {
133
- type: "string",
134
- description: "reference of the source (e.g., tool name, file path)",
135
- },
136
- // [Fase 6A / ACE-03] Pelajaran kandidat wajib menjalani verifikasi dulu.
137
- validation: {
138
- type: "string",
139
- enum: ["validated", "provisional"],
140
- description:
141
- "validated (default) = durable fact; provisional = candidate lesson hidden from retrieval until the next verification promotes it",
142
- },
143
- // [Fase 12 / LF-4] Identitas memori lama yang digantikan entri baru ini —
144
- // teruskan untuk men-tombstone baris lama (supersession) lewat jalur tool.
145
- supersedes_id: {
146
- type: "string",
147
- description:
148
- "optional id of a previous memory row this new entry supersedes (replaces without deleting it)",
104
+ export function createWriteMemoryTool(runtimeSessionId?: string): Tool {
105
+ return {
106
+ name: "write_memory",
107
+ description:
108
+ "Write a concise fact to project memory (MEMORY.md + vector store). Use for lasting facts, decisions, preferences, and verified snippets. Keep to 1-2 sentences.",
109
+ parameters: {
110
+ type: "object",
111
+ properties: {
112
+ text: { type: "string", description: "new memory, 1-2 concise sentences" },
113
+ category: {
114
+ type: "string",
115
+ enum: ["fact", "decision", "preference", "snippet", "summary"],
116
+ description:
117
+ "retrieval category: fact/decision/preference are durable, snippet is short-lived, summary for session summaries",
118
+ },
119
+ tags: { type: "array", items: { type: "string" } },
120
+ // [Fase 6A / ACE-03] Pelajaran kandidat wajib menjalani verifikasi dulu.
121
+ validation: {
122
+ type: "string",
123
+ enum: ["validated", "provisional"],
124
+ description:
125
+ "validated (default) = durable fact; provisional = candidate lesson hidden from retrieval until the next verification promotes it",
126
+ },
127
+ // [Fase 12 / LF-4] Identitas memori lama yang digantikan entri baru ini —
128
+ // teruskan untuk men-tombstone baris lama (supersession) lewat jalur tool.
129
+ supersedes_id: {
130
+ type: "string",
131
+ description:
132
+ "optional id of a previous memory row this new entry supersedes (replaces without deleting it)",
133
+ },
149
134
  },
135
+ required: ["text"],
136
+ additionalProperties: false,
150
137
  },
151
- required: ["text"],
152
- additionalProperties: false,
153
- },
154
- async execute(
155
- { text, category, tags, sessionId, turnId, sourceKind, sourceRef, validation, supersedes_id },
156
- ctx,
157
- ) {
158
- ctx.signal.throwIfAborted()
159
- const t = text as string
160
- if (!t.trim()) throw new Error("text empty")
161
- const cwd = ctx.cwd ?? process.cwd()
162
- // [Fase 6A / ACE-03] Pelajaran kandidat TIDAK ditulis ke MEMORY.md (file
163
- // itu dibaca mentah saat query kosong) dan hanya hidup di store vektor
164
- // dengan status `provisional` sampai verifikasi mempromosikannya.
165
- if (validation === "provisional") {
166
- if (typeof sessionId !== "string" || !sessionId) {
167
- throw new Error("validation=provisional requires sessionId for later promotion")
138
+ async execute({ text, category, tags, validation, supersedes_id }, ctx) {
139
+ ctx.signal.throwIfAborted()
140
+ const t = text as string
141
+ if (!t.trim()) throw new Error("text empty")
142
+ const cwd = requireToolCwd(ctx)
143
+ // Identitas datang dari komposisi sesi; turn berasal dari state runtime.
144
+ // Pemanggilan manual/library tanpa binding sengaja menyimpan NULL provenance.
145
+ const sessionId = runtimeSessionId || undefined
146
+ const turnId = sessionId ? String(ctx.state.turnCount) : undefined
147
+ const sourceKind = sessionId ? "agent" : undefined
148
+ const sourceRef = sessionId ? "write_memory" : undefined
149
+ // [Fase 6A / ACE-03] Pelajaran kandidat TIDAK ditulis ke MEMORY.md (file
150
+ // itu dibaca mentah saat query kosong) dan hanya hidup di store vektor
151
+ // dengan status `provisional` sampai verifikasi mempromosikannya.
152
+ if (validation === "provisional") {
153
+ if (typeof sessionId !== "string" || !sessionId) {
154
+ throw new Error("validation=provisional requires sessionId for later promotion")
155
+ }
156
+ const baseUrl = process.env.AGENT_BASE_URL ?? "https://api.openai.com/v1"
157
+ const apiKey =
158
+ process.env.DEEPSEEK_API_KEY ??
159
+ process.env.OPENAI_API_KEY ??
160
+ process.env.AGENT_API_KEY ??
161
+ ""
162
+ const tagArr = Array.isArray(tags) ? (tags as string[]) : undefined
163
+ const id = await recordCandidateLesson(sessionId, t, {
164
+ cwd,
165
+ ...(apiKey ? { baseUrl, apiKey } : {}),
166
+ ...(category ? { category: category as string } : {}),
167
+ ...(tagArr ? { tags: tagArr } : {}),
168
+ turnId: (turnId as string | undefined) ?? null,
169
+ sourceRef: (sourceRef as string | undefined) ?? null,
170
+ })
171
+ return `candidate lesson recorded (provisional) id=${id}: ${t.slice(0, 100)}`
168
172
  }
173
+ // [Live Hardening §7.5] Validasi supersedes_id SEBELUM file/vector tersentuh.
174
+ // Id yang tak ada → error actionable, bukan tombstone no-op yang menyisakan
175
+ // row lama hidup. Kegagalan di sini tak menulis apa pun (tanpa split-brain).
176
+ if (typeof supersedes_id === "string" && supersedes_id) {
177
+ // P1.3: validasi target AKTIF (bukan sekadar "ada"). Target yang sudah
178
+ // superseded/stale harus ditolak SEBELUM file disentuh; kalau tidak,
179
+ // MEMORY.md berubah sementara store menolak → split-brain.
180
+ const target = await checkMemorySupersessionTarget(supersedes_id, cwd)
181
+ if (!target.ok) {
182
+ const msg =
183
+ target.code === "NOT_FOUND"
184
+ ? `supersedes_id not found: "${supersedes_id}". Use read_memory to get a real [id:...] from a previous result, or omit supersedes_id to store this as a new fact.`
185
+ : `supersedes_id rejected (${target.code}): ${target.reason}. Re-read memory and supersede the current live entry instead.`
186
+ throw new Error(msg)
187
+ }
188
+ }
189
+ // [Area E / D2] Tag provenance DIHITUNG SEBELUM appendMemory — versi lama
190
+ // menulisnya hanya ke hasil tool, sehingga baris di MEMORY.md tak punya
191
+ // bukti provenance (tag yang dibangun di bawah terbuang percuma).
192
+ const cat = (category as string) ?? "fact"
193
+ const tagArr = Array.isArray(tags) ? (tags as string[]) : undefined
194
+ // [Fase 12 / LF-4] id memori lama yang digantikan (supersession) dari argumen tool.
195
+ const supersedesId = typeof supersedes_id === "string" && supersedes_id ? supersedes_id : null
196
+
197
+ // MEM-01: add provenance tags to MEMORY.md (as metadata comment at end of line)
198
+ const memTags = tagArr ? [...tagArr] : []
199
+ if (sessionId) memTags.push(`session:${sessionId}`)
200
+ if (turnId) memTags.push(`turn:${turnId}`)
201
+ if (sourceKind) memTags.push(`source:${sourceKind}`)
202
+ if (sourceRef) memTags.push(`ref:${sourceRef}`)
203
+
204
+ const path = await appendMemory(t, cwd, memTags)
205
+ // [Fase 9 / 9.2] Fault-injection boundary: file (MEMORY.md) sudah ketulis,
206
+ // vector.db belum. Injector yang melempar di stage ini menyimulasikan crash
207
+ // persis di titik ini → menghasilkan entri file-only (split-brain arah 1).
208
+ invokeMemoryWriteFaultForTest("after_file_before_vector")
209
+
169
210
  const baseUrl = process.env.AGENT_BASE_URL ?? "https://api.openai.com/v1"
170
211
  const apiKey =
171
212
  process.env.DEEPSEEK_API_KEY ??
172
213
  process.env.OPENAI_API_KEY ??
173
214
  process.env.AGENT_API_KEY ??
174
215
  ""
175
- const tagArr = Array.isArray(tags) ? (tags as string[]) : undefined
176
- const id = await recordCandidateLesson(sessionId, t, {
177
- cwd,
178
- ...(apiKey ? { baseUrl, apiKey } : {}),
179
- ...(category ? { category: category as string } : {}),
180
- ...(tagArr ? { tags: tagArr } : {}),
181
- turnId: (turnId as string | undefined) ?? null,
182
- sourceRef: (sourceRef as string | undefined) ?? null,
183
- })
184
- return `candidate lesson recorded (provisional) id=${id}: ${t.slice(0, 100)}`
185
- }
186
- // [Live Hardening §7.5] Validasi supersedes_id SEBELUM file/vector tersentuh.
187
- // Id yang tak ada → error actionable, bukan tombstone no-op yang menyisakan
188
- // row lama hidup. Kegagalan di sini tak menulis apa pun (tanpa split-brain).
189
- if (typeof supersedes_id === "string" && supersedes_id) {
190
- // P1.3: validasi target AKTIF (bukan sekadar "ada"). Target yang sudah
191
- // superseded/stale harus ditolak SEBELUM file disentuh; kalau tidak,
192
- // MEMORY.md berubah sementara store menolak → split-brain.
193
- const target = await checkMemorySupersessionTarget(supersedes_id, cwd)
194
- if (!target.ok) {
195
- const msg =
196
- target.code === "NOT_FOUND"
197
- ? `supersedes_id not found: "${supersedes_id}". Use read_memory to get a real [id:...] from a previous result, or omit supersedes_id to store this as a new fact.`
198
- : `supersedes_id rejected (${target.code}): ${target.reason}. Re-read memory and supersede the current live entry instead.`
199
- throw new Error(msg)
216
+ let added = false
217
+ if (apiKey) {
218
+ try {
219
+ await addMemory(t, {
220
+ baseUrl,
221
+ apiKey,
222
+ cwd,
223
+ category: cat,
224
+ tags: tagArr,
225
+ sessionId,
226
+ turnId,
227
+ sourceKind,
228
+ sourceRef,
229
+ supersedesId,
230
+ })
231
+ added = true
232
+ } catch (e) {
233
+ process.stderr.write(`[warn] memory vector embedding failed: ${(e as Error).message}\n`)
234
+ }
200
235
  }
201
- }
202
- // [Area E / D2] Tag provenance DIHITUNG SEBELUM appendMemory — versi lama
203
- // menulisnya hanya ke hasil tool, sehingga baris di MEMORY.md tak punya
204
- // bukti provenance (tag yang dibangun di bawah terbuang percuma).
205
- const cat = (category as string) ?? "fact"
206
- const tagArr = Array.isArray(tags) ? (tags as string[]) : undefined
207
- // [Fase 12 / LF-4] id memori lama yang digantikan (supersession) dari argumen tool.
208
- const supersedesId = typeof supersedes_id === "string" && supersedes_id ? supersedes_id : null
209
-
210
- // MEM-01: add provenance tags to MEMORY.md (as metadata comment at end of line)
211
- const memTags = tagArr ? [...tagArr] : []
212
- if (sessionId) memTags.push(`session:${sessionId}`)
213
- if (turnId) memTags.push(`turn:${turnId}`)
214
- if (sourceKind) memTags.push(`source:${sourceKind}`)
215
- if (sourceRef) memTags.push(`ref:${sourceRef}`)
216
-
217
- const path = await appendMemory(t, cwd, memTags)
218
- // [Fase 9 / 9.2] Fault-injection boundary: file (MEMORY.md) sudah ketulis,
219
- // vector.db belum. Injector yang melempar di stage ini menyimulasikan crash
220
- // persis di titik ini → menghasilkan entri file-only (split-brain arah 1).
221
- invokeMemoryWriteFaultForTest("after_file_before_vector")
222
-
223
- const baseUrl = process.env.AGENT_BASE_URL ?? "https://api.openai.com/v1"
224
- const apiKey =
225
- process.env.DEEPSEEK_API_KEY ?? process.env.OPENAI_API_KEY ?? process.env.AGENT_API_KEY ?? ""
226
- let added = false
227
- if (apiKey) {
228
- try {
229
- await addMemory(t, {
230
- baseUrl,
231
- apiKey,
232
- cwd,
233
- category: cat,
234
- tags: tagArr,
235
- sessionId,
236
- turnId,
237
- sourceKind,
238
- sourceRef,
239
- supersedesId,
240
- })
241
- added = true
242
- } catch (e) {
243
- process.stderr.write(`[warn] memory vector embedding failed: ${(e as Error).message}\n`)
236
+ if (!added) {
237
+ try {
238
+ await addMemory(t, {
239
+ cwd,
240
+ category: cat,
241
+ tags: tagArr,
242
+ sessionId,
243
+ turnId,
244
+ sourceKind,
245
+ sourceRef,
246
+ supersedesId,
247
+ })
248
+ added = true
249
+ } catch (e2) {
250
+ process.stderr.write(
251
+ `[warn] memory keyword-only fallback failed: ${(e2 as Error).message}\n`,
252
+ )
253
+ }
244
254
  }
245
- }
246
- if (!added) {
247
- try {
248
- await addMemory(t, {
249
- cwd,
250
- category: cat,
251
- tags: tagArr,
252
- sessionId,
253
- turnId,
254
- sourceKind,
255
- sourceRef,
256
- supersedesId,
257
- })
258
- added = true
259
- } catch (e2) {
260
- process.stderr.write(
261
- `[warn] memory keyword-only fallback failed: ${(e2 as Error).message}\n`,
262
- )
255
+ // [Area E / D6] Fakta lama yang digantikan harus hilang dari MEMORY.md —
256
+ // jalur retrieval file membaca berkas mentah, jadi menambah fakta baru
257
+ // saja membuat fakta lama tetap "benar". Hanya dilakukan bila store vektor
258
+ // benar-benar menerapkan supersession (added=true); bila tidak, baris lama
259
+ // tetap valid dan tidak boleh dihapus.
260
+ if (added && supersedesId) {
261
+ try {
262
+ const oldText = await memoryEntryText(supersedesId, cwd)
263
+ if (oldText) await deleteMemoryEntry(oldText, cwd)
264
+ } catch {}
263
265
  }
264
- }
265
- // [Area E / D6] Fakta lama yang digantikan harus hilang dari MEMORY.md —
266
- // jalur retrieval file membaca berkas mentah, jadi menambah fakta baru
267
- // saja membuat fakta lama tetap "benar". Hanya dilakukan bila store vektor
268
- // benar-benar menerapkan supersession (added=true); bila tidak, baris lama
269
- // tetap valid dan tidak boleh dihapus.
270
- if (added && supersedesId) {
271
- try {
272
- const oldText = await memoryEntryText(supersedesId, cwd)
273
- if (oldText) await deleteMemoryEntry(oldText, cwd)
274
- } catch {}
275
- }
276
- // P1.3: bila store menolak (mis. race: target baru saja superseded), tarik
277
- // kembali baris file yang sudah ditulis agar tidak ada fakta "file-only"
278
- // yang tetap terbaca sementara relasi supersession gagal.
279
- if (!added && supersedesId) {
280
- try {
281
- await deleteMemoryEntry(t, cwd)
282
- } catch {}
283
- }
284
- // [Area E / D1] Jangan klaim sukses penuh bila indeks vektor gagal total:
285
- // fakta memang tersimpan di berkas, tetapi pencarian hybrid tak akan
286
- // menemukannya sampai reconcile. Pesan ini membuat degradasi TERLIHAT
287
- // (bukan hanya warning stderr yang tak dibaca model).
288
- const vectorNote = added
289
- ? ""
290
- : " (vector index unavailable — saved to file only; run `minicode memory reconcile` to index)"
291
- return `saved to ${path}: ${t.slice(0, 100)}${memTags.length ? ` [tags: ${JSON.stringify(memTags)}]` : ""}${vectorNote}`
292
- },
266
+ // P1.3: bila store menolak (mis. race: target baru saja superseded), tarik
267
+ // kembali baris file yang sudah ditulis agar tidak ada fakta "file-only"
268
+ // yang tetap terbaca sementara relasi supersession gagal.
269
+ if (!added && supersedesId) {
270
+ try {
271
+ await deleteMemoryEntry(t, cwd)
272
+ } catch {}
273
+ }
274
+ // [Area E / D1] Jangan klaim sukses penuh bila indeks vektor gagal total:
275
+ // fakta memang tersimpan di berkas, tetapi pencarian hybrid tak akan
276
+ // menemukannya sampai reconcile. Pesan ini membuat degradasi TERLIHAT
277
+ // (bukan hanya warning stderr yang tak dibaca model).
278
+ const vectorNote = added
279
+ ? ""
280
+ : " (vector index unavailable — saved to file only; run `minicode memory reconcile` to index)"
281
+ return `saved to ${path}: ${t.slice(0, 100)}${memTags.length ? ` [tags: ${JSON.stringify(memTags)}]` : ""}${vectorNote}`
282
+ },
283
+ }
293
284
  }
294
285
 
286
+ // Jalur library/manual tanpa komposisi sesi menyimpan provenance NULL; jalur
287
+ // CLI menggunakan createWriteMemoryTool(sessionId) dari tool-layer.
288
+ export const writeMemoryTool: Tool = createWriteMemoryTool()
289
+
295
290
  export const forgetMemoryTool: Tool = {
296
291
  name: "forget_memory",
297
292
  description:
@@ -316,7 +311,7 @@ export const forgetMemoryTool: Tool = {
316
311
  throw new Error("query or provenance criteria required")
317
312
  }
318
313
 
319
- const cwd = ctx.cwd ?? process.cwd()
314
+ const cwd = requireToolCwd(ctx)
320
315
 
321
316
  let resultText = ""
322
317
 
@@ -3,6 +3,7 @@ import { dirname } from "node:path"
3
3
  import type { Tool } from "#minicore"
4
4
  import { resolveSafePath } from "../lib/safe-open.ts"
5
5
  import { trashFile } from "../lib/trash.ts"
6
+ import { requireToolCwd } from "./context.ts"
6
7
 
7
8
  export const moveFileTool: Tool = {
8
9
  name: "move_file",
@@ -19,7 +20,7 @@ export const moveFileTool: Tool = {
19
20
  },
20
21
  async execute({ from, to }, ctx) {
21
22
  ctx.signal.throwIfAborted()
22
- const root = ctx.cwd ?? process.cwd()
23
+ const root = requireToolCwd(ctx)
23
24
  const f = from as string
24
25
  const t = to as string
25
26
  // Verifikasi kedua ujung via pemilik tunggal (logis + target nyata) —
@@ -3,6 +3,7 @@ import type { Tool } from "#minicore"
3
3
  import { LIMITS } from "../constants.ts"
4
4
  import { atomicWriteText } from "../lib/atomic-write.ts"
5
5
  import { assertSafeWriteTarget, resolveSafePath, safeReadFile } from "../lib/safe-open.ts"
6
+ import { requireToolCwd } from "./context.ts"
6
7
  import { flexibleMatch } from "./edit.ts"
7
8
 
8
9
  // Apply SEARCH/REPLACE block (a la Aider) ke file. Search block harus match
@@ -38,7 +39,7 @@ export const applyPatchTool: Tool = {
38
39
  async execute({ path, patches }, ctx) {
39
40
  ctx.signal.throwIfAborted()
40
41
  const p = path as string
41
- const root = ctx.cwd ?? process.cwd()
42
+ const root = requireToolCwd(ctx)
42
43
  // Verifikasi path terpusat (logis + target nyata) — detail di safe-open.ts.
43
44
  const { abs, real: realAbs } = await resolveSafePath(p, root)
44
45
  // Tolak menimpa symlink final (swap antara cek dan tulis gagal tutup).
@@ -1,8 +1,10 @@
1
+ import type { FileHandle } from "node:fs/promises"
1
2
  import { isAbsolute, resolve } from "node:path"
2
3
  import type { Tool } from "#minicore"
3
4
  import { LIMITS } from "../constants.ts"
4
5
  import { safeOpenRead } from "../lib/safe-open.ts"
5
6
  import { scrubSecrets } from "../policy/scrub.ts"
7
+ import { requireToolCwd } from "./context.ts"
6
8
 
7
9
  // defense-in-depth: also jail inside tool (permission layer is primary)
8
10
 
@@ -66,6 +68,88 @@ export function formatLines(
66
68
  return { text: body + footer, totalLines, from, to }
67
69
  }
68
70
 
71
+ async function formatHandleRange(
72
+ handle: FileHandle,
73
+ from: number,
74
+ limit: number,
75
+ signal: AbortSignal,
76
+ ): Promise<string> {
77
+ const chunk = Buffer.alloc(64 * 1024)
78
+ const decoder = new TextDecoder()
79
+ const selected: string[] = []
80
+ const end = from + limit - 1
81
+ let line = ""
82
+ let lineNumber = 1
83
+ let totalLines = 0
84
+ let position = 0
85
+ let sawBytes = false
86
+ let endedWithNewline = false
87
+
88
+ const appendSegment = (segment: string): void => {
89
+ if (!segment) return
90
+ const keep = LIMITS.READ_FILE_MAX_LINE_CHARS + 1 - line.length
91
+ if (keep > 0) line += segment.slice(0, keep)
92
+ }
93
+ const finishLine = (): void => {
94
+ if (lineNumber >= from && lineNumber <= end) selected.push(line)
95
+ totalLines++
96
+ lineNumber++
97
+ line = ""
98
+ }
99
+ const consume = (text: string): void => {
100
+ if (!text) return
101
+ let start = 0
102
+ for (let i = 0; i < text.length; i++) {
103
+ if (text[i] !== "\n") continue
104
+ appendSegment(text.slice(start, i))
105
+ finishLine()
106
+ endedWithNewline = true
107
+ start = i + 1
108
+ }
109
+ if (start < text.length) {
110
+ appendSegment(text.slice(start))
111
+ endedWithNewline = false
112
+ }
113
+ }
114
+
115
+ while (true) {
116
+ signal.throwIfAborted()
117
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, position)
118
+ if (bytesRead === 0) break
119
+ sawBytes = true
120
+ position += bytesRead
121
+ consume(decoder.decode(chunk.subarray(0, bytesRead), { stream: true }))
122
+ }
123
+ consume(decoder.decode())
124
+ // String.split treats an empty file as one empty line and does not add a
125
+ // phantom line after a final newline; keep the same paging contract.
126
+ if (!endedWithNewline || !sawBytes) finishLine()
127
+ totalLines = Math.max(1, totalLines)
128
+
129
+ if (from > totalLines)
130
+ return `(offset ${from} is past the end of the file — ${totalLines} lines total)`
131
+
132
+ const to = Math.min(totalLines, end)
133
+ const width = String(to).length
134
+ const body = selected
135
+ .map((raw, index) => {
136
+ const capped =
137
+ raw.length > LIMITS.READ_FILE_MAX_LINE_CHARS
138
+ ? `${raw.slice(0, LIMITS.READ_FILE_MAX_LINE_CHARS)}… [line truncated]`
139
+ : raw
140
+ return `${String(from + index).padStart(width, " ")}: ${capped}`
141
+ })
142
+ .join("\n")
143
+ const remaining = totalLines - to
144
+ const footer =
145
+ remaining > 0
146
+ ? `\n… ${remaining} more lines (continue: offset=${to + 1})`
147
+ : from > 1
148
+ ? "\n(end of file)"
149
+ : ""
150
+ return body + footer
151
+ }
152
+
69
153
  export const readFileTool: Tool = {
70
154
  name: "read_file",
71
155
  description:
@@ -83,7 +167,7 @@ export const readFileTool: Tool = {
83
167
  async execute({ path, offset, limit }, ctx) {
84
168
  ctx.signal.throwIfAborted()
85
169
  const p = path as string
86
- const root = ctx.cwd ?? process.cwd()
170
+ const root = requireToolCwd(ctx)
87
171
  const abs = isAbsolute(p) ? resolve(p) : resolve(root, p)
88
172
  // Semua verifikasi path (jail + sensitif + O_NOFOLLOW) terjadi di SATU
89
173
  // titik saat open — detail di safe-open.ts. Tidak ada resolve/stat
@@ -117,6 +201,15 @@ export const readFileTool: Tool = {
117
201
  `file too large: ${p} (${st.size} bytes > ${LIMITS.READ_FILE_MAX_BYTES}) — read it in chunks with offset/limit`,
118
202
  )
119
203
  }
204
+ if (paged) {
205
+ const rawOffset = Number(offset ?? 1)
206
+ const from = Number.isFinite(rawOffset) ? Math.max(1, Math.floor(rawOffset)) : 1
207
+ const rawLimit = Number(limit ?? LIMITS.READ_FILE_DEFAULT_LINE_LIMIT)
208
+ const pageLimit = Number.isFinite(rawLimit)
209
+ ? Math.min(Math.max(1, Math.floor(rawLimit)), LIMITS.READ_FILE_MAX_LINE_LIMIT)
210
+ : LIMITS.READ_FILE_DEFAULT_LINE_LIMIT
211
+ return scrubSecrets(await formatHandleRange(handle, from, pageLimit, ctx.signal))
212
+ }
120
213
  raw = await handle.readFile("utf8")
121
214
  } finally {
122
215
  await handle.close().catch(() => {})
@@ -3,6 +3,7 @@ import type { Tool } from "#minicore"
3
3
  import { LIMITS } from "../constants.ts"
4
4
  import { safeOpenRead } from "../lib/safe-open.ts"
5
5
  import { estimateImageTokens } from "../policy/context.ts"
6
+ import { requireToolCwd } from "./context.ts"
6
7
 
7
8
  // Batas b64 = batas truncate kernel yang sebenarnya: toolResultMaxTokens
8
9
  // (default 4096) × DEFAULT_CHARS_PER_TOKEN (4) = 16.384 chars, dengan margin
@@ -25,7 +26,7 @@ export const readImageTool: Tool = {
25
26
  async execute({ path }, ctx) {
26
27
  ctx.signal.throwIfAborted()
27
28
  const p = path as string
28
- const root = ctx.cwd ?? process.cwd()
29
+ const root = requireToolCwd(ctx)
29
30
  const abs = isAbsolute(p) ? resolve(p) : resolve(root, p)
30
31
  // TOCTOU-safe: safeOpenRead = realpath(abs) → cek jail+sensitif di dalam
31
32
  // root → open(preReal, O_NOFOLLOW). Bukan open(abs) yang bisa di-swap jadi
package/src/tools/task.ts CHANGED
@@ -34,6 +34,7 @@ import {
34
34
  persistEffectIntent,
35
35
  persistEffectReceipt,
36
36
  } from "../session/verification.ts"
37
+ import { requireToolCwd } from "./context.ts"
37
38
  import { withEvidence } from "./evidence.ts"
38
39
  import { todoSession } from "./todo.ts"
39
40
 
@@ -347,7 +348,7 @@ export const delegateTaskTool: Tool = {
347
348
  })
348
349
  // Child tools are wrapped with canonical P2.10 evidence after the child
349
350
  // identity and authoritative domain exist (see below).
350
- const parentCwd = ctx.cwd ?? process.cwd()
351
+ const parentCwd = requireToolCwd(ctx)
351
352
  const parentId = todoSession.id || "main"
352
353
  // P2.9: id anak = identitas Session KANONIK (128-bit). Id P1 lawas
353
354
  // `sub_<8hex>` (32-bit) tidak cukup untuk durable authority; prefix `sub_`
package/src/tools/todo.ts CHANGED
@@ -14,6 +14,7 @@ import { type CanonicalAssignmentTable, encodeCanonicalAssignments } from "../ta
14
14
  import { isTaskId, TaskError } from "../task/model.ts"
15
15
  import { TaskStore } from "../task/store.ts"
16
16
  import { hasCanonicalIdentity, hasCanonicalTasks, synchronizeCanonicalTasks } from "../task/sync.ts"
17
+ import { requireToolCwd } from "./context.ts"
17
18
 
18
19
  // Todo list per sesi — state eksplisit untuk task multi-langkah.
19
20
  // Tanpa ini agent tidak punya tempat menyimpan rencana antar step, sehingga
@@ -561,10 +562,8 @@ export const todoSession = { id: "default", cwd: undefined as string | undefined
561
562
  * so the operation stays bound to the session it was invoked with no matter what
562
563
  * another request does to the global.
563
564
  *
564
- * Resolution order (preserved from the original code, which preferred `ctx` over
565
- * the global):
566
- * sessionId: ctx.sessionId -> todoSession.id
567
- * cwd: ctx.cwd -> todoSession.cwd -> process.cwd()
565
+ * Identitas boleh memakai default composition. Root workspace wajib dari
566
+ * request context agar tool tidak berpindah diam-diam ke cwd proses.
568
567
  *
569
568
  * `todoSession` remains the composition-root DEFAULT — `cli/setup.ts` binds it
570
569
  * once at startup and never mutates it during operation. It is read here exactly
@@ -575,7 +574,7 @@ export function todoOperationContext(ctx: unknown): { sessionId: string; cwd: st
575
574
  const c = (ctx ?? {}) as { sessionId?: string; cwd?: string }
576
575
  return {
577
576
  sessionId: typeof c.sessionId === "string" && c.sessionId !== "" ? c.sessionId : todoSession.id,
578
- cwd: c.cwd ?? todoSession.cwd ?? process.cwd(),
577
+ cwd: requireToolCwd(c),
579
578
  }
580
579
  }
581
580