@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/identity.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
2
  import { mkdir, open, readFile, readdir, rename, unlink, writeFile } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
+ import { conflict, invalidRequest, notFound } from './errors.js';
4
5
  function digest(text) { return createHash('sha256').update(text).digest('hex'); }
5
6
  function name(config, kind) { return kind === 'soul' ? config.identity.soul_file : config.identity.identity_file; }
6
7
  function historyDir(dir, kind) { return join(dir, 'state', 'identity-history', kind); }
@@ -9,20 +10,20 @@ export async function readIdentity(dir, config, kind) {
9
10
  const filename = name(config, kind);
10
11
  const text = await readFile(join(dir, filename), 'utf8');
11
12
  if (Buffer.byteLength(text) > 128 * 1024)
12
- throw new Error('Identity file exceeds 128 KiB');
13
+ throw invalidRequest('Identity file exceeds 128 KiB');
13
14
  return { kind, name: filename, text, revision: digest(text) };
14
15
  }
15
16
  export async function writeIdentity(dir, config, kind, nextText, expectedRevision) {
16
17
  if (!nextText.trim() || Buffer.byteLength(nextText) > 128 * 1024)
17
- throw new Error('Identity text must be 1 to 128 KiB');
18
+ throw invalidRequest('Identity text must be 1 to 128 KiB');
18
19
  const history = historyDir(dir, kind);
19
20
  await mkdir(history, { recursive: true, mode: 0o700 });
20
21
  const lockPath = join(history, '.write.lock');
21
- const lock = await open(lockPath, 'wx', 0o600).catch(() => { throw new Error('Identity edit is already in progress'); });
22
+ const lock = await open(lockPath, 'wx', 0o600).catch(() => { throw conflict('Identity edit is already in progress'); });
22
23
  try {
23
24
  const previous = await readIdentity(dir, config, kind);
24
25
  if (previous.revision !== expectedRevision)
25
- throw new Error('Identity revision conflict');
26
+ throw conflict('Identity revision conflict');
26
27
  await writeFile(join(history, `${Date.now()}-${randomUUID().replaceAll('-', '').slice(0, 12)}-${previous.revision}.md`), previous.text, { mode: 0o600, flag: 'wx' });
27
28
  const temporary = join(dir, `.${previous.name}.${randomUUID()}.tmp`);
28
29
  await writeFile(temporary, nextText, { mode: 0o600, flag: 'wx' });
@@ -44,8 +45,12 @@ export async function identityHistory(dir, kind) {
44
45
  export async function restoreIdentity(dir, config, kind, historyName, expectedRevision) {
45
46
  const revision = historyNamePattern.exec(historyName)?.[1];
46
47
  if (!revision)
47
- throw new Error('Invalid identity history entry');
48
- const text = await readFile(join(historyDir(dir, kind), historyName), 'utf8');
48
+ throw invalidRequest('Invalid identity history entry');
49
+ const text = await readFile(join(historyDir(dir, kind), historyName), 'utf8').catch((error) => {
50
+ if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT')
51
+ throw notFound('Identity history entry not found');
52
+ throw error;
53
+ });
49
54
  if (digest(text) !== revision)
50
55
  throw new Error('Identity history checksum mismatch');
51
56
  return writeIdentity(dir, config, kind, text, expectedRevision);
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';
@@ -1,5 +1,6 @@
1
1
  import type Database from './sqlite.js';
2
2
  import { z } from 'zod';
3
+ import { type Logger } from './log.js';
3
4
  declare const definition: z.ZodObject<{
4
5
  id: z.ZodString;
5
6
  owner: z.ZodString;
@@ -161,6 +162,8 @@ export declare class JobEngine {
161
162
  readonly ownershipCheck: OwnershipCheck;
162
163
  readonly clock: () => number;
163
164
  readonly random: () => number;
165
+ /** Where failed, unknown and retried job windows are logged; the gateway sets it. */
166
+ logger: Logger;
164
167
  /** `clock` measures elapsed time within a tick; the injected tick time stays the timeline origin. */
165
168
  constructor(db: Database, profileDir: string, profile: string, registry: JobRegistry, ownershipCheck: OwnershipCheck, clock?: () => number, random?: () => number);
166
169
  load(): Promise<{
@@ -4,6 +4,7 @@ import { open, readFile, unlink } from 'node:fs/promises';
4
4
  import { join } from 'node:path';
5
5
  import { z } from 'zod';
6
6
  import { backoffDelay } from '@hivemagnus/hive-common/retry';
7
+ import { silentLogger } from './log.js';
7
8
  const identifier = z.string().regex(/^[a-z][a-z0-9._-]{0,79}$/);
8
9
  const jobId = z.string().regex(/^[a-z0-9][a-z0-9._-]{0,79}$/);
9
10
  const timezone = z.string().min(1).max(80).refine(value => {
@@ -153,6 +154,8 @@ export class JobEngine {
153
154
  ownershipCheck;
154
155
  clock;
155
156
  random;
157
+ /** Where failed, unknown and retried job windows are logged; the gateway sets it. */
158
+ logger = silentLogger;
156
159
  #lastValidationError = null;
157
160
  #lastActive = null;
158
161
  #busy = false;
@@ -448,6 +451,8 @@ export class JobEngine {
448
451
  retry++;
449
452
  else if (state === 'unknown')
450
453
  unknown++;
454
+ if (state !== 'completed')
455
+ this.logger[state === 'retry' ? 'info' : 'warn'](`Job window ${state}`, { job_id: job.id, window_key: window.window_key, attempt });
451
456
  }
452
457
  }
453
458
  return { scanned, claimed, completed, retry, unknown };
@@ -0,0 +1,90 @@
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
+ /**
7
+ * Mattermost history claimed on a channel's first sight, never to be answered (it has no channel
8
+ * type: live and catch-up posts always record one). Such a row is finished, not admitted work.
9
+ */
10
+ /** task_recovery statuses: `active` ones count only while their task is running. */
11
+ export declare const TASK_RECOVERY_STATUSES: Readonly<{
12
+ readonly active: readonly ["ready", "reconciling"];
13
+ readonly uncertain: readonly ["awaiting_decision", "unsupported", "unknown"];
14
+ readonly terminal: readonly ["resumed", "resolved"];
15
+ }>;
16
+ export declare const SEEDED_INBOUND = "(inbound.platform='mattermost' AND inbound.channel_type='unknown')";
17
+ export declare const JOURNAL_POLICY_VERSION = 1;
18
+ /** A table whose `state` or `status` column says whether a row is still work. */
19
+ export type JournalStateRule = {
20
+ readonly kind: 'state';
21
+ readonly column: 'state' | 'status';
22
+ /** Rows a gateway start would run, resume, or send: counted as `active`. */
23
+ readonly active: readonly string[];
24
+ /** Rows whose outcome is uncertain and need reconciliation or an operator: counted as `unknown`. */
25
+ readonly uncertain: readonly string[];
26
+ /** Settled rows: not counted. */
27
+ readonly terminal: readonly string[];
28
+ };
29
+ /** A table that holds no runnable work. It must not have a `state` or `status` column. */
30
+ export type JournalPassiveRule = {
31
+ readonly kind: 'passive';
32
+ };
33
+ /** A history table with a state column that records what happened, never work a start resumes. */
34
+ export type JournalLedgerRule = {
35
+ readonly kind: 'ledger';
36
+ };
37
+ /** A table with its own rule, described in `description`. */
38
+ export type JournalSpecialRule = {
39
+ readonly kind: 'special';
40
+ readonly rule: 'a2a_tasks' | 'a2a_team_child_claims' | 'a2a_request_receipts' | 'channel_inbound' | 'admission_fence' | 'task_recovery';
41
+ };
42
+ export type JournalTableRule = (JournalStateRule | JournalPassiveRule | JournalLedgerRule | JournalSpecialRule) & {
43
+ readonly description: string;
44
+ };
45
+ /** Every table in Ardent's journal and its idle rule. Keep schema changes and this map in the same commit. */
46
+ export declare const JOURNAL_TABLES: Readonly<Record<string, JournalTableRule>>;
47
+ /** The machine-readable policy: what `ardent journal policy` prints. */
48
+ export declare function journalPolicy(): {
49
+ policy_version: number;
50
+ tables: Record<string, JournalTableRule>;
51
+ };
52
+ export type JournalTableStatus = {
53
+ name: string;
54
+ kind: JournalTableRule['kind'] | 'unclassified';
55
+ active: number;
56
+ unknown: number;
57
+ unsupported: number;
58
+ /** Why rows or the table counted as unsupported. Present only when `unsupported` is not zero. */
59
+ problems?: string[];
60
+ };
61
+ export type JournalStatus = {
62
+ policy_version: number;
63
+ /** True when `active`, `unknown` and `unsupported` are all zero. */
64
+ idle: boolean;
65
+ /** Work a gateway start would run, resume, or send. */
66
+ active: number;
67
+ /** Work whose outcome is uncertain and needs reconciliation or an operator decision. */
68
+ unknown: number;
69
+ /** Tables, columns, or values this policy does not recognize, and the closed admission fence. Never idle. */
70
+ unsupported: number;
71
+ tables: JournalTableStatus[];
72
+ };
73
+ /**
74
+ * Inspect a journal file in place, read-only. SQLite may still create or touch
75
+ * the `-shm` file beside it, so use this only on a private copy (for example a
76
+ * snapshot staging directory). For a live profile directory use `inspectJournal`.
77
+ */
78
+ export declare function inspectJournalFile(path: string): JournalStatus;
79
+ /**
80
+ * Inspect a profile's journal (`state/ardent.sqlite`) without changing a byte
81
+ * of it. The database and its WAL are copied to a private directory, verified
82
+ * by digest, and inspected there, so committed but uncheckpointed work in the
83
+ * WAL is counted. Throws when the files change during inspection, which means
84
+ * a gateway is writing. It does not check the gateway lock: an idle gateway
85
+ * that writes nothing during the copy can be reported idle, so stop the
86
+ * profile (or hold its gateway lock) before relying on `idle` for a snapshot.
87
+ * Tables an extension created and this policy does not classify count as
88
+ * `unsupported`, so such a profile is never reported idle.
89
+ */
90
+ export declare function inspectJournal(path: string): Promise<JournalStatus>;
@@ -0,0 +1,395 @@
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
+ /**
29
+ * Mattermost history claimed on a channel's first sight, never to be answered (it has no channel
30
+ * type: live and catch-up posts always record one). Such a row is finished, not admitted work.
31
+ */
32
+ /** task_recovery statuses: `active` ones count only while their task is running. */
33
+ export const TASK_RECOVERY_STATUSES = Object.freeze({ active: ['ready', 'reconciling'], uncertain: ['awaiting_decision', 'unsupported', 'unknown'], terminal: ['resumed', 'resolved'] });
34
+ export const SEEDED_INBOUND = "(inbound.platform='mattermost' AND inbound.channel_type='unknown')";
35
+ export const JOURNAL_POLICY_VERSION = 1;
36
+ const state = (column, active, uncertain, terminal, description) => ({ kind: 'state', column, active, uncertain, terminal, description });
37
+ const passive = (description) => ({ kind: 'passive', description });
38
+ /** Every table in Ardent's journal and its idle rule. Keep schema changes and this map in the same commit. */
39
+ export const JOURNAL_TABLES = Object.freeze({
40
+ // Tasks, deliveries and jobs.
41
+ 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.'),
42
+ channel_deliveries: state('state', ['queued'], ['unknown'], ['sent', 'failed'], 'Chat replies recorded before they are sent.'),
43
+ channel_inbound: { kind: 'special', rule: 'channel_inbound',
44
+ description: 'Admitted chat updates. An update with no task whose delivery is missing, queued or unknown is active.' },
45
+ job_windows: state('state', ['queued', 'running', 'retry'], ['unknown'], ['completed', 'failed', 'superseded'], 'Scheduled job windows.'),
46
+ // Attempts are immutable receipts: a historical retry is not runnable work; the window owns retry admission.
47
+ job_attempts: state('state', [], ['unknown'], ['completed', 'failed', 'superseded', 'retry'], 'Receipts of job attempts. An attempt with an unknown effect is uncertain.'),
48
+ admission_fence: { kind: 'special', rule: 'admission_fence',
49
+ description: 'The one-way rollback fence. Any row is unsupported: a temporary snapshot must never clear it.' },
50
+ // Ardent 3.2.0 execution recovery.
51
+ 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.'),
52
+ task_recovery: { kind: 'special', rule: 'task_recovery',
53
+ description: 'Execution recovery decisions for interrupted tasks. A ready or reconciling row is active only while its task is running; awaiting_decision, unsupported and unknown rows are uncertain; resumed and resolved rows are finished.' },
54
+ artifact_transfers: state('state', ['queued', 'transferring', 'verifying'], ['unknown'], ['completed', 'failed'], 'Resumable peer artifact imports.'),
55
+ // A2A.
56
+ a2a_tasks: { kind: 'special', rule: 'a2a_tasks',
57
+ 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.' },
58
+ a2a_request_receipts: { kind: 'special', rule: 'a2a_request_receipts',
59
+ description: 'A2A request idempotency receipts. A receipt not yet bound to a task is active.' },
60
+ a2a_push_deliveries: state('state', ['queued'], ['unknown'], ['sent', 'failed'], 'A2A push notifications recorded before they are sent.'),
61
+ // A bound call was accepted by the peer; its push callbacks are received whenever they come.
62
+ a2a_outbound_calls: state('state', ['pending'], ['unknown'], ['bound', 'failed'], 'Outbound A2A calls. A pending call is being sent; a bound call has its peer task and only receives callbacks.'),
63
+ a2a_team_artifacts: state('status', [], ['unknown'], ['available', 'revoked'], 'Artifacts this profile exports to team peers.'),
64
+ a2a_team_artifact_transfers: state('status', [], ['unknown'], ['complete'], 'Team artifacts received from peers.'),
65
+ a2a_team_child_claims: { kind: 'special', rule: 'a2a_team_child_claims',
66
+ 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.' },
67
+ a2a_recovery_publications: { kind: 'ledger',
68
+ description: 'What a peer was told about a recovered task.' },
69
+ // Ledgers and passive state.
70
+ channel_catchup_runs: { kind: 'ledger', description: 'Missed-post catch-up walks.' },
71
+ channel_catchup_gaps: passive('Detected gaps in missed-post catch-up.'),
72
+ sessions: passive('Chat sessions.'),
73
+ session_messages: passive('Chat session transcripts.'),
74
+ channel_cursors: passive('Channel offsets and small runtime cursors.'),
75
+ channel_preferences: passive('Per-conversation backend preferences.'),
76
+ events: passive('Task event journal.'),
77
+ context_checkpoints: passive('Context checkpoints (historical summaries).'),
78
+ context_checkpoint_heads: passive('Current context checkpoint per session.'),
79
+ context_compaction_attempts: passive('Context compaction attempt records.'),
80
+ emberfold_checkpoint_metadata: passive('Emberfold checkpoint metadata.'),
81
+ task_admission: passive('Per-task admission holds (pause and resume).'),
82
+ job_scan: passive('Job scheduler scan cursor.'),
83
+ artifact_manifests: passive('Artifact manifests.'),
84
+ artifact_renditions: passive('Artifact renditions.'),
85
+ artifact_sweeps: passive('Preview artifact sweep records.'),
86
+ development_records: passive('Agent development history.'),
87
+ execution_state: passive('Execution checkpoints; work is tracked by tasks and tool_invocations.'),
88
+ task_execution: passive('Task ancestry.'),
89
+ plugin_hook_failures: passive('Plugin hook failure diagnostics.'),
90
+ a2a_operation_map: passive('A2A task to operation mapping.'),
91
+ a2a_operation_links: passive('A2A operation links.'),
92
+ a2a_team_missions: passive('Validated team mission envelopes.'),
93
+ a2a_team_control_requests: passive('Team control requests.'),
94
+ a2a_team_controls: passive('Team control state.'),
95
+ a2a_team_admission: passive('Team admission records.'),
96
+ a2a_push_configs: passive('A2A push notification configurations.'),
97
+ a2a_inbound_push: passive('Received A2A push events.'),
98
+ });
99
+ /** The machine-readable policy: what `ardent journal policy` prints. */
100
+ export function journalPolicy() {
101
+ return { policy_version: JOURNAL_POLICY_VERSION, tables: { ...JOURNAL_TABLES } };
102
+ }
103
+ const identifier = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/);
104
+ const A2A_STATES = ['UNSPECIFIED', 'SUBMITTED', 'WORKING', 'COMPLETED', 'FAILED', 'CANCELED', 'INPUT_REQUIRED', 'REJECTED', 'AUTH_REQUIRED'];
105
+ const A2A_ACTIVE = new Set([1, 2, 6, 8]);
106
+ function a2aState(value) {
107
+ if (typeof value === 'number' || (typeof value === 'string' && /^-?\d+(?:\.0+)?$/.test(value))) {
108
+ const number = Number(value);
109
+ return Number.isInteger(number) && number >= 0 && number < A2A_STATES.length ? number : null;
110
+ }
111
+ if (typeof value !== 'string')
112
+ return null;
113
+ const index = A2A_STATES.indexOf(value.replace(/^TASK_STATE_/, '').replace(/-/g, '_').toUpperCase());
114
+ return index < 0 ? null : index;
115
+ }
116
+ const A2ATaskJson = z.object({ id: z.string().min(1), contextId: z.string(), status: z.object({ state: z.union([z.string(), z.number()]) }) });
117
+ const Settlement = z.object({ outcome: z.enum(['completed', 'partial', 'failed', 'blocked', 'input_required', 'cancelled', 'unknown']) });
118
+ function inspectOpen(db) {
119
+ const check = db.prepare('PRAGMA quick_check').all();
120
+ const first = check[0];
121
+ if (check.length !== 1 || !first || typeof first !== 'object' || Object.values(first)[0] !== 'ok')
122
+ throw new Error('Journal integrity check failed');
123
+ if (db.prepare('PRAGMA foreign_key_check').get())
124
+ throw new Error('Journal foreign-key integrity check failed');
125
+ const rows = z.array(z.object({ name: z.string(), sql: z.string().nullable() }))
126
+ .parse(db.prepare("SELECT name,sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all());
127
+ const names = new Set(rows.map(row => row.name));
128
+ const count = (sql) => z.object({ count: z.number().int() }).parse(db.prepare(sql).get()).count;
129
+ const tables = [];
130
+ for (const row of rows) {
131
+ const rule = Object.hasOwn(JOURNAL_TABLES, row.name) ? JOURNAL_TABLES[row.name] : undefined;
132
+ const result = { name: row.name, kind: rule?.kind ?? 'unclassified', active: 0, unknown: 0, unsupported: 0 };
133
+ tables.push(result);
134
+ const problems = [];
135
+ const unsupported = (problem, amount = 1) => { result.unsupported += amount; if (!problems.includes(problem))
136
+ problems.push(problem); };
137
+ try {
138
+ const id = identifier.safeParse(row.name);
139
+ if (!id.success) {
140
+ unsupported('table name is not a plain identifier');
141
+ continue;
142
+ }
143
+ if (row.sql === null || /CREATE\s+VIRTUAL\s+TABLE/i.test(row.sql)) {
144
+ unsupported('virtual table');
145
+ continue;
146
+ }
147
+ if (!rule) {
148
+ unsupported('table is not classified by this Ardent version');
149
+ continue;
150
+ }
151
+ if (rule.kind === 'ledger')
152
+ continue;
153
+ const columns = new Set(z.array(z.object({ name: z.string() })).parse(db.prepare(`PRAGMA table_info("${id.data}")`).all()).map(c => c.name));
154
+ const missing = (...required) => {
155
+ const absent = required.filter(column => !columns.has(column));
156
+ if (absent.length)
157
+ unsupported(`missing column ${absent.join(', ')}`);
158
+ return absent.length > 0;
159
+ };
160
+ if (rule.kind === 'state') {
161
+ if (missing(rule.column))
162
+ continue;
163
+ const other = rule.column === 'state' ? 'status' : 'state';
164
+ if (columns.has(other))
165
+ unsupported(`unexpected ${other} column`);
166
+ for (const entry of db.prepare(`SELECT "${rule.column}" AS value,count(*) AS count FROM "${id.data}" GROUP BY "${rule.column}"`).all()) {
167
+ const group = z.object({ value: z.unknown(), count: z.number().int() }).parse(entry);
168
+ const value = typeof group.value === 'string' ? group.value : null;
169
+ if (value !== null && rule.terminal.includes(value))
170
+ continue;
171
+ if (value !== null && rule.uncertain.includes(value))
172
+ result.unknown += group.count;
173
+ else if (value !== null && rule.active.includes(value))
174
+ result.active += group.count;
175
+ else
176
+ unsupported(`unrecognized ${rule.column} ${JSON.stringify(group.value)}`, group.count || 1);
177
+ }
178
+ continue;
179
+ }
180
+ if (rule.kind === 'passive') {
181
+ if (columns.has('state') || columns.has('status'))
182
+ unsupported('passive table has a state or status column');
183
+ continue;
184
+ }
185
+ switch (rule.rule) {
186
+ case 'a2a_tasks': {
187
+ if (missing('status', 'task_json'))
188
+ break;
189
+ if (columns.has('state'))
190
+ unsupported('unexpected state column');
191
+ for (const entry of db.prepare('SELECT status,task_json FROM a2a_tasks').iterate()) {
192
+ const task = z.object({ status: z.unknown(), task_json: z.unknown() }).parse(entry);
193
+ let json;
194
+ try {
195
+ json = JSON.parse(String(task.task_json));
196
+ }
197
+ catch {
198
+ unsupported('task JSON does not parse');
199
+ continue;
200
+ }
201
+ const parsed = A2ATaskJson.safeParse(json);
202
+ const indexed = a2aState(task.status), recorded = parsed.success ? a2aState(parsed.data.status.state) : null;
203
+ if (indexed === null || recorded === null || indexed !== recorded)
204
+ unsupported('indexed status and task JSON disagree');
205
+ for (const value of new Set([indexed, recorded])) {
206
+ if (value === 0)
207
+ result.unknown++;
208
+ else if (value !== null && A2A_ACTIVE.has(value))
209
+ result.active++;
210
+ }
211
+ }
212
+ break;
213
+ }
214
+ case 'admission_fence': {
215
+ if (columns.has('state') || columns.has('status')) {
216
+ unsupported('unexpected state or status column');
217
+ break;
218
+ }
219
+ const fence = count('SELECT count(*) AS count FROM admission_fence');
220
+ if (fence)
221
+ unsupported('admission fence is closed', fence);
222
+ break;
223
+ }
224
+ case 'a2a_team_child_claims': {
225
+ if (columns.has('state') || columns.has('status')) {
226
+ unsupported('unexpected state or status column');
227
+ break;
228
+ }
229
+ if (missing('acknowledged', 'settlement_json'))
230
+ break;
231
+ // Gateway startup flushes retained settlements, even though this table has no state column.
232
+ result.active += count('SELECT count(*) AS count FROM a2a_team_child_claims WHERE acknowledged IS NULL OR acknowledged!=1 OR settlement_json IS NULL');
233
+ for (const entry of db.prepare('SELECT settlement_json FROM a2a_team_child_claims WHERE settlement_json IS NOT NULL').iterate()) {
234
+ let json;
235
+ try {
236
+ json = JSON.parse(String(z.object({ settlement_json: z.unknown() }).parse(entry).settlement_json));
237
+ }
238
+ catch {
239
+ unsupported('settlement JSON does not parse');
240
+ continue;
241
+ }
242
+ const outcome = Settlement.safeParse(json);
243
+ if (!outcome.success)
244
+ unsupported('unrecognized settlement outcome');
245
+ else if (outcome.data.outcome === 'unknown')
246
+ result.unknown++;
247
+ else if (outcome.data.outcome === 'input_required')
248
+ result.active++;
249
+ }
250
+ break;
251
+ }
252
+ case 'a2a_request_receipts': {
253
+ if (columns.has('state') || columns.has('status')) {
254
+ unsupported('unexpected state or status column');
255
+ break;
256
+ }
257
+ if (!missing('task_id'))
258
+ result.active += count("SELECT count(*) AS count FROM a2a_request_receipts WHERE task_id IS NULL OR task_id=''");
259
+ break;
260
+ }
261
+ case 'channel_inbound': {
262
+ if (columns.has('state') || columns.has('status')) {
263
+ unsupported('unexpected state or status column');
264
+ break;
265
+ }
266
+ if (missing('task_id', 'platform', 'account', 'update_id'))
267
+ break;
268
+ if (!names.has('channel_deliveries')) {
269
+ unsupported('channel_deliveries table is missing');
270
+ break;
271
+ }
272
+ result.active += count(`SELECT count(*) AS count FROM channel_inbound AS inbound
273
+ LEFT JOIN channel_deliveries AS delivery ON delivery.platform=inbound.platform
274
+ AND delivery.account=inbound.account AND delivery.update_id=inbound.update_id
275
+ WHERE inbound.task_id IS NULL${columns.has('disposition') ? " AND inbound.disposition='admitted'" : ''}${columns.has('channel_type') ? ` AND NOT ${SEEDED_INBOUND}` : ''}
276
+ AND (delivery.id IS NULL OR delivery.state IN ('queued','unknown'))`);
277
+ break;
278
+ }
279
+ case 'task_recovery': {
280
+ if (columns.has('state')) {
281
+ unsupported('unexpected state column');
282
+ break;
283
+ }
284
+ if (missing('status', 'task_id'))
285
+ break;
286
+ if (!names.has('tasks')) {
287
+ unsupported('tasks table is missing');
288
+ break;
289
+ }
290
+ for (const entry of db.prepare(`SELECT r.status AS value, t.state AS task_state, count(*) AS count FROM task_recovery r
291
+ LEFT JOIN tasks t ON t.id=r.task_id GROUP BY r.status, t.state`).all()) {
292
+ const group = z.object({ value: z.unknown(), task_state: z.unknown(), count: z.number().int() }).parse(entry);
293
+ const value = typeof group.value === 'string' ? group.value : null;
294
+ const is = (list) => value !== null && list.includes(value);
295
+ if (is(TASK_RECOVERY_STATUSES.terminal))
296
+ continue;
297
+ if (is(TASK_RECOVERY_STATUSES.uncertain))
298
+ result.unknown += group.count;
299
+ // A ready or reconciling plan whose task no longer runs was settled another way: nothing resumes it.
300
+ else if (is(TASK_RECOVERY_STATUSES.active)) {
301
+ if (group.task_state === 'running')
302
+ result.active += group.count;
303
+ }
304
+ else
305
+ unsupported(`unrecognized status ${JSON.stringify(group.value)}`, group.count || 1);
306
+ }
307
+ break;
308
+ }
309
+ }
310
+ }
311
+ finally {
312
+ if (problems.length)
313
+ result.problems = problems;
314
+ }
315
+ }
316
+ const total = (key) => tables.reduce((sum, table) => sum + table[key], 0);
317
+ // An empty file is not an Ardent journal.
318
+ const unsupported = total('unsupported') + (rows.length === 0 ? 1 : 0);
319
+ const active = total('active'), unknown = total('unknown');
320
+ return { policy_version: JOURNAL_POLICY_VERSION, idle: active === 0 && unknown === 0 && unsupported === 0, active, unknown, unsupported, tables };
321
+ }
322
+ /**
323
+ * Inspect a journal file in place, read-only. SQLite may still create or touch
324
+ * the `-shm` file beside it, so use this only on a private copy (for example a
325
+ * snapshot staging directory). For a live profile directory use `inspectJournal`.
326
+ */
327
+ export function inspectJournalFile(path) {
328
+ const db = new Database(path, { readonly: true, fileMustExist: true });
329
+ try {
330
+ return inspectOpen(db);
331
+ }
332
+ finally {
333
+ db.close();
334
+ }
335
+ }
336
+ async function sha256(path) {
337
+ const hash = createHash('sha256');
338
+ const stream = createReadStream(path);
339
+ stream.on('data', (chunk) => { hash.update(chunk); });
340
+ await finished(stream);
341
+ return hash.digest('hex');
342
+ }
343
+ async function regularFile(path, optional = false) {
344
+ const stat = await lstat(path).catch((error) => {
345
+ if (optional && error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT')
346
+ return undefined;
347
+ throw error;
348
+ });
349
+ if (!stat)
350
+ return false;
351
+ if (!stat.isFile() || stat.isSymbolicLink())
352
+ throw new Error('Journal path must be a regular file');
353
+ return true;
354
+ }
355
+ /**
356
+ * Inspect a profile's journal (`state/ardent.sqlite`) without changing a byte
357
+ * of it. The database and its WAL are copied to a private directory, verified
358
+ * by digest, and inspected there, so committed but uncheckpointed work in the
359
+ * WAL is counted. Throws when the files change during inspection, which means
360
+ * a gateway is writing. It does not check the gateway lock: an idle gateway
361
+ * that writes nothing during the copy can be reported idle, so stop the
362
+ * profile (or hold its gateway lock) before relying on `idle` for a snapshot.
363
+ * Tables an extension created and this policy does not classify count as
364
+ * `unsupported`, so such a profile is never reported idle.
365
+ */
366
+ export async function inspectJournal(path) {
367
+ await regularFile(path);
368
+ const scratch = await mkdtemp(join(tmpdir(), 'ardent-journal-'));
369
+ try {
370
+ await chmod(scratch, 0o700);
371
+ const destination = join(scratch, 'journal.sqlite');
372
+ const sources = [];
373
+ for (const suffix of ['', '-wal']) {
374
+ const source = path + suffix;
375
+ if (!await regularFile(source, suffix !== ''))
376
+ continue;
377
+ const digest = await sha256(source), copied = destination + suffix;
378
+ await copyFile(source, copied);
379
+ await chmod(copied, 0o600);
380
+ if (await sha256(copied) !== digest)
381
+ throw new Error('Journal changed while it was being copied for inspection');
382
+ sources.push({ path: source, sha256: digest });
383
+ }
384
+ const result = inspectJournalFile(destination);
385
+ for (const source of sources)
386
+ if (await sha256(source.path) !== source.sha256)
387
+ throw new Error('Journal changed during inspection');
388
+ if (await regularFile(path + '-wal', true) !== sources.some(source => source.path === path + '-wal'))
389
+ throw new Error('Journal WAL appeared or disappeared during inspection');
390
+ return result;
391
+ }
392
+ finally {
393
+ await rm(scratch, { recursive: true, force: true });
394
+ }
395
+ }
package/dist/log.d.ts ADDED
@@ -0,0 +1,11 @@
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(options?: {
8
+ requestContext?: boolean;
9
+ }): Logger;
10
+ /** A logger that writes nothing: the default of a runtime or component nobody gave a logger. */
11
+ export declare const silentLogger: Logger;
package/dist/log.js ADDED
@@ -0,0 +1,12 @@
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(options = {}) {
7
+ return createLogger({ bindings: { service: 'ardent' }, write: line => { process.stderr.write(`${line}\n`); },
8
+ // Task work outlives the request that queued it: without the request context, its lines carry their own ids.
9
+ ...(options.requestContext === false ? { context: () => undefined } : {}) });
10
+ }
11
+ /** A logger that writes nothing: the default of a runtime or component nobody gave a logger. */
12
+ export const silentLogger = createLogger({ level: 'silent' });
@@ -147,6 +147,7 @@ export class MattermostAdapter {
147
147
  const event = { platform: 'mattermost', channel_type: isDm ? 'mattermost_dm' : 'mattermost_channel',
148
148
  account: me.id, user: post.user_id, conversation: post.channel_id, thread: post.root_id || null, update_id: post.id, reply_to: post.id, text, attachments, authorized: true, bot_message: false };
149
149
  const operation = this.#core.handle(event, async (reply) => this.#deliver({ channel_id: post.channel_id, root_id: post.root_id, id: post.id }, channelType, reply)).catch(error => {
150
+ this.runtime.logger.warn('Mattermost post failed', { post_id: post.id, channel_id: post.channel_id, err: error });
150
151
  this.runtime.store.setCursor(`mattermost:${me.id}:last_error`, error instanceof Error ? error.message.slice(0, 500) : 'unknown');
151
152
  });
152
153
  // A live post never moves an existing boundary: posts missed before it are
@@ -284,8 +285,9 @@ export class MattermostAdapter {
284
285
  const posts = await this.#page(channelId, undefined, readSignal);
285
286
  if (signal?.aborted)
286
287
  return 0;
288
+ // Not admitted work: nothing will answer these posts.
287
289
  for (const post of posts)
288
- store.claimInbound('mattermost', me.id, post.id);
290
+ store.claimInbound('mattermost', me.id, post.id, 'unknown', 'skipped_stale');
289
291
  const newest = posts[0];
290
292
  // An empty channel starts at 0: every later post is new, whatever the clocks say.
291
293
  this.#saveBoundary(channelId, newest ? { last_ms: newest.create_at, last_post_id: newest.id } : { last_ms: 0, last_post_id: null });
@@ -515,8 +517,11 @@ export class MattermostAdapter {
515
517
  if (signal.aborted)
516
518
  break;
517
519
  failures++;
518
- if (failures >= 10)
520
+ if (failures >= 10) {
521
+ this.runtime.logger.error('Mattermost connection stopped after 10 failures', { err: error });
519
522
  throw error;
523
+ }
524
+ this.runtime.logger.warn('Mattermost connection failed; reconnecting', { failures, err: error });
520
525
  }
521
526
  if (!signal.aborted)
522
527
  await sleep(Math.min(30_000, 1000 * 2 ** Math.min(failures, 5)), undefined, { signal }).catch(() => { });