@0perator/operator 0.1.352 → 0.1.353

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 (90) hide show
  1. package/dist/acp/agent.js +2 -2
  2. package/dist/acp/tool-map.js +5 -4
  3. package/dist/autonomy/delegate.js +54 -1
  4. package/dist/autonomy/headless.js +2 -0
  5. package/dist/autonomy/session-factory.js +1 -0
  6. package/dist/background/index.js +86 -10
  7. package/dist/background/notices.js +16 -4
  8. package/dist/cli.js +1066 -175
  9. package/dist/config/home.js +6 -0
  10. package/dist/config/memory-sections.js +92 -0
  11. package/dist/config/persona.js +144 -26
  12. package/dist/config/settings.js +15 -4
  13. package/dist/consolidation/scheduler.js +9 -2
  14. package/dist/consolidation/sleep.js +39 -278
  15. package/dist/engine/agent.js +444 -76
  16. package/dist/engine/anthropic-chat.js +13 -2
  17. package/dist/engine/aurora.js +43 -19
  18. package/dist/engine/batch-scheduler.js +27 -3
  19. package/dist/engine/compaction.js +12 -5
  20. package/dist/engine/continuation.js +14 -12
  21. package/dist/engine/contract.js +1 -1
  22. package/dist/engine/decision-points.js +7 -1
  23. package/dist/engine/front-door.js +59 -0
  24. package/dist/engine/grandmaster.js +13 -1
  25. package/dist/engine/loop-guard.js +694 -0
  26. package/dist/engine/owner-act.js +52 -0
  27. package/dist/engine/verify-gate.js +52 -0
  28. package/dist/flywheel/processor.js +3 -1
  29. package/dist/flywheel/srft.js +8 -4
  30. package/dist/hooks/index.js +12 -8
  31. package/dist/mcp/index.js +9 -4
  32. package/dist/permissions/index.js +32 -11
  33. package/dist/permissions/modes.js +42 -0
  34. package/dist/permissions/plan-review.js +100 -0
  35. package/dist/permissions/policy.js +16 -5
  36. package/dist/permissions/signature.js +8 -3
  37. package/dist/remote/safe-commands.js +1 -1
  38. package/dist/router/read-rates.js +152 -0
  39. package/dist/selfimprove/backfill.js +174 -0
  40. package/dist/selfimprove/index.js +146 -57
  41. package/dist/selfimprove/lessons.js +429 -0
  42. package/dist/selfimprove/sync.js +58 -0
  43. package/dist/session.js +350 -30
  44. package/dist/skills/finder.js +219 -0
  45. package/dist/tools/deferred.js +28 -18
  46. package/dist/tools/executor.js +7 -3
  47. package/dist/tools/registry.js +34 -4
  48. package/dist/ui/ActivitySpinner.js +21 -12
  49. package/dist/ui/App.js +107 -30
  50. package/dist/ui/ApprovalPrompt.js +5 -3
  51. package/dist/ui/ArtifactPicker.js +3 -3
  52. package/dist/ui/BgPanel.js +105 -5
  53. package/dist/ui/Composer.js +85 -9
  54. package/dist/ui/PlanPane.js +72 -8
  55. package/dist/ui/QuestionPrompt.js +6 -4
  56. package/dist/ui/SecretPrompt.js +8 -3
  57. package/dist/ui/SessionPicker.js +2 -2
  58. package/dist/ui/SkillFinder.js +153 -0
  59. package/dist/ui/StatusRule.js +5 -2
  60. package/dist/ui/SummaryCard.js +3 -1
  61. package/dist/ui/ThinkingSpinner.js +11 -2
  62. package/dist/ui/ToolBatch.js +11 -2
  63. package/dist/ui/ToolStep.js +36 -13
  64. package/dist/ui/Transcript.js +13 -2
  65. package/dist/ui/actNow.js +61 -0
  66. package/dist/ui/batchLine.js +165 -0
  67. package/dist/ui/conversations.js +154 -0
  68. package/dist/ui/decodeHealth.js +77 -0
  69. package/dist/ui/expand.js +17 -0
  70. package/dist/ui/fit.js +40 -0
  71. package/dist/ui/fitTail.js +14 -0
  72. package/dist/ui/fold.js +149 -0
  73. package/dist/ui/format.js +46 -2
  74. package/dist/ui/liveTools.js +163 -13
  75. package/dist/ui/modelPicker.js +78 -6
  76. package/dist/ui/nextStep.js +103 -0
  77. package/dist/ui/pending.js +57 -0
  78. package/dist/ui/phase.js +105 -0
  79. package/dist/ui/planExit.js +0 -5
  80. package/dist/ui/progressbar.js +4 -26
  81. package/dist/ui/readForecast.js +44 -0
  82. package/dist/ui/readProgress.js +119 -0
  83. package/dist/ui/reportLine.js +62 -0
  84. package/dist/ui/slashCommands.js +1 -1
  85. package/dist/ui/theme.js +1 -0
  86. package/dist/ui/turnFlow.js +72 -0
  87. package/dist/ui/turnLedger.js +121 -0
  88. package/dist/ui/turnScope.js +11 -0
  89. package/dist/util/slash.js +18 -0
  90. package/package.json +1 -1
