@0perator/operator 0.1.235 → 0.1.262

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 +104 -17
  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,128 @@
1
+ // BTX — the shared batch-execution scheduler (mission spec: _ai-docs/features/2026-10-07-batch-exec-v2.md).
2
+ // ONE pure, node-free DAG executor that ToolExecutor, withPermissions and withMcp all delegate to, so
3
+ // batch ordering holds at EVERY layer of the composition (the race this kills: withPermissions used to
4
+ // Promise.all per-call execute(), bypassing the walk the 0.1.225 fix introduced).
5
+ //
6
+ // Semantics (superset of the old walk):
7
+ // • Results land in INPUT ORDER in slots; onSettle(index, result) fires the moment each call finishes.
8
+ // • Each call declares resource keys (path-ish args) or a device class. Two calls CONFLICT when a
9
+ // key equals or is a path prefix of the other (dir vs child), when either is a device barrier, or
10
+ // both are unknown-name writes with no keys (conservative: no keys + mutating = device-class).
11
+ // • READS (pure ops) run alongside anything that cannot change what they observe: they wait only for
12
+ // prior WRITES on conflicting keys. WRITES wait for everything conflicting (read-after-write is a
13
+ // read's concern; write-after-write and write-after-read are this write's concern) — serialized
14
+ // per-resource in INPUT ORDER via the resource's tail promise.
15
+ // • Barrier tools (bash/shell_exec/git_command/checkpoint/computer_*/browser*/browser_vault/…) can
16
+ // touch ANYTHING and share one persistent shell — they run alone, in input order.
17
+ // • A rejected/denied run resolves as a string (executor contract: resolve-not-reject); one call's
18
+ // failure never strands its dependents — the chain advances regardless.
19
+ // Pure JS: no node builtins, no asyncLocalStorage — safe for the neutral engine bundle (run-jsc).
20
+ const BARRIER_EXACT = new Set([
21
+ "bash", "shell_exec", "shell_background", "bash_kill",
22
+ "git_command", "checkpoint", "tool_call",
23
+ "delegate_task", // a whole sub-agent session with the full tool set: it can touch anything, so it runs alone like bash
24
+ "app_open", "app_activate", "computer_applescript", "computer_type", "computer_key", "computer_click", "computer_screenshot",
25
+ ]);
26
+ const BARRIER_PREFIX = ["computer_", "browser", "shell", "mcp__"]; // browser_vault included: it drives the same browser device
27
+ export function defaultClassify(name, isSafe) {
28
+ return (n) => {
29
+ if (BARRIER_EXACT.has(n))
30
+ return "barrier";
31
+ for (const p of BARRIER_PREFIX)
32
+ if (n.startsWith(p) || n.includes("__" + p))
33
+ return "barrier";
34
+ return isSafe(n) ? "read" : "write";
35
+ };
36
+ }
37
+ /** Path-ish arg keys: any string value under a path-named arg, normalized to a comparable key.
38
+ * A MUTATING call with no path keys gets a per-name lock — injected by runBatch (which knows the
39
+ * class), never here: reads must not acquire locks or they could never pair with their writes. */
40
+ export function defaultKeys(_name, args) {
41
+ const out = [];
42
+ for (const [k, v] of Object.entries(args ?? {})) {
43
+ if (typeof v === "string" && v && /path|dir|file|cwd|target|token|handle/i.test(k))
44
+ out.push(normKey(v));
45
+ }
46
+ return out;
47
+ }
48
+ function normKey(p) {
49
+ const t = p.replace(/\\/g, "/").replace(/\/{2,}/g, "/");
50
+ const trimmed = t.replace(/\/+$/, "");
51
+ return trimmed || "/";
52
+ }
53
+ function conflicts(a, b) {
54
+ if (a === b)
55
+ return true;
56
+ if (a.startsWith("lock:") || b.startsWith("lock:"))
57
+ return a === b;
58
+ return a.startsWith(b + "/") || b.startsWith(a + "/");
59
+ }
60
+ /** Schedule a whole batch; resolves when every slot has its result (input order). */
61
+ export function runBatch(calls, opts) {
62
+ const results = new Array(calls.length);
63
+ const done = [];
64
+ const writeTails = new Map(); // resource key -> last WRITE on it
65
+ const inflight = new Set(); // everything not yet settled (barrier gate)
66
+ let afterBarrier = Promise.resolve(); // every op must clear the last barrier
67
+ for (let i = 0; i < calls.length; i++) {
68
+ const c = calls[i];
69
+ const kind = opts.classify(c.name);
70
+ let keys = kind === "barrier" ? [] : opts.keys(c.name, c.args);
71
+ // no-path MUTATIONS (memory_store, task_add, cron create…): serialize per tool-name lock.
72
+ // Reads never take the lock — a path-less read pairs with nothing and is safe to overlap.
73
+ if (kind === "write" && keys.length === 0)
74
+ keys = ["lock:" + c.name];
75
+ const gate = [];
76
+ if (kind === "barrier") {
77
+ gate.push(afterBarrier);
78
+ for (const p of inflight)
79
+ gate.push(p); // a barrier runs ALONE: waits for everything prior
80
+ }
81
+ else if (kind === "read") {
82
+ gate.push(afterBarrier); // barriers can change anything a read observes
83
+ if (!keys.length) {
84
+ for (const t2 of writeTails.values())
85
+ gate.push(t2); // path-less read: any prior write may target it
86
+ }
87
+ for (const k of keys) {
88
+ // A read waits only for PRIOR WRITES on overlapping resources. Prior READS never matter
89
+ // (nothing to serialize), and a write after a read must NOT wait for the read: the model
90
+ // consumes results next turn; any pre/post read value is a valid serialization.
91
+ for (const [wk, wt] of writeTails)
92
+ if (conflicts(k, wk))
93
+ gate.push(wt);
94
+ }
95
+ }
96
+ else {
97
+ gate.push(afterBarrier);
98
+ for (const k of keys) {
99
+ for (const [wk, wt] of writeTails)
100
+ if (conflicts(k, wk))
101
+ gate.push(wt);
102
+ }
103
+ }
104
+ const run = Promise.all(gate).then(async () => {
105
+ let r;
106
+ try {
107
+ r = await opts.runOne(c);
108
+ }
109
+ catch (e) {
110
+ r = `error running ${c.name}: ${e?.message ?? String(e)}`;
111
+ }
112
+ results[i] = r;
113
+ try {
114
+ opts.onSettle?.(i, r);
115
+ }
116
+ catch { /* UI never breaks execution */ }
117
+ });
118
+ if (kind === "barrier")
119
+ afterBarrier = run; // everything later waits behind this barrier
120
+ else if (kind === "write")
121
+ for (const k of keys)
122
+ writeTails.set(k, run);
123
+ inflight.add(run);
124
+ run.then(() => inflight.delete(run));
125
+ done.push(run);
126
+ }
127
+ return Promise.all(done).then(() => results);
128
+ }
@@ -0,0 +1,105 @@
1
+ // json-repair — one-shot, conservative argument-JSON repair for model-emitted tool calls.
2
+ // WHY: models frequently emit tool-call arguments with RAW newlines/tabs inside string values
3
+ // (multi-line bash/python -c scripts — the escape gets emitted as the literal control char, which
4
+ // strict JSON.parse rejects as "Bad control character"), or get CUT mid-string at the output token
5
+ // limit ("Unterminated string"). Both failure modes showed live (Spectre autonomous review turn,
6
+ // 2026-10-07): the generic error left the model guessing, and it burned 69 tool calls hunting a
7
+ // phantom "btx binary" instead of shortening its command. Fix: repair what is SAFE to repair
8
+ // (control chars — the command semantics survive), never guess at what is not (a truncated
9
+ // argument is a HALF-WRITTEN COMMAND; executing a repaired-by-closing-brace version could run
10
+ // something the model never finished deciding). For truncation we return guidance the model can
11
+ // actually act on. Pure JS: no node builtins — loaded inside the engine bundle.
12
+ /** Escape raw control chars that appear INSIDE string literals. Outside-string whitespace is
13
+ * legitimate JSON whitespace and untouched. Backslash state is honored, so an existing
14
+ * sequence like \\" or a proper \\n escape passes through unchanged. */
15
+ export function escapeControlChars(raw) {
16
+ let out = "";
17
+ let inStr = false;
18
+ let esc = false;
19
+ for (const ch of raw) {
20
+ if (!inStr) {
21
+ if (ch === '"')
22
+ inStr = true;
23
+ out += ch;
24
+ continue;
25
+ }
26
+ if (esc) {
27
+ out += ch;
28
+ esc = false;
29
+ continue;
30
+ }
31
+ if (ch === "\\") {
32
+ out += ch;
33
+ esc = true;
34
+ continue;
35
+ }
36
+ switch (ch) {
37
+ case "\n":
38
+ out += "\\n";
39
+ break;
40
+ case "\r":
41
+ out += "\\r";
42
+ break;
43
+ case "\t":
44
+ out += "\\t";
45
+ break;
46
+ default:
47
+ out += ch.codePointAt(0) < 0x20 ? "\\u" + ch.codePointAt(0).toString(16).padStart(4, "0") : ch;
48
+ }
49
+ }
50
+ return out;
51
+ }
52
+ /** Does the JSON look CUT OFF (truncation) rather than merely malformed? Signals: ends inside an
53
+ * unterminated string, ends mid-escape, ends on an open structure with missing closers. */
54
+ export function looksTruncated(raw) {
55
+ let inStr = false;
56
+ let esc = false;
57
+ const stack = [];
58
+ for (const ch of raw) {
59
+ if (!inStr && (ch === "{" || ch === "["))
60
+ stack.push(ch);
61
+ else if (!inStr && (ch === "}" || ch === "]"))
62
+ stack.pop();
63
+ else if (inStr && esc)
64
+ esc = false;
65
+ else if (inStr && ch === "\\")
66
+ esc = true;
67
+ else if (ch === '"')
68
+ inStr = !inStr;
69
+ }
70
+ return inStr || esc || stack.length > 0;
71
+ }
72
+ /** Parse model-emitted tool-call arguments with one conservative repair pass. Empty/whitespace =
73
+ * {} (zero-arg tools emit "" constantly — already tolerated upstream, kept identical). */
74
+ export function parseToolArgs(raw) {
75
+ if (!raw || raw.trim() === "")
76
+ return { ok: true, args: {}, repaired: false };
77
+ let lastErr = "";
78
+ try {
79
+ const v = JSON.parse(raw);
80
+ if (v && typeof v === "object" && !Array.isArray(v))
81
+ return { ok: true, args: v, repaired: false };
82
+ lastErr = "arguments did not parse to an object";
83
+ }
84
+ catch (e) {
85
+ lastErr = e instanceof Error ? e.message : String(e);
86
+ }
87
+ // repair pass (control chars inside strings)
88
+ const fixed = escapeControlChars(raw);
89
+ if (fixed !== raw) {
90
+ try {
91
+ const v = JSON.parse(fixed);
92
+ if (v && typeof v === "object" && !Array.isArray(v))
93
+ return { ok: true, args: v, repaired: true };
94
+ lastErr = "repaired arguments did not parse to an object";
95
+ }
96
+ catch (e) {
97
+ lastErr = e instanceof Error ? e.message : String(e);
98
+ }
99
+ }
100
+ const truncated = looksTruncated(raw);
101
+ const guidance = truncated
102
+ ? "the arguments were CUT OFF mid-generation (output token limit hit inside the JSON). Do NOT retry the same giant call: for long or multi-line scripts, file_write the script first, then bash a short command that runs the file; or split into several smaller calls. Keep arguments under ~4KB."
103
+ : `malformed JSON in arguments (${lastErr}). Re-emit valid JSON: escape quotes/newlines inside strings, close all braces.`;
104
+ return { ok: false, truncated, error: guidance };
105
+ }
@@ -46,12 +46,56 @@ function repairToolPairs(messages) {
46
46
  }
