@dimassetoid/septum-mcp 0.3.0 → 0.5.1

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.
Files changed (129) hide show
  1. package/README.md +38 -55
  2. package/package.json +7 -5
  3. package/src/cli/commands/check.ts +14 -10
  4. package/src/cli/commands/hook.ts +41 -6
  5. package/src/cli/commands/init.ts +10 -1
  6. package/src/cli/commands/stats.ts +33 -0
  7. package/src/cli/commands/sync-progress.ts +71 -0
  8. package/src/cli/commands/sync.ts +32 -4
  9. package/src/cli/index.ts +7 -0
  10. package/src/cli/templates/hooks.ts +3 -14
  11. package/src/cli/templates/skill.ts +17 -10
  12. package/src/core/boundary/audit.ts +383 -0
  13. package/src/core/boundary/evaluator.ts +251 -114
  14. package/src/core/boundary/staged-auditor.ts +147 -55
  15. package/src/core/config/domain-ownership.ts +6 -4
  16. package/src/core/config/domain-registration.ts +141 -0
  17. package/src/core/config/loader.ts +1 -25
  18. package/src/core/config/schema.ts +24 -36
  19. package/src/core/database/client.ts +2 -0
  20. package/src/core/database/repositories/dependency.repository.ts +334 -572
  21. package/src/core/database/repositories/domain.repository.ts +2 -1
  22. package/src/core/database/repositories/file.repository.ts +10 -0
  23. package/src/core/database/repositories/symbol.repository.ts +97 -398
  24. package/src/core/database/repository.ts +68 -9
  25. package/src/core/database/schema.ts +26 -0
  26. package/src/core/discovery/declarative-routes.ts +69 -0
  27. package/src/core/discovery/framework-detector.ts +149 -0
  28. package/src/core/discovery/navigation.ts +222 -58
  29. package/src/core/discovery/topology-detector.ts +93 -168
  30. package/src/core/errors.ts +19 -0
  31. package/src/core/ingestion/pipeline.ts +287 -88
  32. package/src/core/parser/extractors/base.ts +11 -3
  33. package/src/core/parser/extractors/csharp.ts +2 -2
  34. package/src/core/parser/extractors/django-routing.ts +163 -0
  35. package/src/core/parser/extractors/django-semantic.ts +397 -481
  36. package/src/core/parser/extractors/elysia-semantic.ts +172 -475
  37. package/src/core/parser/extractors/express-semantic.ts +195 -383
  38. package/src/core/parser/extractors/fastapi-semantic.ts +178 -361
  39. package/src/core/parser/extractors/fastify-semantic.ts +216 -717
  40. package/src/core/parser/extractors/flask-semantic.ts +89 -352
  41. package/src/core/parser/extractors/go-routing.ts +344 -0
  42. package/src/core/parser/extractors/go-semantic.ts +205 -562
  43. package/src/core/parser/extractors/go.ts +6 -3
  44. package/src/core/parser/extractors/graphql-entrypoint.ts +146 -0
  45. package/src/core/parser/extractors/hono-semantic.ts +132 -509
  46. package/src/core/parser/extractors/java.ts +2 -2
  47. package/src/core/parser/extractors/laravel-routing.ts +263 -0
  48. package/src/core/parser/extractors/laravel-semantic.ts +143 -335
  49. package/src/core/parser/extractors/manifest-helpers.ts +64 -0
  50. package/src/core/parser/extractors/mcp-cli-dispatch.ts +268 -0
  51. package/src/core/parser/extractors/mcp-cli-semantic.ts +82 -333
  52. package/src/core/parser/extractors/nestjs-semantic.ts +238 -494
  53. package/src/core/parser/extractors/nextjs-semantic.ts +164 -0
  54. package/src/core/parser/extractors/php-ast-helpers.ts +51 -0
  55. package/src/core/parser/extractors/php.ts +1 -1
  56. package/src/core/parser/extractors/python-route-ast.ts +249 -0
  57. package/src/core/parser/extractors/python.ts +5 -9
  58. package/src/core/parser/extractors/registry.ts +2 -0
  59. package/src/core/parser/extractors/route-prefixes.ts +43 -0
  60. package/src/core/parser/extractors/ruby.ts +2 -2
  61. package/src/core/parser/extractors/rust.ts +4 -4
  62. package/src/core/parser/extractors/symfony-routing.ts +114 -0
  63. package/src/core/parser/extractors/symfony-semantic.ts +72 -226
  64. package/src/core/parser/extractors/typescript-bindings.ts +333 -0
  65. package/src/core/parser/extractors/typescript-compiler-fallback.ts +380 -0
  66. package/src/core/parser/extractors/typescript-fallback.ts +207 -0
  67. package/src/core/parser/extractors/typescript-route-context.ts +58 -0
  68. package/src/core/parser/extractors/typescript.ts +23 -216
  69. package/src/core/parser/language-capabilities.ts +1 -1
  70. package/src/core/parser/schema/providers/laravel-migration-provider.ts +4 -1
  71. package/src/core/parser/wasm-loader.ts +6 -2
  72. package/src/core/resolver/ast-method-tracer.ts +230 -0
  73. package/src/core/resolver/call-graph-helpers.ts +72 -0
  74. package/src/core/resolver/call-graph-tracer.ts +169 -414
  75. package/src/core/resolver/dependency-analysis.ts +593 -0
  76. package/src/core/resolver/import-candidates.ts +120 -0
  77. package/src/core/resolver/import-evidence.ts +88 -0
  78. package/src/core/resolver/import-resolver.ts +60 -7
  79. package/src/core/resolver/interpretation-inputs.ts +60 -2
  80. package/src/core/resolver/languages/python.ts +31 -13
  81. package/src/core/resolver/languages/shared.ts +4 -1
  82. package/src/core/resolver/module-resolver.ts +10 -3
  83. package/src/core/resolver/path-resolver.ts +6 -3
  84. package/src/core/resolver/polyglot-slice-tracer.ts +197 -0
  85. package/src/core/resolver/slice-catalog.ts +21 -6
  86. package/src/core/resolver/slice-format.ts +13 -0
  87. package/src/core/resolver/slice-selection.ts +237 -0
  88. package/src/core/resolver/symbol-impact.ts +104 -8
  89. package/src/core/resolver/symbol-locator.ts +82 -15
  90. package/src/core/resolver/vertical-slice-tracer.ts +31 -230
  91. package/src/core/resources/ignore.ts +0 -1
  92. package/src/core/resources/limits.ts +2 -1
  93. package/src/core/resources/work-queue.ts +167 -4
  94. package/src/core/retrieval/context-page.ts +11 -4
  95. package/src/core/retrieval/context.ts +363 -226
  96. package/src/{mcp/tools/get-symbol.ts → core/retrieval/source-context.ts} +145 -96
  97. package/src/core/retrieval/symbol-details.ts +453 -0
  98. package/src/core/retrieval/symbol-evidence.ts +3 -3
  99. package/src/core/retrieval/typescript-references.ts +38 -7
  100. package/src/core/retrieval/universal-context.ts +182 -0
  101. package/src/core/telemetry/summary.ts +114 -0
  102. package/src/core/telemetry/telemetry.ts +192 -49
  103. package/src/mcp/formatters/compact-text.ts +439 -0
  104. package/src/mcp/resources-and-prompts.ts +255 -0
  105. package/src/mcp/schemas/boundary.ts +145 -0
  106. package/src/mcp/schemas/map.ts +250 -0
  107. package/src/mcp/schemas/shared.ts +52 -0
  108. package/src/mcp/schemas/slice.ts +60 -0
  109. package/src/mcp/schemas/symbol.ts +268 -0
  110. package/src/mcp/schemas.ts +5 -746
  111. package/src/mcp/server.ts +269 -429
  112. package/src/mcp/tool-catalog.ts +331 -0
  113. package/src/mcp/tools/boundary.ts +68 -3
  114. package/src/mcp/tools/map.ts +104 -4
  115. package/src/mcp/tools/slice.ts +101 -3
  116. package/src/mcp/tools/symbol.ts +469 -17
  117. package/src/mcp/ui/app-client.ts +899 -0
  118. package/src/mcp/ui/app.html +478 -0
  119. package/src/mcp/workflow-playbooks.ts +181 -0
  120. package/src/mcp/workspace-boundary.ts +50 -0
  121. package/src/mcp/workspace-manager.ts +88 -15
  122. package/src/mcp/workspace-watcher.ts +30 -11
  123. package/src/types/index.ts +12 -0
  124. package/src/mcp/tools/check-boundary.ts +0 -382
  125. package/src/mcp/tools/get-domain-catalog.ts +0 -39
  126. package/src/mcp/tools/get-symbol-impact.ts +0 -104
  127. package/src/mcp/tools/locate-symbol.ts +0 -236
  128. package/src/mcp/tools/register-domain.ts +0 -113
  129. package/src/mcp/tools/trace-vertical-slice.ts +0 -106
