pi-observational-memory 2.4.3 → 3.0.1

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 (38) hide show
  1. package/README.md +318 -103
  2. package/package.json +9 -9
  3. package/src/agents/dropper/agent.ts +281 -0
  4. package/src/agents/dropper/coverage.ts +128 -0
  5. package/src/agents/dropper/pool.ts +67 -0
  6. package/src/agents/dropper/prompts.ts +48 -0
  7. package/src/{observer.ts → agents/observer/agent.ts} +11 -13
  8. package/src/agents/observer/prompts.ts +119 -0
  9. package/src/agents/reflector/agent.ts +203 -0
  10. package/src/agents/reflector/prompts.ts +81 -0
  11. package/src/clipboard.ts +63 -0
  12. package/src/commands/status.ts +79 -78
  13. package/src/commands/view.ts +58 -66
  14. package/src/config.ts +78 -55
  15. package/src/debug-log.ts +24 -5
  16. package/src/hooks/compaction-hook.ts +24 -369
  17. package/src/hooks/compaction-trigger.ts +12 -21
  18. package/src/hooks/consolidation-trigger.ts +368 -0
  19. package/src/index.ts +3 -3
  20. package/src/model-budget.ts +1 -1
  21. package/src/runtime.ts +46 -19
  22. package/src/serialize.ts +1 -1
  23. package/src/session-ledger/fold.ts +100 -0
  24. package/src/session-ledger/index.ts +6 -0
  25. package/src/session-ledger/progress.ts +129 -0
  26. package/src/session-ledger/projection.ts +220 -0
  27. package/src/session-ledger/recall.ts +237 -0
  28. package/src/session-ledger/render-summary.ts +31 -0
  29. package/src/session-ledger/types.ts +200 -0
  30. package/src/tokens.ts +1 -1
  31. package/src/tools/recall-observation.ts +84 -214
  32. package/src/branch.ts +0 -577
  33. package/src/compaction.ts +0 -1030
  34. package/src/hooks/observer-trigger.ts +0 -129
  35. package/src/progress.ts +0 -155
  36. package/src/prompts.ts +0 -302
  37. package/src/relevance.ts +0 -15
  38. package/src/types.ts +0 -155
