@0perator/operator 0.1.285 → 0.1.321

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 (118) 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 +308 -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 +217 -44
  11. package/dist/autonomy/delegate.js +34 -5
  12. package/dist/autonomy/incidents.js +135 -0
  13. package/dist/autonomy/index.js +22 -0
  14. package/dist/autonomy/profile.js +1 -1
  15. package/dist/autonomy/session-factory.js +25 -16
  16. package/dist/background/index.js +40 -0
  17. package/dist/browser/cdp.js +1 -1
  18. package/dist/bus/inbox.js +20 -0
  19. package/dist/classifier/config.js +47 -0
  20. package/dist/classifier/modes.js +41 -0
  21. package/dist/classifier/types.js +1 -0
  22. package/dist/cli.js +645 -93
  23. package/dist/config/features.js +69 -0
  24. package/dist/config/persona.js +143 -107
  25. package/dist/config/scaffold.js +15 -0
  26. package/dist/config/settings.js +107 -12
  27. package/dist/consolidation/sleep.js +73 -11
  28. package/dist/engine/agent.js +279 -20
  29. package/dist/engine/anthropic-chat.js +343 -0
  30. package/dist/engine/aurora.js +109 -16
  31. package/dist/engine/batch-scheduler.js +41 -9
  32. package/dist/engine/classifier.js +85 -0
  33. package/dist/engine/compaction.js +25 -6
  34. package/dist/engine/fast-start.js +25 -0
  35. package/dist/engine/loop-guard.js +448 -0
  36. package/dist/engine/net-error.js +24 -0
  37. package/dist/engine/repetition-guard.js +180 -0
  38. package/dist/engine/router-adapter.js +1 -0
  39. package/dist/engine/selfheal.js +8 -0
  40. package/dist/engine/toolcalls.js +51 -1
  41. package/dist/engine/verify-gate.js +2 -0
  42. package/dist/flywheel/processor.js +78 -31
  43. package/dist/flywheel/srft.js +13 -0
  44. package/dist/hooks/index.js +196 -0
  45. package/dist/idle/activity.js +20 -0
  46. package/dist/idle/index.js +5 -0
  47. package/dist/idle/monitor.js +71 -0
  48. package/dist/idle/policy.js +66 -0
  49. package/dist/idle/proc.js +22 -0
  50. package/dist/idle/reaper.js +69 -0
  51. package/dist/idle/session-record.js +59 -0
  52. package/dist/index.js +1 -1
  53. package/dist/mcp/config.js +93 -15
  54. package/dist/mcp/index.js +9 -2
  55. package/dist/memory/index.js +0 -0
  56. package/dist/memory/providers.js +210 -0
  57. package/dist/memory/session-catalog.js +422 -0
  58. package/dist/memory/session-providers.js +121 -0
  59. package/dist/memory/session-sources.js +335 -0
  60. package/dist/memory/skylark.js +131 -0
  61. package/dist/models/bench.js +103 -0
  62. package/dist/models/registry.js +144 -0
  63. package/dist/models/switch.js +69 -0
  64. package/dist/observability/blackbox.js +37 -0
  65. package/dist/permissions/index.js +22 -7
  66. package/dist/permissions/policy.js +31 -6
  67. package/dist/permissions/tier.js +1 -1
  68. package/dist/remote/host.js +20 -2
  69. package/dist/remote/safe-commands.js +38 -0
  70. package/dist/router/discovery.js +127 -0
  71. package/dist/router/models.js +107 -16
  72. package/dist/router/portal.js +100 -0
  73. package/dist/router/router.js +1 -1
  74. package/dist/services/preflight.js +108 -8
  75. package/dist/services/store-sync.js +111 -0
  76. package/dist/session-teardown.js +10 -1
  77. package/dist/session.js +338 -46
  78. package/dist/skills/catalogue.js +1 -1
  79. package/dist/tools/chauffeur-native.js +155 -0
  80. package/dist/tools/chauffeur.js +26 -3
  81. package/dist/tools/download.js +229 -0
  82. package/dist/tools/executor.js +19 -9
  83. package/dist/tools/find-files.js +483 -0
  84. package/dist/tools/git-pr.js +94 -0
  85. package/dist/tools/incident-tools.js +82 -0
  86. package/dist/tools/memory.js +12 -2
  87. package/dist/tools/monitoring-tools.js +312 -0
  88. package/dist/tools/paths.js +154 -0
  89. package/dist/tools/registry.js +582 -95
  90. package/dist/tools/semantic-compress.js +124 -0
  91. package/dist/tools/shell-context.js +1 -0
  92. package/dist/tools/shell-jobs.js +163 -0
  93. package/dist/tools/shell-session.js +174 -6
  94. package/dist/tools/tool-output-spill.js +1 -1
  95. package/dist/tools/wave-tools.js +609 -0
  96. package/dist/tools/wave2-tools.js +411 -0
  97. package/dist/ui/App.js +15 -4
  98. package/dist/ui/BgPanel.js +30 -6
  99. package/dist/ui/Composer.js +15 -2
  100. package/dist/ui/QuestionPrompt.js +32 -12
  101. package/dist/ui/SessionPicker.js +86 -0
  102. package/dist/ui/StatusRule.js +5 -5
  103. package/dist/ui/ToolStep.js +17 -1
  104. package/dist/ui/Transcript.js +17 -1
  105. package/dist/ui/index.js +1 -1
  106. package/dist/ui/liveTools.js +21 -3
  107. package/dist/ui/slashCommands.js +2 -0
  108. package/dist/util/mentions.js +1 -1
  109. package/dist/util/screenshots.js +74 -8
  110. package/dist/util/slash.js +2 -2
  111. package/dist/vault/store.js +1 -1
  112. package/mcp/README.md +88 -0
  113. package/mcp/ocr-macos.swift +45 -0
  114. package/mcp/powertools-media.mjs +464 -0
  115. package/mcp/powertools-toolbox.mjs +1114 -0
  116. package/mcp/powertools.md +210 -0
  117. package/mcp/powertools.mjs +861 -0
  118. package/package.json +9 -2