@@ -0,0 +1,182 @@
1
+ import { resolve } from "node:path";
2
+ import type { SeptumRepository } from "../database/repository.ts";
3
+ import type { ValidatedSeptumConfig } from "../config/schema.ts";
4
+ import type { SymbolCandidate } from "../../types/index.ts";
5
+ import { computeContentHash } from "../ingestion/hasher.ts";
6
+ import { assertPathContained } from "../resolver/path-resolver.ts";
7
+ import { readSourceFile } from "../resources/source-files.ts";
8
+ import {
9
+ pageContext,
10
+ response,
11
+ budgetedResponse,
12
+ type ContextItem,
13
+ type SourceItem,
14
+ } from "./context-page.ts";
15
+ import type { ContextQuery } from "./context.ts";
16
+
17
+ export const UNIVERSAL_CONTEXT_POLICY = "referenced-universal-declarations/v1";
18
+
19
+ function indexLineOffsets(source: string): { lineStarts: number[]; lineEnds: number[] } {
20
+ const lineStarts = [0];
21
+ const lineEnds: number[] = [];
22
+ for (const match of source.matchAll(/\r\n|\n|\r/g)) {
23
+ const end = match.index!;
24
+ lineEnds.push(end);
25
+ lineStarts.push(end + match[0].length);
26
+ }
27
+ lineEnds.push(source.length);
28
+ return { lineStarts, lineEnds };
29
+ }
30
+
31
+ export async function retrieveUniversalContext(
32
+ repo: SeptumRepository,
33
+ config: ValidatedSeptumConfig,
34
+ query: ContextQuery,
35
+ target: SymbolCandidate,
36
+ workspaceRoot: string,
37
+ signal?: AbortSignal
38
+ ) {
39
+ signal?.throwIfAborted();
40
+ const root = resolve(workspaceRoot);
41
+ const budget = query.budget_bytes ?? 65536;
42
+ const maxDepth = query.max_depth ?? 2;
43
+
44
+ const targetFile = repo.getFileByPath(target.file_path);
45
+ if (!targetFile) {
46
+ return response({ status: "file_not_indexed", message: `File '${target.file_path}' is not indexed.` });
47
+ }
48
+
49
+ let targetSource: string;
50
+ try {
51
+ assertPathContained(target.file_path, root, "Universal context");
52
+ targetSource = readSourceFile(resolve(root, target.file_path));
53
+ } catch {
54
+ return response({ status: "source_unavailable", message: `Could not read source file '${target.file_path}'.` });
55
+ }
56
+
57
+ const currentHash = computeContentHash(targetSource);
58
+ if (currentHash !== targetFile.content_hash) {
59
+ return response({
60
+ status: "stale_reference",
61
+ message: `File '${target.file_path}' has changed on disk since last indexed. Run 'septum sync'.`,
62
+ });
63
+ }
64
+
65
+ const { lineStarts, lineEnds } = indexLineOffsets(targetSource);
66
+ const startIdx = lineStarts[Math.max(0, target.line_start - 1)] ?? 0;
67
+ const endIdx = lineEnds[Math.min(lineEnds.length - 1, target.line_end - 1)] ?? targetSource.length;
68
+ const targetText = targetSource.slice(startIdx, endIdx);
69
+
70
+ const items: ContextItem[] = [];
71
+ const emittedKeys = new Set<string>();
72
+
73
+ const targetKey = `${target.file_path}:${target.line_start}-${target.line_end}`;
74
+ emittedKeys.add(targetKey);
75
+
76
+ // 1. Target implementation
77
+ const targetItem: SourceItem = {
78
+ kind: "source",
79
+ selection_role: "implementation",
80
+ depth: 0,
81
+ name: target.name,
82
+ reason: "target_implementation",
83
+ source: {
84
+ file_path: target.file_path,
85
+ indexed_content_hash: targetFile.content_hash,
86
+ start_line: target.line_start,
87
+ end_line: target.line_end,
88
+ text: targetText,
89
+ },
90
+ };
91
+ items.push(targetItem);
92
+
93
+ // 2. Import relationships from target file
94
+ const fileRels = repo.getImportRelationships(root, target.file_path);
95
+ for (const edge of fileRels) {
96
+ if (edge.source.line >= target.line_start && edge.source.line <= target.line_end) {
97
+ items.push({
98
+ kind: "relationship",
99
+ reason: "target_file_import",
100
+ relationship: edge,
101
+ });
102
+ }
103
+ }
104
+
105
+ // 3. Inspect direct outbound calls & symbol dependencies if maxDepth > 0
106
+ if (maxDepth > 0) {
107
+ const details = repo.getSymbolDetails(target.name, {
108
+ filePath: target.file_path,
109
+ workspaceRoot: root,
110
+ });
111
+
112
+ const calls = details?.outbound_calls ?? [];
113
+ for (const callName of calls) {
114
+ if (items.length >= 32) break;
115
+ const candidates = repo.findSymbolsByName(callName, {
116
+ domain: query.domain,
117
+ });
118
+ const resolved = candidates.find(c => c.file_path === target.file_path) ?? candidates[0];
119
+ if (resolved) {
120
+ const key = `${resolved.file_path}:${resolved.line_start}-${resolved.line_end}`;
121
+ if (emittedKeys.has(key)) continue;
122
+ emittedKeys.add(key);
123
+
124
+ try {
125
+ const resFile = repo.getFileByPath(resolved.file_path);
126
+ if (!resFile) continue;
127
+ const resSource = readSourceFile(resolve(root, resolved.file_path));
128
+ if (computeContentHash(resSource) !== resFile.content_hash) continue;
129
+
130
+ const offsets = indexLineOffsets(resSource);
131
+ const sIdx = offsets.lineStarts[Math.max(0, resolved.line_start - 1)] ?? 0;
132
+ const eIdx = offsets.lineEnds[Math.min(offsets.lineEnds.length - 1, resolved.line_end - 1)] ?? resSource.length;
133
+ const text = resSource.slice(sIdx, eIdx);
134
+
135
+ items.push({
136
+ kind: "source",
137
+ selection_role: "implementation",
138
+ depth: 1,
139
+ name: resolved.name,
140
+ reason: resolved.file_path === target.file_path ? "local_dependency" : "direct_import_declaration",
141
+ source: {
142
+ file_path: resolved.file_path,
143
+ indexed_content_hash: resFile.content_hash,
144
+ start_line: resolved.line_start,
145
+ end_line: resolved.line_end,
146
+ text,
147
+ },
148
+ });
149
+ } catch {
150
+ // Graceful degradation if dependency source is unreadable
151
+ }
152
+ }
153
+ }
154
+ }
155
+
156
+ const queryId = computeContentHash(JSON.stringify({
157
+ root,
158
+ target: target.name,
159
+ file_path: target.file_path,
160
+ policy: UNIVERSAL_CONTEXT_POLICY,
161
+ budget,
162
+ }));
163
+
164
+ return pageContext({
165
+ items,
166
+ start: 0,
167
+ sourceOffset: 0,
168
+ budget,
169
+ incomplete: false,
170
+ base: {
171
+ policy: UNIVERSAL_CONTEXT_POLICY,
172
+ query_id: queryId,
173
+ snapshot_id: currentHash,
174
+ target: target.name,
175
+ file_path: target.file_path,
176
+ },
177
+ accounting: {
178
+ omitted_by_capacity: 0,
179
+ unexpanded_dependency_files: 0,
180
+ },
181
+ });
182
+ }
@@ -0,0 +1,114 @@
1
+ import { closeSync, constants, fstatSync, openSync, readSync } from "node:fs";
2
+ import { SeptumTelemetry, type SeptumToolCallEvent } from "./telemetry.ts";
3
+
4
+ const SAMPLE_LIMIT = 500;
5
+
6
+ function readLogTail(path: string): string[] {
7
+ let fd;
8
+ try {
9
+ fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK);
10
+ } catch (error) {
11
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
12
+ throw error;
13
+ }
14
+ try {
15
+ const stat = fstatSync(fd);
16
+ if (!stat.isFile()) throw new Error(`Telemetry log is not a regular file: ${path}`);
17
+ const length = Math.min(stat.size, SeptumTelemetry.MAX_LOG_SIZE_BYTES);
18
+ const offset = stat.size - length;
19
+ const buffer = Buffer.alloc(length);
20
+ let read = 0;
21
+ while (read < length) {
22
+ const count = readSync(fd, buffer, read, length - read, offset + read);
23
+ if (count === 0) break;
24
+ read += count;
25
+ }
26
+ const lines = buffer.subarray(0, read).toString("utf8").split("\n");
27
+ return offset ? lines.slice(1) : lines;
28
+ } finally {
29
+ closeSync(fd);
30
+ }
31
+ }
32
+
33
+ function parseToolEvent(line: string): SeptumToolCallEvent | undefined {
34
+ try {
35
+ const event = JSON.parse(line);
36
+ if ((event?.event === "tool_call_completed" || event?.event === "tool_call_failed") &&
37
+ (event.status === "success" || event.status === "error") &&
38
+ typeof event.tool === "string" && Number.isFinite(event.duration_ms) && event.duration_ms >= 0) return event;
39
+ } catch { /* The log can contain incomplete writes or older formats. */ }
40
+ }
41
+
42
+ function distribution(values: number[]) {
43
+ const sorted = values.sort((a, b) => a - b);
44
+ const percentile = (p: number) => sorted[Math.ceil(sorted.length * p) - 1] ?? null;
45
+ return { samples: sorted.length, p50: percentile(0.5), p95: percentile(0.95), max: sorted.at(-1) ?? null };
46
+ }
47
+
48
+ export function summarizeToolCalls(workspaceRoot: string) {
49
+ const path = SeptumTelemetry.getLogPath(workspaceRoot);
50
+ // Read active first so a concurrent rotation can be deduplicated by trace ID.
51
+ const active = readLogTail(path);
52
+ const seen = new Set<string>();
53
+ const events: SeptumToolCallEvent[] = [];
54
+ for (const lines of [active, readLogTail(`${path}.1`)]) {
55
+ for (let i = lines.length - 1; i >= 0 && events.length < SAMPLE_LIMIT; i--) {
56
+ const event = parseToolEvent(lines[i]!);
57
+ if (!event) continue;
58
+ if (typeof event.trace_id === "string") {
59
+ if (seen.has(event.trace_id)) continue;
60
+ seen.add(event.trace_id);
61
+ }
62
+ events.push(event);
63
+ }
64
+ }
65
+
66
+ const byTool = new Map<string, { calls: number; errors: number; actions: Map<string, { calls: number; errors: number }> }>();
67
+ const responseBytes: number[] = [];
68
+ const durations: number[] = [];
69
+ const recentErrors = [];
70
+ let errors = 0;
71
+ for (const event of events) {
72
+ const tool = byTool.get(event.tool) ?? { calls: 0, errors: 0, actions: new Map() };
73
+ byTool.set(event.tool, tool);
74
+ const action = typeof event.action === "string" ? event.action : "unspecified";
75
+ const counts = tool.actions.get(action) ?? { calls: 0, errors: 0 };
76
+ tool.actions.set(action, counts);
77
+ tool.calls++;
78
+ counts.calls++;
79
+ durations.push(event.duration_ms);
80
+ const bytes = event.metrics?.response_bytes;
81
+ if (typeof bytes === "number" && Number.isFinite(bytes) && bytes >= 0) responseBytes.push(bytes);
82
+ if (event.status === "error") {
83
+ errors++;
84
+ tool.errors++;
85
+ counts.errors++;
86
+ if (recentErrors.length < 10) recentErrors.push({
87
+ tool: event.tool,
88
+ action: event.action,
89
+ timestamp: event.timestamp,
90
+ trace_id: event.trace_id,
91
+ stage: event.stage,
92
+ code: event.error?.code,
93
+ });
94
+ }
95
+ }
96
+
97
+ return {
98
+ workspace: workspaceRoot,
99
+ sample_limit: SAMPLE_LIMIT,
100
+ sources: ["septum.log", "septum.log.1"],
101
+ first_timestamp: events.at(-1)?.timestamp ?? null,
102
+ last_timestamp: events[0]?.timestamp ?? null,
103
+ calls: events.length,
104
+ errors,
105
+ duration_ms: distribution(durations),
106
+ response_bytes: distribution(responseBytes),
107
+ tools: Object.fromEntries([...byTool].map(([name, tool]) => [name, {
108
+ calls: tool.calls,
109
+ errors: tool.errors,
110
+ actions: Object.fromEntries(tool.actions),
111
+ }])),
112
+ recent_errors: recentErrors,
113
+ };
114
+ }
@@ -1,3 +1,4 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
1
2
  import { appendFileSync, existsSync, renameSync, statSync } from "node:fs";
