@0perator/operator 0.1.352 → 0.1.354
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.
- package/dist/acp/agent.js +4 -2
- package/dist/acp/tool-map.js +5 -4
- package/dist/autonomy/delegate.js +55 -2
- package/dist/autonomy/headless.js +4 -1
- package/dist/autonomy/session-factory.js +1 -0
- package/dist/background/index.js +86 -10
- package/dist/background/notices.js +16 -4
- package/dist/cli.js +1072 -178
- package/dist/config/home.js +6 -0
- package/dist/config/memory-sections.js +92 -0
- package/dist/config/persona.js +144 -26
- package/dist/config/settings.js +15 -4
- package/dist/consolidation/scheduler.js +9 -2
- package/dist/consolidation/sleep.js +39 -278
- package/dist/engine/agent.js +547 -92
- package/dist/engine/anthropic-chat.js +13 -2
- package/dist/engine/aurora.js +135 -30
- package/dist/engine/batch-scheduler.js +27 -3
- package/dist/engine/compaction.js +12 -5
- package/dist/engine/continuation.js +51 -22
- package/dist/engine/contract.js +1 -1
- package/dist/engine/decision-points.js +7 -1
- package/dist/engine/front-door.js +59 -0
- package/dist/engine/grandmaster.js +13 -1
- package/dist/engine/loop-guard.js +694 -0
- package/dist/engine/net-error.js +2 -1
- package/dist/engine/owner-act.js +52 -0
- package/dist/engine/selfheal.js +48 -0
- package/dist/engine/verify-gate.js +52 -0
- package/dist/flywheel/processor.js +3 -1
- package/dist/flywheel/srft.js +8 -4
- package/dist/hooks/index.js +12 -8
- package/dist/mcp/index.js +9 -4
- package/dist/permissions/index.js +32 -11
- package/dist/permissions/modes.js +42 -0
- package/dist/permissions/plan-review.js +100 -0
- package/dist/permissions/policy.js +16 -5
- package/dist/permissions/signature.js +8 -3
- package/dist/remote/safe-commands.js +1 -1
- package/dist/router/read-rates.js +152 -0
- package/dist/selfimprove/backfill.js +174 -0
- package/dist/selfimprove/index.js +146 -57
- package/dist/selfimprove/lessons.js +429 -0
- package/dist/selfimprove/sync.js +58 -0
- package/dist/session.js +375 -31
- package/dist/skills/finder.js +219 -0
- package/dist/tools/deferred.js +28 -18
- package/dist/tools/executor.js +7 -3
- package/dist/tools/registry.js +34 -4
- package/dist/ui/ActivitySpinner.js +21 -12
- package/dist/ui/App.js +107 -30
- package/dist/ui/ApprovalPrompt.js +5 -3
- package/dist/ui/ArtifactPicker.js +3 -3
- package/dist/ui/BgPanel.js +105 -5
- package/dist/ui/Composer.js +85 -9
- package/dist/ui/PlanPane.js +72 -8
- package/dist/ui/QuestionPrompt.js +6 -4
- package/dist/ui/SecretPrompt.js +8 -3
- package/dist/ui/SessionPicker.js +2 -2
- package/dist/ui/SkillFinder.js +153 -0
- package/dist/ui/StatusRule.js +5 -2
- package/dist/ui/SummaryCard.js +3 -1
- package/dist/ui/ThinkingSpinner.js +11 -2
- package/dist/ui/ToolBatch.js +11 -2
- package/dist/ui/ToolStep.js +36 -13
- package/dist/ui/Transcript.js +13 -2
- package/dist/ui/actNow.js +61 -0
- package/dist/ui/batchLine.js +165 -0
- package/dist/ui/conversations.js +154 -0
- package/dist/ui/decodeHealth.js +77 -0
- package/dist/ui/expand.js +17 -0
- package/dist/ui/fit.js +40 -0
- package/dist/ui/fitTail.js +14 -0
- package/dist/ui/fold.js +149 -0
- package/dist/ui/format.js +46 -2
- package/dist/ui/liveTools.js +163 -13
- package/dist/ui/modelPicker.js +78 -6
- package/dist/ui/nextStep.js +103 -0
- package/dist/ui/pending.js +57 -0
- package/dist/ui/phase.js +105 -0
- package/dist/ui/planExit.js +0 -5
- package/dist/ui/progressbar.js +4 -26
- package/dist/ui/readForecast.js +44 -0
- package/dist/ui/readProgress.js +119 -0
- package/dist/ui/reportLine.js +62 -0
- package/dist/ui/slashCommands.js +1 -1
- package/dist/ui/theme.js +1 -0
- package/dist/ui/turnFlow.js +72 -0
- package/dist/ui/turnLedger.js +121 -0
- package/dist/ui/turnScope.js +11 -0
- package/dist/util/slash.js +18 -0
- package/package.json +1 -1
|
@@ -0,0 +1,429 @@
|
|
|
1
|
+
// Lessons in the GLOBAL memories.md — the one store the self-improvement loop teaches through, loaded in every project.
|
|
2
|
+
// Pure string work (no node imports). Every writer goes through curateLessons: a live turn (selfimprove/index.ts), the
|
|
3
|
+
// fold over the flywheel and the reviewers' mentor pairs (selfimprove/backfill.ts — `operator selfimprove backfill` and
|
|
4
|
+
// sleep consolidation alike) and curateProjectMemories. config/persona.ts renders the same lines first in the prompt.
|
|
5
|
+
//
|
|
6
|
+
// One line per kind + class:
|
|
7
|
+
// - [loop·review ×3 · last 2026-11-02T14:15Z] "now review and test it all" — 37 rounds, 89 min: 5 loop warnings …
|
|
8
|
+
// - [stuck·repetition ×2 · last 2026-11-02T14:33Z] "use codestack" — the reply degenerated into a repetition loop …
|
|
9
|
+
// - [taught·branch-base ×1 · last 2026-10-21T00:00Z] Always name the base.
|
|
10
|
+
// loop and stuck come from my own turns, taught from a reviewer's verified mentor pair. A repeat bumps the count and
|
|
11
|
+
// `last` (a loop line keeps the strongest evidence seen); `last` is also the watermark that keeps a re-run idempotent
|
|
12
|
+
// (a turn at or before it was already counted).
|
|
13
|
+
import { describeReads } from "../engine/loop-guard.js";
|
|
14
|
+
import { inferType } from "../engine/grandmaster.js";
|
|
15
|
+
import { redactSecrets } from "../engine/redact.js";
|
|
16
|
+
import { taughtRules } from "../config/memory-sections.js";
|
|
17
|
+
export const LESSONS_HEADING = "## Lessons learned (my own turns and my reviewers' corrections — every project)";
|
|
18
|
+
/** Headings older writers used: captureFailureLesson's project stuck lessons before 2026-11-02, the old
|
|
19
|
+
* curateProjectMemories, and this section's first name. Read as lessons, rewritten only by curateLessons. */
|
|
20
|
+
export const LEGACY_LESSON_HEADINGS = [
|
|
21
|
+
"## Lessons (auto-captured from stuck sessions)", "## Lessons (auto-captured)", "## Lessons learned (auto-captured from my own turns — every project)",
|
|
22
|
+
];
|
|
23
|
+
export const isLessonHeading = (line) => {
|
|
24
|
+
const t = line.trim();
|
|
25
|
+
return t === LESSONS_HEADING || LEGACY_LESSON_HEADINGS.includes(t);
|
|
26
|
+
};
|
|
27
|
+
export const LESSON_MAX_CHARS = 480; // 440 until the rule named line ranges and the announced fix (11/02 replay): 40 more keeps three re-read files in the line
|
|
28
|
+
/** Lines one lessons section keeps (settings.autonomy.sleepConsolidation.maxLessonsPerFile overrides). 49 distinct
|
|
29
|
+
* mentor traps (11/02) plus a line per loop / stuck class fit with room; past it the oldest taught lines go first. */
|
|
30
|
+
export const MAX_LESSONS = 100;
|
|
31
|
+
export const KIND_ORDER = ["loop", "stuck", "taught"];
|
|
32
|
+
const TAG_RE = /^- \[(\w+)·([\w-]+) ×(\d+) · last (\d{4}-\d{2}-\d{2}T\d{2}:\d{2})Z\]/;
|
|
33
|
+
export function parseLessonTag(line) {
|
|
34
|
+
const m = TAG_RE.exec(line);
|
|
35
|
+
return m ? { kind: m[1], cls: m[2], count: Number(m[3]), last: m[4] } : null;
|
|
36
|
+
}
|
|
37
|
+
const minute = (ts) => new Date(ts).toISOString().slice(0, 16);
|
|
38
|
+
const tag = (t) => `- [${t.kind}·${t.cls} ×${t.count} · last ${t.last}Z]`;
|
|
39
|
+
const keyOf = (t) => `${t.kind}·${t.cls}`;
|
|
40
|
+
const slug = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "general";
|
|
41
|
+
const ANSWER_CLASSES = new Set(["review", "search", "research", "plan"]);
|
|
42
|
+
/** A sub-agent's turn (grandmaster.ts briefCore): its lesson would teach the owner's prompt about a task the owner never
|
|
43
|
+
* set, and a sub-agent never loads these memories (persona.ts subagentSystemPrompt). Its row still never trains. */
|
|
44
|
+
export const isSubagentBrief = (task) => /^\s*# Sub-agent brief\b/.test(task);
|
|
45
|
+
/** The owner's words: a carried engine note at the head of a turn's input is the engine's, not the task. */
|
|
46
|
+
export function ownerWords(input) {
|
|
47
|
+
let t = input.trim();
|
|
48
|
+
while (t.startsWith("[engine note")) {
|
|
49
|
+
const cut = t.indexOf("\n\n");
|
|
50
|
+
if (cut < 0)
|
|
51
|
+
break;
|
|
52
|
+
t = t.slice(cut + 2).trim();
|
|
53
|
+
}
|
|
54
|
+
return t.replace(/\s+/g, " ");
|
|
55
|
+
}
|
|
56
|
+
// ── Taught rules an auto lesson reinforces ───────────────────────────────────
|
|
57
|
+
// A loop or stuck lesson is the same failure a reviewer already wrote a rule for — "Bias to action — build, don't
|
|
58
|
+
// circle", HARD RULE 3 DECISIVENESS (anti-micro-stepping). The lesson names those rules ("Taught as …: <rule>") so the
|
|
59
|
+
// prompt carries one reinforced rule, not a second, unconnected one. Matched on rule names only: a note that merely
|
|
60
|
+
// mentions a circle ("the 46-min circle here") is not a rule about circling.
|
|
61
|
+
const CIRCLING_RE = /circl|re-?read|re-?grep|over-?gather|micro-?step/i;
|
|
62
|
+
/** The taught rules in a memories file that a loop / stuck lesson reinforces, by name, in file order. */
|
|
63
|
+
export function reinforcedRules(memoriesText) {
|
|
64
|
+
return taughtRules(memoriesText, isLessonHeading).filter((r) => CIRCLING_RE.test(r.title)).map((r) => r.name);
|
|
65
|
+
}
|
|
66
|
+
const ruleClause = (rule, taught = []) => taught.length ? `Taught as ${taught.join(" + ")}: ${rule}` : `Rule: ${rule}`;
|
|
67
|
+
// The rule for a loop of repeated CALLS (a command, a tool) with no file in it: reading less is not the fix there.
|
|
68
|
+
const CALL_LOOP_RULE = "the same call gave the same result again — change the command or the approach (another tool, a smaller step), or say what blocks you; never re-run it unchanged.";
|
|
69
|
+
function checkHint(files) {
|
|
70
|
+
if (files.some((f) => /\.[cm]?tsx?$/.test(f)))
|
|
71
|
+
return " (npx tsc --noEmit)";
|
|
72
|
+
if (files.some((f) => f.endsWith(".py")))
|
|
73
|
+
return " (pytest)";
|
|
74
|
+
return "";
|
|
75
|
+
}
|
|
76
|
+
/** The loop lesson for one turn: what happened (task, size, warnings, the files re-read and how often) and the rule
|
|
77
|
+
* for next time, which depends on whether the task wanted an answer or a change; `taught` = the rules it reinforces.
|
|
78
|
+
* At most LESSON_MAX_CHARS. */
|
|
79
|
+
export function loopLessonLine(o) {
|
|
80
|
+
// Everything written here lands in a file every session puts in its system prompt, for every model, cloud vendors
|
|
81
|
+
// included: secret shapes are masked before anything is cut to length (a cut token no longer matches its pattern).
|
|
82
|
+
const words = ownerWords(redactSecrets(o.task));
|
|
83
|
+
const cls = inferType(words); // the task class: the sub-agent role vocabulary
|
|
84
|
+
const e = { ...o.evidence, rereads: o.evidence.rereads.map((r) => ({ ...r, target: redactSecrets(r.target) })) };
|
|
85
|
+
const files = e.rereads.filter((r) => !r.target.startsWith("$ ") && !/^\w+ \{/.test(r.target));
|
|
86
|
+
const hint = checkHint(files.map((f) => f.target));
|
|
87
|
+
// 11/02 replay: with the lesson loaded the model read files once — then re-ran the same `sed -n` line ranges four times,
|
|
88
|
+
// each time announcing "Fixing them now." So the rule names ranges, and the announced fix.
|
|
89
|
+
const rule = ruleClause(!files.length && e.rereads.length ? CALL_LOOP_RULE : ANSWER_CLASSES.has(cls)
|
|
90
|
+
? `read each file or line range once; a fix you announce is your next call; answer with the type-check/tests${hint} as proof, not re-reads or a bare build.`
|
|
91
|
+
: `read only the lines you will change, once; a fix you announce is your next call — the smallest edit, verified with the type-check/tests${hint}; never re-read an unchanged file.`, o.taught);
|
|
92
|
+
const head = tag({ kind: "loop", cls, count: 1, last: minute(o.ts) });
|
|
93
|
+
const size = `${o.rounds} rounds${o.durationMs ? `, ${Math.max(1, Math.round(o.durationMs / 60000))} min` : ""}${o.interrupted ? ", interrupted" : ""}`;
|
|
94
|
+
const recovered = e.recoveries ?? 0;
|
|
95
|
+
const warned = `${e.nudges} loop warning${e.nudges === 1 ? "" : "s"}${e.ignored ? ` (${e.ignored} ignored)` : ""}` +
|
|
96
|
+
(e.compactions ? `, ${e.compactions} loop reset${e.compactions === 1 ? "" : "s"}` : "") +
|
|
97
|
+
(recovered ? `, ${recovered} round${recovered === 1 ? "" : "s"} of refused repeats recovered` : "");
|
|
98
|
+
const build = (task, reads) => `${head} "${task}" — ${size}: ${warned}${reads ? `; re-read ${reads}` : ""}. ${rule}`;
|
|
99
|
+
let task = words.slice(0, 60);
|
|
100
|
+
const budget = LESSON_MAX_CHARS - build(task, "").length - "; re-read ".length;
|
|
101
|
+
let reads = files.length ? describeReads(files, budget, o.home) : "";
|
|
102
|
+
if (!files.length) {
|
|
103
|
+
for (const r of e.rereads) { // a repeated command: its words shortened, never its count
|
|
104
|
+
const item = `${r.target.length > 60 ? r.target.slice(0, 59) + "…" : r.target} ×${r.count}`;
|
|
105
|
+
if ((reads ? reads.length + 2 : 0) + item.length > budget)
|
|
106
|
+
break;
|
|
107
|
+
reads = reads ? `${reads}, ${item}` : item;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
let line = build(task, reads);
|
|
111
|
+
while (line.length > LESSON_MAX_CHARS && task.length > 20) {
|
|
112
|
+
task = task.slice(0, task.length - 10).trimEnd() + "…";
|
|
113
|
+
line = build(task, reads);
|
|
114
|
+
}
|
|
115
|
+
if (line.length > LESSON_MAX_CHARS) {
|
|
116
|
+
reads = "";
|
|
117
|
+
line = build(task, reads);
|
|
118
|
+
}
|
|
119
|
+
return line.slice(0, LESSON_MAX_CHARS);
|
|
120
|
+
}
|
|
121
|
+
// ── Stuck lessons: a turn that ended on an engine stop ───────────────────────
|
|
122
|
+
// What captureFailureLesson wrote per turn into the project file before 2026-11-02 ("Got stuck on task …"), now one
|
|
123
|
+
// line per stop class in the global store. The rule is the one those lessons taught, verbatim.
|
|
124
|
+
const STUCK_RULE = "break the step down or switch approach early instead of repeating; if it involved sub-agents contending for one model endpoint, do the work inline.";
|
|
125
|
+
// The stops that are circling — the failure the taught circling rules are about. A degenerated reply (repetition) or an
|
|
126
|
+
// outgrown window (context) is not, so their lessons name no taught rule.
|
|
127
|
+
const CIRCLING_STUCK = new Set(["circles", "repeated-step", "converge"]);
|
|
128
|
+
const STUCK_CLASSES = [
|
|
129
|
+
["repetition", /degenerated into a repetition loop/i, "the reply degenerated into a repetition loop and was cut off"],
|
|
130
|
+
["circles", /going in circles/i, "it said it was going in circles without making a change that broke the loop"],
|
|
131
|
+
["repeated-step", /repeated the same step/i, "it repeated the same step while the tools returned nothing new"],
|
|
132
|
+
["converge", /not converging|no write-progress in/i, "it ran tool round after tool round with no new explanation and no file change"],
|
|
133
|
+
["context", /context is over this model's window|compaction can't free/i, "the context outgrew the model's window and compaction could not free it"],
|
|
134
|
+
];
|
|
135
|
+
/** A stuck turn's stop class and what happened, from its final text (the engine's "[stopped — …]" note) or its
|
|
136
|
+
* repetition stopReason; a turn cut for repetition mid-answer keeps the model's own text, so it is "repetition". */
|
|
137
|
+
export function stuckClass(content, stopReason) {
|
|
138
|
+
const c = STUCK_CLASSES.find(([, re]) => re.test(content));
|
|
139
|
+
if (c)
|
|
140
|
+
return { cls: c[0], what: c[2] };
|
|
141
|
+
if (stopReason === "repetition" || !/^\[stopped\s[—-]/.test(content.trim()))
|
|
142
|
+
return { cls: "repetition", what: STUCK_CLASSES[0][2] };
|
|
143
|
+
return { cls: "other", what: content.trim().replace(/^\[stopped\s[—-]\s*/, "").replace(/\s+/g, " ").slice(0, 140) };
|
|
144
|
+
}
|
|
145
|
+
export function stuckLessonLine(o) {
|
|
146
|
+
const { cls, what } = stuckClass(redactSecrets(o.content), o.stopReason);
|
|
147
|
+
const task = ownerWords(redactSecrets(o.task)).slice(0, 90);
|
|
148
|
+
const line = `${tag({ kind: "stuck", cls, count: o.count ?? 1, last: o.last ?? minute(o.ts) })} "${task}" — ${what}. ${ruleClause(STUCK_RULE, CIRCLING_STUCK.has(cls) ? o.taught : [])}`;
|
|
149
|
+
return line.slice(0, LESSON_MAX_CHARS);
|
|
150
|
+
}
|
|
151
|
+
const LEGACY_RE = /^- \[(\d{4}-\d{2}-\d{2})\] Got stuck on task "(.*?)": (.*?)(?: — next time, .*)?$/;
|
|
152
|
+
/** The old per-turn stuck lessons of a project file, folded into one line per stop class: the count, the latest day,
|
|
153
|
+
* the first task as the example. Nothing they taught is dropped — they all taught the same rule. */
|
|
154
|
+
export function foldLegacyLessons(lines, taught = []) {
|
|
155
|
+
const groups = new Map();
|
|
156
|
+
for (const l of lines) {
|
|
157
|
+
const m = LEGACY_RE.exec(l);
|
|
158
|
+
if (!m)
|
|
159
|
+
continue;
|
|
160
|
+
const { cls } = stuckClass(m[3]);
|
|
161
|
+
const g = groups.get(cls);
|
|
162
|
+
if (g) {
|
|
163
|
+
g.count++;
|
|
164
|
+
if (m[1] > g.last.slice(0, 10))
|
|
165
|
+
g.last = `${m[1]}T00:00`;
|
|
166
|
+
}
|
|
167
|
+
else
|
|
168
|
+
groups.set(cls, { first: { task: m[2], gist: m[3] }, count: 1, last: `${m[1]}T00:00` });
|
|
169
|
+
}
|
|
170
|
+
return [...groups.values()].map((g) => stuckLessonLine({ task: g.first.task, content: g.first.gist, ts: 0, count: g.count, last: g.last, taught }));
|
|
171
|
+
}
|
|
172
|
+
export const TAUGHT_RULE_MAX = 220;
|
|
173
|
+
const IMPERATIVE_RE = /^(?:always|never|don'?t|do not|when|whenever|before|after|once|if|check|name|read|run|use|write|verify|match|test|survey|stop|keep|resolve|fix|open|look|proceed|prefer|re-?run|re-?grep|commit|grep|act|state|either|every|each|any|only|restate|counts? come|record|split|substitute|trace|switch|rm|ask|report|treat|put)\b/i;
|
|
174
|
+
const MODAL_RE = /\b(?:must|never|always|only when|don'?t|do not|is the craft|first move|the move is|before)\b/i;
|
|
175
|
+
function sentences(t) {
|
|
176
|
+
if (typeof t !== "string")
|
|
177
|
+
return [];
|
|
178
|
+
const out = [];
|
|
179
|
+
let cur = "";
|
|
180
|
+
for (const p of redactSecrets(t).replace(/\s+/g, " ").trim().split(/(?<=[.!?])\s+/)) {
|
|
181
|
+
cur = cur ? `${cur} ${p}` : p;
|
|
182
|
+
if (/(?:\be\.g|\bi\.e|\bvs|\betc|\bcf)\.$/i.test(cur))
|
|
183
|
+
continue; // an abbreviation, not a sentence end
|
|
184
|
+
if (cur)
|
|
185
|
+
out.push(cur);
|
|
186
|
+
cur = "";
|
|
187
|
+
}
|
|
188
|
+
if (cur)
|
|
189
|
+
out.push(cur);
|
|
190
|
+
return out;
|
|
191
|
+
}
|
|
192
|
+
function fit(ss, cap) {
|
|
193
|
+
let out = "";
|
|
194
|
+
for (const s of ss) {
|
|
195
|
+
const next = out ? `${out} ${s}` : s;
|
|
196
|
+
if (next.length > cap) {
|
|
197
|
+
if (!out)
|
|
198
|
+
out = s.slice(0, cap).replace(/\s+\S*$/, "").replace(/[,;:]$/, "") + "…";
|
|
199
|
+
break;
|
|
200
|
+
}
|
|
201
|
+
out = next;
|
|
202
|
+
}
|
|
203
|
+
return out;
|
|
204
|
+
}
|
|
205
|
+
/** The reviewer's rule from a pair: its rule sentences (imperative, or must / never / always / only when / don't) from
|
|
206
|
+
* the rationale, else from the chosen answer, else the rationale's opening — at most TAUGHT_RULE_MAX chars. */
|
|
207
|
+
export function distillMentorRule(p) {
|
|
208
|
+
const pools = [sentences(p.rationale), sentences(p.chosen), sentences(p.completion)];
|
|
209
|
+
for (const pool of pools) {
|
|
210
|
+
const rules = pool.filter((s) => IMPERATIVE_RE.test(s) || MODAL_RE.test(s));
|
|
211
|
+
if (rules.length)
|
|
212
|
+
return fit(rules, TAUGHT_RULE_MAX);
|
|
213
|
+
}
|
|
214
|
+
for (const pool of pools)
|
|
215
|
+
if (pool.length)
|
|
216
|
+
return fit(pool, TAUGHT_RULE_MAX);
|
|
217
|
+
return "";
|
|
218
|
+
}
|
|
219
|
+
/** Lesson 1's traps (mentor-pairs-2026-10-21, the four pairs the owner wrote up as "Engineering traps — HARD RULES
|
|
220
|
+
* … learned live in Lesson 1 with Forge") and the rule each became. A taught line for one of them says it is that
|
|
221
|
+
* rule, so the prompt carries one rule, not two disconnected ones. Rules 5+ came from other lessons. */
|
|
222
|
+
export const LESSON_1_HARD_RULES = { "branch-base": 1, "test-vs-code": 2, "micro-stepping": 3, "passive-wait": 4 };
|
|
223
|
+
/** The HARD RULES a memories file numbers, by number → how a lesson names it (`HARD RULE 1 BRANCH BASE`); the first
|
|
224
|
+
* section that numbers a rule wins. */
|
|
225
|
+
export function hardRuleNames(memoriesText) {
|
|
226
|
+
const out = new Map();
|
|
227
|
+
for (const r of taughtRules(memoriesText, isLessonHeading)) {
|
|
228
|
+
const n = /^HARD RULE (\d+) /.exec(r.name)?.[1];
|
|
229
|
+
if (n && !out.has(Number(n)))
|
|
230
|
+
out.set(Number(n), r.name);
|
|
231
|
+
}
|
|
232
|
+
return out;
|
|
233
|
+
}
|
|
234
|
+
/** The mentor pairs as taught lessons, one per trap — a pair with no trap is keyed by its lens, numbered from the
|
|
235
|
+
* second (`chain-to-completion`, `chain-to-completion-2`): two rules under one lens are two lessons. Only verified
|
|
236
|
+
* pairs with a rule teach. `date` = the pair file's day; `hardRules` = the target file's (hardRuleNames). */
|
|
237
|
+
export function taughtLessons(pairs, hardRules = new Map()) {
|
|
238
|
+
const lensSeen = new Map();
|
|
239
|
+
const out = [];
|
|
240
|
+
for (const { pair: p, date } of pairs) {
|
|
241
|
+
if (!p || typeof p !== "object" || !p.id || !p.verified)
|
|
242
|
+
continue;
|
|
243
|
+
const rule = distillMentorRule(p);
|
|
244
|
+
if (!rule)
|
|
245
|
+
continue;
|
|
246
|
+
let cls = p.trap ? slug(p.trap) : "";
|
|
247
|
+
if (!cls) {
|
|
248
|
+
const lens = slug(p.lens || "general");
|
|
249
|
+
const n = (lensSeen.get(lens) ?? 0) + 1;
|
|
250
|
+
lensSeen.set(lens, n);
|
|
251
|
+
cls = n === 1 ? lens : `${lens}-${n}`;
|
|
252
|
+
}
|
|
253
|
+
const own = typeof p.ts === "string" ? Date.parse(p.ts) : NaN;
|
|
254
|
+
const ts = Number.isFinite(own) ? own : Date.parse(`${date}T00:00:00Z`);
|
|
255
|
+
if (!Number.isFinite(ts))
|
|
256
|
+
continue;
|
|
257
|
+
const same = hardRules.get(LESSON_1_HARD_RULES[cls] ?? 0);
|
|
258
|
+
out.push({ line: `${tag({ kind: "taught", cls, count: 1, last: minute(ts) })} ${same ? `Same as ${same}: ` : ""}${rule}`, ts, id: String(p.id), cls });
|
|
259
|
+
}
|
|
260
|
+
return out;
|
|
261
|
+
}
|
|
262
|
+
// ── The section: parse, curate, render ───────────────────────────────────────
|
|
263
|
+
/** Every lessons section's bounds in a file: [heading line, end) by line index. */
|
|
264
|
+
function sectionBounds(lines) {
|
|
265
|
+
const out = [];
|
|
266
|
+
for (let i = 0; i < lines.length; i++) {
|
|
267
|
+
if (!isLessonHeading(lines[i]))
|
|
268
|
+
continue;
|
|
269
|
+
let end = i + 1;
|
|
270
|
+
while (end < lines.length && !/^#{1,2} /.test(lines[end]))
|
|
271
|
+
end++;
|
|
272
|
+
out.push([i, end]);
|
|
273
|
+
i = end - 1;
|
|
274
|
+
}
|
|
275
|
+
return out;
|
|
276
|
+
}
|
|
277
|
+
// A lesson the owner retired: its text struck through or marked OBSOLETE / SUPERSEDED right after its tag —
|
|
278
|
+
// "- [loop·review ×3 · last …Z] ~~…~~", "- [2026-10-15] OBSOLETE Got stuck on task …". Lesson lines only, these marks
|
|
279
|
+
// only, case-sensitive: an owner's note that says "obsolete" or "Superseded" is a note, kept as written.
|
|
280
|
+
const RETIRED_RE = /^- \[[^\]]*\]\s*(?:~~|OBSOLETE\b|SUPERSEDED\b)/;
|
|
281
|
+
/** A line without its retired mark: an old stuck lesson marked OBSOLETE is still recognised as one. */
|
|
282
|
+
const unmarked = (l) => l.replace(/^(- \[[^\]]*\])\s*(?:~~|OBSOLETE\b|SUPERSEDED\b)[\s:—-]*/, "$1 ");
|
|
283
|
+
/** A memories file's lessons — every lessons section, the old stuck lessons folded per class (`taught` = the rules they
|
|
284
|
+
* reinforce) — and the file without those sections. `other` = the sections' other lines (an owner's note under the
|
|
285
|
+
* heading, a `/remember` note an older build appended there), kept as written: only a run of blank lines is folded
|
|
286
|
+
* to one, and none trail. */
|
|
287
|
+
export function splitLessons(fileText, taught = []) {
|
|
288
|
+
const lines = fileText.split("\n");
|
|
289
|
+
const bounds = sectionBounds(lines);
|
|
290
|
+
if (!bounds.length)
|
|
291
|
+
return { lessons: [], other: [], rest: fileText };
|
|
292
|
+
const tagged = [], legacy = [], other = [];
|
|
293
|
+
for (const [s, e] of bounds) {
|
|
294
|
+
for (const l of lines.slice(s + 1, e)) {
|
|
295
|
+
if (parseLessonTag(l)) {
|
|
296
|
+
if (!RETIRED_RE.test(l))
|
|
297
|
+
tagged.push(l);
|
|
298
|
+
}
|
|
299
|
+
else if (LEGACY_RE.test(unmarked(l))) {
|
|
300
|
+
if (!RETIRED_RE.test(l))
|
|
301
|
+
legacy.push(l);
|
|
302
|
+
}
|
|
303
|
+
else if (l.trim() || !other.length || other[other.length - 1].trim())
|
|
304
|
+
other.push(l); // a run of blank lines → one
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
while (other.length && !other[other.length - 1].trim())
|
|
308
|
+
other.pop();
|
|
309
|
+
const restLines = [];
|
|
310
|
+
let at = 0;
|
|
311
|
+
for (const [s, e] of bounds) {
|
|
312
|
+
restLines.push(...lines.slice(at, s));
|
|
313
|
+
at = e;
|
|
314
|
+
}
|
|
315
|
+
restLines.push(...lines.slice(at));
|
|
316
|
+
return { lessons: mergeLessons(tagged, foldLegacyLessons(legacy, taught)), other, rest: restLines.join("\n") };
|
|
317
|
+
}
|
|
318
|
+
/** Lessons in canonical order: auto lessons before taught ones, then the most recently confirmed first. */
|
|
319
|
+
export function orderLessons(lines) {
|
|
320
|
+
const rank = (k) => { const i = KIND_ORDER.indexOf(k); return i < 0 ? KIND_ORDER.length : i; };
|
|
321
|
+
return lines
|
|
322
|
+
.map((l) => ({ l, t: parseLessonTag(l) }))
|
|
323
|
+
.sort((a, b) => rank(a.t.kind) - rank(b.t.kind) || (a.t.last === b.t.last ? (a.t.cls < b.t.cls ? -1 : a.t.cls > b.t.cls ? 1 : 0) : a.t.last < b.t.last ? 1 : -1))
|
|
324
|
+
.map((x) => x.l);
|
|
325
|
+
}
|
|
326
|
+
/** Lines from two files (the global store and a project's older stuck lessons) as one list: a kind + class in both is
|
|
327
|
+
* one line — the counts add (different turns), the newer line's words and `last` win. */
|
|
328
|
+
export function mergeLessons(a, b) {
|
|
329
|
+
const out = new Map();
|
|
330
|
+
for (const l of [...a, ...b]) {
|
|
331
|
+
const t = parseLessonTag(l);
|
|
332
|
+
if (!t)
|
|
333
|
+
continue;
|
|
334
|
+
const prev = out.get(keyOf(t));
|
|
335
|
+
if (!prev) {
|
|
336
|
+
out.set(keyOf(t), l);
|
|
337
|
+
continue;
|
|
338
|
+
}
|
|
339
|
+
const p = parseLessonTag(prev);
|
|
340
|
+
const newer = t.last > p.last ? { t, l } : { t: p, l: prev };
|
|
341
|
+
out.set(keyOf(t), tag({ ...newer.t, count: p.count + t.count }) + newer.l.slice(tag(newer.t).length));
|
|
342
|
+
}
|
|
343
|
+
return orderLessons([...out.values()]);
|
|
344
|
+
}
|
|
345
|
+
/** How much a loop line's evidence shows: its re-read counts, then its ignored warnings, then its rounds. Over the whole
|
|
346
|
+
* flywheel (what sleep consolidation reads) the first `loop·review` row is 10/19's `$ echo "test" ×2`; last night's
|
|
347
|
+
* 92 re-reads of five files is the evidence that teaches. */
|
|
348
|
+
function strength(line) {
|
|
349
|
+
const body = line.slice(line.indexOf("] ") + 2);
|
|
350
|
+
return [[...body.matchAll(/×(\d+)/g)].reduce((s, m) => s + Number(m[1]), 0), Number(/\((\d+) ignored\)/.exec(body)?.[1] ?? 0), Number(/ — (\d+) rounds/.exec(body)?.[1] ?? 0)];
|
|
351
|
+
}
|
|
352
|
+
const stronger = (a, b) => { for (let i = 0; i < a.length; i++)
|
|
353
|
+
if (a[i] !== b[i])
|
|
354
|
+
return a[i] > b[i]; return false; };
|
|
355
|
+
/** THE curation of a lessons section — every writer goes through it, so a live turn, the backfill and sleep
|
|
356
|
+
* consolidation give the same file for the same input. Each incoming line (ts order) is deduplicated by kind + class:
|
|
357
|
+
* a newer one bumps that line's count and `last` (a loop line takes its words when its evidence is stronger), one at
|
|
358
|
+
* or before `last` was already counted (a loop line of the same minute — the same turn again — still takes stronger
|
|
359
|
+
* words), a new key is added.
|
|
360
|
+
* The section is then written in canonical order (orderLessons) and capped at `cap` lines (the oldest taught lines go
|
|
361
|
+
* first); older stuck lessons in the file are folded in and retired lessons dropped; the section's other lines (an
|
|
362
|
+
* owner's notes) follow the lessons as written. Everything outside the section stays byte-for-byte; a section is
|
|
363
|
+
* created at the end of the file when there is none (persona.ts appendMemory then adds a note before it). */
|
|
364
|
+
export function curateLessons(fileText, incoming, o = {}) {
|
|
365
|
+
const lines = fileText.split("\n");
|
|
366
|
+
const bounds = sectionBounds(lines);
|
|
367
|
+
const { lessons, other } = splitLessons(fileText, o.taught ?? []);
|
|
368
|
+
// Every lesson leaves here masked (redact.ts), whoever built it: the file goes into every session's system prompt.
|
|
369
|
+
const byKey = new Map(lessons.map((l) => [keyOf(parseLessonTag(l)), redactSecrets(l)]));
|
|
370
|
+
const actions = [];
|
|
371
|
+
for (const { line: raw, ts } of incoming) {
|
|
372
|
+
const line = redactSecrets(raw);
|
|
373
|
+
const want = parseLessonTag(line);
|
|
374
|
+
if (!want) {
|
|
375
|
+
actions.push("unchanged");
|
|
376
|
+
continue;
|
|
377
|
+
}
|
|
378
|
+
const have = byKey.get(keyOf(want));
|
|
379
|
+
const haveTag = have ? parseLessonTag(have) : null;
|
|
380
|
+
if (!have || !haveTag) {
|
|
381
|
+
byKey.set(keyOf(want), line);
|
|
382
|
+
actions.push("added");
|
|
383
|
+
continue;
|
|
384
|
+
}
|
|
385
|
+
if (minute(ts) <= haveTag.last) {
|
|
386
|
+
// The same minute is the same turn again (a live turn writes its lesson at a loop recovery, then at its end with the
|
|
387
|
+
// same stamp): counted once, but a loop line takes the stronger evidence.
|
|
388
|
+
const refresh = minute(ts) === haveTag.last && want.kind === "loop" && stronger(strength(line), strength(have));
|
|
389
|
+
if (refresh)
|
|
390
|
+
byKey.set(keyOf(want), tag(haveTag) + line.slice(tag(want).length));
|
|
391
|
+
actions.push(refresh ? "updated" : "unchanged");
|
|
392
|
+
continue;
|
|
393
|
+
}
|
|
394
|
+
const words = want.kind === "loop" && stronger(strength(line), strength(have)) ? line.slice(tag(want).length) : have.slice(tag(haveTag).length);
|
|
395
|
+
byKey.set(keyOf(want), tag({ ...haveTag, count: haveTag.count + 1, last: minute(ts) }) + words);
|
|
396
|
+
actions.push("updated");
|
|
397
|
+
}
|
|
398
|
+
const ordered = orderLessons([...byKey.values()]);
|
|
399
|
+
const cap = Math.max(1, o.cap ?? MAX_LESSONS);
|
|
400
|
+
const kept = ordered.slice(0, cap);
|
|
401
|
+
const dropped = ordered.slice(cap);
|
|
402
|
+
const body = [...kept, ...other];
|
|
403
|
+
if (!bounds.length) {
|
|
404
|
+
if (!body.length)
|
|
405
|
+
return { text: fileText, actions, dropped };
|
|
406
|
+
const head = fileText.replace(/\s*$/, "");
|
|
407
|
+
return { text: `${head ? head + "\n\n" : "# Operator memories\n\n"}${LESSONS_HEADING}\n${body.join("\n")}\n`, actions, dropped };
|
|
408
|
+
}
|
|
409
|
+
const [s0, e0] = bounds[0];
|
|
410
|
+
let blanks = e0;
|
|
411
|
+
while (blanks > s0 + 1 && !lines[blanks - 1].trim())
|
|
412
|
+
blanks--;
|
|
413
|
+
const out = [...lines.slice(0, s0), LESSONS_HEADING, ...body, ...lines.slice(blanks, e0)];
|
|
414
|
+
let at = e0;
|
|
415
|
+
for (const [s, e] of bounds.slice(1)) {
|
|
416
|
+
out.push(...lines.slice(at, s));
|
|
417
|
+
at = e;
|
|
418
|
+
}
|
|
419
|
+
out.push(...lines.slice(at));
|
|
420
|
+
const text = out.join("\n");
|
|
421
|
+
return { text: text === fileText ? fileText : text, actions, dropped };
|
|
422
|
+
}
|
|
423
|
+
/** One line into a file's lessons section (curateLessons with a single incoming line). */
|
|
424
|
+
export function upsertLesson(fileText, line, ts, o = {}) {
|
|
425
|
+
const r = curateLessons(fileText, [{ line, ts }], o);
|
|
426
|
+
const want = parseLessonTag(line);
|
|
427
|
+
const now = want ? splitLessons(r.text).lessons.find((l) => keyOf(parseLessonTag(l)) === keyOf(want)) : undefined;
|
|
428
|
+
return { text: r.text, action: r.actions[0] ?? "unchanged", line: now ?? line };
|
|
429
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// The self-improvement sinks for a process that is going down — a SIGTERM / SIGHUP / SIGINT handler, where nothing can be
|
|
2
|
+
// awaited (cli.tsx teardown). The same row and the same lesson runSelfImprove writes (selfimprove/index.ts flywheelRow /
|
|
3
|
+
// withLesson), with synchronous I/O. Node-only: only session.ts imports it, for the turn still in flight. Best-effort.
|
|
4
|
+
import { appendFileSync, chmodSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { dirname, join } from "node:path";
|
|
7
|
+
import { globalMemoriesPath, operatorPath } from "../config/home.js";
|
|
8
|
+
import { flywheelRow, lessonKind, withLesson } from "./index.js";
|
|
9
|
+
/** writeMemoriesAtomic, synchronously: tmp + rename next to the real file, its mode kept. */
|
|
10
|
+
export function writeMemoriesAtomicSync(file, text) {
|
|
11
|
+
let real = file;
|
|
12
|
+
try {
|
|
13
|
+
real = realpathSync(file);
|
|
14
|
+
}
|
|
15
|
+
catch { /* a new file */ }
|
|
16
|
+
mkdirSync(dirname(real), { recursive: true });
|
|
17
|
+
let mode;
|
|
18
|
+
try {
|
|
19
|
+
mode = statSync(real).mode & 0o777;
|
|
20
|
+
}
|
|
21
|
+
catch { /* a new file */ }
|
|
22
|
+
const tmp = `${real}.${process.pid}.${Date.now()}.tmp`;
|
|
23
|
+
writeFileSync(tmp, text, { encoding: "utf8", mode: mode ?? 0o644 });
|
|
24
|
+
if (mode !== undefined)
|
|
25
|
+
chmodSync(tmp, mode);
|
|
26
|
+
renameSync(tmp, real);
|
|
27
|
+
}
|
|
28
|
+
export function runSelfImproveSync(cfg, r) {
|
|
29
|
+
if (!cfg)
|
|
30
|
+
return;
|
|
31
|
+
const ts = Date.now();
|
|
32
|
+
if (cfg.flywheel !== false) {
|
|
33
|
+
try {
|
|
34
|
+
const dir = operatorPath("flywheel");
|
|
35
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
36
|
+
const { day, line } = flywheelRow(r, ts);
|
|
37
|
+
appendFileSync(join(dir, day), line, { encoding: "utf8", mode: 0o600 });
|
|
38
|
+
}
|
|
39
|
+
catch { /* best-effort */ }
|
|
40
|
+
}
|
|
41
|
+
if (!cfg.memory)
|
|
42
|
+
return;
|
|
43
|
+
try {
|
|
44
|
+
const kind = lessonKind(r);
|
|
45
|
+
if (!kind)
|
|
46
|
+
return;
|
|
47
|
+
const file = globalMemoriesPath();
|
|
48
|
+
let existing = "";
|
|
49
|
+
try {
|
|
50
|
+
existing = readFileSync(file, "utf8");
|
|
51
|
+
}
|
|
52
|
+
catch { /* none yet */ }
|
|
53
|
+
const up = withLesson(kind, r, existing, { ts: r.lessonTs ?? ts, cap: cfg.maxLessons, home: homedir() });
|
|
54
|
+
if (up.text !== existing)
|
|
55
|
+
writeMemoriesAtomicSync(file, up.text);
|
|
56
|
+
}
|
|
57
|
+
catch { /* best-effort */ }
|
|
58
|
+
}
|