@0perator/operator 0.1.285 → 0.1.313

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 (98) hide show
  1. package/README.md +24 -2
  2. package/dist/acp/agent.js +2 -1
  3. package/dist/acp/config-options.js +3 -1
  4. package/dist/acp/tool-map.js +2 -1
  5. package/dist/auth/commands.js +69 -13
  6. package/dist/autonomy/agent-cli.js +304 -0
  7. package/dist/autonomy/cloud-agent.js +439 -0
  8. package/dist/autonomy/cron-lifecycle.js +78 -0
  9. package/dist/autonomy/cron-lock.js +121 -0
  10. package/dist/autonomy/cron.js +216 -43
  11. package/dist/autonomy/delegate.js +5 -1
  12. package/dist/autonomy/incidents.js +135 -0
  13. package/dist/autonomy/session-factory.js +25 -16
  14. package/dist/background/index.js +40 -0
  15. package/dist/bus/inbox.js +20 -0
  16. package/dist/classifier/config.js +47 -0
  17. package/dist/classifier/modes.js +41 -0
  18. package/dist/classifier/types.js +1 -0
  19. package/dist/cli.js +529 -53
  20. package/dist/config/features.js +69 -0
  21. package/dist/config/persona.js +118 -99
  22. package/dist/config/scaffold.js +15 -0
  23. package/dist/config/settings.js +96 -6
  24. package/dist/consolidation/sleep.js +73 -11
  25. package/dist/engine/agent.js +275 -18
  26. package/dist/engine/anthropic-chat.js +343 -0
  27. package/dist/engine/aurora.js +101 -13
  28. package/dist/engine/batch-scheduler.js +41 -9
  29. package/dist/engine/classifier.js +85 -0
  30. package/dist/engine/compaction.js +24 -5
  31. package/dist/engine/fast-start.js +25 -0
  32. package/dist/engine/loop-guard.js +448 -0
  33. package/dist/engine/net-error.js +24 -0
  34. package/dist/engine/repetition-guard.js +180 -0
  35. package/dist/engine/selfheal.js +8 -0
  36. package/dist/engine/toolcalls.js +51 -1
  37. package/dist/engine/verify-gate.js +2 -0
  38. package/dist/flywheel/processor.js +78 -31
  39. package/dist/flywheel/srft.js +13 -0
  40. package/dist/hooks/index.js +196 -0
  41. package/dist/mcp/config.js +21 -1
  42. package/dist/memory/index.js +0 -0
  43. package/dist/memory/providers.js +210 -0
  44. package/dist/memory/session-catalog.js +422 -0
  45. package/dist/memory/session-providers.js +121 -0
  46. package/dist/memory/session-sources.js +335 -0
  47. package/dist/memory/skylark.js +131 -0
  48. package/dist/models/bench.js +103 -0
  49. package/dist/models/registry.js +144 -0
  50. package/dist/models/switch.js +69 -0
  51. package/dist/observability/blackbox.js +37 -0
  52. package/dist/permissions/policy.js +31 -6
  53. package/dist/router/discovery.js +127 -0
  54. package/dist/router/models.js +107 -16
  55. package/dist/router/portal.js +100 -0
  56. package/dist/router/router.js +1 -1
  57. package/dist/services/preflight.js +55 -7
  58. package/dist/session.js +316 -46
  59. package/dist/tools/chauffeur.js +12 -0
  60. package/dist/tools/executor.js +19 -9
  61. package/dist/tools/find-files.js +483 -0
  62. package/dist/tools/git-pr.js +94 -0
  63. package/dist/tools/incident-tools.js +82 -0
  64. package/dist/tools/memory.js +12 -2
  65. package/dist/tools/registry.js +281 -85
  66. package/dist/tools/semantic-compress.js +124 -0
  67. package/dist/tools/shell-context.js +1 -0
  68. package/dist/tools/shell-jobs.js +160 -0
  69. package/dist/tools/shell-session.js +170 -4
  70. package/dist/tools/wave-tools.js +609 -0
  71. package/dist/tools/wave2-tools.js +411 -0
  72. package/dist/ui/App.js +15 -4
  73. package/dist/ui/BgPanel.js +30 -6
  74. package/dist/ui/Composer.js +11 -1
  75. package/dist/ui/QuestionPrompt.js +31 -11
  76. package/dist/ui/SessionPicker.js +86 -0
  77. package/dist/ui/StatusRule.js +5 -5
  78. package/dist/ui/ToolStep.js +2 -1
  79. package/dist/ui/Transcript.js +17 -1
  80. package/dist/ui/index.js +1 -1
  81. package/dist/ui/liveTools.js +21 -3
  82. package/dist/ui/slashCommands.js +2 -0
  83. package/dist/util/screenshots.js +74 -8
  84. package/dist/util/slash.js +2 -2
  85. package/package.json +8 -2
  86. package/dist/engine/cli.js +0 -1171
  87. package/dist/router/models.js.bak +0 -78
  88. package/dist/router/models.js.bak-1791259923 +0 -78
  89. package/dist/router/models.js.bak-pre-gateway +0 -78
  90. package/dist/router/models.js.bak-pre-patch2 +0 -78
  91. package/dist/router/models.js.bak2 +0 -78
  92. package/dist/services/model-autodetect.js +0 -240
  93. package/dist/tools/native-redirect.js +0 -140
  94. package/dist/tools/power-tools.js +0 -627
  95. package/dist/tools/registry.js.bak-1791259948 +0 -1914
  96. package/dist/tools/registry.js.bak-pre-plugins +0 -1914
  97. package/dist/ui/BusTray.js +0 -70
  98. package/dist/ui/resize.js +0 -160
