# Personal session library — v0.3 (save, resume, acquire, publish; scoped library tokens)

**Status:** descriptive. It describes `release/0.545.0`. The code is in `collector/routes/memory.py`
(the `/library/*` content routes) and `collector/routes/tenants.py` (`/library/sessions`, `/library/ensure`,
publish targets, profiles). Gaps are listed under §7 *Open*.

## 1. What it is

Every signed-in person has a **private library** for their agent sessions: raw transcripts, scrubbed
of secrets, that can be resumed later. The library belongs to your **account**, not to a web
address. It is a free, private personal tenant created on first use
(`tenants.py:resolve_or_create_personal_tenant`: `plan=personal`, no hostname, never sold,
never expires). Everything in it is **staged and private**. Nothing in the library is ever
published unless you publish it explicitly (§5).

All `/library/*` content routes require a signed-in human (401 otherwise). They are scoped to the
caller's own library, so you can only ever read or write your own entries.

**New in v0.3 (additive):** a tool can hold a **scoped library token** instead of the person's full
account session. It reaches only the routes its scopes name, always on its own user's library (§7).
Every v0.2 request and response keeps its meaning.

## 2. Saving and reading

| Route | Behaviour |
|---|---|
| `POST /library/push?label=&title=` (body = the raw `.jsonl`) | Scrubs secrets but keeps the structural ids, so the transcript still resumes (`_scrub`, `PROVENANCE_RULES` skipped). It then stages a private collection wrapping the session. Pushing the same session again adds a new version. (`library_push`) |
| `GET /library/sessions` | Your saved sessions, each with `created_at`, `updated_at`, `versions` and (on a fork) `forked_at` — see §2.2. (`tenants.py:list_library_sessions`) |
| `GET /library/fetch?name=\|cid=` | The staged bundle (manifest plus files, base64) for resume. It resolves by exact id, then `label:`, then a title substring. (`library_fetch`) |
| `GET /library/session?cid=` and `/library/session/{cid}` | Detail: metadata, the §2.2 times, version history, `SESSION.md`, the transcript, and a token-usage estimate from the transcript's own usage records. (`library_session_detail`) |
| `GET /library/session/{cid}/version/{ver}` | One version, plus the text appended since its parent. (`library_session_version`) |
| `POST /library/session/{cid}/meta` | Edits the title, label, tags, description or folder (§2.3). This stages a new manifest version; the transcript is untouched. |
| `POST /library/session/{cid}/scrub[?dry_run=1]` | Re-runs the scrubber. A change publishes a cleaned session version, and the older version stays in history. |
| `DELETE /library/session/{cid}` | Clears the entry's `staging` channel, so it stops listing and cannot be fetched. The version history stays in storage: **this is not an erasure**. Erasure is `specs/erasure`. |

Re-staging carries the entry's `parent`, `acquired_from`, `compact_version`, `tokens` and
`summary` forward (`_LIB_CARRY`), so an edit never cuts the entry out of its lineage.

### 2.2 When — created, updated, versions (additive, 2026-09-29)

Every saved version is a git tag in the memory projection whose commit date is the publish event's
timestamp, i.e. the push time (rebuild-stable: a JSONL replay re-derives the same date). The list
reads every tag's date in ONE `git for-each-ref --format='%(refname) %(creatordate:iso-strict)'`
over the tag namespace (`MemoryProjection.tag_dates`) — never a `git log` per row.

Times are ISO-8601 in UTC (`2026-09-29T21:50:00+00:00`), whole seconds; clients render them in the
viewer's own zone. They come from the entry's **session** member's versions — each backup push
(`push`, `push --into`, a cleaning `/scrub`) is one — and from the collection's own versions only
when the entry has no session. A `/meta` edit re-stages the manifest but is not a backup, so it moves
neither time. An older collector omits the fields; clients treat them as optional.

