diff --git a/AGENTS.md b/AGENTS.md index b3e0aa6..e0468df 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -59,6 +59,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | Date | Log | |------|-----| +| 2026-11-16 | [20261116-status-overlay-compaction-count_log.md](docs/devlog/20261116-status-overlay-compaction-count_log.md) | | 2026-11-16 | [20261116-smart-compact-status-overlay-panel-fanout-audit_log.md](docs/devlog/20261116-smart-compact-status-overlay-panel-fanout-audit_log.md) | | 2026-11-15 | [20261115-reviewer-fanout-audit-hardening_log.md](docs/devlog/20261115-reviewer-fanout-audit-hardening_log.md) | diff --git a/CHANGELOG.md b/CHANGELOG.md index dd6ed4b..8629ada 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,3 +3,7 @@ All notable changes to this project will be documented in this file. The format is based on [Common Changelog](https://common-changelog.org) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] + +### Added + +- **status:** `/smart-compact` panel shows how many times the session has been compacted, counted from persisted compaction entries (correct across restarts and resumes) with an in-memory fallback where `sessionManager` is unavailable. diff --git a/README.md b/README.md index 4c50924..55e2859 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ Optional. `~/.pi/agent/settings.json` (global) or `.pi/settings.json` (project; ## Command -`/smart-compact` opens a centered overlay panel (the `/dcp context` look): current tokens, a usage bar, both effective thresholds (with crossed indicators), and cycle flags. Dismiss it with esc, enter, q, or ctrl+c. Where overlays are unavailable (print/RPC mode) it falls back to a plain notification. Useful for checking what a given model's thresholds resolve to without filling a session. +`/smart-compact` opens a centered overlay panel (the `/dcp context` look): current tokens, a usage bar, both effective thresholds (with crossed indicators), cycle flags, and the session's compaction count. The count comes from the session's persisted compaction entries, so it stays correct across restarts and resumes. Dismiss it with esc, enter, q, or ctrl+c. Where overlays are unavailable (print/RPC mode) it falls back to a plain notification. Useful for checking what a given model's thresholds resolve to without filling a session. ## Install @@ -88,7 +88,7 @@ Pi discovers `*/index.ts` one level deep, following the symlink. Reload with `/r ## Verification - Loads clean under Pi 1.5.2 (`pi -p` smoke test). -- 14-test committed harness: `node --test harness.ts` (Node ≥ 22.18 with type stripping). Covers warn-once-per-cycle at the effective threshold, force only at `agent_settled` (never from `turn_end`, not when busy), awaiting compaction completion in the settled handler, the in-flight lock and failure cooldown, the stale-token guard after `session_compact`, per-field config validation (`null`/string/zero/oversized values), cycle reset, `enabled: false`, and the status command. +- 23-test committed harness: `node --test harness.ts` (Node ≥ 22.18 with type stripping). Covers warn-once-per-cycle at the effective threshold, force only at `agent_settled` (never from `turn_end`, not when busy), awaiting compaction completion in the settled handler, the in-flight lock and failure cooldown, the stale-token guard after `session_compact`, per-field config validation (`null`/string/zero/oversized values), cycle reset, `enabled: false`, and the status command. - Live-session validation of the first real 100k crossing is still pending — the warn message is a single string in `index.ts` if the wording needs tuning. ## License diff --git a/docs/devlog/20261116-status-overlay-compaction-count_log.md b/docs/devlog/20261116-status-overlay-compaction-count_log.md new file mode 100644 index 0000000..78a25a6 --- /dev/null +++ b/docs/devlog/20261116-status-overlay-compaction-count_log.md @@ -0,0 +1,52 @@ +# Status overlay: session compaction count + +> **Date:** 2026-11-16 +> **Type:** generic +> **Reference:** None + +## Goal + +Extend the `/smart-compact` status overlay with a row showing how many times the session has already been compacted. + +## What Was Done + +- `index.ts`: new `sessionCompactions` counter, incremented in the existing `session_compact` handler (alongside `resetCycle()`). +- `index.ts`: `countCompactions()` in the status command handler — primary source counts persisted `type === "compaction"` entries via `ctx.sessionManager.getEntries()`; falls back to the in-memory counter when `sessionManager` is unavailable or unreadable. +- `index.ts`: new `compactions` panel row (padded to the shared label column), rendered last; command doc-comment updated. +- `harness.ts`: `makeCtx` now mocks `sessionManager.getEntries()` (new `entries` override, default `[]`); the status-panel test asserts `compactions 0` on a fresh session; new test verifies entry-tree counting (3 compaction entries of 5) and the in-memory fallback after `sessionManager` is removed. +- `README.md`: command paragraph mentions the compaction count and its persisted-entry source; stale "14-test harness" corrected to 23. +- `CHANGELOG.md`: Added entry under Unreleased. + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Count persisted compaction entries (`ctx.sessionManager.getEntries()`), not just an in-memory `session_compact` counter | An in-memory counter resets to 0 on `--resume`/restart and would report "0 compactions" for a session compacted N times in a prior process — actively misleading for a status panel. Persisted entries are authoritative across resume/restart/fork. | +| Keep the in-memory counter as a fallback | Hosts without `sessionManager` still get a number (compactions seen this process) instead of nothing; costs two lines inside the already-registered `session_compact` handler. | +| Count all entries (all branches), not `getBranch()` | "How many times has the session been compacted" is session-lifetime semantics: every compaction that ever happened in this session file, independent of `/tree` navigation. | +| `session_compact_failed` does not increment | A failed compaction persists no entry; only successful compactions count. | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| README claimed a "14-test committed harness" while the suite had grown to 22 | The overlay-panel session updated the harness without refreshing the README count | Corrected to 23 as part of this change | + +## Files Changed + +| File | Change Summary | +|------|----------------| +| `index.ts` | `sessionCompactions` counter, `countCompactions()` helper, `compactions` panel row | +| `harness.ts` | `sessionManager.getEntries()` mock; new counting/fallback test; fresh-session assertion | +| `README.md` | Command section + harness test count | +| `CHANGELOG.md` | Unreleased → Added entry | +| `docs/devlog/INDEX.md` | New log row (newest first) | +| `AGENTS.md` | Session-log window refreshed | + +## Open Items & Next Steps + +- [ ] Live-session validation still pending (as before): confirm the row shows the true count after a real compaction and after `--resume`. + +--- + +*Log written by write-log skill* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index c57e465..6b0424f 100644 --- a/docs/devlog/INDEX.md +++ b/docs/devlog/INDEX.md @@ -5,5 +5,6 @@ Complete history of session logs in this directory, newest first. One-line summa | Date | Type | File | Summary | |------|------|------|---------| +| 2026-11-16 | generic | [20261116-status-overlay-compaction-count_log.md](20261116-status-overlay-compaction-count_log.md) | Status overlay adds a compactions row counted from the session's persisted compaction entries | | 2026-11-16 | generic | [20261116-smart-compact-status-overlay-panel-fanout-audit_log.md](20261116-smart-compact-status-overlay-panel-fanout-audit_log.md) | Status overlay panel with usage bar; reviewer fanout fixed kitty close keys, width contract, label padding | | 2026-11-15 | generic | [20261115-reviewer-fanout-audit-hardening_log.md](20261115-reviewer-fanout-audit-hardening_log.md) | Reviewer fanout converged in 4 rounds: force tier moved to agent_settled, config validated, 15-test harness added | diff --git a/harness.ts b/harness.ts index 76bdd57..5d4004c 100644 --- a/harness.ts +++ b/harness.ts @@ -20,6 +20,7 @@ interface CtxOverrides { window: number; onCompact?: (opts: any) => void; idle?: boolean; + entries?: any[]; } function load(settings: Record) { @@ -50,7 +51,7 @@ function load(settings: Record) { return pi; } -function makeCtx({ tokens, window, onCompact, idle = true }: CtxOverrides) { +function makeCtx({ tokens, window, onCompact, idle = true, entries = [] }: CtxOverrides) { const calls: { compact: number; notified: string[]; @@ -63,6 +64,7 @@ function makeCtx({ tokens, window, onCompact, idle = true }: CtxOverrides) { ctx: { isIdle: () => idle, getContextUsage: () => ({ tokens, contextWindow: window }), + sessionManager: { getEntries: () => entries }, ui: { notify: (msg: string) => calls.notified.push(msg), // Minimal ctx.ui.custom: captures overlay options, instantiates the @@ -232,6 +234,7 @@ test("status command opens a centered overlay panel with thresholds", async () = assert.match(text, /56% of window/); assert.match(text, /warn threshold\s+55k \(crossed\)/); assert.match(text, /force threshold\s+80k(?!\s*\(crossed\))/); + assert.match(text, /compactions\s+0/); assert.match(text, /esc\/enter\/q to close/); comp.handleInput("\x1b"); await pending; // resolves once done() fires @@ -382,6 +385,27 @@ test("status falls back to notify when overlay UI is unavailable", async () => { assert.doesNotMatch(text, /to close/); // hint is overlay-mode only }); + test("status counts compactions from the session tree; in-memory fallback without sessionManager", async () => { + const pi = load(FULL); + const entries = [{ type: "message" }, { type: "compaction" }, { type: "message" }, { type: "compaction" }, { type: "compaction" }]; + const { ctx, calls } = makeCtx({ tokens: 56_000, window: 100_000, entries }); + const pending = pi.commands["smart-compact"].handler(undefined, ctx); + await new Promise((r) => setImmediate(r)); + assert.match(calls.components[0].render(80).join("\n"), /compactions\s+3/); + calls.components[0].handleInput("\x1b"); + await pending; + + // No sessionManager: fall back to compactions this process has seen. + const { ctx: bareCtx, calls: bareCalls } = makeCtx({ tokens: 56_000, window: 100_000 }); + delete (bareCtx as any).sessionManager; + await fire(pi, "session_compact", bareCtx); + const pending2 = pi.commands["smart-compact"].handler(undefined, bareCtx); + await new Promise((r) => setImmediate(r)); + assert.match(bareCalls.components[0].render(80).join("\n"), /compactions\s+1/); + bareCalls.components[0].handleInput("\x1b"); + await pending2; + }); + test("usage bar hidden when window is unknown", async () => { const pi = load(FULL); const { ctx, calls } = makeCtx({ tokens: 56_000, window: 0 }); diff --git a/index.ts b/index.ts index 10bc8fd..904f053 100644 --- a/index.ts +++ b/index.ts @@ -216,6 +216,10 @@ export default function smartCompact(pi: any) { let forceInFlight = false; let lastForceFailureAt = 0; let lastKnownTokens: number | null = null; + // Compactions observed by this process (session_compact). Panel fallback + // only; the panel prefers counting persisted compaction entries, which + // stays correct across resume/restart. + let sessionCompactions = 0; /** min(absolute, fraction × window); absolute-only when window unknown. */ const effective = (absolute: number, fraction: number, window?: number | null): number => @@ -319,7 +323,10 @@ export default function smartCompact(pi: any) { forceInFlight = false; lastKnownTokens = null; }; - pi.on("session_compact", async () => resetCycle()); + pi.on("session_compact", async () => { + sessionCompactions++; + resetCycle(); + }); pi.on("session_compact_failed", async () => { forceInFlight = false; // Keep warnedThisCycle set — context is still large; don't re-nag. @@ -327,7 +334,8 @@ export default function smartCompact(pi: any) { // ── Debug/status command ───────────────────────────────────────── // Shows a centered bordered overlay (the /dcp context look): current - // tokens, a usage bar, both effective thresholds, and cycle flags. + // tokens, a usage bar, both effective thresholds, cycle flags, and the + // session's compaction count. // Dismissed with esc / enter / q / ctrl+c; notify() remains the // fallback where ctx.ui.custom is unavailable (print/RPC mode). pi.registerCommand?.("smart-compact", { @@ -338,6 +346,23 @@ export default function smartCompact(pi: any) { const forceAt = effective(cfg.forceTokens, cfg.forceFraction, window); const fmt = (n: number): string => `${Math.round(n / 1000)}k`; + // Session-lifetime compaction count. Authoritative source: persisted + // `compaction` entries in the session tree (all branches — every + // compaction this session ever had, correct across resume/restart). + // Fallback: the in-memory counter (hosts without sessionManager; + // counts only this process's compactions). + const countCompactions = (): number => { + try { + const entries = ctx.sessionManager?.getEntries?.(); + if (Array.isArray(entries)) { + return entries.filter((e: any) => e?.type === "compaction").length; + } + } catch { + /* unreadable tree — use the in-memory count */ + } + return sessionCompactions; + }; + const rows: StatusRow[] = []; const add = (l: string, value: string, color?: string) => rows.push({ text: `${l} ${value}`, color }); @@ -372,6 +397,7 @@ export default function smartCompact(pi: any) { ); add(pad("warned this cycle"), String(warnedThisCycle)); add(pad("force in flight"), String(forceInFlight)); + add(pad("compactions"), String(countCompactions())); await showStatusPanel(ctx, "smart-compact status", rows); },