minicode-ai 0.13.0 → 0.14.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 (83) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/LICENSE +21 -21
  3. package/README.md +4 -0
  4. package/cli/args.ts +50 -2
  5. package/cli/commands/acp.ts +18 -3
  6. package/cli/commands/daemon.ts +114 -19
  7. package/cli/commands/exec.ts +95 -7
  8. package/cli/commands/mcp.ts +66 -5
  9. package/cli/commands/memory.ts +46 -14
  10. package/cli/commands.ts +5 -0
  11. package/cli/index.ts +30 -5
  12. package/cli/minicode.js +6 -0
  13. package/cli/setup.ts +365 -24
  14. package/cli/tui.ts +72 -27
  15. package/docs/TERMINAL_CONTRACT.md +91 -24
  16. package/docs/agents.md +2 -2
  17. package/docs/cli.md +1 -0
  18. package/docs/environment.md +1 -0
  19. package/docs/memory-sessions.md +5 -0
  20. package/package.json +3 -2
  21. package/src/app/session.ts +153 -35
  22. package/src/app/tool-layer.ts +67 -61
  23. package/src/daemon/approvals.ts +25 -1
  24. package/src/daemon/client.ts +51 -1
  25. package/src/daemon/control.ts +8 -0
  26. package/src/daemon/protocol.ts +47 -1
  27. package/src/daemon/server.ts +45 -9
  28. package/src/daemon/subscription.ts +25 -1
  29. package/src/daemon/telemetry.ts +4 -0
  30. package/src/hooks/run.ts +5 -1
  31. package/src/mcp/client.ts +349 -90
  32. package/src/mcp/http-transport.ts +7 -0
  33. package/src/mcp/transport.ts +5 -0
  34. package/src/memory/files.ts +69 -3
  35. package/src/memory/vector.ts +556 -160
  36. package/src/policy/approval-binding.ts +199 -0
  37. package/src/policy/context.ts +20 -1
  38. package/src/policy/executor.ts +44 -5
  39. package/src/policy/permission.ts +243 -26
  40. package/src/policy/tool-contract.ts +77 -0
  41. package/src/policy/usage.ts +3 -1
  42. package/src/policy/work-mode.ts +49 -1
  43. package/src/presentation/adapter.ts +157 -7
  44. package/src/presentation/events.ts +173 -1
  45. package/src/presentation/model.ts +37 -0
  46. package/src/presentation/projection.ts +107 -18
  47. package/src/presentation/reducer.ts +134 -10
  48. package/src/sandbox/os.ts +18 -1
  49. package/src/session/persistence.ts +153 -11
  50. package/src/task/store.ts +43 -3
  51. package/src/tools/memory.ts +70 -10
  52. package/src/tools/task.ts +7 -1
  53. package/src/tools/todo.ts +14 -4
  54. package/src/ui/approval/prompt.ts +52 -7
  55. package/src/ui/assistant/simple.ts +160 -57
  56. package/src/ui/contract.ts +46 -0
  57. package/src/ui/footer.ts +14 -5
  58. package/src/ui/i18n/en.ts +9 -0
  59. package/src/ui/i18n/id.ts +9 -0
  60. package/src/ui/render/collapse.ts +24 -52
  61. package/src/ui/render/detail.ts +14 -9
  62. package/src/ui/render/errors.ts +8 -0
  63. package/src/ui/render/reasoning.ts +13 -8
  64. package/src/ui/session-state.ts +243 -0
  65. package/src/ui/tui/app.ts +7 -3
  66. package/src/ui/tui/transcript.ts +271 -30
  67. package/vendor/minicore/src/core/budget.ts +25 -25
  68. package/vendor/minicore/src/core/compact.ts +75 -75
  69. package/vendor/minicore/src/core/errors.ts +59 -59
  70. package/vendor/minicore/src/core/events.ts +73 -73
  71. package/vendor/minicore/src/core/executor.ts +139 -139
  72. package/vendor/minicore/src/core/history.ts +31 -31
  73. package/vendor/minicore/src/core/index.ts +41 -41
  74. package/vendor/minicore/src/core/loop.ts +355 -355
  75. package/vendor/minicore/src/core/permission.ts +22 -22
  76. package/vendor/minicore/src/core/provider.ts +39 -39
  77. package/vendor/minicore/src/core/recovery.ts +35 -35
  78. package/vendor/minicore/src/core/session.ts +327 -327
  79. package/vendor/minicore/src/core/snapshot.ts +146 -146
  80. package/vendor/minicore/src/core/tokens.ts +107 -107
  81. package/vendor/minicore/src/core/tool.ts +115 -115
  82. package/vendor/minicore/src/core/types.ts +50 -50
  83. package/vendor/minicore/src/providers/openai-compat.ts +417 -417
