Skip to content

feat(import): import mcp servers as connected accounts - #318

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

nixuuu merged 1 commit into
feat/cli-import-7from
feat/cli-import-8

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

Stage 8 of the CLI import (stack B, top). Design: docs/import.md ("Serwery MCP").

What

  • Remote MCP servers (Claude ~/.claude.json, user and per-project; Codex [mcp_servers.*]) become custom connected accounts in Connectors. Each keeps its URL and transport and has no access (workers, bots) until the owner grants it.
  • The scan carries the URL, the transport and the secret slots (header name, and whether it is literal or from an env var), never values. Env-var values are never read.
  • A secret moves only on confirmation. For a literal header the owner ticks "Bring the value of {header} from the CLI file" (off by default). Then:
    • the gateway stores the sha256 of a one-time token on the item;
    • it asks the worker (ReadImportSecret, not journaled or replayed);
    • the worker checks the key, the MCP place, the scan digest and the slot kind;
    • the gateway accepts the value only if the token comes back and the stored hash matches. It reads and clears that hash in one transaction, with the run locked.
  • The value goes straight into the account's encrypted credentials (CANOPY_SECRETS_KEY). It never reaches a row, a log, the UI, a worker or a model.
  • Stays out, listed with the reason:
    • stdio servers: the gateway is the only MCP client and runs no processes;
    • URLs with user, password or query;
    • model providers (pointed to Proxies).
  • Undo removes the account unless it changed since (e.g. access was granted), in which case it is kept.

Why

Users' MCP servers are part of their working setup. Making them connected accounts keeps every credential in the gateway, encrypted, with explicit grants, as the security rules require.

Verification

  • tests/integration/import-library-connectors.test.ts (gRPC, real worker):
    • a chosen secret goes from the worker into the encrypted account only, and the account works against a fake MCP server;
    • no value appears in rows, responses or logs;
    • an unticked secret never leaves the worker;
    • a forged or replayed token is refused;
    • only headers with a value can be chosen;
    • stdio servers stay listed only;
    • Undo.
  • Worker tests: MCP parsing for both CLIs, literal vs env slots, the digest check in readImportSecret.
  • Gates on this top of the stack:
    • bun install, gen:check, typecheck, lint and format check: clean;
    • current full-suite results are recorded in “Re-check fixes” below;
    • web build passes;
    • all import integration files green.
  • Original implementation browser check of the MCP rows and the secret checkbox: light and dark, desktop and iPhone SE width.

Copy audit (docs/copy.md §8)

  • New strings:
    • badge "MCP server";
    • outcomes: "New connected account, with no access yet", "Added to Connectors, no access yet." / "… Enter {headers} there.";
    • slot hint: "Authorization: enter the value of {VAR} in Connectors.";
    • checkbox: "Bring the value of {header} from the CLI file. Canopy keeps it encrypted.";
    • reasons: "Runs a command on this computer. Canopy calls MCP servers over the network, from the gateway only.", "Canopy calls MCP servers over HTTP(S) only.", "Its URL may hold a secret (user, password or query). Add it in Connectors.", "The URL is not valid.";
    • errors: "Choose only headers of {name} that have a value in the CLI file.", "The import of this server is not valid. Scan again.", "The worker's answer for {header} did not match this import.";
    • the section description now ends "…skills, marketplaces and MCP servers."
  • Changed during the audit:
    • "Choose secrets of {name} from its headers with a value." → "Choose only headers of {name} that have a value in the CLI file.";
    • "reaches MCP servers" → "calls MCP servers" (one verb in both reasons).
  • Checks: "connected account" and "Connectors" match the glossary; the secret checkbox is off by default and says where the value goes; no error contains a value.

Security review fixes

  • MCP URL credentials (P1): a server URL with user info or a credential-like query is unavailable, as before, and now also masked in detail/value (the single item constructor masks every field). The gateway also refuses such a URL independently.
  • Connector undo race (P2): connectors.remove takes an expected revision. It checks it on the account row locked in the owner-scoped delete transaction and records the item as undone in that same transaction; a changed account stays (kept). Account creation and the item's receipt are also one transaction.
  • Tests (import-library-connectors.test.ts): URLs with user info or ?api_key= are unavailable, and ListImportLibrary carries no part of them. A remove with a stale revision returns changed and the account stays; Undo then marks it kept.
  • connectorWrites header checks moved into a helper (size limit).