| Field | On | Meaning |
|---|---|---|
| `created_at` | list row, detail | the earliest version's time — when the session was first uploaded |
| `updated_at` | list row, detail | the latest version's time — the last push. Same-second ties go to the highest version |
| `versions` | list row | how many backup versions exist (an **integer** here) |
| `version_count` | detail | the same count (the detail's `versions` is, as before, the **list** of collection versions) |
| `forked_at` | list row, detail — only when `parent` is set | when the fork was made (= its `created_at`) |
| `parent_title` | detail | the parent's title if it is still in your library, else `null` ("forked from <title>@<version>") |
| `history[]` | detail | per version, newest first: `{version, ts, bytes, lines}` — `ts` is the same instant as the tag date |

My Sessions shows "updated <relative>" (exact local time on hover), "created <date>" and "N versions"
per row, "forked from <parent>@<version> on <date>" on a fork, and a sort control (last updated —
the default —, created, name; siblings in the lineage tree keep the order). The detail page shows a
version timeline, newest first, with the time and size of each version and the one resume/fork uses
(the latest; the compact tip is marked when set).

### 2.1 Session summary (tester #3, 2026-09-29)

`POST /library/push` generates a 1-2 sentence (<= 200 char) abstract and stores it on the
manifest as `summary`. It is the library-list line and the session-detail line when the author
wrote no `description`. Four rules, each with a test in `tests/test_session_summary.py`:

- **It summarizes the conversation, not the envelope.** `_conversation_text` parses the scrubbed
  JSONL and keeps the first real human prompt(s) + the LAST assistant text + the outline
  headings. `isMeta` records, tool_result carriers, system-reminder / command / notification
  wrappers and non-user/assistant records are dropped — a raw transcript's first 6000 chars are
  permission-mode / file-history envelope, and summarizing that gives a summary of the harness,
  not of the work.
- **Scrubbed input only.** It runs *after* the scrub gate, on the scrubber's output — so a
  summary can never be a channel for what the scrubber just redacted.
- **Fail-soft and time-bounded.** The LLM call is wrapped in `asyncio.wait_for(..., TIMEOUT_S)`
  (default 8 s) — the *real* bound, since httpx's timeout is per operation and the 4xx protocol
  fallback makes a second request with its own timeout. Unconfigured / unreachable / timed out /
  non-2xx / unparseable all yield no summary and the push still succeeds. One request, no retries.
- **Existing LLM path, no new key.** The fleet-router (`FLEET_ROUTER_URL` / `FLEET_ROUTER_TOKEN`
  via `secret_source`, the pair `flywheel_reaper` uses), model `AGENT_MDX_SUMMARY_MODEL` (default
  `claude-haiku-4-5`). `FLEET_ROUTER_TOKEN` is **vault-served** in prod (`secret_source.DEFAULT_NAMES`
  maps it to `fleet-router-token`, and a vault value wins over the env — so `printenv` seeing no
  token does NOT mean the path is off). Failures warn ONCE per `AGENT_MDX_SUMMARY_WARN_S`
  (default 3600 s), not once per push, so a misrouted model or an unconfigured key is noticeable
  without flooding.

**Consent: BOTH a deployment switch AND the user's own opt-in.** A summary is generated only
when both hold; otherwise nothing is sent to the LLM (`_push_summary` in `routes/memory.py`, the
single call site; tests in `tests/test_session_summary_opt_in.py`):

1. **The deployment switch** `AGENT_MDX_SUMMARY_ENABLED=1` — the operator kill-switch. It ships
   **off**: the LLM path is live in prod (the token is vault-served), so a default of ON would
   start shipping library content the moment this deploys. Turning it on is a deliberate env change.
2. **The pushing human opted in** on their own account. Summaries are **opt-in per user** (owner
   decision 2026-09-29). The default for every account is **not opted in**; consent is never
   inferred — not from the switch, not from a plan, not from an earlier push. A push with no
   human behind it (a machine / emit / admin token) has no consent and gets no summary.

What is sent, to whom, and why (the copy the account toggle shows): a short *scrubbed* excerpt of
the session — the first request(s) and the final answer, capped at `AGENT_MDX_SUMMARY_MAX_CHARS` —
to an LLM through the a4sx fleet-router, to produce a one-line summary shown only in the
user's own private library.

| Route | Meaning |
|---|---|
| `GET /auth/me` (and `GET /accounts/me`) | adds `summary_opt_in` (bool, the caller's own), `summary_opt_in_at` (when it last changed, or null) and `summary_available` (the deployment switch, read-only). |
| `PUT /auth/me/preferences` | body `{"summary_opt_in": true\|false}`. **Session-only** (`ge_sess_`, like `GET /auth/me`): any other token → 401 `not_logged_in`. Acts on the caller's own account only — there is no user id in the path or body; an unknown key (e.g. `user_id`) → 400 `bad_field`, a non-boolean → 400 `bad_field`. Returns the preference view. |

The flag lives on the user record (`summary_opt_in`, `summary_opt_in_at`; `store/users.py`
`set_summary_opt_in`, a JSONL append replayed at boot). It is never in `public_view`, and erasure
(`specs/erasure`) drops it with the rest of the record.

**The push response says why.** `POST /library/push` returns `summary_status` next to `summary`:
`"off"` (deployment switch off), `"not_opted_in"` (no consent), `"generated"`, or `"failed"` (opted
in and switched on, but nothing was produced: router unreachable / timed out / errored, or too
little conversation to summarize). A deduplicated no-op push (200) carries neither field.

**Opting out** stops generation from the next push on. Summaries already generated **stay**: they
live on the user's own entries in their private library, visible to nobody else. An `--into` push
by a user who is not opted in keeps the entry's previous summary and generates no new one. (To
remove one, delete the entry or erase the account.)

**Not public copy.** The auto-summary is a **Library-only** fallback. It is deliberately NOT the
abstract fallback on a marketplace listing: that is public copy the author never saw. An author
who wants a line there writes a `description` or `abstract` in the Sell flow.

**No backfill:** there is no sweep over existing sessions. A summary appears for a session only
from its next push by an opted-in user (`--into` regenerates it; a plain `/meta` edit keeps the
one it has).

### 2.3 Folders (additive, 2026-10-23)

A saved session may carry ONE folder path, set by its user. It is stored as the tag `folder:<path>`
in the collection manifest (next to `label:`) and is never derived from the transcript.

- **Path.** 1 to 4 segments joined by `/`. Each segment is 1 to 40 characters of `[A-Za-z0-9 _.-]`
  after trimming spaces, and is neither `.` nor `..`. No leading or trailing `/`, no empty segment,
  at most 120 characters in total. Case is kept and compared as is. An invalid path is refused, never
  repaired.
- **Set / clear.** The caller's credential is checked first (a key without `library:organize` gets
  403 whatever the body). `POST /library/session/{cid}/meta` with `"folder": "work/a4sx"` sets it;
  `"folder": null` or `""` clears it; no `folder` key leaves it as it is. An invalid path answers
  `400 bad_folder` and changes nothing.