@@ -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 highest-resistance, load-bearing observations and require the strongest evidence before leaving active memory. 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.`;
@@ -0,0 +1,203 @@
1
+ import { agentLoop, type AgentContext, type AgentLoopConfig, type AgentTool } from "@earendil-works/pi-agent-core";
2
+ import type { Message, Model, ModelThinkingLevel } from "@earendil-works/pi-ai";
3
+ import { Type } from "@earendil-works/pi-ai";
4
+ import type { Static } from "typebox";
5
+ import { debugLog } from "../../debug-log.js";
6
+ import { hashId } from "../../ids.js";
7
+ import { AGENT_LOOP_MAX_TOKENS, boundedMaxTokens } from "../../model-budget.js";
8
+ import { truncateRecordContent } from "../../serialize.js";
9
+ import { REFLECTOR_SYSTEM } from "./prompts.js";
10
+ import { estimateStringTokens } from "../../tokens.js";
11
+ import { reflectionToSummaryLine, type Observation, type Reflection } from "../../session-ledger/index.js";
12
+ import {
13
+ coverageTierForObservation,
14
+ reflectionCoverageMap,
15
+ summarizeCoverageByRelevance,
16
+ summarizeCoverageTransitionsByRelevance,
17
+ type ReflectionCoverageTier,
18
+ } from "../dropper/coverage.js";
19
+
20
+ interface RunReflectorArgs {
21
+ model: Model<any>;
22
+ apiKey: string;
23
+ headers?: Record<string, string>;
24
+ reflections: Reflection[];
25
+ observations: Observation[];
26
+ signal?: AbortSignal;
27
+ agentLoop?: typeof agentLoop;
28
+ maxTurns?: number;
29
+ thinkingLevel?: ModelThinkingLevel;
30
+ }
31
+
32
+ const RecordReflectionsSchema = Type.Object({
33
+ reflections: Type.Array(
34
+ Type.Object({
35
+ content: Type.String({ minLength: 1 }),
36
+ supportingObservationIds: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }),
37
+ }),
38
+ { minItems: 1 },
39
+ ),
40
+ });
41
+
42
+ type RecordReflectionsArgs = Static<typeof RecordReflectionsSchema>;
43
+
44
+ function joinOrEmpty(items: string[]): string {
45
+ return items.length ? items.join("\n") : "(none yet)";
46
+ }
47
+
48
+ export function observationToReflectorLine(
49
+ observation: Observation,
50
+ coverage: ReflectionCoverageTier,
51
+ ): string {
52
+ return `[${observation.id}] ${observation.timestamp} [${observation.relevance}] [coverage: ${coverage}] ${observation.content}`;
53
+ }
54
+
55
+ export function summarizeSupportIdCounts(reflections: readonly Reflection[]): {
56
+ reflectionCount: number;
57
+ totalSupportIds: number;
58
+ minSupportIds: number;
59
+ maxSupportIds: number;
60
+ averageSupportIds: number;
61
+ histogram: Record<string, number>;
62
+ } {
63
+ if (reflections.length === 0) {
64
+ return { reflectionCount: 0, totalSupportIds: 0, minSupportIds: 0, maxSupportIds: 0, averageSupportIds: 0, histogram: {} };
65
+ }
66
+ const counts = reflections.map((reflection) => reflection.supportingObservationIds.length);
67
+ const totalSupportIds = counts.reduce((sum, count) => sum + count, 0);
68
+ const histogram: Record<string, number> = {};
69
+ for (const count of counts) histogram[String(count)] = (histogram[String(count)] ?? 0) + 1;
70
+ return {
71
+ reflectionCount: reflections.length,
72
+ totalSupportIds,
73
+ minSupportIds: Math.min(...counts),
74
+ maxSupportIds: Math.max(...counts),
75
+ averageSupportIds: totalSupportIds / reflections.length,
76
+ histogram,
77
+ };
78
+ }
79
+
80
+ export function normalizeSupportingObservationIds(
81
+ supportingObservationIds: readonly string[] | undefined,
82
+ allowedObservationIds: readonly string[],
83
+ ): string[] | undefined {
84
+ if (!supportingObservationIds || supportingObservationIds.length === 0) return undefined;
85
+ const allowedOrder = new Map<string, number>();
86
+ for (let i = 0; i < allowedObservationIds.length; i++) {
87
+ if (!allowedOrder.has(allowedObservationIds[i])) allowedOrder.set(allowedObservationIds[i], i);
88
+ }
89
+
90
+ const seen = new Set<string>();
91
+ for (const id of supportingObservationIds) {
92
+ if (!allowedOrder.has(id)) return undefined;
93
+ seen.add(id);
94
+ }
95
+ if (seen.size === 0) return undefined;
96
+ return Array.from(seen).sort((a, b) => (allowedOrder.get(a) ?? 0) - (allowedOrder.get(b) ?? 0));
97
+ }
98
+
99
+ function normalizeReflectionContent(content: string): string | undefined {
100
+ const normalized = truncateRecordContent(content.trim());
101
+ if (!normalized || /\r|\n/.test(normalized)) return undefined;
102
+ return normalized;
103
+ }
104
+
105
+ export async function runReflector(args: RunReflectorArgs): Promise<Reflection[] | undefined> {
106
+ const { model, apiKey, headers, reflections, observations, signal } = args;
107
+ if (observations.length === 0) return undefined;
108
+
109
+ const coverageById = reflectionCoverageMap(observations, reflections);
110
+ debugLog("reflector.agent_start", {
111
+ activeObservationCount: observations.length,
112
+ reflectionCount: reflections.length,
113
+ coverageSummaryByRelevance: summarizeCoverageByRelevance(observations, coverageById),
114
+ });
115
+
116
+ const allowedObservationIds = observations.map((observation) => observation.id);
117
+ const existingReflectionIds = new Set(reflections.map((reflection) => reflection.id));
118
+ const accumulated = new Map<string, Reflection>();
119
+ let toolCallCount = 0;
120
+ let rawProposedReflectionCount = 0;
121
+ let acceptedReflectionCount = 0;
122
+ let duplicateReflectionCount = 0;
123
+ let rejectedReflectionCount = 0;
124
+
125
+ const recordReflections: AgentTool<typeof RecordReflectionsSchema> = {
126
+ name: "record_reflections",
127
+ label: "Record reflections",
128
+ description: "Record new durable reflections with supporting observation ids.",
129
+ parameters: RecordReflectionsSchema,
130
+ execute: async (_id, params: RecordReflectionsArgs) => {
131
+ toolCallCount++;
132
+ rawProposedReflectionCount += params.reflections.length;
133
+ let added = 0;
134
+ let duplicates = 0;
135
+ let rejected = 0;
136
+ for (const proposal of params.reflections) {
137
+ const content = normalizeReflectionContent(proposal.content);
138
+ const supportingObservationIds = normalizeSupportingObservationIds(proposal.supportingObservationIds, allowedObservationIds);
139
+ if (!content || !supportingObservationIds) {
140
+ rejected++;
141
+ continue;
142
+ }
143
+ const id = hashId(content);
144
+ if (existingReflectionIds.has(id) || accumulated.has(id)) {
145
+ duplicates++;
146
+ continue;
147
+ }
148
+ accumulated.set(id, {
149
+ id,
150
+ content,
151
+ supportingObservationIds,
152
+ tokenCount: estimateStringTokens(content),
153
+ });
154
+ added++;
155
+ }
156
+ acceptedReflectionCount += added;
157
+ duplicateReflectionCount += duplicates;
158
+ rejectedReflectionCount += rejected;
159
+ return {
160
+ content: [{ type: "text", text: `Recorded ${added} reflection${added === 1 ? "" : "s"}; ${duplicates} duplicate${duplicates === 1 ? "" : "s"}; ${rejected} rejected. Total this run: ${accumulated.size}.` }],
161
+ details: { added, duplicates, rejected, total: accumulated.size },
162
+ };
163
+ },
164
+ };
165
+
166
+ const userText = `CURRENT REFLECTIONS:\n${joinOrEmpty(reflections.map(reflectionToSummaryLine))}\n\nCURRENT OBSERVATIONS:\n${joinOrEmpty(observations.map((observation) => observationToReflectorLine(observation, coverageTierForObservation(observation, coverageById))))}\n\nCrystallize any missing durable facts or patterns into new reflections. If nothing is stable enough, do not call the tool.`;
167
+ const prompts: Message[] = [{ role: "user", content: [{ type: "text", text: userText }], timestamp: Date.now() }];
168
+ const context: AgentContext = { systemPrompt: REFLECTOR_SYSTEM, messages: [], tools: [recordReflections as AgentTool<any>] };
169
+ const reasoning = (model as { reasoning?: unknown }).reasoning;
170
+ const thinkingLevel = args.thinkingLevel ?? "low";
171
+ const effectiveMaxTurns = args.maxTurns && args.maxTurns > 0 ? args.maxTurns : undefined;
172
+ let turnCount = 0;
173
+ const config: AgentLoopConfig = {
174
+ model,
175
+ apiKey,
176
+ headers,
177
+ maxTokens: boundedMaxTokens(model, AGENT_LOOP_MAX_TOKENS),
178
+ convertToLlm: (msgs) => msgs as Message[],
179
+ toolExecution: "sequential",
180
+ ...(reasoning && thinkingLevel !== "off" ? { reasoning: thinkingLevel } : {}),
181
+ ...(effectiveMaxTurns !== undefined ? { shouldStopAfterTurn: () => ++turnCount >= effectiveMaxTurns } : {}),
182
+ };
183
+
184
+ const loop = args.agentLoop ?? agentLoop;
185
+ const stream = loop(prompts, context, config, signal);
186
+ for await (const _event of stream) {
187
+ // Tool execution collects records.
188
+ }
189
+ await stream.result();
190
+ const acceptedReflections = Array.from(accumulated.values());
191
+ const afterCoverageById = reflectionCoverageMap(observations, [...reflections, ...acceptedReflections]);
192
+ debugLog("reflector.result", {
193
+ reason: acceptedReflections.length > 0 ? "accepted_nonempty" : toolCallCount === 0 ? "no_tool_call" : "all_filtered",
194
+ toolCallCount,
195
+ rawProposedReflectionCount,
196
+ acceptedReflectionCount,
197
+ duplicateReflectionCount,
198
+ rejectedReflectionCount,
199
+ acceptedSupportIdCounts: summarizeSupportIdCounts(acceptedReflections),
200
+ coverageTransitionsByRelevance: summarizeCoverageTransitionsByRelevance(observations, coverageById, afterCoverageById),
201
+ });
202
+ return acceptedReflections.length > 0 ? acceptedReflections : undefined;
203
+ }
@@ -0,0 +1,81 @@
1
+ export const REFLECTOR_SYSTEM = `You are the reflection 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 fail to preserve may be forgotten. Anything you distort may be remembered wrong. Take this seriously. Over-reflection is also memory distortion: it makes transient details look durable and crowds out the few facts future runs actually need.
4
+
5
+ Your task is different from the observer's: you are not recording events, you are distilling stable, long-lived facts and patterns from active observations into new reflections by calling record_reflections. Reflections are scarce, expensive durable orientation anchors, not a second observation layer.
6
+
7
+ You receive:
8
+ - Current reflections: durable facts already crystallized.
9
+ - Current observations: active timestamped evidence lines, each shown as "[id] YYYY-MM-DD HH:MM [relevance] [coverage: none|partial|strong] content".
10
+ - Coverage tiers are review context: none means no current reflection supports the observation id, partial means exactly one current reflection supports it, and strong means two or more current reflections support it. Coverage is not a quota, target, priority score, or instruction to emit reflections.
11
+
12
+ What to emit:
13
+ - Emit only new durable reflections not already present in current reflections.
14
+ - A good reflection captures meaning that should survive after individual observations are dropped from active compacted memory.
15
+ - High and critical observations deserve careful review, not automatic reflection. Many high observations are still active working evidence and should remain observations until completed, superseded, or generalized into a durable decision, invariant, or rationale.
16
+ - Ignore low observations unless a repeated pattern across many low observations is itself significant.
17
+ - 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 an existing reflection.
18
+ - Do not emit update-style records or provenance metadata. Reflections are plain durable facts, not patches.
19
+ - It is fine to emit zero reflections when nothing new is stable enough; in that case do not call the tool and reply briefly.
20
+
21
+ Decision procedure:
22
+ 1. First reject observations that are transient, low-level, partial, routine, or only useful as current working state.
23
+ 2. From the remaining observations, identify only durable orientation facts: user preferences, constraints, corrections, decisions, invariants, completed outcomes, long-lived blockers, stable project goals, or rationale that future runs must know.
24
+ 3. Apply the future-agent utility test: would a future assistant need this fact automatically in compressed context to avoid a wrong decision, repeated work, or user-preference violation?
25
+ 4. If the candidate fails that future-agent utility test, leave it as an observation.
26
+ 5. If unsure, emit no reflection.
27
+
28
+ Abstraction gate:
29
+ - Do not turn each observation into a reflection. Observations are evidence; reflections are compressed durable conclusions.
30
+ - A reflection should usually do at least one of these: combine multiple observations into one durable pattern, preserve a user preference/constraint/correction/decision, record a completed outcome future runs must not redo, or capture durable rationale that explains why a decision was made.
31
+ - Single-observation reflections are allowed when the observation itself contains a durable user preference, constraint, correction, decision, invariant, completed outcome, or long-lived blocker.
32
+ - Do not copy or lightly paraphrase observation lines just because they are high or critical. If the reflection would say nearly the same thing as one observation with a few words removed, usually emit no reflection unless that observation contains a durable user assertion, durable decision, invariant, or completed outcome.
33
+ - Most transient task-log observations, tool status, one-off attempts, files inspected, commands run, failed attempts, partial implementation, and current working state should not become reflections. Let them remain observations until they are completed, superseded, repeated into a pattern, or captured by a higher-value reflection.
34
+ - Prefer fewer, higher-value reflections. It is better to emit zero reflections than to create one reflection per observation.
35
+
36
+ Focus on:
37
+ - User identity, role, preferences, constraints, and durable corrections.
38
+ - Project goals, architecture, technical decisions, and the rationale behind them.
39
+ - Recurring user behavior or preferences that will matter in future turns.
40
+ - Completed outcomes future runs must not redo.
41
+ - Durable blockers, invariants, and open decisions that should survive compaction.
42
+
43
+ Support ids and coverage stewardship:
44
+ - Every reflection must include supportingObservationIds from the current observations list.
45
+ - First decide whether the reflection content passes the durable-value bar. Then audit support ids for that already-worthy reflection.
46
+ - supportingObservationIds are a coverage/provenance set and downstream dropper coverage evidence: include all current observation ids whose durable meaning is preserved by the reflection with equivalent fidelity and can later be treated as redundant active-memory detail.
47
+ - supportingObservationIds are not a checklist to cover every observation. Do not add ids merely to improve coverage counts, maximize support ids, maximize strong coverage, or unlock the dropper.
48
+ - False or inflated support ids can cause unsafe downstream dropper pruning, including removal of high-resistance active observations whose meaning was not actually preserved.
49
+ - Include additional observation ids only when the reflection preserves their durable meaning with equivalent fidelity.
50
+ - Leave observations unsupported when their details are still active working state, too specific to compress safely, or not yet durable enough.
51
+ - Do not include observations whose unique exact detail, current task state, user correction, user constraint, or concrete completion is not captured by the reflection.
52
+ - If no candidate reflection passes the durable-value bar, emit zero reflections even when observations have coverage: none.
53
+ - Never invent observation ids. Proposals with missing, empty, or invalid supportingObservationIds are rejected.
54
+
55
+ User 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 — crystallize the assertion, never the question, as the durable fact.
56
+
57
+ Reflection content rules:
58
+ - Single line of plain prose. No markdown, no bullets, no code fences, no XML/HTML tags, no emojis.
59
+ - No timestamp, no priority marker, no bracketed tags, no "key: value" fields, no JSON.
60
+ - Lead with the fact or pattern; include the reason or mechanism when known so future readers can judge edge cases.
61
+ - Preserve user assertions exactly. Use the user's exact words when non-standard.
62
+ - Preserve named identifiers, paths, commands, package names, error codes, dates, decisions, constraints, and rationale when those details are part of the durable meaning.
63
+
64
+ Examples:
65
+ - BAD: User discussed databases.
66
+ - GOOD: User stated they use Postgres for the project database.
67
+ - BAD: User asked about database setup.
68
+ - GOOD: User stated they use Postgres for the project database.
69
+ - BAD: User ran npm test and it failed.
70
+ - GOOD: The test suite currently fails because auth middleware rejects expired JWT fixtures.
71
+ - BAD: User prefers React Query.
72
+ - BAD: User switched from SWR.
73
+ - GOOD: User chose React Query over SWR for server-state caching.
74
+ - BAD: completed: edited src/hooks/reflect-drop-trigger.ts.
75
+ - GOOD: completed: V3 reflect/drop coverage now uses raw progress watermarks, so same-turn reflection entries are no longer used as drop progress markers.
76
+ - BAD: npm test passed.
77
+ - GOOD: completed: V3 package namespace migration passed full tests and typecheck.
78
+ - BAD: Observation aaaaaaaaaaaa says the user likes short answers.
79
+ - GOOD: User prefers short answers without generic summaries.
80
+ - ZERO REFLECTIONS: The only new observations are files inspected, commands run, failed attempts, partial implementation, transient debugging, or current working state with no durable conclusion yet.
81
+ - ZERO REFLECTIONS: The only new observations are routine command outputs, transient debugging attempts, or partial work with no durable conclusion yet.`;
@@ -0,0 +1,63 @@
1
+ import { spawn } from "node:child_process";
2
+
3
+ export interface ClipboardCommand {
4
+ command: string;
5
+ args: string[];
6
+ }
7
+
8
+ export type ClipboardCommandRunner = (command: ClipboardCommand, text: string) => Promise<boolean>;
9
+
10
+ export function getClipboardCommands(platform: NodeJS.Platform = process.platform): ClipboardCommand[] {
11
+ switch (platform) {
12
+ case "darwin":
13
+ return [{ command: "pbcopy", args: [] }];
14
+ case "win32":
15
+ return [{ command: "clip", args: [] }];
16
+ default:
17
+ return [
18
+ { command: "wl-copy", args: [] },
19
+ { command: "xclip", args: ["-selection", "clipboard"] },
20
+ { command: "xsel", args: ["--clipboard", "--input"] },
21
+ { command: "termux-clipboard-set", args: [] },
22
+ ];
23
+ }
24
+ }
25
+
26
+ export async function copyTextToClipboard(
27
+ text: string,
28
+ runner: ClipboardCommandRunner = runClipboardCommand,
29
+ commands: ClipboardCommand[] = getClipboardCommands(),
30
+ ): Promise<boolean> {
31
+ for (const command of commands) {
32
+ if (await runner(command, text)) return true;
33
+ }
34
+ return false;
35
+ }
36
+
37
+ export function runClipboardCommand(command: ClipboardCommand, text: string): Promise<boolean> {
38
+ return new Promise((resolve) => {
39
+ let settled = false;
40
+ let timeout: ReturnType<typeof setTimeout> | undefined;
41
+
42
+ const finish = (ok: boolean) => {
43
+ if (settled) return;
44
+ settled = true;
45
+ if (timeout) clearTimeout(timeout);
46
+ resolve(ok);
47
+ };
48
+
49
+ const child = spawn(command.command, command.args, {
50
+ stdio: ["pipe", "ignore", "ignore"],
51
+ });
52
+
53
+ timeout = setTimeout(() => {
54
+ child.kill();
55
+ finish(false);
56
+ }, 2_000);
57
+
58
+ child.on("error", () => finish(false));
59
+ child.on("close", (code) => finish(code === 0));
60
+ child.stdin.on("error", () => undefined);
61
+ child.stdin.end(text, "utf8");
62
+ });
63
+ }