@@ -0,0 +1,180 @@
1
+ // Degenerate-repetition detection for model output, completed or still streaming. Pure functions, no I/O.
2
+ //
3
+ // A model stuck in a repetition loop can spend its whole output budget echoing one fragment; the
4
+ // finish_reason=length continuation then stitches that into the reply with a "continue" nudge and re-seeds
5
+ // the loop on the next request. These checks let the engine abort the round BEFORE any nudge and keep the
6
+ // looped bytes out of history. Deliberately conservative: only LONG exact repeats covering a majority of
7
+ // the text trip it, so asked-for repetition (a table of similar rows, "say X 50 times") is delivered.
8
+ /** Below this length the check does not run: short truncations trivially contain repeated tokens. */
9
+ export const MIN_FRAGMENT_LENGTH = 400;
10
+ const REPEAT_WINDOW = 60; // exact-repeat window, far beyond ordinary phrasing reuse (citations, headings, similar code)
11
+ const MIN_REPEAT_COUNT = 5; // a window repeating at least this often is a signal even for short fragments
12
+ const DOMINANCE_RATIO = 0.5; // "repetition-dominated" = repeated windows cover at least this fraction
13
+ const MAX_ANCHOR_SAMPLES = 32; // bounds keep the periodic scan linear in output size
14
+ const MAX_ANCHOR_MATCHES = 8;
15
+ const RUNAWAY_DISTINCT_LINE_RATIO = 0.5; // batch-style output shares prefixes but every line is distinct; a loop re-emits lines
16
+ /** A COMPLETED answer is only discarded at runaway scale: real stop-path loops run 80k-350k chars, while
17
+ * asked-for repeats stay in the low KB. */
18
+ export const STOP_PATH_MIN_CHARS = 16_000;
19
+ /** A live stream is judged on at most this much of its latest text, so one check stays bounded. */
20
+ export const STREAM_TAIL_CHARS = 4 * STOP_PATH_MIN_CHARS;
21
+ /** What history keeps INSTEAD of a looped reply, and what the user reads. Replaying the looped bytes would
22
+ * re-seed the loop; the model only needs to know the reply degenerated and was cut off. */
23
+ export const REPETITION_INTERRUPTED = "[stopped — the reply degenerated into a repetition loop and was interrupted, so I cut it off instead of continuing it. " +
24
+ "Nothing was lost; send your request again or ask me to continue and I'll take a different approach.]";
25
+ /** True when one normalized line, repeated, covers at least half of the text (the common echo shape). */
26
+ function lineRepetitionDominated(text, n) {
27
+ const counts = new Map();
28
+ for (const raw of text.split("\n")) {
29
+ const line = raw.trim();
30
+ if (line)
31
+ counts.set(line, (counts.get(line) ?? 0) + 1);
32
+ }
33
+ for (const [line, c] of counts)
34
+ if (c >= MIN_REPEAT_COUNT && c * line.length >= n * DOMINANCE_RATIO)
35
+ return true;
36
+ return false;
37
+ }
38
+ /** True when one 60-char window recurs often enough to cover half of the text (catches loops whose repeats
39
+ * differ by a counter or a noise token). */
40
+ function windowCountDominated(text, n) {
41
+ const needed = Math.max(MIN_REPEAT_COUNT, Math.ceil((n * DOMINANCE_RATIO) / REPEAT_WINDOW));
42
+ const counts = new Map();
43
+ for (let i = 0; i + REPEAT_WINDOW <= n; i++) {
44
+ const key = text.slice(i, i + REPEAT_WINDOW);
45
+ const c = (counts.get(key) ?? 0) + 1;
46
+ if (c >= needed)
47
+ return true;
48
+ counts.set(key, c);
49
+ }
50
+ return false;
51
+ }
52
+ /** Expand one known-equal window to the [left, right) bounds of its exact periodic run. */
53
+ function expandRun(text, n, start, period, matched) {
54
+ let left = start;
55
+ while (left > 0 && text[left - 1] === text[left - 1 + period])
56
+ left--;
57
+ let right = start + matched;
58
+ while (right + period < n && text[right] === text[right + period])
59
+ right++;
60
+ return [left, right + period];
61
+ }
62
+ /** Detect a dominant exact periodic run from evenly spaced anchors. Matching a 60-char anchor at a later
63
+ * position supplies a candidate period; expanding recovers the whole run, so a long multi-line loop unit is
64
+ * credited with its true period instead of 60 chars per occurrence. */
65
+ function periodicRunDominated(text, n) {
66
+ const maxStart = n - REPEAT_WINDOW;
67
+ if (maxStart < 1)
68
+ return false;
69
+ const step = Math.max(1, Math.floor((maxStart + MAX_ANCHOR_SAMPLES - 2) / (MAX_ANCHOR_SAMPLES - 1)));
70
+ const starts = [];
71
+ for (let s = 0; s <= maxStart; s += step)
72
+ starts.push(s);
73
+ if (starts[starts.length - 1] !== maxStart)
74
+ starts.push(maxStart);
75
+ const rejected = []; // runs already expanded and rejected: (left, right, period)
76
+ for (const start of starts) {
77
+ const anchor = text.slice(start, start + REPEAT_WINDOW);
78
+ let from = start + 1;
79
+ for (let k = 0; k < MAX_ANCHOR_MATCHES; k++) {
80
+ const match = text.indexOf(anchor, from);
81
+ if (match < 0)
82
+ break;
83
+ const period = match - start;
84
+ from = match + 1;
85
+ if (rejected.some(([lo, hi, p]) => lo <= start && start < hi && period % p === 0))
86
+ continue;
87
+ const [left, right] = expandRun(text, n, start, period, REPEAT_WINDOW);
88
+ if (right - left >= MIN_REPEAT_COUNT * period && right - left >= n * DOMINANCE_RATIO)
89
+ return true;
90
+ rejected.push([left, right, period]);
91
+ }
92
+ }
93
+ return false;
94
+ }
95
+ /** True when a contiguous run of at least five exact repetitions covers at least half of `text`. Fails open
96
+ * (false) for short or non-string input. */
97
+ export function isRepetitionDominated(text) {
98
+ if (typeof text !== "string")
99
+ return false;
100
+ const n = text.length;
101
+ if (n < MIN_FRAGMENT_LENGTH)
102
+ return false;
103
+ return lineRepetitionDominated(text, n) || windowCountDominated(text, n) || periodicRunDominated(text, n);
104
+ }
105
+ /** Stricter than isRepetitionDominated, for the paths that DISCARD the text: when it has line structure, at
106
+ * most half of its non-empty lines may be distinct, so distinct batch rows are never dropped. */
107
+ export function isRunawayRepetition(text) {
108
+ if (!isRepetitionDominated(text))
109
+ return false;
110
+ const lines = text.split("\n").map((l) => l.trim()).filter(Boolean);
111
+ if (lines.length < MIN_REPEAT_COUNT)
112
+ return true; // no line structure to judge by: a dominated single-line loop
113
+ return new Set(lines).size <= lines.length * RUNAWAY_DISTINCT_LINE_RATIO;
114
+ }
115
+ /** Judge one COMPLETED model reply. `stopReason` is the transport's verdict: "repetition" means the decode
116
+ * breaker already cut it; "length" means the reply was truncated and would be continued, so the cheap
117
+ * dominance test is enough; anything else is a finished answer and only runaway scale discards it. */
118
+ export function isDegenerateReply(text, stopReason) {
119
+ if (stopReason === "repetition")
120
+ return true;
121
+ if (stopReason === "length")
122
+ return isRepetitionDominated(text);
123
+ return text.length >= STOP_PATH_MIN_CHARS && isRunawayRepetition(text);
124
+ }
125
+ /** The runaway criterion applied WHILE one channel (visible text or reasoning) streams. A stream that keeps
126
+ * producing never reaches a completion check. The first check runs at STOP_PATH_MIN_CHARS and the gap doubles
127
+ * until it reaches one tail window, then stays there; each check reads only the tail, so total work stays
128
+ * linear in the output and the watch never holds more than two tail windows plus the latest delta. */
129
+ export class RunawayStreamWatch {
130
+ parts = [];
131
+ chars = 0;
132
+ nextCheck = STOP_PATH_MIN_CHARS;
133
+ /** Add one delta; true once the channel has become a runaway loop. */
134
+ feed(text) {
135
+ if (!text)
136
+ return false;
137
+ this.parts.push(text);
138
+ this.chars += text.length;
139
+ if (this.chars < this.nextCheck)
140
+ return false;
141
+ this.nextCheck = this.chars + Math.min(this.chars, STREAM_TAIL_CHARS);
142
+ const tail = this.parts.join("").slice(-STREAM_TAIL_CHARS);
143
+ this.parts = [tail];
144
+ return isRunawayRepetition(tail);
145
+ }
146
+ }
147
+ /** Per-round reasoning budget, in characters. RunawayStreamWatch only catches a REPETITION spiral (the same
148
+ * fragment echoed); it misses "going in circles" — a long chain of NEW-but-circular reasoning that keeps
149
+ * theorizing instead of acting (observed: one round reasoned ~24k tokens without a tool call). A round that
150
+ * reasons past this budget without ending in an action is almost always that spiral. ~50k chars ≈ 12.5k
151
+ * tokens of reasoning in ONE round with no tool call — generous enough that deep/ultrathink reasoning never
152
+ * trips it, tight enough to cut an hour-long circle. */
153
+ // 2026-10-19: raised 50k → 400k chars (~100k tokens) and env-overridable (KODE_REASONING_BUDGET_CHARS; 0
154
+ // disables). Aurora is a thinking model and a long autonomous step can legitimately reason at length before
155
+ // acting; the old 50k budget aborted that reasoning MID-STREAM, which surfaced as a cut-off tool call. The
156
+ // round-level think-spiral latch (agent.ts, across rounds) still catches a genuine never-acts spiral, so this
157
+ // mid-stream backstop can be generous without reintroducing an infinite reasoning loop.
158
+ export const REASONING_BUDGET_CHARS = Number(process.env.KODE_REASONING_BUDGET_CHARS ?? 400_000);
159
+ /** What the turn keeps INSTEAD of a reasoning spiral. Unlike a repetition loop the reasoning isn't garbage —
160
+ * the model just won't stop thinking and act — so the note is a RESET directive, not just "I cut it off". */
161
+ export const REASONING_BUDGET_INTERRUPTED = "[stopped — I reasoned a long time in one step without acting (going in circles). Reset: state the " +
162
+ "one-line root cause and the single smallest next experiment, then DO it — and reuse an existing " +
163
+ "tool/pattern instead of building from scratch. Ask me to continue and I'll take that concrete step.]";
164
+ /** Trips once a single round's reasoning stream exceeds `budgetChars`. A FRESH watch per round (agent.ts)
165
+ * means it measures reasoning since the last action, so a tool call resets it — it fires only on a round
166
+ * that thinks a great deal and never acts. `budgetChars <= 0` disables it. */
167
+ export class ReasoningBudgetWatch {
168
+ budgetChars;
169
+ chars = 0;
170
+ constructor(budgetChars = REASONING_BUDGET_CHARS) {
171
+ this.budgetChars = budgetChars;
172
+ }
173
+ /** Add one reasoning delta; true once this round's reasoning has exceeded the budget. */
174
+ feed(text) {
175
+ if (!text || this.budgetChars <= 0)
176
+ return false;
177
+ this.chars += text.length;
178
+ return this.chars > this.budgetChars;
179
+ }
180
+ }
@@ -15,6 +15,12 @@ const CTX_RE = /context|n_ctx|exceed|too long|too many tokens|maximum context|ou
15
15
  // JSON at position …". This is NOT a busy backend — failing over just truncates the same write on the