47
47
  return out;
48
48
  }
49
- /** Prepends the system prompt (if any), repairs interrupted tool pairs, and validates the result. */
49
+ /** Are these tool-call arguments safe to send? llama.cpp re-parses EVERY historical tool_call's `arguments`
50
+ * on EVERY request and 500s the WHOLE request if any one is invalid JSON — so a single truncated/malformed
51
+ * tool call persisted into history poisons the session PERMANENTLY: every later request fails before
52
+ * generating a token, and `--resume` reloads the poison (verified 2026-10-08: a 1,494-char unterminated
53
+ * bash `arguments` wedged a live session, server log "missing closing quote, column 1495"). Empty args are
54
+ * fine (the no-arg call); a non-empty string that won't `JSON.parse` is the hazard. */
55
+ function isParseableArgs(s) {
56
+ if (!s || !s.trim())
57
+ return true;
58
+ try {
59
+ JSON.parse(s);
60
+ return true;
61
+ }
62
+ catch {
63
+ return false;
64
+ }
65
+ }
66
+ /** Neutralize ONE tool call whose arguments are unparseable → `{}` (valid JSON). The model still sees the
67
+ * tool's result (the engine records the parse-error as that call's result), so it retries; only the STORED
68
+ * arguments are made safe so they can never wedge the conversation on a re-parse. Returns the input untouched
69
+ * when already valid (so callers can cheaply detect "no change"). */
70
+ export function sanitizeToolCall(tc) {
71
+ if (isParseableArgs(tc.function?.arguments ?? ""))
72
+ return tc;
73
+ return { ...tc, function: { ...tc.function, arguments: "{}" } };
74
+ }
75
+ /** Sweep a message list, replacing any unparseable assistant tool_call `arguments` with `{}`. Idempotent;
76
+ * returns the same array reference when nothing changed. This is the guarantee that no poisoned history — a
77
+ * fresh truncation OR a loaded poisoned session file — ever reaches the model server. */
78
+ export function sanitizeToolCallArgs(messages) {
79
+ let changed = false;
80
+ const out = messages.map((m) => {
81
+ if (m.role !== "assistant" || !m.tool_calls?.length)
82
+ return m;
83
+ const tool_calls = m.tool_calls.map(sanitizeToolCall);
84
+ if (tool_calls.some((tc, i) => tc !== m.tool_calls[i])) {
85
+ changed = true;
86
+ return { ...m, tool_calls };
87
+ }
88
+ return m;
89
+ });
90
+ return changed ? out : messages;
91
+ }
92
+ /** Prepends the system prompt (if any), repairs interrupted tool pairs, neutralizes any unparseable tool-call
93
+ * arguments (so a poisoned history never 500s the server), and validates the result. */
50
94
  export function buildMessages(systemPrompt, conversation) {
51
95
  const withSystem = systemPrompt
52
96
  ? [{ role: "system", content: systemPrompt }, ...conversation]
53
97
  : [...conversation];
54
- const messages = repairToolPairs(withSystem);
98
+ const messages = sanitizeToolCallArgs(repairToolPairs(withSystem));
55
99
  assertValidMessages(messages);
56
100
  return messages;
57
101
  }
