Skip to content

feat(import): import and continue grok sessions - #313

Merged
nixuuu merged 1 commit into
feat/cli-import-4from
feat/cli-import-5
Nov 7, 2026
Merged

nixuuu merged 1 commit into
feat/cli-import-4from
feat/cli-import-5

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

Stage 5 of 5 of the CLI import (stack A, top of the stack). Design: docs/import.md.

What it ships

  • Grok history from the session's ACP log (updates.jsonl) through the adapter's own GrokEventMapper, with full tool updates (input, output, diffs, status); turns open at the user's prompt chunks and end at turn_completed (end_turn / cancelled / other). Interactive sessions that log no prompts still form turns. Without an ACP log, chat_history.jsonl gives prompts, answers and tool calls with results. Sessions without any conversation are listed as empty; an import that yields no turn leaves no empty thread ("Nothing to import").
  • Native continue for Grok: the session directory (without lock files) is copied into the instance's durable sessions root; the thread resumes it with session/load. Undo removes the copy.
  • All three agent CLIs are importable; the interim "not supported yet" state is gone.
  • Deviation from the design: history is read from the ACP log through the live mapper instead of replaying session/load in a helper process — same result, no CLI process on user data.

Tests

  • apps/worker/src/import/grok-history.test.ts: fixture turns, terminal command with output, reasoning, stable ids across page splits; interactive session without prompts (turn_completed boundaries, cancelled turn, broken line); chat-history-only session.
  • apps/worker/src/import/grok-resume.test.ts: the real Grok CLI loads the copied session over ACP against the fake endpoint; the request carries both earlier prompts and an answer.
  • tests/integration/import-grok.test.ts (fake ACP agent, now also loading the real session layout): history with command and output, untouched sessions; native import with copy and session/load on a Canopy turn.
  • Live (CANOPY_LIVE=1): a session made with the real grok -p learns a code word, is imported and loaded in Canopy; the real model answers with the word. Passed on this machine.
  • Top-of-stack gates: bun install, gen:check, typecheck, lint, format:check, check:tmp, web build, bunx expo lint.

Copy audit

New strings: "Nothing to import" (item warning). Removed: "Not supported yet".

Review fixes

  • Grok history files are read through the confined reader (a linked chat_history.jsonl reads nothing).
  • The native copy is the session as scanned: the ACP log up to the snapshot and the chat history up to the same turns, plus the metadata files session/load needs, masked, through the same writer and manifest; a session without chat history continues in a new thread.
  • Tests: a prompt appended after the scan stays out of the copy; linked history; the real Grok loads the copy.

Re-check fixes

  • F5: the scan records a separate snapshot of chat_history.jsonl (size and first bytes); the native copy cuts both the ACP log and the chat history at their own snapshots, so neither a later prompt nor a longer answer gets in; without that snapshot the thread continues in a new one. Tests: a later prompt and a later answer stay out; a scan without the chat-history snapshot falls back.
  • F6 (Grok): an answer that grew after the import gets a new event when the last turn is read again; test included.

Round 3 fixes

  • Grok readers no longer cut text before masking (H1).
  • M3: a Grok copy is identified by both snapshots (ACP log and chat history); a copy from another scan is never reused. Test: an older scan after a newer copy makes its own copy again.

Round 4 fixes

  • R1: Grok records (ACP updates and chat history) are masked as decoded values before they become tool calls, diffs or terminal output. Test: a diff of JSON with an escaped secret.

Round 5 fixes

  • The Grok reader masks each record through the single entry point from stage 1 (maskedRecord); scan previews and titles mask the whole record first. Covered by masking.test.ts (all three CLIs) and the stage tests.
  • An empty session at the end of its source is finished, warned and its empty thread removed in one locked transaction (finishEmpty).

Final review fixes

  • Blocker: Grok's streamed prompt, answer and thinking chunks are joined as written and masked once as the whole message (in finish(), with the turn-level joined check), not chunk by chunk. The scan preview joins the first prompt's chunks before masking.
  • apps/worker/src/import/split-secrets.test.ts: a freshly generated RSA key split into its header, a body cut at odd places, and its footer. It sits in Grok prompt/answer/thinking chunks, Grok chat-history content parts, Claude prompt parts and separate entries of one message (text and thinking), Codex content and summary parts, and a native-copy record. No 16 consecutive characters of the key body appear in the scan or the pages (line breaks and JSON escapes removed). All 5 tests fail on the previous code. Also covered: a credential as a JSON key, and an escaped secret next to a masked sibling.
  • The six import integration files ran 3× in a row (foreground, Claude/Anthropic env unset): all green each time.

