@omacode/micromanager 0.0.0-stage → 0.1.1

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 (109) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +27 -2
  3. package/evolver/mm_evolve/__init__.py +1 -0
  4. package/evolver/mm_evolve/entry.py +3 -0
  5. package/evolver/mm_evolve/evaluator.py +119 -0
  6. package/evolver/mm_evolve/llm.py +76 -0
  7. package/evolver/mm_evolve/run.py +89 -0
  8. package/evolver/mm_evolve/spec.py +62 -0
  9. package/evolver/pyproject.toml +21 -0
  10. package/evolver/uv.lock +772 -0
  11. package/package.json +55 -4
  12. package/skills/THIRD_PARTY.md +58 -0
  13. package/skills/code-review/SKILL.md +46 -0
  14. package/skills/deliberate/SKILL.md +39 -0
  15. package/skills/diagnosing-bugs/SKILL.md +75 -0
  16. package/skills/receiving-code-review/SKILL.md +36 -0
  17. package/skills/research/SKILL.md +18 -0
  18. package/skills/tdd/SKILL.md +56 -0
  19. package/skills/tdd/mocking.md +59 -0
  20. package/skills/tdd/tests.md +77 -0
  21. package/skills/verification-before-completion/SKILL.md +50 -0
  22. package/src/agenda.ts +56 -0
  23. package/src/agents.ts +74 -0
  24. package/src/ask.ts +243 -0
  25. package/src/backends.ts +144 -0
  26. package/src/backlog.ts +436 -0
  27. package/src/bench.ts +163 -0
  28. package/src/board.ts +1 -0
  29. package/src/brief.ts +151 -0
  30. package/src/browser.ts +624 -0
  31. package/src/budget.ts +73 -0
  32. package/src/catalog.ts +214 -0
  33. package/src/checkchange.ts +180 -0
  34. package/src/checkpoint.ts +99 -0
  35. package/src/cli.ts +117 -0
  36. package/src/compact.ts +162 -0
  37. package/src/config.ts +340 -0
  38. package/src/context/capture.ts +1 -0
  39. package/src/context/digest.ts +1 -0
  40. package/src/context/embed.ts +1 -0
  41. package/src/context/index.ts +2 -0
  42. package/src/context/ledger.ts +1 -0
  43. package/src/context/manager.ts +1 -0
  44. package/src/context/memory.ts +1 -0
  45. package/src/context/policy.ts +1 -0
  46. package/src/context/prices.ts +1 -0
  47. package/src/context/recall.ts +1 -0
  48. package/src/context/rules.ts +1 -0
  49. package/src/context/search.ts +1 -0
  50. package/src/context/status.ts +1 -0
  51. package/src/context/store.ts +1 -0
  52. package/src/context/summary.ts +1 -0
  53. package/src/context/tokens.ts +1 -0
  54. package/src/context/tools.ts +1 -0
  55. package/src/continuation.ts +122 -0
  56. package/src/contract.ts +342 -0
  57. package/src/contractround.ts +225 -0
  58. package/src/control.ts +1 -0
  59. package/src/dataset.ts +133 -0
  60. package/src/decide.ts +690 -0
  61. package/src/eval.ts +66 -0
  62. package/src/evolver.ts +369 -0
  63. package/src/followups.ts +50 -0
  64. package/src/forms.ts +191 -0
  65. package/src/gate.ts +90 -0
  66. package/src/grants.ts +239 -0
  67. package/src/graph.ts +74 -0
  68. package/src/guard/index.ts +1 -0
  69. package/src/guard/wire.ts +1 -0
  70. package/src/helpers.ts +105 -0
  71. package/src/hooks.ts +199 -0
  72. package/src/integration.ts +4 -0
  73. package/src/jev.ts +141 -0
  74. package/src/journal.ts +1 -0
  75. package/src/look.ts +390 -0
  76. package/src/memory.ts +1 -0
  77. package/src/native.ts +2455 -0
  78. package/src/nogit.ts +112 -0
  79. package/src/outcomes.ts +210 -0
  80. package/src/pick.ts +112 -0
  81. package/src/pipelines.ts +252 -0
  82. package/src/plan.ts +449 -0
  83. package/src/plugin.ts +3187 -0
  84. package/src/policy.ts +84 -0
  85. package/src/pools.ts +1 -0
  86. package/src/profile.ts +186 -0
  87. package/src/progress.ts +1 -0
  88. package/src/redact.ts +1 -0
  89. package/src/registry.ts +207 -0
  90. package/src/roles.ts +1 -0
  91. package/src/routing.ts +1 -0
  92. package/src/runner.ts +1506 -0
  93. package/src/sandbox.ts +4 -0
  94. package/src/scheduler.ts +200 -0
  95. package/src/session.ts +269 -0
  96. package/src/shell/decide.ts +1 -0
  97. package/src/shell/index.ts +2 -0
  98. package/src/shell/sandbox.ts +1 -0
  99. package/src/shell/wire.ts +1 -0
  100. package/src/skills.ts +111 -0
  101. package/src/state.ts +1 -0
  102. package/src/store.ts +1 -0
  103. package/src/switcher.ts +1 -0
  104. package/src/tools.ts +480 -0
  105. package/src/trials.ts +247 -0
  106. package/src/usage.ts +1 -0
  107. package/src/wait.ts +180 -0
  108. package/src/watchdog.ts +498 -0
  109. package/src/worktree/git.ts +378 -0