@@ -66,10 +110,13 @@ export class Conversation {
66
110
  this.messages.push({ role: "user", content });
67
111
  }
68
112
  assistant(content, toolCalls) {
113
+ // Neutralize unparseable arguments at the point they enter history, so the SAVED session file never carries
114
+ // a poisoned call (buildMessages re-sanitizes outgoing requests too — belt and braces).
115
+ const clean = toolCalls && toolCalls.length ? toolCalls.map(sanitizeToolCall) : undefined;
69
116
  this.messages.push({
70
117
  role: "assistant",
71
118
  content,
72
- ...(toolCalls && toolCalls.length ? { tool_calls: toolCalls } : {}),
119
+ ...(clean && clean.length ? { tool_calls: clean } : {}),
73
120
  });
74
121
  }
75
122
  tool(toolCallId, content) {
@@ -6,9 +6,9 @@
6
6
  //
7
7
  // Also pre-builds the living-memory block for Pillar B's journal index.
8
8
  import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
9
- import { join } from "node:path";
10
- import { homedir } from "node:os";
11
- const SESSION_MEMORY_DIR = `${homedir()}/.axe/operator/session-memory`;
9
+ import { join, dirname } from "node:path";
10
+ import { operatorPath } from "../config/home.js";
11
+ const SESSION_MEMORY_DIR = operatorPath("session-memory");
12
12
  const SUMMARY_FILE = join(SESSION_MEMORY_DIR, "summary.md");
13
13
  const DEFAULTS = {
14
14
  minTokensSinceUpdate: 5000,
@@ -86,8 +86,10 @@ export class RollingSummarizer {
86
86
  /** Whether to persist the summary to disk. */
87
87
  writeSummary() {
88
88
  try {
89
- mkdirSync(SESSION_MEMORY_DIR, { recursive: true });
90
- writeFileSync(this.path, this.summaryCache, "utf8");
89
+ // dirname(this.path), not the global dir: a per-session path (ACP, bots, delegate) lives elsewhere and the write
90
+ // used to fail silently there. The summary is a digest of the conversation, so owner-only.
91
+ mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 });
92
+ writeFileSync(this.path, this.summaryCache, { encoding: "utf8", mode: 0o600 });
91
93
  }
92
94
  catch { /* best-effort — summary persistence never blocks a turn */ }
93
95
  }
@@ -0,0 +1,137 @@
1
+ // `operator audit …` and `operator doctor` — the enterprise review surface. A security reviewer's two
2
+ // questions are "is the audit trail intact?" and "what is actually in force on this seat?"; both are answered
3
+ // here from the same code paths the engine runs (no parallel re-implementation to drift).
4
+ // operator audit verify [--file <path>] [--json] verify the hash-chained trail (rotated files + active); exit 2 on a break
5
+ // operator audit tail [n] the last n events, human-readable
6
+ // operator doctor [--json] [--strict] policy / seat / sandbox / home / audit / credential posture
7
+ import { existsSync, readFileSync, statSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { auditHome } from "../config/scaffold.js";
10
+ import { get_operator_home } from "../config/home.js";
11
+ import { auditFilesFor, verifyAuditFiles } from "../telemetry/audit-verify.js";
12
+ import { defaultEventsFile } from "../telemetry/events.js";
13
+ import { loadCredentials } from "../auth/store.js";
14
+ import { PermissionPolicy } from "../permissions/index.js";
15
+ const activeFile = (flag) => {
16
+ const raw = flag ?? defaultEventsFile();
17
+ return raw.startsWith("~/") ? join(process.env.HOME ?? "", raw.slice(2)) : raw;
18
+ };
19
+ const flagVal = (a, f) => { const i = a.indexOf(f); return i >= 0 ? a[i + 1] : undefined; };
20
+ function auditVerify(args, out) {
21
+ const active = activeFile(flagVal(args, "--file"));
22
+ const files = auditFilesFor(active);
23
+ if (!files.length) {
24
+ out(`no audit log at ${active} yet — the trail is written once a seat is audited (a narrowed tier, audit/gated mode, or a managed policy)`);
25
+ return 0;
26
+ }
27
+ const rep = verifyAuditFiles(files);
28
+ if (args.includes("--json")) {
29
+ out(JSON.stringify(rep, null, 2));
30
+ return rep.ok ? 0 : 2;
31
+ }
32
+ out(`audit trail: ${rep.files.length} file(s), ${rep.events} event(s) — ${rep.chained} chained across ${rep.chains} chain(s), ${rep.unchained} unchained`);
33
+ if (rep.midstream.length)
34
+ out(` note: ${rep.midstream.length} chain(s) begin mid-stream (earlier rotations were pruned); verified from their first retained line`);
35
+ if (rep.unchained)
36
+ out(` note: ${rep.unchained} line(s) carry no chain fields (pre-chain history or dashboard-ingested events) — not verifiable, not a break`);
37
+ for (const b of rep.breaks.slice(0, 20))
38
+ out(` BREAK ${b.file}:${b.line} chain ${b.cid} ${b.reason}`);
39
+ if (rep.breaks.length > 20)
40
+ out(` … and ${rep.breaks.length - 20} more`);
41
+ out(rep.ok ? "OK — no edited, missing or reordered lines within any chain (tail truncation is not detectable; keep the remote copy)" : `FAILED — ${rep.breaks.length} break(s)`);
42
+ return rep.ok ? 0 : 2;
43
+ }
44
+ function auditTail(args, out) {
45
+ const n = Math.max(1, Math.min(500, Number(args.find((a) => /^\d+$/.test(a))) || 20));
46
+ const file = activeFile(flagVal(args, "--file"));
47
+ let lines = [];
48
+ try {
49
+ lines = readFileSync(file, "utf8").split("\n").filter(Boolean);
50
+ }
51
+ catch {
52
+ out(`no audit log at ${file} yet`);
53
+ return 0;
54
+ }
55
+ for (const l of lines.slice(-n)) {
56
+ let e;
57
+ try {
58
+ e = JSON.parse(l);
59
+ }
60
+ catch {
61
+ out(` (unparseable line)`);
62
+ continue;
63
+ }
64
+ const who = `${e.actor?.sub ?? "local"}@${e.actor?.tier}/${e.actor?.surface}`;
65
+ const what = e.kind === "tool" ? `${e.tool?.name} [${e.tool?.decision}/${e.tool?.outcome}] ${e.tool?.args ?? ""}` : e.kind === "control" ? `${e.control?.event} ${e.control?.detail ?? ""}` : e.kind === "turn" ? `turn ${e.turn?.tokens} tok ${e.turn?.route}` : `${e.service?.name} ${e.service?.state}`;
66
+ out(`${e.ts.slice(11, 19)} ${who.padEnd(28)} ${e.session.slice(0, 14).padEnd(14)} ${what}`.trimEnd());
67
+ }
68
+ return 0;
69
+ }
70
+ export async function collectChecks(settings, ctx) {
71
+ const rows = [];
72
+ const add = (id, status, message) => rows.push({ id, status, message });
73
+ const tier = settings.permissions.tier ?? "admin";
74
+ const audited = new PermissionPolicy(settings.permissions).audits;
75
+ add("version", "info", `operator ${ctx.version} · node ${process.versions.node}`);
76
+ const home = get_operator_home();
77
+ const findings = auditHome(home);
78
+ const warns = findings.filter((f) => f.severity === "warn");
79
+ add("home", warns.length ? "warn" : existsSync(join(home, "home.json")) ? "ok" : "warn", `${home}${existsSync(join(home, "home.json")) ? " (scaffolded)" : " — not scaffolded yet"}${ctx.scaffold?.tightened.length ? "; permissions tightened this run" : ""}`);
80
+ for (const f of findings)
81
+ add("home", f.severity, `${f.path}: ${f.message}`);
82
+ const m = settings.managed;
83
+ if (!m || m.status === "none")
84
+ add("policy", tier === "admin" ? "info" : "warn", "no managed policy — user settings and env are authoritative, so this seat can change its own tier/mode/sandbox (deploy managed-settings.json to enforce them)");
85
+ else if (m.status === "ok")
86
+ add("policy", "ok", `managed policy ${m.id} from ${m.path}`);
87
+ else
88
+ add("policy", "fail", `managed policy at ${m.path} is NOT usable — running locked down: ${m.errors.join("; ")}`);
89
+ const seat = settings.seat;
90
+ add("seat", seat?.source === "lockdown" ? "warn" : "ok", `tier=${tier} source=${seat?.source ?? "local-owner"}${seat?.sub ? ` sub=${seat.sub}` : ""}${seat?.reasons?.length ? ` (${seat.reasons.join("; ")})` : ""}`);
91
+ add("permissions", settings.permissions.mode === "bypass" && tier === "admin" ? "info" : "ok", `mode=${settings.permissions.mode} tier=${tier} rules=${Object.keys(settings.permissions.rules ?? {}).length}`);
92
+ const narrowed = tier !== "admin" || m?.status === "ok";
93
+ add("sandbox", settings.sandbox.mode === "off" && narrowed ? "warn" : "ok", `mode=${settings.sandbox.mode}${settings.sandbox.mode === "off" && narrowed ? " — the agent can write outside the workspace; with the sandbox on it also cannot touch its own settings/credentials/audit log" : ""}`);
94
+ add("computer", settings.computer.enabled ? "warn" : "ok", settings.computer.enabled ? "computer control ENABLED" : "computer control off");
95
+ add("mcp", "info", settings.mcp ? "fleet MCP tools enabled" : "fleet MCP off");
96
+ add("flywheel", settings.selfImprove.flywheel && narrowed ? "warn" : "info", settings.selfImprove.flywheel ? "training-flywheel capture ON (prompts + answers, secret-masked, 0600)" : "training-flywheel capture off");
97
+ const active = activeFile();
98
+ const files = auditFilesFor(active);
99
+ if (!files.length)
100
+ add("audit", audited ? "info" : "info", `no audit log yet at ${active}${audited ? "" : " (this seat is not audited: bypass + admin, no rules)"}`);
101
+ else {
102
+ const rep = verifyAuditFiles(files);
103
+ const size = existsSync(active) ? statSync(active).size : 0;
104
+ add("audit", rep.ok ? "ok" : "fail", `${active} (${(size / 1024).toFixed(0)} KiB, ${files.length} file(s), ${rep.events} events): ${rep.ok ? "hash chain intact" : `${rep.breaks.length} chain break(s) — run \`operator audit verify\``}`);
105
+ }
106
+ if (audited && !process.env.KODE_TELEMETRY_URL)
107
+ add("audit", "info", "no remote audit sink configured: the local chain detects edits, but an append-only remote/SIEM copy is what makes the trail non-repudiable");
108
+ const creds = await loadCredentials().catch(() => null);
109
+ add("credentials", "info", process.env.KODE_OPERATOR_TOKEN ? "operator token supplied through the environment" : creds ? `signed in as ${creds.user ?? "?"}` : "not signed in");
110
+ add("acp", "info", "`operator acp`: permission requests are bridged to the editor (fail-closed); SDK @zed-industries/agent-client-protocol is deprecated → @agentclientprotocol/sdk (migration pending)");
111
+ return rows;
112
+ }
113
+ async function doctor(settings, args, ctx, out) {
114
+ const rows = await collectChecks(settings, ctx);
115
+ if (args.includes("--json"))
116
+ out(JSON.stringify(rows, null, 2));
117
+ else {
118
+ out(`Operator doctor`);
119
+ for (const r of rows)
120
+ out(` [${r.status.padEnd(4)}] ${r.id.padEnd(12)} ${r.message}`);
121
+ const f = rows.filter((r) => r.status === "fail").length, w = rows.filter((r) => r.status === "warn").length;
122
+ out(f ? `${f} failing, ${w} warning(s)` : w ? `no failures, ${w} warning(s)` : "all checks passed");
123
+ }
124
+ const bad = rows.some((r) => r.status === "fail") || (args.includes("--strict") && rows.some((r) => r.status === "warn"));
125
+ return bad ? 1 : 0;
126
+ }
127
+ export async function runEnterpriseCli(argv, settings, ctx, out = (l) => process.stdout.write(l + "\n")) {
128
+ const [cmd, sub, ...rest] = argv;
129
+ if (cmd === "doctor")
130
+ return doctor(settings, [sub, ...rest].filter((x) => !!x), ctx, out);
131
+ if (cmd === "audit" && sub === "verify")
132
+ return auditVerify(rest, out);
133
+ if (cmd === "audit" && sub === "tail")
134
+ return auditTail(rest, out);
135
+ out("usage: operator audit <verify [--file <path>] [--json] | tail [n]> · operator doctor [--json] [--strict]");
136
+ return cmd === "audit" || cmd === "doctor" ? 1 : 0;
137
+ }
@@ -1,6 +1,7 @@
1
1
  // Training flywheel upgrades — SRFT step masking, mutation verify, and eval harness.
2
2
  // This turns the existing graded trajectory recorder into a self-improving loop.
3
3
  import { mkdirSync, appendFileSync } from "node:fs";
4
+ import { screenRecord } from "./secret-gate.js"; // HV3-N1: the training stream must never carry secrets
4
5
  import { join, dirname } from "node:path";
5
6
  /** Apply SRFT-style step masking to a trajectory.
6
7
  * Marks each step as productive (keep in loss) or harmful (mask from loss).
@@ -198,7 +199,7 @@ export class FlywheelProcessor {
198
199
  const { join } = await import("node:path");
199
200
  const flywheelDir = this.opts.flywheelDir;
200
201
  if (!existsSync(flywheelDir)) {
201
- return { total: 0, processed: 0, masked: 0, results: [] };
202
+ return { total: 0, processed: 0, masked: 0, quarantined: 0, results: [] };
202
203
  }
203
204
  const files = readdirSync(flywheelDir).filter(f => f.endsWith(".jsonl"));
204
205
  const allRows = [];
@@ -216,10 +217,35 @@ export class FlywheelProcessor {
216
217
  catch { /* skip malformed rows */ }
217
218
  }
218
219
  }
220
+ // HV3-N1 SECRET GATE: screen every record BEFORE processing; hits are quarantined with their
221
+ // full original line preserved (rename-not-delete doctrine) for owner review. Fail-closed:
222
+ // the gate runs unless the owner explicitly set secretGate === false.
223
+ let quarantinePath = null;
224
+ let gate = { clean: [], hits: [] };
225
+ if (this.opts.secretGate === false) {
226
+ gate = { clean: allRows, hits: [] };
227
+ }
228
+ else {
229
+ for (const row of allRows) {
230
+ const v = screenRecord(JSON.stringify(row));
231
+ if (v.clean)
232
+ gate.clean.push(row);
233
+ else
234
+ gate.hits.push({ row, why: v.findings.map((f) => `${f.rule} ${f.sample}`).join("; ") });
235
+ }
236
+ if (gate.hits.length) {
237
+ const qdir = join(flywheelDir, "quarantine");
238
+ mkdirSync(qdir, { recursive: true });
239
+ quarantinePath = join(qdir, `${new Date().toISOString().slice(0, 10)}-secrets.jsonl`);
240
+ for (const { row, why } of gate.hits) {
241
+ appendFileSync(quarantinePath, JSON.stringify({ quarantinedAt: new Date().toISOString(), why, record: row }) + "\n", "utf8");
242
+ }
243
+ }
244
+ }
219
245
  // Process each trajectory
220
246
  const processed = [];
221
247
  let maskedCount = 0;
222
- for (const traj of allRows) {
248
+ for (const traj of gate.clean) {
223
249
  let processedTraj = { ...traj };
224
250
  // Apply SRFT masking
225
251
  if (this.opts.applySRFT) {
@@ -241,10 +267,12 @@ export class FlywheelProcessor {
241
267
  for (const p of processed) {
242
268
  appendFileSync(outputFile, JSON.stringify(p) + "\n", "utf8");
243
269
  }
270
+ void quarantinePath;
244
271
  return {
245
272
  total: allRows.length,
246
273
  processed: processed.length,
247
274
  masked: maskedCount,
275
+ quarantined: gate.hits.length,
248
276
  results: processed,
249
277
  };
250
278
  }