@omacode/micromanager 0.0.0-stage → 1.0.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 (146) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +30 -2
  3. package/THIRD_PARTY.md +100 -0
  4. package/decider/.python-version +1 -0
  5. package/decider/README.md +35 -0
  6. package/decider/decider/__init__.py +1 -0
  7. package/decider/decider/server.py +327 -0
  8. package/decider/pyproject.toml +34 -0
  9. package/decider/uv.lock +1255 -0
  10. package/dist/agenda.js +51 -0
  11. package/dist/agents.js +58 -0
  12. package/dist/artifact/handoff.js +281 -0
  13. package/dist/ask.js +200 -0
  14. package/dist/backends.js +219 -0
  15. package/dist/backlog.js +414 -0
  16. package/dist/bench.js +427 -0
  17. package/dist/board.js +1 -0
  18. package/dist/brief.js +202 -0
  19. package/dist/browser.js +679 -0
  20. package/dist/budget.js +61 -0
  21. package/dist/catalog.js +187 -0
  22. package/dist/checkchange.js +145 -0
  23. package/dist/checkpoint.js +94 -0
  24. package/dist/cli.js +764 -0
  25. package/dist/comfy-gate.js +258 -0
  26. package/dist/compact.js +142 -0
  27. package/dist/config.js +344 -0
  28. package/dist/context/capture.js +1 -0
  29. package/dist/context/digest.js +1 -0
  30. package/dist/context/embed.js +1 -0
  31. package/dist/context/index.js +2 -0
  32. package/dist/context/ledger.js +1 -0
  33. package/dist/context/manager.js +1 -0
  34. package/dist/context/memory.js +1 -0
  35. package/dist/context/policy.js +1 -0
  36. package/dist/context/prices.js +1 -0
  37. package/dist/context/recall.js +1 -0
  38. package/dist/context/rules.js +1 -0
  39. package/dist/context/search.js +1 -0
  40. package/dist/context/status.js +1 -0
  41. package/dist/context/store.js +1 -0
  42. package/dist/context/summary.js +1 -0
  43. package/dist/context/tokens.js +1 -0
  44. package/dist/context/tools.js +1 -0
  45. package/dist/continuation.js +184 -0
  46. package/dist/contract.js +294 -0
  47. package/dist/contractround.js +178 -0
  48. package/dist/control.js +1 -0
  49. package/dist/creative-tools.js +237 -0
  50. package/dist/dataset.js +175 -0
  51. package/dist/decide.js +676 -0
  52. package/dist/decider.js +171 -0
  53. package/dist/design-shell.js +448 -0
  54. package/dist/design.js +1410 -0
  55. package/dist/desktop.js +44 -0
  56. package/dist/egress.js +156 -0
  57. package/dist/eval.js +60 -0
  58. package/dist/evolver.js +302 -0
  59. package/dist/features.js +193 -0
  60. package/dist/followups.js +32 -0
  61. package/dist/forms.js +195 -0
  62. package/dist/gate.js +108 -0
  63. package/dist/gatebox.js +46 -0
  64. package/dist/grants.js +189 -0
  65. package/dist/graph.js +65 -0
  66. package/dist/guard/index.js +1 -0
  67. package/dist/guard/wire.js +1 -0
  68. package/dist/helpers.js +85 -0
  69. package/dist/hooks.js +158 -0
  70. package/dist/image-models.js +117 -0
  71. package/dist/integration.js +3 -0
  72. package/dist/journal.js +1 -0
  73. package/dist/look.js +363 -0
  74. package/dist/memory.js +1 -0
  75. package/dist/mode.js +97 -0
  76. package/dist/native.js +3348 -0
  77. package/dist/nogit.js +259 -0
  78. package/dist/outcomes.js +148 -0
  79. package/dist/permission.js +35 -0
  80. package/dist/pick.js +89 -0
  81. package/dist/pipelines.js +262 -0
  82. package/dist/plan.js +641 -0
  83. package/dist/plandoc.js +211 -0
  84. package/dist/plugin.js +4736 -0
  85. package/dist/policy.js +58 -0
  86. package/dist/pools.js +1 -0
  87. package/dist/preview.js +274 -0
  88. package/dist/profile.js +165 -0
  89. package/dist/progress.js +1 -0
  90. package/dist/promote.js +313 -0
  91. package/dist/redact.js +1 -0
  92. package/dist/registry.js +179 -0
  93. package/dist/riskscore.js +126 -0
  94. package/dist/roles.js +1 -0
  95. package/dist/routing.js +1 -0
  96. package/dist/runner.js +1892 -0
  97. package/dist/sandbox.js +3 -0
  98. package/dist/sandboxgate.js +90 -0
  99. package/dist/scheduler.js +170 -0
  100. package/dist/services-main.js +131 -0
  101. package/dist/services.js +265 -0
  102. package/dist/session.js +241 -0
  103. package/dist/setup.js +423 -0
  104. package/dist/shell/decide.js +1 -0
  105. package/dist/shell/index.js +2 -0
  106. package/dist/shell/sandbox.js +1 -0
  107. package/dist/shell/wire.js +1 -0
  108. package/dist/skills.js +103 -0
  109. package/dist/state.js +1 -0
  110. package/dist/store.js +1 -0
  111. package/dist/switcher.js +1 -0
  112. package/dist/synth.js +418 -0
  113. package/dist/tools.js +477 -0
  114. package/dist/trials.js +223 -0
  115. package/dist/usage.js +1 -0
  116. package/dist/wait.js +167 -0
  117. package/dist/watchdog.js +476 -0
  118. package/dist/web-guidance.js +43 -0
  119. package/dist/which.js +20 -0
  120. package/dist/worktree/git.js +545 -0
  121. package/dist/writeguard.js +311 -0
  122. package/evolver/mm_evolve/__init__.py +1 -0
  123. package/evolver/mm_evolve/entry.py +3 -0
  124. package/evolver/mm_evolve/evaluator.py +119 -0
  125. package/evolver/mm_evolve/llm.py +76 -0
  126. package/evolver/mm_evolve/run.py +89 -0
  127. package/evolver/mm_evolve/spec.py +62 -0
  128. package/evolver/pyproject.toml +21 -0
  129. package/evolver/uv.lock +772 -0
  130. package/package.json +74 -4
  131. package/skills/THIRD_PARTY.md +58 -0
  132. package/skills/code-review/SKILL.md +46 -0
  133. package/skills/deck/SKILL.md +98 -0
  134. package/skills/deliberate/SKILL.md +39 -0
  135. package/skills/design/SKILL.md +150 -0
  136. package/skills/diagnosing-bugs/SKILL.md +75 -0
  137. package/skills/image/SKILL.md +66 -0
  138. package/skills/orchestrator/SKILL.md +107 -0
  139. package/skills/receiving-code-review/SKILL.md +36 -0
  140. package/skills/research/SKILL.md +18 -0
  141. package/skills/tdd/SKILL.md +56 -0
  142. package/skills/tdd/mocking.md +59 -0
  143. package/skills/tdd/tests.md +77 -0
  144. package/skills/verification-before-completion/SKILL.md +50 -0
  145. package/skills/video/SKILL.md +97 -0
  146. package/skills/web/SKILL.md +60 -0