@@ -0,0 +1,152 @@
1
+ // Measured read and decode speed per model (TUI A3.2 / A3.6), so a switch, a /think toggle or a compaction can say what
2
+ // its re-read will cost BEFORE it happens. llama.cpp's timings.prompt_n counts only the tokens a request actually read (the
3
+ // part its prefix cache did not hold) and prompt_ms how long that took, so promptTokens ÷ promptMs is a model's read rate.
4
+ // The shell feeds every round's onCacheStats here, attributed to the model active at onRoute; it skips rounds a gateway
5
+ // fallback served (another box answered) and reads under MIN_READ_TOKENS (too small to time). Samples persist with their
6
+ // timestamps in the Operator home (0600), so the first switch of a session already has a number. A rate is never guessed:
7
+ // no sample, no time — callers show the token count alone. Node-only: imported by cli.tsx, like free-models.ts.
8
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
9
+ import { dirname } from "node:path";
10
+ import { operatorPath } from "../config/home.js";
11
+ export const MIN_READ_TOKENS = 2048;
12
+ const KEEP = 8; // samples kept per model and kind
13
+ const MIN_DECODE_TOKENS = 64;
14
+ const tps = (s) => s.tokens / (s.ms / 1000);
15
+ const median = (xs) => { const v = [...xs].sort((a, b) => a - b); const m = Math.floor(v.length / 2); return v.length % 2 ? v[m] : (v[m - 1] + v[m]) / 2; };
16
+ export class ReadRates {
17
+ file;
18
+ now;
19
+ store = { version: 1, read: {}, decode: {} };
20
+ loaded = false;
21
+ constructor(file = () => operatorPath("read-rates.json"), now = Date.now) {
22
+ this.file = file;
23
+ this.now = now;
24
+ }
25
+ load() {
26
+ if (this.loaded)
27
+ return;
28
+ this.loaded = true;
29
+ try {
30
+ const raw = JSON.parse(readFileSync(this.file(), "utf8"));
31
+ const clean = (m) => {
32
+ const out = {};
33
+ if (!m || typeof m !== "object")
34
+ return out;
35
+ for (const [k, v] of Object.entries(m)) {
36
+ if (!Array.isArray(v))
37
+ continue;
38
+ const ok = v.filter((s) => !!s && typeof s === "object" && [s.tokens, s.ms, s.at].every((n) => typeof n === "number" && Number.isFinite(n) && n > 0));
39
+ if (ok.length)
40
+ out[k] = ok.slice(-KEEP);
41
+ }
42
+ return out;
43
+ };
44
+ this.store = { version: 1, read: clean(raw.read), decode: clean(raw.decode) };
45
+ }
46
+ catch { /* no file yet, or unreadable: start empty */ }
47
+ }
48
+ save() {
49
+ try {
50
+ mkdirSync(dirname(this.file()), { recursive: true, mode: 0o700 });
51
+ writeFileSync(this.file(), JSON.stringify(this.store), { mode: 0o600 });
52
+ }
53
+ catch { /* best-effort: a rate that is not saved is re-measured next session */ }
54
+ }
55
+ add(kind, model, s) {
56
+ this.load();
57
+ const list = (this.store[kind][model] ??= []);
58
+ list.push(s);
59
+ if (list.length > KEEP)
60
+ list.splice(0, list.length - KEEP);
61
+ this.save();
62
+ }
63
+ /** One round's prompt read. False (nothing recorded) for a read too small to time or without a server time. */
64
+ recordRead(model, promptTokens, promptMs) {
65
+ if (!model || !(promptTokens >= MIN_READ_TOKENS) || !(promptMs && promptMs > 0))
66
+ return false;
67
+ this.add("read", model, { tokens: promptTokens, ms: promptMs, at: this.now() });
68
+ return true;
69
+ }
70
+ /** One turn's generation: output tokens over the server's generation time. */
71
+ recordDecode(model, tokens, genMs) {
72
+ if (!model || !tokens || tokens < MIN_DECODE_TOKENS || !(genMs && genMs > 0))
73
+ return false;
74
+ this.add("decode", model, { tokens, ms: genMs, at: this.now() });
75
+ return true;
76
+ }
77
+ /** The model's read rate for a read of about `forTokens`: prefill slows with depth, so samples that read at least half
78
+ * as much are preferred when there are any. Median, so one cold outlier does not set it. */
79
+ readRate(model, forTokens = 0) {
80
+ this.load();
81
+ const all = this.store.read[model] ?? [];
82
+ const deep = all.filter((s) => s.tokens >= forTokens / 2);
83
+ const use = deep.length ? deep : all;
84
+ if (!use.length)
85
+ return undefined;
86
+ return { tokPerSec: median(use.map(tps)), at: Math.max(...use.map((s) => s.at)) };
87
+ }
88
+ decodeRate(model) {
89
+ this.load();
90
+ const use = this.store.decode[model] ?? [];
91
+ if (!use.length)
92
+ return undefined;
93
+ return { tokPerSec: median(use.map(tps)), at: Math.max(...use.map((s) => s.at)) };
94
+ }
95
+ }
96
+ /** The process-wide store the shell feeds and the pickers read. */
97
+ export const readRates = new ReadRates();
98
+ /** One session's attribution, driven from the turn handlers: a round's read belongs to the model active at its onRoute;
99
+ * a round a gateway fallback served (x-0perator-fallback — another box answered) belongs to no one, and a turn with any
100
+ * such round records no decode rate. */
101
+ export class RateFeed {
102
+ store;
103
+ model = "";
104
+ fallback = false;
105
+ turnFallback = false;
106
+ constructor(store = readRates) {
107
+ this.store = store;
108
+ }
109
+ startTurn() { this.turnFallback = false; }
110
+ route(model) { this.model = model; this.fallback = false; }
111
+ servedByFallback() { this.fallback = true; this.turnFallback = true; }
112
+ read(promptTokens, promptMs) { return !this.fallback && this.store.recordRead(this.model, promptTokens, promptMs); }
113
+ decode(model, tokens, genMs) { return !this.turnFallback && this.store.recordDecode(model, tokens, genMs); }
114
+ }
115
+ // ── formatting (pure) ────────────────────────────────────────────────────────────────────────────────────────────────
116
+ /** "~61K", "~8.4K", "~900". Always approximate: these are estimates of what a request will hold. */
117
+ export function approxTokens(n) {
118
+ if (n >= 10_000)
119
+ return `~${Math.round(n / 1000)}K`;
120
+ if (n >= 1000)
121
+ return `~${(n / 1000).toFixed(1)}K`;
122
+ return `~${Math.round(n)}`;
123
+ }
124
+ /** "4m 14s", "45s", "1h 2m". */
125
+ export function fmtWait(sec) {
126
+ const s = Math.max(0, Math.round(sec));
127
+ if (s < 60)
128
+ return `${s}s`;
129
+ if (s < 3600)
130
+ return `${Math.floor(s / 60)}m ${s % 60}s`;
131
+ return `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m`;
132
+ }
133
+ /** "10:52" — when a rate was measured; a day or more ago adds the date ("Nov 2 10:52"). */
134
+ export function fmtWhen(at, now = Date.now()) {
135
+ const d = new Date(at);
136
+ const hm = `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
137
+ if (now - at < 20 * 3600_000)
138
+ return hm;
139
+ return `${d.toLocaleString("en-US", { month: "short" })} ${d.getDate()} ${hm}`;
140
+ }
141
+ /** Seconds a read of `tokens` takes at `rate`, or undefined when the rate is unmeasured. */
142
+ export function readSeconds(tokens, rate) {
143
+ return rate && rate.tokPerSec > 0 ? tokens / rate.tokPerSec : undefined;
144
+ }
145
+ /** The cost tail of a re-read, e.g. "~61K ≈ 4m 14s (240 tok/s, 10:52)", or just "~61K" when no rate was measured. */
146
+ export function rereadCost(tokens, rate, opts = {}) {
147
+ const secs = readSeconds(tokens, rate);
148
+ if (secs === undefined)
149
+ return approxTokens(tokens);
150
+ const src = opts.source === false ? "" : ` (${Math.round(rate.tokPerSec)} tok/s, ${fmtWhen(rate.at, opts.now)})`;
151
+ return `${approxTokens(tokens)} ≈ ${fmtWait(secs)}${src}`;
152
+ }
@@ -0,0 +1,174 @@
1
+ // The fold: what the flywheel and the reviewers have taught, into the global memories.md through the one curation path
2
+ // (selfimprove/lessons.ts curateLessons). Two entry points run it unchanged, so they give the same file for the same
3
+ // input: `operator selfimprove backfill [--since YYYY-MM-DD] [--dry-run]` and sleep consolidation
4
+ // (consolidation/sleep.ts runConsolidationPass). Reads, never rewrites:
5
+ // - the daily flywheel files: every row judged from its recorded loop evidence or steps (engine/loop-guard.ts rowLooped);
6
+ // a looped row becomes the loop lesson a live turn leaves (a job notice / report row is filed under the request it
7
+ // served, a mentor-wake under its bus message's subject); a sub-agent's looped row is counted, never a lesson;
8
+ // - flywheel/mentor-pairs-*.jsonl: each verified pair a taught lesson, one per trap (always, whatever --since says);
9
+ // - the reward scorer's scores (row.score, else scored_trajectories.jsonl joined by source file + ts): reported beside
10
+ // each looped row, and a strongly negative row with no loop evidence is listed as a candidate — never a lesson.
11
+ // Idempotent: a lesson's `last` stamp marks what it already counted. --dry-run writes nothing.
12
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
13
+ import { join } from "node:path";
14
+ import { globalMemoriesPath, operatorPath } from "../config/home.js";
15
+ import { isLooped, isSystemNotice, loopEvidenceFromSteps, servedTask } from "../engine/loop-guard.js";
16
+ import { curateLessons, hardRuleNames, isSubagentBrief, reinforcedRules, splitLessons, taughtLessons } from "./lessons.js";
17
+ import { loopLessonFor, writeMemoriesAtomic } from "./index.js";
18
+ const DAY_FILE_RE = /^(\d{4}-\d{2}-\d{2})\.jsonl$/;
19
+ const MENTOR_FILE_RE = /^mentor-pairs-(\d{4}-\d{2}-\d{2})\.jsonl$/;
20
+ /** "Strongly negative": the scorer's signed logit sat at a median of -3.8 over the 1,927 rows it scored by 11/02; -4.5 is
21
+ * roughly its bottom tenth. KODE_SELFIMPROVE_NEGATIVE_SCORE overrides. */
22
+ export const NEGATIVE_SCORE = -4.5;
23
+ const CANDIDATES_SHOWN = 10;
24
+ function jsonLines(file) {
25
+ const out = [];
26
+ let raw = "";
27
+ try {
28
+ raw = readFileSync(file, "utf8");
29
+ }
30
+ catch {
31
+ return out;
32
+ }
33
+ for (const line of raw.split("\n")) {
34
+ if (!line.trim())
35
+ continue;
36
+ try {
37
+ const v = JSON.parse(line);
38
+ if (v && typeof v === "object")
39
+ out.push(v);
40
+ }
41
+ catch { /* a torn line — skip it */ }
42
+ }
43
+ return out;
44
+ }
45
+ /** The scorer's audit trail: `${source file}|${ts}` → its latest score. */
46
+ function auditScores(file) {
47
+ const out = new Map();
48
+ for (const r of jsonLines(file))
49
+ if (typeof r.score === "number" && Number.isFinite(r.score))
50
+ out.set(`${r.source}|${r.ts}`, r.score);
51
+ return out;
52
+ }
53
+ export async function foldLessons(o = {}) {
54
+ const dir = o.dir ?? operatorPath("flywheel");
55
+ const memoriesFile = o.memoriesFile ?? globalMemoriesPath();
56
+ const names = existsSync(dir) ? readdirSync(dir).sort() : [];
57
+ const files = names.filter((f) => DAY_FILE_RE.test(f) && (!o.since || f.slice(0, 10) >= o.since));
58
+ const rows = [];
59
+ for (const file of files)
60
+ for (const row of jsonLines(join(dir, file)))
61
+ rows.push({ file, row });
62
+ rows.sort((a, b) => (Number(a.row.ts) || 0) - (Number(b.row.ts) || 0));
63
+ const scores = auditScores(o.scoresFile ?? operatorPath("scored_trajectories.jsonl"));
64
+ const negative = Number(process.env.KODE_SELFIMPROVE_NEGATIVE_SCORE);
65
+ const floor = Number.isFinite(negative) ? negative : NEGATIVE_SCORE;
66
+ let text = "";
67
+ try {
68
+ text = readFileSync(memoriesFile, "utf8");
69
+ }
70
+ catch { /* none yet */ }
71
+ const taughtNames = reinforcedRules(text);
72
+ const lastAsk = new Map(); // cwd → the request last asked there: the task a job notice / report served
73
+ const flagged = [];
74
+ const candidates = [];
75
+ let subagentLoops = 0;
76
+ for (const { file, row } of rows) {
77
+ const input = String(row.input ?? "");
78
+ const cwd = String(row.cwd ?? "");
79
+ const notice = isSystemNotice(input);
80
+ const brief = isSubagentBrief(String(row.task || input));
81
+ const task = String(row.task || (notice ? lastAsk.get(cwd) ?? input : servedTask(input)));
82
+ if (!notice && !brief)
83
+ lastAsk.set(cwd, task);
84
+ const ts = Number(row.ts) || 0;
85
+ const stamp = Number(row.lessonTs) || ts; // a turn that wrote its lesson at a loop recovery: that lesson's stamp, so it counts once
86
+ const score = typeof row.score === "number" && Number.isFinite(row.score) ? row.score : scores.get(`${file}|${row.ts}`);
87
+ const evidence = row.loop ?? loopEvidenceFromSteps(row.steps, cwd);
88
+ if (!(row.looped ?? isLooped(evidence))) {
89
+ if (score !== undefined && score <= floor)
90
+ candidates.push({ file, ts, input, rounds: Number(row.rounds) || 0, score });
91
+ continue;
92
+ }
93
+ if (brief) {
94
+ subagentLoops++;
95
+ continue;
96
+ }
97
+ const r = {
98
+ input, content: String(row.content ?? ""), rounds: Number(row.rounds) || 0, toolCalls: Number(row.toolCalls) || 0,
99
+ model: String(row.model ?? ""), cwd, durationMs: row.durationMs, task, loop: evidence, interrupted: row.interrupted === true || undefined,
100
+ };
101
+ flagged.push({ file, ts, input, task, rounds: r.rounds, durationMs: r.durationMs, evidence, score, stamp, lesson: await loopLessonFor(r, stamp, taughtNames) });
102
+ }
103
+ const pairs = [];
104
+ for (const file of names.filter((f) => MENTOR_FILE_RE.test(f))) {
105
+ for (const pair of jsonLines(join(dir, file)))
106
+ pairs.push({ pair: pair, date: MENTOR_FILE_RE.exec(file)[1], file });
107
+ }
108
+ const taught = taughtLessons(pairs, hardRuleNames(text));
109
+ const fileOfPair = new Map(pairs.map((p) => [String(p.pair.id), p.file]));
110
+ const cur = curateLessons(text, [...flagged.map((f) => ({ line: f.lesson, ts: f.stamp })), ...taught.map((t) => ({ line: t.line, ts: t.ts }))], { cap: o.maxLessons, taught: taughtNames });
111
+ const { lessons } = splitLessons(cur.text);
112
+ const current = (line) => {
113
+ const key = line.slice(0, line.indexOf(" ×"));
114
+ return lessons.find((l) => l.startsWith(key + " ×")) ?? line;
115
+ };
116
+ const wrote = !o.dryRun && cur.text !== text;
117
+ if (wrote)
118
+ await writeMemoriesAtomic(memoriesFile, cur.text);
119
+ candidates.sort((a, b) => a.score - b.score);
120
+ return {
121
+ files, rows: rows.length, memoriesFile, wrote, candidates, subagentLoops,
122
+ flagged: flagged.map(({ lesson, stamp: _stamp, ...f }, i) => ({ ...f, action: cur.actions[i], line: current(lesson) })),
123
+ taught: taught.map((t, i) => ({ file: fileOfPair.get(t.id) ?? "", id: t.id, cls: t.cls, action: cur.actions[flagged.length + i], line: current(t.line) })),
124
+ };
125
+ }
126
+ const USAGE = "usage: operator selfimprove backfill [--since YYYY-MM-DD] [--dry-run]";
127
+ const fmtScore = (s) => (s === undefined ? "unscored" : `score ${s >= 0 ? "+" : ""}${s.toFixed(2)}`);
128
+ /** `operator selfimprove …` (cli.tsx, before any boot I/O). Exit 0 done, 2 bad command line. */
129
+ export async function runSelfImproveCli(args, out = (s) => process.stdout.write(s)) {
130
+ const [sub, ...rest] = args;
131
+ let since;
132
+ let dryRun = false;
133
+ for (let i = 0; i < rest.length; i++) {
134
+ if (rest[i] === "--dry-run")
135
+ dryRun = true;
136
+ else if (rest[i] === "--since")
137
+ since = rest[++i] ?? "";
138
+ else if (rest[i].startsWith("--since="))
139
+ since = rest[i].slice(8);
140
+ else {
141
+ process.stderr.write(`operator: unknown argument ${rest[i]}\n${USAGE}\n`);
142
+ return 2;
143
+ }
144
+ }
145
+ if (sub !== "backfill" || (since !== undefined && !/^\d{4}-\d{2}-\d{2}$/.test(since))) {
146
+ process.stderr.write(`${USAGE}\n`);
147
+ return 2;
148
+ }
149
+ const { loadSettings } = await import("../config/settings.js");
150
+ const r = await foldLessons({ since, dryRun, maxLessons: loadSettings().autonomy?.sleepConsolidation?.maxLessonsPerFile });
151
+ const count = (xs, k) => xs.filter((f) => f.action === k).length;
152
+ out(`selfimprove backfill: ${r.files.length} flywheel file(s)${since ? ` since ${since}` : ""}, ${r.rows} turns, ${r.flagged.length} looped` +
153
+ `${r.subagentLoops ? ` (+${r.subagentLoops} sub-agent loop${r.subagentLoops === 1 ? "" : "s"}: no lesson — a sub-agent never loads these memories)` : ""}\n`);
154
+ for (const f of r.flagged) {
155
+ const e = f.evidence;
156
+ const when = new Date(f.ts).toISOString().slice(0, 16).replace("T", " ");
157
+ out(`\n ${when}Z "${f.input.replace(/\s+/g, " ").slice(0, 70)}"\n` +
158
+ ` ${f.rounds} rounds${f.durationMs ? `, ${Math.round(f.durationMs / 60000)} min` : ""}; ${e.nudges} loop warning${e.nudges === 1 ? "" : "s"} (${e.ignored} ignored), ` +
159
+ `${e.stale} stale re-reads; ${fmtScore(f.score)}${f.score !== undefined && f.score >= 0 ? " (the scorer would have promoted it)" : ""}; lesson ${f.action}\n ${f.line}\n`);
160
+ }
161
+ out(`\ntaught by reviewers: ${r.taught.length} mentor pair(s) → ${count(r.taught, "added")} added, ${count(r.taught, "updated")} updated, ${count(r.taught, "unchanged")} already counted\n`);
162
+ if (r.candidates.length) {
163
+ out(`\nstrongly negative score, no loop evidence — candidates to look at, no lesson written (${r.candidates.length}):\n`);
164
+ for (const c of r.candidates.slice(0, CANDIDATES_SHOWN)) {
165
+ out(` ${new Date(c.ts).toISOString().slice(0, 16).replace("T", " ")}Z ${fmtScore(c.score)} ${c.rounds} rounds "${c.input.replace(/\s+/g, " ").slice(0, 70)}"\n`);
166
+ }
167
+ if (r.candidates.length > CANDIDATES_SHOWN)
168
+ out(` … and ${r.candidates.length - CANDIDATES_SHOWN} more\n`);
169
+ }
170
+ const all = [...r.flagged, ...r.taught];
171
+ out(`\nlessons → ${r.memoriesFile}: ${count(all, "added")} added, ${count(all, "updated")} updated, ${count(all, "unchanged")} already counted` +
172
+ `${dryRun ? " (dry run — nothing written)" : r.wrote ? "" : " (nothing to write)"}\n`);
173
+ return 0;
174
+ }
@@ -3,9 +3,11 @@
3
3
  // per-turn hook is where the other sinks layer in: MEMORY distillation, SKILL capture, and post-task
4
4
  // REFLECTION. All sinks are best-effort and MUST never block or throw into a turn. Node imports are lazy
5
5
  // (same mobile/JSCore-bundle discipline as services/preflight.ts) so the neutral bundle carries none of it.
6
- import { operatorPath } from "../config/home.js";
6
+ import { operatorPath, globalMemoriesPath } from "../config/home.js";
7
7
  import { redactSecrets } from "../engine/redact.js";
8
8
  import { isEngineFinal } from "../engine/continuation.js"; // a stop/pause/no-reply note is the engine's text, never a promotable answer
9
+ import { isLooped } from "../engine/loop-guard.js";
10
+ import { isSubagentBrief, loopLessonLine, ownerWords, reinforcedRules, stuckLessonLine, upsertLesson } from "./lessons.js";
9
11
  const nodeImport = (m) => import(/* @vite-ignore */ m);
10
12
  // GW-18 (flywheel gate): markers of a STRUCTURED tool call that leaked into the assistant's plain text instead
11
13
  // of being parsed into tool_calls — the documented Qwen3 failure when the server runs without `--jinja` (the
@@ -24,25 +26,33 @@ export function hasLeakedToolCall(content) {
24
26
  /** FLYWHEEL sink — append the turn as one JSONL row to a daily capture the fleet's training pipeline reads.
25
27
  * A turn that produced content, ran ≥1 round, and wasn't cut for repetition/abort is marked graded:true,
26
28
  * so downstream can filter to promotable trajectories without re-judging every row. */
27
- async function captureFlywheel(r) {
29
+ /** One turn's flywheel row: the day file it goes in (under the operator home's flywheel/) and the JSONL line. Pure. */
30
+ export function flywheelRow(r, ts) {
31
+ // graded = a promotable trajectory. A turn that changed files but never ran a passing check
32
+ // (unverified, per the verify-before-done gate) is NOT promotable — that is precisely the hollow
33
+ // "done" this whole loop exists to stop the fleet from training on.
34
+ // A leaked/garbled tool call recorded as a "completed" turn would train the model to emit tool markup as
35
+ // prose (self-poisoning) — exclude it from promotable rows AND tag it so the pipeline can audit leak rate
36
+ // and the serving side (GW-01/GW-18 `--jinja`) can be verified by the trend going to ~0.
37
+ const parseFallback = hasLeakedToolCall(r.content);
38
+ // A turn that ignored its loop warnings is the trajectory the loop must NOT learn from: the 11/02 review loop
39
+ // (37 rounds re-reading five files) was graded:true. Tagged looped so the pipeline can count them.
40
+ const looped = isLooped(r.loop);
41
+ const graded = !!r.content.trim() && r.stopReason !== "repetition" && r.rounds > 0 && !r.unverified && !parseFallback && !isEngineFinal(r.content) && !looped && !r.interrupted;
42
+ // The row carries the user's PROMPT and the full answer, and the corpus is read by the training pipeline —
43
+ // mask known secret shapes before they reach disk (the same boundary events.jsonl enforces) and keep the
44
+ // file owner-only; this used to be a 0644 file in a 0755 dir with raw prompts in it.
45
+ const line = redactSecrets(JSON.stringify({ ts, graded, parse_fallback: parseFallback, ...(looped ? { looped } : {}), ...r })) + "\n";
46
+ return { day: `${new Date(ts).toISOString().slice(0, 10)}.jsonl`, line };
47
+ }
48
+ async function captureFlywheel(r, ts) {
28
49
  try {
29
50
  const { appendFile, mkdir } = await nodeImport("node:fs/promises");
30
51
  const { join } = await nodeImport("node:path");
31
52
  const dir = operatorPath("flywheel"); // follows $KODE_HOME/$KODE_PROFILE — one identity's prompts never land in another's corpus
32
53
  await mkdir(dir, { recursive: true, mode: 0o700 });
33
- // graded = a promotable trajectory. A turn that changed files but never ran a passing check
34
- // (unverified, per the verify-before-done gate) is NOT promotable — that is precisely the hollow
35
- // "done" this whole loop exists to stop the fleet from training on.
36
- // A leaked/garbled tool call recorded as a "completed" turn would train the model to emit tool markup as
37
- // prose (self-poisoning) — exclude it from promotable rows AND tag it so the pipeline can audit leak rate
38
- // and the serving side (GW-01/GW-18 `--jinja`) can be verified by the trend going to ~0.
39
- const parseFallback = hasLeakedToolCall(r.content);
40
- const graded = !!r.content.trim() && r.stopReason !== "repetition" && r.rounds > 0 && !r.unverified && !parseFallback && !isEngineFinal(r.content);
41
- // The row carries the user's PROMPT and the full answer, and the corpus is read by the training pipeline —
42
- // mask known secret shapes before they reach disk (the same boundary events.jsonl enforces) and keep the
43
- // file owner-only; this used to be a 0644 file in a 0755 dir with raw prompts in it.
44
- const row = redactSecrets(JSON.stringify({ ts: Date.now(), graded, parse_fallback: parseFallback, ...r })) + "\n";
45
- await appendFile(join(dir, `${new Date().toISOString().slice(0, 10)}.jsonl`), row, { encoding: "utf8", mode: 0o600 });
54
+ const { day, line } = flywheelRow(r, ts);
55
+ await appendFile(join(dir, day), line, { encoding: "utf8", mode: 0o600 });
46
56
  }
47
57
  catch { /* best-effort — capture never blocks or fails a turn */ }
48
58
  }
@@ -52,57 +62,136 @@ async function captureFlywheel(r) {
52
62
  function endedStuck(r) {
53
63
  return r.stopReason === "repetition" || /^\[stopped\s[—-]/.test(r.content.trim());
54
64
  }
55
- /** MEMORY sink (the closed self-improvement loop). When a turn ends STUCK, append a concise, deduplicated
56
- * LESSON to this repo's `.operator/memories.md` — the flat memory `persona.loadMemories()` injects into
57
- * EVERY future session's system prompt here. So a failure the agent hit once becomes durable, always-loaded
58
- * context and it doesn't walk into the same trap next time. Deterministic (no LLM pass): the lesson is the
59
- * task + the gist of what it got stuck on + the standing advice (decompose / switch / do sub-agent work
60
- * inline). Best-effort, never blocks a turn, and OPT-IN (settings.selfImprove.memory, default off) since it
61
- * writes into the repo. An LLM-distilled, higher-insight version is the next increment. */
62
- async function captureFailureLesson(r) {
65
+ /** MEMORY sink (the closed self-improvement loop). A LOOPED turn — it ignored its loop warnings (engine/loop-guard.ts
66
+ * isLooped) — or one that ended STUCK on an engine stop becomes a lesson in the GLOBAL memories.md, which every session
67
+ * loads ahead of the rest (persona.loadMemories): for a loop, the task, its size, the warnings, the files it re-read
68
+ * and how often; for a stop, the task and the stop; then the rule, naming the taught rules it reinforces. One line per
69
+ * kind + class; a repeat bumps that line's count. Behaviour lessons hold in every repo, so neither goes to the project
70
+ * file (where stuck lessons went before 11/02 — persona folds those old lines in). The same curateLessons the backfill
71
+ * and sleep consolidation use. A sub-agent's turn leaves none (lessons.ts isSubagentBrief). Deterministic, best-effort,
72
+ * never blocks a turn; on by default (settings.selfImprove.memory false / KODE_SELFIMPROVE_MEMORY=0 turns it off). */
73
+ async function captureFailureLesson(r, ts = Date.now(), cap) {
63
74
  try {
64
- if (!endedStuck(r) || !r.cwd)
65
- return;
66
- const gist = r.content.trim().replace(/\s+/g, " ").slice(0, 220);
67
- const task = r.input.trim().replace(/\s+/g, " ").slice(0, 90);
68
- const { readFile, appendFile, writeFile, mkdir } = await nodeImport("node:fs/promises");
69
- const { join, dirname } = await nodeImport("node:path");
70
- const file = join(r.cwd, ".operator", "memories.md");
71
- let existing = "";
72
- try {
73
- existing = await readFile(file, "utf8");
74
- }
75
- catch { /* none yet */ }
76
- // Dedup: skip if a lesson for this task with this gist is already recorded (avoids re-logging a
77
- // repeated failure every session).
78
- const dedupKey = gist.slice(0, 70);
79
- if (existing.includes(`task "${task}"`) && existing.includes(dedupKey))
80
- return;
81
- const date = new Date().toISOString().slice(0, 10);
82
- const lesson = `- [${date}] Got stuck on task "${task}": ${gist} — next time, break the step down or switch approach ` +
83
- `early instead of repeating; if it involved sub-agents contending for one model endpoint, do the work inline.`;
84
- const HEADING = "## Lessons (auto-captured from stuck sessions)";
85
- if (!existing.trim()) {
86
- await mkdir(dirname(file), { recursive: true });
87
- await writeFile(file, `# Operator memory — ${r.cwd}\n\n${HEADING}\n${lesson}\n`);
88
- }
89
- else if (existing.includes(HEADING)) {
90
- await appendFile(file, `${lesson}\n`);
91
- }
92
- else {
93
- await appendFile(file, `\n${HEADING}\n${lesson}\n`);
94
- }
75
+ const kind = lessonKind(r);
76
+ if (kind)
77
+ await recordLesson(kind, r, { ts, cap });
78
+ }
79
+ catch { /* best-effort — never blocks or fails a turn */ }
80
+ }
81
+ /** The lesson a turn leaves: a loop, a stuck stop, or none — a sub-agent's turn never leaves one. */
82
+ export function lessonKind(r) {
83
+ if (isSubagentBrief(r.task || r.input))
84
+ return undefined;
85
+ return isLooped(r.loop) ? "loop" : endedStuck(r) ? "stuck" : undefined;
86
+ }
87
+ /** The loop lesson line for one looped turn (selfimprove/lessons.ts), filed under the owner's task; `taught` = the
88
+ * rules in the target memories file it reinforces; `home` shortens paths to ~. Pure. */
89
+ export function loopLessonLineFor(r, ts, taught = [], home) {
90
+ return loopLessonLine({ task: r.task || r.input, rounds: r.rounds, durationMs: r.durationMs, evidence: r.loop, ts, home, taught, interrupted: r.interrupted });
91
+ }
92
+ export async function loopLessonFor(r, ts, taught = []) {
93
+ const { homedir } = await nodeImport("node:os");
94
+ return loopLessonLineFor(r, ts, taught, homedir());
95
+ }
96
+ /** A memories file's text with one looped or stuck turn's lesson added or bumped (curateLessons). Pure. */
97
+ export function withLesson(kind, r, existing, o) {
98
+ const taught = reinforcedRules(existing);
99
+ const line = kind === "loop"
100
+ ? loopLessonLineFor(r, o.ts, taught, o.home)
101
+ : stuckLessonLine({ task: r.task || r.input, content: r.content, stopReason: r.stopReason, ts: o.ts, taught });
102
+ return upsertLesson(existing, line, o.ts, { cap: o.cap, taught });
103
+ }
104
+ /** Replace a memories file in one step (tmp + rename next to the real file, its mode kept): it is the owner's file,
105
+ * and a turn that dies mid-write must not leave half of it. */
106
+ export async function writeMemoriesAtomic(file, text) {
107
+ const { writeFile, rename, mkdir, stat, chmod, realpath } = await nodeImport("node:fs/promises");
108
+ const { dirname } = await nodeImport("node:path");
109
+ const real = await realpath(file).catch(() => file);
110
+ await mkdir(dirname(real), { recursive: true });
111
+ let mode;
112
+ try {
113
+ mode = (await stat(real)).mode & 0o777;
114
+ }
115
+ catch { /* a new file */ }
116
+ const tmp = `${real}.${process.pid}.${Date.now()}.tmp`;
117
+ await writeFile(tmp, text, { encoding: "utf8", mode: mode ?? 0o644 });
118
+ if (mode !== undefined)
119
+ await chmod(tmp, mode);
120
+ await rename(tmp, real);
121
+ }
122
+ /** Add or bump the lesson for one looped or stuck turn in a memories file (default: the global one). */
123
+ export async function recordLesson(kind, r, o) {
124
+ const { readFile } = await nodeImport("node:fs/promises");
125
+ const { homedir } = await nodeImport("node:os");
126
+ const file = o.file ?? globalMemoriesPath();
127
+ let existing = "";
128
+ try {
129
+ existing = await readFile(file, "utf8");
130
+ }
131
+ catch { /* none yet */ }
132
+ const up = withLesson(kind, r, existing, { ts: o.ts, cap: o.cap, home: homedir() });
133
+ if (up.text !== existing)
134
+ await writeMemoriesAtomic(file, up.text);
135
+ return { action: up.action, line: up.line, file };
136
+ }
137
+ /** Add or bump the lesson for one looped turn (recordLesson "loop"). */
138
+ export async function recordLoopLesson(r, o) {
139
+ return recordLesson("loop", r, o);
140
+ }
141
+ /** A loop recovery's lesson, written while the turn still runs (session.ts): the turn's record so far under the stamp its
142
+ * own lesson keeps (`lessonTs`), so a turn with two recoveries — and its end — counts once, with its strongest evidence. */
143
+ export async function recordRecoveryLesson(cfg, r) {
144
+ if (!cfg?.memory || lessonKind(r) !== "loop")
145
+ return;
146
+ try {
147
+ await recordLesson("loop", r, { ts: r.lessonTs, cap: cfg.maxLessons });
148
+ }
149
+ catch { /* best-effort — never blocks or fails a turn */ }
150
+ }
151
+ // ── Mentor pairs from loop recoveries ─────────────────────────────────────────
152
+ // A dead round's recovery hands the model what its repeated calls returned and asks for a different step (engine/agent.ts
153
+ // recoverDeadRound). The step it then takes is the other half of a DPO pair: rejected = the calls it kept repeating, chosen
154
+ // = the step that moved it forward. Same file and shape as the reviewers' pairs (flywheel/mentor-pairs-*.jsonl), marked
155
+ // `source: "loop-recovery"`. The engine saw the step run and differ, not that it was right: `verified` stays false until a
156
+ // reviewer sets it, and only a verified pair teaches (lessons.ts taughtLessons).
157
+ const PAIR_FIELD_CHARS = 1_000;
158
+ const capped = (s, n = PAIR_FIELD_CHARS) => { const t = redactSecrets(s); return t.length > n ? t.slice(0, n - 1) + "…" : t; };
159
+ const asCall = (c) => `${c.name} ${JSON.stringify(c.args)}`;
160
+ export const LOOP_PAIR_RATIONALE = "The repeated calls returned the same result each time and were refused as repeats; after the loop recovery this step moved " +
161
+ "the turn forward. Never re-run a call whose result you already have: take a different step — an edit, a different command, " +
162
+ "an updated task list, or a question to the owner.";
163
+ /** One loop recovery's mentor pair: every field masked (redactSecrets) before it is cut to length. */
164
+ export function loopMentorPair(o) {
165
+ return {
166
+ id: `loop-recovery-${o.ts.toString(36)}-${o.attempt}-${Math.random().toString(36).slice(2, 6)}`,
167
+ type: "dpo", source: "loop-recovery", trap: "repeated-call-loop", ts: new Date(o.ts).toISOString(), verified: false, model: o.model,
168
+ prompt: capped(ownerWords(o.request), 500),
169
+ rejected: capped(o.repeated.map((c) => `${asCall(c)} (ran ${c.ran}×, then refused as a repeat)`).join("\n")),
170
+ chosen: capped(o.forward.length ? o.forward.map(asCall).join("\n") : `answer: ${o.answer ?? ""}`),
171
+ rationale: LOOP_PAIR_RATIONALE,
172
+ };
173
+ }
174
+ /** Append a mentor pair to the day's flywheel/mentor-pairs-<day>.jsonl (owner-only, masked again whole). Best-effort. */
175
+ export async function recordMentorPair(pair, ts = Date.now()) {
176
+ try {
177
+ const { appendFile, mkdir } = await nodeImport("node:fs/promises");
178
+ const { join } = await nodeImport("node:path");
179
+ const dir = operatorPath("flywheel");
180
+ await mkdir(dir, { recursive: true, mode: 0o700 });
181
+ await appendFile(join(dir, `mentor-pairs-${new Date(ts).toISOString().slice(0, 10)}.jsonl`), redactSecrets(JSON.stringify(pair)) + "\n", { encoding: "utf8", mode: 0o600 });
95
182
  }
96
183
  catch { /* best-effort — never blocks or fails a turn */ }
97
184
  }
98
- /** Run the enabled self-improvement sinks for one completed turn. Fire-and-forget from the session. */
185
+ /** Run the enabled self-improvement sinks for one turn — completed, or interrupted (session.ts; a process going down uses
186
+ * selfimprove/sync.ts). Fire-and-forget from the session. */
99
187
  export async function runSelfImprove(cfg, r) {
100
188
  if (!cfg)
101
189
  return;
190
+ const ts = Date.now(); // one stamp for the row and its lesson: a later backfill sees the lesson already counted the row
102
191
  if (cfg.flywheel !== false)
103
- await captureFlywheel(r);
192
+ await captureFlywheel(r, ts);
104
193
  if (cfg.memory)
105
- await captureFailureLesson(r); // opt-in closed loop: a stuck session leaves a durable lesson
194
+ await captureFailureLesson(r, r.lessonTs ?? ts, cfg.maxLessons); // the closed loop: a looped or stuck turn leaves a durable lesson (under the stamp a recovery already wrote it with)
106
195
  // skills / reflect sinks hang off this same hook — implemented incrementally.
107
196
  }
108
197
  // Exposed for tests: the stuck-detection predicate is the trigger for the memory sink.