@iworkforces/tracelattice 2.2.1 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -233,6 +233,8 @@ TraceLattice uses separate session concepts with separate identifiers:
233
233
 
234
234
  `ConnectionPool` slots are an optional HTTP isolation layer and are separate from both thought sessions and MCP transport sessions.
235
235
 
236
+ Thought sessions have a 30-minute idle TTL, checked every five minutes, and can also be evicted for live-session capacity. Once eviction succeeds, ordinary access to that named session returns `SESSION_EXPIRED` instead of creating empty history. To start a fresh chain, use a new `session_id`, await an authorized `resetSession(sessionId)`, or submit a validated replacement thought with `reset_state: true`. Explicit reset deletes that session's durable data; it doesn't resume or rehydrate the old chain. Authorization runs before reset, and a failed or invalid reset doesn't reopen the session. See the [reliability contract](docs/reliability-contract.md#lifecycle-and-failure-semantics) for marker lifetime and ownership guarantees.
237
+
236
238
  ### Stateless HTTP library API
237
239
 
238
240
  Import the stateless transport from the package root. The package does not expose transport internals or deep import paths.
@@ -289,7 +291,9 @@ The checked evaluation report separates deterministic structural validation and
289
291
 
290
292
  `PersistenceBackend` requires `saveBacktrackForSession(sessionId, thought, targetThoughtId)`. Every custom backend must implement it. The operation atomically corrects every retained stable-ID copy of the target, appends the backtrack thought, and applies retention. There is no capability fallback; the ordinary persistence methods retain their existing contracts.
291
293
 
292
- Restore reads retained records only. It repairs retained backtrack copies without writing the snapshot, ignores an absent retained target, and rejects an ambiguous retained numeric target. Evidence already pruned by retention or eviction cannot be recovered.
294
+ Startup File/SQLite restore reads supported retained durable records with provenance restrictions; it doesn't restore all transient auxiliary state. It repairs retained backtrack copies without writing the snapshot, ignores an absent retained target, and rejects an ambiguous retained numeric target. TTL and capacity eviction remove live state without deleting durable records, but ordinary access doesn't reload them. Evidence pruned from durable storage by retention or deleted by explicit reset cannot be recovered. With persistence disabled, state cannot resume across restart; process-local expiration markers are also lost on restart.
295
+
296
+ Branches and revisions may legally reuse thought numbers. A numeric `verification_target` must uniquely identify a retained thought identity in the same session, so avoid reusing numbers when you intend unique numeric verification references. Targets may have any thought type. Recording a verification outcome requires an explicit result of `0` or `1` and a non-retracted target with confidence.
293
297
 
294
298
  ## Development
295
299
 
