loopengine 0.3.100 → 0.4.1

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.
@@ -0,0 +1,70 @@
1
+ import type { DatabaseSync } from 'node:sqlite';
2
+ export type VersionKind = 'brief' | 'policies';
3
+ export interface Version {
4
+ number: number;
5
+ at: string;
6
+ by?: string;
7
+ reason?: string;
8
+ content: string;
9
+ }
10
+ export type AuditEventKind = 'decision' | 'answer' | 'feedback';
11
+ export interface AuditEvent {
12
+ id: number;
13
+ at: string;
14
+ agent: string;
15
+ workflow_id?: string;
16
+ run_id?: string;
17
+ kind: AuditEventKind;
18
+ by?: string;
19
+ data: Record<string, unknown>;
20
+ }
21
+ /** Opens (creating if need be) the database in `dir`. */
22
+ export declare function openAuditDb(dir: string): DatabaseSync | undefined;
23
+ export declare function schedulerDir(): string;
24
+ /** The process-wide database; undefined where node:sqlite isn't there,
25
+ * or LOOPENGINE_RUN_STORE=files asks for the JSON files. */
26
+ export declare function auditDb(): DatabaseSync | undefined;
27
+ /** Tests: use this database (or none). */
28
+ export declare function setAuditDb(next: DatabaseSync | undefined): void;
29
+ /** How long finished runs are kept, in days. */
30
+ export declare function retentionDays(): number;
31
+ /** Appends what someone did in or about a run. Never throws: the record
32
+ * must not stop the work it records. */
33
+ export declare function recordEvent(event: Omit<AuditEvent, 'id' | 'at'> & {
34
+ at?: string;
35
+ }, database?: DatabaseSync | undefined): void;
36
+ /** A run's events, oldest first. */
37
+ export declare function runEvents(runId: string, database?: DatabaseSync | undefined): AuditEvent[];
38
+ /** The version number of `content`: the latest version's when it's the
39
+ * same text, else a new version noted now. Undefined without a database.
40
+ * `agent` and `workflowId` are '' for the workspace's policies. */
41
+ export declare function noteVersion(key: {
42
+ agent: string;
43
+ workflowId: string;
44
+ kind: VersionKind;
45
+ }, content: string, about?: {
46
+ by?: string;
47
+ reason?: string;
48
+ }, database?: DatabaseSync | undefined): number | undefined;
49
+ /** Every version, newest first. */
50
+ export declare function listVersions(key: {
51
+ agent: string;
52
+ workflowId: string;
53
+ kind: VersionKind;
54
+ }, database?: DatabaseSync | undefined): Version[];
55
+ export declare function getVersion(key: {
56
+ agent: string;
57
+ workflowId: string;
58
+ kind: VersionKind;
59
+ }, number: number, database?: DatabaseSync | undefined): Version | undefined;
60
+ /** What a workflow's brief version holds: its instructions and the
61
+ * result format, as one text (the format under a heading). */
62
+ export declare function briefContent(workflow: {
63
+ instructions: string;
64
+ output?: string;
65
+ }): string;
66
+ /** The instructions and result format a brief version holds. */
67
+ export declare function briefFromContent(content: string): {
68
+ instructions: string;
69
+ output?: string;
70
+ };
@@ -0,0 +1,191 @@
1
+ // The workspace's record of what its workflows did and what they ran
2
+ // under: one SQLite file, `<LOOPENGINE_SCHEDULER_DIR or .scheduler>/loopengine.db`,
3
+ // beside the scheduler's own files. It holds
4
+ //
5
+ // - runs: every workflow run (core/workflow-runs.ts's SqliteRunStore),
6
+ // kept for LOOPENGINE_RETENTION_DAYS (400 by default) rather than the
7
+ // latest 500 per agent the console lists;
8
+ // - events: what people did in or about a run (an approval decided, with
9
+ // the tool's input before and after a change and any reason; a question
10
+ // answered; feedback on the result), appended and never changed;
11
+ // - versions: each workflow's brief (its instructions and result format)
12
+ // and the workspace's shared policies, numbered. A new version is noted
13
+ // whenever the text differs from the latest, however it changed: saved
14
+ // in the console, restored, or edited in the file.
15
+ //
16
+ // It uses node:sqlite, built into Node 22.5 and later. Where that's
17
+ // missing, auditDb() is undefined: runs stay in JSON files and nothing is
18
+ // versioned.
19
+ import { createHash } from 'node:crypto';
20
+ import { mkdirSync } from 'node:fs';
21
+ import { createRequire } from 'node:module';
22
+ import path from 'node:path';
23
+ const SCHEMA = `
24
+ CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
25
+ CREATE TABLE IF NOT EXISTS runs (
26
+ run_id TEXT PRIMARY KEY,
27
+ agent TEXT NOT NULL,
28
+ workflow_id TEXT NOT NULL,
29
+ status TEXT NOT NULL,
30
+ started_at TEXT NOT NULL,
31
+ finished_at TEXT,
32
+ session_id TEXT NOT NULL,
33
+ data TEXT NOT NULL
34
+ );
35
+ CREATE INDEX IF NOT EXISTS runs_agent ON runs (agent, workflow_id, started_at);
36
+ CREATE INDEX IF NOT EXISTS runs_session ON runs (session_id);
37
+ CREATE INDEX IF NOT EXISTS runs_finished ON runs (finished_at);
38
+ CREATE TABLE IF NOT EXISTS events (
39
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
40
+ at TEXT NOT NULL,
41
+ agent TEXT NOT NULL,
42
+ workflow_id TEXT,
43
+ run_id TEXT,
44
+ kind TEXT NOT NULL,
45
+ by TEXT,
46
+ data TEXT NOT NULL
47
+ );
48
+ CREATE INDEX IF NOT EXISTS events_run ON events (run_id);
49
+ CREATE INDEX IF NOT EXISTS events_workflow ON events (agent, workflow_id, at);
50
+ CREATE TABLE IF NOT EXISTS versions (
51
+ agent TEXT NOT NULL,
52
+ workflow_id TEXT NOT NULL,
53
+ kind TEXT NOT NULL,
54
+ number INTEGER NOT NULL,
55
+ hash TEXT NOT NULL,
56
+ content TEXT NOT NULL,
57
+ at TEXT NOT NULL,
58
+ by TEXT,
59
+ reason TEXT,
60
+ PRIMARY KEY (agent, workflow_id, kind, number)
61
+ );
62
+ `;
63
+ // node:sqlite, or undefined on a Node without it. Node 22 marks it
64
+ // experimental and says so once on load; that warning is dropped here.
65
+ function loadSqlite() {
66
+ const emit = process.emitWarning;
67
+ process.emitWarning = ((warning, ...rest) => {
68
+ if (/SQLite/i.test(typeof warning === 'string' ? warning : warning.message))
69
+ return;
70
+ return emit.call(process, warning, ...rest);
71
+ });
72
+ try {
73
+ return createRequire(import.meta.url)('node:sqlite');
74
+ }
75
+ catch {
76
+ return undefined;
77
+ }
78
+ finally {
79
+ process.emitWarning = emit;
80
+ }
81
+ }
82
+ /** Opens (creating if need be) the database in `dir`. */
83
+ export function openAuditDb(dir) {
84
+ const sqlite = loadSqlite();
85
+ if (!sqlite)
86
+ return undefined;
87
+ mkdirSync(dir, { recursive: true });
88
+ const db = new sqlite.DatabaseSync(path.join(dir, 'loopengine.db'));
89
+ db.exec('PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;');
90
+ db.exec(SCHEMA);
91
+ return db;
92
+ }
93
+ let db;
94
+ export function schedulerDir() {
95
+ return process.env.LOOPENGINE_SCHEDULER_DIR || path.join(process.cwd(), '.scheduler');
96
+ }
97
+ /** The process-wide database; undefined where node:sqlite isn't there,
98
+ * or LOOPENGINE_RUN_STORE=files asks for the JSON files. */
99
+ export function auditDb() {
100
+ if (db === undefined)
101
+ db = process.env.LOOPENGINE_RUN_STORE === 'files' ? null : (openAuditDb(schedulerDir()) ?? null);
102
+ return db ?? undefined;
103
+ }
104
+ /** Tests: use this database (or none). */
105
+ export function setAuditDb(next) {
106
+ db = next ?? null;
107
+ }
108
+ /** How long finished runs are kept, in days. */
109
+ export function retentionDays() {
110
+ const n = Number(process.env.LOOPENGINE_RETENTION_DAYS);
111
+ return Number.isFinite(n) && n > 0 ? n : 400;
112
+ }
113
+ // ---------- events ----------
114
+ /** Appends what someone did in or about a run. Never throws: the record
115
+ * must not stop the work it records. */
116
+ export function recordEvent(event, database = auditDb()) {
117
+ if (!database)
118
+ return;
119
+ try {
120
+ database.prepare('INSERT INTO events (at, agent, workflow_id, run_id, kind, by, data) VALUES (?, ?, ?, ?, ?, ?, ?)').run(event.at ?? new Date().toISOString(), event.agent, event.workflow_id ?? null, event.run_id ?? null, event.kind, event.by ?? null, JSON.stringify(event.data));
121
+ }
122
+ catch (err) {
123
+ console.error('[loopengine] could not record an audit event:', err);
124
+ }
125
+ }
126
+ /** A run's events, oldest first. */
127
+ export function runEvents(runId, database = auditDb()) {
128
+ if (!database)
129
+ return [];
130
+ const rows = database.prepare('SELECT * FROM events WHERE run_id = ? ORDER BY id').all(runId);
131
+ return rows.map((r) => ({
132
+ id: Number(r.id),
133
+ at: String(r.at),
134
+ agent: String(r.agent),
135
+ ...(r.workflow_id ? { workflow_id: String(r.workflow_id) } : {}),
136
+ ...(r.run_id ? { run_id: String(r.run_id) } : {}),
137
+ kind: String(r.kind),
138
+ ...(r.by ? { by: String(r.by) } : {}),
139
+ data: JSON.parse(String(r.data)),
140
+ }));
141
+ }
142
+ // ---------- versions ----------
143
+ const hashOf = (content) => createHash('sha256').update(content).digest('hex');
144
+ /** The version number of `content`: the latest version's when it's the
145
+ * same text, else a new version noted now. Undefined without a database.
146
+ * `agent` and `workflowId` are '' for the workspace's policies. */
147
+ export function noteVersion(key, content, about = {}, database = auditDb()) {
148
+ if (!database)
149
+ return undefined;
150
+ try {
151
+ const hash = hashOf(content);
152
+ const latest = database.prepare('SELECT number, hash FROM versions WHERE agent = ? AND workflow_id = ? AND kind = ? ORDER BY number DESC LIMIT 1')
153
+ .get(key.agent, key.workflowId, key.kind);
154
+ if (latest && latest.hash === hash)
155
+ return Number(latest.number);
156
+ const number = (latest ? Number(latest.number) : 0) + 1;
157
+ database.prepare('INSERT INTO versions (agent, workflow_id, kind, number, hash, content, at, by, reason) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)').run(key.agent, key.workflowId, key.kind, number, hash, content, new Date().toISOString(), about.by ?? null, about.reason ?? (latest ? 'Changed outside the console' : 'First version'));
158
+ return number;
159
+ }
160
+ catch (err) {
161
+ console.error('[loopengine] could not note a version:', err);
162
+ return undefined;
163
+ }
164
+ }
165
+ /** Every version, newest first. */
166
+ export function listVersions(key, database = auditDb()) {
167
+ if (!database)
168
+ return [];
169
+ const rows = database.prepare('SELECT number, at, by, reason, content FROM versions WHERE agent = ? AND workflow_id = ? AND kind = ? ORDER BY number DESC')
170
+ .all(key.agent, key.workflowId, key.kind);
171
+ return rows.map((r) => ({
172
+ number: Number(r.number),
173
+ at: String(r.at),
174
+ ...(r.by ? { by: String(r.by) } : {}),
175
+ ...(r.reason ? { reason: String(r.reason) } : {}),
176
+ content: String(r.content),
177
+ }));
178
+ }
179
+ export function getVersion(key, number, database = auditDb()) {
180
+ return listVersions(key, database).find((v) => v.number === number);
181
+ }
182
+ /** What a workflow's brief version holds: its instructions and the
183
+ * result format, as one text (the format under a heading). */
184
+ export function briefContent(workflow) {
185
+ return workflow.output?.trim() ? `${workflow.instructions}\n\n## Result format\n\n${workflow.output.trim()}` : workflow.instructions;
186
+ }
187
+ /** The instructions and result format a brief version holds. */
188
+ export function briefFromContent(content) {
189
+ const at = content.lastIndexOf('\n\n## Result format\n\n');
190
+ return at < 0 ? { instructions: content } : { instructions: content.slice(0, at), output: content.slice(at + '\n\n## Result format\n\n'.length) };
191
+ }
@@ -1,3 +1,4 @@
1
+ import type { DatabaseSync } from 'node:sqlite';
1
2
  import type { CallbackDelivery } from './run-callbacks.js';
