minicode-ai 0.27.0 → 0.30.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 (145) hide show
  1. package/README.md +1 -1
  2. package/cli/args.ts +184 -57
  3. package/cli/bootstrap/presentation-bridge.ts +383 -0
  4. package/cli/commands/acp.ts +45 -29
  5. package/cli/commands/auth.ts +17 -17
  6. package/cli/commands/config.ts +65 -66
  7. package/cli/commands/daemon.ts +44 -16
  8. package/cli/commands/doctor.ts +18 -15
  9. package/cli/commands/exec.ts +41 -89
  10. package/cli/commands/mcp.ts +25 -8
  11. package/cli/commands/memory.ts +16 -24
  12. package/cli/commands/openwork.ts +6 -2
  13. package/cli/commands/pricing.ts +14 -12
  14. package/cli/commands/providers.ts +36 -57
  15. package/cli/commands/sessions.ts +24 -18
  16. package/cli/commands/skills.ts +33 -18
  17. package/cli/commands/stats.ts +15 -30
  18. package/cli/commands.ts +73 -44
  19. package/cli/context-command-run.ts +30 -18
  20. package/cli/index.ts +51 -100
  21. package/cli/model-manager.ts +7 -2
  22. package/cli/provider-manager.ts +33 -18
  23. package/cli/router.ts +41 -12
  24. package/cli/setup.ts +241 -485
  25. package/cli/tui.ts +303 -100
  26. package/docs/TERMINAL_CONTRACT.md +258 -73
  27. package/docs/UI_RENDER_PIPELINE.md +9 -1
  28. package/docs/agents.md +2 -2
  29. package/docs/architecture.md +17 -32
  30. package/docs/choosing-mode.md +7 -9
  31. package/docs/cli.md +3 -5
  32. package/docs/environment.md +1 -2
  33. package/docs/policy-sandbox.md +3 -3
  34. package/docs/repl.md +2 -2
  35. package/docs/tools.md +1 -1
  36. package/package.json +1 -1
  37. package/src/app/mentions.ts +60 -13
  38. package/src/app/rag-layer.ts +17 -20
  39. package/src/app/session.ts +144 -68
  40. package/src/app/tool-layer.ts +38 -16
  41. package/src/config.ts +64 -104
  42. package/src/constants.ts +4 -6
  43. package/src/daemon/capability.ts +8 -1
  44. package/src/daemon/control.ts +3 -2
  45. package/src/daemon/server.ts +57 -0
  46. package/src/hooks/run.ts +73 -41
  47. package/src/lib/atomic-write.ts +31 -59
  48. package/src/lib/db-path.ts +47 -0
  49. package/src/lib/process-tree.ts +62 -0
  50. package/src/lib/public-http.ts +88 -23
  51. package/src/lib/trusted-exec.ts +48 -1
  52. package/src/lsp/client.ts +62 -17
  53. package/src/mcp/client.ts +85 -38
  54. package/src/mcp/http-transport.ts +28 -16
  55. package/src/mcp/transport.ts +42 -6
  56. package/src/memory/files.ts +164 -134
  57. package/src/memory/vector.ts +371 -420
  58. package/src/policy/approval-binding.ts +122 -45
  59. package/src/policy/bash-guard.ts +18 -7
  60. package/src/policy/compaction.ts +51 -18
  61. package/src/policy/context-window.ts +31 -8
  62. package/src/policy/context.ts +62 -36
  63. package/src/policy/executor.ts +17 -7
  64. package/src/policy/jail.ts +6 -8
  65. package/src/policy/microcompact.ts +4 -3
  66. package/src/policy/no-progress.ts +103 -22
  67. package/src/policy/permission.ts +36 -12
  68. package/src/policy/tool-contract.ts +74 -416
  69. package/src/policy/usage.ts +24 -2
  70. package/src/policy/verifier.ts +50 -2
  71. package/src/policy/work-mode.ts +28 -54
  72. package/src/presentation/adapter.ts +24 -16
  73. package/src/providers/anthropic.ts +16 -5
  74. package/src/providers/provision.ts +6 -56
  75. package/src/providers/responses.ts +38 -7
  76. package/src/providers/sse-bounds.ts +6 -4
  77. package/src/runtime/execution-journal.ts +4 -29
  78. package/src/sandbox/docker.ts +58 -34
  79. package/src/sandbox/mask.ts +157 -0
  80. package/src/sandbox/os.ts +107 -73
  81. package/src/session/authority.ts +29 -10
  82. package/src/session/context-projection.ts +6 -5
  83. package/src/session/db/runs.ts +397 -0
  84. package/src/session/db/schema.ts +358 -0
  85. package/src/session/open-work.ts +26 -3
  86. package/src/session/persistence.ts +74 -998
  87. package/src/session/verification.ts +170 -20
  88. package/src/skills/loader.ts +31 -16
  89. package/src/task/db/schema.ts +325 -0
  90. package/src/task/db/types.ts +269 -0
  91. package/src/task/production-scheduler.ts +13 -1
  92. package/src/task/store.ts +92 -1021
  93. package/src/telemetry/trace.ts +27 -0
  94. package/src/tools/ask_user.ts +1 -13
  95. package/src/tools/bash.ts +27 -92
  96. package/src/tools/code_run.ts +1 -1
  97. package/src/tools/context.ts +133 -0
  98. package/src/tools/delete_file.ts +3 -2
  99. package/src/tools/edit.ts +37 -72
  100. package/src/tools/git.ts +86 -9
  101. package/src/tools/glob.ts +26 -51
  102. package/src/tools/grep.ts +67 -57
  103. package/src/tools/hashline.ts +4 -0
  104. package/src/tools/lsp.ts +11 -8
  105. package/src/tools/mcp_call.ts +9 -6
  106. package/src/tools/memory.ts +56 -33
  107. package/src/tools/move_file.ts +36 -10
  108. package/src/tools/patch.ts +13 -21
  109. package/src/tools/read_file.ts +18 -25
  110. package/src/tools/read_image.ts +35 -33
  111. package/src/tools/submit_result.ts +29 -8
  112. package/src/tools/task.ts +74 -17
  113. package/src/tools/todo.ts +181 -74
  114. package/src/tools/web_fetch.ts +42 -2
  115. package/src/tools/web_search.ts +47 -8
  116. package/src/ui/approval/prompt.ts +206 -47
  117. package/src/ui/assistant/turn-status.ts +14 -5
  118. package/src/ui/footer.ts +4 -4
  119. package/src/ui/i18n/en.ts +47 -23
  120. package/src/ui/i18n/id.ts +76 -51
  121. package/src/ui/input/input.ts +4 -3
  122. package/src/ui/input/prompt-engine.ts +35 -5
  123. package/src/ui/render/activity-panel.ts +4 -2
  124. package/src/ui/render/hint.ts +7 -4
  125. package/src/ui/render/list.ts +32 -0
  126. package/src/ui/render/markdown.ts +6 -3
  127. package/src/ui/render/notice.ts +19 -0
  128. package/src/ui/render/table-grid.ts +7 -8
  129. package/src/ui/render/theme.ts +113 -39
  130. package/src/ui/runtime/screen.ts +74 -10
  131. package/src/ui/runtime/spinner.ts +19 -6
  132. package/src/ui/screens/dialog.ts +19 -1
  133. package/src/ui/screens/form.ts +80 -35
  134. package/src/ui/screens/model-manager.ts +82 -61
  135. package/src/ui/screens/output-window.ts +263 -0
  136. package/src/ui/screens/picker.ts +94 -81
  137. package/src/ui/screens/provider-manager.ts +100 -69
  138. package/src/ui/screens/wizard.ts +117 -28
  139. package/src/ui/tui/app.ts +196 -33
  140. package/src/ui/tui/transcript.ts +158 -25
  141. package/vendor/minicore/src/core/executor.ts +2 -0
  142. package/vendor/minicore/src/core/loop.ts +17 -6
  143. package/vendor/minicore/src/core/session.ts +3 -0
  144. package/vendor/minicore/src/core/tool.ts +1 -0
  145. package/vendor/minicore/src/providers/openai-compat.ts +35 -19
