@iworkforces/tracelattice 2.3.6 → 2.4.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 (85) hide show
  1. package/README.md +18 -5
  2. package/dist/ServerConfig.d.ts +16 -0
  3. package/dist/ServerConfig.d.ts.map +1 -1
  4. package/dist/ServerConfig.js +11 -0
  5. package/dist/ServerConfig.js.map +1 -1
  6. package/dist/cli.js +234 -18
  7. package/dist/cli.js.map +1 -1
  8. package/dist/config/ConfigLoader.d.ts +2 -0
  9. package/dist/config/ConfigLoader.d.ts.map +1 -1
  10. package/dist/config/ConfigLoader.js +2 -0
  11. package/dist/config/ConfigLoader.js.map +1 -1
  12. package/dist/contracts/PersistenceBackend.d.ts +26 -0
  13. package/dist/contracts/PersistenceBackend.d.ts.map +1 -1
  14. package/dist/contracts/persistence-backlog.d.ts +21 -0
  15. package/dist/contracts/persistence-backlog.d.ts.map +1 -0
  16. package/dist/contracts/persistence-backlog.js +1 -0
  17. package/dist/core/HistoryManager.d.ts +15 -1
  18. package/dist/core/HistoryManager.d.ts.map +1 -1
  19. package/dist/core/HistoryManager.js +12 -2
  20. package/dist/core/HistoryManager.js.map +1 -1
  21. package/dist/core/IHistoryManager.d.ts +2 -0
  22. package/dist/core/IHistoryManager.d.ts.map +1 -1
  23. package/dist/core/PersistenceBuffer.d.ts +25 -0
  24. package/dist/core/PersistenceBuffer.d.ts.map +1 -1
  25. package/dist/core/PersistenceBuffer.js +27 -5
  26. package/dist/core/PersistenceBuffer.js.map +1 -1
  27. package/dist/core/PersistenceBufferErrors.d.ts +10 -0
  28. package/dist/core/PersistenceBufferErrors.d.ts.map +1 -1
  29. package/dist/core/PersistenceBufferErrors.js +13 -1
  30. package/dist/core/PersistenceBufferErrors.js.map +1 -1
  31. package/dist/core/PersistenceRestore.d.ts.map +1 -1
  32. package/dist/core/PersistenceRestore.js +25 -30
  33. package/dist/core/PersistenceRestore.js.map +1 -1
  34. package/dist/core/PersistenceWorkQueue.d.ts +9 -0
  35. package/dist/core/PersistenceWorkQueue.d.ts.map +1 -1
  36. package/dist/core/PersistenceWorkQueue.js +18 -0
  37. package/dist/core/PersistenceWorkQueue.js.map +1 -1
  38. package/dist/core/ThoughtEvaluator.d.ts +6 -0
  39. package/dist/core/ThoughtEvaluator.d.ts.map +1 -1
  40. package/dist/core/ThoughtEvaluator.js +15 -1
  41. package/dist/core/ThoughtEvaluator.js.map +1 -1
  42. package/dist/core/ThoughtProcessor.d.ts.map +1 -1
  43. package/dist/core/ThoughtProcessor.js +3 -10
  44. package/dist/core/ThoughtProcessor.js.map +1 -1
  45. package/dist/core/evaluator/VerificationLinks.d.ts +5 -0
  46. package/dist/core/evaluator/VerificationLinks.d.ts.map +1 -1
  47. package/dist/core/evaluator/VerificationLinks.js +47 -53
  48. package/dist/core/evaluator/VerificationLinks.js.map +1 -1
  49. package/dist/core/reasoning/ActiveEvidenceProjection.d.ts.map +1 -1
  50. package/dist/core/reasoning/ActiveEvidenceProjection.js +4 -3
  51. package/dist/core/reasoning/ActiveEvidenceProjection.js.map +1 -1
  52. package/dist/errors.d.ts +1 -0
  53. package/dist/errors.d.ts.map +1 -1
  54. package/dist/errors.js +2 -1
  55. package/dist/errors.js.map +1 -1
  56. package/dist/health/HealthChecker.d.ts +42 -1
  57. package/dist/health/HealthChecker.d.ts.map +1 -1
  58. package/dist/health/HealthChecker.js +60 -8
  59. package/dist/health/HealthChecker.js.map +1 -1
  60. package/dist/lib.d.ts +2 -2
  61. package/dist/lib.d.ts.map +1 -1
  62. package/dist/lib.js +1 -0
  63. package/dist/lib.js.map +1 -1
  64. package/dist/metrics/metrics.impl.js.map +1 -1
  65. package/dist/persistence/FilePersistence.d.ts +2 -1
  66. package/dist/persistence/FilePersistence.d.ts.map +1 -1
  67. package/dist/persistence/FilePersistence.js +6 -1
  68. package/dist/persistence/FilePersistence.js.map +1 -1
  69. package/dist/persistence/FileSnapshotV2.d.ts +2 -0
  70. package/dist/persistence/FileSnapshotV2.d.ts.map +1 -1
  71. package/dist/persistence/FileSnapshotV2.js +39 -1
  72. package/dist/persistence/FileSnapshotV2.js.map +1 -1
  73. package/dist/persistence/MemoryPersistence.d.ts +4 -1
  74. package/dist/persistence/MemoryPersistence.d.ts.map +1 -1
  75. package/dist/persistence/MemoryPersistence.js +30 -0
  76. package/dist/persistence/MemoryPersistence.js.map +1 -1
  77. package/dist/persistence/SqlitePersistence.d.ts +6 -1
  78. package/dist/persistence/SqlitePersistence.d.ts.map +1 -1
  79. package/dist/persistence/SqlitePersistence.js +31 -4
  80. package/dist/persistence/SqlitePersistence.js.map +1 -1
  81. package/dist/transport/StreamableHttpTransport.d.ts +12 -0
  82. package/dist/transport/StreamableHttpTransport.d.ts.map +1 -1
  83. package/dist/transport/StreamableHttpTransport.js +19 -5
  84. package/dist/transport/StreamableHttpTransport.js.map +1 -1
  85. package/package.json +11 -11
@@ -1,4 +1,9 @@
1
1
  import { getErrorMessage } from "../errors.js";
