@codelia/storage 0.1.83 → 0.1.84

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,15 +1,23 @@
1
- import { GeneratedImageMetadata, ImageArtifactRef, ImageMediaType, AttachedImageMetadata, ImageArtifactMetadata, ApprovalMode, SubagentLineage, AgentMessage, TaskTerminationReason, TaskUsage } from '@codelia/shared-types';
2
- import { StoragePaths, ResolveStorageOptions, RunEventStoreFactory, RunEventStoreInit, SessionStore, StoragePathService, SessionStateStore, SessionState, SessionStateSummary, SessionRecord, ToolOutputCacheStore, ToolOutputCacheRecord, ToolOutputRef, ToolOutputCacheReadOptions, ToolOutputCacheSearchOptions } from '@codelia/core';
1
+ import * as _codelia_core from '@codelia/core';
2
+ import { StoragePaths, ResolveStorageOptions, RunEventStoreFactory, RunEventStoreInit, SessionStore, ConversationSearchResult, ConversationMessage, SessionStateStore, SessionState, SessionStateSummary, StoragePathService, SessionRecord, ToolOutputCacheStore, ToolOutputCacheRecord, ToolOutputRef, ToolOutputCacheReadOptions, ToolOutputCacheSearchOptions } from '@codelia/core';
3
3
  export { ResolveStorageOptions, StorageLayout, StoragePathService, StoragePaths } from '@codelia/core';
4
+ import { GeneratedImageMetadata, ImageArtifactRef, ImageMediaType, AttachedImageMetadata, ImageArtifactMetadata, AttachmentRef, ApprovalMode, SubagentLineage, AgentMessage, TaskTerminationReason, TaskUsage } from '@codelia/shared-types';
4
5
 