Re-check fixes

  • MCP metadata uses the shared WHATWG URL validator, including decoded query/fragment names, unusual HTTPS spellings, long userinfo and malformed credential-bearing URLs. Both gateway candidate and plan boundaries reject unsafe URLs; gateway responses independently redact them. Synthetic worker-to-gateway fixtures cover masked unavailable metadata and the absence of persisted credential URLs.
  • Nested slot names, kinds and environment-variable names now pass through the same masking builder as all other library text. Worker and integration regressions cover known credentials in slot names and variables, including unavailable servers.
  • A changed account's kept receipt now runs inside the owner-scoped transaction that checks its locked revision. A simulated failure after writing that receipt rolls it back; retry records kept while preserving the account. Successful deletion still records undone atomically.
  • Validation: install, generation, typecheck, lint and format check passed. Focused import tests: 107 passed, 3 live tests skipped, 0 failed. The web production build passed. Tests used synthetic HOME/CLI fixtures; Git discovery was capped at the temporary root so uninitialized fixtures could not inherit the worktree's origin. No repository workaround was added.
  • Copy audit (§8): existing unavailable reasons are reused. The additional plan-boundary error says to add the server in Connectors; no values appear in errors. No UI controls or layouts changed; browser checks were not rerun.

Round 3

  • MCP metadata and gateway validation inherit feat(import): import cli defaults and instruction documents #316's single strict parameter classifier. Double/deeper encoded names in query and fragment, malformed encodings, and space/quote userinfo remain masked and unavailable.
  • Synthetic WorkerLink regressions verify masked lists and independently forge worker metadata to check gateway redaction, rejected StartImport and no persisted credential plan. A plain #authentication fragment stays readable and available.
  • Gates: install, generation, typecheck, lint and format check passed. Focused worker/gateway import tests plus all three library integrations: 107 passed, 3 live tests skipped, 0 failed. Tests used synthetic homes with Git discovery capped at the temporary root; no real CLI homes or credentials were read.
  • Copy audit: existing reasons are reused; no UI text, controls or layout changed.

Final targeted fixes

  • Inherits feat(import): import cli defaults and instruction documents #316's conservative authority/value boundaries and unconditional OAuth code classification. The shared matrix is installed as actual MCP configuration and also supplied independently as forged worker metadata.
  • Every case stays masked/unavailable in ListImportLibrary, StartImport rejects it, and SQL verifies no supplied URL enters a persisted plan. Bare documentation fragments stay readable and available. The inherited instruction integration covers scan metadata, instruction_documents, environment API and actual WorkerLink sync for every case, including the valid-host prose sentence.
  • Final bun run check:tmp: 1,695 passed, 161 skipped, 0 failed, nothing left in its temp directory. The web production build passed. All local gates completed in the foreground; only synthetic CLI homes were used.

@nixuuu
nixuuu added this pull request to stack #319 November 7, 2026 03:35
@nixuuu
nixuuu force-pushed the feat/cli-import-8 branch from 99fea5f to 3869cd1 Compare November 7, 2026 09:02
nixuuu added a commit that referenced this pull request Nov 7, 2026
Scheduled Release runs on dev were cancelled when one flaky integration
test failed in a test shard. This PR collects every test failure from
the Release runs and PR CI runs of 2026-11-05 to 2026-11-07, finds the
cause of each, and fixes it deterministically. It adds no retries,
skips, global timeout increases or workflow changes.

Evidence was collected locally: gateway suites ran one file at a time,
mostly pinned to one CPU (`taskset -c 3`). Where a race could not be
forced naturally, a temporary delay was injected at the racing point,
and the same test was run with and without the fix. No injected delay is
committed.

### Fixed here

