pi-smart-compact 7.5.1 → 7.7.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.
package/README.md CHANGED
@@ -4,107 +4,298 @@
4
4
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](./LICENSE)
5
5
  [![GitHub](https://img.shields.io/badge/GitHub-alpertarhan%2Fpi--smart--compact-blue)](https://github.com/alpertarhan/pi-smart-compact)
6
6
 
7
- > EESV-powered intelligent context compaction for the [Pi Coding Agent](https://github.com/earendil-works/pi-coding-agent).
7
+ > Intelligent, verification-oriented conversation compaction for the [Pi Coding Agent](https://github.com/earendil-works/pi-coding-agent).
8
8
 
9
- **Smart Compact** compresses long conversation contexts by understanding *what happened* not by blindly truncating. It deterministically extracts files, errors, decisions, and constraints from your session, then uses LLM-guided exploration and parallel batch synthesis to produce a structured summary that preserves the meaning and state of your work.
9
+ **Smart Compact** is a Pi extension that compresses long coding sessions by preserving the *working state* of the conversation - not just the words. Instead of blindly truncating old messages, it extracts verified facts, explores ambiguous areas when needed, synthesizes a structured summary, and checks that the result still covers the important parts of the session.
10
10
 
11
- The result: a shorter context that the agent can actually work with, without losing critical information.
11
+ In practice, that means your agent keeps the things that actually matter:
12
+
13
+ - the real goal
14
+ - exact file paths
15
+ - unresolved errors
16
+ - decisions already made
17
+ - constraints and preferences
18
+ - follow-up work still pending
19
+ - **open loops** — unresolved tasks that survive compaction
20
+ - **delta since last compaction** — what changed, what resolved, what's new
21
+ - **structured state** — machine-readable JSON alongside the Markdown summary
22
+
23
+ ---
24
+
25
+ ## Table of Contents
26
+
27
+ - [Why this exists](#why-this-exists)
28
+ - [What makes it different](#what-makes-it-different)
29
+ - [Design philosophy](#design-philosophy)
30
+ - [Inspiration](#inspiration)
31
+ - [How it works](#how-it-works)
32
+ - [Key capabilities](#key-capabilities)
33
+ - [Installation](#installation)
34
+ - [Quick start](#quick-start)
35
+ - [Configuration](#configuration)
36
+ - [Output format](#output-format)
37
+ - [Architecture details](#architecture-details)
38
+ - [Quality and safety controls](#quality-and-safety-controls)
39
+ - [Compatibility](#compatibility)
40
+ - [Development](#development)
41
+ - [Limitations](#limitations)
42
+ - [Contributing](#contributing)
43
+ - [License](#license)
12
44
 
13
45
  ---
14
46
 
15
- ## Why Smart Compact?
47
+ ## Why this exists
48
+
49
+ Large coding sessions have a very specific failure mode: the context window fills up, compaction happens, and the agent loses the operational memory required to continue well.
50
+
51
+ Typical summaries often miss at least one of these:
16
52
 
17
- Pi's built-in compaction truncates old messages. Smart Compact **understands** them first:
53
+ - which files were actually changed
54
+ - whether an error was resolved or only retried
55
+ - what the user explicitly asked for
56
+ - which architectural decision already won
57
+ - what still needs to happen next
18
58
 
19
- - **Zero-LLM extraction** files modified/read, errors with retry lifecycle, user decisions, constraints, topic segmentation all deterministically extracted before any LLM call
20
- - **Hallucination detection** — verifies the summary doesn't invent file paths or misstate error status
21
- - **Decision propagation** carries decisions across batch boundaries so the LLM never forgets what was decided
22
- - **Redundancy pruning** — collapses duplicate reads, consecutive failures, and low-info messages before compaction, reducing input by 15–30%
23
- - **Cross-session memory** — learns your project's language, framework, and file structure across sessions
24
- - **Damage detection** — monitors post-compaction behavior for regression signals
59
+ For a coding agent, these omissions are expensive. They lead to redundant reads, repeated questions, contradictory edits, or unfinished follow-up work.
60
+
61
+ **Smart Compact** is built to reduce those failures.
25
62
 
26
63
  ---
27
64
 
28
- ## The EESV Pipeline
65
+ ## What makes it different
29
66
 
30
- ```
67
+ Smart Compact is not just "another summary prompt." It is a **multi-stage compaction pipeline** with deterministic extraction, targeted exploration, structured synthesis, and verification.
68
+
69
+ That design gives it a few practical advantages over plain truncation or one-shot summarization:
70
+
71
+ - **Deterministic first, LLM second** - verified facts are extracted before any model call
72
+ - **Cheaper when possible** - simple sessions skip exploration entirely
73
+ - **Safer by default** - summaries are checked for missing files, errors, constraints, and fabricated paths
74
+ - **More agent-friendly** - output is structured around goal, progress, decisions, files, next steps, and critical context
75
+ - **Better continuity** - follow-up work survives compaction more reliably
76
+
77
+ ---
78
+
79
+ ## Design philosophy
80
+
81
+ Smart Compact is built around a few core principles:
82
+
83
+ ### 1. Accuracy over style
84
+ A beautiful summary that invents a file path is worse than a plain summary that is correct.
85
+
86
+ ### 2. Determinism before generation
87
+ Anything we can extract mechanically from the conversation should not be guessed by an LLM.
88
+
89
+ ### 3. Preserve working state, not transcript fidelity
90
+ The goal is not to recreate the whole conversation. The goal is to preserve the information needed to continue the work correctly.
91
+
92
+ ### 4. Spend tokens where they matter
93
+ Easy sessions should stay cheap. Complex sessions should get deeper exploration and better synthesis.
94
+
95
+ ### 5. Optimize for real coding sessions
96
+ This extension is designed for implementation, debugging, review, and discussion workflows inside Pi - not for generic meeting notes.
97
+
98
+ ---
99
+
100
+ ## Inspiration
101
+
102
+ This project is informed by the broader **context engineering** and **agentic context management** space.
103
+
104
+ In particular, the design is influenced by:
105
+
106
+ - long-context summarization patterns used in agent systems
107
+ - deterministic-plus-LLM hybrid pipelines
108
+ - structured memory preservation for coding workflows
109
+ - ideas popularized in the ecosystem by people such as **Greg Kamradt** around context quality, retrieval discipline, and practical LLM memory design
110
+
111
+ Smart Compact is **not** a copy of any single project. It is a Pi-native implementation focused specifically on coding-agent conversations, with strong emphasis on verified facts, exact code references, and safe continuation after compaction.
112
+
113
+ ---
114
+
115
+ ## How it works
116
+
117
+ Smart Compact uses an **EESV** pipeline:
118
+
119
+ ```text
31
120
  Extract → Explore → Synthesize → Verify
32
- (0 LLM) (0–8 LLM) (N+1 LLM) (0–1 LLM)
33
121
  ```
34
122
 
35
- | Phase | What it does | LLM cost |
36
- |-------|-------------|----------|
37
- | **Extract** | Deterministically mine files, errors, decisions, constraints, topics | **0 calls** |
38
- | **Explore** | LLM investigates conversation with tools to verify boundaries and enrich context. **Skipped for simple sessions.** | 08 calls |
39
- | **Synthesize** | Parallel batch summarization with decision propagation, then single-pass assembly | N+1 calls |
40
- | **Verify** | Coverage checks, hallucination detection, deterministic patching (zero LLM), LLM patch only as last resort | 01 calls |
123
+ | Phase | Purpose | Typical LLM cost |
124
+ | --- | --- | --- |
125
+ | **Extract** | Deterministically mine files, errors, decisions, constraints, and topic boundaries | **0 calls** |
126
+ | **Explore** | Investigate ambiguous areas with tools and improve topic understanding | 0-8 calls |
127
+ | **Synthesize** | Build batch summaries and merge them into one structured compaction summary | N+1 calls |
128
+ | **Verify** | Check coverage, detect hallucinations, patch missing facts deterministically first | 0-1 calls |
41
129
 
42
- ### Pre-Processing (before EESV)
130
+ ### Before EESV
43
131
 
44
- ```
45
- Pruning: Remove duplicate reads, collapse error chains, strip acknowledgments, truncate long outputs
46
- ↳ Reduces compaction input by 15–30%
47
- Fingerprint: Load project context (language, framework, known files) from previous sessions
48
- ```
132
+ Smart Compact first performs lightweight preprocessing:
49
133
 
50
- ### Post-Processing (after EESV)
134
+ - **redundancy pruning**
135
+ - **project fingerprint loading**
136
+ - **incremental extraction cache lookup**
51
137
 
52
- ```
53
- Damage Detection: Monitor agent behavior for regression signals (re-reads, user complaints, re-questions)
54
- Builds a quality feedback dataset over time
55
- ```
138
+ ### After EESV
139
+
140
+ It can also record quality signals for future analysis:
141
+
142
+ - re-reads after compaction
143
+ - user complaints
144
+ - weak continuity indicators
145
+
146
+ ---
147
+
148
+ ## Key capabilities
149
+
150
+ ### Deterministic extraction
151
+ Before asking any model to summarize anything, Smart Compact extracts:
152
+
153
+ - modified, read, and deleted files
154
+ - error chains and retry attempts
155
+ - explicit and implicit decisions
156
+ - user constraints and preferences
157
+ - heuristic topic segments
158
+ - main goal and recent user signals
159
+
160
+ ### Adaptive exploration
161
+ Not every session needs expensive model-driven exploration.
162
+
163
+ Simple sessions can skip Phase 2 entirely when they have:
164
+
165
+ - few topics
166
+ - few unresolved errors
167
+ - few decisions
168
+ - limited cross-directory work
169
+
170
+ ### Open Loops detection
171
+ Every compaction identifies unresolved work and tracks it as **open loops**:
172
+
173
+ - **bugfix** — unresolved errors from tool calls
174
+ - **follow-up** — user mentions of pending next steps
175
+ - **blocked** — dependencies waiting on external input
176
+ - **retry** — retried but still-unresolved failures
177
+
178
+ Each loop gets a stable ID, priority, and file references. They appear in both the Markdown summary and the structured JSON state.
179
+
180
+ ### Cross-compaction tracking
181
+ Smart Compact persists structured state between compactions. On the next compaction, it loads the previous state and computes a **delta**:
182
+
183
+ - which open loops were resolved
184
+ - which are still persistent
185
+ - which decisions carried over
186
+ - which errors were fixed vs newly introduced
187
+ - which files are newly modified
188
+ - whether the goal shifted
189
+
190
+ This means every compaction builds on the last one — not from scratch.
191
+
192
+ ### Structured JSON state output
193
+ Alongside the human-readable Markdown summary, Smart Compact produces a machine-readable `CompactionState` JSON object:
194
+
195
+ - goal, decisions, constraints
196
+ - modified/read/deleted files
197
+ - unresolved and resolved errors
198
+ - open loops with stable IDs
199
+ - next actions and critical context
200
+ - session type and version
201
+
202
+ This structured state enables better verification, follow-up tracking, and future retrieval integration.
203
+
204
+ ### Decision propagation
205
+ Batch summaries receive decisions from earlier segments, reducing a common failure mode where later summaries "forget" what was decided earlier.
206
+
207
+ ### Verification-oriented synthesis
208
+ The final summary is checked against extracted facts. If important information is missing, Smart Compact tries to patch it deterministically before spending another LLM call.
209
+
210
+ ### Redundancy pruning
211
+ Input is reduced by removing or compressing low-value patterns such as:
212
+
213
+ - duplicate file reads
214
+ - repetitive failure chains
215
+ - empty acknowledgments
216
+ - oversized tool outputs
217
+
218
+ ### Cross-session project context
219
+ The extension keeps a small project fingerprint so later compactions can reuse context such as:
220
+
221
+ - dominant language
222
+ - likely framework
223
+ - important directories
224
+ - recently relevant files
225
+
226
+ ### Auto-triggered compaction
227
+ When enabled, Smart Compact hooks into Pi's `session_before_compact` event and can replace default blind compaction with a smarter summary.
56
228
 
57
229
  ---
58
230
 
59
231
  ## Installation
60
232
 
233
+ ### Recommended: install as a Pi package
234
+
61
235
  ```bash
62
- # Option 1: Install via bun (recommended)
63
- bun add pi-smart-compact
236
+ pi install npm:pi-smart-compact
237
+ ```
64
238
 
65
- # Option 2: Install via npm
66
- npm install pi-smart-compact
239
+ ### Or install from GitHub
67
240
 
68
- # Option 3: Clone directly
69
- cd ~/.pi/agent/extensions
70
- git clone https://github.com/alpertarhan/pi-smart-compact.git
71
- cd pi-smart-compact && bun install
241
+ ```bash
242
+ pi install git:github.com/alpertarhan/pi-smart-compact
72
243
  ```
73
244
 
74
- Then add to your Pi `settings.json`:
245
+ ### Or work on it locally
75
246
 
76
- ```json
77
- {
78
- "extensions": ["pi-smart-compact"]
79
- }
247
+ ```bash
248
+ cd ~/.pi/agent/extensions
249
+ git clone https://github.com/alpertarhan/pi-smart-compact.git
250
+ cd pi-smart-compact
251
+ bun install
252
+ bun run build
80
253
  ```
81
254
 
255
+ The published package loads the compiled extension entry at **`dist/index.js`**. Source code lives in `src/`, but the package manifest points Pi at `./dist/index.js` for distribution.
256
+
82
257
  ---
83
258
 
84
- ## Usage
259
+ ## Quick start
85
260
 
86
- ### Command
261
+ ### Slash command
87
262
 
88
263
  ```bash
89
- # Interactive TUI — pick model + profile
90
264
  /smart-compact
265
+ ```
266
+
267
+ This opens the interactive picker and lets you choose:
268
+
269
+ - model
270
+ - compression profile
271
+
272
+ ### Direct usage
91
273
 
92
- # Direct — specific model + profile
274
+ ```bash
93
275
  /smart-compact anthropic/claude-sonnet-4 balanced
276
+ ```
277
+
278
+ ### Dry run
94
279
 
95
- # Dry run — preview what would be compacted
280
+ ```bash
96
281
  /smart-compact dry-run
282
+ ```
283
+
284
+ ### Verbose mode
97
285
 
98
- # Verbose — detailed pipeline logging
286
+ ```bash
99
287
  /smart-compact debug
288
+ ```
289
+
290
+ ### Add steering / follow-up emphasis
100
291
 
101
- # Steering note — guide the summary focus
102
- /smart-compact "focus on auth changes"
292
+ ```bash
293
+ /smart-compact "focus on auth changes and remaining follow-up work"
103
294
  ```
104
295
 
105
- ### Tool (agent-callable)
296
+ ### Tool usage
106
297
 
107
- The extension registers a tool the agent can call automatically:
298
+ Smart Compact also registers an agent-callable tool:
108
299
 
109
300
  ```json
110
301
  {
@@ -117,25 +308,11 @@ The extension registers a tool the agent can call automatically:
117
308
  }
118
309
  ```
119
310
 
120
- ### Auto-Trigger
121
-
122
- When `autoTrigger` is enabled (default), Smart Compact runs automatically before Pi's built-in compaction kicks in. The `session_before_compact` hook intercepts the event and produces the smart summary instead of blind truncation.
123
-
124
- ---
125
-
126
- ## Profiles
127
-
128
- | Profile | Summary Budget | Keep Recent | Best For |
129
- |---------|---------------|-------------|----------|
130
- | **light** | 10K tokens | 30K tokens | Debugging sessions, complex multi-file refactors where detail matters |
131
- | **balanced** | 6K tokens | 20K tokens | General development (default) |
132
- | **aggressive** | 3K tokens | 10K tokens | Quick exploration, prototyping, or very large contexts |
133
-
134
311
  ---
135
312
 
136
313
  ## Configuration
137
314
 
138
- Add to `~/.pi/agent/settings.json`:
315
+ Add this to `~/.pi/agent/settings.json`:
139
316
 
140
317
  ```json
141
318
  {
@@ -146,181 +323,314 @@ Add to `~/.pi/agent/settings.json`:
146
323
  "autoTrigger": true,
147
324
  "backupEnabled": true,
148
325
  "profiles": {
149
- "balanced": { "summaryBudgetTokens": 6000, "keepRecentTokens": 20000 }
326
+ "balanced": {
327
+ "summaryBudgetTokens": 6000,
328
+ "keepRecentTokens": 20000
329
+ }
150
330
  }
151
331
  }
152
332
  }
153
333
  ```
154
334
 
155
- | Option | Type | Default | Description |
156
- |--------|------|---------|-------------|
157
- | `profile` | `"light"` \| `"balanced"` \| `"aggressive"` | `"balanced"` | Default compression profile |
158
- | `summaryModel` | `string` \| `null` | `null` | Override model for summarization (e.g. `"anthropic/claude-sonnet-4"`) |
159
- | `segmentationModel` | `string` \| `null` | `null` | Override model for exploration (e.g. `"anthropic/claude-haiku-3"`) |
160
- | `autoTrigger` | `boolean` | `true` | Automatically run on Pi's `session_before_compact` hook |
161
- | `backupEnabled` | `boolean` | `true` | Save conversation backup before compaction |
162
- | `profiles` | `object` | | Override per-profile token budgets |
335
+ ### Supported options
336
+
337
+ | Option | Type | Default | Meaning |
338
+ | --- | --- | --- | --- |
339
+ | `profile` | `"light" \| "balanced" \| "aggressive"` | `"balanced"` | Default compaction profile |
340
+ | `summaryModel` | `string \| null` | `null` | Override summarization model |
341
+ | `segmentationModel` | `string \| null` | `null` | Override exploration model |
342
+ | `autoTrigger` | `boolean` | `true` | Run automatically before Pi's built-in compaction |
343
+ | `backupEnabled` | `boolean` | `true` | Save a backup before compaction |
344
+ | `profiles` | `object` | built-in defaults | Override per-profile budgets |
345
+
346
+ ### Profiles
347
+
348
+ | Profile | Summary budget | Keep recent | Best for |
349
+ | --- | --- | --- | --- |
350
+ | **light** | 10K | 30K | sessions where more detail should survive |
351
+ | **balanced** | 6K | 20K | general daily development |
352
+ | **aggressive** | 3K | 10K | large contexts and faster reduction |
353
+
354
+ ### Backward compatibility
355
+
356
+ For migration safety, the extension still accepts the older config key:
357
+
358
+ - `semanticCompact`
359
+
360
+ but the current key is:
361
+
362
+ - `smartCompact`
163
363
 
164
364
  ---
165
365
 
166
- ## Architecture Deep Dive
366
+ ## Output format
367
+
368
+ Smart Compact produces structured Markdown designed to be both human-readable and useful to the agent:
369
+
370
+ ```markdown
371
+ ## Goal
372
+ ## Constraints & Preferences
373
+ ## Progress
374
+ ### Done
375
+ ### In Progress
376
+ ### Blocked
377
+ ## Key Decisions
378
+ ## Files Modified
379
+ ## Files Read
380
+ ## Open Loops
381
+ ## Changes Since Last Compaction
382
+ ## Next Steps
383
+ ## Critical Context
384
+ ## Topics Covered
385
+ ```
386
+
387
+ New sections:
388
+
389
+ - **Open Loops** — unresolved tasks with priority and file references
390
+ - **Changes Since Last Compaction** — delta from previous compaction state
167
391
 
168
- ### Deterministic Extraction (Phase 1)
392
+ The format is intentionally opinionated. It is optimized to preserve:
169
393
 
170
- Zero LLM calls. Extracts purely from message structure:
394
+ - actionable state
395
+ - exact references
396
+ - unresolved issues
397
+ - open loops and follow-up integrity
398
+ - state transitions across compactions
399
+ - clear continuation paths
171
400
 
172
- - **File operations** — tracks read/write/edit/delete with no-op detection (`"applied: 0"`, `"no changes"`)
173
- - **Error lifecycle** — not just "isError" but retry detection (same tool re-called within 6 messages) and resolution tracking
174
- - **Decisions** — explicit (`ask_user` tool calls) and implicit (user choice patterns like "use X instead of Y")
175
- - **Constraints** — regex-based mining with English + Turkish patterns, categorized as requirement/prohibition/preference
176
- - **Topic segmentation** — heuristic boundaries based on file transitions, error density, user "shift" patterns, and token limits
401
+ ### Structured JSON output
177
402
 
178
- ### Adaptive Exploration Gate
403
+ In addition to Markdown, Smart Compact produces a structured `CompactionState` object accessible in compaction details:
179
404
 
180
- Exploration is **skipped** for simple sessions that meet all criteria:
181
- - ≤ 3 topics
182
- - 1 unresolved error
183
- - 2 decisions
184
- - 2 directory groups
405
+ ```json
406
+ {
407
+ "goal": "Build auth module",
408
+ "decisions": [{ "id": "decision-1", "summary": "Use JWT", "type": "explicit" }],
409
+ "constraints": [{ "id": "constraint-1", "text": "Must use TypeScript", "category": "requirement" }],
410
+ "modifiedFiles": ["src/auth.ts"],
411
+ "unresolvedErrors": [],
412
+ "openLoops": [{ "id": "loop-1", "type": "follow-up", "priority": "normal", "summary": "add tests" }],
413
+ "resolvedErrors": [{ "id": "error-1", "message": "login returns undefined", "tool": "bash" }],
414
+ "nextActions": ["Add unit tests for auth"],
415
+ "sessionType": "implementation",
416
+ "compactionVersion": "7.7.0"
417
+ }
418
+ ```
185
419
 
186
- This saves 3–8 LLM calls on straightforward sessions.
420
+ ---
187
421
 
188
- ### Decision Propagation
422
+ ## Architecture details
189
423
 
190
- Each batch receives "Active Decisions from previous segments" — decisions made before the batch's message range. This prevents the common failure mode where Batch 2 doesn't know that Batch 1 decided to use React.
424
+ ## 1) Extract
191
425
 
192
- ### Immutable Context Framing
426
+ The extraction phase performs zero-LLM analysis on message structure.
193
427
 
194
- The assembly prompt presents deterministic data as **IMMUTABLE CONTEXT** with explicit rules:
428
+ It identifies:
195
429
 
196
- > *"These are deterministically verified from the original conversation. They take priority over ANY summary content below."*
430
+ - file operations from tool calls and tool results
431
+ - no-op edits (`applied: 0`, `no changes`)
432
+ - tool errors and bash-like failures
433
+ - retries and likely resolutions
434
+ - explicit `ask_user` decisions
435
+ - implicit user choices such as "use X instead of Y"
436
+ - English and Turkish constraint language
437
+ - topic boundaries from file transitions, error density, and user shift cues
197
438
 
198
- This reduces fabrication by making the LLM treat verified data as ground truth.
439
+ ## 2) Explore
199
440
 
200
- ### Verification & Patching
441
+ Exploration is only used when the session is complex enough to justify it.
201
442
 
202
- 1. **Verification** — checks file coverage, error coverage, constraint coverage, hallucinated file paths, error-done inconsistencies, decision coverage
203
- 2. **Deterministic patch** (score < 85) — injects missing items directly into the relevant markdown sections, zero LLM cost
204
- 3. **LLM patch** (score < 75 after deterministic) — last resort, only if deterministic patch was insufficient
205
- 4. **Skip** (score ≥ 85) — no patching needed
443
+ When active, the model can use tools such as:
206
444
 
207
- ### Redundancy Pruning
445
+ - `get_message_range`
446
+ - `search_conversation`
447
+ - `get_recent_user_messages`
448
+ - `get_context_around`
449
+ - `get_file_changes`
450
+ - `get_error_chain`
208
451
 
209
- Before compaction, deterministic pruning removes:
210
- - **Duplicate file reads** — keeps only the last read per file
211
- - **Collapsed error chains** — 3+ consecutive same-tool failures → keep first + last only
212
- - **Agent acknowledgments** — "I'll fix that", "Let me check", "Sure" (zero-information messages)
213
- - **Long tool outputs** — truncates to 800 chars (head 400 + tail 400)
452
+ This phase helps refine:
214
453
 
215
- ### Project Fingerprint
454
+ - topic boundaries
455
+ - cross-topic relationships
456
+ - missing constraints
457
+ - completion state
458
+ - narrative continuity
216
459
 
217
- Cross-session learning stored at `~/.pi/agent/.cache/smart-compact/projects/`:
460
+ ## 3) Synthesize
218
461
 
219
- | Field | How it's detected |
220
- |-------|-------------------|
221
- | Language | Most common file extension (.ts → typescript, .rs → rust, etc.) |
222
- | Framework | Config file patterns (next.config → nextjs, vite.config → vite, etc.) |
223
- | Key directories | Most frequently modified directory paths |
224
- | Known files | Last 50 unique files across sessions |
225
- | Session count | Incremented each compaction |
462
+ Synthesis supports two modes:
226
463
 
227
- 30-day TTL. Loaded before Phase 1 and injected into the synthesis prompt as project context.
464
+ ### Single-pass
465
+ Used when the compacted portion is small enough.
228
466
 
229
- ### Damage Detection
467
+ ### Hierarchical
468
+ Used for larger sessions:
230
469
 
231
- After compaction, monitors the next 15 messages for regression signals:
470
+ - chunk messages into segments
471
+ - summarize segments in batches
472
+ - propagate prior decisions forward
473
+ - merge summaries into one final structured summary
232
474
 
233
- | Signal | Severity | Detection |
234
- |--------|----------|-----------|
235
- | Agent re-reads compacted file | Medium | Tool call `read` with path from compacted section |
236
- | User complaint | High | Regex: "I already told you", "you forgot", "nerede kaldı" |
237
- | Re-question | Low | User mentions compacted decision topic |
475
+ ## 4) Verify
238
476
 
239
- Logged to `~/.pi/agent/.cache/smart-compact/damage-reports.jsonl` for future analysis.
477
+ Verification checks the final summary against deterministic extraction data.
240
478
 
241
- ### Token Estimation
479
+ It looks for issues such as:
242
480
 
243
- - **Provider-specific ratios** (OpenAI: 4.0, Anthropic: 3.5, MiniMax: 3.8)
244
- - **JSON penalty** (0.85x) — JSON.stringify'd content has denser tokenization
245
- - **Language penalty** (0.9x) — Turkish/CE characters tokenize differently
246
- - **Per-provider EMA calibration** — learns from actual API responses, scoped per provider
481
+ - missing modified files
482
+ - missing unresolved errors
483
+ - missing strong constraints
484
+ - missing explicit decisions
485
+ - missing Open Loops section when unresolved errors exist
486
+ - suspicious file references not seen in the conversation
487
+ - structural omissions
247
488
 
248
- ### Provider Concurrency
489
+ If needed, Smart Compact applies:
249
490
 
250
- | Provider | Concurrency Limit | Cache Strategy |
251
- |----------|-------------------|----------------|
252
- | OpenAI | 5 | prompt caching |
253
- | Anthropic (zai) | 3 | anthropic caching |
254
- | MiniMax | 2 | anthropic caching |
255
- | Xiaomi | 2 | openai caching |
256
- | Default | 2 | none |
491
+ 1. **deterministic patching first**
492
+ 2. **LLM patching only if necessary**
257
493
 
258
494
  ---
259
495
 
260
- ## Summary Format
496
+ ## Quality and safety controls
261
497
 
262
- Smart Compact produces structured markdown:
498
+ ### Exact-name discipline
499
+ Prompts explicitly tell the model to preserve exact file paths, identifiers, and verified facts.
263
500
 
264
- ```markdown
265
- ## Goal
266
- [What the user is trying to accomplish]
501
+ ### Immutable context framing
502
+ Deterministically extracted facts are presented as ground truth during assembly.
267
503
 
268
- ## Constraints & Preferences
269
- - [requirement] Must use TypeScript strict mode
270
- - [preference] Prefer functional components
504
+ ### Verification-first fallback strategy
505
+ The extension prefers:
271
506
 
272
- ## Progress
273
- ### Done
274
- - [x] Auth module implemented (src/auth.ts)
275
- ### In Progress
276
- - [ ] Database migration
277
- ### Blocked
278
- - Waiting for API credentials
507
+ - no patch
508
+ - deterministic patch
509
+ - LLM patch as last resort
279
510
 
280
- ## Key Decisions
281
- - **Use JWT for auth**: User confirmed over session cookies
511
+ ### Backups
512
+ Conversation backups can be written before compaction.
282
513
 
283
- ## Files Modified
284
- - src/auth.ts
285
- - src/db/migrations/001.sql
514
+ ### Metrics
515
+ The pipeline tracks:
286
516
 
287
- ## Files Read
288
- - src/config.ts
289
- - package.json
517
+ - call counts
518
+ - input/output token volume
519
+ - cache hit rate
520
+ - average latency
290
521
 
291
- ## Next Steps
292
- 1. Complete database migration
293
- 2. Add integration tests
522
+ ### Incremental extraction cache
523
+ Structured extraction results are cached per session to avoid reprocessing unchanged history.
294
524
 
295
- ## Critical Context
296
- - Unresolved error: test failed in auth.ts line 42
297
- - API base URL: https://api.example.com/v2
525
+ ### Cross-compaction state persistence
526
+ After each compaction, the structured state is persisted to disk. On the next compaction, Smart Compact:
298
527
 
299
- ## Topics Covered
300
- - **Auth implementation** [high]
301
- - **DB schema design** [normal]
302
- - **Config review** [low]
303
- ```
528
+ 1. loads the previous state
529
+ 2. computes a delta (resolved loops, new errors, goal shifts, etc.)
530
+ 3. injects `## Changes Since Last Compaction` into the summary
531
+ 4. saves the updated state for the next cycle
532
+
533
+ This creates a **compaction memory chain** — every compaction builds on the last.
534
+
535
+ ---
536
+
537
+ ## Compatibility
538
+
539
+ Smart Compact is designed as a standalone Pi extension, but it is also intended to fit naturally into richer Pi setups.
540
+
541
+ It should be a good conceptual fit alongside workflow-oriented extensions and packages such as:
542
+
543
+ - `pi-agent-flow`
544
+ - `pi-simplify`
545
+ - `pi-lens`
546
+
547
+ As always with Pi packages, review interactions in your own environment if you combine multiple extensions that hook into related session flows.
304
548
 
305
549
  ---
306
550
 
307
551
  ## Development
308
552
 
553
+ ### Project structure
554
+
555
+ ```text
556
+ src/ TypeScript source
557
+ dist/ compiled package entry for distribution
558
+ test/ Bun tests
559
+ README.md package documentation
560
+ ```
561
+
562
+ ### Test suite
563
+
564
+ Smart Compact has **91 tests** across 9 files, including:
565
+
566
+ - **Unit tests** — extraction, tokens, verification, pruning, fingerprint, exploration
567
+ - **State tests** — open loops, compaction state, delta computation, state persistence
568
+ - **Evaluation harness** — 5 gold conversation scenarios with expected extraction results, delta evaluation across compactions, and fabrication safety checks
569
+
570
+ ```bash
571
+ bun test # run all 91 tests
572
+ bun test test/eval.test.ts # evaluation harness only
573
+ ```
574
+
575
+ ### Local commands
576
+
309
577
  ```bash
310
578
  bun install
311
- bun test # 56 tests across 7 files
312
- bun run typecheck # TypeScript check
579
+ bun run build
580
+ bun run typecheck
313
581
  ```
314
582
 
583
+ ### Build output
584
+
585
+ Published builds use:
586
+
587
+ - `dist/index.js`
588
+
589
+ This keeps the distributed package aligned with common npm packaging expectations while preserving a TypeScript-first source layout during development.
590
+
591
+ ### Local package path
592
+
593
+ If you are developing inside Pi directly, this project commonly lives at:
594
+
595
+ ```text
596
+ ~/.pi/agent/extensions/pi-smart-compact
597
+ ```
598
+
599
+ ---
600
+
601
+ ## Limitations
602
+
603
+ Smart Compact is strong, but it is not magic.
604
+
605
+ A few honest limitations:
606
+
607
+ - it still depends on model quality during exploration and synthesis
608
+ - very noisy sessions can still produce weaker summaries than ideal
609
+ - verification is strong for extracted facts, but not a formal proof system
610
+ - project fingerprints are intentionally lightweight, not a full memory database
611
+ - token estimates are calibrated heuristics, not exact provider tokenizers
612
+
315
613
  ---
316
614
 
317
615
  ## Contributing
318
616
 
319
- 1. Fork the repo
320
- 2. Create your branch (`git checkout -b feat/amazing-feature`)
321
- 3. Commit (`git commit -am 'Add amazing feature'`)
322
- 4. Push (`git push origin feat/amazing-feature`)
323
- 5. Open a Pull Request
617
+ Issues, suggestions, and pull requests are welcome.
618
+
619
+ If you contribute, the best changes tend to be:
620
+
621
+ - measurable
622
+ - easy to validate with tests
623
+ - explicit about quality/cost trade-offs
624
+ - careful about hallucination risk and continuation quality
625
+
626
+ Typical flow:
627
+
628
+ ```bash
629
+ git checkout -b feat/my-change
630
+ bun test
631
+ bun run build
632
+ git commit -m "feat: ..."
633
+ ```
324
634
 
325
635
  ---
326
636