- **Tags.** Only `folder` changes the folder. Editing `tags` keeps it, and a tag the caller sends
  never becomes a folder tag (a sent tag starting with `folder:`, after sanitising, is dropped).
  Re-pushing, `--into` and `/scrub` keep it.
- **Read.** `GET /library/sessions` rows, the session detail and the `/meta` reply carry
  `"folder": "<path>" | null`; the raw `folder:` tag stays in `tags`. With several `folder:` tags
  (legacy user tags), the first valid one counts and invalid ones are ignored; the next `/meta` edit
  keeps only that one. The MCP `search_sessions`
  library rows carry `folder` too, and its query matches it.
- **Private.** `publish-to` drops the folder (like the label) from the workspace copy.

## 3. Acquiring a marketplace item — `POST /library/acquire/{cid}` (`library_acquire`)

This copies a marketplace item you are **entitled** to into your library as a private, resumable
base. `{cid}` is a **collection** (its session member is copied) or a **bare session** listing
(synthesised as a one-member collection, so the copy, the scrub and the provenance are identical).

- The same entitlement gate as the bundle applies: a priced item without entitlement gets **402**.
  A collection is gated by `_require_entitlement_collection` (store + manifest price, visibility) at
  your **pinned** version (`specs/collection-versions`); a bare session by `_require_entitlement`
  on `kind=session` at the served version.
