apcore-js 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.
Files changed (142) hide show
  1. package/.claude/settings.local.json +11 -0
  2. package/.gitmessage +60 -0
  3. package/.pre-commit-config.yaml +28 -0
  4. package/CHANGELOG.md +47 -0
  5. package/CLAUDE.md +68 -0
  6. package/README.md +131 -0
  7. package/apcore-logo.svg +79 -0
  8. package/package.json +37 -0
  9. package/planning/acl-system/overview.md +54 -0
  10. package/planning/acl-system/plan.md +92 -0
  11. package/planning/acl-system/state.json +76 -0
  12. package/planning/acl-system/tasks/acl-core.md +226 -0
  13. package/planning/acl-system/tasks/acl-rule.md +92 -0
  14. package/planning/acl-system/tasks/conditional-rules.md +259 -0
  15. package/planning/acl-system/tasks/pattern-matching.md +152 -0
  16. package/planning/acl-system/tasks/yaml-loading.md +271 -0
  17. package/planning/core-executor/overview.md +53 -0
  18. package/planning/core-executor/plan.md +88 -0
  19. package/planning/core-executor/state.json +76 -0
  20. package/planning/core-executor/tasks/async-support.md +106 -0
  21. package/planning/core-executor/tasks/execution-pipeline.md +113 -0
  22. package/planning/core-executor/tasks/redaction.md +85 -0
  23. package/planning/core-executor/tasks/safety-checks.md +65 -0
  24. package/planning/core-executor/tasks/setup.md +75 -0
  25. package/planning/decorator-bindings/overview.md +62 -0
  26. package/planning/decorator-bindings/plan.md +104 -0
  27. package/planning/decorator-bindings/state.json +87 -0
  28. package/planning/decorator-bindings/tasks/binding-directory.md +79 -0
  29. package/planning/decorator-bindings/tasks/binding-loader.md +148 -0
  30. package/planning/decorator-bindings/tasks/explicit-schemas.md +85 -0
  31. package/planning/decorator-bindings/tasks/function-module.md +127 -0
  32. package/planning/decorator-bindings/tasks/module-factory.md +89 -0
  33. package/planning/decorator-bindings/tasks/schema-modes.md +142 -0
  34. package/planning/middleware-system/overview.md +48 -0
  35. package/planning/middleware-system/plan.md +102 -0
  36. package/planning/middleware-system/state.json +65 -0
  37. package/planning/middleware-system/tasks/adapters.md +170 -0
  38. package/planning/middleware-system/tasks/base.md +115 -0
  39. package/planning/middleware-system/tasks/logging-middleware.md +304 -0
  40. package/planning/middleware-system/tasks/manager.md +313 -0
  41. package/planning/observability/overview.md +53 -0
  42. package/planning/observability/plan.md +119 -0
  43. package/planning/observability/state.json +98 -0
  44. package/planning/observability/tasks/context-logger.md +201 -0
  45. package/planning/observability/tasks/exporters.md +121 -0
  46. package/planning/observability/tasks/metrics-collector.md +162 -0
  47. package/planning/observability/tasks/metrics-middleware.md +141 -0
  48. package/planning/observability/tasks/obs-logging-middleware.md +179 -0
  49. package/planning/observability/tasks/span-model.md +120 -0
  50. package/planning/observability/tasks/tracing-middleware.md +179 -0
  51. package/planning/overview.md +81 -0
  52. package/planning/registry-system/overview.md +57 -0
  53. package/planning/registry-system/plan.md +114 -0
  54. package/planning/registry-system/state.json +109 -0
  55. package/planning/registry-system/tasks/dependencies.md +157 -0
  56. package/planning/registry-system/tasks/entry-point.md +148 -0
  57. package/planning/registry-system/tasks/metadata.md +198 -0
  58. package/planning/registry-system/tasks/registry-core.md +323 -0
  59. package/planning/registry-system/tasks/scanner.md +172 -0
  60. package/planning/registry-system/tasks/schema-export.md +261 -0
  61. package/planning/registry-system/tasks/types.md +124 -0
  62. package/planning/registry-system/tasks/validation.md +177 -0
  63. package/planning/schema-system/overview.md +56 -0
  64. package/planning/schema-system/plan.md +121 -0
  65. package/planning/schema-system/state.json +98 -0
  66. package/planning/schema-system/tasks/exporter.md +153 -0
  67. package/planning/schema-system/tasks/loader.md +106 -0
  68. package/planning/schema-system/tasks/ref-resolver.md +133 -0
  69. package/planning/schema-system/tasks/strict-mode.md +140 -0
  70. package/planning/schema-system/tasks/typebox-generation.md +133 -0
  71. package/planning/schema-system/tasks/types-and-annotations.md +160 -0
  72. package/planning/schema-system/tasks/validator.md +149 -0
  73. package/src/acl.ts +188 -0
  74. package/src/bindings.ts +208 -0
  75. package/src/config.ts +24 -0
  76. package/src/context.ts +75 -0
  77. package/src/decorator.ts +110 -0
  78. package/src/errors.ts +369 -0
  79. package/src/executor.ts +348 -0
  80. package/src/index.ts +81 -0
  81. package/src/middleware/adapters.ts +54 -0
  82. package/src/middleware/base.ts +33 -0
  83. package/src/middleware/index.ts +6 -0
  84. package/src/middleware/logging.ts +103 -0
  85. package/src/middleware/manager.ts +105 -0
  86. package/src/module.ts +41 -0
  87. package/src/observability/context-logger.ts +201 -0
  88. package/src/observability/index.ts +4 -0
  89. package/src/observability/metrics.ts +212 -0
  90. package/src/observability/tracing.ts +187 -0
  91. package/src/registry/dependencies.ts +99 -0
  92. package/src/registry/entry-point.ts +64 -0
  93. package/src/registry/index.ts +8 -0
  94. package/src/registry/metadata.ts +111 -0
  95. package/src/registry/registry.ts +314 -0
  96. package/src/registry/scanner.ts +150 -0
  97. package/src/registry/schema-export.ts +177 -0
  98. package/src/registry/types.ts +32 -0
  99. package/src/registry/validation.ts +38 -0
  100. package/src/schema/annotations.ts +67 -0
  101. package/src/schema/exporter.ts +93 -0
  102. package/src/schema/index.ts +14 -0
  103. package/src/schema/loader.ts +270 -0
  104. package/src/schema/ref-resolver.ts +235 -0
  105. package/src/schema/strict.ts +128 -0
  106. package/src/schema/types.ts +73 -0
  107. package/src/schema/validator.ts +82 -0
  108. package/src/utils/index.ts +1 -0
  109. package/src/utils/pattern.ts +30 -0
  110. package/tests/helpers.ts +30 -0
  111. package/tests/integration/test-acl-safety.test.ts +268 -0
  112. package/tests/integration/test-binding-executor.test.ts +194 -0
  113. package/tests/integration/test-e2e-flow.test.ts +117 -0
  114. package/tests/integration/test-error-propagation.test.ts +259 -0
  115. package/tests/integration/test-middleware-chain.test.ts +120 -0
  116. package/tests/integration/test-observability-integration.test.ts +438 -0
  117. package/tests/observability/test-context-logger.test.ts +123 -0
  118. package/tests/observability/test-metrics.test.ts +89 -0
  119. package/tests/observability/test-tracing.test.ts +131 -0
  120. package/tests/registry/test-dependencies.test.ts +70 -0
  121. package/tests/registry/test-entry-point.test.ts +133 -0
  122. package/tests/registry/test-metadata.test.ts +265 -0
  123. package/tests/registry/test-registry.test.ts +140 -0
  124. package/tests/registry/test-scanner.test.ts +257 -0
  125. package/tests/registry/test-schema-export.test.ts +224 -0
  126. package/tests/registry/test-validation.test.ts +75 -0
  127. package/tests/schema/test-loader.test.ts +97 -0
  128. package/tests/schema/test-ref-resolver.test.ts +105 -0
  129. package/tests/schema/test-strict.test.ts +139 -0
  130. package/tests/schema/test-validator.test.ts +64 -0
  131. package/tests/test-acl.test.ts +206 -0
  132. package/tests/test-bindings.test.ts +227 -0
  133. package/tests/test-config.test.ts +76 -0
  134. package/tests/test-context.test.ts +151 -0
  135. package/tests/test-decorator.test.ts +173 -0
  136. package/tests/test-errors.test.ts +204 -0
  137. package/tests/test-executor.test.ts +252 -0
  138. package/tests/test-middleware-manager.test.ts +185 -0
  139. package/tests/test-middleware.test.ts +86 -0
  140. package/tsconfig.build.json +8 -0
  141. package/tsconfig.json +20 -0
  142. package/vitest.config.ts +18 -0
