Repository navigation
feat(import): scan agent cli homes and preview their threads - #309
Merged
Merged
Conversation
nixuuu
force-pushed
the
feat/cli-import-1
branch
4 times, most recently
from
November 7, 2026 02:03
49955b9 to
fc45cae
Compare
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
force-pushed
the
feat/cli-import-1
branch
from
November 7, 2026 02:43
fc45cae to
5521a5a
Compare
nixuuu
marked this pull request as ready for review
November 7, 2026 03:23
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.
This was referenced Nov 13, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stage 1 of 5 of the CLI import (stack A, threads). Design:
docs/import.md.What it ships
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).ScanImportSourcesbehind capabilitycli_import_v1(WORKER_LINK_PROTOCOLstays 1); UIScanImport,ListImportCandidates. Not routed to linked computers. Mobile hides the section (its own view comes with stack C)./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)
Review fixes
O_NOFOLLOWopen, inode recheck and descriptor-path check (scanners, indexes, companion files).envblocks, Claudesettings.json/settings.local.json, Groksettings.json), not only login files.envsecrets are masked.Re-check fixes
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
Round 5 fixes (structural)
masking.ts,secret-matcher.ts):BEGIN/ENDmarkers; aBEGINwithoutENDmasks the rest of the field;\",\\,\/,\n…,\uXXXXincl. 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);IMPORT_TOO_MANY_SECRETS, naming none of them.maskText/maskJson/maskedRecord, used by the scan and by every history reader. Scan previews and titles go throughpreviewOf(masker, record, take): the whole decoded record is masked before the prompt or title is taken, trimmed, whitespace-joined or cut.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
ENDmarker withoutBEGINmasks back to the start of the field.maskTextalways ends with the whole-field check, so a masked sibling never skips it.