@0perator/operator 0.1.222 → 0.1.261

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 (110) hide show
  1. package/README.md +6 -5
  2. package/dashboard/server.mjs +1 -1
  3. package/dist/acp/agent.js +320 -53
  4. package/dist/acp/auth.js +44 -0
  5. package/dist/acp/config-options.js +34 -0
  6. package/dist/acp/prompt.js +41 -0
  7. package/dist/acp/run.js +116 -10
  8. package/dist/acp/tool-map.js +48 -0
  9. package/dist/auth/byo.js +125 -0
  10. package/dist/auth/client.js +12 -6
  11. package/dist/auth/commands.js +71 -3
  12. package/dist/auth/identity.js +136 -0
  13. package/dist/auth/store.js +7 -5
  14. package/dist/autonomy/board.js +3 -2
  15. package/dist/autonomy/cron.js +332 -0
  16. package/dist/autonomy/delegate.js +168 -0
  17. package/dist/autonomy/dream.js +1 -1
  18. package/dist/autonomy/index.js +16 -2
  19. package/dist/autonomy/media-robot.js +137 -0
  20. package/dist/autonomy/profile.js +77 -0
  21. package/dist/autonomy/routines.js +5 -4
  22. package/dist/autonomy/session-factory.js +19 -10
  23. package/dist/background/index.js +8 -1
  24. package/dist/browser/cdp.js +266 -0
  25. package/dist/browser/session.js +286 -0
  26. package/dist/cli.js +207 -106
  27. package/dist/compose/client.js +56 -0
  28. package/dist/config/brand.js +3 -3
  29. package/dist/config/home.js +70 -0
  30. package/dist/config/managed.js +230 -0
  31. package/dist/config/persona.js +243 -21
  32. package/dist/config/scaffold.js +142 -0
  33. package/dist/config/settings.js +87 -20
  34. package/dist/config/skills-index.js +175 -0
  35. package/dist/consolidation/scheduler.js +10 -7
  36. package/dist/consolidation/sleep.js +17 -3
  37. package/dist/engine/agent.js +231 -21
  38. package/dist/engine/aurora.js +79 -14
  39. package/dist/engine/batch-scheduler.js +128 -0
  40. package/dist/engine/compaction.js +129 -2
  41. package/dist/engine/computer-event.js +139 -0
  42. package/dist/engine/continuation.js +55 -0
  43. package/dist/engine/contract.js +3 -1
  44. package/dist/engine/grandmaster.js +13 -3
  45. package/dist/engine/json-repair.js +105 -0
  46. package/dist/engine/messages.js +52 -5
  47. package/dist/engine/redact.js +25 -0
  48. package/dist/engine/rolling-summary.js +28 -11
  49. package/dist/engine/router-adapter.js +2 -0
  50. package/dist/engine/unrestricted.js +51 -0
  51. package/dist/engine/verify-gate.js +6 -0
  52. package/dist/enterprise/cli.js +137 -0
  53. package/dist/flywheel/processor.js +30 -2
  54. package/dist/flywheel/secret-gate.js +123 -0
  55. package/dist/index.browser.js +4 -0
  56. package/dist/index.js +4 -0
  57. package/dist/mcp/index.js +18 -24
  58. package/dist/memory/index.js +0 -0
  59. package/dist/memory/session-index.js +324 -0
  60. package/dist/memory/session-rewind.js +92 -0
  61. package/dist/memory/state-maintenance.js +441 -0
  62. package/dist/observability/index.js +3 -3
  63. package/dist/permissions/audit.js +4 -1
  64. package/dist/permissions/index.js +24 -12
  65. package/dist/permissions/policy.js +4 -3
  66. package/dist/permissions/tier.js +31 -14
  67. package/dist/remote/host.js +9 -2
  68. package/dist/router/models.js +62 -2
  69. package/dist/selfimprove/index.js +9 -7
  70. package/dist/session.js +129 -42
  71. package/dist/skills/catalogue.js +167 -0
  72. package/dist/telemetry/audit-verify.js +94 -0
  73. package/dist/telemetry/events.js +92 -7
  74. package/dist/telemetry/lifecycle.js +18 -0
  75. package/dist/tools/computer.js +1 -1
  76. package/dist/tools/deferred.js +117 -0
  77. package/dist/tools/executor.js +27 -23
  78. package/dist/tools/memory.js +117 -0
  79. package/dist/tools/mutating.js +6 -0
  80. package/dist/tools/registry.js +1022 -46
  81. package/dist/tools/sandbox.js +63 -17
  82. package/dist/tools/searxng.js +2 -2
  83. package/dist/tools/shell-session.js +36 -1
  84. package/dist/tools/tool-output-spill.js +4 -4
  85. package/dist/ui/ActivitySpinner.js +17 -6
  86. package/dist/ui/App.js +36 -14
  87. package/dist/ui/ArtifactPicker.js +109 -0
  88. package/dist/ui/Composer.js +39 -8
  89. package/dist/ui/Markdown.js +5 -3
  90. package/dist/ui/MouseProvider.js +99 -19
  91. package/dist/ui/QuestionPrompt.js +24 -3
  92. package/dist/ui/ThinkingSpinner.js +9 -5
  93. package/dist/ui/ToolStep.js +17 -12
  94. package/dist/ui/Transcript.js +28 -9
  95. package/dist/ui/capabilities.js +0 -9
  96. package/dist/ui/listhit.js +23 -0
  97. package/dist/ui/mouse.js +22 -0
  98. package/dist/ui/osc.js +7 -4
  99. package/dist/ui/progressbar.js +46 -0
  100. package/dist/ui/shimmer.js +43 -0
  101. package/dist/ui/theme.js +2 -0
  102. package/dist/ui/tick.js +48 -0
  103. package/dist/ui/toolicons.js +69 -0
  104. package/dist/ui/useInputHistory.js +3 -3
  105. package/dist/util/slash.js +1 -0
  106. package/dist/vault/cli.js +48 -0
  107. package/dist/vault/store.js +157 -0
  108. package/dist/vault/tool.js +50 -0
  109. package/package.json +3 -5
  110. package/CHANGELOG.md +0 -1629