| Test | Cause | Fix | Before → after |
| --- | --- | --- | --- |
| `worker-ssh-command` › fixed SSH stdin … preserves the gateway and TLS
pin (nightly 42352444980) | After enrollment the installer runs `npm
prefix -g`. The test ran the runner's real npm, which cold-starts Node:
the success path took 0.3–4.1 s on CI (the tampering path, which exits
earlier, takes ~10 ms) and once went over the 5 s test timeout ("killed
1 dangling process"). | A stub `npm` in `$HOME/.local/bin`, which the
installer searches before the system paths. | 20 reruns with 6 busy
loops on the same CPU: mean 211 → 133 ms, max 662 → 314 ms; unloaded
mean 62 → 20 ms. |
| `full-access-mode` › an agent's side thread never gets Full access;
plus `agent-bus` › spawn options (PR CI) and the same race in 3 more
`agent-bus`/`agent-bus-cross` assertions | `spawn_thread` answers once
the side thread is stored. The gateway delivers the `createThread`
command to the worker afterwards, and the tests read `worker.created`
right away (Expected: 4, Received: undefined). |
`ScriptedWorker.createdThread(id)` waits for that command. | With the
worker's `createThread` handling delayed 200 ms: full-access 1 fail → 0;
agent-bus 3 relevant fails → 0; agent-bus-cross 2 fails → 0.
full-access-mode with 10 reruns on one CPU: 30/30. |
| `bots` › an expired lease cannot commit an old model answer (PR #318
CI) | The old gateway's 250 ms queue tick could re-claim the turn whose
lease the test expired before the competitor ticked. The held model then
ran again and the turn never settled (10 s timeout, last message "take
over"). | The old gateway drains, like one handing over: it keeps its
running turn but claims nothing. | With a 300 ms gap before the
competitor's tick: fail (identical error) → 3/3 pass. 10/10 on one CPU.
|
| `lan-routes` › routes are tried in order of last success (PR CI) | The
announcement test left B's withdrawn loopback route `127.0.5.2` in A's
routes. It is the newest route, so A's dial after the dead route
succeeded through it (dumped locally). B's next 1 s advertisement then
withdrew it, and the stale `127.0.0.1` route came first. On CI
`lastSuccessMs` was exactly one hour old, the value the test writes. |
The announcement test waits for the withdrawal and removes the route. |
The CI interleaving was not forced locally; the route dumps show each
step. After: 8/8 file runs on one CPU. |
| `config-sync-environment` › a document, a skill and a plugin arrive on
B (PR CI) | The test waited for the plugin only. A skill stays `WAITING`
until its version blob is fetched, one blob at a time (Expected:
`aeb81c…`, Received: undefined). | Wait for the document, the skill
version and the plugin artifact. | With B's blob fetches delayed 400 ms:
1 pass / 7 fail, the first with the exact CI error → 8/8. 5 runs on one
CPU: 8/8 each. |
| `composer-shell` › Codex steer executes at delivery (PR CI) | A watch
snapshot reads items before steers (`core-watch.ts`). When the
provider's user message item is ingested between the two reads, the
steer shows as delivered without its item. The stream sends the event
right after, so clients converge; the test only reads the first
snapshot. | Wait for a snapshot that has both. | 15 reruns on one CPU:
2/15 and 4/15 failed (the debug dump showed an empty item list) → 15/15.
|
| `schedules-new-thread` › offline pools retry the same occurrence (PR
CI) | A test closed a scripted worker's link while a command was on its
way. The worker loop replied on the closed link, and the `ConnectError`
escaped as an unhandled rejection that failed whichever test was
running. | The scripted worker's loop ends quietly on an unavailable
link. | Throwaway repro (close right after `createThread`, 20
iterations): 10/20 fail → 20/20 pass in 7 consecutive runs. The file
with 3 reruns: 21/21. |
| `worker-ssh` › owner-scoped SSH enrollment trust boundary (PR CI) |
ssh2's ed25519 keygen drops a leading zero byte of the public key (1 key
in 256). It writes a 31-byte public and 63-byte private key that neither
ssh2 nor OpenSSH (`ssh-keygen -y`) can read. The test's server host key
failed with "Malformed OpenSSH private key". | Product fix below; the
test uses the same helper. | `generateKeyPairSync`: 60/20000 and
83/20000 unreadable; `ed25519KeyPair`: 0/20000. worker-ssh 6/6. |

### Product fix (separate commit `fix(gateway): never store an
unreadable ssh install key`)

The gateway generates each owner's SSH install key with the same ssh2
call (`apps/gateway/src/core/worker-ssh.ts`, introduced in #5) and keeps
it until rotation. About 1 owner in 256 got a truncated public key and a
private key that can never be parsed, so every SSH install failed until
they rotated the key. `ed25519KeyPair` generates the pair again when it
does not parse. Keys already stored in that state still need Rotate. The
commit body carries `Fixes: #5`. This PR squashes under a `test:` title,
so that link and the patch release only apply if the fix is split out or
the PR is retitled.

### Already fixed by #262 (no change here)

- `config-sync-execution` › an unreachable home fails immediately…: all
6 failures were before #262 merged (last one 2026-11-06 09:01; #262
merged 10:27), and none since. 8/8 runs on one CPU.
- `remote-threads` › a file attached on A… / a file placed in the text
on A…: a cascade from the first test (worker `created` read without
waiting, thread not settled before the next test held turns). #262 fixed
exactly that, and none have recurred since.
- `computer-relay` › Share onward, `process-governor`, `bots-harness` ›
gateway restart: fixed by #262, and none have recurred since.

