minicode-ai 0.11.0 → 0.13.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 (221) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/LICENSE +21 -21
  3. package/README.md +4 -4
  4. package/cli/args.ts +46 -0
  5. package/cli/commands/acp.ts +163 -10
  6. package/cli/commands/config.ts +33 -18
  7. package/cli/commands/daemon.ts +515 -0
  8. package/cli/commands/exec.ts +145 -53
  9. package/cli/commands/openwork.ts +986 -0
  10. package/cli/commands/sessions.ts +4 -1
  11. package/cli/commands/stats.ts +34 -4
  12. package/cli/commands.ts +217 -2
  13. package/cli/index.ts +146 -14
  14. package/cli/recovery-warning.ts +115 -0
  15. package/cli/router.ts +32 -1
  16. package/cli/setup.ts +2332 -171
  17. package/cli/tui.ts +113 -7
  18. package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +489 -0
  19. package/docs/OUTPUT_EVENT_MODEL.md +289 -0
  20. package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +391 -0
  21. package/docs/OUTPUT_PROTOCOL_SPEC.md +285 -0
  22. package/docs/OUTPUT_RENDERING_SPEC.md +248 -0
  23. package/docs/OUTPUT_UX_RULES.md +449 -0
  24. package/docs/PLAN_UIUX_V6.md +2 -2
  25. package/docs/README.md +4 -3
  26. package/docs/TERMINAL_CONTRACT.md +278 -66
  27. package/docs/architecture.md +89 -7
  28. package/docs/changelog.md +1 -1
  29. package/docs/choosing-mode.md +2 -2
  30. package/docs/cli.md +9 -5
  31. package/docs/concepts.md +1 -1
  32. package/docs/contributing.md +9 -2
  33. package/docs/environment.md +6 -2
  34. package/docs/exec.md +46 -5
  35. package/docs/memory-sessions.md +2 -0
  36. package/docs/policy-sandbox.md +1 -1
  37. package/docs/pricing-budget.md +1 -1
  38. package/docs/quickstart.md +2 -2
  39. package/docs/repl.md +6 -2
  40. package/docs/security-model.md +1 -1
  41. package/docs/security.md +1 -1
  42. package/docs/skills.md +2 -2
  43. package/docs/terminal.md +9 -5
  44. package/docs/tools.md +1 -1
  45. package/package.json +35 -5
  46. package/src/app/session.ts +261 -15
  47. package/src/app/tool-layer.ts +94 -7
  48. package/src/daemon/approvals.ts +361 -0
  49. package/src/daemon/capability.ts +145 -0
  50. package/src/daemon/children.ts +142 -0
  51. package/src/daemon/client.ts +267 -0
  52. package/src/daemon/control.ts +350 -0
  53. package/src/daemon/discovery.ts +234 -0
  54. package/src/daemon/feed.ts +155 -0
  55. package/src/daemon/framing.ts +94 -0
  56. package/src/daemon/host.ts +316 -0
  57. package/src/daemon/protocol.ts +217 -0
  58. package/src/daemon/resource.ts +170 -0
  59. package/src/daemon/sanitize.ts +57 -0
  60. package/src/daemon/server.ts +627 -0
  61. package/src/daemon/store.ts +317 -0
  62. package/src/daemon/subscription.ts +270 -0
  63. package/src/daemon/telemetry.ts +81 -0
  64. package/src/hooks/run.ts +12 -1
  65. package/src/lib/atomic-write.ts +29 -3
  66. package/src/lib/db-path.ts +26 -0
  67. package/src/lib/keystore.ts +544 -42
  68. package/src/lib/net.ts +43 -1
  69. package/src/lib/safe-open.ts +116 -1
  70. package/src/lib/session-id.ts +15 -0
  71. package/src/lsp/client.ts +123 -5
  72. package/src/mcp/client.ts +139 -17
  73. package/src/mcp/server.ts +177 -50
  74. package/src/mcp/transport.ts +16 -19
  75. package/src/memory/vector.ts +770 -55
  76. package/src/policy/allowlist.ts +14 -2
  77. package/src/policy/bash-guard.ts +105 -10
  78. package/src/policy/compaction.ts +82 -5
  79. package/src/policy/consequence-engine.ts +220 -0
  80. package/src/policy/context.ts +132 -0
  81. package/src/policy/executor.ts +187 -121
  82. package/src/policy/no-progress.ts +559 -0
  83. package/src/policy/permission.ts +4 -8
  84. package/src/policy/pricing.ts +17 -3
  85. package/src/policy/scrub.ts +69 -2
  86. package/src/policy/tool-contract.ts +515 -0
  87. package/src/policy/usage.ts +310 -24
  88. package/src/policy/verifier.ts +6 -3
  89. package/src/policy/work-mode.ts +182 -0
  90. package/src/presentation/adapter.ts +533 -26
  91. package/src/presentation/events.ts +151 -0
  92. package/src/presentation/model.ts +180 -27
  93. package/src/presentation/projection.ts +858 -0
  94. package/src/presentation/reducer.ts +645 -310
  95. package/src/presentation/store.ts +12 -7
  96. package/src/providers/anthropic.ts +18 -10
  97. package/src/providers/responses.ts +17 -7
  98. package/src/runtime/capability.ts +409 -0
  99. package/src/runtime/child-execution.ts +274 -0
  100. package/src/runtime/composition.ts +958 -0
  101. package/src/runtime/dispatch.ts +591 -0
  102. package/src/runtime/execution-backend.ts +632 -0
  103. package/src/runtime/execution-events.ts +272 -0
  104. package/src/runtime/execution-id.ts +230 -0
  105. package/src/runtime/execution-journal.ts +926 -0
  106. package/src/runtime/execution-kernel.ts +456 -0
  107. package/src/runtime/execution-registry.ts +379 -0
  108. package/src/runtime/process-supervision.ts +276 -0
  109. package/src/runtime/production-execution.ts +551 -0
  110. package/src/runtime/production-runtime.ts +217 -0
  111. package/src/runtime/recovery-safety.ts +70 -0
  112. package/src/runtime/recovery.ts +477 -0
  113. package/src/runtime/runtime-capabilities.ts +179 -0
  114. package/src/runtime/runtime-diagnostics.ts +141 -0
  115. package/src/runtime/runtime-host.ts +365 -0
  116. package/src/runtime/runtime-status-facts.ts +222 -0
  117. package/src/runtime/runtime-status-provider.ts +74 -0
  118. package/src/runtime/runtime-status.ts +459 -0
  119. package/src/runtime/runtime-task-admission.ts +101 -0
  120. package/src/runtime/supervisor.ts +444 -0
  121. package/src/session/authority.ts +168 -0
  122. package/src/session/checkpoint.ts +88 -1
  123. package/src/session/context-adapter.ts +251 -0
  124. package/src/session/context-assembly.ts +242 -0
  125. package/src/session/context-identity.ts +389 -0
  126. package/src/session/context-projection.ts +248 -0
  127. package/src/session/context-selector.ts +500 -0
  128. package/src/session/cross-session-adoption.ts +249 -0
  129. package/src/session/full-history-fold.ts +171 -0
  130. package/src/session/identity.ts +192 -0
  131. package/src/session/journal.ts +805 -102
  132. package/src/session/open-work-intent.ts +732 -0
  133. package/src/session/open-work.ts +767 -0
  134. package/src/session/pending-tools.ts +94 -0
  135. package/src/session/persistence.ts +3569 -127
  136. package/src/session/runtime-header.ts +208 -0
  137. package/src/session/shadow-git.ts +13 -5
  138. package/src/session/verification.ts +1623 -0
  139. package/src/task/assignment.ts +136 -0
  140. package/src/task/autonomous-adapter.ts +168 -0
  141. package/src/task/autonomous-context.ts +630 -0
  142. package/src/task/autonomous-policy.ts +490 -0
  143. package/src/task/continuity.ts +179 -0
  144. package/src/task/execution-cancellation.ts +165 -0
  145. package/src/task/graph-validate.ts +379 -0
  146. package/src/task/graph.ts +305 -0
  147. package/src/task/identity.ts +230 -0
  148. package/src/task/model.ts +417 -0
  149. package/src/task/production-scheduler.ts +293 -0
  150. package/src/task/readiness.ts +229 -0
  151. package/src/task/scheduler-observability.ts +387 -0
  152. package/src/task/scheduler.ts +1197 -0
  153. package/src/task/scheduling-policy.ts +165 -0
  154. package/src/task/session-authority.ts +148 -0
  155. package/src/task/session-ownership.ts +211 -0
  156. package/src/task/store.ts +2887 -0
  157. package/src/task/sync.ts +343 -0
  158. package/src/task/trigger.ts +260 -0
  159. package/src/tools/bash.ts +377 -211
  160. package/src/tools/code_run.ts +1 -1
  161. package/src/tools/delete_file.ts +1 -1
  162. package/src/tools/edit.ts +33 -6
  163. package/src/tools/evidence.ts +30 -0
  164. package/src/tools/git.ts +4 -4
  165. package/src/tools/glob.ts +12 -3
  166. package/src/tools/grep.ts +1 -1
  167. package/src/tools/lsp.ts +4 -4
  168. package/src/tools/mcp_call.ts +11 -4
  169. package/src/tools/memory.ts +153 -18
  170. package/src/tools/move_file.ts +1 -1
  171. package/src/tools/patch.ts +1 -1
  172. package/src/tools/read_file.ts +1 -1
  173. package/src/tools/read_image.ts +1 -1
  174. package/src/tools/submit_result.ts +1 -1
  175. package/src/tools/task.ts +437 -41
  176. package/src/tools/todo.ts +662 -35
  177. package/src/tools/web_fetch.ts +4 -2
  178. package/src/tools/web_search.ts +9 -3
  179. package/src/tools/write_file.ts +1 -1
  180. package/src/ui/assistant/simple.ts +123 -50
  181. package/src/ui/assistant/turn-status.ts +17 -3
  182. package/src/ui/contract.ts +184 -0
  183. package/src/ui/footer.ts +54 -18
  184. package/src/ui/i18n/en.ts +62 -6
  185. package/src/ui/i18n/id.ts +62 -6
  186. package/src/ui/input/prompt-engine.ts +120 -25
  187. package/src/ui/render/errors.ts +39 -1
  188. package/src/ui/render/markdown-table.ts +455 -0
  189. package/src/ui/render/markdown.ts +22 -1
  190. package/src/ui/render/table-grid.ts +184 -0
  191. package/src/ui/render/table.ts +15 -76
  192. package/src/ui/runtime/screen.ts +7 -2
  193. package/src/ui/runtime/statusline.ts +25 -6
  194. package/src/ui/tui/app.ts +598 -133
  195. package/src/ui/tui/transcript.ts +531 -89
  196. package/vendor/minicore/VENDOR.md +1 -1
  197. package/vendor/minicore/src/core/budget.ts +25 -25
  198. package/vendor/minicore/src/core/compact.ts +75 -75
  199. package/vendor/minicore/src/core/errors.ts +59 -59
  200. package/vendor/minicore/src/core/events.ts +73 -73
  201. package/vendor/minicore/src/core/executor.ts +139 -139
  202. package/vendor/minicore/src/core/history.ts +31 -31
  203. package/vendor/minicore/src/core/index.ts +41 -41
  204. package/vendor/minicore/src/core/loop.ts +355 -355
  205. package/vendor/minicore/src/core/permission.ts +22 -22
  206. package/vendor/minicore/src/core/provider.ts +39 -39
  207. package/vendor/minicore/src/core/recovery.ts +35 -35
  208. package/vendor/minicore/src/core/session.ts +327 -327
  209. package/vendor/minicore/src/core/snapshot.ts +146 -146
  210. package/vendor/minicore/src/core/tokens.ts +107 -107
  211. package/vendor/minicore/src/core/tool.ts +115 -115
  212. package/vendor/minicore/src/core/types.ts +50 -50
  213. package/vendor/minicore/src/providers/openai-compat.ts +417 -417
  214. package/AGENTS.md +0 -45
  215. package/PLAN.md +0 -491
  216. package/docs/ARCHITECTURE.html +0 -1248
  217. package/docs/CONTROL-PLANE-MAP.md +0 -139
  218. package/docs/HARNESS.md +0 -150
  219. package/docs/SUMMARY.md +0 -52
  220. package/docs/UI_RENDER_PIPELINE.md +0 -165
  221. package/docs/USAGE.md +0 -11