@@ -0,0 +1,498 @@
1
+ // The loop watchdog (design.md §10.1): code, not the model, decides that a session is going in circles.
2
+ //
3
+ // It is fed every tool call of a watched session (tool.execute.after) and every provider turn (the context hook,
4
+ // which carries the message history), and returns a signal when a limit or a loop signature fires. The plugin
5
+ // then interrupts the session; the runner never resumes it, but may start a fresh one with a handoff note.
6
+ // The signatures come from real failures: Kimi restarting its task, Gemini's read loops, and a local planner
7
+ // that read the same directory sixty times in this project's own test.
8
+
9
+ import { createHash } from "node:crypto"
10
+
11
+ export type SignalKind = "steps" | "same_call" | "read_loop" | "no_new_files" | "restart" | "monologue" | "repeat_text" | "tokens" | "stalled" | "checkpoint" | "handback"
12
+
13
+ // How hard a signal hits. A nudge asks the worker to get on with it (Jev decides whether to pass it on); a stop
14
+ // interrupts the session. Absent means "stop", so every caller written before this field keeps its behaviour.
15
+ export type SignalSeverity = "stop" | "nudge"
16
+
17
+ export interface Signal {
18
+ readonly kind: SignalKind
19
+ readonly detail: string
20
+ readonly severity?: SignalSeverity // absent = "stop"
21
+ }
22
+
23
+ export interface Limits {
24
+ readonly maxSteps: number // provider turns
25
+ readonly sameCall: number // the same tool with the same input this often ...
26
+ readonly window: number // ... within this many calls
27
+ readonly readRepeat: number // the same path read this often ...
28
+ readonly readWindow: number // ... within this many calls, and with no write in between
29
+ readonly noNewFiles: number // this many calls in a row without progress; 0 disables the check (see below)
30
+ readonly restartLength: number // the opening calls repeated in this length
31
+ readonly monologue: number // assistant turns in a row without a tool call
32
+ }
33
+
34
+ // The thresholds, and what each one defends against (2026-10-06, after a live run in which nine signals fired on
35
+ // healthy sessions and three were escalated):
36
+ //
37
+ // - sameCall 3 in window 10, unchanged: the tightest loop there is, and the one the real failures showed first
38
+ // (Kimi restarting its task, Gemini rereading). Keeping the value means a genuinely stuck session still ends at
39
+ // three repeats; raising it to spare a TDD loop that runs `npm test` three times would let a real forever-loop
40
+ // (the same failing command, forever) run on to the step limit, which is a much more expensive mistake.
41
+ // - readRepeat 3 in readWindow 16: "the same file again and again" only means a loop *while it stays the recent
42
+ // work*. Before the window, reading a config file three times anywhere in a 200-call session was a hard stop, and
43
+ // normal work looked like the planner's loop. 16 calls is more than a read-explore-read cycle takes and less than
44
+ // a session's worth, so a real loop cannot hide outside it.
45
+ // - noNewFiles 16: calls in a row that make no progress. Three things count as progress: a new path, a search, and
46
+ // a command that actually did something. A command that runs is progress -- a worker verifying with `npm test` or
47
+ // `git status` ten times over is working, not stuck -- and the signature that actually catches a stuck command is
48
+ // sameCall, which compares the command itself rather than counting calls (live test, 2026-10-07: a worker was
49
+ // stopped after "8 calls in a row without a new file or a search" while it was eight calls into reading a source
50
+ // file it had already opened, before it had written anything). Only a command that keeps FAILING now counts
51
+ // towards the run, because that is the case sameCall cannot see. Readers, whose whole job is reading and who never
52
+ // write, are the extreme case: they would trip a low bar on ordinary work.
53
+ // - restartLength 4: the opening calls repeated verbatim at the tail of the *whole* session. That comparison is
54
+ // deliberately not windowed: starting over is by definition where the session began. Four is enough of an opening
55
+ // to be a shape rather than a coincidence (one read can repeat by chance, four calls rarely do).
56
+ // - monologue 3: a worker writing a long report in several messages was interrupted mid-report, so it only nudges.
57
+ // - maxSteps: the last safety net for a session that never ends (the user, 2026-10-05: a cut session wastes work).
58
+ // How many times a worker's failing checks are handed back for another try, on both gate paths (the runner's fix
59
+ // rounds and the native finish_task loop). The runner's own cap is configurable through RunnerDeps.fixRounds; this is
60
+ // the default both use. A check that cannot be satisfied in the environment -- a path that does not exist there, a
61
+ // command the gate refuses -- is the case this exists for: handed back forever, it burned a whole session.
62
+ export const FIX_ROUNDS = 2
63
+
64
+ export const DEFAULT_LIMITS: Limits = { maxSteps: 60, sameCall: 3, window: 10, readRepeat: 3, readWindow: 16, noNewFiles: 16, restartLength: 4, monologue: 3 }
65
+
66
+ // The budget tier the decision model picks (design.md §8.1) maps to step limits; code keeps the ceiling.
67
+ export const TIER_STEPS = { S: 30, M: 60, L: 120 } as const
68
+ // The user's choice (2026-10-05): no budget estimates per task, since a cut session wastes what it did. Loops are
69
+ // caught by the signatures above; this is only the last safety net for a session that never ends.
70
+ export const MAX_STEPS = 400
71
+
72
+ // Task checkpoints (the user's idea, 2026-10-05): every CHECKPOINT_STEPS steps a task is reviewed, not cut. Jev looks
73
+ // at the facts below and says whether it still makes progress (go on), needs another approach (a fresh session on
74
+ // another family), or goes back to the micromanager.
75
+ export const CHECKPOINT_STEPS = 60
76
+ // The signs that pull a checkpoint forward (the user's choice after the Ralph spike, 2026-10-25).
77
+ export const PULL_GAP = 10
78
+ export const PULL_SINCE_WRITE = 25
79
+ export const PULL_FAILURES = 6
80
+
81
+ // What a checkpoint is decided on: facts the watchdog has anyway, no estimate.
82
+ export interface Progress {
83
+ readonly steps: number
84
+ readonly calls: number
85
+ readonly writes: number
86
+ readonly callsSinceWrite: number
87
+ readonly filesRead: number
88
+ readonly newLines?: number
89
+ readonly newFiles?: number
90
+ readonly repeats?: number
91
+ readonly cycle?: boolean
92
+ readonly filesTouched?: readonly string[]
93
+ readonly repeatDetail?: string
94
+ readonly lastCommand?: string
95
+ readonly seenLines?: ReadonlyMap<string, ReadonlySet<string>>
96
+ readonly seenLineHashes?: ReadonlyMap<string, ReadonlySet<string>>
97
+ readonly recent: readonly string[] // the last tool calls, short
98
+ readonly recentFailures: number // failed tool calls among them
99
+ }
100
+ // ... and to tokens per session (input + output over all turns), checked after each turn by the runner.
101
+ export const TIER_TOKENS = { S: 250_000, M: 600_000, L: 1_500_000 } as const
102
+
103
+ const READS = new Set(["read", "list"])
104
+ const WRITES = new Set(["edit", "write", "patch", "multiedit", "apply_patch"])
105
+ // Searching is work: a worker that greps and globs nine times in a row is exploring a repository, not going in
106
+ // circles, and none of those calls opens a path the noNewFiles counter could see. code_graph is in here because it
107
+ // is a search over the syntax tree that opens no path at all (added 2026-10-06, missed by this list until then).
108
+ const SEARCHES = new Set([
109
+ "grep", "glob", "ast-grep", "astgrep", "websearch", "webfetch", "search", "code_search", "code_graph",
110
+ ])
111
+ // Tools that act: they run something whose outcome is not a file this watchdog can see. A successful one is progress,
112
+ // whatever it touched. A failing one is not counted here -- it falls through and counts towards the run, which is
113
+ // what a worker repeatedly failing the same way looks like, and the one case sameCall cannot catch because the
114
+ // command text differs each time.
115
+ const ACTS = new Set(["shell", "bash", "execute", "task"])
116
+
117
+ interface State {
118
+ limits: Limits
119
+ calls: string[] // tool + input, in order
120
+ readWindow: string[] // the read part key per call, "" for anything else, trimmed to limits.readWindow
121
+ readPaths: Set<string>
122
+ checkpointReadPaths: Set<string>
123
+ writtenPaths: Set<string>
124
+ quiet: number // calls in a row without a new path and without a search
125
+ steps: number
126
+ texts: string[] // normalized assistant texts seen so far
127
+ writes: number // writes since the last checkpoint
128
+ totalWrites: number
129
+ lastWrite: number // index into calls of the last write, -1 before any
130
+ failed: boolean[] // per call: did it fail
131
+ seenLines: Map<string, Set<string>>
132
+ newLines: number // unseen lines since the last checkpoint
133
+ ring: string[] // last ~12 call signatures with identical result hash
134
+ lastCommand?: string
135
+ lastRepeatedKey?: string
136
+ lastRepeatedInput?: { tool: string; input: unknown }
137
+ lastRepeatedCount?: number
138
+ // The adaptive checkpoint (src/checkpoint.ts): how many steps until the next review, and the step of the last one.
139
+ // Without an interval the review comes every CHECKPOINT_STEPS steps, as before.
140
+ interval?: number
141
+ next?: number
142
+ lastCheck: number
143
+ }
144
+
145
+ function stable(value: unknown): string {
146
+ if (value === null || typeof value !== "object") return JSON.stringify(value)
147
+ if (Array.isArray(value)) return `[${value.map(stable).join(",")}]`
148
+ return `{${Object.keys(value as object).sort().map((k) => `${k}:${stable((value as Record<string, unknown>)[k])}`).join(",")}}`
149
+ }
150
+
151
+ function pathOf(input: unknown): string | undefined {
152
+ const i = input as Record<string, unknown> | undefined
153
+ const p = i?.path ?? i?.filePath ?? i?.file_path
154
+ return typeof p === "string" ? p.replace(/\/+$/, "") : undefined
155
+ }
156
+
157
+ const normalize = (text: string) => text.toLowerCase().replace(/\s+/g, " ").trim()
158
+
159
+
160
+
161
+ function resultTextSafe(result: unknown): string {
162
+ try {
163
+ // Reuse the same shapes as hooks.resultText without importing (avoid cycle).
164
+ const r = result as { content?: unknown; output?: unknown } | undefined
165
+ if (!r || typeof r !== "object") return typeof result === "string" ? result : JSON.stringify(result ?? "")
166
+ const slots: string[] = []
167
+ if (Array.isArray(r.content)) for (const part of r.content as { text?: unknown }[]) if (part && typeof part.text === "string") slots.push(part.text as string)
168
+ if (typeof r.output === "string") slots.push(r.output as string)
169
+ else if (r.output && typeof r.output === "object") {
170
+ const o = r.output as Record<string, unknown>
171
+ for (const key of ["output", "content", "text"]) if (typeof o[key] === "string") slots.push(o[key] as string)
172
+ }
173
+ return slots.length ? slots.join("\n") : JSON.stringify(result)
174
+ } catch {
175
+ return String(result)
176
+ }
177
+ }
178
+
179
+
180
+
181
+ function detectCycle(ring: readonly string[]): boolean {
182
+ const n = ring.length
183
+ for (let patLen = 1; patLen <= 3; patLen++) {
184
+ if (n < patLen * 2) continue
185
+ for (let cycles = 2; cycles <= Math.floor(n / patLen); cycles++) {
186
+ const seg = ring.slice(-cycles * patLen)
187
+ const pat = seg.slice(0, patLen)
188
+ let ok = true
189
+ for (let i = 0; i < seg.length; i++) if (seg[i] !== pat[i % patLen]) { ok = false; break }
190
+ if (ok) return true
191
+ }
192
+ }
193
+ return false
194
+ }
195
+
196
+ function formatRepeat(tool: string, input: unknown, count: number): string {
197
+ const i = input as Record<string, unknown> | undefined
198
+ if (tool === "read") {
199
+ const path = i?.path ?? i?.filePath ?? i?.file_path
200
+ const offset = i?.offset
201
+ const limit = i?.limit
202
+ const where = offset !== undefined ? ` from line ${String(offset)}` : ""
203
+ const span = limit !== undefined ? ` for ${String(limit)} lines` : ""
204
+ return `read ${String(path)}${where}${span} ${count}x`
205
+ }
206
+ return `${tool} ${JSON.stringify(input)} ${count}x`
207
+ }
208
+
209
+ export class Watchdog {
210
+ readonly #sessions = new Map<string, State>()
211
+
212
+ watch(sessionID: string, limits: Partial<Limits> = {}): void {
213
+ this.#sessions.set(sessionID, {
214
+ limits: { ...DEFAULT_LIMITS, ...limits },
215
+ calls: [],
216
+ readWindow: [],
217
+ readPaths: new Set(),
218
+ checkpointReadPaths: new Set(),
219
+ writtenPaths: new Set(),
220
+ quiet: 0,
221
+ steps: 0,
222
+ texts: [],
223
+ writes: 0,
224
+ totalWrites: 0,
225
+ lastWrite: -1,
226
+ failed: [],
227
+ seenLines: new Map(),
228
+ newLines: 0,
229
+ ring: [],
230
+ lastCheck: 0,
231
+ })
232
+ }
233
+
234
+ // The session's first checkpoint interval, set once (from the task's class or difficulty, src/checkpoint.ts).
235
+ schedule(sessionID: string, interval: number): void {
236
+ const s = this.#sessions.get(sessionID)
237
+ if (!s || s.interval !== undefined) return
238
+ s.interval = interval
239
+ s.next = s.lastCheck + interval
240
+ }
241
+
242
+ scheduled(sessionID: string): number | undefined {
243
+ return this.#sessions.get(sessionID)?.interval
244
+ }
245
+
246
+ // A checkpoint was held: the next one comes after interval more steps.
247
+ checked(sessionID: string, interval: number): void {
248
+ const s = this.#sessions.get(sessionID)
249
+ if (!s) return
250
+ s.lastCheck = s.steps
251
+ s.interval = interval
252
+ s.next = s.steps + interval
253
+ // Reset the novelty accumulators and the repeat window: the next review starts fresh.
254
+ s.newLines = 0
255
+ s.writes = 0
256
+ s.ring = []
257
+ s.checkpointReadPaths = new Set(s.readPaths)
258
+ s.lastRepeatedKey = undefined
259
+ s.lastRepeatedInput = undefined
260
+ s.lastRepeatedCount = undefined
261
+ }
262
+
263
+ unwatch(sessionID: string): void {
264
+ this.#sessions.delete(sessionID)
265
+ }
266
+
267
+ watching(sessionID: string | undefined): boolean {
268
+ return sessionID !== undefined && this.#sessions.has(sessionID)
269
+ }
270
+
271
+ // failed: the call's result reads like an error (for the checkpoint's facts).
272
+ onTool(sessionID: string, tool: string, input: unknown, failedOrResult: unknown = false, resultMaybe?: unknown): Signal | undefined {
273
+ // Accept either (..., failed, result) or (..., result, failed) or (..., result) or (..., {result, failed}).
274
+ let failed = false
275
+ let result: unknown
276
+ if (failedOrResult && typeof failedOrResult === "object" && !Array.isArray(failedOrResult) && ("result" in (failedOrResult as object) || "failed" in (failedOrResult as object))) {
277
+ const o = failedOrResult as { result?: unknown; failed?: unknown }
278
+ result = o.result
279
+ failed = Boolean(o.failed)
280
+ if (resultMaybe !== undefined) result = resultMaybe
281
+ } else if (typeof failedOrResult === "boolean") {
282
+ failed = failedOrResult
283
+ result = resultMaybe
284
+ } else if (typeof resultMaybe === "boolean") {
285
+ result = failedOrResult
286
+ failed = resultMaybe
287
+ } else if (failedOrResult === undefined) {
288
+ result = resultMaybe
289
+ } else {
290
+ result = failedOrResult
291
+ }
292
+
293
+ const s = this.#sessions.get(sessionID)
294
+ if (!s) return undefined
295
+ const key = `${tool} ${stable(input)}`
296
+ s.calls.push(key)
297
+ s.failed.push(failed)
298
+ const resultTextStr = result === undefined ? "" : (typeof result === "string" ? result : resultTextSafe(result))
299
+ // One definition of "changed something": the writes counter and the re-read window reset on the same calls.
300
+ // A `git commit` or `git add` through the shell is a write too; without this a session that read a file,
301
+ // committed and read again kept its read count and looked like a loop.
302
+ const wrote = WRITES.has(tool) || (tool === "shell" && /\b(git (add|commit)|>|tee|sed -i|mv|cp)\b/.test(stable(input)))
303
+ if (wrote) {
304
+ s.writes++
305
+ s.totalWrites++
306
+ s.lastWrite = s.calls.length - 1
307
+ const path = pathOf(input)
308
+ if (path) s.writtenPaths.add(path)
309
+ }
310
+ // The same call again is a loop only when nothing was written in between: running the task's check after each
311
+ // edit is the work, not a circle (live run, 2026-10-25: a worker was stopped for its third `node check.js` with an
312
+ // edit before each). A write repeated with the same input still counts over the whole window.
313
+ const recent = s.calls.slice(-s.limits.window)
314
+ const since = wrote ? recent : s.calls.slice(Math.max(s.lastWrite + 1, s.calls.length - s.limits.window))
315
+ const same = since.filter((c) => c === key).length
316
+ if (same >= s.limits.sameCall) {
317
+ s.lastRepeatedKey = key
318
+ s.lastRepeatedInput = { tool, input }
319
+ s.lastRepeatedCount = same
320
+ return { kind: "same_call", severity: "stop", detail: `${tool} with the same input ${same}x in the last ${recent.length} calls` }
321
+ }
322
+ const path = pathOf(input)
323
+ const i = input as { offset?: unknown; limit?: unknown } | undefined
324
+ // A long file read part by part (offset/limit) is no loop (live test: a reader stopped while reading
325
+ // conversation.py in three parts); the same part again is.
326
+ const part = READS.has(tool) && path ? `${path}@${String(i?.offset ?? 0)}+${String(i?.limit ?? "")}` : ""
327
+ s.readWindow.push(part)
328
+ if (s.readWindow.length > s.limits.readWindow) s.readWindow.shift() // only recent work counts as a repeat
329
+ if (wrote) s.readWindow.length = 0 // a write changes what a re-read shows
330
+ if (part) {
331
+ const n = s.readWindow.filter((p) => p === part).length
332
+ if (n >= s.limits.readRepeat) {
333
+ s.lastRepeatedKey = key
334
+ s.lastRepeatedInput = { tool, input }
335
+ s.lastRepeatedCount = n
336
+ return { kind: "read_loop", severity: "nudge", detail: `read ${path}${i?.offset !== undefined ? ` from line ${String(i.offset)}` : ""} ${n}x in a row with no write in between` }
337
+ }
338
+ }
339
+ // Progress, not only new files. A search counts, and so does a command that ran and did not fail -- including
340
+ // the `execute` tool, which is how a worker acts in code mode and which opens no path for the check below to
341
+ // see. Only a command that keeps failing counts towards the run (see ACTS above).
342
+ if (wrote || SEARCHES.has(tool)) s.quiet = 0
343
+ else if (ACTS.has(tool) && !failed) s.quiet = 0
344
+ else if (path && READS.has(tool) && !s.readPaths.has(path)) {
345
+ s.readPaths.add(path)
346
+ s.quiet = 0
347
+ } else s.quiet++
348
+ if (s.limits.noNewFiles > 0 && s.quiet >= s.limits.noNewFiles) {
349
+ return { kind: "no_new_files", severity: "stop", detail: `${s.quiet} calls in a row without progress: no new file, no search, no command that worked` }
350
+ }
351
+ const k = s.limits.restartLength
352
+ if (s.calls.length >= 2 * k && s.calls.slice(-k).join("\n") === s.calls.slice(0, k).join("\n")) {
353
+ return { kind: "restart", detail: `the first ${k} calls came again: the session started over` }
354
+ }
355
+
356
+ // --- novelty tracking (this task) ---------------------------------------------
357
+ if (READS.has(tool) && path) {
358
+ if (!s.readPaths.has(path)) s.readPaths.add(path)
359
+ // newFiles is computed in progress() from checkpointReadPaths; nothing to do here.
360
+ if (resultTextStr) {
361
+ const lines = resultTextStr.split(/\r?\n/).filter((l) => l.trim() !== "")
362
+ if (lines.length > 0) {
363
+ const seen = s.seenLines.get(path) ?? new Set<string>()
364
+ let unseen = 0
365
+ for (const line of lines) {
366
+ const h = createHash("sha256").update(line).digest("hex")
367
+ if (!seen.has(h)) unseen++
368
+ }
369
+ for (const line of lines) {
370
+ const h = createHash("sha256").update(line).digest("hex")
371
+ seen.add(h)
372
+ }
373
+ s.seenLines.set(path, seen)
374
+ const seenRatio = (lines.length - unseen) / lines.length
375
+ if (seenRatio < 0.9) s.newLines += unseen
376
+ }
377
+ }
378
+ }
379
+ if (ACTS.has(tool) || tool === "shell" || tool === "bash" || tool === "execute") {
380
+ const inp = input as { command?: unknown; code?: unknown } | undefined
381
+ const cmd = typeof inp?.command === "string" ? inp.command : (typeof inp?.code === "string" ? inp.code : undefined)
382
+ if (cmd) s.lastCommand = cmd
383
+ }
384
+
385
+ // --- repeat tracking (ring buffer of last ~12 signatures with identical result) ---
386
+ const resultHash = createHash("sha256").update(resultTextStr).digest("hex").slice(0, 16)
387
+ const combined = `${key}#${resultHash}`
388
+ s.ring.push(combined)
389
+ if (s.ring.length > 12) s.ring.shift()
390
+ // Track the most repeated combined signature for a concrete nudge message.
391
+ const counts = new Map<string, number>()
392
+ for (const e of s.ring) counts.set(e, (counts.get(e) ?? 0) + 1)
393
+ let maxCount = 0
394
+ let maxKey = ""
395
+ for (const [kk, v] of counts) if (v > maxCount) { maxCount = v; maxKey = kk }
396
+ const repeatCount = Math.max(maxCount, same)
397
+ if (repeatCount >= 2) {
398
+ s.lastRepeatedKey = maxKey ? maxKey.split("#")[0] : key
399
+ s.lastRepeatedInput = { tool, input }
400
+ s.lastRepeatedCount = repeatCount
401
+ }
402
+
403
+ return undefined
404
+ }
405
+
406
+ // A checkpoint is due when the session's interval is reached, or earlier when the watchdog sees signs of a stall: a
407
+ // long stretch without a write, or many failures among the last calls (at least PULL_GAP steps after the last
408
+ // review, so one bad patch does not ask Jev on every step). Unscheduled: every CHECKPOINT_STEPS steps.
409
+ checkpointDue(sessionID: string, every = CHECKPOINT_STEPS): boolean {
410
+ const s = this.#sessions.get(sessionID)
411
+ if (!s || s.steps === 0) return false
412
+ if (s.next === undefined) return s.steps % every === 0
413
+ if (s.steps >= s.next) return true
414
+ const sinceWrite = s.calls.length - 1 - s.lastWrite
415
+ const failing = s.failed.slice(-12).filter(Boolean).length
416
+ return s.steps - s.lastCheck >= PULL_GAP && (sinceWrite >= PULL_SINCE_WRITE || failing >= PULL_FAILURES)
417
+ }
418
+
419
+ progress(sessionID: string): Progress | undefined {
420
+ const s = this.#sessions.get(sessionID)
421
+ if (!s) return undefined
422
+ const tail = s.calls.slice(-12)
423
+ // newFiles: distinct paths first touched since the last checkpoint.
424
+ let newFiles = 0
425
+ for (const p of s.readPaths) if (!s.checkpointReadPaths.has(p)) newFiles++
426
+ // repeats: max occurrences of one combined signature in the ring buffer.
427
+ const counts = new Map<string, number>()
428
+ for (const e of s.ring) counts.set(e, (counts.get(e) ?? 0) + 1)
429
+ let repeats = 0
430
+ for (const v of counts.values()) if (v > repeats) repeats = v
431
+ // cycle over <=3 signatures?
432
+ const cycle = detectCycle(s.ring)
433
+ const filesTouched = [...new Set([...s.readPaths, ...s.writtenPaths])]
434
+ const repeatDetail = (repeats >= 2 || cycle)
435
+ ? (s.lastRepeatedCount && s.lastRepeatedInput
436
+ ? formatRepeat(s.lastRepeatedInput.tool, s.lastRepeatedInput.input, s.lastRepeatedCount)
437
+ : (s.lastRepeatedKey ? `${s.lastRepeatedKey} ${repeats}x` : undefined))
438
+ : undefined
439
+ return {
440
+ steps: s.steps,
441
+ calls: s.calls.length,
442
+ writes: s.writes,
443
+ callsSinceWrite: s.calls.length - 1 - s.lastWrite,
444
+ filesRead: s.readPaths.size,
445
+ newLines: s.newLines,
446
+ newFiles,
447
+ repeats,
448
+ cycle,
449
+ filesTouched,
450
+ repeatDetail,
451
+ lastCommand: s.lastCommand,
452
+ seenLines: s.seenLines,
453
+ seenLineHashes: s.seenLines,
454
+ recent: tail.map((c) => c.slice(0, 120)),
455
+ recentFailures: s.failed.slice(-12).filter(Boolean).length,
456
+ }
457
+ }
458
+
459
+ // One provider turn; messages as the context hook gives them (role + content parts).
460
+ onTurn(sessionID: string, messages: unknown): Signal | undefined {
461
+ const s = this.#sessions.get(sessionID)
462
+ if (!s) return undefined
463
+ s.steps++
464
+ if (s.steps > s.limits.maxSteps) return { kind: "steps", detail: `more than ${s.limits.maxSteps} steps` }
465
+ if (!Array.isArray(messages)) return undefined
466
+ const assistant = (messages as { role?: string; content?: unknown }[]).filter((m) => m.role === "assistant")
467
+ const parts = (m: { content?: unknown }) => (Array.isArray(m.content) ? (m.content as { type?: string; text?: string }[]) : [])
468
+ let silent = 0
469
+ for (let i = assistant.length - 1; i >= 0 && !parts(assistant[i]!).some((p) => p.type === "tool-call"); i--) silent++
470
+ // A nudge, not a stop: a worker that writes a long report in several messages was interrupted mid-report (live
471
+ // run, 2026-10-06), and three text turns say nothing about a loop.
472
+ if (silent >= s.limits.monologue) return { kind: "monologue", severity: "nudge", detail: `${silent} replies in a row without a tool call` }
473
+ const last = assistant.at(-1)
474
+ const text = last ? normalize(parts(last).filter((p) => p.type === "text").map((p) => p.text ?? "").join(" ")) : ""
475
+ if (text.length > 40) {
476
+ if (s.texts.includes(text)) return { kind: "repeat_text", detail: "the same answer text came again" }
477
+ s.texts.push(text)
478
+ }
479
+ return undefined
480
+ }
481
+ }
482
+
483
+ // What a fresh session is told after the watchdog stopped (or nudged) the previous one.
484
+ export function handoffNote(signal: Signal, changed: readonly string[], progress?: Progress): string {
485
+ const what = signal.severity === "nudge" ? "drew a nudge from the loop watchdog, not a stop" : "was stopped by the loop watchdog"
486
+ const digest = [
487
+ "Digest:",
488
+ `Files touched: ${changed.join(", ") || (progress?.filesTouched?.join(", ") ?? "none")}`,
489
+ `Learned: ${progress?.newLines ?? 0} new lines, ${progress?.newFiles ?? 0} new files`,
490
+ `Last command: ${progress?.lastCommand ?? "none"}`,
491
+ ].join("\n")
492
+ return [
493
+ `A previous attempt at this task ${what}: ${signal.detail}.`,
494
+ changed.length ? `Files already changed in this directory: ${changed.join(", ")}. Check them instead of starting over.` : "No file was changed yet.",
495
+ digest,
496
+ "Do not read the same file again and again: once you have read a file, use what you know. If something is missing, say so in your report.",
497
+ ].join("\n")
498
+ }