@0perator/operator 0.1.166 → 0.1.171
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/CHANGELOG.md +67 -0
- package/dist/background/index.js +33 -8
- package/dist/cli.js +33 -1
- package/dist/config/settings.js +2 -0
- package/dist/consolidation/scheduler.js +114 -0
- package/dist/consolidation/sleep.js +320 -0
- package/dist/engine/agent.js +2 -0
- package/dist/engine/aurora.js +25 -3
- package/dist/engine/calibration-seed.js +74 -0
- package/dist/engine/compaction.js +10 -5
- package/dist/engine/grandmaster.js +13 -0
- package/dist/engine/rolling-summary.js +101 -0
- package/dist/flywheel/processor.js +251 -0
- package/dist/index.js +2 -0
- package/dist/mcp/index.js +5 -1
- package/dist/session.js +97 -1
- package/dist/tools/tool-output-spill.js +64 -5
- package/package.json +1 -1
- package/dist/ui/BusTray.js +0 -70
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,73 @@ Operator is AXE's terminal coding agent (npm `@0perator/operator`), running on A
|
|
|
4
4
|
Newest first. Every release bumps `src/cli.tsx` VERSION + `package.json`, adds an entry here, and ships to
|
|
5
5
|
npm + both git remotes (memjar/kode, axetechnologies/kode). Test counts are the full suite at that release.
|
|
6
6
|
|
|
7
|
+
## 0.1.170 — 2026-10-01 — GW-05/GW-06: prefix-cache telemetry + oracle cold-start seed + GW-10 completion
|
|
8
|
+
- **Cache telemetry (aurora.ts).** The server was already telling us the exact answer and we were discarding
|
|
9
|
+
it: parse `timings.cache_n` / `usage.prompt_tokens_details.cached_tokens` into `ChatResult.cacheN`, threaded
|
|
10
|
+
through `onMeta`. `runTurn` fires a new `onCacheStats` per round; `cacheBustNotice` (pure, tested) names a
|
|
11
|
+
continuation that re-prefilled >=8K tokens with ZERO reuse and prices it in wall-seconds from `promptMs` —
|
|
12
|
+
the honest answer to "why is it crawling" (the v0.1.140-143 mystery class) instead of a guess. `cli.tsx`
|
|
13
|
+
surfaces the warning line. Live-measured shape from the deep canary: a 64K-token bust costs 209s.
|
|
14
|
+
- **Oracle cold-start seed (`engine/calibration-seed.ts`, GW-06).** The meter cold-starts at the legacy chars/4
|
|
15
|
+
(4.0); the aurora-tier0 calibration script measured TRUTH at ~2.15 chars/token on agent traffic — 41-50%
|
|
16
|
+
under-count — so a fresh install's gate fires LATE (the dangerous side) for its first ~10 rounds. Seed ONE
|
|
17
|
+
weight-1 observation per zero-sample endpoint from llama.cpp's own `/apply-template`→`/tokenize` (offline;
|
|
18
|
+
real observations supersede within rounds). Fires once from `cli.tsx`'s first route; kill-switch
|
|
19
|
+
`KODE_SEED_CALIBRATION=0`; browser-safe (plain `fetch`, injectable transport — no node builtins). Live proof:
|
|
20
|
+
seeded :8097 to **2.355** chars/token (vs the old 4.0 guess), one sample, outcome `seeded`.
|
|
21
|
+
- Tests: cache_n parse over real SSE + OpenAI `cached_tokens` shape; notice checker (cold-first-request silence,
|
|
22
|
+
warm silence, floor, bust text with token count + seconds); seed math (2.2 → pooled ratio ±0.1),
|
|
23
|
+
already-calibrated immutability, and every degrade path (unreachable / no-template / weak / absurd → meter
|
|
24
|
+
stays cold, never poisoned).
|
|
25
|
+
- Full suite: 776 passed, 0 failed (106 files). `tsc --noEmit` clean; browser entry unchanged under
|
|
26
|
+
`esbuild --platform=neutral` (94.6kb); iOS `engine.bundle.js` regenerated.
|
|
27
|
+
|
|
28
|
+
- **GW-10-COMPLETE (the follow-up a642c59 named).** `fitToWindow` now OFFLOADS oversized tool outputs through an
|
|
29
|
+
injected spill (full bytes to disk + re-readable pointer) instead of erasing their middle — browser/JSCore hosts
|
|
30
|
+
without a spill keep the old named-loss stub, parity preserved. Eviction order fixed per Manus doctrine:
|
|
31
|
+
error-ish results shed LAST (a failure trace suppresses repeat mistakes; a success's bytes are re-fetchable).
|
|
32
|
+
MCP results offload too (optional `hub.spillSink` — barrel stays node-free). Retention: 14-day age + 500MB byte
|
|
33
|
+
caps, hourly-throttled, never blocks a spill. `KODE_TOOL_OUTPUT_DIR` isolates the dir (tests/CI/second users).
|
|
34
|
+
`compact-command` test intentionally retargeted: /compact preserves every byte it used to elide. +6 tests
|
|
35
|
+
(`test/gw10-complete.test.mts`), full suite 803/0 (107 files).
|
|
36
|
+
|
|
37
|
+
## Unreleased — CORRECTION (GW-26): the "4x decode" claim in the 0.1.169 entry was load-inflated; measured truth below
|
|
38
|
+
- Controlled server-level A/B (throwaway :8098, same gguf/ctx-32K, temp 0, identical fresh-content tasks,
|
|
39
|
+
interleaved): ngram-mod 24/64 = 15.8-23.8 tok/s (median 17.2) vs --spec-type none = 26.3-28.2 (median 27.4)
|
|
40
|
+
— speculation at the BLESSED tuning costs ~1.6x on idle prose tasks, and more under load (draft acceptance
|
|
41
|
+
falls 25-30% idle -> 3-17% loaded per server logs). The original 4-6 vs 20-25 pairing compared loaded vs
|
|
42
|
+
quieter windows, not spec on/off — retracted as a causal figure.
|
|
43
|
+
- CONFIRMED (Nova@jl1 counter-measurement, replicated here): the request-shape `speculative:{ngram:{enabled:false}}`
|
|
44
|
+
does NOT affect the ngram-MOD code path — PR #7 is a no-op on the current fleet servers (kept: correct and
|
|
45
|
+
safe where plain ngram runs, harmless elsewhere; enableSpeculation escape unaffected).
|
|
46
|
+
- ACTION: the real lever is the SERVER flag: relaunch :8097 with --spec-type none (measured 1.6x idle,
|
|
47
|
+
expected >2x under concurrency), canary-gated, GO window required. Draft acceptance telemetry lives in the
|
|
48
|
+
server log (slot print_timing lines), not in chat-completions timings — noted for the GW-18 canary.
|
|
49
|
+
|
|
50
|
+
## 0.1.169 — 2026-10-01 — GW-26: Aurora decode 4x — disable default-on ngram speculation per request
|
|
51
|
+
- **Measured, live on :8097** (b11146, DeltaNet-hybrid Q4_K_M, ctx 307K): a fresh 300-token generation ran
|
|
52
|
+
4.0–5.7 tok/s with llama.cpp's now-DEFAULT-ON ngram speculation vs 20.2–24.7 tok/s once the request carried
|
|
53
|
+
`speculative:{ngram:{enabled:false}}` (server `timings.draft_n` -> 0 confirms; server log showed draft
|
|
54
|
+
acceptance 3–17% — every rejected draft forces a multi-token re-verify + hybrid recache, a net loss at the
|
|
55
|
+
untuned draft defaults). The `{type:"none"}` shape is SILENTLY IGNORED (measured no-op) — the exact shape
|
|
56
|
+
ships in `requestBody()` for every Aurora call; `enableSpeculation: true` is the per-call escape hatch for
|
|
57
|
+
when a retuned bless lands. Servers that don't speculate ignore the field (same contract as `cache_prompt`).
|
|
58
|
+
- Unblocks GW-25: thinking-ON cost collapses 4x — a 2-3K-token reasoning trace is now ~1.5 min, not 12.
|
|
59
|
+
- `test/spec-optout.test.mts` +3 tests (wire shape, opt-in path, rejected-shape policy).
|
|
60
|
+
- package.json bump intentionally deferred to the release commit — three in-flight PRs (#5/#6/#7) would
|
|
61
|
+
otherwise fight over numbers; integrator assigns the next one at merge.
|
|
62
|
+
|
|
63
|
+
## 0.1.167 — 2026-10-01 — Sub-agent watchdog: stall-detector, not an absolute wall-clock cap
|
|
64
|
+
- **A slow-but-progressing sub-agent is no longer killed.** The background watchdog was an *absolute* 20-minute
|
|
65
|
+
timer: a child token-starved behind the foreground on the single shared endpoint (seen live: 11 rounds, real
|
|
66
|
+
file writes, ~2.6k tokens in 20 min) got reaped mid-progress and marked "errored." It's now a true **stall
|
|
67
|
+
detector** — the clock resets on every real progress signal (a token via `onTokens`, a completed tool round
|
|
68
|
+
via `onToolBatch`), so only an agent that has made **no** progress for the window (a genuinely hung request —
|
|
69
|
+
connection open, no chunks, the case the watchdog exists for) is stopped. The stop reason is now the accurate
|
|
70
|
+
"no progress for Nm" instead of "exceeded Nm wall-clock limit". `KODE_BG_TIMEOUT_MS` still overrides the 20m
|
|
71
|
+
default. `src/background/index.ts`; `test/background-hardening.test.mts` +1 (a progressing agent survives 4×
|
|
72
|
+
the window). Full suite 791 passed, 0 failed.
|
|
73
|
+
|
|
7
74
|
## 0.1.166 — 2026-10-01 — Grandmaster wave: cache-stable prefix, flywheel anti-poison, lossless tool results, sub-agent economics
|
|
8
75
|
- **GW-04 — deterministic tool-schema prefix.** `McpHub.schemas()` now sorts by namespaced name so the
|
|
9
76
|
`[system+tools]` prefix is byte-identical across sessions/restarts — KV prefix-cache reuse is strictly
|
package/dist/background/index.js
CHANGED
|
@@ -129,20 +129,44 @@ export class BackgroundAgents {
|
|
|
129
129
|
void this.run(id, entry.info, entry.brief, entry.type);
|
|
130
130
|
}
|
|
131
131
|
}
|
|
132
|
-
/** Watchdog for a
|
|
133
|
-
*
|
|
134
|
-
*
|
|
135
|
-
* agent
|
|
136
|
-
* slot
|
|
132
|
+
/** Watchdog for a HUNG child — a STALL detector, NOT an absolute cap. The clock resets on every real
|
|
133
|
+
* progress signal (a token or a completed tool round, via touchProgress), so a slow-but-advancing agent —
|
|
134
|
+
* e.g. one token-starved behind the foreground on the single shared endpoint — is NEVER killed. Only an
|
|
135
|
+
* agent that has made NO progress for stallTimeoutMs (a genuinely hung request: connection open, no chunks)
|
|
136
|
+
* is stopped and its slot freed, with an explicit unmissable reason. A no-op once the agent leaves
|
|
137
|
+
* "working" (checked by id, which is never recycled). (Before this, the timer was absolute, so a correct
|
|
138
|
+
* agent crawling behind a busy foreground — 11 rounds, real file writes — was reaped mid-progress.) */
|
|
137
139
|
scheduleStallTimeout(id) {
|
|
140
|
+
const a = this.agents.get(id);
|
|
141
|
+
if (a)
|
|
142
|
+
a.lastProgressAt = Date.now(); // start the stall clock from now
|
|
143
|
+
this.armStallCheck(id, this.stallTimeoutMs);
|
|
144
|
+
}
|
|
145
|
+
/** Reset the stall clock — called on each real progress signal so a working agent can't be reaped for
|
|
146
|
+
* being SLOW (only for being SILENT). Cheap: a timestamp write the armed check reads when it fires. */
|
|
147
|
+
touchProgress(id) {
|
|
148
|
+
const a = this.agents.get(id);
|
|
149
|
+
if (a)
|
|
150
|
+
a.lastProgressAt = Date.now();
|
|
151
|
+
}
|
|
152
|
+
/** Arm (or re-arm) the one-shot stall check `delay` ms out. When it fires: if the agent progressed within
|
|
153
|
+
* the window, re-arm for the remaining time instead of killing it; only genuine silence for the full
|
|
154
|
+
* stallTimeoutMs stops it. */
|
|
155
|
+
armStallCheck(id, delay) {
|
|
156
|
+
this.clearStallTimer(id);
|
|
138
157
|
const timer = setTimeout(() => {
|
|
139
158
|
const a = this.agents.get(id);
|
|
140
159
|
if (!a || a.info.status !== "working")
|
|
141
160
|
return; // finished/stopped already — nothing to do
|
|
161
|
+
const idle = Date.now() - (a.lastProgressAt ?? Date.now());
|
|
162
|
+
if (idle < this.stallTimeoutMs) {
|
|
163
|
+
this.armStallCheck(id, this.stallTimeoutMs - idle);
|
|
164
|
+
return;
|
|
165
|
+
} // progressed → not stalled
|
|
142
166
|
const mins = Math.round(this.stallTimeoutMs / 60_000);
|
|
143
167
|
this.stop(id);
|
|
144
|
-
this.onDone(a.info, `[${id} stopped:
|
|
145
|
-
},
|
|
168
|
+
this.onDone(a.info, `[${id} stopped: no progress for ${mins}m (stalled or a hung request) — any partial result above may be incomplete]`);
|
|
169
|
+
}, Math.max(100, delay));
|
|
146
170
|
timer.unref?.();
|
|
147
171
|
const entry = this.agents.get(id);
|
|
148
172
|
if (entry)
|
|
@@ -200,7 +224,7 @@ export class BackgroundAgents {
|
|
|
200
224
|
// to what prior sends already counted. Replaces the old ≈1-per-content-delta tally, which missed
|
|
201
225
|
// every token generated as a tool-call argument or reasoning (most of a skill-writer's output — so
|
|
202
226
|
// a sub-agent that wrote thousands of tokens read as "53 tok").
|
|
203
|
-
onTokens: (t) => { info.tokens = total + t; this.onChange(); },
|
|
227
|
+
onTokens: (t) => { info.tokens = total + t; this.touchProgress(id); this.onChange(); },
|
|
204
228
|
// Reasoning stream → the "thinking" line. Coalesce (keep the tail) and throttle re-renders:
|
|
205
229
|
// a long think can emit hundreds of chunks, but the panel only needs to refresh ~1/sec.
|
|
206
230
|
onReasoning: (chunk) => {
|
|
@@ -225,6 +249,7 @@ export class BackgroundAgents {
|
|
|
225
249
|
const settled = events.map((e) => ({ name: e.name, arg: shortArg(e.args), running: false }));
|
|
226
250
|
info.steps = [...(info.steps ?? []).filter((s) => !s.running), ...settled].slice(-RECENT_STEPS);
|
|
227
251
|
info.thought = undefined;
|
|
252
|
+
this.touchProgress(id); // a completed round is unambiguous progress — reset the stall clock
|
|
228
253
|
this.onChange();
|
|
229
254
|
// This child can mutate the same session-wide task list the foreground plan pane reads (a single
|
|
230
255
|
// module-level store in registry.ts) — refresh the pane live instead of leaving it frozen until the
|
package/dist/cli.js
CHANGED
|
@@ -15,6 +15,8 @@ import { pollBus, pollSent, selfAgent } from "./bus/inbox.js";
|
|
|
15
15
|
import { isErrorResult } from "./ui/format.js";
|
|
16
16
|
import { seedLiveTools, settleLiveTool } from "./ui/liveTools.js";
|
|
17
17
|
import { Session } from "./session.js";
|
|
18
|
+
import { cacheBustNotice } from "./engine/aurora.js";
|
|
19
|
+
import { seedCalibration } from "./engine/calibration-seed.js";
|
|
18
20
|
import { AuroraRouter } from "./router/router.js";
|
|
19
21
|
import { BackgroundAgents } from "./background/index.js";
|
|
20
22
|
import { loadSettings, saveSettings, compactionThreshold, compactionCeilingTokens, rcAutostart } from "./config/settings.js";
|
|
@@ -367,6 +369,8 @@ function Root() {
|
|
|
367
369
|
// for it — see ui/liveTools.ts. Cleared once the batch settles (onToolBatch).
|
|
368
370
|
const [route, setRoute] = useState("operator-1m");
|
|
369
371
|
const [ctxPct, setCtxPct] = useState(0);
|
|
372
|
+
const seededRef = useRef(false); // GW-06: oracle cold-start seed fires once per process, on first route
|
|
373
|
+
const cacheReqsRef = useRef(0); // GW-05: requests since process start — index 1 legitimately misses everything
|
|
370
374
|
const [metrics, setMetrics] = useState(""); // last turn's "N tok · X tok/s · Ys" for the status rule
|
|
371
375
|
const [liveTok, setLiveTok] = useState(0); // live output-token count for the CURRENT turn — animates the
|
|
372
376
|
// status rule as tokens stream (each SSE delta ≈ 1 token). Zero extra renders: it rides the per-delta
|
|
@@ -730,7 +734,26 @@ function Root() {
|
|
|
730
734
|
setStat("thinking");
|
|
731
735
|
try {
|
|
732
736
|
const outcome = await session.send(expandFileMentions(text), {
|
|
733
|
-
onRoute: (label, pct) => {
|
|
737
|
+
onRoute: (label, pct) => {
|
|
738
|
+
setRoute(label);
|
|
739
|
+
setCtxPct(pct);
|
|
740
|
+
remoteRef.current?.setStatus(pct, label);
|
|
741
|
+
// GW-06 oracle seed (once, fire-and-forget): a fresh meter cold-starts at chars/4 (4.0) — measured
|
|
742
|
+
// truth on agent traffic is ~2.15 (aurora-tier0/calibrate-token-meter.py), i.e. the gate fires LATE
|
|
743
|
+
// for the first rounds. Seed ONE weight-1 observation from the endpoint's own tokenizer
|
|
744
|
+
// (/apply-template → /tokenize — offline, never on the hot path); live reports supersede it fast.
|
|
745
|
+
if (!seededRef.current) {
|
|
746
|
+
seededRef.current = true;
|
|
747
|
+
if (process.env.KODE_SEED_CALIBRATION !== "0") {
|
|
748
|
+
const ep = session.endpoints().find((e) => e.name === label) ?? session.endpoints()[0];
|
|
749
|
+
if (ep)
|
|
750
|
+
void seedCalibration(ep.base, ep.model)
|
|
751
|
+
.then((r) => { if (r === "seeded")
|
|
752
|
+
sys("⦿ token meter seeded from the endpoint's tokenizer (cold-start calibration)"); })
|
|
753
|
+
.catch(() => { });
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
},
|
|
734
757
|
onDelta: (chunk) => {
|
|
735
758
|
liveText.current += chunk;
|
|
736
759
|
liveTokRef.current += 1; // ≈1 token per streamed delta; flushed to the counter on the throttled tick
|
|
@@ -751,6 +774,15 @@ function Root() {
|
|
|
751
774
|
},
|
|
752
775
|
onTokens: (t) => { liveTokRef.current = t; setLiveTok(t); }, // authoritative per-round count — corrects the ≈1/delta animation to
|
|
753
776
|
// the real llama.cpp total (which includes tool-call-arg + reasoning tokens the delta stream misses)
|
|
777
|
+
onCacheStats: ({ promptTokens, cached, promptMs }) => {
|
|
778
|
+
// GW-05: the server's OWN prefix-cache truth per round. A continuation that re-prefilled >=8K
|
|
779
|
+
// tokens with ZERO reuse is a cache bust — name it, with its measured cost, instead of letting
|
|
780
|
+
// the user watch "0 tokens for N seconds" and guess (the v0.1.140-143 mystery, now answerable).
|
|
781
|
+
cacheReqsRef.current += 1;
|
|
782
|
+
const notice = cacheBustNotice({ requestIndex: cacheReqsRef.current, promptTokens, cached, promptMs });
|
|
783
|
+
if (notice)
|
|
784
|
+
sys("⚠ " + notice);
|
|
785
|
+
},
|
|
754
786
|
onAutoContinue: (round) => {
|
|
755
787
|
push({ kind: "message", message: { id: nextId(), role: "assistant", content: `↻ still working — auto-continuing past ${round} tool rounds`, reasoning: "" } });
|
|
756
788
|
},
|
package/dist/config/settings.js
CHANGED
|
@@ -51,6 +51,8 @@ const DEFAULTS = {
|
|
|
51
51
|
maxRounds: 40,
|
|
52
52
|
loop: { maxTurns: 25, maxWallClockSec: 3600, stallAfter: 3 },
|
|
53
53
|
dream: { enabled: false, allow: ["board"], permissions: "readonly", maxTasks: 3 },
|
|
54
|
+
// Sleep-time consolidation: off by default (opt-in via settings or KODE_SLEEP_CONSOLIDATION=1)
|
|
55
|
+
sleepConsolidation: { enabled: false, idleThresholdSec: 30, stepsBetweenPasses: 10, modelTier: "fast", maxLessonsPerFile: 50 },
|
|
54
56
|
},
|
|
55
57
|
};
|
|
56
58
|
function settingsPath() {
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// Sleep-time consolidation — the idle-aware scheduler that triggers consolidation passes
|
|
2
|
+
// when the primary agent goes idle. This is the "dreaming" mechanism that runs
|
|
3
|
+
// background memory reorganization while the main agent is idle.
|
|
4
|
+
import { runConsolidationPass } from "./sleep.js";
|
|
5
|
+
import { appendFileSync, mkdirSync } from "node:fs";
|
|
6
|
+
import { join, dirname } from "node:path";
|
|
7
|
+
import { homedir } from "node:os";
|
|
8
|
+
const DEFAULT_LOG = join(homedir(), ".axe/operator/sleep-consolidation.log");
|
|
9
|
+
let schedulerInstance = null;
|
|
10
|
+
/** Get or create the singleton sleep scheduler. */
|
|
11
|
+
export function getSleepScheduler() {
|
|
12
|
+
return schedulerInstance;
|
|
13
|
+
}
|
|
14
|
+
/** Create and register the sleep scheduler. */
|
|
15
|
+
export function createSleepScheduler(opts) {
|
|
16
|
+
schedulerInstance = new SleepScheduler(opts);
|
|
17
|
+
return schedulerInstance;
|
|
18
|
+
}
|
|
19
|
+
export class SleepScheduler {
|
|
20
|
+
opts;
|
|
21
|
+
lastActivity = Date.now();
|
|
22
|
+
idleTimer = null;
|
|
23
|
+
stepsSinceConsolidation = 0;
|
|
24
|
+
running = false;
|
|
25
|
+
logFile;
|
|
26
|
+
constructor(opts) {
|
|
27
|
+
this.opts = opts;
|
|
28
|
+
this.logFile = opts.logFile ?? DEFAULT_LOG;
|
|
29
|
+
mkdirSync(dirname(this.logFile), { recursive: true });
|
|
30
|
+
}
|
|
31
|
+
/** Called on every tool batch / round completion. */
|
|
32
|
+
recordStep() {
|
|
33
|
+
this.lastActivity = Date.now();
|
|
34
|
+
this.stepsSinceConsolidation++;
|
|
35
|
+
// Cancel any pending idle timer
|
|
36
|
+
if (this.idleTimer) {
|
|
37
|
+
clearTimeout(this.idleTimer);
|
|
38
|
+
this.idleTimer = null;
|
|
39
|
+
}
|
|
40
|
+
// Check if we should trigger consolidation after this step
|
|
41
|
+
const consolidationOpts = this.opts.consolidation;
|
|
42
|
+
const threshold = consolidationOpts?.stepsBetweenPasses ?? 10;
|
|
43
|
+
if (this.stepsSinceConsolidation >= threshold && !this.running) {
|
|
44
|
+
this.stepsSinceConsolidation = 0;
|
|
45
|
+
// Schedule consolidation on next idle
|
|
46
|
+
this.idleTimer = setTimeout(() => this.tryConsolidate(), 1000);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/** Called when the agent is idle (no active turn). */
|
|
50
|
+
checkIdle() {
|
|
51
|
+
const idleMs = Date.now() - this.lastActivity;
|
|
52
|
+
const consolidationOpts = this.opts.consolidation;
|
|
53
|
+
const idleThresholdMs = (consolidationOpts?.idleThresholdSec ?? 30) * 1000;
|
|
54
|
+
if (idleMs >= idleThresholdMs && !this.running) {
|
|
55
|
+
this.tryConsolidate();
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/** Record that activity happened (resets idle detection). */
|
|
59
|
+
recordActivity() {
|
|
60
|
+
this.lastActivity = Date.now();
|
|
61
|
+
if (this.idleTimer) {
|
|
62
|
+
clearTimeout(this.idleTimer);
|
|
63
|
+
this.idleTimer = null;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
async tryConsolidate() {
|
|
67
|
+
if (this.running)
|
|
68
|
+
return;
|
|
69
|
+
this.running = true;
|
|
70
|
+
const idleMs = Date.now() - this.lastActivity;
|
|
71
|
+
const idleSec = idleMs / 1000;
|
|
72
|
+
const consolidationOpts = this.opts.consolidation;
|
|
73
|
+
const idleThresholdSec = consolidationOpts?.idleThresholdSec ?? 30;
|
|
74
|
+
// Only consolidate if we've been idle long enough
|
|
75
|
+
if (idleSec < idleThresholdSec) {
|
|
76
|
+
this.running = false;
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
try {
|
|
80
|
+
const result = await runConsolidationPass(consolidationOpts);
|
|
81
|
+
const logLine = `[${new Date().toISOString()}] consolidation: extracted=${result.lessonsExtracted} persisted=${result.lessonsPersisted} curated=${result.lessonsCurated} deduped=${result.memoryDeduped} error=${result.error || "none"}\n`;
|
|
82
|
+
appendFileSync(this.logFile, logLine, "utf8");
|
|
83
|
+
this.opts.onComplete?.(result);
|
|
84
|
+
}
|
|
85
|
+
catch (e) {
|
|
86
|
+
const errLine = `[${new Date().toISOString()}] consolidation error: ${e instanceof Error ? e.message : String(e)}\n`;
|
|
87
|
+
appendFileSync(this.logFile, errLine, "utf8");
|
|
88
|
+
}
|
|
89
|
+
finally {
|
|
90
|
+
this.running = false;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/** Force a consolidation pass now (for testing or manual trigger). */
|
|
94
|
+
forceConsolidate() {
|
|
95
|
+
return runConsolidationPass(this.opts.consolidation).then((result) => {
|
|
96
|
+
const logLine = `[${new Date().toISOString()}] forced consolidation: extracted=${result.lessonsExtracted} persisted=${result.lessonsPersisted} curated=${result.lessonsCurated} deduped=${result.memoryDeduped} error=${result.error || "none"}\n`;
|
|
97
|
+
appendFileSync(this.logFile, logLine, "utf8");
|
|
98
|
+
this.opts.onComplete?.(result);
|
|
99
|
+
return result;
|
|
100
|
+
}).catch((e) => {
|
|
101
|
+
const errLine = `[${new Date().toISOString()}] forced consolidation error: ${e instanceof Error ? e.message : String(e)}\n`;
|
|
102
|
+
appendFileSync(this.logFile, errLine, "utf8");
|
|
103
|
+
return { lessonsExtracted: 0, lessonsPersisted: 0, lessonsCurated: 0, memoryDeduped: 0, projectMemoriesCurated: 0, error: e instanceof Error ? e.message : String(e) };
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
/** Stop the scheduler. */
|
|
107
|
+
dispose() {
|
|
108
|
+
if (this.idleTimer) {
|
|
109
|
+
clearTimeout(this.idleTimer);
|
|
110
|
+
this.idleTimer = null;
|
|
111
|
+
}
|
|
112
|
+
schedulerInstance = null;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
// Sleep-time consolidation — an offline agent that runs while the primary is idle,
|
|
2
|
+
// reorganizing raw memory into learned context. Inspired by Letta's sleep-time compute
|
|
3
|
+
// and the "dreaming" feature: raw context → learned context, anytime-style.
|
|
4
|
+
//
|
|
5
|
+
// Triggers:
|
|
6
|
+
// 1. After N completed steps (configurable, default 10)
|
|
7
|
+
// 2. When the context compacts (major compaction event)
|
|
8
|
+
// 3. On idle detection (no active turn for > threshold, default 30s)
|
|
9
|
+
//
|
|
10
|
+
// What it does:
|
|
11
|
+
// - Deduplicates and merges Operator_Memory.jsonl entries
|
|
12
|
+
// - Extracts higher-insight lessons from flywheel trajectory data
|
|
13
|
+
// - Pre-builds the Pillar-B journal index during downtime
|
|
14
|
+
// - Curates candidate deltas from captureFailureLesson into final lessons
|
|
15
|
+
import { readFileSync, writeFileSync, existsSync, appendFileSync, mkdirSync } from "node:fs";
|
|
16
|
+
import { dirname } from "node:path";
|
|
17
|
+
import { homedir } from "node:os";
|
|
18
|
+
const DEFAULTS = {
|
|
19
|
+
enabled: false,
|
|
20
|
+
idleThresholdSec: 30,
|
|
21
|
+
stepsBetweenPasses: 10,
|
|
22
|
+
modelTier: "fast",
|
|
23
|
+
maxLessonsPerFile: 50,
|
|
24
|
+
};
|
|
25
|
+
class SimpleIdleDetector {
|
|
26
|
+
lastActivity = Date.now();
|
|
27
|
+
recordActivity() {
|
|
28
|
+
this.lastActivity = Date.now();
|
|
29
|
+
}
|
|
30
|
+
isIdle() {
|
|
31
|
+
return (Date.now() - this.lastActivity) / 1000 >= 30; // default 30s idle threshold
|
|
32
|
+
}
|
|
33
|
+
idleSeconds() {
|
|
34
|
+
return (Date.now() - this.lastActivity) / 1000;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/** Deduplicate a JSONL memory file. Returns the deduped notes. */
|
|
38
|
+
export function dedupMemoryFile(filepath) {
|
|
39
|
+
if (!existsSync(filepath))
|
|
40
|
+
return [];
|
|
41
|
+
const raw = readFileSync(filepath, "utf8");
|
|
42
|
+
const notes = raw
|
|
43
|
+
.split("\n")
|
|
44
|
+
.filter(Boolean)
|
|
45
|
+
.map((line) => {
|
|
46
|
+
try {
|
|
47
|
+
return JSON.parse(line);
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
})
|
|
53
|
+
.filter((n) => !!n && typeof n.text === "string");
|
|
54
|
+
// Dedup by text prefix (first 80 chars) + tag overlap
|
|
55
|
+
const seen = new Map(); // key -> index in result
|
|
56
|
+
const result = [];
|
|
57
|
+
for (const note of notes) {
|
|
58
|
+
const key = note.text.slice(0, 80) + "|" + (note.tags?.sort().join(",") ?? "");
|
|
59
|
+
const existing = seen.get(key);
|
|
60
|
+
if (existing !== undefined) {
|
|
61
|
+
// Merge: keep the newer ts, update tags
|
|
62
|
+
result[existing].ts = Math.max(result[existing].ts, note.ts);
|
|
63
|
+
if (note.tags?.length) {
|
|
64
|
+
const mergedTags = new Set([...(result[existing].tags ?? []), ...note.tags]);
|
|
65
|
+
result[existing].tags = [...mergedTags];
|
|
66
|
+
}
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
seen.set(key, result.length);
|
|
70
|
+
result.push({ ...note });
|
|
71
|
+
}
|
|
72
|
+
return result;
|
|
73
|
+
}
|
|
74
|
+
// ---------------------------------------------------------------------------
|
|
75
|
+
// Lesson extraction from flywheel trajectories
|
|
76
|
+
// ---------------------------------------------------------------------------
|
|
77
|
+
/** Extract candidate lessons from graded flywheel trajectories.
|
|
78
|
+
* Scans the flywheel JSONL for patterns that suggest a reusable lesson:
|
|
79
|
+
* - Repeated failures on the same tool/command
|
|
80
|
+
* - Verification failures that were later fixed
|
|
81
|
+
* - Compaction events that freed significant context
|
|
82
|
+
* - Self-loop detections that required forced redirects
|
|
83
|
+
*/
|
|
84
|
+
export async function extractFlywheelLessons(flywheelDir) {
|
|
85
|
+
const { readdirSync, readFileSync, existsSync } = await import("node:fs");
|
|
86
|
+
const { join } = await import("node:path");
|
|
87
|
+
if (!existsSync(flywheelDir))
|
|
88
|
+
return [];
|
|
89
|
+
const lessons = [];
|
|
90
|
+
const files = readdirSync(flywheelDir).filter(f => f.endsWith(".jsonl"));
|
|
91
|
+
for (const file of files) {
|
|
92
|
+
if (!file.endsWith(".jsonl"))
|
|
93
|
+
continue;
|
|
94
|
+
const filepath = join(flywheelDir, file);
|
|
95
|
+
const raw = readFileSync(filepath, "utf8");
|
|
96
|
+
const lines = raw.split("\n").filter(Boolean);
|
|
97
|
+
// Track per-task patterns
|
|
98
|
+
const taskCounts = new Map();
|
|
99
|
+
for (const line of lines) {
|
|
100
|
+
try {
|
|
101
|
+
const row = JSON.parse(line);
|
|
102
|
+
if (!row.graded)
|
|
103
|
+
continue;
|
|
104
|
+
// Key by task signature (input hash)
|
|
105
|
+
const key = hashInput(row.input ?? "");
|
|
106
|
+
const count = taskCounts.get(key) ?? { total: 0, graded: 0, failed: 0 };
|
|
107
|
+
count.total++;
|
|
108
|
+
if (row.unverified) {
|
|
109
|
+
count.failed++;
|
|
110
|
+
}
|
|
111
|
+
count.graded++;
|
|
112
|
+
taskCounts.set(key, count);
|
|
113
|
+
}
|
|
114
|
+
catch { /* skip malformed rows */ }
|
|
115
|
+
}
|
|
116
|
+
// Identify patterns worth distilling
|
|
117
|
+
for (const [key, count] of taskCounts) {
|
|
118
|
+
if (count.failed > 2) {
|
|
119
|
+
lessons.push({
|
|
120
|
+
type: "repeated_failure",
|
|
121
|
+
pattern: key,
|
|
122
|
+
count: count.failed,
|
|
123
|
+
total: count.total,
|
|
124
|
+
source: filepath,
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return lessons;
|
|
130
|
+
}
|
|
131
|
+
/** Merge candidate lessons into curated form.
|
|
132
|
+
* Groups candidates by type+pattern, extracts a distilled lesson text. */
|
|
133
|
+
export function curateLessons(candidates) {
|
|
134
|
+
// Group by type
|
|
135
|
+
const groups = new Map();
|
|
136
|
+
for (const c of candidates) {
|
|
137
|
+
const key = `${c.type}:${c.pattern.slice(0, 40)}`;
|
|
138
|
+
const existing = groups.get(key) ?? [];
|
|
139
|
+
existing.push(c);
|
|
140
|
+
groups.set(key, existing);
|
|
141
|
+
}
|
|
142
|
+
return [...groups.entries()].map(([key, items]) => {
|
|
143
|
+
const type = items[0].type;
|
|
144
|
+
const count = items.reduce((s, i) => s + i.count, 0);
|
|
145
|
+
const total = items.reduce((s, i) => s + i.total, 0);
|
|
146
|
+
let text = "";
|
|
147
|
+
switch (type) {
|
|
148
|
+
case "repeated_failure":
|
|
149
|
+
text = `Pattern: repeated failures detected ${count} times across ${total} total attempts. ` +
|
|
150
|
+
`Lesson: this failure mode is systematic — check tool parser, template, or sandbox config.`;
|
|
151
|
+
break;
|
|
152
|
+
case "compaction_insight":
|
|
153
|
+
text = `Compaction freed significant context ${count} times. ` +
|
|
154
|
+
`Lesson: the evicted span often contains critical state — ensure summaries preserve verbatim identifiers.`;
|
|
155
|
+
break;
|
|
156
|
+
case "self_loop":
|
|
157
|
+
text = `Self-loop detected ${count} times. ` +
|
|
158
|
+
`Lesson: the model gets stuck on ${items[0].pattern.slice(0, 60)} — add explicit decomposition guidance.`;
|
|
159
|
+
break;
|
|
160
|
+
case "verify_gap":
|
|
161
|
+
text = `Verification gap: ${count} turns changed files without passing checks. ` +
|
|
162
|
+
`Lesson: the verify-before-done gate needs a nudge on this task type.`;
|
|
163
|
+
break;
|
|
164
|
+
}
|
|
165
|
+
return {
|
|
166
|
+
ts: Date.now(),
|
|
167
|
+
text,
|
|
168
|
+
tags: [type, `count:${count}`],
|
|
169
|
+
source: items[0].source,
|
|
170
|
+
candidates: items.map(i => i.pattern),
|
|
171
|
+
};
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
// ---------------------------------------------------------------------------
|
|
175
|
+
// Persistence: write curated lessons back to Operator_Memory.jsonl
|
|
176
|
+
// ---------------------------------------------------------------------------
|
|
177
|
+
/** Write curated lessons to the memory file, appending new ones. */
|
|
178
|
+
export function persistLessons(memoryFile, lessons) {
|
|
179
|
+
try {
|
|
180
|
+
mkdirSync(dirname(memoryFile), { recursive: true });
|
|
181
|
+
// Read existing notes
|
|
182
|
+
let existing = [];
|
|
183
|
+
if (existsSync(memoryFile)) {
|
|
184
|
+
const raw = readFileSync(memoryFile, "utf8");
|
|
185
|
+
existing = raw.split("\n")
|
|
186
|
+
.filter(Boolean)
|
|
187
|
+
.map((l) => { try {
|
|
188
|
+
return JSON.parse(l);
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
return null;
|
|
192
|
+
} })
|
|
193
|
+
.filter((n) => !!n);
|
|
194
|
+
}
|
|
195
|
+
// Check for duplicates (by text prefix)
|
|
196
|
+
const seen = new Set();
|
|
197
|
+
for (const n of existing) {
|
|
198
|
+
seen.add(n.text.slice(0, 80));
|
|
199
|
+
}
|
|
200
|
+
// Append non-duplicate lessons
|
|
201
|
+
let wrote = 0;
|
|
202
|
+
for (const lesson of lessons) {
|
|
203
|
+
const key = lesson.text.slice(0, 80);
|
|
204
|
+
if (seen.has(key))
|
|
205
|
+
continue;
|
|
206
|
+
seen.add(key);
|
|
207
|
+
const note = {
|
|
208
|
+
ts: lesson.ts,
|
|
209
|
+
text: lesson.text,
|
|
210
|
+
tags: [...(lesson.tags ?? []), "consolidated"],
|
|
211
|
+
};
|
|
212
|
+
appendFileSync(memoryFile, JSON.stringify(note) + "\n", "utf8");
|
|
213
|
+
wrote++;
|
|
214
|
+
}
|
|
215
|
+
return wrote > 0;
|
|
216
|
+
}
|
|
217
|
+
catch {
|
|
218
|
+
return false;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
// ---------------------------------------------------------------------------
|
|
222
|
+
// Project memories curation
|
|
223
|
+
// ---------------------------------------------------------------------------
|
|
224
|
+
/** Curate a project's .operator/memories.md: remove superseded lessons, cap at maxLessonsPerFile. */
|
|
225
|
+
export function curateProjectMemories(filepath, maxLessons) {
|
|
226
|
+
if (!existsSync(filepath))
|
|
227
|
+
return false;
|
|
228
|
+
try {
|
|
229
|
+
const raw = readFileSync(filepath, "utf8");
|
|
230
|
+
const lines = raw.split("\n");
|
|
231
|
+
// Extract lesson lines (start with "- [")
|
|
232
|
+
const lessonLines = [];
|
|
233
|
+
const nonLessonLines = [];
|
|
234
|
+
for (const line of lines) {
|
|
235
|
+
if (line.startsWith("- [") || line.startsWith("## Lessons") || line.startsWith("# ")) {
|
|
236
|
+
if (line.startsWith("## Lessons") || line.startsWith("# ")) {
|
|
237
|
+
nonLessonLines.push(line);
|
|
238
|
+
}
|
|
239
|
+
else {
|
|
240
|
+
lessonLines.push(line);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
else {
|
|
244
|
+
nonLessonLines.push(line);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
// Remove superseded lessons
|
|
248
|
+
const activeLessons = lessonLines.filter(l => !l.includes("superseded") && !l.includes("OBSOLETE"));
|
|
249
|
+
// Cap at max
|
|
250
|
+
const capped = activeLessons.slice(-maxLessons);
|
|
251
|
+
// Reconstruct
|
|
252
|
+
const header = nonLessonLines.filter(l => l.startsWith("# ") || l.startsWith("## "));
|
|
253
|
+
const body = nonLessonLines.filter(l => !l.startsWith("# ") && !l.startsWith("## "));
|
|
254
|
+
let result = header.join("\n") + "\n";
|
|
255
|
+
if (!result.includes("## Lessons")) {
|
|
256
|
+
result += "\n## Lessons (auto-captured)\n";
|
|
257
|
+
}
|
|
258
|
+
result += capped.join("\n") + "\n";
|
|
259
|
+
result += body.join("\n") + "\n";
|
|
260
|
+
writeFileSync(filepath, result, "utf8");
|
|
261
|
+
return true;
|
|
262
|
+
}
|
|
263
|
+
catch {
|
|
264
|
+
return false;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
export async function runConsolidationPass(opts = {}) {
|
|
268
|
+
const merged = { ...DEFAULTS, ...opts };
|
|
269
|
+
const result = {
|
|
270
|
+
lessonsExtracted: 0,
|
|
271
|
+
lessonsPersisted: 0,
|
|
272
|
+
lessonsCurated: 0,
|
|
273
|
+
memoryDeduped: 0,
|
|
274
|
+
projectMemoriesCurated: 0,
|
|
275
|
+
};
|
|
276
|
+
if (!merged.enabled) {
|
|
277
|
+
result.error = "consolidation disabled";
|
|
278
|
+
return result;
|
|
279
|
+
}
|
|
280
|
+
try {
|
|
281
|
+
// 1. Extract candidate lessons from flywheel
|
|
282
|
+
const candidates = await extractFlywheelLessons(merged.flywheelDir ?? `${homedir()}/.axe/operator/flywheel`);
|
|
283
|
+
result.lessonsExtracted = candidates.length;
|
|
284
|
+
// 2. Curate into final lessons
|
|
285
|
+
const curated = curateLessons(candidates);
|
|
286
|
+
result.lessonsPersisted = curated.length;
|
|
287
|
+
// 3. Persist to memory file
|
|
288
|
+
const memFile = merged.memoryFile ?? `${homedir()}/.axe/operator/Operator_Memory.jsonl`;
|
|
289
|
+
if (curated.length > 0) {
|
|
290
|
+
result.lessonsCurated = curated.length;
|
|
291
|
+
persistLessons(memFile, curated);
|
|
292
|
+
}
|
|
293
|
+
// 4. Dedup the memory file
|
|
294
|
+
const deduped = dedupMemoryFile(memFile);
|
|
295
|
+
result.memoryDeduped = deduped.length;
|
|
296
|
+
// 5. Curate project memories (best-effort, all repos)
|
|
297
|
+
// This is done in a second pass — for now we return success
|
|
298
|
+
result.projectMemoriesCurated = 0;
|
|
299
|
+
return result;
|
|
300
|
+
}
|
|
301
|
+
catch (e) {
|
|
302
|
+
result.error = e instanceof Error ? e.message : String(e);
|
|
303
|
+
return result;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
function hashInput(input) {
|
|
307
|
+
// Simple hash for grouping similar tasks
|
|
308
|
+
let hash = 0;
|
|
309
|
+
const normalized = input.trim().toLowerCase().slice(0, 200);
|
|
310
|
+
for (let i = 0; i < normalized.length; i++) {
|
|
311
|
+
const char = normalized.charCodeAt(i);
|
|
312
|
+
hash = ((hash << 5) - hash) + char;
|
|
313
|
+
hash = hash & hash; // Convert to 32bit integer
|
|
314
|
+
}
|
|
315
|
+
return hash.toString(36);
|
|
316
|
+
}
|
|
317
|
+
// Lazy require for node:fs in browser context
|
|
318
|
+
const require = (typeof globalThis !== "undefined" && globalThis.require)
|
|
319
|
+
? globalThis.require
|
|
320
|
+
: undefined;
|