@@ -3,8 +3,10 @@
3
3
  // default. Never throws — a missing or malformed file just falls back to defaults, same as an env
4
4
  // var that was never set.
5
5
  import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
6
- import { homedir, totalmem } from "node:os";
7
- import { join, dirname } from "node:path";
6
+ import { totalmem } from "node:os";
7
+ import { dirname } from "node:path";
8
+ import { operatorPath } from "./home.js";
9
+ import { applyManagedPolicy, loadManagedPolicy } from "./managed.js";
8
10
  import { DEFAULT_MODEL_ID } from "../router/models.js";
9
11
  // The sole endpoint: Aurora on :8097 at its REAL served context — 307,200 tokens (300K; the llama-server
10
12
  // runs --ctx-size 307200 with q8_0 KV cache, standardized on JL1+JL2 2026-09-27). ctxWindow MUST match the
@@ -29,8 +31,9 @@ const DEFAULTS = {
29
31
  memory: { recall: true },
30
32
  selfImprove: { flywheel: true, memory: false, skills: false, reflect: false }, // trajectory capture ON; memory/skills/reflect sinks staged
31
33
  verifyGate: { enabled: true, maxNudges: 1 }, // verify-before-done ON; KODE_VERIFY_GATE=0 to run the raw model
34
+ unrestricted: true, // owner's private system — on by default; KODE_UNRESTRICTED=0 to disable
32
35
  background: { maxConcurrent: 2, worktree: true }, // ≤2 bg agents at once (KODE_BG_MAX); file-editing ones isolate in a git worktree (KODE_BG_WORKTREE=0 to disable)
33
- ui: { fullscreen: false }, // inline by default (native scrollback + the masthead boot); --fullscreen / KODE_FULLSCREEN=1 opt in (its alt-screen boot render still needs work before it can be default)
36
+ ui: { fullscreen: false, reasoning: "think" }, // inline by default; reasoning "think" = the model's thoughts stream dim above the answer every turn (the owner wants to see the process); set "off" for spinner-only, or /think to toggle per-session
34
37
  permissions: { mode: "bypass" }, // zero gates by default — enforcement is opt-in
35
38
  telemetry: { enabled: true }, // local-only metrics (silent JSONL); remote sink opt-in via KODE_TELEMETRY_URL
36
39
  sandbox: { mode: "off" }, // no isolation by default — enterprise turns it on (KODE_SANDBOX / settings)
@@ -48,15 +51,20 @@ const DEFAULTS = {
48
51
  // allowlist. An interactive owner never touches any of this until they run an autonomy subcommand.
49
52
  autonomy: {
50
53
  keepAwake: false,
51
- maxRounds: 40,
52
- loop: { maxTurns: 25, maxWallClockSec: 3600, stallAfter: 3 },
54
+ // UNBOUNDED AUTONOMY (owner directive, James 2026-10-05): the round + wall-clock caps are removed so Operator
55
+ // runs long tasks to completion. These stay settings-overridable (set a number to re-impose a cap); only the
56
+ // genuine-STALL break (loop.stallAfter) remains, as a correctness safety against a no-progress loop, NOT a limit.
57
+ maxRounds: 100000, // effectively no soft round cap (was 200)
58
+ maxTurnWallClockSec: 0, // 0 ⇒ no per-turn time brake (was 900); turnWallClockMs() returns undefined
59
+ loop: { maxTurns: 100000, maxWallClockSec: 86400, stallAfter: 3 }, // essentially unbounded loop; keep the stall break
53
60
  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 },
61
+ // Sleep-time consolidation: ON by default — memory dedup, lesson extraction, and project curation run
62
+ // during idle windows to keep the operator's knowledge base organized without blocking turns.
63
+ sleepConsolidation: { enabled: true, idleThresholdSec: 30, stepsBetweenPasses: 10, modelTier: "fast", maxLessonsPerFile: 50 },
56
64
  },
57
65
  };