@@ -8,18 +8,43 @@ import { dirname } from "node:path";
8
8
  import { operatorPath } from "./home.js";
9
9
  import { applyManagedPolicy, loadManagedPolicy } from "./managed.js";
10
10
  import { DEFAULT_MODEL_ID } from "../router/models.js";
11
- // The sole endpoint: Aurora on :8097 at its REAL served context — 307,200 tokens (300K; the llama-server
12
- // runs --ctx-size 307200 with q8_0 KV cache, standardized on JL1+JL2 2026-09-27). ctxWindow MUST match the
13
- // server's real --ctx-size: an inflated value (it was 1048576/"1M") makes compaction fire far too late — the
14
- // server's real ceiling is hit first, forcing a failover. Override base/model in settings.json for any
15
- // OpenAI-compatible server.
11
+ /** Resolve an endpoint's bearer from config/env/secret-file (first hit wins); undefined when none set
12
+ * (a local/un-gated endpoint). Keeps the raw key out of settings when `apiKeyEnv`/`apiKeyFile` are used. */
13
+ export function resolveEndpointApiKey(ep) {
14
+ if (!ep)
15
+ return undefined;
16
+ const inline = ep.apiKey?.trim();
17
+ if (inline)
18
+ return inline;
19
+ const named = ep.apiKeyEnv ? process.env[ep.apiKeyEnv]?.trim() : undefined;
20
+ if (named)
21
+ return named;
22
+ const def = process.env.KODE_AURORA_TOKEN?.trim();
23
+ if (def)
24
+ return def;
25
+ if (ep.apiKeyFile) {
26
+ try {
27
+ const v = readFileSync(ep.apiKeyFile.replace(/^~(?=\/)/, process.env.HOME ?? "~"), "utf8").trim();
28
+ if (v)
29
+ return v;
30
+ }
31
+ catch { /* missing/unreadable → fall through to undefined */ }
32
+ }
33
+ return undefined;
34
+ }
35
+ // Aurora endpoint is discovered from ~/.operator/runtime/server.json (dynamic port).
36
+ // The empty base below is a sentinel — preflight reads server.json and resolves the real base_url
37
+ // before any request. ctxWindow MUST match the server's real --ctx-size. Override in settings.json.
16
38
  const DEFAULTS = {
17
39
  endpoints: {
18
- aurora: { base: "http://127.0.0.1:8097", ctxWindow: 307200, model: "aurora-code-1" },
40
+ // Fallback literal for hosts without a running operator-runtime gateway (mobile, browser, dev).
41
+ // Fleet nodes with ~/.operator/runtime/server.json dynamically override this at startup via the
42
+ // gateway-discovery path in cli.tsx — single source of truth, enterprise-safe for both postures.
43
+ aurora: { base: "http://127.0.0.1:8097", ctxWindow: 1000000, model: "aurora-code-1" },
19
44
  // HA hot-standby: JL2 (64GB) serving Aurora @ 300K on the LAN — task #50, replaces the old
20
45
  // dolphin3-tools:8b "8k trap". Same model + same real window as primary, so a failover holds any live
21
46
  // session instead of truncating it. Point elsewhere / omit to disable.
22
- failover: { base: "http://192.168.1.146:8097", ctxWindow: 307200, model: "aurora-code-1" },
47
+ failover: { base: "http://192.168.1.146:8097", ctxWindow: 1000000, model: "aurora-code-1" },
23
48
  },
24
49
  modelMode: "local", // default: this node uses its own local model (endpoints.aurora); set "aurora" to use the shared fleet
25
50
  fleet: { auroraNodes: ["http://192.168.1.103:8097", "http://192.168.1.146:8097"] }, // JL1, JL2 — the live Aurora serving nodes (priority order)
@@ -29,21 +54,23 @@ const DEFAULTS = {
29
54
  temperature: 0.7,
30
55
  mcp: false,
31
56
  memory: { recall: true },
32
- selfImprove: { flywheel: true, memory: false, skills: false, reflect: false }, // trajectory capture ON; memory/skills/reflect sinks staged
57
+ selfImprove: { flywheel: true, memory: true, skills: false, reflect: false }, // trajectory capture ON; memory sink (failure-lesson → .operator/memories.md) ON — the proven closed loop; skills/reflect staged
33
58
  verifyGate: { enabled: true, maxNudges: 1 }, // verify-before-done ON; KODE_VERIFY_GATE=0 to run the raw model
34
59
  unrestricted: true, // owner's private system — on by default; KODE_UNRESTRICTED=0 to disable
35
- background: { maxConcurrent: 2, worktree: true }, // ≤2 bg agents at once (KODE_BG_MAX); file-editing ones isolate in a git worktree (KODE_BG_WORKTREE=0 to disable)
60
+ background: { maxConcurrent: 2, worktree: true, jobNotices: "wake" }, // jobNotices: KODE_BG_JOB_NOTICES=wake|queue|off; ≤2 bg agents at once (KODE_BG_MAX); file-editing ones isolate in a git worktree (KODE_BG_WORKTREE=0 to disable)
36
61
  ui: { fullscreen: false, reasoning: "think" }, // inline by default; reasoning "think" = the model's thoughts stream dim above the answer every turn (the owner wants to see the process); set "off" for spinner-only, or /think to toggle per-session
37
- permissions: { mode: "bypass" }, // zero gates by default — enforcement is opt-in
62
+ permissions: { mode: "gated" }, // ask-by-default: the user decides Allow/Deny; bypass is the opt-out
38
63
  telemetry: { enabled: true }, // local-only metrics (silent JSONL); remote sink opt-in via KODE_TELEMETRY_URL
39
64
  sandbox: { mode: "off" }, // no isolation by default — enterprise turns it on (KODE_SANDBOX / settings)
40
65
  computer: { enabled: false }, // computer control OFF by default; enable with KODE_COMPUTER=1 or settings.json
66
+ sessionSearch: { enabled: true }, // /sessions + session_search over Operator's and agents.md providers' sessions; per-provider switches in sources; KODE_SESSION_SEARCH=0 to disable
41
67
  search: {}, // web_search backend unset by default; set search.searxngUrl / search.autopilotUrl or the env vars
42
68
  // Service lever — JL1 defaults. On a machine without these launchd agents every start step just fails
43
69
  // harmlessly and the boot screen falls back to the manual hint (autostart is best-effort by design).
44
70
  services: {
45
- aurora: { autostart: true, launchdLabel: "com.imi.aurora-serve", plistPath: "~/Library/LaunchAgents/com.imi.aurora-serve.plist", waitSec: 90 },
71
+ aurora: { autostart: true, launchdLabel: "ai.operator.gateway", plistPath: "~/Library/LaunchAgents/ai.operator.gateway.plist", waitSec: 90 },
46
72
  autopilot: { autostart: true, launchdLabel: "com.axe.autopilot", plistPath: "~/Library/LaunchAgents/com.axe.autopilot.plist", url: "http://127.0.0.1:9333" },
73
+ vision: { autostart: false, launchdLabel: "axe.vision-bot", plistPath: "~/Library/LaunchAgents/axe.vision-bot.plist", url: "http://127.0.0.1:7788", remoteUrl: "http://192.168.1.103:8095" },
47
74
  stopOnExit: { searxng: true }, // aurora/autopilot are shared + never stopped; only the SearXNG container is
48
75
  },
49
76
  activeModel: DEFAULT_MODEL_ID, // /model default — the 1M endpoint, unchanged from before /model existed
@@ -126,8 +153,20 @@ function applyEnv(s) {
126
153
  const mtt = Number(process.env.KODE_TURN_MAX_TOKENS); // opt-in per-turn cost ceiling (total tokens)
127
154
  if (Number.isFinite(mtt) && mtt > 0)
128
155
  out.maxTurnTokens = Math.floor(mtt);
156
+ const lg = process.env.KODE_LOOP_GUARD; // loop guard master switch
157
+ const lgHard = process.env.KODE_LOOP_GUARD_HARD_STOP; // force the hard stop on/off regardless of interactive/headless
158
+ if (lg === "0" || lgHard === "0" || lgHard === "1") {
159
+ out.loopGuard = { ...out.loopGuard, ...(lg === "0" ? { enabled: false } : {}), ...(lgHard === "0" || lgHard === "1" ? { hardStop: lgHard === "1" } : {}) };
160
+ }
129
161
  if (process.env.KODE_TELEMETRY === "0")
130
162
  out.telemetry = { ...out.telemetry, enabled: false };
163
+ if (process.env.KODE_STORE_URL)
164
+ out.store = { ...out.store, endpoint: process.env.KODE_STORE_URL };
165
+ if (process.env.KODE_STORE_KEY)
166
+ out.store = { ...out.store, key: process.env.KODE_STORE_KEY };
167
+ const jn = process.env.KODE_BG_JOB_NOTICES;
168
+ if (jn === "wake" || jn === "queue" || jn === "off")
169
+ out.background = { ...out.background, jobNotices: jn };
131
170
  if (process.env.KODE_UNRESTRICTED === "0")
132
171
  out.unrestricted = false; // owner's private system; opt out per-box
133
172
  const sb = process.env.KODE_SANDBOX;
@@ -135,7 +174,7 @@ function applyEnv(s) {
135
174
  out.sandbox = { mode: sb };
136
175
  if (process.env.KODE_COMPUTER === "1")
137
176
  out.computer = { enabled: true };
138
- // Service lever: KODE_SERVICES_AUTOSTART=0 disables autostart of BOTH launchd services (Operator then
177
+ // Service lever: KODE_SERVICES_AUTOSTART=0 disables autostart of ALL launchd services (Operator then
139
178
  // only probes + reports); KODE_STOP_SEARXNG_ON_EXIT=0 keeps the SearXNG container running after exit.
140
179
  if (out.services) {
141
180
  if (process.env.KODE_SERVICES_AUTOSTART === "0") {
@@ -143,6 +182,7 @@ function applyEnv(s) {
143
182
  ...out.services,
144
183
  aurora: { ...out.services.aurora, autostart: false },
145
184
  autopilot: { ...out.services.autopilot, autostart: false },
185
+ vision: { ...out.services.vision, autostart: false },
146
186
  };
147
187
  }
148
188
  if (process.env.KODE_STOP_SEARXNG_ON_EXIT === "0") {
@@ -261,6 +301,61 @@ function resolveModelMode(s) {
261
301
  }
262
302
  return s;
263
303
  }
304
+ // The AXE cloud tier — AXE's own gateway (nginx + LiteLLM → llama.cpp), the LAST-RESORT failover reached
305
+ // only when the whole local fleet is wedged/degraded. Mirrors the `axe-aurora-300k` BUILTIN profile: same
306
+ // served model + window. The base is bare (no `/v1` — aurora.ts appends it); it carries NO explicit token
307
+ // because authHeaders() sends the operator bearer to *.axe.onl automatically (credential-scope guard). Opt
308
+ // out with `settings.endpoints.cloudFailover === false` for a sovereign deployment that must never egress.
309
+ const CLOUD_FAILOVER = {
310
+ name: "axe-cloud",
311
+ base: "https://api.axe.onl",
312
+ model: "aurora-code-1",
313
+ ctxLimit: 307200,
314
+ transport: "openai",
315
+ };
316
+ function hostLabel(base) {
317
+ try {
318
+ const u = new URL(base);
319
+ return `${u.hostname}${u.port ? `-${u.port}` : ""}`;
320
+ }
321
+ catch {
322
+ return base.replace(/^https?:\/\//, "").replace(/[^\w.-]+/g, "-");
323
+ }
324
+ }
325
+ /** Assemble the MULTI-TIER self-heal endpoint chain the router consumes, in priority order:
326
+ * primary (endpoints.aurora)
327
+ * → every OTHER live fleet node (fleet.auroraNodes, same served model + window, deduped)
328
+ * → an explicit back-compat single failover (endpoints.failover, deduped)
329
+ * → the AXE cloud tier (opt-outable via endpoints.cloudFailover:false) as last resort.
330
+ * Deduped by base (trailing-slash-insensitive) so a node already in the chain is never added twice — e.g.
331
+ * resolveModelMode's derived `failover` (== a fleet node) collapses in. Each endpoint resolves its OWN
332
+ * bearer via resolveEndpointApiKey (a local/LAN/un-gated node → none; the cloud tier → the operator bearer
333
+ * via authHeaders scoping). The single source of truth for both cli.tsx (interactive) and the autonomy
334
+ * session factory (headless), so the two paths can never drift to different chains. */
335
+ export function buildEndpointChain(s) {
336
+ const { aurora, failover } = s.endpoints;
337
+ const chain = [];
338
+ const seen = new Set();
339
+ const add = (ep) => {
340
+ const key = ep.base.replace(/\/+$/, "");
341
+ if (seen.has(key))
342
+ return;
343
+ seen.add(key);
344
+ chain.push(ep);
345
+ };
346
+ add({ name: "operator-1m", base: aurora.base, model: aurora.model, ctxLimit: aurora.ctxWindow, token: resolveEndpointApiKey(aurora), loopbackAuth: true });
347
+ for (const base of (s.fleet?.auroraNodes ?? []).filter(Boolean)) {
348
+ const cfg = { base, model: aurora.model, ctxWindow: aurora.ctxWindow };
349
+ add({ name: `fleet-${hostLabel(base)}`, base, model: aurora.model, ctxLimit: aurora.ctxWindow, token: resolveEndpointApiKey(cfg) });
350
+ }
351
+ if (failover)
352
+ add({ name: "failover", base: failover.base, model: failover.model, ctxLimit: failover.ctxWindow, token: resolveEndpointApiKey(failover) });
353
+ if (s.endpoints.cloudFailover !== false) {
354
+ const cfg = { base: CLOUD_FAILOVER.base, model: CLOUD_FAILOVER.model, ctxWindow: CLOUD_FAILOVER.ctxLimit };
355
+ add({ ...CLOUD_FAILOVER, token: resolveEndpointApiKey(cfg) });
356
+ }
357
+ return chain;
358
+ }
264
359
  // The seat this process resolved at startup (auth/identity.ts). Re-applied by every loadSettings() so a later
265
360
  // caller (cron, delegate_task) can never see a WIDER tier than the one the identity was narrowed to.
266
361
  let activeSeat = null;
@@ -15,7 +15,8 @@
15
15
  import { readFileSync, writeFileSync, existsSync, appendFileSync, mkdirSync } from "node:fs";
16
16
  import { dirname } from "node:path";
17
17
  import { operatorPath } from "../config/home.js";
18
- import { FlywheelProcessor } from "../flywheel/processor.js";
18
+ import { FlywheelProcessor, scoreThreshold } from "../flywheel/processor.js";
19
+ import { isPromotable } from "../flywheel/srft.js";
19
20
  const DEFAULTS = {
20
21
  enabled: false,
21
22
  idleThresholdSec: 30,
@@ -75,6 +76,13 @@ export function dedupMemoryFile(filepath) {
75
76
  // ---------------------------------------------------------------------------
76
77
  // Lesson extraction from flywheel trajectories
77
78
  // ---------------------------------------------------------------------------
79
+ /** Min repeated failures on one task CLASS before it becomes a candidate lesson. Lowered from the old
80
+ * `> 2 on a byte-identical input hash` (which real traffic never satisfied) to a bar a fuzzy task class
81
+ * can actually reach. Override with KODE_CONSOLIDATION_FAILURE_MIN. */
82
+ const REPEATED_FAILURE_MIN = (() => {
83
+ const n = Number(process.env.KODE_CONSOLIDATION_FAILURE_MIN);
84
+ return Number.isFinite(n) && n >= 1 ? n : 2;
85
+ })();
78
86
  /** Extract candidate lessons from graded flywheel trajectories.
79
87
  * Scans the flywheel JSONL for patterns that suggest a reusable lesson:
80
88
  * - Repeated failures on the same tool/command
@@ -95,28 +103,61 @@ export async function extractFlywheelLessons(flywheelDir) {
95
103
  const filepath = join(flywheelDir, file);
96
104
  const raw = readFileSync(filepath, "utf8");
97
105
  const lines = raw.split("\n").filter(Boolean);
106
+ // Mentor-pair lanes are already-distilled, human/teacher-VERIFIED lessons (chosen vs rejected with the
107
+ // reasoning attached) — the richest signal in the directory. Each valid pair IS a lesson; no counting
108
+ // bar applies. Before this path existed the extractor parsed these files as trajectories, found no
109
+ // graded/score fields, and dropped every row — the hand-curated lane contributed nothing.
110
+ if (file.startsWith("mentor-pairs")) {
111
+ for (const line of lines) {
112
+ try {
113
+ const pair = JSON.parse(line);
114
+ const chosen = typeof pair.chosen === "string" ? pair.chosen.trim() : "";
115
+ if (!chosen)
116
+ continue;
117
+ lessons.push({
118
+ type: "mentor_pair",
119
+ pattern: (pair.lens || "general").slice(0, 60),
120
+ count: 1,
121
+ total: 1,
122
+ source: filepath,
123
+ text: chosen,
124
+ });
125
+ }
126
+ catch { /* skip malformed rows */ }
127
+ }
128
+ continue;
129
+ }
98
130
  // Track per-task patterns
99
131
  const taskCounts = new Map();
132
+ const threshold = scoreThreshold();
100
133
  for (const line of lines) {
101
134
  try {
102
135
  const row = JSON.parse(line);
103
- if (!row.graded)
104
- continue;
105
- // Key by task signature (input hash)
106
- const key = hashInput(row.input ?? "");
136
+ // Key by TASK CLASS (normalized first tokens), not a byte-exact input hash. Real prompts almost
137
+ // never repeat verbatim, so the old exact-hash grouping (hashInput) produced ~0 candidates on live
138
+ // traffic; collapsing near-identical prompts into a class is what lets a repeated failure MODE show.
139
+ const key = taskClassKey(row.input ?? "");
107
140
  const count = taskCounts.get(key) ?? { total: 0, graded: 0, failed: 0 };
108
141
  count.total++;
142
+ // Failure MINING is deliberately not gated on promotability: an unverified failure is almost never
143
+ // `graded:true`, so requiring isPromotable here meant count.failed could not increment on live
144
+ // traffic (verified 2026-10-22: 31/32 recent rows graded+verified, 0 unverified-promotable) — the
145
+ // structural reason every nightly pass logged extracted=0. The promotion gate still governs what
146
+ // the TRAINING pipeline exports (processor.ts); lesson mining wants the failures it excludes.
109
147
  if (row.unverified) {
110
148
  count.failed++;
111
149
  }
112
- count.graded++;
150
+ if (isPromotable(row, threshold)) {
151
+ count.graded++;
152
+ }
113
153
  taskCounts.set(key, count);
114
154
  }
115
155
  catch { /* skip malformed rows */ }
116
156
  }
117
- // Identify patterns worth distilling
157
+ // Identify patterns worth distilling. A repeated failure on the same task CLASS (>=2) is the trigger —
158
+ // a real, attainable bar, unlike the old `>2 on an identical input hash` that live traffic never hit.
118
159
  for (const [key, count] of taskCounts) {
119
- if (count.failed > 2) {
160
+ if (count.failed >= REPEATED_FAILURE_MIN) {
120
161
  lessons.push({
121
162
  type: "repeated_failure",
122
163
  pattern: key,
@@ -132,10 +173,14 @@ export async function extractFlywheelLessons(flywheelDir) {
132
173
  /** Merge candidate lessons into curated form.
133
174
  * Groups candidates by type+pattern, extracts a distilled lesson text. */
134
175
  export function curateLessons(candidates) {
135
- // Group by type
176
+ // Group by type. Mentor pairs key on their distilled TEXT, not the lens: several pairs share one lens
177
+ // (e.g. chain-to-completion) but each carries a distinct rule — a lens-keyed group would collapse them
178
+ // into whichever rule happened to arrive first.
136
179
  const groups = new Map();
137
180
  for (const c of candidates) {
138
- const key = `${c.type}:${c.pattern.slice(0, 40)}`;
181
+ const key = c.type === "mentor_pair"
182
+ ? `${c.type}:${(c.text ?? "").slice(0, 80)}`
183
+ : `${c.type}:${c.pattern.slice(0, 40)}`;
139
184
  const existing = groups.get(key) ?? [];
140
185
  existing.push(c);
141
186
  groups.set(key, existing);
@@ -162,11 +207,16 @@ export function curateLessons(candidates) {
162
207
  text = `Verification gap: ${count} turns changed files without passing checks. ` +
163
208
  `Lesson: the verify-before-done gate needs a nudge on this task type.`;
164
209
  break;
210
+ case "mentor_pair":
211
+ // Already distilled and verified at capture time — carry the rule through verbatim (capped),
212
+ // prefixed with its lens so recall can match on the failure mode it addresses.
213
+ text = `Mentor rule [${items[0].pattern}]: ${(items[0].text ?? "").slice(0, 400)}`;
214
+ break;
165
215
  }
166
216
  return {
167
217
  ts: Date.now(),
168
218
  text,
169
- tags: [type, `count:${count}`],
219
+ tags: type === "mentor_pair" ? [type, items[0].pattern] : [type, `count:${count}`],
170
220
  source: items[0].source,
171
221
  candidates: items.map(i => i.pattern),
172
222
  };
@@ -317,6 +367,18 @@ export async function runConsolidationPass(opts = {}) {
317
367
  return result;
318
368
  }
319
369
  }
370
+ /** Group near-identical prompts into one TASK CLASS. Normalizes case/whitespace, strips punctuation, and
371
+ * keeps the first few significant tokens — so "fix the login bug" and "fix the login bug please" land in
372
+ * the same class and a repeated failure MODE can surface, where an exact-hash key never would. */
373
+ function taskClassKey(input) {
374
+ const tokens = input
375
+ .toLowerCase()
376
+ .replace(/[^\p{L}\p{N}\s]+/gu, " ")
377
+ .split(/\s+/)
378
+ .filter(Boolean)
379
+ .slice(0, 8);
380
+ return tokens.length ? tokens.join(" ") : hashInput(input);
381
+ }
320
382
  function hashInput(input) {
321
383
  // Simple hash for grouping similar tasks
322
384
  let hash = 0;