- A collection of memories only is reading material. The answer is **409 `memory_only`**, with pointers
  to `/memory/collections/{cid}/bundle` and `/import`. A session without a `.jsonl` gets 400
  `no_transcript`. Both are rejections on purpose: `GET /library/sessions` lists **only** what this
  route stages, so a quiet success for something that cannot be a base is a lie.
- An id that is neither a collection nor a session is **404** `item_not_found`.
- The session transcript is scrubbed and staged as `libacq-<slug>` / `col-libacq-<slug>`. Acquiring
  again adds a new version of the same entry (idempotent per source id — one library row). The copy
  carries `acquired_from {cid, tenant, version}`. This is **provenance only**, not a royalty edge.
- Acquiring records `<kind>.imported` (kind follows the SOURCE: `collection.imported` or
  `session.imported`) and `entitlement.granted{version}` for you.

### 3.1 Client contract (tester bug #8, 2026-09-29)

"Added to your library" may only be said when this route returned 2xx — the Library is exactly the
set of staged copies. An import (`/memory/{kind}/{id}/import`) alone records a consume signal and
grants entitlement but stages **nothing**; a UI that imports and never acquires must not claim the
item is in the Library. An acquire rejection surfaces the server's reason (never a green notice),
and a `memory_only` kit gets an honest note naming the two routes that do serve it.

Three consequences the UI must hold to:

- **Access is not a staged copy.** `has_access` is also true for a memory-only kit after import and
  for an item added on another device. Those say **"imported"**, not "in your library".
- **"use" with no known copy id acquires first.** Re-acquire is idempotent (a new version of the
  same `col-lib*` row), so "use" on an already-accessible item stages/finds the copy and then
  reveals `a4sx launch --a4sx-session <lib-cid>` (the former `amdx launch --agent-mdx-session`
  still works). It must not link to the Library, where such
  an item is not listed.
- **A bare session with no discovery doc fails closed.** Only a public item is in the index, so a
  missing doc makes the synthesised manifest `visibility: private` — the owner and the entitled
  still pass `_require_entitlement`; anyone else gets 402, never a free copy.

## 4. Refunds end the licence (WP-13a) — `_refuse_revoked_copy`

If the purchase behind an acquired copy is **fully refunded or charged back**, the entitlement is
revoked with a dispute id (`store/entitlements.py:revoked_by_refund`). This holds for a copy of a
marketplace **collection** and of a bare **session** listing alike. From then on the copy answers
**410 `license_revoked`** (Terms § 9) on every read path:

- `GET /library/fetch`, `GET /library/session[/{cid}]`, `GET /library/session/{cid}/version/{ver}`
  (and so every MCP tool, which reads through these);
- the generic per-tenant reads of the copy's items in the personal library —
  `GET /memory/sessions/{sid}/{version}[/{path}]?tenant=<personal>` (also `?t=`), the collection
  manifest and bundle — at every version (`staging`, explicit);
- bundle hydrate (the member becomes a `license_revoked` stub);
- every write route that goes through `_lib_open` (meta, scrub), `POST /library/push?into=` (no new
  version, no dedup answer) and `publish-to`;
- a **`publish-to` copy in a workspace** made before the refund, for every reader there. It records
  the publishing user (`acquired_by`); an older copy without it rests on the workspace's
  owners/admins, the only roles that may publish there.

**Per entitlement:** the refund ends the licence that was refunded, not another one. While the
holder still has the item through a live workspace licence (#773: a `tenant:` grant of a workspace
they belong to, or membership of the seller workspace), the copy stays readable. A workspace
licence counts only for the **major** line it covers, like a personal entitlement: a v1 licence
does not keep a copy of v2 readable. A membership whose workspace has no tenant record does not
count (fail closed). A refunded buyer who later **joins the seller's workspace** can read the copy
through that membership, like any member: membership is the seller's consent (accepted by the
coordinator, 2026-10-05).