16
16
  // next endpoint — so it gets its own class: nudge the model to chunk the write and retry in place.
17
17
  const TRUNC_TOOL_RE = /parse tool call arguments|unterminated string|missing closing quote/i;
18
+ // Our OWN client-side stream aborts (aurora.ts): the idle-gap guard tore down a wedged decode, or the
19
+ // degraded-decode guard tore down a CPU-fallback-slow one. Neither carries an HTTP status (they're health
20
+ // signals, not server replies), so they'd already self-classify transient via the no-status default — but
21
+ // name them explicitly so recovery stays transient (mark-unhealthy + fail over) even if the message ever
22
+ // carries an incidental 3-digit number that statusOf() would otherwise misread.
23
+ const DEGRADED_RE = /decode wedged|endpoint degraded|stream stalled/i;
18
24
  // When an endpoint rejects a request for exceeding its window, its error body carries the REAL window it
19
25
  // enforces — aurora /v1 returns {"type":"exceed_context_size_error","n_ctx":65536,...} plus the human
20
26
  // "exceeds the available context size (65536 tokens)". The configured ctxWindow is often optimistic (a
@@ -42,6 +48,8 @@ function statusOf(err) {
42
48
  export function classifyFailure(err) {
43
49
  const s = statusOf(err);
44
50
  const msg = err instanceof Error ? err.message : String(err);
51
+ if (DEGRADED_RE.test(msg))
52
+ return "transient"; // our own wedged/degraded-decode stream abort → fail over
45
53
  if (s === 401 || s === 403)
46
54
  return "auth"; // credentials — resending never helps
47
55
  // The model's own tool-call JSON was truncated mid-arguments → server can't parse it. Recover by
@@ -1,3 +1,16 @@
1
+ const CALL_TAG = /<\/?tool_call>|<function=[^>]*>|<\/function>|<parameter=[^>]*>|<\/parameter>/g;
2
+ /** Remove tool-call debris from prose: an unclosed `<tool_call>` swallows the rest of the text (it is the call's
3
+ * body, cut off), and stray open/close tags with no pair are dropped. Returns the cleaned text and whether
4
+ * anything was found. */
5
+ function stripCallFragments(text) {
6
+ let found = false;
7
+ // Fenced code blocks are real content (a reply may quote this very markup): hide them while stripping.
8
+ const fences = [];
9
+ const hidden = text.replace(/```[\s\S]*?```/g, (f) => { fences.push(f); return `\u0000F${fences.length - 1}\u0000`; });
10
+ let out = hidden.replace(/<tool_call>[\s\S]*$/g, () => { found = true; return ""; });
11
+ out = out.replace(CALL_TAG, () => { found = true; return ""; });
12
+ return { text: out.replace(/\u0000F(\d+)\u0000/g, (_m, i) => fences[Number(i)]), found };
13
+ }
1
14
  /** Coerce a raw XML parameter value string to its likely JSON type. */
2
15
  function coerceParamValue(raw) {
3
16
  const t = raw.trim();
@@ -86,6 +99,27 @@ function buildToolCall(name, args) {
86
99
  function: { name, arguments: typeof args === "string" ? args : JSON.stringify(args ?? {}) },
87
100
  };
88
101
  }
102
+ /**
103
+ * Always-on prose hygiene for assistant content that ships to the UI/history. A model can emit STRUCTURED
104
+ * tool_calls (parsed by the server) and STILL leak the tool-call/thinking delimiter tags into `content` — the
105
+ * trailing `</parameter></function></tool_call>` or a stray `</thinking>` seen live. The text-recovery path
106
+ * (recoverToolCalls) cleans those, but the structured-tool_calls path stored content raw, so they rendered.
107
+ * This strips the structural debris WITHOUT extracting calls (the structured calls already ran — recovering
108
+ * here would double-dispatch). Fenced code blocks are preserved verbatim (a reply may legitimately quote this
109
+ * markup). Use recoverToolCalls when there are NO structured calls; use this whenever content ships.
110
+ */
111
+ export function cleanAssistantProse(content) {
112
+ if (!content)
113
+ return content;
114
+ const fences = [];
115
+ let out = content.replace(/```[\s\S]*?```/g, (f) => { fences.push(f); return `\u0000F${fences.length - 1}\u0000`; });
116
+ out = out.replace(/<\/?think(?:ing)?>/gi, ""); // leaked reasoning-channel delimiters
117
+ out = out.replace(/<tool_call>[\s\S]*$/g, ""); // an unclosed opener is the cut-off call body
118
+ out = out.replace(CALL_TAG, ""); // stray open/close tool-call tags
119
+ out = out.replace(/<function>|<parameter>/g, ""); // attribute-less openers (not covered by CALL_TAG)
120
+ out = out.replace(/\u0000F(\d+)\u0000/g, (_m, i) => fences[Number(i)]);
121
+ return out.replace(/\n{3,}/g, "\n\n").trim();
122
+ }
89
123
  /**
90
124
  * Extract tool calls emitted as text. Removes every recognized span from the content so
91
125
  * `cleanedContent` is safe to show/store as the assistant's prose.
@@ -120,6 +154,21 @@ export function recoverToolCalls(content) {
120
154
  remaining += m[0]; // unrecognized — leave it visible rather than silently eating it
121
155
  }
122
156
  remaining += content.slice(cursor);
157
+ // Pass 1b: a Qwen XML <function=NAME>...</function> whose <tool_call> opener went missing (the opener can land in
158
+ // the reasoning channel while the rest streams as content).
159
+ const bareFn = /<function=([^>]+)>([\s\S]*?)<\/function>/g;
160
+ let bare = "";
161
+ let bareCursor = 0;
162
+ while ((m = bareFn.exec(remaining))) {
163
+ const xml = parseQwenXmlFunction(m[0]);
164
+ if (!xml)
165
+ continue;
166
+ bare += remaining.slice(bareCursor, m.index);
167
+ bareCursor = m.index + m[0].length;
168
+ calls.push(buildToolCall(xml.name, xml.args));
169
+ }
170
+ if (bareCursor > 0)
171
+ remaining = bare + remaining.slice(bareCursor);
123
172
  // Pass 2: fenced ```json / ```tool_call blocks.
124
173
  let afterFences = "";
125
174
  cursor = 0;
@@ -160,5 +209,6 @@ export function recoverToolCalls(content) {
160
209
  }
161
210
  }
162
211
  final += afterFences.slice(cursor);
163
- return { calls, cleanedContent: final.replace(/\n{3,}/g, "\n\n").trim() };
212
+ const stripped = stripCallFragments(final);
213
+ return { calls, cleanedContent: stripped.text.replace(/\n{3,}/g, "\n\n").trim(), malformed: stripped.found };
164
214
  }
@@ -47,6 +47,8 @@ export function ranButFailed(result) {
47
47
  return Number(m[1]) !== 0;
48
48
  if (/timed out after \d+ms/.test(result))
49
49
  return true;
50
+ if (/^moved to background as /.test(result.trim()))
51
+ return true; // ctrl+b: the command had not finished, so nothing was verified
50
52
  if (/^error running command:/i.test(result.trim()))
51
53
  return true;
52
54
  return false;
@@ -6,8 +6,13 @@ import { join, dirname } from "node:path";
6
6
  // ---------------------------------------------------------------------------
7
7
  // SRFT (Step Rejection Fine-Tuning) — per-step masking for trajectories
8
8
  // ---------------------------------------------------------------------------
9
- import { applySRFTMask } from "./srft.js";
10
- export { applySRFTMask } from "./srft.js"; // one import surface for existing consumers
9
+ import { applySRFTMask, isPromotable, DEFAULT_SCORE_THRESHOLD } from "./srft.js";
10
+ export { applySRFTMask, isPromotable } from "./srft.js"; // one import surface for existing consumers
11
+ /** The reward-score promotion threshold in effect: KODE_FLYWHEEL_SCORE_THRESHOLD if set, else the default. */
12
+ export function scoreThreshold() {
13
+ const n = Number(process.env.KODE_FLYWHEEL_SCORE_THRESHOLD);
14
+ return Number.isFinite(n) ? n : DEFAULT_SCORE_THRESHOLD;
15
+ }
11
16
  /** Run a mutation check on a verified turn.
12
17
  * Stashes the worktree, reverts the diff, runs verify_command.
13
18
  * If the suite still passes, the tests are vacuous (they don't test the change). */
@@ -63,41 +68,80 @@ export async function runMutationCheck(cwd, verifyCommand, diffSha) {
63
68
  };
64
69
  }
65
70
  }