@@ -0,0 +1,157 @@
1
+ import {
2
+ chmodSync,
3
+ existsSync,
4
+ lstatSync,
5
+ mkdtempSync,
6
+ readdirSync,
7
+ rmSync,
8
+ writeFileSync,
9
+ } from "node:fs"
10
+ import { tmpdir } from "node:os"
11
+ import { join, relative, resolve } from "node:path"
12
+
13
+ /** Template env publik non-rahasia yang tetap diizinkan terbaca di sandbox (Opsi A). */
14
+ export const SAFE_ENV_TEMPLATES: ReadonlySet<string> = new Set([
15
+ ".env.example",
16
+ ".env.sample",
17
+ ".env.template",
18
+ ])
19
+
20
+ const SKIP_DIRS: ReadonlySet<string> = new Set([
21
+ ".git",
22
+ "node_modules",
23
+ ".minicode",
24
+ "dist",
25
+ "build",
26
+ ])
27
+ const MAX_SCAN_DIRS = 500
28
+ const MAX_SCAN_DEPTH = 3
29
+
30
+ /** Apakah nama file termasuk berkas `.env*` sensitif yang wajib dimasking. */
31
+ export function isSensitiveEnvFileName(name: string): boolean {
32
+ const lower = name.toLowerCase()
33
+ if (SAFE_ENV_TEMPLATES.has(lower)) return false
34
+ return lower === ".env" || lower.startsWith(".env.")
35
+ }
36
+
37
+ export interface SandboxMaskTargets {
38
+ readonly hasMinicode: boolean
39
+ /** Path relatif berformat POSIX terhadap workspace root (`".env"`, `"apps/a/.env.local"`). */
40
+ readonly envFiles: readonly string[]
41
+ }
42
+
43
+ /**
44
+ * Temukan `.minicode/` dan file `.env*` sensitif yang BENAR-BENAR ada di workspace.
45
+ * Hanya mengembalikan path yang sudah eksis agar bind-mount read-only tidak pernah
46
+ * menciptakan entri `.env` kosong di host.
47
+ */
48
+ export function discoverSandboxMaskTargets(cwd: string): SandboxMaskTargets {
49
+ const abs = resolve(cwd)
50
+ let hasMinicode = false
51
+ try {
52
+ hasMinicode = existsSync(join(abs, ".minicode"))
53
+ } catch {
54
+ hasMinicode = false
55
+ }
56
+ const envFiles: string[] = []
57
+ const queue: { dir: string; depth: number }[] = [{ dir: abs, depth: 0 }]
58
+ let visitedDirs = 0
59
+
60
+ while (queue.length > 0 && visitedDirs < MAX_SCAN_DIRS) {
61
+ const { dir, depth } = queue.shift()!
62
+ visitedDirs++
63
+ let entries: string[]
64
+ try {
65
+ entries = readdirSync(dir)
66
+ } catch {
67
+ continue
68
+ }
69
+ for (const name of entries) {
70
+ const full = join(dir, name)
71
+ let st: ReturnType<typeof lstatSync>
72
+ try {
73
+ st = lstatSync(full)
74
+ } catch {
75
+ continue
76
+ }
77
+ if (st.isDirectory()) {
78
+ if (depth < MAX_SCAN_DEPTH && !SKIP_DIRS.has(name)) {
79
+ queue.push({ dir: full, depth: depth + 1 })
80
+ }
81
+ continue
82
+ }
83
+ if ((st.isFile() || st.isSymbolicLink()) && isSensitiveEnvFileName(name)) {
84
+ const rel = relative(abs, full).replace(/\\/g, "/")
85
+ if (rel && !rel.startsWith("..")) envFiles.push(rel)
86
+ }
87
+ }
88
+ }
89
+ envFiles.sort()
90
+ return { hasMinicode, envFiles }
91
+ }
92
+
93
+ /**
94
+ * Buat satu berkas kosong read-only (0 byte) di tempdir host untuk memasking
95
+ * file `.env*` di dalam Docker/bwrap, lengkap dengan fungsi pembersihan idempoten.
96
+ */
97
+ export function allocateEmptyMaskFile(needed: boolean): {
98
+ path: string | null
99
+ cleanup: () => void
100
+ } {
101
+ if (!needed) return { path: null, cleanup: () => {} }
102
+ let tempDir: string | null = null
103
+ let cleaned = false
104
+ try {
105
+ tempDir = mkdtempSync(join(tmpdir(), "mc-sb-mask-"))
106
+ const maskFile = join(tempDir, "empty-mask")
107
+ writeFileSync(maskFile, "", { mode: 0o444 })
108
+ try {
109
+ chmodSync(maskFile, 0o444)
110
+ } catch {}
111
+ return {
112
+ path: maskFile,
113
+ cleanup: () => {
114
+ if (cleaned || !tempDir) return
115
+ cleaned = true
116
+ try {
117
+ rmSync(tempDir, { recursive: true, force: true })
118
+ } catch {}
119
+ },
120
+ }
121
+ } catch {
122
+ if (tempDir) {
123
+ try {
124
+ rmSync(tempDir, { recursive: true, force: true })
125
+ } catch {}
126
+ }
127
+ return { path: null, cleanup: () => {} }
128
+ }
129
+ }
130
+
131
+ /** Kolektor output proses (stdout+stderr) berbatas karakter untuk runner sandbox. */
132
+ export function createCappedOutputCollector(cap: number) {
133
+ let out = ""
134
+ let err = ""
135
+ let truncated = false
136
+ const append = (target: "out" | "err", d: Buffer | string): void => {
137
+ const s = typeof d === "string" ? d : d.toString()
138
+ const cur = target === "out" ? out : err
139
+ if (cur.length >= cap) {
140
+ truncated = true
141
+ return
142
+ }
143
+ const room = cap - cur.length
144
+ if (s.length > room) truncated = true
145
+ const piece = s.slice(0, Math.max(0, room))
146
+ if (target === "out") out += piece
147
+ else err += piece
148
+ }
149
+ const format = () => {
150
+ const marker = truncated ? "\n… [output truncated]" : ""
151
+ return {
152
+ marker,
153
+ output: (out + (err ? `\n[stderr]\n${err}` : "")).trim() + marker,
154
+ }
155
+ }
156
+ return { append, format }
157
+ }
package/src/sandbox/os.ts CHANGED
@@ -1,8 +1,13 @@
1
1
  import { spawn, spawnSync } from "node:child_process"
