@fiale-plus/pi-rogue 0.2.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 (68) hide show
  1. package/README.md +50 -0
  2. package/node_modules/@fiale-plus/pi-core/README.md +13 -0
  3. package/node_modules/@fiale-plus/pi-core/package.json +25 -0
  4. package/node_modules/@fiale-plus/pi-core/src/context-broker.ts +109 -0
  5. package/node_modules/@fiale-plus/pi-core/src/index.ts +5 -0
  6. package/node_modules/@fiale-plus/pi-core/src/paths.ts +36 -0
  7. package/node_modules/@fiale-plus/pi-core/src/risk.test.ts +129 -0
  8. package/node_modules/@fiale-plus/pi-core/src/risk.ts +97 -0
  9. package/node_modules/@fiale-plus/pi-core/src/storage.ts +39 -0
  10. package/node_modules/@fiale-plus/pi-core/src/text.test.ts +36 -0
  11. package/node_modules/@fiale-plus/pi-core/src/text.ts +14 -0
  12. package/node_modules/@fiale-plus/pi-rogue-advisor/README.md +59 -0
  13. package/node_modules/@fiale-plus/pi-rogue-advisor/advisor/index.ts +1 -0
  14. package/node_modules/@fiale-plus/pi-rogue-advisor/assets/binary-gate-model.json +24026 -0
  15. package/node_modules/@fiale-plus/pi-rogue-advisor/package.json +50 -0
  16. package/node_modules/@fiale-plus/pi-rogue-advisor/skills/advisor/SKILL.md +51 -0
  17. package/node_modules/@fiale-plus/pi-rogue-advisor/src/binary-gate-features.test.ts +19 -0
  18. package/node_modules/@fiale-plus/pi-rogue-advisor/src/binary-gate-features.ts +248 -0
  19. package/node_modules/@fiale-plus/pi-rogue-advisor/src/binary-gate.test.ts +66 -0
  20. package/node_modules/@fiale-plus/pi-rogue-advisor/src/completions.test.ts +28 -0
  21. package/node_modules/@fiale-plus/pi-rogue-advisor/src/completions.ts +79 -0
  22. package/node_modules/@fiale-plus/pi-rogue-advisor/src/extension.test.ts +364 -0
  23. package/node_modules/@fiale-plus/pi-rogue-advisor/src/extension.ts +1677 -0
  24. package/node_modules/@fiale-plus/pi-rogue-advisor/src/index.ts +3 -0
  25. package/node_modules/@fiale-plus/pi-rogue-advisor/src/internal.ts +63 -0
  26. package/node_modules/@fiale-plus/pi-rogue-advisor/src/loop-convergence.test.ts +512 -0
  27. package/node_modules/@fiale-plus/pi-rogue-advisor/src/preflight-signals.test.ts +22 -0
  28. package/node_modules/@fiale-plus/pi-rogue-advisor/src/preflight-signals.ts +21 -0
  29. package/node_modules/@fiale-plus/pi-rogue-advisor/src/router.test.ts +126 -0
  30. package/node_modules/@fiale-plus/pi-rogue-advisor/src/router.ts +580 -0
  31. package/node_modules/@fiale-plus/pi-rogue-advisor/src/state-versioning.test.ts +227 -0
  32. package/node_modules/@fiale-plus/pi-rogue-context-broker/README.md +53 -0
  33. package/node_modules/@fiale-plus/pi-rogue-context-broker/package.json +31 -0
  34. package/node_modules/@fiale-plus/pi-rogue-context-broker/src/extension.test.ts +749 -0
  35. package/node_modules/@fiale-plus/pi-rogue-context-broker/src/extension.ts +818 -0
  36. package/node_modules/@fiale-plus/pi-rogue-context-broker/src/file.ts +191 -0
  37. package/node_modules/@fiale-plus/pi-rogue-context-broker/src/index.test.ts +302 -0
  38. package/node_modules/@fiale-plus/pi-rogue-context-broker/src/index.ts +369 -0
  39. package/node_modules/@fiale-plus/pi-rogue-context-broker/src/sqlite.test.ts +122 -0
  40. package/node_modules/@fiale-plus/pi-rogue-context-broker/src/sqlite.ts +561 -0
  41. package/node_modules/@fiale-plus/pi-rogue-orchestration/README.md +56 -0
  42. package/node_modules/@fiale-plus/pi-rogue-orchestration/orchestration/index.ts +1 -0
  43. package/node_modules/@fiale-plus/pi-rogue-orchestration/package.json +44 -0
  44. package/node_modules/@fiale-plus/pi-rogue-orchestration/skills/orchestration/SKILL.md +44 -0
  45. package/node_modules/@fiale-plus/pi-rogue-orchestration/src/advisor-checkins.test.ts +142 -0
  46. package/node_modules/@fiale-plus/pi-rogue-orchestration/src/advisor-checkins.ts +102 -0
  47. package/node_modules/@fiale-plus/pi-rogue-orchestration/src/autoresearch-state.ts +70 -0
  48. package/node_modules/@fiale-plus/pi-rogue-orchestration/src/autoresearch.test.ts +143 -0
  49. package/node_modules/@fiale-plus/pi-rogue-orchestration/src/autoresearch.ts +139 -0
  50. package/node_modules/@fiale-plus/pi-rogue-orchestration/src/completions.test.ts +23 -0
  51. package/node_modules/@fiale-plus/pi-rogue-orchestration/src/completions.ts +53 -0
  52. package/node_modules/@fiale-plus/pi-rogue-orchestration/src/extension.ts +23 -0
  53. package/node_modules/@fiale-plus/pi-rogue-orchestration/src/goal-resolution.ts +36 -0
  54. package/node_modules/@fiale-plus/pi-rogue-orchestration/src/goal.test.ts +182 -0
  55. package/node_modules/@fiale-plus/pi-rogue-orchestration/src/goal.ts +232 -0
  56. package/node_modules/@fiale-plus/pi-rogue-orchestration/src/index.ts +1 -0
  57. package/node_modules/@fiale-plus/pi-rogue-orchestration/src/internal.ts +98 -0
  58. package/node_modules/@fiale-plus/pi-rogue-orchestration/src/loop.ts +274 -0
  59. package/node_modules/@fiale-plus/pi-rogue-orchestration/src/novelty-guard.test.ts +35 -0
  60. package/node_modules/@fiale-plus/pi-rogue-orchestration/src/novelty-guard.ts +145 -0
  61. package/node_modules/@fiale-plus/pi-rogue-orchestration/src/state.ts +24 -0
  62. package/package.json +51 -0
  63. package/src/context-broker-file.ts +1 -0
  64. package/src/context-broker-sqlite.ts +1 -0
  65. package/src/context-broker.ts +1 -0
  66. package/src/extension.test.ts +68 -0
  67. package/src/extension.ts +27 -0
  68. package/src/index.ts +1 -0