@@ -368,7 +368,15 @@ export function selectNodes(state: PresentationState, mode: ProjectionMode): Pro
368
368
  if (ref.kind === "system") {
369
369
  const entry = state.system.find((s) => s.id === ref.id)
370
370
  if (!entry) continue
371
- if (mode === "normal" && entry.systemKind !== "checkpoint" && entry.systemKind !== "recovery")
371
+ // F-TASK-1: notice status task tetap terlihat di proyeksi `normal` —
372
+ // event ini adalah observabilitas kanonik (bukan notice internal biasa)
373
+ // dan justru hilang bila disaring bersama notice lain.
374
+ if (
375
+ mode === "normal" &&
376
+ entry.systemKind !== "checkpoint" &&
377
+ entry.systemKind !== "recovery" &&
378
+ entry.taskId === undefined
379
+ )
372
380
  continue
373
381
  out.push({ kind: "system", id: ref.id, seq: ref.seq, data: entry })
374
382
  continue
@@ -562,6 +570,24 @@ export interface MachineEventInput {
562
570
  provenance?: unknown
563
571
  /** Observasi verifikasi (tanpa evidenceReference — tetap di jurnal). */
564
572
  verification?: unknown
573
+ // ── P1 Observability & Interaction (aditif) ──
574
+ verdict?: unknown
575
+ failureClass?: unknown
576
+ nextAction?: unknown
577
+ newEvidenceSinceLastAttempt?: unknown
578
+ riskTier?: unknown
579
+ diffPreview?: unknown
580
+ schemaDrift?: unknown
581
+ taskId?: unknown
582
+ taskStatus?: unknown
583
+ parentId?: unknown
584
+ dependsOn?: unknown
585
+ revision?: unknown
586
+ usedTokens?: unknown
587
+ windowTokens?: unknown
588
+ percent?: unknown
589
+ costUsd?: unknown
590
+ providerModel?: unknown
565
591
  }
566
592
 
567
593
  const VALID_PROVENANCE: readonly string[] = ["live", "replay", "reconstructed", "unknown"]
@@ -589,21 +615,6 @@ export interface MachineEnvelope {
589
615
  payload: Record<string, unknown>
590
616
  }
591
617
 
592
- export interface MachineEnvelope {
593
- schema: typeof MACHINE_SCHEMA
594
- eventId: string
595
- type: string
596
- timestamp: string
597
- sessionId: string
598
- turnId?: number
599
- correlationId?: string
600
- source: "derived"
601
- severity: MachineSeverity
602
- status: MachineStatus
603
- visibility: ["machine"]
604
- payload: Record<string, unknown>
605
- }
606
-
607
618
  export interface MachineContext {
608
619
  sessionId: string
609
620
  /** Jam tepi (ms epoch); wajib di-inject agar deterministik di test. */
@@ -653,6 +664,20 @@ export function machineSeverity(event: MachineEventInput): MachineSeverity {
653
664
  const explicit = asString(event.severity)
654
665
  if (explicit && (VALID_SEVERITIES as readonly string[]).includes(explicit))
655
666
  return explicit as MachineSeverity
667
+ // ── P1 Observability (aditif) ──
668
+ if (event.type === "consequence.decided") {
669
+ const verdict = asString(event.verdict)
670
+ // P1.5: PASS = "info" (sebelumnya "warning" — salah karena bukan masalah),
671
+ // INCONCLUSIVE = "warning" (memerlukan perhatian tapi bukan error).
672
+ if (verdict === "FAIL" || verdict === "BLOCKED") return "error"
673
+ if (verdict === "INCONCLUSIVE") return "warning"
674
+ return "info"
675
+ }
676
+ if (event.type === "context.cutoff") return "warning"
677
+ if (event.type === "task.status") {
678
+ const status = asString(event.taskStatus)
679
+ return status === "FAILED" ? "error" : status === "BLOCKED" ? "warning" : "info"
680
+ }
656
681
  const suffix = eventSuffix(event.type)
657
682
  if (suffix === "failed" || suffix === "interrupted" || event.error !== undefined) return "error"
658
683
  if (suffix === "denied" || suffix === "cancelled") return "warning"
@@ -677,6 +702,26 @@ export function machineStatus(event: MachineEventInput): MachineStatus {
677
702
  }
678
703
  if (event.type === "finding.detected") return "completed"
679
704
  if (event.type === "diagnostic.raised") return "active"
705
+ // ── P1 Observability (aditif) ──
706
+ // P1.5: consequence.decided status mencerminkan verdict — sebelumnya
707
+ // selalu "completed" meskipun FAIL/BLOCKED.
708
+ if (event.type === "consequence.decided") {
709
+ const verdict = asString(event.verdict)
710
+ if (verdict === "FAIL") return "failed"
711
+ if (verdict === "BLOCKED") return "interrupted"
712
+ if (verdict === "INCONCLUSIVE") return "active"
713
+ return "completed"
714
+ }
715
+ if (event.type === "context.cutoff") return "interrupted"
716
+ if (event.type === "context.window") return "active"
717
+ if (event.type === "task.status") {
718
+ const status = asString(event.taskStatus)
719
+ if (status === "COMPLETED") return "completed"
720
+ if (status === "FAILED") return "failed"
721
+ if (status === "CANCELLED") return "cancelled"
722
+ if (status === "BLOCKED") return "interrupted"
723
+ return "active"
724
+ }
680
725
  const suffix = eventSuffix(event.type)
681
726
  if (
682
727
  suffix === "started" ||
@@ -751,6 +796,36 @@ export function machinePayload(event: MachineEventInput): Record<string, unknown
751
796
  put("severity", asString(event.severity))
752
797
  put("action", asString(event.action))
753
798
  put("compactionReason", asString(event.compactionReason))
799
+ // ── P1 Observability & Interaction (aditif) ──
800
+ put("verdict", asString(event.verdict))
801
+ put("failureClass", asString(event.failureClass))
802
+ put("nextAction", asString(event.nextAction))
803
+ put(
804
+ "newEvidenceSinceLastAttempt",
805
+ typeof event.newEvidenceSinceLastAttempt === "boolean"
806
+ ? event.newEvidenceSinceLastAttempt
807
+ : undefined,
808
+ )
809
+ put("riskTier", asString(event.riskTier))
810
+ put("diffPreview", asString(event.diffPreview))
811
+ if (event.schemaDrift !== undefined && event.schemaDrift !== null)
812
+ payload.schemaDrift = event.schemaDrift
813
+ put("taskId", asString(event.taskId))
814
+ put("taskStatus", asString(event.taskStatus))
815
+ put("parentId", asString(event.parentId))
816
+ if (Array.isArray(event.dependsOn)) payload.dependsOn = event.dependsOn.slice(0, 100)
817
+ put("revision", asNumber(event.revision))
818
+ const taskVerification = asRecord((event as { taskVerification?: unknown }).taskVerification)
819
+ if (taskVerification) payload.taskVerification = taskVerification
820
+ put("usedTokens", asNumber(event.usedTokens))
821
+ put("windowTokens", asNumber(event.windowTokens))
822
+ put("percent", asNumber(event.percent))
823
+ put("costUsd", asNumber(event.costUsd))
824
+ put("providerModel", asString(event.providerModel))
825
+ // P1.6: identitas anak tidak boleh hilang di machine envelope. `childSessionId`
826
+ // = session anak, `runId` = run kanonik anak, `parentToolCallId` = taut pemanggil.
827
+ put("childSessionId", asString((event as { childSessionId?: unknown }).childSessionId))
828
+ put("runId", asString((event as { runId?: unknown }).runId))
754
829
  const outcome = asRecord(event.outcome)
755
830
  if (outcome) payload.outcome = outcome
756
831
  const summary = asRecord(event.summary)
@@ -789,12 +864,16 @@ export function toMachineEnvelope(
789
864
  const turnId = asNumber(event.turnId)
790
865
  const seq = asNumber(event.seq)
791
866
  const provenance = asProvenance(event.provenance)
867
+ // Identitas event mengikuti session pemilik event (anak untuk forward), bukan
868
+ // selalu session induk. Adapter anak punya `seq`/`turnId` sendiri; memakai
869
+ // induk akan menghasilkan eventId yang sama untuk dua event berbeda.
870
+ const eventSessionId = asString((event as { sessionId?: unknown }).sessionId) ?? ctx.sessionId
792
871
  const envelope: MachineEnvelope = {
793
872
  schema: MACHINE_SCHEMA,
794
- eventId: machineEventId(ctx.sessionId, turnId, seq),
873
+ eventId: machineEventId(eventSessionId, turnId, seq),
795
874
  type: event.type,
796
875
  timestamp: machineTimestamp(ctx.timestamp),
797
- sessionId: ctx.sessionId,
876
+ sessionId: eventSessionId,
798
877
  ...(turnId !== undefined ? { turnId } : {}),
799
878
  source: "derived",
800
879
  severity: machineSeverity(event),
@@ -843,6 +922,16 @@ export function machineError(e: unknown): MachineError {
843
922
  )
844
923
  if (name === "NoProviderError" || /no provider configured/i.test(message))
845
924
  return { category: "CONFIGURATION_ERROR", message, action: "configure a provider" }
925
+ // [Live Hardening 0.13.x §8.1] kind budget_exceeded yang sebenarnya kehabisan
926
+ // jendela konteks ("context window exceeded after compaction", vendor loop)
927
+ // HARUS disarankan start-sesi-baru/model-jendela-besar, bukan --budget. Branch
928
+ // ini diselaraskan dengan Fix 4 di src/ui/render/errors.ts (err.context).
929
+ if (kind === "budget_exceeded" && /context window/i.test(message))
930
+ return {
931
+ category: "USER_ERROR",
932
+ message,
933
+ action: "start a new session or use a model with a larger context window",
934
+ }
846
935
  if (kind === "budget_exceeded" || /over budget|unknown cost/i.test(message))
847
936
  return { category: "USER_ERROR", message, action: "raise --budget or reduce usage" }
848
937
  if (kind === "timeout" || (/timeout|timed out/i.test(message) && kind !== "aborted"))
@@ -72,13 +72,35 @@ function isTurnTerminal(status: TurnStatus): boolean {
72
72
  return TURN_TERMINAL.has(status)
73
73
  }
74
74
 
75
+ // P2.2: index non-enumerable untuk `order`. Tanpa ini `addOrder`/`removeOrder`
76
+ // melakukan scan linear pada SETIAP event; saat transkrip panjang (cap 4096)
77
+ // burst 5k event menjadi O(n²). Index dibangun lazy dan tidak ikut serialisasi
78
+ // (cloneState/replay membangun ulang dari `order`).
79
+ const ORDER_KEYS = Symbol("minicode.orderKeys")
80
+ type OrderKeyedState = PresentationState & { [ORDER_KEYS]?: Set<string> }
81
+ const orderKey = (kind: string, id: string): string => `${kind}\u0000${id}`
82
+
83
+ function orderKeys(state: PresentationState): Set<string> {
84
+ const holder = state as OrderKeyedState
85
+ let keys = holder[ORDER_KEYS]
86
+ if (!keys) {
87
+ keys = new Set(state.order.map((o) => orderKey(o.kind, o.id)))
88
+ Object.defineProperty(state, ORDER_KEYS, { value: keys, enumerable: false, configurable: true })
89
+ }
90
+ return keys
91
+ }
92
+
75
93
  function addOrder(
76
94
  state: PresentationState,
77
95
  kind: PresentationState["order"][number]["kind"],
78
96
  id: string,
79
97
  seq: number,
80
98
  ): void {
81
- if (!state.order.some((o) => o.kind === kind && o.id === id)) state.order.push({ kind, id, seq })
99
+ const keys = orderKeys(state)
100
+ const key = orderKey(kind, id)
101
+ if (keys.has(key)) return
102
+ keys.add(key)
103
+ state.order.push({ kind, id, seq })
82
104
  }
83
105
 
84
106
  function removeOrder(
@@ -86,8 +108,15 @@ function removeOrder(
86
108
  kind: PresentationState["order"][number]["kind"],
87
109
  id: string,
88
110
  ): void {
89
- for (let i = state.order.length - 1; i >= 0; i--) {
90
- if (state.order[i]!.kind === kind && state.order[i]!.id === id) state.order.splice(i, 1)
111
+ const keys = orderKeys(state)
112
+ keys.delete(orderKey(kind, id))
113
+ // Scan dari depan: entri yang dievict adalah yang paling tua, jadi biasanya
114
+ // ketemu di awal. Satu key hanya punya satu entri order.
115
+ for (let i = 0; i < state.order.length; i++) {
116
+ if (state.order[i]!.kind === kind && state.order[i]!.id === id) {
117
+ state.order.splice(i, 1)
118
+ return
119
+ }
91
120
  }
92
121
  }
93
122
 
@@ -315,11 +344,21 @@ function trimState(state: PresentationState): void {
315
344
  removable: (value: T) => boolean,
316
345
  ): void => {
317
346
  while (values.size > MAX_STATE_ENTRIES) {
318
- const entry = [...values.entries()].find(([, value]) => removable(value))
319
- if (!entry) return
320
- values.delete(entry[0])
321
- state.evicted.push({ kind, id: entry[0], seq: entry[1].seq, reason: "bounded" })
322
- removeOrder(state, kind, entry[0])
347
+ // P2.2: iterasi langsung, bukan `[...entries()].find()` — versi lama
348
+ // mengalokasikan array berisi ribuan entri untuk SETIAP eviction.
349
+ let removedKey: string | undefined
350
+ let removedValue: T | undefined
351
+ for (const [key, value] of values) {
352
+ if (removable(value)) {
353
+ removedKey = key
354
+ removedValue = value
355
+ break
356
+ }
357
+ }
358
+ if (removedKey === undefined || removedValue === undefined) return
359
+ values.delete(removedKey)
360
+ state.evicted.push({ kind, id: removedKey, seq: removedValue.seq, reason: "bounded" })
361
+ removeOrder(state, kind, removedKey)
323
362
  }
324
363
  }
325
364
  trimMap(state.turns, "turn", (v) => isTurnTerminal(v.status))
@@ -330,8 +369,11 @@ function trimState(state: PresentationState): void {
330
369
  trimMap(state.results, "result", () => true)
331
370
  if (state.evicted.length > MAX_STATE_ENTRIES)
332
371
  state.evicted.splice(0, state.evicted.length - MAX_STATE_ENTRIES)
333
- if (state.order.length > MAX_STATE_ENTRIES * 2)
334
- state.order.splice(0, state.order.length - MAX_STATE_ENTRIES * 2)
372
+ if (state.order.length > MAX_STATE_ENTRIES * 2) {
373
+ const removed = state.order.splice(0, state.order.length - MAX_STATE_ENTRIES * 2)
374
+ const keys = orderKeys(state)
375
+ for (const entry of removed) keys.delete(orderKey(entry.kind, entry.id))
376
+ }
335
377
  }
336
378
 
337
379
  export function reduce(
@@ -388,6 +430,10 @@ export function reduce(
388
430
  toolCallId: event.toolCallId,
389
431
  sessionId: event.sessionId,
390
432
  ...(event.parentLink ? { parentToolCallId: event.parentLink.parentToolCallId } : {}),
433
+ ...(event.parentLink?.childSessionId
434
+ ? { childSessionId: event.parentLink.childSessionId }
435
+ : {}),
436
+ ...(event.parentLink?.runId ? { runId: event.parentLink.runId } : {}),
391
437
  identity: event.identity,
392
438
  ...(target ? { target } : {}),
393
439
  status: "running",
@@ -487,6 +533,11 @@ export function reduce(
487
533
  toolCallId: event.toolCallId ?? "",
488
534
  identity: event.identity,
489
535
  state: "requested",
536
+ // F-APPROVAL-1: tier risiko + pratinjau diff diteruskan utuh ke model
537
+ // (bukan ditelan) agar proyeksi/machine punya bukti yang sama dengan
538
+ // yang user lihat di kartu approval.
539
+ ...(event.riskTier ? { riskTier: event.riskTier } : {}),
540
+ ...(event.diffPreview ? { diffPreview: event.diffPreview } : {}),
490
541
  }
491
542
  state.approvals.set(key, entry)
492
543
  addOrder(state, "approval", key, seq)
@@ -755,6 +806,79 @@ export function reduce(
755
806
  case "model.delta":
756
807
  case "reasoning.delta":
757
808
  return state
809
+ // F-CTX-1: meter jendela konteks live — NON-durable, murni untuk footer /
810
+ // machine. Tidak menyentuh state (tidak boleh di-replay jadi histori).
811
+ case "context.window":
812
+ return state
813
+ // F-CTRL-1/F-CTRL-2: keputusan consequence terstruktur (ACE). Masuk
814
+ // diagnostics sebagai kategori "ACE" agar terlihat terstruktur, bukan
815
+ // stderr yang hilang.
816
+ case "consequence.decided": {
817
+ ensureTurn(state, event.sessionId, event.turnId, seq, event.ts)
818
+ const id = `${event.sessionId}:${event.turnId}:ace:${seq}`
819
+ const entry: DiagnosticEntry = {
820
+ kind: "diagnostic",
821
+ id,
822
+ seq,
823
+ sessionId: event.sessionId,
824
+ turnId: event.turnId,
825
+ category: "ACE",
826
+ severity: event.verdict === "FAIL" || event.verdict === "BLOCKED" ? "error" : "warning",
827
+ message: event.rationale,
828
+ verdict: event.verdict,
829
+ cause: event.failureClass,
830
+ action: event.nextAction,
831
+ ...(event.newEvidenceSinceLastAttempt !== undefined
832
+ ? { newEvidenceSinceLastAttempt: event.newEvidenceSinceLastAttempt }
833
+ : {}),
834
+ }
835
+ state.diagnostics.push(entry)
836
+ addOrder(state, "diagnostic", id, seq)
837
+ return state
838
+ }
839
+ // F-CTX-2: pemotongan mi-stream yang durable — masuk transkrip.
840
+ case "context.cutoff": {
841
+ ensureTurn(state, event.sessionId, event.turnId, seq, event.ts)
842
+ const id = `${event.sessionId}:${event.turnId}:cutoff:${seq}`
843
+ const entry: DiagnosticEntry = {
844
+ kind: "diagnostic",
845
+ id,
846
+ seq,
847
+ sessionId: event.sessionId,
848
+ turnId: event.turnId,
849
+ category: "CONTEXT_CUTOFF",
850
+ severity: "warning",
851
+ message: event.reason,
852
+ }
853
+ state.diagnostics.push(entry)
854
+ addOrder(state, "diagnostic", id, seq)
855
+ return state
856
+ }
857
+ // F-TASK-1: transisi status task kanonik + DAG (notice system).
858
+ case "task.status": {
859
+ ensureTurn(state, event.sessionId, event.turnId, seq, event.ts)
860
+ const id = `${event.sessionId}:${event.turnId}:task:${event.taskId}:${seq}`
861
+ const deps = event.dependsOn?.length ? `dependsOn=[${event.dependsOn.join(",")}]` : ""
862
+ const entry: SystemEntry = {
863
+ kind: "system",
864
+ id,
865
+ seq,
866
+ sessionId: event.sessionId,
867
+ turnId: event.turnId,
868
+ systemKind: "notice",
869
+ text: `${event.taskId} ${event.status.toLowerCase()}`,
870
+ reason: deps || undefined,
871
+ severity: "info",
872
+ taskId: event.taskId,
873
+ taskStatus: event.status,
874
+ ...(event.parentId ? { parentId: event.parentId } : {}),
875
+ ...(event.dependsOn?.length ? { dependsOn: [...event.dependsOn] } : {}),
876
+ ...(event.revision !== undefined ? { revision: event.revision } : {}),
877
+ }
878
+ state.system.push(entry)
879
+ addOrder(state, "system", id, seq)
880
+ return state
881
+ }
758
882
  default: {
759
883
  diag.unknownEvent++
760
884
  return state
package/src/sandbox/os.ts CHANGED
@@ -154,10 +154,16 @@ function runSpawn(
154
154
  // F-23: bin di-resolve absolut dari PATH terpercaya di sini (satu titik
155
155
  // untuk seatbelt/bwrap) — spawn dengan cwd workspace di Windows bisa
156
156
  // mengeksekusi <bin>.bat repo bila hanya nama telanjang.
157
+ // detached:true → bwrap/sandbox-exec menjadi process-group leader, sehingga
158
+ // timeout bisa membunuh SELURUH pohon (runner + child command) via group kill,
159
+ // bukan hanya pemimpinnya. Tanpa ini, p.kill("SIGKILL") hanya membunuh bwrap;
160
+ // child `node -e 'while(true){}'` tetap hidup mewarisi stdio pipe sehingga
161
+ // event `close` tak pernah menyala → hang + proses bocor (test code_run loop).
157
162
  const p = spawn(resolveTrustedExecutable(bin), args, {
158
163
  cwd,
159
164
  env,
160
165
  stdio: ["ignore", "pipe", "pipe"],
166
+ detached: true,
161
167
  })
162
168
  const OUT_CAP = LIMITS.DOCKER_OUTPUT_MAX_CHARS
163
169
  let out = ""
@@ -178,7 +184,18 @@ function runSpawn(
178
184
  }
179
185
  p.stdout.on("data", (d) => appendCapped("out", d))
180
186
  p.stderr.on("data", (d) => appendCapped("err", d))
181
- const t = setTimeout(() => p.kill("SIGKILL"), timeoutMs)
187
+ const t = setTimeout(() => {
188
+ // SIGKILL ke seluruh process group (bwrap + child command). Fallback ke
189
+ // kill tunggal bila pid tak tersedia (spawn gagal sinkron).
190
+ try {
191
+ if (p.pid !== undefined) process.kill(-p.pid, "SIGKILL")
192
+ else p.kill("SIGKILL")
193
+ } catch {
194
+ try {
195
+ p.kill("SIGKILL")
196
+ } catch {}
197
+ }
198
+ }, timeoutMs)
182
199
  p.on("error", (e) => {
183
200
  clearTimeout(t)
184
201
  resolveResult({ code: null, output: `[os-sandbox] ${e.message}` })
@@ -4,7 +4,7 @@ import { existsSync } from "node:fs"
4
4
  import { LIMITS } from "../constants.ts"
5
5
  import { resolveDbPath, resolveLocalDbPath } from "../lib/db-path.ts"
6
6
  import { scrubSecrets } from "../policy/scrub.ts"
7
- import { type DomainEvent, DURABILITY } from "../presentation/events.ts"
7
+ import { type DomainEvent, DURABILITY, EVENT_SCHEMA_VERSION } from "../presentation/events.ts"
8
8
 
9
9
  // `local=true` = SELALU `<cwd>/.minicode/sessions.db`, tanpa fallback ke
10
10
  // `~/.minicode` global. Fallback global itu benar untuk histori lintas-repo,
@@ -34,7 +34,9 @@ const migratedSessionPaths = new Set<string>()
34
34
  function daemonApprovalsMigrated(db: Database): boolean {
35
35
  try {
36
36
  const cols = db.prepare("PRAGMA table_info(daemon_approvals)").all() as { name: string }[]
37
- return cols.some((c) => c.name === "invocation_id")
37
+ if (!cols.some((c) => c.name === "invocation_id")) return false
38
+ const sessCols = db.prepare("PRAGMA table_info(sessions)").all() as { name: string }[]
39
+ return sessCols.some((c) => c.name === "work_mode")
38
40
  } catch {
39
41
  return false
40
42
  }
@@ -180,7 +182,7 @@ function open(cwd?: string, local = false): Database {
180
182
  // gagal di statement berikutnya dengan pesan yang lebih jelas.
181
183
  withBusyRetrySync(() => {
182
184
  db.exec(`
183
- CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, created_at INTEGER, cwd TEXT, system TEXT, writer_epoch INTEGER NOT NULL DEFAULT 0, default_thread_id TEXT NULL);
185
+ CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, created_at INTEGER, cwd TEXT, system TEXT, writer_epoch INTEGER NOT NULL DEFAULT 0, default_thread_id TEXT NULL, work_mode TEXT NULL);
184
186
  CREATE TABLE IF NOT EXISTS messages (session_id TEXT, seq INTEGER, role TEXT, content TEXT, toolCalls TEXT, toolCallId TEXT, name TEXT, reasoning TEXT, is_error INTEGER, ts INTEGER, thread_id TEXT NULL, event_id TEXT NULL, run_id TEXT NULL, migrated INTEGER NOT NULL DEFAULT 0, migrated_compacted INTEGER NOT NULL DEFAULT 0, projection_note TEXT NULL, PRIMARY KEY(session_id, seq));
185
187
  CREATE TABLE IF NOT EXISTS turns (session_id TEXT, turn_idx INTEGER, usage TEXT, ts INTEGER, PRIMARY KEY(session_id, turn_idx));
186
188
  CREATE TABLE IF NOT EXISTS presentation_events (
@@ -214,6 +216,11 @@ function open(cwd?: string, local = false): Database {
214
216
  if (!cols.some((c) => c.name === "parent_run_id")) {
215
217
  db.exec("ALTER TABLE sessions ADD COLUMN parent_run_id TEXT NULL")
216
218
  }
219
+ // P0.2 (Q5): persistensi WorkMode di metadata sesi lintas `--resume`.
220
+ // NULL = sesi legacy pra-P0.2 (resume fallback ke default EXECUTE).
221
+ if (!cols.some((c) => c.name === "work_mode")) {
222
+ db.exec("ALTER TABLE sessions ADD COLUMN work_mode TEXT NULL")
223
+ }
217
224
  db.exec(`CREATE INDEX IF NOT EXISTS idx_sessions_parent ON sessions(parent_session_id)`)
218
225
  } catch (e) {
219
226
  process.stderr.write(
@@ -692,11 +699,47 @@ function isValidPlanStep(s: unknown): boolean {
692
699
 
693
700
  const PLAN_STEP_STATUSES = new Set(["pending", "active", "completed", "cancelled", "blocked"])
694
701
  const PLAN_STATUSES = new Set(["open", "completed", "cancelled"])
702
+ // F-TASK-1: status task kanonik (cermin local dari events.ts — persistence tidak
703
+ // mengimpor src/ui; literal display distabilkan di sini untuk validasi shape).
704
+ const TASK_STATUS_DISPLAY = new Set([
705
+ "PENDING",
706
+ "IN_PROGRESS",
707
+ "VERIFYING",
708
+ "BLOCKED",
709
+ "FAILED",
710
+ "RETRYING",
711
+ "COMPLETED",
712
+ "CANCELLED",
713
+ ])
714
+
715
+ /** P2.1: boundary validation untuk link anak (opsional tetapi shape-nya ketat). */
716
+ function isValidParentLink(value: unknown): boolean {
717
+ if (value === undefined) return true
718
+ if (!value || typeof value !== "object") return false
719
+ const link = value as Record<string, unknown>
720
+ if (typeof link.parentToolCallId !== "string" || typeof link.childSessionId !== "string")
721
+ return false
722
+ for (const key of ["parentSessionId", "runId"]) {
723
+ if (link[key] !== undefined && typeof link[key] !== "string") return false
724
+ }
725
+ return true
726
+ }
727
+
728
+ function isValidTaskVerification(value: unknown): boolean {
729
+ if (value === undefined) return true
730
+ if (!value || typeof value !== "object") return false
731
+ const v = value as Record<string, unknown>
732
+ return (
733
+ (v.verdict === "passed" || v.verdict === "failed" || v.verdict === "unverified") &&
734
+ typeof v.checkedAt === "string"
735
+ )
736
+ }
695
737
 
696
738
  function isValidEventShape(value: Record<string, unknown>): boolean {
697
739
  const isStr = (k: string): boolean => typeof value[k] === "string"
698
740
  const isNum = (k: string): boolean => typeof value[k] === "number"
699
741
  const isArr = (k: string): boolean => Array.isArray(value[k])
742
+ if (!isValidParentLink(value.parentLink)) return false
700
743
  switch (value.type) {
701
744
  case "plan.updated":
702
745
  return (
@@ -705,8 +748,19 @@ function isValidEventShape(value: Record<string, unknown>): boolean {
705
748
  isArr("steps") &&
706
749
  (value.steps as unknown[]).every(isValidPlanStep)
707
750
  )
708
- case "tool.started":
709
- return isStr("toolCallId") && isNum("stepId") && !!value.identity && !!value.argsSummary
751
+ case "tool.started": {
752
+ const identity = value.identity as { name?: unknown; qualified?: unknown } | undefined
753
+ const argsSummary = value.argsSummary as { target?: unknown } | undefined
754
+ return (
755
+ isStr("toolCallId") &&
756
+ isNum("stepId") &&
757
+ !!identity &&
758
+ typeof identity.name === "string" &&
759
+ typeof identity.qualified === "string" &&
760
+ !!argsSummary &&
761
+ typeof argsSummary === "object"
762
+ )
763
+ }
710
764
  case "tool.progress":
711
765
  case "tool.completed":
712
766
  case "tool.failed":
@@ -752,8 +806,21 @@ function isValidEventShape(value: Record<string, unknown>): boolean {
752
806
  return isStr("resultId") && !!value.status
753
807
  case "diagnostic.raised":
754
808
  return isStr("category") && isStr("message")
809
+ case "consequence.decided":
810
+ return isStr("verdict") && isStr("failureClass") && isStr("nextAction") && isStr("rationale")
811
+ case "context.cutoff":
812
+ return isStr("reason")
813
+ case "task.status":
814
+ return (
815
+ isStr("taskId") &&
816
+ isStr("status") &&
817
+ TASK_STATUS_DISPLAY.has(value.status as string) &&
818
+ isValidTaskVerification(value.verification)
819
+ )
755
820
  default:
756
- return true
821
+ // P2.1: fail-safe. Tipe durable baru wajib punya validator eksplisit;
822
+ // default-true membuat payload rusak dari versi lain lolos ke reducer.
823
+ return false
757
824
  }
758
825
  }
759
826
 
@@ -774,6 +841,17 @@ function decodePresentationEvent(payload: string): DomainEvent | null {
774
841
  // Stub hasil truncate (`encodePresentationEvent`) hanya punya Base +
775
842
  // `truncated`. Tolak eksplisit supaya tidak pernah sampai ke `reduce`.
776
843
  if ((value as { truncated?: unknown }).truncated === true) return null
844
+ // P2.1: versi skema. Absen = v1 (kompatibilitas replay lama); versi masa
845
+ // depan ditolak fail-safe, bukan dibaca dengan cast yang berasumsi shape.
846
+ const version = (value as { v?: unknown }).v
847
+ if (
848
+ version !== undefined &&
849
+ (typeof version !== "number" ||
850
+ !Number.isInteger(version) ||
851
+ version < 1 ||
852
+ version > EVENT_SCHEMA_VERSION)
853
+ )
854
+ return null
777
855
  if (!isValidEventShape(value as unknown as Record<string, unknown>)) return null
778
856
  return value as DomainEvent
779
857
  } catch {
@@ -1032,7 +1110,11 @@ export async function saveSession(
1032
1110
  // legacy/test tanpa epoch memakai jalur tak-berpagar (tercatat di guard).
1033
1111
  // P2.6: runId opsional — baris BARU (bukan adopsi) dicap milik run ini dan
1034
1112
  // kursor run maju ke head dalam txn yang SAMA (atomik histori+kursor).
1035
- opts?: { expectedEpoch?: number; runId?: string },
1113
+ opts?: {
1114
+ expectedEpoch?: number
1115
+ runId?: string
1116
+ workMode?: "DISCUSS" | "PLAN" | "EXECUTE"
1117
+ },
1036
1118
  ) {
1037
1119
  const db = open(cwd)
1038
1120
  const now = Date.now()
@@ -1048,8 +1130,8 @@ export async function saveSession(
1048
1130
  // P2.2: upsert MEMPERTAHANKAN writer_epoch. INSERT OR REPLACE menghapus
1049
1131
  // lalu menyisipkan ulang (epoch kembali 0!) — dilarang untuk baris sesi.
1050
1132
  db.prepare(
1051
- "INSERT INTO sessions (id, created_at, updated_at, cwd, system, writer_epoch) VALUES (?, ?, ?, ?, ?, COALESCE((SELECT writer_epoch FROM sessions WHERE id = ?), 0)) ON CONFLICT(id) DO UPDATE SET updated_at = excluded.updated_at, cwd = excluded.cwd, system = excluded.system",
1052
- ).run(id, createdAt, now, cwd ?? "", system ?? "", id)
1133
+ "INSERT INTO sessions (id, created_at, updated_at, cwd, system, writer_epoch, work_mode) VALUES (?, ?, ?, ?, ?, COALESCE((SELECT writer_epoch FROM sessions WHERE id = ?), 0), ?) ON CONFLICT(id) DO UPDATE SET updated_at = excluded.updated_at, cwd = excluded.cwd, system = excluded.system, work_mode = COALESCE(excluded.work_mode, sessions.work_mode)",
1134
+ ).run(id, createdAt, now, cwd ?? "", system ?? "", id, opts?.workMode ?? null)
1053
1135
  // P2.4: histori dimiliki default Thread — ensure atomik dalam txn yang
1054
1136
  // sama (sesi + thread tak pernah terpisah; tak ada sesi threadless yang
1055
1137
  // durable). Backfill NULL aditif; archived menolak tulis (dorman).
@@ -1368,16 +1450,69 @@ function decodeMessageRows(rows: StoredMessageRow[]): unknown[] {
1368
1450
  })
1369
1451
  }
1370
1452
 
1453
+ function parseStoredWorkMode(raw: unknown): "DISCUSS" | "PLAN" | "EXECUTE" | undefined {
1454
+ if (raw === "DISCUSS" || raw === "PLAN" || raw === "EXECUTE") return raw
1455
+ return undefined
1456
+ }
1457
+
1458
+ export function loadSessionWorkMode(
1459
+ id: string,
1460
+ cwd?: string,
1461
+ ): "DISCUSS" | "PLAN" | "EXECUTE" | undefined {
1462
+ const db = open(cwd)
1463
+ try {
1464
+ const row = db.prepare("SELECT work_mode FROM sessions WHERE id = ?").get(id) as {
1465
+ work_mode?: string | null
1466
+ } | null
1467
+ return parseStoredWorkMode(row?.work_mode)
1468
+ } finally {
1469
+ db.close()
1470
+ }
1471
+ }
1472
+
1473
+ export function saveSessionWorkMode(
1474
+ id: string,
1475
+ workMode: "DISCUSS" | "PLAN" | "EXECUTE",
1476
+ cwd?: string,
1477
+ opts?: { expectedEpoch?: number },
1478
+ ): void {
1479
+ const db = open(cwd)
1480
+ try {
1481
+ const txn = db.transaction(() => {
1482
+ const existing = db.prepare("SELECT id FROM sessions WHERE id = ?").get(id) as {
1483
+ id: string
1484
+ } | null
1485
+ if (!existing) return
1486
+ if (opts?.expectedEpoch !== undefined) assertWriterEpochInTxn(db, id, opts.expectedEpoch)
1487
+ db.prepare("UPDATE sessions SET work_mode = ?, updated_at = ? WHERE id = ?").run(
1488
+ workMode,
1489
+ Date.now(),
1490
+ id,
1491
+ )
1492
+ })
1493
+ txn()
1494
+ } finally {
1495
+ db.close()
1496
+ }
1497
+ }
1498
+
1371
1499
  export function loadSession(
1372
1500
  id: string,
1373
1501
  cwd?: string,
1374
- ): { messages: unknown[]; system?: string; cwd?: string; turnCount?: number } | null {
1502
+ ): {
1503
+ messages: unknown[]
1504
+ system?: string
1505
+ cwd?: string
1506
+ turnCount?: number
1507
+ workMode?: "DISCUSS" | "PLAN" | "EXECUTE"
1508
+ } | null {
1375
1509
  const db = open(cwd)
1376
1510
  try {
1377
1511
  const sess = db.prepare("SELECT * FROM sessions WHERE id = ?").get(id) as {
1378
1512
  system: string
1379
1513
  cwd: string
1380
1514
  default_thread_id: string | null
1515
+ work_mode?: string | null
1381
1516
  } | null
1382
1517
  if (!sess) {
1383
1518
  return null
@@ -1395,7 +1530,14 @@ export function loadSession(
1395
1530
  .prepare("SELECT MAX(turn_idx) as m FROM turns WHERE session_id = ?")
1396
1531
  .get(id) as { m: number | null } | null
1397
1532
  const turnCount = turnRow?.m != null ? turnRow.m + 1 : 0
1398
- return { messages, system: sess.system, cwd: sess.cwd, turnCount }
1533
+ const workMode = parseStoredWorkMode(sess.work_mode)
1534
+ return {
1535
+ messages,
1536
+ system: sess.system,
1537
+ cwd: sess.cwd,
1538
+ turnCount,
1539
+ ...(workMode ? { workMode } : {}),
1540
+ }
1399
1541
  } finally {
1400
1542
  db.close()
1401
1543
  }