@@ -46,7 +46,7 @@ export const codeRunTool: Tool = {
46
46
  }
47
47
  const src = code as string
48
48
  if (src.includes("\0")) throw new Error("code contains NUL byte")
49
- const root = (ctx as { cwd?: string }).cwd ?? process.cwd()
49
+ const root = ctx.cwd ?? process.cwd()
50
50
  const timeoutMs =
51
51
  typeof timeout === "number" && Number.isFinite(timeout) && timeout > 0 ? timeout : 10000
52
52
  // Tanpa shell perantara di sisi kita: kode jadi SATU argumen single-quoted
@@ -18,7 +18,7 @@ export const deleteFileTool: Tool = {
18
18
  async execute({ path }, ctx) {
19
19
  ctx.signal.throwIfAborted()
20
20
  const p = path as string
21
- const root = (ctx as { cwd?: string }).cwd ?? process.cwd()
21
+ const root = ctx.cwd ?? process.cwd()
22
22
  // Verifikasi path terpusat (logis + target nyata) — detail di safe-open.ts.
23
23
  const { abs, real } = await resolveSafePath(p, root)
24
24
  const st = await stat(real).catch(() => null)
package/src/tools/edit.ts CHANGED
@@ -109,6 +109,19 @@ export function flexibleMatch(content: string, needle: string): MatchResult | nu
109
109
  return null
110
110
  }
111
111
 
112
+ // Aturan uniqueness: `needle` harus menunjuk SATU tempat di `content` menurut
113
+ // matcher yang sama dengan flexibleMatch (exact → crlf → trimmed → fuzzy).
114
+ // Satu aturan untuk DUA jalur edit (hashline cepat & fallback) — sebelumnya
115
+ // jalur hashline hanya mencari duplikat SUBSTRING PERSIS, sehingga needle yang
116
+ // unik-persis tapi ambigu-fuzzy lolos dan blok PERTAMA diedit diam-diam.
117
+ // `first` dipakai kalau pemanggil sudah punya hasil flexibleMatch (jalur
118
+ // fallback); kalau tidak, dihitung di sini.
119
+ function isAmbiguousMatch(content: string, needle: string, first?: MatchResult | null): boolean {
120
+ const m = first ?? flexibleMatch(content, needle)
121
+ if (!m) return false
122
+ return flexibleMatch(content.slice(m.end), needle) !== null
123
+ }
124
+
112
125
  export const editTool: Tool = {
113
126
  name: "edit",
114
127
  description:
@@ -132,7 +145,7 @@ export const editTool: Tool = {
132
145
  async execute({ path, oldString, newString }, ctx) {
133
146
  ctx.signal.throwIfAborted()
134
147
  const p = path as string
135
- const root = (ctx as { cwd?: string }).cwd ?? process.cwd()
148
+ const root = ctx.cwd ?? process.cwd()
136
149
  // Verifikasi path terpusat (logis + target nyata, induk symlink ikut
137
150
  // ter-resolusi) — symlink internal tetap bisa diedit, targetnya yang dicek.
138
151
  const { abs, real: realAbs } = await resolveSafePath(p, root)
@@ -158,9 +171,24 @@ export const editTool: Tool = {
158
171
  if (canHashline) {
159
172
  const hunk = applyHashline(content, oldS, newS)
160
173
  if (hunk !== null) {
161
- // uniqueness: if exact oldString occurs >1 times, require more context (mirror flexibleMatch)
162
- const firstIdx = content.indexOf(oldS)
163
- if (firstIdx !== -1 && content.indexOf(oldS, firstIdx + oldS.length) !== -1) {
174
+ // Uniqueness: aturan YANG SAMA dengan jalur flexibleMatch di bawah
175
+ // (exact → crlf → trimmed → fuzzy). Pemeriksaan lama hanya mencari
176
+ // duplikat SUBSTRING PERSIS, jadi needle yang unik-persis tapi
177
+ // ambigu-fuzzy (mis. "\tfoo" vs " foo") lolos dan blok PERTAMA
178
+ // diedit diam-diam — kelas bug yang sama dengan "duplikat diam-diam
179
+ // edit blok pertama" yang sudah ditutup di jalur bawah.
180
+ //
181
+ // flexibleMatch di sini TIDAK memilih target (itu tetap hashline) —
182
+ // hanya menjawab "apakah needle ini unik?", supaya kedua jalur
183
+ // menjawab pertanyaan yang sama.
184
+ const first = flexibleMatch(content, oldS)
185
+ if (!first) {
186
+ // Hashline menemukan, flexibleMatch tidak (atau fuzzy-nya ambigu →
187
+ // flexibleMatch sengaja null). Jalur bawah menolak dengan "not
188
+ // found"; jalur cepat tidak boleh lebih longgar.
189
+ throw new Error(`oldString not found in ${p}`)
190
+ }
191
+ if (isAmbiguousMatch(content, oldS, first)) {
164
192
  throw new Error(
165
193
  `oldString found multiple times in ${p} — provide more surrounding lines to make it unique`,
166
194
  )
@@ -185,8 +213,7 @@ export const editTool: Tool = {
185
213
 
186
214
  // ensure uniqueness untuk semua mode (exact/crlf/trimmed/fuzzy) — trimmed/fuzzy
187
215
  // sebelumnya hanya dicek untuk exact/crlf sehingga duplikat diam-diam edit blok pertama
188
- const second = flexibleMatch(content.slice(match.end), oldS)
189
- if (second) {
216
+ if (isAmbiguousMatch(content, oldS, match)) {
190
217
  throw new Error(
191
218
  `oldString found multiple times in ${p} — provide more surrounding lines to make it unique`,
192
219
  )
@@ -0,0 +1,30 @@
1
+ // P2.10 canonical tool wrapper: await intent → inner execute → await receipt.
2
+ //
3
+ // This wrapper lives at the tool layer so every covered registry execution
4
+ // passes through one canonical evidence path. Special paths keep their own
5
+ // single intent/terminal pair: delegate_task writes explicitly, dotted MCP
6
+ // tools stay on the existing path, and MCP server mode has awaited wiring.
7
+
8
+ import type { Tool, ToolContext } from "#minicore"
9
+ import { isCanonicalEvidenceCovered } from "../session/journal.ts"
10
+ import { type CanonicalScope, executeCanonicalInvocation } from "../session/verification.ts"
11
+
12
+ const UNWRAPPED = Symbol.for("minicode.p210.unwrapped-tool")
13
+
14
+ type MaybeWrappedTool = Tool & { [UNWRAPPED]?: Tool }
15
+
16
+ /** Wrap one covered registry tool without changing its name, schema, or result. */
17
+ export function withEvidence(tool: Tool, scope: CanonicalScope): Tool {
18
+ if (!isCanonicalEvidenceCovered(tool.name)) return tool
19
+ const inner = (tool as MaybeWrappedTool)[UNWRAPPED] ?? tool
20
+ const wrapped: Tool = {
21
+ ...inner,
22
+ async execute(input: unknown, ctx: ToolContext): Promise<unknown> {
23
+ // Awaited intent precedes inner execute; awaited receipt follows return.
24
+ // No inner execution begins before durable invocation identity exists.
25
+ return executeCanonicalInvocation(inner, input, ctx, scope)
26
+ },
27
+ }
28
+ ;(wrapped as MaybeWrappedTool)[UNWRAPPED] = inner
29
+ return wrapped
30
+ }
package/src/tools/git.ts CHANGED
@@ -92,7 +92,7 @@ export const gitStatusTool: Tool = {
92
92
  },
93
93
  async execute({ cwd }, ctx) {
94
94
  const c = cwd as string | undefined
95
- const sessionRoot = (ctx as { cwd?: string }).cwd ?? process.cwd()
95
+ const sessionRoot = ctx.cwd ?? process.cwd()
96
96
  assertCwd(c, sessionRoot)
97
97
  const resolvedCwd = c ? resolve(sessionRoot, c) : sessionRoot
98
98
  if (!(await isGitRepo(resolvedCwd, ctx.signal))) return "not a git repository"
@@ -131,7 +131,7 @@ export const gitDiffTool: Tool = {
131
131
  additionalProperties: false,
132
132
  },
133
133
  async execute({ cwd, staged }, ctx) {
134
- const sessionRoot = (ctx as { cwd?: string }).cwd ?? process.cwd()
134
+ const sessionRoot = ctx.cwd ?? process.cwd()
135
135
  assertCwd(cwd as string | undefined, sessionRoot)
136
136
  const resolvedCwd = (cwd as string | undefined)
137
137
  ? resolve(sessionRoot, cwd as string)
@@ -160,7 +160,7 @@ export const gitLogTool: Tool = {
160
160
  additionalProperties: false,
161
161
  },
162
162
  async execute({ cwd, limit }, ctx) {
163
- const sessionRoot = (ctx as { cwd?: string }).cwd ?? process.cwd()
163
+ const sessionRoot = ctx.cwd ?? process.cwd()
164
164
  assertCwd(cwd as string | undefined, sessionRoot)
165
165
  const resolvedCwd = (cwd as string | undefined)
166
166
  ? resolve(sessionRoot, cwd as string)
@@ -222,7 +222,7 @@ export const gitCommitTool: Tool = {
222
222
  async execute({ message, paths, all, cwd }, ctx) {
223
223
  ctx.signal.throwIfAborted()
224
224
  const c = cwd as string | undefined
225
- const sessionRoot = (ctx as { cwd?: string }).cwd ?? process.cwd()
225
+ const sessionRoot = ctx.cwd ?? process.cwd()
226
226
  assertCwd(c, sessionRoot)
227
227
  const resolvedCwd = c ? resolve(sessionRoot, c) : sessionRoot
228
228
  const msg = String(message ?? "").trim()
package/src/tools/glob.ts CHANGED
@@ -46,11 +46,20 @@ export function globToRegExp(glob: string): RegExp {
46
46
  esc = esc.replace(/\0BRACE_END\0/g, ")")
47
47
  esc = esc.replace(/\*\*/g, "§§")
48
48
  // **/ di awal/pola rekursif harus cocok file root juga: **/* sekarang jadi
49
- // (.*/)?[^/]*, bukan .*/[^/]* yang butuh slash dan membuat root kosong.
50
- esc = esc.replace(/§§\//g, "(.*/)?")
49
+ // (?:.*/)?[^/]*, bukan .*/[^/]* yang butuh slash dan membuat root kosong.
50
+ //
51
+ // Penting: fragmen rekursif HARUS dipasang SESUDAH substitusi `*`→`[^/]*`
52
+ // dan `?`→`.` di bawah. Kalau dipasang lebih awal, `*` di dalamnya ikut
53
+ // ditulis ulang jadi `[^/]*` dan `?` (quantifier) jadi `.` — hasilnya
54
+ // `(.[^/]*\/)`: grup WAJIB yang butuh satu karakter tambahan. Akibatnya
55
+ // `**/*.ts` tak lagi cocok file di root maupun direktori depth >= 2, dan
56
+ // `src/**/*.ts` tak lagi cocok file langsung di `src/`. Placeholder yang
57
+ // sama seperti brace expansion di atas.
58
+ esc = esc.replace(/§§\//g, "\0REC\0")
51
59
  esc = esc.replace(/\*/g, "[^/]*")
52
60
  esc = esc.replace(/§§/g, ".*")
53
61
  esc = esc.replace(/\?/g, ".")
62
+ esc = esc.replace(/\0REC\0/g, "(?:.*/)?")
54
63
  return new RegExp(`^${esc}$`)
55
64
  }
56
65
 
@@ -69,7 +78,7 @@ export const globTool: Tool = {
69
78
  additionalProperties: false,
70
79
  },
71
80
  async execute({ pattern, cwd, limit }, ctx) {
72
- const sessionRoot = (ctx as { cwd?: string }).cwd ?? process.cwd()
81
+ const sessionRoot = ctx.cwd ?? process.cwd()
73
82
  const rawRoot = (cwd as string) ?? "."
74
83
  const root = resolve(sessionRoot, rawRoot)
75
84
  if (isPathOutsideRoot(root, sessionRoot)) throw new Error(`cwd outside workspace: ${rawRoot}`)
package/src/tools/grep.ts CHANGED
@@ -219,7 +219,7 @@ export const grepTool: Tool = {
219
219
  additionalProperties: false,
220
220
  },
221
221
  async execute({ pattern, cwd, include, limit }, ctx) {
222
- const sessionRoot = (ctx as { cwd?: string }).cwd ?? process.cwd()
222
+ const sessionRoot = ctx.cwd ?? process.cwd()
223
223
  const rawRoot = (cwd as string) ?? "."
224
224
  const root = resolve(sessionRoot, rawRoot)
225
225
  if (isPathOutsideRoot(root, sessionRoot)) throw new Error(`cwd outside workspace: ${rawRoot}`)
package/src/tools/lsp.ts CHANGED
@@ -126,7 +126,7 @@ function posTool(
126
126
  },
127
127
  async execute(args, ctx) {
128
128
  ctx.signal.throwIfAborted()
129
- const cwd = (ctx as { cwd?: string }).cwd ?? process.cwd()
129
+ const cwd = ctx.cwd ?? process.cwd()
130
130
  try {
131
131
  const resolved = await resolvePosition(args as PosArgs, cwd)
132
132
  if (typeof resolved === "string") return resolved
@@ -168,7 +168,7 @@ export const lspDiagnosticsTool: Tool = {
168
168
  },
169
169
  async execute({ file }, ctx) {
170
170
  ctx.signal.throwIfAborted()
171
- const cwd = (ctx as { cwd?: string }).cwd ?? process.cwd()
171
+ const cwd = ctx.cwd ?? process.cwd()
172
172
  try {
173
173
  const { abs, text } = await readTarget(String(file), cwd)
174
174
  const { items } = await raceAbort(lspDiagnostics(abs, text, undefined, cwd), ctx.signal)
@@ -225,7 +225,7 @@ export const lspSymbolsTool: Tool = {
225
225
  },
226
226
  async execute({ file }, ctx) {
227
227
  ctx.signal.throwIfAborted()
228
- const cwd = (ctx as { cwd?: string }).cwd ?? process.cwd()
228
+ const cwd = ctx.cwd ?? process.cwd()
229
229
  try {
230
230
  const { abs, text } = await readTarget(String(file), cwd)
231
231
  const result = await raceAbort(
@@ -273,7 +273,7 @@ export const lspWorkspaceSymbolsTool: Tool = {
273
273
  if (getConfiguredExts().length === 0)
274
274
  return "(no LSP servers configured — add via minicode config lsp add)"
275
275
  try {
276
- const cwd = (ctx as { cwd?: string }).cwd ?? process.cwd()
276
+ const cwd = ctx.cwd ?? process.cwd()
277
277
  const symbols = await raceAbort(
278
278
  workspaceSymbols((query as string) ?? "", 5000, cwd),
279
279
  ctx.signal,
@@ -8,7 +8,7 @@ import {
8
8
  mcpInventory,
9
9
  readMcpResource,
10
10
  } from "../mcp/client.ts"
11
- import { scrubSecrets } from "../policy/scrub.ts"
11
+ import { fenceUntrustedToolOutput, isAlreadyFenced, scrubSecrets } from "../policy/scrub.ts"
12
12
 
13
13
  export const mcpListTool: Tool = {
14
14
  name: "mcp_list",
@@ -86,7 +86,10 @@ export const mcpCallTool: Tool = {
86
86
  try {
87
87
  const result = await callMcpTool(sid, tn, a, ctx.signal)
88
88
  const content = extractMcpText(result)
89
- return capMcpText(content)
89
+ const capped = capMcpText(content)
90
+ return isAlreadyFenced(capped)
91
+ ? capped
92
+ : fenceUntrustedToolOutput(`mcp_call:${sid}.${tn}`, capped)
90
93
  } catch (e) {
91
94
  return `[mcp] error: ${scrubSecrets((e as Error).message)}`
92
95
  }
@@ -121,7 +124,8 @@ export const mcpReadTool: Tool = {
121
124
  try {
122
125
  const text = await readMcpResource(sid, u, ctx.signal)
123
126
  if (!text) return `[mcp] resource '${u}' is empty or returned no text`
124
- return capMcpText(text)
127
+ const capped = capMcpText(text)
128
+ return isAlreadyFenced(capped) ? capped : fenceUntrustedToolOutput(`mcp_read:${sid}`, capped)
125
129
  } catch (e) {
126
130
  return `[mcp] error: ${scrubSecrets((e as Error).message)}`
127
131
  }
@@ -155,7 +159,10 @@ export const mcpPromptTool: Tool = {
155
159
  try {
156
160
  const text = await getMcpPrompt(sid, pn, (args as Record<string, unknown>) ?? {}, ctx.signal)
157
161
  if (!text) return `[mcp] prompt '${pn}' returned no message`
158
- return capMcpText(text)
162
+ const capped = capMcpText(text)
163
+ return isAlreadyFenced(capped)
164
+ ? capped
165
+ : fenceUntrustedToolOutput(`mcp_prompt:${sid}`, capped)
159
166
  } catch (e) {
160
167
  return `[mcp] error: ${scrubSecrets((e as Error).message)}`
161
168
  }
@@ -1,6 +1,12 @@
1
1
  import type { Tool } from "#minicore"
2
2
  import { appendMemory, deleteMemoryLines, readMemoryFile } from "../memory/files.ts"
3
- import { addMemory, deleteMemoryByQuery, searchHybrid } from "../memory/vector.ts"
3
+ import {
4
+ addMemory,
5
+ deleteMemoryByQuery,
6
+ invokeMemoryWriteFaultForTest,
7
+ recordCandidateLesson,
8
+ searchHybrid,
9
+ } from "../memory/vector.ts"
4
10
 
5
11
  export const readMemoryTool: Tool = {
6
12
  name: "read_memory",
@@ -17,7 +23,7 @@ export const readMemoryTool: Tool = {
17
23
  },
18
24
  async execute({ query, topK }, ctx) {
19
25
  ctx.signal.throwIfAborted()
20
- const cwd = (ctx as { cwd?: string }).cwd ?? process.cwd()
26
+ const cwd = ctx.cwd ?? process.cwd()
21
27
  // Mode readonly/plan: retrieval tidak boleh menulis access_count/WAL —
22
28
  // permissionMode diteruskan kernel per turn (lihat task.ts).
23
29
  const pm = (ctx as unknown as { permissionMode?: string }).permissionMode
@@ -62,7 +68,20 @@ export const readMemoryTool: Tool = {
62
68
  }
63
69
  let out = ""
64
70
  if (hits.length)
65
- out += `vector hits:\n${hits.map((h) => `- ${h.text.slice(0, 300)}${h.text.length > 300 ? "…" : ""} (${h.score.toFixed(2)}, ${fmtDate(h.createdAt)})`).join("\n")}\n`
71
+ out += `vector hits:\n${hits
72
+ .map(
73
+ (
74
+ h: (typeof hits)[number] & {
75
+ provenance?: { sessionId?: string | null; turnId?: string | null }
76
+ },
77
+ ) => {
78
+ const meta = h.provenance
79
+ ? `[session:${h.provenance.sessionId || "?"}] [turn:${h.provenance.turnId || "?"}] `
80
+ : ""
81
+ return `- ${h.text.slice(0, 300)}${h.text.length > 300 ? "…" : ""} (${h.score.toFixed(2)}, ${fmtDate(h.createdAt)}) ${meta}`
82
+ },
83
+ )
84
+ .join("\n")}\n`
66
85
  if (kw) out += `\nfile hits:\n${kw}`
67
86
  return out.trim() || "(no memory)"
68
87
  },
@@ -83,26 +102,109 @@ export const writeMemoryTool: Tool = {
83
102
  "retrieval category: fact/decision/preference are durable, snippet is short-lived, summary for session summaries",
84
103
  },
85
104
  tags: { type: "array", items: { type: "string" } },
105
+ // MEM-01 / Fase 5A: provenance metadata untuk forensik & revokasi selektif
106
+ sessionId: {
107
+ type: "string",
108
+ description: "session ID if this memory originates from a session",
109
+ },
110
+ turnId: {
111
+ type: "string",
112
+ description: "turn ID if this memory originates from a specific turn",
113
+ },
114
+ sourceKind: {
115
+ type: "string",
116
+ enum: ["user", "tool", "agent", "compaction", "manual", "legacy"],
117
+ description: "source category: user/manual input vs tool/agent auto-memory vs compaction",
118
+ },
119
+ sourceRef: {
120
+ type: "string",
121
+ description: "reference of the source (e.g., tool name, file path)",
122
+ },
123
+ // [Fase 6A / ACE-03] Pelajaran kandidat wajib menjalani verifikasi dulu.
124
+ validation: {
125
+ type: "string",
126
+ enum: ["validated", "provisional"],
127
+ description:
128
+ "validated (default) = durable fact; provisional = candidate lesson hidden from retrieval until the next verification promotes it",
129
+ },
130
+ // [Fase 12 / LF-4] Identitas memori lama yang digantikan entri baru ini —
131
+ // teruskan untuk men-tombstone baris lama (supersession) lewat jalur tool.
132
+ supersedes_id: {
133
+ type: "string",
134
+ description:
135
+ "optional id of a previous memory row this new entry supersedes (replaces without deleting it)",
136
+ },
86
137
  },
87
138
  required: ["text"],
88
139
  additionalProperties: false,
89
140
  },
90
- async execute({ text, category, tags }, ctx) {
141
+ async execute(
142
+ { text, category, tags, sessionId, turnId, sourceKind, sourceRef, validation, supersedes_id },
143
+ ctx,
144
+ ) {
91
145
  ctx.signal.throwIfAborted()
92
146
  const t = text as string
93
147
  if (!t.trim()) throw new Error("text empty")
94
- const cwd = (ctx as { cwd?: string }).cwd ?? process.cwd()
148
+ const cwd = ctx.cwd ?? process.cwd()
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)}`
172
+ }
95
173
  const path = await appendMemory(t, cwd)
174
+ // [Fase 9 / 9.2] Fault-injection boundary: file (MEMORY.md) sudah ketulis,
175
+ // vector.db belum. Injector yang melempar di stage ini menyimulasikan crash
176
+ // persis di titik ini → menghasilkan entri file-only (split-brain arah 1).
177
+ invokeMemoryWriteFaultForTest("after_file_before_vector")
96
178
  const cat = (category as string) ?? "fact"
97
179
  const tagArr = Array.isArray(tags) ? (tags as string[]) : undefined
98
- // also add to vector (hybrid) — pass cwd so local vector.db is used
180
+ // [Fase 12 / LF-4] id memori lama yang digantikan (supersession) dari argumen tool.
181
+ const supersedesId = typeof supersedes_id === "string" && supersedes_id ? supersedes_id : null
182
+
183
+ // MEM-01: add provenance tags to MEMORY.md (as metadata comment at end of line)
184
+ const memTags = tagArr ? [...tagArr] : []
185
+ if (sessionId) memTags.push(`session:${sessionId}`)
186
+ if (turnId) memTags.push(`turn:${turnId}`)
187
+ if (sourceKind) memTags.push(`source:${sourceKind}`)
188
+ if (sourceRef) memTags.push(`ref:${sourceRef}`)
189
+
99
190
  const baseUrl = process.env.AGENT_BASE_URL ?? "https://api.openai.com/v1"
100
191
  const apiKey =
101
192
  process.env.DEEPSEEK_API_KEY ?? process.env.OPENAI_API_KEY ?? process.env.AGENT_API_KEY ?? ""
102
193
  let added = false
103
194
  if (apiKey) {
104
195
  try {
105
- await addMemory(t, { baseUrl, apiKey, cwd, category: cat, tags: tagArr })
196
+ await addMemory(t, {
197
+ baseUrl,
198
+ apiKey,
199
+ cwd,
200
+ category: cat,
201
+ tags: tagArr,
202
+ sessionId,
203
+ turnId,
204
+ sourceKind,
205
+ sourceRef,
206
+ supersedesId,
207
+ })
106
208
  added = true
107
209
  } catch (e) {
108
210
  process.stderr.write(`[warn] memory vector embedding failed: ${(e as Error).message}\n`)
@@ -110,14 +212,23 @@ export const writeMemoryTool: Tool = {
110
212
  }
111
213
  if (!added) {
112
214
  try {
113
- await addMemory(t, { cwd, category: cat, tags: tagArr })
215
+ await addMemory(t, {
216
+ cwd,
217
+ category: cat,
218
+ tags: tagArr,
219
+ sessionId,
220
+ turnId,
221
+ sourceKind,
222
+ sourceRef,
223
+ supersedesId,
224
+ })
114
225
  } catch (e2) {
115
226
  process.stderr.write(
116
227
  `[warn] memory keyword-only fallback failed: ${(e2 as Error).message}\n`,
117
228
  )
118
229
  }
119
230
  }
120
- return `saved to ${path}: ${t.slice(0, 100)}`
231
+ return `saved to ${path}: ${t.slice(0, 100)}${memTags.length ? ` [tags: ${JSON.stringify(memTags)}]` : ""}`
121
232
  },
122
233
  }
123
234
 
@@ -127,19 +238,43 @@ export const forgetMemoryTool: Tool = {
127
238
  "Delete memories matching the query from the vector store AND MEMORY.md files, in both project (cwd) and global scopes — search merges both, so forgetting one side would leave rows behind.",
128
239
  parameters: {
129
240
  type: "object",
130
- properties: { query: { type: "string" } },
241
+ properties: {
242
+ query: { type: "string" },
243
+ // MEM-01 / Fase 5A: selective revocation via provenance (alternative to query-based)
244
+ sessionId: { type: "string", description: "delete all memory from this session ID" },
245
+ turnId: { type: "string", description: "delete all memory from this turn ID" },
246
+ sourceKind: { type: "string", description: "delete all memory from this source category" },
247
+ },
131
248
  required: ["query"],
132
249
  additionalProperties: false,
133
250
  },
134
- async execute({ query }, ctx) {
251
+ async execute({ query, sessionId, turnId, sourceKind }, ctx) {
135
252
  ctx.signal.throwIfAborted()
136
253
  const q = query as string
137
- if (!q.trim()) throw new Error("query empty")
138
- const cwd = (ctx as { cwd?: string }).cwd ?? process.cwd()
139
- const del = await deleteMemoryByQuery(q, cwd)
140
- // Temuan audit #06: vector saja tak cukup — entri file (sumber file
141
- // hits) harus ikut terhapus agar "lupa" benar-benar terjadi.
142
- const fileDel = await deleteMemoryLines(q, cwd)
143
- return `deleted ${del} memories + ${fileDel} file lines matching "${query}"`
254
+
255
+ if (!q.trim() && !sessionId && !turnId && !sourceKind) {
256
+ throw new Error("query or provenance criteria required")
257
+ }
258
+
259
+ const cwd = ctx.cwd ?? process.cwd()
260
+
261
+ let resultText = ""
262
+
263
+ // Use provenance-based deletion if specified, otherwise fall back to query-based
264
+ if (sessionId || turnId || sourceKind) {
265
+ const { revokeByProvenance } = await import("../memory/vector.ts")
266
+ const criteria: { sessionId?: string; turnId?: string; sourceKind?: string } = {}
267
+ if (sessionId as string) criteria.sessionId = sessionId as string
268
+ if (turnId as string) criteria.turnId = turnId as string
269
+ if (sourceKind as string) criteria.sourceKind = sourceKind as string
270
+ const { vectorRows, fileLines } = await revokeByProvenance(criteria, cwd)
271
+ resultText = `revoked ${vectorRows} vector entries + ${fileLines} file lines by provenance`
272
+ } else {
273
+ const del = await deleteMemoryByQuery(q, cwd)
274
+ const fileDel = await deleteMemoryLines(q, cwd)
275
+ resultText = `deleted ${del} memories + ${fileDel} file lines matching "${query}"`
276
+ }
277
+
278
+ return resultText
144
279
  },
145
280
  }
@@ -19,7 +19,7 @@ export const moveFileTool: Tool = {
19
19
  },
20
20
  async execute({ from, to }, ctx) {
21
21
  ctx.signal.throwIfAborted()
22
- const root = (ctx as { cwd?: string }).cwd ?? process.cwd()
22
+ const root = ctx.cwd ?? process.cwd()
23
23
  const f = from as string
24
24
  const t = to as string
25
25
  // Verifikasi kedua ujung via pemilik tunggal (logis + target nyata) —
@@ -38,7 +38,7 @@ export const applyPatchTool: Tool = {
38
38
  async execute({ path, patches }, ctx) {
39
39
  ctx.signal.throwIfAborted()
40
40
  const p = path as string
41
- const root = (ctx as { cwd?: string }).cwd ?? process.cwd()
41
+ const root = ctx.cwd ?? process.cwd()
42
42
  // Verifikasi path terpusat (logis + target nyata) — detail di safe-open.ts.
43
43
  const { abs, real: realAbs } = await resolveSafePath(p, root)
44
44
  // Tolak menimpa symlink final (swap antara cek dan tulis gagal tutup).
@@ -83,7 +83,7 @@ export const readFileTool: Tool = {
83
83
  async execute({ path, offset, limit }, ctx) {
84
84
  ctx.signal.throwIfAborted()
85
85
  const p = path as string
86
- const root = (ctx as { cwd?: string }).cwd ?? process.cwd()
86
+ const root = ctx.cwd ?? process.cwd()
87
87
  const abs = isAbsolute(p) ? resolve(p) : resolve(root, p)
88
88
  // Semua verifikasi path (jail + sensitif + O_NOFOLLOW) terjadi di SATU
89
89
  // titik saat open — detail di safe-open.ts. Tidak ada resolve/stat
@@ -25,7 +25,7 @@ export const readImageTool: Tool = {
25
25
  async execute({ path }, ctx) {
26
26
  ctx.signal.throwIfAborted()
27
27
  const p = path as string
28
- const root = (ctx as { cwd?: string }).cwd ?? process.cwd()
28
+ const root = ctx.cwd ?? process.cwd()
29
29
  const abs = isAbsolute(p) ? resolve(p) : resolve(root, p)
30
30
  // TOCTOU-safe: safeOpenRead = realpath(abs) → cek jail+sensitif di dalam
31
31
  // root → open(preReal, O_NOFOLLOW). Bukan open(abs) yang bisa di-swap jadi
@@ -24,7 +24,7 @@ export function clearSubmittedResult(): void {
24
24
  export const submitResultTool: Tool = {
25
25
  name: "submit_result",
26
26
  description:
27
- "Submit the final structured result of this task as a JSON object (instead of burying it in prose). Call once when done; exec --json surfaces it verbatim.",
27
+ "Submit the final structured result of this task as a JSON object (instead of burying it in prose). Call once when done; exec --json surfaces it verbatim. If result.findings is an array of {category, severity, summary, evidence?}, those findings are also surfaced as finding.detected events.",
28
28
  parameters: {
29
29
  type: "object",
30
30
  properties: {