@hivemagnus/ardent 3.2.1 → 3.4.0

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 (52) hide show
  1. package/README.md +15 -923
  2. package/dist/a2a-client.js +3 -2
  3. package/dist/a2a-peers.d.ts +26 -0
  4. package/dist/a2a-peers.js +60 -18
  5. package/dist/a2a-push.d.ts +3 -1
  6. package/dist/a2a-push.js +5 -1
  7. package/dist/a2a-rate-limit.d.ts +3 -3
  8. package/dist/a2a-rate-limit.js +6 -3
  9. package/dist/a2a-server.d.ts +13 -1
  10. package/dist/a2a-server.js +20 -11
  11. package/dist/api.d.ts +12 -0
  12. package/dist/api.js +312 -131
  13. package/dist/artifact-transfer.js +3 -2
  14. package/dist/channel-catchup.d.ts +2 -2
  15. package/dist/channels.d.ts +6 -6
  16. package/dist/channels.js +4 -1
  17. package/dist/cli.js +106 -8
  18. package/dist/config.d.ts +9 -1
  19. package/dist/config.js +15 -6
  20. package/dist/development.d.ts +3 -3
  21. package/dist/development.js +2 -1
  22. package/dist/errors.d.ts +54 -0
  23. package/dist/errors.js +76 -0
  24. package/dist/identity.js +11 -6
  25. package/dist/index.d.ts +1 -0
  26. package/dist/index.js +1 -0
  27. package/dist/job-engine.d.ts +3 -0
  28. package/dist/job-engine.js +5 -0
  29. package/dist/journal.d.ts +90 -0
  30. package/dist/journal.js +395 -0
  31. package/dist/log.d.ts +11 -0
  32. package/dist/log.js +12 -0
  33. package/dist/mattermost.js +7 -2
  34. package/dist/memory.js +3 -2
  35. package/dist/metrics.d.ts +34 -0
  36. package/dist/metrics.js +73 -0
  37. package/dist/missions.js +2 -1
  38. package/dist/plugin-http.js +10 -1
  39. package/dist/plugin-sdk.d.ts +2 -0
  40. package/dist/plugin-sdk.js +2 -0
  41. package/dist/retention.d.ts +64 -0
  42. package/dist/retention.js +239 -0
  43. package/dist/runtime.d.ts +17 -1
  44. package/dist/runtime.js +52 -15
  45. package/dist/skills.js +5 -4
  46. package/dist/store.d.ts +42 -0
  47. package/dist/store.js +114 -14
  48. package/dist/telegram.js +5 -1
  49. package/package.json +8 -4
  50. package/profiles/assistant/config.yaml +1 -1
  51. package/dist/codex-output-budget.test.d.ts +0 -1
  52. package/dist/codex-output-budget.test.js +0 -29
package/dist/memory.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { resolveReference } from './config.js';
3
+ import { dependencyUnavailable } from './errors.js';
3
4
  const Memory = z.object({ id: z.string(), agent_id: z.string(), content: z.string(), scope: z.enum(['private', 'shared']), workspace_id: z.string().optional(),
4
5
  created_at: z.string().optional(), metadata: z.object({ project_id: z.string().optional() }).passthrough().optional() }).passthrough();
5
6
  const Search = z.object({ results: z.array(z.object({ memory: Memory, score: z.number().optional(), citation: z.unknown().optional() }).passthrough()) }).passthrough();