@@ -0,0 +1,476 @@
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
+ import { createHash } from "node:crypto";
9
+ // The thresholds, and what each one defends against (2026-10-06, after a live run in which nine signals fired on
10
+ // healthy sessions and three were escalated):
11
+ //
12
+ // - sameCall 3 in window 10, unchanged: the tightest loop there is, and the one the real failures showed first
13
+ // (Kimi restarting its task, Gemini rereading). Keeping the value means a genuinely stuck session still ends at
14
+ // three repeats; raising it to spare a TDD loop that runs `npm test` three times would let a real forever-loop
15
+ // (the same failing command, forever) run on to the step limit, which is a much more expensive mistake.
16
+ // - readRepeat 3 in readWindow 16: "the same file again and again" only means a loop *while it stays the recent
17
+ // work*. Before the window, reading a config file three times anywhere in a 200-call session was a hard stop, and
18
+ // normal work looked like the planner's loop. 16 calls is more than a read-explore-read cycle takes and less than
19
+ // a session's worth, so a real loop cannot hide outside it.
20
+ // - noNewFiles 16: calls in a row that make no progress. Three things count as progress: a new path, a search, and
21
+ // a command that actually did something. A command that runs is progress -- a worker verifying with `npm test` or
22
+ // `git status` ten times over is working, not stuck -- and the signature that actually catches a stuck command is
23
+ // sameCall, which compares the command itself rather than counting calls (live test, 2026-10-07: a worker was
24
+ // stopped after "8 calls in a row without a new file or a search" while it was eight calls into reading a source
25
+ // file it had already opened, before it had written anything). Only a command that keeps FAILING now counts
26
+ // towards the run, because that is the case sameCall cannot see. Readers, whose whole job is reading and who never
27
+ // write, are the extreme case: they would trip a low bar on ordinary work.
28
+ // - restartLength 4: the opening calls repeated verbatim at the tail of the *whole* session. That comparison is
29
+ // deliberately not windowed: starting over is by definition where the session began. Four is enough of an opening
30
+ // to be a shape rather than a coincidence (one read can repeat by chance, four calls rarely do).
31
+ // - monologue 3: a worker writing a long report in several messages was interrupted mid-report, so it only nudges.
32
+ // - maxSteps: the last safety net for a session that never ends (the user, 2026-10-05: a cut session wastes work).
33
+ // How many times a worker's failing checks are handed back for another try, on both gate paths (the runner's fix
34
+ // rounds and the native finish_task loop). The runner's own cap is configurable through RunnerDeps.fixRounds; this is
35
+ // the default both use. A check that cannot be satisfied in the environment -- a path that does not exist there, a
36
+ // command the gate refuses -- is the case this exists for: handed back forever, it burned a whole session.
37
+ export const FIX_ROUNDS = 2;
38
+ export const DEFAULT_LIMITS = { maxSteps: 60, sameCall: 3, window: 10, readRepeat: 3, readWindow: 16, noNewFiles: 16, restartLength: 4, monologue: 3 };
39
+ // The budget tier the decision model picks (design.md §8.1) maps to step limits; code keeps the ceiling.
40
+ export const TIER_STEPS = { S: 30, M: 60, L: 120 };
41
+ // The user's choice (2026-10-05): no budget estimates per task, since a cut session wastes what it did. Loops are
42
+ // caught by the signatures above; this is only the last safety net for a session that never ends.
43
+ export const MAX_STEPS = 400;
44
+ // Task checkpoints (the user's idea, 2026-10-05): every CHECKPOINT_STEPS steps a task is reviewed, not cut. The decider looks
45
+ // at the facts below and says whether it still makes progress (go on), needs another approach (a fresh session on
46
+ // another family), or goes back to the micromanager.
47
+ export const CHECKPOINT_STEPS = 60;
48
+ // The signs that pull a checkpoint forward (the user's choice after the Ralph spike, 2026-10-25).
49
+ export const PULL_GAP = 10;
50
+ export const PULL_SINCE_WRITE = 25;
51
+ export const PULL_FAILURES = 6;
52
+ // ... and to tokens per session (input + output over all turns), checked after each turn by the runner.
53
+ export const TIER_TOKENS = { S: 250_000, M: 600_000, L: 1_500_000 };
54
+ const READS = new Set(["read", "list"]);
55
+ const WRITES = new Set(["edit", "write", "patch", "multiedit", "apply_patch"]);
56
+ // Searching is work: a worker that greps and globs nine times in a row is exploring a repository, not going in
57
+ // circles, and none of those calls opens a path the noNewFiles counter could see. code_graph is in here because it
58
+ // is a search over the syntax tree that opens no path at all (added 2026-10-06, missed by this list until then).
59
+ const SEARCHES = new Set([
60
+ "grep", "glob", "ast-grep", "astgrep", "websearch", "webfetch", "search", "code_search", "code_graph",
61
+ ]);
62
+ // Tools that act: they run something whose outcome is not a file this watchdog can see. A successful one is progress,
63
+ // whatever it touched. A failing one is not counted here -- it falls through and counts towards the run, which is
64
+ // what a worker repeatedly failing the same way looks like, and the one case sameCall cannot catch because the
65
+ // command text differs each time.
66
+ const ACTS = new Set(["shell", "bash", "execute", "task"]);
67
+ const sha256 = (text) => createHash("sha256").update(text).digest("hex");
68
+ // A call key only needs to tell one input from another, not to carry it: a `write` with a 100 KB body would otherwise
69
+ // be sorted, concatenated and kept in the session for the whole run. Longer strings are hashed instead, so `same_call`
70
+ // stays exact (two different bodies need a SHA-256 collision to collide) while the key stays small.
71
+ const STABLE_INLINE = 512;
72
+ function stable(value) {
73
+ if (typeof value === "string") {
74
+ return value.length <= STABLE_INLINE ? JSON.stringify(value) : `"#sha256:${sha256(value)}:${value.length}"`;
75
+ }
76
+ if (value === null || typeof value !== "object")
77
+ return JSON.stringify(value);
78
+ if (Array.isArray(value))
79
+ return `[${value.map(stable).join(",")}]`;
80
+ return `{${Object.keys(value).sort().map((k) => `${k}:${stable(value[k])}`).join(",")}}`;
81
+ }
82
+ // The write probe reads a shell input in full (never the hashed form above): a command longer than STABLE_INLINE that
83
+ // commits is still a write. Shell commands are small, and this runs only for them.
84
+ function inputText(input) {
85
+ try {
86
+ return JSON.stringify(input) ?? "";
87
+ }
88
+ catch {
89
+ return "";
90
+ }
91
+ }
92
+ function pathOf(input) {
93
+ const i = input;
94
+ const p = i?.path ?? i?.filePath ?? i?.file_path;
95
+ return typeof p === "string" ? p.replace(/\/+$/, "") : undefined;
96
+ }
97
+ const normalize = (text) => text.toLowerCase().replace(/\s+/g, " ").trim();
98
+ // Only recent answers can realistically come back verbatim, and a long session must not grow its seen-text memory
99
+ // without bound. The set keeps insertion order, so evicting the first entry drops the oldest text in O(1).
100
+ const MAX_TEXTS = 512;
101
+ function resultTextSafe(result) {
102
+ try {
103
+ // Reuse the same shapes as hooks.resultText without importing (avoid cycle).
104
+ const r = result;
105
+ if (!r || typeof r !== "object")
106
+ return typeof result === "string" ? result : JSON.stringify(result ?? "");
107
+ const slots = [];
108
+ if (Array.isArray(r.content))
109
+ for (const part of r.content)
110
+ if (part && typeof part.text === "string")
111
+ slots.push(part.text);
112
+ if (typeof r.output === "string")
113
+ slots.push(r.output);
114
+ else if (r.output && typeof r.output === "object") {
115
+ const o = r.output;
116
+ for (const key of ["output", "content", "text"])
117
+ if (typeof o[key] === "string")
118
+ slots.push(o[key]);
119
+ }
120
+ return slots.length ? slots.join("\n") : JSON.stringify(result);
121
+ }
122
+ catch {
123
+ return String(result);
124
+ }
125
+ }
126
+ function detectCycle(ring) {
127
+ const n = ring.length;
128
+ for (let patLen = 1; patLen <= 3; patLen++) {
129
+ if (n < patLen * 2)
130
+ continue;
131
+ for (let cycles = 2; cycles <= Math.floor(n / patLen); cycles++) {
132
+ const seg = ring.slice(-cycles * patLen);
133
+ const pat = seg.slice(0, patLen);
134
+ let ok = true;
135
+ for (let i = 0; i < seg.length; i++)
136
+ if (seg[i] !== pat[i % patLen]) {
137
+ ok = false;
138
+ break;
139
+ }
140
+ if (ok)
141
+ return true;
142
+ }
143
+ }
144
+ return false;
145
+ }
146
+ function formatRepeat(tool, input, count) {
147
+ const i = input;
148
+ if (tool === "read") {
149
+ const path = i?.path ?? i?.filePath ?? i?.file_path;
150
+ const offset = i?.offset;
151
+ const limit = i?.limit;
152
+ const where = offset !== undefined ? ` from line ${String(offset)}` : "";
153
+ const span = limit !== undefined ? ` for ${String(limit)} lines` : "";
154
+ return `read ${String(path)}${where}${span} ${count}x`;
155
+ }
156
+ return `${tool} ${JSON.stringify(input)} ${count}x`;
157
+ }
158
+ export class Watchdog {
159
+ #sessions = new Map();
160
+ watch(sessionID, limits = {}) {
161
+ this.#sessions.set(sessionID, {
162
+ limits: { ...DEFAULT_LIMITS, ...limits },
163
+ calls: [],
164
+ readWindow: [],
165
+ readPaths: new Set(),
166
+ checkpointReadPaths: new Set(),
167
+ writtenPaths: new Set(),
168
+ quiet: 0,
169
+ steps: 0,
170
+ texts: new Set(),
171
+ writes: 0,
172
+ totalWrites: 0,
173
+ lastWrite: -1,
174
+ failed: [],
175
+ seenLines: new Map(),
176
+ newLines: 0,
177
+ ring: [],
178
+ lastCheck: 0,
179
+ });
180
+ }
181
+ // The session's first checkpoint interval, set once (from the task's class or difficulty, src/checkpoint.ts).
182
+ schedule(sessionID, interval) {
183
+ const s = this.#sessions.get(sessionID);
184
+ if (!s || s.interval !== undefined)
185
+ return;
186
+ s.interval = interval;
187
+ s.next = s.lastCheck + interval;
188
+ }
189
+ scheduled(sessionID) {
190
+ return this.#sessions.get(sessionID)?.interval;
191
+ }
192
+ // A checkpoint was held: the next one comes after interval more steps.
193
+ checked(sessionID, interval) {
194
+ const s = this.#sessions.get(sessionID);
195
+ if (!s)
196
+ return;
197
+ s.lastCheck = s.steps;
198
+ s.interval = interval;
199
+ s.next = s.steps + interval;
200
+ // Reset the novelty accumulators and the repeat window: the next review starts fresh.
201
+ s.newLines = 0;
202
+ s.writes = 0;
203
+ s.ring = [];
204
+ s.checkpointReadPaths = new Set(s.readPaths);
205
+ s.lastRepeatedKey = undefined;
206
+ s.lastRepeatedInput = undefined;
207
+ s.lastRepeatedCount = undefined;
208
+ }
209
+ unwatch(sessionID) {
210
+ this.#sessions.delete(sessionID);
211
+ }
212
+ watching(sessionID) {
213
+ return sessionID !== undefined && this.#sessions.has(sessionID);
214
+ }
215
+ // failed: the call's result reads like an error (for the checkpoint's facts).
216
+ onTool(sessionID, tool, input, failedOrResult = false, resultMaybe) {
217
+ // Accept either (..., failed, result) or (..., result, failed) or (..., result) or (..., {result, failed}).
218
+ let failed = false;
219
+ let result;
220
+ if (failedOrResult && typeof failedOrResult === "object" && !Array.isArray(failedOrResult) && ("result" in failedOrResult || "failed" in failedOrResult)) {
221
+ const o = failedOrResult;
222
+ result = o.result;
223
+ failed = Boolean(o.failed);
224
+ if (resultMaybe !== undefined)
225
+ result = resultMaybe;
226
+ }
227
+ else if (typeof failedOrResult === "boolean") {
228
+ failed = failedOrResult;
229
+ result = resultMaybe;
230
+ }
231
+ else if (typeof resultMaybe === "boolean") {
232
+ result = failedOrResult;
233
+ failed = resultMaybe;
234
+ }
235
+ else if (failedOrResult === undefined) {
236
+ result = resultMaybe;
237
+ }
238
+ else {
239
+ result = failedOrResult;
240
+ }
241
+ const s = this.#sessions.get(sessionID);
242
+ if (!s)
243
+ return undefined;
244
+ const key = `${tool} ${stable(input)}`;
245
+ s.calls.push(key);
246
+ s.failed.push(failed);
247
+ const resultTextStr = result === undefined ? "" : (typeof result === "string" ? result : resultTextSafe(result));
248
+ // One definition of "changed something": the writes counter and the re-read window reset on the same calls.
249
+ // A `git commit` or `git add` through the shell is a write too; without this a session that read a file,
250
+ // committed and read again kept its read count and looked like a loop.
251
+ const wrote = WRITES.has(tool) || (tool === "shell" && /\b(git (add|commit)|>|tee|sed -i|mv|cp)\b/.test(inputText(input)));
252
+ if (wrote) {
253
+ s.writes++;
254
+ s.totalWrites++;
255
+ s.lastWrite = s.calls.length - 1;
256
+ const path = pathOf(input);
257
+ if (path)
258
+ s.writtenPaths.add(path);
259
+ }
260
+ // The same call again is a loop only when nothing was written in between: running the task's check after each
261
+ // edit is the work, not a circle (live run, 2026-10-25: a worker was stopped for its third `node check.js` with an
262
+ // edit before each). A write repeated with the same input still counts over the whole window.
263
+ const recent = s.calls.slice(-s.limits.window);
264
+ const since = wrote ? recent : s.calls.slice(Math.max(s.lastWrite + 1, s.calls.length - s.limits.window));
265
+ const same = since.filter((c) => c === key).length;
266
+ if (same >= s.limits.sameCall) {
267
+ s.lastRepeatedKey = key;
268
+ s.lastRepeatedInput = { tool, input };
269
+ s.lastRepeatedCount = same;
270
+ return { kind: "same_call", severity: "stop", detail: `${tool} with the same input ${same}x in the last ${recent.length} calls` };
271
+ }
272
+ const path = pathOf(input);
273
+ const i = input;
274
+ // A long file read part by part (offset/limit) is no loop (live test: a reader stopped while reading
275
+ // conversation.py in three parts); the same part again is.
276
+ const part = READS.has(tool) && path ? `${path}@${String(i?.offset ?? 0)}+${String(i?.limit ?? "")}` : "";
277
+ s.readWindow.push(part);
278
+ if (s.readWindow.length > s.limits.readWindow)
279
+ s.readWindow.shift(); // only recent work counts as a repeat
280
+ if (wrote)
281
+ s.readWindow.length = 0; // a write changes what a re-read shows
282
+ if (part) {
283
+ const n = s.readWindow.filter((p) => p === part).length;
284
+ if (n >= s.limits.readRepeat) {
285
+ s.lastRepeatedKey = key;
286
+ s.lastRepeatedInput = { tool, input };
287
+ s.lastRepeatedCount = n;
288
+ 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` };
289
+ }
290
+ }
291
+ // Progress, not only new files. A search counts, and so does a command that ran and did not fail -- including
292
+ // the `execute` tool, which is how a worker acts in code mode and which opens no path for the check below to
293
+ // see. Only a command that keeps failing counts towards the run (see ACTS above).
294
+ if (wrote || SEARCHES.has(tool))
295
+ s.quiet = 0;
296
+ else if (ACTS.has(tool) && !failed)
297
+ s.quiet = 0;
298
+ else if (path && READS.has(tool) && !s.readPaths.has(path)) {
299
+ s.readPaths.add(path);
300
+ s.quiet = 0;
301
+ }
302
+ else
303
+ s.quiet++;
304
+ if (s.limits.noNewFiles > 0 && s.quiet >= s.limits.noNewFiles) {
305
+ 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` };
306
+ }
307
+ const k = s.limits.restartLength;
308
+ if (s.calls.length >= 2 * k && s.calls.slice(-k).join("\n") === s.calls.slice(0, k).join("\n")) {
309
+ return { kind: "restart", detail: `the first ${k} calls came again: the session started over` };
310
+ }
311
+ // --- novelty tracking (this task) ---------------------------------------------
312
+ if (READS.has(tool) && path) {
313
+ if (!s.readPaths.has(path))
314
+ s.readPaths.add(path);
315
+ // newFiles is computed in progress() from checkpointReadPaths; nothing to do here.
316
+ if (resultTextStr) {
317
+ const lines = resultTextStr.split(/\r?\n/).filter((l) => l.trim() !== "");
318
+ if (lines.length > 0) {
319
+ const seen = s.seenLines.get(path) ?? new Set();
320
+ // One hash per line, reused for the count and for `seen`: hashing each line twice was pure waste on the
321
+ // hottest path in the plugin (every read result of every watched session).
322
+ const hashes = lines.map((line) => sha256(line));
323
+ let unseen = 0;
324
+ for (const h of hashes)
325
+ if (!seen.has(h))
326
+ unseen++;
327
+ for (const h of hashes)
328
+ seen.add(h);
329
+ s.seenLines.set(path, seen);
330
+ const seenRatio = (lines.length - unseen) / lines.length;
331
+ if (seenRatio < 0.9)
332
+ s.newLines += unseen;
333
+ }
334
+ }
335
+ }
336
+ if (ACTS.has(tool) || tool === "shell" || tool === "bash" || tool === "execute") {
337
+ const inp = input;
338
+ const cmd = typeof inp?.command === "string" ? inp.command : (typeof inp?.code === "string" ? inp.code : undefined);
339
+ if (cmd)
340
+ s.lastCommand = cmd;
341
+ }
342
+ // --- repeat tracking (ring buffer of last ~12 signatures with identical result) ---
343
+ const resultHash = sha256(resultTextStr).slice(0, 16);
344
+ const combined = `${key}#${resultHash}`;
345
+ s.ring.push(combined);
346
+ if (s.ring.length > 12)
347
+ s.ring.shift();
348
+ // Track the most repeated combined signature for a concrete nudge message.
349
+ const counts = new Map();
350
+ for (const e of s.ring)
351
+ counts.set(e, (counts.get(e) ?? 0) + 1);
352
+ let maxCount = 0;
353
+ let maxKey = "";
354
+ for (const [kk, v] of counts)
355
+ if (v > maxCount) {
356
+ maxCount = v;
357
+ maxKey = kk;
358
+ }
359
+ const repeatCount = Math.max(maxCount, same);
360
+ if (repeatCount >= 2) {
361
+ s.lastRepeatedKey = maxKey ? maxKey.split("#")[0] : key;
362
+ s.lastRepeatedInput = { tool, input };
363
+ s.lastRepeatedCount = repeatCount;
364
+ }
365
+ return undefined;
366
+ }
367
+ // A checkpoint is due when the session's interval is reached, or earlier when the watchdog sees signs of a stall: a
368
+ // long stretch without a write, or many failures among the last calls (at least PULL_GAP steps after the last
369
+ // review, so one bad patch does not ask the decider on every step). Unscheduled: every CHECKPOINT_STEPS steps.
370
+ checkpointDue(sessionID, every = CHECKPOINT_STEPS) {
371
+ const s = this.#sessions.get(sessionID);
372
+ if (!s || s.steps === 0)
373
+ return false;
374
+ if (s.next === undefined)
375
+ return s.steps % every === 0;
376
+ if (s.steps >= s.next)
377
+ return true;
378
+ const sinceWrite = s.calls.length - 1 - s.lastWrite;
379
+ const failing = s.failed.slice(-12).filter(Boolean).length;
380
+ return s.steps - s.lastCheck >= PULL_GAP && (sinceWrite >= PULL_SINCE_WRITE || failing >= PULL_FAILURES);
381
+ }
382
+ progress(sessionID) {
383
+ const s = this.#sessions.get(sessionID);
384
+ if (!s)
385
+ return undefined;
386
+ const tail = s.calls.slice(-12);
387
+ // newFiles: distinct paths first touched since the last checkpoint.
388
+ let newFiles = 0;
389
+ for (const p of s.readPaths)
390
+ if (!s.checkpointReadPaths.has(p))
391
+ newFiles++;
392
+ // repeats: max occurrences of one combined signature in the ring buffer.
393
+ const counts = new Map();
394
+ for (const e of s.ring)
395
+ counts.set(e, (counts.get(e) ?? 0) + 1);
396
+ let repeats = 0;
397
+ for (const v of counts.values())
398
+ if (v > repeats)
399
+ repeats = v;
400
+ // cycle over <=3 signatures?
401
+ const cycle = detectCycle(s.ring);
402
+ const filesTouched = [...new Set([...s.readPaths, ...s.writtenPaths])];
403
+ const repeatDetail = (repeats >= 2 || cycle)
404
+ ? (s.lastRepeatedCount && s.lastRepeatedInput
405
+ ? formatRepeat(s.lastRepeatedInput.tool, s.lastRepeatedInput.input, s.lastRepeatedCount)
406
+ : (s.lastRepeatedKey ? `${s.lastRepeatedKey} ${repeats}x` : undefined))
407
+ : undefined;
408
+ return {
409
+ steps: s.steps,
410
+ calls: s.calls.length,
411
+ writes: s.writes,
412
+ callsSinceWrite: s.calls.length - 1 - s.lastWrite,
413
+ filesRead: s.readPaths.size,
414
+ newLines: s.newLines,
415
+ newFiles,
416
+ repeats,
417
+ cycle,
418
+ filesTouched,
419
+ repeatDetail,
420
+ lastCommand: s.lastCommand,
421
+ seenLines: s.seenLines,
422
+ seenLineHashes: s.seenLines,
423
+ recent: tail.map((c) => c.slice(0, 120)),
424
+ recentFailures: s.failed.slice(-12).filter(Boolean).length,
425
+ };
426
+ }
427
+ // One provider turn; messages as the context hook gives them (role + content parts).
428
+ onTurn(sessionID, messages) {
429
+ const s = this.#sessions.get(sessionID);
430
+ if (!s)
431
+ return undefined;
432
+ s.steps++;
433
+ if (s.steps > s.limits.maxSteps)
434
+ return { kind: "steps", detail: `more than ${s.limits.maxSteps} steps` };
435
+ if (!Array.isArray(messages))
436
+ return undefined;
437
+ const assistant = messages.filter((m) => m.role === "assistant");
438
+ const parts = (m) => (Array.isArray(m.content) ? m.content : []);
439
+ let silent = 0;
440
+ for (let i = assistant.length - 1; i >= 0 && !parts(assistant[i]).some((p) => p.type === "tool-call"); i--)
441
+ silent++;
442
+ // A nudge, not a stop: a worker that writes a long report in several messages was interrupted mid-report (live
443
+ // run, 2026-10-06), and three text turns say nothing about a loop.
444
+ if (silent >= s.limits.monologue)
445
+ return { kind: "monologue", severity: "nudge", detail: `${silent} replies in a row without a tool call` };
446
+ const last = assistant.at(-1);
447
+ const text = last ? normalize(parts(last).filter((p) => p.type === "text").map((p) => p.text ?? "").join(" ")) : "";
448
+ if (text.length > 40) {
449
+ if (s.texts.has(text))
450
+ return { kind: "repeat_text", detail: "the same answer text came again" };
451
+ if (s.texts.size >= MAX_TEXTS) {
452
+ const oldest = s.texts.values().next().value;
453
+ if (oldest !== undefined)
454
+ s.texts.delete(oldest);
455
+ }
456
+ s.texts.add(text);
457
+ }
458
+ return undefined;
459
+ }
460
+ }
461
+ // What a fresh session is told after the watchdog stopped (or nudged) the previous one.
462
+ export function handoffNote(signal, changed, progress) {
463
+ const what = signal.severity === "nudge" ? "drew a nudge from the loop watchdog, not a stop" : "was stopped by the loop watchdog";
464
+ const digest = [
465
+ "Digest:",
466
+ `Files touched: ${changed.join(", ") || (progress?.filesTouched?.join(", ") ?? "none")}`,
467
+ `Learned: ${progress?.newLines ?? 0} new lines, ${progress?.newFiles ?? 0} new files`,
468
+ `Last command: ${progress?.lastCommand ?? "none"}`,
469
+ ].join("\n");
470
+ return [
471
+ `A previous attempt at this task ${what}: ${signal.detail}.`,
472
+ changed.length ? `Files already changed in this directory: ${changed.join(", ")}. Check them instead of starting over.` : "No file was changed yet.",
473
+ digest,
474
+ "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.",
475
+ ].join("\n");
476
+ }
@@ -0,0 +1,43 @@
1
+ // modern-web-guidance as a skill agents can use (Google Chrome, Apache-2.0; installed by creative-tools.ts at its pin).
2
+ // The upstream skill tells an agent to run `npx -y modern-web-guidance@latest …` for every web task: that fetches and
3
+ // runs whatever version is newest, over the network, every time. omacode installs one pinned, checksum-checked copy
4
+ // and registers an adapted skill instead (Apache-2.0 §4: the change is stated in the skill itself):
5
+ //
6
+ // - every `npx -y modern-web-guidance@latest` becomes `node "<copy>/modern-web.mjs"`: local, pinned, offline;
7
+ // - the section on npx, pnpx and asking for network access is dropped (none is needed);
8
+ // - "MANDATORY … Do NOT skip" becomes a plain instruction, and a note asks for features that are Baseline widely
9
+ // available unless the user targets newer browsers (each guide states its support and a fallback).
10
+ //
11
+ // search and retrieve report nothing to Google; the commands that would (install, update, list, legacy-scan) run with
12
+ // DISABLE_TELEMETRY=1 in every agent shell (core/telemetry.ts).
13
+ import { existsSync, readFileSync } from "node:fs";
14
+ import { join } from "node:path";
15
+ import { home, PINS, webGuidanceDir } from "./creative-tools.js";
16
+ export const WEB_GUIDANCE_SKILL = "modern-web-guidance";
17
+ const NOTE = (dir) => `> Adapted by omacode from modern-web-guidance ${PINS.webGuidance} (Google Chrome, Apache-2.0; licence in ${dir}/LICENSE):
18
+ > the commands run the pinned local copy instead of \`npx … @latest\`, which needs no network; the npx section is left
19
+ > out. Prefer features that are Baseline widely available unless the user targets newer browsers: every guide states
20
+ > its browser support and gives a fallback.`;
21
+ export function adaptGuidance(text, dir) {
22
+ const cli = `node "${join(dir, "modern-web.mjs")}"`;
23
+ let out = text
24
+ .replace(/npx -y modern-web-guidance@latest/g, cli)
25
+ .replace(/npx modern-web-guidance@latest/g, cli)
26
+ .replace(/Run `modern-web-guidance` directly with `npx`/g, "Run the local `modern-web-guidance` (the command below)")
27
+ .replace(/MANDATORY: Execute FIRST for all HTML\/CSS and clientside JS tasks\. Do NOT skip — web APIs evolve rapidly and training weights contain obsolete patterns\./, "Use it first for HTML/CSS and client-side JS work: web APIs evolve rapidly and training data contains obsolete patterns.");
28
+ // The section about running it through npx/pnpx and asking for network access: not needed for the local copy.
29
+ out = out.replace(/\n## Using npx \/ pnpx\n[\s\S]*?(?=\n## )/, "\n");
30
+ // The note goes right after the front matter.
31
+ const end = out.indexOf("\n---", 3);
32
+ return end > 0 ? `${out.slice(0, end + 4)}\n\n${NOTE(dir)}\n${out.slice(end + 4)}` : `${NOTE(dir)}\n\n${out}`;
33
+ }
34
+ // The skill when the copy is installed, else nothing (it is an optional part).
35
+ export function webGuidanceSkill(h = home()) {
36
+ const dir = webGuidanceDir(h);
37
+ const path = join(dir, "SKILL.md");
38
+ if (!existsSync(path) || !existsSync(join(dir, "modern-web.mjs")))
39
+ return undefined;
40
+ const content = adaptGuidance(readFileSync(path, "utf8"), dir);
41
+ const description = /^description:\s*\|?\s*\n?\s*(.+)$/m.exec(content)?.[1]?.trim() ?? "modern web development best practices, searched offline";
42
+ return { name: WEB_GUIDANCE_SKILL, description, path, content };
43
+ }
package/dist/which.js ADDED
@@ -0,0 +1,20 @@
1
+ // "Installed" has one meaning in this plugin: a file of that name on PATH. browser.ts used this test for ffmpeg and
2
+ // ffprobe; backends.ts asks it about the optional local decision servers (A2-T1), so the test lives in one place.
3
+ import { statSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ export function findTool(name, env = process.env) {
6
+ const exts = process.platform === "win32" ? [".exe", ".cmd", ""] : [""];
7
+ for (const dir of (env.PATH ?? "").split(":").filter(Boolean)) {
8
+ for (const ext of exts) {
9
+ const file = join(dir, name + ext);
10
+ try {
11
+ if (statSync(file).isFile())
12
+ return file;
13
+ }
14
+ catch {
15
+ // not here
16
+ }
17
+ }
18
+ }
19
+ return undefined;
20
+ }