# agy


<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

Find, read, search, and compact Antigravity CLI and desktop
conversations stored on this machine.

## Conversation layout

Antigravity CLI stores each conversation as a SQLite database under
`AGY_HOME/conversations/<id>.db`, alongside a summary index at
`AGY_HOME/conversation_summaries.db` and JSONL transcript mirrors under
`AGY_HOME/brain/<id>/.system_generated/logs/`. Desktop conversations use
the same schema under `AGY_APP_HOME` (`~/.gemini/antigravity`). Passing
`agy_home=None` searches both directories. Use
[`cur_conv`](https://AnswerDotAI.github.io/llmsurgery/agy.html#cur_conv)
for a running session’s id,
[`conv_file`](https://AnswerDotAI.github.io/llmsurgery/agy.html#conv_file)
to locate a database by id or unique prefix,
[`project_conv`](https://AnswerDotAI.github.io/llmsurgery/agy.html#project_conv)
for the newest conversation in a project,
[`resolve_conv`](https://AnswerDotAI.github.io/llmsurgery/agy.html#resolve_conv)
to accept an id, prefix, or title, and
[`prompt_hist`](https://AnswerDotAI.github.io/llmsurgery/agy.html#prompt_hist)
to recover earlier user prompts.

The `steps` table stores ordered protobuf records: user inputs (`14`),
planner responses (`15`), tool results (`132`), system messages (`101`),
and compaction checkpoints (`23`).
[`load_steps`](https://AnswerDotAI.github.io/llmsurgery/agy.html#load_steps)
decodes every step in the database.
[`active_steps`](https://AnswerDotAI.github.io/llmsurgery/agy.html#active_steps)
starts from the latest checkpoint.
[`steps2chat`](https://AnswerDotAI.github.io/llmsurgery/agy.html#steps2chat)
converts steps into canonical messages, unwrapping `call_mcp_tool` calls
and preserving untruncated `𝍁…𝍁` outputs.

## Reading workflow

Start with
[`conv2dlg`](https://AnswerDotAI.github.io/llmsurgery/agy.html#conv2dlg)
to read a conversation as an aidialog dialog. Search with
`d.find_msgs(pat)` and read messages with `view_msg`. For step-level
inspection, load with
[`load_conv`](https://AnswerDotAI.github.io/llmsurgery/agy.html#load_conv),
search with
[`step_search`](https://AnswerDotAI.github.io/llmsurgery/agy.html#step_search),
and display slices with
[`show_steps`](https://AnswerDotAI.github.io/llmsurgery/agy.html#show_steps).

Reading functions open SQLite read-only and never modify databases.
Synthetic compaction appends one `CHECKPOINT` row (`step_type = 23`)
directly to `steps`. Close Antigravity before running
[`append_compaction`](https://AnswerDotAI.github.io/llmsurgery/agy.html#append_compaction)
or
[`compact_session`](https://AnswerDotAI.github.io/llmsurgery/agy.html#compact_session).

``` python
from collections import Counter
from fastcore.test import *
import shutil, tempfile
```

## Protobuf wire helpers

Antigravity stores step payloads and metadata as standard unencrypted
protobuf messages. These wire helpers decode and encode varints and
length-delimited fields without adding a protobuf runtime dependency.

Check round-trip encoding for integers, strings, and timestamps:

``` python
ts_dt = datetime(2026, 11, 20, 2, 56, 12, 469000, timezone.utc)
wire = _pb_f_int(1, 23) + _pb_f_bytes(5, 'summary') + _pb_f_bytes(8, _pb_ts_bytes(ts_dt))
dec = _pb_decode(wire)
test_eq(_pb_one(dec, 1), 23)
test_eq(_pb_str(dec, 5), 'summary')
test_eq(_pb_ts(_pb_one(dec, 8)), '2026-11-20T02:56:12.469Z')
dec
```

## Where conversations live

Antigravity CLI stores databases in `AGY_HOME/conversations` and indexes
them in `AGY_HOME/conversation_summaries.db`. Commands started inside
Antigravity inherit `ANTIGRAVITY_CONVERSATION_ID`.
[`conv_file`](https://AnswerDotAI.github.io/llmsurgery/agy.html#conv_file)
looks up `<id>.db` directly first, then checks
`conversation_summaries.db` so desktop conversations under sibling app
data directories resolve by id too.

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/llmsurgery/blob/main/llmsurgery/agy.py#L132"
target="_blank" style="float:right; font-size:smaller">source</a>

### cur_conv

``` python
def cur_conv():
```

*The current Antigravity conversation id, when running inside
Antigravity*

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/llmsurgery/blob/main/llmsurgery/agy.py#L122"
target="_blank" style="float:right; font-size:smaller">source</a>

### db_mtime_ns

``` python
def db_mtime_ns(
    path, # Path to a transcript file or SQLite `.db`
):
```

*Modification time in nanoseconds, including a non-empty SQLite `-wal`
file when present*

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/llmsurgery/blob/main/llmsurgery/agy.py#L110"
target="_blank" style="float:right; font-size:smaller">source</a>

### agy_homes

``` python
def agy_homes(
    agy_home:NoneType=None, # Single app data directory, list of directories, or None for both CLI and desktop stores
):
```

*App data directories to search for Antigravity conversations*

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/llmsurgery/blob/main/llmsurgery/agy.py#L187"
target="_blank" style="float:right; font-size:smaller">source</a>

### project_conv

``` python
def project_conv(
    cwd:str='.', # Project directory
    agy_home:NoneType=None, # Antigravity app data directory, list of directories, or None for CLI and desktop
):
```

*The newest top-level `(conv_id, db_path)` for `cwd`*

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/llmsurgery/blob/main/llmsurgery/agy.py#L161"
target="_blank" style="float:right; font-size:smaller">source</a>

### conv_file

``` python
def conv_file(
    conv_id, # Conversation UUID, unique id prefix, or path to a `.db` file
    agy_home:NoneType=None, # Antigravity app data directory, list of directories, or None for CLI and desktop
):
```

*The conversation database for `conv_id`, if it exists*

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/llmsurgery/blob/main/llmsurgery/agy.py#L221"
target="_blank" style="float:right; font-size:smaller">source</a>

### resolve_conv

``` python
def resolve_conv(
    ref:NoneType=None, # Conversation id, prefix, or title; current or project's newest if None
    cwd:str='.', # Project directory when resolving the newest conversation
    agy_home:NoneType=None, # Antigravity app data directory, list of directories, or None for CLI and desktop
):
```

*Resolve a conversation reference to `(conv_id, db_path)`*

## Building synthetic conversations

These test helpers construct valid SQLite conversation databases with
real protobuf wire records matching Antigravity’s table and field
numbers. Keeping fixtures synthetic lets every notebook example run fast
without checking binary databases into git.

Create a temporary Antigravity home with one conversation that uses the
persistent kernel (including a `𝍁…𝍁` full-string output), `run_command`,
`read_file` on a `SKILL.md`, a hook system message, and an agent report:

``` python
_td = tempfile.TemporaryDirectory()
home = Path(_td.name)
proj = home/'project'
proj.mkdir()
cid, tid = 'ab12cd34-0000-4000-8000-000000000000', '11111111-0000-4000-8000-000000000000'
t0 = datetime(2026, 11, 20, 2, 0, 0, tzinfo=timezone.utc)
t1 = datetime(2026, 11, 20, 2, 1, 0, tzinfo=timezone.utc)
t2 = datetime(2026, 11, 20, 2, 2, 0, tzinfo=timezone.utc)

mcp_args = dict(ServerName='aai-coding_clikernel', ToolName='exec', Arguments=dict(code='6 * 7'))
sample_rows = [_mk_user(0, 'Check the flux meter skill and compute 6*7.', tid, cid, ts=t0),
    _mk_sys(1, 'The following system message was injected by a SessionStart hook:\nnbdev project.', 'hook_json_SessionStart', tid, cid, ts=t0),
    _mk_asst(2, 'Reading the skill and running the kernel.', tid, cid, thinking='Private thought.',
        calls=[('c1', 'read_file', dict(Path='/skills/flux/SKILL.md')),
            ('c2', 'call_mcp_tool', mcp_args),
            ('c3', 'run_command', dict(CommandLine='printf "flux: 41.7\\n"'))], ts=t0),
    _mk_tool(3, 'c1', 'read_file', dict(Path='/skills/flux/SKILL.md'),
        'Created At: 2026-11-20T12:00:00+10:00\nCompleted At: 2026-11-20T12:00:01+10:00\nShowing lines 1-2 of 2\n1: # Flux skill', tid, cid, ts=t0),
    _mk_tool(4, 'c2', 'call_mcp_tool', mcp_args,
        'A pre-tool hook changed the arguments of this tool call before it ran.\n\nCreated At: 2026-11-20T12:00:01+10:00\nCompleted At: 2026-11-20T12:00:02+10:00\n𝍁42𝍁',
        tid, cid, mcp_raw='𝍁42𝍁', ts=t0),
    _mk_tool(5, 'c3', 'run_command', dict(CommandLine='printf "flux: 41.7\\n"'),
        'Created At: 2026-11-20T12:00:02+10:00\nCompleted At: 2026-11-20T12:00:03+10:00\nCommand exited with code 0.\n\nCommand output:\nflux: 41.7', tid, cid, ts=t0),
    _mk_asst(6, 'The kernel returned 42 and the flux reading is 41.7.', tid, cid, ts=t1),
    _mk_sys(7, '[Message] timestamp=2026-11-20T02:02:00Z sender=e6572eae priority=MESSAGE_PRIORITY_HIGH content=Subagent verified flux units.', 'agent_message', tid, cid, ts=t2)]
db_path = _init_conv_db(home/'conversations'/f'{cid}.db', cid, tid, proj, sample_rows, title='Flux Check', agy_home=home)
```

Resolve the conversation by id prefix, path, project directory, or
title;
[`project_conv`](https://AnswerDotAI.github.io/llmsurgery/agy.html#project_conv)
skips child conversations (summarized or not), ignores empty `-wal`
files, and reads closed databases without creating `-wal` files:

``` python
test_eq(conv_file('ab12cd34', home), db_path)
test_eq(project_conv(proj, home), (cid, db_path))
test_eq(resolve_conv('Flux Check', proj, home), (cid, db_path))
test_eq(conv_file(db_path), db_path)
w1_cid, w2_cid = 'cd34ef56-1111-4000-8000-000000000000', 'ef56ab78-2222-4000-8000-000000000000'
w1 = _init_conv_db(home/'conversations'/f'{w1_cid}.db', w1_cid, tid, proj, [], agy_home=home, parent=cid)
w2 = _init_conv_db(home/'conversations'/f'{w2_cid}.db', w2_cid, tid, proj, [], parent=cid)
con = sqlite3.connect(w2)
con.execute('PRAGMA journal_mode=WAL')
con.close()
os.utime(w1, ns=(db_path.stat().st_atime_ns, db_path.stat().st_mtime_ns + 2_000_000_000))
wal0 = Path(f'{db_path}-wal')
wal0.write_bytes(b'')
os.utime(wal0, ns=(db_path.stat().st_atime_ns, db_path.stat().st_mtime_ns + 3_000_000_000))
test_eq(db_mtime_ns(db_path), db_path.stat().st_mtime_ns)
test_eq(project_conv(proj, home), (cid, db_path))
assert not Path(f'{w2}-wal').exists()
wal0.unlink()
resolve_conv('ab12cd34', proj, home)
```

## Reading and searching a conversation

[`load_steps`](https://AnswerDotAI.github.io/llmsurgery/agy.html#load_steps)
decodes every row in `steps` into a uniform `AttrDict`. For
`call_mcp_tool` calls,
[`_norm_call`](https://AnswerDotAI.github.io/llmsurgery/agy.html#_norm_call)
unwraps `ServerName`, `ToolName`, and `Arguments` into
`mcp__<server>__<tool>` so downstream compaction and dialog tools treat
persistent-kernel calls like those from Claude Code and Codex. For MCP
results,
[`_tool_result_text`](https://AnswerDotAI.github.io/llmsurgery/agy.html#_tool_result_text)
reads the raw `McpTool` payload (or an offloaded `output.txt` when it
carries `𝍁…𝍁` markers) so Antigravity’s hook and timestamp prefixes
never hide untruncated `FullString` outputs.

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/llmsurgery/blob/main/llmsurgery/agy.py#L315"
target="_blank" style="float:right; font-size:smaller">source</a>

### load_conv

``` python
def load_conv(
    ref:NoneType=None, # Conversation id, prefix, or title; current or project's newest if None
    cwd:str='.', # Project directory
    agy_home:NoneType=None, # Antigravity app data directory, list of directories, or None for CLI and desktop
):
```

*Load all decoded steps for conversation `ref`*

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/llmsurgery/blob/main/llmsurgery/agy.py#L307"
target="_blank" style="float:right; font-size:smaller">source</a>

### load_steps

``` python
def load_steps(
    path, # Path to a conversation SQLite `.db` file
):
```

*Decode every step in `path` in index order*

Load the synthetic conversation and verify that `call_mcp_tool`
unwrapped cleanly and the `𝍁42𝍁` result kept its `full` flag:

``` python
steps = load_steps(db_path)
test_eq(Counter(steps.attrgot('role')), Counter(user=1, system=2, assistant=2, tool=3))
test_eq(steps[2].tool_calls[1].name, 'mcp__aai-coding_clikernel__exec')
test_eq((steps[4].tool_name, steps[4].text, steps[4].full), ('mcp__aai-coding_clikernel__exec', '𝍁42𝍁', True))
[(s.idx, s.role, s.get('tool_name', s.get('tag', ''))) for s in steps]
```

[`step_search`](https://AnswerDotAI.github.io/llmsurgery/agy.html#step_search)
and
[`show_steps`](https://AnswerDotAI.github.io/llmsurgery/agy.html#show_steps)
mirror
`ant.sess_search`/[`show_recs`](https://AnswerDotAI.github.io/llmsurgery/ant.html#show_recs)
and
`oai.item_search`/[`show_items`](https://AnswerDotAI.github.io/llmsurgery/oai.html#show_items).
Each search hit keeps its decoded step on `.step` and the full searched
list on `.steps`.

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/llmsurgery/blob/main/llmsurgery/agy.py#L360"
target="_blank" style="float:right; font-size:smaller">source</a>

### show_steps

``` python
def show_steps(
    steps, # Decoded steps, e.g. a slice of `StepHits.steps`
    mx:int=500, # Text characters per step
):
```

*Readable view of decoded steps*

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/llmsurgery/blob/main/llmsurgery/agy.py#L342"
target="_blank" style="float:right; font-size:smaller">source</a>

### step_search

``` python
def step_search(
    pat, # Regex to find
    steps, # Decoded steps, e.g. from `load_steps`
    maxlen:int=180, # Preview characters around the match
):
```

*Search decoded steps:
[`StepHits`](https://AnswerDotAI.github.io/llmsurgery/agy.html#stephits)
rows, each carrying its step on `.step` and all searched steps on
`.steps`*

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/llmsurgery/blob/main/llmsurgery/agy.py#L333"
target="_blank" style="float:right; font-size:smaller">source</a>

### StepHits

``` python
def StepHits(
    items:NoneType=None, # Initial item, iterable, or `None` (empty `L`); strings, bytes, dicts, arrays, and tensors stay single items unless `use_list=True`
    *rest, # Additional positional items, e.g. `L(1, 2, 3)`
    use_list:bool=False, # `True` forces `list(items)`; `False` wraps scalars/strings/dicts as 1 item; `None` keeps array/DataFrame in place
    match:NoneType=None, # Replicate a 1-item `L` to `len(match)`, or assert lengths match
):
```

*Search hits with one match-centered preview per line, each carrying its
step on `.step`*

``` python
hits = step_search(r'41\.7', steps)
test_eq([h.role for h in hits], ['assistant', 'tool', 'assistant'])
test_eq(type(hits[:1]).__name__, 'StepHits')
show_steps(hits.steps[hits[1].i-1:hits[1].i+2], mx=120)
```

## Prompt history

[`prompt_hist`](https://AnswerDotAI.github.io/llmsurgery/agy.html#prompt_hist)
recovers user prompts from Antigravity conversation databases across CLI
and desktop stores. Each row identifies the timestamp, project
directory, conversation id, and prompt text.

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/llmsurgery/blob/main/llmsurgery/agy.py#L374"
target="_blank" style="float:right; font-size:smaller">source</a>

### prompt_hist

``` python
def prompt_hist(
    project:NoneType=None, # Only conversations whose workspace is this path
    since:NoneType=None, # Only timestamps at or after this ISO string
    pat:NoneType=None, # Only prompt text matching this regex
    agy_home:NoneType=None, # Antigravity app data directory, list of directories, or None for CLI and desktop
):
```

*User prompts retained in Antigravity conversation databases, oldest
first*

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/llmsurgery/blob/main/llmsurgery/agy.py#L369"
target="_blank" style="float:right; font-size:smaller">source</a>

### PromptHist

``` python
def PromptHist(
    *args, **kwargs
):
```

*Antigravity prompt-history rows, one line per user message*

``` python
ph = prompt_hist(proj, pat='flux', agy_home=home)
test_eq(len(ph), 1)
test_eq(ph[0].conv, cid)
ph
```

## Active history and dialogs

[`split_compaction`](https://AnswerDotAI.github.io/llmsurgery/agy.html#split_compaction)
locates the latest `CHECKPOINT` step (`step_type = 23`). For an
`llmsurgery` synthetic checkpoint (whose text contains
`\n\n## Conversation\n\n`), it extracts the unchanged DSL body with
[`compact_body`](https://AnswerDotAI.github.io/llmsurgery/compact.html#compact_body).
For a native `/compact` checkpoint, it keeps the native summary text.
[`active_steps`](https://AnswerDotAI.github.io/llmsurgery/agy.html#active_steps)
returns steps from that latest checkpoint onward.

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/llmsurgery/blob/main/llmsurgery/agy.py#L409"
target="_blank" style="float:right; font-size:smaller">source</a>

### active_steps

``` python
def active_steps(
    steps, # Decoded steps from `load_steps`
):
```

*Steps from the latest `CHECKPOINT` onward, or all steps if uncompacted*

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/llmsurgery/blob/main/llmsurgery/agy.py#L398"
target="_blank" style="float:right; font-size:smaller">source</a>

### split_compaction

``` python
def split_compaction(
    steps, # Decoded steps from `load_steps`
):
```

*Return `(prior_summary, new_steps)` split at the latest `CHECKPOINT`
step*

[`steps2chat`](https://AnswerDotAI.github.io/llmsurgery/agy.html#steps2chat)
converts decoded steps into canonical `Msg` objects with `created` and
`uid` metadata. It drops hook plumbing (`hook_json_*`), fork notices,
and `sender=system` restart notices. With `agent_results=True`, it
retains `agent_message`, `task_notification`, `plan_mode_handoff`, and
untagged `[Message]` steps so compaction preserves subagent reports
under their bounded budget.

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/llmsurgery/blob/main/llmsurgery/agy.py#L450"
target="_blank" style="float:right; font-size:smaller">source</a>

### conv2dlg

``` python
def conv2dlg(
    ref:NoneType=None, # Conversation id, prefix, or title; current or project's newest if None
    cwd:str='.', # Project directory
    agy_home:NoneType=None, # Antigravity app data directory, list of directories, or None for CLI and desktop
    name:NoneType=None, # Dialog name; conversation id if None
    mx:int=2000, # Maximum rendered tool string length
    since_compact:bool=False, # Only the conversation since the last checkpoint?
    steps:NoneType=None, # Optional preloaded steps
):
```

*Convert an Antigravity conversation into an editable aidialog `Dialog`*

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/llmsurgery/blob/main/llmsurgery/agy.py#L425"
target="_blank" style="float:right; font-size:smaller">source</a>

### steps2chat

``` python
def steps2chat(
    steps, # Decoded steps from `load_steps`
    agent_results:bool=False, # Include subagent messages, task notifications, and plan handoffs as user turns?
):
```

*Convert Antigravity steps into canonical `Msg` objects*

``` python
dlg = conv2dlg('ab12cd34', proj, home)
test_eq(len(dlg.messages), 1)
test('41.7', dlg.messages[0].ai_res, in_)
dlg.summary()
```

Subagent conversations start with an `agent_message` system step instead
of a `USER_INPUT` step.
[`steps2chat`](https://AnswerDotAI.github.io/llmsurgery/agy.html#steps2chat)
turns that opening message into the dialog’s first user prompt:

``` python
def _row2step(r): return _parse_step(r[0], r[1], r[2], r[4], r[5], r[9])
sub_msgs = steps2chat([
    _row2step(_mk_sys(0, '[Message] timestamp=2026-11-20T02:00:00Z sender=parent priority=MESSAGE_PRIORITY_HIGH content=Check the tests.', 'agent_message', tid, cid, ts=t0)),
    _row2step(_mk_asst(1, 'All tests pass.', tid, cid, ts=t1))])
test_eq([m.role for m in sub_msgs], ['user', 'assistant'])
test_eq(sub_msgs[0].content[0].text, 'Check the tests.')
sub_msgs[0].content[0].text
```

## Synthetic compaction

Antigravity compacts a conversation by appending one `CHECKPOINT` row
(`step_type = 23`, `status = 3`) to `steps` without rewriting prior rows
or `gen_metadata`. When resumed, Antigravity builds `<CONTEXT_SUMMARY>`
from payload field `30 -> 5`, stops before the cutoff index in
`30 -> 12`, and uses `30 -> 29` as the rendered summary message’s
identifier.

[`transcript_path`](https://AnswerDotAI.github.io/llmsurgery/agy.html#transcript_path)
points the continuation document to
`brain/<id>/.system_generated/logs/transcript_full.jsonl` when present,
falling back to the `.db` path.

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/llmsurgery/blob/main/llmsurgery/agy.py#L489"
target="_blank" style="float:right; font-size:smaller">source</a>

### transcript_path

``` python
def transcript_path(
    conv_id, # Conversation UUID
    db_path, # Path to `<conv_id>.db`
):
```

*Path to `transcript_full.jsonl` when present, otherwise `db_path`*

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/llmsurgery/blob/main/llmsurgery/agy.py#L468"
target="_blank" style="float:right; font-size:smaller">source</a>

### checkpoint_step

``` python
def checkpoint_step(
    idx, # Step index for the new `CHECKPOINT` row
    content, # Continuation document stored in checkpoint field `5`
    traj_id, # Owning trajectory UUID from `trajectory_meta`
    conv_id, # Conversation (cascade) UUID
    gen_count:int=0, # Current `gen_metadata` row count
    ts:NoneType=None, # Timestamp datetime; current UTC time if None
):
```

*Build protobuf `metadata` and `step_payload` bytes for a `CHECKPOINT`
(`step_type = 23`) step*

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/llmsurgery/blob/main/llmsurgery/agy.py#L540"
target="_blank" style="float:right; font-size:smaller">source</a>

### compact_session

``` python
def compact_session(
    ref:NoneType=None, # Conversation id, prefix, or title; current or project's newest if None
    cwd:str='.', # Project directory
    agy_home:NoneType=None, # Antigravity app data directory, list of directories, or None for CLI and desktop
    policy:dict={'user_toks': 2000, 'asst_toks': 150, 'call_toks': 60, 'result_toks': 35}, # Token budget dictionary for `compact_chat`
    enc:NoneType=None, # Tokenizer encoding; `compact_enc()` if None
):
```

*Generate and append a synthetic `CHECKPOINT` compaction*

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/llmsurgery/blob/main/llmsurgery/agy.py#L524"
target="_blank" style="float:right; font-size:smaller">source</a>

### append_compaction

``` python
def append_compaction(
    compaction, # Result of `prepare_compaction`
):
```

*Insert a prepared `CHECKPOINT` row into the conversation database and
update `conversation_summaries.db`*

------------------------------------------------------------------------

<a
href="https://github.com/AnswerDotAI/llmsurgery/blob/main/llmsurgery/agy.py#L498"
target="_blank" style="float:right; font-size:smaller">source</a>

### prepare_compaction

``` python
def prepare_compaction(
    ref:NoneType=None, # Conversation id, prefix, or title; current or project's newest if None
    cwd:str='.', # Project directory
    agy_home:NoneType=None, # Antigravity app data directory, list of directories, or None for CLI and desktop
    policy:dict={'user_toks': 2000, 'asst_toks': 150, 'call_toks': 60, 'result_toks': 35}, # Token budget dictionary for `compact_chat`
    enc:NoneType=None, # Tokenizer encoding; `compact_enc()` if None
):
```

*Prepare an incremental synthetic compaction without writing to SQLite*

Prepare a compaction first and inspect it before writing. The
`clikernel` call renders as fenced Python, `𝍁42𝍁` stays marked
untruncated, `run_command` renders with `!`, the agent message uses
`> Agent:`, and the footer reminds the resumed session to re-read
`/skills/flux/SKILL.md`:

``` python
before_n = len(load_steps(db_path))
comp = prepare_compaction('ab12cd34', proj, home)
test_eq(len(load_steps(db_path)), before_n)
test('```python\n6 * 7\n```', comp.chat, in_)
test('𝍁> 42𝍁', comp.chat, in_)
test('! printf "flux: 41.7\\n"', comp.chat, in_)
test('> Agent: Subagent verified flux units.', comp.chat, in_)
test('re-read: /skills/flux/SKILL.md', comp.content, in_)
comp.pre_toks, comp.post_toks, comp.step.idx
```

Append the checkpoint and confirm it becomes the latest step in the
database:

``` python
append_compaction(comp)
after = load_steps(db_path)
test_eq(len(after), before_n + 1)
test_eq(after[-1].step_type, STEP_CHECKPOINT)
test_eq(split_compaction(after), (comp.chat, L()))
test_eq(_summary_rows(home)[0].cid, cid)
after[-1].step_type, after[-1].idx
```

Append a second exchange and compact again with
[`compact_session`](https://AnswerDotAI.github.io/llmsurgery/agy.html#compact_session).
The new checkpoint keeps the earlier DSL body unchanged and appends only
the new turns:

``` python
more = [_mk_user(9, 'Now verify the units.', tid, cid, ts=t2),
    _mk_asst(10, 'Units confirmed: kilofinches.', tid, cid, ts=t2)]
with sqlite3.connect(db_path) as con: con.executemany('INSERT INTO steps VALUES (?,?,?,?,?,?,?,?,?,?,?)', more)
comp2 = compact_session(cid, proj, home)
test_eq(comp2.prior, comp.chat)
test('Now verify the units.', comp2.new_chat, in_)
test('Units confirmed: kilofinches.', comp2.chat, in_)
test_eq(load_steps(db_path)[-1].idx, 11)
comp2.chat
```

A native Antigravity `/compact` checkpoint holds a
`<summary>...</summary>` block instead of `## Conversation`. Subsequent
[`compact_session`](https://AnswerDotAI.github.io/llmsurgery/agy.html#compact_session)
calls keep that native summary verbatim and compact only the steps added
after it:

``` python
nat_cid = 'cd34ef56-0000-4000-8000-000000000000'
nat_ckpt = checkpoint_step(1, '<summary>\nNative summary of earlier work.\n</summary>', tid, nat_cid)
nat_rows = [_mk_user(0, 'Old turn before native compact.', tid, nat_cid, ts=t0),
    (1, STEP_CHECKPOINT, STATUS_DONE, 0, nat_ckpt.metadata, None, None, None, None, nat_ckpt.step_payload, 0),
    _mk_user(2, 'Continue after native compact.', tid, nat_cid, ts=t1),
    _mk_asst(3, 'Continuing now.', tid, nat_cid, ts=t1)]
nat_db = _init_conv_db(home/'conversations'/f'{nat_cid}.db', nat_cid, tid, proj, nat_rows, agy_home=home)
nat_comp = prepare_compaction(nat_cid, proj, home)
test_eq(nat_comp.prior, '<summary>\nNative summary of earlier work.\n</summary>')
assert 'Old turn before native compact.' not in nat_comp.chat
test('Continue after native compact.', nat_comp.chat, in_)
nat_comp.chat
```

## Cleanup

Remove the temporary Antigravity home directory.