66
- /** Run a single eval task. Returns the result. */
71
+ /** Run ONE eval task end-to-end: generate with the model, APPLY its output, then verify by EXIT CODE.
72
+ * This is the real loop the old harness faked — it never called the model (line 124 TODO) and graded on a
73
+ * gameable `output.includes("pass")`. Here: the model actually runs, its code is written to disk, and the
74
+ * verify command's exit status (execSync throws on non-zero) is the pass/fail — a metric you cannot spell
75
+ * your way past. A model or verify failure is an honest fail, not a crash. */
67
76
  export async function runEvalTask(task, modelFn) {
68
77
  const startTime = Date.now();
78
+ const fin = (passed, detail) => ({
79
+ taskId: task.id, passed, detail: detail.slice(0, 500), durationMs: Date.now() - startTime, timestamp: Date.now(),
80
+ });
81
+ let output;
82
+ try {
83
+ output = await modelFn(task.description); // actually run the model (was never called before)
84
+ }
85
+ catch (e) {
86
+ return fin(false, `model error: ${e instanceof Error ? e.message : String(e)}`);
87
+ }
69
88
  try {
70
- // Apply the "after" state
71
89
  const { execSync } = await import("node:child_process");
72
- // Restore to before state
73
- execSync(`git checkout ${task.beforeState} -- .`, { cwd: task.cwd, stdio: "pipe" });
74
- // Apply the model's output (diff, file writes, etc.)
75
- // This is where the harness would apply the model's generated changes
76
- // For now, we assume the changes are already applied and we verify them
77
- const verifyOutput = execSync(task.verifyCommand, {
78
- cwd: task.cwd,
79
- encoding: "utf8",
80
- timeout: task.timeoutMs ?? 120000,
81
- stdio: "pipe",
82
- });
83
- const passed = verifyOutput.includes("pass") || verifyOutput.includes("PASSED") || verifyOutput.includes("0 failing");
84
- return {
85
- taskId: task.id,
86
- passed,
87
- detail: verifyOutput.slice(0, 500),
88
- durationMs: Date.now() - startTime,
89
- timestamp: Date.now(),
90
- };
90
+ const { writeFileSync, mkdirSync } = await import("node:fs");
91
+ const { join, dirname } = await import("node:path");
92
+ if (task.outputFile) {
93
+ const dest = join(task.cwd, task.outputFile);
94
+ mkdirSync(dirname(dest), { recursive: true });
95
+ writeFileSync(dest, output, "utf8"); // apply the model's output so verify runs against it
96
+ }
97
+ // PASS = exit 0. execSync throws on a non-zero exit, which the catch turns into an honest fail.
98
+ execSync(task.verifyCommand, { cwd: task.cwd, timeout: task.timeoutMs ?? 120000, stdio: "pipe" });
99
+ return fin(true, "verify exited 0");
91
100
  }
92
101
  catch (e) {
93
- return {
94
- taskId: task.id,
95
- passed: false,
96
- detail: e instanceof Error ? e.message : String(e),
97
- durationMs: Date.now() - startTime,
98
- timestamp: Date.now(),
99
- };
102
+ return fin(false, e instanceof Error ? e.message : String(e));
103
+ }
104
+ }
105
+ /** A minimal, fixed, REAL task set — each task makes the model produce a file whose correctness is decided
106
+ * by running it (node exits non-zero on a wrong answer). Tiny by design: one tracked, moving number beats
107
+ * five unused subsystems. `workdir` must be writable; the suite points it at a temp dir. */
108
+ export function builtinEvalTasks(workdir) {
109
+ return [
110
+ {
111
+ id: "add-two-numbers",
112
+ description: "Write a JavaScript ES module that exports a function `add(a, b)` returning their sum. Output ONLY the module source, no fences, no prose.",
113
+ outputFile: "add.mjs",
114
+ cwd: workdir,
115
+ verifyCommand: `node --input-type=module -e "import('file://${workdir}/add.mjs').then(m=>{if(m.add(2,3)!==5||m.add(-1,1)!==0)process.exit(1)})"`,
116
+ },
117
+ {
118
+ id: "reverse-string",
119
+ description: "Write a JavaScript ES module that exports a function `reverse(s)` returning the string reversed. Output ONLY the module source, no fences, no prose.",
120
+ outputFile: "reverse.mjs",
121
+ cwd: workdir,
122
+ verifyCommand: `node --input-type=module -e "import('file://${workdir}/reverse.mjs').then(m=>{if(m.reverse('abc')!=='cba')process.exit(1)})"`,
123
+ },
124
+ ];
125
+ }
126
+ /** Run a whole suite, aggregate, and append the pass-rate to a JSONL log so the metric MOVES OVER TIME —
127
+ * the before/after a self-improvement claim is unfalsifiable without. Logging is best-effort. */
128
+ export async function runEvalSuite(tasks, modelFn, logPath) {
129
+ const results = [];
130
+ for (const task of tasks)
131
+ results.push(await runEvalTask(task, modelFn));
132
+ const report = aggregateEvalResults(results);
133
+ if (logPath) {
134
+ try {
135
+ const { appendFileSync, mkdirSync } = await import("node:fs");
136
+ const { dirname } = await import("node:path");
137
+ mkdirSync(dirname(logPath), { recursive: true });
138
+ appendFileSync(logPath, JSON.stringify({
139
+ ts: report.timestamp, total: report.total, passed: report.passed, passRate: report.passRate,
140
+ }) + "\n", "utf8");
141
+ }
142
+ catch { /* logging is best-effort — never fail a suite over it */ }
100
143
  }
144
+ return report;
101
145
  }
