@0perator/operator 0.1.351 → 0.1.353

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/dist/acp/agent.js +2 -2
  2. package/dist/acp/tool-map.js +5 -4
  3. package/dist/autonomy/delegate.js +54 -1
  4. package/dist/autonomy/headless.js +2 -0
  5. package/dist/autonomy/session-factory.js +1 -0
  6. package/dist/background/index.js +86 -10
  7. package/dist/background/notices.js +16 -4
  8. package/dist/cli.js +1073 -177
  9. package/dist/config/home.js +6 -0
  10. package/dist/config/memory-sections.js +92 -0
  11. package/dist/config/persona.js +144 -26
  12. package/dist/config/settings.js +15 -4
  13. package/dist/consolidation/scheduler.js +9 -2
  14. package/dist/consolidation/sleep.js +39 -278
  15. package/dist/engine/agent.js +444 -76
  16. package/dist/engine/anthropic-chat.js +13 -2
  17. package/dist/engine/aurora.js +66 -19
  18. package/dist/engine/batch-scheduler.js +27 -3
  19. package/dist/engine/compaction.js +12 -5
  20. package/dist/engine/continuation.js +14 -12
  21. package/dist/engine/contract.js +1 -1
  22. package/dist/engine/decision-points.js +7 -1
  23. package/dist/engine/front-door.js +59 -0
  24. package/dist/engine/grandmaster.js +13 -1
  25. package/dist/engine/loop-guard.js +694 -0
  26. package/dist/engine/owner-act.js +52 -0
  27. package/dist/engine/verify-gate.js +52 -0
  28. package/dist/flywheel/processor.js +3 -1
  29. package/dist/flywheel/srft.js +8 -4
  30. package/dist/hooks/index.js +12 -8
  31. package/dist/mcp/index.js +9 -4
  32. package/dist/permissions/index.js +32 -11
  33. package/dist/permissions/modes.js +42 -0
  34. package/dist/permissions/plan-review.js +100 -0
  35. package/dist/permissions/policy.js +16 -5
  36. package/dist/permissions/signature.js +8 -3
  37. package/dist/remote/safe-commands.js +1 -1
  38. package/dist/router/read-rates.js +152 -0
  39. package/dist/selfimprove/backfill.js +174 -0
  40. package/dist/selfimprove/index.js +146 -57
  41. package/dist/selfimprove/lessons.js +429 -0
  42. package/dist/selfimprove/sync.js +58 -0
  43. package/dist/session.js +362 -33
  44. package/dist/skills/finder.js +219 -0
  45. package/dist/toolchain/toolchain.py +528 -112
  46. package/dist/tools/deferred.js +28 -18
  47. package/dist/tools/executor.js +7 -3
  48. package/dist/tools/registry.js +68 -7
  49. package/dist/tools/result-cap.js +1 -1
  50. package/dist/ui/ActivitySpinner.js +21 -12
  51. package/dist/ui/App.js +107 -30
  52. package/dist/ui/ApprovalPrompt.js +5 -3
  53. package/dist/ui/ArtifactPicker.js +3 -3
  54. package/dist/ui/BgPanel.js +105 -5
  55. package/dist/ui/Composer.js +85 -9
  56. package/dist/ui/PlanPane.js +72 -8
  57. package/dist/ui/QuestionPrompt.js +6 -4
  58. package/dist/ui/SecretPrompt.js +8 -3
  59. package/dist/ui/SessionPicker.js +2 -2
  60. package/dist/ui/SkillFinder.js +153 -0
  61. package/dist/ui/StatusRule.js +5 -2
  62. package/dist/ui/SummaryCard.js +3 -1
  63. package/dist/ui/ThinkingSpinner.js +11 -2
  64. package/dist/ui/ToolBatch.js +11 -2
  65. package/dist/ui/ToolStep.js +36 -13
  66. package/dist/ui/Transcript.js +13 -2
  67. package/dist/ui/actNow.js +61 -0
  68. package/dist/ui/batchLine.js +165 -0
  69. package/dist/ui/conversations.js +154 -0
  70. package/dist/ui/decodeHealth.js +77 -0
  71. package/dist/ui/expand.js +17 -0
  72. package/dist/ui/fit.js +40 -0
  73. package/dist/ui/fitTail.js +14 -0
  74. package/dist/ui/fold.js +149 -0
  75. package/dist/ui/format.js +46 -2
  76. package/dist/ui/liveTools.js +163 -13
  77. package/dist/ui/modelPicker.js +78 -6
  78. package/dist/ui/nextStep.js +103 -0
  79. package/dist/ui/pending.js +57 -0
  80. package/dist/ui/phase.js +105 -0
  81. package/dist/ui/planExit.js +0 -5
  82. package/dist/ui/progressbar.js +4 -26
  83. package/dist/ui/readForecast.js +44 -0
  84. package/dist/ui/readProgress.js +119 -0
  85. package/dist/ui/reportLine.js +62 -0
  86. package/dist/ui/slashCommands.js +1 -1
  87. package/dist/ui/theme.js +1 -0
  88. package/dist/ui/turnFlow.js +72 -0
  89. package/dist/ui/turnLedger.js +121 -0
  90. package/dist/ui/turnScope.js +11 -0
  91. package/dist/util/slash.js +18 -0
  92. package/package.json +1 -1
