@hivemagnus/ardent 3.3.0 → 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 (48) hide show
  1. package/README.md +10 -973
  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 +10 -0
  12. package/dist/api.js +296 -127
  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 +55 -3
  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/job-engine.d.ts +3 -0
  26. package/dist/job-engine.js +5 -0
  27. package/dist/journal.d.ts +17 -2
  28. package/dist/journal.js +48 -4
  29. package/dist/log.d.ts +5 -1
  30. package/dist/log.js +6 -2
  31. package/dist/mattermost.js +7 -2
  32. package/dist/memory.js +3 -2
  33. package/dist/metrics.d.ts +34 -0
  34. package/dist/metrics.js +73 -0
  35. package/dist/missions.js +2 -1
  36. package/dist/plugin-http.js +10 -1
  37. package/dist/plugin-sdk.d.ts +2 -0
  38. package/dist/plugin-sdk.js +2 -0
  39. package/dist/retention.d.ts +64 -0
  40. package/dist/retention.js +239 -0
  41. package/dist/runtime.d.ts +17 -1
  42. package/dist/runtime.js +52 -15
  43. package/dist/skills.js +5 -4
  44. package/dist/store.d.ts +28 -0
  45. package/dist/store.js +97 -14
  46. package/dist/telegram.js +5 -1
  47. package/package.json +2 -2
  48. package/profiles/assistant/config.yaml +1 -1
package/README.md CHANGED
@@ -12,7 +12,7 @@ What you get:
12
12
  per-task event journal in SQLite. Interrupted work resumes from its last
13
13
  verified step after a restart; an operation whose effect is uncertain is