All of them use one predicate, `collector/libacq_refund.py` (library routes: the copy's manifest;
generic reads: `item_tombstone`, which covers `col-libacq-*` / `libacq-*` items in any tenant,
checks the library owner's (or the workspace publisher's) licence, and fails closed across every
stored version). A read with no refund on record for that user reads no manifest (O(1)); otherwise
the copy's sources are parsed once per stored version set and cached.
Listing the copy (metadata only) stays possible, so it can be found and deleted.

Deleting the copy is still allowed. The versions stay in storage. If the platform later **wins**
the chargeback, the entitlement is granted again and the copy works again. A partial refund does
not revoke. Operators can switch the tombstone off with `AGENT_MDX_REFUND_TOMBSTONE=0` (default on),
which is gated on owner question Q2.

**A kit refund (#1091).** A copy of a bare **session** acquired through a kit (the kit is recorded
on the copy as `acquired_from.via_kits`) is covered by that kit's refund too. A copy made before
`via_kits` was recorded counts every kit that lists the session as a possible basis; when the only
one was refunded and nothing else licenses the copy, it is revoked (fail closed). A live grant on
the session itself, on another kit listing it, or a workspace licence keeps it readable.

### 4a. A copy made under a rental ends with the rental (#1081) — `_refuse_lapsed_copy`

