@datasynx/agentic-ai-cartography 0.2.6 → 0.3.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.
package/dist/index.d.ts CHANGED
@@ -5,8 +5,6 @@ declare const NODE_TYPES: readonly ["host", "database_server", "database", "tabl
5
5
  type NodeType = typeof NODE_TYPES[number];
6
6
  declare const EDGE_RELATIONSHIPS: readonly ["connects_to", "reads_from", "writes_to", "calls", "contains", "depends_on"];
7
7
  type EdgeRelationship = typeof EDGE_RELATIONSHIPS[number];
8
- declare const EVENT_TYPES: readonly ["process_start", "process_end", "connection_open", "connection_close", "window_focus", "tool_switch"];
9
- type EventType = typeof EVENT_TYPES[number];
10
8
  declare const NodeSchema: z.ZodObject<{
11
9
  id: z.ZodString;
12
10
  type: z.ZodEnum<["host", "database_server", "database", "table", "web_service", "api_endpoint", "cache_server", "message_broker", "queue", "topic", "container", "pod", "k8s_cluster", "config_file", "saas_tool", "unknown"]>;
@@ -53,32 +51,6 @@ declare const EdgeSchema: z.ZodObject<{
53
51
  confidence?: number | undefined;
54
52
  }>;
55
53
  type DiscoveryEdge = z.infer<typeof EdgeSchema>;
56
- declare const EventSchema: z.ZodObject<{
57
- eventType: z.ZodEnum<["process_start", "process_end", "connection_open", "connection_close", "window_focus", "tool_switch"]>;
58
- process: z.ZodString;
59
- pid: z.ZodNumber;
60
- target: z.ZodOptional<z.ZodString>;
61
- targetType: z.ZodOptional<z.ZodEnum<["host", "database_server", "database", "table", "web_service", "api_endpoint", "cache_server", "message_broker", "queue", "topic", "container", "pod", "k8s_cluster", "config_file", "saas_tool", "unknown"]>>;
62
- protocol: z.ZodOptional<z.ZodString>;
63
- port: z.ZodOptional<z.ZodNumber>;
64
- }, "strip", z.ZodTypeAny, {
65
- eventType: "process_start" | "process_end" | "connection_open" | "connection_close" | "window_focus" | "tool_switch";
66
- process: string;
67
- pid: number;
68
- target?: string | undefined;
69
- targetType?: "host" | "database_server" | "database" | "table" | "web_service" | "api_endpoint" | "cache_server" | "message_broker" | "queue" | "topic" | "container" | "pod" | "k8s_cluster" | "config_file" | "saas_tool" | "unknown" | undefined;
70
- protocol?: string | undefined;
71
- port?: number | undefined;
72
- }, {
73
- eventType: "process_start" | "process_end" | "connection_open" | "connection_close" | "window_focus" | "tool_switch";
74
- process: string;
75
- pid: number;
76
- target?: string | undefined;
77
- targetType?: "host" | "database_server" | "database" | "table" | "web_service" | "api_endpoint" | "cache_server" | "message_broker" | "queue" | "topic" | "container" | "pod" | "k8s_cluster" | "config_file" | "saas_tool" | "unknown" | undefined;
78
- protocol?: string | undefined;
79
- port?: number | undefined;
80
- }>;
81
- type ActivityEvent = z.infer<typeof EventSchema>;
82
54
  declare const SOPStepSchema: z.ZodObject<{
83
55
  order: z.ZodNumber;
84
56
  instruction: z.ZodString;
@@ -167,16 +139,35 @@ interface EdgeRow extends DiscoveryEdge {
167
139
  discoveredAt: string;
168
140
  pathId?: string;
169
141
  }
142
+ interface SessionRow {
143
+ id: string;
144
+ mode: 'discover';
145
+ startedAt: string;
146
+ completedAt?: string;
147
+ config: string;
148
+ }
149
+ interface CartographyConfig {
150
+ maxDepth: number;
151
+ maxTurns: number;
152
+ entryPoints: string[];
153
+ agentModel: string;
154
+ organization?: string;
155
+ outputDir: string;
156
+ dbPath: string;
157
+ verbose: boolean;
158
+ }
159
+ declare function defaultConfig(overrides?: Partial<CartographyConfig>): CartographyConfig;
160
+
170
161
  interface EventRow {
171
162
  id: string;
172
163
  sessionId: string;
173
164
  taskId?: string;
174
165
  timestamp: string;
175
- eventType: EventType;
166
+ eventType: string;
176
167
  process: string;
177
168
  pid: number;
178
169
  target?: string;
179
- targetType?: NodeType;
170
+ targetType?: string;
180
171
  port?: number;
181
172
  durationMs?: number;
182
173
  }
@@ -203,94 +194,12 @@ interface WorkflowRow {
203
194
  avgDurationMs: number;
204
195
  involvedServices: string;
205
196
  }
206
- interface SessionRow {
207
- id: string;
208
- mode: 'discover' | 'shadow';
209
- startedAt: string;
210
- completedAt?: string;
211
- config: string;
212
- }
213
- type DaemonMessage = {
214
- type: 'event';
215
- data: EventRow;
216
- } | {
217
- type: 'prompt';
218
- id: string;
219
- prompt: PendingPrompt;
220
- } | {
221
- type: 'status';
222
- data: ShadowStatus;
223
- } | {
224
- type: 'agent-output';
225
- text: string;
226
- } | {
227
- type: 'info';
228
- message: string;
229
- };
230
- type ClientMessage = {
231
- type: 'prompt-response';
232
- id: string;
233
- answer: string;
234
- } | {
235
- type: 'command';
236
- command: 'new-task' | 'end-task' | 'status' | 'stop' | 'pause' | 'resume';
237
- } | {
238
- type: 'task-description';
239
- description: string;
240
- };
241
- interface PendingPrompt {
242
- kind: 'node-approval' | 'task-boundary' | 'task-end';
243
- context: Record<string, unknown>;
244
- options: string[];
245
- defaultAnswer: string;
246
- timeoutMs: number;
247
- createdAt: string;
248
- }
249
- interface ShadowStatus {
250
- pid: number;
251
- uptime: number;
252
- nodeCount: number;
253
- eventCount: number;
254
- taskCount: number;
255
- sopCount: number;
256
- pendingPrompts: number;
257
- autoSave: boolean;
258
- mode: 'foreground' | 'daemon';
259
- agentActive: boolean;
260
- paused: boolean;
261
- cyclesRun: number;
262
- cyclesSkipped: number;
263
- }
264
- declare const MIN_POLL_INTERVAL_MS = 15000;
265
- interface CartographyConfig {
266
- mode: 'discover' | 'shadow';
267
- maxDepth: number;
268
- maxTurns: number;
269
- entryPoints: string[];
270
- agentModel: string;
271
- shadowMode: 'foreground' | 'daemon';
272
- pollIntervalMs: number;
273
- inactivityTimeoutMs: number;
274
- promptTimeoutMs: number;
275
- trackWindowFocus: boolean;
276
- autoSaveNodes: boolean;
277
- enableNotifications: boolean;
278
- shadowModel: string;
279
- organization?: string;
280
- outputDir: string;
281
- dbPath: string;
282
- socketPath: string;
283
- pidFile: string;
284
- verbose: boolean;
285
- }
286
- declare function defaultConfig(overrides?: Partial<CartographyConfig>): CartographyConfig;
287
-
288
197
  declare class CartographyDB {
289
198
  private db;
290
199
  constructor(dbPath: string);
291
200
  private migrate;
292
201
  close(): void;
293
- createSession(mode: 'discover' | 'shadow', config: CartographyConfig): string;
202
+ createSession(mode: 'discover', config: CartographyConfig): string;
294
203
  endSession(id: string): void;
295
204
  getSession(id: string): SessionRow | undefined;
296
205
  getLatestSession(mode?: string): SessionRow | undefined;
@@ -301,7 +210,7 @@ declare class CartographyDB {
301
210
  deleteNode(sessionId: string, nodeId: string): void;
302
211
  insertEdge(sessionId: string, edge: DiscoveryEdge): void;
303
212
  getEdges(sessionId: string): EdgeRow[];
304
- insertEvent(sessionId: string, event: ActivityEvent, taskId?: string): void;
213
+ insertEvent(sessionId: string, event: Pick<EventRow, 'eventType' | 'process' | 'pid' | 'target' | 'targetType' | 'port'>, taskId?: string): void;
305
214
  getEvents(sessionId: string, since?: string): EventRow[];
306
215
  startTask(sessionId: string, description?: string): string;
307
216
  endCurrentTask(sessionId: string): void;
@@ -363,8 +272,6 @@ type DiscoveryEvent = {
363
272
  };
364
273
  type AskUserFn = (question: string, context?: string) => Promise<string>;
365
274
  declare function runDiscovery(config: CartographyConfig, db: CartographyDB, sessionId: string, onEvent?: (event: DiscoveryEvent) => void, onAskUser?: AskUserFn, hint?: string): Promise<void>;
366
- declare function runShadowCycle(config: CartographyConfig, db: CartographyDB, sessionId: string, prevSnapshot: string, currSnapshot: string, onOutput?: (msg: unknown) => void): Promise<void>;
367
- declare function generateSOPs(db: CartographyDB, sessionId: string): Promise<number>;
368
275
 
369
276
  declare function generateTopologyMermaid(nodes: NodeRow[], edges: EdgeRow[]): string;
370
277
  declare function generateDependencyMermaid(nodes: NodeRow[], edges: EdgeRow[]): string;
@@ -381,6 +288,5 @@ declare function exportSOPDashboard(sops: Array<SOP & {
381
288
  declare function exportAll(db: CartographyDB, sessionId: string, outputDir: string, formats?: string[]): void;
382
289
 
383
290
  declare function checkPrerequisites(): void;
384
- declare function checkPollInterval(intervalMs: number): number;
385
291
 
386
- export { type ActivityEvent, type CartographyConfig, CartographyDB, type ClientMessage, type DaemonMessage, type DiscoveryEdge, type DiscoveryEvent, type DiscoveryNode, EDGE_RELATIONSHIPS, EVENT_TYPES, type EdgeRelationship, type EdgeRow, EdgeSchema, type EventRow, EventSchema, type EventType, MIN_POLL_INTERVAL_MS, NODE_TYPES, type NodeRow, NodeSchema, type NodeType, type PendingPrompt, type SOP, SOPSchema, type SOPStep, SOPStepSchema, type SessionRow, type ShadowStatus, type TaskRow, type WorkflowRow, checkPollInterval, checkPrerequisites, createCartographyTools, CartographyDB as default, defaultConfig, exportAll, exportBackstageYAML, exportHTML, exportJSON, exportSOPDashboard, exportSOPMarkdown, generateDependencyMermaid, generateSOPs, generateTopologyMermaid, generateWorkflowMermaid, runDiscovery, runShadowCycle, safetyHook, stripSensitive };
292
+ export { type CartographyConfig, CartographyDB, type DiscoveryEdge, type DiscoveryEvent, type DiscoveryNode, EDGE_RELATIONSHIPS, type EdgeRelationship, type EdgeRow, EdgeSchema, NODE_TYPES, type NodeRow, NodeSchema, type NodeType, type SOP, SOPSchema, type SOPStep, SOPStepSchema, type SessionRow, checkPrerequisites, createCartographyTools, CartographyDB as default, defaultConfig, exportAll, exportBackstageYAML, exportHTML, exportJSON, exportSOPDashboard, exportSOPMarkdown, generateDependencyMermaid, generateTopologyMermaid, generateWorkflowMermaid, runDiscovery, safetyHook, stripSensitive };
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ PRAGMA busy_timeout = 5000;
9
9
 
10
10
  CREATE TABLE IF NOT EXISTS sessions (
11
11
  id TEXT PRIMARY KEY,
12
- mode TEXT NOT NULL CHECK (mode IN ('discover','shadow')),
12
+ mode TEXT NOT NULL CHECK (mode IN ('discover')),
13
13
  started_at TEXT NOT NULL,
14
14
  completed_at TEXT,
15
15
  config TEXT NOT NULL DEFAULT '{}'
@@ -454,14 +454,6 @@ var EDGE_RELATIONSHIPS = [
454
454
  "contains",
455
455
  "depends_on"
456
456
  ];
457
- var EVENT_TYPES = [
458
- "process_start",
459
- "process_end",
460
- "connection_open",
461
- "connection_close",
462
- "window_focus",
463
- "tool_switch"
464
- ];
465
457
  var NodeSchema = z.object({
466
458
  id: z.string().describe('Format: "{type}:{host}:{port}" oder "{type}:{name}"'),
467
459
  type: z.enum(NODE_TYPES),
@@ -478,15 +470,6 @@ var EdgeSchema = z.object({
478
470
  evidence: z.string(),
479
471
  confidence: z.number().min(0).max(1).default(0.5)
480
472
  });
481
- var EventSchema = z.object({
482
- eventType: z.enum(EVENT_TYPES),
483
- process: z.string(),
484
- pid: z.number(),
485
- target: z.string().optional(),
486
- targetType: z.enum(NODE_TYPES).optional(),
487
- protocol: z.string().optional(),
488
- port: z.number().optional()
489
- });
490
473
  var SOPStepSchema = z.object({
491
474
  order: z.number(),
492
475
  instruction: z.string(),
@@ -503,27 +486,15 @@ var SOPSchema = z.object({
503
486
  frequency: z.string(),
504
487
  confidence: z.number().min(0).max(1)
505
488
  });
506
- var MIN_POLL_INTERVAL_MS = 15e3;
507
489
  function defaultConfig(overrides = {}) {
508
490
  const home = process.env.HOME ?? process.env.USERPROFILE ?? "/tmp";
509
491
  return {
510
- mode: "discover",
511
492
  maxDepth: 8,
512
493
  maxTurns: 50,
513
494
  entryPoints: ["localhost"],
514
495
  agentModel: "claude-sonnet-4-5-20250929",
515
- shadowMode: "daemon",
516
- pollIntervalMs: 3e4,
517
- inactivityTimeoutMs: 3e5,
518
- promptTimeoutMs: 6e4,
519
- trackWindowFocus: false,
520
- autoSaveNodes: false,
521
- enableNotifications: true,
522
- shadowModel: "claude-haiku-4-5-20251001",
523
496
  outputDir: "./cartography-output",
524
497
  dbPath: `${home}/.cartography/cartography.db`,
525
- socketPath: `${home}/.cartography/daemon.sock`,
526
- pidFile: `${home}/.cartography/daemon.pid`,
527
498
  verbose: false,
528
499
  ...overrides
529
500
  };
@@ -829,24 +800,6 @@ async function createCartographyTools(db, sessionId, opts = {}) {
829
800
  });
830
801
  return { content: [{ type: "text", text: `\u2713 ${args["sourceId"]}\u2192${args["targetId"]}` }] };
831
802
  }),
832
- tool("save_event", "Save an activity event (process/connection observed)", {
833
- eventType: z2.enum(EVENT_TYPES),
834
- process: z2.string(),
835
- pid: z2.number(),
836
- target: z2.string().optional(),
837
- targetType: z2.enum(NODE_TYPES).optional(),
838
- port: z2.number().optional()
839
- }, async (args) => {
840
- db.insertEvent(sessionId, {
841
- eventType: args["eventType"],
842
- process: args["process"],
843
- pid: args["pid"],
844
- target: args["target"] ? stripSensitive(args["target"]) : void 0,
845
- targetType: args["targetType"],
846
- port: args["port"]
847
- });
848
- return { content: [{ type: "text", text: `\u2713 ${args["eventType"]}` }] };
849
- }),
850
803
  tool("get_catalog", "Get the current catalog \u2014 use before save_node to avoid duplicates", {
851
804
  includeEdges: z2.boolean().default(true)
852
805
  }, async (args) => {
@@ -862,22 +815,6 @@ async function createCartographyTools(db, sessionId, opts = {}) {
862
815
  }]
863
816
  };
864
817
  }),
865
- tool("manage_task", "Start, end or describe a workflow task", {
866
- action: z2.enum(["start", "end", "describe"]),
867
- description: z2.string().optional()
868
- }, async (args) => {
869
- const action = args["action"];
870
- if (action === "start") {
871
- const id = db.startTask(sessionId, args["description"]);
872
- return { content: [{ type: "text", text: `\u2713 Task started: ${id}` }] };
873
- }
874
- if (action === "end") {
875
- db.endCurrentTask(sessionId);
876
- return { content: [{ type: "text", text: "\u2713 Task ended" }] };
877
- }
878
- db.updateTaskDescription(sessionId, args["description"]);
879
- return { content: [{ type: "text", text: "\u2713 Description updated" }] };
880
- }),
881
818
  tool("ask_user", "Ask the user a question \u2014 for clarifications, missing context, or consent (e.g. before scanning browser history)", {
882
819
  question: z2.string().describe("The question for the user (clear and specific)"),
883
820
  context: z2.string().optional().describe("Optional context explaining why this is relevant")
@@ -1470,109 +1407,6 @@ Use ask_user when you need context from the user.`;
1470
1407
  }
1471
1408
  }
1472
1409
  }
1473
- async function runShadowCycle(config, db, sessionId, prevSnapshot, currSnapshot, onOutput) {
1474
- const { query } = await import("@anthropic-ai/claude-code");
1475
- const tools = await createCartographyTools(db, sessionId);
1476
- const prompt = `Analyze the diff between these two system snapshots.
1477
- Find:
1478
- - New/closed TCP connections \u2192 save_event
1479
- - New/terminated processes \u2192 save_event
1480
- - Previously unknown services \u2192 check get_catalog, then save_node
1481
- - Task boundaries (inactivity, tool switches) \u2192 manage_task
1482
- target = host:port ONLY. Be concise and efficient.
1483
-
1484
- === BEFORE ===
1485
- ${prevSnapshot}
1486
-
1487
- === NOW ===
1488
- ${currSnapshot}`;
1489
- for await (const msg of query({
1490
- prompt,
1491
- options: {
1492
- model: config.shadowModel,
1493
- maxTurns: 5,
1494
- mcpServers: { cartography: tools },
1495
- allowedTools: [
1496
- "mcp__cartograph__save_event",
1497
- "mcp__cartograph__save_node",
1498
- "mcp__cartograph__save_edge",
1499
- "mcp__cartograph__get_catalog",
1500
- "mcp__cartograph__manage_task"
1501
- ],
1502
- permissionMode: "bypassPermissions"
1503
- }
1504
- })) {
1505
- if (onOutput) onOutput(msg);
1506
- }
1507
- }
1508
- async function generateSOPs(db, sessionId) {
1509
- const Anthropic = (await import("@anthropic-ai/sdk")).default;
1510
- const client = new Anthropic();
1511
- const tasks = db.getTasks(sessionId).filter((t) => t.status === "completed");
1512
- if (tasks.length === 0) return 0;
1513
- const clusters = clusterTasks(tasks);
1514
- let generated = 0;
1515
- for (const cluster of clusters) {
1516
- const workflowId = crypto.randomUUID();
1517
- const involved = JSON.parse(cluster[0]?.involvedServices ?? "[]");
1518
- const taskDescriptions = cluster.map((t, i) => `Task ${i + 1}: ${t.description ?? "Unnamed"}
1519
- Steps: ${t.steps}`).join("\n\n");
1520
- const response = await client.messages.create({
1521
- model: "claude-sonnet-4-5-20250929",
1522
- max_tokens: 2048,
1523
- messages: [{
1524
- role: "user",
1525
- content: `Generate a Standard Operating Procedure (SOP) for this recurring workflow.
1526
- Reply ONLY with valid JSON in this format:
1527
- {
1528
- "title": "...",
1529
- "description": "...",
1530
- "steps": [{"order": 1, "instruction": "...", "tool": "...", "target": "...", "notes": "..."}],
1531
- "involvedSystems": ["..."],
1532
- "estimatedDuration": "~N minutes",
1533
- "frequency": "X times daily",
1534
- "confidence": 0.8
1535
- }
1536
-
1537
- Tasks:
1538
- ${taskDescriptions}
1539
-
1540
- Involved services: ${involved.join(", ")}`
1541
- }]
1542
- });
1543
- const text = response.content[0]?.type === "text" ? response.content[0].text : "";
1544
- try {
1545
- const jsonMatch = text.match(/\{[\s\S]*\}/);
1546
- if (!jsonMatch) continue;
1547
- const parsed = JSON.parse(jsonMatch[0]);
1548
- db.insertSOP({ workflowId, ...parsed });
1549
- generated++;
1550
- } catch {
1551
- }
1552
- }
1553
- return generated;
1554
- }
1555
- function clusterTasks(tasks) {
1556
- const clusters = [];
1557
- const assigned = /* @__PURE__ */ new Set();
1558
- for (const task of tasks) {
1559
- if (assigned.has(task.id)) continue;
1560
- const cluster = [task];
1561
- assigned.add(task.id);
1562
- const taskServices = new Set(JSON.parse(task.involvedServices ?? "[]"));
1563
- for (const other of tasks) {
1564
- if (assigned.has(other.id)) continue;
1565
- const otherServices = new Set(JSON.parse(other.involvedServices ?? "[]"));
1566
- const overlap = [...taskServices].filter((s) => otherServices.has(s));
1567
- if (overlap.length > 0) {
1568
- cluster.push(other);
1569
- assigned.add(other.id);
1570
- }
1571
- }
1572
- clusters.push(cluster);
1573
- }
1574
- return clusters;
1575
- }
1576
1410
 
1577
1411
  // src/exporter.ts
1578
1412
  import { mkdirSync as mkdirSync2, writeFileSync } from "fs";
@@ -2428,7 +2262,7 @@ function exportSOPDashboard(sops) {
2428
2262
  <body>
2429
2263
  <div class="header">
2430
2264
  <h1>SOP Dashboard</h1>
2431
- <div class="subtitle">Datasynx Cartography \u2014 Standard Operating Procedures</div>
2265
+ <div class="subtitle">Cartography \u2014 Standard Operating Procedures</div>
2432
2266
  <div class="stats-row">
2433
2267
  <div class="stat-card"><div class="value" id="sop-count">0</div><div class="label">SOPs</div></div>
2434
2268
  <div class="stat-card"><div class="value" id="step-count">0</div><div class="label">Total Steps</div></div>
@@ -2465,7 +2299,7 @@ systems.forEach(([name, count]) => {
2465
2299
 
2466
2300
  const listDiv = document.getElementById('sop-list');
2467
2301
  if (sops.length === 0) {
2468
- listDiv.innerHTML = '<div class="empty">No SOPs found. Start the shadow daemon and observe workflows.</div>';
2302
+ listDiv.innerHTML = '<div class="empty">No SOPs found. Run a discovery session first.</div>';
2469
2303
  }
2470
2304
 
2471
2305
  sops.forEach((sop, i) => {
@@ -2585,20 +2419,8 @@ function checkPrerequisites() {
2585
2419
  process.stderr.write("\u2713 Eingeloggt via claude login (Subscription)\n");
2586
2420
  }
2587
2421
  }
2588
- function checkPollInterval(intervalMs) {
2589
- if (intervalMs < MIN_POLL_INTERVAL_MS) {
2590
- process.stderr.write(
2591
- `\u26A0 Minimum Shadow-Intervall: ${MIN_POLL_INTERVAL_MS / 1e3} Sekunden (Agent SDK Overhead)
2592
- `
2593
- );
2594
- return MIN_POLL_INTERVAL_MS;
2595
- }
2596
- return intervalMs;
2597
- }
2598
2422
  export {
2599
2423
  CartographyDB,
2600
- MIN_POLL_INTERVAL_MS,
2601
- checkPollInterval,
2602
2424
  checkPrerequisites,
2603
2425
  createCartographyTools,
2604
2426
  CartographyDB as default,
@@ -2610,11 +2432,9 @@ export {
2610
2432
  exportSOPDashboard,
2611
2433
  exportSOPMarkdown,
2612
2434
  generateDependencyMermaid,
2613
- generateSOPs,
2614
2435
  generateTopologyMermaid,
2615
2436
  generateWorkflowMermaid,
2616
2437
  runDiscovery,
2617
- runShadowCycle,
2618
2438
  safetyHook,
2619
2439
  stripSensitive
2620
2440
  };