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
package/src/mcp/server.ts CHANGED
@@ -2,14 +2,13 @@ import { randomUUID } from "node:crypto"
2
2
  import { createInterface } from "node:readline"
3
3
  import type { ExecutorDeps, Tool, ToolContext } from "#minicore"
4
4
  import { scrubSecrets } from "../policy/scrub.ts"
5
+ import { finalizeJournal, hashArgs, isMutationTool } from "../session/journal.ts"
5
6
  import {
6
- appendMutationIntent,
7
- appendMutationTerminal,
8
- finalizeJournal,
9
- hashArgs,
10
- isMutationTool,
11
- verifyPaths,
12
- } from "../session/journal.ts"
7
+ type EffectIntentResult,
8
+ persistEffectIntent,
9
+ persistEffectReceipt,
10
+ } from "../session/verification.ts"
11
+ import { createBashJobTools } from "../tools/bash.ts"
13
12
  import { allTools } from "../tools/index.ts"
14
13
  import { todoSession } from "../tools/todo.ts"
15
14
  import { capMcpText } from "./client.ts"
@@ -71,14 +70,24 @@ async function invokeTool(
71
70
  opts: McpServeOptions,
72
71
  signal: AbortSignal,
73
72
  journal: { session: string; root: string },
73
+ /** PHASE 4A.4B: the 4A.3 durable task namespace for THIS server instance.
74
+ * Threaded explicitly so the per-request ToolContext can carry it. It is a
75
+ * parameter, never a read of process-global state, so two in-flight requests
76
+ * cannot observe each other's session. */
77
+ contextId: string,
74
78
  /** Kunci bukti dedup `req:<id>:<argsHash>` (dibuat pemanggil dari argumen
75
79
  * mentah) — ditulis apa adanya ke outcome.note + flag dedup. */
76
80
  noteKey?: string,
77
81
  ): Promise<{ content: { type: string; text: string }[]; isError: boolean }> {
78
82
  const root = journal.root
79
83
  // validateArgs KERNEL (bukan validasi ad-hoc): argumen invalid ditolak
80
- // SEBELUM permission/execute — sama seperti jalur REPL. Tanpa ini argumen
81
- // mentah mencapai execute (temuan audit #05: crash/perilaku indefinisi).
84
+ // SEBELUM permission/execute — kontrak C3: KEDUA gerbang (otorisasi +
85
+ // validasi) wajib mendahului execute. Urutan berbeda dari kernel REPL
86
+ // (permission dulu, lalu validate) DISENGAJA dan setara aman: kernel butuh
87
+ // argumen mentah untuk prompt approval + describeDenial; server menolak
88
+ // input remote rusak sebelum membangun konteks permission apa pun.
89
+ // Tanpa validasi ini argumen mentah mencapai execute (temuan audit #05:
90
+ // crash/perilaku indefinisi).
82
91
  const { validateArgs } = await import("#minicore")
83
92
  const parsed = validateArgs(tool.parameters, args ?? {})
84
93
  if (!parsed.ok) {
@@ -124,46 +133,72 @@ async function invokeTool(
124
133
  // terminal. Server mode tak punya turn/session kernel, jadi sesi jurnal
125
134
  // tetap "mcp-server".
126
135
  const mutating = isMutationTool(tool.name)
127
- let intent: { id: string; seq: number } | null = null
136
+ let intent: EffectIntentResult | null = null
128
137
  if (mutating) {
129
- intent = await appendMutationIntent({
130
- session: journal.session,
138
+ intent = await persistEffectIntent({
139
+ sessionId: journal.session,
140
+ threadId: journal.session,
131
141
  tool: tool.name,
132
142
  cwd: root,
133
- paths: verifyPaths(tool.name, validArgs, root),
134
- argsHash: hashArgs(validArgs),
135
- // Kunci idempotency sejak intent (audit #08): crash di tengah eksekusi
136
- // (tanpa terminal) tetap terdeteksi sebagai unknown, bukan fresh.
137
- ...(noteKey ? { note: noteKey } : {}),
143
+ args: validArgs,
144
+ idempotencyKey: noteKey,
145
+ idempotencyScope: "mcp",
146
+ specialPath: "mcp-server",
138
147
  })
148
+ // Evidence fail-closed: without a durable canonical intent the server
149
+ // must not execute. This preserves the existing fail-open authority rule
150
+ // for journal I/O elsewhere while refusing unverifiable execution here.
151
+ if (!intent.durable) {
152
+ return {
153
+ content: [
154
+ {
155
+ type: "text",
156
+ text: `[error] evidence incomplete: durable EffectIntent unavailable for ${tool.name}`,
157
+ },
158
+ ],
159
+ isError: true,
160
+ }
161
+ }
139
162
  }
140
- const ctx: ToolContext = {
163
+ const ctx: ToolContext & { sessionId?: string } = {
141
164
  signal,
142
165
  state: { history: [], turnCount: 0, stepCount: 0 },
143
166
  emit: () => {},
144
167
  // P0 audit #05: root eksekusi HARUS sama dengan root jail permission.
145
- // Sebelumnya ctx tanpa cwd → tool jatuh ke process.cwd() sementara jail
146
- // memakai opts.root — divergensi jail-vs-eksekusi bila --cwd dipakai.
168
+ // Sebelumnya ctx tanpa cwd tool jatuh ke process.cwd() sementara jail
169
+ // memakai opts.root - divergensi jail-vs-eksekusi bila --cwd dipakai.
147
170
  cwd: root,
171
+ // PHASE 4A.4B: bind this request to the 4A.3 namespace explicitly. The
172
+ // ctx object is already built per request, so this is the existing
173
+ // composition mechanism doing the job - no new global, and the session
174
+ // cannot be swapped by another request mid-flight.
175
+ sessionId: contextId,
148
176
  }
149
177
  try {
150
178
  const out = await tool.execute(validArgs, ctx)
151
179
  const text =
152
180
  typeof out === "string" ? out : out instanceof Uint8Array ? "(binary)" : JSON.stringify(out)
153
181
  if (intent) {
154
- await appendMutationTerminal(
155
- journal.session,
156
- root,
157
- intent.id,
158
- intent.seq,
159
- tool.name,
160
- "committed",
161
- {
162
- note: noteKey,
182
+ await persistEffectReceipt({
183
+ sessionId: journal.session,
184
+ threadId: journal.session,
185
+ tool: tool.name,
186
+ cwd: root,
187
+ invocation: intent.invocation,
188
+ intent: {
189
+ id: intent.record.id,
190
+ seq: intent.record.seq,
191
+ tool: intent.record.tool,
192
+ session: intent.record.session,
193
+ ...(intent.record.invocationId ? { invocationId: intent.record.invocationId } : {}),
194
+ ...(intent.record.argsHash ? { argsHash: intent.record.argsHash } : {}),
163
195
  },
164
- undefined,
165
- { dedup: true },
166
- )
196
+ state: "committed",
197
+ result: out,
198
+ outcome: noteKey ? { note: noteKey } : undefined,
199
+ dedup: true,
200
+ specialPath: "mcp-server",
201
+ })
167
202
  }
168
203
  // capMcpText scrub + cap + tandai dalam satu langkah (tanpa double-scrub).
169
204
  return {
@@ -172,24 +207,95 @@ async function invokeTool(
172
207
  }
173
208
  } catch (e) {
174
209
  if (intent) {
175
- await appendMutationTerminal(
176
- journal.session,
177
- root,
178
- intent.id,
179
- intent.seq,
180
- tool.name,
181
- "failed",
182
- {
183
- note: noteKey,
210
+ await persistEffectReceipt({
211
+ sessionId: journal.session,
212
+ threadId: journal.session,
213
+ tool: tool.name,
214
+ cwd: root,
215
+ invocation: intent.invocation,
216
+ intent: {
217
+ id: intent.record.id,
218
+ seq: intent.record.seq,
219
+ tool: intent.record.tool,
220
+ session: intent.record.session,
221
+ ...(intent.record.invocationId ? { invocationId: intent.record.invocationId } : {}),
222
+ ...(intent.record.argsHash ? { argsHash: intent.record.argsHash } : {}),
184
223
  },
185
- undefined,
186
- { dedup: true },
187
- )
224
+ state: "failed",
225
+ error: e,
226
+ signalAborted: signal.aborted,
227
+ outcome: noteKey ? { note: noteKey } : undefined,
228
+ dedup: true,
229
+ specialPath: "mcp-server",
230
+ })
188
231
  }
189
232
  throw e
190
233
  }
191
234
  }
192
235
 
236
+ /**
237
+ * PHASE 4A.3 - durable MCP task namespace.
238
+ *
239
+ * WHY THIS EXISTS. `todoSession.id` used to be the literal `"mcp-server"` for
240
+ * the whole process. As a durable task namespace that is unsafe: it is a
241
+ * constant, so every MCP context that has ever run against the same `root`
242
+ * shares one identity space, and it can also collide with anything else that
243
+ * ever uses that string. `TASK_ARCHITECTURE_AUDIT.md` already flagged the
244
+ * underlying problem - `mcp serve` is single-tenant, and concurrent requests
245
+ * overwrite each other's files last-writer-wins.
246
+ *
247
+ * WHAT THIS IDENTIFIES. One server instance = one logical MCP context. That
248
+ * matches this implementation's actual lifecycle, which was verified rather
249
+ * than assumed:
250
+ * - `initialize` is a stateless reply (server.ts `case "initialize"`) - it
251
+ * issues no session id and the server keeps no state for it;
252
+ * - there is no client identity anywhere in the protocol surface here;
253
+ * - the idempotency key is the client-supplied JSON-RPC id, and the code
254
+ * itself documents that "client reconnect resets seq", so request ids are
255
+ * client-controlled and are NOT stable logical identity.
256
+ *
257
+ * So a per-request id would be wrong (it is not a context) and a per-client id
258
+ * is not available (no client identity exists). One context per server instance
259
+ * is the smallest identity the evidence actually supports.
260
+ *
261
+ * NOT CLAIMED: persistence across a process restart. There is no mechanism
262
+ * storing this id, so a restart creates a NEW context and the previous
263
+ * context's tasks are left on disk and unreachable. That is stated rather than
264
+ * papered over, and nothing is deleted to hide it.
265
+ *
266
+ * The value is namespaced with an `mcp:` prefix so it can never equal a legacy
267
+ * `"mcp-server"` row, nor a CLI `presentationSessionId`, and so it is greppable
268
+ * in diagnostics.
269
+ */
270
+ export function newMcpContextId(): string {
271
+ return `mcp:${randomUUID()}`
272
+ }
273
+
274
+ /**
275
+ * Install `contextId` as the durable todo namespace for this server, scoped to
276
+ * `root`, and return the previous globals so the caller can restore them.
277
+ *
278
+ * Extracted from `serveMcp` so the production wiring itself is testable -
279
+ * `serveMcp` needs a live stdin transport and cannot run in a unit test, and a
280
+ * factory-only test would prove nothing about what actually gets installed.
281
+ */
282
+ export function applyMcpContext(
283
+ contextId: string,
284
+ root: string,
285
+ ): { prevId: string; prevCwd: string | undefined } {
286
+ // Fail closed. There is deliberately NO fallback to "mcp-server": if a
287
+ // namespace cannot be established, serving must not continue with a shared
288
+ // identity.
289
+ if (!contextId || contextId === "mcp-server") {
290
+ throw new Error("mcp: refusing to serve without a unique task namespace")
291
+ }
292
+ const prevId = todoSession.id
293
+ const prevCwd = todoSession.cwd
294
+ todoSession.id = contextId
295
+ todoSession.cwd = root
296
+ return { prevId, prevCwd }
297
+ }
298
+
193
299
  export async function serveMcp(opts: McpServeOptions = {}): Promise<void> {
194
300
  const tools = selectTools(opts)
195
301
  const byName = new Map(tools.map((t) => [t.name, t]))
@@ -197,15 +303,35 @@ export async function serveMcp(opts: McpServeOptions = {}): Promise<void> {
197
303
  // Root tunggal: jail permission, cwd eksekusi, dan jurnal memakai nilai
198
304
  // yang sama (audit #05: divergensi ketiganya = jail bypass).
199
305
  const root = opts.root ?? process.cwd()
306
+ // The journal key is an internal, per-process record. It is deliberately NOT
307
+ // the durable task namespace and is left unchanged.
200
308
  const JOURNAL_SESSION = "mcp-server"
201
309
 
202
310
  // todoSession global dipakai tool todo_*; di proses serve khusus, skop ke
203
- // sesi server agar tak mencemari/membaca state sesi lain (P2 isolation).
204
- // Default "default" bila serve dipakai sebagai library tanpa setup root.
205
- const prevTodo = todoSession.id
206
- const prevTodoCwd = todoSession.cwd
207
- todoSession.id = "mcp-server"
208
- todoSession.cwd = root
311
+ // konteks server ini agar tak mencemari/membaca state sesi lain (P2
312
+ // isolation). Phase 4A.3: the scope is now a unique per-instance id rather
313
+ // than the shared literal "mcp-server".
314
+ //
315
+ // PHASE 4A.4B: the id is captured in a `const` so the SAME per-instance
316
+ // namespace can be attached to every request's ToolContext below. The global is
317
+ // still installed for the tools that have no other way to learn it, but the
318
+ // todo write path no longer depends on it surviving an await.
319
+ const mcpContextId = newMcpContextId()
320
+ const { prevId: prevTodo, prevCwd: prevTodoCwd } = applyMcpContext(mcpContextId, root)
321
+ // F-03 (P5 §C2): background bash job diikat ke contextId instance ini —
322
+ // mekanisme sama dengan todo namespace (applyMcpContext). Cross-context
323
+ // (server lain / sesi penerima ctx.sessionId berbeda) tak bisa inspect/cancel
324
+ // hanya dengan tahu job id.
325
+ {
326
+ const ownedBash = createBashJobTools(mcpContextId)
327
+ for (const t of [ownedBash.bash, ownedBash.bashOutput, ownedBash.bashKill]) {
328
+ const i = tools.findIndex((x) => x.name === t.name)
329
+ if (i !== -1) {
330
+ tools[i] = t
331
+ byName.set(t.name, t)
332
+ }
333
+ }
334
+ }
209
335
 
210
336
  // Idempotency request (audit #05 P0, diperkuat #08 P0): retry client
211
337
  // (atau crash-restart) tak boleh mengeksekusi ulang mutasi non-idempoten
@@ -490,6 +616,7 @@ export async function serveMcp(opts: McpServeOptions = {}): Promise<void> {
490
616
  opts,
491
617
  linkedSignal(reqCtrl),
492
618
  { session: JOURNAL_SESSION, root },
619
+ mcpContextId,
493
620
  noteKey,
494
621
  )
495
622
  } finally {
@@ -12,6 +12,8 @@ export class McpTransport {
12
12
  resolve: (v: unknown) => void
13
13
  reject: (e: Error) => void
14
14
  timer: ReturnType<typeof setTimeout>
15
+ /** Lepas listener abort saat request settle (RL-5 — anti bocor). */
16
+ unsubscribe?: () => void
15
17
  }
16
18
  >()
17
19
  private seq = 0
@@ -50,6 +52,7 @@ export class McpTransport {
50
52
  if (msg.id != null && this.pending.has(msg.id)) {
51
53
  const p = this.pending.get(msg.id)!
52
54
  clearTimeout(p.timer)
55
+ p.unsubscribe?.()
53
56
  this.pending.delete(msg.id)
54
57
  if (msg.error) p.reject(new Error(msg.error.message || JSON.stringify(msg.error)))
55
58
  else p.resolve(msg.result)
@@ -73,27 +76,21 @@ export class McpTransport {
73
76
  return new Promise((resolve, reject) => {
74
77
  const timer = setTimeout(() => {
75
78
  this.pending.delete(id)
79
+ unsubscribe()
76
80
  reject(new Error(`MCP request ${method} timed out after ${timeoutMs}ms`))
77
81
  }, timeoutMs)
78
- const entry = { resolve, reject, timer }
79
- this.pending.set(id, entry)
80
- // stdio JSON-RPC tak punya pembatalan di-kabel: abort hanya menghentikan
81
- // PENUNGGUAN di sisi kita (server child tetap hidup sampai close/timeout
82
- // dan efek yang sudah terjadi di server TIDAK dibatalkan).
83
- signal?.addEventListener(
84
- "abort",
85
- () => {
86
- if (!this.pending.has(id)) return
87
- this.pending.delete(id)
88
- clearTimeout(timer)
89
- reject(
90
- signal.reason instanceof Error
91
- ? signal.reason
92
- : new Error(`MCP request ${method} aborted`),
93
- )
94
- },
95
- { once: true },
96
- )
82
+ const onAbort = () => {
83
+ if (!this.pending.has(id)) return
84
+ this.pending.delete(id)
85
+ clearTimeout(timer)
86
+ const reason = signal?.reason
87
+ reject(reason instanceof Error ? reason : new Error(`MCP request ${method} aborted`))
88
+ }
89
+ // [RL-5] Simpan pembersih listener agar request yang settle normal
90
+ // (respon masuk / timeout) melepas `onAbort` dari signal — anti bocor.
91
+ const unsubscribe = () => signal?.removeEventListener("abort", onAbort)
92
+ signal?.addEventListener("abort", onAbort, { once: true })
93
+ this.pending.set(id, { resolve, reject, timer, unsubscribe })
97
94
  })
98
95
  }
99
96