@@ -0,0 +1,369 @@
1
+ import { createHash } from "node:crypto";
2
+ import { safeName } from "@fiale-plus/pi-core";
3
+ import type {
4
+ BoundedContextBroker,
5
+ ContextArtifact,
6
+ ContextArtifactInput,
7
+ ContextArtifactKind,
8
+ ContextArtifactTier,
9
+ ContextBrokerOptions,
10
+ ContextBrokerStatus,
11
+ ContextLookupQuery,
12
+ ContextPurgeOptions,
13
+ } from "@fiale-plus/pi-core";
14
+
15
+ export type {
16
+ BoundedContextBroker,
17
+ ContextArtifact,
18
+ ContextArtifactInput,
19
+ ContextArtifactKind,
20
+ ContextArtifactTier,
21
+ ContextBrokerOptions,
22
+ ContextBrokerStatus,
23
+ ContextLookupQuery,
24
+ ContextPurgeOptions,
25
+ } from "@fiale-plus/pi-core";
26
+
27
+ const DEFAULT_MAX_RECORDS = 256;
28
+ const DEFAULT_MAX_BYTES = 128 * 1024 * 1024;
29
+ const DEFAULT_TTL_MS = 7 * 24 * 60 * 60 * 1000;
30
+ const DEFAULT_SUMMARY_BYTES = 320;
31
+ const DEFAULT_BRIEF_BYTES = 2_000;
32
+ const TIER_ORDER: Record<ContextArtifactTier, number> = { hot: 0, warm: 1, cold: 2 };
33
+ const TIER_REMOVAL_ORDER: Record<ContextArtifactTier, number> = { cold: 0, warm: 1, hot: 2 };
34
+
35
+ function normalizeList(values: string[] | undefined): string[] {
36
+ return [...new Set((values ?? []).map((value) => String(value || "").trim()).filter(Boolean))];
37
+ }
38
+
39
+ function payloadText(payload: string | Buffer): string {
40
+ return Buffer.isBuffer(payload) ? payload.toString("utf8") : String(payload ?? "");
41
+ }
42
+
43
+ function payloadBytes(payload: string | Buffer): number {
44
+ return Buffer.isBuffer(payload) ? payload.length : Buffer.byteLength(String(payload ?? ""), "utf8");
45
+ }
46
+
47
+ function hashPayload(payload: string | Buffer): string {
48
+ return createHash("sha256").update(Buffer.isBuffer(payload) ? payload : String(payload)).digest("hex");
49
+ }
50
+
51
+ function normalizeNeedle(value: string | undefined): string {
52
+ return String(value ?? "").trim().toLowerCase();
53
+ }
54
+
55
+ function truncateUtf8(text: string, maxBytes: number): string {
56
+ const limit = Math.max(0, Math.floor(maxBytes));
57
+ if (Buffer.byteLength(text, "utf8") <= limit) return text;
58
+ if (limit === 0) return "";
59
+
60
+ const ellipsis = "…";
61
+ const ellipsisBytes = Buffer.byteLength(ellipsis, "utf8");
62
+ const contentLimit = Math.max(0, limit - ellipsisBytes);
63
+ let used = 0;
64
+ let result = "";
65
+
66
+ for (const char of text) {
67
+ const bytes = Buffer.byteLength(char, "utf8");
68
+ if (used + bytes > contentLimit) break;
69
+ result += char;
70
+ used += bytes;
71
+ }
72
+
73
+ if (Buffer.byteLength(result + ellipsis, "utf8") <= limit) return result + ellipsis;
74
+ return result;
75
+ }
76
+
77
+ function summarizeArtifact(summary: string | undefined, kind: ContextArtifactKind, bytes: number, sha256: string, maxBytes: number): string {
78
+ const cleaned = String(summary ?? "").replace(/\s+/g, " ").trim();
79
+ if (cleaned) return truncateUtf8(cleaned, maxBytes);
80
+ return truncateUtf8(`[${kind} payload stored externally; ${bytes} bytes; sha256=${sha256.slice(0, 16)}]`, maxBytes);
81
+ }
82
+
83
+ function classifyBaseTier(input: ContextArtifactInput, tags: string[]): ContextArtifactTier {
84
+ if (input.tier) return input.tier;
85
+ const normalizedTags = tags.map((tag) => tag.toLowerCase());
86
+ if (normalizedTags.includes("hot")) return "hot";
87
+ if (normalizedTags.includes("warm")) return "warm";
88
+ if (normalizedTags.includes("cold")) return "cold";
89
+ if (normalizedTags.some((tag) => tag === "error" || tag === "failed" || tag === "failure")) return "hot";
90
+ if (normalizedTags.some((tag) => tag === "archive" || tag === "historical" || tag === "completed")) return "cold";
91
+ if (input.kind === "advisor_brief" || input.kind === "memory_note") return "hot";
92
+ return "warm";
93
+ }
94
+
95
+ function artifactMatches(artifact: ContextArtifact, query: ContextLookupQuery): boolean {
96
+ if (query.id && artifact.id !== query.id) return false;
97
+ if (query.handle && artifact.handle !== query.handle) return false;
98
+ if (query.sessionId && artifact.sessionId !== query.sessionId) return false;
99
+ if (query.kind && artifact.kind !== query.kind) return false;
100
+ if (query.branch && artifact.branch !== query.branch) return false;
101
+ if (query.tier && artifact.tier !== query.tier) return false;
102
+ if (query.tag && !artifact.tags.includes(query.tag)) return false;
103
+ if (query.path) {
104
+ const queryPath = query.path.replace(/\/$/, "");
105
+ if (!artifact.paths.some((path) => path === query.path || path.startsWith(`${queryPath}/`))) return false;
106
+ }
107
+ if (query.commandPrefix && !artifact.command?.startsWith(query.commandPrefix)) return false;
108
+
109
+ const text = normalizeNeedle(query.text);
110
+ if (text) {
111
+ const haystack = [artifact.summary, artifact.payload, artifact.command, artifact.tags.join(" "), artifact.paths.join(" ")]
112
+ .join("\n")
113
+ .toLowerCase();
114
+ if (!haystack.includes(text)) return false;
115
+ }
116
+
117
+ return true;
118
+ }
119
+
120
+ function tierLine(artifact: ContextArtifact): string {
121
+ const pin = artifact.pinned ? " pinned" : "";
122
+ const path = artifact.paths.length ? ` paths=${artifact.paths.slice(0, 3).join(",")}` : "";
123
+ const tags = artifact.tags.length ? ` tags=${artifact.tags.slice(0, 3).join(",")}` : "";
124
+ return `- ${artifact.handle} tier=${artifact.tier} kind=${artifact.kind}${pin}${path}${tags} summary="${artifact.summary}"`;
125
+ }
126
+
127
+ export function createInMemoryContextBroker(options: ContextBrokerOptions = {}): BoundedContextBroker {
128
+ const maxRecords = Math.max(1, Math.floor(options.maxRecords ?? DEFAULT_MAX_RECORDS));
129
+ const maxBytes = Math.max(1, Math.floor(options.maxBytes ?? DEFAULT_MAX_BYTES));
130
+ const globalMaxRecords = typeof options.globalMaxRecords === "number" && Number.isFinite(options.globalMaxRecords)
131
+ ? Math.max(1, Math.floor(options.globalMaxRecords))
132
+ : Number.POSITIVE_INFINITY;
133
+ const globalMaxBytes = typeof options.globalMaxBytes === "number" && Number.isFinite(options.globalMaxBytes)
134
+ ? Math.max(1, Math.floor(options.globalMaxBytes))
135
+ : Number.POSITIVE_INFINITY;
136
+ const defaultTtlMs = Math.max(0, Math.floor(options.defaultTtlMs ?? DEFAULT_TTL_MS));
137
+ const tierTtlMs: Record<ContextArtifactTier, number> = {
138
+ hot: Math.max(0, Math.floor(options.hotTtlMs ?? defaultTtlMs)),
139
+ warm: Math.max(0, Math.floor(options.warmTtlMs ?? defaultTtlMs)),
140
+ cold: Math.max(0, Math.floor(options.coldTtlMs ?? defaultTtlMs)),
141
+ };
142
+ const tierMaxRecords: Record<ContextArtifactTier, number> = {
143
+ hot: Math.max(1, Math.floor(options.hotMaxRecords ?? maxRecords)),
144
+ warm: Math.max(1, Math.floor(options.warmMaxRecords ?? maxRecords)),
145
+ cold: Math.max(1, Math.floor(options.coldMaxRecords ?? maxRecords)),
146
+ };
147
+ const tierMaxBytes: Record<ContextArtifactTier, number> = {
148
+ hot: Math.max(1, Math.floor(options.hotMaxBytes ?? maxBytes)),
149
+ warm: Math.max(1, Math.floor(options.warmMaxBytes ?? maxBytes)),
150
+ cold: Math.max(1, Math.floor(options.coldMaxBytes ?? maxBytes)),
151
+ };
152
+ const summaryBytes = Math.max(16, Math.floor(options.summaryBytes ?? DEFAULT_SUMMARY_BYTES));
153
+ const defaultBriefBytes = Math.max(64, Math.floor(options.briefBytes ?? DEFAULT_BRIEF_BYTES));
154
+ let artifacts: Array<ContextArtifact & { sequence: number; baseTier: ContextArtifactTier }> = [];
155
+ let sequence = 0;
156
+
157
+ function currentStatus(): ContextBrokerStatus {
158
+ const bytes = artifacts.reduce((sum, artifact) => sum + artifact.bytes, 0);
159
+ const pinned = artifacts.filter((artifact) => artifact.pinned);
160
+ const byTier = (tier: ContextArtifactTier) => artifacts.filter((artifact) => artifact.tier === tier);
161
+ const hot = byTier("hot");
162
+ const warm = byTier("warm");
163
+ const cold = byTier("cold");
164
+ return {
165
+ records: artifacts.length,
166
+ bytes,
167
+ pinnedRecords: pinned.length,
168
+ pinnedBytes: pinned.reduce((sum, artifact) => sum + artifact.bytes, 0),
169
+ hotRecords: hot.length,
170
+ hotBytes: hot.reduce((sum, artifact) => sum + artifact.bytes, 0),
171
+ warmRecords: warm.length,
172
+ warmBytes: warm.reduce((sum, artifact) => sum + artifact.bytes, 0),
173
+ coldRecords: cold.length,
174
+ coldBytes: cold.reduce((sum, artifact) => sum + artifact.bytes, 0),
175
+ maxRecords,
176
+ maxBytes,
177
+ };
178
+ }
179
+
180
+ function dropExpired(now = Date.now(), protectedIds = new Set<string>()): void {
181
+ artifacts = artifacts.filter(
182
+ (artifact) => artifact.pinned || protectedIds.has(artifact.id) || !artifact.expiresAt || artifact.expiresAt > now,
183
+ );
184
+ }
185
+
186
+ function removalCandidates(sessionId: string, protectedIds: Set<string>, tier?: ContextArtifactTier): Array<{ artifact: ContextArtifact & { sequence: number; baseTier: ContextArtifactTier }; index: number }> {
187
+ return artifacts
188
+ .map((artifact, index) => ({ artifact, index }))
189
+ .filter(({ artifact }) => artifact.sessionId === sessionId && !artifact.pinned && !protectedIds.has(artifact.id) && (!tier || artifact.tier === tier))
190
+ .sort((a, b) => {
191
+ if (!tier && TIER_REMOVAL_ORDER[a.artifact.tier] !== TIER_REMOVAL_ORDER[b.artifact.tier]) {
192
+ return TIER_REMOVAL_ORDER[a.artifact.tier] - TIER_REMOVAL_ORDER[b.artifact.tier];
193
+ }
194
+ if (a.artifact.createdAt !== b.artifact.createdAt) return a.artifact.createdAt - b.artifact.createdAt;
195
+ return a.artifact.sequence - b.artifact.sequence;
196
+ });
197
+ }
198
+
199
+ function removalCandidatesGlobal(protectedIds: Set<string>, tier?: ContextArtifactTier): Array<{ artifact: ContextArtifact & { sequence: number; baseTier: ContextArtifactTier }; index: number }> {
200
+ return artifacts
201
+ .map((artifact, index) => ({ artifact, index }))
202
+ .filter(({ artifact }) => !artifact.pinned && !protectedIds.has(artifact.id) && (!tier || artifact.tier === tier))
203
+ .sort((a, b) => {
204
+ if (!tier && TIER_REMOVAL_ORDER[a.artifact.tier] !== TIER_REMOVAL_ORDER[b.artifact.tier]) {
205
+ return TIER_REMOVAL_ORDER[a.artifact.tier] - TIER_REMOVAL_ORDER[b.artifact.tier];
206
+ }
207
+ if (a.artifact.createdAt !== b.artifact.createdAt) return a.artifact.createdAt - b.artifact.createdAt;
208
+ return a.artifact.sequence - b.artifact.sequence;
209
+ });
210
+ }
211
+
212
+ function withinCaps(sessionId: string, tier?: ContextArtifactTier): boolean {
213
+ const sessionArtifacts = artifacts.filter((artifact) => artifact.sessionId === sessionId && (!tier || artifact.tier === tier));
214
+ const recordsCap = tier ? tierMaxRecords[tier] : maxRecords;
215
+ const bytesCap = tier ? tierMaxBytes[tier] : maxBytes;
216
+ return sessionArtifacts.length <= recordsCap && sessionArtifacts.reduce((sum, artifact) => sum + artifact.bytes, 0) <= bytesCap;
217
+ }
218
+
219
+ function withinGlobalCaps(): boolean {
220
+ if (globalMaxRecords === Number.POSITIVE_INFINITY && globalMaxBytes === Number.POSITIVE_INFINITY) return true;
221
+ const records = artifacts.length;
222
+ const bytes = artifacts.reduce((sum, artifact) => sum + artifact.bytes, 0);
223
+ return records <= globalMaxRecords && bytes <= globalMaxBytes;
224
+ }
225
+
226
+ function prune(now = Date.now(), protectedIds = new Set<string>()): ContextBrokerStatus {
227
+ dropExpired(now, protectedIds);
228
+
229
+ for (const sessionId of new Set(artifacts.map((artifact) => artifact.sessionId))) {
230
+ for (const tier of ["cold", "warm", "hot"] as ContextArtifactTier[]) {
231
+ while (!withinCaps(sessionId, tier)) {
232
+ const candidate = removalCandidates(sessionId, protectedIds, tier)[0];
233
+ if (!candidate) break;
234
+ artifacts.splice(candidate.index, 1);
235
+ }
236
+ }
237
+
238
+ while (!withinCaps(sessionId)) {
239
+ const candidate = removalCandidates(sessionId, protectedIds)[0];
240
+ if (!candidate) break;
241
+ artifacts.splice(candidate.index, 1);
242
+ }
243
+ }
244
+
245
+ while (!withinGlobalCaps()) {
246
+ const candidate = removalCandidatesGlobal(protectedIds)[0];
247
+ if (!candidate) break;
248
+ artifacts.splice(candidate.index, 1);
249
+ }
250
+
251
+ return currentStatus();
252
+ }
253
+
254
+ function status(): ContextBrokerStatus {
255
+ dropExpired();
256
+ return currentStatus();
257
+ }
258
+
259
+ function purge(options: ContextPurgeOptions = {}): ContextBrokerStatus {
260
+ dropExpired();
261
+ const keepPinned = options.keepPinned ?? true;
262
+ artifacts = artifacts.filter((artifact) => {
263
+ if (options.sessionId && artifact.sessionId !== options.sessionId) return true;
264
+ return keepPinned && artifact.pinned;
265
+ });
266
+ return currentStatus();
267
+ }
268
+
269
+ function publish(input: ContextArtifactInput): ContextArtifact {
270
+ const now = input.createdAt ?? Date.now();
271
+ const payload = payloadText(input.payload);
272
+ const sha256 = hashPayload(input.payload);
273
+ const bytes = payloadBytes(input.payload);
274
+ const artifactSequence = ++sequence;
275
+ const id = `ctx-${now.toString(36)}-${String(artifactSequence).padStart(4, "0")}-${sha256.slice(0, 12)}`;
276
+ const session = safeName(input.sessionId || "session");
277
+ const kind = input.kind;
278
+ const tags = normalizeList(input.tags);
279
+ const baseTier = classifyBaseTier(input, tags);
280
+ const tier: ContextArtifactTier = input.pinned ? "hot" : baseTier;
281
+ const handle = `ctx://session/${session}/${kind}/${sha256.slice(0, 16)}/${id}`;
282
+ const ttlMs = input.ttlMs ?? tierTtlMs[tier];
283
+
284
+ const artifact: ContextArtifact & { sequence: number; baseTier: ContextArtifactTier } = {
285
+ id,
286
+ handle,
287
+ sessionId: input.sessionId,
288
+ kind,
289
+ createdAt: now,
290
+ updatedAt: now,
291
+ bytes,
292
+ sha256,
293
+ payload,
294
+ summary: summarizeArtifact(input.summary, kind, bytes, sha256, summaryBytes),
295
+ tags,
296
+ paths: normalizeList(input.paths),
297
+ command: input.command?.trim() || undefined,
298
+ branch: input.branch?.trim() || undefined,
299
+ tier,
300
+ expiresAt: ttlMs > 0 ? now + ttlMs : undefined,
301
+ pinned: Boolean(input.pinned),
302
+ parentIds: normalizeList(input.parentIds),
303
+ sequence: artifactSequence,
304
+ baseTier,
305
+ };
306
+
307
+ artifacts = [artifact, ...artifacts];
308
+ prune(now, new Set([artifact.id]));
309
+ return artifact;
310
+ }
311
+
312
+ function lookup(query: ContextLookupQuery = {}): ContextArtifact[] {
313
+ dropExpired();
314
+ const limit = Math.max(1, Math.floor(query.limit ?? (artifacts.length || 1)));
315
+ return artifacts
316
+ .filter((artifact) => artifactMatches(artifact, query))
317
+ .sort((a, b) => Number(b.pinned) - Number(a.pinned)
318
+ || TIER_ORDER[a.tier] - TIER_ORDER[b.tier]
319
+ || b.createdAt - a.createdAt
320
+ || b.sequence - a.sequence)
321
+ .slice(0, limit);
322
+ }
323
+
324
+ function pin(idOrHandle: string, pinned = true): ContextArtifact | null {
325
+ dropExpired();
326
+ const artifact = artifacts.find((candidate) => candidate.id === idOrHandle || candidate.handle === idOrHandle) ?? null;
327
+ if (!artifact) return null;
328
+ artifact.pinned = pinned;
329
+ artifact.tier = pinned ? "hot" : artifact.baseTier;
330
+ artifact.updatedAt = Date.now();
331
+ prune();
332
+ return artifacts.find((candidate) => candidate.id === artifact.id) ?? null;
333
+ }
334
+
335
+ function renderBrief(query: ContextLookupQuery & { budgetBytes?: number } = {}): string {
336
+ const budget = Math.max(64, Math.floor(query.budgetBytes ?? defaultBriefBytes));
337
+ const explicitCold = query.tier === "cold" || Boolean(query.handle || query.id);
338
+ const baseQuery = { ...query };
339
+ delete (baseQuery as { budgetBytes?: number }).budgetBytes;
340
+ const candidates = lookup({ ...baseQuery, limit: query.limit ?? 32 })
341
+ .filter((artifact) => explicitCold || artifact.tier !== "cold");
342
+ const hot = candidates.filter((artifact) => artifact.tier === "hot");
343
+ const warm = candidates.filter((artifact) => artifact.tier === "warm");
344
+ const cold = candidates.filter((artifact) => artifact.tier === "cold");
345
+ const lines = [
346
+ "## Context Broker",
347
+ `Budget: ${budget} bytes`,
348
+ hot.length ? "Hot:" : "",
349
+ ...hot.map(tierLine),
350
+ warm.length ? "Warm:" : "",
351
+ ...warm.map(tierLine),
352
+ cold.length ? "Cold:" : "",
353
+ ...cold.map(tierLine),
354
+ "Lookup: use broker lookup by handle/path/tag/kind/session before replaying raw payloads.",
355
+ ].filter(Boolean);
356
+
357
+ return truncateUtf8(lines.join("\n"), budget);
358
+ }
359
+
360
+ return {
361
+ publish,
362
+ lookup,
363
+ pin,
364
+ prune,
365
+ purge,
366
+ status,
367
+ renderBrief,
368
+ };
369
+ }
@@ -0,0 +1,122 @@
1
+ import { mkdtempSync, rmSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { describe, expect, it } from "vitest";
5
+ import { createSqliteContextBroker } from "./sqlite.js";
6
+
7
+ describe("createSqliteContextBroker", () => {
8
+ it("persists handles, payloads, tiers, and pin state without replay reconstruction", () => {
9
+ const dir = mkdtempSync(join(tmpdir(), "ctx-sqlite-test-"));
10
+ try {
11
+ const path = join(dir, "artifacts.sqlite");
12
+ let broker = createSqliteContextBroker({ path, defaultTtlMs: 0, briefBytes: 800 });
13
+ const warm = broker.publish({ sessionId: "s", kind: "tool_output", payload: "needle payload", summary: "warm summary", createdAt: Date.now() });
14
+ const cold = broker.publish({ sessionId: "s", kind: "subagent_result", payload: "archived payload", summary: "cold archive", tier: "cold", createdAt: Date.now() + 1 });
15
+ expect(broker.pin(cold.handle, true)?.tier).toBe("hot");
16
+
17
+ broker = createSqliteContextBroker({ path, defaultTtlMs: 0, briefBytes: 800 });
18
+
19
+ expect(broker.lookup({ handle: warm.handle })[0]?.payload).toBe("needle payload");
20
+ const reloadedCold = broker.lookup({ handle: cold.handle })[0];
21
+ expect(reloadedCold?.pinned).toBe(true);
22
+ expect(reloadedCold?.tier).toBe("hot");
23
+ expect(broker.renderBrief({ sessionId: "s" })).toContain(cold.handle);
24
+ } finally {
25
+ rmSync(dir, { recursive: true, force: true });
26
+ }
27
+ });
28
+
29
+ it("uses SQLite FTS for text lookup and enforces tier caps", () => {
30
+ const dir = mkdtempSync(join(tmpdir(), "ctx-sqlite-test-"));
31
+ try {
32
+ const broker = createSqliteContextBroker({ path: join(dir, "artifacts.sqlite"), defaultTtlMs: 0, coldMaxRecords: 1 });
33
+ const firstCold = broker.publish({ sessionId: "s", kind: "tool_output", payload: "alpha archive", tier: "cold", createdAt: Date.now() });
34
+ const secondCold = broker.publish({ sessionId: "s", kind: "tool_output", payload: "needle beta archive", tier: "cold", createdAt: Date.now() + 1 });
35
+
36
+ expect(broker.lookup({ id: firstCold.id })).toEqual([]);
37
+ expect(broker.lookup({ text: "needle" })[0]?.handle).toBe(secondCold.handle);
38
+ } finally {
39
+ rmSync(dir, { recursive: true, force: true });
40
+ }
41
+ });
42
+
43
+ it("dedupes replayed source artifacts so durable handles survive caps", () => {
44
+ const dir = mkdtempSync(join(tmpdir(), "ctx-sqlite-test-"));
45
+ try {
46
+ const path = join(dir, "artifacts.sqlite");
47
+ let broker = createSqliteContextBroker({ path, defaultTtlMs: 0, maxRecords: 1 });
48
+ const original = broker.publish({ sessionId: "s", kind: "tool_output", payload: "same replayed payload", parentIds: ["tool-call-1"], createdAt: Date.now() });
49
+
50
+ broker = createSqliteContextBroker({ path, defaultTtlMs: 0, maxRecords: 1 });
51
+ const replayed = broker.publish({ sessionId: "s", kind: "tool_output", payload: "same replayed payload", parentIds: ["tool-call-1"], createdAt: Date.now() + 1 });
52
+
53
+ expect(replayed.handle).toBe(original.handle);
54
+ expect(broker.lookup({ handle: original.handle })[0]?.payload).toBe("same replayed payload");
55
+ expect(broker.status().records).toBe(1);
56
+ } finally {
57
+ rmSync(dir, { recursive: true, force: true });
58
+ }
59
+ });
60
+
61
+ it("republishes expired replayed sources instead of returning dead handles", () => {
62
+ const dir = mkdtempSync(join(tmpdir(), "ctx-sqlite-test-"));
63
+ try {
64
+ const path = join(dir, "artifacts.sqlite");
65
+ let broker = createSqliteContextBroker({ path, defaultTtlMs: 1 });
66
+ const expired = broker.publish({ sessionId: "s", kind: "tool_output", payload: "expired payload", parentIds: ["tool-call-1"], createdAt: 1 });
67
+ expect(broker.lookup({ handle: expired.handle })).toEqual([]);
68
+
69
+ broker = createSqliteContextBroker({ path, defaultTtlMs: 1 });
70
+ const replayed = broker.publish({ sessionId: "s", kind: "tool_output", payload: "fresh replayed payload", parentIds: ["tool-call-1"], createdAt: 1, ttlMs: Date.now() + 60_000 });
71
+
72
+ expect(replayed.handle).not.toBe(expired.handle);
73
+ expect(broker.lookup({ handle: replayed.handle })[0]?.payload).toBe("fresh replayed payload");
74
+ } finally {
75
+ rmSync(dir, { recursive: true, force: true });
76
+ }
77
+ });
78
+
79
+ it("purges unpinned durable artifacts for a session", () => {
80
+ const dir = mkdtempSync(join(tmpdir(), "ctx-sqlite-test-"));
81
+ try {
82
+ const path = join(dir, "artifacts.sqlite");
83
+ let broker = createSqliteContextBroker({ path, defaultTtlMs: 0 });
84
+ const scratch = broker.publish({ sessionId: "s", kind: "tool_output", payload: "scratch" });
85
+ const pinned = broker.publish({ sessionId: "s", kind: "tool_output", payload: "keep", pinned: true });
86
+ const other = broker.publish({ sessionId: "other", kind: "tool_output", payload: "other" });
87
+
88
+ broker.purge({ sessionId: "s", keepPinned: true });
89
+ broker = createSqliteContextBroker({ path, defaultTtlMs: 0 });
90
+
91
+ expect(broker.lookup({ handle: scratch.handle })).toEqual([]);
92
+ expect(broker.lookup({ handle: pinned.handle })[0]?.payload).toBe("keep");
93
+ expect(broker.lookup({ handle: other.handle })[0]?.payload).toBe("other");
94
+ } finally {
95
+ rmSync(dir, { recursive: true, force: true });
96
+ }
97
+ });
98
+
99
+ it("enforces optional global caps across sessions", () => {
100
+ const dir = mkdtempSync(join(tmpdir(), "ctx-sqlite-test-"));
101
+ try {
102
+ const path = join(dir, "artifacts.sqlite");
103
+ const broker = createSqliteContextBroker({
104
+ path,
105
+ defaultTtlMs: 0,
106
+ globalMaxBytes: 10,
107
+ globalMaxRecords: Number.POSITIVE_INFINITY,
108
+ });
109
+ const one = broker.publish({ sessionId: "s1", kind: "tool_output", payload: "aaa", summary: "first" });
110
+ const two = broker.publish({ sessionId: "s2", kind: "tool_output", payload: "bbb", summary: "second" });
111
+ const pinned = broker.publish({ sessionId: "s3", kind: "tool_output", payload: "ccc", summary: "third", pinned: true });
112
+ const four = broker.publish({ sessionId: "s1", kind: "tool_output", payload: "ddd", summary: "fourth" });
113
+
114
+ expect(broker.lookup({ handle: one.handle })).toEqual([]);
115
+ expect(broker.lookup({ handle: two.handle })[0]?.payload).toBe("bbb");
116
+ expect(broker.lookup({ handle: pinned.handle })[0]?.payload).toBe("ccc");
117
+ expect(broker.lookup({ handle: four.handle })[0]?.payload).toBe("ddd");
118
+ } finally {
119
+ rmSync(dir, { recursive: true, force: true });
120
+ }
121
+ });
122
+ });