102
146
  /** Run a suite of eval tasks. Returns aggregate results. */
103
147
  export function aggregateEvalResults(results) {
@@ -165,6 +209,7 @@ export class FlywheelProcessor {
165
209
  }
166
210
  const files = readdirSync(flywheelDir).filter(f => f.endsWith(".jsonl"));
167
211
  const allRows = [];
212
+ const threshold = scoreThreshold();
168
213
  for (const file of files) {
169
214
  const filepath = join(flywheelDir, file);
170
215
  const raw = readFileSync(filepath, "utf8");
@@ -172,7 +217,9 @@ export class FlywheelProcessor {
172
217
  for (const line of lines) {
173
218
  try {
174
219
  const row = JSON.parse(line);
175
- if (row.graded) {
220
+ // Promotion gate: a real reward score (written back by the scoring daemon) decides when present;
221
+ // until then fall back to the capture-time `graded` boolean. Replaces the bare `if (row.graded)`.
222
+ if (isPromotable(row, threshold)) {
176
223
  allRows.push(row);
177
224
  }
178
225
  }
@@ -1,3 +1,16 @@
1
+ /** Promotion threshold for a reward-model score. Skywork-Reward-V2 emits a signed logit; a non-negative
2
+ * score is the "good enough to train on" floor (dpo_pipeline.py treats >0 as the high side). Override with
3
+ * KODE_FLYWHEEL_SCORE_THRESHOLD. */
4
+ export const DEFAULT_SCORE_THRESHOLD = 0;
5
+ /** The promotion gate for a flywheel row. A REAL reward score, once the scoring daemon has written it onto
6
+ * the row, is the authority: promote iff `score >= threshold`. Until a score exists the gate falls back to
7
+ * the capture-time `graded` boolean (the safe default) so nothing in the loop stalls waiting for the daemon.
8
+ * Pure — no imports — so it is shared by the processor, the consolidation extractor, and tests alike. */
9
+ export function isPromotable(row, threshold = DEFAULT_SCORE_THRESHOLD) {
10
+ if (typeof row.score === "number" && Number.isFinite(row.score))
11
+ return row.score >= threshold;
12
+ return row.graded === true;
13
+ }
1
14
  /** Apply SRFT-style step masking to a trajectory.
2
15
  * Marks each step as productive (keep in loss) or harmful (mask from loss).
3
16
  * A step is harmful if:
@@ -0,0 +1,196 @@
1
+ // Hook subsystem — model-agnostic lifecycle hooks. User-defined shell commands fire on engine events
2
+ // (PreToolUse/PostToolUse/UserPromptSubmit/Stop/...), receive a JSON payload on stdin, and steer the run via
3
+ // exit code or JSON stdout. Uses the common agent-hooks contract, so an existing hooks config ports over.
4
+ // withHooks composes over any ToolExecutor like withPermissions: INERT (returns inner untouched) when no
5
+ // Pre/PostToolUse hooks are configured, so the default path has zero overhead.
6
+ import { spawn } from "node:child_process";
7
+ import { ownChild } from "../util/owned-children.js";
8
+ function matcherHits(matcher, toolName) {
9
+ if (matcher === undefined || matcher === "" || matcher === "*")
10
+ return true;
11
+ if (!toolName)
12
+ return true;
13
+ if (matcher === toolName)
14
+ return true;
15
+ try {
16
+ return new RegExp(matcher).test(toolName);
17
+ }
18
+ catch {
19
+ return matcher === toolName;
20
+ }
21
+ }
22
+ function runCommand(command, payload, timeoutMs, opts) {
23
+ return new Promise((resolve) => {
24
+ let settled = false;
25
+ const done = (r) => {
26
+ if (!settled) {
27
+ settled = true;
28
+ resolve(r);
29
+ }
30
+ };
31
+ let child;
32
+ try {
33
+ child = spawn(command, { shell: true, cwd: opts.cwd, env: process.env });
34
+ ownChild(child, "hook", { cmd: command, group: true }); // reaped on /exit so a slow hook can't outlive the session (group: shell may fork)
35
+ }
36
+ catch (e) {
37
+ done({ code: 1, stdout: "", stderr: e instanceof Error ? e.message : String(e) });
38
+ return;
39
+ }
40
+ let stdout = "";
41
+ let stderr = "";
42
+ const timer = setTimeout(() => {
43
+ try {
44
+ child.kill("SIGKILL");
45
+ }
46
+ catch {
47
+ /* already gone */
48
+ }
49
+ done({ code: 124, stdout, stderr: stderr + `\n[hook timed out after ${timeoutMs}ms]` });
50
+ }, timeoutMs);
51
+ child.stdout?.on("data", (d) => {
52
+ stdout += d.toString();
53
+ });
54
+ child.stderr?.on("data", (d) => {
55
+ stderr += d.toString();
56
+ });
57
+ child.on("error", (e) => {
58
+ clearTimeout(timer);
59
+ done({ code: 1, stdout, stderr: stderr + (e instanceof Error ? e.message : String(e)) });
60
+ });
61
+ child.on("close", (code) => {
62
+ clearTimeout(timer);
63
+ done({ code, stdout, stderr });
64
+ });
65
+ try {
66
+ child.stdin?.write(JSON.stringify(payload));
67
+ child.stdin?.end();
68
+ }
69
+ catch {
70
+ /* stdin may already be closed */
71
+ }
72
+ });
73
+ }
74
+ /** Interpret one hook's output under the standard hook contract. Returns a partial outcome; caller folds them. */
75
+ function interpret(event, r, opts) {
76
+ const out = r.stdout.trim();
77
+ // Structured JSON stdout takes precedence over the exit code (standard hook contract).
78
+ if (out.startsWith("{")) {
79
+ try {
80
+ const j = JSON.parse(out);
81
+ const hso = (j.hookSpecificOutput ?? {});
82
+ const systemMessage = typeof j.systemMessage === "string" ? j.systemMessage : undefined;
83
+ // continue:false is a hard stop for any event (standard contract).
84
+ if (j.continue === false) {
85
+ return { blocked: true, reason: typeof j.stopReason === "string" ? j.stopReason : systemMessage, systemMessage };
86
+ }
87
+ if (event === "PreToolUse") {
88
+ const pd = hso.permissionDecision ?? (j.decision === "block" ? "deny" : j.decision === "approve" ? "allow" : undefined);
89
+ if (pd === "deny")
90
+ return { blocked: true, reason: hso.permissionDecisionReason ?? j.reason ?? "denied by PreToolUse hook", systemMessage };
91
+ return { blocked: false, systemMessage };
92
+ }
93
+ if (event === "PostToolUse") {
94
+ if (j.decision === "block")
95
+ return { blocked: true, reason: j.reason ?? "flagged by PostToolUse hook", systemMessage };
96
+ return { blocked: false, context: hso.additionalContext, systemMessage };
97
+ }
98
+ // UserPromptSubmit / others: decision "block" stops; additionalContext (or raw stdout) is injected.
99
+ if (j.decision === "block")
100
+ return { blocked: true, reason: j.reason ?? "blocked by hook", systemMessage };
101
+ return { blocked: false, context: hso.additionalContext, systemMessage };
102
+ }
103
+ catch {
104
+ /* not valid JSON — fall through to exit-code handling */
105
+ }
106
+ }
107
+ // Exit-code contract: 2 = block (stderr → model); 0 = ok (stdout is context for the injecting events);
108
+ // anything else = non-blocking error (surface to the log, don't stop the run).
109
+ if (r.code === 2)
110
+ return { blocked: true, reason: r.stderr.trim() || out || "blocked by hook (exit 2)" };
111
+ if (r.code !== 0 && r.code !== null) {
112
+ if (r.stderr.trim())
113
+ opts.onLog?.(`[hook] exit ${r.code}: ${r.stderr.trim()}`);
114
+ return { blocked: false };
115
+ }
116
+ const inject = event === "UserPromptSubmit" || event === "PostToolUse" || event === "SessionStart";
117
+ return { blocked: false, context: inject && out ? out : undefined };
118
+ }
119
+ /** Run every matching hook for an event, fold outcomes: first block wins; otherwise concatenate context. */
120
+ export async function runHooks(event, payload, config, opts) {
121
+ const entries = config?.[event];
122
+ if (!entries || entries.length === 0)
123
+ return { blocked: false };
124
+ const full = {
125
+ session_id: opts.session,
126
+ transcript_path: opts.transcript,
127
+ cwd: opts.cwd,
128
+ hook_event_name: event,
129
+ ...payload,
130
+ };
131
+ const contexts = [];
132
+ const messages = [];
133
+ for (const entry of entries) {
134
+ if ((event === "PreToolUse" || event === "PostToolUse") && !matcherHits(entry.matcher, payload.tool_name))
135
+ continue;
136
+ for (const h of entry.hooks) {
137
+ if (h.type !== "command" || !h.command)
138
+ continue;
139
+ const r = await runCommand(h.command, full, Math.max(1, h.timeout ?? 60) * 1000, opts);
140
+ const o = interpret(event, r, opts);
141
+ if (o.systemMessage)
142
+ messages.push(o.systemMessage);
143
+ if (o.context)
144
+ contexts.push(o.context);
145
+ if (o.blocked) {
146
+ return { blocked: true, reason: o.reason, context: contexts.join("\n") || undefined, systemMessage: messages.join("\n") || undefined };
147
+ }
148
+ }
149
+ }
150
+ return { blocked: false, context: contexts.join("\n") || undefined, systemMessage: messages.join("\n") || undefined };
151
+ }
152
+ const DENIED_BY_HOOK = (name, reason) => `Blocked by a PreToolUse hook: "${name}" was not run.` + (reason ? `\nReason: ${reason}` : "");
153
+ /** Does this config have any tool-gating hooks? If not, withHooks is a no-op (keeps batch scheduling intact). */
154
+ function hasToolHooks(config) {
155
+ return !!(config && ((config.PreToolUse?.length ?? 0) > 0 || (config.PostToolUse?.length ?? 0) > 0));
156
+ }
157
+ /** Compose Pre/PostToolUse hooks over a ToolExecutor. Inert (returns inner) when no tool hooks are set, so the
158
+ * default path keeps the inner batch scheduler untouched. When active, calls run through the single-call path
159
+ * (Pre → inner.execute → Post), preserving input order. */
160
+ export function withHooks(inner, config, opts) {
161
+ if (!hasToolHooks(config))
162
+ return inner;
163
+ const gated = async (name, args) => {
164
+ const pre = await runHooks("PreToolUse", { tool_name: name, tool_input: args }, config, opts);
165
+ if (pre.blocked)
166
+ return DENIED_BY_HOOK(name, pre.reason);
167
+ const result = await inner.execute(name, args);
168
+ const post = await runHooks("PostToolUse", { tool_name: name, tool_input: args, tool_response: result }, config, opts);
169
+ if (post.blocked && post.reason)
170
+ return `${result}\n\n[PostToolUse hook] ${post.reason}`;
171
+ if (post.context)
172
+ return `${result}\n\n[PostToolUse hook] ${post.context}`;
173
+ return result;
174
+ };
175
+ return {
176
+ sched: inner.sched,
177
+ execute: (name, args) => gated(name, args),
178
+ executeParallel: async (calls, onSettle, signal) => {
179
+ // Hooks active ⇒ run sequentially so every call is gated (the inner scheduler's conflict-ordering is a
180
+ // superset of sequential, so correctness holds; the perf cost applies only when hooks are configured).
181
+ const results = [];
182
+ for (let i = 0; i < calls.length; i++) {
183
+ if (signal?.aborted) {
184
+ results.push(`error: cancelled`);
185
+ onSettle?.(i, results[i]);
186
+ continue;
187
+ }
188
+ const c = calls[i];
189
+ const r = await gated(c.name, c.args);
190
+ results.push(r);
191
+ onSettle?.(i, r);
192
+ }
193
+ return results;
194
+ },
195
+ };
196
+ }