package/dist/cli.js CHANGED
@@ -125,6 +125,7 @@ __webpack_require__.d(__webpack_exports__, {
125
125
  LOCK_TIMEOUT: 'LOCK_TIMEOUT',
126
126
  CLI_SHUTDOWN_TIMEOUT: 'CLI_SHUTDOWN_TIMEOUT',
127
127
  SESSION_ACCESS_DENIED: 'SESSION_ACCESS_DENIED',
128
+ SESSION_EXPIRED: 'SESSION_EXPIRED',
128
129
  SESSION_LIFECYCLE_CLOSED: 'SESSION_LIFECYCLE_CLOSED',
129
130
  PERSISTENCE_OWNERSHIP: 'PERSISTENCE_OWNERSHIP',
130
131
  PERSISTENCE_CORRUPTION: 'PERSISTENCE_CORRUPTION',
@@ -888,7 +889,7 @@ Reasoning Enhancement Parameters:
888
889
  - quality_score: Self-assessed quality of this thought (0-1)
889
890
  - confidence: Confidence in this thought's correctness (0-1)
890
891
  - hypothesis_id: Links hypothesis to verification (alphanumeric, hyphens, underscores)
891
- - verification_target: For 'verification'/'critique' types, the thought_number being evaluated
892
+ - verification_target: For 'verification'/'critique', the thought_number of a uniquely retained identity. Branch/revision number reuse is legal, but ambiguous numeric targets fail. Result-bearing verification requires a non-retracted target with confidence.
892
893
  - verification_result: Optional exact outcome label (0 = incorrect, 1 = correct) for a verification_target; only has outcome semantics on thought_type='verification'
893
894
  - synthesis_sources: For 'synthesis' type, the thought_numbers being combined
894
895
  - merge_from_thoughts: Thought numbers from other branches merged (graph reasoning)
@@ -896,7 +897,7 @@ Reasoning Enhancement Parameters:
896
897
  - meta_observation: Observation about reasoning process (with thought_type 'meta')
897
898
  - reasoning_depth: How deep to reason: 'shallow' (quick), 'moderate' (default), 'deep' (thorough)
898
899
  - session_id: Required unique identifier that scopes thought history, branches, and statistics to an explicit session. Format: alphanumeric, hyphens, underscores, 1-100 chars; the retired value __global__ is rejected.
899
- - reset_state: (Optional) When true, clears all state for the required session_id before processing the current thought. Use this to start a fresh reasoning chain without accumulated state from previous chains.
900
+ - reset_state: (Optional) Authorized fresh-chain replacement for session_id, deleting its durable data and preserving its former owner. SESSION_EXPIRED requires this explicit recovery or a new session_id; invalid or failed reset does not reopen the expired scope.
900
901
 
901
902
  Response Enrichment:
902
903
  - When reasoning fields are set, response includes confidence_signals (depth, revision/branch count, type distribution, avg confidence, structural_quality, quality_components) and reasoning_stats (hypothesis tracking)
@@ -1188,7 +1189,7 @@ You should:
1188
1189
  quality_score: valibot__rspack_import_0.optional(valibot__rspack_import_0.pipe(valibot__rspack_import_0.number(), valibot__rspack_import_0.minValue(0), valibot__rspack_import_0.maxValue(1), valibot__rspack_import_0.description('Self-assessed quality score (0-1)'))),
1189
1190
  confidence: valibot__rspack_import_0.optional(valibot__rspack_import_0.pipe(valibot__rspack_import_0.number(), valibot__rspack_import_0.minValue(0), valibot__rspack_import_0.maxValue(1), valibot__rspack_import_0.description('Explicit confidence in correctness (0-1)'))),
1190
1191
  hypothesis_id: valibot__rspack_import_0.optional(valibot__rspack_import_0.pipe(valibot__rspack_import_0.string(), valibot__rspack_import_0.regex(/^[a-zA-Z0-9_-]+$/, 'Hypothesis ID must contain only letters, numbers, hyphens, and underscores'), valibot__rspack_import_0.minLength(1), valibot__rspack_import_0.maxLength(50), valibot__rspack_import_0.description('Identifier linking hypothesis to verification thoughts'))),
1191
- verification_target: valibot__rspack_import_0.optional(valibot__rspack_import_0.pipe(valibot__rspack_import_0.number(), valibot__rspack_import_0.minValue(1), valibot__rspack_import_0.description('Thought number being verified or critiqued'))),
1192
+ verification_target: valibot__rspack_import_0.optional(valibot__rspack_import_0.pipe(valibot__rspack_import_0.number(), valibot__rspack_import_0.minValue(1), valibot__rspack_import_0.description('Uniquely retained thought number being verified or critiqued; ambiguous numeric targets fail even though branch/revision number reuse is legal'))),
1192
1193
  verification_result: valibot__rspack_import_0.optional(valibot__rspack_import_0.pipe(valibot__rspack_import_0.union([
1193
1194
  valibot__rspack_import_0.literal(0),
1194
1195
  valibot__rspack_import_0.literal(1)
@@ -1202,8 +1203,8 @@ You should:
1202
1203
  'moderate',
1203
1204
  'deep'
1204
1205
  ]), valibot__rspack_import_0.description('Effort signal: how deep reasoning should go'))),
1205
- session_id: valibot__rspack_import_0.pipe(valibot__rspack_import_0.string(), valibot__rspack_import_0.regex(/^[a-zA-Z0-9_-]+$/, 'Session ID must contain only letters, numbers, hyphens, and underscores'), valibot__rspack_import_0.minLength(1), valibot__rspack_import_0.maxLength(100), valibot__rspack_import_0.notValue('__global__', "Session ID '__global__' is retired; use an explicit named session"), valibot__rspack_import_0.description('Required session identifier for state isolation. Thought history, branches, and statistics are scoped to this explicit named session.')),
1206
- reset_state: valibot__rspack_import_0.optional(valibot__rspack_import_0.pipe(valibot__rspack_import_0.boolean(), valibot__rspack_import_0.description('When true, clears all state for the target session before processing this thought. The thought is then processed as the first in a fresh session.'))),
1206
+ session_id: valibot__rspack_import_0.pipe(valibot__rspack_import_0.string(), valibot__rspack_import_0.regex(/^[a-zA-Z0-9_-]+$/, 'Session ID must contain only letters, numbers, hyphens, and underscores'), valibot__rspack_import_0.minLength(1), valibot__rspack_import_0.maxLength(100), valibot__rspack_import_0.notValue('__global__', "Session ID '__global__' is retired; use an explicit named session"), valibot__rspack_import_0.description('Required named session for state isolation. SESSION_EXPIRED after runtime eviction requires an authorized reset_state fresh chain or a new session_id; ordinary continuation cannot recreate it.')),
1207
+ reset_state: valibot__rspack_import_0.optional(valibot__rspack_import_0.pipe(valibot__rspack_import_0.boolean(), valibot__rspack_import_0.description('Authorized fresh-chain replacement, deleting target-session durable data and preserving its former owner. Recovers SESSION_EXPIRED only on successful reset; invalid or failed reset does not reopen it.'))),
1207
1208
  tool_name: valibot__rspack_import_0.optional(valibot__rspack_import_0.pipe(valibot__rspack_import_0.string(), valibot__rspack_import_0.minLength(1), valibot__rspack_import_0.description('Name of the tool being invoked (for tool_call thoughts)'))),
1208
1209
  tool_arguments: valibot__rspack_import_0.optional(valibot__rspack_import_0.pipe(valibot__rspack_import_0.record(valibot__rspack_import_0.string(), valibot__rspack_import_0.unknown()), valibot__rspack_import_0.description('Arguments passed to the tool (for tool_call thoughts)'))),
1209
1210
  tool_result: valibot__rspack_import_0.optional(valibot__rspack_import_0.pipe(valibot__rspack_import_0.unknown(), valibot__rspack_import_0.description('Result returned by the tool (for tool_observation thoughts)'))),
@@ -71,6 +71,7 @@ export declare class HistoryManager implements IHistoryManager {
71
71
  private static readonly SESSION_TTL_MS;
72
72
  private static readonly MAX_SESSIONS;
73
73
  private _sessions;
74
+ private readonly _expiredSessions;
74
75
  private _maxHistorySize;
75
76
  private _maxBranches;
76
77
  private _maxBranchSize;
@@ -121,7 +122,8 @@ export declare class HistoryManager implements IHistoryManager {
121
122
  * Gets or creates session state; updates lastAccessedAt.
122
123
  *
123
124
  * Ownership semantics:
124
- * - `owner === undefined` (stdio path): never rejects, never sets owner.
125
+ * - `owner === undefined` (stdio path): bypasses ownership checks without setting
126
+ * owner; expired sessions still reject access.
125
127
  * - `owner !== undefined`: if session has a different owner, throws
126
128
  * `SessionAccessDeniedError`. If session was created without an owner
127
129
  * (e.g. by stdio), the owner is set on first owner-aware access.
@@ -129,6 +131,7 @@ export declare class HistoryManager implements IHistoryManager {
129
131
  private _getSession;
130
132
  private _getSessionWithinOperation;
131
133
  private _assertSessionOwner;
134
+ private _planCapacityForSession;
132
135
  private _makeCapacityForSession;
133
136
  private _isCapacityEvictionEligible;
134
137
  private _isTtlEvictionEligible;
@@ -138,6 +141,8 @@ export declare class HistoryManager implements IHistoryManager {
138
141
  private _removeLiveSession;
139
142
  private _createSessionState;
140
143
  private _authorizeExistingSession;
144
+ private _authorizeSessionReset;
145
+ assertSessionResetAuthorized(sessionId: string): void;
141
146
  private _assertOwnerlessResetAll;
142
147
  /**
143
148
  * Adds a thought to the history. Routes per-session, applies retraction for backtrack,
@@ -1 +1 @@
1
-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OAAO;IAI/B,qBAAqB,IAAI,kBAAkB,GAAG,IAAI;IAIzD,sFAAsF;IAC/E,eAAe,CAAC,OAAO,EAAE,uBAAuB,GAAG,IAAI;IAK9D;;;;;;OAMG;IACI,iBAAiB,CAAC,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI;IAO1D,kGAAkG;IAC3F,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAQhC,4EAA4E;IAC/D,uBAAuB,IAAI,OAAO,CAAC,IAAI,CAAC;IAMrD,sFAAsF;IAC/E,2BAA2B,IAAI,IAAI;IAY1C,kFAAkF;IAC3E,oBAAoB,IAAI,MAAM;CAGrC"}
@@ -2,7 +2,7 @@ import { asSessionId } from "../contracts/ids.js";
2
2
  import { ERROR_CODES, InvalidBacktrackError, MaxSessionsReachedError, SequentialThinkingError, ValidationError } from "../errors.js";
3
3
  import { NullLogger } from "../logger/NullLogger.js";
4
4
  import { DehydrationPolicy } from "./compression/DehydrationPolicy.js";
5
- import { SessionAccessDeniedError } from "./SessionErrors.js";
5
+ import { SessionAccessDeniedError, SessionExpiredError } from "./SessionErrors.js";
6
6
  import { EdgeEmitter } from "./graph/EdgeEmitter.js";
7
7
  import { PersistenceBuffer } from "./PersistenceBuffer.js";
8
8
  import { SessionManager } from "./SessionManager.js";
@@ -19,6 +19,7 @@ class HistoryManager {
19
19
  static SESSION_TTL_MS = 1800000;
20
20
  static MAX_SESSIONS = 100;
21
21
  _sessions = new Map();
22
+ _expiredSessions = new Map();
22
23
  _maxHistorySize;
23
24
  _maxBranches;
24
25
  _maxBranchSize;
@@ -100,6 +101,12 @@ class HistoryManager {
100
101
  summaryStore: this._summaryStore,
101
102
  sessions: this._sessions,
102
103
  createSessionState: (owner)=>this._createSessionState(owner),
104
+ assertReplacementCapacity: (sessionId, owner)=>{
105
+ if (!this._sessions.has(sessionId)) this._planCapacityForSession(owner);
106
+ },
107
+ admitReplacement: (sessionId, owner)=>{
108
+ if (!this._sessions.has(sessionId)) this._makeCapacityForSession(owner);
109
+ },
103
110
  logger: this._logger
104
111
  });
105
112
  this._sessionManager.startCleanupTimer(this._sessions, (sessionId)=>this._isTtlEvictionEligible(sessionId), (sessionIds)=>this._evictSessions(sessionIds));
@@ -124,6 +131,7 @@ class HistoryManager {
124
131
  return this._persistenceBuffer?.drainSession(sessionId) ?? Promise.resolve();
125
132
  }
126
133
  bufferSummaries(sessionId, summaries) {
134
+ this._authorizeExistingSession(sessionId, this._getCurrentOwner());
127
135
  this._lifecycle.runMutation(sessionId, ()=>{
128
136
  this._persistenceBuffer?.bufferSummaries(sessionId, summaries);
129
137
  const session = this._sessions.get(sessionId);
@@ -141,6 +149,7 @@ class HistoryManager {
141
149
  }
142
150
  _getSession(sessionId, owner) {
143
151
  const key = asSessionId(sessionId);
152
+ this._authorizeExistingSession(key, owner);
144
153
  const existing = this._sessions.get(key);
145
154
  if (void 0 !== existing) {
146
155
  this._assertSessionOwner(key, existing, owner);
@@ -150,6 +159,7 @@ class HistoryManager {
150
159
  return this._lifecycle.runMutation(key, ()=>this._getSessionWithinOperation(key, owner));
151
160
  }
152
161
  _getSessionWithinOperation(key, owner) {
162
+ this._authorizeExistingSession(key, owner);
153
163
  let session = this._sessions.get(key);
154
164
  if (session) this._assertSessionOwner(key, session, owner);
155
165
  else {
@@ -166,9 +176,13 @@ class HistoryManager {
166
176
  if (void 0 !== session.owner && session.owner !== owner) throw new SessionAccessDeniedError(sessionId, session.owner, owner);
167
177
  if (void 0 === session.owner) session.owner = owner;
168
178
  }
169
- _makeCapacityForSession(owner) {
179
+ _planCapacityForSession(owner) {
170
180
  const victims = this._sessionManager.planProspectiveAdmission(this._sessions, owner, (sessionId)=>this._isCapacityEvictionEligible(sessionId));
171
181
  if (void 0 === victims) throw new MaxSessionsReachedError(HistoryManager.MAX_SESSIONS);
182
+ return victims;
183
+ }
184
+ _makeCapacityForSession(owner) {
185
+ const victims = this._planCapacityForSession(owner);
172
186
  if (0 === victims.length) return;
173
187
  const evicted = this._lifecycle.tryEvictIdleSessions(victims, (sessionIds)=>{
174
188
  if (sessionIds.some((sessionId)=>!this._isPersistenceQuiescent(sessionId))) throw new MaxSessionsReachedError(HistoryManager.MAX_SESSIONS);
@@ -204,12 +218,16 @@ class HistoryManager {
204
218
  });
205
219
  }
206
220
  _removeLiveSession(sessionId) {
221
+ const session = this._sessions.get(sessionId);
207
222
  this._clearSessionAuxiliaryState?.(sessionId);
208
223
  this._edgeStore?.clearSession(sessionId);
209
224
  this._summaryStore?.clearSession(sessionId);
210
225
  this._referenceIndex.clearSession(sessionId);
211
226
  this._sessions.delete(sessionId);
212
227
  this._persistenceBuffer?.forgetQuiescentSession(sessionId);
228
+ if (void 0 !== session) this._expiredSessions.set(sessionId, {
229
+ owner: session.owner
230
+ });
213
231
  }
214
232
  _createSessionState(owner, provenance) {
215
233
  return {
@@ -226,11 +244,20 @@ class HistoryManager {
226
244
  };
227
245
  }
228
246
  _authorizeExistingSession(sessionId, owner) {
229
- const sessionOwner = this._sessions.get(sessionId)?.owner;
247
+ const preservedOwner = this._authorizeSessionReset(sessionId, owner);
248
+ if (this._expiredSessions.has(sessionId)) throw new SessionExpiredError(sessionId);
249
+ return preservedOwner;
250
+ }
251
+ _authorizeSessionReset(sessionId, owner) {
252
+ const marker = this._expiredSessions.get(sessionId);
253
+ const sessionOwner = void 0 === marker ? this._sessions.get(sessionId)?.owner : marker.owner;
230
254
  if (void 0 !== owner && this._sessions.get(sessionId)?.provenance === 'restored') throw new SessionAccessDeniedError(sessionId, 'unavailable', owner);
231
255
  if (void 0 !== owner && void 0 !== sessionOwner && sessionOwner !== owner) throw new SessionAccessDeniedError(sessionId, sessionOwner, owner);
232
256
  return sessionOwner ?? owner;
233
257
  }
258
+ assertSessionResetAuthorized(sessionId) {
259
+ this._authorizeSessionReset(asSessionId(sessionId), this._getCurrentOwner());
260
+ }
234
261
  _assertOwnerlessResetAll() {
235
262
  const owner = this._getCurrentOwner();
236
263
  if (void 0 === owner) return;
@@ -240,12 +267,13 @@ class HistoryManager {
240
267
  }
241
268
  addThought(thought, context) {
242
269
  const sessionId = asSessionId(thought.session_id);
270
+ this._authorizeExistingSession(sessionId, this._getCurrentOwner());
243
271
  this._lifecycle.runMutation(sessionId, ()=>this._addThoughtWithinOperation(sessionId, thought, context));
244
272
  }
245
273
  assertThoughtIdentityAvailable(thought) {
246
- if (void 0 === thought.id) return;
247
274
  const sessionId = asSessionId(thought.session_id);
248
275
  this._authorizeExistingSession(sessionId, this._getCurrentOwner());
276
+ if (void 0 === thought.id) return;
249
277
  if (this._referenceIndex.has(sessionId, thought.id) || this._persistenceBuffer?.hasThoughtIdentity(sessionId, thought.id) === true) throw new ValidationError('id', `Thought id already exists in session: ${thought.id}`);
250
278
  }
251
279
  _addThoughtWithinOperation(sessionId, thought, context) {
@@ -438,6 +466,7 @@ class HistoryManager {
438
466
  };
439
467
  }
440
468
  registerBranch(sessionId, branchId) {
469
+ this._authorizeExistingSession(asSessionId(sessionId), this._getCurrentOwner());
441
470
  if ('string' != typeof branchId || 0 === branchId.length) throw new ValidationError('branch_id', 'branch_id must be a non-empty string');
442
471
  const canonicalSessionId = asSessionId(sessionId);
443
472
  this._lifecycle.runMutation(canonicalSessionId, ()=>{
@@ -471,7 +500,7 @@ class HistoryManager {
471
500
  }
472
501
  async resetSession(sessionId, clearAuxiliaryState) {
473
502
  const canonicalSessionId = asSessionId(sessionId);
474
- this._authorizeExistingSession(canonicalSessionId, this._getCurrentOwner());
503
+ this.assertSessionResetAuthorized(canonicalSessionId);
475
504
  await this._lifecycle.withSessionReset(canonicalSessionId, async ()=>{
476
505
  const reset = async ()=>await this.resetSessionWithinExclusive(canonicalSessionId, clearAuxiliaryState);
477
506
  if (void 0 === this._sessionLock) return await reset();
@@ -479,9 +508,10 @@ class HistoryManager {
479
508
  });
480
509
  }
481
510
  async resetSessionWithinExclusive(sessionId, clearAuxiliaryState) {
482
- const preservedOwner = this._authorizeExistingSession(sessionId, this._getCurrentOwner());
511
+ const preservedOwner = this._authorizeSessionReset(sessionId, this._getCurrentOwner());
483
512
  await this._resetCoordinator.resetSession(sessionId, preservedOwner, clearAuxiliaryState ?? (void 0 === this._clearSessionAuxiliaryState ? void 0 : ()=>this._clearSessionAuxiliaryState?.(sessionId)));
484
513
  this._referenceIndex.clearSession(sessionId);
514
+ this._expiredSessions.delete(sessionId);
485
515
  }
486
516
  async resetAll(clearAuxiliaryState) {
487
517
  this._assertOwnerlessResetAll();
@@ -491,6 +521,7 @@ class HistoryManager {
491
521
  this._assertOwnerlessResetAll();
492
522
  await this._resetCoordinator.resetAll(clearAuxiliaryState ?? this._clearAllAuxiliaryState);
493
523
  this._referenceIndex.clearAll();
524
+ this._expiredSessions.clear();
494
525
  }
495
526
  getSessionIds() {
496
527
  return Array.from(this._sessions.keys());
@@ -596,6 +627,7 @@ class HistoryManager {
596
627
  this._edgeStore?.clearAll();
597
628
  this._summaryStore?.clearAll();
598
629
  this._clearAllAuxiliaryState?.();
630
+ this._expiredSessions.clear();
599
631
  }
600
632
  getWriteBufferLength() {
601
633
  return this._persistenceBuffer?.pendingThoughtCount ?? 0;