@hivemagnus/ardent 3.2.1 → 3.3.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.
package/README.md CHANGED
@@ -90,10 +90,11 @@ ardent gateway run # management API, A2A, channels, jobs
90
90
  ### Under Magnus and in the Hive suite
91
91
 
92
92
  Each [Magnus](https://github.com/ChefTaco/magnus) release is built and tested
93
- against one pinned Ardent version: Magnus 3.1.1 pins Ardent 3.1.3. Every Ardent
94
- release is followed by a Magnus release that moves the pin, regenerates its
95
- Ardent contract and updates the node agent; until then, managed nodes keep the
96
- pinned version.
93
+ against one pinned Ardent version; Magnus's CHANGELOG names it, and
94
+ `npm run ardent:latest:check` in a Magnus checkout fails while that pin is older
95
+ than the latest Ardent release. Every Ardent release is followed by a Magnus
96
+ release that moves the pin, regenerates its Ardent contract and updates the
97
+ node agent; until then, managed nodes keep the pinned version.
97
98
 
98
99
  Magnus installs that pinned package on a node and creates profiles with its
99
100
  **New Agent** workflow, which always enables HiveMem. In a
@@ -136,6 +137,60 @@ The default target is the profile's loopback management listener; an optional
136
137
  Acceptance executes no model generation or tools. Verify scoped inference,
137
138
  memory, skills and channel workflows separately before enabling consumers.
138
139
 
140
+ ### Journal quiescence
141
+
142
+ Backup, snapshot and upgrade tools need to know whether a stopped profile's
143
+ SQLite journal (`state/ardent.sqlite`) still holds work. Ardent owns that
144
+ answer, because it owns the schema; a tool should ask Ardent instead of keeping
145
+ its own list of tables.
146
+
147
+ ```bash
148
+ ardent --profile-path DIR journal status --json # or: journal status --db FILE
149
+ ardent journal policy # the table classification
150
+ ```
151
+
152
+ `journal status` is read-only and needs neither a valid configuration nor
153
+ plugins. It copies the database and its WAL to a private temporary directory,
154
+ verifies the copy by digest, and inspects it there, so committed but
155
+ uncheckpointed work in the WAL is counted and no byte of the profile changes.
156
+ It fails if the files change during inspection, which means a gateway is
157
+ writing. It prints:
158
+
159
+ ```json
160
+ { "ardent_version": "3.3.0", "profile": "assistant", "policy_version": 1,
161
+ "idle": true, "active": 0, "unknown": 0, "unsupported": 0,
162
+ "tables": [{ "name": "tasks", "kind": "state", "active": 0, "unknown": 0, "unsupported": 0 }] }
163
+ ```
164
+
165
+ | Count | Meaning |
166
+ |---|---|
167
+ | `active` | Work a gateway start would run, resume or send: queued or running tasks, deliveries and job windows, dispatched tool calls, recovery ready to resume, pending artifact imports, unbound A2A receipts, unsettled team-child claims. |
168
+ | `unknown` | Work whose outcome is uncertain and needs reconciliation or an operator decision (`unknown` tasks, deliveries and job windows, `failed_unknown` tool calls, recovery `awaiting_decision` or `unsupported`). |
169
+ | `unsupported` | Anything this Ardent version does not recognize: a table it does not classify, a virtual table, a missing or unexpected `state`/`status` column, an unrecognized state value, an empty file. The closed admission fence also counts here, because a temporary snapshot must never clear it. Tables with problems list them in `problems`. |
170
+
171
+ `idle` is true only when all three are zero. It describes the journal, not
172
+ whether a gateway is running: check that the service is stopped separately.
173
+ An integrity or foreign-key check failure is an error, not a count.
174
+
175
+ The same inspector is a library entry point that loads no runtime, store,
176
+ plugin or job handler:
177
+
178
+ ```ts
179
+ import { inspectJournal, inspectJournalFile, journalPolicy, JOURNAL_POLICY_VERSION } from '@hivemagnus/ardent/journal';
180
+
181
+ const status = await inspectJournal('/path/to/profile/state/ardent.sqlite'); // private copy, as the CLI does
182
+ const staged = inspectJournalFile('/private/copy/ardent.sqlite'); // a copy you already own
183
+ ```
184
+
185
+ `journalPolicy()` (and `JOURNAL_TABLES`) classifies every table as `state`
186
+ (with its `column` and its `active`, `uncertain` and `terminal` values),
187
+ `passive`, `ledger` or `special` (with a rule described in `description`).
188
+ `policy_version` changes only when the format or the counting rules change;
189
+ adding a table or a state value does not change it. A release that adds a table
190
+ classifies it in the same change (a test fails otherwise), so inspect a journal
191
+ with the Ardent version that wrote it or a newer one. An older Ardent reports a
192
+ newer table as `unsupported` rather than guessing.
193
+
139
194
  ## Configuration
140
195
 
141
196
  `config.yaml` (schema 1) is validated strictly; unknown keys are rejected. A
package/dist/api.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { Hono } from 'hono';
2
+ import { type Logger } from './log.js';
2
3
  import { type LoadedConfig } from './config.js';
3
4
  import type { ArdentRuntime } from './runtime.js';
4
5
  import type { JobEngine } from './job-engine.js';
@@ -12,4 +13,5 @@ export declare function ardentOpenApi(): object;
12
13
  export declare function createArdentApi(runtime: ArdentRuntime, loaded: LoadedConfig, env?: NodeJS.ProcessEnv, jobEngine?: JobEngine, options?: {
13
14
  envFile?: string;
14
15
  artifactTransfers?: ArtifactTransfers;
16
+ logger?: Logger;
15
17
  }): Hono;
package/dist/api.js CHANGED
@@ -3,6 +3,7 @@ import { Hono } from 'hono';
3
3
  import { streamSSE } from 'hono/streaming';
4
4
  import { z } from 'zod';
5
5
  import { ARDENT_VERSION } from './version.js';
6
+ import { ardentLogger } from './log.js';
6
7
  import { ConfigSchema } from './config.js';
7
8
  import { isConfigNotice, runtimeProblems, saveConfig, loadConfig, resolveReference, parseConfig } from './config.js';
8
9
  import { listSkills, setSkillEnabled } from './skills.js';
@@ -159,7 +160,9 @@ export function ardentOpenApi() {
159
160
  get: { operationId: 'listArtifactImports', security: [{ bearerAuth: [] }], parameters: [{ in: 'query', name: 'limit', schema: { type: 'integer', minimum: 1, maximum: 100, default: 50 } }], responses: { '200': jsonResponse('Recent imports, newest first', z.object({ imports: z.array(ArtifactImportSchema) })) } }
160
161
  },
161
162
  '/api/v1/artifacts/imports/{id}': { get: { operationId: 'getArtifactImport', description: 'Import progress. error.code is TRANSFER_REQUIRES_V2 (peer lacks urn:hive:artifact-transfer:2 and the artifact is over 2 MiB), DIGEST_MISMATCH (bytes discarded; reissue to retry), TRANSFER_TOO_LARGE, TRANSFER_SOURCE_GONE, TRANSFER_INTERRUPTED (retries exhausted; reissue resumes) or another stable code.', security: [{ bearerAuth: [] }], parameters: [{ in: 'path', name: 'id', required: true, schema: { type: 'string', pattern: '^[a-f0-9]{32}$' } }], responses: { '200': jsonResponse('Import state', ArtifactImportSchema), '404': { description: 'Import absent' } } } },
162
- '/api/v1/status': { get: { operationId: 'getOperationalStatus', security: [{ bearerAuth: [] }], responses: { '200': jsonResponse('Active profile summary; capabilities.artifact_transfer is the highest artifact transfer version served', z.object({ version: z.string(), profile: z.string(), backend: z.enum(['llamacpp', 'codex']), tasks: z.number().int(), channels: z.object({ mattermost: z.object({ catchup: z.array(CatchupStatusSchema).describe('Latest missed-post catch-up walk per Mattermost channel') }) }), capabilities: z.object({ artifact_transfer: z.literal(2) }), recovery: RecoveryCounts.optional() })) } } },
163
+ '/api/v1/status': { get: { operationId: 'getOperationalStatus', security: [{ bearerAuth: [] }], responses: { '200': jsonResponse('Active profile summary; capabilities.artifact_transfer is the highest artifact transfer version served', z.object({ version: z.string(), profile: z.string(), backend: z.enum(['llamacpp', 'codex']), tasks: z.number().int().describe('Number of tasks in the journal'),
164
+ task_states: z.record(z.string(), z.number().int()).optional().describe('Number of tasks in each state'), channels: z.object({ mattermost: z.object({ catchup: z.array(CatchupStatusSchema).describe('Latest missed-post catch-up walk per Mattermost channel') }) }), capabilities: z.object({ artifact_transfer: z.literal(2) }), recovery: RecoveryCounts.optional(),
165
+ jobs: z.object({ last_tick_error: z.object({ message: z.string(), at: z.string().datetime() }).nullable().describe('Last scheduler tick failure the gateway recorded, or null') }).optional() })) } } },
163
166
  '/api/v1/jobs/definitions/status': { get: { operationId: 'getJobDefinitionsStatus', security: [{ bearerAuth: [] }], responses: { '200': { description: 'Active profile job definition revision, digest, and redacted window status' }, '503': { description: 'Job engine unavailable' } } } },
164
167
  '/api/v1/profile': { get: { operationId: 'getProfile', security: [{ bearerAuth: [] }], responses: { '200': jsonResponse('Profile identity and path', z.object({ profile: z.string(), name: z.string(), product: z.string(), timezone: z.string(), path: z.string() })) } } },
165
168
  '/api/v1/config': { get: { operationId: 'getConfig', security: [{ bearerAuth: [] }], responses: { '200': jsonResponse('Raw YAML and revision; secrets remain references', z.object({ revision: z.string(), text: z.string() })) } }, put: { operationId: 'saveConfig', security: [{ bearerAuth: [] }], requestBody: { required: true, content: { 'application/json': { schema: jsonSchema(ConfigEdit) } } }, responses: { '200': jsonResponse('Saved; activation required', z.object({ revision: z.string(), activation_required: z.boolean() })), '409': { description: 'Revision conflict' } } } },
@@ -192,6 +195,7 @@ export function ardentOpenApi() {
192
195
  */
193
196
  export function createArdentApi(runtime, loaded, env = process.env, jobEngine, options = {}) {
194
197
  const app = new Hono();
198
+ const logger = options.logger ?? ardentLogger();
195
199
  const transfers = options.artifactTransfers ?? new ArtifactTransfers(runtime, env);
196
200
  let current = loaded;
197
201
  // A saved configuration requires activation; it must not rotate the live
@@ -231,6 +235,9 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
231
235
  : /unavailable|stale|unconfigured|missing|login required|wrong auth mode|CODEX_LOGIN_REQUIRED|CODEX_WRONG_AUTH_MODE|fetch failed|ECONNREFUSED|ETIMEDOUT|timeout/i.test(message) ? 503
232
236
  : error instanceof z.ZodError || error instanceof SyntaxError || /invalid|must be|exceeds|requires/i.test(message) ? 400 : 500;
233
237
  const code = status === 409 ? 'CONFLICT' : status === 404 ? 'NOT_FOUND' : status === 503 ? 'DEPENDENCY_UNAVAILABLE' : status === 400 ? 'INVALID_REQUEST' : 'INTERNAL_ERROR';
238
+ // The caller sees only a generic message; record what failed so the operator can find it.
239
+ if (status === 500)
240
+ logger.error('Unhandled management API error', { method: c.req.method, path: c.req.path, err: error });
234
241
  return c.json({ error: { code, message: status === 500 ? 'Internal request error' : message.slice(0, 500) } }, status);
235
242
  });
236
243
  app.get('/health/live', c => c.json({ status: 'live' }));
@@ -266,15 +273,19 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
266
273
  return c.json({ error: { code: 'UNAUTHORIZED', message: 'Bearer token required' } }, 401);
267
274
  return next();
268
275
  });