2
3
  import { dirname, join } from "node:path";
3
4
 
@@ -6,6 +7,7 @@ export interface SeptumToolCallMetrics {
6
7
  lines_out?: number;
7
8
  estimated_tokens?: number;
8
9
  nodes_returned?: number;
10
+ response_bytes?: number;
9
11
  }
10
12
 
11
13
  export interface SeptumOutputDigest {
@@ -13,7 +15,17 @@ export interface SeptumOutputDigest {
13
15
  sample_preview?: string;
14
16
  }
15
17
 
18
+ export type ToolCallStage = "validation" | "workspace" | "execution" | "cancelled" | "timeout";
19
+
20
+ export interface ToolResponse {
21
+ content?: ReadonlyArray<{ text?: unknown }>;
22
+ metadata?: unknown;
23
+ isError?: boolean;
24
+ }
25
+
16
26
  export interface SeptumToolCallEvent {
27
+ trace_id?: string;
28
+ stage?: ToolCallStage;
17
29
  timestamp?: string;
18
30
  event: "tool_call_completed" | "tool_call_failed";
19
31
  tool: string;
@@ -36,11 +48,44 @@ export interface SeptumToolCallEvent {
36
48
  };
37
49
  }
38
50
 
51
+ const SAFE_ACTIONS = new Set(["locate", "context", "inspect", "impact", "catalog", "register", "file", "staged", "all", "domain", "compact", "full", "deep", "source"]);
52
+ const OUTCOMES = new Set(["success", "partial", "unknown", "approved", "rejected", "ambiguous", "not_found", "NOT_INDEXED", "stale_reference", "invalid_context_options", "budget_too_small"]);
53
+
54
+ function errorCodeFromMetadata(value: unknown): string | undefined {
55
+ if (!value || typeof value !== "object" || !("code" in value)) return;
56
+ const code = value.code;
57
+ return typeof code === "string" && /^[A-Z][A-Z0-9_]{0,63}$/.test(code) ? code : undefined;
58
+ }
59
+
60
+ function outcomeFrom(value: unknown): string | undefined {
61
+ if (!value || typeof value !== "object") return;
62
+ const record = value as Record<string, unknown>;
63
+ const status = record.status ?? (record.found === false ? "not_found" : undefined);
64
+ return typeof status === "string" && OUTCOMES.has(status) ? status : undefined;
65
+ }
66
+
67
+ export interface SeptumTraceContext {
68
+ traceId: string;
69
+ workspaceRoot?: string;
70
+ }
71
+
72
+ export type SeptumSystemLevel = "INFO" | "WARN" | "ERROR";
73
+
39
74
  export class SeptumTelemetry {
75
+ private static readonly traceStorage = new AsyncLocalStorage<SeptumTraceContext>();
40
76
  public static readonly MAX_LOG_SIZE_BYTES = 2 * 1024 * 1024; // 2MB
77
+ public static readonly MAX_EVENT_BYTES = 4096;
41
78
  public static readonly SLOW_EXECUTION_THRESHOLD_MS = 250;
42
79
  public static readonly BLOAT_BYTE_THRESHOLD = 16 * 1024; // Serialized output byte threshold.
43
80
 
81
+ public static withTrace<T>(traceId: string, fn: () => T, workspaceRoot?: string): T {
82
+ return this.traceStorage.run({ traceId, workspaceRoot }, fn);
83
+ }
84
+
85
+ public static getActiveTraceContext(): SeptumTraceContext | undefined {
86
+ return this.traceStorage.getStore();
87
+ }
88
+
44
89
  /**
45
90
  * Generates a concise sample preview of output content to inspect payload relevancy and bloat.
46
91
  */
@@ -50,18 +95,63 @@ export class SeptumTelemetry {
50
95
  return { summary: "empty_output" };
51
96
  }
52
97
 
53
- let samplePreview = trimmed;
54
- if (trimmed.length > maxPreviewChars) {
55
- const head = trimmed.slice(0, 200).replace(/\s+/g, " ");
56
- const tail = trimmed.slice(-80).replace(/\s+/g, " ");
57
- samplePreview = `${head} ... [${trimmed.length - 280} chars omitted] ... ${tail}`;
58
- } else {
59
- samplePreview = trimmed.replace(/\s+/g, " ");
60
- }
98
+ const preview = trimmed.replace(/\s+/g, " ");
99
+ const limit = Number.isFinite(maxPreviewChars) ? Math.max(0, Math.min(300, Math.floor(maxPreviewChars))) : 300;
100
+ if (preview.length <= limit) return { sample_preview: preview };
101
+ const marker = " ... [chars omitted] ... ";
102
+ const available = Math.max(0, limit - marker.length);
103
+ const head = Math.ceil(available / 2);
104
+ const tail = available - head;
105
+ return { sample_preview: (preview.slice(0, head) + marker + (tail ? preview.slice(-tail) : "")).slice(0, limit) };
106
+ }
61
107
 
62
- return {
63
- sample_preview: samplePreview,
64
- };
108
+ public static recordToolResponse(
109
+ event: Omit<SeptumToolCallEvent, "event" | "status">,
110
+ response: ToolResponse,
111
+ workspaceRoot: string | null,
112
+ allowDetails = true,
113
+ ): void {
114
+ try {
115
+ let bytes = 0;
116
+ let lines = 0;
117
+ let preview = "";
118
+ let outcome = outcomeFrom(response.metadata);
119
+ const previewEnabled = allowDetails && (process.env.SEPTUM_LOG_PREVIEW === "1" || process.env.SEPTUM_DEBUG_TELEMETRY === "1");
120
+ for (const item of response.content ?? []) {
121
+ if (typeof item.text !== "string") continue;
122
+ const chunk = item.text;
123
+ bytes += Buffer.byteLength(chunk);
124
+ if (chunk.length > 0) {
125
+ lines++;
126
+ for (let i = 0; i < chunk.length; i++) if (chunk.charCodeAt(i) === 10) lines++;
127
+ }
128
+ if (previewEnabled && preview.length < 1500) preview += chunk.slice(0, 1500 - preview.length);
129
+ if (!outcome && chunk.length <= 65536 && chunk.trimStart().startsWith("{")) {
130
+ try { outcome = outcomeFrom(JSON.parse(chunk)); } catch { /* Text-only results have no structured outcome. */ }
131
+ }
132
+ }
133
+
134
+ const responseBytes = Buffer.byteLength(JSON.stringify(response));
135
+ this.recordToolCall({
136
+ ...event,
137
+ event: response.isError ? "tool_call_failed" : "tool_call_completed",
138
+ status: response.isError ? "error" : "success",
139
+ outcome,
140
+ metrics: { bytes_out: bytes, lines_out: lines, estimated_tokens: Math.round(bytes / 4), response_bytes: responseBytes },
141
+ bloat_alert: responseBytes >= this.BLOAT_BYTE_THRESHOLD,
142
+ output_digest: previewEnabled ? this.createOutputDigest(preview) : undefined,
143
+ error: response.isError ? {
144
+ message: event.error?.message ?? "Tool returned an error.",
145
+ stack: event.error?.stack,
146
+ code: event.error?.code ?? errorCodeFromMetadata(response.metadata) ?? (event.stage === "validation" ? "INVALID_ARGUMENT" :
147
+ event.stage === "workspace" ? "WORKSPACE_ERROR" :
148
+ event.stage === "cancelled" ? "REQUEST_CANCELLED" :
149
+ event.stage === "timeout" ? "REQUEST_TIMEOUT" : "TOOL_ERROR"),
150
+ } : undefined,
151
+ }, workspaceRoot, allowDetails);
152
+ } catch {
153
+ // Measurement failures cannot change the public response.
154
+ }
65
155
  }
66
156
 
67
157
  /**
@@ -76,40 +166,102 @@ export class SeptumTelemetry {
76
166
  */
77
167
  public static recordToolCall(
78
168
  event: SeptumToolCallEvent,
79
- workspaceRoot: string = process.cwd()
169
+ workspaceRoot: string | null = process.cwd(),
170
+ allowDetails = true,
80
171
  ): void {
81
- const debug = process.env.SEPTUM_DEBUG_TELEMETRY === "1";
82
- const input = Object.fromEntries(Object.entries(event.input).filter(([key, value]) =>
83
- ["include_source", "include_dependencies", "limit", "max_depth", "budget_bytes", "source_line_limit", "semantic_depth", "ingest_now", "staged"].includes(key) && (typeof value === "number" || typeof value === "boolean") ||
84
- ["action", "scope", "detail_level", "context_mode"].includes(key) && typeof value === "string" && ["locate", "context", "inspect", "impact", "catalog", "register", "file", "staged", "all", "domain", "compact", "full", "deep", "source"].includes(value)));
85
- const payload: SeptumToolCallEvent = {
86
- timestamp: event.timestamp || new Date().toISOString(),
87
- ...event,
88
- input: debug ? event.input : input,
89
- output_digest: debug ? event.output_digest : undefined,
90
- error: event.error && !debug ? { message: "Tool execution failed; inspect the tool response for details.", code: event.error.code } : event.error,
91
- };
92
-
93
- const jsonLine = JSON.stringify(payload);
94
-
95
- // Sink 1: Live stderr stream for operator monitoring (slow queries, bloat alerts & failures)
96
- if (payload.status === "error") {
97
- console.error(`[Septum Telemetry ERROR] ${jsonLine}`);
98
- } else if (payload.bloat_alert) {
99
- console.error(`[Septum Telemetry BLOAT_WARN] Tool '${payload.tool}' output exceeds configured byte threshold (${payload.metrics?.bytes_out} bytes)`);
100
- } else if (payload.duration_ms >= this.SLOW_EXECUTION_THRESHOLD_MS) {
101
- console.error(`[Septum Telemetry SLOW_WARN] ${jsonLine}`);
102
- }
172
+ try {
173
+ const debug = allowDetails && process.env.SEPTUM_DEBUG_TELEMETRY === "1";
174
+ const rawInput = allowDetails && (debug || process.env.SEPTUM_LOG_INPUT === "1");
175
+ const preview = allowDetails && (debug || process.env.SEPTUM_LOG_PREVIEW === "1");
176
+ const errorDetails = allowDetails && (debug || process.env.SEPTUM_LOG_ERROR_DETAILS === "1");
177
+ const safeInput = Object.fromEntries(Object.entries(event.input).filter(([key, value]) =>
178
+ ["include_source", "include_dependencies", "limit", "max_depth", "budget_bytes", "source_line_limit", "semantic_depth", "ingest_now", "staged"].includes(key) && (typeof value === "number" || typeof value === "boolean") ||
179
+ ["action", "scope", "detail_level", "context_mode"].includes(key) && typeof value === "string" && SAFE_ACTIONS.has(value)));
180
+ const payload: SeptumToolCallEvent = {
181
+ ...event,
182
+ timestamp: event.timestamp ?? new Date().toISOString(),
183
+ tool: event.tool.slice(0, 64),
184
+ action: event.action && SAFE_ACTIONS.has(event.action) ? event.action : undefined,
185
+ input: rawInput ? event.input : safeInput,
186
+ output_digest: preview ? event.output_digest : undefined,
187
+ error: event.error && {
188
+ code: event.error.code?.slice(0, 64),
189
+ message: errorDetails ? event.error.message.slice(0, 512) : "Tool execution failed; inspect the tool response for details.",
190
+ stack: errorDetails ? event.error.stack?.slice(0, 1024) : undefined,
191
+ },
192
+ };
103
193
 
104
- this.appendLog(jsonLine, workspaceRoot);
194
+ let jsonLine = JSON.stringify(payload);
195
+ if (Buffer.byteLength(jsonLine) + 1 > this.MAX_EVENT_BYTES) {
196
+ payload.input = safeInput;
197
+ payload.output_digest = undefined;
198
+ if (payload.error) {
199
+ delete payload.error.stack;
200
+ payload.error.message = "Tool execution failed; inspect the tool response for details.";
201
+ }
202
+ jsonLine = JSON.stringify(payload);
203
+ }
204
+ if (Buffer.byteLength(jsonLine) + 1 > this.MAX_EVENT_BYTES) return;
205
+
206
+ const severity = payload.status === "error" ? "ERROR" :
207
+ payload.bloat_alert ? "BLOAT_WARN" :
208
+ payload.duration_ms >= this.SLOW_EXECUTION_THRESHOLD_MS ? "SLOW_WARN" : undefined;
209
+ if (severity) this.writeStderr(`[Septum Telemetry ${severity}] ${jsonLine}`);
210
+ if (workspaceRoot) this.appendLog(jsonLine, workspaceRoot);
211
+ } catch {
212
+ // Serialization failures cannot change tool execution.
213
+ }
105
214
  }
106
215
 
107
216
  public static recordMemorySample(metrics: Record<string, number>, workspaceRoot: string = process.cwd()): void {
108
- const jsonLine = JSON.stringify({timestamp: new Date().toISOString(), event: "memory_sample", metrics});
109
- console.error(`[Septum Memory] ${jsonLine}`);
217
+ const jsonLine = JSON.stringify({ timestamp: new Date().toISOString(), event: "memory_sample", metrics });
218
+ this.writeStderr(`[Septum Memory] ${jsonLine}`);
110
219
  this.appendLog(jsonLine, workspaceRoot);
111
220
  }
112
221
 
222
+ public static recordSystemEvent(options: {
223
+ level: SeptumSystemLevel;
224
+ component: string;
225
+ event: string;
226
+ fields?: Record<string, unknown>;
227
+ workspaceRoot?: string | null;
228
+ emitStderr?: boolean;
229
+ }): void {
230
+ try {
231
+ const ctx = this.traceStorage.getStore();
232
+ const root = options.workspaceRoot !== undefined ? options.workspaceRoot : ctx?.workspaceRoot;
233
+ const payload: Record<string, unknown> = {
234
+ timestamp: new Date().toISOString(),
235
+ severity_text: options.level,
236
+ ...(ctx?.traceId ? { trace_id: ctx.traceId } : {}),
237
+ component: options.component.slice(0, 64),
238
+ event: options.event.slice(0, 64),
239
+ ...(options.fields ?? {}),
240
+ };
241
+ let jsonLine = JSON.stringify(payload);
242
+ if (Buffer.byteLength(jsonLine) + 1 > this.MAX_EVENT_BYTES) {
243
+ jsonLine = JSON.stringify({
244
+ timestamp: payload.timestamp,
245
+ severity_text: options.level,
246
+ ...(ctx?.traceId ? { trace_id: ctx.traceId } : {}),
247
+ component: payload.component,
248
+ event: payload.event,
249
+ truncated: true,
250
+ });
251
+ }
252
+ if (options.emitStderr !== false && (options.level === "WARN" || options.level === "ERROR")) {
253
+ this.writeStderr(`[Septum ${options.component} ${options.level}] ${jsonLine}`);
254
+ }
255
+ if (root) this.appendLog(jsonLine, root);
256
+ } catch {
257
+ // Telemetry failures must never disrupt caller execution.
258
+ }
259
+ }
260
+
261
+ private static writeStderr(message: string): void {
262
+ try { console.error(message); } catch { /* Keep file logging independent. */ }
263
+ }
264
+
113
265
  private static appendLog(jsonLine: string, workspaceRoot: string): void {
114
266
  // Sink 2: Append-only persistent file recorder in .septum/septum.log
115
267
  try {
@@ -121,20 +273,11 @@ export class SeptumTelemetry {
121
273
  return;
122
274
  }
123
275
 
124
- // Check for rotation if file exceeds 2MB
125
- if (existsSync(logPath)) {
126
- try {
127
- const stats = statSync(logPath);
128
- if (stats.size >= this.MAX_LOG_SIZE_BYTES) {
129
- const rotatedPath = `${logPath}.1`;
130
- renameSync(logPath, rotatedPath);
131
- }
132
- } catch {
133
- // If stat/rotation fails, proceed to append without crashing
134
- }
276
+ if (existsSync(logPath) && statSync(logPath).size + Buffer.byteLength(jsonLine) + 1 > this.MAX_LOG_SIZE_BYTES) {
277
+ renameSync(logPath, `${logPath}.1`);
135
278
  }
136
279
 
137
- appendFileSync(logPath, `${jsonLine}\n`, "utf8");
280
+ appendFileSync(logPath, `${jsonLine}\n`, { encoding: "utf8", mode: 0o600 });
138
281
  } catch {
139
282
  // Telemetry file writes must never crash the main application process
140
283
  }