Checkout stages a library copy for rentals as well as purchases. A copy is licensed only while its
holder has a **live** licence for the item it was copied from: their own grant on it, a grant on a
kit that lists it, or a workspace licence (the #773 basis, `collector/libacq_rental.py`). When the
holder's grant has **lapsed** (a rental ran out) and nothing else licenses the copy, it answers
**402 `rental_ended`** on the same read paths as §4 (the `publish-to` copy too, unless the workspace
holds its own licence). It is decided at read time: re-renting or buying makes the copy readable
again with nothing written, and copies made before this change are covered the same way.

- **A fork of a copy is covered like the copy.** The resume flow (launch from the copy, work, push
  a new entry with `?parent=`, or MCP `publish_session` with a parent) stamps the copy's source on
  the fork as `derived_from` ({cid, tenant, version, via_kits?, copy}); a re-push of the same entry
  keeps it, and publish-to carries it (with `acquired_by`) into the workspace. A fork made before
  this is found through its `parent` chain (a lineage deeper than 32 hops answers 402
  `lineage_unknown`: fail closed). Deleting an entry first stamps its source onto its unstamped
  descendants and their workspace copies, so erasing a copy never makes an older fork readable.
  The refund gate (§4) uses the same provenance, so a refund ends forks too.
- A wrapping collection's bundle and `POST /memory/scrub-preview` check every member the same way
  (an ended member is a `rental_ended` stub in the bundle; scrub-preview refuses).
- A rental withdrawn by a plain (non-refund) revoke counts as ended, so a revoke never turns an
  ended rental's copy back on; a later grant lifts it.
- A copy of an item that is **free and public now** stays readable.
- The library listing keeps the row (to re-rent or delete it), withholds its `summary` and adds
  `licence: {status: "ended", reason: "rental_ended", expired_at}`.
- A copy whose holder has no grant record on the item at all is not a rental copy: §4 and #773
  decide it, unchanged.
- Global admins are not refused. Operators can switch the gate off
  with `AGENT_MDX_RENTAL_COPY_GATE=0` (default on).
- `ops/prod/audit-rental-copies.py` (read-only, ids only) lists the copies whose only licence is an
  expired rental, a rental that #1058's bug made permanent, or a refunded kit.

## 5. Publishing to the marketplace — `POST /library/session/{cid}/publish-to/{tenant}` (`library_publish_to`)

- The target must be a **paid seller tenant you own or administer** (`eligible_publish_target`), else
  403 `forbidden_publish`. `GET /library/publish-targets` lists them.
- The route copies the session and a **public-visibility staged draft** into that tenant. It does **not**
  list it. Pricing, sign-off and promote happen in the Sell cockpit (`specs/marketplace-core` §2).
  Your library copy is untouched.
- `acquired_from` is carried into the seller copy. If the source was acquired, the response includes a
  `builds_on_hint`. You must declare that lineage yourself, and the relisting guard enforces it at
  price-set and promote (`specs/marketplace-core` §5).

## 6. Retention

Library content is event-sourced like all items. The general event window applies
(`collector/retention_policy.py:EVENTS_DEFAULT_DAYS` = 3653 days). A deleted entry keeps its history
until an erasure (`specs/erasure`) or account deletion removes it.

## 7. Scoped library tokens (v0.3)

The full description is `docs/library-tokens.md`. Summary of the contract:

| Scope | Routes |
|---|---|
| `library:read` | `GET /library/sessions`, `GET /library/fetch`, `GET /library/session`, `GET /library/session/{cid}`, `GET /library/session/{cid}/version/{ver}` |
| `library:publish` | `POST /library/ensure`, `POST /library/push` (always private and staged) |
| `library:acquire` | `POST /library/acquire/{cid}`, `GET /library/fetch` (without `library:read`: acquired entries only) |
| `profiles:read` | `GET /library/profiles`, `GET /library/profile` (additive, 2026-10-23). An allow-list only (name, model, harness, use_router, base_url as scheme://host[:port], two common headers, known harness flags), each value through a secret filter; everything else is left out, counted in `hidden_fields` |
| `profiles:write` | `PUT /library/profiles/{pid}`, `DELETE /library/profiles/{pid}` (and `POST /library/profiles/{pid}/default`, which answers a key `409 needs_signin`). A key changes only `name` and `model` and creates at most 10 profiles per user (`429 profile_limit`); every other field, flags included, is read-only (`409 needs_signin`, `409 base_url_needs_signin`) and kept byte for byte; it never makes a profile the default, never deletes the default or a profile holding anything but a name and a model (`409 needs_signin`); deleting an unknown profile is `404 no_such_profile` and writes nothing; every 409 is audited as `launch_profile.change_refused`; each write as `launch_profile.changed` (field names only) |
| `library:organize` | `POST /library/session/{cid}/meta` (title, label, tags, description, folder) |

- **Mint:** `POST /accounts/me/tokens` with your own session. Body `{label?, scopes, expires_in_days?}`.
  Every token expires: `expires_in_days` is an integer from 1 to 365 and defaults to 90; `null` is
  refused (`400 bad_expiry`). The same rule applies to the device login. Reply 201 with the token **once**, plus
  `{id, label, kind:"scoped", scopes, issued_at, expires_at, ...}`. Only a SHA-256 hash is stored.
- **List:** `GET /accounts/me/tokens` adds `kind` (`scoped` | `retrieval`) and `scopes` to each row.
- **Revoke:** `POST /accounts/me/tokens/{id}/revoke`. It takes effect on the next request.
- **Device login:** `POST /auth/cli/start {"token_type":"library", "scopes"?, "label"?,
  "expires_in_days"?}` echoes `token_type` and `scopes`. Once approved, `GET /auth/cli/poll` returns
  `{status:"ok", token, token_type:"library", token_id, scopes, expires_at}` and creates **no**
  session. Default scopes: `library:read` + `library:publish` (never the profile or organize scopes). Without `token_type` the flow is
  unchanged and returns `{session}`.
- **Refusals:** any other route answers `403 insufficient_scope` with `details.required_scope` (the scope
  that would allow it, or `null`) and `details.token_valid: true`. A route that accepts only a
  session answers `401`. A revoked token gets `401 auth_invalid`, an expired one `401 token_expired`.

## 8. Open

1. ~~**Tombstone bypass.**~~ Closed: the detail routes check the tombstone, and the generic
   `/memory/sessions/…?tenant=<personal>` reads and bare-session copies are covered too (§4).
2. `library_acquire` also grants an entitlement for **free** collections (see `specs/marketplace-core`
   §8). The `_refuse_revoked_copy` docstring assumes free imports never have a grant.
3. Plan WP-14 asked for the CLI message on `memory_only` and a "resumable only where
   `has_transcript`" wording in /orient. Both belong to the CLI and copy owners, and this spec does not verify them.