2
+ const DEFAULT_PROBE_TIMEOUT_MS = 1000;
3
+ function describeBacklog(view) {
4
+ const counts = `quarantined sessions: ${view.quarantinedSessionCount}, retained failures: ${view.retainedFailureCount}, pending thoughts: ${view.pendingThoughtCount}`;
5
+ return view.globalQuarantined ? `Persistence is globally quarantined; ${counts}` : counts;
6
+ }
2
7
  class NoopLogger {
3
8
  info() {}
4
9
  warn() {}
@@ -7,10 +12,18 @@ class NoopLogger {
7
12
  }
8
13
  class HealthChecker {
9
14
  _persistence;
15
+ _backlog;
10
16
  _logger;
17
+ _probeTimeoutMs;
18
+ _probeFreshnessMs;
19
+ _inFlight = null;
20
+ _settled = null;
11
21
  constructor(options = {}){
12
22
  this._persistence = options.persistence ?? null;
23
+ this._backlog = options.persistenceBacklog ?? null;
13
24
  this._logger = options.logger ?? new NoopLogger();
25
+ this._probeTimeoutMs = options.probeTimeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS;
26
+ this._probeFreshnessMs = options.probeFreshnessMs ?? 0;
14
27
  }
15
28
  checkLiveness() {
16
29
  return {
@@ -21,14 +34,13 @@ class HealthChecker {
21
34
  }
22
35
  async checkReadiness() {
23
36
  const components = {};
24
- let healthyCount = 0;
25
- let totalCount = 0;
26
- if (this._persistence) {
27
- totalCount++;
28
- const component = await this._checkPersistence();
29
- components['persistence'] = component;
30
- if (component.healthy) healthyCount++;
31
- }
37
+ if (this._persistence) components['persistence'] = {
38
+ ...await this._checkPersistence()
39
+ };
40
+ const backlog = this._checkBacklog();
41
+ if (backlog) components['persistenceBacklog'] = backlog;
42
+ const totalCount = Object.keys(components).length;
43
+ const healthyCount = Object.values(components).filter((component)=>component.healthy).length;
32
44
  let status;
33
45
  status = 0 === totalCount || healthyCount === totalCount ? 'ok' : 0 === healthyCount ? 'unhealthy' : 'degraded';
34
46
  const result = {
@@ -43,6 +55,46 @@ class HealthChecker {
43
55
  return result;
44
56
  }
45
57
  async _checkPersistence() {
58
+ const settled = this._settled;
59
+ if (null !== settled && Date.now() - settled.settledAt < this._probeFreshnessMs) return settled.component;
60
+ this._inFlight ??= this._startProbe();
61
+ return this._inFlight;
62
+ }
63
+ _startProbe() {
64
+ const settled = this._probeBackend().then((component)=>{
65
+ this._inFlight = null;
66
+ this._settled = {
67
+ component,
68
+ settledAt: Date.now()
69
+ };
70
+ return component;
71
+ });
72
+ return new Promise((resolve)=>{
73
+ const timer = setTimeout(()=>{
74
+ resolve({
75
+ name: 'persistence',
76
+ healthy: false,
77
+ latencyMs: this._probeTimeoutMs,
78
+ details: `Health check timed out after ${this._probeTimeoutMs}ms`
79
+ });
80
+ }, this._probeTimeoutMs);
81
+ timer.unref();
82
+ settled.then((component)=>{
83
+ clearTimeout(timer);
84
+ resolve(component);
85
+ });
86
+ });
87
+ }
88
+ _checkBacklog() {
89
+ const view = this._backlog?.getPersistenceBacklogView() ?? null;
90
+ if (null === view) return null;
91
+ return {
92
+ name: 'persistenceBacklog',
93
+ healthy: !view.globalQuarantined,
94
+ details: describeBacklog(view)
95
+ };
96
+ }
97
+ async _probeBackend() {
46
98
  const start = Date.now();
47
99
  try {
48
100
  const healthy = await this._persistence.healthy();
@@ -1 +1 @@
1
- {"version":3,"file":"health/HealthChecker.js","sources":["../../src/health/HealthChecker.ts"],"sourcesContent":["/**\n * Aggregate health checking system.\n *\n * Provides liveness and readiness checks by aggregating the health\n * status of registered backend components (persistence, pool, etc.).\n *\n * @module health\n */\n\nimport type { Logger } from '../logger/StructuredLogger.js';\nimport type { PersistenceBackend } from '../contracts/PersistenceBackend.js';\nimport { getErrorMessage } from '../errors.js';\n\n/**\n * Health status of an individual component.\n */\nexport interface HealthComponent {\n\tname: string;\n\thealthy: boolean;\n\tdetails?: string;\n\tlatencyMs?: number;\n}\n\n/**\n * Aggregate health check result.\n */\nexport interface HealthCheckResult {\n\tstatus: 'ok' | 'degraded' | 'unhealthy';\n\ttimestamp: string;\n\tcomponents: Record<string, HealthComponent>;\n}\n\n/**\n * Options for constructing a HealthChecker.\n */\nexport interface HealthCheckerOptions {\n\tpersistence?: PersistenceBackend | null;\n\tlogger?: Logger;\n}\n\n/**\n * No-op logger used when none is provided.\n */\nclass NoopLogger implements Pick<Logger, 'info' | 'warn' | 'error' | 'debug'> {\n\tinfo(): void {}\n\twarn(): void {}\n\terror(): void {}\n\tdebug(): void {}\n}\n\n/**\n * Aggregates component health into liveness and readiness checks.\n *\n * - `checkLiveness()` always returns 'ok' if the process is running.\n * - `checkReadiness()` checks all registered backends and returns an aggregate status.\n *\n * @example\n * ```typescript\n * const checker = new HealthChecker({ persistence: myBackend });\n * const readiness = await checker.checkReadiness();\n * // { status: 'ok', timestamp: '...', components: { persistence: { ... } } }\n * ```\n */\nexport class HealthChecker {\n\tprivate _persistence: PersistenceBackend | null;\n\tprivate _logger: Pick<Logger, 'info' | 'warn' | 'error' | 'debug'>;\n\n\tconstructor(options: HealthCheckerOptions = {}) {\n\t\tthis._persistence = options.persistence ?? null;\n\t\tthis._logger = options.logger ?? new NoopLogger();\n\t}\n\n\t/**\n\t * Liveness check — returns 'ok' if the process is alive.\n\t *\n\t * This is a synchronous check that always succeeds; if this code\n\t * can execute, the process is alive.\n\t */\n\tcheckLiveness(): HealthCheckResult {\n\t\treturn {\n\t\t\tstatus: 'ok',\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tcomponents: {},\n\t\t};\n\t}\n\n\t/**\n\t * Readiness check — aggregates health of all registered backends.\n\t *\n\t * Checks each component and returns:\n\t * - 'ok' if all components are healthy (or no components registered)\n\t * - 'degraded' if some components are unhealthy\n\t * - 'unhealthy' if all components are unhealthy\n\t */\n\tasync checkReadiness(): Promise<HealthCheckResult> {\n\t\tconst components: Record<string, HealthComponent> = {};\n\t\tlet healthyCount = 0;\n\t\tlet totalCount = 0;\n\n\t\t// Check persistence backend\n\t\tif (this._persistence) {\n\t\t\ttotalCount++;\n\t\t\tconst component = await this._checkPersistence();\n\t\t\tcomponents['persistence'] = component;\n\t\t\tif (component.healthy) {\n\t\t\t\thealthyCount++;\n\t\t\t}\n\t\t}\n\n\t\t// Determine aggregate status\n\t\tlet status: 'ok' | 'degraded' | 'unhealthy';\n\t\tif (totalCount === 0 || healthyCount === totalCount) {\n\t\t\tstatus = 'ok';\n\t\t} else if (healthyCount === 0) {\n\t\t\tstatus = 'unhealthy';\n\t\t} else {\n\t\t\tstatus = 'degraded';\n\t\t}\n\n\t\tconst result: HealthCheckResult = {\n\t\t\tstatus,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tcomponents,\n\t\t};\n\n\t\tif (status !== 'ok') {\n\t\t\tthis._logger.warn('Readiness check returned non-ok status', {\n\t\t\t\tstatus,\n\t\t\t\tcomponents,\n\t\t\t});\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Check persistence backend health with latency measurement.\n\t */\n\tprivate async _checkPersistence(): Promise<HealthComponent> {\n\t\tconst start = Date.now();\n\t\ttry {\n\t\t\tconst healthy = await this._persistence!.healthy();\n\t\t\treturn {\n\t\t\t\tname: 'persistence',\n\t\t\t\thealthy,\n\t\t\t\tlatencyMs: Date.now() - start,\n\t\t\t\tdetails: healthy ? 'Backend is responsive' : 'Backend reported unhealthy',\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tthis._logger.error('Persistence health check failed', {\n\t\t\t\terror: getErrorMessage(error),\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tname: 'persistence',\n\t\t\t\thealthy: false,\n\t\t\t\tlatencyMs: Date.now() - start,\n\t\t\t\tdetails: `Health check error: ${getErrorMessage(error)}`,\n\t\t\t};\n\t\t}\n\t}\n}\n"],"names":["NoopLogger","HealthChecker","options","Date","components","healthyCount","totalCount","component","status","result","start","healthy","error","getErrorMessage"],"mappings":";AA2CA,MAAMA;IACL,OAAa,CAAC;IACd,OAAa,CAAC;IACd,QAAc,CAAC;IACf,QAAc,CAAC;AAChB;AAeO,MAAMC;IACJ,aAAwC;IACxC,QAA2D;IAEnE,YAAYC,UAAgC,CAAC,CAAC,CAAE;QAC/C,IAAI,CAAC,YAAY,GAAGA,QAAQ,WAAW,IAAI;QAC3C,IAAI,CAAC,OAAO,GAAGA,QAAQ,MAAM,IAAI,IAAIF;IACtC;IAQA,gBAAmC;QAClC,OAAO;YACN,QAAQ;YACR,WAAW,IAAIG,OAAO,WAAW;YACjC,YAAY,CAAC;QACd;IACD;IAUA,MAAM,iBAA6C;QAClD,MAAMC,aAA8C,CAAC;QACrD,IAAIC,eAAe;QACnB,IAAIC,aAAa;QAGjB,IAAI,IAAI,CAAC,YAAY,EAAE;YACtBA;YACA,MAAMC,YAAY,MAAM,IAAI,CAAC,iBAAiB;YAC9CH,UAAU,CAAC,cAAc,GAAGG;YAC5B,IAAIA,UAAU,OAAO,EACpBF;QAEF;QAGA,IAAIG;QAEHA,SADGF,AAAe,MAAfA,cAAoBD,iBAAiBC,aAC/B,OACCD,AAAiB,MAAjBA,eACD,cAEA;QAGV,MAAMI,SAA4B;YACjCD;YACA,WAAW,IAAIL,OAAO,WAAW;YACjCC;QACD;QAEA,IAAII,AAAW,SAAXA,QACH,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,0CAA0C;YAC3DA;YACAJ;QACD;QAGD,OAAOK;IACR;IAKA,MAAc,oBAA8C;QAC3D,MAAMC,QAAQP,KAAK,GAAG;QACtB,IAAI;YACH,MAAMQ,UAAU,MAAM,IAAI,CAAC,YAAY,CAAE,OAAO;YAChD,OAAO;gBACN,MAAM;gBACNA;gBACA,WAAWR,KAAK,GAAG,KAAKO;gBACxB,SAASC,UAAU,0BAA0B;YAC9C;QACD,EAAE,OAAOC,OAAO;YACf,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,mCAAmC;gBACrD,OAAOC,gBAAgBD;YACxB;YACA,OAAO;gBACN,MAAM;gBACN,SAAS;gBACT,WAAWT,KAAK,GAAG,KAAKO;gBACxB,SAAS,CAAC,oBAAoB,EAAEG,gBAAgBD,QAAQ;YACzD;QACD;IACD;AACD"}
1
+ {"version":3,"file":"health/HealthChecker.js","sources":["../../src/health/HealthChecker.ts"],"sourcesContent":["/**\n * Aggregate health checking system.\n *\n * Provides liveness and readiness checks by aggregating the health\n * status of registered backend components (persistence, pool, etc.).\n *\n * @module health\n */\n\nimport type { Logger } from '../logger/StructuredLogger.js';\nimport type { PersistenceBackend } from '../contracts/PersistenceBackend.js';\nimport type {\n\tPersistenceBacklogSource,\n\tPersistenceBacklogView,\n} from '../contracts/persistence-backlog.js';\nimport { getErrorMessage } from '../errors.js';\n\nconst DEFAULT_PROBE_TIMEOUT_MS = 1000;\n\n/**\n * Health status of an individual component.\n */\nexport interface HealthComponent {\n\tname: string;\n\thealthy: boolean;\n\tdetails?: string;\n\tlatencyMs?: number;\n}\n\n/**\n * Aggregate health check result.\n */\nexport interface HealthCheckResult {\n\tstatus: 'ok' | 'degraded' | 'unhealthy';\n\ttimestamp: string;\n\tcomponents: Record<string, HealthComponent>;\n}\n\n/**\n * Options for constructing a HealthChecker.\n */\nexport interface HealthCheckerOptions {\n\tpersistence?: PersistenceBackend | null;\n\t/**\n\t * Reports quarantine and unflushed-work counts. Its component is omitted while the source\n\t * returns `null` (persistence disabled).\n\t */\n\tpersistenceBacklog?: PersistenceBacklogSource | null;\n\tlogger?: Logger;\n\t/**\n\t * Deadline for `persistence.healthy()`, in milliseconds. A probe that outlives it reports the\n\t * persistence component unhealthy but keeps running; later checks join it instead of starting\n\t * another.\n\t * @default 1000\n\t */\n\tprobeTimeoutMs?: number;\n\t/**\n\t * How long a settled probe result is reused, in milliseconds. `0` probes on every call.\n\t * @default 0\n\t */\n\tprobeFreshnessMs?: number;\n}\n\ninterface SettledProbe {\n\treadonly component: HealthComponent;\n\treadonly settledAt: number;\n}\n\nfunction describeBacklog(view: PersistenceBacklogView): string {\n\tconst counts =\n\t\t`quarantined sessions: ${view.quarantinedSessionCount}, ` +\n\t\t`retained failures: ${view.retainedFailureCount}, ` +\n\t\t`pending thoughts: ${view.pendingThoughtCount}`;\n\treturn view.globalQuarantined ? `Persistence is globally quarantined; ${counts}` : counts;\n}\n\n/**\n * No-op logger used when none is provided.\n */\nclass NoopLogger implements Pick<Logger, 'info' | 'warn' | 'error' | 'debug'> {\n\tinfo(): void {}\n\twarn(): void {}\n\terror(): void {}\n\tdebug(): void {}\n}\n\n/**\n * Aggregates component health into liveness and readiness checks.\n *\n * - `checkLiveness()` always returns 'ok' if the process is running.\n * - `checkReadiness()` checks all registered backends and returns an aggregate status.\n *\n * @example\n * ```typescript\n * const checker = new HealthChecker({ persistence: myBackend });\n * const readiness = await checker.checkReadiness();\n * // { status: 'ok', timestamp: '...', components: { persistence: { ... } } }\n * ```\n */\nexport class HealthChecker {\n\tprivate _persistence: PersistenceBackend | null;\n\tprivate _backlog: PersistenceBacklogSource | null;\n\tprivate _logger: Pick<Logger, 'info' | 'warn' | 'error' | 'debug'>;\n\tprivate readonly _probeTimeoutMs: number;\n\tprivate readonly _probeFreshnessMs: number;\n\t/** Verdict of the backend probe that has not settled yet, shared by every caller. */\n\tprivate _inFlight: Promise<HealthComponent> | null = null;\n\tprivate _settled: SettledProbe | null = null;\n\n\tconstructor(options: HealthCheckerOptions = {}) {\n\t\tthis._persistence = options.persistence ?? null;\n\t\tthis._backlog = options.persistenceBacklog ?? null;\n\t\tthis._logger = options.logger ?? new NoopLogger();\n\t\tthis._probeTimeoutMs = options.probeTimeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS;\n\t\tthis._probeFreshnessMs = options.probeFreshnessMs ?? 0;\n\t}\n\n\t/**\n\t * Liveness check — returns 'ok' if the process is alive.\n\t *\n\t * This is a synchronous check that always succeeds; if this code\n\t * can execute, the process is alive.\n\t */\n\tcheckLiveness(): HealthCheckResult {\n\t\treturn {\n\t\t\tstatus: 'ok',\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tcomponents: {},\n\t\t};\n\t}\n\n\t/**\n\t * Readiness check — aggregates health of all registered backends.\n\t *\n\t * Checks each component and returns:\n\t * - 'ok' if all components are healthy (or no components registered)\n\t * - 'degraded' if some components are unhealthy\n\t * - 'unhealthy' if all components are unhealthy\n\t *\n\t * The persistence probe is bounded by `probeTimeoutMs`, shared between concurrent calls, and\n\t * reused for `probeFreshnessMs` after it settles. The backlog component is read on every call.\n\t */\n\tasync checkReadiness(): Promise<HealthCheckResult> {\n\t\tconst components: Record<string, HealthComponent> = {};\n\n\t\tif (this._persistence) {\n\t\t\tcomponents['persistence'] = { ...(await this._checkPersistence()) };\n\t\t}\n\n\t\tconst backlog = this._checkBacklog();\n\t\tif (backlog) {\n\t\t\tcomponents['persistenceBacklog'] = backlog;\n\t\t}\n\n\t\tconst totalCount = Object.keys(components).length;\n\t\tconst healthyCount = Object.values(components).filter((component) => component.healthy).length;\n\n\t\t// Determine aggregate status\n\t\tlet status: 'ok' | 'degraded' | 'unhealthy';\n\t\tif (totalCount === 0 || healthyCount === totalCount) {\n\t\t\tstatus = 'ok';\n\t\t} else if (healthyCount === 0) {\n\t\t\tstatus = 'unhealthy';\n\t\t} else {\n\t\t\tstatus = 'degraded';\n\t\t}\n\n\t\tconst result: HealthCheckResult = {\n\t\t\tstatus,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tcomponents,\n\t\t};\n\n\t\tif (status !== 'ok') {\n\t\t\tthis._logger.warn('Readiness check returned non-ok status', {\n\t\t\t\tstatus,\n\t\t\t\tcomponents,\n\t\t\t});\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Persistence component from the freshest source available: a settled result still inside\n\t * the freshness window, else the probe already running (even past its deadline), else a new\n\t * probe.\n\t */\n\tprivate async _checkPersistence(): Promise<HealthComponent> {\n\t\tconst settled = this._settled;\n\t\tif (settled !== null && Date.now() - settled.settledAt < this._probeFreshnessMs) {\n\t\t\treturn settled.component;\n\t\t}\n\t\tthis._inFlight ??= this._startProbe();\n\t\treturn this._inFlight;\n\t}\n\n\t/**\n\t * Start one backend probe. The backend call is never abandoned: it stays tracked until it\n\t * settles, while the returned verdict resolves at that point or at the deadline, whichever\n\t * comes first.\n\t */\n\tprivate _startProbe(): Promise<HealthComponent> {\n\t\tconst settled = this._probeBackend().then((component) => {\n\t\t\tthis._inFlight = null;\n\t\t\tthis._settled = { component, settledAt: Date.now() };\n\t\t\treturn component;\n\t\t});\n\t\treturn new Promise<HealthComponent>((resolve) => {\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tresolve({\n\t\t\t\t\tname: 'persistence',\n\t\t\t\t\thealthy: false,\n\t\t\t\t\tlatencyMs: this._probeTimeoutMs,\n\t\t\t\t\tdetails: `Health check timed out after ${this._probeTimeoutMs}ms`,\n\t\t\t\t});\n\t\t\t}, this._probeTimeoutMs);\n\t\t\ttimer.unref();\n\t\t\tvoid settled.then((component) => {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\tresolve(component);\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate _checkBacklog(): HealthComponent | null {\n\t\tconst view = this._backlog?.getPersistenceBacklogView() ?? null;\n\t\tif (view === null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn {\n\t\t\tname: 'persistenceBacklog',\n\t\t\thealthy: !view.globalQuarantined,\n\t\t\tdetails: describeBacklog(view),\n\t\t};\n\t}\n\n\t/**\n\t * Probe the persistence backend with latency measurement. Never rejects: every failure,\n\t * including a rejection that arrives after the deadline, becomes an unhealthy component.\n\t */\n\tprivate async _probeBackend(): Promise<HealthComponent> {\n\t\tconst start = Date.now();\n\t\ttry {\n\t\t\tconst healthy = await this._persistence!.healthy();\n\t\t\treturn {\n\t\t\t\tname: 'persistence',\n\t\t\t\thealthy,\n\t\t\t\tlatencyMs: Date.now() - start,\n\t\t\t\tdetails: healthy ? 'Backend is responsive' : 'Backend reported unhealthy',\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tthis._logger.error('Persistence health check failed', {\n\t\t\t\terror: getErrorMessage(error),\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tname: 'persistence',\n\t\t\t\thealthy: false,\n\t\t\t\tlatencyMs: Date.now() - start,\n\t\t\t\tdetails: `Health check error: ${getErrorMessage(error)}`,\n\t\t\t};\n\t\t}\n\t}\n}\n"],"names":["DEFAULT_PROBE_TIMEOUT_MS","describeBacklog","view","counts","NoopLogger","HealthChecker","options","Date","components","backlog","totalCount","Object","healthyCount","component","status","result","settled","Promise","resolve","timer","setTimeout","clearTimeout","start","healthy","error","getErrorMessage"],"mappings":";AAiBA,MAAMA,2BAA2B;AAmDjC,SAASC,gBAAgBC,IAA4B;IACpD,MAAMC,SACL,CAAC,sBAAsB,EAAED,KAAK,uBAAuB,CACpD,qBAAmB,EAAEA,KAAK,oBAAoB,CAC9C,oBAAkB,EAAEA,KAAK,mBAAmB,EAFY;IAG1D,OAAOA,KAAK,iBAAiB,GAAG,CAAC,qCAAqC,EAAEC,QAAQ,GAAGA;AACpF;AAKA,MAAMC;IACL,OAAa,CAAC;IACd,OAAa,CAAC;IACd,QAAc,CAAC;IACf,QAAc,CAAC;AAChB;AAeO,MAAMC;IACJ,aAAwC;IACxC,SAA0C;IAC1C,QAA2D;IAClD,gBAAwB;IACxB,k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N,MAAM;gBACN,SAAS;gBACT,WAAWjB,KAAK,GAAG,KAAKe;gBACxB,SAAS,CAAC,oBAAoB,EAAEG,gBAAgBD,QAAQ;YACzD;QACD;IACD;AACD"}
package/dist/lib.d.ts CHANGED
@@ -11,7 +11,7 @@ import { HistoryManager } from './core/HistoryManager.js';
11
11
  import { type CallToolResult } from './core/ThoughtProcessor.js';
12
12
  import { Container } from './di/Container.js';
13
13
  import { StructuredLogger } from './logger/StructuredLogger.js';
14
- import type { PersistenceBackend } from './contracts/PersistenceBackend.js';
14
+ import type { PersistedBranchRecord, PersistedSessionRecord, PersistenceBackend, PersistenceRestoreRead } from './contracts/PersistenceBackend.js';
15
15
  import { SkillRegistry } from './registry/SkillRegistry.js';
16
16
  import { ToolRegistry } from './registry/ToolRegistry.js';
17
17
  import { ServerConfig } from './ServerConfig.js';
@@ -20,7 +20,7 @@ import type { HttpTransportOptions } from './transport/HttpTransport.js';
20
20
  import type { TransportOptions } from './transport/BaseTransport.js';
21
21
  import type { ITransport, TransportKind } from './contracts/transport.js';
22
22
  export { HttpTransport, createHttpTransport };
23
- export type { HttpTransportOptions, TransportOptions, ITransport, TransportKind, PersistenceBackend, ThoughtData, Edge, Summary, SessionId, ThoughtId, BranchId, };
23
+ export type { HttpTransportOptions, TransportOptions, ITransport, TransportKind, PersistenceBackend, PersistedBranchRecord, PersistedSessionRecord, PersistenceRestoreRead, ThoughtData, Edge, Summary, SessionId, ThoughtId, BranchId, };
24
24
  export interface ServerOptions {
25
25
  maxHistorySize?: number;
26
26
  maxBranches?: number;
package/dist/lib.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"lib.d.ts","sourceRoot":"","sources":["../src/lib.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,KAAK,KAAK,CAAC,MAAM,SAAS,CAAC;AAClC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAErD,OAA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IG;IACI,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;CAc/B;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAsB,YAAY,CACjC,OAAO,GAAE,aAAkB,GACzB,OAAO,CAAC,iCAAiC,CAAC,CAE5C;AAGD,wBAAsB,gBAAgB,IAAI,OAAO,CAAC,iCAAiC,CAAC,CAsBnF"}
package/dist/lib.js CHANGED
@@ -229,6 +229,7 @@ class ToolAwareSequentialThinkingServer extends EventEmitter {
229
229
  persistenceBufferSize: cfg.persistenceBufferSize,
230
230
  persistenceFlushInterval: cfg.persistenceFlushInterval,
231
231
  persistenceMaxRetries: cfg.persistenceMaxRetries,
232
+ persistenceMaxPendingThoughtsPerSession: cfg.persistenceMaxPendingThoughtsPerSession,
232
233
  persistenceHistorySize: cfg.persistence.options?.maxHistorySize ?? ABSOLUTE_MAX_HISTORY_SIZE,
233
234
  persistBranches: cfg.persistence.options?.persistBranches ?? true,
234
235
  edgeStore,
package/dist/lib.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"lib.js","sources":["../src/lib.ts"],"sourcesContent":["// Library exports for tracelattice\n// This module contains all public API exports with NO CLI side effects.\n// For the CLI entry point, see cli.ts.\n\nimport { EventEmitter } from 'node:events';\nimport type * as v from 'valibot';\nimport type { ThoughtData } from './core/thought.js';\nimport { asSessionId } from './contracts/ids.js';\nimport type { BranchId, SessionId, ThoughtId } from './contracts/ids.js';\nimport type { Edge } from './core/graph/Edge.js';\nimport type { Summary } from './core/compression/Summary.js';\nimport type { SequentialThinkingSchema } from './schema.js';\nimport { SEQUENTIAL_THINKING_TOOL } from './schema.js';\nimport type { IDisposable } from './types/disposable.js';\nimport { getErrorMessage } from './errors.js';\nimport { assertNever } from './utils.js';\n\n// New component imports\nimport { DiscoveryCache } from './cache/DiscoveryCache.js';\nimport type { ConfigFileOptions } from './config/ConfigLoader.js';\nimport { ConfigLoader } from './config/ConfigLoader.js';\nimport { ABSOLUTE_MAX_HISTORY_SIZE, HistoryManager } from './core/HistoryManager.js';\nimport { EdgeStore } from './core/graph/EdgeStore.js';\nimport { InMemorySummaryStore } from './core/compression/InMemorySummaryStore.js';\nimport { CompressionService } from './core/compression/CompressionService.js';\nimport { InMemorySuspensionStore } from './core/tools/InMemorySuspensionStore.js';\nimport { ThoughtEvaluator } from './core/ThoughtEvaluator.js';\nimport { Calibrator } from './core/evaluator/Calibrator.js';\nimport { OutcomeRecorder } from './core/reasoning/OutcomeRecorder.js';\nimport { createReasoningStrategy } from './core/reasoning/strategies/StrategyFactory.js';\nimport { ThoughtFormatter } from './core/ThoughtFormatter.js';\nimport { ThoughtProcessor, type CallToolResult } from './core/ThoughtProcessor.js';\nimport { SessionLock } from './core/SessionLock.js';\nimport { SessionLifecycleClosedError } from './core/SessionErrors.js';\nimport { SessionLifecycleCoordinator } from './core/SessionLifecycleCoordinator.js';\nimport { Container } from './di/Container.js';\nimport { StructuredLogger } from './logger/StructuredLogger.js';\nimport { Metrics } from './metrics/metrics.impl.js';\nimport type { PersistenceBackend } from './contracts/PersistenceBackend.js';\nimport { createPersistenceBackend } from './persistence/PersistenceFactory.js';\nimport { SkillRegistry } from './registry/SkillRegistry.js';\nimport { ToolRegistry } from './registry/ToolRegistry.js';\nimport { ServerConfig } from './ServerConfig.js';\nimport { SkillWatcher } from './watchers/SkillWatcher.js';\nimport { ToolWatcher } from './watchers/ToolWatcher.js';\nimport { HttpTransport, createHttpTransport } from './transport/HttpTransport.js';\nimport type { HttpTransportOptions } from './transport/HttpTransport.js';\nimport type { TransportOptions } from './transport/BaseTransport.js';\nimport type { ITransport, TransportKind } from './contracts/transport.js';\n\nexport { HttpTransport, createHttpTransport };\nexport type {\n\tHttpTransportOptions,\n\tTransportOptions,\n\tITransport,\n\tTransportKind,\n\tPersistenceBackend,\n\tThoughtData,\n\tEdge,\n\tSummary,\n\tSessionId,\n\tThoughtId,\n\tBranchId,\n};\n\nexport interface ServerOptions {\n\tmaxHistorySize?: number;\n\tmaxBranches?: number;\n\tmaxBranchSize?: number;\n\tlogger?: StructuredLogger;\n\tenableWatcher?: boolean;\n\tconfig?: ServerConfig;\n\tfileConfig?: ConfigFileOptions;\n\tcontainer?: Container;\n\t/**\n\t * Use this backend instead of the configured persistence factory.\n\t * The caller owns and closes it; the server only drains its buffered writes.\n\t * @default undefined\n\t */\n\tpersistenceBackend?: PersistenceBackend;\n\t/**\n\t * Enable automatic tool and skill discovery on server startup.\n\t * @default true\n\t */\n\tautoDiscover?: boolean;\n\t/**\n\t * Suppress startup discovery so callers can discover through registry APIs explicitly.\n\t * @default false\n\t */\n\tlazyDiscovery?: boolean;\n\t/**\n\t * Load history from persistence on initialization\n\t * @default true\n\t */\n\tloadFromPersistence?: boolean;\n}\n\n/**\n * Server error events for event-driven error handling\n */\ninterface ServerEvents {\n\tpersistenceError: { operation: string; error: Error };\n\tdiscoveryError: { directory: string; error: Error };\n\ttransportError: { transport: string; error: Error };\n\tthoughtProcessed: { thoughtNumber: number; duration: number };\n}\n\ntype CleanupOperation = () => void | Promise<void>;\n\nasync function closeOwnedPersistence(\n\tpersistence: PersistenceBackend | null,\n\tborrowed: PersistenceBackend | null\n): Promise<void> {\n\tif (persistence !== null && persistence !== borrowed) await persistence.close();\n}\n\nfunction appendCleanupFailure(failures: unknown[], failure: unknown): void {\n\tif (failure instanceof AggregateError) {\n\t\tfailures.push(...failure.errors);\n\t\treturn;\n\t}\n\tfailures.push(failure);\n}\n\nasync function collectCleanupFailures(operations: readonly CleanupOperation[]): Promise<unknown[]> {\n\tconst failures: unknown[] = [];\n\tfor (const operation of operations) {\n\t\ttry {\n\t\t\tawait operation();\n\t\t} catch (error) {\n\t\t\tappendCleanupFailure(failures, error);\n\t\t}\n\t}\n\treturn failures;\n}\n\n/**\n * Public API contract for the tool-aware sequential thinking server.\n *\n * Extends {@link IDisposable} for resource cleanup. Concrete implementations\n * are expected to also extend Node's `EventEmitter` to support the typed\n * `emit`/`on` overloads.\n */\nexport interface IToolAwareSequentialThinkingServer extends IDisposable {\n\t/** Direct access to the history manager. */\n\treadonly history: HistoryManager;\n\n\t/** Direct access to the tool registry. */\n\treadonly tools: ToolRegistry;\n\n\t/** Direct access to the skill registry. */\n\treadonly skills: SkillRegistry;\n\n\t/** Server configuration. */\n\treadonly config: ServerConfig;\n\n\t/**\n\t * Discover skills asynchronously without blocking server startup.\n\t *\n\t * @returns The number of skills discovered\n\t */\n\tdiscoverSkillsAsync(): Promise<number>;\n\n\t/** Rescan configured tool and skill directories. */\n\trefreshDiscovery(): Promise<{ tools: number; skills: number }>;\n\n\t/**\n\t * Get all branches for one explicit thought session.\n\t *\n\t * @param sessionId - Valid thought-session identifier\n\t * @returns Map of branch IDs to thought arrays\n\t */\n\tgetBranches(sessionId: string): Record<string, ThoughtData[]>;\n\n\t/**\n\t * Process a thought through the configured pipeline.\n\t *\n\t * @param input - Validated thought input matching the schema\n\t * @returns The processing result\n\t */\n\tprocessThought(input: v.InferInput<typeof SequentialThinkingSchema>): Promise<CallToolResult>;\n\n\t/**\n\t * Export the current Prometheus metrics snapshot.\n\t */\n\tgetMetricsSnapshot(): string;\n\n\t/**\n\t * Get the DI container used by this server.\n\t * Useful for testing and advanced customizations.\n\t */\n\tgetContainer(): Container;\n\n\t/**\n\t * Stop the server and clean up watchers, suspension stores, and persistence.\n\t */\n\tstop(): Promise<void>;\n\n\t/** Awaitably reset one session and all matching auxiliary state. */\n\tresetSession(sessionId: string): Promise<void>;\n\n\t/** Awaitably reset all state from a trusted ownerless context. */\n\tresetAll(): Promise<void>;\n\n\t/**\n\t * Dispose of the server and all container services.\n\t */\n\tdispose(): Promise<void>;\n}\n\nexport class ToolAwareSequentialThinkingServer\n\textends EventEmitter\n\timplements IToolAwareSequentialThinkingServer\n{\n\t/**\n\t * Factory method to create a new server instance with async initialization.\n\t * This is the recommended way to create server instances.\n\t *\n\t * @param options - Server configuration options\n\t * @returns A Promise that resolves to a configured server instance\n\t */\n\tstatic async create(options: ServerOptions = {}): Promise<ToolAwareSequentialThinkingServer> {\n\t\tconst container = await ToolAwareSequentialThinkingServer._createContainerAsyncStatic(options);\n\t\tlet server: ToolAwareSequentialThinkingServer | undefined;\n\t\ttry {\n\t\t\tserver = new ToolAwareSequentialThinkingServer({\n\t\t\t\t...options,\n\t\t\t\tcontainer,\n\t\t\t});\n\t\t\tawait Promise.all([\n\t\t\t\tserver._skillWatcher?.ready() ?? Promise.resolve(),\n\t\t\t\tserver._toolWatcher?.ready() ?? Promise.resolve(),\n\t\t\t]);\n\n\t\t\tif (options.loadFromPersistence !== false) {\n\t\t\t\tawait server.history.loadFromPersistence();\n\t\t\t}\n\n\t\t\tif (options.autoDiscover !== false && options.lazyDiscovery !== true) {\n\t\t\t\tawait Promise.all([server.tools.discoverAsync(), server.discoverSkillsAsync()]);\n\t\t\t}\n\n\t\t\treturn server;\n\t\t} catch (error) {\n\t\t\tconst startedServer = server;\n\t\t\tconst cleanupFailures = await collectCleanupFailures(\n\t\t\t\tstartedServer\n\t\t\t\t\t? [() => startedServer.dispose()]\n\t\t\t\t\t: [\n\t\t\t\t\t\t\t() => {\n\t\t\t\t\t\t\t\tif (container.has('suspensionStore')) {\n\t\t\t\t\t\t\t\t\tcontainer.resolve('suspensionStore').stop();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t() =>\n\t\t\t\t\t\t\t\tcloseOwnedPersistence(\n\t\t\t\t\t\t\t\t\tcontainer.resolve('Persistence'),\n\t\t\t\t\t\t\t\t\toptions.persistenceBackend ?? null\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t() => container.dispose(),\n\t\t\t\t\t\t]\n\t\t\t);\n\t\t\tif (cleanupFailures.length > 0) {\n\t\t\t\tthrow new AggregateError(\n\t\t\t\t\t[error, ...cleanupFailures],\n\t\t\t\t\t'Server startup failed and cleanup also failed',\n\t\t\t\t\t{ cause: error }\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t// Type-safe event emission\n\toverride emit<K extends keyof ServerEvents>(event: K, payload: ServerEvents[K]): boolean {\n\t\treturn super.emit(event, payload);\n\t}\n\n\toverride on<K extends keyof ServerEvents>(\n\t\tevent: K,\n\t\tlistener: (payload: ServerEvents[K]) => void\n\t): this {\n\t\treturn super.on(event, listener);\n\t}\n\n\t// DI Container for managing dependencies\n\tprivate _container: Container;\n\tprivate readonly _borrowedPersistence: PersistenceBackend | null;\n\n\t// Component instances (private)\n\tprivate _logger: StructuredLogger;\n\tprivate _historyManager: HistoryManager;\n\tprivate _thoughtProcessor: ThoughtProcessor;\n\tprivate _metrics: Metrics;\n\tprivate _skillWatcher: SkillWatcher | null = null;\n\tprivate _toolWatcher: ToolWatcher | null = null;\n\tprivate _config: ServerConfig;\n\tprivate _acceptingDiscoveryRefreshes = true;\n\tprivate _refreshPromise: Promise<{ tools: number; skills: number }> | null = null;\n\tprivate _stopPromise: Promise<void> | null = null;\n\tprivate _disposePromise: Promise<void> | null = null;\n\n\t// Public manager properties (recommended API)\n\t/**\n\t * Direct access to the history manager\n\t * @example\n\t * ```typescript\n\t * server.history.getHistory('analysis-session');\n\t * await server.resetAll();\n\t * ```\n\t */\n\tpublic readonly history: HistoryManager;\n\n\t/**\n\t * Direct access to the tool registry\n\t * @example\n\t * ```typescript\n\t * server.tools.add(tool);\n\t * server.tools.get('my-tool');\n\t * ```\n\t */\n\tpublic readonly tools: ToolRegistry;\n\n\t/**\n\t * Direct access to the skill registry\n\t * @example\n\t * ```typescript\n\t * server.skills.add(skill);\n\t * server.skills.get('my-skill');\n\t * ```\n\t */\n\tpublic readonly skills: SkillRegistry;\n\n\t/**\n\t * Server configuration\n\t * @example\n\t * ```typescript\n\t * console.log(server.config.maxHistorySize);\n\t * ```\n\t */\n\tpublic readonly config: ServerConfig;\n\n\tconstructor(options: ServerOptions = {}) {\n\t\t// Use provided container or create a new one\n\t\tsuper();\n\t\tif (!options.container) {\n\t\t\tthrow new Error('Container is required. Use createServer() or provide a container.');\n\t\t}\n\t\tthis._container = options.container;\n\t\tthis._borrowedPersistence = options.persistenceBackend ?? null;\n\n\t\t// Resolve dependencies from container\n\t\tthis._logger = this._container.resolve('Logger');\n\t\tthis._historyManager = this._container.resolve('HistoryManager');\n\t\tthis._historyManager.bindShutdownOwner(() => this.stop());\n\t\tthis._thoughtProcessor = this._container.resolve('ThoughtProcessor');\n\t\tthis._metrics = this._container.resolve('Metrics');\n\t\tthis._config = this._container.resolve('Config');\n\n\t\t// Expose managers as public properties (recommended API)\n\t\tthis.history = this._historyManager;\n\n\t\t// Wire up persistence error event emitter\n\t\tthis._historyManager.setEventEmitter(this);\n\t\tthis.tools = this._container.resolve('ToolRegistry');\n\t\tthis.skills = this._container.resolve('SkillRegistry');\n\t\tthis.config = this._config;\n\n\t\t// Always include the sequential thinking tool\n\t\tthis.tools.add(SEQUENTIAL_THINKING_TOOL);\n\n\t\t// Initialize watchers if enabled\n\t\tif (options.enableWatcher) {\n\t\t\tthis._skillWatcher = new SkillWatcher(this.skills, this._logger, this.config.skillDirs);\n\t\t\tthis._toolWatcher = new ToolWatcher(this.tools, this._logger, this.config.toolDirs);\n\t\t}\n\t}\n\n\t/**\n\t * Shared core logic for container creation.\n\t * This method contains all common initialization logic between sync and async paths.\n\t */\n\tprivate static _createContainerCore(\n\t\toptions: ServerOptions,\n\t\tfileConfig: ConfigFileOptions | null,\n\t\tpersistence: PersistenceBackend | null\n\t): Container {\n\t\tconst container = new Container();\n\t\tconst metrics = new Metrics({\n\t\t\tprefix: 'sequentialthinking',\n\t\t});\n\n\t\tconst config = ToolAwareSequentialThinkingServer._resolveEffectiveConfig(options, fileConfig);\n\n\t\t// Initialize logger\n\t\tconst logger =\n\t\t\toptions.logger ??\n\t\t\tnew StructuredLogger({\n\t\t\t\tlevel: fileConfig?.logLevel ?? 'info',\n\t\t\t\tcontext: 'SequentialThinking',\n\t\t\t\tpretty: fileConfig?.prettyLog ?? true,\n\t\t\t});\n\n\t\t// Register all services in the container\n\t\tcontainer.registerInstance('Logger', logger);\n\t\tcontainer.registerInstance('Config', config);\n\t\tcontainer.registerInstance('FileConfig', fileConfig || {});\n\t\tcontainer.registerInstance('Persistence', persistence);\n\t\tcontainer.registerInstance('Metrics', metrics);\n\t\tToolAwareSequentialThinkingServer._registerDiscoveryRegistries(\n\t\t\tcontainer,\n\t\t\toptions.lazyDiscovery\n\t\t);\n\n\t\t// Register EdgeStore as a lazy singleton (always registered; flag gates writes)\n\t\tcontainer.register('EdgeStore', () => new EdgeStore());\n\n\t\t// Register SummaryStore as a lazy singleton (always registered; flag gates writes)\n\t\tcontainer.register('summaryStore', () => new InMemorySummaryStore());\n\n\t\t// Register SuspensionStore as a lazy singleton (only when toolInterleave flag is on)\n\t\tif (config.features.toolInterleave) {\n\t\t\tcontainer.register('suspensionStore', () => {\n\t\t\t\tconst store = new InMemorySuspensionStore({\n\t\t\t\t\tttlMs: config.toolInterleaveTtlMs,\n\t\t\t\t\tsweepIntervalMs: config.toolInterleaveSweepMs,\n\t\t\t\t\tlogger,\n\t\t\t\t});\n\t\t\t\tstore.start();\n\t\t\t\treturn store;\n\t\t\t});\n\t\t}\n\n\t\t// Register CompressionService as a lazy singleton (always registered; flag gates invocation)\n\t\tcontainer.register('compressionService', () => {\n\t\t\tconst historyManager = container.resolve('HistoryManager');\n\t\t\tconst edgeStore = container.resolve('EdgeStore');\n\t\t\tconst summaryStore = container.resolve('summaryStore');\n\t\t\tconst log = container.resolve('Logger');\n\t\t\treturn new CompressionService({\n\t\t\t\thistoryManager,\n\t\t\t\tedgeStore,\n\t\t\t\tsummaryStore,\n\t\t\t\tonSummaryCreated: (summary) => {\n\t\t\t\t\thistoryManager.bufferSummaries(\n\t\t\t\t\t\tsummary.sessionId,\n\t\t\t\t\t\tsummaryStore.forSession(summary.sessionId)\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t\tlogger: log,\n\t\t\t});\n\t\t});\n\n\t\t// Register ReasoningStrategy as a lazy singleton (selected via feature flag)\n\t\tcontainer.register('reasoningStrategy', () =>\n\t\t\tcreateReasoningStrategy(config.features.reasoningStrategy)\n\t\t);\n\n\t\t// Register SessionLock as a lazy singleton (always registered;\n\t\t// serializes ThoughtProcessor.process() per-session).\n\t\tcontainer.register('sessionLock', () => new SessionLock());\n\t\tcontainer.register('sessionLifecycle', () => new SessionLifecycleCoordinator());\n\n\t\tToolAwareSequentialThinkingServer._registerHistoryManager(container);\n\t\tToolAwareSequentialThinkingServer._registerThoughtPipeline(container, config);\n\n\t\treturn container;\n\t}\n\n\tprivate static _resolveEffectiveConfig(\n\t\toptions: ServerOptions,\n\t\tfileConfig: ConfigFileOptions | null\n\t): ServerConfig {\n\t\tif (options.config) return options.config;\n\t\tconst loadedOptions = new ConfigLoader().toServerConfigOptions(fileConfig ?? {});\n\t\treturn new ServerConfig({\n\t\t\t...loadedOptions,\n\t\t\tmaxHistorySize: options.maxHistorySize ?? loadedOptions.maxHistorySize,\n\t\t\tmaxBranches: options.maxBranches ?? loadedOptions.maxBranches,\n\t\t\tmaxBranchSize: options.maxBranchSize ?? loadedOptions.maxBranchSize,\n\t\t});\n\t}\n\n\tprivate static _registerDiscoveryRegistries(\n\t\tcontainer: Container,\n\t\tlazyDiscovery: ServerOptions['lazyDiscovery']\n\t): void {\n\t\tconst logger = container.resolve('Logger');\n\t\tconst config = container.resolve('Config');\n\t\tconst metrics = container.resolve('Metrics');\n\n\t\tcontainer.register(\n\t\t\t'ToolRegistry',\n\t\t\t() =>\n\t\t\t\tnew ToolRegistry({\n\t\t\t\t\tlogger,\n\t\t\t\t\tcache: config.discoveryCache\n\t\t\t\t\t\t? new DiscoveryCache({ ...config.discoveryCache, metrics })\n\t\t\t\t\t\t: undefined,\n\t\t\t\t\ttoolDirs: config.toolDirs,\n\t\t\t\t\tlazyDiscovery,\n\t\t\t\t})\n\t\t);\n\t\tcontainer.register(\n\t\t\t'SkillRegistry',\n\t\t\t() =>\n\t\t\t\tnew SkillRegistry({\n\t\t\t\t\tlogger,\n\t\t\t\t\tcache: config.discoveryCache\n\t\t\t\t\t\t? new DiscoveryCache({ ...config.discoveryCache, metrics })\n\t\t\t\t\t\t: undefined,\n\t\t\t\t\tskillDirs: config.skillDirs,\n\t\t\t\t\tlazyDiscovery,\n\t\t\t\t})\n\t\t);\n\t}\n\n\tprivate static _registerHistoryManager(container: Container): void {\n\t\t// Register HistoryManager with lazy initialization\n\t\tcontainer.register('HistoryManager', () => {\n\t\t\tconst cfg = container.resolve('Config');\n\t\t\tconst log = container.resolve('Logger');\n\t\t\tconst pers = container.resolve('Persistence');\n\t\t\tconst componentMetrics = container.resolve('Metrics');\n\t\t\tconst edgeStore = container.resolve('EdgeStore');\n\t\t\tconst summaryStore = container.resolve('summaryStore');\n\t\t\treturn new HistoryManager({\n\t\t\t\tmaxHistorySize: cfg.maxHistorySize,\n\t\t\t\tmaxBranches: cfg.maxBranches,\n\t\t\t\tmaxBranchSize: cfg.maxBranchSize,\n\t\t\t\tlogger: log,\n\t\t\t\tpersistence: pers,\n\t\t\t\tmetrics: componentMetrics,\n\t\t\t\tpersistenceBufferSize: cfg.persistenceBufferSize,\n\t\t\t\tpersistenceFlushInterval: cfg.persistenceFlushInterval,\n\t\t\t\tpersistenceMaxRetries: cfg.persistenceMaxRetries,\n\t\t\t\tpersistenceHistorySize:\n\t\t\t\t\tcfg.persistence.options?.maxHistorySize ?? ABSOLUTE_MAX_HISTORY_SIZE,\n\t\t\t\tpersistBranches: cfg.persistence.options?.persistBranches ?? true,\n\t\t\t\tedgeStore,\n\t\t\t\tsummaryStore,\n\t\t\t\tdagEdges: cfg.features.dagEdges,\n\t\t\t\tmaxSessionsPerOwner: cfg.maxSessionsPerOwner,\n\t\t\t\tsessionLock: container.resolve('sessionLock'),\n\t\t\t\tlifecycleCoordinator: container.resolve('sessionLifecycle'),\n\t\t\t\tclearSessionAuxiliaryState: (sessionId) =>\n\t\t\t\t\tcontainer.resolve('ThoughtProcessor').clearSessionAuxiliaryState(sessionId),\n\t\t\t\tclearAllAuxiliaryState: () =>\n\t\t\t\t\tcontainer.resolve('ThoughtProcessor').clearAllAuxiliaryState(),\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate static _registerThoughtPipeline(container: Container, config: ServerConfig): void {\n\t\t// Register ThoughtFormatter (can be transient)\n\t\tcontainer.registerFactory('ThoughtFormatter', () => new ThoughtFormatter());\n\n\t\t// Register OutcomeRecorder as a lazy singleton (gated by feature flag)\n\t\tcontainer.register(\n\t\t\t'outcomeRecorder',\n\t\t\t() => new OutcomeRecorder({ enabled: config.features.outcomeRecording ?? false })\n\t\t);\n\n\t\t// Register Calibrator as a lazy singleton (gated by feature flag)\n\t\tcontainer.register(\n\t\t\t'calibrator',\n\t\t\t() =>\n\t\t\t\tnew Calibrator(container.resolve('outcomeRecorder'), config.features.calibration ?? false)\n\t\t);\n\n\t\t// Register ThoughtEvaluator (stateless, transient) with injected calibrator\n\t\tcontainer.registerFactory(\n\t\t\t'ThoughtEvaluator',\n\t\t\t() => new ThoughtEvaluator(container.resolve('calibrator'))\n\t\t);\n\n\t\t// Register ThoughtProcessor\n\t\tcontainer.register('ThoughtProcessor', () => {\n\t\t\tconst history = container.resolve('HistoryManager');\n\t\t\tconst formatter = container.resolve('ThoughtFormatter');\n\t\t\tconst evaluator = container.resolve('ThoughtEvaluator');\n\t\t\tconst log = container.resolve('Logger');\n\t\t\tconst strategy = container.resolve('reasoningStrategy');\n\t\t\tconst compressionService = config.features.compression\n\t\t\t\t? container.resolve('compressionService')\n\t\t\t\t: undefined;\n\t\t\tconst suspensionStore = config.features.toolInterleave\n\t\t\t\t? container.resolve('suspensionStore')\n\t\t\t\t: undefined;\n\t\t\tconst toolRegistry = container.resolve('ToolRegistry');\n\t\t\tconst sessionLock = container.resolve('sessionLock');\n\t\t\treturn new ThoughtProcessor(\n\t\t\t\thistory,\n\t\t\t\tformatter,\n\t\t\t\tevaluator,\n\t\t\t\tlog,\n\t\t\t\tstrategy,\n\t\t\t\tcompressionService,\n\t\t\t\tsuspensionStore,\n\t\t\t\ttoolRegistry,\n\t\t\t\tconfig.features,\n\t\t\t\tsessionLock,\n\t\t\t\tcontainer.resolve('outcomeRecorder'),\n\t\t\t\tcontainer.resolve('sessionLifecycle'),\n\t\t\t\tcontainer.resolve('calibrator')\n\t\t\t);\n\t\t});\n\t}\n\n\t/**\n\t * Create and configure the DI container with async persistence initialization.\n\t * This is used internally by the static create() factory.\n\t */\n\tprivate static async _createContainerAsyncStatic(options: ServerOptions): Promise<Container> {\n\t\tlet fileConfig: ConfigFileOptions | null;\n\t\tlet config: ServerConfig;\n\t\tif (options.config) {\n\t\t\tfileConfig = options.fileConfig ?? null;\n\t\t\tconfig = options.config;\n\t\t} else {\n\t\t\tconst configLoader = new ConfigLoader();\n\t\t\tfileConfig =\n\t\t\t\toptions.fileConfig === undefined\n\t\t\t\t\t? configLoader.load()\n\t\t\t\t\t: configLoader.applyEnvironmentOverrides(options.fileConfig);\n\t\t\tconfig = ToolAwareSequentialThinkingServer._resolveEffectiveConfig(options, fileConfig);\n\t\t}\n\n\t\tlet persistence: PersistenceBackend | null = null;\n\t\ttry {\n\t\t\tpersistence =\n\t\t\t\toptions.persistenceBackend ?? (await createPersistenceBackend(config.persistence));\n\t\t\treturn ToolAwareSequentialThinkingServer._createContainerCore(\n\t\t\t\t{ ...options, config },\n\t\t\t\tfileConfig,\n\t\t\t\tpersistence\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst acquiredPersistence = persistence;\n\t\t\tconst cleanupFailures =\n\t\t\t\tacquiredPersistence === null\n\t\t\t\t\t? []\n\t\t\t\t\t: await collectCleanupFailures([\n\t\t\t\t\t\t\t() => closeOwnedPersistence(acquiredPersistence, options.persistenceBackend ?? null),\n\t\t\t\t\t\t]);\n\t\t\tif (cleanupFailures.length > 0) {\n\t\t\t\tthrow new AggregateError(\n\t\t\t\t\t[error, ...cleanupFailures],\n\t\t\t\t\t'Container construction failed and cleanup also failed',\n\t\t\t\t\t{ cause: error }\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Get the DI container used by this server\n\t * Useful for testing and advanced customizations\n\t */\n\tpublic getContainer(): Container {\n\t\treturn this._container;\n\t}\n\n\t/**\n\t * Discover skills asynchronously without blocking server startup.\n\t * This is the recommended method for skill discovery.\n\t * @returns Promise<number> - The number of skills discovered\n\t */\n\tpublic async discoverSkillsAsync(): Promise<number> {\n\t\tconst discovered = await this.skills.discoverAsync();\n\t\treturn discovered;\n\t}\n\n\t/** Rescan configured tool and skill directories. */\n\tpublic refreshDiscovery(): Promise<{ tools: number; skills: number }> {\n\t\tif (!this._acceptingDiscoveryRefreshes) {\n\t\t\treturn Promise.reject(new SessionLifecycleClosedError(undefined, 'shutting_down'));\n\t\t}\n\t\tif (this._refreshPromise !== null) return this._refreshPromise;\n\n\t\tconst refreshPromise = Promise.allSettled([\n\t\t\tthis.tools.refreshAsync(),\n\t\t\tthis.skills.refreshAsync(),\n\t\t]).then(([toolResult, skillResult]) => {\n\t\t\tif (toolResult.status === 'rejected') {\n\t\t\t\tif (skillResult.status === 'rejected') {\n\t\t\t\t\tthrow new AggregateError(\n\t\t\t\t\t\t[toolResult.reason, skillResult.reason],\n\t\t\t\t\t\t'Failed to refresh tool and skill discovery'\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthrow toolResult.reason;\n\t\t\t}\n\t\t\tif (skillResult.status === 'rejected') throw skillResult.reason;\n\t\t\treturn { tools: toolResult.value, skills: skillResult.value };\n\t\t});\n\t\tthis._refreshPromise = refreshPromise;\n\t\tconst clearRefreshPromise = (): void => {\n\t\t\tif (this._refreshPromise === refreshPromise) this._refreshPromise = null;\n\t\t};\n\t\tvoid refreshPromise.then(clearRefreshPromise, clearRefreshPromise);\n\t\treturn refreshPromise;\n\t}\n\n\t/**\n\t * Get all branches for one explicit thought session.\n\t * @param sessionId - Valid thought-session identifier\n\t * @returns Record<string, ThoughtData[]> - Map of branch IDs to thought arrays\n\t */\n\tpublic getBranches(sessionId: string): Record<BranchId, ThoughtData[]> {\n\t\treturn this._historyManager.getBranches(asSessionId(sessionId));\n\t}\n\n\t// Main processing method - delegate to ThoughtProcessor\n\tpublic async processThought(input: v.InferInput<typeof SequentialThinkingSchema>) {\n\t\tconst startTime = Date.now();\n\t\tconst result = await this._thoughtProcessor.process(input as ThoughtData);\n\t\tconst durationSeconds = (Date.now() - startTime) / 1000;\n\t\tthis._metrics.histogram('thought_processing_duration_seconds', durationSeconds, {});\n\t\treturn result;\n\t}\n\n\tpublic getMetricsSnapshot(): string {\n\t\treturn this._metrics.export();\n\t}\n\n\t/**\n\t * Stop the server and clean up watchers.\n\t * Closes persistence backend gracefully to ensure data is flushed.\n\t */\n\tpublic stop(): Promise<void> {\n\t\tthis._acceptingDiscoveryRefreshes = false;\n\t\tif (this._stopPromise) return this._stopPromise;\n\t\tconst acceptedRefresh = this._refreshPromise;\n\t\tthis._stopPromise = this._container.resolve('sessionLifecycle').shutdown(async () => {\n\t\t\tconst failures: unknown[] = [];\n\t\t\tconst [skillWatcherResult, toolWatcherResult, refreshResult] = await Promise.allSettled([\n\t\t\t\tthis._skillWatcher?.stop() ?? Promise.resolve(),\n\t\t\t\tthis._toolWatcher?.stop() ?? Promise.resolve(),\n\t\t\t\tacceptedRefresh ?? Promise.resolve(),\n\t\t\t]);\n\t\t\tfor (const result of [skillWatcherResult, toolWatcherResult]) {\n\t\t\t\tswitch (result.status) {\n\t\t\t\t\tcase 'fulfilled':\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'rejected':\n\t\t\t\t\t\tappendCleanupFailure(failures, result.reason);\n\t\t\t\t\t\tthis._logger.error('Error stopping watcher', {\n\t\t\t\t\t\t\terror: getErrorMessage(result.reason),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tassertNever(result);\n\t\t\t\t}\n\t\t\t}\n\t\t\tswitch (refreshResult.status) {\n\t\t\t\tcase 'fulfilled':\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'rejected':\n\t\t\t\t\tappendCleanupFailure(failures, refreshResult.reason);\n\t\t\t\t\tthis._logger.error('Error refreshing discovery during shutdown', {\n\t\t\t\t\t\terror: getErrorMessage(refreshResult.reason),\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tassertNever(refreshResult);\n\t\t\t}\n\n\t\t\t// Stop suspension store sweeper if registered\n\t\t\tif (this._config.features.toolInterleave && this._container.has('suspensionStore')) {\n\t\t\t\ttry {\n\t\t\t\t\tconst suspensionStore = this._container.resolve('suspensionStore');\n\t\t\t\t\tsuspensionStore.stop();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tappendCleanupFailure(failures, error);\n\t\t\t\t\tthis._logger.error('Error stopping suspension store', {\n\t\t\t\t\t\terror: getErrorMessage(error),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Flush any buffered writes before closing persistence\n\t\t\ttry {\n\t\t\t\tawait this._historyManager.shutdownWithinLifecycle();\n\t\t\t} catch (error) {\n\t\t\t\tappendCleanupFailure(failures, error);\n\t\t\t\tthis._logger.error('Error flushing write buffer during shutdown', {\n\t\t\t\t\terror: getErrorMessage(error),\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Close persistence backend if available\n\t\t\tconst persistence = this._container.resolve('Persistence');\n\t\t\tif (persistence && persistence !== this._borrowedPersistence) {\n\t\t\t\ttry {\n\t\t\t\t\tawait persistence.close();\n\t\t\t\t\tthis._logger.info('Persistence backend closed');\n\t\t\t\t} catch (error) {\n\t\t\t\t\tappendCleanupFailure(failures, error);\n\t\t\t\t\tthis._logger.error('Error closing persistence backend', {\n\t\t\t\t\t\terror: getErrorMessage(error),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (failures.length > 0) {\n\t\t\t\tthrow new AggregateError(failures, 'Failed to stop server cleanly');\n\t\t\t}\n\t\t\tthis._historyManager.clearLiveStateAfterShutdown();\n\t\t\tthis._logger.info('Server stopped, watchers cleaned up');\n\t\t});\n\t\treturn this._stopPromise;\n\t}\n\n\t/** Awaitably resets one session and matching processor-owned state. */\n\tpublic async resetSession(sessionId: string): Promise<void> {\n\t\tawait this._thoughtProcessor.resetSession(sessionId);\n\t\tthis._logger.info('Server session reset', { sessionId });\n\t}\n\n\t/** Awaitably resets all server state from a trusted ownerless context. */\n\tpublic async resetAll(): Promise<void> {\n\t\tawait this._thoughtProcessor.resetAll();\n\t\tthis._logger.info('All server sessions reset');\n\t}\n\n\t/**\n\t * Dispose of the server and all container services.\n\t * Implements the IDisposable interface.\n\t * Calls stop() for existing cleanup, then disposes the DI container.\n\t */\n\tpublic dispose(): Promise<void> {\n\t\tif (this._disposePromise) return this._disposePromise;\n\t\tthis._disposePromise = (async () => {\n\t\t\tconst failures = await collectCleanupFailures([\n\t\t\t\t() => this.stop(),\n\t\t\t\t() => this._container.dispose(),\n\t\t\t]);\n\t\t\tif (failures.length > 0) {\n\t\t\t\tthrow new AggregateError(failures, 'Failed to dispose server cleanly');\n\t\t\t}\n\t\t\tthis._logger.info('Server disposed, all resources released');\n\t\t})();\n\t\treturn this._disposePromise;\n\t}\n}\n\n/**\n * Factory function to create a new server instance with async initialization.\n *\n * This is the recommended way to create server instances, especially for testing,\n * as it allows for proper async initialization, dependency injection, and persistence.\n *\n * @param options - Server configuration options\n * @returns A Promise that resolves to a configured server instance\n *\n * @example\n * ```typescript\n * import { createServer } from '@iworkforces/tracelattice';\n *\n * // Basic usage (with async discovery and persistence)\n * const server = await createServer();\n *\n * // With custom options\n * const server = await createServer({\n * autoDiscover: false,\n * lazyDiscovery: true,\n * maxHistorySize: 500,\n * loadFromPersistence: true\n * });\n * ```\n */\nexport async function createServer(\n\toptions: ServerOptions = {}\n): Promise<ToolAwareSequentialThinkingServer> {\n\treturn ToolAwareSequentialThinkingServer.create(options);\n}\n\n// Initialize server\nexport async function initializeServer(): Promise<ToolAwareSequentialThinkingServer> {\n\t// Create logger for initialization\n\tconst configLoader = new ConfigLoader();\n\tconst fileConfig = configLoader.load() ?? {};\n\tconst config = new ServerConfig(configLoader.toServerConfigOptions(fileConfig));\n\n\tconst logger = new StructuredLogger({\n\t\tlevel: fileConfig.logLevel ?? 'info',\n\t\tcontext: 'SequentialThinking',\n\t\tpretty: fileConfig.prettyLog ?? true,\n\t});\n\n\t// Create server instance\n\tconst thinkingServer = await createServer({\n\t\tlogger,\n\t\tenableWatcher: true,\n\t\tconfig,\n\t\tfileConfig,\n\t});\n\n\tlogger.info('Server initialized successfully');\n\treturn thinkingServer;\n}\n"],"names":["closeOwnedPersistence","persistence","borrowed","appendCleanupFailure","failures","failure","AggregateError","collectCleanupFailures","operations","operation","error","ToolAwareSequentialThinkingServer","EventEmitter","options","container","server","Promise","startedServer","cleanupFailures","event","payload","listener","Error","SEQUENTIAL_THINKING_TOOL","SkillWatcher","ToolWatcher","fileConfig","Container","metrics","Metrics","config","logger","StructuredLogger","EdgeStore","InMemorySummaryStore","store","InMemorySuspensionStore","historyManager","edgeStore","summaryStore","log","CompressionService","summary","createReasoningStrategy","SessionLock","SessionLifecycleCoordinator","loadedOptions","ConfigLoader","ServerConfig","lazyDiscovery","ToolRegistry","DiscoveryCache","undefined","SkillRegistry","cfg","pers","componentMetrics","HistoryManager","ABSOLUTE_MAX_HISTORY_SIZE","sessionId","ThoughtFormatter","OutcomeRecorder","Calibrator","ThoughtEvaluator","history","formatter","evaluator","strategy","compressionService","suspensionStore","toolRegistry","sessionLock","ThoughtProcessor","configLoader","createPersistenceBackend","acquiredPersistence","discovered","SessionLifecycleClosedError","refreshPromise","toolResult","skillResult","clearRefreshPromise","asSessionId","input","startTime","Date","result","durationSeconds","acceptedRefresh","skillWatcherResult","toolWatcherResult","refreshResult","getErrorMessage","assertNever","createServer","initializeServer","thinkingServer"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6GA,eAAeA,sBACdC,WAAsC,EACtCC,QAAmC;IAEnC,IAAID,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AI,CAAC,OAAO,CAAC,IAAI,CAAC;IACnB;IAOO,UAAyB;QAC/B,IAAI,IAAI,CAAC,eAAe,EAAE,OAAO,IAAI,CAAC,eAAe;QACrD,IAAI,CAAC,eAAe,GAAI;YACvB,MAAMvD,WAAW,MAAMG,uBAAuB;gBAC7C,IAAM,IAAI,CAAC,IAAI;gBACf,IAAM,IAAI,CAAC,UAAU,CAAC,OAAO;aAC7B;YACD,IAAIH,SAAS,MAAM,GAAG,GACrB,MAAM,IAAIE,eAAeF,UAAU;YAEpC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;QACnB;QACA,OAAO,IAAI,CAAC,eAAe;IAC5B;AACD;AA2BO,eAAe0F,aACrBjF,UAAyB,CAAC,CAAC;IAE3B,OAAOF,kCAAkC,MAAM,CAACE;AACjD;AAGO,eAAekF;IAErB,MAAMtB,eAAe,IAAI1B;IACzB,MAAMrB,aAAa+C,aAAa,IAAI,MAAM,CAAC;IAC3C,MAAM3C,SAAS,IAAIkB,aAAayB,aAAa,qBAAqB,CAAC/C;IAEnE,MAAMK,SAAS,IAAIC,iBAAiB;QACnC,OAAON,WAAW,QAAQ,IAAI;QAC9B,SAAS;QACT,QAAQA,WAAW,SAAS,IAAI;IACjC;IAGA,MAAMsE,iBAAiB,MAAMF,aAAa;QACzC/D;QACA,eAAe;QACfD;QACAJ;IACD;IAEAK,OAAO,IAAI,CAAC;IACZ,OAAOiE;AACR"}
1
+ {"version":3,"file":"lib.js","sources":["../src/lib.ts"],"sourcesContent":["// Library exports for tracelattice\n// This module contains all public API exports with NO CLI side effects.\n// For the CLI entry point, see cli.ts.\n\nimport { EventEmitter } from 'node:events';\nimport type * as v from 'valibot';\nimport type { ThoughtData } from './core/thought.js';\nimport { asSessionId } from './contracts/ids.js';\nimport type { BranchId, SessionId, ThoughtId } from './contracts/ids.js';\nimport type { Edge } from './core/graph/Edge.js';\nimport type { Summary } from './core/compression/Summary.js';\nimport type { SequentialThinkingSchema } from './schema.js';\nimport { SEQUENTIAL_THINKING_TOOL } from './schema.js';\nimport type { IDisposable } from './types/disposable.js';\nimport { getErrorMessage } from './errors.js';\nimport { assertNever } from './utils.js';\n\n// New component imports\nimport { DiscoveryCache } from './cache/DiscoveryCache.js';\nimport type { ConfigFileOptions } from './config/ConfigLoader.js';\nimport { ConfigLoader } from './config/ConfigLoader.js';\nimport { ABSOLUTE_MAX_HISTORY_SIZE, HistoryManager } from './core/HistoryManager.js';\nimport { EdgeStore } from './core/graph/EdgeStore.js';\nimport { InMemorySummaryStore } from './core/compression/InMemorySummaryStore.js';\nimport { CompressionService } from './core/compression/CompressionService.js';\nimport { InMemorySuspensionStore } from './core/tools/InMemorySuspensionStore.js';\nimport { ThoughtEvaluator } from './core/ThoughtEvaluator.js';\nimport { Calibrator } from './core/evaluator/Calibrator.js';\nimport { OutcomeRecorder } from './core/reasoning/OutcomeRecorder.js';\nimport { createReasoningStrategy } from './core/reasoning/strategies/StrategyFactory.js';\nimport { ThoughtFormatter } from './core/ThoughtFormatter.js';\nimport { ThoughtProcessor, type CallToolResult } from './core/ThoughtProcessor.js';\nimport { SessionLock } from './core/SessionLock.js';\nimport { SessionLifecycleClosedError } from './core/SessionErrors.js';\nimport { SessionLifecycleCoordinator } from './core/SessionLifecycleCoordinator.js';\nimport { Container } from './di/Container.js';\nimport { StructuredLogger } from './logger/StructuredLogger.js';\nimport { Metrics } from './metrics/metrics.impl.js';\nimport type {\n\tPersistedBranchRecord,\n\tPersistedSessionRecord,\n\tPersistenceBackend,\n\tPersistenceRestoreRead,\n} from './contracts/PersistenceBackend.js';\nimport { createPersistenceBackend } from './persistence/PersistenceFactory.js';\nimport { SkillRegistry } from './registry/SkillRegistry.js';\nimport { ToolRegistry } from './registry/ToolRegistry.js';\nimport { ServerConfig } from './ServerConfig.js';\nimport { SkillWatcher } from './watchers/SkillWatcher.js';\nimport { ToolWatcher } from './watchers/ToolWatcher.js';\nimport { HttpTransport, createHttpTransport } from './transport/HttpTransport.js';\nimport type { HttpTransportOptions } from './transport/HttpTransport.js';\nimport type { TransportOptions } from './transport/BaseTransport.js';\nimport type { ITransport, TransportKind } from './contracts/transport.js';\n\nexport { HttpTransport, createHttpTransport };\nexport type {\n\tHttpTransportOptions,\n\tTransportOptions,\n\tITransport,\n\tTransportKind,\n\tPersistenceBackend,\n\tPersistedBranchRecord,\n\tPersistedSessionRecord,\n\tPersistenceRestoreRead,\n\tThoughtData,\n\tEdge,\n\tSummary,\n\tSessionId,\n\tThoughtId,\n\tBranchId,\n};\n\nexport interface ServerOptions {\n\tmaxHistorySize?: number;\n\tmaxBranches?: number;\n\tmaxBranchSize?: number;\n\tlogger?: StructuredLogger;\n\tenableWatcher?: boolean;\n\tconfig?: ServerConfig;\n\tfileConfig?: ConfigFileOptions;\n\tcontainer?: Container;\n\t/**\n\t * Use this backend instead of the configured persistence factory.\n\t * The caller owns and closes it; the server only drains its buffered writes.\n\t * @default undefined\n\t */\n\tpersistenceBackend?: PersistenceBackend;\n\t/**\n\t * Enable automatic tool and skill discovery on server startup.\n\t * @default true\n\t */\n\tautoDiscover?: boolean;\n\t/**\n\t * Suppress startup discovery so callers can discover through registry APIs explicitly.\n\t * @default false\n\t */\n\tlazyDiscovery?: boolean;\n\t/**\n\t * Load history from persistence on initialization\n\t * @default true\n\t */\n\tloadFromPersistence?: boolean;\n}\n\n/**\n * Server error events for event-driven error handling\n */\ninterface ServerEvents {\n\tpersistenceError: { operation: string; error: Error };\n\tdiscoveryError: { directory: string; error: Error };\n\ttransportError: { transport: string; error: Error };\n\tthoughtProcessed: { thoughtNumber: number; duration: number };\n}\n\ntype CleanupOperation = () => void | Promise<void>;\n\nasync function closeOwnedPersistence(\n\tpersistence: PersistenceBackend | null,\n\tborrowed: PersistenceBackend | null\n): Promise<void> {\n\tif (persistence !== null && persistence !== borrowed) await persistence.close();\n}\n\nfunction appendCleanupFailure(failures: unknown[], failure: unknown): void {\n\tif (failure instanceof AggregateError) {\n\t\tfailures.push(...failure.errors);\n\t\treturn;\n\t}\n\tfailures.push(failure);\n}\n\nasync function collectCleanupFailures(operations: readonly CleanupOperation[]): Promise<unknown[]> {\n\tconst failures: unknown[] = [];\n\tfor (const operation of operations) {\n\t\ttry {\n\t\t\tawait operation();\n\t\t} catch (error) {\n\t\t\tappendCleanupFailure(failures, error);\n\t\t}\n\t}\n\treturn failures;\n}\n\n/**\n * Public API contract for the tool-aware sequential thinking server.\n *\n * Extends {@link IDisposable} for resource cleanup. Concrete implementations\n * are expected to also extend Node's `EventEmitter` to support the typed\n * `emit`/`on` overloads.\n */\nexport interface IToolAwareSequentialThinkingServer extends IDisposable {\n\t/** Direct access to the history manager. */\n\treadonly history: HistoryManager;\n\n\t/** Direct access to the tool registry. */\n\treadonly tools: ToolRegistry;\n\n\t/** Direct access to the skill registry. */\n\treadonly skills: SkillRegistry;\n\n\t/** Server configuration. */\n\treadonly config: ServerConfig;\n\n\t/**\n\t * Discover skills asynchronously without blocking server startup.\n\t *\n\t * @returns The number of skills discovered\n\t */\n\tdiscoverSkillsAsync(): Promise<number>;\n\n\t/** Rescan configured tool and skill directories. */\n\trefreshDiscovery(): Promise<{ tools: number; skills: number }>;\n\n\t/**\n\t * Get all branches for one explicit thought session.\n\t *\n\t * @param sessionId - Valid thought-session identifier\n\t * @returns Map of branch IDs to thought arrays\n\t */\n\tgetBranches(sessionId: string): Record<string, ThoughtData[]>;\n\n\t/**\n\t * Process a thought through the configured pipeline.\n\t *\n\t * @param input - Validated thought input matching the schema\n\t * @returns The processing result\n\t */\n\tprocessThought(input: v.InferInput<typeof SequentialThinkingSchema>): Promise<CallToolResult>;\n\n\t/**\n\t * Export the current Prometheus metrics snapshot.\n\t */\n\tgetMetricsSnapshot(): string;\n\n\t/**\n\t * Get the DI container used by this server.\n\t * Useful for testing and advanced customizations.\n\t */\n\tgetContainer(): Container;\n\n\t/**\n\t * Stop the server and clean up watchers, suspension stores, and persistence.\n\t */\n\tstop(): Promise<void>;\n\n\t/** Awaitably reset one session and all matching auxiliary state. */\n\tresetSession(sessionId: string): Promise<void>;\n\n\t/** Awaitably reset all state from a trusted ownerless context. */\n\tresetAll(): Promise<void>;\n\n\t/**\n\t * Dispose of the server and all container services.\n\t */\n\tdispose(): Promise<void>;\n}\n\nexport class ToolAwareSequentialThinkingServer\n\textends EventEmitter\n\timplements IToolAwareSequentialThinkingServer\n{\n\t/**\n\t * Factory method to create a new server instance with async initialization.\n\t * This is the recommended way to create server instances.\n\t *\n\t * @param options - Server configuration options\n\t * @returns A Promise that resolves to a configured server instance\n\t */\n\tstatic async create(options: ServerOptions = {}): Promise<ToolAwareSequentialThinkingServer> {\n\t\tconst container = await ToolAwareSequentialThinkingServer._createContainerAsyncStatic(options);\n\t\tlet server: ToolAwareSequentialThinkingServer | undefined;\n\t\ttry {\n\t\t\tserver = new ToolAwareSequentialThinkingServer({\n\t\t\t\t...options,\n\t\t\t\tcontainer,\n\t\t\t});\n\t\t\tawait Promise.all([\n\t\t\t\tserver._skillWatcher?.ready() ?? Promise.resolve(),\n\t\t\t\tserver._toolWatcher?.ready() ?? Promise.resolve(),\n\t\t\t]);\n\n\t\t\tif (options.loadFromPersistence !== false) {\n\t\t\t\tawait server.history.loadFromPersistence();\n\t\t\t}\n\n\t\t\tif (options.autoDiscover !== false && options.lazyDiscovery !== true) {\n\t\t\t\tawait Promise.all([server.tools.discoverAsync(), server.discoverSkillsAsync()]);\n\t\t\t}\n\n\t\t\treturn server;\n\t\t} catch (error) {\n\t\t\tconst startedServer = server;\n\t\t\tconst cleanupFailures = await collectCleanupFailures(\n\t\t\t\tstartedServer\n\t\t\t\t\t? [() => startedServer.dispose()]\n\t\t\t\t\t: [\n\t\t\t\t\t\t\t() => {\n\t\t\t\t\t\t\t\tif (container.has('suspensionStore')) {\n\t\t\t\t\t\t\t\t\tcontainer.resolve('suspensionStore').stop();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t() =>\n\t\t\t\t\t\t\t\tcloseOwnedPersistence(\n\t\t\t\t\t\t\t\t\tcontainer.resolve('Persistence'),\n\t\t\t\t\t\t\t\t\toptions.persistenceBackend ?? null\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t() => container.dispose(),\n\t\t\t\t\t\t]\n\t\t\t);\n\t\t\tif (cleanupFailures.length > 0) {\n\t\t\t\tthrow new AggregateError(\n\t\t\t\t\t[error, ...cleanupFailures],\n\t\t\t\t\t'Server startup failed and cleanup also failed',\n\t\t\t\t\t{ cause: error }\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t// Type-safe event emission\n\toverride emit<K extends keyof ServerEvents>(event: K, payload: ServerEvents[K]): boolean {\n\t\treturn super.emit(event, payload);\n\t}\n\n\toverride on<K extends keyof ServerEvents>(\n\t\tevent: K,\n\t\tlistener: (payload: ServerEvents[K]) => void\n\t): this {\n\t\treturn super.on(event, listener);\n\t}\n\n\t// DI Container for managing dependencies\n\tprivate _container: Container;\n\tprivate readonly _borrowedPersistence: PersistenceBackend | null;\n\n\t// Component instances (private)\n\tprivate _logger: StructuredLogger;\n\tprivate _historyManager: HistoryManager;\n\tprivate _thoughtProcessor: ThoughtProcessor;\n\tprivate _metrics: Metrics;\n\tprivate _skillWatcher: SkillWatcher | null = null;\n\tprivate _toolWatcher: ToolWatcher | null = null;\n\tprivate _config: ServerConfig;\n\tprivate _acceptingDiscoveryRefreshes = true;\n\tprivate _refreshPromise: Promise<{ tools: number; skills: number }> | null = null;\n\tprivate _stopPromise: Promise<void> | null = null;\n\tprivate _disposePromise: Promise<void> | null = null;\n\n\t// Public manager properties (recommended API)\n\t/**\n\t * Direct access to the history manager\n\t * @example\n\t * ```typescript\n\t * server.history.getHistory('analysis-session');\n\t * await server.resetAll();\n\t * ```\n\t */\n\tpublic readonly history: HistoryManager;\n\n\t/**\n\t * Direct access to the tool registry\n\t * @example\n\t * ```typescript\n\t * server.tools.add(tool);\n\t * server.tools.get('my-tool');\n\t * ```\n\t */\n\tpublic readonly tools: ToolRegistry;\n\n\t/**\n\t * Direct access to the skill registry\n\t * @example\n\t * ```typescript\n\t * server.skills.add(skill);\n\t * server.skills.get('my-skill');\n\t * ```\n\t */\n\tpublic readonly skills: SkillRegistry;\n\n\t/**\n\t * Server configuration\n\t * @example\n\t * ```typescript\n\t * console.log(server.config.maxHistorySize);\n\t * ```\n\t */\n\tpublic readonly config: ServerConfig;\n\n\tconstructor(options: ServerOptions = {}) {\n\t\t// Use provided container or create a new one\n\t\tsuper();\n\t\tif (!options.container) {\n\t\t\tthrow new Error('Container is required. Use createServer() or provide a container.');\n\t\t}\n\t\tthis._container = options.container;\n\t\tthis._borrowedPersistence = options.persistenceBackend ?? null;\n\n\t\t// Resolve dependencies from container\n\t\tthis._logger = this._container.resolve('Logger');\n\t\tthis._historyManager = this._container.resolve('HistoryManager');\n\t\tthis._historyManager.bindShutdownOwner(() => this.stop());\n\t\tthis._thoughtProcessor = this._container.resolve('ThoughtProcessor');\n\t\tthis._metrics = this._container.resolve('Metrics');\n\t\tthis._config = this._container.resolve('Config');\n\n\t\t// Expose managers as public properties (recommended API)\n\t\tthis.history = this._historyManager;\n\n\t\t// Wire up persistence error event emitter\n\t\tthis._historyManager.setEventEmitter(this);\n\t\tthis.tools = this._container.resolve('ToolRegistry');\n\t\tthis.skills = this._container.resolve('SkillRegistry');\n\t\tthis.config = this._config;\n\n\t\t// Always include the sequential thinking tool\n\t\tthis.tools.add(SEQUENTIAL_THINKING_TOOL);\n\n\t\t// Initialize watchers if enabled\n\t\tif (options.enableWatcher) {\n\t\t\tthis._skillWatcher = new SkillWatcher(this.skills, this._logger, this.config.skillDirs);\n\t\t\tthis._toolWatcher = new ToolWatcher(this.tools, this._logger, this.config.toolDirs);\n\t\t}\n\t}\n\n\t/**\n\t * Shared core logic for container creation.\n\t * This method contains all common initialization logic between sync and async paths.\n\t */\n\tprivate static _createContainerCore(\n\t\toptions: ServerOptions,\n\t\tfileConfig: ConfigFileOptions | null,\n\t\tpersistence: PersistenceBackend | null\n\t): Container {\n\t\tconst container = new Container();\n\t\tconst metrics = new Metrics({\n\t\t\tprefix: 'sequentialthinking',\n\t\t});\n\n\t\tconst config = ToolAwareSequentialThinkingServer._resolveEffectiveConfig(options, fileConfig);\n\n\t\t// Initialize logger\n\t\tconst logger =\n\t\t\toptions.logger ??\n\t\t\tnew StructuredLogger({\n\t\t\t\tlevel: fileConfig?.logLevel ?? 'info',\n\t\t\t\tcontext: 'SequentialThinking',\n\t\t\t\tpretty: fileConfig?.prettyLog ?? true,\n\t\t\t});\n\n\t\t// Register all services in the container\n\t\tcontainer.registerInstance('Logger', logger);\n\t\tcontainer.registerInstance('Config', config);\n\t\tcontainer.registerInstance('FileConfig', fileConfig || {});\n\t\tcontainer.registerInstance('Persistence', persistence);\n\t\tcontainer.registerInstance('Metrics', metrics);\n\t\tToolAwareSequentialThinkingServer._registerDiscoveryRegistries(\n\t\t\tcontainer,\n\t\t\toptions.lazyDiscovery\n\t\t);\n\n\t\t// Register EdgeStore as a lazy singleton (always registered; flag gates writes)\n\t\tcontainer.register('EdgeStore', () => new EdgeStore());\n\n\t\t// Register SummaryStore as a lazy singleton (always registered; flag gates writes)\n\t\tcontainer.register('summaryStore', () => new InMemorySummaryStore());\n\n\t\t// Register SuspensionStore as a lazy singleton (only when toolInterleave flag is on)\n\t\tif (config.features.toolInterleave) {\n\t\t\tcontainer.register('suspensionStore', () => {\n\t\t\t\tconst store = new InMemorySuspensionStore({\n\t\t\t\t\tttlMs: config.toolInterleaveTtlMs,\n\t\t\t\t\tsweepIntervalMs: config.toolInterleaveSweepMs,\n\t\t\t\t\tlogger,\n\t\t\t\t});\n\t\t\t\tstore.start();\n\t\t\t\treturn store;\n\t\t\t});\n\t\t}\n\n\t\t// Register CompressionService as a lazy singleton (always registered; flag gates invocation)\n\t\tcontainer.register('compressionService', () => {\n\t\t\tconst historyManager = container.resolve('HistoryManager');\n\t\t\tconst edgeStore = container.resolve('EdgeStore');\n\t\t\tconst summaryStore = container.resolve('summaryStore');\n\t\t\tconst log = container.resolve('Logger');\n\t\t\treturn new CompressionService({\n\t\t\t\thistoryManager,\n\t\t\t\tedgeStore,\n\t\t\t\tsummaryStore,\n\t\t\t\tonSummaryCreated: (summary) => {\n\t\t\t\t\thistoryManager.bufferSummaries(\n\t\t\t\t\t\tsummary.sessionId,\n\t\t\t\t\t\tsummaryStore.forSession(summary.sessionId)\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t\tlogger: log,\n\t\t\t});\n\t\t});\n\n\t\t// Register ReasoningStrategy as a lazy singleton (selected via feature flag)\n\t\tcontainer.register('reasoningStrategy', () =>\n\t\t\tcreateReasoningStrategy(config.features.reasoningStrategy)\n\t\t);\n\n\t\t// Register SessionLock as a lazy singleton (always registered;\n\t\t// serializes ThoughtProcessor.process() per-session).\n\t\tcontainer.register('sessionLock', () => new SessionLock());\n\t\tcontainer.register('sessionLifecycle', () => new SessionLifecycleCoordinator());\n\n\t\tToolAwareSequentialThinkingServer._registerHistoryManager(container);\n\t\tToolAwareSequentialThinkingServer._registerThoughtPipeline(container, config);\n\n\t\treturn container;\n\t}\n\n\tprivate static _resolveEffectiveConfig(\n\t\toptions: ServerOptions,\n\t\tfileConfig: ConfigFileOptions | null\n\t): ServerConfig {\n\t\tif (options.config) return options.config;\n\t\tconst loadedOptions = new ConfigLoader().toServerConfigOptions(fileConfig ?? {});\n\t\treturn new ServerConfig({\n\t\t\t...loadedOptions,\n\t\t\tmaxHistorySize: options.maxHistorySize ?? loadedOptions.maxHistorySize,\n\t\t\tmaxBranches: options.maxBranches ?? loadedOptions.maxBranches,\n\t\t\tmaxBranchSize: options.maxBranchSize ?? loadedOptions.maxBranchSize,\n\t\t});\n\t}\n\n\tprivate static _registerDiscoveryRegistries(\n\t\tcontainer: Container,\n\t\tlazyDiscovery: ServerOptions['lazyDiscovery']\n\t): void {\n\t\tconst logger = container.resolve('Logger');\n\t\tconst config = container.resolve('Config');\n\t\tconst metrics = container.resolve('Metrics');\n\n\t\tcontainer.register(\n\t\t\t'ToolRegistry',\n\t\t\t() =>\n\t\t\t\tnew ToolRegistry({\n\t\t\t\t\tlogger,\n\t\t\t\t\tcache: config.discoveryCache\n\t\t\t\t\t\t? new DiscoveryCache({ ...config.discoveryCache, metrics })\n\t\t\t\t\t\t: undefined,\n\t\t\t\t\ttoolDirs: config.toolDirs,\n\t\t\t\t\tlazyDiscovery,\n\t\t\t\t})\n\t\t);\n\t\tcontainer.register(\n\t\t\t'SkillRegistry',\n\t\t\t() =>\n\t\t\t\tnew SkillRegistry({\n\t\t\t\t\tlogger,\n\t\t\t\t\tcache: config.discoveryCache\n\t\t\t\t\t\t? new DiscoveryCache({ ...config.discoveryCache, metrics })\n\t\t\t\t\t\t: undefined,\n\t\t\t\t\tskillDirs: config.skillDirs,\n\t\t\t\t\tlazyDiscovery,\n\t\t\t\t})\n\t\t);\n\t}\n\n\tprivate static _registerHistoryManager(container: Container): void {\n\t\t// Register HistoryManager with lazy initialization\n\t\tcontainer.register('HistoryManager', () => {\n\t\t\tconst cfg = container.resolve('Config');\n\t\t\tconst log = container.resolve('Logger');\n\t\t\tconst pers = container.resolve('Persistence');\n\t\t\tconst componentMetrics = container.resolve('Metrics');\n\t\t\tconst edgeStore = container.resolve('EdgeStore');\n\t\t\tconst summaryStore = container.resolve('summaryStore');\n\t\t\treturn new HistoryManager({\n\t\t\t\tmaxHistorySize: cfg.maxHistorySize,\n\t\t\t\tmaxBranches: cfg.maxBranches,\n\t\t\t\tmaxBranchSize: cfg.maxBranchSize,\n\t\t\t\tlogger: log,\n\t\t\t\tpersistence: pers,\n\t\t\t\tmetrics: componentMetrics,\n\t\t\t\tpersistenceBufferSize: cfg.persistenceBufferSize,\n\t\t\t\tpersistenceFlushInterval: cfg.persistenceFlushInterval,\n\t\t\t\tpersistenceMaxRetries: cfg.persistenceMaxRetries,\n\t\t\t\tpersistenceMaxPendingThoughtsPerSession: cfg.persistenceMaxPendingThoughtsPerSession,\n\t\t\t\tpersistenceHistorySize:\n\t\t\t\t\tcfg.persistence.options?.maxHistorySize ?? ABSOLUTE_MAX_HISTORY_SIZE,\n\t\t\t\tpersistBranches: cfg.persistence.options?.persistBranches ?? true,\n\t\t\t\tedgeStore,\n\t\t\t\tsummaryStore,\n\t\t\t\tdagEdges: cfg.features.dagEdges,\n\t\t\t\tmaxSessionsPerOwner: cfg.maxSessionsPerOwner,\n\t\t\t\tsessionLock: container.resolve('sessionLock'),\n\t\t\t\tlifecycleCoordinator: container.resolve('sessionLifecycle'),\n\t\t\t\tclearSessionAuxiliaryState: (sessionId) =>\n\t\t\t\t\tcontainer.resolve('ThoughtProcessor').clearSessionAuxiliaryState(sessionId),\n\t\t\t\tclearAllAuxiliaryState: () =>\n\t\t\t\t\tcontainer.resolve('ThoughtProcessor').clearAllAuxiliaryState(),\n\t\t\t});\n\t\t});\n\t}\n\n\tprivate static _registerThoughtPipeline(container: Container, config: ServerConfig): void {\n\t\t// Register ThoughtFormatter (can be transient)\n\t\tcontainer.registerFactory('ThoughtFormatter', () => new ThoughtFormatter());\n\n\t\t// Register OutcomeRecorder as a lazy singleton (gated by feature flag)\n\t\tcontainer.register(\n\t\t\t'outcomeRecorder',\n\t\t\t() => new OutcomeRecorder({ enabled: config.features.outcomeRecording ?? false })\n\t\t);\n\n\t\t// Register Calibrator as a lazy singleton (gated by feature flag)\n\t\tcontainer.register(\n\t\t\t'calibrator',\n\t\t\t() =>\n\t\t\t\tnew Calibrator(container.resolve('outcomeRecorder'), config.features.calibration ?? false)\n\t\t);\n\n\t\t// Register ThoughtEvaluator (stateless, transient) with injected calibrator\n\t\tcontainer.registerFactory(\n\t\t\t'ThoughtEvaluator',\n\t\t\t() => new ThoughtEvaluator(container.resolve('calibrator'))\n\t\t);\n\n\t\t// Register ThoughtProcessor\n\t\tcontainer.register('ThoughtProcessor', () => {\n\t\t\tconst history = container.resolve('HistoryManager');\n\t\t\tconst formatter = container.resolve('ThoughtFormatter');\n\t\t\tconst evaluator = container.resolve('ThoughtEvaluator');\n\t\t\tconst log = container.resolve('Logger');\n\t\t\tconst strategy = container.resolve('reasoningStrategy');\n\t\t\tconst compressionService = config.features.compression\n\t\t\t\t? container.resolve('compressionService')\n\t\t\t\t: undefined;\n\t\t\tconst suspensionStore = config.features.toolInterleave\n\t\t\t\t? container.resolve('suspensionStore')\n\t\t\t\t: undefined;\n\t\t\tconst toolRegistry = container.resolve('ToolRegistry');\n\t\t\tconst sessionLock = container.resolve('sessionLock');\n\t\t\treturn new ThoughtProcessor(\n\t\t\t\thistory,\n\t\t\t\tformatter,\n\t\t\t\tevaluator,\n\t\t\t\tlog,\n\t\t\t\tstrategy,\n\t\t\t\tcompressionService,\n\t\t\t\tsuspensionStore,\n\t\t\t\ttoolRegistry,\n\t\t\t\tconfig.features,\n\t\t\t\tsessionLock,\n\t\t\t\tcontainer.resolve('outcomeRecorder'),\n\t\t\t\tcontainer.resolve('sessionLifecycle'),\n\t\t\t\tcontainer.resolve('calibrator')\n\t\t\t);\n\t\t});\n\t}\n\n\t/**\n\t * Create and configure the DI container with async persistence initialization.\n\t * This is used internally by the static create() factory.\n\t */\n\tprivate static async _createContainerAsyncStatic(options: ServerOptions): Promise<Container> {\n\t\tlet fileConfig: ConfigFileOptions | null;\n\t\tlet config: ServerConfig;\n\t\tif (options.config) {\n\t\t\tfileConfig = options.fileConfig ?? null;\n\t\t\tconfig = options.config;\n\t\t} else {\n\t\t\tconst configLoader = new ConfigLoader();\n\t\t\tfileConfig =\n\t\t\t\toptions.fileConfig === undefined\n\t\t\t\t\t? configLoader.load()\n\t\t\t\t\t: configLoader.applyEnvironmentOverrides(options.fileConfig);\n\t\t\tconfig = ToolAwareSequentialThinkingServer._resolveEffectiveConfig(options, fileConfig);\n\t\t}\n\n\t\tlet persistence: PersistenceBackend | null = null;\n\t\ttry {\n\t\t\tpersistence =\n\t\t\t\toptions.persistenceBackend ?? (await createPersistenceBackend(config.persistence));\n\t\t\treturn ToolAwareSequentialThinkingServer._createContainerCore(\n\t\t\t\t{ ...options, config },\n\t\t\t\tfileConfig,\n\t\t\t\tpersistence\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst acquiredPersistence = persistence;\n\t\t\tconst cleanupFailures =\n\t\t\t\tacquiredPersistence === null\n\t\t\t\t\t? []\n\t\t\t\t\t: await collectCleanupFailures([\n\t\t\t\t\t\t\t() => closeOwnedPersistence(acquiredPersistence, options.persistenceBackend ?? null),\n\t\t\t\t\t\t]);\n\t\t\tif (cleanupFailures.length > 0) {\n\t\t\t\tthrow new AggregateError(\n\t\t\t\t\t[error, ...cleanupFailures],\n\t\t\t\t\t'Container construction failed and cleanup also failed',\n\t\t\t\t\t{ cause: error }\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Get the DI container used by this server\n\t * Useful for testing and advanced customizations\n\t */\n\tpublic getContainer(): Container {\n\t\treturn this._container;\n\t}\n\n\t/**\n\t * Discover skills asynchronously without blocking server startup.\n\t * This is the recommended method for skill discovery.\n\t * @returns Promise<number> - The number of skills discovered\n\t */\n\tpublic async discoverSkillsAsync(): Promise<number> {\n\t\tconst discovered = await this.skills.discoverAsync();\n\t\treturn discovered;\n\t}\n\n\t/** Rescan configured tool and skill directories. */\n\tpublic refreshDiscovery(): Promise<{ tools: number; skills: number }> {\n\t\tif (!this._acceptingDiscoveryRefreshes) {\n\t\t\treturn Promise.reject(new SessionLifecycleClosedError(undefined, 'shutting_down'));\n\t\t}\n\t\tif (this._refreshPromise !== null) return this._refreshPromise;\n\n\t\tconst refreshPromise = Promise.allSettled([\n\t\t\tthis.tools.refreshAsync(),\n\t\t\tthis.skills.refreshAsync(),\n\t\t]).then(([toolResult, skillResult]) => {\n\t\t\tif (toolResult.status === 'rejected') {\n\t\t\t\tif (skillResult.status === 'rejected') {\n\t\t\t\t\tthrow new AggregateError(\n\t\t\t\t\t\t[toolResult.reason, skillResult.reason],\n\t\t\t\t\t\t'Failed to refresh tool and skill discovery'\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthrow toolResult.reason;\n\t\t\t}\n\t\t\tif (skillResult.status === 'rejected') throw skillResult.reason;\n\t\t\treturn { tools: toolResult.value, skills: skillResult.value };\n\t\t});\n\t\tthis._refreshPromise = refreshPromise;\n\t\tconst clearRefreshPromise = (): void => {\n\t\t\tif (this._refreshPromise === refreshPromise) this._refreshPromise = null;\n\t\t};\n\t\tvoid refreshPromise.then(clearRefreshPromise, clearRefreshPromise);\n\t\treturn refreshPromise;\n\t}\n\n\t/**\n\t * Get all branches for one explicit thought session.\n\t * @param sessionId - Valid thought-session identifier\n\t * @returns Record<string, ThoughtData[]> - Map of branch IDs to thought arrays\n\t */\n\tpublic getBranches(sessionId: string): Record<BranchId, ThoughtData[]> {\n\t\treturn this._historyManager.getBranches(asSessionId(sessionId));\n\t}\n\n\t// Main processing method - delegate to ThoughtProcessor\n\tpublic async processThought(input: v.InferInput<typeof SequentialThinkingSchema>) {\n\t\tconst startTime = Date.now();\n\t\tconst result = await this._thoughtProcessor.process(input as ThoughtData);\n\t\tconst durationSeconds = (Date.now() - startTime) / 1000;\n\t\tthis._metrics.histogram('thought_processing_duration_seconds', durationSeconds, {});\n\t\treturn result;\n\t}\n\n\tpublic getMetricsSnapshot(): string {\n\t\treturn this._metrics.export();\n\t}\n\n\t/**\n\t * Stop the server and clean up watchers.\n\t * Closes persistence backend gracefully to ensure data is flushed.\n\t */\n\tpublic stop(): Promise<void> {\n\t\tthis._acceptingDiscoveryRefreshes = false;\n\t\tif (this._stopPromise) return this._stopPromise;\n\t\tconst acceptedRefresh = this._refreshPromise;\n\t\tthis._stopPromise = this._container.resolve('sessionLifecycle').shutdown(async () => {\n\t\t\tconst failures: unknown[] = [];\n\t\t\tconst [skillWatcherResult, toolWatcherResult, refreshResult] = await Promise.allSettled([\n\t\t\t\tthis._skillWatcher?.stop() ?? Promise.resolve(),\n\t\t\t\tthis._toolWatcher?.stop() ?? Promise.resolve(),\n\t\t\t\tacceptedRefresh ?? Promise.resolve(),\n\t\t\t]);\n\t\t\tfor (const result of [skillWatcherResult, toolWatcherResult]) {\n\t\t\t\tswitch (result.status) {\n\t\t\t\t\tcase 'fulfilled':\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'rejected':\n\t\t\t\t\t\tappendCleanupFailure(failures, result.reason);\n\t\t\t\t\t\tthis._logger.error('Error stopping watcher', {\n\t\t\t\t\t\t\terror: getErrorMessage(result.reason),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tassertNever(result);\n\t\t\t\t}\n\t\t\t}\n\t\t\tswitch (refreshResult.status) {\n\t\t\t\tcase 'fulfilled':\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'rejected':\n\t\t\t\t\tappendCleanupFailure(failures, refreshResult.reason);\n\t\t\t\t\tthis._logger.error('Error refreshing discovery during shutdown', {\n\t\t\t\t\t\terror: getErrorMessage(refreshResult.reason),\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tassertNever(refreshResult);\n\t\t\t}\n\n\t\t\t// Stop suspension store sweeper if registered\n\t\t\tif (this._config.features.toolInterleave && this._container.has('suspensionStore')) {\n\t\t\t\ttry {\n\t\t\t\t\tconst suspensionStore = this._container.resolve('suspensionStore');\n\t\t\t\t\tsuspensionStore.stop();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tappendCleanupFailure(failures, error);\n\t\t\t\t\tthis._logger.error('Error stopping suspension store', {\n\t\t\t\t\t\terror: getErrorMessage(error),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Flush any buffered writes before closing persistence\n\t\t\ttry {\n\t\t\t\tawait this._historyManager.shutdownWithinLifecycle();\n\t\t\t} catch (error) {\n\t\t\t\tappendCleanupFailure(failures, error);\n\t\t\t\tthis._logger.error('Error flushing write buffer during shutdown', {\n\t\t\t\t\terror: getErrorMessage(error),\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// Close persistence backend if available\n\t\t\tconst persistence = this._container.resolve('Persistence');\n\t\t\tif (persistence && persistence !== this._borrowedPersistence) {\n\t\t\t\ttry {\n\t\t\t\t\tawait persistence.close();\n\t\t\t\t\tthis._logger.info('Persistence backend closed');\n\t\t\t\t} catch (error) {\n\t\t\t\t\tappendCleanupFailure(failures, error);\n\t\t\t\t\tthis._logger.error('Error closing persistence backend', {\n\t\t\t\t\t\terror: getErrorMessage(error),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (failures.length > 0) {\n\t\t\t\tthrow new AggregateError(failures, 'Failed to stop server cleanly');\n\t\t\t}\n\t\t\tthis._historyManager.clearLiveStateAfterShutdown();\n\t\t\tthis._logger.info('Server stopped, watchers cleaned up');\n\t\t});\n\t\treturn this._stopPromise;\n\t}\n\n\t/** Awaitably resets one session and matching processor-owned state. */\n\tpublic async resetSession(sessionId: string): Promise<void> {\n\t\tawait this._thoughtProcessor.resetSession(sessionId);\n\t\tthis._logger.info('Server session reset', { sessionId });\n\t}\n\n\t/** Awaitably resets all server state from a trusted ownerless context. */\n\tpublic async resetAll(): Promise<void> {\n\t\tawait this._thoughtProcessor.resetAll();\n\t\tthis._logger.info('All server sessions reset');\n\t}\n\n\t/**\n\t * Dispose of the server and all container services.\n\t * Implements the IDisposable interface.\n\t * Calls stop() for existing cleanup, then disposes the DI container.\n\t */\n\tpublic dispose(): Promise<void> {\n\t\tif (this._disposePromise) return this._disposePromise;\n\t\tthis._disposePromise = (async () => {\n\t\t\tconst failures = await collectCleanupFailures([\n\t\t\t\t() => this.stop(),\n\t\t\t\t() => this._container.dispose(),\n\t\t\t]);\n\t\t\tif (failures.length > 0) {\n\t\t\t\tthrow new AggregateError(failures, 'Failed to dispose server cleanly');\n\t\t\t}\n\t\t\tthis._logger.info('Server disposed, all resources released');\n\t\t})();\n\t\treturn this._disposePromise;\n\t}\n}\n\n/**\n * Factory function to create a new server instance with async initialization.\n *\n * This is the recommended way to create server instances, especially for testing,\n * as it allows for proper async initialization, dependency injection, and persistence.\n *\n * @param options - Server configuration options\n * @returns A Promise that resolves to a configured server instance\n *\n * @example\n * ```typescript\n * import { createServer } from '@iworkforces/tracelattice';\n *\n * // Basic usage (with async discovery and persistence)\n * const server = await createServer();\n *\n * // With custom options\n * const server = await createServer({\n * autoDiscover: false,\n * lazyDiscovery: true,\n * maxHistorySize: 500,\n * loadFromPersistence: true\n * });\n * ```\n */\nexport async function createServer(\n\toptions: ServerOptions = {}\n): Promise<ToolAwareSequentialThinkingServer> {\n\treturn ToolAwareSequentialThinkingServer.create(options);\n}\n\n// Initialize server\nexport async function initializeServer(): Promise<ToolAwareSequentialThinkingServer> {\n\t// Create logger for initialization\n\tconst configLoader = new ConfigLoader();\n\tconst fileConfig = configLoader.load() ?? {};\n\tconst config = new ServerConfig(configLoader.toServerConfigOptions(fileConfig));\n\n\tconst logger = new StructuredLogger({\n\t\tlevel: fileConfig.logLevel ?? 'info',\n\t\tcontext: 'SequentialThinking',\n\t\tpretty: fileConfig.prettyLog ?? true,\n\t});\n\n\t// Create server instance\n\tconst thinkingServer = await createServer({\n\t\tlogger,\n\t\tenableWatcher: true,\n\t\tconfig,\n\t\tfileConfig,\n\t});\n\n\tlogger.info('Server initialized successfully');\n\treturn thinkingServer;\n}\n"],"names":["closeOwnedPersistence","persistence","borrowed","appendCleanupFailure","failures","failure","AggregateError","collectCleanupFailures","operations","operation","error","ToolAwareSequentialThinkingServer","EventEmitter","options","container","server","Promise","startedServer","cleanupFailures","event","payload","listener","Error","SEQUENTIAL_THINKING_TOOL","SkillWatcher","ToolWatcher","fileConfig","Container","metrics","Metrics","config","logger","StructuredLogger","EdgeStore","InMemorySummaryStore","store","InMemorySuspensionStore","historyManager","edgeStore","summaryStore","log","CompressionService","summary","createReasoningStrategy","SessionLock","SessionLifecycleCoordinator","loadedOptions","ConfigLoader","ServerConfig","lazyDiscovery","ToolRegistry","DiscoveryCache","undefined","SkillRegistry","cfg","pers","componentMetrics","HistoryManager","ABSOLUTE_MAX_HISTORY_SIZE","sessionId","ThoughtFormatter","OutcomeRecorder","Calibrator","ThoughtEvaluator","history","formatter","evaluator","strategy","compressionService","suspensionStore","toolRegistry","sessionLock","ThoughtProcessor","configLoader","createPersistenceBackend","acquiredPersistence","discovered","SessionLifecycleClosedError","refreshPromise","toolResult","skillResult","clearRefreshPromise","asSessionId","input","startTime","Date","result","durationSeconds","acceptedRefresh","skillWatcherResult","toolWatcherResult","refreshResult","getErrorMessage","assertNever","createServer","initializeServer","thinkingServer"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqHA,eAAeA,sBACdC,WAAsC,EACtCC,QAAmC;IAEnC,IAAID,AAAgB,SAAhBA,eAAwBA,gBAAgBC,UAAU,MAAMD,YAAY,KAAK;AAC9E;AAEA,SAASE,qBAAqBC,QAAmB,EAAEC,OAAgB;IAClE,IAAIA,mBAAmBC,gBAAgB,YACtCF,SAAS,IAAI,IAAIC,QAAQ,MAAM;IAGhCD,SAAS,IAAI,CAACC;AACf;AAEA,eAAeE,uBAAuBC,UAAuC;IAC5E,MAAMJ,WAAsB,EAAE;IAC9B,KAAK,MAAMK,aAAaD,WACvB,IAAI;QACH,MAAMC;IACP,EAAE,OAAOC,OAAO;QACfP,qBAAqBC,UAAUM;IAChC;IAED,OAAON;AACR;AA4EO,MAAMO,0CACJC;IAUR,aAAa,OAAOC,UAAyB,CAAC,CAAC,EAA8C;QAC5F,MAAMC,YAAY,MAAMH,kCAAkC,2BAA2B,CAACE;QACtF,IAAIE;QACJ,IAAI;YACHA,SAAS,IAAIJ,kCAAkC;gBAC9C,GAAGE,OAAO;gBACVC;YACD;YACA,MAAME,QAAQ,GAAG,CAAC;gBACjBD,OAAO,aAAa,EAAE,WAAWC,QAAQ,OAAO;gBAChDD,OAAO,YAAY,EAAE,WAAWC,QAAQ,OAAO;aAC/C;YAED,IAAIH,AAAgC,UAAhCA,QAAQ,mBAAmB,EAC9B,MAAME,OAAO,OAAO,CAAC,mBA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MsE,iBAAiB,MAAMF,aAAa;QACzC/D;QACA,eAAe;QACfD;QACAJ;IACD;IAEAK,OAAO,IAAI,CAAC;IACZ,OAAOiE;AACR"}
@@ -1 +1 @@
1
- {"version":3,"file":"metrics/metrics.impl.js","sources":["../../src/metrics/metrics.impl.ts"],"sourcesContent":["/**\n * Prometheus-compatible metrics collection.\n *\n * This module provides metrics collection and export in Prometheus text format.\n * Supports counters, gauges, and histograms for observability.\n *\n * @module metrics\n */\n\n/**\n * Metric types supported by the metrics collector.\n */\nexport enum MetricType {\n\t/** Counter - a cumulative metric that only increases */\n\tCounter = 'counter',\n\n\t/** Gauge - a metric that can go up and down */\n\tGauge = 'gauge',\n\n\t/** Histogram - a metric for sampling observations */\n\tHistogram = 'histogram',\n}\n\n/**\n * A collected metric with its value and labels.\n */\nexport interface Metric {\n\t/** Name of the metric */\n\tname: string;\n\n\t/** Type of metric (counter, gauge, histogram) */\n\ttype: MetricType;\n\n\t/** Current value */\n\tvalue: number;\n\n\t/** Labels for the metric */\n\tlabels: Record<string, string>;\n\n\t/** Help text describing the metric */\n\thelp?: string;\n\n\t/** Timestamp when metric was recorded (Unix epoch) */\n\ttimestamp?: number;\n}\n\ninterface HistogramMetric {\n\tname: string;\n\tlabels: Record<string, string>;\n\tsum: number;\n\tcount: number;\n\tboundaries: readonly number[];\n\tbuckets: Map<number, number>;\n}\n\n/**\n * Histogram bucket boundaries for latency tracking.\n */\nconst DEFAULT_BUCKETS = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10];\n\n/**\n * Prometheus-compatible metrics collector.\n *\n * Collects and exports metrics in Prometheus text format for scraping.\n * Thread-safe and supports counters, gauges, and histograms.\n *\n * @remarks\n * **Metric Types:**\n * - **Counter**: Cumulative value that only increases (e.g., request counts)\n * - **Gauge**: Value that can go up or down (e.g., active connections)\n * - **Histogram**: Sampling observations (e.g., request latency)\n *\n * **Labels:**\n * Metrics can have labels for dimensional data:\n * ```typescript\n * counter('http_requests_total', { method: 'GET', status: '200' });\n * ```\n *\n * **Export Format:**\n * Metrics are exported in Prometheus text format:\n * ```\n * # HELP http_requests_total Total HTTP requests\n * # TYPE http_requests_total counter\n * http_requests_total{method=\"GET\",status=\"200\"} 1234\n * ```\n *\n * @example\n * ```typescript\n * const metrics = new Metrics({ prefix: 'mcp_server' });\n *\n * // Count requests\n * metrics.counter('requests_total', { method: 'GET' }).inc();\n *\n * // Track active connections\n * const activeConnections = metrics.gauge('active_connections');\n * activeConnections.set(5);\n * activeConnections.dec();\n *\n * // Record latency\n * metrics.histogram('request_duration_seconds').observe(0.023);\n *\n * // Export for Prometheus\n * const prometheusText = metrics.export();\n * ```\n */\nexport class Metrics {\n\t/** Metrics storage indexed by name and label hash */\n\tprivate _metrics: Map<string, Metric>;\n\n\t/** Histogram samples */\n\tprivate _histograms: Map<string, HistogramMetric>;\n\n\t/** Prefix for all metric names */\n\tprivate _prefix: string;\n\n\t/** Default labels to apply to all metrics */\n\tprivate _defaultLabels: Record<string, string>;\n\n\t/** Counter for metric collection operations */\n\tprivate _operationsCounter: number = 0;\n\n\t/**\n\t * Creates a new Metrics instance.\n\t *\n\t * @param options - Configuration options\n\t *\n\t * @example\n\t * ```typescript\n\t * const metrics = new Metrics({ prefix: 'mcp_server' });\n\t * ```\n\t */\n\tconstructor(options: { prefix?: string; defaultLabels?: Record<string, string> } = {}) {\n\t\tthis._metrics = new Map();\n\t\tthis._histograms = new Map();\n\t\tthis._prefix = options.prefix ?? '';\n\t\tthis._defaultLabels = { ...options.defaultLabels };\n\t}\n\n\t/**\n\t * Creates a counter metric.\n\t *\n\t * @param name - Metric name\n\t * @param value - Increment value (default: 1)\n\t * @param labels - Optional labels\n\t * @param help - Help text\n\t *\n\t * @example\n\t * ```typescript\n\t * metrics.counter('requests_total', 1, { method: 'GET' });\n\t * metrics.counter('errors_total', 1, { type: 'timeout' });\n\t * ```\n\t */\n\tcounter(name: string, value = 1, labels: Record<string, string> = {}, help?: string): void {\n\t\tconst fullName = this._fullName(name);\n\t\tconst allLabels = { ...this._defaultLabels, ...labels };\n\t\tconst key = this._metricKey(fullName, allLabels);\n\t\tconst existing = this._metrics.get(key);\n\n\t\tif (existing) {\n\t\t\texisting.value += value;\n\t\t\tif (help && !existing.help) {\n\t\t\t\texisting.help = help;\n\t\t\t}\n\t\t} else {\n\t\t\tthis._metrics.set(key, {\n\t\t\t\tname: fullName,\n\t\t\t\ttype: MetricType.Counter,\n\t\t\t\tvalue,\n\t\t\t\tlabels: { ...allLabels },\n\t\t\t\thelp,\n\t\t\t});\n\t\t}\n\t\tthis._operationsCounter++;\n\t}\n\n\t/**\n\t * Creates a gauge metric.\n\t *\n\t * @param name - Metric name\n\t * @param value - Current value\n\t * @param labels - Optional labels\n\t * @param help - Help text\n\t *\n\t * @example\n\t * ```typescript\n\t * const activeConnections = metrics.gauge('active_connections');\n\t * activeConnections.set(5);\n\t * activeConnections.dec();\n\t * ```\n\t */\n\tgauge(name: string, value: number, labels: Record<string, string> = {}, help?: string): void {\n\t\tconst fullName = this._fullName(name);\n\t\tconst allLabels = { ...this._defaultLabels, ...labels };\n\t\tconst key = this._metricKey(fullName, allLabels);\n\t\tconst existing = this._metrics.get(key);\n\t\tthis._metrics.set(key, {\n\t\t\tname: fullName,\n\t\t\ttype: MetricType.Gauge,\n\t\t\tvalue,\n\t\t\tlabels: { ...allLabels },\n\t\t\thelp: help ?? existing?.help,\n\t\t});\n\t\tthis._operationsCounter++;\n\t}\n\n\t/**\n\t * Records a histogram observation.\n\t *\n\t * @param name - Histogram name\n\t * @param value - Observed value\n\t * @param labels - Optional labels\n\t * @param help - Help text\n\t * @param buckets - Custom bucket boundaries\n\t *\n\t * @example\n\t * ```typescript\n\t * metrics.histogram('request_duration_seconds').observe(0.023);\n\t * metrics.histogram('thought_processing_ms').observe(45);\n\t * ```\n\t */\n\thistogram(\n\t\tname: string,\n\t\tvalue: number,\n\t\tlabels: Record<string, string> = {},\n\t\tbuckets = DEFAULT_BUCKETS\n\t): void {\n\t\tconst fullName = this._fullName(name);\n\t\tconst allLabels = { ...this._defaultLabels, ...labels };\n\t\tconst key = this._metricKey(fullName, allLabels);\n\t\tconst histogram = this._histograms.get(key);\n\t\tlet previousBoundary = -Infinity;\n\t\tfor (const boundary of buckets) {\n\t\t\tif (!Number.isFinite(boundary) || boundary <= previousBoundary) {\n\t\t\t\tthrow new RangeError('Histogram boundaries must be finite and strictly increasing');\n\t\t\t}\n\t\t\tpreviousBoundary = boundary;\n\t\t}\n\t\tif (\n\t\t\thistogram &&\n\t\t\t(histogram.boundaries.length !== buckets.length ||\n\t\t\t\thistogram.boundaries.some((boundary, index) => boundary !== buckets[index]))\n\t\t) {\n\t\t\tthrow new RangeError('Histogram bucket layout differs from the existing series');\n\t\t}\n\n\t\tif (histogram) {\n\t\t\thistogram.sum += value;\n\t\t\thistogram.count += 1;\n\t\t\tfor (const boundary of histogram.boundaries) {\n\t\t\t\tif (value <= boundary) {\n\t\t\t\t\thistogram.buckets.set(boundary, (histogram.buckets.get(boundary) ?? 0) + 1);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tconst histogramData = {\n\t\t\t\tname: fullName,\n\t\t\t\tlabels: { ...allLabels },\n\t\t\t\tsum: value,\n\t\t\t\tcount: 1,\n\t\t\t\tboundaries: [...buckets],\n\t\t\t\tbuckets: new Map<number, number>(),\n\t\t\t};\n\t\t\tfor (const boundary of buckets) {\n\t\t\t\thistogramData.buckets.set(boundary, value <= boundary ? 1 : 0);\n\t\t\t}\n\t\t\tthis._histograms.set(key, histogramData);\n\t\t}\n\t\tthis._operationsCounter++;\n\t}\n\n\t/**\n\t * Gets the current value of a metric.\n\t *\n\t * @param name - Metric name\n\t * @param labels - Labels\n\t * @returns Current value or undefined if not found\n\t *\n\t * @example\n\t * ```typescript\n\t * const count = metrics.get('requests_total', { method: 'GET' });\n\t * ```\n\t */\n\tget(name: string, labels: Record<string, string> = {}): number | undefined {\n\t\tconst fullName = this._fullName(name);\n\t\tconst allLabels = { ...this._defaultLabels, ...labels };\n\t\tconst key = this._metricKey(fullName, allLabels);\n\t\treturn this._metrics.get(key)?.value;\n\t}\n\n\t/**\n\t * Increments a counter by 1.\n\t *\n\t * @param name - Metric name\n\t * @param labels - Optional labels\n\t *\n\t * @example\n\t * ```typescript\n\t * metrics.inc('requests_total', { method: 'GET' });\n\t * ```\n\t */\n\tinc(name: string, labels?: Record<string, string>): void {\n\t\tthis.counter(name, 1, labels);\n\t}\n\n\t/**\n\t * Decrements a gauge by 1.\n\t *\n\t * @param name - Metric name\n\t * @param labels - Optional labels\n\t *\n\t * @example\n\t * ```typescript\n\t * metrics.dec('active_connections');\n\t * ```\n\t */\n\tdec(name: string, labels?: Record<string, string>): void {\n\t\tconst value = this.get(name, labels) ?? 0;\n\t\tthis.gauge(name, value - 1, labels);\n\t}\n\n\t/**\n\t * Resets all metrics to zero.\n\t * Useful for testing or on server restart.\n\t *\n\t * @example\n\t * ```typescript\n\t * metrics.reset();\n\t * ```\n\t */\n\treset(): void {\n\t\tthis._metrics.clear();\n\t\tthis._histograms.clear();\n\t\tthis._operationsCounter = 0;\n\t}\n\n\t/**\n\t * Gets the number of metric operations performed.\n\t * Useful for testing.\n\t *\n\t * @returns Operation count\n\t *\n\t * @example\n\t * ```typescript\n\t * const ops = metrics.getOperationCount();\n\t * ```\n\t */\n\tgetOperationCount(): number {\n\t\treturn this._operationsCounter;\n\t}\n\n\t/**\n\t * Exports metrics in Prometheus text format.\n\t *\n\t * @returns Prometheus text format string\n\t *\n\t * @example\n\t * ```typescript\n\t * const prometheusText = metrics.export();\n\t * console.log(prometheusText);\n\t * // Output:\n\t * // # HELP http_requests_total Total HTTP requests\n\t * // # TYPE http_requests_total counter\n\t * // http_requests_total{method=\"GET\",status=\"200\"} 1234\n\t * ```\n\t */\n\texport(): string {\n\t\tconst lines: string[] = [];\n\n\t\tconst metrics = Array.from(this._metrics.values());\n\t\tconst histograms = Array.from(this._histograms.values());\n\n\t\tconst helpEntries = new Map<string, string>();\n\t\tconst typeEntries = new Map<string, MetricType>();\n\n\t\tfor (const metric of metrics) {\n\t\t\tif (!helpEntries.has(metric.name)) {\n\t\t\t\tconst helpText = metric.help ?? `${metric.name} metric`;\n\t\t\t\tlines.push(\n\t\t\t\t\t`# HELP ${metric.name} ${helpText.replaceAll('\\\\', '\\\\\\\\').replaceAll('\\n', '\\\\n')}`\n\t\t\t\t);\n\t\t\t\thelpEntries.set(metric.name, helpText);\n\t\t\t}\n\t\t\tif (!typeEntries.has(metric.name)) {\n\t\t\t\tlines.push(`# TYPE ${metric.name} ${metric.type}`);\n\t\t\t\ttypeEntries.set(metric.name, metric.type);\n\t\t\t}\n\n\t\t\tconst labelStr = this._formatLabels(metric.labels);\n\t\t\tlines.push(`${metric.name}{${labelStr}} ${metric.value}`);\n\t\t}\n\n\t\tfor (const histogram of histograms) {\n\t\t\tconst { name: fullName, labels } = histogram;\n\t\t\tif (histogram.count > 0) {\n\t\t\t\tif (!typeEntries.has(fullName)) {\n\t\t\t\t\tlines.push(`# TYPE ${fullName} histogram`);\n\t\t\t\t\ttypeEntries.set(fullName, MetricType.Histogram);\n\t\t\t\t}\n\n\t\t\t\tconst labelStr = this._formatLabels(labels);\n\t\t\t\tconst formatMetricLine = (suffix: string, value: number): string => {\n\t\t\t\t\tif (labelStr.length === 0) {\n\t\t\t\t\t\treturn `${fullName}${suffix} ${value}`;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn `${fullName}${suffix}{${labelStr}} ${value}`;\n\t\t\t\t};\n\n\t\t\t\tlines.push(formatMetricLine('_sum', histogram.sum));\n\t\t\t\tlines.push(formatMetricLine('_count', histogram.count));\n\n\t\t\t\tfor (const boundary of histogram.boundaries) {\n\t\t\t\t\tconst count = histogram.buckets.get(boundary);\n\t\t\t\t\tconst boundaryLabel = String(boundary);\n\t\t\t\t\tconst boundaryLabelStr = this._formatLabels({ le: boundaryLabel });\n\t\t\t\t\tconst bucketLabels =\n\t\t\t\t\t\tlabelStr.length === 0 ? boundaryLabelStr : `${labelStr},${boundaryLabelStr}`;\n\t\t\t\t\tlines.push(`${fullName}_bucket{${bucketLabels}} ${count}`);\n\t\t\t\t}\n\t\t\t\tconst infLabelStr = this._formatLabels({ le: '+Inf' });\n\t\t\t\tconst infLabels = labelStr.length === 0 ? infLabelStr : `${labelStr},${infLabelStr}`;\n\t\t\t\tlines.push(`${fullName}_bucket{${infLabels}} ${histogram.count}`);\n\t\t\t}\n\t\t}\n\n\t\treturn lines.join('\\n');\n\t}\n\n\t/**\n\t * Gets metric name with prefix.\n\t * @param name - Metric name\n\t * @returns Full metric name\n\t * @private\n\t */\n\tprivate _fullName(name: string): string {\n\t\tif (!this._prefix) {\n\t\t\treturn name;\n\t\t}\n\n\t\tconst prefix = `${this._prefix}_`;\n\t\treturn name.startsWith(prefix) ? name : `${prefix}${name}`;\n\t}\n\n\t/**\n\t * Creates a unique key for a metric with labels.\n\t * @param name - Metric name\n\t * @param labels - Labels\n\t * @returns Unique key\n\t * @private\n\t */\n\tprivate _metricKey(name: string, labels: Record<string, string>): string {\n\t\tconst sortedLabels = Object.entries(labels).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n\t\treturn JSON.stringify([name, sortedLabels]);\n\t}\n\n\tprivate _formatLabels(labels: Record<string, string>): string {\n\t\treturn Object.entries(labels)\n\t\t\t.map(([key, value]) => `${key}=\"${this._escapeLabelValue(value)}\"`)\n\t\t\t.join(',');\n\t}\n\n\tprivate _escapeLabelValue(value: string): string {\n\t\treturn value.replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\\\"').replaceAll('\\n', '\\\\n');\n\t}\n}\n"],"names":["MetricType","DEFAULT_BUCKETS","Metrics","options","Map","name","value","labels","help","fullName","allLabels","key","existing","buckets","histogram","previousBoundary","boundary","Number","RangeError","index","histogramData","lines","metrics","Array","histograms","helpEntries","typeEntries","metric","helpText","labelStr","formatMetricLine","suffix","count","boundaryLabel","String","boundaryLabelStr","bucketLabels","infLabelStr","inf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AAO,OAAO,CAAClC,QAAQ,IAAI,CAAC,CAAC,CAACmC,EAAE,EAAE,CAACC,EAAE,GAAMD,IAAIC,IAAI,KAAKD,IAAIC,IAAI,IAAI;QACzF,OAAOC,KAAK,SAAS,CAAC;YAACvC;YAAMmC;SAAa;IAC3C;IAEQ,cAAcjC,MAA8B,EAAU;QAC7D,OAAOkC,OAAO,OAAO,CAAClC,QACpB,GAAG,CAAC,CAAC,CAACI,KAAKL,MAAM,GAAK,GAAGK,IAAI,EAAE,EAAE,IAAI,CAAC,iBAAiB,CAACL,OAAO,CAAC,CAAC,EACjE,IAAI,CAAC;IACR;IAEQ,kBAAkBA,KAAa,EAAU;QAChD,OAAOA,MAAM,UAAU,CAAC,MAAM,QAAQ,UAAU,CAAC,KAAK,OAAO,UAAU,CAAC,MAAM;IAC/E;AACD"}
1
+ {"version":3,"file":"metrics/metrics.impl.js","sources":["../../src/metrics/metrics.impl.ts"],"sourcesContent":["/**\n * Prometheus-compatible metrics collection.\n *\n * This module provides metrics collection and export in Prometheus text format.\n * Supports counters, gauges, and histograms for observability.\n *\n * @module metrics\n */\n\n/**\n * Metric types supported by the metrics collector.\n */\nexport enum MetricType {\n\t/** Counter - a cumulative metric that only increases */\n\tCounter = 'counter',\n\n\t/** Gauge - a metric that can go up and down */\n\tGauge = 'gauge',\n\n\t/** Histogram - a metric for sampling observations */\n\tHistogram = 'histogram',\n}\n\n/**\n * A collected metric with its value and labels.\n */\nexport interface Metric {\n\t/** Name of the metric */\n\tname: string;\n\n\t/** Type of metric (counter, gauge, histogram) */\n\ttype: MetricType;\n\n\t/** Current value */\n\tvalue: number;\n\n\t/** Labels for the metric */\n\tlabels: Record<string, string>;\n\n\t/** Help text describing the metric */\n\thelp?: string;\n\n\t/** Timestamp when metric was recorded (Unix epoch) */\n\ttimestamp?: number;\n}\n\ninterface HistogramMetric {\n\tname: string;\n\tlabels: Record<string, string>;\n\tsum: number;\n\tcount: number;\n\tboundaries: readonly number[];\n\tbuckets: Map<number, number>;\n}\n\n/**\n * Histogram bucket boundaries for latency tracking.\n */\nconst DEFAULT_BUCKETS = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10];\n\n/**\n * Prometheus-compatible metrics collector.\n *\n * Collects and exports metrics in Prometheus text format for scraping.\n * Thread-safe and supports counters, gauges, and histograms.\n *\n * @remarks\n * **Metric Types:**\n * - **Counter**: Cumulative value that only increases (e.g., request counts)\n * - **Gauge**: Value that can go up or down (e.g., active connections)\n * - **Histogram**: Sampling observations (e.g., request latency)\n *\n * **Labels:**\n * Metrics can have labels for dimensional data:\n * ```typescript\n * counter('http_requests_total', { method: 'GET', status: '200' });\n * ```\n *\n * **Export Format:**\n * Metrics are exported in Prometheus text format:\n * ```\n * # HELP http_requests_total Total HTTP requests\n * # TYPE http_requests_total counter\n * http_requests_total{method=\"GET\",status=\"200\"} 1234\n * ```\n *\n * @example\n * ```typescript\n * const metrics = new Metrics({ prefix: 'mcp_server' });\n *\n * // Count requests\n * metrics.counter('requests_total', { method: 'GET' }).inc();\n *\n * // Track active connections\n * const activeConnections = metrics.gauge('active_connections');\n * activeConnections.set(5);\n * activeConnections.dec();\n *\n * // Record latency\n * metrics.histogram('request_duration_seconds').observe(0.023);\n *\n * // Export for Prometheus\n * const prometheusText = metrics.export();\n * ```\n */\nexport class Metrics {\n\t/** Metrics storage indexed by name and label hash */\n\tprivate _metrics: Map<string, Metric>;\n\n\t/** Histogram samples */\n\tprivate _histograms: Map<string, HistogramMetric>;\n\n\t/** Prefix for all metric names */\n\tprivate _prefix: string;\n\n\t/** Default labels to apply to all metrics */\n\tprivate _defaultLabels: Record<string, string>;\n\n\t/** Counter for metric collection operations */\n\tprivate _operationsCounter: number = 0;\n\n\t/**\n\t * Creates a new Metrics instance.\n\t *\n\t * @param options - Configuration options\n\t *\n\t * @example\n\t * ```typescript\n\t * const metrics = new Metrics({ prefix: 'mcp_server' });\n\t * ```\n\t */\n\tconstructor(options: { prefix?: string; defaultLabels?: Record<string, string> } = {}) {\n\t\tthis._metrics = new Map();\n\t\tthis._histograms = new Map();\n\t\tthis._prefix = options.prefix ?? '';\n\t\tthis._defaultLabels = { ...options.defaultLabels };\n\t}\n\n\t/**\n\t * Creates a counter metric.\n\t *\n\t * @param name - Metric name\n\t * @param value - Increment value (default: 1)\n\t * @param labels - Optional labels\n\t * @param help - Help text\n\t *\n\t * @example\n\t * ```typescript\n\t * metrics.counter('requests_total', 1, { method: 'GET' });\n\t * metrics.counter('errors_total', 1, { type: 'timeout' });\n\t * ```\n\t */\n\tcounter(name: string, value = 1, labels: Record<string, string> = {}, help?: string): void {\n\t\tconst fullName = this._fullName(name);\n\t\tconst allLabels = { ...this._defaultLabels, ...labels };\n\t\tconst key = this._metricKey(fullName, allLabels);\n\t\tconst existing = this._metrics.get(key);\n\n\t\tif (existing) {\n\t\t\texisting.value += value;\n\t\t\tif (help && !existing.help) {\n\t\t\t\texisting.help = help;\n\t\t\t}\n\t\t} else {\n\t\t\tthis._metrics.set(key, {\n\t\t\t\tname: fullName,\n\t\t\t\ttype: MetricType.Counter,\n\t\t\t\tvalue,\n\t\t\t\tlabels: { ...allLabels },\n\t\t\t\thelp,\n\t\t\t});\n\t\t}\n\t\tthis._operationsCounter++;\n\t}\n\n\t/**\n\t * Creates a gauge metric.\n\t *\n\t * @param name - Metric name\n\t * @param value - Current value\n\t * @param labels - Optional labels\n\t * @param help - Help text\n\t *\n\t * @example\n\t * ```typescript\n\t * const activeConnections = metrics.gauge('active_connections');\n\t * activeConnections.set(5);\n\t * activeConnections.dec();\n\t * ```\n\t */\n\tgauge(name: string, value: number, labels: Record<string, string> = {}, help?: string): void {\n\t\tconst fullName = this._fullName(name);\n\t\tconst allLabels = { ...this._defaultLabels, ...labels };\n\t\tconst key = this._metricKey(fullName, allLabels);\n\t\tconst existing = this._metrics.get(key);\n\t\tthis._metrics.set(key, {\n\t\t\tname: fullName,\n\t\t\ttype: MetricType.Gauge,\n\t\t\tvalue,\n\t\t\tlabels: { ...allLabels },\n\t\t\thelp: help ?? existing?.help,\n\t\t});\n\t\tthis._operationsCounter++;\n\t}\n\n\t/**\n\t * Records a histogram observation.\n\t *\n\t * @param name - Histogram name\n\t * @param value - Observed value\n\t * @param labels - Optional labels\n\t * @param help - Help text\n\t * @param buckets - Custom bucket boundaries\n\t *\n\t * @example\n\t * ```typescript\n\t * metrics.histogram('request_duration_seconds').observe(0.023);\n\t * metrics.histogram('thought_processing_ms').observe(45);\n\t * ```\n\t */\n\thistogram(\n\t\tname: string,\n\t\tvalue: number,\n\t\tlabels: Record<string, string> = {},\n\t\tbuckets = DEFAULT_BUCKETS\n\t): void {\n\t\tconst fullName = this._fullName(name);\n\t\tconst allLabels = { ...this._defaultLabels, ...labels };\n\t\tconst key = this._metricKey(fullName, allLabels);\n\t\tconst histogram = this._histograms.get(key);\n\t\tlet previousBoundary = -Infinity;\n\t\tfor (const boundary of buckets) {\n\t\t\tif (!Number.isFinite(boundary) || boundary <= previousBoundary) {\n\t\t\t\tthrow new RangeError('Histogram boundaries must be finite and strictly increasing');\n\t\t\t}\n\t\t\tpreviousBoundary = boundary;\n\t\t}\n\t\tif (\n\t\t\thistogram &&\n\t\t\t(histogram.boundaries.length !== buckets.length ||\n\t\t\t\thistogram.boundaries.some((boundary, index) => boundary !== buckets[index]))\n\t\t) {\n\t\t\tthrow new RangeError('Histogram bucket layout differs from the existing series');\n\t\t}\n\n\t\tif (histogram) {\n\t\t\thistogram.sum += value;\n\t\t\thistogram.count += 1;\n\t\t\tfor (const boundary of histogram.boundaries) {\n\t\t\t\tif (value <= boundary) {\n\t\t\t\t\thistogram.buckets.set(boundary, (histogram.buckets.get(boundary) ?? 0) + 1);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tconst histogramData = {\n\t\t\t\tname: fullName,\n\t\t\t\tlabels: { ...allLabels },\n\t\t\t\tsum: value,\n\t\t\t\tcount: 1,\n\t\t\t\tboundaries: [...buckets],\n\t\t\t\tbuckets: new Map<number, number>(),\n\t\t\t};\n\t\t\tfor (const boundary of buckets) {\n\t\t\t\thistogramData.buckets.set(boundary, value <= boundary ? 1 : 0);\n\t\t\t}\n\t\t\tthis._histograms.set(key, histogramData);\n\t\t}\n\t\tthis._operationsCounter++;\n\t}\n\n\t/**\n\t * Gets the current value of a metric.\n\t *\n\t * @param name - Metric name\n\t * @param labels - Labels\n\t * @returns Current value or undefined if not found\n\t *\n\t * @example\n\t * ```typescript\n\t * const count = metrics.get('requests_total', { method: 'GET' });\n\t * ```\n\t */\n\tget(name: string, labels: Record<string, string> = {}): number | undefined {\n\t\tconst fullName = this._fullName(name);\n\t\tconst allLabels = { ...this._defaultLabels, ...labels };\n\t\tconst key = this._metricKey(fullName, allLabels);\n\t\treturn this._metrics.get(key)?.value;\n\t}\n\n\t/**\n\t * Increments a counter by 1.\n\t *\n\t * @param name - Metric name\n\t * @param labels - Optional labels\n\t *\n\t * @example\n\t * ```typescript\n\t * metrics.inc('requests_total', { method: 'GET' });\n\t * ```\n\t */\n\tinc(name: string, labels?: Record<string, string>): void {\n\t\tthis.counter(name, 1, labels);\n\t}\n\n\t/**\n\t * Decrements a gauge by 1.\n\t *\n\t * @param name - Metric name\n\t * @param labels - Optional labels\n\t *\n\t * @example\n\t * ```typescript\n\t * metrics.dec('active_connections');\n\t * ```\n\t */\n\tdec(name: string, labels?: Record<string, string>): void {\n\t\tconst value = this.get(name, labels) ?? 0;\n\t\tthis.gauge(name, value - 1, labels);\n\t}\n\n\t/**\n\t * Resets all metrics to zero.\n\t * Useful for testing or on server restart.\n\t *\n\t * @example\n\t * ```typescript\n\t * metrics.reset();\n\t * ```\n\t */\n\treset(): void {\n\t\tthis._metrics.clear();\n\t\tthis._histograms.clear();\n\t\tthis._operationsCounter = 0;\n\t}\n\n\t/**\n\t * Gets the number of metric operations performed.\n\t * Useful for testing.\n\t *\n\t * @returns Operation count\n\t *\n\t * @example\n\t * ```typescript\n\t * const ops = metrics.getOperationCount();\n\t * ```\n\t */\n\tgetOperationCount(): number {\n\t\treturn this._operationsCounter;\n\t}\n\n\t/**\n\t * Exports metrics in Prometheus text format.\n\t *\n\t * @returns Prometheus text format string\n\t *\n\t * @example\n\t * ```typescript\n\t * const prometheusText = metrics.export();\n\t * console.log(prometheusText);\n\t * // Output:\n\t * // # HELP http_requests_total Total HTTP requests\n\t * // # TYPE http_requests_total counter\n\t * // http_requests_total{method=\"GET\",status=\"200\"} 1234\n\t * ```\n\t */\n\texport(): string {\n\t\tconst lines: string[] = [];\n\n\t\tconst metrics = Array.from(this._metrics.values());\n\t\tconst histograms = Array.from(this._histograms.values());\n\n\t\tconst helpEntries = new Map<string, string>();\n\t\tconst typeEntries = new Map<string, MetricType>();\n\n\t\tfor (const metric of metrics) {\n\t\t\tif (!helpEntries.has(metric.name)) {\n\t\t\t\tconst helpText = metric.help ?? `${metric.name} metric`;\n\t\t\t\tlines.push(\n\t\t\t\t\t`# HELP ${metric.name} ${helpText.replaceAll('\\\\', '\\\\\\\\').replaceAll('\\n', '\\\\n')}`\n\t\t\t\t);\n\t\t\t\thelpEntries.set(metric.name, helpText);\n\t\t\t}\n\t\t\tif (!typeEntries.has(metric.name)) {\n\t\t\t\tlines.push(`# TYPE ${metric.name} ${metric.type}`);\n\t\t\t\ttypeEntries.set(metric.name, metric.type);\n\t\t\t}\n\n\t\t\tconst labelStr = this._formatLabels(metric.labels);\n\t\t\tlines.push(`${metric.name}{${labelStr}} ${metric.value}`);\n\t\t}\n\n\t\tfor (const histogram of histograms) {\n\t\t\tconst { name: fullName, labels } = histogram;\n\t\t\tif (histogram.count > 0) {\n\t\t\t\tif (!typeEntries.has(fullName)) {\n\t\t\t\t\tlines.push(`# TYPE ${fullName} histogram`);\n\t\t\t\t\ttypeEntries.set(fullName, MetricType.Histogram);\n\t\t\t\t}\n\n\t\t\t\tconst labelStr = this._formatLabels(labels);\n\t\t\t\tconst formatMetricLine = (suffix: string, value: number): string => {\n\t\t\t\t\tif (labelStr.length === 0) {\n\t\t\t\t\t\treturn `${fullName}${suffix} ${value}`;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn `${fullName}${suffix}{${labelStr}} ${value}`;\n\t\t\t\t};\n\n\t\t\t\tlines.push(formatMetricLine('_sum', histogram.sum));\n\t\t\t\tlines.push(formatMetricLine('_count', histogram.count));\n\n\t\t\t\tfor (const boundary of histogram.boundaries) {\n\t\t\t\t\tconst count = histogram.buckets.get(boundary);\n\t\t\t\t\tconst boundaryLabel = String(boundary);\n\t\t\t\t\tconst boundaryLabelStr = this._formatLabels({ le: boundaryLabel });\n\t\t\t\t\tconst bucketLabels =\n\t\t\t\t\t\tlabelStr.length === 0 ? boundaryLabelStr : `${labelStr},${boundaryLabelStr}`;\n\t\t\t\t\tlines.push(`${fullName}_bucket{${bucketLabels}} ${count}`);\n\t\t\t\t}\n\t\t\t\tconst infLabelStr = this._formatLabels({ le: '+Inf' });\n\t\t\t\tconst infLabels = labelStr.length === 0 ? infLabelStr : `${labelStr},${infLabelStr}`;\n\t\t\t\tlines.push(`${fullName}_bucket{${infLabels}} ${histogram.count}`);\n\t\t\t}\n\t\t}\n\n\t\treturn lines.join('\\n');\n\t}\n\n\t/**\n\t * Gets metric name with prefix.\n\t * @param name - Metric name\n\t * @returns Full metric name\n\t * @private\n\t */\n\tprivate _fullName(name: string): string {\n\t\tif (!this._prefix) {\n\t\t\treturn name;\n\t\t}\n\n\t\tconst prefix = `${this._prefix}_`;\n\t\treturn name.startsWith(prefix) ? name : `${prefix}${name}`;\n\t}\n\n\t/**\n\t * Creates a unique key for a metric with labels.\n\t * @param name - Metric name\n\t * @param labels - Labels\n\t * @returns Unique key\n\t * @private\n\t */\n\tprivate _metricKey(name: string, labels: Record<string, string>): string {\n\t\tconst sortedLabels = Object.entries(labels).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n\t\treturn JSON.stringify([name, sortedLabels]);\n\t}\n\n\tprivate _formatLabels(labels: Record<string, string>): string {\n\t\treturn Object.entries(labels)\n\t\t\t.map(([key, value]) => `${key}=\"${this._escapeLabelValue(value)}\"`)\n\t\t\t.join(',');\n\t}\n\n\tprivate _escapeLabelValue(value: string): string {\n\t\treturn value.replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\\\"').replaceAll('\\n', '\\\\n');\n\t}\n}\n"],"names":["MetricType","DEFAULT_BUCKETS","Metrics","options","Map","name","value","labels","help","fullName","allLabels","key","existing","buckets","histogram","previousBoundary","boundary","Number","RangeError","index","histogramData","lines","metrics","Array","histograms","helpEntries","typeEntries","metric","helpText","labelStr","formatMetricLine","suffix","count","boundaryLabel","String","boundaryLabelStr","bucketLabels","infLabelStr","infLabels","prefix","sortedLabels","Object","a","b","JSON"],"mappings":"AAYO,IAAKA,0BAAUA,WAAAA,GAAAA,SAAAA,UAAAA;IACiC;IAGT;IAGM;;;AAuCpD,MAAMC,kBAAkB;IAAC;IAAO;IAAM;IAAO;IAAM;IAAK;IAAM;IAAK;IAAG;IAAK;IAAG;CAAG;AA+C1E,MAAMC;IAEJ,SAA8B;IAG9B,YAA0C;IAG1C,QAAgB;IAGhB,eAAuC;IAGvC,qBAA6B,EAAE;IAYvC,YAAYC,UAAuE,CAAC,CAAC,CAAE;QACtF,IAAI,CAAC,QAAQ,GAAG,IAAIC;QACpB,IAAI,CAAC,WAAW,GAAG,IAAIA;QACvB,IAAI,CAAC,OAAO,GAAGD,QAAQ,MAAM,IAAI;QACjC,IAAI,CAAC,cAAc,GAAG;YAAE,GAAGA,QAAQ,aAAa;QAAC;IAClD;IAgBA,QAAQE,IAAY,EAAEC,QAAQ,CAAC,EAAEC,SAAiC,CAAC,CAAC,EAAEC,IAAa,EAAQ;QAC1F,MAAMC,WAAW,IAAI,CAAC,SAAS,CAACJ;QAChC,MAAMK,YAAY;YAAE,GAAG,IAAI,CAAC,cAAc;YAAE,GAAGH,MAAM;QAAC;QACtD,MAAMI,MAAM,IAAI,CAAC,UAAU,CAACF,UAAUC;QACtC,MAAME,WAAW,IAAI,CAAC,QAAQ,CAAC,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,SAAS,QAAQ,EAAE6B,UAAU,EAAE,EAAExB,UAAU,KAAK,EAAE;YACjE;QACD;QAEA,OAAOO,MAAM,IAAI,CAAC;IACnB;IAQQ,UAAUhB,IAAY,EAAU;QACvC,IAAI,CAAC,IAAI,CAAC,OAAO,EAChB,OAAOA;QAGR,MAAMkC,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;QACjC,OAAOlC,KAAK,UAAU,CAACkC,UAAUlC,OAAO,GAAGkC,SAASlC,MAAM;IAC3D;IASQ,WAAWA,IAAY,EAAEE,MAA8B,EAAU;QACxE,MAAMiC,eAAeC,OAAO,OAAO,CAAClC,QAAQ,IAAI,CAAC,CAAC,CAACmC,EAAE,EAAE,CAACC,EAAE,GAAMD,IAAIC,IAAI,KAAKD,IAAIC,IAAI,IAAI;QACzF,OAAOC,KAAK,SAAS,CAAC;YAACvC;YAAMmC;SAAa;IAC3C;IAEQ,cAAcjC,MAA8B,EAAU;QAC7D,OAAOkC,OAAO,OAAO,CAAClC,QACpB,GAAG,CAAC,CAAC,CAACI,KAAKL,MAAM,GAAK,GAAGK,IAAI,EAAE,EAAE,IAAI,CAAC,iBAAiB,CAACL,OAAO,CAAC,CAAC,EACjE,IAAI,CAAC;IACR;IAEQ,kBAAkBA,KAAa,EAAU;QAChD,OAAOA,MAAM,UAAU,CAAC,MAAM,QAAQ,UAAU,CAAC,KAAK,OAAO,UAAU,CAAC,MAAM;IAC/E;AACD"}
@@ -1,5 +1,5 @@
1
1
  import type { IMetrics } from '../contracts/interfaces.js';
2
- import type { PersistenceConfig, PersistenceBackend } from '../contracts/PersistenceBackend.js';
2
+ import type { PersistenceConfig, PersistenceBackend, PersistenceRestoreRead } from '../contracts/PersistenceBackend.js';
3
3
  import { type BranchId, type SessionId, type ThoughtId } from '../contracts/ids.js';
4
4
  import type { Summary } from '../core/compression/Summary.js';
5
5
  import type { Edge } from '../core/graph/Edge.js';
@@ -27,6 +27,7 @@ export declare class FilePersistence implements PersistenceBackend {
27
27
  loadBranchForSession(sessionId: SessionId, branchId: BranchId): Promise<ThoughtData[] | undefined>;
28
28
  listBranchesForSession(sessionId: SessionId): Promise<BranchId[]>;
29
29
  listSessions(): Promise<SessionId[]>;
30
+ loadAllSessionsForRestore(): Promise<PersistenceRestoreRead>;
30
31
  clearAll(): Promise<void>;
31
32
  clearSession(sessionId: SessionId): Promise<void>;
32
33
  saveEdges(sessionId: SessionId, edges: readonly Edge[]): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"FilePersistence.d.ts","sourceRoot":"","sources":["../../src/persistence/FilePersistence.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,KAAK,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,oCAAoC,CAAC;AAChG,OAAO,EAAe,KAAK,QAAQ,EAAE,KAAK,SAAS,EAAE,KAAK,SAAS,EAAE,MAAM,qBAAqB,CAAC;AACjG,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gCAAgC,CAAC;AAC9D,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAUtD,OAAO,EAAqC,KAAK,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAY/F,KAAK,sBAAsB,GAAG,WAAW,CAAC,iBAAiB,CAAC,SAAS,CAAC,CAAC,GAAG;IACzE,QAAQ,CAAC,OAAO,CAAC,EAAE,QAAQ,CAAC;IAC5B,QAAQ,CAAC,gBAAgB,CAAC,EAAE,oBAAoB,CAAC;CACjD,CAAC;AAIF,qBAAa,eAAgB,YAAW,kBAAkB;IACzD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IACzC,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAU;IAC3C,OAAO,CAAC,QAA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AE,SAAS,EAAE,KAAK,EAAE,SAAS,IAAI,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAYtE,SAAS,CAAC,SAAS,EAAE,SAAS,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;IAOhD,aAAa,CAAC,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,OAAO,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAcjF,aAAa,CAAC,SAAS,EAAE,SAAS,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC;IAQvD,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC;IAUjC,UAAU,IAAI,MAAM;IAId,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;YAIrB,KAAK;YAQL,OAAO;YAaP,aAAa;YAYb,QAAQ;CAUtB"}
@@ -4,7 +4,7 @@ import { homedir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import { asSessionId } from "../contracts/ids.js";
6
6
  import { PersistenceCompatibilityError } from "../errors.js";
7
- import { EMPTY_FILE_SNAPSHOT_V2, parseFileSnapshotV2, serializeFileSnapshotV2, sessionsInSnapshot } from "./FileSnapshotV2.js";
7
+ import { EMPTY_FILE_SNAPSHOT_V2, parseFileSnapshotV2, restoreRecordsInSnapshot, serializeFileSnapshotV2, sessionsInSnapshot } from "./FileSnapshotV2.js";
8
8
  import { stageBacktrackPersistence } from "./BacktrackPersistence.js";
9
9
  import { FILE_WRITER_LOCK_NAME, FileWriter } from "./FileWriter.js";
10
10
  import { assertBranchScope, assertEdgeScopes, assertPersistableThoughtCollections, assertPersistableThoughts, assertSummaryScopes, assertThoughtScope, compareCodePoint, parsePersistenceBranchId } from "./PersistenceScope.js";
@@ -177,6 +177,11 @@ class FilePersistence {
177
177
  async listSessions() {
178
178
  return await this._read('list_sessions', sessionsInSnapshot);
179
179
  }
180
+ async loadAllSessionsForRestore() {
181
+ return await this._read('load_restore', (snapshot)=>({
182
+ sessions: restoreRecordsInSnapshot(snapshot, this._persistBranches)
183
+ }));
184
+ }
180
185
  async clearAll() {
181
186
  await this._mutate('clear_all', ()=>EMPTY_FILE_SNAPSHOT_V2);
182
187
  }