2
3
  export type WorkflowRunStatus = 'running' | 'awaiting_approval' | 'done' | 'error';
3
4
  export interface WorkflowRun {
@@ -54,15 +55,12 @@ export interface WorkflowRun {
54
55
  warnings?: string[];
55
56
  /** Each callback delivery, oldest first (the latest 10). */
56
57
  callbacks?: CallbackDelivery[];
58
+ /** The brief and shared policies it ran under (core/audit-store.ts's
59
+ * versions), when the workspace keeps versions. */
60
+ versions?: RunVersions;
57
61
  /** Each approval decided while it ran, oldest first, with who decided
58
62
  * (an email, or a chat name) when known. */
59
- decisions?: {
60
- tool: string;
61
- approved: boolean;
62
- at: string;
63
- by?: string;
64
- edited?: boolean;
65
- }[];
63
+ decisions?: RunDecision[];
66
64
  /** Each question it asked that was answered, oldest first. */
67
65
  answers?: {
68
66
  question: string;
@@ -75,6 +73,23 @@ export interface WorkflowRun {
75
73
  * much it was edited from the result, and a verdict. */
76
74
  feedback?: RunFeedback;
77
75
  }
76
+ export interface RunVersions {
77
+ brief?: number;
78
+ policies?: number;
79
+ }
80
+ export interface RunDecision {
81
+ tool: string;
82
+ approved: boolean;
83
+ at: string;
84
+ by?: string;
85
+ edited?: boolean;
86
+ /** For an approval changed before it ran: the input the agent asked
87
+ * for, and what ran instead. */
88
+ before?: unknown;
89
+ after?: unknown;
90
+ /** Why it was denied, when the person said. */
91
+ reason?: string;
92
+ }
78
93
  export interface RunFeedback {
79
94
  verdict?: 'good' | 'bad';
80
95
  /** How far the text actually used is from the result. */
@@ -104,6 +119,15 @@ export interface RunStore {
104
119
  put(run: WorkflowRun): Promise<void>;
105
120
  remove(runId: string): Promise<void>;
106
121
  update(runId: string, fn: (run: WorkflowRun | undefined) => WorkflowRun | undefined): Promise<WorkflowRun | undefined>;
122
+ /** An agent's runs, newest first, without reading every run. */
123
+ forAgent?(agent: string, filter: {
124
+ workflowId?: string;
125
+ limit?: number;
126
+ }): Promise<WorkflowRun[]>;
127
+ /** The run with this session, without reading every run. */
128
+ bySession?(sessionId: string): Promise<WorkflowRun | undefined>;
129
+ /** Drops what's past keeping, instead of the runner's per-agent cap. */
130
+ prune?(): Promise<void>;
107
131
  }
108
132
  /** One JSON file per run under `<dir>/runs/` — one server process. */
109
133
  export declare class FileRunStore implements RunStore {
@@ -116,7 +140,38 @@ export declare class FileRunStore implements RunStore {
116
140
  remove(runId: string): Promise<void>;
117
141
  update(runId: string, fn: (run: WorkflowRun | undefined) => WorkflowRun | undefined): Promise<WorkflowRun | undefined>;
118
142
  }
119
- /** The process-wide store: `runs/` in the scheduler's folder. */
143
+ /** Runs in the workspace's database (core/audit-store.ts). list() is what
144
+ * the console shows: every run under way, and each agent's latest
145
+ * `listed` finished ones; older runs stay until the retention period
146
+ * ends. */
147
+ export declare class SqliteRunStore implements RunStore {
148
+ private readonly db;
149
+ private readonly listed;
150
+ private lastPrune;
151
+ /** `importFrom`: a scheduler folder whose runs/ JSON files are copied in
152
+ * the first time. */
153
+ constructor(db: DatabaseSync, options?: {
154
+ importFrom?: string;
155
+ listed?: number;
156
+ });
157
+ private importFiles;
158
+ private write;
159
+ private read;
160
+ list(): Promise<WorkflowRun[]>;
161
+ forAgent(agent: string, filter: {
162
+ workflowId?: string;
163
+ limit?: number;
164
+ }): Promise<WorkflowRun[]>;
165
+ bySession(sessionId: string): Promise<WorkflowRun | undefined>;
166
+ get(runId: string): Promise<WorkflowRun | undefined>;
167
+ put(run: WorkflowRun): Promise<void>;
168
+ remove(runId: string): Promise<void>;
169
+ update(runId: string, fn: (run: WorkflowRun | undefined) => WorkflowRun | undefined): Promise<WorkflowRun | undefined>;
170
+ /** At most hourly: runs finished before the retention period. */
171
+ prune(): Promise<void>;
172
+ }
173
+ /** The process-wide store: the workspace's database, or JSON files in
174
+ * `runs/` in the scheduler's folder where there's none. */
120
175
  export declare function getRunStore(): RunStore;
121
176
  export declare function setRunStore(next: RunStore): void;
122
177
  /** An agent's runs, newest first; of one workflow when `workflowId` is given. */
@@ -150,15 +205,19 @@ export declare class WorkflowRunner {
150
205
  private readonly execute;
151
206
  private readonly maxFinishedPerAgent;
152
207
  private readonly onChange?;
208
+ private readonly versionsFor?;
153
209
  private readonly inFlight;
154
210
  /** `onChange`: called with the run when it starts, and each time it
155
211
  * finishes, fails or stops for a decision (the server sends its chat
156
- * messages and callbacks). */
212
+ * messages and callbacks). `versionsFor`: the brief and policies
213
+ * versions a run of this workflow starts under. */
157
214
  constructor(options: {
158
215
  execute: ExecuteRun;
159
216
  maxFinishedPerAgent?: number;
160
217
  onChange?: (run: WorkflowRun) => void | Promise<void>;
218
+ versionsFor?: (agent: string, workflowId: string) => RunVersions | undefined;
161
219
  });
220
+ private versionsOf;
162
221
  private changed;
163
222
  /** Records a run and starts it; returns at once with the record. */
164
223
  start(input: StartRunInput): Promise<WorkflowRun>;
@@ -190,13 +249,20 @@ export declare class WorkflowRunner {
190
249
  }): Promise<void>;
191
250
  /** The run a session belongs to, if it's a workflow run's. */
192
251
  forSession(sessionId: string): Promise<WorkflowRun | undefined>;
193
- /** Records an approval decided in a run's session. */
252
+ /** Records an approval decided in a run's session: on the run, and in
253
+ * the workspace's audit events. */
194
254
  recordDecision(sessionId: string, decision: {
195
255
  tool: string;
196
256
  approved: boolean;
197
257
  by?: string;
198
258
  edited?: boolean;
259
+ before?: unknown;
260
+ after?: unknown;
261
+ reason?: string;
199
262
  }): Promise<void>;
263
+ /** Records feedback given on a run's result in the audit events (the
264
+ * run itself carries the latest). */
265
+ recordFeedback(run: WorkflowRun, feedback: RunFeedback, by?: string): void;
200
266
  /** Records a question answered in a run's session. */
201
267
  recordAnswer(sessionId: string, answer: {
202
268
  question: string;
@@ -12,13 +12,16 @@
12
12
  // run that pauses there is settled by settleFromResume once someone
13
13
  // decides.
14
14
  //
15
- // Stored like scheduled tasks: one JSON file per run under
16
- // `<LOOPENGINE_SCHEDULER_DIR or .scheduler>/runs/`. Each agent keeps its
17
- // latest MAX_FINISHED_PER_AGENT finished runs; older ones are removed as
18
- // new runs start.
15
+ // Stored in the workspace's database (core/audit-store.ts), kept for
16
+ // its retention period; the console lists each agent's latest
17
+ // MAX_FINISHED_PER_AGENT finished runs. Where there's no database (no
18
+ // node:sqlite), one JSON file per run under
19
+ // `<LOOPENGINE_SCHEDULER_DIR or .scheduler>/runs/`, keeping only those.
20
+ // Runs already in files are copied into the database once.
19
21
  import { randomUUID } from 'node:crypto';
20
22
  import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
21
23
  import path from 'node:path';
24
+ import { auditDb, recordEvent, retentionDays, schedulerDir } from './audit-store.js';
22
25
  import { KeyedMutex } from './session-store.js';
23
26
  const MAX_FINISHED_PER_AGENT = 500;
24
27
  const SESSION_PREFIX = 'run-';
@@ -76,10 +79,119 @@ export class FileRunStore {
76
79
  });
77
80
  }
78
81
  }
82
+ const UNDER_WAY = "('running', 'awaiting_approval')";
83
+ /** Runs in the workspace's database (core/audit-store.ts). list() is what
84
+ * the console shows: every run under way, and each agent's latest
85
+ * `listed` finished ones; older runs stay until the retention period
86
+ * ends. */
87
+ export class SqliteRunStore {
88
+ db;
89
+ listed;
90
+ lastPrune = 0;
91
+ /** `importFrom`: a scheduler folder whose runs/ JSON files are copied in
92
+ * the first time. */
93
+ constructor(db, options = {}) {
94
+ this.db = db;
95
+ this.listed = options.listed ?? MAX_FINISHED_PER_AGENT;
96
+ if (options.importFrom)
97
+ this.importFiles(options.importFrom);
98
+ }
99
+ importFiles(dir) {
100
+ const done = this.db.prepare("SELECT value FROM meta WHERE key = 'runs_imported'").get();
101
+ if (done)
102
+ return;
103
+ const runsDir = path.join(dir, 'runs');
104
+ let count = 0;
105
+ if (existsSync(runsDir)) {
106
+ this.db.exec('BEGIN');
107
+ try {
108
+ for (const name of readdirSync(runsDir)) {
109
+ if (!name.endsWith('.json'))
110
+ continue;
111
+ try {
112
+ const run = JSON.parse(readFileSync(path.join(runsDir, name), 'utf8'));
113
+ if (run.run_id && run.agent) {
114
+ this.write(run, 'OR IGNORE');
115
+ count++;
116
+ }
117
+ }
118
+ catch {
119
+ // Not a run: skip it.
120
+ }
121
+ }
122
+ this.db.exec('COMMIT');
123
+ }
124
+ catch (err) {
125
+ this.db.exec('ROLLBACK');
126
+ throw err;
127
+ }
128
+ }
129
+ // The files stay, untouched, as they were.
130
+ this.db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES ('runs_imported', ?)").run(`${new Date().toISOString()} ${count}`);
131
+ }
132
+ write(run, conflict = 'OR REPLACE') {
133
+ this.db.prepare(`INSERT ${conflict} INTO runs (run_id, agent, workflow_id, status, started_at, finished_at, session_id, data) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)
134
+ .run(run.run_id, run.agent, run.workflow_id ?? '', run.status, run.started_at, run.finished_at ?? null, run.session_id ?? '', JSON.stringify(run));
135
+ }
136
+ read(row) {
137
+ return JSON.parse(String(row.data));
138
+ }
139
+ async list() {
140
+ const rows = this.db.prepare(`
141
+ SELECT data, started_at FROM runs WHERE status IN ${UNDER_WAY}
142
+ UNION ALL
143
+ SELECT data, started_at FROM (
144
+ SELECT data, started_at, ROW_NUMBER() OVER (PARTITION BY agent ORDER BY started_at DESC) AS n
145
+ FROM runs WHERE status NOT IN ${UNDER_WAY}
146
+ ) WHERE n <= ?
147
+ ORDER BY started_at DESC`).all(this.listed);
148
+ return rows.map((r) => this.read(r));
149
+ }
150
+ async forAgent(agent, filter) {
151
+ const limit = Math.min(filter.limit ?? this.listed, this.listed);
152
+ const rows = filter.workflowId
153
+ ? this.db.prepare('SELECT data FROM runs WHERE agent = ? AND workflow_id = ? ORDER BY started_at DESC LIMIT ?').all(agent, filter.workflowId, limit)
154
+ : this.db.prepare('SELECT data FROM runs WHERE agent = ? ORDER BY started_at DESC LIMIT ?').all(agent, limit);
155
+ return rows.map((r) => this.read(r));
156
+ }
157
+ async bySession(sessionId) {
158
+ const row = this.db.prepare('SELECT data FROM runs WHERE session_id = ? ORDER BY started_at DESC LIMIT 1').get(sessionId);
159
+ return row ? this.read(row) : undefined;
160
+ }
161
+ async get(runId) {
162
+ const row = this.db.prepare('SELECT data FROM runs WHERE run_id = ?').get(runId);
163
+ return row ? this.read(row) : undefined;
164
+ }
165
+ async put(run) {
166
+ this.write(run);
167
+ }
168
+ async remove(runId) {
169
+ this.db.prepare('DELETE FROM runs WHERE run_id = ?').run(runId);
170
+ }
171
+ // node:sqlite is synchronous, so read-change-write here can't interleave.
172
+ async update(runId, fn) {
173
+ const next = fn(await this.get(runId));
174
+ if (next)
175
+ this.write(next);
176
+ return next;
177
+ }
178
+ /** At most hourly: runs finished before the retention period. */
179
+ async prune() {
180
+ if (Date.now() - this.lastPrune < 60 * 60 * 1000)
181
+ return;
182
+ this.lastPrune = Date.now();
183
+ const before = new Date(Date.now() - retentionDays() * 24 * 60 * 60 * 1000).toISOString();
184
+ this.db.prepare(`DELETE FROM runs WHERE status NOT IN ${UNDER_WAY} AND COALESCE(finished_at, started_at) < ?`).run(before);
185
+ }
186
+ }
79
187
  let store;
80
- /** The process-wide store: `runs/` in the scheduler's folder. */
188
+ /** The process-wide store: the workspace's database, or JSON files in
189
+ * `runs/` in the scheduler's folder where there's none. */
81
190
  export function getRunStore() {
82
- store ??= new FileRunStore(process.env.LOOPENGINE_SCHEDULER_DIR || path.join(process.cwd(), '.scheduler'));
191
+ if (!store) {
192
+ const db = auditDb();
193
+ store = db ? new SqliteRunStore(db, { importFrom: schedulerDir() }) : new FileRunStore(schedulerDir());
194
+ }
83
195
  return store;
84
196
  }
85
197
  export function setRunStore(next) {
@@ -88,6 +200,9 @@ export function setRunStore(next) {
88
200
  // ---------- reading ----------
89
201
  /** An agent's runs, newest first; of one workflow when `workflowId` is given. */
90
202
  export async function listRuns(agent, filter = {}) {
203
+ const store = getRunStore();
204
+ if (store.forAgent)
205
+ return store.forAgent(agent, filter);
91
206
  const runs = (await getRunStore().list()).filter((r) => r.agent === agent && (!filter.workflowId || r.workflow_id === filter.workflowId));
92
207
  return filter.limit ? runs.slice(0, filter.limit) : runs;
93
208
  }
@@ -105,14 +220,29 @@ export class WorkflowRunner {
105
220
  execute;
106
221
  maxFinishedPerAgent;
107
222
  onChange;
223
+ versionsFor;
108
224
  inFlight = new Set();
109
225
  /** `onChange`: called with the run when it starts, and each time it
110
226
  * finishes, fails or stops for a decision (the server sends its chat
111
- * messages and callbacks). */
227
+ * messages and callbacks). `versionsFor`: the brief and policies
228
+ * versions a run of this workflow starts under. */
112
229
  constructor(options) {
113
230
  this.execute = options.execute;
114
231
  this.maxFinishedPerAgent = options.maxFinishedPerAgent ?? MAX_FINISHED_PER_AGENT;
115
232
  this.onChange = options.onChange;
233
+ this.versionsFor = options.versionsFor;
234
+ }
235
+ versionsOf(agent, workflowId) {
236
+ if (!this.versionsFor || !workflowId)
237
+ return {};
238
+ try {
239
+ const versions = this.versionsFor(agent, workflowId);
240
+ return versions && (versions.brief || versions.policies) ? { versions } : {};
241
+ }
242
+ catch (err) {
243
+ console.error('[loopengine] could not note the versions a run starts under:', err);
244
+ return {};
245
+ }
116
246
  }
117
247
  changed(run) {
118
248
  if (!run || !this.onChange)
@@ -138,6 +268,7 @@ export class WorkflowRunner {
138
268
  ...(input.trigger_id ? { trigger_id: input.trigger_id } : {}),
139
269
  ...(input.job ? { job: input.job } : {}),
140
270
  ...(input.chained_from ? { chained_from: input.chained_from, chain_depth: input.chain_depth ?? 1 } : {}),
271
+ ...this.versionsOf(input.agent, input.workflow_id),
141
272
  status: 'running',
142
273
  started_at: new Date().toISOString(),
143
274
  message: input.message,
@@ -168,6 +299,7 @@ export class WorkflowRunner {
168
299
  ...(input.decisions_to ? { decisions_to: input.decisions_to } : {}),
169
300
  ...(input.chat_notice ? { chat_notice: input.chat_notice } : {}),
170
301
  ...(input.warnings?.length ? { warnings: input.warnings } : {}),
302
+ ...this.versionsOf(input.agent, input.workflow_id),
171
303
  status: 'running',
172
304
  started_at: new Date().toISOString(),
173
305
  message: input.message,
@@ -217,9 +349,7 @@ export class WorkflowRunner {
217
349
  * its resolve path, for every resumed session): settle it, or record
218
350
  * what it's waiting on now. */
219
351
  async settleFromResume(sessionId, outcome) {
220
- if (!sessionId.startsWith(SESSION_PREFIX) && !sessionId.startsWith(SCHEDULE_SESSION_PREFIX))
221
- return;
222
- const run = (await getRunStore().list()).find((r) => r.session_id === sessionId);
352
+ const run = await this.forSession(sessionId);
223
353
  if (!run)
224
354
  return;
225
355
  if (outcome.pendingIds?.length) {
@@ -232,15 +362,35 @@ export class WorkflowRunner {
232
362
  async forSession(sessionId) {
233
363
  if (!sessionId.startsWith(SESSION_PREFIX) && !sessionId.startsWith(SCHEDULE_SESSION_PREFIX))
234
364
  return undefined;
235
- return (await getRunStore().list()).find((r) => r.session_id === sessionId);
365
+ const store = getRunStore();
366
+ if (store.bySession)
367
+ return store.bySession(sessionId);
368
+ return (await store.list()).find((r) => r.session_id === sessionId);
236
369
  }
237
- /** Records an approval decided in a run's session. */
370
+ /** Records an approval decided in a run's session: on the run, and in
371
+ * the workspace's audit events. */
238
372
  async recordDecision(sessionId, decision) {
239
373
  const run = await this.forSession(sessionId);
240
374
  if (!run)
241
375
  return;
242
- const entry = { tool: decision.tool, approved: decision.approved, at: new Date().toISOString(), ...(decision.by ? { by: decision.by } : {}), ...(decision.edited ? { edited: true } : {}) };
376
+ const reason = decision.reason?.trim().slice(0, 2000);
377
+ const entry = {
378
+ tool: decision.tool,
379
+ approved: decision.approved,
380
+ at: new Date().toISOString(),
381
+ ...(decision.by ? { by: decision.by } : {}),
382
+ ...(decision.edited ? { edited: true, before: clip(decision.before), after: clip(decision.after) } : {}),
383
+ ...(reason ? { reason } : {}),
384
+ };
243
385
  await getRunStore().update(run.run_id, (r) => r && { ...r, decisions: [...(r.decisions ?? []), entry].slice(-50) });
386
+ const { at, by, ...data } = entry;
387
+ recordEvent({ at, agent: run.agent, workflow_id: run.workflow_id, run_id: run.run_id, kind: 'decision', ...(by ? { by } : {}), data });
388
+ }
389
+ /** Records feedback given on a run's result in the audit events (the
390
+ * run itself carries the latest). */
391
+ recordFeedback(run, feedback, by) {
392
+ const { at, ...data } = feedback;
393
+ recordEvent({ at, agent: run.agent, workflow_id: run.workflow_id, run_id: run.run_id, kind: 'feedback', ...(by ? { by } : {}), data });
244
394
  }
245
395
  /** Records a question answered in a run's session. */
246
396
  async recordAnswer(sessionId, answer) {
@@ -249,6 +399,7 @@ export class WorkflowRunner {
249
399
  return;
250
400
  const entry = { question: answer.question.slice(0, 4000), answer: answer.answer.slice(0, 4000), at: new Date().toISOString(), ...(answer.by ? { by: answer.by } : {}) };
251
401
  await getRunStore().update(run.run_id, (r) => r && { ...r, answers: [...(r.answers ?? []), entry].slice(-50) });
402
+ recordEvent({ at: entry.at, agent: run.agent, workflow_id: run.workflow_id, run_id: run.run_id, kind: 'answer', ...(answer.by ? { by: answer.by } : {}), data: { question: entry.question, answer: entry.answer } });
252
403
  }
253
404
  /** On startup: a run a restart cut off can't continue, so it's an
254
405
  * error. One waiting on a decision is kept: its checkpoint survives. */
@@ -259,8 +410,19 @@ export class WorkflowRunner {
259
410
  }
260
411
  }
261
412
  async prune(agent) {
413
+ const store = getRunStore();
414
+ if (store.prune)
415
+ return store.prune();
262
416
  const finished = (await listRuns(agent)).filter((r) => !isUnderWay(r));
263
417
  for (const old of finished.slice(this.maxFinishedPerAgent))
264
418
  await getRunStore().remove(old.run_id);
265
419
  }
266
420
  }
421
+ // A tool input kept on a decision: as given when small, else its JSON cut
422
+ // to 8,000 characters.
423
+ function clip(value) {
424
+ if (value === undefined)
425
+ return undefined;
426
+ const text = JSON.stringify(value);
427
+ return text.length <= 8000 ? value : text.slice(0, 8000);
428
+ }