### Not flakes

Failures from in-progress feature-branch pushes, not on dev: the CLI
import suites on `feat/cli-import-*`, and the migration list and
error-text failures on `feat/linked-shared-config-7`.

### Gates

`bun install`, `bun run gen:check`, `bun run typecheck`, `bun run lint`,
`bun run format:check`, the web build and `bun run check:tmp` (1671
pass, 0 fail, 162 skip; nothing left in the temp dir) are all clean.

One thing to know: if TMPDIR is inside a Git checkout, `add-project` and
`linked-projects` fail locally, because their "folder without Git"
fixtures inherit the checkout's origin. `check:tmp` above ran with
TMPDIR on disk outside any repository.

Copy audit: no UI text changed.
@nixuuu
nixuuu force-pushed the feat/cli-import-8 branch from 3869cd1 to d47c1d5 Compare November 7, 2026 09:46
@nixuuu
nixuuu force-pushed the feat/cli-import-8 branch 2 times, most recently from c812b8b to c8a8a77 Compare November 7, 2026 10:18
@nixuuu
nixuuu force-pushed the feat/cli-import-8 branch from c8a8a77 to 680bd49 Compare November 7, 2026 10:26
Settings → Import lists the remote MCP servers of Claude Code and Codex
and imports each as a custom connected account with no access until the
owner grants it. A header value moves only for a slot the owner ticks:
the worker reads it on a one-time confirmation and it goes straight into
the account's encrypted credentials. Stdio servers are listed with the
reason they stay out; model providers point to Proxies.