@@ -12,12 +13,12 @@ export class HiveMemClient {
12
13
  agentId;
13
14
  constructor(config, env = process.env) {
14
15
  if (config.provider !== 'hivemem')
15
- throw new Error('Memory provider is not configured (memory.provider: none)');
16
+ throw dependencyUnavailable('Memory provider is not configured (memory.provider: none)');
16
17
  const base = resolveReference(config.base_url, env);
17
18
  const workspace = resolveReference(config.workspace_id, env);
18
19
  const token = env[config.token_env];
19
20
  if (!base || !workspace || !token)
20
- throw new Error('HiveMem URL, workspace, or scoped token is unconfigured');
21
+ throw dependencyUnavailable('HiveMem URL, workspace, or scoped token is unconfigured');
21
22
  const url = new URL(base);
22
23
  if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password)
23
24
  throw new Error('HiveMem URL is invalid');
@@ -0,0 +1,34 @@
1
+ import type { TaskStore } from './store.js';
2
+ /** The OpenMetrics text format's media type. */
3
+ export declare const OPENMETRICS_CONTENT_TYPE = "application/openmetrics-text; version=1.0.0; charset=utf-8";
4
+ type Labels = Readonly<Record<string, string>>;
5
+ /**
6
+ * In-process counters of things the journal does not record, such as A2A
7
+ * rate-limit refusals. They start at zero when the process starts.
8
+ */
9
+ export declare class RuntimeCounters {
10
+ #private;
11
+ increment(name: string, labels?: Labels, by?: number): void;
12
+ value(name: string, labels?: Labels): number;
13
+ series(name: string): Array<{
14
+ labels: Labels;
15
+ value: number;
16
+ }>;
17
+ }
18
+ /** A2A rate-limit refusal scopes: by client address, per peer, and the per-peer task cap. */
19
+ export declare const A2A_REFUSAL_SCOPES: readonly ["ip", "peer", "tasks"];
20
+ export interface MetricsSource {
21
+ readonly version: string;
22
+ readonly profile: string;
23
+ readonly backend: string;
24
+ readonly store: TaskStore;
25
+ readonly counters: RuntimeCounters;
26
+ readonly startedMs: number;
27
+ readonly now?: () => number;
28
+ }
29
+ /**
30
+ * The profile's metrics in the OpenMetrics text format. Gauges are read from
31
+ * the journal at scrape time; counters are this process's own.
32
+ */
33
+ export declare function renderMetrics(source: MetricsSource): string;
34
+ export {};
@@ -0,0 +1,73 @@
1
+ import { z } from 'zod';
2
+ /** The OpenMetrics text format's media type. */
3
+ export const OPENMETRICS_CONTENT_TYPE = 'application/openmetrics-text; version=1.0.0; charset=utf-8';
4
+ const labelKey = (labels) => JSON.stringify(Object.entries(labels).sort(([a], [b]) => a.localeCompare(b)));
5
+ /**
6
+ * In-process counters of things the journal does not record, such as A2A
7
+ * rate-limit refusals. They start at zero when the process starts.
8
+ */
9
+ export class RuntimeCounters {
10
+ #counts = new Map();
11
+ increment(name, labels = {}, by = 1) {
12
+ const series = this.#counts.get(name) ?? new Map();
13
+ const key = labelKey(labels);
14
+ const entry = series.get(key) ?? { labels, value: 0 };
15
+ entry.value += by;
16
+ series.set(key, entry);
17
+ this.#counts.set(name, series);
18
+ }
19
+ value(name, labels = {}) { return this.#counts.get(name)?.get(labelKey(labels))?.value ?? 0; }
20
+ series(name) { return [...this.#counts.get(name)?.values() ?? []]; }
21
+ }
22
+ const escapeLabel = (value) => value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n');
23
+ const sample = (name, labels, value) => {
24
+ const entries = Object.entries(labels);
25
+ return `${name}${entries.length ? `{${entries.map(([key, label]) => `${key}="${escapeLabel(label)}"`).join(',')}}` : ''} ${Number.isFinite(value) ? value : 0}`;
26
+ };
27
+ /** A2A rate-limit refusal scopes: by client address, per peer, and the per-peer task cap. */
28
+ export const A2A_REFUSAL_SCOPES = ['ip', 'peer', 'tasks'];
29
+ /**
30
+ * The profile's metrics in the OpenMetrics text format. Gauges are read from
31
+ * the journal at scrape time; counters are this process's own.
32
+ */
33
+ export function renderMetrics(source) {
34
+ const now = source.now?.() ?? Date.now();
35
+ const lines = [];
36
+ const family = (name, type, help, samples) => {
37
+ lines.push(`# TYPE ${name} ${type}`, `# HELP ${name} ${help}`);
38
+ for (const item of samples)
39
+ lines.push(sample(`${name}${item.suffix ?? ''}`, item.labels ?? {}, item.value));
40
+ };
41
+ const db = source.store.db;
42
+ const tables = new Set(z.array(z.object({ name: z.string() })).parse(db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all()).map(row => row.name));
43
+ /** Rows per state of a journal table; a table this profile never created (no jobs, no A2A) counts nothing. */
44
+ const counts = (table) => tables.has(table)
45
+ ? z.array(z.object({ key: z.string(), count: z.number().int() })).parse(db.prepare(`SELECT state AS key, count(*) AS count FROM ${table} GROUP BY state`).all()) : [];
46
+ family('ardent_build', 'info', 'Ardent version, profile and selected backend', [{ labels: { version: source.version, profile: source.profile, backend: source.backend }, value: 1, suffix: '_info' }]);
47
+ family('ardent_process_start_time_seconds', 'gauge', 'When this gateway process started (Unix time)', [{ value: source.startedMs / 1000 }]);
48
+ const tasks = source.store.taskCounts();
49
+ const states = ['queued', 'running', 'input_required', 'completed', 'partial', 'failed', 'cancelled', 'unknown'];
50
+ family('ardent_tasks', 'gauge', 'Tasks in the journal, by state', states.map(state => ({ labels: { state }, value: tasks.by_state[state] ?? 0 })));
51
+ const recovery = source.store.executionState.counts();
52
+ family('ardent_recovery_tasks', 'gauge', 'Tasks in each open execution recovery status', Object.entries(recovery).map(([status, value]) => ({ labels: { status }, value })));
53
+ const windows = counts('job_windows');
54
+ family('ardent_job_windows', 'gauge', 'Scheduled job windows in the journal, by state', ['queued', 'running', 'retry', 'completed', 'failed', 'unknown', 'superseded']
55
+ .map(state => ({ labels: { state }, value: windows.find(row => row.key === state)?.count ?? 0 })));
56
+ const deliveries = counts('channel_deliveries');
57
+ family('ardent_channel_deliveries', 'gauge', 'Channel replies in the journal, by delivery state', ['queued', 'sent', 'failed', 'unknown']
58
+ .map(state => ({ labels: { state }, value: deliveries.find(row => row.key === state)?.count ?? 0 })));
59
+ const push = counts('a2a_push_deliveries');
60
+ family('ardent_a2a_push_deliveries', 'gauge', 'A2A push notifications in the journal, by delivery state', ['queued', 'sent', 'failed', 'unknown']
61
+ .map(state => ({ labels: { state }, value: push.find(row => row.key === state)?.count ?? 0 })));
62
+ family('ardent_a2a_rate_limited', 'counter', 'A2A requests refused with 429 since the process started, by limit', A2A_REFUSAL_SCOPES
63
+ .map(scope => ({ labels: { scope }, value: source.counters.value('a2a_rate_limited', { scope }), suffix: '_total' })));
64
+ // Mattermost catch-up: how old each channel's settled boundary and its last finished walk are.
65
+ const catchup = source.store.catchup.status('mattermost');
66
+ const boundaries = new Map((tables.has('channel_cursors') ? z.array(z.object({ key: z.string(), value: z.string() })).parse(db.prepare("SELECT key,value FROM channel_cursors WHERE key LIKE 'mattermost:%:%:last_ms'").all()) : [])
67
+ .map(row => [row.key.split(':').slice(1, 3).join(':'), Number(row.value)]));
68
+ family('ardent_mattermost_catchup_boundary_age_seconds', 'gauge', 'Seconds since the newest Mattermost post up to which every older post is settled, per channel', catchup.flatMap(item => { const at = boundaries.get(`${item.account}:${item.channel}`); return at && Number.isFinite(at) ? [{ labels: { account: item.account, channel: item.channel }, value: Math.max(0, (now - at) / 1000) }] : []; }));
69
+ family('ardent_mattermost_catchup_walk_age_seconds', 'gauge', 'Seconds since the last finished Mattermost catch-up walk, per channel', catchup.flatMap(item => item.finished_ms === null ? [] : [{ labels: { account: item.account, channel: item.channel, state: item.state }, value: Math.max(0, (now - item.finished_ms) / 1000) }]));
70
+ family('ardent_mattermost_catchup_gaps', 'gauge', 'Recorded Mattermost history gaps catch-up could not walk, per channel', catchup.map(item => ({ labels: { account: item.account, channel: item.channel }, value: item.gaps })));
71
+ lines.push('# EOF');
72
+ return `${lines.join('\n')}\n`;
73
+ }
package/dist/missions.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { z } from 'zod';
2
2
  import { ExecutionInput } from './execution.js';
3
3
  import { TEAM_VERSION, CoreTeamAction, TeamMission, TeamResult, validateTeamResult } from './team-contract.js';
4
+ import { invalidRequest } from './errors.js';
4
5
  /** Bound on the combined text of a mission's context items. */
5
6
  export const MAX_CONTEXT_ITEM_BYTES = 64 * 1024;
6
7
  const MISSION_EVENT = 'mission';
@@ -24,7 +25,7 @@ export const MissionRecord = z.object({ mission: TeamMission, context_items: z.a
24
25
  /** Accept a mission as a durable `mission` task. The mission and its context are journaled atomically with the task. */
25
26
  export function acceptMission(accept, store, input, nowMs = Date.now()) {
26
27
  if (input.mission.deadline * 1000 <= nowMs)
27
- throw new Error('Mission deadline must be in the future');
28
+ throw invalidRequest('Mission deadline must be in the future');
28
29
  const record = { mission: input.mission, context_items: input.context_items ?? [], labels: input.labels ?? {} };
29
30
  return accept({ prompt: input.objective, ...(input.session_id ? { sessionId: input.session_id } : {}), idempotencyKey: input.idempotency_key,
30
31
  deadlineMs: input.mission.deadline * 1000, content: record, onAccepted: task => store.append(task.id, MISSION_EVENT, record) });
@@ -2,6 +2,7 @@ import { z } from 'zod';
2
2
  import { bodyLimit } from 'hono/body-limit';
3
3
  import { pluginContext } from './plugins.js';
4
4
  import { TokenBucketLimiter } from './a2a-rate-limit.js';
5
+ import { legacyPluginError } from './errors.js';
5
6
  const capacity = z.object({ perMinute: z.number().int().min(1).max(6000), burst: z.number().int().min(1).max(1200) }).strict();
6
7
  /** Hono's route precedence must never let an extension shadow an existing handler. */
7
8
  function overlaps(a, b) {
@@ -46,6 +47,14 @@ export function mountPluginHttp(app, runtime, env, jobs) {
46
47
  if (!result.allowed)
47
48
  return c.json({ error: { code: 'RATE_LIMITED' } }, 429, { 'Retry-After': String(result.retryAfterSeconds), 'Cache-Control': 'no-store' });
48
49
  return next();
49
- }, bodyLimit({ maxSize: 1_048_576, onError: c => c.json({ error: { code: 'BODY_TOO_LARGE' } }, 413) }), route.handler);
50
+ }, bodyLimit({ maxSize: 1_048_576, onError: c => c.json({ error: { code: 'BODY_TOO_LARGE' } }, 413) }), async (c, next) => {
51
+ // A plugin error without a type answers as it did before typed errors.
52
+ try {
53
+ return await route.handler(c, next);
54
+ }
55
+ catch (error) {
56
+ throw legacyPluginError(error);
57
+ }
58
+ });
50
59
  }
51
60
  }
@@ -26,3 +26,5 @@ export { Database as SqliteDatabase } from './sqlite.js';
26
26
  export type SqliteStatement = ReturnType<import('./sqlite.js').Database['prepare']>;
27
27
  export * from './team-contract.js';
28
28
  export { ARDENT_VERSION } from './version.js';
29
+ /** Typed errors: a plugin route that throws one answers with its status and code. */
30
+ export { HiveError, isHiveError, ErrorCode, invalidRequest, notFound, conflict, dependencyUnavailable, notAcceptingWork } from './errors.js';
@@ -25,3 +25,5 @@ export * from './job-engine.js';
25
25
  export { Database as SqliteDatabase } from './sqlite.js';
26
26
  export * from './team-contract.js';
27
27
  export { ARDENT_VERSION } from './version.js';
28
+ /** Typed errors: a plugin route that throws one answers with its status and code. */
29
+ export { HiveError, isHiveError, ErrorCode, invalidRequest, notFound, conflict, dependencyUnavailable, notAcceptingWork } from './errors.js';
@@ -0,0 +1,64 @@
1
+ import type { ArtifactStore } from './artifacts.js';
2
+ import type { TaskStore } from './store.js';
3
+ /** A task that ended this way can be pruned; queued, running, input_required and unknown tasks never are. */
4
+ export declare const PRUNABLE_STATES: readonly ["completed", "partial", "failed", "cancelled"];
5
+ /** The shortest retention: younger work stays, so channel replay protection outlives any catch-up window. */
6
+ export declare const MIN_RETENTION_MS: number;
7
+ export type PruneOptions = {
8
+ /** Prune tasks that last changed before now minus this. At least one day. */
9
+ olderThanMs: number;
10
+ dryRun?: boolean;
11
+ /** Tasks per pass; the prune runs passes until none is left. Default 500. */
12
+ batch?: number;
13
+ now?: number;
14
+ };
15
+ export type PruneResult = {
16
+ dry_run: boolean;
17
+ cutoff: string;
18
+ tasks: number;
19
+ rows: Record<string, number>;
20
+ artifacts: {
21
+ deleted: number;
22
+ retained: number;
23
+ };
24
+ };
25
+ /**
26
+ * Delete old finished tasks and everything that belongs only to them: events,
27
+ * execution state, settled tool invocations and recovery, settled channel
28
+ * deliveries and their inbound updates, and artifact manifests. Artifact bytes
29
+ * go when no manifest or kept task's journal still names them. Unknown, held,
30
+ * queued, running and paused work, tasks with (immutable) session messages,
31
+ * and any task another record refers to, are kept.
32
+ */
33
+ export declare function pruneJournal(store: TaskStore, artifacts: ArtifactStore, options: PruneOptions): Promise<PruneResult>;
34
+ /** `90d`, `36h` or `45m`. */
35
+ export declare function parseDuration(text: string): number;
36
+ export type BackupResult = {
37
+ format: 'ardent-backup';
38
+ version: 1;
39
+ ardent_version: string;
40
+ created_at: string;
41
+ directory: string;
42
+ journal: {
43
+ file: string;
44
+ bytes: number;
45
+ sha256: string;
46
+ integrity: 'ok';
47
+ idle: boolean;
48
+ };
49
+ artifacts: {
50
+ included: boolean;
51
+ files: number;
52
+ bytes: number;
53
+ };
54
+ };
55
+ /**
56
+ * Copy the profile journal with SQLite's online backup API: a consistent copy
57
+ * while the gateway keeps running. The directory must be new (or empty) and is
58
+ * private. With `artifacts`, the content-addressed artifact files are copied too.
59
+ * Configuration, identity and `.env` are not copied.
60
+ */
61
+ export declare function backupProfile(profileDir: string, target: string, options?: {
62
+ artifacts?: boolean;
63
+ now?: () => number;
64
+ }): Promise<BackupResult>;
@@ -0,0 +1,239 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { createReadStream } from 'node:fs';
3
+ import { chmod, cp, mkdir, readdir, rm, stat, writeFile } from 'node:fs/promises';
4
+ import { join, resolve } from 'node:path';
5
+ import { z } from 'zod';
6
+ import { inspectJournal } from './journal.js';
7
+ import { Database } from './sqlite.js';
8
+ import { invalidRequest } from './errors.js';
9
+ import { ARDENT_VERSION } from './version.js';
10
+ /** A task that ended this way can be pruned; queued, running, input_required and unknown tasks never are. */
11
+ export const PRUNABLE_STATES = ['completed', 'partial', 'failed', 'cancelled'];
12
+ /** The shortest retention: younger work stays, so channel replay protection outlives any catch-up window. */
13
+ export const MIN_RETENTION_MS = 24 * 3_600_000;
14
+ /**
15
+ * Tables whose rows belong to one task and go with it. Any other table that
16
+ * names a task (a foreign key to tasks, or a `*task_id` / `operation_id`
17
+ * column) keeps the task: A2A, team, job and future records are never orphaned.
18
+ */
19
+ const OWNED = {
20
+ events: 'task_id', task_admission: 'task_id', task_execution: 'task_id', execution_state: 'task_id',
21
+ tool_invocations: 'task_id', task_recovery: 'task_id', artifact_manifests: 'task_id',
22
+ channel_deliveries: 'task_id', channel_inbound: 'task_id',
23
+ };
24
+ const ids = z.array(z.object({ id: z.string() }));
25
+ /** Columns of other tables that name a task, found from the schema so a new table is covered without a change here. */
26
+ function referencingColumns(db) {
27
+ const tables = z.array(z.object({ name: z.string() })).parse(db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'").all()).map(row => row.name);
28
+ const result = [];
29
+ for (const table of tables) {
30
+ if (table === 'tasks' || table in OWNED)
31
+ continue;
32
+ const quoted = `"${table.replace(/"/g, '""')}"`;
33
+ const columns = z.array(z.object({ name: z.string() })).parse(db.prepare(`PRAGMA table_info(${quoted})`).all()).map(row => row.name);
34
+ const keys = z.array(z.object({ table: z.string(), from: z.string() })).parse(db.prepare(`PRAGMA foreign_key_list(${quoted})`).all())
35
+ .filter(key => key.table === 'tasks').map(key => key.from);
36
+ for (const column of new Set([...keys, ...columns.filter(name => /task_id$/.test(name) || name === 'operation_id')]))
37
+ result.push({ table: quoted, column: `"${column}"` });
38
+ }
39
+ return result;
40
+ }
41
+ /** One page of prunable tasks after `after` (oldest first), minus any another record still needs. */
42
+ function candidates(db, cutoff, limit, after) {
43
+ const has = (table) => db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?").get(table) !== undefined;
44
+ const guards = [];
45
+ if (has('task_recovery'))
46
+ guards.push("NOT EXISTS (SELECT 1 FROM task_recovery r WHERE r.task_id=t.id AND r.status NOT IN ('resumed','resolved'))", 'NOT EXISTS (SELECT 1 FROM task_recovery r WHERE r.continuation_task_id=t.id)');
47
+ if (has('tool_invocations'))
48
+ guards.push("NOT EXISTS (SELECT 1 FROM tool_invocations i WHERE i.task_id=t.id AND i.state IN ('dispatched','failed_unknown','unknown'))");
49
+ if (has('channel_deliveries'))
50
+ guards.push("NOT EXISTS (SELECT 1 FROM channel_deliveries d WHERE d.task_id=t.id AND d.state NOT IN ('sent','failed'))");
51
+ // Session transcripts are immutable and context checkpoints rest on them: a task with session messages stays.
52
+ if (has('session_messages'))
53
+ guards.push('NOT EXISTS (SELECT 1 FROM session_messages m WHERE m.task_id=t.id)');
54
+ for (const { table, column } of referencingColumns(db))
55
+ guards.push(`NOT EXISTS (SELECT 1 FROM ${table} x WHERE x.${column}=t.id)`);
56
+ const page = z.array(z.object({ id: z.string(), updated_ms: z.number().int() })).parse(db.prepare(`SELECT t.id, t.updated_ms FROM tasks t
57
+ WHERE t.state IN (${PRUNABLE_STATES.map(() => '?').join(',')}) AND t.updated_ms < ?
58
+ ${after ? 'AND (t.updated_ms > ? OR (t.updated_ms = ? AND t.id > ?))' : ''} ORDER BY t.updated_ms, t.id LIMIT ?`)
59
+ .all(...PRUNABLE_STATES, cutoff, ...(after ? [after.updated_ms, after.updated_ms, after.id] : []), limit));
60
+ const tail = page.at(-1);
61
+ const last = tail ? { updated_ms: tail.updated_ms, id: tail.id } : undefined;
62
+ if (!page.length)
63
+ return { ids: [], last, scanned: 0 };
64
+ const placeholders = page.map(() => '?').join(',');
65
+ const rows = ids.parse(db.prepare(`SELECT t.id FROM tasks t WHERE t.id IN (${placeholders}) ${guards.map(guard => `AND ${guard}`).join(' ')}`).all(...page.map(row => row.id))).map(row => row.id);
66
+ if (!has('task_execution') || !rows.length)
67
+ return { ids: rows, last, scanned: page.length };
68
+ // A kept task's ancestry (parent or root) keeps the tasks it names.
69
+ const selected = new Set(rows);
70
+ for (let changed = true; changed;) {
71
+ changed = false;
72
+ for (const id of [...selected]) {
73
+ const placeholders = [...selected].map(() => '?').join(',');
74
+ const named = db.prepare(`SELECT 1 FROM task_execution WHERE task_id NOT IN (${placeholders}) AND (instr(coalesce(parent_ref,''), ?)>0 OR instr(root_ref, ?)>0) LIMIT 1`)
75
+ .get(...selected, id, id);
76
+ if (named) {
77
+ selected.delete(id);
78
+ changed = true;
79
+ }
80
+ }
81
+ }
82
+ return { ids: [...selected], last, scanned: page.length };
83
+ }
84
+ /**
85
+ * Delete old finished tasks and everything that belongs only to them: events,
86
+ * execution state, settled tool invocations and recovery, settled channel
87
+ * deliveries and their inbound updates, and artifact manifests. Artifact bytes
88
+ * go when no manifest or kept task's journal still names them. Unknown, held,
89
+ * queued, running and paused work, tasks with (immutable) session messages,
90
+ * and any task another record refers to, are kept.
91
+ */
92
+ export async function pruneJournal(store, artifacts, options) {
93
+ if (!Number.isSafeInteger(options.olderThanMs) || options.olderThanMs < MIN_RETENTION_MS)
94
+ throw invalidRequest('Retention must be at least one day');
95
+ const now = options.now ?? Date.now();
96
+ const cutoff = now - options.olderThanMs;
97
+ const db = store.db;
98
+ const rows = {};
99
+ const add = (table, count) => { rows[table] = (rows[table] ?? 0) + count; };
100
+ const freed = new Set();
101
+ let tasks = 0;
102
+ const batch = Math.max(1, Math.min(options.batch ?? 500, 5000));
103
+ // Pages move forward by (updated_ms, id), so a kept task is looked at once and deleted ones never come back.
104
+ for (let after, scanned = batch; scanned === batch;) {
105
+ const page = candidates(db, cutoff, batch, after);
106
+ ({ last: after, scanned } = page);
107
+ const ids = page.ids;
108
+ if (!ids.length)
109
+ continue;
110
+ tasks += ids.length;
111
+ if (options.dryRun) {
112
+ add('tasks', ids.length);
113
+ continue;
114
+ }
115
+ db.transaction(() => {
116
+ const placeholders = ids.map(() => '?').join(',');
117
+ const has = (table) => db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?").get(table) !== undefined;
118
+ if (has('artifact_manifests')) {
119
+ for (const row of z.array(z.object({ sha256: z.string() })).parse(db.prepare(`SELECT DISTINCT sha256 FROM artifact_manifests WHERE task_id IN (${placeholders})`).all(...ids)))
120
+ freed.add(row.sha256);
121
+ if (has('artifact_renditions'))
122
+ add('artifact_renditions', Number(db.prepare(`DELETE FROM artifact_renditions WHERE rendition_artifact_id IN (SELECT artifact_id FROM artifact_manifests WHERE task_id IN (${placeholders}))`).run(...ids).changes));
123
+ }
124
+ for (const [table, column] of Object.entries(OWNED))
125
+ if (has(table))
126
+ add(table, Number(db.prepare(`DELETE FROM ${table} WHERE ${column} IN (${placeholders})`).run(...ids).changes));
127
+ add('tasks', Number(db.prepare(`DELETE FROM tasks WHERE id IN (${placeholders})`).run(...ids).changes));
128
+ })();
129
+ }
130
+ const result = { deleted: 0, retained: 0 };
131
+ for (const sha of freed) {
132
+ const manifest = db.prepare('SELECT 1 FROM artifact_manifests WHERE sha256=? LIMIT 1').get(sha);
133
+ const rendition = db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='artifact_renditions'").get() !== undefined
134
+ && db.prepare('SELECT 1 FROM artifact_renditions WHERE original_sha256=? OR rendition_sha256=? LIMIT 1').get(sha, sha) !== undefined;
135
+ const journaled = db.prepare('SELECT 1 FROM events WHERE instr(detail_json, ?)>0 LIMIT 1').get(sha);
136
+ if (manifest || rendition || journaled) {
137
+ result.retained++;
138
+ continue;
139
+ }
140
+ await artifacts.delete(sha).catch(() => undefined);
141
+ result.deleted++;
142
+ }
143
+ return { dry_run: options.dryRun ?? false, cutoff: new Date(cutoff).toISOString(), tasks, rows, artifacts: result };
144
+ }
145
+ /** `90d`, `36h` or `45m`. */
146
+ export function parseDuration(text) {
147
+ const match = /^(\d{1,6})([dhm])$/.exec(text.trim());
148
+ const unit = match?.[2] === 'd' ? 86_400_000 : match?.[2] === 'h' ? 3_600_000 : match?.[2] === 'm' ? 60_000 : undefined;
149
+ if (!match || unit === undefined)
150
+ throw invalidRequest('Use a duration such as 90d, 36h or 45m');
151
+ return Number(match[1]) * unit;
152
+ }
153
+ async function sha256File(path) {
154
+ const hash = createHash('sha256');
155
+ for await (const chunk of createReadStream(path))
156
+ hash.update(z.instanceof(Buffer).parse(chunk));
157
+ return hash.digest('hex');
158
+ }
159
+ async function tree(path) {
160
+ let files = 0, bytes = 0;
161
+ for (const entry of await readdir(path, { withFileTypes: true }).catch(() => [])) {
162
+ const child = join(path, entry.name);
163
+ if (entry.isDirectory()) {
164
+ const sub = await tree(child);
165
+ files += sub.files;
166
+ bytes += sub.bytes;
167
+ }
168
+ else if (entry.isFile()) {
169
+ files++;
170
+ bytes += (await stat(child)).size;
171
+ await chmod(child, 0o600);
172
+ }
173
+ }
174
+ return { files, bytes };
175
+ }
176
+ /**
177
+ * Copy the profile journal with SQLite's online backup API: a consistent copy
178
+ * while the gateway keeps running. The directory must be new (or empty) and is
179
+ * private. With `artifacts`, the content-addressed artifact files are copied too.
180
+ * Configuration, identity and `.env` are not copied.
181
+ */
182
+ export async function backupProfile(profileDir, target, options = {}) {
183
+ const directory = resolve(target);
184
+ const existing = await readdir(directory).catch((error) => {
185
+ if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT')
186
+ return undefined;
187
+ throw error;
188
+ });
189
+ if (existing && existing.length)
190
+ throw invalidRequest('The backup directory exists and is not empty');
191
+ const created = existing === undefined;
192
+ await mkdir(directory, { recursive: true, mode: 0o700 });
193
+ await chmod(directory, 0o700);
194
+ const source = join(profileDir, 'state', 'ardent.sqlite');
195
+ const file = join(directory, 'ardent.sqlite');
196
+ try {
197
+ const db = new Database(source, { fileMustExist: true });
198
+ try {
199
+ await db.backup(file);
200
+ }
201
+ finally {
202
+ db.close();
203
+ }
204
+ await chmod(file, 0o600);
205
+ const copy = new Database(file, { readonly: true, fileMustExist: true });
206
+ try {
207
+ const check = z.object({ integrity_check: z.string() }).parse(copy.prepare('PRAGMA integrity_check').get());
208
+ if (check.integrity_check !== 'ok')
209
+ throw new Error('The backup copy failed its integrity check');
210
+ }
211
+ finally {
212
+ copy.close();
213
+ }
214
+ const inspected = await inspectJournal(file);
215
+ let artifacts = { included: false, files: 0, bytes: 0 };
216
+ if (options.artifacts) {
217
+ // Artifact files are immutable and named by digest, so a plain copy is consistent.
218
+ await cp(join(profileDir, 'artifacts'), join(directory, 'artifacts'), { recursive: true, errorOnExist: true, force: false }).catch((error) => {
219
+ if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT')
220
+ return;
221
+ throw error;
222
+ });
223
+ artifacts = { included: true, ...await tree(join(directory, 'artifacts')) };
224
+ }
225
+ const result = { format: 'ardent-backup', version: 1, ardent_version: ARDENT_VERSION, created_at: new Date(options.now?.() ?? Date.now()).toISOString(), directory,
226
+ journal: { file: 'ardent.sqlite', bytes: (await stat(file)).size, sha256: await sha256File(file), integrity: 'ok', idle: inspected.idle }, artifacts };
227
+ await writeFile(join(directory, 'backup.json'), `${JSON.stringify(result, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
228
+ return result;
229
+ }
230
+ catch (error) {
231
+ // Never leave a partial backup that looks complete.
232
+ if (created)
233
+ await rm(directory, { recursive: true, force: true });
234
+ else
235
+ for (const entry of await readdir(directory).catch(() => []))
236
+ await rm(join(directory, entry), { recursive: true, force: true });
237
+ throw error;
238
+ }
239
+ }
package/dist/runtime.d.ts CHANGED
@@ -12,6 +12,9 @@ import { DevelopmentRecords } from './development.js';
12
12
  import { type PreviewSubmit } from './preview.js';
13
13
  import { type MissionSubmit } from './missions.js';
14
14
  import { type ExecutionAcceptance, type ExecutionContext } from './execution.js';
15
+ import { HiveError } from './errors.js';
16
+ import { type Logger } from './log.js';
17
+ import { RuntimeCounters } from './metrics.js';
15
18
  /** A finished task. A mission also carries its validated TeamResult, which is the task's stored result. */
16
19
  export type RunResult = {
17
20
  task: Task;
@@ -37,7 +40,10 @@ export type TaskEvidence = {
37
40
  export declare class RecoveryHeldError extends Error {
38
41
  }
39
42
  /** A recovery decision that is not valid now (HTTP 409). */
40
- export declare class RecoveryConflictError extends Error {
43
+ /** No recovery decision, or not this one, is valid now (HTTP 409 CONFLICT). */
44
+ export declare class RecoveryConflictError extends HiveError {
45
+ readonly name: string;
46
+ constructor(message: string);
41
47
  }
42
48
  export declare class ArdentRuntime {
43
49
  #private;
@@ -60,6 +66,16 @@ export declare class ArdentRuntime {
60
66
  held: string[];
61
67
  };
62
68
  get draining(): boolean;
69
+ /**
70
+ * Operational log lines of this runtime and the components it owns (channels,
71
+ * A2A push, plugin hooks). Silent unless the host sets one; the gateway sets
72
+ * `ardentLogger({ requestContext: false })`.
73
+ */
74
+ logger: Logger;
75
+ /** In-process counters for GET /api/v1/metrics (A2A rate-limit refusals). */
76
+ readonly counters: RuntimeCounters;
77
+ /** When this runtime was created. */
78
+ readonly startedMs: number;
63
79
  get plugins(): readonly ArdentPlugin[];
64
80
  /** The instance part of this runtime's qualified references (`ARDENT_INSTANCE_REF`, else `local.<profile>`). */
65
81
  readonly instanceRef: string;