269
- app.get('/api/v1/status', c => c.json({ version: ARDENT_VERSION, profile: runtime.config.profile, backend: runtime.config.execution.backend, tasks: runtime.store.list(10).length,
270
- channels: { mattermost: { catchup: runtime.store.catchup.status('mattermost') } },
271
- capabilities: { artifact_transfer: 2 }, recovery: runtime.store.executionState.counts() }));
276
+ app.get('/api/v1/status', c => {
277
+ const tasks = runtime.store.taskCounts();
278
+ return c.json({ version: ARDENT_VERSION, profile: runtime.config.profile, backend: runtime.config.execution.backend,
279
+ tasks: tasks.total, task_states: tasks.by_state,
280
+ channels: { mattermost: { catchup: runtime.store.catchup.status('mattermost') } }, jobs: { last_tick_error: runtime.store.jobTickError() },
281
+ capabilities: { artifact_transfer: 2 }, recovery: runtime.store.executionState.counts() });
282
+ });
272
283
  app.get('/api/v1/jobs/definitions/status', async (c) => {
273
284
  if (!jobEngine)
274
285
  throw new Error('Job engine is unavailable');
275
286
  const status = await jobEngine.status();
276
287
  return c.json({ profile: runtime.config.profile, revision: status.active_revision,
277
- sha256: status.active_sha256, ...status });
288
+ sha256: status.active_sha256, ...status, last_tick_error: runtime.store.jobTickError() });
278
289
  });
279
290
  app.get('/api/v1/profile', c => c.json({ profile: runtime.config.profile, name: runtime.config.name, product: runtime.config.product, timezone: runtime.config.timezone, path: runtime.profileDir }));
280
291
  app.get('/api/v1/config', c => c.json({ revision: current.revision, text: current.text }));