@@ -0,0 +1,438 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { Type } from '@sinclair/typebox';
3
+ import { Executor } from '../../src/executor.js';
4
+ import { FunctionModule } from '../../src/decorator.js';
5
+ import { Registry } from '../../src/registry/registry.js';
6
+ import { Context, createIdentity } from '../../src/context.js';
7
+ import { InMemoryExporter, TracingMiddleware } from '../../src/observability/tracing.js';
8
+ import { MetricsCollector, MetricsMiddleware } from '../../src/observability/metrics.js';
9
+ import { ContextLogger, ObsLoggingMiddleware } from '../../src/observability/context-logger.js';
10
+
11
+ describe('Observability Integration', () => {
12
+ it('full observability stack on success', async () => {
13
+ const registry = new Registry();
14
+ const testModule = new FunctionModule({
15
+ execute: (inputs) => ({ result: `Processed ${inputs['value']}` }),
16
+ moduleId: 'test.success',
17
+ inputSchema: Type.Object({ value: Type.String() }),
18
+ outputSchema: Type.Object({ result: Type.String() }),
19
+ description: 'Test module',
20
+ });
21
+ registry.register('test.success', testModule);
22
+
23
+ const metrics = new MetricsCollector();
24
+ const exporter = new InMemoryExporter();
25
+ const logLines: string[] = [];
26
+ const captureOutput = {
27
+ write(s: string): void {
28
+ logLines.push(s);
29
+ },
30
+ };
31
+ const logger = new ContextLogger({ name: 'test', output: captureOutput });
32
+
33
+ const executor = new Executor({
34
+ registry,
35
+ middlewares: [
36
+ new MetricsMiddleware(metrics),
37
+ new TracingMiddleware(exporter),
38
+ new ObsLoggingMiddleware({ logger }),
39
+ ],
40
+ });
41
+
42
+ const result = await executor.call('test.success', { value: 'hello' });
43
+ expect(result['result']).toBe('Processed hello');
44
+
45
+ // Verify span exported with status='ok'
46
+ const spans = exporter.getSpans();
47
+ expect(spans).toHaveLength(1);
48
+ expect(spans[0].status).toBe('ok');
49
+ expect(spans[0].name).toBe('apcore.module.execute');
50
+
51
+ // Verify success counter incremented
52
+ const snap = metrics.snapshot();
53
+ const counters = snap['counters'] as Record<string, number>;
54
+ expect(counters['apcore_module_calls_total|module_id=test.success,status=success']).toBe(1);
55
+
56
+ // Verify duration observed
57
+ const histograms = snap['histograms'] as Record<string, unknown>;
58
+ const counts = histograms['counts'] as Record<string, number>;
59
+ expect(counts['apcore_module_duration_seconds|module_id=test.success']).toBe(1);
60
+
61
+ // Verify logger captured "started" and "completed" messages
62
+ expect(logLines.length).toBeGreaterThanOrEqual(2);
63
+ const startedLog = logLines.find((line) => line.includes('Module call started'));
64
+ const completedLog = logLines.find((line) => line.includes('Module call completed'));
65
+ expect(startedLog).toBeDefined();
66
+ expect(completedLog).toBeDefined();
67
+ });
68
+
69
+ it('full observability stack on failure', async () => {
70
+ const registry = new Registry();
71
+ const testModule = new FunctionModule({
72
+ execute: (_inputs) => {
73
+ throw new Error('Test failure');
74
+ },
75
+ moduleId: 'test.failure',
76
+ inputSchema: Type.Object({ value: Type.String() }),
77
+ outputSchema: Type.Object({ result: Type.String() }),
78
+ description: 'Failing module',
79
+ });
80
+ registry.register('test.failure', testModule);
81
+
82
+ const metrics = new MetricsCollector();
83
+ const exporter = new InMemoryExporter();
84
+ const logLines: string[] = [];
85
+ const captureOutput = {
86
+ write(s: string): void {
87
+ logLines.push(s);
88
+ },
89
+ };
90
+ const logger = new ContextLogger({ name: 'test', output: captureOutput });
91
+
92
+ const executor = new Executor({
93
+ registry,
94
+ middlewares: [
95
+ new MetricsMiddleware(metrics),
96
+ new TracingMiddleware(exporter),
97
+ new ObsLoggingMiddleware({ logger }),
98
+ ],
99
+ });
100
+
101
+ await expect(executor.call('test.failure', { value: 'test' })).rejects.toThrow('Test failure');
102
+
103
+ // Verify span has status='error' and error_code attribute
104
+ const spans = exporter.getSpans();
105
+ expect(spans).toHaveLength(1);
106
+ expect(spans[0].status).toBe('error');
107
+ expect(spans[0].attributes['error_code']).toBe('Error');
108
+
109
+ // Verify error counter incremented
110
+ const snap = metrics.snapshot();
111
+ const counters = snap['counters'] as Record<string, number>;
112
+ expect(counters['apcore_module_calls_total|module_id=test.failure,status=error']).toBe(1);
113
+ expect(counters['apcore_module_errors_total|error_code=Error,module_id=test.failure']).toBe(1);
114
+
115
+ // Verify logger captured "started" and "failed" messages
116
+ expect(logLines.length).toBeGreaterThanOrEqual(2);
117
+ const startedLog = logLines.find((line) => line.includes('Module call started'));
118
+ const failedLog = logLines.find((line) => line.includes('Module call failed'));
119
+ expect(startedLog).toBeDefined();
120
+ expect(failedLog).toBeDefined();
121
+ });
122
+
123
+ it('tracing with nested calls', async () => {
124
+ const registry = new Registry();
125
+
126
+ const moduleB = new FunctionModule({
127
+ execute: (inputs) => ({ value: `B: ${inputs['data']}` }),
128
+ moduleId: 'mod.b',
129
+ inputSchema: Type.Object({ data: Type.String() }),
130
+ outputSchema: Type.Object({ value: Type.String() }),
131
+ description: 'Module B',
132
+ });
133
+
134
+ const moduleA = new FunctionModule({
135
+ execute: async (_inputs, context) => {
136
+ const executor = context.executor as Executor;
137
+ return executor.call('mod.b', { data: 'nested' }, context);
138
+ },
139
+ moduleId: 'mod.a',
140
+ inputSchema: Type.Object({}),
141
+ outputSchema: Type.Object({ value: Type.String() }),
142
+ description: 'Module A',
143
+ });
144
+
145
+ registry.register('mod.a', moduleA);
146
+ registry.register('mod.b', moduleB);
147
+
148
+ const exporter = new InMemoryExporter();
149
+ const executor = new Executor({
150
+ registry,
151
+ middlewares: [new TracingMiddleware(exporter)],
152
+ });
153
+
154
+ const result = await executor.call('mod.a', {});
155
+ expect(result['value']).toBe('B: nested');
156
+
157
+ // Verify 2 spans exported
158
+ const spans = exporter.getSpans();
159
+ expect(spans).toHaveLength(2);
160
+
161
+ // Second span has parentSpanId matching first span's spanId
162
+ const spanA = spans.find((s) => s.attributes['moduleId'] === 'mod.a');
163
+ const spanB = spans.find((s) => s.attributes['moduleId'] === 'mod.b');
164
+ expect(spanA).toBeDefined();
165
+ expect(spanB).toBeDefined();
166
+ expect(spanB!.parentSpanId).toBe(spanA!.spanId);
167
+
168
+ // Both share same traceId
169
+ expect(spanA!.traceId).toBe(spanB!.traceId);
170
+ });
171
+
172
+ it('metrics accumulate across calls', async () => {
173
+ const registry = new Registry();
174
+
175
+ let callCount = 0;
176
+ const testModule = new FunctionModule({
177
+ execute: (_inputs) => {
178
+ callCount++;
179
+ if (callCount === 4) {
180
+ throw new Error('Fourth call fails');
181
+ }
182
+ return { result: 'ok' };
183
+ },
184
+ moduleId: 'test.accumulate',
185
+ inputSchema: Type.Object({}),
186
+ outputSchema: Type.Object({ result: Type.String() }),
187
+ description: 'Test module',
188
+ });
189
+ registry.register('test.accumulate', testModule);
190
+
191
+ const metrics = new MetricsCollector();
192
+ const executor = new Executor({
193
+ registry,
194
+ middlewares: [new MetricsMiddleware(metrics)],
195
+ });
196
+
197
+ // Call 3 times successfully
198
+ await executor.call('test.accumulate', {});
199
+ await executor.call('test.accumulate', {});
200
+ await executor.call('test.accumulate', {});
201
+
202
+ // Call once with failure
203
+ await expect(executor.call('test.accumulate', {})).rejects.toThrow('Fourth call fails');
204
+
205
+ // Verify: success counter = 3, error counter = 1, duration histogram count = 4
206
+ const snap = metrics.snapshot();
207
+ const counters = snap['counters'] as Record<string, number>;
208
+ expect(counters['apcore_module_calls_total|module_id=test.accumulate,status=success']).toBe(3);
209
+ expect(counters['apcore_module_calls_total|module_id=test.accumulate,status=error']).toBe(1);
210
+
211
+ const histograms = snap['histograms'] as Record<string, unknown>;
212
+ const counts = histograms['counts'] as Record<string, number>;
213
+ expect(counts['apcore_module_duration_seconds|module_id=test.accumulate']).toBe(4);
214
+ });
215
+
216
+ it('TracingMiddleware with error_first sampling', async () => {
217
+ const registry = new Registry();
218
+
219
+ const successModule = new FunctionModule({
220
+ execute: (_inputs) => ({ result: 'ok' }),
221
+ moduleId: 'test.sampling.success',
222
+ inputSchema: Type.Object({}),
223
+ outputSchema: Type.Object({ result: Type.String() }),
224
+ description: 'Success module',
225
+ });
226
+
227
+ const errorModule = new FunctionModule({
228
+ execute: (_inputs) => {
229
+ throw new Error('Sampling error');
230
+ },
231
+ moduleId: 'test.sampling.error',
232
+ inputSchema: Type.Object({}),
233
+ outputSchema: Type.Object({ result: Type.String() }),
234
+ description: 'Error module',
235
+ });
236
+
237
+ registry.register('test.sampling.success', successModule);
238
+ registry.register('test.sampling.error', errorModule);
239
+
240
+ const exporter = new InMemoryExporter();
241
+ const executor = new Executor({
242
+ registry,
243
+ middlewares: [new TracingMiddleware(exporter, 0.0, 'error_first')],
244
+ });
245
+
246
+ // Success calls don't export spans
247
+ await executor.call('test.sampling.success', {});
248
+ await executor.call('test.sampling.success', {});
249
+ expect(exporter.getSpans()).toHaveLength(0);
250
+
251
+ // Error calls DO export spans
252
+ await expect(executor.call('test.sampling.error', {})).rejects.toThrow('Sampling error');
253
+ const spans = exporter.getSpans();
254
+ expect(spans).toHaveLength(1);
255
+ expect(spans[0].status).toBe('error');
256
+ expect(spans[0].attributes['moduleId']).toBe('test.sampling.error');
257
+ });
258
+
259
+ it('TracingMiddleware with off strategy', async () => {
260
+ const registry = new Registry();
261
+
262
+ const successModule = new FunctionModule({
263
+ execute: (_inputs) => ({ result: 'ok' }),
264
+ moduleId: 'test.off.success',
265
+ inputSchema: Type.Object({}),
266
+ outputSchema: Type.Object({ result: Type.String() }),
267
+ description: 'Success module',
268
+ });
269
+
270
+ const errorModule = new FunctionModule({
271
+ execute: (_inputs) => {
272
+ throw new Error('Off error');
273
+ },
274
+ moduleId: 'test.off.error',
275
+ inputSchema: Type.Object({}),
276
+ outputSchema: Type.Object({ result: Type.String() }),
277
+ description: 'Error module',
278
+ });
279
+
280
+ registry.register('test.off.success', successModule);
281
+ registry.register('test.off.error', errorModule);
282
+
283
+ const exporter = new InMemoryExporter();
284
+ const executor = new Executor({
285
+ registry,
286
+ middlewares: [new TracingMiddleware(exporter, 1.0, 'off')],
287
+ });
288
+
289
+ // No spans exported for success calls
290
+ await executor.call('test.off.success', {});
291
+ expect(exporter.getSpans()).toHaveLength(0);
292
+
293
+ // No spans exported for error calls
294
+ await expect(executor.call('test.off.error', {})).rejects.toThrow('Off error');
295
+ expect(exporter.getSpans()).toHaveLength(0);
296
+ });
297
+
298
+ it('ObsLoggingMiddleware captures inputs and outputs', async () => {
299
+ const registry = new Registry();
300
+ const testModule = new FunctionModule({
301
+ execute: (inputs) => ({ output_value: `processed_${inputs['input_value']}` }),
302
+ moduleId: 'test.logging',
303
+ inputSchema: Type.Object({ input_value: Type.String() }),
304
+ outputSchema: Type.Object({ output_value: Type.String() }),
305
+ description: 'Logging test',
306
+ });
307
+ registry.register('test.logging', testModule);
308
+
309
+ const logLines: string[] = [];
310
+ const captureOutput = {
311
+ write(s: string): void {
312
+ logLines.push(s);
313
+ },
314
+ };
315
+ const logger = new ContextLogger({ name: 'test', output: captureOutput });
316
+
317
+ const executor = new Executor({
318
+ registry,
319
+ middlewares: [new ObsLoggingMiddleware({ logger, logInputs: true, logOutputs: true })],
320
+ });
321
+
322
+ await executor.call('test.logging', { input_value: 'test_input' });
323
+
324
+ // Verify 'Module call started' includes module_id and inputs
325
+ const startedLog = logLines.find((line) => line.includes('Module call started'));
326
+ expect(startedLog).toBeDefined();
327
+ const startedData = JSON.parse(startedLog!);
328
+ expect(startedData.message).toBe('Module call started');
329
+ expect(startedData.extra.module_id).toBe('test.logging');
330
+ expect(startedData.extra.inputs).toEqual({ input_value: 'test_input' });
331
+
332
+ // Verify 'Module call completed' includes duration_ms and output
333
+ const completedLog = logLines.find((line) => line.includes('Module call completed'));
334
+ expect(completedLog).toBeDefined();
335
+ const completedData = JSON.parse(completedLog!);
336
+ expect(completedData.message).toBe('Module call completed');
337
+ expect(completedData.extra.module_id).toBe('test.logging');
338
+ expect(completedData.extra.output).toEqual({ output_value: 'processed_test_input' });
339
+ expect(typeof completedData.extra.duration_ms).toBe('number');
340
+ expect(completedData.extra.duration_ms).toBeGreaterThanOrEqual(0);
341
+ });
342
+
343
+ it('Context logger redacts _secret_ fields', async () => {
344
+ const registry = new Registry();
345
+ const testModule = new FunctionModule({
346
+ execute: (_inputs) => ({ result: 'done' }),
347
+ moduleId: 'test.redact',
348
+ inputSchema: Type.Object({
349
+ _secret_key: Type.String(),
350
+ normal_field: Type.String(),
351
+ }),
352
+ outputSchema: Type.Object({ result: Type.String() }),
353
+ description: 'Redaction test',
354
+ });
355
+ registry.register('test.redact', testModule);
356
+
357
+ const logLines: string[] = [];
358
+ const captureOutput = {
359
+ write(s: string): void {
360
+ logLines.push(s);
361
+ },
362
+ };
363
+ const logger = new ContextLogger({
364
+ name: 'test',
365
+ output: captureOutput,
366
+ redactSensitive: true,
367
+ });
368
+
369
+ const executor = new Executor({
370
+ registry,
371
+ middlewares: [new ObsLoggingMiddleware({ logger, logInputs: true })],
372
+ });
373
+
374
+ await executor.call('test.redact', {
375
+ _secret_key: 'super_secret_value',
376
+ normal_field: 'normal_value',
377
+ });
378
+
379
+ // Verify the logged extra has _secret_key redacted
380
+ const startedLog = logLines.find((line) => line.includes('Module call started'));
381
+ expect(startedLog).toBeDefined();
382
+ const logData = JSON.parse(startedLog!);
383
+ expect(logData.extra.inputs._secret_key).toBe('***REDACTED***');
384
+ expect(logData.extra.inputs.normal_field).toBe('normal_value');
385
+ });
386
+
387
+ it('Span attributes include moduleId, method, callerId', async () => {
388
+ const registry = new Registry();
389
+
390
+ const moduleB = new FunctionModule({
391
+ execute: (_inputs) => ({ result: 'B done' }),
392
+ moduleId: 'test.b',
393
+ inputSchema: Type.Object({}),
394
+ outputSchema: Type.Object({ result: Type.String() }),
395
+ description: 'Module B',
396
+ });
397
+
398
+ const moduleA = new FunctionModule({
399
+ execute: async (_inputs, context) => {
400
+ const executor = context.executor as Executor;
401
+ return executor.call('test.b', {}, context);
402
+ },
403
+ moduleId: 'test.a',
404
+ inputSchema: Type.Object({}),
405
+ outputSchema: Type.Object({ result: Type.String() }),
406
+ description: 'Module A',
407
+ });
408
+
409
+ registry.register('test.a', moduleA);
410
+ registry.register('test.b', moduleB);
411
+
412
+ const exporter = new InMemoryExporter();
413
+ const executor = new Executor({
414
+ registry,
415
+ middlewares: [new TracingMiddleware(exporter)],
416
+ });
417
+
418
+ await executor.call('test.a', {});
419
+
420
+ // Verify span attributes contain moduleId, method, callerId
421
+ const spans = exporter.getSpans();
422
+ expect(spans).toHaveLength(2);
423
+
424
+ // First span (test.a) has null callerId since it's top-level
425
+ const spanA = spans.find((s) => s.attributes['moduleId'] === 'test.a');
426
+ expect(spanA).toBeDefined();
427
+ expect(spanA!.attributes['moduleId']).toBe('test.a');
428
+ expect(spanA!.attributes['method']).toBe('execute');
429
+ expect(spanA!.attributes['callerId']).toBeNull();
430
+
431
+ // Second span (test.b) has callerId='test.a' since it's called by test.a
432
+ const spanB = spans.find((s) => s.attributes['moduleId'] === 'test.b');
433
+ expect(spanB).toBeDefined();
434
+ expect(spanB!.attributes['moduleId']).toBe('test.b');
435
+ expect(spanB!.attributes['method']).toBe('execute');
436
+ expect(spanB!.attributes['callerId']).toBe('test.a');
437
+ });
438
+ });
@@ -0,0 +1,123 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { Context, createIdentity } from '../../src/context.js';
3
+ import { ContextLogger, ObsLoggingMiddleware } from '../../src/observability/context-logger.js';
4
+
5
+ function createBufferOutput() {
6
+ const lines: string[] = [];
7
+ return {
8
+ output: { write: (s: string) => lines.push(s) },
9
+ lines,
10
+ };
11
+ }
12
+
13
+ describe('ContextLogger', () => {
14
+ it('creates with defaults', () => {
15
+ const logger = new ContextLogger();
16
+ // Should not throw
17
+ expect(logger).toBeDefined();
18
+ });
19
+
20
+ it('logs JSON format by default', () => {
21
+ const { output, lines } = createBufferOutput();
22
+ const logger = new ContextLogger({ output });
23
+ logger.info('test message');
24
+ expect(lines).toHaveLength(1);
25
+ const parsed = JSON.parse(lines[0]);
26
+ expect(parsed.level).toBe('info');
27
+ expect(parsed.message).toBe('test message');
28
+ });
29
+
30
+ it('logs text format', () => {
31
+ const { output, lines } = createBufferOutput();
32
+ const logger = new ContextLogger({ format: 'text', output });
33
+ logger.info('test message');
34
+ expect(lines).toHaveLength(1);
35
+ expect(lines[0]).toContain('[INFO]');
36
+ expect(lines[0]).toContain('test message');
37
+ });
38
+
39
+ it('respects log level filtering', () => {
40
+ const { output, lines } = createBufferOutput();
41
+ const logger = new ContextLogger({ level: 'warn', output });
42
+ logger.debug('should not appear');
43
+ logger.info('should not appear');
44
+ logger.warn('should appear');
45
+ logger.error('should appear');
46
+ expect(lines).toHaveLength(2);
47
+ });
48
+
49
+ it('redacts _secret_ prefix keys', () => {
50
+ const { output, lines } = createBufferOutput();
51
+ const logger = new ContextLogger({ output });
52
+ logger.info('test', { _secret_token: 'abc123', name: 'Bob' });
53
+ const parsed = JSON.parse(lines[0]);
54
+ expect(parsed.extra._secret_token).toBe('***REDACTED***');
55
+ expect(parsed.extra.name).toBe('Bob');
56
+ });
57
+
58
+ it('does not redact when disabled', () => {
59
+ const { output, lines } = createBufferOutput();
60
+ const logger = new ContextLogger({ output, redactSensitive: false });
61
+ logger.info('test', { _secret_token: 'abc123' });
62
+ const parsed = JSON.parse(lines[0]);
63
+ expect(parsed.extra._secret_token).toBe('abc123');
64
+ });
65
+
66
+ it('fromContext sets trace/module/caller', () => {
67
+ const { output, lines } = createBufferOutput();
68
+ const ctx = Context.create(undefined, createIdentity('user1'));
69
+ const childCtx = ctx.child('mod.test');
70
+ const logger = ContextLogger.fromContext(childCtx, 'test-logger', { output });
71
+ logger.info('context log');
72
+ const parsed = JSON.parse(lines[0]);
73
+ expect(parsed.trace_id).toBe(ctx.traceId);
74
+ expect(parsed.module_id).toBe('mod.test');
75
+ expect(parsed.logger).toBe('test-logger');
76
+ });
77
+
78
+ it('all log levels work', () => {
79
+ const { output, lines } = createBufferOutput();
80
+ const logger = new ContextLogger({ level: 'trace', output });
81
+ logger.trace('t');
82
+ logger.debug('d');
83
+ logger.info('i');
84
+ logger.warn('w');
85
+ logger.error('e');
86
+ logger.fatal('f');
87
+ expect(lines).toHaveLength(6);
88
+ });
89
+ });
90
+
91
+ describe('ObsLoggingMiddleware', () => {
92
+ it('logs before and after', () => {
93
+ const { output, lines } = createBufferOutput();
94
+ const logger = new ContextLogger({ output });
95
+ const mw = new ObsLoggingMiddleware({ logger });
96
+ const ctx = Context.create();
97
+
98
+ mw.before('mod.a', { name: 'Alice' }, ctx);
99
+ mw.after('mod.a', { name: 'Alice' }, { result: 'ok' }, ctx);
100
+
101
+ expect(lines).toHaveLength(2);
102
+ const before = JSON.parse(lines[0]);
103
+ const after = JSON.parse(lines[1]);
104
+ expect(before.message).toBe('Module call started');
105
+ expect(after.message).toBe('Module call completed');
106
+ expect(after.extra.duration_ms).toBeDefined();
107
+ });
108
+
109
+ it('logs onError', () => {
110
+ const { output, lines } = createBufferOutput();
111
+ const logger = new ContextLogger({ output });
112
+ const mw = new ObsLoggingMiddleware({ logger });
113
+ const ctx = Context.create();
114
+
115
+ mw.before('mod.a', {}, ctx);
116
+ mw.onError('mod.a', {}, new Error('boom'), ctx);
117
+
118
+ expect(lines).toHaveLength(2);
119
+ const errorLog = JSON.parse(lines[1]);
120
+ expect(errorLog.message).toBe('Module call failed');
121
+ expect(errorLog.extra.error_type).toBe('Error');
122
+ });
123
+ });
@@ -0,0 +1,89 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { MetricsCollector, MetricsMiddleware } from '../../src/observability/metrics.js';
3
+ import { Context } from '../../src/context.js';
4
+
5
+ describe('MetricsCollector', () => {
6
+ it('increments counters', () => {
7
+ const collector = new MetricsCollector();
8
+ collector.increment('test_counter', { method: 'GET' });
9
+ collector.increment('test_counter', { method: 'GET' });
10
+ const snap = collector.snapshot();
11
+ expect((snap['counters'] as Record<string, number>)['test_counter|method=GET']).toBe(2);
12
+ });
13
+
14
+ it('observes histogram values', () => {
15
+ const collector = new MetricsCollector();
16
+ collector.observe('test_hist', { module: 'a' }, 0.05);
17
+ collector.observe('test_hist', { module: 'a' }, 0.5);
18
+ const snap = collector.snapshot();
19
+ const hists = snap['histograms'] as Record<string, Record<string, number>>;
20
+ expect(hists['sums']['test_hist|module=a']).toBeCloseTo(0.55);
21
+ expect(hists['counts']['test_hist|module=a']).toBe(2);
22
+ });
23
+
24
+ it('convenience methods work', () => {
25
+ const collector = new MetricsCollector();
26
+ collector.incrementCalls('mod.a', 'success');
27
+ collector.incrementErrors('mod.a', 'TIMEOUT');
28
+ collector.observeDuration('mod.a', 0.1);
29
+
30
+ const snap = collector.snapshot();
31
+ const counters = snap['counters'] as Record<string, number>;
32
+ expect(counters['apcore_module_calls_total|module_id=mod.a,status=success']).toBe(1);
33
+ expect(counters['apcore_module_errors_total|error_code=TIMEOUT,module_id=mod.a']).toBe(1);
34
+ });
35
+
36
+ it('reset clears all data', () => {
37
+ const collector = new MetricsCollector();
38
+ collector.incrementCalls('mod.a', 'success');
39
+ collector.observeDuration('mod.a', 0.1);
40
+ collector.reset();
41
+ const snap = collector.snapshot();
42
+ expect(Object.keys(snap['counters'] as Record<string, unknown>)).toHaveLength(0);
43
+ });
44
+
45
+ it('exportPrometheus produces valid format', () => {
46
+ const collector = new MetricsCollector();
47
+ collector.incrementCalls('mod.a', 'success');
48
+ collector.observeDuration('mod.a', 0.05);
49
+ const output = collector.exportPrometheus();
50
+ expect(output).toContain('# HELP');
51
+ expect(output).toContain('# TYPE');
52
+ expect(output).toContain('apcore_module_calls_total');
53
+ expect(output).toContain('apcore_module_duration_seconds');
54
+ });
55
+
56
+ it('empty collector returns empty prometheus string', () => {
57
+ const collector = new MetricsCollector();
58
+ expect(collector.exportPrometheus()).toBe('');
59
+ });
60
+ });
61
+
62
+ describe('MetricsMiddleware', () => {
63
+ it('records call metrics on success', () => {
64
+ const collector = new MetricsCollector();
65
+ const mw = new MetricsMiddleware(collector);
66
+ const ctx = Context.create();
67
+
68
+ mw.before('mod.a', {}, ctx);
69
+ mw.after('mod.a', {}, { result: 'ok' }, ctx);
70
+
71
+ const snap = collector.snapshot();
72
+ const counters = snap['counters'] as Record<string, number>;
73
+ expect(counters['apcore_module_calls_total|module_id=mod.a,status=success']).toBe(1);
74
+ });
75
+
76
+ it('records error metrics on failure', () => {
77
+ const collector = new MetricsCollector();
78
+ const mw = new MetricsMiddleware(collector);
79
+ const ctx = Context.create();
80
+
81
+ mw.before('mod.a', {}, ctx);
82
+ mw.onError('mod.a', {}, new Error('boom'), ctx);
83
+
84
+ const snap = collector.snapshot();
85
+ const counters = snap['counters'] as Record<string, number>;
86
+ expect(counters['apcore_module_calls_total|module_id=mod.a,status=error']).toBe(1);
87
+ expect(counters['apcore_module_errors_total|error_code=Error,module_id=mod.a']).toBe(1);
88
+ });
89
+ });