@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
@@ -0,0 +1,441 @@
1
+ // State hygiene for the operator home (operator-home-v2 HV3-05a): a self-healing audit-and-repair
2
+ // layer over the session-index store at $KODE_HOME/state/state.db (and its JSON fallback at
3
+ // state/session-index.json, see src/memory/session-index.ts).
4
+ //
5
+ // The store is DERIVED data — every byte in it is re-indexable from $KODE_HOME/sessions/*.json —
6
+ // which makes aggressive repair safe: a corrupt or desynced store is quarantined (renamed
7
+ // `<name>.corrupt-<ts>`, never deleted) and rebuilt from the transcripts. The one thing we never
8
+ // touch is a store that is merely LOCKED by a concurrent writer; "database is locked" is health,
9
+ // not damage, and quarantining it would yank the rug out from under the live process.
10
+ //
11
+ // Surface (exported module only; parent wires registry/cron/home):
12
+ // inspectState() read-only audit — reports issues, repairs nothing;
13
+ // maintainState() audit + self-heal + verify, writes a heartbeat summary to
14
+ // state/maintenance.json; idempotent, safe to call every session.
15
+ // stateMaintenanceStatus() last summary (for the home surface / cron alerting), null before
16
+ // the first run.
17
+ //
18
+ // Browser-safe: node builtins load lazily (same dynamic-import idiom as session-index.ts) and
19
+ // without fs everything degrades to a clean no-op report — index.browser.ts must keep passing the
20
+ // esbuild --platform=neutral purity gate.
21
+ import { get_operator_home, operatorPath } from "../config/home.js";
22
+ import { indexSessions, sessionIndexBackendKind } from "./session-index.js";
23
+ const nodeImport = (m) => import(/* @vite-ignore */ m);
24
+ let _fs = null;
25
+ let _path = null;
26
+ async function fsp() {
27
+ if (!_fs)
28
+ _fs = (await nodeImport("node:fs"));
29
+ if (!_path)
30
+ _path = (await nodeImport("node:path"));
31
+ return { fs: _fs, path: _path };
32
+ }
33
+ /** fs/path, or null on node-free hosts (JSCore/browser) where maintenance is a no-op. */
34
+ async function tryFs() {
35
+ try {
36
+ return await fsp();
37
+ }
38
+ catch {
39
+ return null;
40
+ }
41
+ }
42
+ const SQLITE_SIDECARS = ["-wal", "-shm", "-journal"];
43
+ const errMsg = (e) => (e instanceof Error ? e.message : String(e));
44
+ /** First value of the first row of a `.all()` result (PRAGMA/count queries vary in column name). */
45
+ function firstValue(rows) {
46
+ const row = rows[0];
47
+ if (row && typeof row === "object") {
48
+ const vals = Object.values(row);
49
+ if (vals.length)
50
+ return String(vals[0]);
51
+ }
52
+ return String(row);
53
+ }
54
+ function issue(code, detail) {
55
+ return { code, detail };
56
+ }
57
+ /** Map a sqlite/fs error onto our three repair classes: busy (hands-off), missing schema (create),
58
+ * anything else (treat the file as damaged — the store is re-derivable, quarantine is safe). */
59
+ function classifyError(err) {
60
+ const msg = errMsg(err);
61
+ if (/locked|busy/i.test(msg))
62
+ return "locked";
63
+ if (/no such table/i.test(msg))
64
+ return "schema";
65
+ return "damaged";
66
+ }
67
+ function emptyScan() {
68
+ return {
69
+ backend: "none", storeFile: null, sessions: new Map(), indexed: new Map(),
70
+ orphans: [], drifted: 0, issues: [], locked: false, needsQuarantine: false,
71
+ staleSidecarFiles: [],
72
+ };
73
+ }
74
+ async function listTranscripts(fs, path) {
75
+ const out = new Map();
76
+ const dir = operatorPath("sessions");
77
+ let names;
78
+ try {
79
+ names = fs.readdirSync(dir);
80
+ }
81
+ catch {
82
+ return out; // no sessions dir — nothing that should be indexed
83
+ }
84
+ for (const name of names) {
85
+ if (!name.endsWith(".json"))
86
+ continue;
87
+ try {
88
+ const st = fs.statSync(path.join(dir, name));
89
+ if (st.isFile())
90
+ out.set(name.slice(0, -".json".length), st.mtimeMs);
91
+ }
92
+ catch {
93
+ /* vanished mid-scan — a later run sees the truth */
94
+ }
95
+ }
96
+ return out;
97
+ }
98
+ async function openSqliteDb(dbFile) {
99
+ const sqlite = await nodeImport("node:sqlite");
100
+ if (!sqlite?.DatabaseSync)
101
+ throw new Error("node:sqlite unavailable");
102
+ return new sqlite.DatabaseSync(dbFile);
103
+ }
104
+ async function scanSqlite(dbFile) {
105
+ const issues = [];
106
+ const indexed = new Map();
107
+ let db;
108
+ try {
109
+ db = await openSqliteDb(dbFile);
110
+ }
111
+ catch (err) {
112
+ const k = classifyError(err);
113
+ if (k === "locked")
114
+ return { issues: [issue("locked-store", `state.db: ${errMsg(err)}`)], indexed, locked: true, needsQuarantine: false };
115
+ return { issues: [issue("corrupt-store", `state.db cannot be opened: ${errMsg(err)}`)], indexed, locked: false, needsQuarantine: true };
116
+ }
117
+ try {
118
+ try {
119
+ const rows = db.prepare("PRAGMA integrity_check").all();
120
+ const verdict = rows.length ? firstValue(rows) : "ok";
121
+ if (verdict !== "ok") {
122
+ return { issues: [issue("corrupt-store", `integrity_check: ${verdict}`)], indexed, locked: false, needsQuarantine: true };
123
+ }
124
+ }
125
+ catch (err) {
126
+ const k = classifyError(err);
127
+ if (k === "locked")
128
+ return { issues: [issue("locked-store", `integrity_check: ${errMsg(err)}`)], indexed, locked: true, needsQuarantine: false };
129
+ return { issues: [issue("corrupt-store", `integrity_check: ${errMsg(err)}`)], indexed, locked: false, needsQuarantine: true };
130
+ }
131
+ let metaRows;
132
+ try {
133
+ metaRows = db.prepare("SELECT id, mtime FROM sessions_meta").all();
134
+ }
135
+ catch (err) {
136
+ const k = classifyError(err);
137
+ if (k === "locked")
138
+ return { issues: [issue("locked-store", `sessions_meta: ${errMsg(err)}`)], indexed, locked: true, needsQuarantine: false };
139
+ if (k === "schema")
140
+ return { issues: [issue("schema-missing", "state.db has no sessions_meta table")], indexed, locked: false, needsQuarantine: false };
141
+ return { issues: [issue("corrupt-store", `sessions_meta: ${errMsg(err)}`)], indexed, locked: false, needsQuarantine: true };
142
+ }
143
+ for (const row of metaRows) {
144
+ indexed.set(String(row.id), Number(row.mtime));
145
+ }
146
+ try {
147
+ const ftsCount = Number(firstValue(db.prepare("SELECT count(*) AS n FROM sessions_fts").all()));
148
+ if (Number.isFinite(ftsCount) && ftsCount !== indexed.size) {
149
+ return {
150
+ issues: [issue("index-desync", `sessions_meta has ${indexed.size} rows, sessions_fts has ${ftsCount}`)],
151
+ indexed, locked: false, needsQuarantine: true,
152
+ };
153
+ }
154
+ }
155
+ catch (err) {
156
+ const k = classifyError(err);
157
+ if (k === "locked")
158
+ return { issues: [issue("locked-store", `sessions_fts: ${errMsg(err)}`)], indexed, locked: true, needsQuarantine: false };
159
+ if (k === "schema")
160
+ return { issues: [issue("index-desync", "state.db has no sessions_fts table")], indexed, locked: false, needsQuarantine: true };
161
+ return { issues: [issue("corrupt-store", `sessions_fts: ${errMsg(err)}`)], indexed, locked: false, needsQuarantine: true };
162
+ }
163
+ return { issues, indexed, locked: false, needsQuarantine: false };
164
+ }
165
+ finally {
166
+ try {
167
+ db.close();
168
+ }
169
+ catch {
170
+ /* best-effort */
171
+ }
172
+ }
173
+ }
174
+ function scanJson(fs, jsonFile) {
175
+ const indexed = new Map();
176
+ let raw;
177
+ try {
178
+ raw = fs.readFileSync(jsonFile, "utf8");
179
+ }
180
+ catch (err) {
181
+ const k = classifyError(err);
182
+ if (k === "locked")
183
+ return { issues: [issue("locked-store", `session-index.json: ${errMsg(err)}`)], indexed, locked: true, needsQuarantine: false };
184
+ return { issues: [issue("unreadable-store", `session-index.json: ${errMsg(err)}`)], indexed, locked: false, needsQuarantine: true };
185
+ }
186
+ let parsed;
187
+ try {
188
+ parsed = JSON.parse(raw);
189
+ }
190
+ catch (err) {
191
+ return { issues: [issue("corrupt-store", `session-index.json is not valid JSON: ${errMsg(err)}`)], indexed, locked: false, needsQuarantine: true };
192
+ }
193
+ if (parsed?.version !== 1 || !parsed.entries || typeof parsed.entries !== "object") {
194
+ return { issues: [issue("corrupt-store", "session-index.json has an unexpected shape (expected { version: 1, entries })")], indexed, locked: false, needsQuarantine: true };
195
+ }
196
+ for (const [id, e] of Object.entries(parsed.entries)) {
197
+ indexed.set(id, Number(e?.mtimeMs));
198
+ }
199
+ return { issues: [], indexed, locked: false, needsQuarantine: false };
200
+ }
201
+ async function scan() {
202
+ const f = await tryFs();
203
+ if (!f)
204
+ return emptyScan(); // node-free host: maintenance is a clean no-op
205
+ const { fs, path } = f;
206
+ const s = emptyScan();
207
+ s.sessions = await listTranscripts(fs, path);
208
+ const dbFile = operatorPath("state", "state.db");
209
+ const jsonFile = operatorPath("state", "session-index.json");
210
+ const exists = (p) => {
211
+ try {
212
+ return fs.existsSync(p);
213
+ }
214
+ catch {
215
+ return false;
216
+ }
217
+ };
218
+ if (exists(dbFile)) {
219
+ // sqlite is the effective store whenever its file exists — session-index prefers it (and the
220
+ // json file is then just an inactive fallback).
221
+ s.backend = "sqlite";
222
+ s.storeFile = dbFile;
223
+ Object.assign(s, await scanSqlite(dbFile));
224
+ }
225
+ else if (exists(jsonFile)) {
226
+ s.backend = "json";
227
+ s.storeFile = jsonFile;
228
+ Object.assign(s, scanJson(fs, jsonFile));
229
+ }
230
+ else {
231
+ for (const sidecar of SQLITE_SIDECARS.map((suffix) => dbFile + suffix)) {
232
+ if (exists(sidecar))
233
+ s.staleSidecarFiles.push(sidecar);
234
+ }
235
+ if (s.staleSidecarFiles.length) {
236
+ s.issues.push(issue("stale-sidecars", s.staleSidecarFiles.map((p) => path.basename(p)).join(", ") + " without a state.db"));
237
+ }
238
+ if (s.sessions.size) {
239
+ s.issues.push(issue("missing-index", `${s.sessions.size} transcript(s) present but no state store exists`));
240
+ }
241
+ return s;
242
+ }
243
+ // Entry drift only means something when the store could actually be read and isn't destined
244
+ // for a full quarantine + rebuild anyway.
245
+ if (!s.locked && !s.needsQuarantine && s.storeFile) {
246
+ s.orphans = [...s.indexed.keys()].filter((id) => !s.sessions.has(id)).sort();
247
+ s.drifted = [...s.sessions].filter(([id, mtime]) => s.indexed.get(id) !== mtime).length;
248
+ if (s.orphans.length) {
249
+ s.issues.push(issue("orphan-entries", `${s.orphans.length} indexed session(s) have no transcript file: ${s.orphans.slice(0, 6).join(", ")}`));
250
+ }
251
+ if (s.drifted > 0) {
252
+ s.issues.push(issue("stale-entries", `${s.drifted} transcript(s) changed since they were indexed (or are missing from the index)`));
253
+ }
254
+ }
255
+ return s;
256
+ }
257
+ // ---------------------------------------------------------------------------
258
+ // Repair
259
+ // ---------------------------------------------------------------------------
260
+ /** session-index caches its backend by the resolved-home STRING; after a quarantine the cached
261
+ * handle still points at the moved-aside file. Flipping KODE_HOME to an equivalent-but-distinct
262
+ * spelling (trailing separator — path.join normalizes it away, so it's the same directory)
263
+ * forces a close + fresh open under both spellings. */
264
+ async function invalidateSessionIndexCache() {
265
+ const env = globalThis.process?.env;
266
+ if (!env)
267
+ return;
268
+ const prev = env.KODE_HOME;
269
+ const home = get_operator_home();
270
+ try {
271
+ env.KODE_HOME = `${home}/`;
272
+ await sessionIndexBackendKind(); // backend() sees the key mismatch: closes the stale handle, opens the store fresh
273
+ }
274
+ catch {
275
+ /* best-effort — a failed reopen is re-attempted on the next call */
276
+ }
277
+ finally {
278
+ if (prev === undefined)
279
+ delete env.KODE_HOME;
280
+ else
281
+ env.KODE_HOME = prev;
282
+ }
283
+ }
284
+ /** Best-effort space reclaim on the sqlite store after prune/rebuild; silently skipped on json. */
285
+ async function vacuumSqliteStore(dbFile) {
286
+ let db = null;
287
+ try {
288
+ db = await openSqliteDb(dbFile);
289
+ db.exec("VACUUM");
290
+ return true;
291
+ }
292
+ catch {
293
+ return false;
294
+ }
295
+ finally {
296
+ try {
297
+ db?.close();
298
+ }
299
+ catch {
300
+ /* best-effort */
301
+ }
302
+ }
303
+ }
304
+ function summaryOf(r) {
305
+ return {
306
+ schemaVersion: 1,
307
+ ranAtMs: r.ranAtMs,
308
+ ok: r.ok,
309
+ backend: r.backend,
310
+ issues: r.issues,
311
+ unresolved: r.unresolved,
312
+ actions: r.actions,
313
+ };
314
+ }
315
+ async function writeSummary(fs, summary) {
316
+ try {
317
+ const file = operatorPath("state", "maintenance.json");
318
+ fs.mkdirSync(operatorPath("state"), { recursive: true });
319
+ fs.writeFileSync(file, JSON.stringify(summary, null, 2));
320
+ }
321
+ catch {
322
+ /* heartbeat file is best-effort; the report itself is the return value */
323
+ }
324
+ }
325
+ function buildReport(ranAtMs, before, after, actions, quarantined, rebuilt) {
326
+ return {
327
+ ranAtMs,
328
+ backend: after.backend,
329
+ storeFile: after.storeFile,
330
+ ok: after.issues.length === 0,
331
+ issues: before.issues,
332
+ unresolved: after.issues,
333
+ actions,
334
+ orphans: before.orphans,
335
+ drifted: before.drifted,
336
+ quarantined,
337
+ rebuilt,
338
+ sessionsPresent: before.sessions.size,
339
+ indexedEntries: before.indexed.size,
340
+ };
341
+ }
342
+ /** Read-only audit of $KODE_HOME/state: what exists, whether it's readable, and how far the index
343
+ * has drifted from $KODE_HOME/sessions. Repairs nothing; never writes anything. */
344
+ export async function inspectState() {
345
+ const ranAtMs = Date.now();
346
+ const s = await scan();
347
+ return buildReport(ranAtMs, s, s, [], null, false);
348
+ }
349
+ /** Audit, then self-heal: quarantine damaged stores (renamed, never deleted — the content is
350
+ * fully re-derivable from the transcripts), drop stale sidecars, re-sync orphans/drift/new files
351
+ * through session-index, vacuum, re-audit, and record a heartbeat at state/maintenance.json.
352
+ * A store that is merely locked is reported, never touched. Idempotent — a clean run is a no-op
353
+ * apart from the heartbeat — so wiring it to cron / session start is safe. */
354
+ export async function maintainState() {
355
+ const ranAtMs = Date.now();
356
+ const before = await scan();
357
+ const f = await tryFs();
358
+ const actions = [];
359
+ if (!f || before.issues.length === 0) {
360
+ const report = buildReport(ranAtMs, before, before, [], null, false);
361
+ if (f)
362
+ await writeSummary(f.fs, summaryOf(report));
363
+ return report;
364
+ }
365
+ const { fs, path } = f;
366
+ let quarantined = null;
367
+ let rebuilt = false;
368
+ if (before.locked) {
369
+ // Concurrent writer — the healthiest this store can be. Report and bail out untouched.
370
+ }
371
+ else {
372
+ for (const sidecar of before.staleSidecarFiles) {
373
+ try {
374
+ fs.rmSync(sidecar, { force: true });
375
+ actions.push(`removed stale sidecar ${path.basename(sidecar)}`);
376
+ }
377
+ catch {
378
+ actions.push(`could not remove ${path.basename(sidecar)}`);
379
+ }
380
+ }
381
+ if (before.needsQuarantine && before.storeFile) {
382
+ const kept = `${before.storeFile}.corrupt-${ranAtMs}`;
383
+ try {
384
+ fs.renameSync(before.storeFile, kept);
385
+ quarantined = kept;
386
+ actions.push(`quarantined ${path.basename(before.storeFile)} as ${path.basename(kept)}`);
387
+ for (const suffix of SQLITE_SIDECARS) {
388
+ const sidecar = before.storeFile + suffix;
389
+ try {
390
+ if (fs.existsSync(sidecar)) {
391
+ fs.renameSync(sidecar, `${sidecar}.corrupt-${ranAtMs}`);
392
+ actions.push(`quarantined ${path.basename(sidecar)}`);
393
+ }
394
+ }
395
+ catch {
396
+ /* sidecar cleanup is best-effort; a fresh state.db reopens clean regardless */
397
+ }
398
+ }
399
+ }
400
+ catch (err) {
401
+ actions.push(`quarantine of ${path.basename(before.storeFile)} failed: ${errMsg(err)}`);
402
+ }
403
+ }
404
+ const needsResync = quarantined !== null || before.issues.some((i) => i.code !== "stale-sidecars");
405
+ if (needsResync) {
406
+ await invalidateSessionIndexCache();
407
+ try {
408
+ const res = await indexSessions();
409
+ rebuilt = true;
410
+ actions.push(`resynced state store from ${before.sessions.size} transcript(s) (indexed ${res.indexed}, skipped ${res.skipped})`);
411
+ }
412
+ catch (err) {
413
+ actions.push(`resync failed: ${errMsg(err)}`);
414
+ }
415
+ if (rebuilt && (await sessionIndexBackendKind()) === "sqlite" && before.storeFile?.endsWith("state.db") && (quarantined !== null || before.orphans.length > 0)) {
416
+ if (await vacuumSqliteStore(before.storeFile))
417
+ actions.push("compacted state store (VACUUM)");
418
+ }
419
+ }
420
+ }
421
+ const after = before.locked ? before : await scan();
422
+ const report = buildReport(ranAtMs, before, after, actions, quarantined, rebuilt);
423
+ await writeSummary(fs, summaryOf(report));
424
+ return report;
425
+ }
426
+ /** The last maintainState() summary, read back from state/maintenance.json — null before the
427
+ * first run or if the heartbeat is unreadable. Home surfaces / cron alerting read this. */
428
+ export async function stateMaintenanceStatus() {
429
+ const f = await tryFs();
430
+ if (!f)
431
+ return null;
432
+ try {
433
+ const parsed = JSON.parse(f.fs.readFileSync(operatorPath("state", "maintenance.json"), "utf8"));
434
+ if (!parsed || typeof parsed !== "object" || typeof parsed.ranAtMs !== "number")
435
+ return null;
436
+ return parsed;
437
+ }
438
+ catch {
439
+ return null;
440
+ }
441
+ }
@@ -6,10 +6,10 @@
6
6
  // poster to KODE_TELEMETRY_URL — one wire shape for mobile, the dashboard, and the audit log; this module