58
66
  function settingsPath() {
59
- return process.env.KODE_TSI_SETTINGS ?? join(homedir(), ".axe", "operator", "settings.json");
67
+ return process.env.KODE_TSI_SETTINGS ?? operatorPath("settings.json");
60
68
  }
61
69
  function isPlainObject(v) {
62
70
  return typeof v === "object" && v !== null && !Array.isArray(v);
@@ -109,6 +117,9 @@ function applyEnv(s) {
109
117
  const cct = Number(process.env.KODE_COMPACTION_CEILING_TOKENS); // absolute-token compact-sooner knob (big window / small HW)
110
118
  if (Number.isFinite(cct))
111
119
  out.compaction = { ...out.compaction, ceilingTokens: cct };
120
+ const acct = Number(process.env.KODE_AUTONOMY_CEILING_TOKENS); // higher ceiling for unattended headless/loop runs
121
+ if (Number.isFinite(acct))
122
+ out.compaction = { ...out.compaction, autonomyCeilingTokens: acct };
112
123
  const rcAuto = process.env.KODE_RC_AUTOSTART; // RC host auto-start on boot (opt-in)
113
124
  if (rcAuto === "1" || rcAuto === "0")
114
125
  out.remote = { ...out.remote, autostart: rcAuto === "1" };
@@ -117,6 +128,8 @@ function applyEnv(s) {
117
128
  out.maxTurnTokens = Math.floor(mtt);
118
129
  if (process.env.KODE_TELEMETRY === "0")
119
130
  out.telemetry = { ...out.telemetry, enabled: false };
131
+ if (process.env.KODE_UNRESTRICTED === "0")
132
+ out.unrestricted = false; // owner's private system; opt out per-box
120
133
  const sb = process.env.KODE_SANDBOX;
121
134
  if (sb === "off" || sb === "workspace" || sb === "strict")
122
135
  out.sandbox = { mode: sb };
@@ -178,20 +191,42 @@ export function defaultCompactionCeiling(totalBytes, windowTokens) {
178
191
  const cap = Math.floor((windowTokens > 0 ? windowTokens : 0) * 0.85);
179
192
  return Math.max(8000, Math.min(raw, cap));
180
193
  }
181
- /** The absolute-token proactive-compaction ceiling to hand runTurn: settings.compaction.ceilingTokens
182
- * (env-overridden in loadSettings), validated to a sane floor of 8000 tokens. When UNSET, we no longer leave
183
- * it uncapped — we apply a RAM-aware safe default (defaultCompactionCeiling) so a large window can't grow the
184
- * KV cache past the box's memory into swap (the "88 tokens in 6 minutes" stall). An explicit valid setting
185
- * always wins. `windowTokens` is the active endpoint's context window; pass 0 if unknown (then only the floor
186
- * applies). Resolved here so CLI, headless, and ACP surfaces read it identically. */
187
- export function compactionCeilingTokens(s, windowTokens = 0) {
188
- const t = s.compaction?.ceilingTokens;
189
- if (typeof t === "number" && Number.isFinite(t) && t >= 8000)
190
- return Math.floor(t);
194
+ // Per-mode default ceilings (tokens), applied when no explicit setting/env is present, then clamped by the
195
+ // RAM-aware safe ceiling (defaultCompactionCeiling) so neither can push the KV cache past the box's swap cliff.
196
+ // Interactive stays tight because decode is context-bound (measured ~45→9→5 tok/s as the live context grows), so
197
+ // a small live context keeps every owner-facing reply fast; retrieval reclaims what compaction summarizes out.
198
+ // Autonomy rides high — just under the 64GB swap cliff (~126k) — because an unattended run isn't waiting on
199
+ // decode and fewer compactions means it holds the thread across a long multi-step mission instead of thrashing.
200
+ const INTERACTIVE_DEFAULT_CEILING = 24_000;
201
+ const AUTONOMY_DEFAULT_CEILING = 100_000;
202
+ /** The absolute-token proactive-compaction ceiling to hand runTurn, resolved PER SESSION MODE — the one knob
203
+ * that stops us trading reign for speed. Interactive and autonomy each have their own explicit override
204
+ * (`compaction.ceilingTokens` / `compaction.autonomyCeilingTokens`, env-overridden in loadSettings) validated
205
+ * to a sane floor of 8000; the other mode's override is deliberately ignored, so a tight interactive value can
206
+ * no longer throttle an unattended build into a compaction-thrash loop (the 0.1.178 fix). When a mode has no
207
+ * explicit override we apply its per-mode default (above), clamped by the RAM-aware safe ceiling
208
+ * (defaultCompactionCeiling) so a large window can't grow the KV cache into swap (the "88 tokens in 6 minutes"
209
+ * stall). `windowTokens` is the active endpoint's context window; pass 0 if unknown (then only the floor path
210
+ * applies). Resolved here so CLI (interactive), headless/autonomy, and ACP surfaces read it identically. */
211
+ export function compactionCeilingTokens(s, windowTokens = 0, mode = "interactive") {
212
+ const explicit = mode === "autonomy" ? s.compaction?.autonomyCeilingTokens : s.compaction?.ceilingTokens;
213
+ if (typeof explicit === "number" && Number.isFinite(explicit) && explicit >= 8000)
214
+ return Math.floor(explicit);
215
+ const target = mode === "autonomy" ? AUTONOMY_DEFAULT_CEILING : INTERACTIVE_DEFAULT_CEILING;
191
216
  if (windowTokens >= 8000)
192
- return defaultCompactionCeiling(totalmem(), windowTokens);
217
+ return Math.min(target, defaultCompactionCeiling(totalmem(), windowTokens));
193
218
  return undefined;
194
219
  }
220
+ /** The per-turn WALL-CLOCK budget (ms) to hand runTurn — the only bound on TIME, the brake on hour-long turns.
221
+ * settings.autonomy.maxTurnWallClockSec, env KODE_TURN_MAX_WALLCLOCK_SEC wins; 0/unset ⇒ undefined (no cap).
222
+ * Resolved here so headless/autonomy (and any surface that opts in) read it identically. */
223
+ export function turnWallClockMs(s) {
224
+ const env = Number(process.env.KODE_TURN_MAX_WALLCLOCK_SEC);
225
+ const sec = Number.isFinite(env) && env >= 0 ? env : s.autonomy?.maxTurnWallClockSec;
226
+ if (typeof sec !== "number" || !Number.isFinite(sec) || sec <= 0)
227
+ return undefined;
228
+ return Math.floor(sec * 1000);
229
+ }
195
230
  /** Whether to auto-start a Remote Control host on session boot. An explicit setting/env wins
196
231
  * (settings.remote.autostart / KODE_RC_AUTOSTART=1/0). Otherwise it is FEATURE-FLAGGED to the admin/VIP
197
232
  * tier only (owner decision, James 2026-09-28): auto-RC ships ON for admin accounts and OFF for everyone
@@ -226,12 +261,44 @@ function resolveModelMode(s) {
226
261
  }
227
262
  return s;
228
263
  }
264
+ // The seat this process resolved at startup (auth/identity.ts). Re-applied by every loadSettings() so a later
265
+ // caller (cron, delegate_task) can never see a WIDER tier than the one the identity was narrowed to.
266
+ let activeSeat = null;
267
+ let warnedManaged = false;
268
+ const TIER_RANK = { readonly: 0, enterprise: 1, admin: 2 };
269
+ /** Narrow `s` to `seat` (never widen) and drop the training-flywheel default for a narrowed seat that did not
270
+ * ask for it. Pure. */
271
+ export function applySeat(s, seat) {
272
+ const cur = seat.configured ?? s.seat?.configured ?? s.permissions.tier ?? "admin";
273
+ const tier = TIER_RANK[seat.tier] < TIER_RANK[cur] ? seat.tier : cur;
274
+ const out = { ...s, seat: { ...seat, tier, configured: cur }, permissions: { ...s.permissions, tier } };
275
+ if (tier !== "admin" && !s.explicit?.flywheel)
276
+ out.selfImprove = { ...s.selfImprove, flywheel: false };
277
+ return out;
278
+ }
279
+ export function setActiveSeat(seat) { activeSeat = seat; }
229
280
  export function loadSettings() {
230
281
  const file = readSettingsFile(settingsPath());
231
282
  // structuredClone the base so a returned settings object never aliases the module-level DEFAULTS —
232
283
  // deepMerge only recurses into keys the override touches, so an untouched nested endpoint would
233
284
  // otherwise flow through by reference and a later mutation would corrupt defaults process-wide.
234
- return resolveModelMode(applyEnv(deepMerge(structuredClone(DEFAULTS), file)));
285
+ const merged = applyEnv(deepMerge(structuredClone(DEFAULTS), file));
286
+ // Managed policy goes LAST: over defaults, the user's file and env. Absent file = identity function.
287
+ const managed = loadManagedPolicy();
288
+ const flywheelPinned = (isPlainObject(file) && isPlainObject(file.selfImprove) && typeof file.selfImprove.flywheel === "boolean") ||
289
+ process.env.KODE_SELFIMPROVE !== undefined ||
290
+ typeof managed.policy?.selfImprove?.flywheel === "boolean";
291
+ let out = applyManagedPolicy({ ...merged, explicit: { flywheel: flywheelPinned } }, managed);
292
+ if (managed.info.status === "invalid" && !warnedManaged) {
293
+ warnedManaged = true;
294
+ process.stderr.write(`[operator] managed policy ${managed.info.path} is not usable (${managed.info.errors.join("; ")}) — running locked down (read-only) until it is fixed\n`);
295
+ }
296
+ // Enterprise default: a narrowed seat does not feed the training flywheel unless it explicitly says so.
297
+ if ((out.permissions.tier ?? "admin") !== "admin" && !flywheelPinned)
298
+ out = { ...out, selfImprove: { ...out.selfImprove, flywheel: false } };
299
+ if (activeSeat)
300
+ out = applySeat(out, activeSeat);
301
+ return resolveModelMode(out);
235
302
  }
236
303
  /** Persist a partial settings patch onto whatever's on disk (deep-merged, file values win over
237
304
  * defaults for anything the patch doesn't touch), so a runtime choice like /model survives a
@@ -0,0 +1,175 @@
1
+ // Local profile skills — flat `skills/*.md` and directory `skills/<cat>/<name>/SKILL.md`.
2
+ // No static `node:` imports: process.getBuiltinModule keeps the engine bundle node-free.
3
+ // renderSkillsIndex is sync so composeSystemPrompt can drop it in without going async.
4
+ import { get_operator_home } from "./home.js";
5
+ const INDEX_CAP = 4000;
6
+ const INDEX_DESC = 57;
7
+ function nodeBuiltins() {
8
+ try {
9
+ const proc = globalThis.process;
10
+ const fs = proc?.getBuiltinModule?.("node:fs");
11
+ const path = proc?.getBuiltinModule?.("node:path");
12
+ const os = proc?.getBuiltinModule?.("node:os");
13
+ if (!fs || !path || !os)
14
+ return null;
15
+ return { fs, path, os, env: proc?.env ?? {} };
16
+ }
17
+ catch {
18
+ return null;
19
+ }
20
+ }
21
+ export function localSkillsDir() {
22
+ const b = nodeBuiltins();
23
+ if (!b)
24
+ return "";
25
+ return b.path.join(get_operator_home(), "skills");
26
+ }
27
+ function yamlScalar(raw) {
28
+ const v = raw.trim();
29
+ if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'")))
30
+ return v.slice(1, -1);
31
+ return v.replace(/\s+#.*$/, "").trim();
32
+ }
33
+ function frontmatter(raw) {
34
+ if (!raw.startsWith("---"))
35
+ return null;
36
+ const nl = raw.startsWith("---\r\n") ? "\r\n" : "\n";
37
+ const end = raw.indexOf(`${nl}---`, 3);
38
+ if (end === -1)
39
+ return null;
40
+ return raw.slice(3 + nl.length, end);
41
+ }
42
+ function field(fm, key) {
43
+ const m = fm.match(new RegExp(`^${key}:\\s*(.*)$`, "m"));
44
+ return m ? yamlScalar(m[1]) : "";
45
+ }
46
+ function parseDescription(raw) {
47
+ const fm = frontmatter(raw);
48
+ if (fm) {
49
+ const desc = field(fm, "description");
50
+ if (desc && desc !== "|" && desc !== ">")
51
+ return desc;
52
+ }
53
+ const body = fm === null ? raw : raw.slice(raw.indexOf("---", 3) + 3);
54
+ for (const line of body.split(/\r?\n/)) {
55
+ const t = line.trim();
56
+ if (!t || t === "---" || t.startsWith("#"))
57
+ continue;
58
+ return t;
59
+ }
60
+ return "";
61
+ }
62
+ function parseName(raw, fallback) {
63
+ const fm = frontmatter(raw);
64
+ if (fm) {
65
+ const name = field(fm, "name");
66
+ if (name)
67
+ return name;
68
+ }
69
+ return fallback;
70
+ }
71
+ function isFile(fs, p) {
72
+ try {
73
+ return fs.statSync(p).isFile();
74
+ }
75
+ catch {
76
+ return false;
77
+ }
78
+ }
79
+ function readSkill(fs, file) {
80
+ let raw = "";
81
+ try {
82
+ raw = fs.readFileSync(file, "utf8");
83
+ }
84
+ catch { /* empty */ }
85
+ const fallback = file.replace(/\\/g, "/").split("/").pop()?.replace(/\.md$/i, "") || "skill";
86
+ const leaf = fallback === "SKILL" ? (file.replace(/\\/g, "/").split("/").slice(-2, -1)[0] || "skill") : fallback;
87
+ return { name: parseName(raw, leaf), description: parseDescription(raw) };
88
+ }
89
+ export function listLocalSkills() {
90
+ const b = nodeBuiltins();
91
+ if (!b)
92
+ return [];
93
+ const root = localSkillsDir();
94
+ if (!root)
95
+ return [];
96
+ let ents = [];
97
+ try {
98
+ ents = b.fs.readdirSync(root, { withFileTypes: true });
99
+ }
100
+ catch {
101
+ return [];
102
+ }
103
+ const found = [];
104
+ for (const ent of ents) {
105
+ if (ent.name.startsWith("."))
106
+ continue;
107
+ const full = b.path.join(root, ent.name);
108
+ if (ent.isFile() && ent.name.endsWith(".md")) {
109
+ const meta = readSkill(b.fs, full);
110
+ found.push({ name: meta.name, file: full, dir: false, description: meta.description });
111
+ }
112
+ }
113
+ const walk = (dir, depth) => {
114
+ if (depth >= 2)
115
+ return;
116
+ let kids = [];
117
+ try {
118
+ kids = b.fs.readdirSync(dir, { withFileTypes: true });
119
+ }
120
+ catch {
121
+ return;
122
+ }
123
+ for (const ent of kids) {
124
+ if (ent.name.startsWith(".") || !ent.isDirectory())
125
+ continue;
126
+ const full = b.path.join(dir, ent.name);
127
+ const skillMd = b.path.join(full, "SKILL.md");
128
+ if (isFile(b.fs, skillMd)) {
129
+ const meta = readSkill(b.fs, skillMd);
130
+ found.push({ name: meta.name, file: skillMd, dir: true, root: full, description: meta.description });
131
+ }
132
+ else {
133
+ walk(full, depth + 1);
134
+ }
135
+ }
136
+ };
137
+ walk(root, 0);
138
+ found.sort((a, c) => a.file.localeCompare(c.file));
139
+ const byName = new Map();
140
+ for (const s of found) {
141
+ const prev = byName.get(s.name);
142
+ if (!prev || (s.dir && !prev.dir))
143
+ byName.set(s.name, s);
144
+ }
145
+ return [...byName.values()].sort((a, c) => a.name.localeCompare(c.name));
146
+ }
147
+ export function resolveSkillFile(skillRoot, filePath) {
148
+ const b = nodeBuiltins();
149
+ if (!b || !filePath)
150
+ return null;
151
+ if (b.path.isAbsolute(filePath))
152
+ return null;
153
+ const target = b.path.resolve(skillRoot, filePath);
154
+ const rel = b.path.relative(skillRoot, target);
155
+ if (!rel || rel.startsWith("..") || b.path.isAbsolute(rel))
156
+ return null;
157
+ return target;
158
+ }
159
+ export function renderSkillsIndex() {
160
+ const skills = listLocalSkills();
161
+ if (!skills.length)
162
+ return "";
163
+ const lines = [];
164
+ let used = 0;
165
+ for (const s of skills) {
166
+ const desc = s.description.replace(/\s+/g, " ").trim().slice(0, INDEX_DESC);
167
+ const line = `${s.name}: ${desc}`;
168
+ const next = used + line.length + (lines.length ? 1 : 0);
169
+ if (next > INDEX_CAP)
170
+ break;
171
+ lines.push(line);
172
+ used = next;
173
+ }
174
+ return lines.join("\n");
175
+ }
@@ -3,9 +3,9 @@
3
3
  // background memory reorganization while the main agent is idle.
4
4
  import { runConsolidationPass } from "./sleep.js";
5
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");
6
+ import { dirname } from "node:path";
7
+ import { operatorPath } from "../config/home.js";
8
+ const DEFAULT_LOG = operatorPath("sleep-consolidation.log");
9
9
  let schedulerInstance = null;
10
10
  /** Get or create the singleton sleep scheduler. */
11
11
  export function getSleepScheduler() {
@@ -42,8 +42,11 @@ export class SleepScheduler {
42
42
  const threshold = consolidationOpts?.stepsBetweenPasses ?? 10;
43
43
  if (this.stepsSinceConsolidation >= threshold && !this.running) {
44
44
  this.stepsSinceConsolidation = 0;
45
- // Schedule consolidation on next idle
46
- this.idleTimer = setTimeout(() => this.tryConsolidate(), 1000);
45
+ // Arm for the idle threshold, NOT a fixed 1s. tryConsolidate() bails unless we've actually been idle
46
+ // >= idleThresholdSec, and any later step cancels this timer (above) — so firing at 1s always observed
47
+ // ~1s idle and aborted, meaning consolidation never ran. Fire once a genuine idle window has elapsed. (0.1.177)
48
+ const idleThresholdMs = (consolidationOpts?.idleThresholdSec ?? 30) * 1000;
49
+ this.idleTimer = setTimeout(() => this.tryConsolidate(), idleThresholdMs);
47
50
  }
48
51
  }
49
52
  /** Called when the agent is idle (no active turn). */
@@ -78,7 +81,7 @@ export class SleepScheduler {
78
81
  }
79
82
  try {
80
83
  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`;
84
+ const logLine = `[${new Date().toISOString()}] consolidation: extracted=${result.lessonsExtracted} persisted=${result.lessonsPersisted} curated=${result.lessonsCurated} deduped=${result.memoryDeduped} flywheel=${result.flywheelProcessed ?? 0} error=${result.error || "none"}\n`;
82
85
  appendFileSync(this.logFile, logLine, "utf8");
83
86
  this.opts.onComplete?.(result);
84
87
  }
@@ -93,7 +96,7 @@ export class SleepScheduler {
93
96
  /** Force a consolidation pass now (for testing or manual trigger). */
94
97
  forceConsolidate() {
95
98
  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`;
99
+ const logLine = `[${new Date().toISOString()}] forced consolidation: extracted=${result.lessonsExtracted} persisted=${result.lessonsPersisted} curated=${result.lessonsCurated} deduped=${result.memoryDeduped} flywheel=${result.flywheelProcessed ?? 0} error=${result.error || "none"}\n`;
97
100
  appendFileSync(this.logFile, logLine, "utf8");
98
101
  this.opts.onComplete?.(result);
99
102
  return result;
@@ -14,7 +14,8 @@
14
14
  // - Curates candidate deltas from captureFailureLesson into final lessons
15
15
  import { readFileSync, writeFileSync, existsSync, appendFileSync, mkdirSync } from "node:fs";
16
16
  import { dirname } from "node:path";
17
- import { homedir } from "node:os";
17
+ import { operatorPath } from "../config/home.js";
18
+ import { FlywheelProcessor } from "../flywheel/processor.js";
18
19
  const DEFAULTS = {
19
20
  enabled: false,
20
21
  idleThresholdSec: 30,
@@ -279,13 +280,26 @@ export async function runConsolidationPass(opts = {}) {
279
280
  }
280
281
  try {
281
282
  // 1. Extract candidate lessons from flywheel
282
- const candidates = await extractFlywheelLessons(merged.flywheelDir ?? `${homedir()}/.axe/operator/flywheel`);
283
+ const flywheelDir = merged.flywheelDir ?? operatorPath("flywheel");
284
+ const candidates = await extractFlywheelLessons(flywheelDir);
283
285
  result.lessonsExtracted = candidates.length;
286
+ // 1b. Recursive self-improvement: run the full flywheel processor over graded trajectories — SRFT
287
+ // masking + a processed/ export the training pipeline consumes. Best-effort: a failure here must
288
+ // never sink the memory-consolidation pass. (Wired 0.1.177 — FlywheelProcessor was dead code.)
289
+ try {
290
+ const processed = await new FlywheelProcessor({
291
+ flywheelDir,
292
+ applySRFT: true,
293
+ runMutationCheck: false, // needs a per-turn verify cmd + diff sha, unavailable in the offline pass
294
+ }).processAll();
295
+ result.flywheelProcessed = processed.processed;
296
+ }
297
+ catch { /* flywheel processing is best-effort — never fail consolidation over it */ }
284
298
  // 2. Curate into final lessons
285
299
  const curated = curateLessons(candidates);
286
300
  result.lessonsPersisted = curated.length;
287
301
  // 3. Persist to memory file
288
- const memFile = merged.memoryFile ?? `${homedir()}/.axe/operator/Operator_Memory.jsonl`;
302
+ const memFile = merged.memoryFile ?? operatorPath("Operator_Memory.jsonl");
289
303
  if (curated.length > 0) {
290
304
  result.lessonsCurated = curated.length;
291
305
  persistLessons(memFile, curated);