@@ -334,8 +345,9 @@ export function createArdentApi(runtime, loaded, env = process.env, jobEngine, o
334
345
  try {
335
346
  await server.initialize();
336
347
  const auth = await server.accountStatus();
337
- if (auth !== 'chatgpt')
338
- throw new Error(auth === 'login-required' ? 'Codex ChatGPT login required' : 'Codex account uses the wrong auth mode');
348
+ // Match readiness: the account must use the configured auth mode (ChatGPT sign-in or API key).
349
+ if (auth !== runtime.config.providers.codex.auth_mode)
350
+ throw new Error(auth === 'login-required' ? 'Codex login required' : 'Codex account uses the wrong auth mode');
339
351
  return c.json({ backend: 'codex', auth_mode: auth });
340
352
  }
341
353
  finally {
package/dist/cli.js CHANGED
@@ -7,7 +7,8 @@ import { stdin, stdout, stderr } from 'node:process';
7
7
  import { z } from 'zod';
8
8
  import { ardentHome, ConfigSchema, DEFAULT_PROFILE, initProfile, loadConfig, profilePath, redactedConfig, resolveReference, runtimeProblems } from './config.js';
9
9
  import { ArdentRuntime } from './runtime.js';
10
- import { TaskStore } from './store.js';
10
+ import { JOB_TICK_ERROR_CURSOR, readJobTickError, TaskStore } from './store.js';
11
+ import { ardentLogger } from './log.js';
11
12
  import { ardentOpenApi, createArdentApi } from './api.js';
12
13
  import { serve } from '@hono/node-server';
13
14
  import { listSkills, readSkill, setSkillEnabled } from './skills.js';
@@ -35,10 +36,11 @@ import { PlainTextFilter } from './live-text.js';
35
36
  import { developmentQuery, missionSubmitInput, previewInput } from './cli-commands.js';
36
37
  import { developmentPage, DevelopmentRecords, recordSkillChange } from './development.js';
37
38
  import { ArtifactTransfers } from './artifact-transfer.js';
39
+ import { inspectJournal, journalPolicy } from './journal.js';
38
40
  function args(argv, extraValues = []) {
39
41
  const words = [];
40
42
  const options = new Map();
41
- const valued = new Set([...extraValues, 'env-file', 'profile', 'profile-path', 'api-port', 'template', 'prompt', 'prompt-file', 'idempotency-key', 'session-id', 'login-id', 'source', 'schedule-id', 'window-key', 'release-id', 'caller', 'context', 'expected-head', 'expected-policy-revision', 'mission-file', 'after', 'limit', 'kind', 'soul-file', 'identity-file', 'skills', 'model', 'peer', 'task', 'artifact', 'local-task']);
43
+ const valued = new Set([...extraValues, 'env-file', 'profile', 'profile-path', 'api-port', 'template', 'prompt', 'prompt-file', 'idempotency-key', 'session-id', 'login-id', 'source', 'schedule-id', 'window-key', 'release-id', 'caller', 'context', 'expected-head', 'expected-policy-revision', 'mission-file', 'after', 'limit', 'kind', 'soul-file', 'identity-file', 'skills', 'model', 'peer', 'task', 'artifact', 'local-task', 'db']);
42
44
  for (let i = 0; i < argv.length; i++) {
43
45
  const arg = argv[i];
44
46
  if (!arg)
@@ -75,6 +77,25 @@ async function environment(dir, explicitFile) {
75
77
  env[name] = val;
76
78
  return env;
77
79
  }
80
+ /** Read-only. A profile that has never run has no journal; doctor never fails on a journal it cannot open. */
81
+ async function profileJobTickError(dir) {
82
+ const path = join(dir, 'state', 'ardent.sqlite');
83
+ const stat = await lstat(path).catch(() => undefined);
84
+ if (!stat?.isFile() || stat.isSymbolicLink())
85
+ return null;
86
+ try {
87
+ const database = new Database(path, { readonly: true, fileMustExist: true });
88
+ try {
89
+ return readJobTickError(database);
90
+ }
91
+ finally {
92
+ database.close();
93
+ }
94
+ }
95
+ catch {
96
+ return null;
97
+ }
98
+ }
78
99
  function print(value) { stdout.write(`${JSON.stringify(value, null, 2)}\n`); }
79
100
  async function assertNoGateway(dir) {
80
101
  const lock = await readFile(join(dir, 'state', 'gateway.lock'), 'utf8').catch((error) => {
@@ -114,6 +135,8 @@ Commands:
114
135
  jobs definitions status Show installed job definitions
115
136
  context status | compact Inspect or compact a session context
116
137
  admission status | close --release-id ID Inspect or close the admission fence
138
+ journal status [--db FILE] [--json] Report whether the journal holds active, unknown or unsupported work (read-only)
139
+ journal policy Print the journal table classification
117
140
  a2a discover <peer> | call <peer> Talk to a configured A2A peer
118
141
  a2a team-card Print the Hermes team card (a2a.hermes_compat)
119
142
  openapi export Print the management OpenAPI document
@@ -155,6 +178,21 @@ async function main() {
155
178
  print(entries.filter(entry => entry.isDirectory()).map(entry => ({ name: entry.name })));
156
179
  return;
157
180
  }
181
+ if (command === 'journal') {
182
+ // Read-only and independent of config and plugins, so it also answers for a profile that cannot start.
183
+ // Output is always JSON; --json is accepted for scripts that ask for it explicitly.
184
+ if (subcommand === 'policy') {
185
+ print(journalPolicy());
186
+ return;
187
+ }
188
+ if (subcommand === 'status') {
189
+ const db = value(parsed.options, 'db');
190
+ const path = db ? resolvePath(db) : join(dir, 'state', 'ardent.sqlite');
191
+ print({ ardent_version: ARDENT_VERSION, ...(db ? {} : { profile }), ...await inspectJournal(path) });
192
+ return;
193
+ }
194
+ throw new Error('Use journal status [--db FILE] or journal policy');
195
+ }
158
196
  const loaded = await loadConfig(dir);
159
197
  const env = await environment(dir, value(parsed.options, 'env-file'));
160
198
  if (command === 'acceptance') {
@@ -260,6 +298,7 @@ async function main() {
260
298
  if (action === 'status') {
261
299
  let activeJobs = 0;
262
300
  let unknownJobs = 0;
301
+ let lastTickError = null;
263
302
  const dbPath = join(dir, 'state', 'ardent.sqlite');
264
303
  const dbStat = await lstat(dbPath);
265
304
  if (!dbStat.isFile() || dbStat.isSymbolicLink())
@@ -272,12 +311,13 @@ async function main() {
272
311
  activeJobs = count.parse(database.prepare("SELECT count(*) AS n FROM job_windows WHERE state IN ('queued','running','retry')").get()).n;
273
312
  unknownJobs = count.parse(database.prepare("SELECT count(*) AS n FROM job_windows WHERE state='unknown'").get()).n;
274
313
  }
314
+ lastTickError = readJobTickError(database);
275
315
  }
276
316
  finally {
277
317
  database.close();
278
318
  }
279
319
  print({ profile, revision: validated.definitions.revision, sha256, job_count: validated.job_count,
280
- active_jobs: activeJobs, unknown_jobs: unknownJobs, last_validation_error: null });
320
+ active_jobs: activeJobs, unknown_jobs: unknownJobs, last_validation_error: null, last_tick_error: lastTickError });
281
321
  return;
282
322
  }
283
323
  throw new Error('Use jobs definitions validate or jobs definitions status');
@@ -319,7 +359,8 @@ async function main() {
319
359
  return;
320
360
  }
321
361
  if (command === 'doctor') {
322
- print({ profile: loaded.config.profile, config_valid: true, runtime_problems: runtimeProblems(loaded.config, env), checked_at: new Date().toISOString() });
362
+ print({ profile: loaded.config.profile, config_valid: true, runtime_problems: runtimeProblems(loaded.config, env),
363
+ last_job_tick_error: await profileJobTickError(dir), checked_at: new Date().toISOString() });
323
364
  return;
324
365
  }
325
366
  if (command === 'a2a' && subcommand === 'team-card') {
@@ -500,6 +541,7 @@ async function main() {
500
541
  }
501
542
  const lockPath = join(dir, 'state', 'gateway.lock');
502
543
  const lock = await acquireGatewayLock(lockPath);
544
+ const logger = ardentLogger().child({ profile: loaded.config.profile });
503
545
  let runtime;
504
546
  let shutdownUnsettled = false;
505
547
  try {
@@ -539,7 +581,7 @@ async function main() {
539
581
  // The API reloads rotated credentials from the same file the gateway started from.
540
582
  const envFile = value(parsed.options, 'env-file');
541
583
  const artifactTransfers = new ArtifactTransfers(runtime, env);
542
- const api = createArdentApi(runtime, loaded, env, jobEngine, { ...(envFile ? { envFile: resolvePath(envFile) } : {}), artifactTransfers });
584
+ const api = createArdentApi(runtime, loaded, env, jobEngine, { ...(envFile ? { envFile: resolvePath(envFile) } : {}), artifactTransfers, logger });
543
585
  const server = serve({ fetch: api.fetch, hostname: loaded.config.api.host, port: loaded.config.api.port });
544
586
  await new Promise((resolve, reject) => { server.once('listening', resolve); server.once('error', reject); });
545
587
  // Imports a previous process left unfinished resume from their retained bytes.
@@ -559,7 +601,11 @@ async function main() {
559
601
  if (jobEngine) {
560
602
  const tickJobs = () => {
561
603
  const operation = jobEngine.tick(new Date(), deliveryAbort.signal, channelAbort.signal)
562
- .catch(error => runtime?.store.setCursor('jobs:last_error', error instanceof Error ? error.message.slice(0, 500) : 'unknown'));
604
+ .catch((error) => {
605
+ // Reported by /api/v1/status, /api/v1/jobs/definitions/status and `ardent doctor`.
606
+ runtime?.store.setCursor(JOB_TICK_ERROR_CURSOR, error instanceof Error ? error.message.slice(0, 500) : 'unknown');
607
+ logger.error('Job engine tick failed', { err: error });
608
+ });
563
609
  noticeRuns.add(operation);
564
610
  void operation.finally(() => noticeRuns.delete(operation));
565
611
  };
@@ -657,7 +703,7 @@ async function main() {
657
703
  await lock.release();
658
704
  }
659
705
  if (shutdownUnsettled) {
660
- stderr.write('Gateway shutdown left unresolved work; interrupted tasks will be marked unknown on restart.\n');
706
+ stderr.write('Gateway shutdown left unresolved work; on restart execution recovery resumes or holds interrupted tasks (they are marked unknown when execution.recovery.enabled is false).\n');
661
707
  process.exit(1);
662
708
  }
663
709
  return;
package/dist/index.d.ts CHANGED
@@ -10,3 +10,4 @@ export { createArdentApi, ardentOpenApi } from './api.js';
10
10
  export { JobEngine, validateJobDefinitions, type JobContext, type JobDefinition, type JobHandler, type JobRegistry, type JobResult, type OwnershipCheck } from './job-engine.js';
11
11
  export { definePlugin, registerPlugin, registeredPlugins, clearRegisteredPlugins, loadPlugins, type ArdentPlugin, type ArdentPluginContext, type ArdentCliCommand, type ArdentCliInvocation, type ArdentPluginFactory, type ArdentPluginFactoryContext, type ArdentTaskPluginContext, type ArdentChannelMessage, type ArdentChannelDelivery, type ArdentDeliveryOutcome, type ArdentToolCall, type ArdentToolDenial, type ArdentToolCancellation } from './plugins.js';
12
12
  export type { TeamEnvelope, TeamMission, TeamResult } from './team-contract.js';
13
+ export { inspectJournal, inspectJournalFile, journalPolicy, JOURNAL_POLICY_VERSION, JOURNAL_TABLES, type JournalStatus, type JournalTableStatus, type JournalTableRule } from './journal.js';
package/dist/index.js CHANGED
@@ -8,3 +8,4 @@ export { toolIdempotencyKey } from './tool-scheduler.js';
8
8
  export { createArdentApi, ardentOpenApi } from './api.js';
9
9
  export { JobEngine, validateJobDefinitions } from './job-engine.js';
10
10
  export { definePlugin, registerPlugin, registeredPlugins, clearRegisteredPlugins, loadPlugins } from './plugins.js';
11
+ export { inspectJournal, inspectJournalFile, journalPolicy, JOURNAL_POLICY_VERSION, JOURNAL_TABLES } from './journal.js';
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Version of the classification format and counting rules. It changes only
3
+ * when a consumer would need to read the policy or status differently; adding
4
+ * a table or a state value does not change it.
5
+ */
6
+ export declare const JOURNAL_POLICY_VERSION = 1;
7
+ /** A table whose `state` or `status` column says whether a row is still work. */
8
+ export type JournalStateRule = {
9
+ readonly kind: 'state';
10
+ readonly column: 'state' | 'status';
11
+ /** Rows a gateway start would run, resume, or send: counted as `active`. */
12
+ readonly active: readonly string[];
13
+ /** Rows whose outcome is uncertain and need reconciliation or an operator: counted as `unknown`. */
14
+ readonly uncertain: readonly string[];
15
+ /** Settled rows: not counted. */
16
+ readonly terminal: readonly string[];
17
+ };
18
+ /** A table that holds no runnable work. It must not have a `state` or `status` column. */
19
+ export type JournalPassiveRule = {
20
+ readonly kind: 'passive';
21
+ };
22
+ /** A history table with a state column that records what happened, never work a start resumes. */
23
+ export type JournalLedgerRule = {
24
+ readonly kind: 'ledger';
25
+ };
26
+ /** A table with its own rule, described in `description`. */
27
+ export type JournalSpecialRule = {
28
+ readonly kind: 'special';
29
+ readonly rule: 'a2a_tasks' | 'a2a_team_child_claims' | 'a2a_request_receipts' | 'channel_inbound' | 'admission_fence';
30
+ };
31
+ export type JournalTableRule = (JournalStateRule | JournalPassiveRule | JournalLedgerRule | JournalSpecialRule) & {
32
+ readonly description: string;
33
+ };
34
+ /** Every table in Ardent's journal and its idle rule. Keep schema changes and this map in the same commit. */
35
+ export declare const JOURNAL_TABLES: Readonly<Record<string, JournalTableRule>>;
36
+ /** The machine-readable policy: what `ardent journal policy` prints. */
37
+ export declare function journalPolicy(): {
38
+ policy_version: number;
39
+ tables: Record<string, JournalTableRule>;
40
+ };
41
+ export type JournalTableStatus = {
42
+ name: string;
43
+ kind: JournalTableRule['kind'] | 'unclassified';
44
+ active: number;
45
+ unknown: number;
46
+ unsupported: number;
47
+ /** Why rows or the table counted as unsupported. Present only when `unsupported` is not zero. */
48
+ problems?: string[];
49
+ };
50
+ export type JournalStatus = {
51
+ policy_version: number;
52
+ /** True when `active`, `unknown` and `unsupported` are all zero. */
53
+ idle: boolean;
54
+ /** Work a gateway start would run, resume, or send. */
55
+ active: number;
56
+ /** Work whose outcome is uncertain and needs reconciliation or an operator decision. */
57
+ unknown: number;
58
+ /** Tables, columns, or values this policy does not recognize, and the closed admission fence. Never idle. */
59
+ unsupported: number;
60
+ tables: JournalTableStatus[];
61
+ };
62
+ /**
63
+ * Inspect a journal file in place, read-only. SQLite may still create or touch
64
+ * the `-shm` file beside it, so use this only on a private copy (for example a
65
+ * snapshot staging directory). For a live profile directory use `inspectJournal`.
66
+ */
67
+ export declare function inspectJournalFile(path: string): JournalStatus;
68
+ /**
69
+ * Inspect a profile's journal (`state/ardent.sqlite`) without changing a byte
70
+ * of it. The database and its WAL are copied to a private directory, verified
71
+ * by digest, and inspected there, so committed but uncheckpointed work in the
72
+ * WAL is counted. Throws when the files change during inspection, which means
73
+ * a gateway is writing: a running profile is never idle.
74
+ */
75
+ export declare function inspectJournal(path: string): Promise<JournalStatus>;
@@ -0,0 +1,351 @@
1
+ /**
2
+ * Journal quiescence: which tables in a profile's SQLite journal can hold
3
+ * runnable or uncertain work, and how to count it.
4
+ *
5
+ * Ardent owns this classification because Ardent owns the schema. Tools that
6
+ * back up, snapshot, or upgrade a stopped profile (Magnus's node agent among
7
+ * them) ask this module instead of keeping their own table list. Every table
8
+ * Ardent creates is classified here; `test/journal.test.ts` fails when a new
9
+ * `CREATE TABLE` has no entry.
10
+ *
11
+ * The inspector is read-only and dependency-light: it opens the journal with
12
+ * the embedded SQLite driver and never constructs a TaskStore, runtime, plugin,
13
+ * queue, or job handler.
14
+ */
15
+ import { createHash } from 'node:crypto';
16
+ import { createReadStream } from 'node:fs';
17
+ import { chmod, copyFile, lstat, mkdtemp, rm } from 'node:fs/promises';
18
+ import { tmpdir } from 'node:os';
19
+ import { finished } from 'node:stream/promises';
20
+ import { join } from 'node:path';
21
+ import { z } from 'zod';
22
+ import Database from './sqlite.js';
23
+ /**
24
+ * Version of the classification format and counting rules. It changes only
25
+ * when a consumer would need to read the policy or status differently; adding
26
+ * a table or a state value does not change it.
27
+ */
28
+ export const JOURNAL_POLICY_VERSION = 1;
29
+ const state = (column, active, uncertain, terminal, description) => ({ kind: 'state', column, active, uncertain, terminal, description });
30
+ const passive = (description) => ({ kind: 'passive', description });
31
+ /** Every table in Ardent's journal and its idle rule. Keep schema changes and this map in the same commit. */
32
+ export const JOURNAL_TABLES = Object.freeze({
33
+ // Tasks, deliveries and jobs.
34
+ tasks: state('state', ['queued', 'running', 'input_required'], ['unknown'], ['completed', 'partial', 'failed', 'cancelled'], 'Task journal. Queued and running tasks are work; unknown tasks need an operator.'),
35
+ channel_deliveries: state('state', ['queued'], ['unknown'], ['sent', 'failed'], 'Chat replies recorded before they are sent.'),
36
+ channel_inbound: { kind: 'special', rule: 'channel_inbound',
37
+ description: 'Admitted chat updates. An update with no task whose delivery is missing, queued or unknown is active.' },
38
+ job_windows: state('state', ['queued', 'running', 'retry'], ['unknown'], ['completed', 'failed', 'superseded'], 'Scheduled job windows.'),
39
+ // Attempts are immutable receipts: a historical retry is not runnable work; the window owns retry admission.
40
+ job_attempts: state('state', [], ['unknown'], ['completed', 'failed', 'superseded', 'retry'], 'Receipts of job attempts. An attempt with an unknown effect is uncertain.'),
41
+ admission_fence: { kind: 'special', rule: 'admission_fence',
42
+ description: 'The one-way rollback fence. Any row is unsupported: a temporary snapshot must never clear it.' },
43
+ // Ardent 3.2.0 execution recovery.
44
+ tool_invocations: state('state', ['dispatched'], ['failed_unknown', 'unknown'], ['succeeded', 'failed_no_effect', 'reconciled_applied', 'reconciled_not_applied', 'operator_applied', 'operator_not_applied', 'not_dispatched'], 'Tool calls with a possible effect. A dispatched call is in flight; an uncertain one needs reconciliation.'),
45
+ task_recovery: state('status', ['ready', 'reconciling'], ['awaiting_decision', 'unsupported', 'unknown'], ['resumed', 'resolved'], 'Execution recovery decisions for interrupted tasks.'),
46
+ artifact_transfers: state('state', ['queued', 'transferring', 'verifying'], ['unknown'], ['completed', 'failed'], 'Resumable peer artifact imports.'),
47
+ // A2A.
48
+ a2a_tasks: { kind: 'special', rule: 'a2a_tasks',
49
+ description: 'A2A task records. The indexed status and the stored task JSON must agree; submitted, working, input-required and auth-required tasks are active, an unspecified state is unknown.' },
50
+ a2a_request_receipts: { kind: 'special', rule: 'a2a_request_receipts',
51
+ description: 'A2A request idempotency receipts. A receipt not yet bound to a task is active.' },
52
+ a2a_push_deliveries: state('state', ['queued'], ['unknown'], ['sent', 'failed'], 'A2A push notifications recorded before they are sent.'),
53
+ a2a_outbound_calls: state('state', ['pending', 'bound'], ['unknown'], ['failed'], 'Outbound A2A calls awaiting the peer\'s push callbacks.'),
54
+ a2a_team_artifacts: state('status', [], ['unknown'], ['available', 'revoked'], 'Artifacts this profile exports to team peers.'),
55
+ a2a_team_artifact_transfers: state('status', [], ['unknown'], ['complete'], 'Team artifacts received from peers.'),
56
+ a2a_team_child_claims: { kind: 'special', rule: 'a2a_team_child_claims',
57
+ description: 'Team child claims. An unacknowledged or unsettled claim is active (startup flushes it); a settlement with an unknown outcome is unknown, input-required is active.' },
58
+ a2a_recovery_publications: { kind: 'ledger',
59
+ description: 'What a peer was told about a recovered task.' },
60
+ // Ledgers and passive state.
61
+ channel_catchup_runs: { kind: 'ledger', description: 'Missed-post catch-up walks.' },
62
+ channel_catchup_gaps: passive('Detected gaps in missed-post catch-up.'),
63
+ sessions: passive('Chat sessions.'),
64
+ session_messages: passive('Chat session transcripts.'),
65
+ channel_cursors: passive('Channel offsets and small runtime cursors.'),
66
+ channel_preferences: passive('Per-conversation backend preferences.'),
67
+ events: passive('Task event journal.'),
68
+ context_checkpoints: passive('Context checkpoints (historical summaries).'),
69
+ context_checkpoint_heads: passive('Current context checkpoint per session.'),
70
+ context_compaction_attempts: passive('Context compaction attempt records.'),
71
+ emberfold_checkpoint_metadata: passive('Emberfold checkpoint metadata.'),
72
+ task_admission: passive('Per-task admission holds (pause and resume).'),
73
+ job_scan: passive('Job scheduler scan cursor.'),
74
+ artifact_manifests: passive('Artifact manifests.'),
75
+ artifact_renditions: passive('Artifact renditions.'),
76
+ artifact_sweeps: passive('Preview artifact sweep records.'),
77
+ development_records: passive('Agent development history.'),
78
+ execution_state: passive('Execution checkpoints; work is tracked by tasks and tool_invocations.'),
79
+ task_execution: passive('Task ancestry.'),
80
+ plugin_hook_failures: passive('Plugin hook failure diagnostics.'),
81
+ a2a_operation_map: passive('A2A task to operation mapping.'),
82
+ a2a_operation_links: passive('A2A operation links.'),
83
+ a2a_team_missions: passive('Validated team mission envelopes.'),
84
+ a2a_team_control_requests: passive('Team control requests.'),
85
+ a2a_team_controls: passive('Team control state.'),
86
+ a2a_team_admission: passive('Team admission records.'),
87
+ a2a_push_configs: passive('A2A push notification configurations.'),
88
+ a2a_inbound_push: passive('Received A2A push events.'),
89
+ });
90
+ /** The machine-readable policy: what `ardent journal policy` prints. */
91
+ export function journalPolicy() {
92
+ return { policy_version: JOURNAL_POLICY_VERSION, tables: { ...JOURNAL_TABLES } };
93
+ }
94
+ const identifier = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/);
95
+ const A2A_STATES = ['UNSPECIFIED', 'SUBMITTED', 'WORKING', 'COMPLETED', 'FAILED', 'CANCELED', 'INPUT_REQUIRED', 'REJECTED', 'AUTH_REQUIRED'];
96
+ const A2A_ACTIVE = new Set([1, 2, 6, 8]);
97
+ function a2aState(value) {
98
+ if (typeof value === 'number' || (typeof value === 'string' && /^-?\d+(?:\.0+)?$/.test(value))) {
99
+ const number = Number(value);
100
+ return Number.isInteger(number) && number >= 0 && number < A2A_STATES.length ? number : null;
101
+ }
102
+ if (typeof value !== 'string')
103
+ return null;
104
+ const index = A2A_STATES.indexOf(value.replace(/^TASK_STATE_/, '').replace(/-/g, '_').toUpperCase());
105
+ return index < 0 ? null : index;
106
+ }
107
+ const A2ATaskJson = z.object({ id: z.string().min(1), contextId: z.string(), status: z.object({ state: z.union([z.string(), z.number()]) }) });
108
+ const Settlement = z.object({ outcome: z.enum(['completed', 'partial', 'failed', 'blocked', 'input_required', 'cancelled', 'unknown']) });
109
+ function inspectOpen(db) {
110
+ const check = db.prepare('PRAGMA quick_check').all();
111
+ const first = check[0];
112
+ if (check.length !== 1 || !first || typeof first !== 'object' || Object.values(first)[0] !== 'ok')
113
+ throw new Error('Journal integrity check failed');
114
+ if (db.prepare('PRAGMA foreign_key_check').get())
115
+ throw new Error('Journal foreign-key integrity check failed');
116
+ const rows = z.array(z.object({ name: z.string(), sql: z.string().nullable() }))
117
+ .parse(db.prepare("SELECT name,sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all());
118
+ const names = new Set(rows.map(row => row.name));
119
+ const count = (sql) => z.object({ count: z.number().int() }).parse(db.prepare(sql).get()).count;
120
+ const tables = [];
121
+ for (const row of rows) {
122
+ const rule = Object.hasOwn(JOURNAL_TABLES, row.name) ? JOURNAL_TABLES[row.name] : undefined;
123
+ const result = { name: row.name, kind: rule?.kind ?? 'unclassified', active: 0, unknown: 0, unsupported: 0 };
124
+ tables.push(result);
125
+ const problems = [];
126
+ const unsupported = (problem, amount = 1) => { result.unsupported += amount; if (!problems.includes(problem))
127
+ problems.push(problem); };
128
+ try {
129
+ const id = identifier.safeParse(row.name);
130
+ if (!id.success) {
131
+ unsupported('table name is not a plain identifier');
132
+ continue;
133
+ }
134
+ if (row.sql === null || /CREATE\s+VIRTUAL\s+TABLE/i.test(row.sql)) {
135
+ unsupported('virtual table');
136
+ continue;
137
+ }
138
+ if (!rule) {
139
+ unsupported('table is not classified by this Ardent version');
140
+ continue;
141
+ }
142
+ if (rule.kind === 'ledger')
143
+ continue;
144
+ const columns = new Set(z.array(z.object({ name: z.string() })).parse(db.prepare(`PRAGMA table_info("${id.data}")`).all()).map(c => c.name));
145
+ const missing = (...required) => {
146
+ const absent = required.filter(column => !columns.has(column));
147
+ if (absent.length)
148
+ unsupported(`missing column ${absent.join(', ')}`);
149
+ return absent.length > 0;
150
+ };
151
+ if (rule.kind === 'state') {
152
+ if (missing(rule.column))
153
+ continue;
154
+ const other = rule.column === 'state' ? 'status' : 'state';
155
+ if (columns.has(other))
156
+ unsupported(`unexpected ${other} column`);
157
+ for (const entry of db.prepare(`SELECT "${rule.column}" AS value,count(*) AS count FROM "${id.data}" GROUP BY "${rule.column}"`).all()) {
158
+ const group = z.object({ value: z.unknown(), count: z.number().int() }).parse(entry);
159
+ const value = typeof group.value === 'string' ? group.value : null;
160
+ if (value !== null && rule.terminal.includes(value))
161
+ continue;
162
+ if (value !== null && rule.uncertain.includes(value))
163
+ result.unknown += group.count;
164
+ else if (value !== null && rule.active.includes(value))
165
+ result.active += group.count;
166
+ else
167
+ unsupported(`unrecognized ${rule.column} ${JSON.stringify(group.value)}`, group.count || 1);
168
+ }
169
+ continue;
170
+ }
171
+ if (rule.kind === 'passive') {
172
+ if (columns.has('state') || columns.has('status'))
173
+ unsupported('passive table has a state or status column');
174
+ continue;
175
+ }
176
+ switch (rule.rule) {
177
+ case 'a2a_tasks': {
178
+ if (missing('status', 'task_json'))
179
+ break;
180
+ if (columns.has('state'))
181
+ unsupported('unexpected state column');
182
+ for (const entry of db.prepare('SELECT status,task_json FROM a2a_tasks').iterate()) {
183
+ const task = z.object({ status: z.unknown(), task_json: z.unknown() }).parse(entry);
184
+ let json;
185
+ try {
186
+ json = JSON.parse(String(task.task_json));
187
+ }
188
+ catch {
189
+ unsupported('task JSON does not parse');
190
+ continue;
191
+ }
192
+ const parsed = A2ATaskJson.safeParse(json);
193
+ const indexed = a2aState(task.status), recorded = parsed.success ? a2aState(parsed.data.status.state) : null;
194
+ if (indexed === null || recorded === null || indexed !== recorded)
195
+ unsupported('indexed status and task JSON disagree');
196
+ for (const value of new Set([indexed, recorded])) {
197
+ if (value === 0)
198
+ result.unknown++;
199
+ else if (value !== null && A2A_ACTIVE.has(value))
200
+ result.active++;
201
+ }
202
+ }
203
+ break;
204
+ }
205
+ case 'admission_fence': {
206
+ if (columns.has('state') || columns.has('status')) {
207
+ unsupported('unexpected state or status column');
208
+ break;
209
+ }
210
+ const fence = count('SELECT count(*) AS count FROM admission_fence');
211
+ if (fence)
212
+ unsupported('admission fence is closed', fence);
213
+ break;
214
+ }
215
+ case 'a2a_team_child_claims': {
216
+ if (columns.has('state') || columns.has('status')) {
217
+ unsupported('unexpected state or status column');
218
+ break;
219
+ }
220
+ if (missing('acknowledged', 'settlement_json'))
221
+ break;
222
+ // Gateway startup flushes retained settlements, even though this table has no state column.
223
+ result.active += count('SELECT count(*) AS count FROM a2a_team_child_claims WHERE acknowledged IS NULL OR acknowledged!=1 OR settlement_json IS NULL');
224
+ for (const entry of db.prepare('SELECT settlement_json FROM a2a_team_child_claims WHERE settlement_json IS NOT NULL').iterate()) {
225
+ let json;
226
+ try {
227
+ json = JSON.parse(String(z.object({ settlement_json: z.unknown() }).parse(entry).settlement_json));
228
+ }
229
+ catch {
230
+ unsupported('settlement JSON does not parse');
231
+ continue;
232
+ }
233
+ const outcome = Settlement.safeParse(json);
234
+ if (!outcome.success)
235
+ unsupported('unrecognized settlement outcome');
236
+ else if (outcome.data.outcome === 'unknown')
237
+ result.unknown++;
238
+ else if (outcome.data.outcome === 'input_required')
239
+ result.active++;
240
+ }
241
+ break;
242
+ }
243
+ case 'a2a_request_receipts': {
244
+ if (columns.has('state') || columns.has('status')) {
245
+ unsupported('unexpected state or status column');
246
+ break;
247
+ }
248
+ if (!missing('task_id'))
249
+ result.active += count("SELECT count(*) AS count FROM a2a_request_receipts WHERE task_id IS NULL OR task_id=''");
250
+ break;
251
+ }
252
+ case 'channel_inbound': {
253
+ if (columns.has('state') || columns.has('status')) {
254
+ unsupported('unexpected state or status column');
255
+ break;
256
+ }
257
+ if (missing('task_id', 'platform', 'account', 'update_id'))
258
+ break;
259
+ if (!names.has('channel_deliveries')) {
260
+ unsupported('channel_deliveries table is missing');
261
+ break;
262
+ }
263
+ result.active += count(`SELECT count(*) AS count FROM channel_inbound AS inbound
264
+ LEFT JOIN channel_deliveries AS delivery ON delivery.platform=inbound.platform
265
+ AND delivery.account=inbound.account AND delivery.update_id=inbound.update_id
266
+ WHERE inbound.task_id IS NULL${columns.has('disposition') ? " AND inbound.disposition='admitted'" : ''} AND (delivery.id IS NULL OR delivery.state IN ('queued','unknown'))`);
267
+ break;
268
+ }
269
+ }
270
+ }
271
+ finally {
272
+ if (problems.length)
273
+ result.problems = problems;
274
+ }
275
+ }
276
+ const total = (key) => tables.reduce((sum, table) => sum + table[key], 0);
277
+ // An empty file is not an Ardent journal.
278
+ const unsupported = total('unsupported') + (rows.length === 0 ? 1 : 0);
279
+ const active = total('active'), unknown = total('unknown');
280
+ return { policy_version: JOURNAL_POLICY_VERSION, idle: active === 0 && unknown === 0 && unsupported === 0, active, unknown, unsupported, tables };
281
+ }
282
+ /**
283
+ * Inspect a journal file in place, read-only. SQLite may still create or touch
284
+ * the `-shm` file beside it, so use this only on a private copy (for example a
285
+ * snapshot staging directory). For a live profile directory use `inspectJournal`.
286
+ */
287
+ export function inspectJournalFile(path) {
288
+ const db = new Database(path, { readonly: true, fileMustExist: true });
289
+ try {
290
+ return inspectOpen(db);
291
+ }
292
+ finally {
293
+ db.close();
294
+ }
295
+ }
296
+ async function sha256(path) {
297
+ const hash = createHash('sha256');
298
+ const stream = createReadStream(path);
299
+ stream.on('data', (chunk) => { hash.update(chunk); });
300
+ await finished(stream);
301
+ return hash.digest('hex');
302
+ }
303
+ async function regularFile(path, optional = false) {
304
+ const stat = await lstat(path).catch((error) => {
305
+ if (optional && error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT')
306
+ return undefined;
307
+ throw error;
308
+ });
309
+ if (!stat)
310
+ return false;
311
+ if (!stat.isFile() || stat.isSymbolicLink())
312
+ throw new Error('Journal path must be a regular file');
313
+ return true;
314
+ }
315
+ /**
316
+ * Inspect a profile's journal (`state/ardent.sqlite`) without changing a byte
317
+ * of it. The database and its WAL are copied to a private directory, verified
318
+ * by digest, and inspected there, so committed but uncheckpointed work in the
319
+ * WAL is counted. Throws when the files change during inspection, which means
320
+ * a gateway is writing: a running profile is never idle.
321
+ */
322
+ export async function inspectJournal(path) {
323
+ await regularFile(path);
324
+ const scratch = await mkdtemp(join(tmpdir(), 'ardent-journal-'));
325
+ try {
326
+ await chmod(scratch, 0o700);
327
+ const destination = join(scratch, 'journal.sqlite');
328
+ const sources = [];
329
+ for (const suffix of ['', '-wal']) {
330
+ const source = path + suffix;
331
+ if (!await regularFile(source, suffix !== ''))
332
+ continue;
333
+ const digest = await sha256(source), copied = destination + suffix;
334
+ await copyFile(source, copied);
335
+ await chmod(copied, 0o600);
336
+ if (await sha256(copied) !== digest)
337
+ throw new Error('Journal changed while it was being copied for inspection');
338
+ sources.push({ path: source, sha256: digest });
339
+ }
340
+ const result = inspectJournalFile(destination);
341
+ for (const source of sources)
342
+ if (await sha256(source.path) !== source.sha256)
343
+ throw new Error('Journal changed during inspection');
344
+ if (await regularFile(path + '-wal', true) !== sources.some(source => source.path === path + '-wal'))
345
+ throw new Error('Journal WAL appeared or disappeared during inspection');
346
+ return result;
347
+ }
348
+ finally {
349
+ await rm(scratch, { recursive: true, force: true });
350
+ }
351
+ }
package/dist/log.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import { type Logger } from '@hivemagnus/hive-common/log';
2
+ export type { Logger } from '@hivemagnus/hive-common/log';
3
+ /**
4
+ * Operational log lines: JSON, secrets redacted, written to stderr so stdout
5
+ * stays the CLI's machine-readable output. `LOG_LEVEL` sets the minimum level.
6
+ */
7
+ export declare function ardentLogger(): Logger;
package/dist/log.js ADDED
@@ -0,0 +1,8 @@
1
+ import { createLogger } from '@hivemagnus/hive-common/log';
2
+ /**
3
+ * Operational log lines: JSON, secrets redacted, written to stderr so stdout
4
+ * stays the CLI's machine-readable output. `LOG_LEVEL` sets the minimum level.
5
+ */
6
+ export function ardentLogger() {
7
+ return createLogger({ bindings: { service: 'ardent' }, write: line => { process.stderr.write(`${line}\n`); } });
8
+ }
package/dist/store.d.ts CHANGED
@@ -191,6 +191,13 @@ export declare class TaskStore {
191
191
  changed: boolean;
192
192
  };
193
193
  get(id: string): Task | undefined;
194
+ /** Tasks by state: every task in the journal, not a page of them. */
195
+ taskCounts(): {
196
+ total: number;
197
+ by_state: Record<string, number>;
198
+ };
199
+ /** The last scheduler tick failure the gateway recorded (cursor `jobs:last_error`), with when it happened. */
200
+ jobTickError(): JobTickError | null;
194
201
  list(limit?: number): Task[];
195
202
  listByCaller(caller: string, limit?: number): Task[];
196
203
  setState(id: string, state: TaskState, result?: string | null, error?: string | null): void;
@@ -226,3 +233,10 @@ export declare class TaskStore {
226
233
  held: string[];
227
234
  };
228
235
  }
236
+ export declare const JOB_TICK_ERROR_CURSOR = "jobs:last_error";
237
+ export type JobTickError = {
238
+ message: string;
239
+ at: string;
240
+ };
241
+ /** Read the recorded job tick failure from an open journal; works on a read-only connection. */
242
+ export declare function readJobTickError(db: Database): JobTickError | null;
package/dist/store.js CHANGED
@@ -358,6 +358,13 @@ export class TaskStore {
358
358
  const row = this.db.prepare('SELECT * FROM tasks WHERE id=?').get(id);
359
359
  return row ? TaskSchema.parse(row) : undefined;
360
360
  }
361
+ /** Tasks by state: every task in the journal, not a page of them. */
362
+ taskCounts() {
363
+ const rows = z.array(z.object({ state: z.string(), count: z.number().int() })).parse(this.db.prepare('SELECT state,count(*) AS count FROM tasks GROUP BY state').all());
364
+ return { total: rows.reduce((sum, row) => sum + row.count, 0), by_state: Object.fromEntries(rows.map(row => [row.state, row.count])) };
365
+ }
366
+ /** The last scheduler tick failure the gateway recorded (cursor `jobs:last_error`), with when it happened. */
367
+ jobTickError() { return readJobTickError(this.db); }
361
368
  list(limit = 50) {
362
369
  return this.db.prepare('SELECT * FROM tasks ORDER BY created_ms DESC LIMIT ?').all(Math.max(1, Math.min(limit, 100))).map(row => TaskSchema.parse(row));
363
370
  }
@@ -428,3 +435,13 @@ export class TaskStore {
428
435
  resumed: planned.resumed, held: planned.held };
429
436
  }
430
437
  }
438
+ export const JOB_TICK_ERROR_CURSOR = 'jobs:last_error';
439
+ /** Read the recorded job tick failure from an open journal; works on a read-only connection. */
440
+ export function readJobTickError(db) {
441
+ const table = db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='channel_cursors'").get();
442
+ const row = table ? db.prepare('SELECT value,updated_ms FROM channel_cursors WHERE key=?').get(JOB_TICK_ERROR_CURSOR) : undefined;
443
+ if (!row)
444
+ return null;
445
+ const parsed = z.object({ value: z.string(), updated_ms: z.number().int() }).parse(row);
446
+ return { message: parsed.value, at: new Date(parsed.updated_ms).toISOString() };
447
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hivemagnus/ardent",
3
- "version": "3.2.1",
3
+ "version": "3.3.0",
4
4
  "description": "Headless TypeScript agent runtime with A2A, scheduled jobs, skills, chat channels, and a plugin API",
5
5
  "keywords": [
6
6
  "agent",
@@ -33,6 +33,10 @@
33
33
  "types": "./dist/plugin-sdk.d.ts",
34
34
  "default": "./dist/plugin-sdk.js"
35
35
  },
36
+ "./journal": {
37
+ "types": "./dist/journal.d.ts",
38
+ "default": "./dist/journal.js"
39
+ },
36
40
  ".": {
37
41
  "types": "./dist/index.d.ts",
38
42
  "default": "./dist/index.js"
@@ -86,7 +90,7 @@
86
90
  "@hivemagnus/canvas-word-codec": "1.1.0",
87
91
  "@hivemagnus/emberfold": "0.1.0",
88
92
  "@hivemagnus/hive-common": "0.6.0",
89
- "@hono/node-server": "^2.1.6",
93
+ "@hono/node-server": "^2.1.11",
90
94
  "@photostructure/sqlite": "3.3.1",
91
95
  "dotenv": "^18.0.9",
92
96
  "express": "5.3.0",
@@ -94,7 +98,7 @@
94
98
  "marked": "18.1.1",
95
99
  "parse5": "8.1.1",
96
100
  "pdfmake": "0.3.13",
97
- "ws": "^8.22.0",
101
+ "ws": "^8.23.0",
98
102
  "yaml": "2.9.1",
99
103
  "zod": "^4.6.7"
100
104
  },
@@ -1 +0,0 @@
1
- export {};
@@ -1,29 +0,0 @@
1
- import { describe, expect, it } from 'vitest';
2
- import { CodexOutputBudget, CODEX_PRODUCTION_OUTPUT_MAX_BYTES } from './codex-output-budget.js';
3
- describe('Codex aggregate agent output byte bound', () => {
4
- it('counts Unicode bytes, including surrogate pairs split across deltas, without double counting completion', () => {
5
- const budget = new CodexOutputBudget(4);
6
- expect(budget.observe('thread', 'turn', 'item', '\ud83e', 'delta')).toBeNull();
7
- expect(budget.observe('thread', 'turn', 'item', '', 'delta')).toBeNull();
8
- expect(budget.observe('thread', 'turn', 'item', '\udd91', 'delta')).toBeNull();
9
- expect(budget.observe('thread', 'turn', 'item', '🦑', 'completed')).toBeNull();
10
- expect(budget.observe('thread', 'turn', 'item', 'a', 'delta')).toMatchObject({ limit: 4, observed: 5, source: 'delta' });
11
- });
12
- it('bounds all agent items together, including commentary and completed-only output', () => {
13
- const budget = new CodexOutputBudget(10);
14
- expect(budget.observe('thread', 'turn', 'commentary', '12345', 'completed')).toBeNull();
15
- expect(budget.observe('thread', 'turn', 'final', '67890', 'delta')).toBeNull();
16
- expect(budget.observe('thread', 'turn', 'final', '67890', 'completed')).toBeNull();
17
- expect(budget.observe('thread', 'turn', 'last', '海', 'completed')).toEqual({ kind: 'agent_output_bytes', threadId: 'thread', turnId: 'turn', itemId: 'last', source: 'completed', limit: 10, observed: 13 });
18
- });
19
- it('separates colliding-looking identities without letting shorter completion regain streamed bytes', () => {
20
- const budget = new CodexOutputBudget(7);
21
- expect(budget.observe('thread', 'a:b', 'c', '123', 'delta')).toBeNull();
22
- expect(budget.observe('thread', 'a:b', 'c', '1', 'completed')).toBeNull();
23
- expect(budget.observe('thread', 'a', 'b:c', '2345', 'completed')).toBeNull();
24
- expect(budget.observe('thread', 'a', 'b:c', '6', 'delta')).toMatchObject({ observed: 8 });
25
- });
26
- it.each([0, -1, 1.5, NaN, Infinity, CODEX_PRODUCTION_OUTPUT_MAX_BYTES + 1])('rejects invalid configured caps %s', cap => {
27
- expect(() => new CodexOutputBudget(cap)).toThrow('CODEX_OUTPUT_BOUND_INVALID');
28
- });
29
- });