7
7
  // no longer POSTs its own ad-hoc shape to that URL (that would collide with the frozen stream).
8
8
  import { appendFile, mkdir } from "node:fs/promises";
9
- import { homedir } from "node:os";
10
- import { join, dirname } from "node:path";
9
+ import { dirname } from "node:path";
10
+ import { operatorPath } from "../config/home.js";
11
11
  import { randomUUID } from "node:crypto";
12
- const DEFAULT_FILE = process.env.KODE_TELEMETRY_FILE ?? join(homedir(), ".axe", "operator", "telemetry.jsonl");
12
+ const DEFAULT_FILE = process.env.KODE_TELEMETRY_FILE ?? operatorPath("telemetry.jsonl");
13
13
  export class Telemetry {
14
14
  enabled;
15
15
  file;
@@ -2,10 +2,13 @@
2
2
  // per tool call (telemetry/events.ts is the sink + wire shape); this keeps the argument-summarizing that
3
3
  // a "who did what" review needs while never leaking secrets or bloating the line. Pure + node-free, so it
4
4
  // is safe to import from any bundle (the CLI and the JSCore/browser engine alike).
5
+ import { redactSecrets } from "../engine/redact.js";
5
6
  /** Summarize args for the log without leaking secrets or bloating the line. Keeps the shape a reviewer
6
7
  * needs (which path, which command head) and drops values that could be sensitive. */
7
8
  export function digestArgs(_name, args) {
8
- const s = (v, n = 120) => (typeof v === "string" ? v : JSON.stringify(v ?? "")).slice(0, n);
9
+ // H4 (audit-tools §1): this digest feeds an events file/POST that claims secret-freeness — every
10
+ // sliced field now runs the known-token mask FIRST (curl -H "Authorization: Bearer …" digests masked).
11
+ const s = (v, n = 120) => redactSecrets(typeof v === "string" ? v : JSON.stringify(v ?? "")).slice(0, n);
9
12
  if (typeof args.command === "string")
10
13
  return `$ ${s(args.command)}`;
11
14
  if (Array.isArray(args.args))
@@ -1,5 +1,7 @@
1
1
  import { digestArgs } from "./audit.js";
2
2
  import { EventSink } from "../telemetry/events.js";
3
+ import { runBatch, defaultClassify, defaultKeys } from "../engine/batch-scheduler.js";
4
+ import { registrySafeTools } from "./tier.js";
3
5
  export { PermissionPolicy } from "./policy.js";
4
6
  const DENIED = (name) => `Permission denied: "${name}" was refused by the operator permission policy. ` +
5
7
  `Ask the user to approve it, or run in a mode that allows it.`;
@@ -57,17 +59,27 @@ export function withPermissions(inner, policy, opts = {}) {
57
59
  }
58
60
  return {
59
61
  execute: (name, args) => gate(name, args, () => inner.execute(name, args)),
60
- executeParallel: (calls, onSettle) =>
61
- // Gate each call individually (its own decision + event), preserving order. We can't hand a
62
- // pre-denied call to inner.executeParallel, so route per-call through execute (the executor's
63
- // own read-only/mutating parallelism still applies to the ones that reach it via execute).
64
- Promise.all(calls.map(async (c, i) => {
65
- const batch = c.batchId !== undefined
66
- ? { batchId: c.batchId, batchSize: c.batchSize ?? calls.length, batchIndex: c.batchIndex ?? i }
67
- : undefined;
68
- const r = await gate(c.name, c.args, () => inner.execute(c.name, c.args), batch);
69
- onSettle?.(i, r);
70
- return r;
71
- })),
62
+ // BTX: batch ordering is SCHEDULED, not Promise.raced. Each slot's run is the FULL gate chain
63
+ // (decision + approval + inner.execute), so per-call modal latency pipelines exactly as before —
64
+ // but conflicting resources serialize in input order through the shared DAG scheduler. The old
65
+ // Promise.all-over-execute() dropped the 0.1.225 walk at this layer: a gated batch of
66
+ // [write f, read f] raced, the read deterministically observing pre-write state on slow writes.
67
+ executeParallel: (calls, onSettle) => {
68
+ const safe = new Set(registrySafeTools());
69
+ return runBatch(calls, {
70
+ // prefer the INNER executor's classification truth (per-session toolset); fall back to the
71
+ // global registry's safe list only when inner exposes no sched (third-party executors).
72
+ classify: inner.sched ? inner.sched.classify : defaultClassify("", (n) => safe.has(n)),
73
+ keys: inner.sched ? (n, a) => inner.sched.keys(n, a) : defaultKeys,
74
+ runOne: (c) => {
75
+ const sc = c;
76
+ const batch = sc.batchId !== undefined
77
+ ? { batchId: sc.batchId, batchSize: sc.batchSize ?? calls.length, batchIndex: sc.batchIndex ?? calls.findIndex((x) => x.id === sc.id) }
78
+ : undefined;
79
+ return gate(sc.name, sc.args, () => inner.execute(sc.name, sc.args), batch);
80
+ },
81
+ onSettle,
82
+ });
83
+ },
72
84
  };
73
85
  }
@@ -3,10 +3,11 @@
3
3
  // everything with no prompt and no log — zero gates, zero overhead — so the owner's experience is
4
4
  // unchanged until they deliberately turn enforcement on. Enterprise deployments flip mode to "gated"
5
5
  // (mutating tools require approval) or tighten `rules`; "audit" allows-but-records (see audit.ts).
6
- import { tierAllows } from "./tier.js";
6
+ import { registrySafeTools, tierAllows } from "./tier.js";
7
7
  import { signatureLine } from "./signature.js";
8
- // Read-only tools (registry `safe: true`) — never gated unless a rule says otherwise.
9
- const DEFAULT_SAFE = ["file_read", "grep_search", "list_directory", "memory_search", "web_fetch"];
8
+ // Read-only tools (registry `safe: true`) — never gated unless a rule says otherwise. DERIVED from the
9
+ // registry, never hand-copied: the old 5-item copy drifted and gated/plan/dream/manual denied 12 safe tools.
10
+ const DEFAULT_SAFE = registrySafeTools();
10
11
  // Genuinely destructive shell shapes — in "gated" these escalate a would-be "allow" to "ask" even for
11
12
  // an allow-listed tool. Deliberately small + conservative (false positives just add one approval).
12
13
  const DANGEROUS = [
@@ -1,17 +1,34 @@
1
- // Enterprise seat: core coding + skills hub. An ALLOWLIST by design — anything not named here (fleet MCP
2
- // tools mcp__*, computer_* control, future privileged tools) is denied, so new tools are safe-by-default.
3
- const ENTERPRISE_ALLOW = new Set([
4
- "file_read", "file_write", "file_edit", "grep_search", "list_directory",
5
- "bash", "shell_exec", "shell_background", "bash_output", "bash_kill",
6
- "git_command", "checkpoint", "task_add", "task_list", "task_update",
7
- "memory_search", "memory_store", "web_fetch", "web_search",
8
- "skill_list", "skill_fetch", "skill_save",
9
- ]);
10
- // Readonly seat: inspection only (a superset-safe subset of the enterprise allowlist).
11
- const READONLY_ALLOW = new Set([
12
- "file_read", "grep_search", "list_directory", "bash_output", "task_list",
13
- "memory_search", "web_fetch", "web_search", "skill_list", "skill_fetch",
14
- ]);
1
+ import { registry } from "../tools/registry.js";
2
+ /** Every registry tool marked `safe: true` (read-only / parallel-safe). The ONE derivation shared by the
3
+ * gated-mode default allowlist (policy.ts) and both tier allowlists below, so a tool added to the registry
4
+ * as safe can never again be silently denied by a hand-copied list. The tier sets snapshot it once at module
5
+ * load; the computer tools cli.tsx registers later are never `safe`, so they stay outside every allowlist. */
6
+ export function registrySafeTools() {
7
+ return [...registry.values()].filter((t) => t.safe === true).map((t) => t.name);
8
+ }
9
+ const SAFE_TOOLS = registrySafeTools();
10
+ // Registry-safe tools a READONLY seat is still denied. They are read-only for the WORKSPACE but each WRITES
11
+ // state: scratchpad appends to a session file, session_handoff overwrites the handoff file that is auto-loaded
12
+ // into the NEXT session's prompt — a persistence channel an inspection-only seat must not have.
13
+ export const READONLY_SAFE_EXCLUDED = ["scratchpad", "session_handoff"];
14
+ // Enterprise seat: core coding + skills hub = EVERY registry-safe tool + this explicit mutating set. An
15
+ // ALLOWLIST by design — anything not safe and not named here (fleet MCP tools mcp__*, computer_* control,
16
+ // future privileged tools) is denied, so new mutating tools are safe-by-default. Deliberately NOT granted:
17
+ // http_request / file_upload (arbitrary outbound bodies / file egress), image_generate / video_generate /
18
+ // image_recreate (GPU spend), artifact_create (publishes a public URL). task_clear is granted — it only
19
+ // resets the session-local todo list, the same class as the already-granted task_add / task_update.
20
+ const ENTERPRISE_MUTATING = [
21
+ "file_write", "file_edit",
22
+ "bash", "shell_exec", "shell_background", "bash_kill",
23
+ "git_command", "checkpoint",
24
+ "task_add", "task_update", "task_clear",
25
+ "memory_store", "skill_save",
26
+ ];
27
+ const ENTERPRISE_ALLOW = new Set([...SAFE_TOOLS, ...ENTERPRISE_MUTATING]);
28
+ // Readonly seat: inspection only = the registry-safe tools minus READONLY_SAFE_EXCLUDED. Every member is
29
+ // registry `safe: true`, so no workspace-mutating tool can be in it — widening it means marking a tool safe
30
+ // in the registry, which test/permissions-parity.test.mts holds to account.
31
+ const READONLY_ALLOW = new Set(SAFE_TOOLS.filter((n) => !READONLY_SAFE_EXCLUDED.includes(n)));
15
32
  export const TIERS = ["admin", "enterprise", "readonly"];
16
33
  export function isTier(v) {
17
34
  return v === "admin" || v === "enterprise" || v === "readonly";
@@ -39,6 +39,7 @@ export class RemoteHost {
39
39
  activity = "idle";
40
40
  ctxPct = 0;
41
41
  route = "aurora";
42
+ tokens = null; // session cumulative tokens — mirrored to the followers' live token meter
42
43
  curAsstId = null; // per-turn assistant message id (stable across stream→final)
43
44
  liveTimer = null;
44
45
  livePending = null;
@@ -162,7 +163,7 @@ export class RemoteHost {
162
163
  this.flushLive();
163
164
  const { transcript, truncated, omittedBefore } = this.capTranscript(this.entries);
164
165
  this.send("snapshot", this.sessionId, {
165
- transcript, activity: this.activity, status: { ctxPct: this.ctxPct, route: this.route },
166
+ transcript, activity: this.activity, status: { ctxPct: this.ctxPct, route: this.route, ...(this.tokens != null ? { tokens: this.tokens } : {}) },
166
167
  ...(truncated ? { truncated: true, omittedBefore } : {}),
167
168
  ...(this.capabilities ? { capabilities: this.capabilities } : {}), // absent until the shell's first setCapabilities() call; already capped by capCapabilities() in setCapabilities()
168
169
  }, this.seq);
@@ -259,7 +260,13 @@ export class RemoteHost {
259
260
  toolStep(step) { this.state("tool_step", { step: this.pickTool(step) }); }
260
261
  pickTool(step) { this.upsertTool(step); return step; }
261
262
  setActivity(state, label) { this.activity = state; this.state("activity", { state, ...(label ? { label } : {}) }); }
262
- setStatus(ctxPct, route) { this.ctxPct = ctxPct; this.route = route; this.state("status", { ctxPct, route }); }
263
+ setStatus(ctxPct, route, tokens) {
264
+ this.ctxPct = ctxPct;
265
+ this.route = route;
266
+ if (tokens != null)
267
+ this.tokens = tokens;
268
+ this.state("status", { ctxPct, route, ...(this.tokens != null ? { tokens: this.tokens } : {}) });
269
+ }
263
270
  approvalRequest(id, tool, args) { this.state("approval_request", { id, tool, args }); }
264
271
  /** Mirrors an ask_user clarification to followers — a DISTINCT frame type from approval_request
265
272
  * (not folded into it), matching the web/mobile follower's contract. A local answer and a