@hmharness/observability 0.7.0 → 0.7.2

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.
@@ -0,0 +1,90 @@
1
+ /**
2
+ * @hmharness/observability - Trajectory Contract v1 (P1-01)
3
+ *
4
+ * The audit called for: "稳定 schema、事件版本、migration、export/import"
5
+ *
6
+ * This module formalizes the trajectory data contract:
7
+ * 1. Versioned RunEvent schema (v1, backward compatible)
8
+ * 2. Export/import with validation
9
+ * 3. Migration hooks for future schema versions
10
+ * 4. Contract validation (every trajectory must conform)
11
+ */
12
+ /** Schema version for this contract */
13
+ export declare const TRAJECTORY_SCHEMA_VERSION = 1;
14
+ /** All valid event types in the v1 schema */
15
+ export declare const EVENT_TYPES_V1: readonly ["session.start", "session.end", "turn.start", "turn.end", "tool.call", "tool.result", "approval.request", "approval.granted", "approval.denied", "model.request", "model.response", "error", "custom"];
16
+ export type EventType = typeof EVENT_TYPES_V1[number];
17
+ /** The canonical RunEvent per the v1 contract */
18
+ export interface RunEventV1 {
19
+ /** schema version (always 1 for this contract) */
20
+ _v: 1;
21
+ /** unique event id */
22
+ id: string;
23
+ /** run/session id this event belongs to */
24
+ runId: string;
25
+ /** event type from EVENT_TYPES_V1 */
26
+ type: EventType;
27
+ /** wall-clock timestamp (ISO 8601) */
28
+ time: string;
29
+ /** event sequence number within the run (monotonic) */
30
+ seq: number;
31
+ /** event-specific payload */
32
+ data: Record<string, unknown>;
33
+ /** redaction metadata (what was stripped) */
34
+ _redacted?: string[];
35
+ }
36
+ /** A complete trajectory (all events for one run) */
37
+ export interface TrajectoryV1 {
38
+ schemaVersion: 1;
39
+ runId: string;
40
+ startedAt: string;
41
+ endedAt?: string;
42
+ events: RunEventV1[];
43
+ /** summary metrics extracted from events */
44
+ metrics: {
45
+ turns: number;
46
+ toolCalls: number;
47
+ toolFailures: number;
48
+ totalTokens: number;
49
+ durationMs: number;
50
+ };
51
+ }
52
+ /**
53
+ * Validate that an event conforms to the v1 contract.
54
+ * Pure - testable.
55
+ */
56
+ export declare function validateEvent(event: unknown): {
57
+ valid: boolean;
58
+ errors: string[];
59
+ };
60
+ /**
61
+ * Validate a complete trajectory.
62
+ * Pure - testable.
63
+ */
64
+ export declare function validateTrajectory(traj: unknown): {
65
+ valid: boolean;
66
+ errors: string[];
67
+ };
68
+ /**
69
+ * Export a trajectory as a portable JSON string.
70
+ * Pure - testable.
71
+ */
72
+ export declare function exportTrajectory(traj: TrajectoryV1): string;
73
+ /**
74
+ * Import a trajectory from a JSON string, with validation.
75
+ * Pure - testable.
76
+ */
77
+ export declare function importTrajectory(json: string): {
78
+ ok: boolean;
79
+ trajectory?: TrajectoryV1;
80
+ errors: string[];
81
+ };
82
+ /**
83
+ * Migration hook: upgrade a trajectory from an older schema version.
84
+ * Currently only v1 exists, but this is where v1->v2 migrations will live.
85
+ * Pure - testable.
86
+ */
87
+ export declare function migrateTrajectory(traj: Record<string, unknown>): {
88
+ migrated: boolean;
89
+ version: number;
90
+ };
@@ -0,0 +1,123 @@
1
+ /**
2
+ * @hmharness/observability - Trajectory Contract v1 (P1-01)
3
+ *
4
+ * The audit called for: "稳定 schema、事件版本、migration、export/import"
5
+ *
6
+ * This module formalizes the trajectory data contract:
7
+ * 1. Versioned RunEvent schema (v1, backward compatible)
8
+ * 2. Export/import with validation
9
+ * 3. Migration hooks for future schema versions
10
+ * 4. Contract validation (every trajectory must conform)
11
+ */
12
+ /** Schema version for this contract */
13
+ export const TRAJECTORY_SCHEMA_VERSION = 1;
14
+ /** All valid event types in the v1 schema */
15
+ export const EVENT_TYPES_V1 = [
16
+ 'session.start', 'session.end',
17
+ 'turn.start', 'turn.end',
18
+ 'tool.call', 'tool.result',
19
+ 'approval.request', 'approval.granted', 'approval.denied',
20
+ 'model.request', 'model.response',
21
+ 'error', 'custom',
22
+ ];
23
+ /**
24
+ * Validate that an event conforms to the v1 contract.
25
+ * Pure - testable.
26
+ */
27
+ export function validateEvent(event) {
28
+ const errors = [];
29
+ const e = event;
30
+ if (typeof e !== 'object' || e === null) {
31
+ errors.push('event is not an object');
32
+ return { valid: false, errors };
33
+ }
34
+ if (e._v !== 1)
35
+ errors.push(`_v must be 1, got ${e._v}`);
36
+ if (!e.id || typeof e.id !== 'string')
37
+ errors.push('id must be a non-empty string');
38
+ if (!e.runId || typeof e.runId !== 'string')
39
+ errors.push('runId must be a non-empty string');
40
+ if (!e.type || !EVENT_TYPES_V1.includes(e.type))
41
+ errors.push(`type must be one of ${EVENT_TYPES_V1.join('|')}, got ${e.type}`);
42
+ if (!e.time || !/^\d{4}-\d{2}-\d{2}T/.test(String(e.time)))
43
+ errors.push('time must be ISO 8601');
44
+ if (typeof e.seq !== 'number' || e.seq < 0)
45
+ errors.push('seq must be a non-negative number');
46
+ if (typeof e.data !== 'object' || e.data === null)
47
+ errors.push('data must be an object');
48
+ return { valid: errors.length === 0, errors };
49
+ }
50
+ /**
51
+ * Validate a complete trajectory.
52
+ * Pure - testable.
53
+ */
54
+ export function validateTrajectory(traj) {
55
+ const errors = [];
56
+ const t = traj;
57
+ if (typeof t !== 'object' || t === null) {
58
+ errors.push('trajectory is not an object');
59
+ return { valid: false, errors };
60
+ }
61
+ if (t.schemaVersion !== 1)
62
+ errors.push(`schemaVersion must be 1, got ${t.schemaVersion}`);
63
+ if (!t.runId || typeof t.runId !== 'string')
64
+ errors.push('runId must be a string');
65
+ if (!t.startedAt || !/^\d{4}-\d{2}-\d{2}T/.test(String(t.startedAt)))
66
+ errors.push('startedAt must be ISO 8601');
67
+ if (!Array.isArray(t.events)) {
68
+ errors.push('events must be an array');
69
+ return { valid: false, errors };
70
+ }
71
+ for (let i = 0; i < t.events.length; i++) {
72
+ const v = validateEvent(t.events[i]);
73
+ if (!v.valid)
74
+ errors.push(`events[${i}]: ${v.errors.join('; ')}`);
75
+ }
76
+ // seq monotonicity check
77
+ for (let i = 1; i < t.events.length; i++) {
78
+ if (t.events[i].seq <= t.events[i - 1].seq) {
79
+ errors.push(`events[${i}].seq (${t.events[i].seq}) not greater than events[${i - 1}].seq (${t.events[i - 1].seq})`);
80
+ }
81
+ }
82
+ return { valid: errors.length === 0, errors };
83
+ }
84
+ /**
85
+ * Export a trajectory as a portable JSON string.
86
+ * Pure - testable.
87
+ */
88
+ export function exportTrajectory(traj) {
89
+ return JSON.stringify({
90
+ ...traj,
91
+ _exportedAt: new Date().toISOString(),
92
+ _contractVersion: TRAJECTORY_SCHEMA_VERSION,
93
+ }, null, 2);
94
+ }
95
+ /**
96
+ * Import a trajectory from a JSON string, with validation.
97
+ * Pure - testable.
98
+ */
99
+ export function importTrajectory(json) {
100
+ try {
101
+ const parsed = JSON.parse(json);
102
+ const v = validateTrajectory(parsed);
103
+ if (!v.valid)
104
+ return { ok: false, errors: v.errors };
105
+ return { ok: true, trajectory: parsed, errors: [] };
106
+ }
107
+ catch (e) {
108
+ return { ok: false, errors: [`invalid JSON: ${String(e).slice(0, 100)}`] };
109
+ }
110
+ }
111
+ /**
112
+ * Migration hook: upgrade a trajectory from an older schema version.
113
+ * Currently only v1 exists, but this is where v1->v2 migrations will live.
114
+ * Pure - testable.
115
+ */
116
+ export function migrateTrajectory(traj) {
117
+ const v = Number(traj.schemaVersion ?? 0);
118
+ if (v === 0) {
119
+ // implicit v0 (before schemaVersion field was added) → add it
120
+ return { migrated: true, version: 1 };
121
+ }
122
+ return { migrated: false, version: v };
123
+ }
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export * from './events.ts';
2
2
  export * from './store.ts';
3
3
  export * from './recorder.ts';
4
+ export * from './contract.ts';
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
1
  export * from "./events.js";
2
2
  export * from "./store.js";
3
3
  export * from "./recorder.js";
4
+ export * from "./contract.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hmharness/observability",
3
- "version": "0.7.0",
3
+ "version": "0.7.2",
4
4
  "description": "hmharness observability: typed RunEvent schema + append-only TrajectoryStore. Every agent run becomes a reproducible, comparable, exportable experiment sample (V2 blueprint M1 - flight recorder). Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",