14
14
  held for a decision, never silently replayed (see
15
- [Execution recovery](#execution-recovery)).
15
+ [Execution recovery](docs/recovery.md#execution-recovery)).
16
16
  - **Management API** (Hono, bearer-token protected) for tasks, sessions,
17
17
  config, identity, skills, peers, channels, and live event streams, including
18
18
  the reply text as the model writes it. The
@@ -81,7 +81,7 @@ ARDENT_LLAMA_MODEL=your-model-name
81
81
  EOF
82
82
  ardent chat # interactive session
83
83
  ardent run --prompt "Summarize RFC 9110 in three bullets"
84
- ardent mission submit --mission-file mission.json # a team mission, see below
84
+ ardent mission submit --mission-file mission.json # a team mission (docs/missions-and-artifacts.md)
85
85
  ardent gateway run # management API, A2A, channels, jobs
86
86
  ```
87
87
 
@@ -105,979 +105,16 @@ Magnus installs that pinned package on a node and creates profiles with its
105
105
  and Magnus's [Ardent guide](https://github.com/ChefTaco/magnus/blob/main/docs/ARDENT.md).
106
106
  Ardent Project Studio and the UI reach those profiles only through Magnus.
107
107
 
108
- ### Native suite artifact
108
+ ## Documentation
109
109
 
110
- Build this repository's `Dockerfile` from the repository root, then select that
111
- reviewed immutable image ID or digest in a [Magnus](https://github.com/ChefTaco/magnus)
112
- checkout:
110
+ The guides in [`docs/`](docs/):
113
111
 
114
- ```bash
115
- npm run build:native-agent -- --product ardent --image PINNED_IMAGE --output NEW_DIRECTORY
116
- ```
117
-
118
- The archive includes the exact Node binary, the public Ardent package, locked
119
- production dependencies and their licenses. It contains no inference runtime or
120
- models. The descriptor supplies literal launch arguments, an exact version
121
- preflight and a read-only acceptance command for Hive's signed release matrix.
122
- Local export does not publish or certify an artifact.
123
-
124
- Select an existing profile explicitly with `--profile-path` and keep credentials
125
- in an owned, mode `0600` environment file selected with `--env-file`. The native
126
- launcher loads that file before Node starts, including `NODE_EXTRA_CA_CERTS`
127
- when a private CA is required. It never evaluates the file as shell code.
128
- Profile initialization is a separate operator action and refuses an existing
129
- profile. Provider sign-in remains explicit.
130
-
131
- `ardent --env-file FILE --profile-path DIR acceptance` checks the running
132
- gateway's authenticated status, exact version, profile, backend and dependency
133
- readiness. It returns bounded JSON without credentials or upstream diagnostics.
134
- The default target is the profile's loopback management listener; an optional
135
- `ARDENT_ACCEPTANCE_URL` must be an HTTPS origin, with an optional protected
136
- `ARDENT_ACCEPTANCE_CA_FILE`. Redirects and nonlocal cleartext are refused.
137
- Acceptance executes no model generation or tools. Verify scoped inference,
138
- memory, skills and channel workflows separately before enabling consumers.
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
-
194
- ## Configuration
195
-
196
- `config.yaml` (schema 1) is validated strictly; unknown keys are rejected. A
197
- string of the form `${NAME}` is resolved from the environment (the profile
198
- `.env` is loaded automatically). Secrets are never written to the config,
199
- only the *names* of the environment variables that hold them.
200
-
201
- | Key | Default | Notes |
202
- |---|---|---|
203
- | `profile`, `name` | required | Profile ID and display name. |
204
- | `product` | `Ardent` | Shown in the profile summary. |
205
- | `timezone` | host zone, else `UTC` | IANA zone used for dates shown to the model. Job schedules carry their own zone. |
206
- | `identity.soul_file`, `identity.identity_file` | `SOUL.md`, `IDENTITY.md` | Persona files in the profile. |
207
- | `execution` | required | `backend: llamacpp \| codex`, step, tool-call, parallelism, and deadline limits. See [Tool scheduling](#tool-scheduling). |
208
- | `execution.recovery.enabled` | `true` | Resume tasks interrupted by a crash or restart. `false` holds them as `unknown`, as before. See [Execution recovery](#execution-recovery). |
209
- | `execution.recovery_max_new_deadline_seconds` | `deadline_seconds` | Longest deadline an operator may give `retry_with_new_deadline`, 1-86400. |
210
- | `providers.llamacpp` | required | `base_url`, `model`, `api_key_env`, `request_timeout_seconds`, optional `context_window_tokens`, `max_output_tokens`, `reasoning_effort`. |
211
- | `providers.codex` | required | `command`, `model`, `auth_mode: chatgpt \| api_key` (default `chatgpt`), `durable_threads` (default `true`: task threads are not ephemeral and their ids are recorded for recovery); `approval_policy: never` and `sandbox: read-only` are fixed. |
212
- | `memory` | `{ provider: none }` | See [HiveMem](#hivemem-memory). |
213
- | `research` | disabled | `enabled`, `searxng_url`, `firecrawl_url`, `firecrawl_token_env`. Enables the `news_search`, `news_article`, `news_collect`, and `news_capabilities` tools. |
214
- | `skills` | `directories: [skills]`, `enabled: []` | Only enabled skills are shown to the model. |
215
- | `a2a` | disabled | See [A2A](#a2a). |
216
- | `channels.telegram`, `channels.mattermost` | disabled | See [Chat channels](#chat-channels). |
217
- | `integrations.magnus_control` | disabled | See [Magnus Control tools](#magnus-control-tools). |
218
- | `artifacts.max_bytes` | `2097152` (2 MiB) | Largest artifact a task may store, export to a peer or import, up to 64 MiB. See [Artifact transfer v2](#artifact-transfer-v2-and-renditions). |
219
- | `plugins` | `[]` | See [Plugins](#plugins). |
220
- | `api` | `127.0.0.1:9910`, `ARDENT_API_TOKEN` | Management listener and the env var holding its bearer token. A non-loopback host is refused; put a TLS proxy in front instead. |
221
-
222
- `ardent config schema` prints the full JSON Schema, and `ardent config
223
- validate` checks a profile without starting it.
224
-
225
- A few settings come from the environment rather than `config.yaml`:
226
-
227
- | Variable | Default | Notes |
228
- |---|---|---|
229
- | `ARDENT_HOME` | `~/.ardent` | Root of the profiles directory and the shared model policy. |
230
- | `ARDENT_API_TOKEN` | — | Management API bearer token (the name is `api.token_env`). |
231
- | `ARDENT_INSTANCE_REF` | `local.<profile>` | The instance part of this runtime's qualified execution references (`hx1:ardent:<instance>:...`). Magnus sets `<node id>.<profile>`. 1 to 96 characters of `A-Z a-z 0-9 . _ -`; any other value stops the runtime from starting and is listed by `ardent config validate`. See [Execution ancestry](#execution-ancestry). |
232
-
233
- ### Tool scheduling
234
-
235
- Task concurrency and tool concurrency are separate settings:
236
-
237
- | Key | Default | Notes |
238
- |---|---|---|
239
- | `execution.max_parallel_tasks` | `3` | Tasks running at once, 1-16. The runtime runs at most 4. |
240
- | `execution.max_parallel_tool_calls` | `4` | Tool calls from one model turn in flight at once, 1-16. |
241
- | `execution.max_parallel_tools` | none | Deprecated. Despite its name it limits tasks. It is used only when `max_parallel_tasks` is absent, and `ardent config validate` and `ardent doctor` then report the notice `execution.max_parallel_tools is deprecated: it limits tasks; set max_parallel_tasks`. A notice never makes the profile unready. |
242
-
243
- The llama.cpp and Codex backends dispatch tool calls through the same scheduler:
244
-
245
- - A call is *parallel-eligible* when its tool is a `read` tool that does not
246
- declare `concurrency: 'serial'`, or any tool that declares
247
- `concurrency: 'parallel'`. Every other call, including an unknown tool and
248
- `team_ask_user`, is serial.
249
- - Calls are admitted in the order the model emitted them (for Codex, the order
250
- the calls arrive). Consecutive parallel-eligible calls overlap, at most
251
- `max_parallel_tool_calls` at a time. A serial call is a barrier: it starts
252
- after every earlier call has settled, and later calls wait for it. A write
253
- therefore never overlaps anything unless its tool opts in.
254
- - Each dispatch waits while the task is paused, checks `max_tool_calls` (for the
255
- whole task), journals `tool_attempt`, waits for team admission, runs plugin
256
- `beforeToolCall` hooks, invokes the tool, journals `tool_result` with the call
257
- `id`, and then runs `afterToolCall` hooks.
258
- - llama.cpp receives the results in the order it emitted the calls, each bound
259
- to its call id. Codex binds each result to its own RPC request, and its
260
- follow-up turn lists results in completion order.
261
- - On cancellation, calls that were not dispatched settle as
262
- `{ ok: false, code: 'CANCELLED', effect: 'none' }` and are journaled as
263
- `tool_not_dispatched` (with a `reason`). A call already started keeps its
264
- uncertainty, so a cancelled task with a started call that may have had an
265
- effect (not a `read`, and not settled without effect, for example denied by a
266
- plugin) is `unknown`, never `cancelled`. A call that would exceed
267
- `max_tool_calls` is not dispatched and fails the task.
268
-
269
- Each tool receives `ctx.idempotencyKey`, `sha256("<task id>:<call id>")` in
270
- hex, as the third `invoke` argument (`defineTool` handlers receive it as their
271
- third argument). A tool may forward it to its service so that a repeated
272
- dispatch of the same model call is harmless. A tool can also declare
273
- `idempotent: true` (repeating it with identical arguments and key is safe) and a
274
- `reconcile(input, ctx, signal)` hook that asks its service what happened to an
275
- interrupted call. [Execution recovery](#execution-recovery) re-dispatches an
276
- interrupted idempotent call under the same key and asks `reconcile` before it
277
- resumes a task; a tool that declares neither is held for an operator when one of
278
- its calls is interrupted. `artifact_write` and `document_render` are idempotent
279
- (a repeat under the same key returns the same registration) and reconcile from
280
- their manifest row; `team_handoff`, `team_ask_user`, `team_propose_decision` and
281
- `development_note` reconcile against their local journal rows. HiveMem writes
282
- and `news_collect` declare neither, so they are held.
283
-
284
- ### HiveMem memory
285
-
286
- Memory is off by default. To use a HiveMem server:
287
-
288
- ```yaml
289
- memory:
290
- provider: hivemem
291
- base_url: ${HIVEMEM_API_URL}
292
- token_env: HIVEMEM_TOKEN
293
- agent_id: assistant
294
- workspace_id: ${HIVEMEM_WORKSPACE}
295
- default_scope: private
296
- ```
297
-
298
- Direct conversations then get `hivemem_status`, `hivemem_search`,
299
- `hivemem_browse`, and explicit write tools. Peers never read private memory; a
300
- validated team mission may grant read access to one shared `project:<id>`
301
- scope.
302
-
303
- To rotate the HiveMem credential without a restart, write the new token into the
304
- profile environment file (`.env`, or the `--env-file` the gateway started with)
305
- and call `POST /api/v1/memory/credential/reload` with no body or `{}`. The
306
- gateway re-reads only the `token_env` variable, checks that it is a well-formed
307
- JWT, and uses it for every later HiveMem request; requests in flight finish
308
- with the previous token. It answers `{"reloaded": true, "token_env": "...",
309
- "changed": true|false}`, `409` when memory is not `hivemem`, and `422` (the old
310
- token stays in use) when the new value is missing or malformed.
311
-
312
- ### Chat channels
313
-
314
- ```yaml
315
- channels:
316
- telegram:
317
- enabled: true
318
- token_env: TELEGRAM_BOT_TOKEN
319
- allowed_user_ids: [123456789] # only these users are answered
320
- mattermost:
321
- enabled: true
322
- base_url: ${MATTERMOST_URL} # e.g. https://chat.example.com
323
- token_env: MATTERMOST_TOKEN
324
- allowed_user_ids: [user-id]
325
- require_mention: true
326
- reply_mode: thread # thread | flat
327
- catchup: # optional; these are the defaults
328
- max_posts: 2000 # 1-10000 posts from others per walk
329
- max_age_hours: 24 # older missed posts are skipped, not answered
330
- ```
331
-
332
- Telegram uses long polling; Mattermost uses its v4 REST and WebSocket APIs.
333
- Both support `/help`, `/new`, `/status`, `/jobs`, `/model`, `/stop`, `/tasks`,
334
- and `/sources`. Each inbound message and outbound reply is journaled, so a
335
- restart never sends the same reply twice.
336
-
337
- **Mattermost catch-up.** Posts missed while Ardent was stopped or its
338
- WebSocket was down are recovered from history. Ardent keeps a boundary per
339
- channel (the newest post up to which everything older is settled). On start,
340
- after every reconnect, and every 30 seconds, it walks back from the newest post
341
- to that boundary in pages of 200 (`before=<post id>`), then handles the posts
342
- oldest first. This works with Mattermost and ChatterMost alike.
343
-
344
- | Key | Default | Meaning |
345
- |---|---|---|
346
- | `catchup.max_posts` | `2000` (at most `10000`) | Posts from others that one walk reads. The bot's own posts do not count, but a walk reads at most `2 × max_posts / 200` pages. |
347
- | `catchup.max_age_hours` | `24` | A missed post older than this is claimed as `skipped_stale` and not answered. |
348
-
349
- Every eligible post in the walk ends in exactly one of four ways:
350
-
351
- - **Answered.** It goes through the normal channel path: an atomic claim, then the task, then the reply.
352
- - **Already claimed.** A live event, an earlier walk or an earlier run claimed it. It is never answered again, so a reply whose outcome is unknown is never replayed.
353
- - **Skipped as stale.** The claim is recorded with `disposition` `skipped_stale`.
354
- - **Lost to a permanent gap.** The gap is recorded as a row with `walk_bound` when the walk reached its bound before the boundary, or `retention` when the server no longer holds the history (for example, the `before` pivot disappeared).
355
-
356
- The boundary moves only past posts settled in order, so an interrupted walk
357
- resumes where it stopped. A channel seen for the first time is seeded without
358
- answering its history.
359
-
360
- Replies that the server rate-limits (`429`) wait out `Retry-After` under the
361
- `mattermost` retry policy (see [Retries](#retries)). `GET /api/v1/status` reports the latest walk of each channel under
362
- `channels.mattermost.catchup`:
363
-
364
- - `state`: `idle`, `catching_up`, `complete` or `gap`.
365
- - Counters: `recovered`, `skipped_stale`, `already_claimed` and `pages`.
366
- - Gaps: the gap count and `last_gap`.
367
-
368
- ### A2A
369
-
370
- ```yaml
371
- a2a:
372
- enabled: true
373
- bindings: [jsonrpc, http-json, grpc]
374
- public_url: ${ARDENT_A2A_PUBLIC_URL} # advertised origin, e.g. https://agent.example.com:9900
375
- listen_host: 127.0.0.1
376
- listen_port: 9900 # gRPC listens on listen_port + 1
377
- peers_file: peers.yaml
378
- skill: { id: research, name: Research, description: Sourced answers, tags: [research] }
379
- hermes_compat: false
380
- rate_limit: # all optional; these are the defaults
381
- enabled: true
382
- ip_requests_per_minute: 600 # every HTTP request, before authentication
383
- ip_burst: 120
384
- peer_requests_per_minute: 300 # after authentication, per peer (also gRPC)
385
- peer_burst: 60
386
- max_concurrent_tasks_per_peer: 16 # queued and running tasks
387
- trusted_proxies: [] # proxies whose X-Forwarded-For is believed
388
- ```
389
-
390
- A limited request is answered with `429` and `Retry-After`. The client address
391
- is the socket address unless the connecting address is listed in
392
- `trusted_proxies` (addresses or CIDR ranges). Behind a reverse proxy, all clients
393
- otherwise share the proxy's address and one bucket, so list the proxy there.
394
- gRPC requests count against the peer limit and the task cap; the address limit
395
- covers HTTP only. Limits are kept in memory, per process.
396
-
397
- Peers are listed in `peers.yaml` with the environment variables holding their
398
- inbound and outbound bearer tokens. An ordinary peer task can reach only the
399
- public news tools. A peer that sends a validated team mission envelope gets
400
- the tools its `resources` allow (`public:news`, `magnus:fleet`,
401
- `magnus:node:<id>`, or `tool:<name>` for any registered tool) and must return
402
- a structured, evidence-checked team result.
403
-
404
- `hermes_compat: true` additionally serves the authenticated
405
- `/.well-known/hermes-team-card.json` discovery document and accepts Hermes
406
- Agent's slash-style JSON-RPC method aliases (`message/send`, `tasks/get`, ...).
407
-
408
- `ardent a2a discover <peer>` and `ardent a2a call <peer> --prompt TEXT` talk
409
- to configured peers from the command line.
410
-
411
- ### Magnus Control tools
412
-
413
- Read-only fleet tools for a [Magnus](https://github.com/ChefTaco/magnus)
414
- Control API (fleet inventory, readiness, node health, dependency impact,
415
- anomalies, command status, and more). Enable them with
416
- `integrations.magnus_control.enabled: true` or `ARDENT_MAGNUS_CONTROL_TOOLS=true`.
417
- The base URL comes only from `integrations.magnus_control.base_url` (default
418
- `${ARDENT_MAGNUS_API_URL}`) and the read token from the env var named by
419
- `token_env` (default `ARDENT_MAGNUS_READ_TOKEN`). Bearer tokens are sent only
420
- over HTTPS or to loopback.
421
-
422
- ### Scheduled jobs
423
-
424
- Put job definitions in `jobs/active.json` inside the profile:
425
-
426
- ```json
427
- {
428
- "schema_version": 1, "profile": "assistant", "revision": 1,
429
- "jobs": [{
430
- "id": "morning-news", "owner": "ardent", "enabled": true, "handler": "news.collect",
431
- "schedule": { "cron": "30 6 * * *", "timezone": "Europe/Berlin", "missed_window": "skip", "catch_up_minutes": 0 },
432
- "input": { "query": "open source AI agents", "max_articles": 3 },
433
- "delivery": { "kind": "none" },
434
- "policy": { "max_attempts": 2, "retry_backoff_seconds": 300 }
435
- }]
436
- }
437
- ```
438
-
439
- `ardent jobs definitions validate --source /abs/path.json` checks a file
440
- before you install it; `ardent jobs definitions status` and
441
- `GET /api/v1/jobs/definitions/status` report the installed revision and recent
442
- windows. The built-in handler is `news.collect` (requires `research`); plugins
443
- add more.
444
-
445
- A window that asks to retry with `effect_status: "none"` waits
446
- `retry_backoff_seconds · 2^(attempt-1)` with equal jitter (a random delay
447
- between half and all of it), and only while the next attempt would start
448
- before the job's next window is due; otherwise it ends `failed` with
449
- `RETRY_DEADLINE`.
450
-
451
- ### Retries
452
-
453
- Every retry site in Ardent names a policy in [`src/retry.ts`](src/retry.ts),
454
- built on the shared `@hivemagnus/hive-common/retry` helpers:
455
-
456
- | Site | Attempts | Backoff | Repeated when |
457
- |---|---|---|---|
458
- | llama.cpp completion and token count | 3 | 250 ms → 4 s, equal jitter; `Retry-After` (seconds or HTTP date) up to 10 s | transport error or 408/425/429/5xx before any response byte is read |
459
- | A2A Agent Card, Hermes team card, `getTask`, `listTasks`, extended card | 3 | 500 ms → 5 s, equal jitter | transport error or 408/425/429/5xx over HTTP |
460
- | A2A `SendMessage` | 3 | 500 ms → 5 s, equal jitter | as above, always with the same `messageId` |
461
- | A2A push delivery | 3 | `Retry-After` clamped to 1–5 s | 408/425/429/5xx (the callback did not accept the event) |
462
- | Telegram Bot API | 4 | Telegram's `retry_after`, capped at 60 s | 429 with `retry_after` |
463
- | Mattermost/ChatterMost REST | 3 | `Retry-After` up to 60 s (1 s without one) | 429 only (the request was not processed) |
464
- | Artifact transfer pull (import) | 5 | 500 ms → 8 s, equal jitter; `Retry-After` up to 30 s | transport error, a dropped response or 408/425/429/5xx; each attempt resumes from the retained bytes with `Range` and `If-Range` |
465
- | Codex turns, tools with a possible effect | 1 | — | never |
466
-
467
- Nothing is repeated once its effect is uncertain, after any response byte was
468
- consumed (a stream that fails mid-way is not restarted), past the deadline
469
- (`RETRY_DEADLINE`; for model calls the task deadline and the request timeout),
470
- or when the response carries `x-hive-retry: exhausted` (the gateway already
471
- retried). Cancelling during a backoff wait ends the call at once. Model
472
- retries are journaled as `model_retry` task events
473
- (`{ step, operation, attempt, reason, delay_ms }`); A2A outbound calls,
474
- push deliveries and Telegram deliveries record `attempts` on their rows.
475
-
476
- ### Model policy
477
-
478
- An optional, owner-only `$ARDENT_HOME/model-policy/active.json` selects the
479
- Codex model and reasoning effort and configures context compaction for all
480
- profiles under that home. [`model-policy.default.json`](model-policy.default.json)
481
- is a starting point; compaction is disabled until you enable it.
482
-
483
- ### Live task streams
484
-
485
- `GET /api/v1/tasks/{id}/stream` is a server-sent event stream. It sends:
486
-
487
- | Event | Data | Notes |
488
- |---|---|---|
489
- | `task.event` | A journal event | The event `id` is the journal sequence. Resume with `Last-Event-ID` or `?after=` |
490
- | `task.text` | `{step, text}`: the visible reply text of the current model step | Sent on connect and when a new step starts showing text |
491
- | `task.delta` | `{step, text}`: text to append | |
492
- | `task.done` | The finished task | Its `result` is the authoritative answer |
493
-
494
- The stream closes after 60 seconds; reconnect to continue.
495
- [`@hivemagnus/ardent-client`](client/README.md) does this for you
496
- (`tasks.follow`).
497
-
498
- Live text works the same for every backend and caller:
499
- - It holds only what a user would see. Structured output, such as tool or research JSON, is never streamed.
500
- - It is not journaled and has no event id. A reconnect receives a `task.text` snapshot instead of a replay.
501
- - Codex sends its answer as one piece when the turn completes.
502
-
503
- `ardent chat` uses the same rule to print replies as they arrive.
504
-
505
- ### Team missions
506
-
507
- `POST /api/v1/missions` runs a team mission locally, for a coordinator such as
508
- a project studio. It is accepted like a task (`202 {task_id, state}`) and
509
- streams on `/api/v1/tasks/{id}/stream` like any task.
510
-
511
- ```json
512
- {
513
- "objective": "Draft the opening scene",
514
- "mission": { "id": "scene-1", "revision": 1, "parent_task": null, "constraints": [],
515
- "allowed_actions": ["observe", "analyze", "create_artifact"],
516
- "resources": ["project:adventure", "tool:artifact_write", "tool:team_handoff"],
517
- "deadline": 1893456000, "acceptance_criteria": ["The scene is saved"], "expected_artifacts": [] },
518
- "context_items": [{ "title": "Brief", "mime": "text/markdown", "text": "..." }],
519
- "labels": { "project": "adventure" },
520
- "session_id": "<a session opened with context: mission>",
521
- "idempotency_key": "scene-1-turn-1"
522
- }
523
- ```
524
-
525
- - `mission` is the A2A team mission shape. The task runs in context `mission`,
526
- and its tools follow the peer mission rule: `resources` grant tools, never
527
- the model.
528
- - The objective is at most 16,000 characters; `context_items` together at most
529
- 64 KiB. Context items reach the model as tool data, so the context fitter can
530
- shorten them; the full text stays in the task journal.
531
- - Memory reads use the agent's private scope plus one `project:<id>` grant.
532
- Missions never write memory.
533
- - A session for a mission is opened with `POST /api/v1/sessions`
534
- `{key, context: "mission"}`.
535
- - The task result is a `TeamResult` JSON document. A prose reply becomes a
536
- `partial` result with the reply as `summary`; a reply carrying a
537
- `team_result` is checked against the mission and the observed artifacts.
538
-
539
- Mission tools are granted with `tool:<name>` resources. The coordination
540
- tools only record a journal event; Ardent never acts on them itself:
541
-
542
- | Tool | Journal event | Notes |
543
- |---|---|---|
544
- | `team_handoff {to_role, objective, deliverables?, note?}` | `team_handoff` | Asks the coordinator to give work to another role |
545
- | `team_ask_user {question, options?}` | `team_ask_user` | Ends the turn; the result is `input_required` with a clarification |
546
- | `team_propose_decision {title, statement, rationale?}` | `team_propose_decision` | A proposal; only the user decides |
547
- | `artifact_write {name, mime, text \| base64 \| workspace_path, revises_sha256?}` | `artifact_registered` | Markdown, text, JSON, CSV, SVG, PNG, JPEG, WebP, PDF or DOCX, up to `artifacts.max_bytes`. `workspace_path` reads a file inside the profile's `workspace` |
548
- | `document_render {source_markdown, format: pdf \| docx, name, revises_sha256?}` | `artifact_registered` | Markdown to PDF or DOCX, up to `artifacts.max_bytes`; see below |
549
- | `development_note {kind, title, body, sources?}` | `development_note` | Also available in direct tasks; see below |
550
-
551
- `document_render` reads GitHub-flavoured Markdown: headings, paragraphs, bold,
552
- italic, strikethrough, inline code, links, bulleted, numbered and task lists,
553
- block quotes, code blocks, tables and horizontal rules. It never fetches a URL
554
- or reads a file. PDF output draws ` ```svg ` blocks as vector figures; images
555
- keep only their alternative text. DOCX output is written with
556
- [`@hivemagnus/canvas-word-codec`](https://www.npmjs.com/package/@hivemagnus/canvas-word-codec):
557
-
558
- - Headings use Word's Heading 1-6 styles, so they appear in the navigation
559
- pane; links to `http(s)` URLs become hyperlinks and other link targets are
560
- kept as text after the label.
561
- - Bulleted lists and numbered lists that start at 1 use Word numbering. Word
562
- numbering here has one level, so nested lists are indented, and a numbered
563
- list that starts elsewhere or has nested content gets its numbers as text.
564
- - Tables keep their header row, column alignment and inline formatting; a
565
- table longer than 100 rows continues in another table.
566
- - PNG and JPEG images given as `data:` URIs are embedded. Other images become
567
- an `[image: alt]` placeholder and ` ```svg ` figures a short note, since
568
- DOCX output does not embed vector figures.
569
- - Raw HTML is kept as literal text. A document beyond the DOCX exchange
570
- limits (for example more than 100 table columns) fails with
571
- `DOCX_RENDER_FAILED` and no effect.
572
-
573
- Every registered artifact has an immutable manifest (digest, size, media type,
574
- revision, provenance and the artifact it supersedes). `revises_sha256` makes
575
- a new artifact a revision of an earlier one. `GET /api/v1/tasks/{id}/artifacts`
576
- lists a task's manifests and `GET /api/v1/artifacts/{sha256}/manifest` returns
577
- the newest manifest for a digest; the bytes stay at `GET /api/v1/artifacts/{id}`.
578
-
579
- ### Artifact transfer v2 and renditions
580
-
581
- Artifacts up to `artifacts.max_bytes` (at most 64 MiB) move between agents
582
- without inline task payloads, with bounded memory: every path streams. A
583
- profile advertises `urn:hive:artifact-transfer:2` on its Agent Card
584
- (`capabilities.extensions`, params `{max_bytes, range: true, renditions: true}`)
585
- and `capabilities.artifact_transfer: 2` in `GET /api/v1/status`.
586
-
587
- Manifest 1.1 is a strict superset of 1.0. It may add `rendition` (`role`
588
- `original | preview | model_input`, `of_sha256`, `purpose`, `transform {name,
589
- version, params}`) and `provenance.execution` (`root`, `task`, `step`, attribution
590
- only). It is as immutable as 1.0 and is shown only to v2 consumers: the existing
591
- manifest routes and the v1 descriptor still return 1.0, and stored 1.0 records
592
- are never rewritten.
593
-
594
- | Route | Purpose |
595
- | --- | --- |
596
- | `GET /api/v1/artifacts/{sha256}/content` | The bytes with `Accept-Ranges: bytes`, `ETag: "<sha256>"`, `Repr-Digest: sha-256=:<base64>:`, `X-Content-SHA256`, the manifest media type and `Content-Disposition: attachment; filename="<name>"`. One `Range` returns `206`, an unsatisfiable one `416`; an `If-Range` other than the ETag returns the whole artifact. |
597
- | `GET /api/v1/artifacts/{sha256}/renditions` | `{renditions: [{sha256, role, mime, size, purpose, width?, height?, has_alpha?}]}`, the original first, the same for the original or any rendition. Pick one with HiveCommon `selectRendition`; `download` always means the original. |
598
- | `GET /api/v1/artifacts/{sha256}/manifest/v2` | The newest manifest as 1.1. |
599
- | `POST /api/v1/artifacts/imports {peer_id, a2a_task_id, artifact_id, task_id?}` | `202 {import_id}`: pull an artifact a configured peer exported from one of its completed tasks. |
600
- | `GET /api/v1/artifacts/imports[/{id}]` | `{state: queued \| transferring \| verifying \| completed \| failed, received_bytes, size, attempts, error?}` |
601
-
602
- An import resolves the peer's descriptor, negotiates `min(peer max_bytes, local
603
- max_bytes)`, and appends to `<profile>/artifacts/.partial/<import id>`, committing
604
- `received_bytes` after an fsync every 4 MiB. After an interruption or restart it
605
- re-hashes the retained bytes as a stream and asks for the rest with `Range` and
606
- `If-Range`; the gateway resumes unfinished imports when it starts. Transport
607
- failures are retried under the `artifact_transfer` policy (see [Retries](#retries))
608
- within the import's deadline; `attempts` counts runs and retries. The final
609
- SHA-256 and size are verified: on `DIGEST_MISMATCH` the partial file is deleted,
610
- nothing is registered and nothing is retried until an operator reissues the
611
- import (`POST` again). The verified file is renamed into the content store (an
612
- existing digest is kept) and registered with a manifest 1.1 whose lineage adds
613
- the peer hop. Without `task_id`, the import records its own completed task.
614
- `ardent artifact import --peer <id> --task <a2a task> --artifact <id>` runs one
615
- from the command line and `ardent artifact imports` lists them.
616
-
617
- A team export to a peer is limited by `artifacts.max_bytes`. Each export emits a
618
- `Team artifact export v2` A2A artifact with one data part of media type
619
- `application/vnd.hive.artifact-transfer.v2+json` carrying `{manifest_1_1,
620
- content_path, renditions_path, size, sha256}`. Up to 2 MiB, the unchanged v1 text
621
- descriptor (`Team artifact export`) is still emitted; above it, a v1 consumer gets
622
- an explicit `TRANSFER_REQUIRES_V2` result that names the capability, and an
623
- importer facing a peer without the URN fails the same way. On the A2A listener,
624
- `/team/artifacts/{id}` serves the v1 full response without `Range` (verified as
625
- it streams) and gains `Range` and the headers above; `/team/artifacts/{id}/manifest`
626
- returns the 1.1 manifest and `/team/artifacts/{id}/renditions` the exported forms
627
- with their export IDs. Renditions of an exported original are exported with it.
628
-
629
- Plugins reach the same primitives through `ctx.runtime` (and types from
630
- `@hivemagnus/ardent/plugin-sdk`):
631
-
632
- - `ctx.runtime.artifacts.putStream(readable, {name, mediaType, expectedSha256?,
633
- expectedSize?, maxBytes?, inspect?, signal?})` stores a stream (temporary file,
634
- incremental SHA-256, size bound, fsync, rename) and returns the `Artifact`;
635
- `openRead(sha256, {start?, end?}, {verify?})` returns `{stream, size, sha256,
636
- start, end}`; `stat(sha256)` returns `{size}` or undefined.
637
- - `ctx.runtime.artifactManifests.registerStream({taskId, name, mime, stream,
638
- source, expectedSha256?, expectedSize?, revisesSha256?, ttlSeconds?, execution?})`
639
- stores and registers an original with a manifest 1.1, checking its content as it
640
- streams.
641
- - `ctx.runtime.artifactManifests.registerRendition({originalSha256, role: preview |
642
- model_input, purpose, transform, mime, bytes | stream, name?, width?, height?,
643
- has_alpha?, producer?})` registers a separate rendition artifact linked to its
644
- original; the original is never changed. `renditions(sha256)` lists the forms
645
- and `manifestV2(sha256)` returns the 1.1 record.
646
-
647
- `development_note` stores an append-only development record: the agent's own
648
- note about how it works (`epistemic: agent_reported`).
649
-
650
- ### Pause, preview and development history
651
-
652
- **Pause and resume.** `POST /api/v1/tasks/{id}/pause` holds a queued or running
653
- task: a queued task does not start (later tasks run instead), and a running
654
- task stops at its next step boundary, before a model call, before a tool call
655
- is journaled, or before it settles. The journal records `pause_requested`,
656
- `paused` (with the boundary) and `resumed`. Both routes are idempotent, and the
657
- deadline keeps running while a task is paused. `POST /api/v1/tasks/{id}/resume`
658
- releases it. Locally, `ardent tasks pause <id>` holds a queued task and
659
- `ardent tasks resume <id>` releases and runs it.
660
-
661
- **Preview.** `POST /api/v1/preview/tasks` `{prompt, overrides: {soul?,
662
- identity?, skills_enabled?, model?}, session_id?}` runs one task in context
663
- `preview` with unsaved changes. A preview gets the read-only direct tools, no
664
- mission tools and no memory tools. It never writes memory, development
665
- records, identity or configuration, and any artifact it produces expires after
666
- 24 hours. It streams like any task; a session for it is opened with
667
- `context: "preview"`. `ardent preview --prompt TEXT [--soul-file FILE]
668
- [--identity-file FILE] [--skills a,b | --no-skills] [--model NAME]` does the
669
- same locally.
670
-
671
- **Development history.** `GET /api/v1/development?after=&limit=&kind=` returns
672
- the agent's development in one portable record shape, oldest first, with a
673
- `next` cursor:
674
-
675
- ```json
676
- {"id": "dev_...", "agent_ref": "assistant", "kind": "self_understanding", "title": "...", "body": "...",
677
- "author": "agent", "epistemic": "agent_reported", "before_sha256": null, "after_sha256": null,
678
- "sources": [{"kind": "task", "ref": "..."}], "created_at": "2026-11-08T12:00:00.000Z"}
679
- ```
680
-
681
- It merges:
682
- - the agent's `development_note` records (`agent_reported`);
683
- - operator notes from `POST /api/v1/development` (`operator_reported`);
684
- - skill selection changes, with the configuration revisions before and after (`observed`);
685
- - soul and identity edits from the retained identity history (`observed`);
686
- - research method reflections (`observed`).
687
-
688
- `agent_ref` is the profile name. `ardent development list [--after CURSOR]
689
- [--limit N] [--kind KIND]` prints the same pages.
690
-
691
- ### Execution recovery
692
-
693
- After a crash or restart, every task that was `running` is evaluated before any
694
- queued work starts. **A write is never repeated merely because execution
695
- resumed**: an unknown effect needs reconciliation, never a retry. Each task is:
696
-
697
- - **resumed under the same id**: it stays `running`, continues at the next
698
- unfinished model step, and reuses completed model replies and settled tool
699
- results;
700
- - **reconciled first**: an interrupted tool call whose tool has a `reconcile`
701
- hook is asked what happened before the task continues; or
702
- - **held** as `unknown` (still terminal) with a recovery status and an
703
- actionable reason, waiting for an operator decision or marked unsupported.
704
-
705
- `TaskState` does not change. Tasks carry an optional `recovery` object (task
706
- `GET` and list, and `GET /api/v1/tasks/{id}/recovery`), so older clients see
707
- `running → completed` for a resumed task and `unknown` for a held one:
708
-
709
- ```json
710
- {"status": "awaiting_decision", "attempt": 1,
711
- "reason": {"code": "UNSETTLED_EXTERNAL_WRITE", "message": "A tool call with a possible external effect was dispatched ..."},
712
- "checkpoint": {"step": 0, "completed_calls": 1,
713
- "pending_calls": [{"call_id": "call-1", "tool": "news_collect", "effect": "artifact-write", "dispatched_at": "2026-11-23T12:00:00.000Z", "reconcilable": false}]},
714
- "actions": ["mark_applied", "mark_not_applied", "retry_with_new_deadline", "abandon"]}
715
- ```
716
-
717
- `status` is `ready` or `reconciling` (resuming), `resumed` (running again),
718
- `awaiting_decision`, `unsupported`, or `resolved` (settled at startup, or
719
- decided). `actions` lists only the decisions valid now. `GET /api/v1/status`
720
- reports `recovery: { ready, reconciling, awaiting_decision, unsupported }`.
721
-
722
- **How a task is planned.** Rules apply in order:
723
-
724
- | Condition | Outcome | `reason.code` |
725
- |---|---|---|
726
- | Cancellation was requested | `cancelled`, or held when an effect is uncertain | `CANCELLED_DURING_OUTAGE` / `CANCELLED_WITH_UNSETTLED_EFFECT` |
727
- | The deadline passed while stopped | `failed`, or held when an effect is uncertain; never extended | `DEADLINE_ELAPSED_DURING_OUTAGE` |
728
- | `execution.recovery.enabled: false` | held, unsupported | `RECOVERY_DISABLED` |
729
- | An extension `taskExecutor` with a possible effect ran, or a preview task | held, unsupported | `EXTENSION_EXECUTION_NOT_RESUMABLE` / `PREVIEW_NOT_RESUMABLE` |
730
- | Codex | see the backend matrix | `CODEX_*` |
731
- | llama.cpp, no checkpoint, no effectful tool dispatched | `ready`: restart from the beginning | `RESTART_NO_EFFECT` |
732
- | llama.cpp, no checkpoint, an effectful tool dispatched (for example, from before this release) | held, unsupported | `NO_EXECUTION_CHECKPOINT` |
733
- | A checkpoint fails its digest | held, unsupported | `CHECKPOINT_INVALID` |
734
- | Every dispatched call settled, or the unsettled ones are reads or idempotent | `ready`: resume at the next step; unsettled reads and idempotent calls are dispatched again under the same idempotency key | `RESUME_FROM_CHECKPOINT` |
735
- | An unsettled call whose tool can reconcile | `reconciling`: `applied` settles it with the service's result; `not_applied` tells the model it was not applied (it is not retried); `unknown` holds the task | `RECONCILE_INTERRUPTED_CALL` / `RECONCILIATION_INCONCLUSIVE` |
736
- | Any other unsettled call with a possible effect | held, awaiting a decision | `UNSETTLED_EXTERNAL_WRITE` |
737
-
738
- A call is *uncertain* when it was dispatched without a recorded outcome and is
739
- not a `read`, or settled with an unknown effect. A call a plugin denied, that
740
- settled without effect, or that was never dispatched leaves nothing uncertain.
741
- Until the gateway knows a task's tools (plugins load after the journal opens),
742
- a call that needs that check reports `reconciling` with `TOOL_CHECK_PENDING`;
743
- the check runs before any queued work is admitted.
744
-
745
- **Resuming.** A resumed task skips the queue transition, journals
746
- `execution_resumed { attempt, from_step, reused_calls, redispatched_calls, mode }`,
747
- reloads its transcript, evidence and tool-call count from its checkpoint, and
748
- continues at the next step, ahead of queued work but still one task per caller
749
- at a time. Tools, mission scope, memory grants, caller, context, ownership and
750
- plugin task contexts are re-derived from their owning stores; the checkpoint
751
- never supplies them, and the system prompt is rebuilt so policy and model
752
- changes apply. A paused task stays paused and waits at its first boundary. The
753
- deadline timer is re-armed from the stored deadline. Interrupted work does not
754
- start again while admission is fenced for a rollback. A task the gateway's
755
- shutdown deadline stops with nothing uncertain stays `running`
756
- (`execution_suspended`) and resumes on the next start.
757
-
758
- **Operator decisions.** `POST /api/v1/tasks/{id}/recovery`
759
- `{ action, call_id?, result?, note?, deadline_seconds? }` resolves a task held
760
- `awaiting_decision`. It is idempotent per task, attempt and action, and returns
761
- the recovery object:
762
-
763
- | Action | Effect |
764
- |---|---|
765
- | `mark_applied` | The pending call is settled `operator_applied` with `result` (at most 64 KiB, checked against the tool's output schema) or "result unavailable"; the work continues without dispatching it. |
766
- | `mark_not_applied` | The pending call is settled `operator_not_applied`; the model is told it was not applied. |
767
- | `retry_with_new_deadline` | The pending call is dispatched again under its original idempotency key, with a new deadline from now (`deadline_seconds`, at most `execution.recovery_max_new_deadline_seconds`). The only way to get a new deadline. |
768
- | `abandon` | Records the decision; nothing continues. |
769
-
770
- Because `unknown` is terminal, the first three create a **continuation task**:
771
- the same caller, context, session and prompt (not added to the session again),
772
- idempotency key `recovery:<original id>:<attempt + 1>`, an execution context
773
- whose parent is the original task (`source: continuation`, listed in the
774
- original's lineage `continuations`), and the original's checkpoint with the
775
- pending call settled as decided. A mission continuation copies the mission and
776
- its `TeamResult` names the continuation as `task_id` and lists the operator
777
- decisions in `uncertain_effects`. The original's recovery becomes `resolved`
778
- with `continuation_task_id`; the journals record `recovery_continued` and
779
- `recovery_continuation_of`. `mark_*` keep the original deadline, so they are
780
- offered only while it has not passed. A task held after a cancellation
781
- request is never continued: a decision only records what the operator
782
- established.
783
-
784
- **Backends.**
785
-
786
- | Backend | Recovery |
787
- |---|---|
788
- | llama.cpp | Full: checkpoints at every model reply and tool boundary, per the table above. |
789
- | Codex | With `providers.codex.durable_threads` (default), thread and turn ids are recorded. (a) When no effectful call is unsettled, the protocol lock verifies thread recovery for the installed CLI, and `thread/read` lists every dynamic tool call in the thread with a settled invocation, the thread is resumed (`CODEX_THREAD_RESUME`). (b) When no effectful tool was ever dispatched, the task restarts on a fresh thread (`CODEX_RESTART_NO_EFFECT`). (c) Otherwise it is held unsupported (`CODEX_THREAD_NOT_VERIFIABLE`). `codex-protocol.lock.json` records `thread_resume_verified` and `thread_read_items_verified`; both are `false` for the observed CLI, so (a) is disabled and the reason says so. |
790
- | Extension `taskExecutor` | Not resumable; held (`EXTENSION_EXECUTION_NOT_RESUMABLE`) when its effect is `possible`. |
791
- | Preview | Not resumable (`PREVIEW_NOT_RESUMABLE`). |
792
-
793
- **Never retried automatically:** a dispatched call with a possible effect and no
794
- recorded outcome, unless its tool is idempotent or its own service reconciles
795
- it; HiveMem writes; `news_collect`; extension executors; and anything after the
796
- original deadline. A settled call is never dispatched again.
797
-
798
- **State.** Three additive SQLite tables, written in the same transaction as the
799
- journal event of each boundary: `execution_state` (the model transcript after
800
- the last boundary, evidence, tool-call count and Codex thread ids, with a
801
- digest), `tool_invocations` (one row per call: `dispatched` before invocation,
802
- then settled with its result; compacted arguments, so file bytes stay in the
803
- artifact store), and `task_recovery`. `model_result` events also carry `calls`
804
- (id, name, compacted arguments). Execution checkpoints are separate from
805
- context checkpoints; neither reads the other. Rolling back to 3.1.x ignores the
806
- new tables and holds interrupted tasks as `unknown`.
807
-
808
- **Channels.** A recovered task has no in-process handler waiting for it, so the
809
- Telegram and Mattermost adapters answer its update themselves: at start and
810
- whenever a task settles they find updates bound to a recovered task with no
811
- recorded delivery, wait for the resumed task (or for the continuation an
812
- operator decision creates), and reply through the usual record-before-send path.
813
- The reply target (conversation, thread, message replied to) is stored with each
814
- inbound claim (`channel_inbound.reply_target_json`). An update that already has
815
- a delivery (queued, sent, failed or unknown) is never sent again, and a task
816
- held awaiting a decision is not answered until its continuation finishes.
817
- Updates claimed before this release have no stored target and are not answered.
818
-
819
- **A2A peers.** The A2A surface publishes the outcome of a peer task whose
820
- operation was recovered, through the same task store (GetTask, ListTasks) and
821
- push sender as a live request:
822
-
823
- | Operation | Peer task |
824
- |---|---|
825
- | Resumed, then completed | Answer, artifacts and `completed` (or `input_required`), as live. |
826
- | Settled at startup (`failed`, `cancelled`) | `failed` or `canceled`. |
827
- | Held `awaiting_decision` | Stays `working`; a status message gives the reason, and task metadata `ardentRecovery: { status, reason_code }`. |
828
- | Continued after a decision | Follows the continuation: its answer and final state are published for the peer's original task, the A2A operation binding moves to the continuation, and `ardentRecovery.continuation_task_id` names it. |
829
- | Held `unsupported`, or abandoned | `failed` with "Execution outcome is unknown: ...", as an interrupted task with an uncertain effect reports today. |
830
-
831
- Each final state is claimed in `a2a_recovery_publications` before it is
832
- published, so it and its push notification are sent at most once.
833
-
834
- ### Execution ancestry
835
-
836
- Every task accepted by this version has an execution context (execution
837
- context v1 from `@hivemagnus/hive-common/execution`): the causal tree it
838
- belongs to, across products. It is **attribution only**: tools, memory scope,
839
- mission scope, team-child admission and artifacts are never selected from it.
840
-
841
- ```json
842
- {"v": 1, "request_id": "req-1", "root": "hx1:studio:inst-1:request:r-1",
843
- "parent": "hx1:studio:inst-1:node:n-1", "self": "hx1:ardent:node-a.assistant:task:<task id>",
844
- "deadline_ms": 1790431800000}
845
- ```
846
-
847
- - **Where it comes from.** `POST /api/v1/tasks`, `POST /api/v1/missions` and
848
- `POST /api/v1/preview/tasks` take an optional `execution` field (else the
849
- `x-hive-execution` header); an A2A message carries it as
850
- `metadata.hiveExecution`. The task keeps the caller's `root` and
851
- `request_id`, takes the caller's `self` as its `parent`, and its `self` is
852
- always `hx1:ardent:<instance>:task:<task id>`, where the instance is
853
- `ARDENT_INSTANCE_REF`. A missing, malformed or unknown-version value is
854
- never rejected: the task gets a new root at its own reference. The context
855
- is not part of the idempotency digest. `deadline_ms` is the earlier of the
856
- caller's and the task's deadline; it does not change the task deadline.
857
- - **Where it is kept.** The `task_execution` table (`self_ref`, `root_ref`,
858
- `parent_ref`, `inputs_json`, `context_json` with the task's W3C trace,
859
- `source`: `caller`, `a2a`, `minted` or `continuation`), written in the same
860
- transaction as the task, and the `accepted` event's `execution`. A team
861
- child's context is also stored next to its retained grant, outside the
862
- grant's digest.
863
- - **Where it goes.** Every llama.cpp request carries a new `x-request-id`, a
864
- `traceparent` that is a child span of the task trace, and `x-hive-execution`
865
- with `self` `hx1:ardent:<instance>:attempt:<task id>/<step>/<n>`, `attempt`
866
- `n` and the deadline. `model_started` events journal `attempt`, `ref`,
867
- `request_id` and `traceparent`, so a gateway's request log links back to the
868
- task. `ArdentA2AClient.sendWithReceipt` / `send` / `sendStreaming` take
869
- `{ execution }` and send it as `metadata.hiveExecution`, so the receiving
870
- agent's task keeps the root and has the delegating task as its parent.
871
- Tools receive it as `ctx.execution`, and plugin hooks as `execution` on the
872
- task context and tool calls. `tool_attempt` events now record the tool's
873
- `effect`.
874
- - **Artifacts.** An artifact a task registers (`artifact_write`,
875
- `document_render`, preview research briefs, plugin `register` /
876
- `registerStream` calls, imports) is stored as manifest 1.1 with
877
- `provenance.execution: {root, task, step?}`: the task's root, its task
878
- reference and, while the task runs, the model step
879
- (`hx1:ardent:<instance>:step:<task id>/<step>`). An imported artifact keeps
880
- its producer's `execution`, and its import task takes the producer task as
881
- parent. Every 1.0 view is unchanged, and a task without a context still
882
- stores manifest 1.0. `ArtifactManifests.executionProvenance(taskId)` returns
883
- the value.
884
- - **Reading it.** Task responses (`GET /api/v1/tasks`, `GET /api/v1/tasks/{id}`)
885
- include `execution` when the task has one. `GET /api/v1/tasks/{id}/lineage`
886
- rebuilds what this profile knows:
887
-
888
- ```json
889
- {"task_id": "...", "execution": {"v": 1, "root": "...", "self": "..."}, "source": "caller",
890
- "traceparent": "00-...-...-01", "parent": {"ref": "...", "local_task_id": "..."},
891
- "children": [{"ref": "...", "local_task_id": "...", "source": "a2a", "created_ms": 0}],
892
- "continuations": [],
893
- "model_attempts": [{"step": 0, "attempt": 1, "backend": "llamacpp", "request_id": "...", "ref": "hx1:ardent:...:attempt:<id>/0/1", "started_ms": 0, "usage": null}],
894
- "tools": [{"call_id": "call-1", "name": "artifact_write", "effect": "artifact-write", "state": "succeeded"}],
895
- "artifacts": [{"sha256": "...", "name": "map.md", "mime": "text/markdown", "size": 12, "artifact_id": "...", "source": "manifest", "created_ms": 0,
896
- "schema_version": "1.1", "execution": {"root": "...", "task": "...", "step": "..."}}]}
897
- ```
898
-
899
- `parent.local_task_id` is set when the parent is a task of this instance.
900
- Tool `state` is `attempted`, `succeeded`, `failed`, `denied` or
901
- `not_dispatched`. Artifacts come from the manifest table (`source:
902
- manifest`, with renditions as `rendition_of`) and, for artifacts with no
903
- manifest, the `artifact_registered` and `research_artifacts` events. Everything comes from SQLite, so lineage survives a
904
- restart; a task accepted before this version has no `execution`, `parent`
905
- or `children`, but still lists its model attempts, tools and artifacts.
906
- The `/stream` events are unchanged apart from `accepted`.
907
-
908
- ## Plugins
909
-
910
- A plugin is an ES module whose default export (or named `plugin` export) is an
911
- `ArdentPlugin` object, or an array of them:
912
-
913
- ```ts
914
- import { definePlugin } from '@hivemagnus/ardent';
915
- import { z } from 'zod';
916
-
917
- export default definePlugin({
918
- name: 'weather',
919
- registerTools(ctx) {
920
- ctx.tools.register(ctx.defineTool({
921
- name: 'weather_now', description: 'Current weather for a city.',
922
- input: z.object({ city: z.string().min(1) }).strict(),
923
- output: z.object({ summary: z.string() }),
924
- effect: 'read', contexts: ['direct'], timeoutMs: 10_000,
925
- handler: async ({ city }, signal) => ({ summary: await lookUp(city, signal) }),
926
- }));
927
- },
928
- routes(app, ctx) { // served under /api/v1/plugins/weather/
929
- app.get('/health', c => c.json({ ok: true, profile: ctx.config.profile }));
930
- },
931
- cliCommands: { // ardent weather-check
932
- 'weather-check': { description: 'Probe the provider', run: async ({ print }) => print({ ok: true }) },
933
- },
934
- jobHandlers: ctx => ({ /* 'weather.daily': JobHandler */ }),
935
- jobOwnership: ctx => async (job, now) => { /* throw to refuse a job window */ },
936
- peerTool: (tool, task, envelope) => false, // allow a peer to call one of your tools
937
- taskTools: ctx => [], // additions bound to the exact persisted task
938
- filterTool: (ctx, tool) => true, // restrictive final filter
939
- drain: async (ctx, timeoutMs) => true, // stop intake and await owned work
940
- close: ctx => {}, // synchronous cleanup after a successful drain
941
- });
942
- ```
943
-
944
- Load it from config, as an npm package name (resolved from the profile
945
- directory first, then from Ardent's own install), an absolute path, or a
946
- `file://` URL:
947
-
948
- ```yaml
949
- plugins: ['@example/ardent-weather', /opt/ardent/plugins/local.mjs]
950
- ```
951
-
952
- Embedders that build the runtime themselves can call `registerPlugin()` before
953
- loading plugins. Plugin tools join the profile's shared tool registry; a tool's
954
- `contexts` decides whether direct, peer, or scheduled tasks may call it, and a
955
- peer still needs an explicit mission grant (`tool:<name>`) or `peerTool`.
956
- Plugin routes sit behind the same bearer-token check as the rest of the
957
- management API.
958
-
959
- A module may also export an asynchronous factory receiving `{ config, profileDir,
960
- env }`. It returns a plugin or an array of plugins. This allows profile-specific
961
- configuration and offline validation without constructing a runtime, claiming jobs,
962
- or starting channel consumers. The CLI supplies the selected profile environment;
963
- embedders can pass it as the third argument of `loadPlugins`.
964
-
965
- Import supported extension primitives from `@hivemagnus/ardent/plugin-sdk` rather
966
- than reaching into `dist`. This entry point includes the runtime, tool and job
967
- contracts, profile/configuration helpers, provider clients, artifact and identity
968
- helpers, and the application SQLite boundary (`SqliteDatabase`). Task additions retain their declared contexts and peer/mission grants. Preview
969
- additions must be read-only. Restrictive filters apply to built-in and extension
970
- tools; duplicate names cannot replace a tool silently. Stateful plugins must stop
971
- intake and await their owned work in `drain`. A false or timed-out drain keeps the
972
- journal open and ownership unsettled; `close` cannot bypass it. Cleanup runs in
973
- reverse registration order, including partially initialized plugins.
974
-
975
- Additional hooks support extensions that retain an existing workflow contract:
976
-
977
- | Hook | Boundary |
978
- | --- | --- |
979
- | `systemPrompt` | Supplies trusted policy text; the full model input is still budgeted. |
980
- | `allowMemory` | Can deny an admitted read; cannot grant a different scope. |
981
- | `observeToolResult`, `beforeFinish`, `taskSettled` | Track actual task evidence, validate before success, and release task-local resources. |
982
- | `teamEnvelope`, `admitTeamEnvelope` | Validate a legacy wire shape and apply extra admission restrictions. Identity, deadlines, parent reservations, constraints and resources remain core-validated. |
983
- | `taskExecutor` | Runs one owned deterministic workflow. Attempts precede invocation in the journal; lost or unknown effects stay held across restart. Preview and mission execution cannot be replaced. |
984
- | `inputImages` | Supplies at most five owned, digest-verified PNG/JPEG artifacts to a direct Codex task. Paths outside the selected profile's artifacts are rejected. |
985
- | `teamEvidence` | Validates retained extension receipts. Artifacts require an exact mission grant and verified bytes; format-only citation aliases must target observed references. |
986
- | `teamCard` | Describes private role capabilities without granting permissions or claiming backend readiness. |
987
- | `prepareGateway`, `start` | Verify prior consumer ownership, then start background intake only in gateway mode. CLI inspection does not start consumers. |
988
- | `channelAdapter` | Replaces one enabled built-in channel consumer. Multiple owners are refused. Intake and delivery receive separate abort signals. |
989
- | `httpRoutes` | Adds explicit compatibility paths; overlapping core routes and authentication-boundary changes are refused. |
990
-
991
- ### Lifecycle hooks
992
-
993
- Message and tool lifecycle hooks let one extension follow a channel message
994
- from receipt to delivery, and a tool call from invocation to its result or
995
- cancellation, without replacing a channel adapter. Every hook is optional and
996
- may be asynchronous. Each one gets a frozen copy of what it observes, and each
997
- must settle within 5 seconds.
998
-
999
- | Hook | When | Permitted | On a throw, rejection or timeout |
1000
- | --- | --- | --- | --- |
1001
- | `messageReceived(ctx, message)` | A built-in Telegram or Mattermost consumer has claimed a new, authenticated message, before command or task handling | Observe | Recorded; handling continues |
1002
- | `messagePersisted(ctx, message, task)` | The message's task is accepted and bound to it, before it runs | Observe | Recorded; the task runs |
1003
- | `transformOutbound(ctx, delivery)` | A reply is recorded for delivery, before it is sent | Return `{ text }` (1 byte to 64 KiB, not blank) to replace the text; return nothing to keep it. Transformations chain. When the text changes, the task journal records `outbound_transformed` with the sent text | The **original** text is sent, discarding every transformation; recorded |
1004
- | `messageDelivered(ctx, delivery, outcome)` | The delivery is recorded `sent`, `failed` or `unknown` | Observe | Recorded |
1005
- | `beforeToolCall(ctx, call)` | After context scoping, argument validation, the `tool_attempt` journal entry and team admission, before the tool is invoked | Return `{ deny: { code, message } }` to deny; the result is `{ ok: false, code, message, effect: 'none' }` and the journal records `tool_denied_by_plugin`. Anything else is ignored | The call is denied (`TOOL_DENIED_BY_PLUGIN`); recorded |
1006
- | `afterToolCall(ctx, call, result)` | The result is journaled, successful or not | Observe | Recorded; the task continues |
1007
- | `toolCallCancelled(ctx, call, { dispatched, effect })` | On cancellation, for calls not yet dispatched (`dispatched: false`, `effect: 'none'`) and calls in flight (`dispatched: true`; `effect: 'unknown'` unless the tool is `read`). Runs before `taskSettled` | Clean up | Recorded |
1008
-
1009
- `message` is `{ platform, account, update_id, channel_type, caller, session_key,
1010
- received_ms, execution? }` and carries no message text. `delivery` is
1011
- `{ delivery_id, task_id, platform, account, update_id, text, attempt }`.
1012
- `call` is `{ task_id, call_id, name, arguments, effect, idempotency_key,
1013
- execution? }` with the validated arguments. `ctx.execution` and `execution` are
1014
- attribution for the causal tree a task belongs to (see
1015
- [Execution ancestry](#execution-ancestry)); they never grant access. They are
1016
- set for every task accepted by this version, and absent for older tasks and for
1017
- a channel `message`, which has no task yet.
1018
-
1019
- Order: `before*` and `transform*` hooks run in plugin registration order, and
1020
- the first denial wins. Observers also run in registration order. Cleanup hooks
1021
- (`toolCallCancelled`, `taskSettled`, `drain`, `close`) run in reverse
1022
- registration order.
1023
-
1024
- A failed hook is recorded as a `plugin_hook_failed` task event `{ plugin, hook }`.
1025
- For a message that never creates a task (a command such as `/help`), the
1026
- failure is recorded against the message's identity instead
1027
- (`runtime.store.pluginHookFailures(platform, account, update_id)`). An observer
1028
- failure never fails the task or the delivery. This includes
1029
- `observeToolResult`: a throwing `observeToolResult` is recorded and no longer
1030
- fails the task.
1031
-
1032
- The hooks cannot widen authority. Context and mission scoping, plugin
1033
- `taskTools` and `filterTool`, and argument validation all happen before
1034
- `beforeToolCall`, which can only deny. A hook cannot change the arguments, the
1035
- result, the declared effect or the effect accounting, and `transformOutbound`
1036
- can change only the text of a reply that Ardent already decided to send.
1037
- Message hooks run for the built-in consumers; a plugin `channelAdapter` that
1038
- replaces one owns its own intake.
1039
-
1040
- An envelope extension uses `mission.extensions[plugin.name]` and action names
1041
- `extension:<plugin-name>:<action>`. No extension is accepted without its configured
1042
- validator. A codec may retain an old wire action while translating it into its
1043
- own namespace; it cannot add a resource or substitute a core action grant.
1044
- Ardent retains the original wire envelope in its journal and revalidates it
1045
- when reading lifecycle controls or export receipts.
1046
-
1047
- Normal plugin `routes` remain under `/api/v1/plugins/<name>/` and require the
1048
- management bearer token. `httpRoutes` declares each mount as `management` or
1049
- `independent`. Management aliases must remain under `/api/v1/` and inherit its
1050
- authentication. Independent device/webhook ingress must authenticate every
1051
- handler with its own credential and replay protection; it cannot use API,
1052
- health or A2A paths. All compatibility handlers receive a 1 MiB body bound and
1053
- share a bounded per-plugin rate bucket (600/minute, burst 120), applied before
1054
- handler authentication and parsing. Wildcard routes and middleware mounts are
1055
- refused so an extension cannot intercept unrelated core requests.
1056
-
1057
- HTTP mounts may set `rateLimit: { perMinute, burst }` for their authentication
1058
- boundary. Defaults are 600 requests per minute and a burst of 120. Limits must be
1059
- positive integers no greater than 6000 and 1200 respectively. All mounts from one
1060
- plugin in the same boundary must agree; management and independent ingress retain
1061
- separate buckets. This capacity is trusted plugin policy and grants no authentication
1062
- or task authority. The one MiB body limit remains in force.
1063
-
1064
- Offline job-validation contexts expose `runtimeAvailable: false`; their runtime
1065
- and tool registry getters throw. CLI extensions receive `rawArgs` for their own
1066
- option grammar, declare `valueOptions` to recognize values before the command, and can use `matches(invocation)` to select one subcommand while
1067
- leaving other core subcommands available. Plugin code has the profile owner's
1068
- process privileges: install only reviewed, pinned artifacts. These hooks preserve
1069
- authority boundaries between tasks; they do not sandbox an untrusted plugin.
1070
-
1071
- Job owner labels other than `ardent` remain external references and never admit
1072
- work. A custom delivery kind requires its registered handler to validate the exact
1073
- descriptor. Existing definition bytes, revisions and receipts need not be rewritten
1074
- to rename an external scheduler. Historical channel labels also remain distinct;
1075
- a compatibility adapter must retain its original platform, account and receipt
1076
- identity instead of creating a second consumer under a renamed transport.
1077
-
1078
- Extensions should
1079
- use `ctx.runtime.store` for the active journal and must not introduce a second
1080
- SQLite driver or rewrite another extension's state.
112
+ - [Configuration](docs/configuration.md): profile configuration, model backends, tools, memory, channels, A2A, Magnus Control tools, scheduled jobs, retries and model policy.
113
+ - [Management API](docs/management-api.md): authentication, errors, task lists, metrics, credential rotation, logs and live task streams.
114
+ - [Team missions and artifacts](docs/missions-and-artifacts.md): team missions, artifact transfer v2 and renditions, pause, preview and development history.
115
+ - [Execution recovery](docs/recovery.md): how interrupted tasks resume or are held, and execution ancestry.
116
+ - [Plugins](docs/plugins.md): the plugin API and its lifecycle hooks.
117
+ - [Operations](docs/operations.md): the native suite artifact, backup and retention, and journal quiescence.
1081
118
 
1082
119
  ## Security model
1083
120