@hivemagnus/ardent 2.1.1 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,10 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import { createHash, randomUUID } from 'node:crypto';
3
3
  import { readFile, readdir, lstat } from 'node:fs/promises';
4
- import { isAbsolute, join } from 'node:path';
4
+ import { isAbsolute, join, resolve as resolvePath } from 'node:path';
5
5
  import { createInterface } from 'node:readline/promises';
6
6
  import { stdin, stdout, stderr } from 'node:process';
7
- import { parse } from 'dotenv';
8
7
  import { z } from 'zod';
9
8
  import { ardentHome, ConfigSchema, DEFAULT_PROFILE, initProfile, loadConfig, profilePath, redactedConfig, resolveReference, runtimeProblems } from './config.js';
10
9
  import { ArdentRuntime } from './runtime.js';
@@ -30,11 +29,15 @@ import { ContextCheckpoints } from './context-checkpoints.js';
30
29
  import { loadModelPolicy } from './model-policy.js';
31
30
  import { loadPlugins, pluginContext, pluginJobHandlers, validationContext } from './plugins.js';
32
31
  import { ARDENT_VERSION } from './version.js';
33
- import { acceptRuntime, readProtectedFile } from './acceptance.js';
32
+ import { acceptRuntime } from './acceptance.js';
33
+ import { readProfileEnv } from './profile-env.js';
34
+ import { PlainTextFilter } from './live-text.js';
35
+ import { developmentQuery, missionSubmitInput, previewInput } from './cli-commands.js';
36
+ import { developmentPage, DevelopmentRecords, recordSkillChange } from './development.js';
34
37
  function args(argv) {
35
38
  const words = [];
36
39
  const options = new Map();
37
- const valued = new Set(['env-file', 'profile', 'profile-path', 'api-port', 'template', 'prompt', 'prompt-file', 'idempotency-key', 'session-id', 'login-id', 'source', 'schedule-id', 'window-key', 'release-id', 'caller', 'context', 'expected-head', 'expected-policy-revision']);
40
+ const valued = new Set(['env-file', 'profile', 'profile-path', 'api-port', 'template', 'prompt', 'prompt-file', 'idempotency-key', 'session-id', 'login-id', 'source', 'schedule-id', 'window-key', 'release-id', 'caller', 'context', 'expected-head', 'expected-policy-revision', 'mission-file', 'after', 'limit', 'kind', 'soul-file', 'identity-file', 'skills', 'model']);
38
41
  for (let i = 0; i < argv.length; i++) {
39
42
  const arg = argv[i];
40
43
  if (!arg)
@@ -66,16 +69,9 @@ function value(options, name) {
66
69
  }
67
70
  async function environment(dir, explicitFile) {
68
71
  const env = { ...process.env };
69
- try {
70
- const data = parse(explicitFile ? await readProtectedFile(explicitFile) : await readFile(join(dir, '.env')));
71
- for (const [name, val] of Object.entries(data))
72
- if (env[name] === undefined)
73
- env[name] = val;
74
- }
75
- catch (error) {
76
- if (explicitFile || !(error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT'))
77
- throw error;
78
- }
72
+ for (const [name, val] of Object.entries(await readProfileEnv(dir, explicitFile)))
73
+ if (env[name] === undefined)
74
+ env[name] = val;
79
75
  return env;
80
76
  }
81
77
  function print(value) { stdout.write(`${JSON.stringify(value, null, 2)}\n`); }
@@ -121,8 +117,12 @@ Commands:
121
117
  a2a team-card Print the Hermes team card (a2a.hermes_compat)
122
118
  openapi export Print the management OpenAPI document
123
119
  run --prompt TEXT | chat | report Run a task, chat, or run a scheduled report
120
+ mission submit --mission-file FILE Run a team mission (a POST /api/v1/missions body)
121
+ preview --prompt TEXT [--soul-file F] Try unsaved soul, identity, --skills or --model changes
122
+ development list [--after C] [--kind K] Show the agent's development history
124
123
  sessions list | new | reset | show Manage local CLI sessions
125
- tasks list | show | cancel | resume Inspect local tasks
124
+ tasks list | show | cancel Inspect local tasks
125
+ tasks pause | resume <id> Hold a queued task, or release and run it
126
126
  gateway run Serve the management API, A2A, channels and jobs`;
127
127
  async function main() {
128
128
  const parsed = args(process.argv.slice(2));
@@ -342,7 +342,15 @@ async function main() {
342
342
  return;
343
343
  }
344
344
  if (subcommand === 'enable' || subcommand === 'disable') {
345
- print({ revision: await setSkillEnabled(dir, id, subcommand === 'enable', loaded.revision) });
345
+ const revision = await setSkillEnabled(dir, id, subcommand === 'enable', loaded.revision);
346
+ const store = new TaskStore(join(dir, 'state', 'ardent.sqlite'));
347
+ try {
348
+ recordSkillChange(new DevelopmentRecords(store, loaded.config.profile), id, subcommand === 'enable', loaded.revision, revision);
349
+ }
350
+ finally {
351
+ store.close();
352
+ }
353
+ print({ revision });
346
354
  return;
347
355
  }
348
356
  throw new Error('Unknown skills command');
@@ -456,7 +464,7 @@ async function main() {
456
464
  }
457
465
  return;
458
466
  }
459
- if (!['run', 'report', 'chat', 'tasks', 'sessions', 'gateway'].includes(command ?? ''))
467
+ if (!['run', 'report', 'chat', 'tasks', 'sessions', 'gateway', 'mission', 'preview', 'development'].includes(command ?? ''))
460
468
  throw new Error(`Unknown command.\n${USAGE}`);
461
469
  if (command === 'gateway' && subcommand === 'run') {
462
470
  if (!['127.0.0.1', '::1', 'localhost'].includes(loaded.config.api.host))
@@ -483,6 +491,11 @@ async function main() {
483
491
  for (const task of runtime.recovered.queued)
484
492
  if (task.caller === 'management')
485
493
  void runtime.run(task.id, env).catch(() => { });
494
+ // Preview artifacts expire after 24 hours; remove their bytes once nothing else refers to them.
495
+ const sweepArtifacts = () => { void runtime?.artifactManifests.sweepExpired().catch(() => { }); };
496
+ sweepArtifacts();
497
+ const artifactSweep = setInterval(sweepArtifacts, 3_600_000);
498
+ artifactSweep.unref();
486
499
  const jobPath = join(dir, 'jobs', 'active.json');
487
500
  const hasJobs = await lstat(jobPath).then(stat => {
488
501
  if (!stat.isFile() || stat.isSymbolicLink())
@@ -501,7 +514,9 @@ async function main() {
501
514
  await jobEngine.load();
502
515
  if (jobEngine)
503
516
  await jobEngine.recoverAfterRestart();
504
- const api = createArdentApi(runtime, loaded, env, jobEngine);
517
+ // The API reloads rotated credentials from the same file the gateway started from.
518
+ const envFile = value(parsed.options, 'env-file');
519
+ const api = createArdentApi(runtime, loaded, env, jobEngine, envFile ? { envFile: resolvePath(envFile) } : {});
505
520
  const server = serve({ fetch: api.fetch, hostname: loaded.config.api.host, port: loaded.config.api.port });
506
521
  await new Promise((resolve, reject) => { server.once('listening', resolve); server.once('error', reject); });
507
522
  let a2aHttp;
@@ -570,6 +585,7 @@ async function main() {
570
585
  finally {
571
586
  if (jobTimer)
572
587
  clearInterval(jobTimer);
588
+ clearInterval(artifactSweep);
573
589
  channelAbort.abort();
574
590
  shutdownUnsettled = !(await runtime.drain(30_000));
575
591
  // Replies and notices admitted before shutdown may still be sending.
@@ -650,17 +666,46 @@ async function main() {
650
666
  print(runtime.cancel(id));
651
667
  return;
652
668
  }
669
+ if (subcommand === 'pause') {
670
+ const { task, admission } = runtime.pause(id);
671
+ print({ task_id: task.id, state: task.state, admission });
672
+ return;
673
+ }
653
674
  if (subcommand === 'resume') {
654
675
  const task = runtime.store.get(id);
655
676
  if (!task)
656
677
  throw new Error('Task not found');
657
678
  if (task.state !== 'queued')
658
679
  throw new Error(`Task is ${task.state}; only unstarted queued work can be resumed without replaying an uncertain effect`);
680
+ runtime.resume(task.id);
659
681
  print(await runtime.run(task.id, env));
660
682
  return;
661
683
  }
662
684
  throw new Error('Unknown tasks command');
663
685
  }
686
+ if (command === 'mission') {
687
+ if (subcommand !== 'submit')
688
+ throw new Error('Use mission submit --mission-file FILE');
689
+ const task = runtime.acceptMission(await missionSubmitInput(parsed.options, path => readFile(path, 'utf8')), 'local');
690
+ const result = await runtime.run(task.id, env);
691
+ print({ task_id: result.task.id, state: result.task.state, team_result: result.team_result ?? null });
692
+ return;
693
+ }
694
+ if (command === 'preview') {
695
+ const task = runtime.acceptPreview(await previewInput(parsed.options, path => readFile(path, 'utf8')), 'local');
696
+ const result = await runtime.run(task.id, env);
697
+ if (parsed.options.has('json'))
698
+ print(result);
699
+ else
700
+ stdout.write(`${result.answer}\n`);
701
+ return;
702
+ }
703
+ if (command === 'development') {
704
+ if (subcommand !== 'list')
705
+ throw new Error('Use development list [--after CURSOR] [--limit N] [--kind KIND]');
706
+ print(await developmentPage({ records: runtime.development, profileDir: dir, config: loaded.config }, developmentQuery(parsed.options)));
707
+ return;
708
+ }
664
709
  if (command === 'sessions') {
665
710
  if (subcommand === 'list') {
666
711
  print(runtime.store.listSessions('local', 'direct'));
@@ -792,40 +837,22 @@ async function main() {
792
837
  }
793
838
  };
794
839
  const progress = setInterval(showProgress, 150);
795
- const streamState = { text: '', step: -1, mode: 'pending' };
840
+ const visible = new PlainTextFilter();
796
841
  const writeModelText = (chunk, step) => {
797
- if (step !== streamState.step) {
798
- streamState.step = step;
799
- streamState.text = '';
800
- streamState.mode = 'pending';
801
- }
802
- if (streamState.mode === 'structured')
803
- return;
804
- if (streamState.mode === 'pending') {
805
- const first = chunk.trimStart()[0];
806
- if (!first) {
807
- streamState.text += chunk;
808
- return;
809
- }
810
- streamState.mode = first === '{' || first === '[' ? 'structured' : 'plain';
811
- if (streamState.mode === 'structured') {
812
- streamState.text = '';
813
- return;
814
- }
842
+ const out = visible.push(chunk, step);
843
+ if (out.started) {
815
844
  showProgress();
816
845
  answerStarted = true;
817
- if (streamState.text)
818
- stdout.write(streamState.text);
819
846
  }
820
- streamState.text += chunk;
821
- stdout.write(chunk);
847
+ if (out.text)
848
+ stdout.write(out.text);
822
849
  };
823
850
  try {
824
851
  const result = await runtime.run(task.id, env, writeModelText);
825
852
  showProgress();
826
- if (streamState.mode !== 'plain' || streamState.text.trim() !== result.answer.trim())
853
+ if (visible.mode !== 'plain' || visible.text.trim() !== result.answer.trim())
827
854
  stdout.write(`${result.answer}\n`);
828
- else if (!streamState.text.endsWith('\n'))
855
+ else if (!visible.text.endsWith('\n'))
829
856
  stdout.write('\n');
830
857
  }
831
858
  catch (error) {
package/dist/config.d.ts CHANGED
@@ -141,6 +141,9 @@ export declare const ConfigSchema: z.ZodObject<{
141
141
  token_env: z.ZodDefault<z.ZodString>;
142
142
  }, z.core.$strict>>;
143
143
  }, z.core.$strict>>;
144
+ artifacts: z.ZodDefault<z.ZodObject<{
145
+ max_bytes: z.ZodDefault<z.ZodNumber>;
146
+ }, z.core.$strict>>;
144
147
  plugins: z.ZodDefault<z.ZodArray<z.ZodString>>;
145
148
  api: z.ZodDefault<z.ZodObject<{
146
149
  host: z.ZodDefault<z.ZodString>;
package/dist/config.js CHANGED
@@ -72,6 +72,8 @@ export const ConfigSchema = z.object({
72
72
  /** Optional read-only Magnus Control tools. URL and token come only from config or the environment. */
73
73
  magnus_control: z.object({ enabled: z.boolean().default(false), base_url: urlReference.default('${ARDENT_MAGNUS_API_URL}'), token_env: z.string().regex(envName).default('ARDENT_MAGNUS_READ_TOKEN') }).strict().default(magnusControlDefault)
74
74
  }).strict().default({ magnus_control: magnusControlDefault }),
75
+ /** Artifact store limits. `max_bytes` bounds each stored artifact (default 2 MiB, at most 64 MiB). */
76
+ artifacts: z.object({ max_bytes: z.number().int().min(1024).max(64 * 1024 * 1024).default(2 * 1024 * 1024) }).strict().default({ max_bytes: 2 * 1024 * 1024 }),
75
77
  /** Plugin modules loaded by the gateway (npm package names, absolute paths, or file:// URLs). */
76
78
  plugins: z.array(pluginSpecifier).max(32).default([]),
77
79
  api: z.object({ host: z.string().min(1).default('127.0.0.1'), port: z.number().int().min(1).max(65535).default(9910), token_env: z.string().regex(envName).default('ARDENT_API_TOKEN') }).strict().default({ host: '127.0.0.1', port: 9910, token_env: 'ARDENT_API_TOKEN' })
@@ -6,7 +6,7 @@ import Database from 'better-sqlite3';
6
6
  import { parse } from 'dotenv';
7
7
  import { z } from 'zod';
8
8
  import { ContextCheckpoints } from './context-checkpoints.js';
9
- import { TaskStore } from './store.js';
9
+ import { TaskContext, TaskStore } from './store.js';
10
10
  import { loadConfig } from './config.js';
11
11
  import { loadModelPolicy } from './model-policy.js';
12
12
  import { compactWithCodex } from './codex.js';
@@ -186,7 +186,7 @@ export async function contextMaintenance(input) {
186
186
  const current = new ContextCheckpoints(store, forbidden);
187
187
  const { ContextCheckpoints: Previous } = previousReaderSchema.parse(await import(pathToFileURL(request.previous_module).href));
188
188
  const previous = new Previous(store, forbidden);
189
- const sessions = z.array(z.object({ id: z.string(), caller: z.string(), context: z.enum(['direct', 'peer', 'scheduled']) })).max(10000)
189
+ const sessions = z.array(z.object({ id: z.string(), caller: z.string(), context: TaskContext })).max(10000)
190
190
  .parse(store.db.prepare('SELECT s.id,s.caller,s.context FROM sessions s JOIN context_checkpoint_heads h ON h.session_id=s.id').all());
191
191
  for (const session of sessions) {
192
192
  const status = current.status(session.id, session.caller, session.context);
@@ -0,0 +1,121 @@
1
+ import { z } from 'zod';
2
+ import type { ArdentConfig } from './config.js';
3
+ import type { TaskStore } from './store.js';
4
+ /** A short machine-readable category, such as `self_understanding`, `method`, `lesson` or `skill_change`. */
5
+ export declare const DevelopmentKind: z.ZodString;
6
+ export declare const DevelopmentSource: z.ZodObject<{
7
+ kind: z.ZodEnum<{
8
+ identity: "identity";
9
+ memory: "memory";
10
+ skill: "skill";
11
+ url: "url";
12
+ task: "task";
13
+ artifact: "artifact";
14
+ note: "note";
15
+ }>;
16
+ ref: z.ZodString;
17
+ }, z.core.$strict>;
18
+ /**
19
+ * Portable record of how an agent developed: its own notes, operator notes and
20
+ * observed changes. `epistemic` says how much the record can be trusted.
21
+ */
22
+ export declare const DevelopmentRecordSchema: z.ZodObject<{
23
+ id: z.ZodString;
24
+ agent_ref: z.ZodString;
25
+ kind: z.ZodString;
26
+ title: z.ZodString;
27
+ body: z.ZodString;
28
+ author: z.ZodEnum<{
29
+ operator: "operator";
30
+ agent: "agent";
31
+ runtime: "runtime";
32
+ }>;
33
+ epistemic: z.ZodEnum<{
34
+ observed: "observed";
35
+ agent_reported: "agent_reported";
36
+ operator_reported: "operator_reported";
37
+ }>;
38
+ before_sha256: z.ZodNullable<z.ZodString>;
39
+ after_sha256: z.ZodNullable<z.ZodString>;
40
+ sources: z.ZodArray<z.ZodObject<{
41
+ kind: z.ZodEnum<{
42
+ identity: "identity";
43
+ memory: "memory";
44
+ skill: "skill";
45
+ url: "url";
46
+ task: "task";
47
+ artifact: "artifact";
48
+ note: "note";
49
+ }>;
50
+ ref: z.ZodString;
51
+ }, z.core.$strict>>;
52
+ created_at: z.ZodString;
53
+ }, z.core.$strict>;
54
+ export type DevelopmentRecord = z.infer<typeof DevelopmentRecordSchema>;
55
+ /** A note written by the agent (`development_note`) or the operator. */
56
+ export declare const DevelopmentNoteInput: z.ZodObject<{
57
+ kind: z.ZodString;
58
+ title: z.ZodString;
59
+ body: z.ZodString;
60
+ sources: z.ZodOptional<z.ZodArray<z.ZodObject<{
61
+ kind: z.ZodEnum<{
62
+ identity: "identity";
63
+ memory: "memory";
64
+ skill: "skill";
65
+ url: "url";
66
+ task: "task";
67
+ artifact: "artifact";
68
+ note: "note";
69
+ }>;
70
+ ref: z.ZodString;
71
+ }, z.core.$strict>>>;
72
+ }, z.core.$strict>;
73
+ export type DevelopmentNoteInput = z.infer<typeof DevelopmentNoteInput>;
74
+ /** Append-only development records owned by the agent profile. */
75
+ export declare class DevelopmentRecords {
76
+ readonly store: TaskStore;
77
+ readonly agentRef: string;
78
+ constructor(store: TaskStore, agentRef: string);
79
+ /** Record a note or an observed change. A task-bound record is also journaled on the task. */
80
+ add(input: DevelopmentNoteInput & {
81
+ author: DevelopmentRecord['author'];
82
+ epistemic: DevelopmentRecord['epistemic'];
83
+ taskId?: string | undefined;
84
+ before_sha256?: string | null;
85
+ after_sha256?: string | null;
86
+ }): DevelopmentRecord;
87
+ /** Stored records after a cursor, in creation order. */
88
+ list(options?: {
89
+ after?: DevelopmentCursor | undefined;
90
+ limit?: number;
91
+ kind?: string | undefined;
92
+ }): Array<DevelopmentRecord & {
93
+ created_ms: number;
94
+ }>;
95
+ }
96
+ /** Position in the merged development history: the creation time and id of the last record seen. */
97
+ export type DevelopmentCursor = {
98
+ ms: number;
99
+ id: string;
100
+ };
101
+ export declare function encodeDevelopmentCursor(cursor: DevelopmentCursor): string;
102
+ export declare function decodeDevelopmentCursor(value: string): DevelopmentCursor;
103
+ /**
104
+ * One page of the agent's development history in the portable record shape:
105
+ * stored notes and skill changes, identity edits, and method reflections,
106
+ * merged in creation order.
107
+ */
108
+ export declare function developmentPage(input: {
109
+ records: DevelopmentRecords;
110
+ profileDir: string;
111
+ config: ArdentConfig;
112
+ }, query?: {
113
+ after?: string | undefined;
114
+ limit?: number | undefined;
115
+ kind?: string | undefined;
116
+ }): Promise<{
117
+ records: DevelopmentRecord[];
118
+ next: string | null;
119
+ }>;
120
+ /** Record an operator's skill selection change, with the configuration revisions before and after it. */
121
+ export declare function recordSkillChange(records: DevelopmentRecords, name: string, enabled: boolean, before: string, after: string): DevelopmentRecord;
@@ -0,0 +1,151 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { z } from 'zod';
3
+ import { identityHistory, readIdentity } from './identity.js';
4
+ const digest = z.string().regex(/^[a-f0-9]{64}$/);
5
+ /** A short machine-readable category, such as `self_understanding`, `method`, `lesson` or `skill_change`. */
6
+ export const DevelopmentKind = z.string().regex(/^[a-z][a-z0-9_]{0,63}$/);
7
+ export const DevelopmentSource = z.object({ kind: z.enum(['task', 'artifact', 'memory', 'url', 'identity', 'skill', 'note']), ref: z.string().trim().min(1).max(512) }).strict();
8
+ /**
9
+ * Portable record of how an agent developed: its own notes, operator notes and
10
+ * observed changes. `epistemic` says how much the record can be trusted.
11
+ */
12
+ export const DevelopmentRecordSchema = z.object({
13
+ id: z.string().regex(/^dev_[A-Za-z0-9_-]{1,120}$/), agent_ref: z.string(), kind: DevelopmentKind,
14
+ title: z.string(), body: z.string(), author: z.enum(['agent', 'operator', 'runtime']),
15
+ epistemic: z.enum(['agent_reported', 'operator_reported', 'observed']),
16
+ before_sha256: digest.nullable(), after_sha256: digest.nullable(), sources: z.array(DevelopmentSource).max(16), created_at: z.string()
17
+ }).strict();
18
+ /** A note written by the agent (`development_note`) or the operator. */
19
+ export const DevelopmentNoteInput = z.object({ kind: DevelopmentKind, title: z.string().trim().min(1).max(200),
20
+ body: z.string().trim().min(1).max(8000), sources: z.array(DevelopmentSource).max(16).optional() }).strict();
21
+ const Row = z.object({ id: z.string(), kind: z.string(), title: z.string(), body: z.string(), author: z.string(), epistemic: z.string(),
22
+ before_sha256: z.string().nullable(), after_sha256: z.string().nullable(), sources_json: z.string(), created_ms: z.number().int() });
23
+ /** Append-only development records owned by the agent profile. */
24
+ export class DevelopmentRecords {
25
+ store;
26
+ agentRef;
27
+ constructor(store, agentRef) {
28
+ this.store = store;
29
+ this.agentRef = agentRef;
30
+ store.db.exec(`CREATE TABLE IF NOT EXISTS development_records (
31
+ id TEXT PRIMARY KEY, kind TEXT NOT NULL, title TEXT NOT NULL, body TEXT NOT NULL, author TEXT NOT NULL,
32
+ epistemic TEXT NOT NULL, before_sha256 TEXT, after_sha256 TEXT, sources_json TEXT NOT NULL,
33
+ task_id TEXT REFERENCES tasks(id), created_ms INTEGER NOT NULL);
34
+ CREATE INDEX IF NOT EXISTS development_records_created ON development_records(created_ms, id);
35
+ CREATE TRIGGER IF NOT EXISTS development_records_immutable_update BEFORE UPDATE ON development_records
36
+ BEGIN SELECT RAISE(ABORT, 'Development records are immutable'); END;
37
+ CREATE TRIGGER IF NOT EXISTS development_records_immutable_delete BEFORE DELETE ON development_records
38
+ BEGIN SELECT RAISE(ABORT, 'Development records are immutable'); END;`);
39
+ }
40
+ /** Record a note or an observed change. A task-bound record is also journaled on the task. */
41
+ add(input) {
42
+ const note = DevelopmentNoteInput.parse({ kind: input.kind, title: input.title, body: input.body, ...(input.sources ? { sources: input.sources } : {}) });
43
+ const sources = [...(input.taskId ? [{ kind: 'task', ref: input.taskId }] : []), ...(note.sources ?? [])]
44
+ .filter((source, index, all) => all.findIndex(other => other.kind === source.kind && other.ref === source.ref) === index).slice(0, 16);
45
+ const created = Date.now();
46
+ const id = `dev_${created.toString(36).padStart(9, '0')}${randomBytes(10).toString('hex')}`;
47
+ const record = DevelopmentRecordSchema.parse({ id, agent_ref: this.agentRef, kind: note.kind, title: note.title, body: note.body,
48
+ author: input.author, epistemic: input.epistemic, before_sha256: input.before_sha256 ?? null, after_sha256: input.after_sha256 ?? null,
49
+ sources, created_at: new Date(created).toISOString() });
50
+ this.store.db.transaction(() => {
51
+ this.store.db.prepare(`INSERT INTO development_records(id,kind,title,body,author,epistemic,before_sha256,after_sha256,sources_json,task_id,created_ms)
52
+ VALUES (?,?,?,?,?,?,?,?,?,?,?)`).run(id, record.kind, record.title, record.body, record.author, record.epistemic, record.before_sha256, record.after_sha256, JSON.stringify(record.sources), input.taskId ?? null, created);
53
+ if (input.taskId)
54
+ this.store.append(input.taskId, 'development_note', { id, kind: record.kind, title: record.title });
55
+ })();
56
+ return record;
57
+ }
58
+ /** Stored records after a cursor, in creation order. */
59
+ list(options = {}) {
60
+ const after = options.after ?? { ms: -1, id: '' };
61
+ return this.store.db.prepare(`SELECT * FROM development_records WHERE (created_ms>? OR (created_ms=? AND id>?)) AND (? IS NULL OR kind=?)
62
+ ORDER BY created_ms, id LIMIT ?`).all(after.ms, after.ms, after.id, options.kind ?? null, options.kind ?? null, Math.max(1, Math.min(options.limit ?? 100, 1000))).map(raw => {
63
+ const row = Row.parse(raw);
64
+ return { ...DevelopmentRecordSchema.parse({ id: row.id, agent_ref: this.agentRef, kind: row.kind, title: row.title, body: row.body,
65
+ author: row.author, epistemic: row.epistemic, before_sha256: row.before_sha256, after_sha256: row.after_sha256,
66
+ sources: JSON.parse(row.sources_json), created_at: new Date(row.created_ms).toISOString() }), created_ms: row.created_ms };
67
+ });
68
+ }
69
+ }
70
+ export function encodeDevelopmentCursor(cursor) {
71
+ return Buffer.from(JSON.stringify([cursor.ms, cursor.id])).toString('base64url');
72
+ }
73
+ export function decodeDevelopmentCursor(value) {
74
+ try {
75
+ const [ms, id] = z.tuple([z.number().int().min(0), z.string().max(160)]).parse(JSON.parse(Buffer.from(value, 'base64url').toString('utf8')));
76
+ return { ms, id };
77
+ }
78
+ catch {
79
+ throw new Error('Invalid development cursor');
80
+ }
81
+ }
82
+ const historyName = /^(\d+)-([a-f0-9]{12})-([a-f0-9]{64})\.md$/;
83
+ /** Identity edits from the retained identity history (the newest 20 per file). */
84
+ async function identityChanges(profileDir, config, agentRef) {
85
+ const records = [];
86
+ for (const kind of ['soul', 'identity']) {
87
+ const names = (await identityHistory(profileDir, kind)).map(item => item.name).reverse();
88
+ let current = null;
89
+ try {
90
+ current = (await readIdentity(profileDir, config, kind)).revision;
91
+ }
92
+ catch { /* A missing file has no current revision. */ }
93
+ names.forEach((name, index) => {
94
+ const match = historyName.exec(name);
95
+ if (!match)
96
+ return;
97
+ const ms = Number(match[1]);
98
+ const after = index + 1 < names.length ? historyName.exec(names[index + 1] ?? '')?.[3] ?? null : current;
99
+ const label = kind === 'soul' ? 'Soul' : 'Identity';
100
+ records.push({ ...DevelopmentRecordSchema.parse({ id: `dev_identity_${kind}_${match[1]}_${match[2]}`, agent_ref: agentRef, kind: 'identity_change',
101
+ title: `${label} updated`, body: `The ${kind} file (${kind === 'soul' ? config.identity.soul_file : config.identity.identity_file}) was replaced.`,
102
+ author: 'runtime', epistemic: 'observed', before_sha256: match[3], after_sha256: after,
103
+ sources: [{ kind: 'identity', ref: `${kind}:${name}` }], created_at: new Date(ms).toISOString() }), created_ms: ms });
104
+ });
105
+ }
106
+ return records;
107
+ }
108
+ /** Research method reflections the runtime journaled for finished tasks. */
109
+ function methodReflections(store, agentRef, after, limit) {
110
+ const rows = z.array(z.object({ sequence: z.number().int(), task_id: z.string(), detail_json: z.string(), created_ms: z.number().int() }))
111
+ .parse(store.db.prepare(`SELECT sequence,task_id,detail_json,created_ms FROM events WHERE kind='method_reflection'
112
+ AND (created_ms>? OR (created_ms=? AND printf('dev_reflection_%012d', sequence)>?)) ORDER BY created_ms, sequence LIMIT ?`)
113
+ .all(after.ms, after.ms, after.id, limit));
114
+ return rows.flatMap(row => {
115
+ const detail = z.object({ category: z.string(), observation: z.string() }).passthrough().safeParse(JSON.parse(row.detail_json));
116
+ if (!detail.success)
117
+ return [];
118
+ return [{ ...DevelopmentRecordSchema.parse({ id: `dev_reflection_${String(row.sequence).padStart(12, '0')}`, agent_ref: agentRef, kind: 'method_reflection',
119
+ title: `Method reflection: ${detail.data.category.replaceAll('_', ' ')}`.slice(0, 200), body: detail.data.observation.slice(0, 8000),
120
+ author: 'runtime', epistemic: 'observed', before_sha256: null, after_sha256: null,
121
+ sources: [{ kind: 'task', ref: row.task_id }], created_at: new Date(row.created_ms).toISOString() }), created_ms: row.created_ms }];
122
+ });
123
+ }
124
+ /**
125
+ * One page of the agent's development history in the portable record shape:
126
+ * stored notes and skill changes, identity edits, and method reflections,
127
+ * merged in creation order.
128
+ */
129
+ export async function developmentPage(input, query = {}) {
130
+ const limit = Math.max(1, Math.min(query.limit ?? 50, 200));
131
+ const after = query.after ? decodeDevelopmentCursor(query.after) : { ms: -1, id: '' };
132
+ const kind = query.kind === undefined ? undefined : DevelopmentKind.parse(query.kind);
133
+ const store = input.records.store;
134
+ const agentRef = input.records.agentRef;
135
+ const later = (record) => record.created_ms > after.ms || (record.created_ms === after.ms && record.id > after.id);
136
+ const merged = [
137
+ ...input.records.list({ after, limit: limit + 1, kind }),
138
+ ...(kind === undefined || kind === 'method_reflection' ? methodReflections(store, agentRef, after, limit + 1) : []),
139
+ ...(kind === undefined || kind === 'identity_change' ? (await identityChanges(input.profileDir, input.config, agentRef)).filter(later) : [])
140
+ ].sort((a, b) => a.created_ms - b.created_ms || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
141
+ const page = merged.slice(0, limit);
142
+ const last = page.at(-1);
143
+ return { records: page.map(({ created_ms: _created, ...record }) => record),
144
+ next: merged.length > limit && last ? encodeDevelopmentCursor({ ms: last.created_ms, id: last.id }) : null };
145
+ }
146
+ /** Record an operator's skill selection change, with the configuration revisions before and after it. */
147
+ export function recordSkillChange(records, name, enabled, before, after) {
148
+ return records.add({ kind: 'skill_change', title: `Skill ${name} ${enabled ? 'enabled' : 'disabled'}`.slice(0, 200),
149
+ body: `The operator ${enabled ? 'enabled' : 'disabled'} the ${name} skill. It applies after the profile restarts.`,
150
+ sources: [{ kind: 'skill', ref: name }], author: 'operator', epistemic: 'observed', before_sha256: before, after_sha256: after });
151
+ }
@@ -0,0 +1,22 @@
1
+ import type { Content } from 'pdfmake/interfaces.js';
2
+ /** Renders Markdown to DOCX bytes. */
3
+ export type DocxWriter = (markdown: string, options: {
4
+ title: string;
5
+ }) => Promise<Uint8Array>;
6
+ export declare const MAX_RENDER_SOURCE_CHARS = 200000;
7
+ export declare function renderDocx(markdown: string, title: string): Promise<Uint8Array>;
8
+ type Inline = string | {
9
+ text: string;
10
+ bold?: boolean;
11
+ italics?: boolean;
12
+ background?: string;
13
+ link?: string;
14
+ decoration?: 'underline';
15
+ };
16
+ /** Bold, italics, inline code and links. Images keep only their alternative text. */
17
+ export declare function inlineMarkdown(source: string): Inline[];
18
+ /** Convert Markdown (headings, paragraphs, lists, quotes, tables, code and ```svg blocks) to pdfmake content. */
19
+ export declare function markdownToPdfContent(markdown: string): Content[];
20
+ /** Render Markdown to a PDF. Remote images and local files are never read. */
21
+ export declare function renderPdf(markdown: string, title: string): Promise<Uint8Array>;
22
+ export {};