@auxiora/callgraph 0.1.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/LICENSE ADDED
@@ -0,0 +1,191 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to the Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by the Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding any notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ Copyright 2026 Auxiora Contributors
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
package/package.json ADDED
@@ -0,0 +1,10 @@
1
+ {
2
+ "name": "@auxiora/callgraph",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": "./src/index.ts"
7
+ },
8
+ "dependencies": {},
9
+ "devDependencies": {}
10
+ }
package/src/index.ts ADDED
@@ -0,0 +1,12 @@
1
+ export { CallgraphTracker } from './tracker.js';
2
+ export { CallgraphStore } from './store.js';
3
+ export type { StoredNode, StoredEdge, StoredSnapshot, WorkflowSummary } from './store.js';
4
+ export type {
5
+ AgentNode,
6
+ AgentNodeInput,
7
+ AgentNodeUpdate,
8
+ AgentStatus,
9
+ CallgraphConfig,
10
+ CallgraphEdge,
11
+ CallgraphSnapshot,
12
+ } from './types.js';
package/src/store.ts ADDED
@@ -0,0 +1,142 @@
1
+ import { DatabaseSync } from 'node:sqlite';
2
+ import type { AgentStatus } from './types.js';
3
+
4
+ export interface StoredNode {
5
+ id: string;
6
+ workflowId: string;
7
+ name: string;
8
+ parentId?: string;
9
+ depth: number;
10
+ status: AgentStatus;
11
+ startedAt: number;
12
+ completedAt?: number;
13
+ tokenUsage: number;
14
+ }
15
+
16
+ export interface StoredEdge {
17
+ workflowId: string;
18
+ parentId: string;
19
+ childId: string;
20
+ }
21
+
22
+ export interface WorkflowSummary {
23
+ workflowId: string;
24
+ nodeCount: number;
25
+ firstStartedAt: number;
26
+ }
27
+
28
+ export interface StoredSnapshot {
29
+ nodes: StoredNode[];
30
+ edges: StoredEdge[];
31
+ totalTokenUsage: number;
32
+ }
33
+
34
+ const NODES_DDL = `
35
+ CREATE TABLE IF NOT EXISTS callgraph_nodes (
36
+ id TEXT NOT NULL,
37
+ workflowId TEXT NOT NULL,
38
+ name TEXT NOT NULL,
39
+ parentId TEXT,
40
+ depth INTEGER NOT NULL,
41
+ status TEXT NOT NULL,
42
+ startedAt INTEGER NOT NULL,
43
+ completedAt INTEGER,
44
+ tokenUsage INTEGER NOT NULL DEFAULT 0,
45
+ PRIMARY KEY (id, workflowId)
46
+ )
47
+ `;
48
+
49
+ const EDGES_DDL = `
50
+ CREATE TABLE IF NOT EXISTS callgraph_edges (
51
+ workflowId TEXT NOT NULL,
52
+ parentId TEXT NOT NULL,
53
+ childId TEXT NOT NULL,
54
+ PRIMARY KEY (workflowId, parentId, childId)
55
+ )
56
+ `;
57
+
58
+ export class CallgraphStore {
59
+ private readonly db: DatabaseSync;
60
+ private closed = false;
61
+
62
+ constructor(dbPath: string) {
63
+ this.db = new DatabaseSync(dbPath);
64
+ this.db.exec('PRAGMA journal_mode=WAL');
65
+ this.db.exec('PRAGMA busy_timeout=5000');
66
+ this.db.exec(NODES_DDL);
67
+ this.db.exec(EDGES_DDL);
68
+ }
69
+
70
+ recordNode(node: StoredNode): void {
71
+ if (this.closed) return;
72
+ const stmt = this.db.prepare(
73
+ 'INSERT OR REPLACE INTO callgraph_nodes (id, workflowId, name, parentId, depth, status, startedAt, completedAt, tokenUsage) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
74
+ );
75
+ stmt.run(node.id, node.workflowId, node.name, node.parentId ?? null, node.depth, node.status, node.startedAt, node.completedAt ?? null, node.tokenUsage);
76
+ }
77
+
78
+ recordEdge(edge: StoredEdge): void {
79
+ if (this.closed) return;
80
+ const stmt = this.db.prepare(
81
+ 'INSERT OR IGNORE INTO callgraph_edges (workflowId, parentId, childId) VALUES (?, ?, ?)',
82
+ );
83
+ stmt.run(edge.workflowId, edge.parentId, edge.childId);
84
+ }
85
+
86
+ getNodesByWorkflow(workflowId: string): StoredNode[] {
87
+ if (this.closed) return [];
88
+ const stmt = this.db.prepare('SELECT * FROM callgraph_nodes WHERE workflowId = ? ORDER BY depth ASC, startedAt ASC');
89
+ const rows = stmt.all(workflowId) as Record<string, unknown>[];
90
+ return rows.map((r) => ({
91
+ id: r.id as string,
92
+ workflowId: r.workflowId as string,
93
+ name: r.name as string,
94
+ parentId: (r.parentId as string) || undefined,
95
+ depth: r.depth as number,
96
+ status: r.status as AgentStatus,
97
+ startedAt: r.startedAt as number,
98
+ completedAt: (r.completedAt as number) || undefined,
99
+ tokenUsage: r.tokenUsage as number,
100
+ }));
101
+ }
102
+
103
+ getEdgesByWorkflow(workflowId: string): StoredEdge[] {
104
+ if (this.closed) return [];
105
+ const stmt = this.db.prepare('SELECT * FROM callgraph_edges WHERE workflowId = ?');
106
+ const rows = stmt.all(workflowId) as Record<string, unknown>[];
107
+ return rows.map((r) => ({
108
+ workflowId: r.workflowId as string,
109
+ parentId: r.parentId as string,
110
+ childId: r.childId as string,
111
+ }));
112
+ }
113
+
114
+ getSnapshot(workflowId: string): StoredSnapshot {
115
+ const nodes = this.getNodesByWorkflow(workflowId);
116
+ const edges = this.getEdgesByWorkflow(workflowId);
117
+ let totalTokenUsage = 0;
118
+ for (const node of nodes) {
119
+ totalTokenUsage += node.tokenUsage;
120
+ }
121
+ return { nodes, edges, totalTokenUsage };
122
+ }
123
+
124
+ listWorkflows(): WorkflowSummary[] {
125
+ if (this.closed) return [];
126
+ const stmt = this.db.prepare(
127
+ 'SELECT workflowId, COUNT(*) as nodeCount, MIN(startedAt) as firstStartedAt FROM callgraph_nodes GROUP BY workflowId ORDER BY firstStartedAt DESC',
128
+ );
129
+ const rows = stmt.all() as Record<string, unknown>[];
130
+ return rows.map((r) => ({
131
+ workflowId: r.workflowId as string,
132
+ nodeCount: r.nodeCount as number,
133
+ firstStartedAt: r.firstStartedAt as number,
134
+ }));
135
+ }
136
+
137
+ close(): void {
138
+ if (this.closed) return;
139
+ this.closed = true;
140
+ this.db.close();
141
+ }
142
+ }
package/src/tracker.ts ADDED
@@ -0,0 +1,127 @@
1
+ import type { CallgraphConfig, AgentNode, AgentNodeInput, AgentNodeUpdate, CallgraphEdge } from './types.js';
2
+
3
+ export class CallgraphTracker {
4
+ private readonly nodes = new Map<string, AgentNode>();
5
+ private readonly edges: CallgraphEdge[] = [];
6
+ private readonly children = new Map<string, string[]>();
7
+ private readonly config: CallgraphConfig;
8
+
9
+ constructor(config: CallgraphConfig) {
10
+ this.config = config;
11
+ }
12
+
13
+ addAgent(input: AgentNodeInput): void {
14
+ if (this.nodes.has(input.id)) {
15
+ throw new Error(`Agent ${input.id} already exists in callgraph`);
16
+ }
17
+
18
+ let depth = 0;
19
+ if (input.parentId) {
20
+ const parent = this.nodes.get(input.parentId);
21
+ if (!parent) {
22
+ throw new Error(`Parent agent ${input.parentId} not found`);
23
+ }
24
+ depth = parent.depth + 1;
25
+ if (depth > this.config.maxDepth) {
26
+ throw new Error(`Agent ${input.id} exceeds depth limit (${depth} > ${this.config.maxDepth})`);
27
+ }
28
+ this.edges.push({ parentId: input.parentId, childId: input.id });
29
+ const siblings = this.children.get(input.parentId) ?? [];
30
+ siblings.push(input.id);
31
+ this.children.set(input.parentId, siblings);
32
+ }
33
+
34
+ this.nodes.set(input.id, {
35
+ id: input.id,
36
+ name: input.name,
37
+ parentId: input.parentId,
38
+ depth,
39
+ status: 'running',
40
+ startedAt: input.startedAt,
41
+ tokenUsage: 0,
42
+ });
43
+ }
44
+
45
+ updateAgent(id: string, update: AgentNodeUpdate): void {
46
+ const node = this.nodes.get(id);
47
+ if (!node) {
48
+ throw new Error(`Agent ${id} not found`);
49
+ }
50
+ if (update.status !== undefined) node.status = update.status;
51
+ if (update.completedAt !== undefined) node.completedAt = update.completedAt;
52
+ if (update.tokenUsage !== undefined) node.tokenUsage = update.tokenUsage;
53
+ }
54
+
55
+ getNode(id: string): AgentNode | undefined {
56
+ return this.nodes.get(id);
57
+ }
58
+
59
+ getNodes(): AgentNode[] {
60
+ return [...this.nodes.values()];
61
+ }
62
+
63
+ getEdges(): CallgraphEdge[] {
64
+ return [...this.edges];
65
+ }
66
+
67
+ getChildren(parentId: string): AgentNode[] {
68
+ const childIds = this.children.get(parentId) ?? [];
69
+ return childIds.map((id) => this.nodes.get(id)!);
70
+ }
71
+
72
+ getMaxDepth(): number {
73
+ let max = 0;
74
+ for (const node of this.nodes.values()) {
75
+ if (node.depth > max) max = node.depth;
76
+ }
77
+ return max;
78
+ }
79
+
80
+ topologicalOrder(): string[] {
81
+ const visited = new Set<string>();
82
+ const result: string[] = [];
83
+
84
+ const visit = (id: string): void => {
85
+ if (visited.has(id)) return;
86
+ visited.add(id);
87
+ result.push(id);
88
+ const childIds = this.children.get(id) ?? [];
89
+ for (const childId of childIds) {
90
+ visit(childId);
91
+ }
92
+ };
93
+
94
+ for (const node of this.nodes.values()) {
95
+ if (!node.parentId) {
96
+ visit(node.id);
97
+ }
98
+ }
99
+
100
+ return result;
101
+ }
102
+
103
+ getSubtreeTokenUsage(rootId: string): number {
104
+ const node = this.nodes.get(rootId);
105
+ if (!node) return 0;
106
+
107
+ let total = node.tokenUsage;
108
+ const childIds = this.children.get(rootId) ?? [];
109
+ for (const childId of childIds) {
110
+ total += this.getSubtreeTokenUsage(childId);
111
+ }
112
+ return total;
113
+ }
114
+
115
+ getSnapshot(): { nodes: AgentNode[]; edges: CallgraphEdge[]; maxDepth: number; totalTokenUsage: number } {
116
+ let totalTokens = 0;
117
+ for (const node of this.nodes.values()) {
118
+ totalTokens += node.tokenUsage;
119
+ }
120
+ return {
121
+ nodes: this.getNodes(),
122
+ edges: this.getEdges(),
123
+ maxDepth: this.getMaxDepth(),
124
+ totalTokenUsage: totalTokens,
125
+ };
126
+ }
127
+ }
package/src/types.ts ADDED
@@ -0,0 +1,41 @@
1
+ export interface CallgraphConfig {
2
+ maxDepth: number;
3
+ }
4
+
5
+ export type AgentStatus = 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';
6
+
7
+ export interface AgentNodeInput {
8
+ id: string;
9
+ name: string;
10
+ startedAt: number;
11
+ parentId?: string;
12
+ }
13
+
14
+ export interface AgentNode {
15
+ id: string;
16
+ name: string;
17
+ parentId?: string;
18
+ depth: number;
19
+ status: AgentStatus;
20
+ startedAt: number;
21
+ completedAt?: number;
22
+ tokenUsage: number;
23
+ }
24
+
25
+ export interface AgentNodeUpdate {
26
+ status?: AgentStatus;
27
+ completedAt?: number;
28
+ tokenUsage?: number;
29
+ }
30
+
31
+ export interface CallgraphEdge {
32
+ parentId: string;
33
+ childId: string;
34
+ }
35
+
36
+ export interface CallgraphSnapshot {
37
+ nodes: AgentNode[];
38
+ edges: CallgraphEdge[];
39
+ maxDepth: number;
40
+ totalTokenUsage: number;
41
+ }
@@ -0,0 +1,77 @@
1
+ import { describe, it, expect, afterEach } from 'vitest';
2
+ import { CallgraphStore } from '../src/store.js';
3
+ import { mkdtempSync, rmSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { tmpdir } from 'node:os';
6
+
7
+ describe('CallgraphStore', () => {
8
+ let store: CallgraphStore;
9
+ let tmpDir: string;
10
+
11
+ afterEach(() => {
12
+ store?.close();
13
+ if (tmpDir) rmSync(tmpDir, { recursive: true, force: true });
14
+ });
15
+
16
+ it('stores and retrieves agent nodes', () => {
17
+ tmpDir = mkdtempSync(join(tmpdir(), 'cg-'));
18
+ store = new CallgraphStore(join(tmpDir, 'callgraph.db'));
19
+
20
+ store.recordNode({
21
+ id: 'agent-1',
22
+ workflowId: 'wf-1',
23
+ name: 'supervisor',
24
+ depth: 0,
25
+ status: 'running',
26
+ startedAt: Date.now(),
27
+ tokenUsage: 0,
28
+ });
29
+
30
+ const nodes = store.getNodesByWorkflow('wf-1');
31
+ expect(nodes).toHaveLength(1);
32
+ expect(nodes[0].name).toBe('supervisor');
33
+ expect(nodes[0].depth).toBe(0);
34
+ });
35
+
36
+ it('stores and retrieves edges', () => {
37
+ tmpDir = mkdtempSync(join(tmpdir(), 'cg-'));
38
+ store = new CallgraphStore(join(tmpDir, 'callgraph.db'));
39
+
40
+ store.recordNode({ id: 'p', workflowId: 'wf-1', name: 'parent', depth: 0, status: 'running', startedAt: Date.now(), tokenUsage: 0 });
41
+ store.recordNode({ id: 'c', workflowId: 'wf-1', name: 'child', depth: 1, status: 'running', startedAt: Date.now(), tokenUsage: 0, parentId: 'p' });
42
+ store.recordEdge({ workflowId: 'wf-1', parentId: 'p', childId: 'c' });
43
+
44
+ const edges = store.getEdgesByWorkflow('wf-1');
45
+ expect(edges).toHaveLength(1);
46
+ expect(edges[0].parentId).toBe('p');
47
+ expect(edges[0].childId).toBe('c');
48
+ });
49
+
50
+ it('retrieves full snapshot for a workflow', () => {
51
+ tmpDir = mkdtempSync(join(tmpdir(), 'cg-'));
52
+ store = new CallgraphStore(join(tmpDir, 'callgraph.db'));
53
+
54
+ store.recordNode({ id: 'root', workflowId: 'wf-2', name: 'root', depth: 0, status: 'completed', startedAt: 1000, tokenUsage: 500 });
55
+ store.recordNode({ id: 'w1', workflowId: 'wf-2', name: 'worker', depth: 1, status: 'completed', startedAt: 2000, tokenUsage: 300, parentId: 'root' });
56
+ store.recordEdge({ workflowId: 'wf-2', parentId: 'root', childId: 'w1' });
57
+
58
+ const snapshot = store.getSnapshot('wf-2');
59
+ expect(snapshot.nodes).toHaveLength(2);
60
+ expect(snapshot.edges).toHaveLength(1);
61
+ expect(snapshot.totalTokenUsage).toBe(800);
62
+ });
63
+
64
+ it('lists workflows with node counts', () => {
65
+ tmpDir = mkdtempSync(join(tmpdir(), 'cg-'));
66
+ store = new CallgraphStore(join(tmpDir, 'callgraph.db'));
67
+
68
+ store.recordNode({ id: 'a', workflowId: 'wf-1', name: 'a', depth: 0, status: 'completed', startedAt: 1000, tokenUsage: 0 });
69
+ store.recordNode({ id: 'b', workflowId: 'wf-1', name: 'b', depth: 1, status: 'completed', startedAt: 2000, tokenUsage: 0, parentId: 'a' });
70
+ store.recordNode({ id: 'c', workflowId: 'wf-2', name: 'c', depth: 0, status: 'running', startedAt: 3000, tokenUsage: 0 });
71
+
72
+ const workflows = store.listWorkflows();
73
+ expect(workflows).toHaveLength(2);
74
+ const wf1 = workflows.find((w) => w.workflowId === 'wf-1');
75
+ expect(wf1?.nodeCount).toBe(2);
76
+ });
77
+ });
@@ -0,0 +1,90 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { CallgraphTracker } from '../src/tracker.js';
3
+ import type { AgentNode } from '../src/types.js';
4
+
5
+ describe('CallgraphTracker', () => {
6
+ it('tracks root agent with no parent', () => {
7
+ const tracker = new CallgraphTracker({ maxDepth: 10 });
8
+ tracker.addAgent({ id: 'root', name: 'orchestrator', startedAt: Date.now() });
9
+
10
+ const nodes = tracker.getNodes();
11
+ expect(nodes).toHaveLength(1);
12
+ expect(nodes[0].id).toBe('root');
13
+ expect(nodes[0].depth).toBe(0);
14
+ });
15
+
16
+ it('tracks parent-child edges', () => {
17
+ const tracker = new CallgraphTracker({ maxDepth: 10 });
18
+ tracker.addAgent({ id: 'root', name: 'supervisor', startedAt: Date.now() });
19
+ tracker.addAgent({ id: 'worker-1', name: 'coder', startedAt: Date.now(), parentId: 'root' });
20
+ tracker.addAgent({ id: 'worker-2', name: 'reviewer', startedAt: Date.now(), parentId: 'root' });
21
+
22
+ const edges = tracker.getEdges();
23
+ expect(edges).toHaveLength(2);
24
+ expect(edges[0]).toEqual({ parentId: 'root', childId: 'worker-1' });
25
+ expect(edges[1]).toEqual({ parentId: 'root', childId: 'worker-2' });
26
+
27
+ const children = tracker.getChildren('root');
28
+ expect(children.map((c) => c.id)).toEqual(['worker-1', 'worker-2']);
29
+ });
30
+
31
+ it('computes depth correctly for nested agents', () => {
32
+ const tracker = new CallgraphTracker({ maxDepth: 10 });
33
+ tracker.addAgent({ id: 'a', name: 'root', startedAt: Date.now() });
34
+ tracker.addAgent({ id: 'b', name: 'mid', startedAt: Date.now(), parentId: 'a' });
35
+ tracker.addAgent({ id: 'c', name: 'leaf', startedAt: Date.now(), parentId: 'b' });
36
+
37
+ const leaf = tracker.getNode('c');
38
+ expect(leaf?.depth).toBe(2);
39
+ expect(tracker.getMaxDepth()).toBe(2);
40
+ });
41
+
42
+ it('rejects agents exceeding max depth', () => {
43
+ const tracker = new CallgraphTracker({ maxDepth: 2 });
44
+ tracker.addAgent({ id: 'a', name: 'root', startedAt: Date.now() });
45
+ tracker.addAgent({ id: 'b', name: 'mid', startedAt: Date.now(), parentId: 'a' });
46
+ tracker.addAgent({ id: 'c', name: 'leaf', startedAt: Date.now(), parentId: 'b' });
47
+
48
+ expect(() =>
49
+ tracker.addAgent({ id: 'd', name: 'too-deep', startedAt: Date.now(), parentId: 'c' }),
50
+ ).toThrow('depth limit');
51
+ });
52
+
53
+ it('updates agent status and token usage', () => {
54
+ const tracker = new CallgraphTracker({ maxDepth: 10 });
55
+ tracker.addAgent({ id: 'a', name: 'worker', startedAt: Date.now() });
56
+ tracker.updateAgent('a', { status: 'completed', tokenUsage: 1500, completedAt: Date.now() });
57
+
58
+ const node = tracker.getNode('a');
59
+ expect(node?.status).toBe('completed');
60
+ expect(node?.tokenUsage).toBe(1500);
61
+ });
62
+
63
+ it('returns topological order', () => {
64
+ const tracker = new CallgraphTracker({ maxDepth: 10 });
65
+ tracker.addAgent({ id: 'root', name: 'root', startedAt: Date.now() });
66
+ tracker.addAgent({ id: 'child-1', name: 'c1', startedAt: Date.now(), parentId: 'root' });
67
+ tracker.addAgent({ id: 'child-2', name: 'c2', startedAt: Date.now(), parentId: 'root' });
68
+ tracker.addAgent({ id: 'grandchild', name: 'gc', startedAt: Date.now(), parentId: 'child-1' });
69
+
70
+ const order = tracker.topologicalOrder();
71
+ const rootIdx = order.indexOf('root');
72
+ const c1Idx = order.indexOf('child-1');
73
+ const gcIdx = order.indexOf('grandchild');
74
+ expect(rootIdx).toBeLessThan(c1Idx);
75
+ expect(c1Idx).toBeLessThan(gcIdx);
76
+ });
77
+
78
+ it('computes aggregate token usage for subtree', () => {
79
+ const tracker = new CallgraphTracker({ maxDepth: 10 });
80
+ tracker.addAgent({ id: 'root', name: 'root', startedAt: Date.now() });
81
+ tracker.addAgent({ id: 'c1', name: 'c1', startedAt: Date.now(), parentId: 'root' });
82
+ tracker.addAgent({ id: 'c2', name: 'c2', startedAt: Date.now(), parentId: 'root' });
83
+ tracker.updateAgent('root', { tokenUsage: 100 });
84
+ tracker.updateAgent('c1', { tokenUsage: 200 });
85
+ tracker.updateAgent('c2', { tokenUsage: 300 });
86
+
87
+ expect(tracker.getSubtreeTokenUsage('root')).toBe(600);
88
+ expect(tracker.getSubtreeTokenUsage('c1')).toBe(200);
89
+ });
90
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,8 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "rootDir": "src",
5
+ "outDir": "dist"
6
+ },
7
+ "include": ["src"]
8
+ }