@0perator/operator 0.1.235 → 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 (68) hide show
  1. package/README.md +2 -1
  2. package/dashboard/server.mjs +1 -1
  3. package/dist/acp/agent.js +290 -62
  4. package/dist/acp/auth.js +44 -0
  5. package/dist/acp/prompt.js +41 -0
  6. package/dist/acp/run.js +40 -15
  7. package/dist/acp/tool-map.js +48 -0
  8. package/dist/auth/byo.js +15 -8
  9. package/dist/auth/client.js +12 -6
  10. package/dist/auth/commands.js +39 -4
  11. package/dist/auth/identity.js +136 -0
  12. package/dist/auth/store.js +7 -5
  13. package/dist/autonomy/board.js +3 -2
  14. package/dist/autonomy/cron.js +332 -0
  15. package/dist/autonomy/delegate.js +168 -0
  16. package/dist/autonomy/media-robot.js +2 -3
  17. package/dist/autonomy/routines.js +5 -4
  18. package/dist/autonomy/session-factory.js +6 -1
  19. package/dist/browser/cdp.js +266 -0
  20. package/dist/browser/session.js +286 -0
  21. package/dist/cli.js +75 -11
  22. package/dist/config/brand.js +3 -3
  23. package/dist/config/home.js +70 -0
  24. package/dist/config/managed.js +230 -0
  25. package/dist/config/persona.js +59 -9
  26. package/dist/config/scaffold.js +142 -0
  27. package/dist/config/settings.js +38 -4
  28. package/dist/config/skills-index.js +175 -0
  29. package/dist/consolidation/scheduler.js +3 -3
  30. package/dist/consolidation/sleep.js +3 -3
  31. package/dist/engine/agent.js +80 -13
  32. package/dist/engine/aurora.js +6 -0
  33. package/dist/engine/batch-scheduler.js +128 -0
  34. package/dist/engine/json-repair.js +105 -0
  35. package/dist/engine/messages.js +50 -3
  36. package/dist/engine/rolling-summary.js +7 -5
  37. package/dist/enterprise/cli.js +137 -0
  38. package/dist/flywheel/processor.js +30 -2
  39. package/dist/flywheel/secret-gate.js +123 -0
  40. package/dist/mcp/index.js +18 -24
  41. package/dist/memory/index.js +0 -0
  42. package/dist/memory/session-index.js +324 -0
  43. package/dist/memory/session-rewind.js +92 -0
  44. package/dist/memory/state-maintenance.js +441 -0
  45. package/dist/observability/index.js +3 -3
  46. package/dist/permissions/index.js +24 -12
  47. package/dist/router/models.js +27 -8
  48. package/dist/selfimprove/index.js +9 -7
  49. package/dist/session.js +16 -6
  50. package/dist/skills/catalogue.js +167 -0
  51. package/dist/telemetry/audit-verify.js +94 -0
  52. package/dist/telemetry/events.js +86 -6
  53. package/dist/telemetry/lifecycle.js +18 -0
  54. package/dist/tools/deferred.js +117 -0
  55. package/dist/tools/executor.js +19 -20
  56. package/dist/tools/memory.js +117 -0
  57. package/dist/tools/registry.js +152 -21
  58. package/dist/tools/sandbox.js +63 -17
  59. package/dist/tools/searxng.js +2 -2
  60. package/dist/tools/tool-output-spill.js +2 -2
  61. package/dist/ui/Transcript.js +14 -2
  62. package/dist/ui/useInputHistory.js +3 -3
  63. package/dist/vault/cli.js +48 -0
  64. package/dist/vault/store.js +157 -0
  65. package/dist/vault/tool.js +50 -0
  66. package/package.json +3 -5
  67. package/CHANGELOG.md +0 -2487
  68. package/dist/ui/BusTray.js +0 -70
