Skip to content

feat(import): scan agent cli homes and preview their threads - #309

Merged
nixuuu merged 1 commit into
devfrom
feat/cli-import-1
Nov 7, 2026
Merged

nixuuu merged 1 commit into
devfrom
feat/cli-import-1

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

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

What it ships

  • Settings → Code → Import: choose a worker of this computer, scan, and see per agent CLI (Claude Code, Codex, Grok) the threads, size on disk, directories and date range.
  • Thread list grouped by directory, with filters (agent CLI, last activity 7/30/90 days or all time, title search, subagent threads), select all that match or single rows, a storage estimate, and a suggested target per directory (existing project workspace or new project; "Directory no longer exists" for missing ones).
  • Worker: read-only scanners (head and tail reads, no CLI process, no SQLite), roots taken only from the worker's own config (device CLI homes and instance home_path), signed source keys (HMAC with a worker-local key, path confinement, no symlinks), masking of secrets in titles and previews (exact values from CLI credential/MCP files plus distinctive token formats).
  • Contracts: ScanImportSources behind capability cli_import_v1 (WORKER_LINK_PROTOCOL stays 1); UI ScanImport, ListImportCandidates. Not routed to linked computers. Mobile hides the section (its own view comes with stack C).
  • Fixtures generated by the real Claude Code 2.1.308, Codex 0.164.0 and Grok 1.0.70 against a local fake model endpoint, sanitized to /home/user (apps/worker/src/import/fixtures/generate.ts).

Tests

  • apps/worker/src/import/scan.test.ts: all three CLIs, untouched homes (content and mtime fingerprint), no conversation content in the scan, masking (another CLI's token, sk-ant- format), synthetic edge cases (broken and cut lines, empty file, newer version, missing directory, symlinked file outside the root, summary-only Grok dir), forged and foreign source keys, a symlink planted under a signed path.
  • tests/integration/import-scan.test.ts: scan over the worker link, filters, groups, project suggestions, canary secret absent from responses, refusals (another owner's worker, worker without the capability, expired scan, offline worker).

Copy audit (docs/copy.md §8)

  • New strings: "Import", "Bring threads from Claude Code, Codex and Grok into Canopy. Canopy only reads the CLI files.", "Scan" / "Scan again", "Looking for Claude Code, Codex and Grok data…", "Found on {worker}", "The scan stopped at its limit. Some threads are not listed.", "Threads" + "Choose the threads to import. Each directory maps to a project.", filters ("Search titles", "Subagent threads", periods), "{n} of {total} selected", "About {size} in Canopy", "No threads match these filters. Choose a longer period or another agent CLI.", badges ("Imported", "Already in Canopy", "History only", "Secrets masked"), errors ("{worker} is offline. Start it, then scan again.", "Update the worker on {worker} to import its data.", "The scan expired. Scan again.").
  • Glossary: "thread" (never "session"), "worker", "directory", "agent CLI". Changed during the audit: the picker's accessible label "Computer" → "Worker" (it lists workers).
  • Buttons start with a verb; every error says what happened and what to do; one idea per sentence; no colour-only cues (badges carry text, history reason in a tooltip).
  • Checked with short, typical and very long titles, paths and worker names at desktop and phone width, light and dark.

Review fixes

  • Every source read is confined to its CLI home: no link below the root or at the file, O_NOFOLLOW open, inode recheck and descriptor-path check (scanners, indexes, companion files).
  • Masking also collects credential-like values from settings files (env blocks, Claude settings.json/settings.local.json, Grok settings.json), not only login files.
  • Tests: linked project/session dirs and companion files read nothing; settings env secrets are masked.

Re-check fixes

  • F9: the confined reader refuses anything but a regular file before opening it (FIFOs, devices), opens with O_NOFOLLOW | O_NONBLOCK, and checks the opened descriptor is the same regular file. Test: FIFOs at a session name and at a credentials name don't hold the scan.

Round 4 fixes

  • Found while auditing R1: the masker also matches each known secret in the forms JSON text gives it (escaped once and twice), so a secret inside JSON pasted into other text (a command line) is masked. Token formats are matched in one pass.

Round 5 fixes (structural)

  • Masking is rebuilt instead of patched (masking.ts, secret-matcher.ts):
    • known values (and their once/twice JSON-escaped forms) are found by one Aho–Corasick automaton in a single linear pass;
    • token formats by a linear scan over token-character runs (no backtracking regex), PEM keys by pairing BEGIN/END markers; a BEGIN without END masks the rest of the field;
    • every field is also checked in decoded views (JSON escapes \", \\, \/, \n…, \uXXXX incl. surrogate pairs, undone up to 3 times). A secret found only there can't be mapped back, so the whole field becomes [hidden: contained a credential] (fail closed);
    • at most 10,000 known values; more fails the command with IMPORT_TOO_MANY_SECRETS, naming none of them.
  • One entry point: maskText / maskJson / maskedRecord, used by the scan and by every history reader. Scan previews and titles go through previewOf(masker, record, take): the whole decoded record is masked before the prompt or title is taken, trimmed, whitespace-joined or cut.
  • Tests (masking.test.ts): a secret with a quote, backslash and non-BMP char in 9 JSON encodings inside commands, diffs and nested JSON; decoded-only hits hide the field; unclosed PEM; the value cap; Claude/Codex/Grok titles and previews with a tab/double-space secret and an escaped one; adversarial 1 MiB (unclosed markers, near-threshold token prefixes, JWT-shaped runs, escapes) with 10,000 known values, two passes under 1.5 s.

Final review fixes

  • Masking within one record checks the record's strings and keys joined by lines in document order (known values and private-key blocks). A secret that crosses from one string into the next hides every string it touches. An END marker without BEGIN masks back to the start of the field.
  • Object keys are masked like values (a credential used as a key no longer survives native-copy masking). The JSON branch of maskText always ends with the whole-field check, so a masked sibling never skips it.
  • The Aho–Corasick root uses an array transition table (160 MB perf session: 2.5 s).

@nixuuu
nixuuu added this pull request to stack #314 November 6, 2026 22:25
@nixuuu
nixuuu force-pushed the feat/cli-import-1 branch 4 times, most recently from 49955b9 to fc45cae Compare November 7, 2026 02:03
Settings → Import lists Claude Code, Codex and Grok threads on the owner's
worker: read-only scan behind the cli_import_v1 capability, signed source
keys, secret masking, filters and directory-to-project suggestions.
Fixtures come from the real CLIs against a local fake model endpoint.

See docs/import.md.
@nixuuu
nixuuu force-pushed the feat/cli-import-1 branch from fc45cae to 5521a5a Compare November 7, 2026 02:43
@nixuuu
nixuuu marked this pull request as ready for review November 7, 2026 03:23
@nixuuu
nixuuu merged commit 1cdf8fa into dev Nov 7, 2026
11 checks passed
@nixuuu
nixuuu deleted the feat/cli-import-1 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