@aexol/spectral 0.9.156 → 0.9.158

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 (62) hide show
  1. package/dist/auth-helper.d.ts +3 -3
  2. package/dist/auth-helper.d.ts.map +1 -1
  3. package/dist/auth-helper.js +3 -3
  4. package/dist/cli.js +5 -13
  5. package/dist/commands/login.d.ts +1 -1
  6. package/dist/commands/login.js +6 -6
  7. package/dist/commands/serve.d.ts.map +1 -1
  8. package/dist/commands/serve.js +8 -20
  9. package/dist/commands/update.d.ts.map +1 -1
  10. package/dist/commands/update.js +6 -15
  11. package/dist/extensions/browser/index.d.ts +1 -1
  12. package/dist/extensions/browser/index.js +1 -1
  13. package/dist/extensions/image-generation/index.js +1 -1
  14. package/dist/memory/compaction.d.ts +0 -89
  15. package/dist/memory/compaction.d.ts.map +1 -1
  16. package/dist/memory/compaction.js +2 -759
  17. package/dist/memory/hooks/compaction-hook.d.ts.map +1 -1
  18. package/dist/memory/hooks/compaction-hook.js +9 -235
  19. package/dist/memory/prompts.d.ts +0 -4
  20. package/dist/memory/prompts.d.ts.map +1 -1
  21. package/dist/memory/prompts.js +0 -165
  22. package/dist/relay/auto-research.d.ts.map +1 -1
  23. package/dist/relay/auto-research.js +0 -1
  24. package/dist/sdk/ai/env-api-keys.d.ts.map +1 -1
  25. package/dist/sdk/ai/env-api-keys.js +0 -4
  26. package/dist/sdk/ai/models.generated.d.ts +0 -399
  27. package/dist/sdk/ai/models.generated.d.ts.map +1 -1
  28. package/dist/sdk/ai/models.generated.js +0 -395
  29. package/dist/sdk/ai/providers/register-builtins.d.ts +0 -4
  30. package/dist/sdk/ai/providers/register-builtins.d.ts.map +1 -1
  31. package/dist/sdk/ai/providers/register-builtins.js +0 -16
  32. package/dist/sdk/ai/types.d.ts +1 -1
  33. package/dist/sdk/ai/types.d.ts.map +1 -1
  34. package/dist/sdk/ai/utils/oauth/index.d.ts +0 -1
  35. package/dist/sdk/ai/utils/oauth/index.d.ts.map +1 -1
  36. package/dist/sdk/ai/utils/oauth/index.js +0 -3
  37. package/dist/sdk/coding-agent/config.d.ts.map +1 -1
  38. package/dist/sdk/coding-agent/config.js +2 -1
  39. package/dist/sdk/coding-agent/core/agent-session.d.ts.map +1 -1
  40. package/dist/sdk/coding-agent/core/agent-session.js +4 -0
  41. package/dist/sdk/coding-agent/core/extensions/native-extensions.d.ts.map +1 -1
  42. package/dist/sdk/coding-agent/core/extensions/native-extensions.js +0 -10
  43. package/dist/sdk/coding-agent/core/model-resolver.d.ts.map +1 -1
  44. package/dist/sdk/coding-agent/core/model-resolver.js +0 -1
  45. package/dist/server/agent-bridge.d.ts.map +1 -1
  46. package/dist/server/agent-bridge.js +0 -2
  47. package/dist/version.d.ts +4 -0
  48. package/dist/version.d.ts.map +1 -0
  49. package/dist/version.js +88 -0
  50. package/package.json +1 -1
  51. package/dist/extensions/kanban-bridge.d.ts +0 -24
  52. package/dist/extensions/kanban-bridge.d.ts.map +0 -1
  53. package/dist/extensions/kanban-bridge.js +0 -858
  54. package/dist/memory/unified-compaction.d.ts +0 -59
  55. package/dist/memory/unified-compaction.d.ts.map +0 -1
  56. package/dist/memory/unified-compaction.js +0 -332
  57. package/dist/sdk/ai/providers/anthropic.d.ts +0 -54
  58. package/dist/sdk/ai/providers/anthropic.d.ts.map +0 -1
  59. package/dist/sdk/ai/providers/anthropic.js +0 -921
  60. package/dist/sdk/ai/utils/oauth/anthropic.d.ts +0 -25
  61. package/dist/sdk/ai/utils/oauth/anthropic.d.ts.map +0 -1
  62. package/dist/sdk/ai/utils/oauth/anthropic.js +0 -334
