@defai.digital/trace-domain 13.0.3

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/LICENSE ADDED
@@ -0,0 +1,214 @@
1
+ AutomatosX Open Source Edition - Apache License 2.0
2
+
3
+ This license applies ONLY to the AutomatosX Open Source Edition code
4
+ published on GitHub at https://github.com/defai-digital/automatosx
5
+
6
+ This license does NOT apply to:
7
+ - AutomatosX Pro Edition (proprietary software - separate EULA)
8
+ - AutomatosX Enterprise Edition (proprietary software - separate agreement)
9
+
10
+ For commercial editions, see COMMERCIAL-LICENSE.md
11
+
12
+ ===============================================================================
13
+
14
+ Apache License
15
+ Version 2.0, January 2004
16
+ http://www.apache.org/licenses/
17
+
18
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
19
+
20
+ 1. Definitions.
21
+
22
+ "License" shall mean the terms and conditions for use, reproduction,
23
+ and distribution as defined by Sections 1 through 9 of this document.
24
+
25
+ "Licensor" shall mean the copyright owner or entity authorized by
26
+ the copyright owner that is granting the License.
27
+
28
+ "Legal Entity" shall mean the union of the acting entity and all
29
+ other entities that control, are controlled by, or are under common
30
+ control with that entity. For the purposes of this definition,
31
+ "control" means (i) the power, direct or indirect, to cause the
32
+ direction or management of such entity, whether by contract or
33
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
34
+ outstanding shares, or (iii) beneficial ownership of such entity.
35
+
36
+ "You" (or "Your") shall mean an individual or Legal Entity
37
+ exercising permissions granted by this License.
38
+
39
+ "Source" form shall mean the preferred form for making modifications,
40
+ including but not limited to software source code, documentation
41
+ source, and configuration files.
42
+
43
+ "Object" form shall mean any form resulting from mechanical
44
+ transformation or translation of a Source form, including but
45
+ not limited to compiled object code, generated documentation,
46
+ and conversions to other media types.
47
+
48
+ "Work" shall mean the work of authorship, whether in Source or
49
+ Object form, made available under the License, as indicated by a
50
+ copyright notice that is included in or attached to the work
51
+ (an example is provided in the Appendix below).
52
+
53
+ "Derivative Works" shall mean any work, whether in Source or Object
54
+ form, that is based on (or derived from) the Work and for which the
55
+ editorial revisions, annotations, elaborations, or other modifications
56
+ represent, as a whole, an original work of authorship. For the purposes
57
+ of this License, Derivative Works shall not include works that remain
58
+ separable from, or merely link (or bind by name) to the interfaces of,
59
+ the Work and Derivative Works thereof.
60
+
61
+ "Contribution" shall mean any work of authorship, including
62
+ the original version of the Work and any modifications or additions
63
+ to that Work or Derivative Works thereof, that is intentionally
64
+ submitted to Licensor for inclusion in the Work by the copyright owner
65
+ or by an individual or Legal Entity authorized to submit on behalf of
66
+ the copyright owner. For the purposes of this definition, "submitted"
67
+ means any form of electronic, verbal, or written communication sent
68
+ to the Licensor or its representatives, including but not limited to
69
+ communication on electronic mailing lists, source code control systems,
70
+ and issue tracking systems that are managed by, or on behalf of, the
71
+ Licensor for the purpose of discussing and improving the Work, but
72
+ excluding communication that is conspicuously marked or otherwise
73
+ designated in writing by the copyright owner as "Not a Contribution."
74
+
75
+ "Contributor" shall mean Licensor and any individual or Legal Entity
76
+ on behalf of whom a Contribution has been received by Licensor and
77
+ subsequently incorporated within the Work.
78
+
79
+ 2. Grant of Copyright License. Subject to the terms and conditions of
80
+ this License, each Contributor hereby grants to You a perpetual,
81
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
82
+ copyright license to reproduce, prepare Derivative Works of,
83
+ publicly display, publicly perform, sublicense, and distribute the
84
+ Work and such Derivative Works in Source or Object form.
85
+
86
+ 3. Grant of Patent License. Subject to the terms and conditions of
87
+ this License, each Contributor hereby grants to You a perpetual,
88
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
89
+ (except as stated in this section) patent license to make, have made,
90
+ use, offer to sell, sell, import, and otherwise transfer the Work,
91
+ where such license applies only to those patent claims licensable
92
+ by such Contributor that are necessarily infringed by their
93
+ Contribution(s) alone or by combination of their Contribution(s)
94
+ with the Work to which such Contribution(s) was submitted. If You
95
+ institute patent litigation against any entity (including a
96
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
97
+ or a Contribution incorporated within the Work constitutes direct
98
+ or contributory patent infringement, then any patent licenses
99
+ granted to You under this License for that Work shall terminate
100
+ as of the date such litigation is filed.
101
+
102
+ 4. Redistribution. You may reproduce and distribute copies of the
103
+ Work or Derivative Works thereof in any medium, with or without
104
+ modifications, and in Source or Object form, provided that You
105
+ meet the following conditions:
106
+
107
+ (a) You must give any other recipients of the Work or
108
+ Derivative Works a copy of this License; and
109
+
110
+ (b) You must cause any modified files to carry prominent notices
111
+ stating that You changed the files; and
112
+
113
+ (c) You must retain, in the Source form of any Derivative Works
114
+ that You distribute, all copyright, patent, trademark, and
115
+ attribution notices from the Source form of the Work,
116
+ excluding those notices that do not pertain to any part of
117
+ the Derivative Works; and
118
+
119
+ (d) If the Work includes a "NOTICE" text file as part of its
120
+ distribution, then any Derivative Works that You distribute must
121
+ include a readable copy of the attribution notices contained
122
+ within such NOTICE file, excluding those notices that do not
123
+ pertain to any part of the Derivative Works, in at least one
124
+ of the following places: within a NOTICE text file distributed
125
+ as part of the Derivative Works; within the Source form or
126
+ documentation, if provided along with the Derivative Works; or,
127
+ within a display generated by the Derivative Works, if and
128
+ wherever such third-party notices normally appear. The contents
129
+ of the NOTICE file are for informational purposes only and
130
+ do not modify the License. You may add Your own attribution
131
+ notices within Derivative Works that You distribute, alongside
132
+ or as an addendum to the NOTICE text from the Work, provided
133
+ that such additional attribution notices cannot be construed
134
+ as modifying the License.
135
+
136
+ You may add Your own copyright statement to Your modifications and
137
+ may provide additional or different license terms and conditions
138
+ for use, reproduction, or distribution of Your modifications, or
139
+ for any such Derivative Works as a whole, provided Your use,
140
+ reproduction, and distribution of the Work otherwise complies with
141
+ the conditions stated in this License.
142
+
143
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
144
+ any Contribution intentionally submitted for inclusion in the Work
145
+ by You to the Licensor shall be under the terms and conditions of
146
+ this License, without any additional terms or conditions.
147
+ Notwithstanding the above, nothing herein shall supersede or modify
148
+ the terms of any separate license agreement you may have executed
149
+ with Licensor regarding such Contributions.
150
+
151
+ 6. Trademarks. This License does not grant permission to use the trade
152
+ names, trademarks, service marks, or product names of the Licensor,
153
+ except as required for reasonable and customary use in describing the
154
+ origin of the Work and reproducing the content of the NOTICE file.
155
+
156
+ 7. Disclaimer of Warranty. Unless required by applicable law or
157
+ agreed to in writing, Licensor provides the Work (and each
158
+ Contributor provides its Contributions) on an "AS IS" BASIS,
159
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
160
+ implied, including, without limitation, any warranties or conditions
161
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
162
+ PARTICULAR PURPOSE. You are solely responsible for determining the
163
+ appropriateness of using or redistributing the Work and assume any
164
+ risks associated with Your exercise of permissions under this License.
165
+
166
+ 8. Limitation of Liability. In no event and under no legal theory,
167
+ whether in tort (including negligence), contract, or otherwise,
168
+ unless required by applicable law (such as deliberate and grossly
169
+ negligent acts) or agreed to in writing, shall any Contributor be
170
+ liable to You for damages, including any direct, indirect, special,
171
+ incidental, or consequential damages of any character arising as a
172
+ result of this License or out of the use or inability to use the
173
+ Work (including but not limited to damages for loss of goodwill,
174
+ work stoppage, computer failure or malfunction, or any and all
175
+ other commercial damages or losses), even if such Contributor
176
+ has been advised of the possibility of such damages.
177
+
178
+ 9. Accepting Warranty or Additional Liability. While redistributing
179
+ the Work or Derivative Works thereof, You may choose to offer,
180
+ and charge a fee for, acceptance of support, warranty, indemnity,
181
+ or other liability obligations and/or rights consistent with this
182
+ License. However, in accepting such obligations, You may act only
183
+ on Your own behalf and on Your sole responsibility, not on behalf
184
+ of any other Contributor, and only if You agree to indemnify,
185
+ defend, and hold each Contributor harmless for any liability
186
+ incurred by, or claims asserted against, such Contributor by reason
187
+ of your accepting any such warranty or additional liability.
188
+
189
+ END OF TERMS AND CONDITIONS
190
+
191
+ APPENDIX: How to apply the Apache License to your work.
192
+
193
+ To apply the Apache License to your work, attach the following
194
+ boilerplate notice, with the fields enclosed by brackets "[]"
195
+ replaced with your own identifying information. (Don't include
196
+ the brackets!) The text should be enclosed in the appropriate
197
+ comment syntax for the file format. We also recommend that a
198
+ file or class name and description of purpose be included on the
199
+ same "printed page" as the copyright notice for easier
200
+ identification within third-party archives.
201
+
202
+ Copyright 2024-2025 DEFAI Private Limited
203
+
204
+ Licensed under the Apache License, Version 2.0 (the "License");
205
+ you may not use this file except in compliance with the License.
206
+ You may obtain a copy of the License at
207
+
208
+ http://www.apache.org/licenses/LICENSE-2.0
209
+
210
+ Unless required by applicable law or agreed to in writing, software
211
+ distributed under the License is distributed on an "AS IS" BASIS,
212
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
213
+ See the License for the specific language governing permissions and
214
+ limitations under the License.
@@ -0,0 +1,99 @@
1
+ import { type Trace, type TraceStatus } from '@defai.digital/contracts';
2
+ import type { TraceReader } from './types.js';
3
+ /**
4
+ * Analysis result for a trace
5
+ */
6
+ export interface TraceAnalysis {
7
+ traceId: string;
8
+ isComplete: boolean;
9
+ status: TraceStatus;
10
+ eventCount: number;
11
+ errorCount: number;
12
+ totalDurationMs: number;
13
+ stepDurations: Map<string, number>;
14
+ routingDecisions: RoutingDecisionInfo[];
15
+ errors: ErrorInfo[];
16
+ timeline: TimelineEntry[];
17
+ }
18
+ /**
19
+ * Routing decision info
20
+ */
21
+ export interface RoutingDecisionInfo {
22
+ eventId: string;
23
+ timestamp: string;
24
+ selectedModel: string;
25
+ provider: string;
26
+ reasoning: string;
27
+ }
28
+ /**
29
+ * Error info
30
+ */
31
+ export interface ErrorInfo {
32
+ eventId: string;
33
+ timestamp: string;
34
+ code: string;
35
+ message: string;
36
+ context?: Record<string, unknown> | undefined;
37
+ }
38
+ /**
39
+ * Timeline entry
40
+ */
41
+ export interface TimelineEntry {
42
+ eventId: string;
43
+ type: string;
44
+ timestamp: string;
45
+ durationMs?: number | undefined;
46
+ status?: TraceStatus | undefined;
47
+ depth: number;
48
+ }
49
+ /**
50
+ * Trace analyzer for understanding execution traces
51
+ * INV-TR-003: Supports full decision replay
52
+ */
53
+ export declare class TraceAnalyzer {
54
+ private readonly reader;
55
+ constructor(reader: TraceReader);
56
+ /**
57
+ * Analyzes a trace
58
+ * INV-TR-001: Checks for complete event chain
59
+ */
60
+ analyze(traceId: string): Promise<TraceAnalysis>;
61
+ /**
62
+ * Gets a complete trace object
63
+ */
64
+ getFullTrace(traceId: string): Promise<Trace>;
65
+ /**
66
+ * Replays routing decisions from a trace
67
+ * INV-TR-003: Full decision replay
68
+ */
69
+ replayRoutingDecisions(traceId: string): Promise<RoutingDecisionInfo[]>;
70
+ /**
71
+ * Extracts routing decisions from events
72
+ */
73
+ private extractRoutingDecisions;
74
+ /**
75
+ * Extracts errors from events
76
+ */
77
+ private extractErrors;
78
+ /**
79
+ * Builds a timeline from events
80
+ */
81
+ private buildTimeline;
82
+ /**
83
+ * Calculates step durations
84
+ */
85
+ private calculateStepDurations;
86
+ /**
87
+ * Determines trace status
88
+ */
89
+ private determineStatus;
90
+ /**
91
+ * Calculates total duration
92
+ */
93
+ private calculateTotalDuration;
94
+ }
95
+ /**
96
+ * Creates a trace analyzer
97
+ */
98
+ export declare function createTraceAnalyzer(reader: TraceReader): TraceAnalyzer;
99
+ //# sourceMappingURL=analyzer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"analyzer.d.ts","sourceRoot":"","sources":["../src/analyzer.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,KAAK,KAAK,EACV,KAAK,WAAW,EACjB,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE9C;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,OAAO,CAAC;IACpB,MAAM,EAAE,WAAW,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,eAAe,EAAE,MAAM,C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;OAEG;IACH,OAAO,CAAC,uBAAuB;IAmB/B;;OAEG;IACH,OAAO,CAAC,aAAa;IAmBrB;;OAEG;IACH,OAAO,CAAC,aAAa;IAuBrB;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAe9B;;OAEG;IACH,OAAO,CAAC,eAAe;IAmBvB;;OAEG;IACH,OAAO,CAAC,sBAAsB;CAsB/B;AAED;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,WAAW,GAAG,aAAa,CAEtE"}
@@ -0,0 +1,190 @@
1
+ import { isTraceComplete, getOrderedEvents, } from '@defai.digital/contracts';
2
+ /**
3
+ * Trace analyzer for understanding execution traces
4
+ * INV-TR-003: Supports full decision replay
5
+ */
6
+ export class TraceAnalyzer {
7
+ reader;
8
+ constructor(reader) {
9
+ this.reader = reader;
10
+ }
11
+ /**
12
+ * Analyzes a trace
13
+ * INV-TR-001: Checks for complete event chain
14
+ */
15
+ async analyze(traceId) {
16
+ const events = await this.reader.getTrace(traceId);
17
+ const orderedEvents = getOrderedEvents(events);
18
+ // INV-TR-001: Check completeness
19
+ const isComplete = isTraceComplete(events);
20
+ // Extract routing decisions (INV-TR-003)
21
+ const routingDecisions = this.extractRoutingDecisions(orderedEvents);
22
+ // Extract errors (INV-TR-005)
23
+ const errors = this.extractErrors(orderedEvents);
24
+ // Build timeline
25
+ const timeline = this.buildTimeline(orderedEvents);
26
+ // Calculate step durations
27
+ const stepDurations = this.calculateStepDurations(orderedEvents);
28
+ // Determine status
29
+ const status = this.determineStatus(orderedEvents, isComplete);
30
+ // Calculate total duration
31
+ const totalDurationMs = this.calculateTotalDuration(orderedEvents);
32
+ return {
33
+ traceId,
34
+ isComplete,
35
+ status,
36
+ eventCount: events.length,
37
+ errorCount: errors.length,
38
+ totalDurationMs,
39
+ stepDurations,
40
+ routingDecisions,
41
+ errors,
42
+ timeline,
43
+ };
44
+ }
45
+ /**
46
+ * Gets a complete trace object
47
+ */
48
+ async getFullTrace(traceId) {
49
+ const events = await this.reader.getTrace(traceId);
50
+ const orderedEvents = getOrderedEvents(events);
51
+ const status = this.determineStatus(orderedEvents, isTraceComplete(events));
52
+ const startEvent = orderedEvents.find((e) => e.type === 'run.start');
53
+ const endEvent = orderedEvents.find((e) => e.type === 'run.end');
54
+ return {
55
+ traceId,
56
+ startTime: startEvent?.timestamp ?? new Date().toISOString(),
57
+ endTime: endEvent?.timestamp,
58
+ events: orderedEvents,
59
+ status,
60
+ summary: {
61
+ totalDurationMs: this.calculateTotalDuration(orderedEvents),
62
+ eventCount: events.length,
63
+ errorCount: events.filter((e) => e.type === 'error').length,
64
+ },
65
+ };
66
+ }
67
+ /**
68
+ * Replays routing decisions from a trace
69
+ * INV-TR-003: Full decision replay
70
+ */
71
+ async replayRoutingDecisions(traceId) {
72
+ const analysis = await this.analyze(traceId);
73
+ return analysis.routingDecisions;
74
+ }
75
+ /**
76
+ * Extracts routing decisions from events
77
+ */
78
+ extractRoutingDecisions(events) {
79
+ return events
80
+ .filter((e) => e.type === 'decision.routing')
81
+ .map((e) => {
82
+ const payload = e.payload;
83
+ return {
84
+ eventId: e.eventId,
85
+ timestamp: e.timestamp,
86
+ selectedModel: payload.selectedModel ?? 'unknown',
87
+ provider: payload.provider ?? 'unknown',
88
+ reasoning: payload.reasoning ?? '',
89
+ };
90
+ });
91
+ }
92
+ /**
93
+ * Extracts errors from events
94
+ */
95
+ extractErrors(events) {
96
+ return events
97
+ .filter((e) => e.type === 'error')
98
+ .map((e) => {
99
+ const payload = e.payload;
100
+ return {
101
+ eventId: e.eventId,
102
+ timestamp: e.timestamp,
103
+ code: payload.code ?? 'UNKNOWN_ERROR',
104
+ message: payload.message ?? 'Unknown error',
105
+ context: payload.context,
106
+ };
107
+ });
108
+ }
109
+ /**
110
+ * Builds a timeline from events
111
+ */
112
+ buildTimeline(events) {
113
+ const depthMap = new Map();
114
+ return events.map((e) => {
115
+ // Calculate depth based on parent
116
+ let depth = 0;
117
+ if (e.parentEventId !== undefined) {
118
+ const parentDepth = depthMap.get(e.parentEventId) ?? 0;
119
+ depth = parentDepth + 1;
120
+ }
121
+ depthMap.set(e.eventId, depth);
122
+ return {
123
+ eventId: e.eventId,
124
+ type: e.type,
125
+ timestamp: e.timestamp,
126
+ durationMs: e.durationMs,
127
+ status: e.status,
128
+ depth,
129
+ };
130
+ });
131
+ }
132
+ /**
133
+ * Calculates step durations
134
+ */
135
+ calculateStepDurations(events) {
136
+ const durations = new Map();
137
+ for (const event of events) {
138
+ if (event.type === 'step.execute' && event.durationMs !== undefined) {
139
+ const payload = event.payload;
140
+ if (payload.stepId !== undefined) {
141
+ durations.set(payload.stepId, event.durationMs);
142
+ }
143
+ }
144
+ }
145
+ return durations;
146
+ }
147
+ /**
148
+ * Determines trace status
149
+ */
150
+ determineStatus(events, isComplete) {
151
+ if (!isComplete) {
152
+ return 'running';
153
+ }
154
+ const endEvent = events.find((e) => e.type === 'run.end');
155
+ if (endEvent !== undefined) {
156
+ const payload = endEvent.payload;
157
+ return payload.success === true ? 'success' : 'failure';
158
+ }
159
+ // Check for any errors
160
+ const hasErrors = events.some((e) => e.type === 'error');
161
+ return hasErrors ? 'failure' : 'success';
162
+ }
163
+ /**
164
+ * Calculates total duration
165
+ */
166
+ calculateTotalDuration(events) {
167
+ const endEvent = events.find((e) => e.type === 'run.end');
168
+ if (endEvent?.durationMs !== undefined) {
169
+ return endEvent.durationMs;
170
+ }
171
+ // Calculate from timestamps
172
+ const startEvent = events.find((e) => e.type === 'run.start');
173
+ if (startEvent === undefined) {
174
+ return 0;
175
+ }
176
+ const lastEvent = events[events.length - 1];
177
+ if (lastEvent === undefined) {
178
+ return 0;
179
+ }
180
+ return (new Date(lastEvent.timestamp).getTime() -
181
+ new Date(startEvent.timestamp).getTime());
182
+ }
183
+ }
184
+ /**
185
+ * Creates a trace analyzer
186
+ */
187
+ export function createTraceAnalyzer(reader) {
188
+ return new TraceAnalyzer(reader);
189
+ }
190
+ //# sourceMappingURL=analyzer.js.map
@@ -0,0 +1 @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MAAM,CAAC,CAAC;AACnC,CAAC"}
@@ -0,0 +1,5 @@
1
+ export { InMemoryTraceStore, createInMemoryTraceStore, } from './store.js';
2
+ export { TraceRecorder, TraceRecorderError, createTraceRecorder, } from './recorder.js';
3
+ export { TraceAnalyzer, createTraceAnalyzer, type TraceAnalysis, type RoutingDecisionInfo, type ErrorInfo, type TimelineEntry, } from './analyzer.js';
4
+ export { TraceErrorCodes, type TraceErrorCode, type TraceWriter, type TraceReader, type TraceStore, type TraceSummary, type ActiveTrace, type TraceOptions, type EventOptions, } from './types.js';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,kBAAkB,EAClB,wBAAwB,GACzB,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,aAAa,EACb,kBAAkB,EAClB,mBAAmB,GACpB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,aAAa,EACb,mBAAmB,EACnB,KAAK,aAAa,EAClB,KAAK,mBAAmB,EACxB,KAAK,SAAS,EACd,KAAK,aAAa,GACnB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,eAAe,EACf,KAAK,cAAc,EACnB,KAAK,WAAW,EAChB,KAAK,WAAW,EAChB,KAAK,UAAU,EACf,KAAK,YAAY,EACjB,KAAK,WAAW,EAChB,KAAK,YAAY,EACjB,KAAK,YAAY,GAClB,MAAM,YAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ // Trace Domain
2
+ // Execution tracing following contract invariants
3
+ export { InMemoryTraceStore, createInMemoryTraceStore, } from './store.js';
4
+ export { TraceRecorder, TraceRecorderError, createTraceRecorder, } from './recorder.js';
5
+ export { TraceAnalyzer, createTraceAnalyzer, } from './analyzer.js';
6
+ export { TraceErrorCodes, } from './types.js';
7
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,eAAe;AACf,kDAAkD;AAElD,OAAO,EACL,kBAAkB,EAClB,wBAAwB,GACzB,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,aAAa,EACb,kBAAkB,EAClB,mBAAmB,GACpB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,aAAa,EACb,mBAAmB,GAKpB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,eAAe,GAShB,MAAM,YAAY,CAAC"}
@@ -0,0 +1,79 @@
1
+ import { type TraceEventType } from '@defai.digital/contracts';
2
+ import type { TraceWriter, TraceOptions, EventOptions } from './types.js';
3
+ /**
4
+ * Error thrown by trace recorder
5
+ */
6
+ export declare class TraceRecorderError extends Error {
7
+ readonly code: string;
8
+ constructor(code: string, message: string);
9
+ }
10
+ /**
11
+ * Trace recorder for capturing execution traces
12
+ *
13
+ * Invariants enforced:
14
+ * - INV-TR-001: Complete event chain (run.start → ... → run.end)
15
+ * - INV-TR-002: Strict event ordering via sequence numbers
16
+ * - INV-TR-003: Full decision replay - all events captured
17
+ * - INV-TR-004: Trace isolation - each trace is independent
18
+ * - INV-TR-005: Error traceability - errors captured with context
19
+ */
20
+ export declare class TraceRecorder {
21
+ private readonly writer;
22
+ private activeTraces;
23
+ constructor(writer: TraceWriter);
24
+ /**
25
+ * Starts a new trace
26
+ * INV-TR-001: Emits run.start as first event
27
+ */
28
+ startTrace(workflowId: string, options?: TraceOptions): Promise<string>;
29
+ /**
30
+ * Ends a trace
31
+ * INV-TR-001: Emits run.end as last event
32
+ */
33
+ endTrace(traceId: string, success: boolean, output?: Record<string, unknown>, error?: Record<string, unknown>): Promise<void>;
34
+ /**
35
+ * Records a trace event
36
+ * INV-TR-002: Events are ordered via sequence numbers
37
+ * INV-TR-003: All events captured for replay
38
+ */
39
+ recordEvent(traceId: string, type: TraceEventType, options?: EventOptions): Promise<string>;
40
+ /**
41
+ * Records an error event
42
+ * INV-TR-005: Errors captured with full context
43
+ */
44
+ recordError(traceId: string, code: string, message: string, context?: Record<string, unknown>): Promise<string>;
45
+ /**
46
+ * Records a routing decision
47
+ * INV-TR-003: Full decision context for replay
48
+ */
49
+ recordRoutingDecision(traceId: string, selectedModel: string, provider: string, reasoning: string): Promise<string>;
50
+ /**
51
+ * Records step execution
52
+ */
53
+ recordStepExecution(traceId: string, stepId: string, stepType: string, input?: Record<string, unknown>, output?: Record<string, unknown>, durationMs?: number): Promise<string>;
54
+ /**
55
+ * Starts a scoped operation (pushes parent onto stack)
56
+ */
57
+ startScope(traceId: string, type: TraceEventType): Promise<string>;
58
+ /**
59
+ * Ends a scoped operation (pops parent from stack)
60
+ */
61
+ endScope(traceId: string, type: TraceEventType, success: boolean, durationMs?: number): Promise<void>;
62
+ /**
63
+ * Gets an active trace
64
+ */
65
+ private getActiveTrace;
66
+ /**
67
+ * Checks if a trace is active
68
+ */
69
+ isActive(traceId: string): boolean;
70
+ /**
71
+ * Gets the current event count for a trace
72
+ */
73
+ getEventCount(traceId: string): number;
74
+ }
75
+ /**
76
+ * Creates a trace recorder
77
+ */
78
+ export declare function createTraceRecorder(writer: TraceWriter): TraceRecorder;
79
+ //# sourceMappingURL=recorder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"recorder.d.ts","sourceRoot":"","sources":["../src/recorder.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,cAAc,EACpB,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EACV,WAAW,EAEX,YAAY,EACZ,YAAY,EACb,MAAM,YAAY,CAAC;AAGpB;;GAEG;AACH,qBAAa,kBAAmB,SAAQ,KAAK;aAEzB,IAAI,EAAE,MAAM;gBAAZ,IAAI,EAAE,MAAM,EAC5B,OAAO,EAAE,MAAM;CAKlB;AAED;;;;;;;;;GASG;AACH,qBAAa,aAAa;IACxB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAc;IACrC,OAAO,CAAC,YAAY,CAAkC;gBAE1C,MAAM,EAAE,WAA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AO,EAAE,MAAM,EACf,IAAI,EAAE,cAAc,EACpB,OAAO,EAAE,OAAO,EAChB,UAAU,CAAC,EAAE,MAAM,GAClB,OAAO,CAAC,IAAI,CAAC;IAahB;;OAEG;IACH,OAAO,CAAC,cAAc;IAWtB;;OAEG;IACH,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO;IAIlC;;OAEG;IACH,aAAa,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM;CAIvC;AAED;;GAEG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,WAAW,GAAG,aAAa,CAEtE"}
@@ -0,0 +1,221 @@
1
+ import { createTraceEvent, createTrace, } from '@defai.digital/contracts';
2
+ import { TraceErrorCodes } from './types.js';
3
+ /**
4
+ * Error thrown by trace recorder
5
+ */
6
+ export class TraceRecorderError extends Error {
7
+ code;
8
+ constructor(code, message) {
9
+ super(message);
10
+ this.code = code;
11
+ this.name = 'TraceRecorderError';
12
+ }
13
+ }
14
+ /**
15
+ * Trace recorder for capturing execution traces
16
+ *
17
+ * Invariants enforced:
18
+ * - INV-TR-001: Complete event chain (run.start → ... → run.end)
19
+ * - INV-TR-002: Strict event ordering via sequence numbers
20
+ * - INV-TR-003: Full decision replay - all events captured
21
+ * - INV-TR-004: Trace isolation - each trace is independent
22
+ * - INV-TR-005: Error traceability - errors captured with context
23
+ */
24
+ export class TraceRecorder {
25
+ writer;
26
+ activeTraces = new Map();
27
+ constructor(writer) {
28
+ this.writer = writer;
29
+ }
30
+ /**
31
+ * Starts a new trace
32
+ * INV-TR-001: Emits run.start as first event
33
+ */
34
+ async startTrace(workflowId, options) {
35
+ const { traceId, startTime } = createTrace();
36
+ const activeTrace = {
37
+ traceId,
38
+ startTime,
39
+ events: [],
40
+ context: options?.context,
41
+ currentSequence: 0,
42
+ status: 'running',
43
+ parentEventStack: [],
44
+ };
45
+ this.activeTraces.set(traceId, activeTrace);
46
+ // INV-TR-001: First event must be run.start
47
+ await this.recordEvent(traceId, 'run.start', {
48
+ payload: {
49
+ workflowId,
50
+ ...options?.metadata,
51
+ },
52
+ status: 'running',
53
+ });
54
+ return traceId;
55
+ }
56
+ /**
57
+ * Ends a trace
58
+ * INV-TR-001: Emits run.end as last event
59
+ */
60
+ async endTrace(traceId, success, output, error) {
61
+ const trace = this.getActiveTrace(traceId);
62
+ if (trace.status !== 'running') {
63
+ throw new TraceRecorderError(TraceErrorCodes.TRACE_ALREADY_ENDED, `Trace ${traceId} has already ended`);
64
+ }
65
+ const durationMs = Date.now() - new Date(trace.startTime).getTime();
66
+ // INV-TR-001: Last event must be run.end
67
+ await this.recordEvent(traceId, 'run.end', {
68
+ payload: {
69
+ success,
70
+ output,
71
+ error,
72
+ totalDurationMs: durationMs,
73
+ stepCount: trace.events.filter((e) => e.type === 'step.execute').length,
74
+ },
75
+ status: success ? 'success' : 'failure',
76
+ durationMs,
77
+ });
78
+ trace.status = success ? 'success' : 'failure';
79
+ // Flush and cleanup
80
+ await this.writer.flush();
81
+ this.activeTraces.delete(traceId);
82
+ }
83
+ /**
84
+ * Records a trace event
85
+ * INV-TR-002: Events are ordered via sequence numbers
86
+ * INV-TR-003: All events captured for replay
87
+ */
88
+ async recordEvent(traceId, type, options) {
89
+ const trace = this.getActiveTrace(traceId);
90
+ // Get parent from stack or options
91
+ const parentEventId = options?.parentEventId ?? trace.parentEventStack[trace.parentEventStack.length - 1];
92
+ // INV-TR-002: Assign sequence number
93
+ const sequence = trace.currentSequence++;
94
+ // Build options object for createTraceEvent
95
+ const eventOptions = {
96
+ sequence,
97
+ };
98
+ if (parentEventId !== undefined) {
99
+ eventOptions.parentEventId = parentEventId;
100
+ }
101
+ if (options?.payload !== undefined) {
102
+ eventOptions.payload = options.payload;
103
+ }
104
+ if (trace.context !== undefined) {
105
+ eventOptions.context = trace.context;
106
+ }
107
+ if (options?.status !== undefined) {
108
+ eventOptions.status = options.status;
109
+ }
110
+ const event = createTraceEvent(traceId, type, eventOptions);
111
+ // Add duration if provided
112
+ if (options?.durationMs !== undefined) {
113
+ event.durationMs = options.durationMs;
114
+ }
115
+ // Store in active trace
116
+ trace.events.push(event);
117
+ // Write to store
118
+ await this.writer.write(event);
119
+ return event.eventId;
120
+ }
121
+ /**
122
+ * Records an error event
123
+ * INV-TR-005: Errors captured with full context
124
+ */
125
+ async recordError(traceId, code, message, context) {
126
+ return this.recordEvent(traceId, 'error', {
127
+ payload: {
128
+ code,
129
+ message,
130
+ context,
131
+ stack: new Error().stack,
132
+ },
133
+ status: 'failure',
134
+ });
135
+ }
136
+ /**
137
+ * Records a routing decision
138
+ * INV-TR-003: Full decision context for replay
139
+ */
140
+ async recordRoutingDecision(traceId, selectedModel, provider, reasoning) {
141
+ return this.recordEvent(traceId, 'decision.routing', {
142
+ payload: {
143
+ selectedModel,
144
+ provider,
145
+ reasoning,
146
+ },
147
+ });
148
+ }
149
+ /**
150
+ * Records step execution
151
+ */
152
+ async recordStepExecution(traceId, stepId, stepType, input, output, durationMs) {
153
+ const options = {
154
+ payload: {
155
+ stepId,
156
+ stepType,
157
+ input,
158
+ output,
159
+ },
160
+ };
161
+ if (durationMs !== undefined) {
162
+ options.durationMs = durationMs;
163
+ }
164
+ return this.recordEvent(traceId, 'step.execute', options);
165
+ }
166
+ /**
167
+ * Starts a scoped operation (pushes parent onto stack)
168
+ */
169
+ async startScope(traceId, type) {
170
+ const eventId = await this.recordEvent(traceId, type, {
171
+ status: 'running',
172
+ });
173
+ const trace = this.getActiveTrace(traceId);
174
+ trace.parentEventStack.push(eventId);
175
+ return eventId;
176
+ }
177
+ /**
178
+ * Ends a scoped operation (pops parent from stack)
179
+ */
180
+ async endScope(traceId, type, success, durationMs) {
181
+ const trace = this.getActiveTrace(traceId);
182
+ trace.parentEventStack.pop();
183
+ const options = {
184
+ status: success ? 'success' : 'failure',
185
+ };
186
+ if (durationMs !== undefined) {
187
+ options.durationMs = durationMs;
188
+ }
189
+ await this.recordEvent(traceId, type, options);
190
+ }
191
+ /**
192
+ * Gets an active trace
193
+ */
194
+ getActiveTrace(traceId) {
195
+ const trace = this.activeTraces.get(traceId);
196
+ if (trace === undefined) {
197
+ throw new TraceRecorderError(TraceErrorCodes.TRACE_NOT_FOUND, `Trace ${traceId} not found or already ended`);
198
+ }
199
+ return trace;
200
+ }
201
+ /**
202
+ * Checks if a trace is active
203
+ */
204
+ isActive(traceId) {
205
+ return this.activeTraces.has(traceId);
206
+ }
207
+ /**
208
+ * Gets the current event count for a trace
209
+ */
210
+ getEventCount(traceId) {
211
+ const trace = this.activeTraces.get(traceId);
212
+ return trace?.events.length ?? 0;
213
+ }
214
+ }
215
+ /**
216
+ * Creates a trace recorder
217
+ */
218
+ export function createTraceRecorder(writer) {
219
+ return new TraceRecorder(writer);
220
+ }
221
+ //# sourceMappingURL=recorder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"recorder.js","sourceRoot":"","sources":["../src/recorder.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gBAAgB,EAChB,WAAW,GAEZ,MAAM,0BAA0B,CAAC;AAOlC,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE7C;;GAEG;AACH,MAAM,OAAO,kBAAmB,SAAQ,KAAK;IAEzB;IADlB,YACkB,IAAY,EAC5B,OAAe;QAEf,KAAK,CAAC,OAAO,CAAC,CAAC;QAHC,SAAI,GAAJ,IAAI,CAAQ;QAI5B,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;IACnC,CAAC;CACF;AAED;;;;;;;;;GASG;AACH,MAAM,OAAO,aAAa;IACP,MAAM,CAAc;IAC7B,YAAY,GAAG,IAAI,GAAG,EAAuB,CAAC;IAEtD,YAAY,MAAmB;QAC7B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,UAAU,CACd,UAAkB,EAClB,OAAsB;QAEtB,MAAM,EAAE,OAAO,EAAE,SAAS,EAAE,GAAG,WAAW,EAAE,CAAC;QAE7C,MAAM,WAAW,GAAgB;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IAED;;OAEG;IACH,QAAQ,CAAC,OAAe;QACtB,OAAO,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IACxC,CAAC;IAED;;OAEG;IACH,aAAa,CAAC,OAAe;QAC3B,MAAM,KAAK,GAAG,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAC7C,OAAO,KAAK,EAAE,MAAM,CAAC,MAAM,IAAI,CAAC,CAAC;IACnC,CAAC;CACF;AAED;;GAEG;AACH,MAAM,UAAU,mBAAmB,CAAC,MAAmB;IACrD,OAAO,IAAI,aAAa,CAAC,MAAM,CAAC,CAAC;AACnC,CAAC"}
@@ -0,0 +1,50 @@
1
+ import type { TraceEvent } from '@defai.digital/contracts';
2
+ import type { TraceSummary, TraceStore } from './types.js';
3
+ /**
4
+ * In-memory trace store implementation
5
+ * INV-TR-004: Each trace is independent and self-contained
6
+ */
7
+ export declare class InMemoryTraceStore implements TraceStore {
8
+ private readonly traces;
9
+ private readonly summaries;
10
+ /**
11
+ * Writes a trace event
12
+ * INV-TR-002: Events must be strictly ordered
13
+ */
14
+ write(event: TraceEvent): Promise<void>;
15
+ /**
16
+ * Flushes pending writes (no-op for in-memory)
17
+ */
18
+ flush(): Promise<void>;
19
+ /**
20
+ * Gets all events for a trace
21
+ * INV-TR-002: Events returned in sequence order
22
+ */
23
+ getTrace(traceId: string): Promise<TraceEvent[]>;
24
+ /**
25
+ * Gets a specific event
26
+ */
27
+ getEvent(traceId: string, eventId: string): Promise<TraceEvent | undefined>;
28
+ /**
29
+ * Lists recent traces
30
+ */
31
+ listTraces(limit?: number): Promise<TraceSummary[]>;
32
+ /**
33
+ * Updates trace summary
34
+ */
35
+ private updateSummary;
36
+ /**
37
+ * Deletes a trace and all its events
38
+ * @returns true if trace existed and was deleted
39
+ */
40
+ deleteTrace(traceId: string): Promise<boolean>;
41
+ /**
42
+ * Clears all traces (for testing)
43
+ */
44
+ clear(): void;
45
+ }
46
+ /**
47
+ * Creates an in-memory trace store
48
+ */
49
+ export declare function createInMemoryTraceStore(): InMemoryTraceStore;
50
+ //# sourceMappingURL=store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../src/store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAC3D,OAAO,KAAK,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE3D;;;GAGG;AACH,qBAAa,kBAAmB,YAAW,UAAU;IACnD,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAmC;IAC1D,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAmC;IAE7D;;;OAGG;IACH,KAAK,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC;IAoBvC;;OAEG;IACH,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAKtB;;;OAGG;IACH,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,EAAE,CAAC;IAgBhD;;OAEG;IACH,QAAQ,CACN,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,GACd,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC;IAKlC;;OAEG;IACH,UAAU,CAAC,KAAK,SAAM,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC;IAWhD;;OAEG;IACH,OAAO,CAAC,aAAa;IAuCrB;;;OAGG;IACH,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAS9C;;OAEG;IACH,KAAK,IAAI,IAAI;CAId;AAED;;GAEG;AACH,wBAAgB,wBAAwB,IAAI,kBAAkB,CAE7D"}
package/dist/store.js ADDED
@@ -0,0 +1,133 @@
1
+ /**
2
+ * In-memory trace store implementation
3
+ * INV-TR-004: Each trace is independent and self-contained
4
+ */
5
+ export class InMemoryTraceStore {
6
+ traces = new Map();
7
+ summaries = new Map();
8
+ /**
9
+ * Writes a trace event
10
+ * INV-TR-002: Events must be strictly ordered
11
+ */
12
+ write(event) {
13
+ const { traceId } = event;
14
+ // Get or create trace
15
+ let events = this.traces.get(traceId);
16
+ if (events === undefined) {
17
+ events = [];
18
+ this.traces.set(traceId, events);
19
+ }
20
+ // Freeze event for immutability
21
+ const frozenEvent = Object.freeze(structuredClone(event));
22
+ events.push(frozenEvent);
23
+ // Update summary
24
+ this.updateSummary(traceId, frozenEvent);
25
+ return Promise.resolve();
26
+ }
27
+ /**
28
+ * Flushes pending writes (no-op for in-memory)
29
+ */
30
+ flush() {
31
+ // No-op for in-memory store
32
+ return Promise.resolve();
33
+ }
34
+ /**
35
+ * Gets all events for a trace
36
+ * INV-TR-002: Events returned in sequence order
37
+ */
38
+ getTrace(traceId) {
39
+ const events = this.traces.get(traceId);
40
+ if (events === undefined) {
41
+ return Promise.resolve([]);
42
+ }
43
+ // Sort by sequence (INV-TR-002)
44
+ const sorted = [...events].sort((a, b) => {
45
+ if (a.sequence !== undefined && b.sequence !== undefined) {
46
+ return a.sequence - b.sequence;
47
+ }
48
+ return new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime();
49
+ });
50
+ return Promise.resolve(sorted);
51
+ }
52
+ /**
53
+ * Gets a specific event
54
+ */
55
+ getEvent(traceId, eventId) {
56
+ const events = this.traces.get(traceId);
57
+ return Promise.resolve(events?.find((e) => e.eventId === eventId));
58
+ }
59
+ /**
60
+ * Lists recent traces
61
+ */
62
+ listTraces(limit = 100) {
63
+ const result = [...this.summaries.values()]
64
+ .sort((a, b) => {
65
+ const timeA = new Date(a.startTime).getTime();
66
+ const timeB = new Date(b.startTime).getTime();
67
+ return timeB - timeA; // Most recent first
68
+ })
69
+ .slice(0, limit);
70
+ return Promise.resolve(result);
71
+ }
72
+ /**
73
+ * Updates trace summary
74
+ */
75
+ updateSummary(traceId, event) {
76
+ let summary = this.summaries.get(traceId);
77
+ if (summary === undefined) {
78
+ summary = {
79
+ traceId,
80
+ startTime: event.timestamp,
81
+ status: 'pending',
82
+ eventCount: 0,
83
+ errorCount: 0,
84
+ };
85
+ this.summaries.set(traceId, summary);
86
+ }
87
+ summary.eventCount++;
88
+ if (event.type === 'error') {
89
+ summary.errorCount++;
90
+ }
91
+ if (event.type === 'run.start') {
92
+ summary.startTime = event.timestamp;
93
+ summary.status = 'running';
94
+ }
95
+ if (event.type === 'run.end') {
96
+ summary.endTime = event.timestamp;
97
+ const payload = event.payload;
98
+ summary.status = payload?.success === true ? 'success' : 'failure';
99
+ if (event.durationMs !== undefined) {
100
+ summary.durationMs = event.durationMs;
101
+ }
102
+ }
103
+ if (event.status !== undefined) {
104
+ summary.status = event.status;
105
+ }
106
+ }
107
+ /**
108
+ * Deletes a trace and all its events
109
+ * @returns true if trace existed and was deleted
110
+ */
111
+ deleteTrace(traceId) {
112
+ const existed = this.traces.has(traceId);
113
+ if (existed) {
114
+ this.traces.delete(traceId);
115
+ this.summaries.delete(traceId);
116
+ }
117
+ return Promise.resolve(existed);
118
+ }
119
+ /**
120
+ * Clears all traces (for testing)
121
+ */
122
+ clear() {
123
+ this.traces.clear();
124
+ this.summaries.clear();
125
+ }
126
+ }
127
+ /**
128
+ * Creates an in-memory trace store
129
+ */
130
+ export function createInMemoryTraceStore() {
131
+ return new InMemoryTraceStore();
132
+ }
133
+ //# sourceMappingURL=store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.js","sourceRoot":"","sources":["../src/store.ts"],"names":[],"mappings":"AAGA;;;GAGG;AACH,MAAM,OAAO,kBAAkB;IACZ,MAAM,GAAG,IAAI,GAAG,EAAwB,CAAC;IACzC,SAAS,GAAG,IAAI,GAAG,EAAwB,CAAC;IAE7D;;;OAGG;IACH,KAAK,CAAC,KAAiB;QACrB,MAAM,EAAE,OAAO,EAAE,GAAG,KAAK,CAAC;QAE1B,sBAAsB;QACtB,IAAI,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QACtC,I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IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;QACpB,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC;IACzB,CAAC;CACF;AAED;;GAEG;AACH,MAAM,UAAU,wBAAwB;IACtC,OAAO,IAAI,kBAAkB,EAAE,CAAC;AAClC,CAAC"}
@@ -0,0 +1,92 @@
1
+ import type { TraceEvent, TraceStatus, TraceContext } from '@defai.digital/contracts';
2
+ /**
3
+ * Trace writer interface for persistence
4
+ */
5
+ export interface TraceWriter {
6
+ /**
7
+ * Writes a trace event
8
+ */
9
+ write(event: TraceEvent): Promise<void>;
10
+ /**
11
+ * Flushes pending writes
12
+ */
13
+ flush(): Promise<void>;
14
+ }
15
+ /**
16
+ * Trace reader interface for querying
17
+ */
18
+ export interface TraceReader {
19
+ /**
20
+ * Gets all events for a trace
21
+ */
22
+ getTrace(traceId: string): Promise<TraceEvent[]>;
23
+ /**
24
+ * Gets a specific event
25
+ */
26
+ getEvent(traceId: string, eventId: string): Promise<TraceEvent | undefined>;
27
+ /**
28
+ * Lists recent traces
29
+ */
30
+ listTraces(limit?: number): Promise<TraceSummary[]>;
31
+ }
32
+ /**
33
+ * Trace store interface with delete capability (for cleanup operations)
34
+ */
35
+ export interface TraceStore extends TraceWriter, TraceReader {
36
+ /**
37
+ * Deletes a trace and all its events
38
+ * @returns true if trace existed and was deleted
39
+ */
40
+ deleteTrace(traceId: string): Promise<boolean>;
41
+ }
42
+ /**
43
+ * Summary of a trace
44
+ */
45
+ export interface TraceSummary {
46
+ traceId: string;
47
+ startTime: string;
48
+ endTime?: string;
49
+ status: TraceStatus;
50
+ eventCount: number;
51
+ errorCount: number;
52
+ durationMs?: number;
53
+ }
54
+ /**
55
+ * Active trace being recorded
56
+ */
57
+ export interface ActiveTrace {
58
+ traceId: string;
59
+ startTime: string;
60
+ events: TraceEvent[];
61
+ context?: TraceContext | undefined;
62
+ currentSequence: number;
63
+ status: TraceStatus;
64
+ parentEventStack: string[];
65
+ }
66
+ /**
67
+ * Options for creating a trace
68
+ */
69
+ export interface TraceOptions {
70
+ context?: TraceContext | undefined;
71
+ metadata?: Record<string, unknown> | undefined;
72
+ }
73
+ /**
74
+ * Options for recording an event
75
+ */
76
+ export interface EventOptions {
77
+ parentEventId?: string | undefined;
78
+ durationMs?: number | undefined;
79
+ payload?: Record<string, unknown> | undefined;
80
+ status?: TraceStatus | undefined;
81
+ }
82
+ /**
83
+ * Error codes for trace domain
84
+ */
85
+ export declare const TraceErrorCodes: {
86
+ readonly TRACE_NOT_FOUND: "TRACE_NOT_FOUND";
87
+ readonly TRACE_ALREADY_ENDED: "TRACE_ALREADY_ENDED";
88
+ readonly TRACE_NOT_STARTED: "TRACE_NOT_STARTED";
89
+ readonly INVALID_EVENT_ORDER: "TRACE_INVALID_EVENT_ORDER";
90
+ };
91
+ export type TraceErrorCode = (typeof TraceErrorCodes)[keyof typeof TraceErrorCodes];
92
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,UAAU,EACV,WAAW,EACX,YAAY,EACb,MAAM,0BAA0B,CAAC;AAElC;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B;;OAEG;IACH,KAAK,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAExC;;OAEG;IACH,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAED;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B;;OAEG;IACH,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC;IAEjD;;OAEG;IACH,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAAC;IAE5E;;OAEG;IACH,UAAU,CAAC,KAAK,CAAC,E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;;;;;CAKlB,CAAC;AAEX,MAAM,MAAM,cAAc,GACxB,CAAC,OAAO,eAAe,CAAC,CAAC,MAAM,OAAO,eAAe,CAAC,CAAC"}
package/dist/types.js ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Error codes for trace domain
3
+ */
4
+ export const TraceErrorCodes = {
5
+ TRACE_NOT_FOUND: 'TRACE_NOT_FOUND',
6
+ TRACE_ALREADY_ENDED: 'TRACE_ALREADY_ENDED',
7
+ TRACE_NOT_STARTED: 'TRACE_NOT_STARTED',
8
+ INVALID_EVENT_ORDER: 'TRACE_INVALID_EVENT_ORDER',
9
+ };
10
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAgGA;;GAEG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,eAAe,EAAE,iBAAiB;IAClC,mBAAmB,EAAE,qBAAqB;IAC1C,iBAAiB,EAAE,mBAAmB;IACtC,mBAAmB,EAAE,2BAA2B;CACxC,CAAC"}
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@defai.digital/trace-domain",
3
+ "version": "13.0.3",
4
+ "type": "module",
5
+ "description": "Trace domain - execution tracing following contract invariants",
6
+ "license": "Apache-2.0",
7
+ "author": "DEFAI Private Limited",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/defai-digital/automatosx.git",
11
+ "directory": "packages/core/trace-domain"
12
+ },
13
+ "homepage": "https://github.com/defai-digital/automatosx#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/defai-digital/automatosx/issues"
16
+ },
17
+ "main": "./dist/index.js",
18
+ "types": "./dist/index.d.ts",
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "import": "./dist/index.js"
23
+ }
24
+ },
25
+ "files": [
26
+ "dist"
27
+ ],
28
+ "engines": {
29
+ "node": ">=20.0.0"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "dependencies": {
35
+ "@defai.digital/contracts": "13.0.3"
36
+ },
37
+ "scripts": {
38
+ "build": "tsc --build",
39
+ "clean": "rm -rf dist *.tsbuildinfo"
40
+ }
41
+ }