2
- import { resolve } from "node:path"
2
+ import { join, resolve } from "node:path"
3
3
  import { LIMITS } from "../constants.ts"
4
4
  import { resolveTrustedExecutable } from "../lib/trusted-exec.ts"
5
5
  import { sanitizeSpawnEnv } from "../policy/scrub.ts"
6
+ import {
7
+ allocateEmptyMaskFile,
8
+ createCappedOutputCollector,
9
+ discoverSandboxMaskTargets,
10
+ } from "./mask.ts"
6
11
 
7
12
  let osSandboxOk: boolean | null = null
8
13
  let osSandboxType: "seatbelt" | "bwrap" | "none" | null = null
@@ -65,8 +70,92 @@ export interface OsSandboxOptions {
65
70
  network?: "none" | "bridge"
66
71
  }
67
72
 
68
- // Seatbelt profile minimal (deny network, restrict writes outside cwd)
69
- // bwrap: bubblewrap with --ro-bind / --bind cwd, --unshare-net, --die-with-parent
73
+ function escapeSeatbelt(s: string): string {
74
+ return s.replace(/\\/g, "\\\\").replace(/"/g, '\\"')
75
+ }
76
+
77
+ /** Susun profil macOS Seatbelt dengan penolakan `.minicode/` dan berkas `.env*` sensitif. */
78
+ export function buildSeatbeltProfile(
79
+ absCwd: string,
80
+ envFiles: readonly string[] = [],
81
+ opts: { network?: "none" | "bridge" } = {},
82
+ ): string {
83
+ const escapedAbs = escapeSeatbelt(absCwd)
84
+ const deniedPaths = new Set<string>([
85
+ ...envFiles.map((rel) => join(absCwd, rel)),
86
+ ...([".env", ".env.local", ".env.production", ".env.development", ".env.test"] as const).map(
87
+ (f) => join(absCwd, f),
88
+ ),
89
+ ])
90
+ const envDenyRules = [...deniedPaths]
91
+ .sort()
92
+ .map((p) => `(deny file-read* file-write* (literal "${escapeSeatbelt(p)}"))`)
93
+ .join("\n")
94
+ const escapedMinicode = escapeSeatbelt(join(absCwd, ".minicode"))
95
+ return `(version 1)
96
+ (deny default)
97
+ (allow process-exec)
98
+ (allow file-read* file-write* (subpath "${escapedAbs}"))
99
+ (deny file-read* file-write* (subpath "${escapedMinicode}"))
100
+ ${envDenyRules}
101
+ (allow file-read* (subpath "/usr") (subpath "/bin") (subpath "/private/tmp"))
102
+ (allow sysctl-read)
103
+ ${opts.network === "bridge" ? "(allow network*)" : "(deny network*)"}
104
+ `
105
+ }
106
+
107
+ /** Susun argumen `bwrap` dengan isolasi namespace penuh dan masking `.minicode/` & `.env*`. */
108
+ export function buildBwrapArgs(
109
+ command: string,
110
+ absCwd: string,
111
+ opts: OsSandboxOptions,
112
+ mask: {
113
+ hasMinicode: boolean
114
+ envFiles: readonly string[]
115
+ emptyMaskPath: string | null
116
+ },
117
+ ): string[] {
118
+ const args = [
119
+ "--ro-bind",
120
+ "/usr",
121
+ "/usr",
122
+ "--ro-bind",
123
+ "/bin",
124
+ "/bin",
125
+ "--ro-bind",
126
+ "/lib",
127
+ "/lib",
128
+ "--ro-bind-try",
129
+ "/lib64",
130
+ "/lib64",
131
+ "--proc",
132
+ "/proc",
133
+ "--dev",
134
+ "/dev",
135
+ "--tmpfs",
136
+ "/tmp",
137
+ "--bind",
138
+ absCwd,
139
+ absCwd,
140
+ ]
141
+ if (mask.hasMinicode) {
142
+ args.push("--tmpfs", join(absCwd, ".minicode"))
143
+ }
144
+ if (mask.emptyMaskPath) {
145
+ for (const rel of mask.envFiles) {
146
+ args.push("--ro-bind", mask.emptyMaskPath, join(absCwd, rel))
147
+ }
148
+ }
149
+ args.push("--chdir", absCwd, "--unshare-pid", "--unshare-ipc", "--unshare-uts", "--new-session")
150
+ if (opts.network !== "bridge") {
151
+ args.push("--unshare-net")
152
+ }
153
+ args.push("--die-with-parent", "--cap-drop", "ALL", "sh", "-c", command)
154
+ return args
155
+ }
156
+
157
+ // Seatbelt profile minimal (deny network, restrict writes outside cwd + .env/.minicode)
158
+ // bwrap: bubblewrap with --ro-bind / --bind cwd, namespace unshare + masking
70
159
  export function runInOsSandbox(
71
160
  command: string,
72
161
  cwd: string,
@@ -87,61 +176,23 @@ export function runInOsSandbox(
87
176
  const abs = resolve(cwd)
88
177
  const sanitizedEnv = sanitizeSpawnEnv(process.env, opts.env) as Record<string, string>
89
178
  const timeout = opts.timeoutMs ?? LIMITS.DOCKER_TIMEOUT_MS
179
+ const targets = discoverSandboxMaskTargets(abs)
90
180
 
91
181
  if (type === "seatbelt") {
92
- // macOS seatbelt - simple deny network profile (escape \ dan " pada path)
93
- const escapedAbs = abs.replace(/\\/g, "\\\\").replace(/"/g, '\\"')
94
- const profile = `(version 1)
95
- (deny default)
96
- (allow process-exec)
97
- (allow file-read* file-write* (subpath "${escapedAbs}"))
98
- (allow file-read* (subpath "/usr") (subpath "/bin") (subpath "/private/tmp"))
99
- (allow sysctl-read)
100
- (deny network*)
101
- `
102
- // Use sandbox-exec with inline profile via stdin? sandbox-exec needs file, write tmp
182
+ const profile = buildSeatbeltProfile(abs, targets.envFiles, { network: opts.network })
103
183
  const args = ["-p", profile, "sh", "-c", command]
104
184
  return runSpawn("sandbox-exec", args, abs, sanitizedEnv, timeout, opts.signal)
105
185
  }
106
186
  if (type === "bwrap") {
107
- const args = [
108
- "--ro-bind",
109
- "/usr",
110
- "/usr",
111
- "--ro-bind",
112
- "/bin",
113
- "/bin",
114
- "--ro-bind",
115
- "/lib",
116
- "/lib",
117
- "--ro-bind-try",
118
- "/lib64",
119
- "/lib64",
120
- "--proc",
121
- "/proc",
122
- "--dev",
123
- "/dev",
124
- "--tmpfs",
125
- "/tmp",
126
- "--bind",
127
- abs,
128
- abs,
129
- "--chdir",
130
- abs,
131
- "--unshare-net",
132
- "--die-with-parent",
133
- "--cap-drop",
134
- "ALL",
135
- "sh",
136
- "-c",
137
- command,
138
- ]
139
- // best-effort: if network bridge requested, omit --unshare-net
140
- if (opts.network === "bridge") {
141
- const idx = args.indexOf("--unshare-net")
142
- if (idx !== -1) args.splice(idx, 1)
143
- }
144
- return runSpawn("bwrap", args, abs, sanitizedEnv, timeout, opts.signal)
187
+ const emptyMask = allocateEmptyMaskFile(targets.envFiles.length > 0)
188
+ const args = buildBwrapArgs(command, abs, opts, {
189
+ hasMinicode: targets.hasMinicode,
190
+ envFiles: targets.envFiles,
191
+ emptyMaskPath: emptyMask.path,
192
+ })
193
+ return runSpawn("bwrap", args, abs, sanitizedEnv, timeout, opts.signal).finally(() =>
194
+ emptyMask.cleanup(),
195
+ )
145
196
  }
146
197
  return Promise.resolve({ code: null, output: "[os-sandbox] unknown type" })
147
198
  }
@@ -170,25 +221,9 @@ function runSpawn(
170
221
  stdio: ["ignore", "pipe", "pipe"],
171
222
  detached: true,
172
223
  })
173
- const OUT_CAP = LIMITS.DOCKER_OUTPUT_MAX_CHARS
174
- let out = ""
175
- let err = ""
176
- let truncated = false
177
- const appendCapped = (target: "out" | "err", d: Buffer | string): void => {
178
- const s = typeof d === "string" ? d : d.toString()
179
- const cur = target === "out" ? out : err
180
- if (cur.length >= OUT_CAP) {
181
- truncated = true
182
- return
183
- }
184
- const room = OUT_CAP - cur.length
185
- if (s.length > room) truncated = true
186
- const piece = s.slice(0, Math.max(0, room))
187
- if (target === "out") out += piece
188
- else err += piece
189
- }
190
- p.stdout.on("data", (d) => appendCapped("out", d))
191
- p.stderr.on("data", (d) => appendCapped("err", d))
224
+ const collector = createCappedOutputCollector(LIMITS.DOCKER_OUTPUT_MAX_CHARS)
225
+ p.stdout.on("data", (d) => collector.append("out", d))
226
+ p.stderr.on("data", (d) => collector.append("err", d))
192
227
  let aborted = false
193
228
  let timedOut = false
194
229
  let settled = false
@@ -231,8 +266,7 @@ function runSpawn(
231
266
  reject(signal?.reason)
232
267
  return
233
268
  }
234
- const marker = truncated ? "\n… [output truncated]" : ""
235
- const output = (out + (err ? `\n[stderr]\n${err}` : "")).trim() + marker
269
+ const { marker, output } = collector.format()
236
270
  if (timedOut) {
237
271
  // Kontrak lapisan ini adalah RESOLVE (bukan reject): runner hanya
238
272
  // melaporkan hasil proses (code/output), dan pemanggil yang memutuskan
@@ -80,21 +80,40 @@ export function acquireSessionWriter(opts: {
80
80
  const now = opts.now ?? Date.now()
81
81
  const token = opts.token ?? writerTokenFor(bootId)
82
82
  const store = new TaskStore(cwd)
83
- const pre = store.getSessionAuthority(sessionId)
84
- if (pre && pre.ownerToken !== token && isLeaseActive(pre.leaseExpiresAt, now)) {
85
- return {
86
- ok: false,
87
- error: new SessionBusyError(sessionId, pre.ownerPid, pre.leaseExpiresAt),
83
+ // Baca status lease sebelumnya dan akuisisi secara atomik dalam transaksi IMMEDIATE
84
+ // agar `pre` selalu mencerminkan pemilik tepat sebelum pengambilalihan tanpa TOCTOU.
85
+ const leaseOutcome = store.withTransaction((tx) => {
86
+ const pre = tx.getSessionAuthority(sessionId)
87
+ if (pre && pre.ownerToken !== token && isLeaseActive(pre.leaseExpiresAt, now)) {
88
+ return {
89
+ ok: false as const,
90
+ holder: { pid: pre.ownerPid, expiresAt: pre.leaseExpiresAt },
91
+ }
88
92
  }
89
- }
90
- const acquired = store.acquireSessionAuthority(sessionId, token, SESSION_LEASE_MS, now)
91
- if (acquired === "REFUSED_LEASE_HELD") {
92
- const holder = holderSummary(sessionId, cwd, now)
93
+ const acquired = tx.acquireSessionAuthority(sessionId, token, SESSION_LEASE_MS, now)
94
+ if (acquired === "REFUSED_LEASE_HELD") {
95
+ const cur = tx.getSessionAuthority(sessionId)
96
+ return {
97
+ ok: false as const,
98
+ holder: {
99
+ pid: cur?.ownerPid ?? null,
100
+ expiresAt: cur?.leaseExpiresAt ?? null,
101
+ },
102
+ }
103
+ }
104
+ return { ok: true as const, pre }
105
+ }, true)
106
+ if (!leaseOutcome.ok) {
93
107
  return {
94
108
  ok: false,
95
- error: new SessionBusyError(sessionId, holder.pid, holder.expiresAt),
109
+ error: new SessionBusyError(
110
+ sessionId,
111
+ leaseOutcome.holder.pid,
112
+ leaseOutcome.holder.expiresAt,
113
+ ),
96
114
  }
97
115
  }
116
+ const { pre } = leaseOutcome
98
117
  // Kita pemegang lease. Takeover (bump epoch) HANYA bila baris lease
99
118
  // sebelumnya milik token LAIN (aktif/expired) — akuisisi fresh atau
100
119
  // re-acquire token sendiri tak menyentuh epoch (§16).
@@ -97,13 +97,10 @@ export function deriveSummaryFromCanonical(
97
97
  // dilihat model saat kompaksi. baseSeq=1: ringkasan mewakili baris indeks 0,
98
98
  // ekor [1, N) verbatim.
99
99
  const first = messages[0] as { role?: unknown; content?: unknown } | undefined
100
- if (
100
+ const isKernelSummary =
101
101
  first?.role === "user" &&
102
102
  typeof first.content === "string" &&
103
- first.content.startsWith("Previous context")
104
- ) {
105
- return { summaryText: first.content, baseSeq: 1 }
106
- }
103
+ first.content.startsWith("Previous context (")
107
104
  const keep =
108
105
  Number.isInteger(policy.keepRecentTurns) && policy.keepRecentTurns >= 1
109
106
  ? policy.keepRecentTurns
@@ -111,6 +108,10 @@ export function deriveSummaryFromCanonical(
111
108
  const store = new ContextStore()
112
109
  store.appendAll(messages)
113
110
  const folded = mechanicalKeepResults(store, keep)
111
+ // Reuse ringkasan kernel apa adanya HANYA bila belum ada turn baru di luar `keepRecentTurns`.
112
+ if (isKernelSummary && folded.length >= messages.length) {
113
+ return { summaryText: first.content as string, baseSeq: 1 }
114
+ }
114
115
  // Tak ada fold (prefix kosong) → tak ada cakupan untuk proyeksi.
115
116
  if (folded.length >= messages.length) return null
116
117
  const kept = folded.length - 1