@@ -40,6 +40,12 @@ export function operatorPath(...parts) {
40
40
  const b = builtins();
41
41
  return b ? b.path.join(home, ...parts) : [home, ...parts].join("/");
42
42
  }
43
+ /** The global memories.md every session loads (config/persona.ts loadMemories): `$KODE_MEMORIES_FILE`, else the
44
+ * operator home's. Lives here, node-free, so the self-improvement loop can write lessons into it (selfimprove/). */
45
+ export function globalMemoriesPath() {
46
+ const env = globalThis.process?.env;
47
+ return env?.KODE_MEMORIES_FILE ?? operatorPath("memories.md");
48
+ }
43
49
  /** The managed owner-CLI toolkit's single PATH addition (operator-home-v2 phase 5): every tool
44
50
  * toolkit-verify.sh materializes lands here as a symlink. */
45
51
  export function toolsBinPath() {
@@ -0,0 +1,92 @@
1
+ // memories.md as whole sections (config/persona.ts loadMemories). A section is a `## ` heading with everything under it
2
+ // (its `### ` subsections included), or the text before the first heading. It loads whole or not at all: the old loader
3
+ // kept the file's last 6000 chars, and on the owner's 19.5K file that cut "Engineering traps — HARD RULES" mid-rule and
4
+ // dropped "Bias to action — build, don't circle", the EXCEPTION list and the codestack default mode entirely.
5
+ // Pure string work (no node imports): selfimprove/lessons.ts reads the taught rules from the same split.
6
+ // A heading that states a rule: RULE(S) / POLICY / EXCEPTION / MODE / DISCIPLINE, or an imperative.
7
+ const RULES_HEADING_RE = /\b(?:RULES?|POLICY|EXCEPTION|MODE|DISCIPLINE)\b|\b(?:never|always|don'?t|do not|must)\b/i;
8
+ /** `## Bias to action — build, don't circle (2026-10-16)` → `Bias to action — build, don't circle`. */
9
+ export function headingName(heading) {
10
+ return heading.replace(/^#+\s*/, "").replace(/\s*\((?:\d{4}-\d{2}-\d{2})[^)]*\)\s*$/, "").trim();
11
+ }
12
+ /** The file split at its `## ` headings; `skip` names headings whose whole section is left out (the lessons). */
13
+ export function splitSections(text, skip = () => false) {
14
+ const out = [];
15
+ let heading = "";
16
+ let body = [];
17
+ const flush = () => {
18
+ const t = [heading, ...body].join("\n").trim();
19
+ if (!heading && body.every((l) => /^(?:#\s.*|>\s.*|\s*)$/.test(l)))
20
+ return; // a file title / blurb only — nothing to load
21
+ if (t && !(heading && skip(heading)))
22
+ out.push({ heading, name: headingName(heading), text: t, rules: !!heading && RULES_HEADING_RE.test(headingName(heading)) });
23
+ };
24
+ for (const line of text.split("\n")) {
25
+ if (/^## /.test(line)) {
26
+ flush();
27
+ heading = line.trim();
28
+ body = [];
29
+ }
30
+ else
31
+ body.push(line);
32
+ }
33
+ flush();
34
+ return out;
35
+ }
36
+ /** The rules a memories file teaches, in file order: every rules section and `### ` subsection by its heading, and the
37
+ * numbered items of a HARD RULES section by number and title ("3. DECISIVENESS (anti-micro-stepping): …"). */
38
+ export function taughtRules(text, skip) {
39
+ const out = [];
40
+ for (const s of splitSections(text, skip)) {
41
+ if (!s.rules)
42
+ continue;
43
+ out.push({ name: `"${s.name}"`, title: s.name });
44
+ const hard = /\bHARD RULES\b/i.test(s.heading);
45
+ for (const line of s.text.split("\n").slice(1)) {
46
+ if (/^### /.test(line)) {
47
+ const n = headingName(line);
48
+ out.push({ name: `"${n}"`, title: n });
49
+ continue;
50
+ }
51
+ const m = hard ? /^(\d+)\.\s+(.+)$/.exec(line) : null;
52
+ if (!m)
53
+ continue;
54
+ const title = m[2].split(/:\s|\.\s/)[0].slice(0, 80).trim();
55
+ out.push({ name: `HARD RULE ${m[1]} ${title.replace(/\s*\([^)]*\)\s*$/, "").trim()}`, title });
56
+ }
57
+ }
58
+ return out;
59
+ }
60
+ /** The facts of a flat list — the text before a file's first heading, where `/remember` appends `- note` lines: each
61
+ * top-level item with its indented continuation lines, in file order. Lines before the first item stay together. */
62
+ export function splitItems(text) {
63
+ const out = [];
64
+ for (const line of text.split("\n")) {
65
+ if (!out.length || /^(?:[-*]|\d+\.)\s/.test(line))
66
+ out.push(line);
67
+ else
68
+ out[out.length - 1] += `\n${line}`;
69
+ }
70
+ return out.map((s) => s.trim()).filter(Boolean);
71
+ }
72
+ /** Fill a budget with whole units in priority order; a unit that does not fit is left out and the next is tried — except
73
+ * in a `run` (the flat facts, newest first): once one misses, the older ones are left out too, so the kept facts are
74
+ * the newest, never a gap with an old one squeezed in. */
75
+ export function fitWhole(units, size, budget, run = () => false) {
76
+ const kept = new Set();
77
+ const dropped = [];
78
+ let used = 0;
79
+ let runBroken = false;
80
+ for (const u of units) {
81
+ const n = size(u);
82
+ if (!(run(u) && runBroken) && used + n <= budget) {
83
+ kept.add(u);
84
+ used += n;
85
+ continue;
86
+ }
87
+ dropped.push(u);
88
+ if (run(u))
89
+ runBroken = true;
90
+ }
91
+ return { kept, dropped, used };
92
+ }
@@ -2,9 +2,9 @@
2
2
  // (autonomy/session-factory.ts). Extracted here so an unattended `operator run/loop/board/dream`
3
3
  // picks up the SAME project context + handoff the TUI does, without importing cli.tsx (which mounts
4
4
  // Ink and refuses a non-TTY). Pure, best-effort, never throws — a missing file is normal.
5
- import { readFileSync, appendFileSync, mkdirSync, existsSync } from "node:fs";
5
+ import { readFileSync, appendFileSync, mkdirSync, existsSync, writeFileSync, renameSync, realpathSync, statSync, chmodSync } from "node:fs";
6
6
  import { join, dirname } from "node:path";
7
- import { operatorPath } from "./home.js";
7
+ import { operatorPath, globalMemoriesPath } from "./home.js";
8
8
  import { renderHarnessContext } from "./operator-harness.js";
9
9
  import { renderToolCatalogue, registry } from "../tools/registry.js";
10
10
  import { NATIVE_CORE_TOOLS } from "../tools/deferred.js";
@@ -12,6 +12,9 @@ import { isFeatureEnabled } from "./features.js";
12
12
  import { renderSkillsIndex } from "./skills-index.js";
13
13
  import { decisionPointsEnabled } from "../engine/decision-points.js";
14
14
  import { SUBAGENT_ROLES, SUBAGENT_TOOL_DENY } from "../engine/grandmaster.js";
15
+ import { LESSONS_HEADING, isLessonHeading, mergeLessons, parseLessonTag, reinforcedRules, splitLessons } from "../selfimprove/lessons.js";
16
+ import { redactSecrets } from "../engine/redact.js";
17
+ import { fitWhole, splitItems, splitSections } from "./memory-sections.js";
15
18
  // Project context: auto-load a per-repo instructions file from `cwd` and append it to the system prompt, so
16
19
  // Operator picks up house rules, conventions and build commands the way modern coding agents do. First match
17
20
  // wins, so the ORDER is the brand precedence: our own `.operator/AGENTS.md`, then the vendor-neutral open
@@ -35,42 +38,129 @@ export function loadProjectContext(cwd = process.cwd()) {
35
38
  // session. Global lives beside operator/settings.json (~/.axe/operator/memories.md; override with
36
39
  // KODE_MEMORIES_FILE); project is .operator/memories.md, or a repo-root memories.md. Global is emitted
37
40
  // FIRST and project LAST, so a repo-specific note overrides a global one — the same more-specific-wins
38
- // precedence as the settings layer. Capped so a huge file
39
- // can't blow the prompt — and the file is append-only (newest last), so the cap keeps the TAIL, like
40
- // loadHandoff; best-effort, never throws — a missing file is normal.
41
- const MEMORIES_CAP = 6000;
42
- const memoriesTail = (t) => (t.length > MEMORIES_CAP ? "…\n" + t.slice(-MEMORIES_CAP) : t);
43
- export function globalMemoriesPath() {
44
- return process.env.KODE_MEMORIES_FILE ?? operatorPath("memories.md");
45
- }
41
+ // precedence as the settings layer. Best-effort, never throws — a missing file is normal.
42
+ // Loaded by WHOLE sections (config/memory-sections.ts) inside one measured budget per file, in priority order: the
43
+ // lessons (selfimprove/lessons.ts — my own turns' first, then my reviewers'), the rules sections, then the notes. A
44
+ // section that does not fit is left out whole and named, never cut. The old loader kept the file's last 6000 chars: on
45
+ // the owner's 19.5K global file that cut "Engineering traps — HARD RULES" mid-rule and dropped "Bias to action — build,
46
+ // don't circle", the EXCEPTION list and the codestack default mode, and a project's older stuck lessons sat past it too.
47
+ // The budget, measured on 11/02 copies of the owner's files: the global file (19,455 chars, 13 sections) plus its lessons
48
+ // (2 loop lines, 49 taught) is a 30,480-char block (~8.5K tokens at the prompt-budget doc's 3.6 chars/token), 32,096 with
49
+ // the 4 folded stuck classes of a session started in ~; the old loader gave 6,062 / 12,120. The global budget fits it
50
+ // with room; a project file keeps the old 6000. Past a budget the notes go first.
51
+ export const MEMORY_BUDGET = { global: 36_000, project: 6_000 };
52
+ export { globalMemoriesPath };
46
53
  export function projectMemoriesPath(cwd = process.cwd()) {
47
54
  return join(cwd, ".operator", "memories.md");
48
55
  }
49
- export function loadMemories(cwd = process.cwd()) {
56
+ const unitSize = (u) => u.text.length + 2;
57
+ /** A file's units: each headed section whole, and the facts of its flat list (the text before the first heading). */
58
+ function fileUnits(rest) {
59
+ return splitSections(rest).flatMap((section) => section.heading
60
+ ? [{ text: section.text, section }]
61
+ : splitItems(section.text).map((text) => ({ text, fact: true })));
62
+ }
63
+ /** One file's sections and facts under `budget` in priority order — `ahead` first (the lessons), then the rules sections,
64
+ * `between` (the taught lessons), the flat facts newest first, the notes sections — rendered as the rules, the facts,
65
+ * then the notes, each in file order; what is left out is named. */
66
+ function fitFile(units, budget, ahead = [], between = []) {
67
+ const rules = units.filter((u) => u.section?.rules);
68
+ const facts = units.filter((u) => u.fact);
69
+ const notes = units.filter((u) => u.section && !u.section.rules);
70
+ const fit = fitWhole([...ahead, ...rules, ...between, ...[...facts].reverse(), ...notes], unitSize, budget, (u) => !!u.fact);
71
+ const keptFacts = facts.filter((u) => fit.kept.has(u));
72
+ const shown = [...rules.filter((u) => fit.kept.has(u)).map((u) => u.text), ...(keptFacts.length ? [keptFacts.map((u) => u.text).join("\n")] : []),
73
+ ...notes.filter((u) => fit.kept.has(u)).map((u) => u.text)];
74
+ const droppedNames = [...rules, ...notes].filter((u) => !fit.kept.has(u)).map((u) => `"${u.section.name}"`);
75
+ const droppedFacts = facts.length - keptFacts.length;
76
+ if (droppedFacts)
77
+ droppedNames.unshift(`${droppedFacts} older note${droppedFacts === 1 ? "" : "s"}`);
78
+ return { fit, shown, droppedNames };
79
+ }
80
+ const leftOut = (names, where) => names.length ? `\n(left out for the memory budget: ${names.join(", ")} — read ${where} for them)` : "";
81
+ /** The memory blocks of the system prompt: the lessons of both files as one list, then the global file's sections, then
82
+ * the project file's — each file under its own MEMORY_BUDGET, whole lessons and sections only. Pure. */
83
+ export function renderMemories(global, project) {
84
+ const taught = reinforcedRules(global?.text ?? "");
85
+ const g = splitLessons(global?.text ?? "", taught);
86
+ const p = project ? splitLessons(project.text, taught) : undefined;
87
+ const lessons = mergeLessons(g.lessons, p?.lessons ?? []).map(redactSecrets); // a line an older build wrote unmasked
88
+ const auto = [...lessons.filter((l) => parseLessonTag(l)?.kind !== "taught"), ...g.other, ...(p?.other ?? [])].map((text) => ({ text }));
89
+ const fromReviewers = lessons.filter((l) => parseLessonTag(l)?.kind === "taught").map((text) => ({ text }));
90
+ const where = global?.path ?? "memories.md";
50
91
  let out = "";
92
+ const gf = fitFile(fileUnits(g.rest), MEMORY_BUDGET.global, auto, fromReviewers);
93
+ const keptLessons = [...auto, ...fromReviewers].filter((u) => gf.fit.kept.has(u));
94
+ const droppedLessons = auto.length + fromReviewers.length - keptLessons.length;
95
+ if (keptLessons.length) {
96
+ out += `\n\n${LESSONS_HEADING}\n${keptLessons.map((u) => u.text).join("\n")}` +
97
+ (droppedLessons ? `\n(${droppedLessons} older lesson${droppedLessons === 1 ? "" : "s"} left out for the memory budget — all of them are in ${where})` : "");
98
+ }
99
+ if (gf.shown.length || gf.droppedNames.length) {
100
+ out += `\n\n## Global memory (memories.md — applies to every project)\n${gf.shown.join("\n\n")}${leftOut(gf.droppedNames, where)}`;
101
+ }
102
+ if (project && p) {
103
+ const pf = fitFile(fileUnits(p.rest), MEMORY_BUDGET.project);
104
+ if (pf.shown.length || pf.droppedNames.length) {
105
+ out += `\n\n## Project memory (${project.name} — this repo)\n${pf.shown.join("\n\n")}${leftOut(pf.droppedNames, project.name)}`;
106
+ }
107
+ }
108
+ return out;
109
+ }
110
+ export function loadMemories(cwd = process.cwd()) {
111
+ let global;
51
112
  try {
52
- const t = readFileSync(globalMemoriesPath(), "utf8").trim();
53
- if (t)
54
- out += `\n\n## Global memory (memories.md — applies to every project)\n${memoriesTail(t)}`;
113
+ global = { text: readFileSync(globalMemoriesPath(), "utf8"), path: globalMemoriesPath() };
55
114
  }
56
115
  catch { /* none yet */ }
116
+ let project;
57
117
  for (const name of [".operator/memories.md", "memories.md"]) {
58
118
  try {
59
- const t = readFileSync(join(cwd, name), "utf8").trim();
60
- if (t) {
61
- out += `\n\n## Project memory (${name} — this repo)\n${memoriesTail(t)}`;
119
+ const t = readFileSync(join(cwd, name), "utf8");
120
+ if (t.trim()) {
121
+ project = { name, text: t };
62
122
  break;
63
123
  }
64
124
  }
65
125
  catch { /* try the next */ }
66
126
  }
67
- return out;
127
+ return renderMemories(global, project);
128
+ }
129
+ /** Where a `/remember` note goes in a memories file: its end — or, when the file ends in the lessons section (the
130
+ * self-improvement loop creates it at the end, selfimprove/lessons.ts), just before that section's heading, so a note
131
+ * never lands among the lessons, where it would load under their heading. A char offset. */
132
+ export function noteInsertAt(text) {
133
+ const lines = text.split("\n");
134
+ let last = -1;
135
+ for (let i = 0; i < lines.length; i++)
136
+ if (/^#{1,2} /.test(lines[i]))
137
+ last = i;
138
+ return last >= 0 && isLessonHeading(lines[last]) ? lines.slice(0, last).join("\n").length + (last ? 1 : 0) : text.length;
139
+ }
140
+ /** Replace the owner's file in one step (tmp + rename beside the real file, its mode kept): a crash mid-write must not
141
+ * leave half of it. The sync twin of selfimprove/index.ts writeMemoriesAtomic. */
142
+ function writeMemoriesAtomicSync(path, text) {
143
+ let real = path;
144
+ try {
145
+ real = realpathSync(path);
146
+ }
147
+ catch { /* a new file */ }
148
+ let mode;
149
+ try {
150
+ mode = statSync(real).mode & 0o777;
151
+ }
152
+ catch { /* a new file */ }
153
+ const tmp = `${real}.${process.pid}.${Date.now()}.tmp`;
154
+ writeFileSync(tmp, text, { encoding: "utf8", mode: mode ?? 0o644 });
155
+ if (mode !== undefined)
156
+ chmodSync(tmp, mode);
157
+ renameSync(tmp, real);
68
158
  }
69
159
  // The write half of loadMemories — append one note to a memories.md so `/remember` keeps the flat file
70
160
  // living, the way a `#`-style quick-add does in comparable agents. scope "global" targets
71
161
  // ~/.axe/operator/memories.md (every project); "project" (default) targets ./.operator/memories.md. Creates
72
- // the file (with a heading) and its parent dir on first write. Returns the path written, or "" on failure
73
- // (best-effort, never throws).
162
+ // the file (with a heading) and its parent dir on first write; a file that ends in the lessons section gets the
163
+ // note just before it (noteInsertAt). Returns the path written, or "" on failure (best-effort, never throws).
74
164
  export function appendMemory(text, scope = "project", cwd = process.cwd()) {
75
165
  const note = text.trim();
76
166
  if (!note)
@@ -79,13 +169,20 @@ export function appendMemory(text, scope = "project", cwd = process.cwd()) {
79
169
  try {
80
170
  mkdirSync(dirname(path), { recursive: true });
81
171
  let header = "";
172
+ let existing;
82
173
  try {
83
- readFileSync(path, "utf8");
174
+ existing = readFileSync(path, "utf8");
84
175
  }
85
176
  catch {
86
177
  header = `# Operator memories\n\n> Always-loaded notes for ${scope === "global" ? "this user (every project)" : "this repo"}. One fact per line.\n\n`;
87
178
  }
88
- appendFileSync(path, `${header}- ${note}\n`);
179
+ const at = existing === undefined ? 0 : noteInsertAt(existing);
180
+ if (existing !== undefined && at < existing.length) {
181
+ const head = existing.slice(0, at).replace(/\n*$/, "");
182
+ writeMemoriesAtomicSync(path, `${head ? `${head}\n` : ""}- ${note}\n\n${existing.slice(at)}`);
183
+ }
184
+ else
185
+ appendFileSync(path, `${header}- ${note}\n`);
89
186
  return path;
90
187
  }
91
188
  catch {
@@ -339,7 +436,7 @@ function decisionPointsSection(opts) {
339
436
  return `\n## Decision points — give the owner options\nAt the START of a new build, feature or refactor, or when ` +
340
437
  `there are 2+ genuinely different approaches or an irreversible step: before your first change, give a short ` +
341
438
  `plan and call ask_user with 2-4 options, the recommended one FIRST marked "(recommended)". Then do what they ` +
342
- `chose. Routine fixes, small edits, questions and checks: never ask.`;
439
+ `chose. Routine fixes, small edits, questions and checks: never ask. In Autonomous mode a plan review replaces this.`;
343
440
  }
344
441
  return `\n## Decision points — give the owner options\nThe owner wants to steer direction, not approve chores. ` +
345
442
  `Call ask_user BEFORE your first change when: (1) the request is a new build, feature, integration or refactor ` +
@@ -350,8 +447,28 @@ function decisionPointsSection(opts) {
350
447
  `each a short line saying what happens. Read what you need first (read-only), then ask; once the owner ` +
351
448
  `answers, proceed with their choice without asking again this turn. Do NOT ask for routine work — a typo, a ` +
352
449
  `small clear edit, a rename, a bug you found, running tests, or a question you can answer. In plan mode, the ` +
353
- `plan you present IS the decision point.`;
450
+ `plan you present IS the decision point; in Autonomous mode, a plan review replaces these options.`;
354
451
  }
452
+ /** Autonomous mode's rules (permissions/modes.ts, plan-review.ts). They ride the conversation, never the system prompt,
453
+ * which stays byte-stable for the session: Session carries them on the owner's next message after the mode turns on,
454
+ * pins them into each compaction summary while it stays on, and carries AUTONOMOUS_MODE_OFF when it turns off. */
455
+ export const AUTONOMOUS_MODE_ON = `Autonomous mode is on: the owner reviews plans, not commands. These rules hold until a note says it is off.\n` +
456
+ `- Commands, edits and computer control run without approval prompts. Plan reviews replace the Decision points ` +
457
+ `options.\n` +
458
+ `- A question, a check or a single edit: just do it.\n` +
459
+ `- Multi-step work: write the plan with task_add (each step its own item, the approach you recommend; name a real ` +
460
+ `alternative in one line), keep working notes in the scratchpad, then ask ONCE: ask_user with planReview: true, a ` +
461
+ `one-line summary as the question, and in risks each class a step needs — money (payments, billing), prod (deploy, ` +
462
+ `push to main, publish, restart a service), destructive (rm -r / -f, dropping data).\n` +
463
+ `- Approve: carry out the whole plan without asking again. Adjust: change the task list and ask again. Cancel: ` +
464
+ `change nothing.\n` +
465
+ `- A money / prod / destructive step runs only if the approved plan lists its class; the engine holds any other. ` +
466
+ `Adding a step or clearing the list ends the approval.\n` +
467
+ `- At each milestone (a phase done, or a finding that changes the plan), report progress in a few lines and ask for ` +
468
+ `review of the next steps the same way. A plan approved with plan mode's Approve & run needs no second review ` +
469
+ `unless it has a risky step.`;
470
+ export const AUTONOMOUS_MODE_OFF = `Autonomous mode is off: stop following its plan-review rules. The Decision points rules apply again, and a step ` +
471
+ `that needs approval asks the owner when you make it.`;
355
472
  // Embodiment guidance, appended only to an interactive session with computer control on. It steers the
356
473
  // model to READ the screen with chauffeur's textual accessibility tree instead of hand-rolling osascript —
357
474
  // the exact loop that failed on Slack (AppleScript can't read Electron UIs). `chauffeurReady` = chauffeur is
@@ -359,7 +476,8 @@ function decisionPointsSection(opts) {
359
476
  function renderEmbodimentGuide(computerEnabled, chauffeurReady) {
360
477
  if (!computerEnabled)
361
478
  return "";
362
- return (`\n## Controlling this computer\nComputer control is ON (every action asks the owner first). Drive apps with ` +
479
+ return (`\n## Controlling this computer\nComputer control is ON (each action asks the owner first, except in Autonomous ` +
480
+ `mode). Drive apps with ` +
363
481
  `app_open / app_activate, computer_type, computer_key, computer_click, computer_screenshot.` +
364
482
  (chauffeurReady
365
483
  ? ` To SEE the screen use the chauffeur tools — NEVER shell_exec/osascript/System Events to read or drive ` +
@@ -380,7 +498,7 @@ function renderEmbodimentGuide(computerEnabled, chauffeurReady) {
380
498
  `- If ANY chauffeur tool returns "session has ended", call chauffeur:start_session ONCE (no arguments), ` +
381
499
  `then retry the read — do not loop the failing call.\n` +
382
500
  `Work END-TO-END from the owner's one instruction: read → decide → act by chaining these tools yourself, ` +
383
- `then report the result. Reads run without a prompt; only actions ask. Use ask_user only for a genuine ` +
501
+ `then report the result. Reads never ask; actions ask outside Autonomous mode. Use ask_user only for a genuine ` +
384
502
  `owner decision — never to walk through a task you can just do.`
385
503
  : ` NOTE: reliably READING on-screen UI (especially Electron apps like Slack) needs the chauffeur driver, ` +
386
504
  `which is not installed here; computer_screenshot only saves a PNG you cannot read back yet. Do not ` +
@@ -63,7 +63,7 @@ const DEFAULTS = {
63
63
  permissions: { mode: "gated" }, // ask-by-default: the user decides Allow/Deny; bypass is the opt-out
64
64
  telemetry: { enabled: true }, // local-only metrics (silent JSONL); remote sink opt-in via KODE_TELEMETRY_URL
65
65
  sandbox: { mode: "off" }, // no isolation by default — enterprise turns it on (KODE_SANDBOX / settings)
66
- computer: { enabled: true }, // computer control ON (every action asks; bg agents denied; macOS TCC on top). Off: KODE_COMPUTER=0, settings.json or managed policy
66
+ computer: { enabled: true }, // computer control ON (actions ask outside Autonomous mode; bg agents denied; macOS TCC on top). Off: KODE_COMPUTER=0, settings.json or managed policy
67
67
  sessionSearch: { enabled: true }, // /sessions + session_search over Operator's and agents.md providers' sessions; per-provider switches in sources; KODE_SESSION_SEARCH=0 to disable
68
68
  search: {}, // web_search backend unset by default; set search.searxngUrl / search.autopilotUrl or the env vars
69
69
  // Service lever — JL1 defaults. On a machine without these launchd agents every start step just fails
@@ -94,9 +94,9 @@ const DEFAULTS = {
94
94
  maxTurnWallClockSec: 0, // 0 ⇒ no per-turn time brake (was 900); turnWallClockMs() returns undefined
95
95
  loop: { maxTurns: 100000, maxWallClockSec: 86400, stallAfter: 3 }, // essentially unbounded loop; keep the stall break
96
96
  dream: { enabled: false, allow: ["board"], permissions: "readonly", maxTasks: 3 },
97
- // Sleep-time consolidation: ON by default — memory dedup, lesson extraction, and project curation run
98
- // during idle windows to keep the operator's knowledge base organized without blocking turns.
99
- sleepConsolidation: { enabled: true, idleThresholdSec: 30, stepsBetweenPasses: 10, modelTier: "fast", maxLessonsPerFile: 50 },
97
+ // Sleep-time consolidation: ON by default — the lessons fold (looped turns + mentor pairs → the global memories.md)
98
+ // and the flywheel processor run during idle windows, without blocking turns.
99
+ sleepConsolidation: { enabled: true, idleThresholdSec: 30, stepsBetweenPasses: 10, modelTier: "fast", maxLessonsPerFile: 100 },
100
100
  },
101
101
  };
102
102
  function settingsPath() {
@@ -186,6 +186,17 @@ function applyEnv(s) {
186
186
  const sb = process.env.KODE_SANDBOX;
187
187
  if (sb === "off" || sb === "workspace" || sb === "strict")
188
188
  out.sandbox = { mode: sb };
189
+ const fd = process.env.KODE_FRONT_DOOR; // the front door's gateway for one run: a base URL turns it on, "off" turns it off
190
+ if (fd === "off" || fd === "0")
191
+ out.frontDoor = undefined;
192
+ else if (fd)
193
+ out.frontDoor = { ...out.frontDoor, portal: fd };
194
+ // A front door needs its gateway's base URL. Without one ({"enabled": true}, the portal's own block pasted in) it is
195
+ // dropped with one line, instead of reaching every turn on the default model and MOA.
196
+ if (out.frontDoor && (typeof out.frontDoor.portal !== "string" || !/^https?:\/\/\S+$/.test(out.frontDoor.portal))) {
197
+ process.stderr.write(`[operator] settings.frontDoor ignored: "portal" must be the gateway's http(s) base URL\n`);
198
+ out.frontDoor = undefined;
199
+ }
189
200
  if (process.env.KODE_COMPUTER === "1")
190
201
  out.computer = { enabled: true };
191
202
  else if (process.env.KODE_COMPUTER === "0")
@@ -6,6 +6,13 @@ import { appendFileSync, mkdirSync } from "node:fs";
6
6
  import { dirname } from "node:path";
7
7
  import { operatorPath } from "../config/home.js";
8
8
  const DEFAULT_LOG = operatorPath("sleep-consolidation.log");
9
+ /** One log line: the counts, then each looped row the lessons fold found with the reward scorer's score beside it. */
10
+ function resultLine(r) {
11
+ const looped = (r.loopedRows ?? []).map((x) => `${new Date(x.ts).toISOString().slice(0, 16)}Z ${x.score === undefined ? "unscored" : x.score.toFixed(2)}`);
12
+ return `extracted=${r.lessonsExtracted} persisted=${r.lessonsPersisted} curated=${r.lessonsCurated} deduped=${r.memoryDeduped} ` +
13
+ `flywheel=${r.flywheelProcessed ?? 0} looped=${looped.length}${looped.length ? ` [${looped.join(", ")}]` : ""} ` +
14
+ `negative-score-candidates=${r.scoreCandidates ?? 0} error=${r.error || "none"}`;
15
+ }
9
16
  let schedulerInstance = null;
10
17
  /** Get or create the singleton sleep scheduler. */
11
18
  export function getSleepScheduler() {
@@ -81,7 +88,7 @@ export class SleepScheduler {
81
88
  }
82
89
  try {
83
90
  const result = await runConsolidationPass(consolidationOpts);
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`;
91
+ const logLine = `[${new Date().toISOString()}] consolidation: ${resultLine(result)}\n`;
85
92
  appendFileSync(this.logFile, logLine, "utf8");
86
93
  this.opts.onComplete?.(result);
87
94
  }
@@ -96,7 +103,7 @@ export class SleepScheduler {
96
103
  /** Force a consolidation pass now (for testing or manual trigger). */
97
104
  forceConsolidate() {
98
105
  return runConsolidationPass(this.opts.consolidation).then((result) => {
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`;
106
+ const logLine = `[${new Date().toISOString()}] forced consolidation: ${resultLine(result)}\n`;
100
107
  appendFileSync(this.logFile, logLine, "utf8");
101
108
  this.opts.onComplete?.(result);
102
109
  return result;