pi-blackhole 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 (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +373 -0
  3. package/example-config.json +115 -0
  4. package/index.ts +39 -0
  5. package/package.json +55 -0
  6. package/src/commands/memory.ts +191 -0
  7. package/src/commands/pi-vcc.ts +94 -0
  8. package/src/commands/vcc-recall.ts +112 -0
  9. package/src/core/brief.ts +390 -0
  10. package/src/core/build-sections.ts +85 -0
  11. package/src/core/content.ts +60 -0
  12. package/src/core/filter-noise.ts +42 -0
  13. package/src/core/format-recall.ts +27 -0
  14. package/src/core/format.ts +76 -0
  15. package/src/core/lineage.ts +26 -0
  16. package/src/core/load-messages.ts +41 -0
  17. package/src/core/normalize.ts +79 -0
  18. package/src/core/recall-scope.ts +14 -0
  19. package/src/core/render-entries.ts +56 -0
  20. package/src/core/report.ts +237 -0
  21. package/src/core/sanitize.ts +5 -0
  22. package/src/core/search-entries.ts +227 -0
  23. package/src/core/settings.ts +34 -0
  24. package/src/core/skill-collapse.ts +35 -0
  25. package/src/core/summarize.ts +213 -0
  26. package/src/core/tool-args.ts +14 -0
  27. package/src/core/unified-config.ts +285 -0
  28. package/src/details.ts +13 -0
  29. package/src/extract/commits.ts +69 -0
  30. package/src/extract/files.ts +80 -0
  31. package/src/extract/goals.ts +79 -0
  32. package/src/extract/preferences.ts +55 -0
  33. package/src/hooks/before-compact.ts +345 -0
  34. package/src/om/agents/dropper/agent.ts +204 -0
  35. package/src/om/agents/dropper/prompts.ts +48 -0
  36. package/src/om/agents/observer/agent.ts +256 -0
  37. package/src/om/agents/observer/prompts.ts +119 -0
  38. package/src/om/agents/reflector/agent.ts +161 -0
  39. package/src/om/agents/reflector/prompts.ts +77 -0
  40. package/src/om/clipboard.ts +63 -0
  41. package/src/om/compaction-hook.ts +63 -0
  42. package/src/om/compaction-trigger.ts +92 -0
  43. package/src/om/config.ts +22 -0
  44. package/src/om/consolidation.ts +514 -0
  45. package/src/om/cooldown.ts +130 -0
  46. package/src/om/debug-log.ts +55 -0
  47. package/src/om/ids.ts +5 -0
  48. package/src/om/ledger/fold.ts +106 -0
  49. package/src/om/ledger/index.ts +6 -0
  50. package/src/om/ledger/progress.ts +225 -0
  51. package/src/om/ledger/projection.ts +237 -0
  52. package/src/om/ledger/recall.ts +243 -0
  53. package/src/om/ledger/render-summary.ts +44 -0
  54. package/src/om/ledger/types.ts +206 -0
  55. package/src/om/model-budget.ts +9 -0
  56. package/src/om/pending.ts +225 -0
  57. package/src/om/reverse-recall.ts +130 -0
  58. package/src/om/runtime.ts +241 -0
  59. package/src/om/serialize.ts +224 -0
  60. package/src/om/tokens.ts +33 -0
  61. package/src/sections.ts +18 -0
  62. package/src/tools/recall.ts +212 -0
  63. package/src/types.ts +19 -0
  64. package/vitest.config.ts +41 -0
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Dropper agent — uses agentLoop to propose prunable observations.
3
+ *
4
+ * Upstream: https://github.com/elpapi42/pi-observational-memory (src/agents/dropper/agent.ts)
5
+ * Modified by pi-vcc-om: detects agent_end stopReason="error" in the stream
6
+ * and throws if the API errored without collecting any drop candidates.
7
+ */
8
+ import { agentLoop, type AgentContext, type AgentLoopConfig, type AgentTool } from "@earendil-works/pi-agent-core";
9
+ import type { Message, Model, ModelThinkingLevel } from "@earendil-works/pi-ai";
10
+ import { Type } from "@earendil-works/pi-ai";
11
+ import type { Static } from "typebox";
12
+ import { AGENT_LOOP_MAX_TOKENS, boundedMaxTokens } from "../../model-budget.js";
13
+ import { observationToSummaryLine, reflectionToSummaryLine, type Observation, type Reflection } from "../../ledger/index.js";
14
+ import { DROPPER_SYSTEM } from "./prompts.js";
15
+
16
+ interface RunDropperArgs {
17
+ model: Model<any>;
18
+ apiKey: string;
19
+ headers?: Record<string, string>;
20
+ reflections: Reflection[];
21
+ observations: Observation[];
22
+ /** Compact summary of existing active observations for context. */
23
+ existingObservationsSummary?: string;
24
+ budgetTokens: number;
25
+ signal?: AbortSignal;
26
+ agentLoop?: typeof agentLoop;
27
+ maxTurns?: number;
28
+ thinkingLevel?: ModelThinkingLevel;
29
+ }
30
+
31
+ const DROP_SKIP_FULLNESS = 0.10;
32
+ const DROP_LOW_URGENCY_FULLNESS = 0.30;
33
+ const DROP_MEDIUM_URGENCY_FULLNESS = 0.60;
34
+ const DROP_MAX_FULLNESS = 1.00;
35
+ const DROP_MIN_RATIO = 0.10;
36
+ const DROP_MAX_RATIO = 0.50;
37
+
38
+ export type DropUrgency = "low" | "medium" | "high";
39
+
40
+ const RELEVANCE_DROP_RANK: Record<Observation["relevance"], number> = {
41
+ low: 0,
42
+ medium: 1,
43
+ high: 2,
44
+ critical: 3,
45
+ };
46
+
47
+ const DropObservationsSchema = Type.Object({
48
+ ids: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
49
+ reason: Type.Optional(Type.String()),
50
+ });
51
+
52
+ type DropObservationsArgs = Static<typeof DropObservationsSchema>;
53
+
54
+ function joinOrEmpty(items: string[]): string {
55
+ return items.length ? items.join("\n") : "(none yet)";
56
+ }
57
+
58
+ export function observationPoolFullness(observationTokens: number, budgetTokens: number): number {
59
+ if (!Number.isFinite(observationTokens) || observationTokens <= 0) return 0;
60
+ if (!Number.isFinite(budgetTokens) || budgetTokens <= 0) return 0;
61
+ return observationTokens / budgetTokens;
62
+ }
63
+
64
+ export function dropUrgencyForFullness(fullness: number): DropUrgency {
65
+ if (fullness < DROP_LOW_URGENCY_FULLNESS) return "low";
66
+ if (fullness < DROP_MEDIUM_URGENCY_FULLNESS) return "medium";
67
+ return "high";
68
+ }
69
+
70
+ export function maxDropCountForPool(observations: readonly Observation[], observationTokens: number, budgetTokens: number): number {
71
+ const droppableCount = observations.filter((observation) => observation.relevance !== "critical").length;
72
+ if (droppableCount === 0) return 0;
73
+
74
+ const fullness = observationPoolFullness(observationTokens, budgetTokens);
75
+ if (fullness < DROP_SKIP_FULLNESS) return 0;
76
+
77
+ const cappedFullness = Math.min(DROP_MAX_FULLNESS, Math.max(DROP_SKIP_FULLNESS, fullness));
78
+ const dropRatio = DROP_MIN_RATIO
79
+ + ((cappedFullness - DROP_SKIP_FULLNESS) / (DROP_MAX_FULLNESS - DROP_SKIP_FULLNESS))
80
+ * (DROP_MAX_RATIO - DROP_MIN_RATIO);
81
+ return Math.max(1, Math.floor(droppableCount * dropRatio));
82
+ }
83
+
84
+ export function normalizeDropObservationIds(
85
+ ids: readonly string[] | undefined,
86
+ observations: readonly Observation[],
87
+ ): string[] | undefined {
88
+ if (!ids || ids.length === 0) return undefined;
89
+ const allowed = new Map(observations.map((observation) => [observation.id, observation]));
90
+ const result: string[] = [];
91
+ const seen = new Set<string>();
92
+ for (const id of ids) {
93
+ const observation = allowed.get(id);
94
+ if (!observation) continue;
95
+ if (observation.relevance === "critical") continue;
96
+ if (seen.has(id)) continue;
97
+ seen.add(id);
98
+ result.push(id);
99
+ }
100
+ return result.length > 0 ? result : undefined;
101
+ }
102
+
103
+ export function selectDropCandidates(
104
+ ids: readonly string[],
105
+ observations: readonly Observation[],
106
+ maxDrops: number,
107
+ ): string[] {
108
+ if (maxDrops <= 0 || ids.length === 0) return [];
109
+
110
+ const byId = new Map(observations.map((observation) => [observation.id, observation]));
111
+ const firstProposalIndex = new Map<string, number>();
112
+ for (let i = 0; i < ids.length; i++) {
113
+ const id = ids[i];
114
+ if (!firstProposalIndex.has(id)) firstProposalIndex.set(id, i);
115
+ }
116
+
117
+ return Array.from(firstProposalIndex.entries())
118
+ .map(([id, index]) => ({ id, index, observation: byId.get(id) }))
119
+ .filter((candidate): candidate is { id: string; index: number; observation: Observation } =>
120
+ candidate.observation !== undefined && candidate.observation.relevance !== "critical"
121
+ )
122
+ .sort((a, b) => {
123
+ const relevanceDelta = RELEVANCE_DROP_RANK[a.observation.relevance] - RELEVANCE_DROP_RANK[b.observation.relevance];
124
+ return relevanceDelta || a.index - b.index;
125
+ })
126
+ .slice(0, maxDrops)
127
+ .map((candidate) => candidate.id);
128
+ }
129
+
130
+ export async function runDropper(args: RunDropperArgs): Promise<string[] | undefined> {
131
+ const { model, apiKey, headers, reflections, observations, budgetTokens, signal } = args;
132
+ if (observations.length === 0) return undefined;
133
+
134
+ const observationTokens = observations.reduce((sum, observation) => sum + observation.tokenCount, 0);
135
+ const fullness = observationPoolFullness(observationTokens, budgetTokens);
136
+ const urgency = dropUrgencyForFullness(fullness);
137
+ const maxDropsAllowed = maxDropCountForPool(observations, observationTokens, budgetTokens);
138
+ if (maxDropsAllowed <= 0) return undefined;
139
+
140
+ const proposedDropIds: string[] = [];
141
+ const proposed = new Set<string>();
142
+
143
+ const dropObservations: AgentTool<typeof DropObservationsSchema> = {
144
+ name: "drop_observations",
145
+ label: "Drop observations",
146
+ description: "Propose active observation ids that are safe to remove from compacted memory.",
147
+ parameters: DropObservationsSchema,
148
+ execute: async (_id, params: DropObservationsArgs) => {
149
+ const normalized = normalizeDropObservationIds(params.ids, observations) ?? [];
150
+ let added = 0;
151
+ for (const id of normalized) {
152
+ if (proposed.has(id)) continue;
153
+ proposed.add(id);
154
+ proposedDropIds.push(id);
155
+ added++;
156
+ }
157
+ return {
158
+ content: [{ type: "text", text: `Queued ${added} drop candidate${added === 1 ? "" : "s"}. Candidates this run: ${proposedDropIds.length}. Maximum drops allowed: ${maxDropsAllowed}.` }],
159
+ details: { added, totalCandidates: proposedDropIds.length, maxDropsAllowed },
160
+ };
161
+ },
162
+ };
163
+
164
+ const fullnessPercent = Math.round(fullness * 100);
165
+ const existingObservationsContext = args.existingObservationsSummary
166
+ ? `EXISTING ACTIVE OBSERVATIONS (for context only — these are NOT candidates for dropping):\n${args.existingObservationsSummary}\n\n`
167
+ : '';
168
+
169
+ const userText = `CURRENT REFLECTIONS:\n${joinOrEmpty(reflections.map(reflectionToSummaryLine))}\n\n${existingObservationsContext}NEW OBSERVATIONS TO EVALUATE FOR DROPPING:\n${joinOrEmpty(observations.map(observationToSummaryLine))}\n\nObservation pool pressure: ~${observationTokens.toLocaleString()} tokens; target budget: ~${budgetTokens.toLocaleString()} tokens; fullness: ~${fullnessPercent.toLocaleString()}%.\nDrop urgency: ${urgency}.\nMaximum drops allowed this run: ${maxDropsAllowed.toLocaleString()} observation${maxDropsAllowed === 1 ? "" : "s"}.\nThis maximum is a hard upper bound, not a target. Drop fewer or none if fewer observations are clearly safe.`;
170
+ const prompts: Message[] = [{ role: "user", content: [{ type: "text", text: userText }], timestamp: Date.now() }];
171
+ const context: AgentContext = { systemPrompt: DROPPER_SYSTEM, messages: [], tools: [dropObservations as AgentTool<any>] };
172
+ const reasoning = (model as { reasoning?: unknown }).reasoning;
173
+ const thinkingLevel = args.thinkingLevel ?? "low";
174
+ const effectiveMaxTurns = args.maxTurns && args.maxTurns > 0 ? args.maxTurns : undefined;
175
+ let turnCount = 0;
176
+ const config: AgentLoopConfig = {
177
+ model,
178
+ apiKey,
179
+ headers,
180
+ maxTokens: boundedMaxTokens(model, AGENT_LOOP_MAX_TOKENS),
181
+ convertToLlm: (msgs) => msgs as Message[],
182
+ toolExecution: "sequential",
183
+ ...(reasoning && thinkingLevel !== "off" ? { reasoning: thinkingLevel } : {}),
184
+ ...(effectiveMaxTurns !== undefined ? { shouldStopAfterTurn: () => ++turnCount >= effectiveMaxTurns } : {}),
185
+ };
186
+
187
+ const loop = args.agentLoop ?? agentLoop;
188
+ const stream = loop(prompts, context, config, signal);
189
+ let agentError: string | undefined;
190
+ for await (const event of stream) {
191
+ // Tool execution collects candidate ids.
192
+ if (event.type === "agent_end") {
193
+ const msgs = ((event as any).messages || []) as Array<{ stopReason?: string; errorMessage?: string }>;
194
+ const lastMsg = msgs[msgs.length - 1];
195
+ if (lastMsg?.stopReason === "error") {
196
+ agentError = lastMsg.errorMessage ?? "Unknown API error";
197
+ }
198
+ }
199
+ }
200
+ await stream.result();
201
+ if (agentError && proposedDropIds.length === 0) throw new Error(`Dropper API error: ${agentError}`);
202
+ const droppedIds = selectDropCandidates(proposedDropIds, observations, maxDropsAllowed);
203
+ return droppedIds.length > 0 ? droppedIds : undefined;
204
+ }
@@ -0,0 +1,48 @@
1
+ export const DROPPER_SYSTEM = `You are the dropper agent for a coding assistant.
2
+
3
+ These records are the ONLY information the assistant will have about past interactions once the raw conversation is compacted out of context. Dropping the wrong observation can make future work repeat, contradict, or misremember the user. Take this seriously.
4
+
5
+ Your job is to identify only the safest active observations to remove from compacted memory by calling drop_observations with their ids. Default action is KEEP. When uncertain, keep the observation.
6
+
7
+ Active-memory framing. Dropping an observation removes it from active compacted memory; it does not erase the ledger history or source evidence. Still, future compressed context will no longer show the observation, so only drop it when its durable meaning is safely captured elsewhere or it is genuinely low-signal and carries no unique future value.
8
+
9
+ The user message includes drop urgency and "Maximum drops allowed this run". The maximum is a hard upper bound, not a target. Never try to hit it. Drop fewer or none when fewer observations are safely removable.
10
+
11
+ Urgency guidance:
12
+ - low urgency: only propose trivially safe drops, usually low-signal observations with no unique detail.
13
+ - medium urgency: perform conservative cleanup; prefer low observations and clearly redundant medium observations.
14
+ - high urgency: cleanup is more useful, but preservation rules do not weaken and load-bearing memory must still be kept.
15
+
16
+ What to drop, in priority order:
17
+ - Redundant observations whose durable meaning is already captured by current reflections with equivalent fidelity.
18
+ - Superseded observations where a later observation clearly replaces the older state.
19
+ - Repeated routine tool acknowledgements or low-signal progress updates that do not carry decisions, constraints, exact errors, or user-specific facts.
20
+ - Older medium observations that no longer carry working context and are covered by a reflection or a newer observation.
21
+
22
+ Age-gradient rule. Recent observations carry working context the assistant may still need; older observations have usually been summarized elsewhere or are no longer load-bearing. Prefer older safe drops before newer working context.
23
+
24
+ Relevance guidance:
25
+ - low: consider first, but drop only when it carries no unique detail, decision, state, error, identifier, or user-specific fact.
26
+ - medium: drop when redundant with reflections or other observations, or when the work state is clearly obsolete.
27
+ - high: drop only when clearly superseded or already captured by a reflection with equivalent fidelity.
28
+ - critical: NEVER drop. Code also rejects critical ids, but you must avoid proposing them.
29
+
30
+ User assertions and concrete completions are never droppable, even at non-critical relevance, unless a current reflection preserves the exact assertion/completion and its important details with equivalent fidelity.
31
+
32
+ Preservation floor. Regardless of relevance label, urgency, budget pressure, or age, do not drop observations that uniquely carry any of the following:
33
+ - User preferences, constraints, corrections, or identity/role facts.
34
+ - Concrete completions that future runs must not redo.
35
+ - Named identifiers, file paths, function names, package names, tickets, commit SHAs, handles, or exact commands.
36
+ - Exact error messages, diagnostic output, or test failure names.
37
+ - Architectural or technical decisions and their rationale.
38
+ - Dates of specific events, deadlines, meetings, migrations, or incidents.
39
+ - Current unresolved blockers, TODOs, partial work, or decisions waiting on the user.
40
+ - Non-standard user terminology or unusual phrasing needed for future recognition.
41
+
42
+ What you cannot do:
43
+ - You cannot merge observations.
44
+ - You cannot rewrite or edit observations.
45
+ - You cannot add new observations or reflections.
46
+ - You can only call drop_observations with ids from the current observations list.
47
+
48
+ Do not force drops you do not believe in. If no observations are safe to drop, do not call the tool and reply briefly. Hitting the budget or maximum count is less important than preserving load-bearing memory.`;
@@ -0,0 +1,256 @@
1
+ /**
2
+ * Observer agent — uses agentLoop to distill conversation chunks into observations.
3
+ *
4
+ * Upstream: https://github.com/elpapi42/pi-observational-memory (src/agents/observer/agent.ts)
5
+ * Modified by pi-vcc-om: detects agent_end stopReason="error" in the stream
6
+ * and throws if the API errored without collecting any tool results.
7
+ * This allows the consolidation pipeline to fall back to alternative models.
8
+ */
9
+ import { agentLoop, type AgentContext, type AgentLoopConfig, type AgentTool } from "@earendil-works/pi-agent-core";
10
+ import type { Message, Model, ModelThinkingLevel } from "@earendil-works/pi-ai";
11
+ import { Type } from "@earendil-works/pi-ai";
12
+ import type { Static } from "typebox";
13
+ import { hashId } from "../../ids.js";
14
+ import { AGENT_LOOP_MAX_TOKENS, boundedMaxTokens } from "../../model-budget.js";
15
+ import { OBSERVER_SYSTEM } from "./prompts.js";
16
+ import { nowTimestamp, truncateRecordContent } from "../../serialize.js";
17
+ import type { Observation, Relevance } from "../../ledger/index.js";
18
+ import { estimateStringTokens } from "../../tokens.js";
19
+
20
+ interface RunObserverArgs {
21
+ model: Model<any>;
22
+ apiKey: string;
23
+ headers?: Record<string, string>;
24
+ priorReflections: string[];
25
+ priorObservations: string[];
26
+ chunk: string;
27
+ allowedSourceEntryIds: string[];
28
+ signal?: AbortSignal;
29
+ agentLoop?: typeof agentLoop;
30
+ maxTurns?: number;
31
+ thinkingLevel?: ModelThinkingLevel;
32
+ }
33
+
34
+ const RelevanceSchema = Type.Union([
35
+ Type.Literal("low"),
36
+ Type.Literal("medium"),
37
+ Type.Literal("high"),
38
+ Type.Literal("critical"),
39
+ ]);
40
+
41
+ export const OBSERVATION_TIMESTAMP_PATTERN = "^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$";
42
+
43
+ const RecordObservationsSchema = Type.Object({
44
+ observations: Type.Array(
45
+ Type.Object({
46
+ timestamp: Type.String({
47
+ pattern: OBSERVATION_TIMESTAMP_PATTERN,
48
+ description: "Observation time in local 'YYYY-MM-DD HH:MM' format.",
49
+ }),
50
+ content: Type.String({
51
+ minLength: 1,
52
+ description: "Single-line plain prose. No markdown, no tags, no embedded timestamp.",
53
+ }),
54
+ relevance: RelevanceSchema,
55
+ sourceEntryIds: Type.Array(
56
+ Type.String({ minLength: 1 }),
57
+ {
58
+ minItems: 1,
59
+ description:
60
+ "Exact source entry ids from the chunk that directly support this observation. " +
61
+ "Use only ids shown in '[Source entry id: ...]' labels; never invent ids.",
62
+ },
63
+ ),
64
+ }),
65
+ { description: "Batch of new observations. May be empty only if the tool is not called at all." },
66
+ ),
67
+ });
68
+
69
+ type RecordObservationsArgs = Static<typeof RecordObservationsSchema>;
70
+
71
+ function joinOrEmpty(items: string[]): string {
72
+ return items.length ? items.join("\n") : "(none yet)";
73
+ }
74
+
75
+ export function normalizeSourceEntryIds(
76
+ sourceEntryIds: readonly string[] | undefined,
77
+ allowedSourceEntryIds: readonly string[],
78
+ ): string[] | undefined {
79
+ if (!sourceEntryIds || sourceEntryIds.length === 0) return undefined;
80
+ const allowedOrder = new Map<string, number>();
81
+ for (let i = 0; i < allowedSourceEntryIds.length; i++) allowedOrder.set(allowedSourceEntryIds[i], i);
82
+
83
+ const seen = new Set<string>();
84
+ for (const id of sourceEntryIds) {
85
+ if (!allowedOrder.has(id)) return undefined;
86
+ seen.add(id);
87
+ }
88
+ if (seen.size === 0) return undefined;
89
+ return Array.from(seen).sort((a, b) => (allowedOrder.get(a) ?? 0) - (allowedOrder.get(b) ?? 0));
90
+ }
91
+
92
+ /** Result returned by runObserver when no observations are recorded. */
93
+ export type ObserverEmptyReason =
94
+ | { kind: "no_new_content" } // model ran but nothing worth recording
95
+ | { kind: "tool_not_called" } // model didn't call record_observations at all
96
+ | { kind: "all_rejected"; count: number } // tool called but all sourceEntryIds invalid
97
+ | { kind: "all_duplicates"; count: number } // tool called but all already seen
98
+ | { kind: "empty_array"; count: number }; // tool called but returned empty observations array
99
+
100
+ export interface ObserverResult {
101
+ observations: Observation[] | undefined;
102
+ emptyReason?: ObserverEmptyReason;
103
+ }
104
+
105
+ export async function runObserver(args: RunObserverArgs): Promise<ObserverResult> {
106
+ const { model, apiKey, headers, priorReflections, priorObservations, chunk, allowedSourceEntryIds, signal } = args;
107
+ const conversation = chunk.trim();
108
+ if (!conversation) return { observations: undefined };
109
+
110
+ const accumulated = new Map<string, Observation>();
111
+ let toolCalled = false;
112
+ let totalAdded = 0;
113
+ let totalDuplicates = 0;
114
+ let totalRejected = 0;
115
+ let totalProposed = 0;
116
+
117
+ const recordObservations: AgentTool<typeof RecordObservationsSchema> = {
118
+ name: "record_observations",
119
+ label: "Record observations",
120
+ description:
121
+ "Record a batch of new observations distilled from the conversation chunk. " +
122
+ "Call this multiple times as you work through the chunk. Stop calling when coverage is complete, " +
123
+ "then emit a short plain-text confirmation to end the run.",
124
+ parameters: RecordObservationsSchema,
125
+ execute: async (_id, params: RecordObservationsArgs) => {
126
+ toolCalled = true;
127
+ let added = 0;
128
+ let duplicates = 0;
129
+ let rejected = 0;
130
+ for (const obs of params.observations) {
131
+ totalProposed++;
132
+ const sourceEntryIds = normalizeSourceEntryIds(obs.sourceEntryIds, allowedSourceEntryIds);
133
+ if (!sourceEntryIds) {
134
+ rejected++;
135
+ continue;
136
+ }
137
+ const content = truncateRecordContent(obs.content);
138
+ const id = hashId(content);
139
+ if (accumulated.has(id)) {
140
+ duplicates++;
141
+ continue;
142
+ }
143
+ accumulated.set(id, {
144
+ id,
145
+ content,
146
+ timestamp: obs.timestamp,
147
+ relevance: obs.relevance as Relevance,
148
+ sourceEntryIds,
149
+ tokenCount: estimateStringTokens(content),
150
+ });
151
+ added++;
152
+ }
153
+ totalAdded += added;
154
+ totalDuplicates += duplicates;
155
+ totalRejected += rejected;
156
+ const rejectedPart = rejected > 0
157
+ ? ` ${rejected} observation${rejected === 1 ? "" : "s"} rejected for missing or invalid sourceEntryIds.`
158
+ : "";
159
+ const ack =
160
+ `Recorded ${added} new observation${added === 1 ? "" : "s"} ` +
161
+ (duplicates > 0 ? `(${duplicates} duplicate${duplicates === 1 ? "" : "s"} skipped).` : ".") +
162
+ rejectedPart +
163
+ ` Total so far this run: ${accumulated.size}. ` +
164
+ `Continue if the chunk still has uncovered content; otherwise stop calling the tool and emit a short plain-text confirmation.`;
165
+ return { content: [{ type: "text", text: ack }], details: { added, duplicates, rejected, total: accumulated.size } };
166
+ },
167
+ };
168
+
169
+ const now = nowTimestamp();
170
+ const userText = `Current local time: ${now}
171
+
172
+ CURRENT REFLECTIONS:
173
+ ${joinOrEmpty(priorReflections)}
174
+
175
+ CURRENT OBSERVATIONS:
176
+ ${joinOrEmpty(priorObservations)}
177
+
178
+ Compress the following new conversation chunk into observations by calling record_observations one or more times. Do not restate facts already present in current reflections or current observations. Prefer inline conversation timestamps when assigning times; fall back to the current local time above only if no message timestamp applies. Stop calling the tool and reply with a short plain-text confirmation once the chunk is fully covered.
179
+
180
+ NEW CONVERSATION CHUNK:
181
+ ${conversation}`;
182
+
183
+ const prompts: Message[] = [
184
+ {
185
+ role: "user",
186
+ content: [{ type: "text", text: userText }],
187
+ timestamp: Date.now(),
188
+ },
189
+ ];
190
+
191
+ const context: AgentContext = {
192
+ systemPrompt: OBSERVER_SYSTEM,
193
+ messages: [],
194
+ tools: [recordObservations as AgentTool<any>],
195
+ };
196
+
197
+ const reasoning = (model as { reasoning?: unknown }).reasoning;
198
+ const thinkingLevel = args.thinkingLevel ?? "low";
199
+ const effectiveMaxTurns = args.maxTurns && args.maxTurns > 0 ? args.maxTurns : undefined;
200
+ let turnCount = 0;
201
+ const config: AgentLoopConfig = {
202
+ model,
203
+ apiKey,
204
+ headers,
205
+ maxTokens: boundedMaxTokens(model, AGENT_LOOP_MAX_TOKENS),
206
+ convertToLlm: (msgs) => msgs as Message[],
207
+ toolExecution: "sequential",
208
+ ...(reasoning && thinkingLevel !== "off" ? { reasoning: thinkingLevel } : {}),
209
+ ...(effectiveMaxTurns !== undefined
210
+ ? {
211
+ shouldStopAfterTurn: () => {
212
+ turnCount++;
213
+ return turnCount >= effectiveMaxTurns;
214
+ },
215
+ }
216
+ : {}),
217
+ };
218
+
219
+ const loop = args.agentLoop ?? agentLoop;
220
+ const stream = loop(prompts, context, config, signal);
221
+ let agentError: string | undefined;
222
+ for await (const event of stream) {
223
+ // Drain events; the tool's execute already collects records.
224
+ if (event.type === "agent_end") {
225
+ const msgs = ((event as any).messages || []) as Array<{ stopReason?: string; errorMessage?: string }>;
226
+ const lastMsg = msgs[msgs.length - 1];
227
+ if (lastMsg?.stopReason === "error") {
228
+ agentError = lastMsg.errorMessage ?? "Unknown API error";
229
+ }
230
+ }
231
+ }
232
+ await stream.result();
233
+
234
+ if (agentError && accumulated.size === 0) {
235
+ throw new Error(`Observer API error: ${agentError}`);
236
+ }
237
+
238
+ if (accumulated.size === 0) {
239
+ // Determine why no observations were recorded
240
+ let emptyReason: ObserverEmptyReason;
241
+ if (!toolCalled) {
242
+ emptyReason = { kind: "tool_not_called" };
243
+ } else if (totalRejected > 0 && totalAdded === 0) {
244
+ emptyReason = { kind: "all_rejected", count: totalRejected };
245
+ } else if (totalDuplicates > 0 && totalAdded === 0) {
246
+ emptyReason = { kind: "all_duplicates", count: totalDuplicates };
247
+ } else if (totalProposed === 0) {
248
+ emptyReason = { kind: "empty_array", count: 0 };
249
+ } else {
250
+ emptyReason = { kind: "no_new_content" };
251
+ }
252
+ return { observations: undefined, emptyReason };
253
+ }
254
+
255
+ return { observations: Array.from(accumulated.values()) };
256
+ }
@@ -0,0 +1,119 @@
1
+ export const OBSERVER_SYSTEM = `You are the observation agent for a coding assistant.
2
+
3
+ These 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.
4
+
5
+ Your job is to compress a chunk of recent conversation into timestamped, rated observations by calling the record_observations tool. The observations you emit — together with the reflections crystallized from them — are the assistant's ONLY memory of this session after the raw conversation falls out of context.
6
+
7
+ You receive:
8
+ - Current reflections (long-lived facts already crystallized).
9
+ - Current observations (already-recorded observations, each shown as "[id] YYYY-MM-DD HH:MM [relevance] content").
10
+ - 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.
11
+ - A current local time fallback for observations that have no obvious message timestamp.
12
+
13
+ How you work:
14
+ 1. Read reflections and current observations so you know what is already captured.
15
+ 2. Read the conversation chunk and identify what new information it contains.
16
+ 3. Call record_observations with a batch covering part (or all) of the chunk.
17
+ 4. Read the progress receipt. If content remains uncovered, call again. You may call the tool many times.
18
+ 5. 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.
19
+
20
+ What to emit:
21
+ - Produce NEW observations for the new chunk only. Do not restate facts already present in reflections or current observations unless something has materially changed.
22
+ - Use the timestamp from the relevant conversation message. Fall back to current local time ONLY when no message timestamp applies.
23
+ - For every observation, include sourceEntryIds: the smallest exact set of "[Source entry id: ...]" ids that directly support the observation.
24
+ - 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.
25
+ - 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.
26
+ - Group repeated similar tool calls into a single observation rather than one per call.
27
+ - Skip routine, low-information events. It is fine to emit zero observations if the chunk carries no new information — in that case, simply do not call the tool and end with a plain-text confirmation.
28
+
29
+ Observation content rules:
30
+
31
+ Format.
32
+ - Single line of plain prose. No markdown, no bullets, no code fences, no XML/HTML tags, no emojis.
33
+ - Do NOT include the timestamp or relevance inside the content string — those are separate fields.
34
+ - No structured fields embedded in the text (no "key: value" lines, no JSON).
35
+
36
+ Preserve user assertions exactly.
37
+ When 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 — a later question on the same topic does not invalidate them.
38
+ BAD: User wondered if they have two kids.
39
+ GOOD: User stated they have two kids.
40
+ BAD: User discussed auth middleware.
41
+ GOOD: User asked how to configure JWT auth middleware.
42
+ Why 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.
43
+
44
+ Preserve unusual phrasing.
45
+ When the user uses non-standard terminology, quote their exact words so future runs can recognize the term.
46
+ BAD: User exercised yesterday.
47
+ GOOD: User stated they did a "movement session" (their term) yesterday.
48
+
49
+ Use precise action verbs. Replace vague verbs with ones that clarify the nature of the action.
50
+ BAD: User got a new subscription.
51
+ GOOD: User subscribed to the Pro plan.
52
+ BAD: User stopped getting the newsletter.
53
+ GOOD: User unsubscribed from the newsletter.
54
+ BAD: User got the library.
55
+ GOOD: User installed the zod package via pnpm.
56
+
57
+ Frame state changes as supersession so the old state is explicit.
58
+ BAD: User prefers React Query now.
59
+ GOOD: User will use React Query (switching from SWR).
60
+ Why this matters: without supersession framing, the reflector may crystallize both the old and the new as equally valid preferences.
61
+
62
+ Mark concrete completions explicitly.
63
+ Use "completed:", "resolved:", "confirmed working", or similar phrasing so future runs know not to redo the work.
64
+ BAD: Wrote the login handler.
65
+ GOOD: completed: implemented login handler at src/auth/login.ts; user confirmed tests pass.
66
+ Why 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.
67
+
68
+ Split compound statements into separate observations.
69
+ If 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 dropping to operate at fact granularity.
70
+ BAD: User will visit their parents this weekend and needs to clean the garage.
71
+ GOOD: User will visit their parents this weekend. + User stated they need to clean the garage this weekend.
72
+ BAD: User started a new job and is moving to a new apartment next week.
73
+ GOOD: User started a new job. + User will move to a new apartment next week.
74
+ BAD: Assistant recommended Lucia, NextAuth, and Clerk for auth, and user chose Lucia.
75
+ GOOD: Assistant recommended auth libraries: Lucia (session-based, minimal), NextAuth (OAuth-heavy, Next-native), Clerk (hosted, paid). + User chose Lucia.
76
+ Why 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.
77
+
78
+ Group repeated similar tool calls into a single observation rather than one per call.
79
+ BAD: Agent viewed src/auth.ts. Agent viewed src/users.ts. Agent viewed src/routes.ts.
80
+ GOOD: Agent surveyed auth-related files (src/auth.ts, src/users.ts, src/routes.ts) and located token validation in src/auth.ts:45.
81
+
82
+ Detail preservation. When an observation references specific things, preserve the distinguishing details so future queries can still find them:
83
+
84
+ - File/location: full path + line number when relevant (src/auth.ts:45, not "the auth file").
85
+ - Identifiers and names: package names, function names, variable names, handles, ticket ids, commit SHAs, error codes. Keep them verbatim.
86
+ - Error messages: quote verbatim.
87
+ BAD: Build failed with a type error.
88
+ GOOD: Build failed: TS2322: Type 'string | undefined' is not assignable to type 'string' at src/auth.ts:47.
89
+ - Numerical results: exact values, units, and direction.
90
+ BAD: Optimization made it faster.
91
+ GOOD: Optimization reduced p95 latency from 420ms to 180ms (57% faster).
92
+ - Quantities and counts: "3 failing tests (auth.test.ts, users.test.ts, routes.test.ts)" not "some failing tests".
93
+ - Recommendation or decision lists: preserve the distinguishing attribute per item.
94
+ BAD: Assistant recommended 3 auth libraries.
95
+ GOOD: Assistant recommended auth libraries: Lucia (session-based, minimal), NextAuth (OAuth-heavy, Next-native), Clerk (hosted, paid).
96
+ - Role / participation: capture the user's role at an event, not just attendance.
97
+ BAD: User worked on the migration.
98
+ GOOD: User led the migration from MySQL to Postgres.
99
+
100
+ If 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.
101
+
102
+ Relevance levels (pick one per observation; this field drives future dropping):
103
+
104
+ - 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.
105
+ - high: non-trivial technical decisions, architectural direction, unresolved blockers, key constraints. Worth keeping across many compactions.
106
+ - medium: task-level context that helps within the current work but isn't durable. The default when you are unsure between medium and high.
107
+ - low: routine tool-call acks, repetitive status updates, content trivially re-derivable from recent messages. The dropper will drop these first.
108
+
109
+ Do NOT default to "critical" or "high". Most observations are medium or low. Reserve "critical" for things that would cause real damage if forgotten.
110
+
111
+ BAD: relevance=critical for "Agent ran tests and they passed."
112
+ GOOD: relevance=low for "Agent ran tests and they passed." (routine; captured by a completion observation if it matters)
113
+
114
+ BAD: relevance=medium for "User said they are colorblind; red/green indicators do not work for them."
115
+ GOOD: relevance=critical for "User said they are colorblind; red/green indicators do not work for them." (persistent constraint; forgetting it causes real harm)
116
+
117
+ Timestamp format: "YYYY-MM-DD HH:MM" (local time, 24-hour, to the minute). This goes in the timestamp field, not the content.
118
+
119
+ Remember: these observations are the assistant's ONLY memory of this chunk once the raw messages fall out of context. Make them count.`;