See docs/import.md.
@nixuuu
nixuuu force-pushed the feat/cli-import-8 branch from 680bd49 to 765963b Compare November 7, 2026 10:56
@nixuuu
nixuuu marked this pull request as ready for review November 7, 2026 11:13
@nixuuu
nixuuu merged commit 58a1457 into dev Nov 7, 2026
21 of 26 checks passed
@nixuuu
nixuuu deleted the feat/cli-import-8 branch November 7, 2026 11:13
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.
nixuuu added a commit that referenced this pull request Nov 7, 2026
Stage 7 of the CLI import (stack B). Design: `docs/import.md` ("Skille i
pluginy").

## What
- **Skills:** `skills/<name>/` in the Claude, Codex and Grok homes, and
the device's `~/.agents/skills/`.
- They are read through the confined reader (regular files only, no
links) and text files are masked.
- They are validated by the library rules (`SKILL.md` with name and
description; limits of 1000 files, 1 MiB per file, 25 MiB in total), so
the scan's digest is the checksum the library will store.
- The same skill in several CLIs is one item. Two versions with one name
are both shown, and the gateway accepts one.
- **Commands and prompts as skills:** Claude `commands/**.md` and Codex
`prompts/*.md` get a generated `SKILL.md`. They are unticked by default.
- **Saving:** through `SaveLibrarySkill` (same validation, limits and
audit as an upload), assigned to the source worker's Canopy platform
homes only. Replace adds a new version. Undo removes the skill or
restores the previous full definition, including repository provenance,
unless the definition changed since.
- **Marketplaces:**
- Claude `known_marketplaces.json` and Codex `[marketplaces.*]` (git
over HTTPS) are added as on manual add.
  - Local-directory marketplaces are listed with the reason.
  - Undo keeps a marketplace a plugin was approved from.
- **Plugins** are listed with their version and "Plugins run code.
Approve each one in Agent environment." An import never activates code.

## Why
Skills and commands are the reusable part of a CLI setup. Bringing them
into the Agent environment library makes them available in Canopy
threads with the library's review and audit. Plugins stay a deliberate,
per-file approval.

## Verification
- `tests/integration/import-library-skills.test.ts` (gRPC):
  - a skill shared across CLIs becomes one item;
  - masked file contents;
  - a link or a file outside the home reads nothing;
  - Replace and Undo with versions;
  - marketplace add and Undo;
  - plugins never activated;
  - command → skill.
- Worker tests: skill validation, sorting, version conflicts,
`~/.agents` lock origin.
- Gates on this stage: typecheck, lint, format check, import unit tests
(67 pass), integration file above.
- Current validation is recorded in “Re-check fixes” below and on the
top stage (#318).
- Original implementation browser check: light and dark, desktop and
phone, long skill names and descriptions.

## Copy audit (docs/copy.md §8)
- **New strings:**
- section description: "Defaults for new threads, instructions, skills
and marketplaces. Undo puts back what was there, unless you changed it
since." (extended again in #318);
- outcomes: "New skill for {CLIs}", "New version {version} in Agent
environment", "New version of the library skill", "New marketplace in
Agent environment", "Added to Agent environment as {name}";
  - badge: "Marketplace";
- reasons: "A marketplace on this computer. Add it in Agent
environment.", "Plugins run code. Approve each one in Agent
environment.", "Canopy can't read this kind of marketplace source.",
"Its name can't be a skill name.", "Another version has this name.
Choose one.", "A skill with this name is in Agent environment.", "Canopy
masks {n} possible secret(s) in this skill.";
- errors: "Choose one version of {name}.", "A skill named {name} is in
Agent environment. Scan again.";
  - generated description: "Imported {command|prompt} /{name}".
- **Checks:** reasons name the next action; glossary terms ("skill",
"marketplace", "plugin", "Agent environment") are used throughout; no
banned synonyms; long names truncate.



## Security review fixes

- **Non-UTF-8 skill files (P1):** fail closed. A skill with any file
that isn't UTF-8 text (another encoding or binary) isn't imported, and
its reason names the file. Nothing of it leaves the worker (reading it
by key is refused).
- **Marketplace URL credentials (P1):** a source with user info or a
credential-like parameter is listed masked and marked "Its URL holds a
credential…". The gateway independently refuses any marketplace whose
source still shows user info or masking, before any plan is stored.
- **Skill undo (P2):** the receipt stores a fingerprint of the whole
skill definition: version, harnesses, selector and per-machine
overrides, homes, source. Undo keeps the skill if any of it changed, not
only the version.
- **Receipts:** skill and marketplace saves and removals take the same
in-transaction receipt as #316.
- **Tests:**
- `library.test.ts`: a Latin-1 `config.env` with a known credential
blocks the skill and its read; marketplace URLs with `?token=` and user
info are masked and unavailable.
- `import-library-skills.test.ts`: an assignment change at the same
version keeps the skill on Undo.

## Re-check fixes

- Marketplace URLs use the shared WHATWG credential check. The gateway
independently checks decoded parameter names and canonical userinfo,
including unusual HTTPS spellings and long userinfo, before plan
insertion. Gateway responses also redact credential URLs independently
of worker masking. Worker fixtures and the gateway integration
regression cover `%74oken`, each authority variant, masked responses and
absent plan rows.
- Skills containing NULs or binary controls are refused as a whole,
including BOM-less UTF-16 ASCII. The reason names the file; read-by-key
also refuses it. Worker fixtures cover UTF-16 and binary controls; the
integration test confirms no artifact is saved.
- Replace receipts save the previous full skill definition. An internal
owner-scoped restore path restores repository/ref/path/commit,
credential association and update policy with the Undo receipt in one
transaction. The fingerprint covers every source field, including
`autoUpdate` and `credentialAccountId`. Regressions verify the restored
source/artifact, receipt-failure rollback, all source fields and the
existing assignment-change guard.
- Validation: install, generation, typecheck, lint and format check
passed. Worker/gateway import tests and both stage integration files: 98
passed, 3 live tests skipped, 0 failed.
- Copy audit (§8): the unavailable marketplace reason is reused; the
plan boundary error says to add the marketplace in Agent environment.
Binary-file reasons name the file and the same action. No controls or
layouts changed; browser checks were not rerun.

### Round 3

- Marketplace checks inherit #316's shared bounded decoder: `%2574oken`,
deeper encoding and malformed escapes are unavailable and redacted.
Worker fixtures verify masked scan metadata; the gateway regression
independently verifies masked lists, rejected StartImport and no
persisted credential plan.
- A benign repository URL with `?design=compact#authentication` stays
readable and available in both worker metadata and gateway lists.
Classification uses actual `name=value` pairs and whole credential-name
tokens.
- Gates: install, generation, typecheck, lint and format check passed.
Worker/gateway import tests plus both stage integrations: 98 passed, 3
live tests skipped, 0 failed. Copy audit: existing reasons are reused;
no UI text, controls or layout changed.

### Final targeted fixes

- Inherits #316's conservative authority/value boundaries and
unconditional OAuth `code` classification. Multiline/quoted userinfo,
spaced/quoted query values and code values containing dots are masked
and unavailable.
- The same synthetic matrix is exercised in actual worker marketplace
scan metadata and independently forged gateway metadata.
ListImportLibrary stays redacted, StartImport rejects every case, and
SQL confirms that none of the supplied URLs enters a persisted plan. The
benign documentation query/anchor remains readable and available.
- 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