5
- /** A workspace-scoped store. No TTL deletion: references must survive session resume. */
6
+ type AttachmentWriteOptions = {
7
+ artifactId?: string;
8
+ ownerSessionId?: string;
9
+ };
10
+ /** Workspace image storage with session-scoped access for copied files. */
6
11
  declare class ImageArtifactStore {
7
12
  readonly root: string;
8
- constructor(root: string);
9
- save(bytes: Buffer, provenance: Omit<GeneratedImageMetadata, keyof ImageArtifactRef | "created_at">): Promise<GeneratedImageMetadata>;
10
- saveAttachment(bytes: Buffer, mediaType: ImageMediaType): Promise<AttachedImageMetadata>;
13
+ private readonly getSessionId?;
14
+ constructor(root: string, getSessionId?: (() => string | null) | undefined);
15
+ save(bytes: Buffer, provenance: Omit<GeneratedImageMetadata, keyof ImageArtifactRef | "created_at">, mediaType?: "image/png" | "image/jpeg"): Promise<GeneratedImageMetadata>;
16
+ saveAttachment(bytes: Buffer, mediaType: ImageMediaType, { artifactId, ownerSessionId, }?: AttachmentWriteOptions): Promise<AttachedImageMetadata>;
17
+ /** Roll back a newly uploaded attachment before its ownership batch is published. */
18
+ discardUnpublishedAttachment(ref: ImageArtifactRef, sessionId: string): Promise<void>;
11
19
  private persist;
12
- read(artifactId: string): Promise<{
20
+ read(artifactId: string, sessionId?: string | null): Promise<{
13
21
  metadata: ImageArtifactMetadata;
14
22
  bytes: Buffer;
15
23
  }>;
@@ -24,6 +32,47 @@ declare class ImageArtifactStore {
24
32
  }>;
25
33
  }
26
34
 
35
+ type StoredAttachment = {
36
+ ref: AttachmentRef;
37
+ imageRef?: ImageArtifactRef;
38
+ };
39
+ /** Host-owned originals and ownership index. commit must publish the entire batch atomically. */
40
+ type AttachmentStore = {
41
+ commit(sessionId: string, entries: readonly {
42
+ record: StoredAttachment;
43
+ bytes: Buffer;
44
+ }[]): Promise<void>;
45
+ /** Validate ownership and integrity before returning an admitted reference. */
46
+ lookup(attachmentId: string, sessionId: string): Promise<StoredAttachment | null>;
47
+ /** Check ownership and integrity of the returned byte range. */
48
+ read(attachmentId: string, sessionId: string, offset: number, length: number): Promise<Uint8Array>;
49
+ resolveImage?: ImageArtifactStore["resolve"];
50
+ };
51
+ declare const createAttachmentId: () => string;
52
+ declare const isAttachmentId: (id: string) => boolean;
53
+ /** An ownership marker makes every member of a batch visible at once. */
54
+ declare class FileAttachmentStore implements AttachmentStore {
55
+ readonly root: string;
56
+ private readonly images;
57
+ constructor(root: string, images: ImageArtifactStore);
58
+ resolveImage: NonNullable<AttachmentStore["resolveImage"]>;
59
+ commit(sessionId: string, entries: readonly {
60
+ record: StoredAttachment;
61
+ bytes: Buffer;
62
+ }[]): Promise<void>;
63
+ lookup(attachmentId: string, sessionId: string): Promise<StoredAttachment | null>;
64
+ read(attachmentId: string, sessionId: string, offset: number, length: number): Promise<Uint8Array>;
65
+ private metadata;
66
+ private readImage;
67
+ }
68
+
69
+ declare function detectImageAttachmentType(bytes: Buffer): ImageMediaType | undefined;
70
+ /** Bounded header validation; attachment originals are not decoded or re-encoded. */
71
+ declare function validateImageAttachment(bytes: Buffer, mediaType: ImageMediaType): {
72
+ width: number;
73
+ height: number;
74
+ };
75
+
27
76
  declare const IMAGE_MAX_BYTES: number;
28
77
  /** Validate chunks, CRC and bounded decompression before accepting provider bytes. */
29
78
  declare function validateImagePng(bytes: Buffer): Promise<{
@@ -54,6 +103,11 @@ declare class McpAuthStore {
54
103
  declare function resolveStoragePaths(options?: ResolveStorageOptions): StoragePaths;
55
104
  declare function ensureStorageDirs(paths: StoragePaths): Promise<void>;
56
105
 
106
+ /** Identity guards PID reuse. Failure is unknown, never permission to kill or remove a live-writer marker. */
107
+ declare const getProcessIdentity: (pid: number, options?: {
108
+ canonicalEnvironment?: boolean;
109
+ }) => Promise<string | null>;
110
+
57
111
  type ProjectsPolicyFile = {
58
112
  version: 1;
59
113
  default?: {
@@ -71,13 +125,60 @@ declare class ProjectsPolicyStore {
71
125
  save(data: ProjectsPolicyFile): Promise<void>;
72
126
  }
73
127
 
128
+ /** One run log of a session, as recorded in `state.db` (`session_runs`). */
129
+ type SessionRunEntry = {
130
+ session_id: string;
131
+ run_id: string;
132
+ /** Canonical `YYYY/MM/DD/<name>.jsonl` path relative to `sessionsDir`. */
133
+ rel_path: string;
134
+ started_at: string;
135
+ };
136
+ /** Narrow write capability handed to run log writers. */
137
+ type SessionRunRecorder = {
138
+ recordSessionRun: (entry: SessionRunEntry) => Promise<void>;
139
+ };
140
+ /**
141
+ * Resolves an indexed run log to a readable path: plain wins, then `.gz`.
142
+ * Only regular files qualify (no symlink/FIFO/directory, as the directory scan
143
+ * admitted only `isFile()` entries). Returns undefined otherwise.
144
+ */
145
+ declare const resolveIndexedRunLog: (sessionsDir: string, relPath: string) => string | undefined;
146
+ /**
147
+ * Reads every run log header under `sessionsDir` (the legacy, store-wide scan)
148
+ * and returns one entry per log whose header names a session. Unreadable or
149
+ * header-less files are skipped, as the legacy history scan did.
150
+ */
151
+ declare const scanSessionRunLogs: (sessionsDir: string) => Promise<SessionRunEntry[]>;
152
+
74
153
  declare class RunEventStoreFactoryImpl implements RunEventStoreFactory {
154
+ private runIndex?;
155
+ private readonly onRunIndexError?;
156
+ /**
157
+ * `runIndex` records each run in state.db (`session_runs`). When omitted, a
158
+ * default-path SessionStateStoreImpl is created on the first run so every
159
+ * normal run log stays indexed.
160
+ */
161
+ constructor(options?: {
162
+ runIndex?: SessionRunRecorder;
163
+ onRunIndexError?: (error: unknown) => void;
164
+ });
75
165
  create(init: RunEventStoreInit): SessionStore;
76
166
  }
77
167
 
78
- declare class StoragePathServiceImpl implements StoragePathService {
79
- resolvePaths(options?: ResolveStorageOptions): StoragePaths;
80
- }
168
+ /** Plain wins if both exist after interrupted compression; never replay twice. */
169
+ declare const resolveRunLogPath: (file: string) => string;
170
+ declare function readRunLogLines(file: string): AsyncGenerator<string>;
171
+
172
+ declare function searchOriginalMessages(file: string, options: {
173
+ query: string;
174
+ cursor?: string;
175
+ limit?: number;
176
+ }): Promise<ConversationSearchResult>;
177
+ declare function readOriginalMessage(file: string, options: {
178
+ id: string;
179
+ offset?: number;
180
+ limit?: number;
181
+ }): Promise<ConversationMessage | null>;
81
182
 
82
183
  type SessionStateStoreOptions = {
83
184
  paths?: StoragePaths;
@@ -86,19 +187,26 @@ type SessionStateStoreOptions = {
86
187
  detail?: string;
87
188
  }) => void;
88
189
  };
89
- declare class SessionStateStoreImpl implements SessionStateStore {
190
+ declare class SessionStateStoreImpl implements SessionStateStore, SessionRunRecorder {
191
+ /** Root that `session_runs.rel_path` values are relative to. */
192
+ readonly sessionsDir: string;
90
193
  private readonly legacyStateDir;
91
194
  private readonly messagesDir;
195
+ private readonly contextsDir;
92
196
  private readonly stateDbPath;
93
197
  private readonly ensureDirs;
94
198
  private db;
95
199
  private schemaInit;
96
200
  private readonly onError?;
97
201
  private lastDbUnavailableError;
202
+ private runIndexBackfill;
98
203
  constructor(options?: SessionStateStoreOptions);
99
204
  private getOrCreateDb;
100
205
  private resolveLegacyPath;
101
206
  private resolveMessagePath;
207
+ private contextPath;
208
+ private writeContext;
209
+ private ensureArchive;
102
210
  private openDatabase;
103
211
  private initDatabaseSchema;
104
212
  private tryGetDb;
@@ -106,21 +214,85 @@ declare class SessionStateStoreImpl implements SessionStateStore {
106
214
  private loadLegacy;
107
215
  private loadFromIndex;
108
216
  private saveToIndex;
217
+ appendMessages(sessionId: string, messages: SessionState["messages"]): Promise<void>;
218
+ searchMessages(sessionId: string, options: Parameters<typeof searchOriginalMessages>[1]): Promise<_codelia_core.ConversationSearchResult>;
219
+ readMessage(sessionId: string, options: Parameters<typeof readOriginalMessage>[1]): Promise<_codelia_core.ConversationMessage | null>;
109
220
  load(sessionId: string): Promise<SessionState | null>;
110
221
  save(state: SessionState): Promise<void>;
222
+ getSummary(sessionId: string): Promise<SessionStateSummary | null>;
223
+ /** Serializes pin changes with the final, synchronous unlink decision. */
224
+ withRetentionGuard<T>(sessionId: string, action: (summary: SessionStateSummary | null) => T): Promise<T>;
225
+ updateMetadata(sessionId: string, patch: {
226
+ pinned?: boolean;
227
+ archived?: boolean;
228
+ }): Promise<SessionStateSummary>;
229
+ /** Records a run log; idempotent, safe across concurrent runtimes. */
230
+ recordSessionRun(entry: SessionRunEntry): Promise<void>;
231
+ /** True when run_id is indexed for the session or was already rescanned. */
232
+ private isRunKnown;
233
+ /**
234
+ * The index answers for a session once a store-wide backfill finished and
235
+ * the session's latest run_id is either indexed or was already rescanned.
236
+ * The run_id check catches logs written by runtimes that predate the index.
237
+ */
238
+ private isSessionRunIndexComplete;
239
+ /** One store-wide header scan per process at a time; rows are idempotent. */
240
+ private backfillSessionRuns;
241
+ /**
242
+ * Returns the session's run logs, newest first. Falls back to one
243
+ * store-wide header scan (which indexes every session) only while the
244
+ * index cannot answer for this session.
245
+ */
246
+ listSessionRuns(sessionId: string): Promise<SessionRunEntry[]>;
111
247
  private listLegacySummaries;
112
248
  list(): Promise<SessionStateSummary[]>;
113
249
  }
114
250
 
251
+ declare const RUN_LOG_RETENTION_MS: number;
252
+ type RunLogCleanupResult = {
253
+ deleted: number;
254
+ compressed: number;
255
+ skipped: number;
256
+ failed: number;
257
+ reclaimed_bytes: number;
258
+ };
259
+ declare function cleanupRunLogs(options: {
260
+ paths: StoragePaths;
261
+ sessions: SessionStateStoreImpl;
262
+ now?: number;
263
+ sessionId?: string;
264
+ }): Promise<RunLogCleanupResult>;
265
+
266
+ declare class StoragePathServiceImpl implements StoragePathService {
267
+ resolvePaths(options?: ResolveStorageOptions): StoragePaths;
268
+ }
269
+
115
270
  declare class SessionStoreWriterImpl implements SessionStore {
116
271
  readonly filePath: string;
117
- private readonly ensureDir;
272
+ readonly usageFilePath: string;
273
+ readonly diagnosticFilePath?: string;
274
+ private readonly paths;
275
+ private readonly runId;
276
+ private readonly startedAt;
277
+ private sessionId?;
278
+ private model?;
279
+ private readonly requestModels;
280
+ private activePath?;
118
281
  private writeChain;
282
+ private readonly runIndex?;
283
+ private readonly onRunIndexError?;
119
284
  constructor(options: {
120
285
  runId: string;
121
286
  startedAt: string;
122
287
  paths?: StoragePaths;
288
+ dump?: boolean;
289
+ /** Records `session -> run` in state.db when the header is appended. */
290
+ runIndex?: SessionRunRecorder;
291
+ onRunIndexError?: (error: unknown) => void;
123
292
  });
293
+ private projectNormalRecord;
294
+ /** Indexed before the log line exists so a written log is never unindexed. */
295
+ private recordRun;
124
296
  append(record: SessionRecord): Promise<void>;
125
297
  }
126
298
 
@@ -228,4 +400,4 @@ declare class ToolOutputCacheStoreImpl implements ToolOutputCacheStore {
228
400
  private resolvePath;
229
401
  }
230
402
 
231
- export { IMAGE_MAX_BYTES, ImageArtifactStore, type McpAuthFile, McpAuthStore, type McpOAuthTokens, type ProjectsPolicyFile, ProjectsPolicyStore, RunEventStoreFactoryImpl, SessionStateStoreImpl, SessionStoreWriterImpl, StoragePathServiceImpl, type TaskArtifact, type TaskKind, type TaskRecord, TaskRegistryStore, type TaskResult, type TaskState, type TaskTruncatedOutput, type TaskWorkspaceMode, ToolOutputCacheStoreImpl, ensureStorageDirs, resolveStoragePaths, validateImagePng };
403
+ export { type AttachmentStore, FileAttachmentStore, IMAGE_MAX_BYTES, ImageArtifactStore, type McpAuthFile, McpAuthStore, type McpOAuthTokens, type ProjectsPolicyFile, ProjectsPolicyStore, RUN_LOG_RETENTION_MS, RunEventStoreFactoryImpl, type RunLogCleanupResult, type SessionRunEntry, type SessionRunRecorder, SessionStateStoreImpl, SessionStoreWriterImpl, StoragePathServiceImpl, type StoredAttachment, type TaskArtifact, type TaskKind, type TaskRecord, TaskRegistryStore, type TaskResult, type TaskState, type TaskTruncatedOutput, type TaskWorkspaceMode, ToolOutputCacheStoreImpl, cleanupRunLogs, createAttachmentId, detectImageAttachmentType, ensureStorageDirs, getProcessIdentity, isAttachmentId, readRunLogLines, resolveIndexedRunLog, resolveRunLogPath, resolveStoragePaths, scanSessionRunLogs, validateImageAttachment, validateImagePng };
package/dist/index.d.ts CHANGED
@@ -1,15 +1,23 @@
1
- import { GeneratedImageMetadata, ImageArtifactRef, ImageMediaType, AttachedImageMetadata, ImageArtifactMetadata, ApprovalMode, SubagentLineage, AgentMessage, TaskTerminationReason, TaskUsage } from '@codelia/shared-types';
2
- import { StoragePaths, ResolveStorageOptions, RunEventStoreFactory, RunEventStoreInit, SessionStore, StoragePathService, SessionStateStore, SessionState, SessionStateSummary, SessionRecord, ToolOutputCacheStore, ToolOutputCacheRecord, ToolOutputRef, ToolOutputCacheReadOptions, ToolOutputCacheSearchOptions } from '@codelia/core';
1
+ import * as _codelia_core from '@codelia/core';
2
+ import { StoragePaths, ResolveStorageOptions, RunEventStoreFactory, RunEventStoreInit, SessionStore, ConversationSearchResult, ConversationMessage, SessionStateStore, SessionState, SessionStateSummary, StoragePathService, SessionRecord, ToolOutputCacheStore, ToolOutputCacheRecord, ToolOutputRef, ToolOutputCacheReadOptions, ToolOutputCacheSearchOptions } from '@codelia/core';
3
3
  export { ResolveStorageOptions, StorageLayout, StoragePathService, StoragePaths } from '@codelia/core';
4
+ import { GeneratedImageMetadata, ImageArtifactRef, ImageMediaType, AttachedImageMetadata, ImageArtifactMetadata, AttachmentRef, ApprovalMode, SubagentLineage, AgentMessage, TaskTerminationReason, TaskUsage } from '@codelia/shared-types';
4
5
 
5
- /** A workspace-scoped store. No TTL deletion: references must survive session resume. */
6
+ type AttachmentWriteOptions = {
7
+ artifactId?: string;
8
+ ownerSessionId?: string;
9
+ };
10
+ /** Workspace image storage with session-scoped access for copied files. */
6
11
  declare class ImageArtifactStore {
7
12
  readonly root: string;
8
- constructor(root: string);
9
- save(bytes: Buffer, provenance: Omit<GeneratedImageMetadata, keyof ImageArtifactRef | "created_at">): Promise<GeneratedImageMetadata>;
10
- saveAttachment(bytes: Buffer, mediaType: ImageMediaType): Promise<AttachedImageMetadata>;
13
+ private readonly getSessionId?;
14
+ constructor(root: string, getSessionId?: (() => string | null) | undefined);
15
+ save(bytes: Buffer, provenance: Omit<GeneratedImageMetadata, keyof ImageArtifactRef | "created_at">, mediaType?: "image/png" | "image/jpeg"): Promise<GeneratedImageMetadata>;
16
+ saveAttachment(bytes: Buffer, mediaType: ImageMediaType, { artifactId, ownerSessionId, }?: AttachmentWriteOptions): Promise<AttachedImageMetadata>;
17
+ /** Roll back a newly uploaded attachment before its ownership batch is published. */
18
+ discardUnpublishedAttachment(ref: ImageArtifactRef, sessionId: string): Promise<void>;
11
19
  private persist;
12
- read(artifactId: string): Promise<{
20
+ read(artifactId: string, sessionId?: string | null): Promise<{
13
21
  metadata: ImageArtifactMetadata;
14
22
  bytes: Buffer;
15
23
  }>;
@@ -24,6 +32,47 @@ declare class ImageArtifactStore {
24
32
  }>;
25
33
  }
26
34
 
35
+ type StoredAttachment = {
36
+ ref: AttachmentRef;
37
+ imageRef?: ImageArtifactRef;
38
+ };
39
+ /** Host-owned originals and ownership index. commit must publish the entire batch atomically. */
40
+ type AttachmentStore = {
41
+ commit(sessionId: string, entries: readonly {
42
+ record: StoredAttachment;
43
+ bytes: Buffer;
44
+ }[]): Promise<void>;
45
+ /** Validate ownership and integrity before returning an admitted reference. */
46
+ lookup(attachmentId: string, sessionId: string): Promise<StoredAttachment | null>;
47
+ /** Check ownership and integrity of the returned byte range. */
48
+ read(attachmentId: string, sessionId: string, offset: number, length: number): Promise<Uint8Array>;
49
+ resolveImage?: ImageArtifactStore["resolve"];
50
+ };
51
+ declare const createAttachmentId: () => string;
52
+ declare const isAttachmentId: (id: string) => boolean;
53
+ /** An ownership marker makes every member of a batch visible at once. */
54
+ declare class FileAttachmentStore implements AttachmentStore {
55
+ readonly root: string;
56
+ private readonly images;
57
+ constructor(root: string, images: ImageArtifactStore);
58
+ resolveImage: NonNullable<AttachmentStore["resolveImage"]>;
59
+ commit(sessionId: string, entries: readonly {
60
+ record: StoredAttachment;
61
+ bytes: Buffer;
62
+ }[]): Promise<void>;
63
+ lookup(attachmentId: string, sessionId: string): Promise<StoredAttachment | null>;
64
+ read(attachmentId: string, sessionId: string, offset: number, length: number): Promise<Uint8Array>;
65
+ private metadata;
66
+ private readImage;
67
+ }
68
+
69
+ declare function detectImageAttachmentType(bytes: Buffer): ImageMediaType | undefined;
70
+ /** Bounded header validation; attachment originals are not decoded or re-encoded. */
71
+ declare function validateImageAttachment(bytes: Buffer, mediaType: ImageMediaType): {
72
+ width: number;
73
+ height: number;
74
+ };
75
+
27
76
  declare const IMAGE_MAX_BYTES: number;
28
77
  /** Validate chunks, CRC and bounded decompression before accepting provider bytes. */
29
78
  declare function validateImagePng(bytes: Buffer): Promise<{
@@ -54,6 +103,11 @@ declare class McpAuthStore {
54
103
  declare function resolveStoragePaths(options?: ResolveStorageOptions): StoragePaths;
55
104
  declare function ensureStorageDirs(paths: StoragePaths): Promise<void>;
56
105
 
106
+ /** Identity guards PID reuse. Failure is unknown, never permission to kill or remove a live-writer marker. */
107
+ declare const getProcessIdentity: (pid: number, options?: {
108
+ canonicalEnvironment?: boolean;
109
+ }) => Promise<string | null>;
110
+
57
111
  type ProjectsPolicyFile = {
58
112
  version: 1;
59
113
  default?: {
@@ -71,13 +125,60 @@ declare class ProjectsPolicyStore {
71
125
  save(data: ProjectsPolicyFile): Promise<void>;
72
126
  }
73
127
 
128
+ /** One run log of a session, as recorded in `state.db` (`session_runs`). */
129
+ type SessionRunEntry = {
130
+ session_id: string;
131
+ run_id: string;
132
+ /** Canonical `YYYY/MM/DD/<name>.jsonl` path relative to `sessionsDir`. */
133
+ rel_path: string;
134
+ started_at: string;
135
+ };
136
+ /** Narrow write capability handed to run log writers. */
137
+ type SessionRunRecorder = {
138
+ recordSessionRun: (entry: SessionRunEntry) => Promise<void>;
139
+ };
140
+ /**
141
+ * Resolves an indexed run log to a readable path: plain wins, then `.gz`.
142
+ * Only regular files qualify (no symlink/FIFO/directory, as the directory scan
143
+ * admitted only `isFile()` entries). Returns undefined otherwise.
144
+ */
145
+ declare const resolveIndexedRunLog: (sessionsDir: string, relPath: string) => string | undefined;
146
+ /**
147
+ * Reads every run log header under `sessionsDir` (the legacy, store-wide scan)
148
+ * and returns one entry per log whose header names a session. Unreadable or
149
+ * header-less files are skipped, as the legacy history scan did.
150
+ */
151
+ declare const scanSessionRunLogs: (sessionsDir: string) => Promise<SessionRunEntry[]>;
152
+
74
153
  declare class RunEventStoreFactoryImpl implements RunEventStoreFactory {
154
+ private runIndex?;
155
+ private readonly onRunIndexError?;
156
+ /**
157
+ * `runIndex` records each run in state.db (`session_runs`). When omitted, a
158
+ * default-path SessionStateStoreImpl is created on the first run so every
159
+ * normal run log stays indexed.
160
+ */
161
+ constructor(options?: {
162
+ runIndex?: SessionRunRecorder;
163
+ onRunIndexError?: (error: unknown) => void;
164
+ });
75
165
  create(init: RunEventStoreInit): SessionStore;
76
166
  }
77
167
 
78
- declare class StoragePathServiceImpl implements StoragePathService {
79
- resolvePaths(options?: ResolveStorageOptions): StoragePaths;
80
- }
168
+ /** Plain wins if both exist after interrupted compression; never replay twice. */
169
+ declare const resolveRunLogPath: (file: string) => string;
170
+ declare function readRunLogLines(file: string): AsyncGenerator<string>;
171
+
172
+ declare function searchOriginalMessages(file: string, options: {
173
+ query: string;
174
+ cursor?: string;
175
+ limit?: number;
176
+ }): Promise<ConversationSearchResult>;
177
+ declare function readOriginalMessage(file: string, options: {
178
+ id: string;
179
+ offset?: number;
180
+ limit?: number;
181
+ }): Promise<ConversationMessage | null>;
81
182
 
82
183
  type SessionStateStoreOptions = {
83
184
  paths?: StoragePaths;
@@ -86,19 +187,26 @@ type SessionStateStoreOptions = {
86
187
  detail?: string;
87
188
  }) => void;
88
189
  };
89
- declare class SessionStateStoreImpl implements SessionStateStore {
190
+ declare class SessionStateStoreImpl implements SessionStateStore, SessionRunRecorder {
191
+ /** Root that `session_runs.rel_path` values are relative to. */
192
+ readonly sessionsDir: string;
90
193
  private readonly legacyStateDir;
91
194
  private readonly messagesDir;
195
+ private readonly contextsDir;
92
196
  private readonly stateDbPath;
93
197
  private readonly ensureDirs;
94
198
  private db;
95
199
  private schemaInit;
96
200
  private readonly onError?;
97
201
  private lastDbUnavailableError;
202
+ private runIndexBackfill;
98
203
  constructor(options?: SessionStateStoreOptions);
99
204
  private getOrCreateDb;
100
205
  private resolveLegacyPath;
101
206
  private resolveMessagePath;
207
+ private contextPath;
208
+ private writeContext;
209
+ private ensureArchive;
102
210
  private openDatabase;
103
211
  private initDatabaseSchema;
104
212
  private tryGetDb;
@@ -106,21 +214,85 @@ declare class SessionStateStoreImpl implements SessionStateStore {
106
214
  private loadLegacy;
107
215
  private loadFromIndex;
108
216
  private saveToIndex;
217
+ appendMessages(sessionId: string, messages: SessionState["messages"]): Promise<void>;
218
+ searchMessages(sessionId: string, options: Parameters<typeof searchOriginalMessages>[1]): Promise<_codelia_core.ConversationSearchResult>;
219
+ readMessage(sessionId: string, options: Parameters<typeof readOriginalMessage>[1]): Promise<_codelia_core.ConversationMessage | null>;
109
220
  load(sessionId: string): Promise<SessionState | null>;
110
221
  save(state: SessionState): Promise<void>;
222
+ getSummary(sessionId: string): Promise<SessionStateSummary | null>;
223
+ /** Serializes pin changes with the final, synchronous unlink decision. */
224
+ withRetentionGuard<T>(sessionId: string, action: (summary: SessionStateSummary | null) => T): Promise<T>;
225
+ updateMetadata(sessionId: string, patch: {
226
+ pinned?: boolean;
227
+ archived?: boolean;
228
+ }): Promise<SessionStateSummary>;
229
+ /** Records a run log; idempotent, safe across concurrent runtimes. */
230
+ recordSessionRun(entry: SessionRunEntry): Promise<void>;
231
+ /** True when run_id is indexed for the session or was already rescanned. */
232
+ private isRunKnown;
233
+ /**
234
+ * The index answers for a session once a store-wide backfill finished and
235
+ * the session's latest run_id is either indexed or was already rescanned.
236
+ * The run_id check catches logs written by runtimes that predate the index.
237
+ */
238
+ private isSessionRunIndexComplete;
239
+ /** One store-wide header scan per process at a time; rows are idempotent. */
240
+ private backfillSessionRuns;
241
+ /**
242
+ * Returns the session's run logs, newest first. Falls back to one
243
+ * store-wide header scan (which indexes every session) only while the
244
+ * index cannot answer for this session.
245
+ */
246
+ listSessionRuns(sessionId: string): Promise<SessionRunEntry[]>;
111
247
  private listLegacySummaries;
112
248
  list(): Promise<SessionStateSummary[]>;
113
249
  }
114
250
 
251
+ declare const RUN_LOG_RETENTION_MS: number;
252
+ type RunLogCleanupResult = {
253
+ deleted: number;
254
+ compressed: number;
255
+ skipped: number;
256
+ failed: number;
257
+ reclaimed_bytes: number;
258
+ };
259
+ declare function cleanupRunLogs(options: {
260
+ paths: StoragePaths;
261
+ sessions: SessionStateStoreImpl;
262
+ now?: number;
263
+ sessionId?: string;
264
+ }): Promise<RunLogCleanupResult>;
265
+
266
+ declare class StoragePathServiceImpl implements StoragePathService {
267
+ resolvePaths(options?: ResolveStorageOptions): StoragePaths;
268
+ }
269
+
115
270
  declare class SessionStoreWriterImpl implements SessionStore {
116
271
  readonly filePath: string;
117
- private readonly ensureDir;
272
+ readonly usageFilePath: string;
273
+ readonly diagnosticFilePath?: string;
274
+ private readonly paths;
275
+ private readonly runId;
276
+ private readonly startedAt;
277
+ private sessionId?;
278
+ private model?;
279
+ private readonly requestModels;
280
+ private activePath?;
118
281
  private writeChain;
282
+ private readonly runIndex?;
283
+ private readonly onRunIndexError?;
119
284
  constructor(options: {
120
285
  runId: string;
121
286
  startedAt: string;
122
287
  paths?: StoragePaths;
288
+ dump?: boolean;
289
+ /** Records `session -> run` in state.db when the header is appended. */
290
+ runIndex?: SessionRunRecorder;
291
+ onRunIndexError?: (error: unknown) => void;
123
292
  });
293
+ private projectNormalRecord;
294
+ /** Indexed before the log line exists so a written log is never unindexed. */
295
+ private recordRun;
124
296
  append(record: SessionRecord): Promise<void>;
125
297
  }
126
298
 
@@ -228,4 +400,4 @@ declare class ToolOutputCacheStoreImpl implements ToolOutputCacheStore {
228
400
  private resolvePath;
229
401
  }
230
402
 
231
- export { IMAGE_MAX_BYTES, ImageArtifactStore, type McpAuthFile, McpAuthStore, type McpOAuthTokens, type ProjectsPolicyFile, ProjectsPolicyStore, RunEventStoreFactoryImpl, SessionStateStoreImpl, SessionStoreWriterImpl, StoragePathServiceImpl, type TaskArtifact, type TaskKind, type TaskRecord, TaskRegistryStore, type TaskResult, type TaskState, type TaskTruncatedOutput, type TaskWorkspaceMode, ToolOutputCacheStoreImpl, ensureStorageDirs, resolveStoragePaths, validateImagePng };
403
+ export { type AttachmentStore, FileAttachmentStore, IMAGE_MAX_BYTES, ImageArtifactStore, type McpAuthFile, McpAuthStore, type McpOAuthTokens, type ProjectsPolicyFile, ProjectsPolicyStore, RUN_LOG_RETENTION_MS, RunEventStoreFactoryImpl, type RunLogCleanupResult, type SessionRunEntry, type SessionRunRecorder, SessionStateStoreImpl, SessionStoreWriterImpl, StoragePathServiceImpl, type StoredAttachment, type TaskArtifact, type TaskKind, type TaskRecord, TaskRegistryStore, type TaskResult, type TaskState, type TaskTruncatedOutput, type TaskWorkspaceMode, ToolOutputCacheStoreImpl, cleanupRunLogs, createAttachmentId, detectImageAttachmentType, ensureStorageDirs, getProcessIdentity, isAttachmentId, readRunLogLines, resolveIndexedRunLog, resolveRunLogPath, resolveStoragePaths, scanSessionRunLogs, validateImageAttachment, validateImagePng };