# pi-supercompact

<p align="center">
  <img src="https://raw.githubusercontent.com/arcanemachine/pi-supercompact/main/logo.jpg" alt="pi-supercompact logo" width="250" />
</p>

A [Pi](https://pi.dev) extension for deliberate, loss-resistant context compaction.

It provides a focused pre-compaction checkpoint, optional automatic supercompaction, configurable confirmation for agent-driven requests, one-shot and live-session agent-driven permission, a canonical full-context handoff, Pi native compaction, invisible handoff restoration, and conservative continuation of authorized work. An explicit `run` or `force` is itself the user authorization and never opens a confirmation dialog.

> Like this extension? See [my other Pi extensions](https://github.com/arcanemachine/pi-projects).

## Requirements

- Pi 0.80.10 or later
- Node.js 22.19.0 or later for package development

## Installation

From GitHub:

```bash
pi install git:github.com/arcanemachine/pi-supercompact
```

From npm after publication:

```bash
pi install npm:@arcanemachine/pi-supercompact
```

For local development:

```bash
pi -e ./src/index.ts
```

## Commands

```text
/supercompact
/supercompact run [-c|--continue|-s|--stop] [extra context]
/supercompact force [-c|--continue|-s|--stop] [extra context]
/supercompact agent-driven-allow
/supercompact agent-driven-allow-once
/supercompact agent-driven-deny
/supercompact abort
/supercompact auto-enable
/supercompact auto-disable
```

`/supercompact` opens a menu with preparation, force, automatic-supercompact controls, agent-driven permission controls, and abort. Preparation and force open a multiline editor for optional context. The menu's permission choices are the same no-dialog allow, one-shot allow, and deny controls exposed by the command forms.

Automatic controls affect only percentage-triggered work. Agent-driven controls grant permission for the public tool to request compaction. Continuation flags apply only to explicit textual `run` and `force` commands; automatic and agent-driven workflows keep their existing continuation safeguards. Neither control grants the other.

### Automatic supercompact

Automatic supercompact is off by default. When enabled, it checks context usage after each completed assistant turn:

- At 80%, it starts the same careful preparation as `/supercompact run`.
- At 90%, it skips unfinished automatic preparation and starts the same immediate summary as `/supercompact force`.
- If usage first reaches 90%, it takes the force path directly.
- Automatic work does not open a confirmation dialog. `/supercompact abort` can cancel it before Pi starts native compaction.
- Automatic prompts identify the threshold trigger rather than treating it as a user request. They preserve momentum: they prefer `continue` for clearly unfinished authorized work, retain the active objective and one exact next action, and stop only when work is complete, blocked, awaiting input or approval, or unsafe to continue.
- Each threshold is tried once until usage falls below the soft threshold or compaction completes. An abort or failure does not retry immediately.

Use `/supercompact auto-enable` or `/supercompact auto-disable` to override the setting for the live session. The choice survives `/reload`, but not a new, resumed, or forked session. It does not write configuration, and disabling it does not cancel automatic work already underway.

### Prepare normally

```text
/supercompact run
/supercompact run --stop preserve the accepted boundaries
/supercompact run -c preserve the accepted boundaries and continue implementation
```

`run` does not compact immediately. It:

1. Creates one pending preparation authorization.
2. Sends a hidden steering prompt for a focused refresh-and-close checkpoint.
3. Lets the agent finish already-authorized work that needs no new input, refresh relevant durable context, and verify or persist work when applicable.
4. Requires the agent to surface blockers or questions, choose whether work should continue, and name one exact next action.
5. Treats the run command itself as explicit user authorization, exactly like `force`: no final confirmation dialog opens, even headlessly.
6. Starts the dedicated continuation decision, canonical summary, and native compaction directly from that authorization.

The checkpoint follows the active session's scope and rules. It does not assume that every session has a repository, files to edit, validation to run, or changes to commit.

`-c`, `--continue`, `-s`, and `--stop` are optional authoritative continuation flags. Each shorthand is equivalent to its long form. They must appear immediately after `run`; the selected value is carried through preparation and cannot be changed by the agent. A conflicting or unknown leading option is rejected. Use `/supercompact abort` to cancel a flagged preparation before it is consumed.

If user input is required, the agent asks and waits. The one-off authorization remains pending across turns until it is used, canceled, denied, or replaced by session lifecycle activity.

### Force immediately

```text
/supercompact force
/supercompact force --stop
/supercompact force --continue preserve the active objective
```

`force` immediately starts the continuation-decision, canonical-summary, and native-compaction workflow. It bypasses preparation and final confirmation because the command itself is explicit user authorization. It remains available when agent-driven requests are denied. An explicit `-c`, `--continue`, `-s`, or `--stop` must appear immediately after `force`; the selected value is authoritative and the dedicated decision turn must record that exact value. Use `/supercompact abort` to cancel a flagged force workflow before native compaction.

### Allow one agent-driven request

```text
/supercompact agent-driven-allow-once
```

`agent-driven-allow-once` arms the next valid agent-driven supercompaction without starting preparation or compaction itself. The user can then instruct the agent to complete the normal focused preparation and request supercompaction. The grant temporarily overlays denied or confirmation-required configured permission without changing it, and the request proceeds without a confirmation dialog. While armed, the status is `Supercompact: agent-driven-allow-once 🗜️ `.

The grant is consumed only after a valid request successfully queues canonical-summary work. Invalid arguments, unavailable tools, or a synchronous queueing failure leave it armed; once work is queued, a later abort or failure does not re-arm it. Consumption automatically reveals the prior configured or live-session permission and status.

If effective configured or live-session permission already allows requests without a confirmation dialog, the command warns and does not arm a redundant grant. The grant is in-memory only. Reloading, replacing, resuming, forking, or shutting down the session clears it, as do `abort`, `agent-driven-deny`, `run`, `force`, and `agent-driven-allow`. The command refuses to arm while a preparation, confirmation, summary, or compaction workflow is active.

### Abort before native compaction

```text
/supercompact abort
```

`abort` cancels pending preparation, an armed one-shot grant, an open confirmation, or queued or active canonical-summary work before native compaction begins. It preserves configured and persistent live-session permission and does not change either tool schema. Calling it with no abortable workflow or one-shot grant reports `No supercompaction is active.` as an error.

Pi does not expose native compaction cancellation to extensions. Once native compaction begins, press Escape in the TUI or use the host's native cancellation mechanism when available.

### Live-session agent-driven permission

- `/supercompact agent-driven-allow` permits agent-driven requests for the current live extension session without opening a confirmation dialog.
- `/supercompact agent-driven-allow-once` temporarily permits one request without the dialog, then restores the effective configured or live-session mode.
- `/supercompact agent-driven-deny` revokes live-session permission and cancels an unused preparation, one-shot grant, or open confirmation.

These commands update or arm session-local permission and never write configuration. They govern agent-driven calls only: a manual `run` or `force` is its own user authorization and never opens the confirmation dialog. A context-excluded custom session entry restores persistent live-session permission across `/reload`; it does not enter model context. One-shot permission uses only transient in-memory state and is cleared by reload. Starting a new process, creating or resuming a session, or forking discards runtime permission and reapplies configured denied or allowed permission.

## Configuration

Persistent request permission, optional confirmation, and automatic supercompact use the `pi-supercompact` namespace in Pi's `settings.json` files:

```json
{
  "pi-supercompact": {
    "agentRequestsAllowed": true,
    "agentRequestsRequireConfirmation": false,
    "supercompact": {
      "enabled": true,
      "thresholdPercent": 80,
      "forceThresholdPercent": 90
    }
  }
}
```

The global settings file is `~/.pi/agent/settings.json`. A trusted project may
override selected values in `<project>/.pi/settings.json`; Pi deep-merges nested
objects, so omitted project values inherit the effective global values. Project
settings are ignored for untrusted projects.

- `agentRequestsAllowed` defaults to `false` and is the only property that grants persistent agent-driven permission.
- `agentRequestsRequireConfirmation` defaults to `false`. Set it to `true` to opt configured agent-driven requests into the final TUI or RPC confirmation dialog. It does not grant permission by itself.
- `requireConfirmation` is no longer recognized or used.
- `supercompact` is optional. It enables automatic supercompact only when `enabled` is `true`. Its thresholds default to 80 and 90 when omitted. They must be finite percentages above 0 and below 100, with `thresholdPercent` below `forceThresholdPercent`.

For one Pi process, `--supercompact-auto` enables automatic supercompact and `--no-supercompact-auto` disables it. If both are supplied, the negative flag wins. Live `/supercompact auto-enable` or `/supercompact auto-disable` settings override flags; flags override trusted project or global configuration. These controls affect automatic triggering only, not the extension's tools or manual `/supercompact` commands.

Prepared `run` never opens a confirmation dialog—the command is the authorization. Config-authorized agent-driven requests follow this table:

| `agentRequestsAllowed` | `agentRequestsRequireConfirmation` | Config-authorized request |
| ---------------------- | ---------------------------------- | ------------------------- |
| `false`                | either                             | Denied                    |
| `true`                 | omitted or `false`                 | No dialog                 |
| `true`                 | `true`                             | Confirm                   |

`/supercompact agent-driven-allow` explicitly overrides configured permission for the live session and proceeds without a dialog. `/supercompact agent-driven-allow-once` overlays configured or live-session permission for one successfully queued request without mutating it. `/supercompact agent-driven-deny` blocks unprepared requests but does not prevent the user from creating a later one-off `run` or one-shot permission. `/supercompact force` always remains immediate and dialog-free, as does a prepared `run`.

A recognized property with a non-boolean value makes that configuration invalid; invalid configuration fails closed to denied agent-driven requests and warns when UI is available.

## Stable tools and authorization

The extension registers these tools once when it loads and keeps their schemas active throughout the extension session:

- `supercompact` — the public request interface
- `record_supercompact_decision` — internal canonical-summary workflow control

Tool visibility does not grant authority. The public tool checks effective configured or live-session permission, an unused `run` grant, or an armed one-shot grant; workflow and confirmation state; internal-tool availability; exact-next-action validity; UI capability when configured confirmation is enabled; and authorization again at the last applicable boundary. The internal tool accepts exactly one short call only during the dedicated continuation-decision phase, with no other tool calls, and all confirmed stop constraints intact. Incidental prose is tolerated. Calls outside that phase are ignored silently instead of generating corrective context. The following canonical-summary phase accepts only a non-empty ordinary Markdown handoff and no tool calls.

The extension never changes Pi's active tool selection to enforce permission. If the user or host excludes a required extension tool, the extension respects that choice. `force` fails before creating workflow state when the internal decision tool is unavailable. Prepared requests only require the public request tool because they carry their continuation outcome directly; the extension explains when a required tool must be re-enabled or the extension reloaded with its tools available. `agent-driven-allow`, `agent-driven-allow-once`, and `agent-driven-deny` update or arm session-local permission while reporting that execution remains unavailable. `abort` never changes the active tool selection.

## How it works

The extension does not replace or customize Pi's native compaction summary. It creates its own canonical working-memory handoff, then calls native compaction without custom instructions.

Pi may automatically compact after the canonical summary turn if that turn crosses the configured threshold. A successful automatic compaction satisfies the workflow, so the extension does not compact twice.

Pi also has built-in automatic compaction. To make supercompact the only automatic compactor, disable Pi's compaction in `settings.json`:

```json
{
  "compaction": {
    "enabled": false
  }
}
```

This also disables Pi's automatic overflow recovery. If supercompact is aborted or cannot finish, Pi will not automatically rescue the session. Keep Pi's compaction enabled if you want it as a final fallback.

### Preparation and confirmation

The hidden preparation prompt asks the agent to:

- re-read applicable plans, instructions, user-facing documentation, and directly referenced durable sources;
- compare them with actual scoped state and focused verification when applicable;
- correct scoped staleness without broadening the task;
- finish only authorized work that needs no new input;
- surface blockers, questions, approvals, credentials, or decisions;
- verify or persist completed work when applicable and follow scoped rules;
- establish `continue` or `stop` and one exact immediate next action.

The confirmation dialog whitespace-normalizes agent-created values—the next action and additional summary context—and limits them to the first 10 words plus `…` when longer. Major blocks are separated by one blank line. The complete values remain unchanged in workflow state, the canonical summary prompt, restored context, and continuation metadata, and user-supplied run context always travels in full through the same paths even though it never appears in a dialog.

When configured confirmation is enabled, the extension locks it before opening the dialog and rechecks authorization afterward. Otherwise configured, live-session, one-shot, automatic, `run`, and `force` authorization opens no dialog and begins the same guarded canonical-summary path directly. A confirmed or explicitly authorized `stop` is a hard constraint. Without an explicit command flag, a `continue` choice is permission, not a mandate: the dedicated decision phase may conservatively choose `stop` when work is complete, blocked, awaiting input, or uncertain. Explicit `--continue` and `--stop` flags are authoritative user choices and cannot be changed by the agent; `/supercompact abort` is the pre-compaction cancellation path.

### Canonical summary workflow

For an unprepared `force` request, the extension:

An explicit `--continue` or `--stop` flag does not remove the dedicated decision turn. It constrains that turn to record the selected value, while unflagged requests retain conservative agent-selected continuation.

1. Queues a short, dedicated continuation-decision turn.
2. Records a schema-validated `continue` or `stop` decision through the internal tool, with no other tool calls allowed.
3. Queues a separate full-context canonical-summary turn.
4. Keeps the generated handoff as ordinary assistant Markdown; this turn accepts no tool calls.
5. Runs Pi's native compaction automatically after valid summary prose settles.
6. Restores the exact handoff invisibly with authorized preparation metadata.
7. Continues once or waits according to the validated decision.

Prepared requests already carry a validated continuation outcome from the preparation or public request call, so they skip the redundant decision turn and queue the Markdown handoff directly. For unprepared force requests, the split keeps the long handoff in ordinary Markdown while making the required tool call short and isolated. Incidental prose does not invalidate a response containing exactly one valid decision call and no other tools. Successful internal control calls are hidden from transcript presentation and terminate the decision turn without an acknowledgement round trip.

After the summary is captured, the extension shows the continue-or-wait outcome once as a durable TUI transcript entry. The entry remains available in scrollback instead of disappearing like a transient notification. It is TUI-only session data: it does not enter model context, trigger another turn, or change the provider prompt prefix.

### Summary contents

The prompt prioritizes:

- the current objective, direction, authorization boundaries, and actionable state;
- open decisions and blockers;
- verified results separately from mutable observations and reported information;
- completed history compressed to outcomes and material rationale;
- one concrete next action as the final section.

Relevant resources are grouped by work horizon. Exact file paths remain available when files materially affect continuation. The model is instructed not to invent work, broaden scope, include transient identifiers, or treat optional follow-ups as authorized.

### Queue, status, and caching

When Pi is idle, preparation, decision, and summary messages trigger immediate steering turns. While Pi is responding, they are queued with steering semantics so the current tool batch finishes first.

Operational status text is shown while the extension is preparing or awaiting configured confirmation:

- `Supercompact: preparing 🗜️ `
- `Supercompact: awaiting confirmation 🗜️ `

Explicit live-session permission and an armed one-shot grant add one of these status items:

- `Supercompact: agent-driven-allow 🗜️ `
- `Supercompact: agent-driven-allow-once 🗜️ `

Every status string includes a trailing space after the emoji to separate adjacent status items. Configured permission is intentionally silent in the status area. Consuming or canceling a one-shot grant reveals the prior live-session status. `/supercompact agent-driven-deny` clears any live-session permission status, while a later `/supercompact agent-driven-allow` displays the new explicit override.

`run`, `agent-driven-allow`, `agent-driven-allow-once`, `agent-driven-deny`, `abort`, configured confirmation, dialog-free execution, summary entry, settlement, and cleanup do not change the extension's active tool vector. This removes extension-caused mid-session schema invalidation and preserves an otherwise reusable prompt-cache prefix.

It does not guarantee provider cache hits. Cache expiration, provider policy, model changes, unrelated extensions, host tool selection, system-prompt changes, and conversation-prefix differences can still cause misses.

Completed or canceled preparation-control messages, stale summary requests, duplicate restored summaries, and completed internal decision artifacts are filtered from later provider context. Substantive preparation work and ordinary conversation remain available.

### Headless behavior

- TUI and RPC modes support the configured final confirmation dialog.
- `force` works in print and JSON modes because it is explicit authorization.
- `run` works headlessly because the command itself is the authorization and never opens a dialog, exactly like `force`.
- Automatic supercompact works headlessly because it never asks for confirmation.
- `agent-driven-allow`, `agent-driven-allow-once`, and `agent-driven-deny` update or arm session-local permission headlessly.
- Configured confirmation-required agent execution fails closed without confirmation UI; configured default, live-session, prepared-run, and one-shot permission work headlessly while retaining every non-dialog guard.
- The bare menu requires TUI or RPC mode.

### Failure behavior

The workflow is bounded and leaves the session usable:

- Concurrent preparation, confirmation, and compaction requests receive state-specific guidance.
- Revocation or lifecycle replacement while confirmation is open prevents compaction.
- Invalid decision arguments use Pi's normal correction loop without making the workflow terminal.
- If the model omits or mixes the short decision call with other tools, the extension requests the decision again without starting summary generation while the automatic correction budget remains.
- If the summary is empty, truncated, errored, or includes a tool call, the extension requests only the Markdown handoff again without repeating the decision.
- Decision and summary correction nudges are bounded. Provider errors, truncation, and unusable responses leave the workflow active for a later retry or resend while the correction budget remains; pressing Escape cancels the extension-controlled workflow instead of requesting another correction.
- `/supercompact abort` cancels extension-controlled work before native compaction; pressing Escape has the same effect while preparation, decision, or canonical-summary work is active. Idle `/supercompact abort` use reports an error.
- Aborted, errored, truncated, or unusable summary turns never start manual compaction. An Escape abort clears the active pre-native workflow; provider errors and truncation preserve it for bounded recovery.
- Native compaction failure prevents final context restoration, and active native compaction must be canceled through Escape or the host.
- Queueing and compaction failures preserve the specific reason and do not retry automatically; a one-shot grant is retained only when canonical-summary work was never successfully queued.
- Every exit path restores Pi's working message and clears confirmation and decision state without changing tool schemas.
- Native compaction that already completed cannot be rolled back.

## Development

```bash
npm install --ignore-scripts --workspaces=false
npm run typecheck
npm run test
npm run build
npm run format
npm pack --dry-run
```

The package is source-loaded by Pi from `src/index.ts`; no compiled runtime artifact is required.