@@ -0,0 +1,123 @@
1
+ // HV3-N1 — FLYWHEEL SECRET GATE (novel). The training flywheel exports real transcripts: graded
2
+ // trajectories destined for SFT/LoRA. One leaked credential in that stream doesn't just disclose —
3
+ // it TEACHES the next adapter to emit secrets. The vault (0.1.239) proved secrets never enter model
4
+ // CONTEXT; this gate closes the other half of the loop: nothing secret-shaped leaves the HOME into
5
+ // TRAINING. Every trajectory record is screened before the processed stream; hits are quarantined
6
+ // (written to quarantine/, rename-not-delete doctrine, full original preserved for owner review),
7
+ // and findings never echo the matched value — only a redacted sample + rule name.
8
+ //
9
+ // Design notes:
10
+ // - Rule families: known provider key shapes, credential assignments, URL userinfo, private key
11
+ // blocks, JWTs, and a Shannon-entropy token rule for the unknown-unknowns.
12
+ // - False-positive discipline for trajectory text: bare git-sha hex (40/64), RFC1918 endpoints,
13
+ // model paths, and `data:`/base64 blobs that are not assignment-shaped are whitelisted — the
14
+ // benign corpus in tests must pass with ZERO findings or this gate will starve the flywheel.
15
+ // - Fail-closed by default (gate ON in processAll); opts.secretGate=false is the only way off.
16
+ const SHANNON = (s) => {
17
+ if (!s.length)
18
+ return 0;
19
+ const freq = new Map();
20
+ for (const ch of s)
21
+ freq.set(ch, (freq.get(ch) ?? 0) + 1);
22
+ let h = 0;
23
+ for (const n of freq.values()) {
24
+ const p = n / s.length;
25
+ h -= p * Math.log2(p);
26
+ }
27
+ return h;
28
+ };
29
+ // Provider-shaped keys: unmistakable prefixes.
30
+ const SHAPES = [
31
+ ["aws-access-key", /\bAKIA[0-9A-Z]{16}\b/g],
32
+ ["github-token", /\b(gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{40,})\b/g],
33
+ ["slack-token", /\bxox[abprs]-[A-Za-z0-9-]{20,}\b/g],
34
+ ["google-api-key", /\bAIza[0-9A-Za-z_-]{35}\b/g],
35
+ ["stripe-key", /\b[sp]k_(live|test)_[A-Za-z0-9]{20,}\b/g],
36
+ ["openai-key", /\bsk-(proj-)?[A-Za-z0-9_-]{32,}\b/g],
37
+ ["jwt", /\beyJ[A-Za-z0-9_-]{12,}\.[A-Za-z0-9_-]{12,}\.[A-Za-z0-9_-]{8,}\b/g],
38
+ ["private-key-block", /-----BEGIN (RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----(?!-)/g],
39
+ ["url-userinfo", /\b[a-z][a-z0-9+.-]*:\/\/[^/\s:@]{1,64}:[^/\s:@]{8,64}@\S/gi],
40
+ ];
41
+ // Assignment-shaped generic credentials: "password": "...", token=..., api_key "...".
42
+ // Separator class INCLUDES the backslash: the gate's primary input is JSON.stringify output, where
43
+ // every quote is escaped — password\":\"x — and an unescaped class silently misses the exact shape
44
+ // it exists to catch (regression pinned by the json-escaped planted case in tests).
45
+ const ASSIGN = /\b(?:password|passwd|pass|secret|api[-_]?key|apikey|access[-_]?token|refresh[-_]?token|auth[-_]?token|client[-_]?secret|credential)s?["'\s:=\\]{1,4}["']?([^\s"',;)\]}\\]{12,120})/gi;
46
+ // Bearer usage in headers: Authorization: Bearer <token>
47
+ const BEARER = /\bauthorization["'\s:=]{1,4}bearer\s+([A-Za-z0-9._-]{16,})/gi;
48
+ // High-entropy standalone tokens (unknown-unknowns): >=32 chars of base64ish alphabet, entropy >= 4.2.
49
+ const ENTROPY_TOKEN = /\b[A-Za-z0-9+/_-]{32,}={0,2}\b/g;
50
+ // Whitelists: things that look secret-shaped but are normal trajectory noise.
51
+ const BENIGN = [
52
+ /^0x[0-9a-f]{40,}$/i, // solidity-ish hex
53
+ /^[0-9a-f]{40}$|^[0-9a-f]{64}$/, // git object ids / sha digests
54
+ /^[A-Za-z0-9_-]{11}:[A-Za-z0-9_-]{37}$/, // YouTube ids appear base64ish
55
+ ];
56
+ // Contexts that demote ENTROPY/ASSIGN findings only (SHAPES are never context-whitelisted —
57
+ // a real AKIA sitting inside a localhost URL is still a real AKIA).
58
+ const BENIGN_CTX = [
59
+ /https?:\/\/(127\.0\.0\.1|localhost|(10|192\.168)\.\d+|172\.(1[6-9]|2\d|3[01])\.)\S*/i, // LAN/local endpoints (fleet hosts)
60
+ /[\w.-]+\.(gguf|safetensors|mlx|bin)\b/i, // model file names
61
+ /(^|[\s/"'])(models|adapters|checkpoints|LoRA)\b/i, // model directory vocabulary
62
+ /\b(commit|tree|blob)\s+[0-9a-f]{7,40}\b/i, // git object lines
63
+ ];
64
+ /** Entropy/assignment false-positive triage: benign token shape, or non-secret context window. */
65
+ function looksBenign(token, text, at) {
66
+ if (BENIGN.some((re) => re.test(token)))
67
+ return true;
68
+ const win = text.slice(Math.max(0, at - 64), at + token.length + 64);
69
+ if (ASSIGN_HARDCORE.test(win))
70
+ return false; // an explicit credential assignment is never context-demoted
71
+ return BENIGN_CTX.some((re) => re.test(win));
72
+ }
73
+ const ASSIGN_HARDCORE = /\b(password|passwd|secret|client[-_]?secret|api[-_]?key|apikey|access[-_]?token|auth[-_]?token)["'\s:=]/i;
74
+ const redact = (v) => `${v.slice(0, 8)}…[len ${v.length}]`;
75
+ /** Scan one text; findings are redacted samples + rule names. Exported for tests + tool surface. */
76
+ export function scanText(text) {
77
+ const out = [];
78
+ const seen = new Set();
79
+ const push = (rule, value, at) => {
80
+ const key = `${rule}@${at}`;
81
+ if (seen.has(key))
82
+ return;
83
+ seen.add(key);
84
+ out.push({ rule, sample: redact(value), at });
85
+ };
86
+ for (const [rule, re] of SHAPES) {
87
+ re.lastIndex = 0;
88
+ let m;
89
+ while ((m = re.exec(text))) {
90
+ if (!looksBenign(m[0], text, m.index))
91
+ push(rule, m[0], m.index);
92
+ }
93
+ }
94
+ for (const re of [ASSIGN, BEARER]) {
95
+ re.lastIndex = 0;
96
+ let m;
97
+ while ((m = re.exec(text))) {
98
+ const val = m[1] ?? m[0];
99
+ const isAssign = re === ASSIGN;
100
+ // Bearer headers are credentials by FORM; generic assignments report when the value is
101
+ // high-entropy OR hard-keyworded — "password was hunter2 horse" prose stays below both.
102
+ if (isAssign && SHANNON(val) < 2.6 && !ASSIGN_HARDCORE.test(m[0]))
103
+ continue;
104
+ if (!looksBenign(val, text, m.index))
105
+ push(isAssign ? "credential-assignment" : "bearer-header", val, m.index);
106
+ }
107
+ }
108
+ ENTROPY_TOKEN.lastIndex = 0;
109
+ let e;
110
+ while ((e = ENTROPY_TOKEN.exec(text))) {
111
+ const t = e[0].replace(/={2,}$/, "");
112
+ if (t.length < 32 || looksBenign(t, text, e.index))
113
+ continue;
114
+ if (SHANNON(t) >= 4.2)
115
+ push("high-entropy-token", t, e.index);
116
+ }
117
+ return out;
118
+ }
119
+ /** Screen a serialized trajectory record. */
120
+ export function screenRecord(serialized) {
121
+ const findings = scanText(serialized);
122
+ return { clean: findings.length === 0, findings };
123
+ }
package/dist/mcp/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { runBatch, defaultKeys } from "../engine/batch-scheduler.js";
1
2
  import { loadMcpConfig } from "./config.js";
2
3
  import { McpHttpClient } from "./client.js";
3
4
  import { McpStdioClient } from "./stdio.js";
@@ -129,30 +130,23 @@ export function withMcp(local, hub) {
129
130
  ready: () => hub?.discover() ?? Promise.resolve(),
130
131
  mcpSchemas: () => hub?.schemas() ?? [],
131
132
  execute: (name, args) => (hub?.has(name) ? hub.call(name, args) : local.execute(name, args)),
132
- executeParallel: async (calls, onSettle) => {
133
- // Route each call to its lane, preserving order. Local calls keep the executor's own
134
- // read-only/mutating parallelism; MCP calls run concurrently (they're remote & independent).
135
- // localIdxMap translates a local-lane sub-index back to its index in the ORIGINAL `calls` array,
136
- // so onSettle (if given) always reports against the index the caller knows about.
137
- const localIdxMap = [];
138
- const localCalls = [];
139
- calls.forEach((c, i) => { if (!hub?.has(c.name)) {
140
- localIdxMap.push(i);
141
- localCalls.push(c);
142
- } });
143
- const localResults = localCalls.length
144
- ? await local.executeParallel(localCalls, onSettle ? (li, r) => onSettle(localIdxMap[li], r) : undefined)
145
- : [];
146
- const localByIdx = new Map();
147
- localCalls.forEach((c, i) => localByIdx.set(c.id, localResults[i]));
148
- const mcpResults = await Promise.all(calls.map(async (c, i) => {
149
- if (!hub?.has(c.name))
150
- return localByIdx.get(c.id) ?? "";
151
- const r = await hub.call(c.name, c.args);
152
- onSettle?.(i, r);
153
- return r;
154
- }));
155
- return mcpResults;
133
+ // BTX: ONE scheduled batch across local AND hub lanes (the old split-then-Promise.all started
134
+ // hub calls alongside any local batch — cross-lane ordering was luck). Finding B (nova review):
135
+ // this layer now EXPOSES its own hub-aware sched so OUTER wrappers keep per-session truth
136
+ // through the full composition; finding C: hub tools serialize PER SERVER (mcp:<server> key)
137
+ // instead of a global barrier — same-server calls keep input order, independent servers overlap.
138
+ sched: {
139
+ classify: (n) => (hub?.has(n) ? "write" : local.sched ? local.sched.classify(n) : "write"),
140
+ keys: (n, a) => (hub?.has(n) ? ["mcp:" + n.split(":")[0]] : local.sched ? local.sched.keys(n, a) : defaultKeys(n, a)),
156
141
  },
142
+ executeParallel: (calls, onSettle) => runBatch(calls, {
143
+ classify: (n) => (hub?.has(n) ? "write" : local.sched ? local.sched.classify(n) : "write"),
144
+ keys: (n, a) => (hub?.has(n) ? ["mcp:" + n.split(":")[0]] : local.sched ? local.sched.keys(n, a) : defaultKeys(n, a)),
145
+ runOne: (c) => {
146
+ const sc = c;
147
+ return hub?.has(sc.name) ? hub.call(sc.name, sc.args) : local.execute(sc.name, sc.args);
148
+ },
149
+ onSettle,
150
+ }),
157
151
  };
158
152
  }
Binary file
@@ -0,0 +1,324 @@
1
+ // Session transcript index (operator-home-v2 §7): indexes the JSON transcripts under
2
+ // $KODE_HOME/sessions/ into a searchable store at $KODE_HOME/state/state.db (node:sqlite + FTS5),
3
+ // falling back to a JSON inverted index at $KODE_HOME/state/session-index.json when node:sqlite
4
+ // (or FTS5) is unavailable. Browser-safe: this module is reachable from the engine bundle through
5
+ // the tool registry, so node builtins load via the dynamic nodeImport pattern (same as
6
+ // src/tools/memory.ts) and every capability probe is wrapped in try/catch — index.browser.ts must
7
+ // stay node-free (esbuild --platform=neutral purity gate).
8
+ import { get_operator_home, operatorPath } from "../config/home.js";
9
+ const nodeImport = (m) => import(/* @vite-ignore */ m);
10
+ let _fs = null;
11
+ let _path = null;
12
+ async function fsp() {
13
+ if (!_fs)
14
+ _fs = (await nodeImport("node:fs"));
15
+ if (!_path)
16
+ _path = (await nodeImport("node:path"));
17
+ return { fs: _fs, path: _path };
18
+ }
19
+ const READ_CAP = 24_000; // readSession truncation cap (chars)
20
+ const SNIPPET_CHARS = 160; // ~160 chars of context around the first query-term match
21
+ const TRUNCATION_NOTE = "\n\n[... transcript truncated at 24000 chars ...]";
22
+ // ---------------------------------------------------------------------------
23
+ // Generic text extraction: recursively collect every string value from the
24
+ // transcript JSON and join with newlines. Tolerant of any shape (real files
25
+ // are arrays of {role, content, tool_calls?}, but we never assume).
26
+ // ---------------------------------------------------------------------------
27
+ function extractStrings(v, out = [], depth = 0) {
28
+ if (depth > 64)
29
+ return out; // runaway nesting guard
30
+ if (typeof v === "string") {
31
+ if (v)
32
+ out.push(v);
33
+ }
34
+ else if (Array.isArray(v))
35
+ for (const x of v)
36
+ extractStrings(x, out, depth + 1);
37
+ else if (v && typeof v === "object")
38
+ for (const x of Object.values(v))
39
+ extractStrings(x, out, depth + 1);
40
+ return out;
41
+ }
42
+ function transcriptText(json) {
43
+ return extractStrings(json).join("\n");
44
+ }
45
+ function tokenize(s) {
46
+ return s.toLowerCase().match(/[a-z0-9]+/g) ?? [];
47
+ }
48
+ /** ~SNIPPET_CHARS window around the first occurrence of any query term. */
49
+ function makeSnippet(body, query) {
50
+ const lower = body.toLowerCase();
51
+ let at = -1;
52
+ for (const term of tokenize(query)) {
53
+ const i = lower.indexOf(term);
54
+ if (i >= 0 && (at < 0 || i < at))
55
+ at = i;
56
+ }
57
+ const flat = body.replace(/\s+/g, " ").trim();
58
+ if (at < 0)
59
+ return flat.slice(0, SNIPPET_CHARS);
60
+ // Map the match position onto the whitespace-flattened string (approximate but stable).
61
+ const flatLower = flat.toLowerCase();
62
+ let pos = -1;
63
+ for (const term of tokenize(query)) {
64
+ const i = flatLower.indexOf(term);
65
+ if (i >= 0 && (pos < 0 || i < pos))
66
+ pos = i;
67
+ }
68
+ if (pos < 0)
69
+ pos = 0;
70
+ const start = Math.max(0, pos - Math.floor(SNIPPET_CHARS / 2));
71
+ const end = Math.min(flat.length, start + SNIPPET_CHARS);
72
+ return (start > 0 ? "…" : "") + flat.slice(start, end) + (end < flat.length ? "…" : "");
73
+ }
74
+ function capText(text) {
75
+ return text.length > READ_CAP ? text.slice(0, READ_CAP) + TRUNCATION_NOTE : text;
76
+ }
77
+ class SqliteBackend {
78
+ db;
79
+ kind = "sqlite";
80
+ constructor(db) {
81
+ this.db = db;
82
+ }
83
+ mtimes() {
84
+ const m = new Map();
85
+ for (const row of this.db.prepare("SELECT id, mtime FROM sessions_meta").all()) {
86
+ m.set(row.id, Number(row.mtime));
87
+ }
88
+ return m;
89
+ }
90
+ upsert(id, body, mtimeMs) {
91
+ this.db.prepare("DELETE FROM sessions_meta WHERE id = ?").run(id);
92
+ this.db.prepare("INSERT INTO sessions_meta (id, mtime) VALUES (?, ?)").run(id, mtimeMs);
93
+ this.db.prepare("DELETE FROM sessions_fts WHERE id = ?").run(id);
94
+ this.db.prepare("INSERT INTO sessions_fts (id, body) VALUES (?, ?)").run(id, body);
95
+ }
96
+ prune(keep) {
97
+ for (const row of this.db.prepare("SELECT id FROM sessions_meta").all()) {
98
+ if (!keep.has(row.id)) {
99
+ this.db.prepare("DELETE FROM sessions_meta WHERE id = ?").run(row.id);
100
+ this.db.prepare("DELETE FROM sessions_fts WHERE id = ?").run(row.id);
101
+ }
102
+ }
103
+ }
104
+ search(query, limit) {
105
+ const terms = tokenize(query);
106
+ if (!terms.length)
107
+ return [];
108
+ // Quote each term as an FTS5 string literal: user queries never parse as FTS syntax.
109
+ const match = terms.map((t) => `"${t.replace(/"/g, "")}"`).join(" ");
110
+ try {
111
+ const rows = this.db
112
+ .prepare("SELECT id, snippet(sessions_fts, 1, '', '', '…', 24) AS snip, bm25(sessions_fts) AS score FROM sessions_fts WHERE sessions_fts MATCH ? ORDER BY score LIMIT ?")
113
+ .all(match, limit);
114
+ return rows.map((r) => ({ id: r.id, snippet: String(r.snip).replace(/\s+/g, " ").trim(), score: Number(r.score) }));
115
+ }
116
+ catch {
117
+ return []; // malformed match expression or corrupt index — degrade to "no matches"
118
+ }
119
+ }
120
+ close() { try {
121
+ this.db.close();
122
+ }
123
+ catch { /* best-effort */ } }
124
+ }
125
+ class JsonBackend {
126
+ file;
127
+ fs;
128
+ kind = "json";
129
+ data = { version: 1, entries: {}, tokens: {} };
130
+ constructor(file, fs) {
131
+ this.file = file;
132
+ this.fs = fs;
133
+ try {
134
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
135
+ if (parsed && parsed.version === 1 && parsed.entries && parsed.tokens)
136
+ this.data = parsed;
137
+ }
138
+ catch { /* missing/corrupt — start fresh */ }
139
+ }
140
+ save() {
141
+ this.fs.writeFileSync(this.file, JSON.stringify(this.data));
142
+ }
143
+ reindexTokens(id) {
144
+ for (const [tok, ids] of Object.entries(this.data.tokens)) {
145
+ const next = ids.filter((x) => x !== id);
146
+ if (next.length)
147
+ this.data.tokens[tok] = next;
148
+ else
149
+ delete this.data.tokens[tok];
150
+ }
151
+ for (const tok of new Set(tokenize(this.data.entries[id]?.body ?? ""))) {
152
+ (this.data.tokens[tok] ??= []).push(id);
153
+ }
154
+ }
155
+ mtimes() {
156
+ return new Map(Object.entries(this.data.entries).map(([id, e]) => [id, e.mtimeMs]));
157
+ }
158
+ upsert(id, body, mtimeMs) {
159
+ this.data.entries[id] = { mtimeMs, body };
160
+ this.reindexTokens(id);
161
+ this.save();
162
+ }
163
+ prune(keep) {
164
+ let changed = false;
165
+ for (const id of Object.keys(this.data.entries)) {
166
+ if (!keep.has(id)) {
167
+ delete this.data.entries[id];
168
+ changed = true;
169
+ }
170
+ }
171
+ if (changed) {
172
+ for (const [tok, ids] of Object.entries(this.data.tokens)) {
173
+ const next = ids.filter((x) => keep.has(x));
174
+ if (next.length)
175
+ this.data.tokens[tok] = next;
176
+ else
177
+ delete this.data.tokens[tok];
178
+ }
179
+ this.save();
180
+ }
181
+ }
182
+ search(query, limit) {
183
+ const terms = tokenize(query);
184
+ if (!terms.length)
185
+ return [];
186
+ // Score = how many distinct query terms the session contains (AND-ish ranking by coverage).
187
+ const counts = new Map();
188
+ for (const t of new Set(terms)) {
189
+ for (const id of this.data.tokens[t] ?? [])
190
+ counts.set(id, (counts.get(id) ?? 0) + 1);
191
+ }
192
+ const uniq = new Set(terms).size;
193
+ return [...counts.entries()]
194
+ .filter(([, n]) => n === uniq) // every query term must appear (matches the sqlite AND semantics)
195
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
196
+ .slice(0, limit)
197
+ .map(([id, n]) => ({ id, snippet: makeSnippet(this.data.entries[id]?.body ?? "", query), score: n }));
198
+ }
199
+ close() { }
200
+ }
201
+ // ---------------------------------------------------------------------------
202
+ // Backend selection (capability-guarded) — cached per operator home so a
203
+ // KODE_HOME change (tests) transparently re-opens the right store.
204
+ // ---------------------------------------------------------------------------
205
+ let _backend = null;
206
+ let _backendHome = null;
207
+ async function openSqlite(fs) {
208
+ try {
209
+ const sqlite = await nodeImport("node:sqlite");
210
+ if (!sqlite?.DatabaseSync)
211
+ return null;
212
+ const dbPath = operatorPath("state", "state.db");
213
+ fs.mkdirSync(operatorPath("state"), { recursive: true });
214
+ const db = new sqlite.DatabaseSync(dbPath);
215
+ db.exec("CREATE TABLE IF NOT EXISTS sessions_meta (id TEXT PRIMARY KEY, mtime REAL NOT NULL)");
216
+ db.exec("CREATE VIRTUAL TABLE IF NOT EXISTS sessions_fts USING fts5(id UNINDEXED, body)");
217
+ return new SqliteBackend(db);
218
+ }
219
+ catch {
220
+ return null; // no node:sqlite, or FTS5 not compiled in — fall back
221
+ }
222
+ }
223
+ async function backend() {
224
+ const home = get_operator_home();
225
+ if (_backend && _backendHome === home)
226
+ return _backend;
227
+ if (_backend) {
228
+ _backend.close();
229
+ _backend = null;
230
+ }
231
+ const { fs } = await fsp();
232
+ _backend = (await openSqlite(fs)) ?? new JsonBackend(operatorPath("state", "session-index.json"), fs);
233
+ _backendHome = home;
234
+ return _backend;
235
+ }
236
+ async function listSessionFiles() {
237
+ const { fs, path } = await fsp();
238
+ const dir = operatorPath("sessions");
239
+ let names;
240
+ try {
241
+ names = fs.readdirSync(dir);
242
+ }
243
+ catch {
244
+ return [];
245
+ } // no sessions yet
246
+ const out = [];
247
+ for (const name of names.sort()) {
248
+ if (!name.endsWith(".json"))
249
+ continue;
250
+ const file = path.join(dir, name);
251
+ try {
252
+ const st = fs.statSync(file);
253
+ if (!st.isFile())
254
+ continue;
255
+ out.push({ id: name.slice(0, -".json".length), file, mtimeMs: st.mtimeMs });
256
+ }
257
+ catch { /* vanished mid-scan */ }
258
+ }
259
+ return out;
260
+ }
261
+ /** Index $KODE_HOME/sessions/*.json incrementally (unchanged files are skipped by mtime). */
262
+ export async function indexSessions() {
263
+ const { fs } = await fsp();
264
+ const be = await backend();
265
+ const files = await listSessionFiles();
266
+ const known = be.mtimes();
267
+ let indexed = 0;
268
+ let skipped = 0;
269
+ for (const f of files) {
270
+ if (known.get(f.id) === f.mtimeMs) {
271
+ skipped++;
272
+ continue;
273
+ }
274
+ let body = "";
275
+ try {
276
+ body = transcriptText(JSON.parse(fs.readFileSync(f.file, "utf8")));
277
+ }
278
+ catch {
279
+ try {
280
+ body = fs.readFileSync(f.file, "utf8");
281
+ }
282
+ catch {
283
+ skipped++;
284
+ continue;
285
+ } // unreadable — leave stale entry
286
+ }
287
+ be.upsert(f.id, body, f.mtimeMs);
288
+ indexed++;
289
+ }
290
+ be.prune(new Set(files.map((f) => f.id)));
291
+ return { indexed, skipped };
292
+ }
293
+ /** Full-text search over indexed transcripts (indexes nothing itself — call indexSessions first). */
294
+ export async function searchSessions(query, limit = 8) {
295
+ const be = await backend();
296
+ const n = Number.isFinite(limit) ? Math.max(1, Math.min(100, Math.floor(limit))) : 8;
297
+ return be.search(query, n);
298
+ }
299
+ /** Read one transcript as readable text (pretty JSON when parseable), capped at 24k chars. */
300
+ export async function readSession(id) {
301
+ if (!id || id.includes("/") || id.includes("\\") || id.includes(".."))
302
+ return null; // no path escapes
303
+ const { fs } = await fsp();
304
+ const file = operatorPath("sessions", `${id}.json`);
305
+ let raw;
306
+ try {
307
+ raw = fs.readFileSync(file, "utf8");
308
+ }
309
+ catch {
310
+ return null;
311
+ }
312
+ let text;
313
+ try {
314
+ text = JSON.stringify(JSON.parse(raw), null, 2);
315
+ }
316
+ catch {
317
+ text = raw;
318
+ } // not JSON — raw it is
319
+ return capText(text);
320
+ }
321
+ /** Which storage backend is active ("sqlite" or "json") — diagnostics/tests. */
322
+ export async function sessionIndexBackendKind() {
323
+ return (await backend()).kind;
324
+ }
@@ -0,0 +1,92 @@
1
+ // HV3-05b — session rewind, transcript half. Truncates a saved session transcript back to before
2
+ // the last N USER turns (that's the turn unit the owner counts in), keeping a rewind copy first —
3
+ // the same doctrine as state-maintenance: derived data may be rebuilt, but nothing is ever only
4
+ // deleted. File-state rewind is DELIBERATELY out of scope for v1: checkpoints are ordinary git
5
+ // commits in the owner's repo, and a tool silently reverting working-tree files is how owners lose
6
+ // work — the owner runs `git checkout` themselves. After truncation the session index drifts (by
7
+ // design) and the next maintainState()/indexSessions() resyncs it.
8
+ import { operatorPath } from "../config/home.js";
9
+ async function fsp() {
10
+ const g = globalThis;
11
+ try {
12
+ const m = g.process?.getBuiltinModule?.("node:fs");
13
+ if (m)
14
+ return m;
15
+ }
16
+ catch { /* dynamic */ }
17
+ const id = "node:fs"; // variable: esbuild must not statically resolve this (neutral-bundle purity)
18
+ return import(id);
19
+ }
20
+ const MAX_TURNS = 50;
21
+ /** Find user-turn boundary indices (turn = a `user` message and everything after it until the next). */
22
+ export function turnBoundaries(messages) {
23
+ const out = [];
24
+ messages.forEach((m, i) => { if (m?.role === "user")
25
+ out.push(i); });
26
+ return out;
27
+ }
28
+ /** Pure core: given a transcript array and turns-to-drop, return the kept prefix or a refusal reason.
29
+ * Exported for tests without fs. */
30
+ export function computeRewind(messages, turnsToDrop) {
31
+ if (!Array.isArray(messages))
32
+ return { error: "transcript is not a message array" };
33
+ const n = Math.floor(turnsToDrop);
34
+ if (!Number.isFinite(n) || n < 1 || n > MAX_TURNS)
35
+ return { error: `turns must be 1..${MAX_TURNS}` };
36
+ const bounds = turnBoundaries(messages);
37
+ if (bounds.length === 0)
38
+ return { error: "transcript has no user turns" };
39
+ if (n >= bounds.length)
40
+ return { error: `rewind of ${n} turn(s) would empty the transcript (${bounds.length} user turn(s) total) — refused` };
41
+ const cut = bounds[bounds.length - n];
42
+ return { keep: messages.slice(0, cut) };
43
+ }
44
+ /** Rewind a saved session by id: read, compute, rewind-copy, truncate-write. Returns a report line. */
45
+ export async function rewindSession(id, turns) {
46
+ const fs = await fsp();
47
+ const safe = id.replace(/[^A-Za-z0-9_-]/g, "");
48
+ if (!safe || safe !== id)
49
+ return "session_rewind: invalid id";
50
+ const file = operatorPath("sessions", `${safe}.json`);
51
+ let raw;
52
+ try {
53
+ raw = fs.readFileSync(file, "utf8");
54
+ }
55
+ catch {
56
+ return `session_rewind: no transcript '${safe}' (ids come from session_search)`;
57
+ }
58
+ let messages;
59
+ try {
60
+ messages = JSON.parse(raw);
61
+ }
62
+ catch {
63
+ return `session_rewind: transcript '${safe}' is corrupt — run state maintenance (session_search \`maintainState\`)`;
64
+ }
65
+ const res = computeRewind(messages, turns);
66
+ if ("error" in res)
67
+ return `session_rewind refused: ${res.error}`;
68
+ const stamp = Date.now();
69
+ const backup = `${file}.rewound-${stamp}`;
70
+ try {
71
+ fs.copyFileSync(file, backup);
72
+ }
73
+ catch (e) {
74
+ return `session_rewind: could not write rewind copy (${e.message}) — refusing to truncate`;
75
+ }
76
+ fs.writeFileSync(file, JSON.stringify(res.keep, null, 1), { mode: 0o600 });
77
+ const dropped = messages.length - res.keep.length;
78
+ return `rewound '${safe}': dropped ${turns} user turn(s) (${dropped} messages), kept ${res.keep.length}; full transcript saved at ${backup.split("/").pop()}; the session index will resync on next maintenance/startup`;
79
+ }
80
+ /** run() for the `session_rewind` tool. */
81
+ export async function runSessionRewind(args) {
82
+ const id = String(args.id ?? "").trim();
83
+ if (!id)
84
+ return "session_rewind: pass id (from session_search) + turns (default 1)";
85
+ const turns = Number(args.turns ?? 1);
86
+ try {
87
+ return await rewindSession(id, turns);
88
+ }
89
+ catch (e) {
90
+ return `session_rewind error: ${e.message}`;
91
+ }
92
+ }