@nixuuu
nixuuu added this pull request to stack #314 November 6, 2026 22:25
@nixuuu
nixuuu force-pushed the feat/cli-import-5 branch 4 times, most recently from ef76809 to 7c577a0 Compare November 7, 2026 01:00
@nixuuu
nixuuu force-pushed the feat/cli-import-5 branch from 7c577a0 to 822bbae Compare November 7, 2026 02:03
@nixuuu
nixuuu force-pushed the feat/cli-import-5 branch from 822bbae to 5fe8413 Compare November 7, 2026 02:43
Grok sessions become Canopy threads from their ACP log (or chat history)
through the adapter's mapper, and continue natively from a copy in the
instance's sessions root. Every agent CLI can now be imported.

See docs/import.md.
@nixuuu
nixuuu force-pushed the feat/cli-import-5 branch from 5fe8413 to 7ee121e Compare November 7, 2026 03:14
@nixuuu
nixuuu marked this pull request as ready for review November 7, 2026 03:23
@nixuuu
nixuuu merged commit 349b09a into dev Nov 7, 2026
16 of 18 checks passed
@nixuuu
nixuuu deleted the feat/cli-import-5 branch November 7, 2026 03:24
nixuuu added a commit that referenced this pull request Nov 7, 2026
Stage 4 of 5 of the CLI import (stack A). Design: `docs/import.md`.

## What it ships
- **Codex history** through the adapter's own `CodexEventMapper` (the
one live threads use): turns from `task_started` … `task_complete` /
`turn_aborted`, whole items from `event_msg item_completed`, shell calls
and code cells from raw `response_item`s, the prompt as the turn's input
(no echo item). Older rollouts without `item_completed` get messages,
reasoning summaries, shell calls and compaction from `response_item`s
and `event_msg user_message`. Injected context is never a prompt.
- **Native continue for Codex**: the rollout prefix is copied into the
instance's `CODEX_HOME/sessions/YYYY/MM/DD/` (archived rollouts too);
the thread resumes it with `thread/resume` by id. Undo removes the copy.
- Codex threads become selectable on the import page.
- Deviation from the design: older rollouts are read by our own mapping
(tested on a synthetic old-format rollout) instead of a helper
app-server on a copy — deterministic and no CLI process on user data.

## Tests
- `apps/worker/src/import/codex-history.test.ts`: fixture turns, command
with output, reasoning, stable ids across page splits; synthetic older
rollout (messages, reasoning, shell call, compaction, aborted and failed
turns, broken line).
- `apps/worker/src/import/codex-resume.test.ts`: the **real Codex
app-server** resumes the copied rollout by id against the fake endpoint;
the request carries both earlier prompts and the tool output.
- `tests/integration/import-codex.test.ts` (fake app-server, now also
resuming the real rollout layout): history without the prompt echo,
command with output, reasoning, untouched rollouts; native import with
copy and `thread/resume` on a Canopy turn.
- Live (`CANOPY_LIVE=1`): a real Codex thread learns a code word, is
imported and resumed in the private `CODEX_HOME`; the real model answers
with the word. **Passed on this machine.**

## Copy audit
No new UI strings beyond stage 2's (Codex rows reuse the same labels).



## Review fixes

- Codex rollouts use the confined reader, complete-record cursors,
masked copies with the same writer and manifest, and the
provider-checked home lookup.
- Tests: partial trailing record; the real Codex resumes the masked copy
without the secret.



## Re-check fixes

- Codex copies use the staged, identity-checked writer and the anchored
Remove; Remove resolves the home per CLI.



## Round 3 fixes

- Codex reader no longer cuts text before masking (H1).



## Round 4 fixes

- R1: Codex records are masked as decoded values before they become
commands, previews or patches. Test: a shell command and an apply_patch
with an escaped secret in JSON.



## Round 5 fixes

- The Codex reader masks each record through the single entry point from
stage 1 (`maskedRecord`); scan previews and titles mask the whole record
first. Covered by `masking.test.ts` (all three CLIs) and the stage
tests.



## Final review fixes