@@ -1 +1 @@
1
- {"version":3,"file":"compaction-hook.d.ts","sourceRoot":"","sources":["../../../src/memory/hooks/compaction-hook.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAA+C,MAAM,iCAAiC,CAAC;AAqBjH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAgE7C,wBAAgB,sBAAsB,CAAC,GAAG,EAAE,YAAY,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI,CA2chF"}
1
+ {"version":3,"file":"compaction-hook.d.ts","sourceRoot":"","sources":["../../../src/memory/hooks/compaction-hook.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAA+C,MAAM,iCAAiC,CAAC;AAajH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAiB7C,wBAAgB,sBAAsB,CAAC,GAAG,EAAE,YAAY,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI,CA0MhF"}
@@ -1,61 +1,15 @@
1
1
  import { debugLog, withDebugLogContext } from "../debug-log.js";
2
- import { resolveTurnLimits } from "../config.js";
3
2
  import { getProjectObsStore } from "../project-observations-store.js";
4
3
  import { relayProjectObservations } from "../inter-agent-relay.js";
5
- import { collectObservationsByCoverage, findLastCompactionIndex, gapRawEntries, getMemoryState, } from "../branch.js";
6
- import { coverageTagCounts, deriveObservationCoverageTags, migrateLegacyReflections, observationPoolTokens, renderSummary, runReflector, } from "../compaction.js";
7
- import { serializeSourceAddressedBranchEntries } from "../serialize.js";
8
- import { estimateStringTokens } from "../tokens.js";
9
- import { OBSERVATION_CUSTOM_TYPE, } from "../types.js";
4
+ import { collectObservationsByCoverage, findLastCompactionIndex, getMemoryState, } from "../branch.js";
5
+ import { migrateLegacyReflections, renderSummary, } from "../compaction.js";
10
6
  import { deterministicPrune } from "../deterministic-pruner.js";
11
- import { generateUnifiedCompaction } from "../unified-compaction.js";
12
7
  function plural(count, singular, pluralForm = `${singular}s`) {
13
8
  return `${count.toLocaleString()} ${count === 1 ? singular : pluralForm}`;
14
9
  }
15
- function formatCoverageCounts(counts) {
16
- return `${counts.uncited.toLocaleString()}/${counts.cited.toLocaleString()}/${counts.reinforced.toLocaleString()} uncited/cited/reinforced`;
17
- }
18
- function formatReflectorStats(stats) {
19
- const failed = stats.failedPass === undefined ? "" : `, failed pass ${stats.failedPass}`;
20
- return `reflector ${plural(stats.toolCalls, "tool call")}, +${stats.added.toLocaleString()} added, ${stats.merged.toLocaleString()} merged, ${stats.promoted.toLocaleString()} promoted, ${stats.duplicates.toLocaleString()} duplicate/no-op, ${stats.unsupported.toLocaleString()} unsupported${failed}`;
21
- }
22
10
  function emitProgressLine(emitProgress, line) {
23
11
  emitProgress?.(`${line}\n`);
24
12
  }
25
- function compactToolDetails(details) {
26
- if (!details || typeof details !== "object")
27
- return "";
28
- const r = details;
29
- const parts = [];
30
- for (const key of ["added", "accepted", "dropped", "duplicates", "rejected", "remaining", "total"]) {
31
- const value = r[key];
32
- if (typeof value === "number")
33
- parts.push(`${key}=${value}`);
34
- if (Array.isArray(value))
35
- parts.push(`${key}=${value.length}`);
36
- }
37
- return parts.length ? ` (${parts.join(", ")})` : "";
38
- }
39
- function emitAgentLoopProgress(emitProgress, phase, event) {
40
- if (!emitProgress || !event || typeof event !== "object")
41
- return;
42
- const e = event;
43
- if (e.type === "message_update") {
44
- const assistantMessageEvent = e.assistantMessageEvent;
45
- if (assistantMessageEvent?.type === "text_delta" && typeof assistantMessageEvent.delta === "string") {
46
- emitProgress(assistantMessageEvent.delta);
47
- }
48
- return;
49
- }
50
- if (e.type === "tool_execution_start" && typeof e.toolName === "string") {
51
- emitProgressLine(emitProgress, `\n[${phase}] ${e.toolName} started`);
52
- return;
53
- }
54
- if (e.type === "tool_execution_end" && typeof e.toolName === "string") {
55
- const result = e.result && typeof e.result === "object" ? e.result : undefined;
56
- emitProgressLine(emitProgress, `[${phase}] ${e.toolName} complete${compactToolDetails(result?.details ?? result)}`);
57
- }
58
- }
59
13
  export function registerCompactionHook(ext, runtime) {
60
14
  ext.on("session_before_compact", async (event, ctx) => {
61
15
  if (runtime.compactHookInFlight) {
@@ -67,39 +21,26 @@ export function registerCompactionHook(ext, runtime) {
67
21
  runtime.ensureConfig(ctx.cwd);
68
22
  const runId = `compaction-${Date.now().toString(36)}-${Math.random().toString(16).slice(2, 8)}`;
69
23
  return await withDebugLogContext({ enabled: runtime.config.debugLog === true, cwd: ctx.cwd, runId }, async () => {
70
- const { preparation, branchEntries, signal } = event;
71
- const { firstKeptEntryId, tokensBefore, messagesToSummarize, settings: compactSettings } = preparation;
24
+ const { preparation, branchEntries } = event;
25
+ const { firstKeptEntryId, tokensBefore, messagesToSummarize } = preparation;
72
26
  const emitProgress = event.emitProgress;
73
27
  emitProgressLine(emitProgress, `Observational memory compaction started on ~${tokensBefore.toLocaleString()} tokens.`);
74
28
  const hasUI = ctx.hasUI;
75
29
  const ui = ctx.ui;
76
- const turnLimits = resolveTurnLimits(runtime.config);
77
30
  debugLog("compaction.start", {
78
31
  firstKeptEntryId,
79
32
  tokensBefore,
80
33
  branchEntryCount: branchEntries.length,
81
34
  reflectionThresholdTokens: runtime.config.reflectionThresholdTokens,
82
- turnLimits,
83
35
  messagesToSummarize: messagesToSummarize?.length ?? 0,
84
36
  });
85
- emitProgressLine(emitProgress, "Resolving memory model…");
86
- const resolved = await runtime.resolveModel(ctx);
87
- if (!resolved.ok) {
88
- debugLog("compaction.model_unavailable", { reason: resolved.reason });
89
- if (hasUI)
90
- ui?.notify(`Observational memory: cannot compact — ${resolved.reason}. ` +
91
- "Fix the model/API key and try /compact manually.", "error");
92
- return { cancel: true };
93
- }
94
- runtime.resolveFailureNotified = false;
95
- emitProgressLine(emitProgress, "Memory model ready.");
96
37
  let entries = branchEntries;
97
38
  if (runtime.observerPromise) {
98
39
  emitProgressLine(emitProgress, "Waiting for in-flight observer…");
99
40
  try {
100
41
  await runtime.observerPromise;
101
42
  }
102
- catch { /* already notified */ }
43
+ catch { }
103
44
  entries = ctx.sessionManager.getBranch();
104
45
  }
105
46
  const memoryState = getMemoryState(entries);
@@ -109,97 +50,18 @@ export function registerCompactionHook(ext, runtime) {
109
50
  reflections: memoryState.reflections.length,
110
51
  });
111
52
  emitProgressLine(emitProgress, `Loaded memory state: ${memoryState.committedObs.length} committed observations, ${memoryState.pendingObs.length} pending observations, ${memoryState.reflections.length} reflections.`);
112
- // ================================================================
113
- // UNIFIED COMPACTION: replaces core generateSummary() + sync
114
- // catch-up observer with a single LLM call.
115
- // ================================================================
116
- let gapObservationData = null;
117
- let unifiedNarrativeSummary;
118
- let unifiedObservations = [];
119
- const gap = gapRawEntries(entries, firstKeptEntryId);
120
- const gapChunk = gap.length > 0
121
- ? serializeSourceAddressedBranchEntries(gap)
122
- : { text: "", sourceEntryIds: [] };
123
- const hasGapContent = gapChunk.text.trim() && gapChunk.sourceEntryIds.length > 0;
124
- // Always run unified compaction — it replaces both the core narrative
125
- // summary and, when gap exists, the sync catch-up observer.
126
- emitProgressLine(emitProgress, "Running unified compaction (narrative + observations)…");
127
- debugLog("compaction.unified.start", {
128
- messagesToSummarize: messagesToSummarize.length,
129
- hasGapContent,
130
- gapEntryCount: gap.length,
131
- });
132
- try {
133
- const unifiedResult = await generateUnifiedCompaction({
134
- messagesToSummarize,
135
- gapChunk: hasGapContent ? gapChunk.text : undefined,
136
- gapSourceEntryIds: hasGapContent ? gapChunk.sourceEntryIds : undefined,
137
- model: resolved.model,
138
- apiKey: resolved.apiKey,
139
- headers: resolved.headers,
140
- signal,
141
- previousSummary: preparation.previousSummary,
142
- customInstructions: event.customInstructions,
143
- thinkingLevel: undefined, // Use model default
144
- reserveTokens: compactSettings.reserveTokens,
145
- });
146
- unifiedNarrativeSummary = unifiedResult.narrativeSummary;
147
- unifiedObservations = unifiedResult.observations;
148
- // If gap entries produced observations, record them as an
149
- // observation entry so recall can resolve source provenance.
150
- if (hasGapContent && unifiedObservations.length > 0) {
151
- const gapFromId = gap[0].id;
152
- const gapUpToId = gap[gap.length - 1].id;
153
- const observationTokens = unifiedObservations.reduce((sum, r) => sum + estimateStringTokens(r.content), 0);
154
- gapObservationData = {
155
- records: unifiedObservations,
156
- coversFromId: gapFromId,
157
- coversUpToId: gapUpToId,
158
- tokenCount: observationTokens,
159
- };
160
- ext.appendEntry(OBSERVATION_CUSTOM_TYPE, gapObservationData);
161
- emitProgressLine(emitProgress, `Unified compaction recorded ${unifiedObservations.length} observation${unifiedObservations.length === 1 ? "" : "s"} from gap (~${observationTokens.toLocaleString()} tokens).`);
162
- }
163
- debugLog("compaction.unified.result", {
164
- narrativeLength: unifiedNarrativeSummary?.length ?? 0,
165
- observationCount: unifiedObservations.length,
166
- });
167
- if (hasUI && ui) {
168
- ui.notify(`Observational memory: unified compaction produced ${unifiedObservations.length} observation${unifiedObservations.length === 1 ? "" : "s"} + narrative summary`, "info");
169
- }
170
- }
171
- catch (error) {
172
- const msg = error instanceof Error ? error.message : String(error);
173
- debugLog("compaction.unified.error", { errorMessage: msg });
174
- if (hasUI && ui)
175
- ui.notify(`Observational memory: unified compaction failed: ${msg}. Cancelling compaction.`, "warning");
176
- return { cancel: true };
177
- }
178
- // ================================================================
179
- // DELTA OBSERVATIONS: collect observer-trigger observations that
180
- // fall within this compaction window (from prior FKI to new FKI).
181
- // ================================================================
182
53
  const priorCompactionIdx = findLastCompactionIndex(entries);
183
54
  const priorFirstKeptEntryId = priorCompactionIdx >= 0 ? entries[priorCompactionIdx].firstKeptEntryId : undefined;
184
55
  const deltaObservationData = collectObservationsByCoverage(entries, priorFirstKeptEntryId, firstKeptEntryId);
185
- // Gap observations were already appended via ext.appendEntry above,
186
- // so collectObservationsByCoverage will pick them up. But to avoid
187
- // double-counting (the unified observations are also in our local set),
188
- // we build the working set from committed + delta, then merge unified
189
- // observations (deduplicated by content hash).
190
56
  const deltaObservationRecords = deltaObservationData.reduce((sum, data) => sum + data.records.length, 0);
191
57
  debugLog("compaction.delta", {
192
58
  priorFirstKeptEntryId,
193
59
  firstKeptEntryId,
194
60
  deltaObservationEntries: deltaObservationData.length,
195
61
  deltaObservationRecords,
196
- gapObservationRecords: gapObservationData?.records.length ?? 0,
197
62
  });
198
63
  emitProgressLine(emitProgress, `Compaction delta contains ${deltaObservationRecords} observation${deltaObservationRecords === 1 ? "" : "s"}.`);
199
- // ================================================================
200
- // NO-DELTA CASE: carry forward existing memory.
201
- // ================================================================
202
- if (deltaObservationData.length === 0 && unifiedObservations.length === 0) {
64
+ if (deltaObservationData.length === 0) {
203
65
  if (memoryState.committedObs.length === 0 && memoryState.reflections.length === 0) {
204
66
  debugLog("compaction.no_delta_cancel", {
205
67
  committedObservations: memoryState.committedObs.length,
@@ -236,21 +98,14 @@ export function registerCompactionHook(ext, runtime) {
236
98
  },
237
99
  };
238
100
  }
239
- // ================================================================
240
- // BUILD WORKING SET: committed + delta (from observer triggers) +
241
- // unified observations (from this compaction).
242
- // Deduplicate by content hash.
243
- // ================================================================
244
101
  const seenObsIds = new Set();
245
102
  const workingObservations = [];
246
- // Add committed observations first (most stable)
247
103
  for (const obs of memoryState.committedObs) {
248
104
  if (!seenObsIds.has(obs.id)) {
249
105
  seenObsIds.add(obs.id);
250
106
  workingObservations.push(obs);
251
107
  }
252
108
  }
253
- // Add delta observations (from observer triggers between compactions)
254
109
  for (const data of deltaObservationData) {
255
110
  for (const obs of data.records) {
256
111
  if (!seenObsIds.has(obs.id)) {
@@ -259,83 +114,14 @@ export function registerCompactionHook(ext, runtime) {
259
114
  }
260
115
  }
261
116
  }
262
- // Add unified observations (from this compaction's LLM call)
263
- for (const obs of unifiedObservations) {
264
- if (!seenObsIds.has(obs.id)) {
265
- seenObsIds.add(obs.id);
266
- workingObservations.push(obs);
267
- }
268
- }
269
117
  const workingReflections = migrateLegacyReflections(memoryState.reflections);
270
- const observationTokens = observationPoolTokens(workingObservations);
271
- // Reflection is an expensive LLM pass and this hook runs synchronously
272
- // inside session_before_compact. Previously we used the total pool size
273
- // here, which meant that once a session crossed the threshold every later
274
- // compaction ran the reflector again, even when all observations were
275
- // already covered by existing reflections. Gate on the unreflected pool
276
- // instead so routine compactions do not block the next user message.
277
- const coverageTags = deriveObservationCoverageTags(workingReflections, workingObservations);
278
- const unreflectedObservationTokens = workingObservations.reduce((sum, observation) => coverageTags.get(observation.id) === "uncited"
279
- ? sum + estimateStringTokens(observation.content)
280
- : sum, 0);
281
- emitProgressLine(emitProgress, `Working set: ${workingObservations.length} observations, ${workingReflections.length} reflections, ~${observationTokens.toLocaleString()} observation tokens (${unreflectedObservationTokens.toLocaleString()} unreflected).`);
118
+ emitProgressLine(emitProgress, `Working set: ${workingObservations.length} observations, ${workingReflections.length} reflections.`);
282
119
  debugLog("compaction.working_set", {
283
120
  observations: workingObservations.length,
284
121
  reflections: workingReflections.length,
285
- observationTokens,
286
122
  });
287
- // ================================================================
288
- // REFLECTOR (1 pass): crystallize durable reflections from
289
- // the observation pool. Preserves quality-critical iteration
290
- // via agentLoop with record_reflections tool.
291
- // ================================================================
292
- let finalReflections = workingReflections;
123
+ const finalReflections = workingReflections;
293
124
  let finalObservations = workingObservations;
294
- if (unreflectedObservationTokens >= runtime.config.reflectionThresholdTokens) {
295
- try {
296
- debugLog("compaction.reflect.start", {
297
- workingObservations: workingObservations.length,
298
- workingReflections: workingReflections.length,
299
- observationTokens,
300
- unreflectedObservationTokens,
301
- });
302
- if (hasUI)
303
- ui?.notify("Observational memory: running reflector (1 pass)...", "info");
304
- emitProgressLine(emitProgress, "Running reflector (1 pass)…");
305
- const coverageBefore = coverageTagCounts(workingReflections, workingObservations);
306
- const reflectorResult = await runReflector({
307
- model: resolved.model,
308
- apiKey: resolved.apiKey,
309
- headers: resolved.headers,
310
- signal,
311
- onEvent: (agentEvent) => emitAgentLoopProgress(emitProgress, "reflector", agentEvent),
312
- maxTurns: turnLimits.reflectorMaxTurnsPerPass,
313
- }, workingReflections, workingObservations, (pass, maxPasses) => emitProgressLine(emitProgress, `Reflector pass ${pass}/${maxPasses} started.`));
314
- finalReflections = reflectorResult.reflections;
315
- const coverageAfter = coverageTagCounts(finalReflections, workingObservations);
316
- debugLog("compaction.reflector.result", {
317
- stats: reflectorResult.stats,
318
- coverageBefore,
319
- coverageAfter,
320
- beforeReflections: workingReflections.length,
321
- afterReflections: finalReflections.length,
322
- });
323
- if (hasUI) {
324
- ui?.notify(`Observational memory: reflector — ${formatReflectorStats(reflectorResult.stats)}; coverage ${formatCoverageCounts(coverageBefore)} → ${formatCoverageCounts(coverageAfter)}`, "info");
325
- }
326
- }
327
- catch (error) {
328
- const msg = error instanceof Error ? error.message : String(error);
329
- debugLog("compaction.reflector.error", { errorMessage: msg });
330
- if (hasUI)
331
- ui?.notify(`Observational memory: reflector failed: ${msg}`, "warning");
332
- }
333
- }
334
- // ================================================================
335
- // DETERMINISTIC PRUNER: sort-based dropping instead of LLM agent.
336
- // Same logic as the LLM pruner (coverage → relevance → age)
337
- // but zero-cost and deterministic.
338
- // ================================================================
339
125
  const prunerResult = deterministicPrune(finalObservations, finalReflections, runtime.config.reflectionThresholdTokens);
340
126
  finalObservations = prunerResult.observations;
341
127
  debugLog("compaction.pruner.result", {
@@ -350,19 +136,9 @@ export function registerCompactionHook(ext, runtime) {
350
136
  if (prunerResult.fellBack && hasUI) {
351
137
  ui?.notify("Observational memory: pruner could not reach budget (too many protected observations)", "warning");
352
138
  }
353
- // ================================================================
354
- // BUILD FINAL SUMMARY: narrative (from unified call) +
355
- // observations/reflections markdown (from renderSummary).
356
- // This gives the LLM BOTH narrative context AND factual memory.
357
- // ================================================================
358
139
  emitProgressLine(emitProgress, `Rendering final memory summary from ${finalObservations.length} observations and ${finalReflections.length} reflections…`);
359
140
  const memoryMarkdown = renderSummary(finalReflections, finalObservations);
360
- // Combine: narrative summary first (what happened), then memory
361
- // (what was learned). Previous compaction's narrative is already
362
- // merged into the unified call's output via previousSummary.
363
- const summary = unifiedNarrativeSummary
364
- ? `${unifiedNarrativeSummary}\n\n---\n\n${memoryMarkdown}`
365
- : memoryMarkdown;
141
+ const summary = memoryMarkdown;
366
142
  if (finalObservations.length === 0) {
367
143
  throw new Error("invariant violated: finalObservations empty after delta guard");
368
144
  }
@@ -377,12 +153,10 @@ export function registerCompactionHook(ext, runtime) {
377
153
  finalReflections: finalReflections.length,
378
154
  firstKeptEntryId,
379
155
  tokensBefore,
380
- hasNarrative: !!unifiedNarrativeSummary,
381
156
  });
382
157
  emitProgressLine(emitProgress, `Compaction assembled — ${finalObservations.length} observation${finalObservations.length === 1 ? "" : "s"}, ${finalReflections.length} reflection${finalReflections.length === 1 ? "" : "s"}.`);
383
158
  if (hasUI)
384
159
  ui?.notify(`Observational memory: compaction assembled — ${finalObservations.length} observation${finalObservations.length === 1 ? "" : "s"}, ${finalReflections.length} reflection${finalReflections.length === 1 ? "" : "s"}`, "info");
385
- // Promote reflections as project observations (cross-session durable memory).
386
160
  persistProjectObservations(ctx, finalReflections);
387
161
  return {
388
162
  compaction: {
@@ -3,9 +3,5 @@ export declare const OBSERVATION_CONTENT_RULES = "Observation content rules:\n\n
3
3
  export declare const DETAIL_PRESERVATION_SCHEMA = "Detail preservation. When an observation references specific things, preserve the distinguishing details so future queries can still find them:\n\n- File/location: full path + line number when relevant (src/auth.ts:45, not \"the auth file\").\n- Identifiers and names: package names, function names, variable names, handles, ticket ids, commit SHAs, error codes. Keep them verbatim.\n- Error messages: quote verbatim.\n BAD: Build failed with a type error.\n GOOD: Build failed: TS2322: Type 'string | undefined' is not assignable to type 'string' at src/auth.ts:47.\n- Numerical results: exact values, units, and direction.\n BAD: Optimization made it faster.\n GOOD: Optimization reduced p95 latency from 420ms to 180ms (57% faster).\n- Quantities and counts: \"3 failing tests (auth.test.ts, users.test.ts, routes.test.ts)\" not \"some failing tests\".\n- Recommendation or decision lists: preserve the distinguishing attribute per item.\n BAD: Assistant recommended 3 auth libraries.\n GOOD: Assistant recommended auth libraries: Lucia (session-based, minimal), NextAuth (OAuth-heavy, Next-native), Clerk (hosted, paid).\n- Role / participation: capture the user's role at an event, not just attendance.\n BAD: User worked on the migration.\n GOOD: User led the migration from MySQL to Postgres.\n\nIf a detail is non-obvious from the code or git history, it belongs in the observation. If it is trivially re-derivable, it does not.";
4
4
  export declare const RELEVANCE_RUBRIC = "Relevance levels (pick one per observation; this field drives future pruning):\n\n- critical: user assertions about identity, role, or persistent preferences; explicit corrections (\"no, don't do X\"); concrete completions that future runs MUST NOT redo. These are load-bearing and will NEVER be dropped. Why this matters: if a \"critical\" item is lost, the assistant may redo finished work, contradict a correction, or misrepresent who the user is.\n- high: non-trivial technical decisions, architectural direction, unresolved blockers, key constraints. Worth keeping across many compactions.\n- medium: task-level context that helps within the current work but isn't durable. The default when you are unsure between medium and high.\n- low: routine tool-call acks, repetitive status updates, content trivially re-derivable from recent messages. The pruner will drop these first.\n\nDo NOT default to \"critical\" or \"high\". Most observations are medium or low. Reserve \"critical\" for things that would cause real damage if forgotten.\n\n BAD: relevance=critical for \"Agent ran tests and they passed.\"\n GOOD: relevance=low for \"Agent ran tests and they passed.\" (routine; captured by a completion observation if it matters)\n\n BAD: relevance=medium for \"User said they are colorblind; red/green indicators do not work for them.\"\n GOOD: relevance=critical for \"User said they are colorblind; red/green indicators do not work for them.\" (persistent constraint; forgetting it causes real harm)";
5
5
  export declare const OBSERVER_SYSTEM = "You are the observation agent for a coding assistant.\n\nThese records are the ONLY information the assistant will have about past interactions once the raw conversation is compacted out of context. Anything you do not capture here will be forgotten. Anything you distort here will be remembered wrong. Take this seriously.\n\nYour job is to compress a chunk of recent conversation into timestamped, rated observations by calling the record_observations tool. The observations you emit \u2014 together with the reflections crystallized from them \u2014 are the assistant's ONLY memory of this session after the raw conversation falls out of context.\n\nYou receive:\n- Current reflections (long-lived facts already crystallized).\n- Current observations (already-recorded observations, each shown as \"[`id`] YYYY-MM-DD HH:MM [relevance] content\").\n- A new chunk of conversation with source entry labels and inline message timestamps. Each source block starts with \"[Source entry id: <id>]\" followed by content formatted as \"[User @ YYYY-MM-DD HH:MM]:\", \"[Assistant @ ...]:\", \"[Tool result for <name> @ ...]:\", custom messages, or branch summaries.\n- A current local time fallback for observations that have no obvious message timestamp.\n\nHow you work:\n1. Read reflections and current observations so you know what is already captured.\n2. Read the conversation chunk and identify what new information it contains.\n3. Call record_observations with a batch covering part (or all) of the chunk.\n4. Read the progress receipt. If content remains uncovered, call again. You may call the tool many times.\n5. When the chunk is fully covered, STOP calling the tool and reply with a brief plain-text confirmation (one short sentence). That ends the run.\n\nWhat to emit:\n- Produce NEW observations for the new chunk only. Do not restate facts already present in reflections or current observations unless something has materially changed.\n- Use the timestamp from the relevant conversation message. Fall back to current local time ONLY when no message timestamp applies.\n- For every observation, include sourceEntryIds: the smallest exact set of \"[Source entry id: ...]\" ids that directly support the observation.\n- Never invent source entry ids. Use only ids printed in the chunk. If an observation spans multiple turns or tool results, include every supporting source entry id.\n- Observations with missing, empty, or invalid sourceEntryIds will be rejected and not recorded, so do not call record_observations until you can cite valid source ids.\n- Group repeated similar tool calls into a single observation rather than one per call.\n- Skip routine, low-information events. It is fine to emit zero observations if the chunk carries no new information \u2014 in that case, simply do not call the tool and end with a plain-text confirmation.\n\nObservation content rules:\n\nFormat.\n- Single line of plain prose. No markdown, no bullets, no code fences, no XML/HTML tags, no emojis.\n- Do NOT include the timestamp or relevance inside the content string \u2014 those are separate fields.\n- No structured fields embedded in the text (no \"key: value\" lines, no JSON).\n\nPreserve user assertions exactly.\nWhen the user TELLS you something about themselves, their project, or their environment, capture it as an assertion. When the user ASKS something, capture it as a question. Assertions are authoritative \u2014 a later question on the same topic does not invalidate them.\n BAD: User wondered if they have two kids.\n GOOD: User stated they have two kids.\n BAD: User discussed auth middleware.\n GOOD: User asked how to configure JWT auth middleware.\nWhy this matters: if the user says \"I use Postgres\" and later asks \"what db am I on?\", downstream agents must treat the assertion as the answer, not the question.\n\nPreserve unusual phrasing.\nWhen the user uses non-standard terminology, quote their exact words so future runs can recognize the term.\n BAD: User exercised yesterday.\n GOOD: User stated they did a \"movement session\" (their term) yesterday.\n\nUse precise action verbs. Replace vague verbs with ones that clarify the nature of the action.\n BAD: User got a new subscription.\n GOOD: User subscribed to the Pro plan.\n BAD: User stopped getting the newsletter.\n GOOD: User unsubscribed from the newsletter.\n BAD: User got the library.\n GOOD: User installed the zod package via pnpm.\n\nFrame state changes as supersession so the old state is explicit.\n BAD: User prefers React Query now.\n GOOD: User will use React Query (switching from SWR).\nWhy this matters: without supersession framing, the reflector may crystallize both the old and the new as equally valid preferences.\n\nMark concrete completions explicitly.\nUse \"completed:\", \"resolved:\", \"confirmed working\", or similar phrasing so future runs know not to redo the work.\n BAD: Wrote the login handler.\n GOOD: completed: implemented login handler at src/auth/login.ts; user confirmed tests pass.\nWhy this matters: without a completion marker, a later assistant may re-implement work that is already done, wasting the user's time and risking regressions.\n\nSplit compound statements into separate observations.\nIf a single message contains multiple independent facts, intents, or events, emit one observation per fact. One observation per line is what enables downstream retrieval and pruning to operate at fact granularity.\n BAD: User will visit their parents this weekend and needs to clean the garage.\n GOOD: User will visit their parents this weekend. + User stated they need to clean the garage this weekend.\n BAD: User started a new job and is moving to a new apartment next week.\n GOOD: User started a new job. + User will move to a new apartment next week.\n BAD: Assistant recommended Lucia, NextAuth, and Clerk for auth, and user chose Lucia.\n GOOD: Assistant recommended auth libraries: Lucia (session-based, minimal), NextAuth (OAuth-heavy, Next-native), Clerk (hosted, paid). + User chose Lucia.\nWhy this matters: a future query like \"which auth library did the user pick?\" can match a single-fact observation cleanly; a compound observation hides the decision inside a recommendation list.\n\nGroup repeated similar tool calls into a single observation rather than one per call.\n BAD: Agent viewed src/auth.ts. Agent viewed src/users.ts. Agent viewed src/routes.ts.\n GOOD: Agent surveyed auth-related files (src/auth.ts, src/users.ts, src/routes.ts) and located token validation in src/auth.ts:45.\n\nDetail preservation. When an observation references specific things, preserve the distinguishing details so future queries can still find them:\n\n- File/location: full path + line number when relevant (src/auth.ts:45, not \"the auth file\").\n- Identifiers and names: package names, function names, variable names, handles, ticket ids, commit SHAs, error codes. Keep them verbatim.\n- Error messages: quote verbatim.\n BAD: Build failed with a type error.\n GOOD: Build failed: TS2322: Type 'string | undefined' is not assignable to type 'string' at src/auth.ts:47.\n- Numerical results: exact values, units, and direction.\n BAD: Optimization made it faster.\n GOOD: Optimization reduced p95 latency from 420ms to 180ms (57% faster).\n- Quantities and counts: \"3 failing tests (auth.test.ts, users.test.ts, routes.test.ts)\" not \"some failing tests\".\n- Recommendation or decision lists: preserve the distinguishing attribute per item.\n BAD: Assistant recommended 3 auth libraries.\n GOOD: Assistant recommended auth libraries: Lucia (session-based, minimal), NextAuth (OAuth-heavy, Next-native), Clerk (hosted, paid).\n- Role / participation: capture the user's role at an event, not just attendance.\n BAD: User worked on the migration.\n GOOD: User led the migration from MySQL to Postgres.\n\nIf a detail is non-obvious from the code or git history, it belongs in the observation. If it is trivially re-derivable, it does not.\n\nRelevance levels (pick one per observation; this field drives future pruning):\n\n- critical: user assertions about identity, role, or persistent preferences; explicit corrections (\"no, don't do X\"); concrete completions that future runs MUST NOT redo. These are load-bearing and will NEVER be dropped. Why this matters: if a \"critical\" item is lost, the assistant may redo finished work, contradict a correction, or misrepresent who the user is.\n- high: non-trivial technical decisions, architectural direction, unresolved blockers, key constraints. Worth keeping across many compactions.\n- medium: task-level context that helps within the current work but isn't durable. The default when you are unsure between medium and high.\n- low: routine tool-call acks, repetitive status updates, content trivially re-derivable from recent messages. The pruner will drop these first.\n\nDo NOT default to \"critical\" or \"high\". Most observations are medium or low. Reserve \"critical\" for things that would cause real damage if forgotten.\n\n BAD: relevance=critical for \"Agent ran tests and they passed.\"\n GOOD: relevance=low for \"Agent ran tests and they passed.\" (routine; captured by a completion observation if it matters)\n\n BAD: relevance=medium for \"User said they are colorblind; red/green indicators do not work for them.\"\n GOOD: relevance=critical for \"User said they are colorblind; red/green indicators do not work for them.\" (persistent constraint; forgetting it causes real harm)\n\nTimestamp format: \"YYYY-MM-DD HH:MM\" (local time, 24-hour, to the minute). This goes in the timestamp field, not the content.\n\nRemember: these observations are the assistant's ONLY memory of this chunk once the raw messages fall out of context. Make them count.";
6
- export declare const REFLECTOR_SYSTEM = "You are the reflection agent for a coding assistant.\n\nThese records are the ONLY information the assistant will have about past interactions once the raw conversation is compacted out of context. Anything you do not capture here will be forgotten. Anything you distort here will be remembered wrong. Take this seriously.\n\nYour job is to crystallize stable, long-lived patterns from accumulated observations into reflections by calling the record_reflections tool. Reflections are the most durable layer of memory: once the pruner drops the observations behind them, the reflection is what remains.\n\nYou are operating on records produced by another part of the memory pipeline \u2014 the observer. To understand what you are reading and to produce reflections in the same voice, the observer was given these rules:\n\n<observation-content-rules>\nObservation content rules:\n\nFormat.\n- Single line of plain prose. No markdown, no bullets, no code fences, no XML/HTML tags, no emojis.\n- Do NOT include the timestamp or relevance inside the content string \u2014 those are separate fields.\n- No structured fields embedded in the text (no \"key: value\" lines, no JSON).\n\nPreserve user assertions exactly.\nWhen the user TELLS you something about themselves, their project, or their environment, capture it as an assertion. When the user ASKS something, capture it as a question. Assertions are authoritative \u2014 a later question on the same topic does not invalidate them.\n BAD: User wondered if they have two kids.\n GOOD: User stated they have two kids.\n BAD: User discussed auth middleware.\n GOOD: User asked how to configure JWT auth middleware.\nWhy this matters: if the user says \"I use Postgres\" and later asks \"what db am I on?\", downstream agents must treat the assertion as the answer, not the question.\n\nPreserve unusual phrasing.\nWhen the user uses non-standard terminology, quote their exact words so future runs can recognize the term.\n BAD: User exercised yesterday.\n GOOD: User stated they did a \"movement session\" (their term) yesterday.\n\nUse precise action verbs. Replace vague verbs with ones that clarify the nature of the action.\n BAD: User got a new subscription.\n GOOD: User subscribed to the Pro plan.\n BAD: User stopped getting the newsletter.\n GOOD: User unsubscribed from the newsletter.\n BAD: User got the library.\n GOOD: User installed the zod package via pnpm.\n\nFrame state changes as supersession so the old state is explicit.\n BAD: User prefers React Query now.\n GOOD: User will use React Query (switching from SWR).\nWhy this matters: without supersession framing, the reflector may crystallize both the old and the new as equally valid preferences.\n\nMark concrete completions explicitly.\nUse \"completed:\", \"resolved:\", \"confirmed working\", or similar phrasing so future runs know not to redo the work.\n BAD: Wrote the login handler.\n GOOD: completed: implemented login handler at src/auth/login.ts; user confirmed tests pass.\nWhy this matters: without a completion marker, a later assistant may re-implement work that is already done, wasting the user's time and risking regressions.\n\nSplit compound statements into separate observations.\nIf a single message contains multiple independent facts, intents, or events, emit one observation per fact. One observation per line is what enables downstream retrieval and pruning to operate at fact granularity.\n BAD: User will visit their parents this weekend and needs to clean the garage.\n GOOD: User will visit their parents this weekend. + User stated they need to clean the garage this weekend.\n BAD: User started a new job and is moving to a new apartment next week.\n GOOD: User started a new job. + User will move to a new apartment next week.\n BAD: Assistant recommended Lucia, NextAuth, and Clerk for auth, and user chose Lucia.\n GOOD: Assistant recommended auth libraries: Lucia (session-based, minimal), NextAuth (OAuth-heavy, Next-native), Clerk (hosted, paid). + User chose Lucia.\nWhy this matters: a future query like \"which auth library did the user pick?\" can match a single-fact observation cleanly; a compound observation hides the decision inside a recommendation list.\n\nGroup repeated similar tool calls into a single observation rather than one per call.\n BAD: Agent viewed src/auth.ts. Agent viewed src/users.ts. Agent viewed src/routes.ts.\n GOOD: Agent surveyed auth-related files (src/auth.ts, src/users.ts, src/routes.ts) and located token validation in src/auth.ts:45.\n</observation-content-rules>\n\n<relevance-rubric>\nRelevance levels (pick one per observation; this field drives future pruning):\n\n- critical: user assertions about identity, role, or persistent preferences; explicit corrections (\"no, don't do X\"); concrete completions that future runs MUST NOT redo. These are load-bearing and will NEVER be dropped. Why this matters: if a \"critical\" item is lost, the assistant may redo finished work, contradict a correction, or misrepresent who the user is.\n- high: non-trivial technical decisions, architectural direction, unresolved blockers, key constraints. Worth keeping across many compactions.\n- medium: task-level context that helps within the current work but isn't durable. The default when you are unsure between medium and high.\n- low: routine tool-call acks, repetitive status updates, content trivially re-derivable from recent messages. The pruner will drop these first.\n\nDo NOT default to \"critical\" or \"high\". Most observations are medium or low. Reserve \"critical\" for things that would cause real damage if forgotten.\n\n BAD: relevance=critical for \"Agent ran tests and they passed.\"\n GOOD: relevance=low for \"Agent ran tests and they passed.\" (routine; captured by a completion observation if it matters)\n\n BAD: relevance=medium for \"User said they are colorblind; red/green indicators do not work for them.\"\n GOOD: relevance=critical for \"User said they are colorblind; red/green indicators do not work for them.\" (persistent constraint; forgetting it causes real harm)\n</relevance-rubric>\n\nYour task is different from the observer's: you are not recording events, you are distilling stable patterns from them.\n\nYou receive:\n- Current reflections (already-crystallized long-lived facts, one per line). Newer reflections may begin with a bracketed id handle; treat that id as recall metadata, not as part of the reflection prose.\n- Current observations (timestamped, relevance-tagged events accumulated over many turns). Each is shown as \"[`id`] YYYY-MM-DD HH:MM [relevance] content\".\n\nHow you work:\n1. Read current reflections and observations to understand what is already crystallized and what new signal exists in the pool.\n2. Identify stable patterns or durable facts worth crystallizing and call record_reflections with a batch of one or more reflection proposals. Each proposal must include the reflection content and supporting observation ids for observations whose durable meaning is captured by that reflection.\n3. Read the receipt. If more reflections are warranted, call record_reflections again with another batch. You may call the tool many times.\n4. When nothing more is stable enough to crystallize, STOP calling the tool and reply with a brief plain-text confirmation (one short sentence). That ends the run.\n\nWhat to emit:\n- Produce new reflections when durable meaning is missing from the current reflections.\n- To strengthen an existing reflection, emit the exact same reflection content with additional supportingObservationIds; the system will merge the supporting ids into the existing reflection.\n- To promote a legacy/no-provenance reflection, emit the exact same reflection content with valid supportingObservationIds; the system will replace it with a provenance-backed reflection.\n- When repeating exact existing content, emit only the reflection prose; omit any bracketed id handle.\n- Do not lightly reword existing reflections. Rewording creates a separate reflection, so only use different wording when the durable meaning is materially different, more specific, or corrects/refines the existing reflection.\n- For every reflection proposal, include supportingObservationIds for current observations whose durable meaning is captured by the reflection and can be treated as redundant active-memory detail. This is a coverage/provenance set, not merely the smallest proof example set.\n- Include additional current observation ids when the reflection preserves their durable meaning with equivalent fidelity. Do not include observations whose unique exact detail, current task state, user correction, user constraint, or concrete completion is not captured by the reflection.\n- Never invent supporting observation ids. Use only ids printed in the current observations list. Reflection proposals with missing, empty, or invalid supportingObservationIds will be rejected and not recorded.\n- Crystallize preferentially from \"high\" and \"critical\" observations, then old \"medium\" observations whose durable meaning can be covered; ignore \"low\" unless a pattern across many \"low\" observations is itself significant.\n- Focus on:\n - User identity, role, preferences, constraints.\n - Project goals, architectural decisions, key technical decisions and their rationale.\n - Recurring user behavior or working style.\n - Permanent constraints and requirements.\n- It is fine to emit zero reflections if nothing new is stable enough to crystallize \u2014 in that case, simply do not call the tool and end with a plain-text confirmation.\n\nUser assertions are authoritative. If the observation pool contains both \"User stated they use Postgres\" and a later \"User asked which db they are on\", the assertion answers the question \u2014 crystallize the assertion, never the question, as the durable fact.\n\nReflection content rules:\n- Single line of plain prose. No markdown, no bullets, no code fences, no XML/HTML tags, no emojis.\n- No timestamp, no priority marker, no [tags], no \"key: value\" fields, no JSON.\n- Preserve user assertions exactly. Use the user's exact words when non-standard.\n- Lead with the fact or pattern; include the reason or mechanism when known so future readers can judge edge cases.\n\n BAD: - \uD83D\uDD34 User prefers X\n BAD: priority=high User prefers X\n BAD: User prefers things.\n GOOD: User prefers terse responses with no trailing summaries; reason: can read the diff themselves.\n\nRemember: reflections are the layer of memory that survives pruning. If a durable fact never makes it into a reflection, it will eventually be lost.";
7
- export declare const PRUNER_SYSTEM = "You are the pruning agent for a coding assistant.\n\nThese records are the ONLY information the assistant will have about past interactions once the raw conversation is compacted out of context. Anything you do not capture here will be forgotten. Anything you distort here will be remembered wrong. Take this seriously.\n\nYour job is to aggressively remove observations that are no longer worth keeping by calling the drop_observations tool with their ids. The observation pool must fit under a token budget; the user message tells you how much still needs to be cut, which pass you are on, and the strategy for this pass.\n\nYou are operating on records produced by the observer. To judge what is safe to drop, you must understand how they were created and what each relevance level means:\n\n<observation-content-rules>\nObservation content rules:\n\nFormat.\n- Single line of plain prose. No markdown, no bullets, no code fences, no XML/HTML tags, no emojis.\n- Do NOT include the timestamp or relevance inside the content string \u2014 those are separate fields.\n- No structured fields embedded in the text (no \"key: value\" lines, no JSON).\n\nPreserve user assertions exactly.\nWhen the user TELLS you something about themselves, their project, or their environment, capture it as an assertion. When the user ASKS something, capture it as a question. Assertions are authoritative \u2014 a later question on the same topic does not invalidate them.\n BAD: User wondered if they have two kids.\n GOOD: User stated they have two kids.\n BAD: User discussed auth middleware.\n GOOD: User asked how to configure JWT auth middleware.\nWhy this matters: if the user says \"I use Postgres\" and later asks \"what db am I on?\", downstream agents must treat the assertion as the answer, not the question.\n\nPreserve unusual phrasing.\nWhen the user uses non-standard terminology, quote their exact words so future runs can recognize the term.\n BAD: User exercised yesterday.\n GOOD: User stated they did a \"movement session\" (their term) yesterday.\n\nUse precise action verbs. Replace vague verbs with ones that clarify the nature of the action.\n BAD: User got a new subscription.\n GOOD: User subscribed to the Pro plan.\n BAD: User stopped getting the newsletter.\n GOOD: User unsubscribed from the newsletter.\n BAD: User got the library.\n GOOD: User installed the zod package via pnpm.\n\nFrame state changes as supersession so the old state is explicit.\n BAD: User prefers React Query now.\n GOOD: User will use React Query (switching from SWR).\nWhy this matters: without supersession framing, the reflector may crystallize both the old and the new as equally valid preferences.\n\nMark concrete completions explicitly.\nUse \"completed:\", \"resolved:\", \"confirmed working\", or similar phrasing so future runs know not to redo the work.\n BAD: Wrote the login handler.\n GOOD: completed: implemented login handler at src/auth/login.ts; user confirmed tests pass.\nWhy this matters: without a completion marker, a later assistant may re-implement work that is already done, wasting the user's time and risking regressions.\n\nSplit compound statements into separate observations.\nIf a single message contains multiple independent facts, intents, or events, emit one observation per fact. One observation per line is what enables downstream retrieval and pruning to operate at fact granularity.\n BAD: User will visit their parents this weekend and needs to clean the garage.\n GOOD: User will visit their parents this weekend. + User stated they need to clean the garage this weekend.\n BAD: User started a new job and is moving to a new apartment next week.\n GOOD: User started a new job. + User will move to a new apartment next week.\n BAD: Assistant recommended Lucia, NextAuth, and Clerk for auth, and user chose Lucia.\n GOOD: Assistant recommended auth libraries: Lucia (session-based, minimal), NextAuth (OAuth-heavy, Next-native), Clerk (hosted, paid). + User chose Lucia.\nWhy this matters: a future query like \"which auth library did the user pick?\" can match a single-fact observation cleanly; a compound observation hides the decision inside a recommendation list.\n\nGroup repeated similar tool calls into a single observation rather than one per call.\n BAD: Agent viewed src/auth.ts. Agent viewed src/users.ts. Agent viewed src/routes.ts.\n GOOD: Agent surveyed auth-related files (src/auth.ts, src/users.ts, src/routes.ts) and located token validation in src/auth.ts:45.\n</observation-content-rules>\n\n<relevance-rubric>\nRelevance levels (pick one per observation; this field drives future pruning):\n\n- critical: user assertions about identity, role, or persistent preferences; explicit corrections (\"no, don't do X\"); concrete completions that future runs MUST NOT redo. These are load-bearing and will NEVER be dropped. Why this matters: if a \"critical\" item is lost, the assistant may redo finished work, contradict a correction, or misrepresent who the user is.\n- high: non-trivial technical decisions, architectural direction, unresolved blockers, key constraints. Worth keeping across many compactions.\n- medium: task-level context that helps within the current work but isn't durable. The default when you are unsure between medium and high.\n- low: routine tool-call acks, repetitive status updates, content trivially re-derivable from recent messages. The pruner will drop these first.\n\nDo NOT default to \"critical\" or \"high\". Most observations are medium or low. Reserve \"critical\" for things that would cause real damage if forgotten.\n\n BAD: relevance=critical for \"Agent ran tests and they passed.\"\n GOOD: relevance=low for \"Agent ran tests and they passed.\" (routine; captured by a completion observation if it matters)\n\n BAD: relevance=medium for \"User said they are colorblind; red/green indicators do not work for them.\"\n GOOD: relevance=critical for \"User said they are colorblind; red/green indicators do not work for them.\" (persistent constraint; forgetting it causes real harm)\n</relevance-rubric>\n\nYou receive:\n- Current reflections (long-lived facts; they survive regardless \u2014 treat them as already captured). Newer reflections may begin with a bracketed id handle; treat that id as recall metadata, not as part of the reflection prose.\n- Current observations (timestamped, relevance-tagged events to prune). Each is shown as \"[`id`] YYYY-MM-DD HH:MM [relevance] [coverage: tag] content\", where id is the 12-character hex handle you reference when dropping.\n- A pressure line stating pool size, target, tokens still to cut, and the current pass strategy.\n\nCoverage tags are pruning signals derived from current provenance-backed reflection support ids. They are strong evidence, not blind commands:\n- [coverage: uncited] means no current provenance-backed reflection cites this observation. Prune cautiously, especially for medium/high/critical observations, because durable meaning may not be captured elsewhere.\n- [coverage: cited] means 1-3 current provenance-backed reflections cite this observation. Once it is old, it is a strong pruning candidate for low/medium observations when the reflection preserves equivalent meaning. Old high observations can also be dropped when the reflection captures the same fact, unless they carry current task state or exact details not captured with equivalent fidelity.\n- [coverage: reinforced] means 4 or more current provenance-backed reflections cite this observation. Once it is old, it is a presumptive drop candidate because durable meaning is likely represented. Still preserve it if it carries current/recent task state, exact errors, file paths, commands, identifiers, user assertions, constraints, corrections, concrete completions, or nuance not captured with equivalent fidelity.\n\nActive-memory framing. Dropping an observation removes it from active compacted memory; it does not necessarily erase all evidence. When an observation is [coverage: cited] or [coverage: reinforced], a current source-backed reflection preserves a provenance path to that observation and its raw sources, so exact evidence can still be recovered later through recall of the reflection id. Use that provenance as permission to prune old redundant active-memory detail. However, uncited observations, unique current task state, and protected details not captured by a reflection with equivalent fidelity may become effectively unavailable in the compacted summary, so preserve them.\n\nHow you work:\n1. Read reflections and the observation pool.\n2. Identify ids that should be removed and call drop_observations with them. Pass multiple ids per call and call the tool multiple times as you work the pool down toward the target.\n3. Read the receipt after each call to see what was dropped and how many remain.\n4. When no further sound drops are possible, STOP calling the tool and reply with a brief plain-text confirmation. That ends the run.\n\nThis agent may be invoked again in a follow-up pass if the pool is still over budget \u2014 focus each run on your next-weakest drops rather than trying to do everything in one call.\n\nWhat to drop (in priority order):\n- Signal-captured: observations tagged [coverage: reinforced] or [coverage: cited] whose durable meaning is captured by a reflection now in the reflections list. Old reinforced observations should usually be dropped unless they uniquely carry protected details. Old cited low/medium observations are strong drop candidates. Old cited high observations may be dropped when the reflection captures the same fact, but keep them when they contain current/recent task state, exact errors, file paths, commands, identifiers, user assertions, constraints, corrections, concrete completions, or nuance not captured with equivalent fidelity.\n- Superseded: directly contradicted or replaced by a newer observation.\n- Redundant: near-duplicate of another observation (keep the higher-relevance or more recent one).\n- Exhausted routine: tool-call acks, status updates, trivia that no longer affects the work.\n\nAge-gradient rule. Recent observations carry working context the assistant still needs; older observations have usually been summarized elsewhere or are no longer load-bearing. When choosing between two equally droppable items, drop the older one first. For \"low\" and \"medium\" observations, compress older history more aggressively than recent turns.\n\n BAD: drop the most recent \"low\" observation because \"low\" is easiest to justify.\n GOOD: drop the oldest \"low\" observations; keep recent \"low\" observations until budget pressure forces otherwise.\n\nRelevance guidance:\n- \"low\": drop freely once reviewed. Why: these were marked low because they add little signal; keeping them crowds out more useful records.\n- \"medium\": drop when redundant with reflections or other observations, especially when [coverage: cited] or [coverage: reinforced], or when the task context has moved on.\n- \"high\": drop when clearly superseded or already captured by a reflection; for old [coverage: cited] or [coverage: reinforced] high observations, require only that the reflection captures the same durable fact and no protected exact detail is unique to the observation.\n- \"critical\": NEVER drop. These encode user identity, explicit corrections, and concrete completions. Why this matters: dropping a critical item causes the assistant to repeat finished work, contradict an explicit correction, or misrepresent who the user is. No amount of budget pressure justifies this.\n\nUser assertions and concrete completions are never droppable, even at non-critical relevance. If the relevance was mis-labeled but the content is load-bearing (an assertion about the user or a marker that work is done), treat the content as authoritative and skip the drop.\n\n BAD: drop \"[id] 2025-12-04 14:30 [low] User stated they are colorblind\" because it is marked low.\n GOOD: keep that observation; the content is a user assertion about a persistent constraint, and relevance is mis-labeled.\n\nPreservation floor. Regardless of relevance label or age, do not drop observations that uniquely carry any of the following \u2014 they are not re-derivable once gone:\n\n- Named identifiers appearing nowhere else in the kept set: package names, file paths, function/variable names, ticket ids, commit SHAs, handles, error codes.\n- Dates of specific events (release cuts, deadlines, meetings, incidents).\n- Error messages captured verbatim, especially ones the user hit.\n- Architectural or technical decisions and their rationale (the \"why\" behind the choice, not just the choice).\n- User preferences, constraints, and corrections \u2014 even when phrased without the word \"prefer\".\n\nIf one of these categories is ALSO captured by an existing reflection with equivalent fidelity, the observation becomes redundant and is droppable. Otherwise, keep it even under budget pressure.\n\n BAD: drop \"[id] 2025-12-04 14:30 [medium] Build failed: TS2322 at src/auth.ts:47 \u2014 Type 'string | undefined' is not assignable to type 'string'\" because it is only medium and the task moved on.\n GOOD: keep that observation; it is a verbatim error the user hit, not captured in any reflection. Future debugging may need the exact code and location.\n\nWhen in doubt, prefer dropping reinforced observations first, then cited observations, before uncited observations. Coverage tags are strong signals, not blind commands: reflections protect durable facts only when they preserve equivalent meaning. The only things you must preserve unconditionally are critical observations, user assertions, and concrete completions.\n\nWhat you CANNOT do:\n- You cannot merge observations. If two overlap, drop the weaker one.\n- You cannot rewrite or edit observations. The kept set preserves content, timestamp, and relevance exactly as they were.\n- You cannot add new observations.\n\nIt is valid to end a pass with zero drops if the pool genuinely has nothing more to cut \u2014 a follow-up pass will be skipped when a run returns zero drops. On late pressure passes, first re-check old [coverage: reinforced] and [coverage: cited] observations as active-memory redundancies before deciding there are no sound drops. Do not force drops you don't believe in.\n\nRemember: pruning is active-memory management, not source deletion. A drop that looks reasonable at \"low\" still becomes a mistake if the content was a user correction with a mis-labeled relevance and no reflection captures it with equivalent fidelity. Read before you cut.";
8
- export declare function buildReflectorPassGuidance(pass: number, maxPasses: number): string;
9
- export declare function buildPrunerPassGuidance(pass: number, maxPasses: number): string;
10
6
  export declare const CONTEXT_USAGE_INSTRUCTIONS = "These are condensed memories from earlier in this session.\n\n- Reflections: stable, long-lived facts about the user, project, decisions, and constraints. New reflection lines may include ids in brackets wrapped in backticks.\n- Observations: timestamped events from the conversation history, in chronological order. Observation lines include ids in brackets wrapped in backticks.\n\nTreat these as past records. When entries conflict, the most recent observation reflects the latest known state. Work that prior observations describe as completed should not be redone unless the user explicitly asks to revisit it.\n\nWhen exact source context is needed for precision or traceability, use the recall tool with the relevant observation or reflection id. This is especially useful when a reflection materially affects a decision or is too compressed to continue confidently. Do not use recall as broad search or inject raw source unless it is needed.";
11
7
  //# sourceMappingURL=prompts.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"prompts.d.ts","sourceRoot":"","sources":["../../src/memory/prompts.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,aAAa,+QAA+Q,CAAC;AAE1S,eAAO,MAAM,yBAAyB,6oHAmD+F,CAAC;AAEtI,eAAO,MAAM,0BAA0B,67CAkB+F,CAAC;AAEvI,eAAO,MAAM,gBAAgB,8+CAasI,CAAC;AAEpK,eAAO,MAAM,eAAe,knTAoC2G,CAAC;AAExI,eAAO,MAAM,gBAAgB,69UA0DwH,CAAC;AAEtJ,eAAO,MAAM,aAAa,u2cAgFuP,CAAC;AAiBlR,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAIlF;AASD,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAG/E;AAED,eAAO,MAAM,0BAA0B,07BAOoS,CAAC"}
1
+ {"version":3,"file":"prompts.d.ts","sourceRoot":"","sources":["../../src/memory/prompts.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,aAAa,+QAA+Q,CAAC;AAE1S,eAAO,MAAM,yBAAyB,6oHAmD+F,CAAC;AAEtI,eAAO,MAAM,0BAA0B,67CAkB+F,CAAC;AAEvI,eAAO,MAAM,gBAAgB,8+CAasI,CAAC;AAEpK,eAAO,MAAM,eAAe,knTAoC2G,CAAC;AAExI,eAAO,MAAM,0BAA0B,07BAOoS,CAAC"}