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
@@ -0,0 +1,559 @@
1
+ // [Fase 3 / LOOP-12, LOOP-G19, LOOP-G27] Detektor deterministik No-Progress &
2
+ // Oscillation.
3
+ //
4
+ // Menutup tiga modus macet otonom tanpa menyentuh kernel frozen:
5
+ // 1. Exact Action-Error Fingerprint (`REPEATED_ACTION_ERROR`): pemanggilan
6
+ // tool dengan nama + argumen kanonis + headline error yang identik N kali
7
+ // berturut-turut diblokir pada percobaan ke-(N+1).
8
+ // 2. Workspace State Oscillation (`WORKSPACE_REVERT_CYCLE`): file mengalami
9
+ // siklus bolak-balik kembali ke hash lama sebanyak M siklus (mis.
10
+ // H1 -> H2 -> H1 -> H2 -> H1 untuk M=2) tanpa verifikasi lulus di antaranya.
11
+ // 3. Read-Only Thrashing (`READ_ONLY_THRASHING`): pemanggilan tool murni-baca
12
+ // (`sideEffectTier === "PURE_READ"`) berturut-turut melampaui ambang batas
13
+ // saat sesi berada pada postur kerja aktif (bukan readonly/explore/plan)
14
+ // tanpa pembaruan rencana (`todo_write`), mutasi, atau jawaban ke user.
15
+ //
16
+ // Modul ini berada di `src/policy/` dan hanya mengimpor `./tool-contract.ts` +
17
+ // pustaka standar Node agar batas lapisan tetap bersih.
18
+
19
+ import { createHash } from "node:crypto"
20
+ import { readFile, stat } from "node:fs/promises"
21
+ import { isAbsolute, relative, resolve } from "node:path"
22
+ import { contractForTool } from "./tool-contract.ts"
23
+
24
+ export type NoProgressPosture = "active" | "readonly" | "explore" | "plan"
25
+
26
+ export type LoopGuardKind = "NO_PROGRESS" | "OSCILLATION"
27
+
28
+ export type LoopGuardReason =
29
+ | "REPEATED_ACTION_ERROR"
30
+ | "WORKSPACE_REVERT_CYCLE"
31
+ | "READ_ONLY_THRASHING"
32
+
33
+ export type NoProgressVerdict =
34
+ | { readonly allowed: true }
35
+ | {
36
+ readonly allowed: false
37
+ readonly kind: LoopGuardKind
38
+ readonly reason: LoopGuardReason
39
+ readonly message: string
40
+ }
41
+
42
+ export class NoProgressError extends Error {
43
+ readonly name = "NoProgressError"
44
+ readonly kind: LoopGuardKind
45
+ readonly reason: LoopGuardReason
46
+
47
+ constructor(kind: LoopGuardKind, reason: LoopGuardReason, message: string) {
48
+ super(message)
49
+ this.kind = kind
50
+ this.reason = reason
51
+ }
52
+ }
53
+
54
+ export interface NoProgressOptions {
55
+ /** Maksimum kegagalan identik berturut-turut sebelum panggilan berikutnya diblokir (default 3). */
56
+ readonly maxRepeatedErrors?: number
57
+ /** Maksimum siklus kembali ke hash file lama tanpa verifikasi hijau (default 2). */
58
+ readonly maxOscillations?: number
59
+ /** Maksimum panggilan PURE_READ berturut-turut di postur aktif (default 15). */
60
+ readonly maxConsecutiveReadCalls?: number
61
+ /** Postur sesi saat ini; non-"active" menonaktifkan detektor read-only thrashing. */
62
+ readonly getPosture?: () => NoProgressPosture
63
+ /**
64
+ * [Fase 6A / ACE-04] Maksimum retry terjustifikasi setelah bukti baru
65
+ * (default 1). Hard cap absolut: tidak pernah menambah budget tanpa batas.
66
+ */
67
+ readonly maxNewEvidenceRetries?: number
68
+ }
69
+
70
+ function canonicalize(value: unknown): string {
71
+ if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null"
72
+ if (Array.isArray(value)) return `[${value.map(canonicalize).join(",")}]`
73
+ const keys = Object.keys(value as Record<string, unknown>).sort()
74
+ return `{${keys
75
+ .map((k) => `${JSON.stringify(k)}:${canonicalize((value as Record<string, unknown>)[k])}`)
76
+ .join(",")}}`
77
+ }
78
+
79
+ /** Hash argumen kanonis (identik dengan `hashArgs` pada `src/session/journal.ts`). */
80
+ export function canonicalArgsHash(args: unknown): string {
81
+ return createHash("sha256")
82
+ .update(canonicalize(args ?? {}))
83
+ .digest("hex")
84
+ }
85
+
86
+ /**
87
+ * Ambil headline error yang stabil (baris pertama bermakna, menormalkan angka
88
+ * durasi volatil agar timeout/error yang sama menghasilkan sidik jari sama).
89
+ */
90
+ export function normalizeErrorHeadline(errorText: string): string {
91
+ const firstLine =
92
+ String(errorText ?? "")
93
+ .split(/\r?\n/)
94
+ .map((line) => line.trim())
95
+ .find((line) => line.length > 0) ?? "error"
96
+ return firstLine
97
+ .replace(/\bduration_ms=\d+/g, "duration_ms=#")
98
+ .replace(/\s+/g, " ")
99
+ .slice(0, 240)
100
+ }
101
+
102
+ export function computeActionErrorFingerprint(
103
+ toolName: string,
104
+ args: unknown,
105
+ errorText: string,
106
+ ): string {
107
+ const payload = `${toolName}\0${canonicalArgsHash(args)}\0${normalizeErrorHeadline(errorText)}`
108
+ return createHash("sha256").update(payload, "utf8").digest("hex")
109
+ }
110
+
111
+ const HASH_MAX_BYTES = 8 * 1024 * 1024
112
+
113
+ async function hashWorkspaceFile(
114
+ absPath: string,
115
+ ): Promise<{ ok: true; hash: string | null } | { ok: false }> {
116
+ try {
117
+ const st = await stat(absPath)
118
+ if (!st.isFile() || st.size > HASH_MAX_BYTES) return { ok: false }
119
+ const bytes = await readFile(absPath)
120
+ return { ok: true, hash: createHash("sha256").update(bytes).digest("hex") }
121
+ } catch (err) {
122
+ if ((err as NodeJS.ErrnoException)?.code === "ENOENT") return { ok: true, hash: null }
123
+ return { ok: false }
124
+ }
125
+ }
126
+
127
+ function targetRelPathForTool(
128
+ toolName: string,
129
+ args: unknown,
130
+ workspaceRoot: string,
131
+ ): string | null {
132
+ const a = (args ?? {}) as Record<string, unknown>
133
+ const raw =
134
+ toolName === "write_file" ||
135
+ toolName === "edit" ||
136
+ toolName === "apply_patch" ||
137
+ toolName === "delete_file"
138
+ ? a.path
139
+ : toolName === "move_file"
140
+ ? a.to
141
+ : undefined
142
+ if (typeof raw !== "string" || !raw.trim()) return null
143
+ const root = resolve(workspaceRoot)
144
+ const rel = relative(root, resolve(root, raw)).replace(/\\/g, "/")
145
+ if (!rel || rel.startsWith("..") || isAbsolute(rel)) return null
146
+ return rel
147
+ }
148
+
149
+ function normalizeTrackPath(rawPath: string): string {
150
+ return rawPath.trim().replace(/\\/g, "/").replace(/^\.\//, "")
151
+ }
152
+
153
+ interface FileHashTracker {
154
+ history: (string | null)[]
155
+ visits: Map<string, number>
156
+ oscillationMessage: string | null
157
+ }
158
+
159
+ const HASH_NULL_SENTINEL = "__ABSENT__"
160
+
161
+ function hashKey(h: string | null): string {
162
+ return h === null ? HASH_NULL_SENTINEL : h
163
+ }
164
+
165
+ export interface NoProgressDetector {
166
+ evaluateBeforeCall(call: { id?: string; name: string; args?: unknown }): NoProgressVerdict
167
+ assertBeforeCall(call: { id?: string; name: string; args?: unknown }): void
168
+ capturePreMutation(
169
+ call: { id: string; name: string; args?: unknown },
170
+ workspaceRoot: string,
171
+ ): Promise<void>
172
+ /**
173
+ * [Fase 3] Titik masuk barrier async tunggal: tunggu seluruh pencatatan
174
+ * post-mutation step sebelumnya selesai dulu (menutup race async antar-step),
175
+ * evaluasi guard, lalu rekam hash pra-mutasi.
176
+ */
177
+ beforeToolEffectCheck(
178
+ call: { id: string; name: string; args?: unknown },
179
+ workspaceRoot: string,
180
+ ): Promise<void>
181
+ flushPending(): Promise<void>
182
+ recordOutcome(input: {
183
+ id?: string
184
+ name: string
185
+ args?: unknown
186
+ isError?: boolean
187
+ content?: string
188
+ }): NoProgressVerdict
189
+ recordFileMutation(input: {
190
+ path: string
191
+ preTargetHash: string | null
192
+ postTargetHash: string | null
193
+ }): NoProgressVerdict
194
+ completePostMutation(
195
+ call: { id: string; name: string; args?: unknown; isError?: boolean },
196
+ workspaceRoot: string,
197
+ ): Promise<NoProgressVerdict>
198
+ noteVerificationPassed(): void
199
+ noteAssistantResponse(): void
200
+ reset(): void
201
+ snapshot(): {
202
+ readonly repeatedErrorStreak: number
203
+ readonly consecutiveReadCalls: number
204
+ readonly oscillatingPaths: readonly string[]
205
+ /** [Fase 6A / ACE-04] Ada bukti baru sejak blokir REPEATED_ACTION_ERROR. */
206
+ readonly newEvidenceSinceFailure: boolean
207
+ /** [Fase 6A / ACE-04] Retry terjustifikasi yang sudah dipakai untuk blokir aktif. */
208
+ readonly justifiedRetriesUsed: number
209
+ }
210
+ }
211
+
212
+ export function createNoProgressDetector(options: NoProgressOptions = {}): NoProgressDetector {
213
+ const maxRepeatedErrors =
214
+ typeof options.maxRepeatedErrors === "number" &&
215
+ Number.isFinite(options.maxRepeatedErrors) &&
216
+ options.maxRepeatedErrors >= 1
217
+ ? Math.floor(options.maxRepeatedErrors)
218
+ : 3
219
+ const maxOscillations =
220
+ typeof options.maxOscillations === "number" &&
221
+ Number.isFinite(options.maxOscillations) &&
222
+ options.maxOscillations >= 1
223
+ ? Math.floor(options.maxOscillations)
224
+ : 2
225
+ const maxConsecutiveReadCalls =
226
+ typeof options.maxConsecutiveReadCalls === "number" &&
227
+ Number.isFinite(options.maxConsecutiveReadCalls) &&
228
+ options.maxConsecutiveReadCalls >= 1
229
+ ? Math.floor(options.maxConsecutiveReadCalls)
230
+ : 15
231
+ const getPosture = options.getPosture ?? (() => "active" as const)
232
+ const maxNewEvidenceRetries =
233
+ typeof options.maxNewEvidenceRetries === "number" &&
234
+ Number.isFinite(options.maxNewEvidenceRetries) &&
235
+ options.maxNewEvidenceRetries >= 0
236
+ ? Math.floor(options.maxNewEvidenceRetries)
237
+ : 1
238
+
239
+ let lastErrorFingerprint: string | null = null
240
+ let lastErrorActionKey: string | null = null
241
+ let repeatedErrorStreak = 0
242
+
243
+ // [Fase 6A / ACE-04] Blokir REPEATED_ACTION_ERROR bersifat PERSISTEN sampai
244
+ // ada bukti baru — sukses yang tidak relevan tidak boleh membuka jalan
245
+ // mengulang perintah yang sama secara buta.
246
+ let activeBlock: { fingerprint: string; actionKey: string; streak: number } | null = null
247
+ let newEvidenceAfterBlock = false
248
+ let justifiedRetries = 0
249
+
250
+ let consecutiveReadCalls = 0
251
+
252
+ const fileTrackers = new Map<string, FileHashTracker>()
253
+ const inflightPreHash = new Map<string, { relPath: string; preHash: string | null }>()
254
+ const pendingPost = new Set<Promise<unknown>>()
255
+
256
+ const evaluateBeforeCall: NoProgressDetector["evaluateBeforeCall"] = (call) => {
257
+ const name = String(call.name ?? "")
258
+ const actionKey = `${name}\0${canonicalArgsHash(call.args)}`
259
+
260
+ // Sinyal 1a: blokir persisten. Hanya boleh dibuka oleh SATU retry
261
+ // terjustifikasi setelah bukti diagnostik/mutasi baru, dengan hard cap.
262
+ if (activeBlock !== null && actionKey === activeBlock.actionKey) {
263
+ if (newEvidenceAfterBlock && justifiedRetries < maxNewEvidenceRetries) {
264
+ justifiedRetries += 1
265
+ newEvidenceAfterBlock = false
266
+ return { allowed: true }
267
+ }
268
+ return {
269
+ allowed: false,
270
+ kind: "NO_PROGRESS",
271
+ reason: "REPEATED_ACTION_ERROR",
272
+ message:
273
+ `[LOOP_GUARD kind=NO_PROGRESS reason=REPEATED_ACTION_ERROR count=${activeBlock.streak}] ` +
274
+ `Identical tool call failed ${activeBlock.streak} times consecutively with the same error. ` +
275
+ `Read fresh diagnostic evidence or change your approach before retrying.`,
276
+ }
277
+ }
278
+
279
+ // Sinyal 1b: panggilan identik yang sudah gagal N kali berturut-turut.
280
+ if (
281
+ repeatedErrorStreak >= maxRepeatedErrors &&
282
+ lastErrorActionKey !== null &&
283
+ actionKey === lastErrorActionKey
284
+ ) {
285
+ return {
286
+ allowed: false,
287
+ kind: "NO_PROGRESS",
288
+ reason: "REPEATED_ACTION_ERROR",
289
+ message:
290
+ `[LOOP_GUARD kind=NO_PROGRESS reason=REPEATED_ACTION_ERROR count=${repeatedErrorStreak}] ` +
291
+ `Identical tool call failed ${repeatedErrorStreak} times consecutively with the same error. ` +
292
+ `Stop repeating this command and revise your approach.`,
293
+ }
294
+ }
295
+
296
+ // Sinyal 2: file target sudah terdeteksi dalam siklus revert berulang.
297
+ const contract = contractForTool(name)
298
+ if (contract?.sideEffectTier === "WORKSPACE_MUTATION") {
299
+ const a = (call.args ?? {}) as Record<string, unknown>
300
+ const rawPath =
301
+ typeof a.path === "string" ? a.path : typeof a.to === "string" ? a.to : undefined
302
+ if (rawPath) {
303
+ const key = normalizeTrackPath(rawPath)
304
+ const tracker = fileTrackers.get(key)
305
+ if (tracker?.oscillationMessage) {
306
+ return {
307
+ allowed: false,
308
+ kind: "OSCILLATION",
309
+ reason: "WORKSPACE_REVERT_CYCLE",
310
+ message: tracker.oscillationMessage,
311
+ }
312
+ }
313
+ }
314
+ }
315
+
316
+ // Sinyal 3: read-only thrashing di postur kerja aktif.
317
+ const isPureRead = contract?.sideEffectTier === "PURE_READ"
318
+ if (isPureRead) {
319
+ if (getPosture() === "active") {
320
+ if (consecutiveReadCalls >= maxConsecutiveReadCalls) {
321
+ const observedCount = consecutiveReadCalls
322
+ // Reset setelah satu intervensi supaya model menerima peringatan keras
323
+ // sebagai tool error dan dapat langsung memanggil todo_write / bertindak.
324
+ consecutiveReadCalls = 0
325
+ return {
326
+ allowed: false,
327
+ kind: "NO_PROGRESS",
328
+ reason: "READ_ONLY_THRASHING",
329
+ message:
330
+ `[LOOP_GUARD kind=NO_PROGRESS reason=READ_ONLY_THRASHING count=${observedCount}] ` +
331
+ `Exceeded ${maxConsecutiveReadCalls} consecutive read-only tool calls without updating the plan, ` +
332
+ `mutating workspace state, or responding to the user. Formulate a plan (todo_write) or act on what you have read.`,
333
+ }
334
+ }
335
+ consecutiveReadCalls += 1
336
+ }
337
+ } else {
338
+ // Pembaruan rencana (`todo_write`), mutasi file/env, delegasi, atau ask_user
339
+ // memutus rentetan baca murni.
340
+ consecutiveReadCalls = 0
341
+ }
342
+
343
+ return { allowed: true }
344
+ }
345
+
346
+ const recordFileMutation: NoProgressDetector["recordFileMutation"] = (input) => {
347
+ const key = normalizeTrackPath(input.path)
348
+ if (!key) return { allowed: true }
349
+ // No-op write (isi tidak berubah) tidak dihitung sebagai transisi bolak-balik.
350
+ if (input.preTargetHash === input.postTargetHash) return { allowed: true }
351
+
352
+ let tracker = fileTrackers.get(key)
353
+ if (!tracker) {
354
+ const visits = new Map<string, number>()
355
+ const preK = hashKey(input.preTargetHash)
356
+ visits.set(preK, 1)
357
+ tracker = {
358
+ history: [input.preTargetHash],
359
+ visits,
360
+ oscillationMessage: null,
361
+ }
362
+ fileTrackers.set(key, tracker)
363
+ } else if (tracker.history[tracker.history.length - 1] !== input.preTargetHash) {
364
+ // Sinkronkan state awal bila file diubah dari luar di sela dua operasi.
365
+ const preK = hashKey(input.preTargetHash)
366
+ tracker.history.push(input.preTargetHash)
367
+ tracker.visits.set(preK, (tracker.visits.get(preK) ?? 0) + 1)
368
+ }
369
+
370
+ const postK = hashKey(input.postTargetHash)
371
+ tracker.history.push(input.postTargetHash)
372
+ const count = (tracker.visits.get(postK) ?? 0) + 1
373
+ tracker.visits.set(postK, count)
374
+
375
+ // `count - 1` = berapa kali file kembali ke hash yang sama setelah pernah
376
+ // meninggalkannya (H1 -> H2 -> H1 = 1 siklus; -> H2 -> H1 = 2 siklus).
377
+ const revertCycles = count - 1
378
+ if (revertCycles >= maxOscillations) {
379
+ const msg =
380
+ `[LOOP_GUARD kind=OSCILLATION reason=WORKSPACE_REVERT_CYCLE path=${key}] ` +
381
+ `File state is oscillating between identical versions without progress.`
382
+ tracker.oscillationMessage = msg
383
+ return {
384
+ allowed: false,
385
+ kind: "OSCILLATION",
386
+ reason: "WORKSPACE_REVERT_CYCLE",
387
+ message: msg,
388
+ }
389
+ }
390
+ return { allowed: true }
391
+ }
392
+
393
+ const flushPending = async (): Promise<void> => {
394
+ while (pendingPost.size > 0) {
395
+ await Promise.allSettled([...pendingPost])
396
+ }
397
+ }
398
+
399
+ return {
400
+ evaluateBeforeCall,
401
+ assertBeforeCall(call) {
402
+ const verdict = evaluateBeforeCall(call)
403
+ if (!verdict.allowed) {
404
+ throw new NoProgressError(verdict.kind, verdict.reason, verdict.message)
405
+ }
406
+ },
407
+ async capturePreMutation(call, workspaceRoot) {
408
+ const contract = contractForTool(call.name)
409
+ if (contract?.sideEffectTier !== "WORKSPACE_MUTATION" || !call.id) return
410
+ const rel = targetRelPathForTool(call.name, call.args, workspaceRoot)
411
+ if (!rel) return
412
+ const pre = await hashWorkspaceFile(resolve(workspaceRoot, rel))
413
+ if (pre.ok) {
414
+ inflightPreHash.set(call.id, { relPath: rel, preHash: pre.hash })
415
+ }
416
+ },
417
+ async beforeToolEffectCheck(call, workspaceRoot) {
418
+ await flushPending()
419
+ const verdict = evaluateBeforeCall(call)
420
+ if (!verdict.allowed) {
421
+ throw new NoProgressError(verdict.kind, verdict.reason, verdict.message)
422
+ }
423
+ const contract = contractForTool(call.name)
424
+ if (contract?.sideEffectTier !== "WORKSPACE_MUTATION" || !call.id) return
425
+ const rel = targetRelPathForTool(call.name, call.args, workspaceRoot)
426
+ if (!rel) return
427
+ const pre = await hashWorkspaceFile(resolve(workspaceRoot, rel))
428
+ if (pre.ok) {
429
+ inflightPreHash.set(call.id, { relPath: rel, preHash: pre.hash })
430
+ }
431
+ },
432
+ flushPending,
433
+ recordOutcome(input) {
434
+ const name = String(input.name ?? "")
435
+ const content = String(input.content ?? "")
436
+ // [LF-2] Jangan hitung error yang berasal dari LOOP_GUARD sendiri sebagai
437
+ // kegagalan tool. Hanya cocokkan pesan SINTETIS yang ber-prefix eksak di
438
+ // AWAL string (`[LOOP_GUARD kind=...]` — format nyata observable di modul
439
+ // ini), bukan substring di tengah output tool eksternal.
440
+ if (/^\[LOOP_GUARD kind=(?:NO_PROGRESS|OSCILLATION)\b/.test(content.trimStart())) {
441
+ return { allowed: true }
442
+ }
443
+ if (input.isError === true) {
444
+ const fp = computeActionErrorFingerprint(name, input.args, content)
445
+ const actionKey = `${name}\0${canonicalArgsHash(input.args)}`
446
+ if (fp === lastErrorFingerprint && actionKey === lastErrorActionKey) {
447
+ repeatedErrorStreak += 1
448
+ } else {
449
+ lastErrorFingerprint = fp
450
+ lastErrorActionKey = actionKey
451
+ repeatedErrorStreak = 1
452
+ }
453
+ if (repeatedErrorStreak >= maxRepeatedErrors) {
454
+ if (activeBlock === null || activeBlock.actionKey !== actionKey) {
455
+ // Blokir baru: buka budget retry dari nol.
456
+ activeBlock = { fingerprint: fp, actionKey, streak: repeatedErrorStreak }
457
+ justifiedRetries = 0
458
+ } else {
459
+ // Retry terjustifikasi gagal lagi: pertahankan budget yang sudah
460
+ // terpakai (hard cap) dan cabut bukti yang sudah dikonsumsi.
461
+ activeBlock = { ...activeBlock, streak: repeatedErrorStreak }
462
+ }
463
+ newEvidenceAfterBlock = false
464
+ return {
465
+ allowed: false,
466
+ kind: "NO_PROGRESS",
467
+ reason: "REPEATED_ACTION_ERROR",
468
+ message:
469
+ `[LOOP_GUARD kind=NO_PROGRESS reason=REPEATED_ACTION_ERROR count=${repeatedErrorStreak}] ` +
470
+ `Identical tool call failed ${repeatedErrorStreak} times consecutively with the same error. ` +
471
+ `Stop repeating this command and revise your approach.`,
472
+ }
473
+ }
474
+ return { allowed: true }
475
+ }
476
+ // Eksekusi sukses memutus streak error berulang. [Fase 6A / ACE-04]
477
+ // Sukses baca diagnostik atau mutasi workspace = bukti baru yang
478
+ // membenarkan SATU retry; sukses lain tidak membuka blokir.
479
+ if (activeBlock !== null) {
480
+ const tier = contractForTool(name)?.sideEffectTier
481
+ if (tier === "PURE_READ" || tier === "WORKSPACE_MUTATION") {
482
+ newEvidenceAfterBlock = true
483
+ }
484
+ }
485
+ lastErrorFingerprint = null
486
+ lastErrorActionKey = null
487
+ repeatedErrorStreak = 0
488
+ return { allowed: true }
489
+ },
490
+ recordFileMutation,
491
+ async completePostMutation(call, workspaceRoot) {
492
+ const task = (async (): Promise<NoProgressVerdict> => {
493
+ const entry = call.id ? inflightPreHash.get(call.id) : undefined
494
+ if (call.id) inflightPreHash.delete(call.id)
495
+ if (!entry || call.isError === true) return { allowed: true }
496
+ const post = await hashWorkspaceFile(resolve(workspaceRoot, entry.relPath))
497
+ if (!post.ok) return { allowed: true }
498
+ return recordFileMutation({
499
+ path: entry.relPath,
500
+ preTargetHash: entry.preHash,
501
+ postTargetHash: post.hash,
502
+ })
503
+ })()
504
+ pendingPost.add(task)
505
+ try {
506
+ return await task
507
+ } finally {
508
+ pendingPost.delete(task)
509
+ }
510
+ },
511
+ noteVerificationPassed() {
512
+ // Verifikasi hijau menandai titik tumpu baru: bersihkan riwayat osilasi
513
+ // masa lalu namun pertahankan hash terakhir sebagai baseline baru.
514
+ for (const [, tracker] of fileTrackers) {
515
+ const latest = tracker.history[tracker.history.length - 1] ?? null
516
+ const visits = new Map<string, number>()
517
+ visits.set(hashKey(latest), 1)
518
+ tracker.history = [latest]
519
+ tracker.visits = visits
520
+ tracker.oscillationMessage = null
521
+ }
522
+ // [Fase 6A / ACE-04] Verifikasi hijau adalah kemajuan nyata: blokir
523
+ // repeated-error tidak lagi relevan.
524
+ activeBlock = null
525
+ newEvidenceAfterBlock = false
526
+ justifiedRetries = 0
527
+ lastErrorFingerprint = null
528
+ lastErrorActionKey = null
529
+ repeatedErrorStreak = 0
530
+ },
531
+ noteAssistantResponse() {
532
+ consecutiveReadCalls = 0
533
+ },
534
+ reset() {
535
+ lastErrorFingerprint = null
536
+ lastErrorActionKey = null
537
+ repeatedErrorStreak = 0
538
+ consecutiveReadCalls = 0
539
+ activeBlock = null
540
+ newEvidenceAfterBlock = false
541
+ justifiedRetries = 0
542
+ fileTrackers.clear()
543
+ inflightPreHash.clear()
544
+ },
545
+ snapshot() {
546
+ const oscillatingPaths: string[] = []
547
+ for (const [p, t] of fileTrackers) {
548
+ if (t.oscillationMessage) oscillatingPaths.push(p)
549
+ }
550
+ return {
551
+ repeatedErrorStreak,
552
+ consecutiveReadCalls,
553
+ oscillatingPaths,
554
+ newEvidenceSinceFailure: newEvidenceAfterBlock,
555
+ justifiedRetriesUsed: justifiedRetries,
556
+ }
557
+ },
558
+ }
559
+ }
@@ -26,6 +26,8 @@ export type PermissionMode = "auto" | "readonly" | "plan" | "allow-all" | "ask"
26
26
  export type PermissionAsk = (call: {
27
27
  name: string
28
28
  args?: unknown
29
+ /** [Fase 2 / LOOP-INV-08] Identitas pemanggilan untuk pengikatan approval. */
30
+ id?: string
29
31
  }) => Promise<"allow" | "deny" | "always">
30
32
 
31
33
  const READONLY_TOOLS = new Set([
@@ -82,14 +84,8 @@ const NO_PROMPT_TOOLS = new Set(["todo_write", "submit_result", "bash_output", "
82
84
  // `ask_user` di-gate: model yang bisa bertanya tanpa batas bisa membanjiri
83
85
  // user (atau memancing jawaban kredensial) — persetujuan sekali per sesi
84
86
  // via `[a] Always` tetap tersedia.
85
- const GATED_TOOLS = new Set([
86
- "delegate_task",
87
- "mcp_call",
88
- "mcp_read",
89
- "mcp_prompt",
90
- "git_commit",
91
- "ask_user",
92
- ])
87
+ // [Fase 2 / TOOL-01] Diimpor dari registry kontrak tool (satu sumber).
88
+ import { GATED_TOOLS } from "./tool-contract.ts"
93
89
 
94
90
  // Denylist bash kini di src/policy/bash-guard.ts — pemeriksaan dilakukan pada
95
91
  // bentuk TERNORMALISASI (quote dibuang, variabel sederhana disubstitusi), bukan
@@ -239,7 +239,7 @@ export async function syncPricing(url: string = MODELS_DEV_URL): Promise<SyncRes
239
239
  const hostname = new URL(url).hostname
240
240
  if (await isPrivateHostWithDns(hostname)) throw new Error(`private host rejected: ${hostname}`)
241
241
  } catch (e) {
242
- if ((e as Error).message.includes("private host")) throw e
242
+ if (e instanceof Error && e.message.includes("private host")) throw e
243
243
  }
244
244
  const res = await fetch(url, {
245
245
  signal: AbortSignal.timeout(LIMITS.PRICING_FETCH_TIMEOUT_MS * 4),
@@ -254,7 +254,7 @@ export async function syncPricing(url: string = MODELS_DEV_URL): Promise<SyncRes
254
254
  if (await isPrivateHostWithDns(nextHost))
255
255
  throw new Error(`private host rejected: ${nextHost}`)
256
256
  } catch (e) {
257
- if ((e as Error).message.includes("private host")) throw e
257
+ if (e instanceof Error && e.message.includes("private host")) throw e
258
258
  }
259
259
  }
260
260
  throw new Error(`models.dev → redirect ${res.status} not followed`)
@@ -296,6 +296,20 @@ export async function syncPricing(url: string = MODELS_DEV_URL): Promise<SyncRes
296
296
  * Overlay (models.dev) diperiksa lebih dulu karena lebih baru; bawaan menjadi
297
297
  * jaring pengaman.
298
298
  */
299
+ // [Audit #2 C.F4] Cache urutan kunci per-tabel (terpanjang dulu). `Object.keys`
300
+ // + sort semula dijalankan setiap `findPrice` (per event token). BUILTIN_PRICING
301
+ // adalah const (cache stabil); overlay di-REASSIGN (bukan di-mutasi), jadi
302
+ // WeakMap otomatis miss saat overlay diganti objek baru.
303
+ const priceKeyOrderCache = new WeakMap<Record<string, ModelPrice>, string[]>()
304
+ function priceKeysDescLength(table: Record<string, ModelPrice>): string[] {
305
+ let keys = priceKeyOrderCache.get(table)
306
+ if (!keys) {
307
+ keys = Object.keys(table).sort((a, b) => b.length - a.length)
308
+ priceKeyOrderCache.set(table, keys)
309
+ }
310
+ return keys
311
+ }
312
+
299
313
  export function findPrice(
300
314
  model: string,
301
315
  overlayMap: Record<string, ModelPrice> = overlay ?? {},
@@ -320,7 +334,7 @@ export function findPrice(
320
334
  const segments = m.split(/[/:]/)
321
335
 
322
336
  for (const table of [overlayMap, BUILTIN_PRICING]) {
323
- const keys = Object.keys(table).sort((a, b) => b.length - a.length)
337
+ const keys = priceKeysDescLength(table)
324
338
  for (const k of keys) {
325
339
  const kl = k.toLowerCase()
326
340
  for (const s of segments) {