- Codex writes each message, reasoning item and call whole in one
record; its content parts and summary parts are covered by the joined
check of #309. `split-secrets.test.ts` (in #313) covers a key split
across Codex content and summary parts.
nixuuu added a commit that referenced this pull request Nov 7, 2026
Stage 6 of the CLI import (stack B, settings and library; stack A
#309–#313 is in `dev`). Design: `docs/import.md` ("Ustawienia i
biblioteka").

## What
- Behind capability `cli_import_library_v1`, the scan also lists each
CLI home's settings and library: names, places and digests, with no
contents and no secrets. `ListImportLibrary` compares them with Canopy's
state, `StartImport.library` picks items, and the run applies them
before threads.
- **Settings:**
- Default model of new threads per provider (only when the worker's own
instance offers that model).
- Permission mode of new threads, as one value. An import **never sets
Full access**, and the gateway refuses it whatever the source.
- When the CLIs disagree, nothing is preselected ("The CLIs differ here.
Choose one.").
- **Instructions:** `CLAUDE.md`, and `AGENTS.override.md` or
`AGENTS.md`, become an instruction document in Agent environment.
- It is assigned to the source worker only, and only to Canopy's
platform homes, never to the device's CLI files.
  - `@` imports are not expanded (warning). The limit is 24 KiB.
  - On a name conflict the owner chooses Keep both or Replace.
- **Shown with the reason they stay out:** hooks, status line, `env`,
permission rules, logins, CLI memory, model providers ("Add it in
Proxies, with its key.").
- **Undo** puts back what the import replaced, unless it changed since
(`kept`). Migration `0094_cli_import_library` adds
`import_library_items` (unique live source).
- **Locks:** every write to library items goes through
`importTransaction`, with its run locked first (locks.ts). Multi-step
changes are single transactions.
- **UI:** a "Settings and library" section above the threads.
  - Each item shows what it will change.
  - Conflicts are resolved inline.
  - "In Canopy or not imported" lists the rest with reasons.
- The run row shows the results; "Remove imported items" undoes threads
and settings.

## Why
New threads in Canopy should start with the defaults and instructions
the user already relies on in their CLIs, without copying secrets or
anything that runs code.

## Verification
- `tests/integration/import-library.test.ts` (gateway ↔ worker over
gRPC):
  - defaults applied and undone;
  - Full access never set;
  - the instruction document goes to platform homes only;
  - Keep both / Replace;
  - Undo keeps what changed since;
  - owner scoping.
- Worker library scan tests: masking, `@` warnings, size limits,
confined reads.
- Gates on this stage: typecheck, lint, format check, worker/gateway
import tests (65 pass), integration file above.
- Current validation is recorded in “Re-check fixes” below and on the
top stage (#318).
- The original implementation was checked in a real browser: light and
dark, desktop and phone width, short and long names and paths.

## Copy audit (docs/copy.md §8)
- **New strings:**
- section: "Settings and library", "Defaults for new threads and
instructions. Undo puts back what was there, unless you changed it
since.";
- item labels: "Default model for {CLI}", "Permissions of new threads";
- outcomes: "Default → {model}", "New instruction document", "Added to
Agent environment (as {name})", "Replaced in Agent environment", "Same
in Canopy", "Not imported", "Kept: changed since";
- reasons: "Canopy has no default effort. Choose it in the composer.",
"Hooks run commands. Canopy threads leave them out.", "Canopy shows its
own thread status.", "Canopy asks for approvals with its own rules.",
"CLI memory stays out of Canopy threads.", "Canopy uses the login of
each provider instance.", "Often holds secrets. Set it per provider
instance.", "Add it in Proxies, with its key.", "An import never sets
Full access. Choose it in Settings → Threads.", "The CLIs differ here.
Choose one.", "{file} takes its place in this CLI.", "Canopy
instructions cover Claude and Codex for now.", "The file is longer than
24 KiB, the limit for Canopy instructions.", "The file is empty.",
"Canopy doesn't follow @ imports in this file.", "Canopy masks {n}
possible secret(s) in this file.";
- conflict: "What to do with {name}", "Keep both" / "Replace", "Choose
Replace or Keep both for {name}.";
  - dialog: "Remove imported items?" + "Remove imported items";
- errors: "Choose at least one thread or setting to import.", "Some of
these settings are imported already. Scan again.", "Some settings
changed since the scan. Scan again.", "Update the worker on {worker} to
import its settings.", "The worker did not return the file.", "The
document was not saved.";
  - empty states: "No settings found.", "Nothing new to import.".
- **Checks:**
  - Every reason says why and, where there is one, what to do instead.
  - Buttons start with a verb.
  - Confirmations repeat the title's verb.
- Glossary terms are used throughout ("worker", "Agent environment",
"instruction document", "provider instance").
  - Long names, models and paths truncate cleanly at every width.



## Security review fixes

- **URL credentials (P1, masking part):** the shared masker now finds
credentials in any URL in linear time: user info (`scheme://user:pass@`)
and values of credential-named parameters (`token`, `key`, `secret`,
`auth`, `sig`, `code`, …). The rest of the URL stays readable. It
applies to threads and to every library item: all text fields (name,
value, detail, reason, warnings) go through the single masking entry
point, including items shown as not importable.
- **Codex permissions (P2):** sandbox and approval policy map together.
`untrusted` and structured policies are unavailable because Canopy has
no mode preserving their approval gates. `workspace-write` +
`on-request`/`on-failure` → Accept edits, + `never` → Full auto; unknown
values import nothing; Full access never.
- **Mutation and receipt (P2):** the settings store and Agent
environment take an optional `receipt`. It records the item's state and
undo receipt through `importTransaction` as the last step of the store's
own transaction (lock order: store row, then run). Worker sync stays
after commit. A receipt with no item to land on rolls the change back.
Undo's restore and the item's new state commit the same way.
- **Retryable undo (P2):** the run stays `undone`. A library item whose
restore fails stays `done` with the reason, and a later Undo (the button
shows again) retries only those items.
- **Hardening:** known credentials are also collected bare: without
quotes, without `Bearer`/`token` prefixes, and for `Basic` the decoded
`user:password` and the password.
- **Tests:**
- `import-library.test.ts`: an undo whose receipt can't land is rolled
back; a failed undo keeps its item and the next Undo finishes it.
  - `library.test.ts`: the Codex mapping table.
- `masking.test.ts`: bare forms of `Bearer`/`Basic`/quoted credentials;
URL credentials.

## Re-check fixes

- Shared URL masking now uses the WHATWG parser and decoded parameter
names and values. Encoded credential parameters (including secrets in
names), single/no-slash HTTPS, tabs, prefixed URLs, backslashes, long
userinfo, SSH and scp-style git sources are covered; ambiguous URLs fail
closed. `masking.test.ts` exercises unknown synthetic credentials as
well as encoded known values.
- Codex `untrusted` and structured approval policies are unavailable,
including active-profile overrides. Worker regressions cover the
mapping; `import-library.test.ts` confirms these candidates cannot enter
a gateway plan.
- Empty-user Basic authentication also contributes the decoded password
to masking, with the existing minimum-length filter. Covered in
`masking.test.ts`.
- Validation: `bun install`, `gen:check`, `typecheck`, `lint`,
`format:check` passed. Worker/gateway import tests plus
`import-library.test.ts`: 84 passed, 3 live tests skipped, 0 failed.
Malformed URLs fail closed and safe git shorthand stays readable.
- Copy audit (§8): no new controls. Structured policies now show
“Unsupported permission policy” with the existing unavailable reason; no
policy contents or credential values enter the text. No layout changes;
browser checks were not rerun for this fix.

### Round 3

- Authority inspection precedes token extraction. An invalid authority
token without `@` masks from the scheme through the next `@` in the
field, across any number of lines; without an `@`, it masks through the
line's end. Valid hostnames and numeric ports establish a safe boundary,
preserving prose containing a later contact address. Percent-encoded
spaces remain covered. Tests exercise prose, Markdown links/code, JSON
and malformed authorities.
- One shared parameter classifier strictly decodes names and values up
to four times. Malformed UTF-8/escapes or unresolved encoding are
credential-bearing, including malformed escapes revealed by another
layer. Only `name=value` pairs count; credential names match whole `_`,
`-`, `.`, camelCase tokens. Every `code` value is a credential,
including short values, words and dots. Known secret values are checked
at every decoded layer. Ordinary documentation/repository URLs, bare
anchors and noncredential parameters stay unchanged.
- The gRPC regression imports ambiguous URLs through CLAUDE.md and
verifies instruction storage, the environment API and actual payloads
received by the worker contain no canary. Masking regressions cover
double/deeper encodings and false positives.
- Gates: install, generation, typecheck, lint and format check passed.
Worker/gateway import tests plus this stage's integration: 84 passed, 3
live tests skipped, 0 failed. Copy audit: no UI text, controls or layout
changed.

### Final targeted fixes

- Broken userinfo boundaries follow the conservative authority rule,
including quotes followed by LF/CRLF and distant `@` characters. An
invalid host token without `@` masks to the end of its line. The
valid-host sentence `See https://docs.example.test (contact
[email protected]).` stays readable.
- Credential parameter values are scanned beyond token delimiters to
`&`/`#`. Spaces, quotes and backticks mask through the end of the line;
line breaks fail closed through the field. Every OAuth `code` value is
sensitive, including readable words, short numbers and dots; the entropy
heuristic is removed.
- A shared synthetic matrix covers each boundary in Markdown, code spans
and JSON, worker scan titles/previews, ListImportLibrary,
instruction_documents, the environment API, persisted plan rows and
actual WorkerLink sync payloads. The prose sentence is also checked
through storage, API and worker sync.
- Polish import documentation describes these rules. No UI copy,
controls or layouts changed.
- Final stack gate on #318: `bun run check:tmp` passed (1,695 passed,
161 skipped, 0 failed; nothing left in its temp directory), and the web
production build passed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant