From 629803ce22ea8ee84038a6f3d2da0ecfeb9d2ef0 Mon Sep 17 00:00:00 2001 From: PerryLink <255665900+PerryLink@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:48:29 +0800 Subject: [PATCH 1/3] feat(sync): restore-time cwd projection and symlink diagnostics (#28, #30) - cwdMap projects a cross-OS header.cwd onto a local path at restore time (longest prefix, segment boundary, Windows case-insensitive). Only the local copy's first zstd frame changes; the mirror keeps the origin device's bytes and a push reattaches the original header frame, so appends stay byte-identical across devices. - Unmatched cross-platform cwds land read-only under /--unmapped-- and are counted in sync_status. - sync_status reports skipped/followed symlinks and the new cwd projection counters; push results carry the same warning. - followSessionSymlinks (default false) follows only links whose realpath stays inside sessionRoot. - Auto-push listener registration is logged once at mount so hosts that never deliver session/event are diagnosable. - New lib modules: cwdmap (matching + host-compatible projectKey), sessionlog (zstd header-frame read/rewrite), projection (local projection state). - Tests drive the real @deepseek-ai/dsh-session-persistence-jsonl backend to prove the projected layout passes the host's stored-identity check. --- ARCHITECTURE.md | 13 +- CHANGELOG.md | 13 ++ README.en.md | 27 +++- README.es.md | 27 +++- README.hi.md | 27 +++- README.md | 27 +++- README.pt.md | 27 +++- cordis.patch.yml | 11 ++ index.mjs | 59 ++++++- lib/constants.mjs | 6 + lib/cwdmap.mjs | 248 +++++++++++++++++++++++++++++ lib/encrypted.mjs | 11 +- lib/engine.mjs | 71 ++++++++- lib/mirror.mjs | 316 +++++++++++++++++++++++++++++++++---- lib/projection.mjs | 191 +++++++++++++++++++++++ lib/render.mjs | 19 ++- lib/sessionlog.mjs | 142 +++++++++++++++++ package.json | 1 + pnpm-lock.yaml | 353 +++++++++++++++++++++++++++++++++++++---- pnpm-workspace.yaml | 4 + test/cwdmap.test.mjs | 364 +++++++++++++++++++++++++++++++++++++++++++ types.d.ts | 34 ++++ 22 files changed, 1914 insertions(+), 77 deletions(-) create mode 100644 lib/cwdmap.mjs create mode 100644 lib/projection.mjs create mode 100644 lib/sessionlog.mjs create mode 100644 test/cwdmap.test.mjs diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index ab573c8..881d3ae 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -19,7 +19,10 @@ | `lib/paths.mjs` | Path resolution, nesting checks, and fork-file naming — pure | | `lib/sanitize.mjs` | Pure display/log redaction (remote-URL credentials, tokens, `key=value` secrets, path-containment display) | | `lib/merge.mjs` | Append-only three-way merge classification — pure | -| `lib/mirror.mjs` | Byte mirror from the session store into the worktree (`node:fs`) | +| `lib/mirror.mjs` | Byte mirror from the session store into the worktree, restore back into the live store, and deletion protection (`node:fs`). Projection-aware: projected local copies are skipped as sources and reattached to the mirror's original header frame; `followSessionSymlinks` opts into contained links only | +| `lib/cwdmap.mjs` | Restore-time cwd matching/projection — pure (`cwdMap` longest-prefix + segment boundary, host-compatible `projectKey`, `--unmapped--` fallback) | +| `lib/sessionlog.mjs` | Session-log first frame read/rewrite (`node:zlib`): the header is its own zstd frame, so a projection replaces only that frame | +| `lib/projection.mjs` | Local projection state (`.git/dsh-session-sync-projection.json`): canonical↔projected path pairs, original cwd and header frame; plans restore placement and reconstructs canonical bytes on push | | `lib/git.mjs` | Git command layer: verb whitelist + argument assertions, never force-push/reset/rebase/branch-switch | | `lib/backend.mjs` | Transport backend seam contract + pure `selectEncryptionMode` (backend/mode/warnings selection) | | `lib/age.mjs` | age binary probe (`detectAge`) + file-based `ageEncrypt`/`ageDecrypt` (optional external binary, graceful degrade) | @@ -36,9 +39,10 @@ $DSH_HOME/sessions ──byte mirror──▶ /sessions ──git──▶ custom remote ``` -1. **Mirror** copies each session file as opaque bytes into the worktree (symlinks refused, deletions only for files that vanished at the source and are neither fork files nor host-private artifacts). Host-private artifacts (`session.lock`, the harness session lease, and `session.migration.*.tmp` staging files) are runtime state, not syncable content: the mirror neither copies them in nor deletes them from the worktree. +1. **Mirror** copies each session file as opaque bytes into the worktree (symlinks refused by default, deletions only for files that vanished at the source and are neither fork files nor host-private artifacts). Host-private artifacts (`session.lock`, the harness session lease, and `session.migration.*.tmp` staging files) are runtime state, not syncable content: the mirror neither copies them in nor deletes them from the worktree. With `followSessionSymlinks: true` only links whose `realpath` stays inside `sessionRoot` are read (still never written through), and every skipped link is reported. 2. **Commit** records the mirror as a git commit (plugin identity, never the user's git identity). 3. **Push/pull** move commits to/from the configured remote over `ctx.subprocess`-driven git. +4. **Restore projection (`cwdMap`)** — a cross-OS session's `header.cwd` is not natively absolute on the receiving host, so neither the workspace index nor the JSONL backend can read it. On restore, `lib/cwdmap.mjs` maps the origin prefix to a local path (longest prefix, segment boundary), `lib/projection.mjs` rewrites the **first frame of the local copy only**, and the file lands at `//` — the same formula the host validates. The mirror keeps the origin device's bytes; on push the original header frame is reattached, so the remote sees only the locally appended frames (byte-identical append-only merge, no fork churn). Without a mapping entry a cross-platform cwd goes read-only to `/--unmapped--` (visible, `cwdUnmapped` in status, never a push source) and its mapped directory is created so the host can group it. ## Conflict resolution — never silently overwrite @@ -80,12 +84,15 @@ Auto runs are covered by the config grant and never re-confirm. - **Verb whitelist** in `lib/git.mjs`; `-f`/`--force`/`--force-with-lease`/`+refspec`, `reset`, `clean`, `rebase`, and branch-switch `checkout` are refused. - **Path containment** before any join (`PATH_UNSAFE` fails loud). -- **Symlinks never followed** on either side of the mirror. +- **Symlinks never followed by default** on either side of the mirror. `followSessionSymlinks: true` (opt-in) reads only links whose `realpath` stays inside `sessionRoot`; writes still refuse link targets and escape paths. +- **Restore projection never rewrites the synced bytes.** Only the local copy's first frame changes; the mirror always receives the origin header frame plus the locally appended frames, so cross-platform mapping cannot create meaningless divergence. - **Sanitize before display/log** — remote-URL credentials, tokens, and `key=value` secrets are redacted before reaching the model or the log. - **Bounded subprocesses** — git runs with `GIT_TERMINAL_PROMPT=0` and `GIT_OPTIONAL_LOCKS=0`, deadline- and signal-bounded, with a per-stream output cap. ## Upstream asks (recorded, not implemented) +- **Host-side cwd alias for session indexing.** `dsh-workspace` indexes sessions by `realpath(header.cwd)` and `session-persistence-jsonl` rejects a header whose cwd is not natively absolute, so cross-OS visibility currently requires the plugin to rewrite a local copy of the header and move the file into the projected project directory. A host-level alias/foreign-root mapping (or a `SessionHeader` cwd override at read time) would let the mirror stay byte-identical everywhere and drop the projection state. + - **Session-directory layout version marker.** The mirror maps fork files back to sessions by path shape (`//` plus the legacy flat form). A version marker in the session-directory layout would let a future plugin declare which layout it understands instead of sniffing segment shapes; recorded here per the 0.1.6 adaptation review (P2, no code change requested). ## Backend vocabulary diff --git a/CHANGELOG.md b/CHANGELOG.md index 3de880c..db48b41 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## [Unreleased] + +### Added + +- **`cwdMap`: restore-time cwd projection so cross-OS sessions appear in the host workspace list (#28).** A session synced from another platform carries a `header.cwd` that is not natively absolute on the receiving host, so `@deepseek-ai/dsh-workspace` never indexes it (`realpathNormalize` refuses it) and `session-persistence-jsonl` cannot even parse the header — the bytes arrived but the session stayed invisible. `cwdMap: [{ from, to }]` maps an origin prefix to a local path; the longest matching prefix wins and prefixes end on a path-segment boundary (Windows prefixes compare case-insensitively, so `C:\Users\me2` does not match `C:\Users\me`). Restore rewrites the first frame of the **local copy** only and lands it at `//`, creating the mapped directory; the mirror keeps the origin device's bytes and a push reattaches the original header frame, so the other device still sees byte-identical appends and no meaningless conflicts. Cross-platform cwds with no entry land **read-only** under `/--unmapped--` and `sync_status` counts them (`cwdUnmapped`). +- **`followSessionSymlinks` (default `false`) and symlink diagnostics (#30).** Android/proot `link2symlink` reports host-written session files as symbolic links whose bytes are still readable, so the strict "never follow symlinks" mirror silently dropped every native session. `sync_status` now reports `skippedSymlinks` / `skippedSymlinkPaths` / `followedSymlinks` and push results carry the same warning; opting in follows only links whose `realpath` stays inside `sessionRoot` — links that escape are always skipped and counted. +- The auto-push listener logs its registration once at mount (`auto push listener registered …`), so a host that never delivers `session/event` is diagnosable from the outside (#30). + +### Changed + +- `sync_status` gains `skippedSymlinks`, `skippedSymlinkPaths`, `followedSymlinks`, `cwdMapped`, `cwdUnmapped`, `cwdProjectionSkipped`, `cwdPlaceholder`, and `followSessionSymlinks`; `sync_pull` gains `cwdMapped` / `cwdUnmapped`; `sync_push` gains `skippedSymlinks` / `skippedSymlinkPaths`. All new fields are optional and JSON-safe. +- `@deepseek-ai/dsh-session-persistence-jsonl` joins the devDependencies as a test gate: the projection tests create a session log with a Windows cwd, restore it, and assert the **real host backend** `stat()`/`list()` accepts the projected layout (the host validates `///`, which pins our `projectKey` implementation and directory layout). + ## [0.2.33] - 2026-11-13 ### Fixed diff --git a/README.en.md b/README.en.md index df89e0f..7980da1 100644 --- a/README.en.md +++ b/README.en.md @@ -154,10 +154,12 @@ Most-used keys: | `branch` | `main` | Remote branch name | | `autoPushOnTurnEnd` | `false` | Push after every closed turn | | `pullIntervalMinutes` | `0` | Periodic pull every N minutes (`0` = off, max `10080`) | +| `cwdMap` | `[]` | Restore-time cwd projection `[{from, to}]` (longest prefix wins; unmatched cross-platform cwds go read-only under `/--unmapped--`) | +| `followSessionSymlinks` | `false` | Follow symbolic links whose realpath stays inside `sessionRoot` (Android/proot diagnostics) | | `confirmVia` | `auto` | Confirmation channel: `auto` (userQuestions first, then approval), `userQuestions`, `approval` |
-Full configuration table (21 keys) +Full configuration table (23 keys) | Key | Default | Meaning | |---|---|---| @@ -174,6 +176,8 @@ Most-used keys: | `autoPullOnStart` | `false` | Pull once when the plugin mounts (config is the grant; no re-confirm) | | `autoPushOnTurnEnd` | `false` | Push after every closed turn | | `pullIntervalMinutes` | `0` | Periodic pull every N minutes (`0` = off, max `10080`) | +| `cwdMap` | `[]` | Restore-time cwd projection `[{from, to}]` (longest prefix wins; unmatched cross-platform cwds go read-only under `/--unmapped--`) | +| `followSessionSymlinks` | `false` | Follow symbolic links whose realpath stays inside `sessionRoot` (Android/proot diagnostics) | | `confirmVia` | `auto` | Confirmation channel: `auto` (userQuestions first, then approval), `userQuestions`, `approval` | | `graceMs` | `10000` | Grace period for git kills (ms) | | `commandTimeoutMs` | `120000` | Per-command timeout (ms) | @@ -268,6 +272,27 @@ What it does **not** protect (the boundary): Baseline: with `backend: git` (the default), session bytes are stored unencrypted in **your** git remote — use a private repository. +### Cross-OS sessions and cwd projection + +A Windows session synced to Linux (or the reverse) carries a `header.cwd` that is not a fully qualified path on the receiving host: `dsh-workspace` indexes sessions through `realpath(header.cwd)`, and `session-persistence-jsonl` cannot even parse a header whose cwd is not natively absolute. Map the origin prefix to a local path: + +```yaml +cwdMap: + - from: 'C:\Users\me' + to: /home/me/win +``` + +- The longest matching prefix wins, and prefixes end on a path-segment boundary (`C:\Users\me2` does not match `C:\Users\me`). +- Restore projects only the **local copy**: its first frame carries the local cwd and lands in the host's project directory, so the session shows up in the workspace list. The mirror keeps the origin device's bytes; a push reattaches the original header frame, so the other device still sees byte-identical appends and never gets meaningless conflicts. +- A cross-platform cwd with no entry lands under `/--unmapped--`: **visible but read-only** (`sync_status` reports it as `cwdUnmapped`, and local edits are never pushed). Add a `cwdMap` entry and pull again to turn it into a continuable local session. + +### Symbolic links (Android/proot) + +The mirror **never follows symbolic links** by default (a safety boundary). Android/proot's `link2symlink` reports host-written session files as symlinks (`readdir` says link, `readlink` is empty, the bytes are readable), so the phone's own sessions never reach the mirror. Diagnostics and opt-in following: + +- `sync_status` reports `skippedSymlinks` / `skippedSymlinkPaths` (count and path samples) and `followedSymlinks`; push results carry the same warning. +- `followSessionSymlinks: true` (default `false`) follows only links whose `realpath` stays inside `sessionRoot`; links that escape are always skipped and counted. + ## Known limitations - **Encryption is optional, and age is an external dependency.** `backend: encrypted` adds an age layer (see "Encryption & threat model" above); a missing `age` or empty `ageRecipient`/`ageIdentity` warns explicitly and degrades to plaintext, and a passphrase-protected identity cannot be used (decryption would block on a TTY prompt, so it fails closed). With `backend: git` (the default), session bytes are stored unencrypted in **your** git remote — use a private repository. diff --git a/README.es.md b/README.es.md index 0df2112..521776c 100644 --- a/README.es.md +++ b/README.es.md @@ -154,10 +154,12 @@ Claves más usadas: | `branch` | `main` | Nombre de la rama remota | | `autoPushOnTurnEnd` | `false` | Push tras cada turno cerrado | | `pullIntervalMinutes` | `0` | Pull periódico cada N minutos (`0` = apagado, máximo `10080`) | +| `cwdMap` | `[]` | Proyección de cwd en la restauración `[{from, to}]` (gana el prefijo más largo; los cwd multiplataforma sin coincidencia quedan en solo lectura bajo `/--unmapped--`) | +| `followSessionSymlinks` | `false` | Sigue enlaces simbólicos cuyo realpath permanece dentro de `sessionRoot` (diagnóstico para Android/proot) | | `confirmVia` | `auto` | Canal de confirmación: `auto` (primero userQuestions, luego approval), `userQuestions`, `approval` |
-Tabla de configuración completa (21 claves) +Tabla de configuración completa (23 claves) | Clave | Valor por defecto | Significado | |---|---|---| @@ -174,6 +176,8 @@ Claves más usadas: | `autoPullOnStart` | `false` | Pull una vez al montar el plugin (la configuración es la autorización; no reconfirma) | | `autoPushOnTurnEnd` | `false` | Push tras cada turno cerrado | | `pullIntervalMinutes` | `0` | Pull periódico cada N minutos (`0` = apagado, máximo `10080`) | +| `cwdMap` | `[]` | Proyección de cwd en la restauración `[{from, to}]` (gana el prefijo más largo; los cwd multiplataforma sin coincidencia quedan en solo lectura bajo `/--unmapped--`) | +| `followSessionSymlinks` | `false` | Sigue enlaces simbólicos cuyo realpath permanece dentro de `sessionRoot` (diagnóstico para Android/proot) | | `confirmVia` | `auto` | Canal de confirmación: `auto` (primero userQuestions, luego approval), `userQuestions`, `approval` | | `graceMs` | `10000` | Margen de gracia para matar git (ms) | | `commandTimeoutMs` | `120000` | Timeout por comando (ms) | @@ -268,6 +272,27 @@ Qué **no** protege (la frontera): Línea base: con `backend: git` (el predeterminado), los bytes de sesión se almacenan sin cifrar en **tu** remoto git — usa un repositorio privado. +### Sesiones multiplataforma y proyección de cwd + +Una sesión de Windows sincronizada en Linux (o al revés) lleva un `header.cwd` que no es una ruta absoluta nativa en el host receptor: `dsh-workspace` indexa las sesiones con `realpath(header.cwd)`, y `session-persistence-jsonl` ni siquiera puede analizar un header cuyo cwd no sea absoluto nativo. Asigna el prefijo de origen a una ruta local: + +```yaml +cwdMap: + - from: 'C:\Users\me' + to: /home/me/win +``` + +- Gana el prefijo más largo y los prefijos deben terminar en un límite de segmento (`C:\Users\me2` no coincide con `C:\Users\me`). +- La restauración solo proyecta la **copia local**: su primer frame lleva el cwd local y aterriza en el directorio de proyecto del host, así la sesión aparece en la lista de workspaces. El espejo conserva los bytes del dispositivo de origen; un push vuelve a enganchar el frame de cabecera original, de modo que el otro dispositivo sigue viendo appends idénticos byte a byte y nunca recibe conflictos sin sentido. +- Un cwd multiplataforma sin entrada cae en `/--unmapped--`: **visible pero de solo lectura** (`sync_status` lo informa como `cwdUnmapped` y las ediciones locales nunca se suben). Añade una entrada `cwdMap` y vuelve a hacer pull para convertirlo en una sesión local continuable. + +### Enlaces simbólicos (Android/proot) + +El espejo **nunca sigue enlaces simbólicos** por defecto (límite de seguridad). El `link2symlink` de Android/proot informa los archivos de sesión escritos por el host como enlaces simbólicos (`readdir` dice enlace, `readlink` está vacío, los bytes son legibles), así que las sesiones propias del teléfono nunca llegan al espejo. Diagnóstico y seguimiento opcional: + +- `sync_status` informa `skippedSymlinks` / `skippedSymlinkPaths` (recuento y muestras de rutas) y `followedSymlinks`; el resultado de push lleva el mismo aviso. +- `followSessionSymlinks: true` (por defecto `false`) sigue solo los enlaces cuyo `realpath` permanece dentro de `sessionRoot`; los enlaces que escapan siempre se omiten y se cuentan. + ## Limitaciones conocidas - **El cifrado es opcional y age es una dependencia externa.** `backend: encrypted` añade una capa age (ver «Cifrado y modelo de amenazas» arriba); si falta `age` o `ageRecipient`/`ageIdentity` están vacíos, avisa explícitamente y cae a texto plano, y una identidad protegida con frase de contraseña no se puede usar (el descifrado bloquearía en un prompt TTY, así que falla en cerrado). Con `backend: git` (el predeterminado), los bytes de sesión se almacenan sin cifrar en **tu** remoto git — usa un repositorio privado. diff --git a/README.hi.md b/README.hi.md index 81c2d9d..e987203 100644 --- a/README.hi.md +++ b/README.hi.md @@ -154,10 +154,12 @@ sync: cancelled: approval requires an open turn; /sync commands run between turn | `branch` | `main` | रिमोट branch का नाम | | `autoPushOnTurnEnd` | `false` | हर बंद टर्न के बाद push | | `pullIntervalMinutes` | `0` | हर N मिनट में आवधिक pull (`0` = बंद, अधिकतम `10080`) | +| `cwdMap` | `[]` | पुनर्स्थापन के समय cwd प्रोजेक्शन `[{from, to}]` (सबसे लंबा प्रीफ़िक्स जीतता है; बिना मेल वाले क्रॉस-प्लेटफ़ॉर्म cwd `/--unmapped--` के नीचे केवल-पढ़ने योग्य रहते हैं) | +| `followSessionSymlinks` | `false` | उन सिम्बोलिक लिंक का पालन करें जिनका realpath `sessionRoot` के भीतर ही रहता है (Android/proot निदान) | | `confirmVia` | `auto` | पुष्टि चैनल: `auto` (पहले userQuestions, फिर approval), `userQuestions`, `approval` |
-पूरी कॉन्फ़िगरेशन तालिका (21 कुंजियाँ) +पूरी कॉन्फ़िगरेशन तालिका (23 कुंजियाँ) | कुंजी | डिफ़ॉल्ट | अर्थ | |---|---|---| @@ -174,6 +176,8 @@ sync: cancelled: approval requires an open turn; /sync commands run between turn | `autoPullOnStart` | `false` | प्लगइन माउंट होने पर एक बार pull (कॉन्फ़िग ही अनुमति है; दोबारा पुष्टि नहीं) | | `autoPushOnTurnEnd` | `false` | हर बंद टर्न के बाद push | | `pullIntervalMinutes` | `0` | हर N मिनट में आवधिक pull (`0` = बंद, अधिकतम `10080`) | +| `cwdMap` | `[]` | पुनर्स्थापन के समय cwd प्रोजेक्शन `[{from, to}]` (सबसे लंबा प्रीफ़िक्स जीतता है; बिना मेल वाले क्रॉस-प्लेटफ़ॉर्म cwd `/--unmapped--` के नीचे केवल-पढ़ने योग्य रहते हैं) | +| `followSessionSymlinks` | `false` | उन सिम्बोलिक लिंक का पालन करें जिनका realpath `sessionRoot` के भीतर ही रहता है (Android/proot निदान) | | `confirmVia` | `auto` | पुष्टि चैनल: `auto` (पहले userQuestions, फिर approval), `userQuestions`, `approval` | | `graceMs` | `10000` | git को समाप्त करने की छूट अवधि (ms) | | `commandTimeoutMs` | `120000` | प्रति-कमांड timeout (ms) | @@ -268,6 +272,27 @@ sync: cancelled: approval requires an open turn; /sync commands run between turn आधार रेखा: `backend: git` (डिफ़ॉल्ट) के साथ सत्र बाइट्स **आपके** git रिमोट में बिना एन्क्रिप्शन के संग्रहीत होते हैं — निजी रिपॉज़िटरी का उपयोग करें। +### क्रॉस-प्लेटफ़ॉर्म सत्र और cwd प्रोजेक्शन + +Windows से Linux (या उलटा) सिंक किए गए सत्र का `header.cwd` प्राप्तकर्ता होस्ट पर मूल निरपेक्ष पथ नहीं होता: `dsh-workspace` सत्रों को `realpath(header.cwd)` से अनुक्रमित करता है, और `session-persistence-jsonl` ऐसे header को पढ़ ही नहीं सकता जिसका cwd मूल रूप से निरपेक्ष न हो। स्रोत प्रीफ़िक्स को स्थानीय पथ पर मैप करें: + +```yaml +cwdMap: + - from: 'C:\Users\me' + to: /home/me/win +``` + +- सबसे लंबा मिलता प्रीफ़िक्स जीतता है, और प्रीफ़िक्स पथ-खंड सीमा पर समाप्त होना चाहिए (`C:\Users\me2` `C:\Users\me` से मेल नहीं खाता)। +- पुनर्स्थापन केवल **स्थानीय प्रति** को प्रोजेक्ट करता है: उसका पहला फ़्रेम स्थानीय cwd लेकर होस्ट के प्रोजेक्ट निर्देशिका में जाता है, इसलिए सत्र workspace सूची में दिखता है। मिरर स्रोत डिवाइस के बाइट्स रखता है; push मूल हेडर फ़्रेम को फिर जोड़ देता है, इसलिए दूसरा डिवाइस अभी भी बाइट-दर-बाइट समान appends देखता है और व्यर्थ conflicts नहीं पाता। +- बिना मेल वाला क्रॉस-प्लेटफ़ॉर्म cwd `/--unmapped--` में जाता है: **दिखता है पर केवल-पढ़ने योग्य** (`sync_status` इसे `cwdUnmapped` बताता है, और स्थानीय बदलाव कभी push नहीं होते)। `cwdMap` प्रविष्टि जोड़कर फिर pull करें तो यह जारी रखने योग्य स्थानीय सत्र बन जाता है। + +### सिम्बोलिक लिंक (Android/proot) + +मिरर डिफ़ॉल्ट रूप से **सिम्बोलिक लिंक का पालन कभी नहीं करता** (सुरक्षा सीमा)। Android/proot का `link2symlink` होस्ट द्वारा लिखी सत्र फ़ाइलों को सिम्बोलिक लिंक बताता है (`readdir` लिंक कहता है, `readlink` खाली है, बाइट्स पढ़े जा सकते हैं), इसलिए फ़ोन के अपने सत्र मिरर तक कभी नहीं पहुँचते। निदान और वैकल्पिक पालन: + +- `sync_status` अब `skippedSymlinks` / `skippedSymlinkPaths` (गिनती और पथ नमूने) तथा `followedSymlinks` बताता है; push परिणाम में वही चेतावनी आती है। +- `followSessionSymlinks: true` (डिफ़ॉल्ट `false`) केवल उन लिंक का पालन करता है जिनका `realpath` `sessionRoot` के भीतर रहता है; बाहर जाने वाले लिंक हमेशा छोड़े और गिने जाते हैं। + ## ज्ञात सीमाएँ - **एन्क्रिप्शन वैकल्पिक है, और age बाहरी निर्भरता है।** `backend: encrypted` age परत जोड़ता है (ऊपर «एन्क्रिप्शन और ख़तरा मॉडल» देखें); `age` न होना या `ageRecipient`/`ageIdentity` का खाली होना स्पष्ट चेतावनी देकर plaintext पर अवनति करता है, और पासफ़्रेज़-संरक्षित identity उपयोग नहीं की जा सकती (डिक्रिप्शन TTY प्रॉम्प्ट पर अटक जाता, इसलिए बंद होकर विफल होता है)। `backend: git` (डिफ़ॉल्ट) के साथ सत्र बाइट्स **आपके** git रिमोट में बिना एन्क्रिप्शन के रहते हैं — निजी रिपॉज़िटरी का उपयोग करें। diff --git a/README.md b/README.md index 696ee1e..3993e55 100644 --- a/README.md +++ b/README.md @@ -154,10 +154,12 @@ sync: cancelled: approval requires an open turn; /sync commands run between turn | `branch` | `main` | 远端分支名 | | `autoPushOnTurnEnd` | `false` | 每个关闭轮次后推送 | | `pullIntervalMinutes` | `0` | 每 N 分钟周期拉取(`0` = 关闭,最大 `10080`) | +| `cwdMap` | `[]` | 恢复期 cwd 投影表 `[{from, to}]`(最长前缀优先;未命中的跨平台 cwd 归一到 `/--unmapped--`,只读) | +| `followSessionSymlinks` | `false` | 是否跟随 realpath 仍在 `sessionRoot` 内的符号链接(Android/proot 诊断) | | `confirmVia` | `auto` | 确认通道:`auto`(优先 userQuestions,其次 approval)、`userQuestions`、`approval` |
-完整配置表(21 个键) +完整配置表(23 个键) | 键 | 默认值 | 含义 | |---|---|---| @@ -174,6 +176,8 @@ sync: cancelled: approval requires an open turn; /sync commands run between turn | `autoPullOnStart` | `false` | 插件挂载时拉取一次(配置即授权,不再确认) | | `autoPushOnTurnEnd` | `false` | 每个关闭轮次后推送 | | `pullIntervalMinutes` | `0` | 每 N 分钟周期拉取(`0` = 关闭,最大 `10080`) | +| `cwdMap` | `[]` | 恢复期 cwd 投影表 `[{from, to}]`(最长前缀优先;未命中的跨平台 cwd 归一到 `/--unmapped--`,只读) | +| `followSessionSymlinks` | `false` | 是否跟随 realpath 仍在 `sessionRoot` 内的符号链接(Android/proot 诊断) | | `confirmVia` | `auto` | 确认通道:`auto`(优先 userQuestions,其次 approval)、`userQuestions`、`approval` | | `graceMs` | `10000` | git 终止宽限(毫秒) | | `commandTimeoutMs` | `120000` | 单条命令超时(毫秒) | @@ -268,6 +272,27 @@ sync: cancelled: approval requires an open turn; /sync commands run between turn 基线:`backend: git`(默认)下,会话字节以未加密形式存放在**你的** git 远端——请使用私有仓库。 +### 跨平台会话与 cwd 投影 + +Windows ↔ Linux 会话的 `header.cwd` 在另一台机器上不是本机绝对路径:宿主 `dsh-workspace` 按 `realpath(header.cwd)` 建索引,`session-persistence-jsonl` 更是 header 解析失败就完全看不到会话。用 `cwdMap` 把源设备前缀映射到本机路径: + +```yaml +cwdMap: + - from: 'C:\Users\me' + to: /home/me/win +``` + +- 最长前缀优先,前缀必须结束在路径段边界上(`C:\Users\me2` 不匹配 `C:\Users\me`)。 +- 恢复时只投影**本地副本**:首帧 cwd 改写为本机路径、文件落到宿主布局的项目目录,因此会话出现在 workspace 列表里。同步仓库里的字节始终是源设备的 cwd;推送时把原首帧接回,对端看到的仍是逐字节 append,不会产生无意义分叉。 +- 没有命中的跨平台 cwd 归一到 `/--unmapped--`:会话**可见但只读**,`sync_status` 的 `cwdUnmapped` 会计数,本地改动不会推送。给它补一条 `cwdMap` 后重新 pull 即可变成可继续的本地会话。 + +### 符号链接(Android/proot) + +默认**绝不跟随符号链接**(安全边界)。Android/proot 的 `link2symlink` 会把宿主写入的会话文件报成符号链接(`readdir` 说是链接、`readlink` 为空、内容可读),导致手机自己的会话永远不进镜像。诊断与可选跟随: + +- `sync_status` 新增 `skippedSymlinks` / `skippedSymlinkPaths`(数量与路径样本)、`followedSymlinks`,push 结果也会带同类 warning; +- `followSessionSymlinks: true`(默认 `false`)只跟随 `realpath` 仍落在 `sessionRoot` 内的链接,越界链接一律跳过并计数。 + ## 已知限制 - **加密可选、age 为外部依赖。** `backend: encrypted` 增加一层 age 加密(见上文「加密与威胁模型」);`age` 缺失或 `ageRecipient`/`ageIdentity` 为空时显式告警并降级明文,口令保护的 identity 不可用(解密会阻塞在 TTY 提示上,因此失败关闭)。`backend: git`(默认)下,会话字节以未加密形式存放在**你的** git 远端——请使用私有仓库。 diff --git a/README.pt.md b/README.pt.md index 0813d59..b40c7c1 100644 --- a/README.pt.md +++ b/README.pt.md @@ -154,10 +154,12 @@ Chaves mais usadas: | `branch` | `main` | Nome do branch remoto | | `autoPushOnTurnEnd` | `false` | Push após cada turno fechado | | `pullIntervalMinutes` | `0` | Pull periódico a cada N minutos (`0` = desligado, máximo `10080`) | +| `cwdMap` | `[]` | Projeção de cwd na restauração `[{from, to}]` (o prefixo mais longo vence; cwds multiplataforma sem entrada ficam somente leitura em `/--unmapped--`) | +| `followSessionSymlinks` | `false` | Segue links simbólicos cujo realpath permanece dentro de `sessionRoot` (diagnóstico Android/proot) | | `confirmVia` | `auto` | Canal de confirmação: `auto` (userQuestions primeiro, depois approval), `userQuestions`, `approval` |
-Tabela de configuração completa (21 chaves) +Tabela de configuração completa (23 chaves) | Chave | Padrão | Significado | |---|---|---| @@ -174,6 +176,8 @@ Chaves mais usadas: | `autoPullOnStart` | `false` | Pull uma vez ao montar o plugin (a configuração é a autorização; sem reconfirmação) | | `autoPushOnTurnEnd` | `false` | Push após cada turno fechado | | `pullIntervalMinutes` | `0` | Pull periódico a cada N minutos (`0` = desligado, máximo `10080`) | +| `cwdMap` | `[]` | Projeção de cwd na restauração `[{from, to}]` (o prefixo mais longo vence; cwds multiplataforma sem entrada ficam somente leitura em `/--unmapped--`) | +| `followSessionSymlinks` | `false` | Segue links simbólicos cujo realpath permanece dentro de `sessionRoot` (diagnóstico Android/proot) | | `confirmVia` | `auto` | Canal de confirmação: `auto` (userQuestions primeiro, depois approval), `userQuestions`, `approval` | | `graceMs` | `10000` | Período de carência para matar o git (ms) | | `commandTimeoutMs` | `120000` | Timeout por comando (ms) | @@ -268,6 +272,27 @@ O que ela **não** protege (a fronteira): Linha de base: com `backend: git` (o padrão), os bytes de sessão são armazenados sem criptografia no **seu** remoto git — use um repositório privado. +### Sessões multiplataforma e projeção de cwd + +Uma sessão do Windows sincronizada no Linux (ou o contrário) carrega um `header.cwd` que não é um caminho absoluto nativo no host receptor: o `dsh-workspace` indexa sessões via `realpath(header.cwd)`, e o `session-persistence-jsonl` nem consegue analisar um header cujo cwd não seja absoluto nativo. Mapeie o prefixo de origem para um caminho local: + +```yaml +cwdMap: + - from: 'C:\Users\me' + to: /home/me/win +``` + +- O prefixo mais longo vence, e os prefixos terminam num limite de segmento (`C:\Users\me2` não corresponde a `C:\Users\me`). +- A restauração projeta apenas a **cópia local**: o primeiro frame leva o cwd local e cai no diretório de projeto do host, então a sessão aparece na lista de workspaces. O espelho mantém os bytes do dispositivo de origem; um push reanexa o frame de cabeçalho original, então o outro dispositivo continua vendo appends idênticos byte a byte e nunca recebe conflitos sem sentido. +- Um cwd multiplataforma sem entrada vai para `/--unmapped--`: **visível mas somente leitura** (`sync_status` o informa como `cwdUnmapped`, e edições locais nunca são enviadas). Adicione uma entrada `cwdMap` e faça pull de novo para torná-lo uma sessão local continuável. + +### Links simbólicos (Android/proot) + +O espelho **nunca segue links simbólicos** por padrão (limite de segurança). O `link2symlink` do Android/proot informa os arquivos de sessão escritos pelo host como links simbólicos (`readdir` diz link, `readlink` está vazio, os bytes são legíveis), então as sessões do próprio telefone nunca chegam ao espelho. Diagnóstico e seguimento opcional: + +- `sync_status` informa `skippedSymlinks` / `skippedSymlinkPaths` (contagem e amostras de caminhos) e `followedSymlinks`; o resultado do push leva o mesmo aviso. +- `followSessionSymlinks: true` (padrão `false`) segue apenas links cujo `realpath` permanece dentro de `sessionRoot`; links que escapam são sempre ignorados e contados. + ## Limitações conhecidas - **A criptografia é opcional e o age é uma dependência externa.** `backend: encrypted` adiciona uma camada age (ver «Criptografia e modelo de ameaças» acima); se o `age` faltar ou `ageRecipient`/`ageIdentity` estiverem vazios, avisa explicitamente e cai para texto plano, e uma identidade protegida por frase de senha não pode ser usada (a descriptografia bloquearia num prompt TTY, então falha fechada). Com `backend: git` (o padrão), os bytes de sessão são armazenados sem criptografia no **seu** remoto git — use um repositório privado. diff --git a/cordis.patch.yml b/cordis.patch.yml index 524b73e..2adc10b 100644 --- a/cordis.patch.yml +++ b/cordis.patch.yml @@ -40,6 +40,17 @@ # auto (userQuestions first, then approval) · userQuestions · approval. # Read-only surfaces (status/diff/log) never ask. confirmVia: auto + # Restore-time cwd projection (cross-OS sessions). Each entry maps an + # origin-device prefix to a local path; longest matching prefix wins and + # prefixes end on a path-segment boundary (C:\Users\me2 does not match + # C:\Users\me). The mirror keeps the origin device's bytes; only the + # restored local copy carries the local cwd. Cross-platform cwds with no + # entry are shown read-only under /--unmapped--. + cwdMap: [] + # Mirror symbolic links whose realpath stays inside sessionRoot + # (Android/proot link2symlink hosts). Default false keeps "never follow + # symlinks"; skipped links are counted and listed in sync_status. + followSessionSymlinks: false # Subprocess tuning: grace period for git kills, per-command timeout, # and the per-stream collected-output cap. graceMs: 10000 diff --git a/index.mjs b/index.mjs index 512efff..d6a24b7 100644 --- a/index.mjs +++ b/index.mjs @@ -57,6 +57,19 @@ import { collectStatus } from './lib/status.mjs' import { renderDiff, renderPull, renderPush, renderStatus, errorValue } from './lib/render.mjs' import { confirmSync, hasOpenTurn, makeEventGate, maybeAppendSessionEvent, openTurnFromProjection } from './lib/gate.mjs' import { sessionSyncDomainSpec } from './lib/domain.mjs' +import { + matchCwdMap, + normalizeCwdMap, + projectCwd, + projectKey, + projectedRelOf, +} from './lib/cwdmap.mjs' +import { + canonicalizeProjectedFile, + planRestoreFile, + readProjectionState, +} from './lib/projection.mjs' +import { readSessionHeader } from './lib/sessionlog.mjs' export const name = PLUGIN_NAME @@ -107,6 +120,8 @@ export function probeIgnorableAppend() { * @property {boolean} [autoPushOnTurnEnd] 每个 turn/end 后自动推送(配置即授权)。 * @property {number} [pullIntervalMinutes] 周期自动拉取间隔分钟(0 = 关闭)。 * @property {'auto'|'userQuestions'|'approval'} [confirmVia] 确认通道(auto 优先 userQuestions)。 + * @property {ReadonlyArray<{from: string, to: string}>} [cwdMap] 恢复期 cwd 投影表(最长前缀优先;未命中的跨平台 cwd 归一到 sessionRoot/--unmapped--)。 + * @property {boolean} [followSessionSymlinks] 镜像时是否跟随 realpath 仍在 sessionRoot 内的符号链接(默认 false)。 * @property {number} [graceMs] git 子进程终止宽限(ms)。 * @property {number} [commandTimeoutMs] 单条 git 命令超时(ms)。 * @property {number} [maxOutputBytes] git 输出单流收集上限(字节)。 @@ -132,6 +147,11 @@ export const Config = Schema.object({ autoPushOnTurnEnd: Schema.boolean().default(DEFAULTS.AUTO_PUSH_ON_TURN_END), pullIntervalMinutes: Schema.number().default(DEFAULTS.PULL_INTERVAL_MINUTES), confirmVia: Schema.union(Object.values(CONFIRM_CHANNELS)).default(DEFAULTS.CONFIRM_VIA), + cwdMap: Schema.array(Schema.object({ + from: Schema.string().required(), + to: Schema.string().required(), + })).default([...DEFAULTS.CWD_MAP]), + followSessionSymlinks: Schema.boolean().default(DEFAULTS.FOLLOW_SESSION_SYMLINKS), graceMs: Schema.number().default(DEFAULTS.GRACE_MS), commandTimeoutMs: Schema.number().default(DEFAULTS.COMMAND_TIMEOUT_MS), maxOutputBytes: Schema.number().default(DEFAULTS.MAX_OUTPUT_BYTES), @@ -162,6 +182,8 @@ export function resolveConfig(config = {}) { autoPushOnTurnEnd: config.autoPushOnTurnEnd ?? DEFAULTS.AUTO_PUSH_ON_TURN_END, pullIntervalMinutes: config.pullIntervalMinutes ?? DEFAULTS.PULL_INTERVAL_MINUTES, confirmVia: config.confirmVia ?? DEFAULTS.CONFIRM_VIA, + cwdMap: normalizeCwdMap(config.cwdMap ?? DEFAULTS.CWD_MAP), + followSessionSymlinks: config.followSessionSymlinks ?? DEFAULTS.FOLLOW_SESSION_SYMLINKS, graceMs: config.graceMs ?? DEFAULTS.GRACE_MS, commandTimeoutMs: config.commandTimeoutMs ?? DEFAULTS.COMMAND_TIMEOUT_MS, maxOutputBytes: config.maxOutputBytes ?? DEFAULTS.MAX_OUTPUT_BYTES, @@ -204,6 +226,9 @@ export function resolveConfig(config = {}) { if (!Number.isInteger(resolved.pullIntervalMinutes) || resolved.pullIntervalMinutes < LIMITS.MIN_PULL_INTERVAL_MINUTES || resolved.pullIntervalMinutes > LIMITS.MAX_PULL_INTERVAL_MINUTES) { throw badConfig(`pullIntervalMinutes must be an integer in [${LIMITS.MIN_PULL_INTERVAL_MINUTES}, ${LIMITS.MAX_PULL_INTERVAL_MINUTES}]`) } + if (typeof resolved.followSessionSymlinks !== 'boolean') { + throw badConfig('followSessionSymlinks must be a boolean') + } if (typeof resolved.commitName !== 'string' || resolved.commitName.trim().length === 0) { throw badConfig('commitName must be a non-empty string') } @@ -348,9 +373,9 @@ const TOOL_TEXT = { } /** sync_status 工具规范结果(与工具 schema 同构)。 */ -/** @typedef {{ok: boolean, branch: string, remote: string, head?: string, remoteHead?: string, ahead: number, behind: number, dirty: string[], forks: string[], diffStat: string, mergeInProgress: boolean, lastCommits: string[], lastPullAt?: number, lastPushAt?: number, lastError?: string, error?: string, warnings?: string[]}} StatusValue */ -/** @typedef {{ok: boolean, pulled?: boolean, merged?: boolean, adopted?: number, appended?: number, diverged?: number, forks?: string[], head?: string, error?: string, warnings?: string[]}} PullValue */ -/** @typedef {{ok: boolean, pushed?: boolean, head?: string, mirrored?: number, deleted?: number, remote?: string, error?: string, warnings?: string[]}} PushValue */ +/** @typedef {{ok: boolean, branch: string, remote: string, head?: string, remoteHead?: string, ahead: number, behind: number, dirty: string[], forks: string[], diffStat: string, mergeInProgress: boolean, lastCommits: string[], lastPullAt?: number, lastPushAt?: number, lastError?: string, error?: string, skippedSymlinks?: number, skippedSymlinkPaths?: string[], followedSymlinks?: number, cwdMapped?: number, cwdUnmapped?: number, cwdProjectionSkipped?: number, cwdPlaceholder?: string, followSessionSymlinks?: boolean, warnings?: string[]}} StatusValue */ +/** @typedef {{ok: boolean, pulled?: boolean, merged?: boolean, adopted?: number, appended?: number, diverged?: number, forks?: string[], head?: string, restored?: number, cwdMapped?: number, cwdUnmapped?: number, error?: string, warnings?: string[]}} PullValue */ +/** @typedef {{ok: boolean, pushed?: boolean, head?: string, mirrored?: number, deleted?: number, remote?: string, skippedSymlinks?: number, skippedSymlinkPaths?: string[], error?: string, warnings?: string[]}} PushValue */ /** * sync_status 工具定义(read-only:不确认、不触网)。 @@ -384,6 +409,14 @@ export function makeSyncStatusTool(engine, readMeta) { lastPushAt: { type: 'integer' }, lastError: { type: 'string' }, error: { type: 'string' }, + skippedSymlinks: { type: 'integer' }, + skippedSymlinkPaths: { type: 'array', items: { type: 'string' } }, + followedSymlinks: { type: 'integer' }, + cwdMapped: { type: 'integer' }, + cwdUnmapped: { type: 'integer' }, + cwdProjectionSkipped: { type: 'integer' }, + cwdPlaceholder: { type: 'string' }, + followSessionSymlinks: { type: 'boolean' }, warnings: { type: 'array', items: { type: 'string' } }, }, }, @@ -437,6 +470,9 @@ export function makeSyncPullTool(deps) { diverged: { type: 'integer' }, forks: { type: 'array', items: { type: 'string' } }, head: { type: 'string' }, + restored: { type: 'integer' }, + cwdMapped: { type: 'integer' }, + cwdUnmapped: { type: 'integer' }, error: { type: 'string' }, warnings: { type: 'array', items: { type: 'string' } }, }, @@ -496,6 +532,8 @@ export function makeSyncPushTool(deps) { mirrored: { type: 'integer' }, deleted: { type: 'integer' }, remote: { type: 'string' }, + skippedSymlinks: { type: 'integer' }, + skippedSymlinkPaths: { type: 'array', items: { type: 'string' } }, error: { type: 'string' }, warnings: { type: 'array', items: { type: 'string' } }, }, @@ -670,6 +708,8 @@ export function apply(ctx, config = {}) { remote: resolved.remote, branch: resolved.branch, deviceId: 'pending', + cwdMap: resolved.cwdMap, + followSessionSymlinks: resolved.followSessionSymlinks, reportMeta, reportError, logger, @@ -865,6 +905,9 @@ export function apply(ctx, config = {}) { // turn/end 自动推送(配置即授权;每轮结束拉一次快照并推送)。 if (resolved.autoPushOnTurnEnd) { + // #30:有些宿主(Android/proot 的 DSH Go)不发 session/event;把"监听器已 + // 注册"记进日志,让外部可判断的是宿主事件还是插件注册。 + logger.info(`auto push listener registered (session/event turn/end → push); pullIntervalMinutes=${resolved.pullIntervalMinutes}`) ctx.on('session/event', (session, event) => { if (event.type !== 'turn/end') return void engine.push().then(result => { @@ -923,4 +966,14 @@ export { sessionSyncDomainSpec, registryUnavailable, errorValue, + // 跨平台 cwd 投影(#28)与符号链接诊断(#30)的复用/测试面。 + normalizeCwdMap, + matchCwdMap, + projectCwd, + projectKey, + projectedRelOf, + planRestoreFile, + canonicalizeProjectedFile, + readProjectionState, + readSessionHeader, } diff --git a/lib/constants.mjs b/lib/constants.mjs index 4456a5c..284e06f 100644 --- a/lib/constants.mjs +++ b/lib/constants.mjs @@ -17,6 +17,10 @@ export const MIRROR_DIR = 'sessions' // 仓库根下的设备身份文件(随机 UUID,提交进仓库供跨设备归属 fork)。 export const DEVICE_FILE = 'device.txt' +// 恢复期 cwd 投影:无 cwdMap 命中的跨平台会话归一到 sessionRoot 下的这个占位 +// 目录(可见但只读——只出现在本机索引里,永远不作为推送源)。 +export const UNMAPPED_DIR = '--unmapped--' + // 存储领域 state 表的单例键。 export const STATE_KEY = 'singleton' @@ -107,6 +111,8 @@ export const DEFAULTS = Object.freeze({ AUTO_PUSH_ON_TURN_END: false, PULL_INTERVAL_MINUTES: 0, CONFIRM_VIA: CONFIRM_CHANNELS.AUTO, + CWD_MAP: Object.freeze([]), + FOLLOW_SESSION_SYMLINKS: false, GRACE_MS: 10000, COMMAND_TIMEOUT_MS: 120000, MAX_OUTPUT_BYTES: 262144, diff --git a/lib/cwdmap.mjs b/lib/cwdmap.mjs new file mode 100644 index 0000000..df0b69b --- /dev/null +++ b/lib/cwdmap.mjs @@ -0,0 +1,248 @@ +// lib/cwdmap.mjs — 恢复期 cwd 投影(纯函数,零依赖)。 +// +// 跨平台会话的 header.cwd 在另一台机器上不是本机绝对路径。宿主的 +// dsh-workspace 用 realpathNormalize(header.cwd) 建 workspace 索引; +// session-persistence-jsonl 更靠前——header 解析本身就要求 cwd 是本机绝对 +// 路径(`isAbsolute`),非本机路径的会话连"可见"都做不到。因此恢复时必须把 +// cwd 投影成本机路径。投影只落在**本地副本**上:同步仓库(镜像)里的字节保持 +// 原设备的 header,推送时由 lib/projection.mjs 把原首帧接回去(逐字节 append +// 语义不变)。 +// +// 匹配语义(issue #28): +// - `cwdMap: [{from, to}]`,按最长前缀优先; +// - 前缀必须结束在路径段边界上(`C:\Users\me2` 不匹配 `C:\Users\me`); +// - Windows 风格前缀按 Windows 语义大小写不敏感比较,其余按字节比较; +// - 无匹配的跨平台 cwd 归一到 `sessionRoot/--unmapped--`(可见但只读)。 + +import path from 'node:path' +import { posix, win32 } from 'node:path' +import { UNMAPPED_DIR } from './constants.mjs' +import { badConfig } from './errors.mjs' + +const WINDOWS_DRIVE_RE = /^[A-Za-z]:/u +const SEPARATOR_RUN_RE = /[\\/]+/gu +const TRAILING_SEPARATOR_RE = /[\\/]+$/u +const SAFE_PROJECT_KEY_CHAR_RE = /^[A-Za-z0-9._-]$/u + +/** + * 是否形如 Windows 路径(盘符或 UNC)。 + * @param {string} value - 原始路径。 + * @returns {boolean} Windows 风格为 true。 + */ +function looksWindows(value) { + return WINDOWS_DRIVE_RE.test(value) || value.startsWith('\\\\') +} + +/** + * 是否为某个平台上的完全限定路径(宿主 fullyQualifiedWorkspacePath 的并集)。 + * @param {string} value - 原始路径。 + * @returns {boolean} 任一并集平台上的绝对路径为 true。 + */ +function absoluteOnSomePlatform(value) { + if (typeof value !== 'string' || value.length === 0) return false + if (posix.isAbsolute(value)) return true + const root = win32.parse(value).root + return win32.isAbsolute(value) && root !== '\\' && root !== '/' +} + +/** + * 宿主 `fullyQualifiedWorkspacePath` 的等价判定:本机平台的完全限定路径。 + * (dsh-workspace/src/paths.ts:非 win32 用 posix.isAbsolute;win32 要求 + * root 不是 `\` 或 `/`。) + * @param {string} value - 待判定路径。 + * @param {NodeJS.Platform} [platform] - 目标平台(测试可注入)。 + * @returns {boolean} 本机完全限定为 true。 + */ +export function isNativeAbsolutePath(value, platform = process.platform) { + if (typeof value !== 'string' || value.length === 0) return false + if (platform !== 'win32') return posix.isAbsolute(value) + const root = win32.parse(value).root + return win32.isAbsolute(value) && root !== '\\' && root !== '/' +} + +/** + * 是否为"另一平台"的绝对路径(本机不可索引,但语义上是绝对路径)。 + * 相对路径/空值不算——那种 header 本来就无效,不归投影管。 + * @param {string} value - header cwd。 + * @param {NodeJS.Platform} [platform] - 目标平台(测试可注入)。 + * @returns {boolean} 跨平台绝对路径为 true。 + */ +export function isForeignCwd(value, platform = process.platform) { + if (typeof value !== 'string' || value.length === 0) return false + if (isNativeAbsolutePath(value, platform)) return false + return absoluteOnSomePlatform(value) +} + +/** + * 路径 → 段数组(分隔符归一;去掉绝对根产生的空首段与尾部空段)。 + * `C:\Users\me` → ['C:','Users','me'];`/home/me` → ['home','me'];`/` → []。 + * @param {string} value - 路径。 + * @returns {string[]} 段数组。 + */ +function splitSegments(value) { + const parts = value.replace(SEPARATOR_RUN_RE, '/').split('/') + if (parts.length > 0 && parts[0] === '') parts.shift() + while (parts.length > 0 && parts[parts.length - 1] === '') parts.pop() + return parts +} + +/** + * 校验并规范化 cwdMap:非法项加载期响亮失败(Loud misconfiguration)。 + * 规范化结果按最长前缀优先排序,并携带预计算段(匹配热路径不重复切分)。 + * @param {unknown} entries - Config.cwdMap 原始值。 + * @returns {ReadonlyArray<{from: string, to: string, windows: boolean, segments: ReadonlyArray}>} 规范化后的映射表。 + */ +export function normalizeCwdMap(entries) { + if (entries === undefined || entries === null) return Object.freeze([]) + if (!Array.isArray(entries)) throw badConfig('cwdMap must be an array of { from, to } objects') + const seen = new Set() + const normalized = [] + for (const [index, entry] of entries.entries()) { + if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) { + throw badConfig(`cwdMap[${index}] must be an object with from/to`) + } + const value = /** @type {{from?: unknown, to?: unknown}} */ (entry) + const extra = Object.keys(entry).filter(key => key !== 'from' && key !== 'to') + if (extra.length > 0) throw badConfig(`cwdMap[${index}] has unknown key(s): ${extra.join(', ')}`) + if (typeof value.from !== 'string' || value.from.trim().length === 0) { + throw badConfig(`cwdMap[${index}].from must be a non-empty string`) + } + if (typeof value.to !== 'string' || value.to.trim().length === 0) { + throw badConfig(`cwdMap[${index}].to must be a non-empty string`) + } + const from = value.from.replace(TRAILING_SEPARATOR_RE, '') || value.from + const to = value.to.replace(TRAILING_SEPARATOR_RE, '') || value.to + if (!absoluteOnSomePlatform(from)) { + throw badConfig(`cwdMap[${index}].from must be an absolute path: ${JSON.stringify(value.from)}`) + } + if (!isNativeAbsolutePath(to)) { + throw badConfig(`cwdMap[${index}].to must be an absolute path on this platform: ${JSON.stringify(value.to)}`) + } + const windows = looksWindows(from) + const key = windows ? from.toLowerCase() : from + if (seen.has(key)) throw badConfig(`cwdMap has a duplicate from: ${JSON.stringify(value.from)}`) + seen.add(key) + normalized.push({ from, to, windows, segments: splitSegments(from) }) + } + normalized.sort((left, right) => + right.segments.length - left.segments.length + || right.from.length - left.from.length + || left.from.localeCompare(right.from)) + return Object.freeze(normalized.map(entry => Object.freeze(entry))) +} + +/** + * 最长前缀匹配(段边界)。cwd 必须能完整覆盖某个 from 的段序列。 + * @param {string} cwd - header.cwd。 + * @param {ReadonlyArray<{from: string, to: string, windows: boolean, segments: ReadonlyArray}>} maps - normalizeCwdMap 的产物。 + * @returns {{entry: {from: string, to: string, windows: boolean, segments: ReadonlyArray}, remainder: string[]}|undefined} 匹配项与剩余段。 + */ +export function matchCwdMap(cwd, maps) { + if (typeof cwd !== 'string' || cwd.length === 0) return undefined + const segments = splitSegments(cwd) + for (const entry of maps) { + if (segments.length < entry.segments.length) continue + let matches = true + for (let index = 0; index < entry.segments.length; index += 1) { + const left = entry.windows ? segments[index].toLowerCase() : segments[index] + const right = entry.windows ? entry.segments[index].toLowerCase() : entry.segments[index] + if (left !== right) { + matches = false + break + } + } + if (!matches) continue + return { entry, remainder: segments.slice(entry.segments.length) } + } + return undefined +} + +/** + * 把匹配项的剩余段接到 to 上(保持 to 的分隔符风格)。 + * @param {{to: string}} entry - 匹配项。 + * @param {string[]} remainder - 剩余段。 + * @returns {string} 映射后的本机路径。 + */ +function joinMapped(entry, remainder) { + const separator = entry.to.includes('\\') ? '\\' : '/' + const tail = remainder.join(separator) + return tail.length === 0 ? entry.to : `${entry.to}${separator}${tail}` +} + +/** + * 宿主 `projectKey(cwd)` 的等价实现(session-persistence-jsonl/src/format.ts)。 + * + * 必须逐字一致:宿主用 `///` 定位 + * 会话,并在 `assertStoredIdentity` 里校验路径等于这条公式——投影后的目录名差 + * 一个字符,恢复出来的会话就会被判 corrupt。分隔符(含 `:`)折叠为单个 `-`, + * 其余不安全字符转 `~XXXX`,截断到 251 字符后包成 `--…--`。 + * @param {string} cwd - 会话的 cwd(必须非空)。 + * @returns {string} 项目目录名。 + */ +export function projectKey(cwd) { + if (typeof cwd !== 'string' || cwd.length === 0) { + throw new Error('cannot encode an empty project path') + } + let readable = '' + let separatorRun = false + for (let index = 0; index < cwd.length; index += 1) { + const code = cwd.charCodeAt(index) + const character = String.fromCharCode(code) + if (character === '/' || character === '\\' || character === ':') { + if (!separatorRun) readable += '-' + separatorRun = true + } else if (character !== '~' && SAFE_PROJECT_KEY_CHAR_RE.test(character)) { + readable += character + separatorRun = false + } else { + readable += `~${code.toString(16).toUpperCase().padStart(4, '0')}` + separatorRun = false + } + } + const slug = readable.replace(/^-+/u, '') || 'root' + return `--${slug.slice(0, 251)}--` +} + +/** + * 计算投影后的镜像相对路径:把 `` 段换成 + * ``,会话目录段与文件名不变(宿主布局 + * `//`)。 + * @param {string} canonicalRel - 镜像相对路径(POSIX 分隔)。 + * @param {string} projectedCwd - 投影后的本机 cwd。 + * @returns {string|undefined} 投影相对路径;旧扁平布局(不足 3 段)为 undefined。 + */ +export function projectedRelOf(canonicalRel, projectedCwd) { + if (typeof canonicalRel !== 'string' || canonicalRel.length === 0) return undefined + const parts = canonicalRel.split('/') + if (parts.length < 3) return undefined + const [projectDir, sessionDir, ...rest] = parts + if (projectDir.length === 0 || sessionDir.length === 0) return undefined + return [projectKey(projectedCwd), sessionDir, ...rest].join('/') +} + +/** + * 恢复期 cwd 决策:有映射 → 映射目标;无映射的跨平台 cwd → 占位目录(只读); + * 本机 cwd → 原样。 + * @param {string|undefined} cwd - header.cwd。 + * @param {{map?: ReadonlyArray, sessionRoot: string, platform?: NodeJS.Platform}} options - 映射表、会话根与平台。 + * @returns {{cwd: string|undefined, mapped: boolean, unmapped: boolean, readOnly: boolean, from: string|undefined}} 投影决策。 + */ +export function projectCwd(cwd, options) { + if (typeof cwd !== 'string' || cwd.length === 0) { + return { cwd: undefined, mapped: false, unmapped: false, readOnly: false, from: cwd } + } + const match = matchCwdMap(cwd, options.map ?? []) + if (match !== undefined) { + return { cwd: joinMapped(match.entry, match.remainder), mapped: true, unmapped: false, readOnly: false, from: cwd } + } + if (!isForeignCwd(cwd, options.platform)) { + return { cwd, mapped: false, unmapped: false, readOnly: false, from: cwd } + } + return { + cwd: path.join(options.sessionRoot, UNMAPPED_DIR), + mapped: false, + unmapped: true, + readOnly: true, + from: cwd, + } +} diff --git a/lib/encrypted.mjs b/lib/encrypted.mjs index ff2f900..1c6a8fd 100644 --- a/lib/encrypted.mjs +++ b/lib/encrypted.mjs @@ -218,13 +218,17 @@ export class EncryptedBackend { #onForks /** @type {{debug: Function, info: Function, warn: Function, error: Function}} */ #logger + /** @type {ReadonlyArray} 恢复期 cwd 投影表(与明文引擎同一份)。 */ + #cwdMap + /** @type {boolean} 是否跟随根内符号链接(#30)。 */ + #followSessionSymlinks /** @type {string[]} */ #warnings = [] /** @type {Promise<{mode: string, warnings: string[]}>|undefined} 惰性探测结果。 */ #ready /** - * @param {object} deps - {git, sessionRoot, repoDir, remote, branch, deviceId, reportMeta, reportError, onForks, logger, run, ageBin, ageRecipient, ageIdentity, timeoutMs}。 + * @param {object} deps - {git, sessionRoot, repoDir, remote, branch, deviceId, reportMeta, reportError, onForks, logger, run, ageBin, ageRecipient, ageIdentity, timeoutMs, cwdMap?, followSessionSymlinks?}。 */ constructor(deps) { this.#git = deps.git @@ -242,6 +246,8 @@ export class EncryptedBackend { this.#reportError = deps.reportError this.#onForks = deps.onForks this.#logger = deps.logger + this.#cwdMap = deps.cwdMap ?? [] + this.#followSessionSymlinks = deps.followSessionSymlinks === true this.#plain = new SyncEngine({ git: deps.git, sessionRoot: deps.sessionRoot, @@ -253,6 +259,8 @@ export class EncryptedBackend { reportError: deps.reportError, onForks: deps.onForks, logger: deps.logger, + cwdMap: this.#cwdMap, + followSessionSymlinks: this.#followSessionSymlinks, }) } @@ -317,6 +325,7 @@ export class EncryptedBackend { sessionRoot: this.#sessionRoot, repoDir: this.#repoDir, mirrorDir: MIRROR_DIR, + followSessionSymlinks: this.#followSessionSymlinks, }) } diff --git a/lib/engine.mjs b/lib/engine.mjs index 1c1a1a8..efb2e80 100644 --- a/lib/engine.mjs +++ b/lib/engine.mjs @@ -10,7 +10,7 @@ import { promises as fs } from 'node:fs' import path from 'node:path' -import { MERGE_KINDS, MIRROR_DIR, DEVICE_FILE } from './constants.mjs' +import { MERGE_KINDS, MIRROR_DIR, DEVICE_FILE, UNMAPPED_DIR } from './constants.mjs' import { planMerge } from './merge.mjs' import { mirrorSessionRoot, restoreSessionRoot, pruneRestoredSessions, ensureDeviceFile } from './mirror.mjs' import { collectStatus } from './status.mjs' @@ -27,6 +27,8 @@ import { redactText, sanitizeRemote } from './sanitize.mjs' * @property {string} remote - 远端地址原文(展示时 sanitize)。 * @property {string} branch - 分支名。 * @property {string} deviceId - 设备 id(fork 归属)。 + * @property {ReadonlyArray} [cwdMap] - 恢复期 cwd 投影表(最长前缀优先)。 + * @property {boolean} [followSessionSymlinks] - 镜像时是否跟随根内符号链接(#30;默认 false)。 * @property {(patch: object) => void} reportMeta - 元数据补丁回调(index.mjs 写领域)。 * @property {(message: string) => void} reportError - 最近错误回调(写领域 lastError)。 * @property {(forkRelPaths: string[]) => void} onForks - fork 文件产生回调(index.mjs 做会话级 fork + 事件)。 @@ -84,10 +86,42 @@ export class SyncEngine { sessionRoot: this.#deps.sessionRoot, repoDir: this.#deps.repoDir, mirrorDir: MIRROR_DIR, + followSessionSymlinks: this.#deps.followSessionSymlinks === true, }) return { deviceWritten, mirror } } + /** + * 镜像诊断(#28/#30):跳过/跟随的符号链接、cwd 投影计数与告警。 + * @param {object} mirror - mirrorSessionRoot 产物。 + * @returns {{skippedSymlinks: number, skippedSymlinkPaths: string[], followedSymlinks: number, cwdMapped: number, cwdUnmapped: number, cwdProjectionSkipped: number, cwdPlaceholder: string, followSessionSymlinks: boolean, warnings: string[]}} 诊断。 + */ + #mirrorDiagnostics(mirror) { + const skipped = Array.isArray(mirror.skippedLinks) ? mirror.skippedLinks : [] + const warnings = [] + if (skipped.length > 0) { + const sample = skipped.slice(0, 5).join(', ') + warnings.push(`${skipped.length} file(s) under sessionRoot were skipped as symbolic links and are not mirrored (${sample}${skipped.length > 5 ? ', …' : ''}); set followSessionSymlinks: true to include links whose realpath stays inside sessionRoot`) + } + if ((mirror.cwdUnmapped ?? 0) > 0) { + warnings.push(`${mirror.cwdUnmapped} session(s) with a cross-platform cwd have no cwdMap entry; they are shown read-only under ${path.join(this.#deps.sessionRoot, UNMAPPED_DIR)}`) + } + if (typeof mirror.projectionError === 'string') { + warnings.push(`cwd projection state is unreadable: ${mirror.projectionError}`) + } + return { + skippedSymlinks: skipped.length, + skippedSymlinkPaths: skipped.slice(0, 20), + followedSymlinks: Array.isArray(mirror.followedLinks) ? mirror.followedLinks.length : 0, + cwdMapped: mirror.cwdMapped ?? 0, + cwdUnmapped: mirror.cwdUnmapped ?? 0, + cwdProjectionSkipped: mirror.cwdProjectionSkipped ?? 0, + cwdPlaceholder: path.join(this.#deps.sessionRoot, UNMAPPED_DIR), + followSessionSymlinks: this.#deps.followSessionSymlinks === true, + warnings, + } + } + // 前置镜像 + 提交。调用方(push/pull)已持有 schedule 锁,这里绝不能再走 // #schedule —— 嵌套 schedule 会在同一 git 链上自锁(fnM 等 fnP 完成、fnP 等 fnM)。 async #mirrorAndCommit(message) { @@ -106,14 +140,30 @@ export class SyncEngine { */ status() { return this.#schedule(async () => { + /** @type {object|undefined} */ + let mirror try { await fs.mkdir(this.#deps.repoDir, { recursive: true }) await this.#deps.git.ensureRepo() - await this.#mirrorOnly() + mirror = (await this.#mirrorOnly()).mirror } catch { // 初始化/镜像失败不阻断状态:collectStatus 会返回带 error 的快照。 } - return collectStatus(this.#deps.git, { branch: this.#deps.branch, remote: this.#deps.remote ?? '' }) + const collected = await collectStatus(this.#deps.git, { branch: this.#deps.branch, remote: this.#deps.remote ?? '' }) + if (mirror === undefined) return collected + const diagnostics = this.#mirrorDiagnostics(mirror) + return { + ...collected, + skippedSymlinks: diagnostics.skippedSymlinks, + skippedSymlinkPaths: diagnostics.skippedSymlinkPaths, + followedSymlinks: diagnostics.followedSymlinks, + cwdMapped: diagnostics.cwdMapped, + cwdUnmapped: diagnostics.cwdUnmapped, + cwdProjectionSkipped: diagnostics.cwdProjectionSkipped, + cwdPlaceholder: diagnostics.cwdPlaceholder, + followSessionSymlinks: diagnostics.followSessionSymlinks, + warnings: diagnostics.warnings, + } }) } @@ -146,6 +196,7 @@ export class SyncEngine { const head = await this.#deps.git.headSha() this.#deps.reportMeta({ lastPushAt: Date.now(), lastPushHead: head, lastError: undefined }) this.#deps.logger.info(`sync push ok: head ${head ?? ''} (${mirror.mirrored} mirrored, ${mirror.deleted} deleted)`) + const diagnostics = this.#mirrorDiagnostics(mirror) return { ok: true, pushed: true, @@ -153,6 +204,9 @@ export class SyncEngine { mirrored: mirror.mirrored, deleted: mirror.deleted.length, remote: sanitizeRemote(this.#deps.remote), + skippedSymlinks: diagnostics.skippedSymlinks, + skippedSymlinkPaths: diagnostics.skippedSymlinkPaths, + warnings: diagnostics.warnings, } } catch (error) { return this.#fail(error) @@ -231,7 +285,15 @@ export class SyncEngine { repoDir: this.#deps.repoDir, mirrorRoot, sessionRoot: this.#deps.sessionRoot, + cwdMap: this.#deps.cwdMap ?? [], }) + const pullWarnings = [] + if (restored.cwdUnmapped > 0) { + pullWarnings.push(`${restored.cwdUnmapped} restored session(s) have a cross-platform cwd and no cwdMap entry; they are visible read-only under ${path.join(this.#deps.sessionRoot, UNMAPPED_DIR)}`) + } + if (restored.cwdProjectionSkipped > 0) { + pullWarnings.push(`${restored.cwdProjectionSkipped} session file(s) could not be cwd-projected (unreadable header or legacy layout) and keep the origin device's cwd`) + } this.#deps.reportMeta({ lastPullAt: Date.now() }) this.#deps.logger.info(`sync pull ok: merged remote head ${remoteHead} → ${newHead ?? ''} (${result.appended} appended-both, ${result.diverged} diverged, ${result.forks.length} forks, ${restored.restored} restored, ${pruned.pruned.length} pulled-deletions)`) if (result.forks.length > 0) this.#deps.onForks(result.forks) @@ -244,7 +306,10 @@ export class SyncEngine { diverged: result.diverged, forks: result.forks, restored: restored.restored, + cwdMapped: restored.cwdMapped, + cwdUnmapped: restored.cwdUnmapped, head: newHead ?? undefined, + warnings: pullWarnings, } } diff --git a/lib/mirror.mjs b/lib/mirror.mjs index 0720a51..f859f06 100644 --- a/lib/mirror.mjs +++ b/lib/mirror.mjs @@ -2,40 +2,126 @@ // // 会话文件一律按不透明字节复制(JSONL/zstd 等物理编码属于宿主,插件不解析)。 // 安全边界: -// - 绝不跟随符号链接(源或目标为链接一律跳过并报告,杜绝写出根外); +// - 默认绝不跟随符号链接(源或目标为链接一律跳过并报告,杜绝写出根外); +// `followSessionSymlinks: true` 时只跟随 realpath 仍落在 sessionRoot 内的链接 +// (proot link2symlink 那类"可读但 dirent 报 symlink"的宿主,见 #30); // - 删除仅限工作树内、源已不存在、且非 fork 文件、非宿主私有产物的常规文件; // - fork 文件(FORK_NAME_RE)永不复制、永不删除——冲突双方字节的持久载体; // - 宿主私有会话产物(HOST_ARTIFACT_NAME_RE:session.lock / 迁移暂存)同样 // 永不复制、永不删除——运行时状态不属于可同步内容。 +// +// 跨平台 cwd 投影(#28):恢复时把 header.cwd 投成本机路径、文件落到宿主布局的 +// 投影位置;镜像里的字节仍是原设备的 header(见 lib/projection.mjs)。镜像枚举 +// 因此跳过投影位置,并按投影表把本地尾部接回镜像里的原首帧——推送出去的字节 +// 与对端追加的字节逐字节一致。 import { promises as fs } from 'node:fs' import path from 'node:path' import { createHash } from 'node:crypto' -import { FORK_NAME_RE, HOST_ARTIFACT_NAME_RE } from './constants.mjs' +import { FORK_NAME_RE, HOST_ARTIFACT_NAME_RE, UNMAPPED_DIR } from './constants.mjs' +import { + canonicalizeProjectedFile, + planRestoreFile, + readProjectionState, + writeProjectionState, +} from './projection.mjs' + +/** 跟随符号链接时允许的最大目录深度(防环耗尽栈)。 */ +const MAX_WALK_DEPTH = 64 + +/** 符号链接的 realpath 是否仍在 root 内(真实路径 containment)。 */ +function insideRoot(rootReal, targetReal) { + const rel = path.relative(rootReal, targetReal) + return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel)) +} -/** 递归枚举 root 下全部常规文件(POSIX 相对路径;符号链接跳过并回报)。 */ -async function listFiles(root) { +/** + * 递归枚举 root 下全部常规文件(POSIX 相对路径;符号链接默认跳过并回报)。 + * 跟随边界:只有当链接的 realpath 仍落在 `realpath(root)` 内时才读取/递归; + * 越界链接仍进 `skipped`。目录链接用 realpath 去环。 + * @param {string} root - 会话存储根。 + * @param {{followSymlinks?: boolean}} [options] - 是否跟随根内符号链接。 + * @returns {Promise<{files: {absolute: string, rel: string}[], skipped: string[], followed: string[]}>} 枚举结果。 + */ +async function listFiles(root, options = {}) { + const followSymlinks = options.followSymlinks === true const files = [] const skipped = [] - const walk = async (dir) => { + const followed = [] + const seenFiles = new Set() + const rootReal = followSymlinks ? await fs.realpath(root) : undefined + const visitedDirectories = new Set() + const walk = async (dir, depth) => { const entries = await fs.readdir(dir, { withFileTypes: true }) for (const entry of entries) { const absolute = path.join(dir, entry.name) + const rel = path.relative(root, absolute).split(path.sep).join('/') if (entry.isSymbolicLink()) { + if (!followSymlinks) { + skipped.push(absolute) + continue + } + if (depth > MAX_WALK_DEPTH) { + skipped.push(absolute) + continue + } + let targetReal + try { + targetReal = await fs.realpath(absolute) + } catch { + skipped.push(absolute) + continue + } + if (!insideRoot(/** @type {string} */ (rootReal), targetReal)) { + skipped.push(absolute) + continue + } + let stats + try { + stats = await fs.stat(absolute) + } catch { + skipped.push(absolute) + continue + } + if (stats.isDirectory()) { + if (visitedDirectories.has(targetReal)) continue + visitedDirectories.add(targetReal) + followed.push(rel) + await walk(absolute, depth + 1) + continue + } + if (stats.isFile()) { + if (seenFiles.has(rel)) continue + seenFiles.add(rel) + files.push({ absolute, rel }) + followed.push(rel) + continue + } skipped.push(absolute) continue } if (entry.isDirectory()) { - await walk(absolute) + if (followSymlinks) { + try { + const real = await fs.realpath(absolute) + if (visitedDirectories.has(real)) continue + visitedDirectories.add(real) + } catch { + continue + } + } + await walk(absolute, depth + 1) continue } if (entry.isFile()) { - files.push({ absolute, rel: path.relative(root, absolute).split(path.sep).join('/') }) + if (seenFiles.has(rel)) continue + seenFiles.add(rel) + files.push({ absolute, rel }) } } } - await walk(root) - return { files, skipped } + await walk(root, 0) + return { files, skipped, followed } } /** 拒绝任何解析后落在 root 之外的写入(含父目录 symlink 逃逸)。 */ @@ -67,7 +153,14 @@ async function writeIfDifferent(target, content, root) { // 目标不存在 → 照写。 } await fs.mkdir(path.dirname(target), { recursive: true }) - await fs.writeFile(target, content) + try { + await fs.writeFile(target, content) + } catch (error) { + // 只读投影副本(占位目录)由本插件写成 0o444;再次恢复前先解开写位。 + if (error?.code !== 'EACCES' && error?.code !== 'EPERM') throw error + await fs.chmod(target, 0o644).catch(() => {}) + await fs.writeFile(target, content) + } return true } @@ -89,7 +182,8 @@ async function readSourceSnapshot(repoDir) { /** @param {string} repoDir @param {Set} sourcePaths */ async function writeSourceSnapshot(repoDir, sourcePaths) { const target = path.join(repoDir, SOURCE_SNAPSHOT_FILE) - const payload = Buffer.from(`${JSON.stringify({ version: 1, sourcePaths: [...sourcePaths].sort() })}\n`) + const payload = Buffer.from(`${JSON.stringify({ version: 1, sourcePaths: [...sourcePaths].sort() })} +`) try { const st = await fs.stat(path.dirname(target)) if (!st.isDirectory()) return @@ -103,12 +197,16 @@ async function writeSourceSnapshot(repoDir, sourcePaths) { * 把 sessionRoot 镜像进 //…。 * 宿主私有会话产物(租约/迁移暂存,HOST_ARTIFACT_NAME_RE)既不复制、也不删除: * 它们是运行时状态,同步它们只会把某设备的瞬时状态变成另一侧的删除/噪音。 - * @param {object} deps - {sessionRoot, repoDir, mirrorDir, forkNameRe?}。 - * @returns {Promise<{mirrored: number, unchanged: number, skippedLinks: string[], deleted: string[], remotePreserved: string[], snapshotUnknown: boolean, forkedPreserved: string[], hostArtifactsSkipped: number, hostArtifactsPreserved: string[]}>} + * 跨平台 cwd 投影:投影位置(`projectedRel`)不作为镜像源;对应条目按投影表 + * 把本地追加尾部接回镜像首帧后写入**原路径**,镜像字节因此保持原设备视角。 + * @param {object} deps - {sessionRoot, repoDir, mirrorDir, forkNameRe?, followSessionSymlinks?, projectionState?}。 + * @returns {Promise<{mirrored: number, unchanged: number, skippedLinks: string[], followedLinks: string[], deleted: string[], remotePreserved: string[], snapshotUnknown: boolean, forkedPreserved: string[], hostArtifactsSkipped: number, hostArtifactsPreserved: string[], cwdMapped: number, cwdUnmapped: number, cwdProjectionSkipped: number, projectionError?: string}>} */ export async function mirrorSessionRoot(deps) { const forkRe = deps.forkNameRe ?? FORK_NAME_RE - const source = await listFiles(deps.sessionRoot) + const projectionState = deps.projectionState ?? await readProjectionState(deps.repoDir) + const projectedRels = new Set(projectionState.entries.map(entry => entry.projectedRel)) + const source = await listFiles(deps.sessionRoot, { followSymlinks: deps.followSessionSymlinks === true }) const mirrorRoot = path.join(deps.repoDir, deps.mirrorDir) const targets = new Set() const previous = await readSourceSnapshot(deps.repoDir) @@ -116,7 +214,11 @@ export async function mirrorSessionRoot(deps) { let mirrored = 0 let unchanged = 0 let hostArtifactsSkipped = 0 + let cwdProjectionSkipped = 0 + let cwdMapped = 0 + let cwdUnmapped = 0 for (const file of source.files) { + if (projectedRels.has(file.rel)) continue if (HOST_ARTIFACT_NAME_RE.test(path.posix.basename(file.rel))) { hostArtifactsSkipped += 1 continue @@ -128,6 +230,42 @@ export async function mirrorSessionRoot(deps) { else unchanged += 1 } + // 投影条目:本地投影副本存在 → 镜像原路径必须继续受保护(删除保护), + // 且只在可推送(非占位只读)时把本地尾部接回原首帧后覆写。 + for (const entry of projectionState.entries) { + let local + const localPath = path.join(deps.sessionRoot, ...entry.projectedRel.split('/')) + try { + const localStat = await fs.lstat(localPath) + // 投影副本必须是常规文件:绝不经符号链接读取(根内跟随只对镜像源开放)。 + if (localStat.isSymbolicLink() || !localStat.isFile()) continue + local = await fs.readFile(localPath) + } catch { + continue + } + targets.add(entry.canonicalRel) + let mirrorExisting + try { + mirrorExisting = await fs.readFile(path.join(mirrorRoot, ...entry.canonicalRel.split('/'))) + } catch { + mirrorExisting = undefined + } + // 占位(只读视图)永不作为推送源;可映射条目要求本地首帧仍是投影形状。 + if (entry.readOnly === true) { + cwdUnmapped += 1 + continue + } + const canonical = canonicalizeProjectedFile({ entry, localContent: local, mirrorContent: mirrorExisting }) + if (canonical === undefined) { + cwdProjectionSkipped += 1 + continue + } + cwdMapped += 1 + const wrote = await writeIfDifferent(path.join(mirrorRoot, ...entry.canonicalRel.split('/')), canonical, deps.repoDir) + if (wrote) mirrored += 1 + else unchanged += 1 + } + // 删除:目标树中源已不存在、且非 fork 命名、非宿主私有产物的文件。 const deleted = [] const remotePreserved = [] @@ -174,7 +312,22 @@ export async function mirrorSessionRoot(deps) { } await writeSourceSnapshot(deps.repoDir, targets) - return { mirrored, unchanged, skippedLinks: source.skipped, deleted, remotePreserved, snapshotUnknown: previous === undefined, forkedPreserved, hostArtifactsSkipped, hostArtifactsPreserved } + return { + mirrored, + unchanged, + skippedLinks: source.skipped, + followedLinks: source.followed, + deleted, + remotePreserved, + snapshotUnknown: previous === undefined, + forkedPreserved, + hostArtifactsSkipped, + hostArtifactsPreserved, + cwdMapped, + cwdUnmapped, + cwdProjectionSkipped, + projectionError: projectionState.error, + } } /** 恢复状态文件:本地、不进提交、不随仓库同步。 */ @@ -226,20 +379,22 @@ async function mirrorRelSet(root) { } /** - * Remove live-store copies that this plugin restored from a previous pull and - * that the remote has now deleted, but only while the live bytes still match - * the restored hash. A user-edited copy is kept (and will push normally). - * @param {{repoDir: string, mirrorRoot: string, sessionRoot: string}} deps + * 删除本插件曾经从某次 pull 恢复、且远端随后删除的本机副本;只有当前字节仍等于 + * 记录的哈希时才删(用户改过的副本保留并照常推送)。投影位置通过投影表映射回 + * 镜像相对路径。 + * @param {{repoDir: string, mirrorRoot: string, sessionRoot: string, projectionState?: object}} deps * @returns {Promise<{pruned: string[], keptEdited: string[]}>} */ export async function pruneRestoredSessions(deps) { const state = await readRestoreState(deps.repoDir) if (state.size === 0) return { pruned: [], keptEdited: [] } + const projectionState = deps.projectionState ?? await readProjectionState(deps.repoDir) const mirror = await mirrorRelSet(deps.mirrorRoot) const pruned = [] const keptEdited = [] for (const [rel, expected] of [...state]) { - if (mirror.has(rel)) continue + const canonicalRel = projectionState.byProjected.get(rel)?.canonicalRel ?? rel + if (mirror.has(canonicalRel)) continue const target = path.join(deps.sessionRoot, ...rel.split('/')) try { const st = await fs.lstat(target) @@ -263,47 +418,138 @@ export async function pruneRestoredSessions(deps) { /** * Copy the merged mirror back into the live session store. Pull used to merge only * into the mirror; the next push then saw those files as "missing locally" and - * unlinked them. This writes new/changed regular files back, never deletes, never - * follows symlinks, and never writes fork files or host-private artifacts. - * @param {object} deps - {repoDir, mirrorRoot, sessionRoot, forkNameRe?}. - * @returns {Promise<{restored: number, unchanged: number, skipped: number, tracked: number}>} + * unlinked them. This writes new/changed regular files back, never deletes, + * never follows symlinks, and never writes fork files or host-private artifacts. + * + * 跨平台 cwd 投影(#28):需要投影的会话写到宿主布局的投影位置 + * (`//`)并改写首帧 cwd;镜像里的原 + * 路径不落盘(同一会话 id 不能同时出现在两个项目目录)。投影表落在本地 + * `.git/` 下,推送时用于把原首帧接回。 + * @param {object} deps - {repoDir, mirrorRoot, sessionRoot, forkNameRe?, cwdMap?, platform?}。 + * @returns {Promise<{restored: number, unchanged: number, skipped: number, tracked: number, cwdMapped: number, cwdUnmapped: number, cwdProjectionSkipped: number, projectionError?: string}>} */ export async function restoreSessionRoot(deps) { const forkRe = deps.forkNameRe ?? FORK_NAME_RE + const mirrorRoot = deps.mirrorRoot let entries try { - entries = await fs.readdir(deps.mirrorRoot, { recursive: true, withFileTypes: true }) + entries = await fs.readdir(mirrorRoot, { recursive: true, withFileTypes: true }) } catch { - return { restored: 0, unchanged: 0, skipped: 0, tracked: 0 } + return { restored: 0, unchanged: 0, skipped: 0, tracked: 0, cwdMapped: 0, cwdUnmapped: 0, cwdProjectionSkipped: 0 } } + const previous = await readProjectionState(deps.repoDir) + const nextEntries = [] + const nextRelSet = new Set() let restored = 0 let unchanged = 0 let skipped = 0 + let cwdMapped = 0 + let cwdUnmapped = 0 + let cwdProjectionSkipped = 0 const state = deps.repoDir === undefined ? new Map() : await readRestoreState(deps.repoDir) for (const entry of entries) { if (!entry.isFile()) { skipped += 1; continue } - const parent = entry.parentPath ?? entry.path ?? deps.mirrorRoot + const parent = entry.parentPath ?? entry.path ?? mirrorRoot const absolute = path.join(parent, entry.name) - const rel = path.relative(deps.mirrorRoot, absolute).split(path.sep).join('/') + const rel = path.relative(mirrorRoot, absolute).split(path.sep).join('/') const basename = path.posix.basename(rel) if (forkRe.test(basename) || HOST_ARTIFACT_NAME_RE.test(basename)) { skipped += 1; continue } - const target = path.join(deps.sessionRoot, ...rel.split('/')) + const content = await fs.readFile(absolute) + const plan = planRestoreFile({ + content, + mirrorRel: rel, + cwdMap: deps.cwdMap ?? [], + sessionRoot: deps.sessionRoot, + platform: deps.platform, + }) + if (plan.kind === 'skipped') { + cwdProjectionSkipped += 1 + // 无法投影(如 id 与目录不符):保持镜像原样落盘,绝不写坏布局。 + } + if (plan.kind === 'mapped') cwdMapped += 1 + if (plan.kind === 'placeholder') cwdUnmapped += 1 + if (plan.entry !== undefined) { + nextEntries.push(plan.entry) + // 映射目标 / 占位目录必须真实存在,宿主才能 realpath 并把它归入 workspace + // (失败不影响可读性:会话仍会以 ungrouped 出现在列表里)。 + await fs.mkdir(plan.entry.projectedCwd, { recursive: true }).catch(() => {}) + } + nextRelSet.add(plan.rel) + const target = path.join(deps.sessionRoot, ...plan.rel.split('/')) let existed = false try { const st = await fs.lstat(target) if (st.isSymbolicLink()) { skipped += 1; continue } existed = true } catch { /* target absent */ } - const content = await fs.readFile(absolute) - const wrote = await writeIfDifferent(target, content, deps.sessionRoot) + const wrote = await writeIfDifferent(target, plan.content, deps.sessionRoot) if (wrote) restored += 1 else unchanged += 1 + // 占位投影是只读视图:尽力在文件系统层面也标注只读(root 可写时由推送端 + // 兜底——占位条目永不作为推送源)。 + if (plan.kind === 'placeholder') await fs.chmod(target, 0o444).catch(() => {}) // Track only copies this plugin created (target absent before) or already // tracked. A pre-existing user file is never claimed by the sync plugin. - if (!existed || state.has(rel)) state.set(rel, hashContent(content)) + if (!existed || state.has(plan.rel)) state.set(plan.rel, hashContent(plan.content)) + // 投影位置与原路径不同:清掉旧版或旧映射遗留在原路径上的本机副本,否则 + // 宿主会把同一 session id 看成两个项目里的重复会话。 + if (plan.rel !== rel) { + const legacyTarget = path.join(deps.sessionRoot, ...rel.split('/')) + let legacyStat + try { + legacyStat = await fs.lstat(legacyTarget) + } catch { + legacyStat = undefined + } + if (legacyStat?.isFile() === true) { + const legacyContent = await fs.readFile(legacyTarget) + const tracked = state.get(rel) + if (legacyContent.equals(content) || (tracked !== undefined && hashContent(legacyContent) === tracked)) { + await fs.unlink(legacyTarget) + state.delete(rel) + } + } + } + } + // 失效投影清理:配置变更(映射删除/改写)后,旧投影位置上的副本若仍是本插件 + // 写的字节,就删掉;否则保留并让状态记录它(用户改动优先)。 + for (const oldEntry of previous.entries) { + if (nextRelSet.has(oldEntry.projectedRel)) continue + const oldTarget = path.join(deps.sessionRoot, ...oldEntry.projectedRel.split('/')) + let oldStat + try { + oldStat = await fs.lstat(oldTarget) + } catch { + oldStat = undefined + } + if (oldStat?.isFile() !== true) continue + const expected = state.get(oldEntry.projectedRel) + try { + const oldContent = await fs.readFile(oldTarget) + // 只删"本插件上次恢复、且此后没人改动"的副本:无哈希记录或字节已变都保留 + // (用户改动优先,宁可留下一个可见副本也不误删数据)。 + if (expected !== undefined && hashContent(oldContent) === expected) { + await fs.unlink(oldTarget) + state.delete(oldEntry.projectedRel) + } + } catch { + // 读不到就不删(安全优先)。 + } + } + if (deps.repoDir !== undefined) { + await writeRestoreState(deps.repoDir, state) + await writeProjectionState(deps.repoDir, nextEntries) + } + return { + restored, + unchanged, + skipped, + tracked: state.size, + cwdMapped, + cwdUnmapped, + cwdProjectionSkipped, + projectionError: previous.error, } - if (deps.repoDir !== undefined) await writeRestoreState(deps.repoDir, state) - return { restored, unchanged, skipped, tracked: state.size } } /** @@ -318,3 +564,5 @@ export async function ensureDeviceFile(repoDir, deviceFile, deviceId) { const content = Buffer.from(`${deviceId}\n`) return writeIfDifferent(target, content) } + +export { UNMAPPED_DIR } diff --git a/lib/projection.mjs b/lib/projection.mjs new file mode 100644 index 0000000..76559f4 --- /dev/null +++ b/lib/projection.mjs @@ -0,0 +1,191 @@ +// lib/projection.mjs — 恢复期 cwd 投影表(本地状态;镜像字节保持原样)。 +// +// 恢复时,跨平台会话被写到宿主布局中的**投影位置** +// (`//`)并把首帧 cwd 换成本机路径。 +// 同步仓库(镜像)里仍是原设备的 header——投影表只落在本地 `.git/` 下、不进 +// 提交,记录 canonicalRel ↔ projectedRel、原始 cwd 与首帧字节,供推送时把本地 +// 追加尾部接回原首帧(对端看到的仍是逐字节 append)。 +// +// 不可解析的日志/状态一律"保持原样":本模块绝不猜测字节,也绝不让一份看不懂的 +// 会话变成一次写坏布局的操作。 + +import { promises as fs } from 'node:fs' +import path from 'node:path' +import { decodeSegment } from './paths.mjs' +import { projectCwd, projectedRelOf } from './cwdmap.mjs' +import { + SESSION_LOG_NAME_RE, + encodeSessionHeader, + isCompressedName, + readSessionHeader, +} from './sessionlog.mjs' + +/** 投影表状态文件(本地、不进提交)。 */ +export const PROJECTION_STATE_FILE = path.join('.git', 'dsh-session-sync-projection.json') + +const STATE_VERSION = 1 +/** header 首帧的缓存上限:超过就不缓存(推送时退回重新压缩)。 */ +const MAX_HEADER_FRAME_BYTES = 64 * 1024 + +/** + * 空投影表。 + * @returns {{entries: object[], byCanonical: Map, byProjected: Map, error?: string}} 投影表。 + */ +function emptyProjection() { + return { entries: [], byCanonical: new Map(), byProjected: new Map() } +} + +/** + * 由条目数组建投影表(按 canonical/projected 双向索引)。 + * @param {object[]} entries - 投影条目。 + * @returns {{entries: object[], byCanonical: Map, byProjected: Map}} 投影表。 + */ +function indexProjection(entries) { + const byCanonical = new Map() + const byProjected = new Map() + for (const entry of entries) { + byCanonical.set(entry.canonicalRel, entry) + byProjected.set(entry.projectedRel, entry) + } + return { entries, byCanonical, byProjected } +} + +/** + * 读取投影表。缺失 = 空表(尚未投影过);损坏 = 空表 + error(fail closed: + * 不投影、不把本地视图当推送源)。 + * @param {string|undefined} repoDir - 同步仓库根。 + * @returns {Promise<{entries: object[], byCanonical: Map, byProjected: Map, error?: string}>} 投影表。 + */ +export async function readProjectionState(repoDir) { + if (typeof repoDir !== 'string' || repoDir.length === 0) return emptyProjection() + let raw + try { + raw = await fs.readFile(path.join(repoDir, PROJECTION_STATE_FILE), 'utf8') + } catch { + return emptyProjection() + } + let parsed + try { + parsed = JSON.parse(raw) + } catch { + return { ...emptyProjection(), error: 'projection state is not valid JSON (run a pull to rebuild it)' } + } + if (parsed === null || typeof parsed !== 'object' || parsed.version !== STATE_VERSION || !Array.isArray(parsed.entries)) { + return { ...emptyProjection(), error: 'projection state has an unsupported shape (run a pull to rebuild it)' } + } + const entries = [] + for (const entry of parsed.entries) { + if (entry === null || typeof entry !== 'object') continue + if (typeof entry.canonicalRel !== 'string' || typeof entry.projectedRel !== 'string') continue + if (typeof entry.originalCwd !== 'string' || typeof entry.projectedCwd !== 'string') continue + if (typeof entry.id !== 'string' || typeof entry.readOnly !== 'boolean') continue + entries.push({ + canonicalRel: entry.canonicalRel, + projectedRel: entry.projectedRel, + id: entry.id, + originalCwd: entry.originalCwd, + projectedCwd: entry.projectedCwd, + readOnly: entry.readOnly, + compressed: entry.compressed === true, + headerFrame: typeof entry.headerFrame === 'string' ? entry.headerFrame : undefined, + }) + } + return indexProjection(entries) +} + +/** + * 写投影表(原子替换;`.git` 不存在时静默跳过——等价于不持久化)。 + * @param {string|undefined} repoDir - 同步仓库根。 + * @param {object[]} entries - 新投影条目。 + * @returns {Promise} + */ +export async function writeProjectionState(repoDir, entries) { + if (typeof repoDir !== 'string' || repoDir.length === 0) return + const target = path.join(repoDir, PROJECTION_STATE_FILE) + try { + const st = await fs.stat(path.dirname(target)) + if (!st.isDirectory()) return + } catch { + return + } + const payload = Buffer.from(`${JSON.stringify({ version: STATE_VERSION, entries: [...entries].sort((a, b) => a.canonicalRel.localeCompare(b.canonicalRel)) })} +`) + const temporary = `${target}.${process.pid}.tmp` + await fs.writeFile(temporary, payload) + await fs.rename(temporary, target) +} + +/** + * 规划一个镜像文件在恢复时的落盘形态。 + * @param {{content: Buffer, mirrorRel: string, cwdMap: ReadonlyArray, sessionRoot: string, platform?: NodeJS.Platform}} deps - 文件与配置。 + * @returns {{rel: string, content: Buffer, kind: 'as-is'|'mapped'|'placeholder'|'skipped', entry?: object}} 落盘计划。 + */ +export function planRestoreFile(deps) { + const name = path.posix.basename(deps.mirrorRel) + const asIs = { rel: deps.mirrorRel, content: deps.content, kind: /** @type {const} */ ('as-is') } + if (!SESSION_LOG_NAME_RE.test(name)) return asIs + const compressed = isCompressedName(name) + const parsed = readSessionHeader(deps.content, compressed) + if (parsed === undefined || typeof parsed.header.cwd !== 'string') return asIs + const parts = deps.mirrorRel.split('/') + // 宿主布局 = //;旧扁平布局不投影(否则路径语义 + // 不对,宁可不改)。 + if (parts.length < 3) return asIs + if (decodeSegment(parts[1]) !== parsed.header.id) { + return { ...asIs, kind: 'skipped' } + } + const projection = projectCwd(parsed.header.cwd, { + map: deps.cwdMap, + sessionRoot: deps.sessionRoot, + platform: deps.platform, + }) + if (!projection.mapped && !projection.unmapped) return asIs + const rel = projectedRelOf(deps.mirrorRel, /** @type {string} */ (projection.cwd)) + if (rel === undefined || rel === deps.mirrorRel) return asIs + const header = { ...parsed.header, cwd: projection.cwd } + const entry = { + canonicalRel: deps.mirrorRel, + projectedRel: rel, + id: parsed.header.id, + originalCwd: parsed.header.cwd, + projectedCwd: projection.cwd, + readOnly: projection.readOnly, + compressed, + headerFrame: parsed.frame.length <= MAX_HEADER_FRAME_BYTES ? parsed.frame.toString('base64') : undefined, + } + return { + rel, + content: Buffer.concat([encodeSessionHeader(header, compressed), parsed.rest]), + kind: projection.readOnly ? 'placeholder' : 'mapped', + entry, + } +} + +/** + * 把本机投影副本还原成镜像字节:镜像里的原首帧 + 本地追加尾部。 + * 占位(只读视图)与 header 被改动的副本一律返回 undefined(永不推送)。 + * @param {{entry: object, localContent: Buffer, mirrorContent?: Buffer}} deps - 投影条目与两侧字节。 + * @returns {Buffer|undefined} 可推送的镜像字节。 + */ +export function canonicalizeProjectedFile(deps) { + const entry = deps.entry + if (entry.readOnly === true) return undefined + if (!Buffer.isBuffer(deps.localContent)) return undefined + const local = readSessionHeader(deps.localContent, entry.compressed === true) + if (local === undefined) return undefined + if (local.header.id !== entry.id) return undefined + if (local.header.cwd !== entry.projectedCwd) return undefined + let headerFrame + if (Buffer.isBuffer(deps.mirrorContent)) { + const mirror = readSessionHeader(deps.mirrorContent, entry.compressed === true) + // 镜像 header 可能被对端迁移更新过:优先沿用它的首帧,保证不丢更新。 + if (mirror !== undefined && mirror.header.id === entry.id) headerFrame = mirror.frame + } + if (headerFrame === undefined && typeof entry.headerFrame === 'string') { + headerFrame = Buffer.from(entry.headerFrame, 'base64') + } + if (headerFrame === undefined) { + headerFrame = encodeSessionHeader({ ...local.header, cwd: entry.originalCwd }, entry.compressed === true) + } + return Buffer.concat([headerFrame, local.rest]) +} diff --git a/lib/render.mjs b/lib/render.mjs index a7a5cfb..b08079b 100644 --- a/lib/render.mjs +++ b/lib/render.mjs @@ -30,6 +30,16 @@ export function renderStatus(status) { if (status.forks.length > 0) { lines.push(` fork files (both-sides-kept conflicts): ${status.forks.slice(0, 10).join(', ')}${status.forks.length > 10 ? ' …' : ''}`) } + if ((status.cwdMapped ?? 0) > 0 || (status.cwdUnmapped ?? 0) > 0) { + lines.push(` cwd projection: ${status.cwdMapped ?? 0} mapped to local path(s), ${status.cwdUnmapped ?? 0} unmapped (read-only under ${status.cwdPlaceholder ?? 'sessionRoot/--unmapped--'})`) + } + if ((status.followedSymlinks ?? 0) > 0) { + lines.push(` followed symbolic links inside sessionRoot: ${status.followedSymlinks}`) + } + if ((status.skippedSymlinks ?? 0) > 0) { + const sample = (status.skippedSymlinkPaths ?? []).slice(0, 5).join(', ') + lines.push(` skipped symbolic links (not mirrored; followSessionSymlinks=${status.followSessionSymlinks === true}): ${status.skippedSymlinks}${sample.length > 0 ? ` — ${sample}${status.skippedSymlinks > 5 ? ' …' : ''}` : ''}`) + } if (status.diffStat !== '') { lines.push(` diff HEAD..remote:\n${status.diffStat.split('\n').map(line => ` ${line}`).join('\n')}`) } @@ -62,7 +72,7 @@ export function renderDiff(status) { /** * pull 结果文本。 - * @param {{ok: boolean, pulled?: boolean, merged?: boolean, adopted?: number, appended?: number, diverged?: number, forks?: string[], head?: string, error?: string, warnings?: string[]}} result - pull 产物。 + * @param {{ok: boolean, pulled?: boolean, merged?: boolean, adopted?: number, appended?: number, diverged?: number, forks?: string[], head?: string, restored?: number, cwdMapped?: number, cwdUnmapped?: number, error?: string, warnings?: string[]}} result - pull 产物。 * @returns {string} */ export function renderPull(result) { @@ -76,6 +86,8 @@ export function renderPull(result) { if ((result.adopted ?? 0) > 0) lines.push(` adopted ${result.adopted} remote-only append(s) (local side was unchanged)`) if ((result.appended ?? 0) > 0) lines.push(` both sides appended in ${result.appended} file(s): local version kept, remote version preserved as fork file(s)`) if ((result.diverged ?? 0) > 0) lines.push(` diverged in ${result.diverged} file(s) (non-append rewrite): local version kept, remote version preserved as fork file(s) — inspect before continuing`) + if ((result.cwdMapped ?? 0) > 0) lines.push(` cwd projection: ${result.cwdMapped} restored session(s) mapped to a local path (header on disk is local; the mirror keeps the origin device's bytes)`) + if ((result.cwdUnmapped ?? 0) > 0) lines.push(` cwd projection: ${result.cwdUnmapped} restored session(s) have no cwdMap entry — shown read-only under the --unmapped-- placeholder`) for (const fork of (result.forks ?? []).slice(0, 20)) lines.push(` fork ${fork}`) if ((result.forks ?? []).length > 20) lines.push(` … ${result.forks.length - 20} more`) for (const warning of (result.warnings ?? [])) lines.push(` warning: ${warning}`) @@ -84,7 +96,7 @@ export function renderPull(result) { /** * push 结果文本。 - * @param {{ok: boolean, pushed?: boolean, head?: string, mirrored?: number, deleted?: number, remote?: string, error?: string, warnings?: string[]}} result - push 产物。 + * @param {{ok: boolean, pushed?: boolean, head?: string, mirrored?: number, deleted?: number, remote?: string, skippedSymlinks?: number, skippedSymlinkPaths?: string[], error?: string, warnings?: string[]}} result - push 产物。 * @returns {string} */ export function renderPush(result) { @@ -95,6 +107,9 @@ export function renderPush(result) { ` mirrored ${result.mirrored ?? 0} file(s)${(result.deleted ?? 0) > 0 ? `, deleted ${result.deleted} (removed locally)` : ''}`, ` pushed to ${result.remote ?? 'remote'} → head ${result.head ?? ''}`, ] + if ((result.skippedSymlinks ?? 0) > 0) { + lines.push(` skipped ${result.skippedSymlinks} symbolic link(s) under sessionRoot (not mirrored; set followSessionSymlinks: true to include links inside the root)`) + } for (const warning of (result.warnings ?? [])) lines.push(` warning: ${warning}`) return lines.join('\n') } diff --git a/lib/sessionlog.mjs b/lib/sessionlog.mjs new file mode 100644 index 0000000..9723ac1 --- /dev/null +++ b/lib/sessionlog.mjs @@ -0,0 +1,142 @@ +// lib/sessionlog.mjs — 会话日志首帧(header)读取/改写(零 DSH 依赖,仅 node:zlib)。 +// +// 宿主 session-persistence-jsonl 把每个会话写成一串**独立的 zstd 帧**:第一帧 +// 只含 header 行,之后每个追加批次各一帧(`compression: none` 时是纯 JSONL, +// header 就是第一行)。追加从不重写已提交帧。因此投影只需要替换第一帧/第一行, +// 其余字节原样保留——这也让反向投影可以"把镜像里的原首帧接回本地尾部",追加 +// 事件仍逐字节相同(append-only 合并语义不受影响)。 +// +// 本模块只做结构性扫描与解压/压缩;任何不可解析的输入都返回 undefined,由调用方 +// 保持文件原样(绝不猜测、绝不改写看不懂的字节)。 + +import { constants, zstdCompressSync, zstdDecompressSync } from 'node:zlib' + +const ZSTD_MAGIC = 0xFD2FB528 +// 与宿主 compressZstdFrame 同参数(带 checksum 的 zstd 帧)。 +const ZSTD_CHECKSUM_OPTIONS = { params: { [constants.ZSTD_c_checksumFlag]: 1 } } + +/** 宿主会话日志文件名:`session.v.jsonl` 或 `session.v.jsonl.zstd`。 */ +export const SESSION_LOG_NAME_RE = /^session\.v\d+\.jsonl(?:\.zstd)?$/u + +/** + * 扩展名是否表示 zstd 编码。 + * @param {string} name - 文件名。 + * @returns {boolean} `.zstd` 结尾为 true。 + */ +export function isCompressedName(name) { + return typeof name === 'string' && name.endsWith('.zstd') +} + +/** + * 扫描首个完整 zstd 帧的结束偏移(只走结构,不解压)。 + * 参考 zstd 帧格式:magic + frame header descriptor + 可选字段 + blocks + 可选 + * checksum。任何结构损坏/尾部不完整都返回 undefined。 + * @param {Buffer} buffer - 文件字节。 + * @returns {number|undefined} 首帧的排他结束偏移。 + */ +function firstFrameEnd(buffer) { + let offset = 0 + if (buffer.length < 4) return undefined + if (buffer.readUInt32LE(offset) !== ZSTD_MAGIC) return undefined + offset += 4 + if (offset === buffer.length) return undefined + const descriptor = buffer.readUInt8(offset) + offset += 1 + if ((descriptor & 0x18) !== 0) return undefined + const contentSizeFlag = descriptor >>> 6 + const singleSegment = (descriptor & 0x20) !== 0 + const checksum = (descriptor & 0x04) !== 0 + const dictionaryFlag = descriptor & 0x03 + const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag + const contentSizeBytes = contentSizeFlag === 0 + ? (singleSegment ? 1 : 0) + : 1 << contentSizeFlag + const remainingHeaderBytes = (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes + if (buffer.length - offset < remainingHeaderBytes) return undefined + offset += remainingHeaderBytes + for (;;) { + if (buffer.length - offset < 3) return undefined + const blockHeader = buffer.readUIntLE(offset, 3) + offset += 3 + const lastBlock = (blockHeader & 1) !== 0 + const blockType = (blockHeader >>> 1) & 0x03 + const blockSize = blockHeader >>> 3 + if (blockType === 0x03) return undefined + const payloadBytes = blockType === 0x01 ? 1 : blockSize + if (buffer.length - offset < payloadBytes) return undefined + offset += payloadBytes + if (lastBlock) break + } + if (checksum) { + if (buffer.length - offset < 4) return undefined + offset += 4 + } + return offset +} + +/** + * 读取会话日志的 header 行(首帧/首行)与其余字节。 + * @param {Buffer} buffer - 文件字节。 + * @param {boolean} compressed - 是否 zstd 编码。 + * @returns {{header: {type: string, id: string, cwd?: string, [key: string]: unknown}, text: string, frame: Buffer, rest: Buffer}|undefined} 解析结果。 + */ +export function readSessionHeader(buffer, compressed) { + if (!Buffer.isBuffer(buffer)) return undefined + let frame + let text + let rest + if (compressed) { + const end = firstFrameEnd(buffer) + if (end === undefined) return undefined + frame = buffer.subarray(0, end) + rest = buffer.subarray(end) + try { + text = zstdDecompressSync(frame).toString('utf8') + } catch { + return undefined + } + } else { + const newline = buffer.indexOf(0x0a) + if (newline < 0) return undefined + frame = buffer.subarray(0, newline + 1) + text = frame.toString('utf8') + rest = buffer.subarray(newline + 1) + } + if (!text.endsWith('\n')) return undefined + const line = text.slice(0, -1) + if (line.length === 0 || line.includes('\n')) return undefined + let header + try { + header = JSON.parse(line) + } catch { + return undefined + } + if (header === null || typeof header !== 'object' || Array.isArray(header)) return undefined + if (header.type !== 'session' || typeof header.id !== 'string' || header.id.length === 0) return undefined + if (header.cwd !== undefined && typeof header.cwd !== 'string') return undefined + return { header: /** @type {{type: string, id: string, cwd?: string, [key: string]: unknown}} */ (header), text, frame, rest } +} + +/** + * 编码一个 header 行为独立帧(zstd 时与宿主同参数,含 checksum)。 + * @param {{type: string, id: string, [key: string]: unknown}} header - header 对象。 + * @param {boolean} compressed - 是否 zstd 编码。 + * @returns {Buffer} 首帧/首行字节。 + */ +export function encodeSessionHeader(header, compressed) { + const line = Buffer.from(`${JSON.stringify(header)}\n`, 'utf8') + return compressed ? zstdCompressSync(line, ZSTD_CHECKSUM_OPTIONS) : line +} + +/** + * 用新 header 替换首帧/首行,其余字节原样保留。 + * @param {Buffer} buffer - 原文件字节。 + * @param {boolean} compressed - 是否 zstd 编码。 + * @param {{type: string, id: string, cwd?: string, [key: string]: unknown}} header - 新 header。 + * @returns {Buffer|undefined} 改写后的字节;输入不可解析时 undefined。 + */ +export function rewriteSessionHeader(buffer, compressed, header) { + const parsed = readSessionHeader(buffer, compressed) + if (parsed === undefined) return undefined + return Buffer.concat([encodeSessionHeader(header, compressed), parsed.rest]) +} diff --git a/package.json b/package.json index 7403ff8..5571908 100644 --- a/package.json +++ b/package.json @@ -129,6 +129,7 @@ "@deepseek-ai/dsh-llm": "0.2.2-rc.1", "@deepseek-ai/dsh-session": "0.2.2-rc.1", "@deepseek-ai/dsh-session-format-v3-to-v4": "0.2.2-rc.1", + "@deepseek-ai/dsh-session-persistence-jsonl": "0.2.2-rc.1", "@deepseek-ai/dsh-storage": "0.2.2-rc.1", "@deepseek-ai/dsh-storage-domain": "0.2.2-rc.1", "@deepseek-ai/dsh-storage-json": "0.2.2-rc.1", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0ee9a04..f6ea5a6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -16,7 +16,7 @@ importers: dependencies: '@deepseek-ai/dsh-session-projection': specifier: '>=0.1.2-rc.1 <0.2.0 || >=0.1.5-alpha.1 <0.2.0 || >=0.1.6-0 <0.2.0 || >=0.1.7-0 <0.2.0 || >=0.2.0-0 <0.3.0 || >=0.2.1-0 <0.3.0 || >=0.2.2-0 <0.3.0' - version: 0.1.6-alpha.2(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))) + version: 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))) zod: specifier: 4.4.3 version: 4.4.3 @@ -35,7 +35,7 @@ importers: version: 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-brand@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) '@deepseek-ai/dsh-commands': specifier: 0.2.2-rc.1 - version: 0.2.2-rc.1(faf5a5eef4aed53aec4d196dbf50657c) + version: 0.2.2-rc.1(70cead30406fe58b6b8b8640601f81fb) '@deepseek-ai/dsh-llm': specifier: 0.2.2-rc.1 version: 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) @@ -48,6 +48,9 @@ importers: '@deepseek-ai/dsh-session-format-v3-to-v4': specifier: 0.2.2-rc.1 version: 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) + '@deepseek-ai/dsh-session-persistence-jsonl': + specifier: 0.2.2-rc.1 + version: 0.2.2-rc.1(2603e2cb22b0dc1a9586cfa110fd10f5) '@deepseek-ai/dsh-storage': specifier: 0.2.2-rc.1 version: 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) @@ -65,16 +68,16 @@ importers: version: 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) '@deepseek-ai/dsh-tools': specifier: 0.2.2-rc.1 - version: 0.2.2-rc.1(c03b195971be4da93d8dc15a5e5e26c4) + version: 0.2.2-rc.1(a13a0f05e8644f33708fe2540ec79e5a) '@deepseek-ai/dsh-user-approval': specifier: 0.2.2-rc.1 - version: 0.2.2-rc.1(85d5fee1657efb4133740ce13435734d) + version: 0.2.2-rc.1(3bd6a1f1902d3e43ac1e8f819c08387c) '@deepseek-ai/dsh-user-questions': specifier: 0.2.2-rc.1 - version: 0.2.2-rc.1(356643d3c097d375ce0bfe90e809159e) + version: 0.2.2-rc.1(2c05509f73576205c7dab735b58f9829) '@deepseek-ai/dsh-working-directory': specifier: 0.2.2-rc.1 - version: 0.2.2-rc.1(222c5866fa4da5f096b83061641f4efa) + version: 0.2.2-rc.1(523417378dd3f3049068ec93f993992c) '@deepseek-ai/schemastery': specifier: 3.19.0 version: 3.19.0 @@ -159,6 +162,24 @@ packages: '@deepseek-ai/dsh-session': 0.2.2-rc.1 '@deepseek-ai/dsh-typert-protocol': 0.2.2-rc.1 + '@deepseek-ai/dsh-compaction-image-offload@0.2.2-rc.1': + resolution: {integrity: sha512-xnGqqDYiM1zLqkvuRWzZdXCvjTbE2m1ia8T+T9Xd/LeE+p0yNvru3xjLLcaJdta13mBXldCDiZDXYeA30yy0gw==} + peerDependencies: + '@deepseek-ai/cordis': 4.1.0 + '@deepseek-ai/dsh-agent': 0.2.2-rc.1 + '@deepseek-ai/dsh-compaction': 0.2.2-rc.1 + '@deepseek-ai/dsh-llm': 0.2.2-rc.1 + '@deepseek-ai/dsh-session': 0.2.2-rc.1 + + '@deepseek-ai/dsh-compaction@0.2.2-rc.1': + resolution: {integrity: sha512-KWn/GpZ5adrSkS4O6U25gvVdtNG4D8tZ/xdUCsIEftveCJvT4R0s38PPcmIALS92jxHjrrCa6msVanW3lh1S1Q==} + peerDependencies: + '@deepseek-ai/cordis': 4.1.0 + '@deepseek-ai/dsh-brand': 0.2.2-rc.1 + '@deepseek-ai/dsh-commands': 0.2.2-rc.1 + '@deepseek-ai/dsh-llm': 0.2.2-rc.1 + '@deepseek-ai/dsh-session': 0.2.2-rc.1 + '@deepseek-ai/dsh-fs-patch@0.2.2-rc.1': resolution: {integrity: sha512-I9uMZxHl+aB5zHzb4Je8PIT32+BMco6iC6nn0tMGa5SvfwPt8WO0Bj/HZIVqOhZIhVVtNL3aiA6YL/vxPB8dPg==} peerDependencies: @@ -199,6 +220,12 @@ packages: peerDependencies: '@deepseek-ai/cordis': 4.1.0 + '@deepseek-ai/dsh-session-format-catalog@0.2.2-rc.1': + resolution: {integrity: sha512-KuNxsJID39plUYnsq/HHtk0h2Tm7BrzLgQPCTRynTO541xFO7W7RmHPekr1hDDGFbS76omfKN/JV0pCHKuJbpA==} + peerDependencies: + '@deepseek-ai/cordis': 4.1.0 + '@deepseek-ai/dsh-session': 0.2.2-rc.1 + '@deepseek-ai/dsh-session-format-v0-to-v1@0.2.2-rc.1': resolution: {integrity: sha512-93MSPI7CpTm6CTZUnxZKSkgBbK4bhm7cX8leQHoaYKOcMpBD/asuD5bNw9MpKgf2eOhmrZfCO/R5rTtC9oh5Tw==} peerDependencies: @@ -224,11 +251,26 @@ packages: peerDependencies: '@deepseek-ai/cordis': 4.1.0 - '@deepseek-ai/dsh-session-projection@0.1.6-alpha.2': - resolution: {integrity: sha512-ig+XpRxv5N+gSpfy3IajvG5AlFm2UKfTKqqtem4DXwxCHIPoRbZnYWgwd/qFIl1bNNJHL6z1zjnOGGNeO640GA==} + '@deepseek-ai/dsh-session-persistence-jsonl@0.2.2-rc.1': + resolution: {integrity: sha512-HZTI2tikM6osoH+b6OlDppQYMDy6UVn0/s/XRX3TnvbOgO27FmXMlKy93Ma5GgiqWWugzsqyzruB7t1Y3SPS3Q==} peerDependencies: '@deepseek-ai/cordis': 4.1.0 - '@deepseek-ai/dsh-session': ^0.1.6-alpha.2 + '@deepseek-ai/dsh-session': 0.2.2-rc.1 + '@deepseek-ai/dsh-session-persistence': 0.2.2-rc.1 + + '@deepseek-ai/dsh-session-persistence@0.2.2-rc.1': + resolution: {integrity: sha512-0Pl9K14QKaFARcwdSJTUa0XusXlFYNAnlIdlL9s3AlWIaYOwUO6kp5pw+tcQBD80sTq8dA414j9TTJS6hszovg==} + peerDependencies: + '@deepseek-ai/cordis': 4.1.0 + '@deepseek-ai/dsh-brand': 0.2.2-rc.1 + '@deepseek-ai/dsh-session': 0.2.2-rc.1 + '@deepseek-ai/dsh-timeout': 0.2.2-rc.1 + + '@deepseek-ai/dsh-session-projection@0.2.2-rc.1': + resolution: {integrity: sha512-+wGhr1kVdhYv7E355HJUCq+foG1Dt40ehGULCdCxT46we6S1Ie2d1yUH18VvVCsEw0eM1ATe241mx3UCUMDYWQ==} + peerDependencies: + '@deepseek-ai/cordis': 4.1.0 + '@deepseek-ai/dsh-session': 0.2.2-rc.1 '@deepseek-ai/dsh-session@0.2.2-rc.1': resolution: {integrity: sha512-e0zx9HFNn8EyqrymGQS85SjKOyr61//ChTgIVDlCBSZvBB723fuXyi9LiHIIuPTlkgmWJl3gm5J51ebEXew7PQ==} @@ -336,6 +378,34 @@ packages: '@deepseek-ai/dsh-session-projection': 0.2.2-rc.1 '@deepseek-ai/dsh-system-prompt': 0.2.2-rc.1 + '@deepseek-ai/node-addon-system-darwin-arm64@0.1.2': + resolution: {integrity: sha512-IR0cx8um19mLCZaJ+H5PLblKr6Eg3PWvVo8eTQBr/SwH2nh5tM9CD9/5fHweNS9Pjt15UdFlGqnvLSd/w+O6Rw==} + engines: {node: '>=20'} + cpu: [arm64] + os: [darwin] + + '@deepseek-ai/node-addon-system-darwin-x64@0.1.2': + resolution: {integrity: sha512-XDbmquNapk9aT28y4EKn9lbONVr9YNs1NM/GKH1Gi5gUhjOT9wgRaTv72FJdNaVIInbPAYbPoyn7/y+MzQMNNg==} + engines: {node: '>=20'} + cpu: [x64] + os: [darwin] + + '@deepseek-ai/node-addon-system-linux-arm64@0.1.2': + resolution: {integrity: sha512-Z/DQtqgEYzjBzb2ocHGjMzx51W7xDILkJKKj89nyErr8gZMNiLs+JNL1uKzJqc3VLZB+vYCPaHGyQ3oX6EzEmA==} + engines: {node: '>=20'} + cpu: [arm64] + os: [linux] + + '@deepseek-ai/node-addon-system-linux-x64@0.1.2': + resolution: {integrity: sha512-S2aPVHvYCpNCppCFyNlooMYuTB7ucK5lvD9oXQQ42v5Z2s5AoaiCdjz9r2l+ED2rI5oS1x0cUZmKjJH2dxV0pg==} + engines: {node: '>=20'} + cpu: [x64] + os: [linux] + + '@deepseek-ai/node-addon-system@0.1.2': + resolution: {integrity: sha512-EFn8K+mXIXiw6s3rxX+cgp2hZTEAQdVIsURhrXnBxycSXvtQ1EQpsSVzoNKtKAQI0I0VqkEcVEjHzS/PeaGsvw==} + engines: {node: '>=20'} + '@deepseek-ai/schemastery@3.19.0': resolution: {integrity: sha512-bDXoYQa7ghAhmdYD5VPlzKxEzJV/aKkz5l4V5h1u06z8GAPN1ROewSjvR9WiXhpa52E9fng8lpH5QdCRIQgnyQ==} @@ -343,6 +413,81 @@ packages: resolution: {integrity: sha512-hloP58zRVCRSpgDxmqCWJNlizAlUgJFqG2ypq79DCvyv9tHjRYMDOcPFjzfl/A1/YxDvRCZz8wvZvmapQnKwFQ==} engines: {node: '>=12'} + '@koromix/koffi-darwin-arm64@3.1.1': + resolution: {integrity: sha512-+Dl0zQDh1Wb55AWOn9hp7K30qgkODvrvN+ZNkFOh81Q0oFX/rpJQtocgjAuYk2zFAcajSeVDumkcHMPwnKSXzA==} + cpu: [arm64] + os: [darwin] + + '@koromix/koffi-darwin-x64@3.1.1': + resolution: {integrity: sha512-cDFAKn1qdZBFLrp7dAc9QUDw3l4xAhTJbOdPWWb0LxssVicUdHcRCLZGrDsmPW2tpH6LGNNeLgqRpAoD2Mo8iA==} + cpu: [x64] + os: [darwin] + + '@koromix/koffi-freebsd-arm64@3.1.1': + resolution: {integrity: sha512-zaP7FJISI/scQW9Wa5QicY3a09WmtKBWSbmC+5nfCqPzwWe7Hx2so74Er7mPsDfCiMMR0Ya+evKbJQDkfyXicg==} + cpu: [arm64] + os: [freebsd] + + '@koromix/koffi-freebsd-ia32@3.1.1': + resolution: {integrity: sha512-7GejVb688TLM8rbjfc0oezJrATxZc0dn801xWEDJekN2DgmRXu7HquGqWQ6z3NeSq7ZxEggz4T3xtlbCysQapA==} + cpu: [ia32] + os: [freebsd] + + '@koromix/koffi-freebsd-x64@3.1.1': + resolution: {integrity: sha512-XLiCFP9OFCyOoGTjAimtDKLhzhfo34WcP1ShVWxRzNCWDGjfz8BYjwd69cp/cDSUXZbxamqs4+/6vmkePq9wxA==} + cpu: [x64] + os: [freebsd] + + '@koromix/koffi-linux-arm64@3.1.1': + resolution: {integrity: sha512-HA9xINK7G4dRAkpfnBWD9VfuyIBgW1SuK+KPHjksUwRMOnhgqP8J/JqgrAzdzcDiefGBkqEacIP776OUwz7knQ==} + cpu: [arm64] + os: [linux] + + '@koromix/koffi-linux-ia32@3.1.1': + resolution: {integrity: sha512-jG7IFytmP8K5Qtbx0ro0ZeuX3JjSsLxmYhq+nmXDdrtOAlxIsWGynuiDLS6Jk3vOchVii2m6Y2f/L3GLG2fG5A==} + cpu: [ia32] + os: [linux] + + '@koromix/koffi-linux-loong64@3.1.1': + resolution: {integrity: sha512-CIsT1cNnih8FuU52Me/IVlJBpH28SQfoDeYPctJswgJzaARktusF7m4MUbtR1PBDjuquCVM4/vFyNdOzfPonvA==} + cpu: [loong64] + os: [linux] + + '@koromix/koffi-linux-riscv64@3.1.1': + resolution: {integrity: sha512-9D6RmqeKsSvs3U6jILJU9PcAjMwKKyn7yLxNBb5k6z9PCoUoGJ3/BrhXAX0qjrLLwEiIpP/hS/40RuXvH8Lc3Q==} + cpu: [riscv64] + os: [linux] + + '@koromix/koffi-linux-x64@3.1.1': + resolution: {integrity: sha512-pyTcX5fePeYbt7TZAwRby69wdlRx3PT+g15ra5IYdat/Pgh3qAKEYeZ+uu7WpPGOy43p/oSRqqZoa2kORzozlA==} + cpu: [x64] + os: [linux] + + '@koromix/koffi-openbsd-ia32@3.1.1': + resolution: {integrity: sha512-iPnPzvG2HOfdzaiG1drdkt86sAqmTPDv9mAf+5gL7mRzkeeQC88EVGboRy7eXwdXn7R+v0ntA3iQxdHrBn6yXw==} + cpu: [ia32] + os: [openbsd] + + '@koromix/koffi-openbsd-x64@3.1.1': + resolution: {integrity: sha512-/Xqc3R0SVoMCYjMPZnJ9bULtRo364+dKmnQhfDrI83tSpxUHRw7HRNf12vBeL+hPgKxSBjtMpWfQ/ZIyVyLFag==} + cpu: [x64] + os: [openbsd] + + '@koromix/koffi-win32-arm64@3.1.1': + resolution: {integrity: sha512-JhqHauEwQvdcWUERxrV5HH/DT9W7hY1A1eU6/o8tB+yck+D3kt5elpRDBt9KjpW6h+vHPy3V0sjDvO0CXyabTA==} + cpu: [arm64] + os: [win32] + + '@koromix/koffi-win32-ia32@3.1.1': + resolution: {integrity: sha512-ZRuyYmlGS/rCc966qqs0qREXDW4FRdul7rDF1VgSWHbVmdc196PUgUT+blq/GjZgTwqzeEXtMRgM+cU8krHjvA==} + cpu: [ia32] + os: [win32] + + '@koromix/koffi-win32-x64@3.1.1': + resolution: {integrity: sha512-KqHPmvj6QILhNyI/To8QSihHsijeVGIYYPBOUnXEpcnH2LuLbargY4Hd6dDeTN3Z90uUUxN+1FWz1UnhVzFOiA==} + cpu: [x64] + os: [win32] + '@oxlint/darwin-arm64@0.18.1': resolution: {integrity: sha512-FqDrcQJmEGNkgmZgI4wbCrGyJl1tiRZa3udxvyYaXag8W80A0zLFNCyWVvHIgUJ0DHlZjRc7O72xUGjiyvQrqQ==} cpu: [arm64] @@ -403,11 +548,18 @@ packages: jsbi@4.3.2: resolution: {integrity: sha512-9fqMSQbhJykSeii05nxKl4m6Eqn2P6rOlYiS+C5Dr/HPIU/7yZxu5qzbs40tgaFORiw2Amd0mirjxatXYMkIew==} + koffi@3.1.1: + resolution: {integrity: sha512-mRX6AMeeKCxSOeOopqAcLAl5jcNvge7NAG8l7rF/8gGJATI0tdHFYjteIdE0mGOtWdsrJOij+PjnP8Q9c1gwgA==} + oxlint@0.18.1: resolution: {integrity: sha512-JGcQvbhd00Qb+nq4f9sYYRh7mZIb0K/7rbMepNdJDMzo8pbmBpx1N2XOG61RjHDsNnY6ImAmVk3h4QVwFenwUQ==} engines: {node: '>=8.*'} hasBin: true + p-limit@7.3.3: + resolution: {integrity: sha512-SKgVvDU5TNIxQ4r30U75BNLC6a+6GOEjngrk/ysM5+Zu3oJuk1SC5ApzIzY/7PjCEjoVPMWJ0zho/4QUiEB7TQ==} + engines: {node: '>=20'} + rrule@2.8.1: resolution: {integrity: sha512-hM3dHSBMeaJ0Ktp7W38BJZ7O1zOgaFEsn41PDk+yHoEtfLV+PoJt9E9xAlZiWgf/iqEqionN0ebHFZIDAp+iGw==} @@ -426,6 +578,10 @@ packages: resolution: {integrity: sha512-u4UB2/IrKdU6lFxumHmmo1a3fCQO5tzQllRorfoRS63txhrB7xTpSn1PftwC4qEHkOaqP95fCWW4lJzwErwzhQ==} engines: {node: '>=22.19.0'} + yocto-queue@1.2.2: + resolution: {integrity: sha512-4LCcse/U2MHZ63HAJVE+v71o7yOdIe4cZ70Wpf8D/IyjDKYQLV5GD46B+hSTjJsvV5PztjvHoU580EftxjDZFQ==} + engines: {node: '>=12.20'} + zod@4.4.3: resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==} @@ -454,14 +610,14 @@ snapshots: '@deepseek-ai/cosmokit@1.9.0': {} - '@deepseek-ai/dsh-agent@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-session-projection@0.1.6-alpha.2(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))))(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-system-prompt@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-typert-protocol@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-util-values@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))': + '@deepseek-ai/dsh-agent@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-session-projection@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))))(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-system-prompt@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-typert-protocol@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-util-values@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))': dependencies: '@deepseek-ai/cordis': 4.1.0(@deepseek-ai/cordis-plugin-include@1.1.0)(@deepseek-ai/cordis-plugin-loader@1.1.0) '@deepseek-ai/dsh-brand': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) '@deepseek-ai/dsh-llm': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) '@deepseek-ai/dsh-scope': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) '@deepseek-ai/dsh-session': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) - '@deepseek-ai/dsh-session-projection': 0.1.6-alpha.2(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))) + '@deepseek-ai/dsh-session-projection': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))) '@deepseek-ai/dsh-system-prompt': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) '@deepseek-ai/dsh-typert-protocol': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) '@deepseek-ai/dsh-util-values': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) @@ -476,10 +632,10 @@ snapshots: dependencies: '@deepseek-ai/cordis': 4.1.0(@deepseek-ai/cordis-plugin-include@1.1.0)(@deepseek-ai/cordis-plugin-loader@1.1.0) - '@deepseek-ai/dsh-commands@0.2.2-rc.1(faf5a5eef4aed53aec4d196dbf50657c)': + '@deepseek-ai/dsh-commands@0.2.2-rc.1(70cead30406fe58b6b8b8640601f81fb)': dependencies: '@deepseek-ai/cordis': 4.1.0(@deepseek-ai/cordis-plugin-include@1.1.0)(@deepseek-ai/cordis-plugin-loader@1.1.0) - '@deepseek-ai/dsh-agent': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-session-projection@0.1.6-alpha.2(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))))(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-system-prompt@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-typert-protocol@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-util-values@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) + '@deepseek-ai/dsh-agent': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-session-projection@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))))(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-system-prompt@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-typert-protocol@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-util-values@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) '@deepseek-ai/dsh-attachment': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-brand@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) '@deepseek-ai/dsh-brand': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) '@deepseek-ai/dsh-llm': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) @@ -489,6 +645,23 @@ snapshots: '@deepseek-ai/dsh-util-crypto': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) zod: 4.4.3 + '@deepseek-ai/dsh-compaction-image-offload@0.2.2-rc.1(39a47f4d7c75c3d72e1974cccfad82ff)': + dependencies: + '@deepseek-ai/cordis': 4.1.0(@deepseek-ai/cordis-plugin-include@1.1.0)(@deepseek-ai/cordis-plugin-loader@1.1.0) + '@deepseek-ai/dsh-agent': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-session-projection@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))))(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-system-prompt@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-typert-protocol@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-util-values@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) + '@deepseek-ai/dsh-compaction': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-brand@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-commands@0.2.2-rc.1(70cead30406fe58b6b8b8640601f81fb))(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))) + '@deepseek-ai/dsh-llm': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) + '@deepseek-ai/dsh-session': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) + '@deepseek-ai/dsh-util-values': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) + + '@deepseek-ai/dsh-compaction@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-brand@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-commands@0.2.2-rc.1(70cead30406fe58b6b8b8640601f81fb))(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))': + dependencies: + '@deepseek-ai/cordis': 4.1.0(@deepseek-ai/cordis-plugin-include@1.1.0)(@deepseek-ai/cordis-plugin-loader@1.1.0) + '@deepseek-ai/dsh-brand': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) + '@deepseek-ai/dsh-commands': 0.2.2-rc.1(70cead30406fe58b6b8b8640601f81fb) + '@deepseek-ai/dsh-llm': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) + '@deepseek-ai/dsh-session': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) + '@deepseek-ai/dsh-fs-patch@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)': dependencies: '@deepseek-ai/cordis': 4.1.0(@deepseek-ai/cordis-plugin-include@1.1.0)(@deepseek-ai/cordis-plugin-loader@1.1.0) @@ -532,6 +705,21 @@ snapshots: dependencies: '@deepseek-ai/cordis': 4.1.0(@deepseek-ai/cordis-plugin-include@1.1.0)(@deepseek-ai/cordis-plugin-loader@1.1.0) + '@deepseek-ai/dsh-session-format-catalog@0.2.2-rc.1(39a47f4d7c75c3d72e1974cccfad82ff)': + dependencies: + '@deepseek-ai/cordis': 4.1.0(@deepseek-ai/cordis-plugin-include@1.1.0)(@deepseek-ai/cordis-plugin-loader@1.1.0) + '@deepseek-ai/dsh-compaction-image-offload': 0.2.2-rc.1(39a47f4d7c75c3d72e1974cccfad82ff) + '@deepseek-ai/dsh-session': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) + '@deepseek-ai/dsh-session-format': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) + '@deepseek-ai/dsh-session-format-v0-to-v1': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) + '@deepseek-ai/dsh-session-format-v1-to-v2': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) + '@deepseek-ai/dsh-session-format-v2-to-v3': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) + '@deepseek-ai/dsh-session-format-v3-to-v4': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) + transitivePeerDependencies: + - '@deepseek-ai/dsh-agent' + - '@deepseek-ai/dsh-compaction' + - '@deepseek-ai/dsh-llm' + '@deepseek-ai/dsh-session-format-v0-to-v1@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)': dependencies: '@deepseek-ai/cordis': 4.1.0(@deepseek-ai/cordis-plugin-include@1.1.0)(@deepseek-ai/cordis-plugin-loader@1.1.0) @@ -565,7 +753,32 @@ snapshots: '@deepseek-ai/cordis': 4.1.0(@deepseek-ai/cordis-plugin-include@1.1.0)(@deepseek-ai/cordis-plugin-loader@1.1.0) '@deepseek-ai/dsh-util-values': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) - '@deepseek-ai/dsh-session-projection@0.1.6-alpha.2(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))': + '@deepseek-ai/dsh-session-persistence-jsonl@0.2.2-rc.1(2603e2cb22b0dc1a9586cfa110fd10f5)': + dependencies: + '@deepseek-ai/cordis': 4.1.0(@deepseek-ai/cordis-plugin-include@1.1.0)(@deepseek-ai/cordis-plugin-loader@1.1.0) + '@deepseek-ai/dsh-llm': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) + '@deepseek-ai/dsh-session': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) + '@deepseek-ai/dsh-session-format': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) + '@deepseek-ai/dsh-session-format-catalog': 0.2.2-rc.1(39a47f4d7c75c3d72e1974cccfad82ff) + '@deepseek-ai/dsh-session-format-v3-to-v4': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) + '@deepseek-ai/dsh-session-persistence': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-brand@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-timeout@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) + '@deepseek-ai/node-addon-system': 0.1.2 + '@deepseek-ai/schemastery': 3.19.0 + koffi: 3.1.1 + p-limit: 7.3.3 + transitivePeerDependencies: + - '@deepseek-ai/dsh-agent' + - '@deepseek-ai/dsh-compaction' + + '@deepseek-ai/dsh-session-persistence@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-brand@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-timeout@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))': + dependencies: + '@deepseek-ai/cordis': 4.1.0(@deepseek-ai/cordis-plugin-include@1.1.0)(@deepseek-ai/cordis-plugin-loader@1.1.0) + '@deepseek-ai/dsh-brand': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) + '@deepseek-ai/dsh-session': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) + '@deepseek-ai/dsh-timeout': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) + '@deepseek-ai/dsh-util-values': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) + + '@deepseek-ai/dsh-session-projection@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))': dependencies: '@deepseek-ai/cordis': 4.1.0(@deepseek-ai/cordis-plugin-include@1.1.0)(@deepseek-ai/cordis-plugin-loader@1.1.0) '@deepseek-ai/dsh-session': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) @@ -612,16 +825,16 @@ snapshots: dependencies: '@deepseek-ai/cordis': 4.1.0(@deepseek-ai/cordis-plugin-include@1.1.0)(@deepseek-ai/cordis-plugin-loader@1.1.0) - '@deepseek-ai/dsh-tools@0.2.2-rc.1(c03b195971be4da93d8dc15a5e5e26c4)': + '@deepseek-ai/dsh-tools@0.2.2-rc.1(a13a0f05e8644f33708fe2540ec79e5a)': dependencies: '@deepseek-ai/cordis': 4.1.0(@deepseek-ai/cordis-plugin-include@1.1.0)(@deepseek-ai/cordis-plugin-loader@1.1.0) - '@deepseek-ai/dsh-agent': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-session-projection@0.1.6-alpha.2(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))))(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-system-prompt@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-typert-protocol@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-util-values@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) + '@deepseek-ai/dsh-agent': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-session-projection@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))))(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-system-prompt@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-typert-protocol@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-util-values@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) '@deepseek-ai/dsh-brand': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) '@deepseek-ai/dsh-llm': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) '@deepseek-ai/dsh-scope': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) '@deepseek-ai/dsh-session': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) '@deepseek-ai/dsh-system-prompt': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) - '@deepseek-ai/dsh-user-approval': 0.2.2-rc.1(85d5fee1657efb4133740ce13435734d) + '@deepseek-ai/dsh-user-approval': 0.2.2-rc.1(3bd6a1f1902d3e43ac1e8f819c08387c) '@deepseek-ai/dsh-util-values': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) '@deepseek-ai/schemastery': 3.19.0 @@ -631,27 +844,27 @@ snapshots: '@deepseek-ai/dsh-brand': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) zod: 4.4.3 - '@deepseek-ai/dsh-user-approval@0.2.2-rc.1(85d5fee1657efb4133740ce13435734d)': + '@deepseek-ai/dsh-user-approval@0.2.2-rc.1(3bd6a1f1902d3e43ac1e8f819c08387c)': dependencies: '@deepseek-ai/cordis': 4.1.0(@deepseek-ai/cordis-plugin-include@1.1.0)(@deepseek-ai/cordis-plugin-loader@1.1.0) - '@deepseek-ai/dsh-agent': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-session-projection@0.1.6-alpha.2(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))))(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-system-prompt@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-typert-protocol@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-util-values@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) + '@deepseek-ai/dsh-agent': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-session-projection@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))))(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-system-prompt@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-typert-protocol@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-util-values@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) '@deepseek-ai/dsh-brand': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) '@deepseek-ai/dsh-llm': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) '@deepseek-ai/dsh-scope': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) '@deepseek-ai/dsh-session': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) - '@deepseek-ai/dsh-session-projection': 0.1.6-alpha.2(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))) + '@deepseek-ai/dsh-session-projection': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))) '@deepseek-ai/dsh-system-prompt': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) '@deepseek-ai/schemastery': 3.19.0 zod: 4.4.3 - '@deepseek-ai/dsh-user-questions@0.2.2-rc.1(356643d3c097d375ce0bfe90e809159e)': + '@deepseek-ai/dsh-user-questions@0.2.2-rc.1(2c05509f73576205c7dab735b58f9829)': dependencies: '@deepseek-ai/cordis': 4.1.0(@deepseek-ai/cordis-plugin-include@1.1.0)(@deepseek-ai/cordis-plugin-loader@1.1.0) - '@deepseek-ai/dsh-agent': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-session-projection@0.1.6-alpha.2(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))))(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-system-prompt@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-typert-protocol@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-util-values@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) + '@deepseek-ai/dsh-agent': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-session-projection@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))))(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-system-prompt@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-typert-protocol@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-util-values@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) '@deepseek-ai/dsh-llm': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) '@deepseek-ai/dsh-scope': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) '@deepseek-ai/dsh-session': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) - '@deepseek-ai/dsh-session-projection': 0.1.6-alpha.2(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))) + '@deepseek-ai/dsh-session-projection': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))) '@deepseek-ai/dsh-typert-protocol': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) '@deepseek-ai/schemastery': 3.19.0 zod: 4.4.3 @@ -670,18 +883,37 @@ snapshots: dependencies: '@deepseek-ai/cordis': 4.1.0(@deepseek-ai/cordis-plugin-include@1.1.0)(@deepseek-ai/cordis-plugin-loader@1.1.0) - '@deepseek-ai/dsh-working-directory@0.2.2-rc.1(222c5866fa4da5f096b83061641f4efa)': + '@deepseek-ai/dsh-working-directory@0.2.2-rc.1(523417378dd3f3049068ec93f993992c)': dependencies: '@deepseek-ai/cordis': 4.1.0(@deepseek-ai/cordis-plugin-include@1.1.0)(@deepseek-ai/cordis-plugin-loader@1.1.0) - '@deepseek-ai/dsh-agent': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-session-projection@0.1.6-alpha.2(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))))(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-system-prompt@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-typert-protocol@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-util-values@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) + '@deepseek-ai/dsh-agent': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-session-projection@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))))(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-system-prompt@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))(@deepseek-ai/dsh-typert-protocol@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-util-values@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) '@deepseek-ai/dsh-fs': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-brand@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-sandbox@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)))) '@deepseek-ai/dsh-llm': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0) '@deepseek-ai/dsh-session': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) - '@deepseek-ai/dsh-session-projection': 0.1.6-alpha.2(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))) + '@deepseek-ai/dsh-session-projection': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-session@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))) '@deepseek-ai/dsh-system-prompt': 0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-llm@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-scope@0.2.2-rc.1(@deepseek-ai/cordis@4.1.0)) '@deepseek-ai/schemastery': 3.19.0 zod: 4.4.3 + '@deepseek-ai/node-addon-system-darwin-arm64@0.1.2': + optional: true + + '@deepseek-ai/node-addon-system-darwin-x64@0.1.2': + optional: true + + '@deepseek-ai/node-addon-system-linux-arm64@0.1.2': + optional: true + + '@deepseek-ai/node-addon-system-linux-x64@0.1.2': + optional: true + + '@deepseek-ai/node-addon-system@0.1.2': + optionalDependencies: + '@deepseek-ai/node-addon-system-darwin-arm64': 0.1.2 + '@deepseek-ai/node-addon-system-darwin-x64': 0.1.2 + '@deepseek-ai/node-addon-system-linux-arm64': 0.1.2 + '@deepseek-ai/node-addon-system-linux-x64': 0.1.2 + '@deepseek-ai/schemastery@3.19.0': dependencies: '@deepseek-ai/cosmokit': 1.9.0 @@ -691,6 +923,51 @@ snapshots: dependencies: jsbi: 4.3.2 + '@koromix/koffi-darwin-arm64@3.1.1': + optional: true + + '@koromix/koffi-darwin-x64@3.1.1': + optional: true + + '@koromix/koffi-freebsd-arm64@3.1.1': + optional: true + + '@koromix/koffi-freebsd-ia32@3.1.1': + optional: true + + '@koromix/koffi-freebsd-x64@3.1.1': + optional: true + + '@koromix/koffi-linux-arm64@3.1.1': + optional: true + + '@koromix/koffi-linux-ia32@3.1.1': + optional: true + + '@koromix/koffi-linux-loong64@3.1.1': + optional: true + + '@koromix/koffi-linux-riscv64@3.1.1': + optional: true + + '@koromix/koffi-linux-x64@3.1.1': + optional: true + + '@koromix/koffi-openbsd-ia32@3.1.1': + optional: true + + '@koromix/koffi-openbsd-x64@3.1.1': + optional: true + + '@koromix/koffi-win32-arm64@3.1.1': + optional: true + + '@koromix/koffi-win32-ia32@3.1.1': + optional: true + + '@koromix/koffi-win32-x64@3.1.1': + optional: true + '@oxlint/darwin-arm64@0.18.1': optional: true @@ -729,6 +1006,24 @@ snapshots: jsbi@4.3.2: {} + koffi@3.1.1: + optionalDependencies: + '@koromix/koffi-darwin-arm64': 3.1.1 + '@koromix/koffi-darwin-x64': 3.1.1 + '@koromix/koffi-freebsd-arm64': 3.1.1 + '@koromix/koffi-freebsd-ia32': 3.1.1 + '@koromix/koffi-freebsd-x64': 3.1.1 + '@koromix/koffi-linux-arm64': 3.1.1 + '@koromix/koffi-linux-ia32': 3.1.1 + '@koromix/koffi-linux-loong64': 3.1.1 + '@koromix/koffi-linux-riscv64': 3.1.1 + '@koromix/koffi-linux-x64': 3.1.1 + '@koromix/koffi-openbsd-ia32': 3.1.1 + '@koromix/koffi-openbsd-x64': 3.1.1 + '@koromix/koffi-win32-arm64': 3.1.1 + '@koromix/koffi-win32-ia32': 3.1.1 + '@koromix/koffi-win32-x64': 3.1.1 + oxlint@0.18.1: optionalDependencies: '@oxlint/darwin-arm64': 0.18.1 @@ -740,6 +1035,10 @@ snapshots: '@oxlint/win32-arm64': 0.18.1 '@oxlint/win32-x64': 0.18.1 + p-limit@7.3.3: + dependencies: + yocto-queue: 1.2.2 + rrule@2.8.1: dependencies: tslib: 2.9.1 @@ -752,4 +1051,6 @@ snapshots: undici@8.11.2: {} + yocto-queue@1.2.2: {} + zod@4.4.3: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 43d72fc..6fa32f1 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -29,3 +29,7 @@ minimumReleaseAgeExclude: # exclusion list above stays as the documented intent. minimumReleaseAge: 0 verifyDepsBeforeRun: false +# koffi is an optional native FFI edge pulled in by the JSONL persistence +# devDependency used as a restore-projection test gate; the tests never load it. +allowBuilds: + koffi: false diff --git a/test/cwdmap.test.mjs b/test/cwdmap.test.mjs new file mode 100644 index 0000000..29ea027 --- /dev/null +++ b/test/cwdmap.test.mjs @@ -0,0 +1,364 @@ +// test/cwdmap.test.mjs — 跨平台 cwd 投影(#28)与符号链接诊断/跟随(#30)。 +// +// 关键判据不靠自证:投影后的会话由**真实宿主后端** +// (@deepseek-ai/dsh-session-persistence-jsonl)`stat()`/`list()` 读取。 +// 宿主 `assertStoredIdentity` 要求文件路径等于 +// `///`,因此这条断言同时钉住 +// 我们的 projectKey 复刻、目录布局与 header 改写。 +// +// @module dsh-session-sync/test/cwdmap.test + +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { promises as fs } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { constants, zstdCompressSync } from 'node:zlib' +import { Context } from '@deepseek-ai/cordis' +import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import { + matchCwdMap, + normalizeCwdMap, + projectCwd, + projectKey, + projectedRelOf, +} from '../lib/cwdmap.mjs' +import { planRestoreFile } from '../lib/projection.mjs' +import { readSessionHeader } from '../lib/sessionlog.mjs' +import { mirrorSessionRoot, pruneRestoredSessions, restoreSessionRoot } from '../lib/mirror.mjs' +import { makeSyncStatusTool, renderStatus, resolveConfig } from '../index.mjs' + +const ZSTD_OPTIONS = { params: { [constants.ZSTD_c_checksumFlag]: 1 } } +const SESSION_ID = 'session-11111111-2222-3333-4444-555555555555' +const WINDOWS_CWD = 'C:\\Users\\me\\proj' +const CANONICAL_REL = `--C-Users-me-proj--/${SESSION_ID}/session.v4.jsonl.zstd` + +/** 一段合法的 V4 header 行(宿主 readHeader 只接受这些键)。 */ +function headerLine(overrides = {}) { + return `${JSON.stringify({ + type: 'session', + version: 4, + id: SESSION_ID, + createdAt: 1_700_000_000_000, + isSeeded: false, + delegationDepth: 0, + cwd: WINDOWS_CWD, + ...overrides, + })}\n` +} + +/** 一帧 zstd(与宿主 compressZstdFrame 同参数)。 */ +function zstdFrame(text) { + return zstdCompressSync(Buffer.from(text, 'utf8'), ZSTD_OPTIONS) +} + +/** 一份会话日志:header 帧 + 可选事件帧。 */ +function sessionLog(header, events = '') { + return events.length === 0 + ? zstdFrame(header) + : Buffer.concat([zstdFrame(header), zstdFrame(events)]) +} + +async function makeTemp() { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'dsh-session-sync-cwdmap-')) + return { root, clean: () => fs.rm(root, { recursive: true, force: true }) } +} + +/** 真实宿主 JSONL 后端(只读面:stat/list)。 */ +async function hostBackend(sessionRoot) { + const ctx = new Context() + ctx.plugin(JsonlSessionPersistence, { root: sessionRoot, compression: 'zstd' }) + const deadline = Date.now() + 5_000 + while (ctx.get('sessionPersistence') === undefined && Date.now() < deadline) { + await new Promise(resolve => setTimeout(resolve, 10)) + } + const persistence = ctx.get('sessionPersistence') + assert.ok(persistence !== undefined, 'the host JSONL backend must register its service') + return { + persistence, + stop: async () => { await (/** @type {any} */ (ctx)).stop?.() }, + } +} + +test('normalizeCwdMap: longest prefix first, segment boundaries, Windows is case-insensitive', () => { + const maps = normalizeCwdMap([ + { from: 'C:\\Users\\me', to: '/home/me/win' }, + { from: 'C:\\Users\\me\\proj', to: '/home/me/win/proj' }, + ]) + assert.equal(maps.length, 2, 'both entries survive normalization') + assert.equal(maps[0].from, 'C:\\Users\\me\\proj', 'the deeper prefix sorts first') + + const deep = matchCwdMap('C:\\Users\\me\\proj\\src', maps) + assert.equal(deep?.remainder.join('/'), 'src') + assert.equal(deep?.entry.to, '/home/me/win/proj') + + // 段边界:me2 不是 me 的前缀命中。 + assert.equal(matchCwdMap('C:\\Users\\me2\\proj', maps), undefined) + assert.equal(matchCwdMap('C:\\Users\\me2', maps), undefined) + // Windows 语义:大小写不敏感。 + assert.equal(matchCwdMap('c:\\users\\ME\\proj', maps)?.entry.to, '/home/me/win/proj') + // 前缀本身(无剩余段)。 + assert.deepEqual(matchCwdMap('C:\\Users\\me', maps)?.remainder, []) + // 映射按段拼接,不会把 `/home/me/win` 变成 `/home/me/winproj`。 + assert.equal(projectCwd('C:\\Users\\me\\proj', { map: maps, sessionRoot: '/root/sessions' }).cwd, '/home/me/win/proj') + assert.equal(projectCwd('C:\\Users\\me\\other', { map: maps, sessionRoot: '/root/sessions' }).cwd, '/home/me/win/other') +}) + +test('normalizeCwdMap rejects malformed entries loudly', () => { + assert.throws(() => normalizeCwdMap('nope'), /cwdMap must be an array/u) + assert.throws(() => normalizeCwdMap([{ from: 'C:\\me', to: '/a' }, { from: 'c:\\ME', to: '/b' }]), /duplicate from/u) + assert.throws(() => normalizeCwdMap([{ from: 'relative/path', to: '/a' }]), /from must be an absolute path/u) + assert.throws(() => normalizeCwdMap([{ from: 'C:\\me', to: 'relative' }]), /to must be an absolute path/u) + assert.throws(() => normalizeCwdMap([{ from: 'C:\\me', to: '/a', extra: 1 }]), /unknown key/u) + assert.throws(() => normalizeCwdMap([{ from: '', to: '/a' }]), /from must be a non-empty string/u) +}) + +test('projectKey matches the host layout formula (golden values)', () => { + assert.equal(projectKey('C:\\Users\\me\\proj'), '--C-Users-me-proj--') + assert.equal(projectKey('/home/me/proj'), '--home-me-proj--') + assert.equal(projectKey('C:\\'), '--C---') + assert.equal(projectKey('/'), '--root--') + assert.equal( + projectedRelOf(CANONICAL_REL, '/home/me/win/proj'), + `--home-me-win-proj--/${SESSION_ID}/session.v4.jsonl.zstd`, + ) + // 旧扁平布局(没有 projectKey 段)不投影。 + assert.equal(projectedRelOf(`${SESSION_ID}/session.v4.jsonl.zstd`, '/home/me/proj'), undefined) +}) + +test('a Windows header becomes visible on Linux after restore (real host backend)', async (t) => { + const { root, clean } = await makeTemp() + t.after(clean) + const sessionRoot = path.join(root, 'sessions') + const repoDir = path.join(root, 'repo') + const mirrorRoot = path.join(repoDir, 'sessions') + const mappedRoot = path.join(root, 'linux') + const mappedCwd = path.join(mappedRoot, 'proj') // from 'C:\Users\me' + remainder 'proj' + await fs.mkdir(path.join(repoDir, '.git'), { recursive: true }) + await fs.mkdir(path.join(mirrorRoot, ...CANONICAL_REL.split('/').slice(0, -1)), { recursive: true }) + const canonical = sessionLog(headerLine(), `${JSON.stringify({ type: 'user/message', seq: 0 })}\n`) + await fs.writeFile(path.join(mirrorRoot, ...CANONICAL_REL.split('/')), canonical) + + const result = await restoreSessionRoot({ + repoDir, + mirrorRoot, + sessionRoot, + cwdMap: normalizeCwdMap([{ from: 'C:\\Users\\me', to: mappedRoot }]), + }) + assert.equal(result.restored, 1) + assert.equal(result.cwdMapped, 1) + assert.equal(result.cwdUnmapped, 0) + + // 投影落在宿主布局的 projectKey(mappedCwd) 目录,原目录不落盘(同一 id 不能重复)。 + const localPath = path.join(sessionRoot, ...`${projectKey(mappedCwd)}/${SESSION_ID}/session.v4.jsonl.zstd`.split('/')) + assert.equal((await fs.stat(localPath)).isFile(), true) + await assert.rejects(fs.stat(path.join(sessionRoot, ...CANONICAL_REL.split('/'))), { code: 'ENOENT' }) + + const parsed = readSessionHeader(await fs.readFile(localPath), true) + assert.equal(parsed?.header.cwd, mappedCwd, 'the local projection carries the local cwd') + + // 真实宿主:stat 会走 assertStoredIdentity(路径必须等于 projectKey(cwd) 公式)。 + const host = await hostBackend(sessionRoot) + t.after(host.stop) + const stat = await host.persistence.stat(SESSION_ID) + assert.equal(stat?.header.cwd, mappedCwd) + const listed = await host.persistence.list() + assert.equal(listed.length, 1) + assert.equal(listed[0].header.cwd, mappedCwd) + + // 镜像字节保持原设备视角:推送时不改写、不新增投影路径。 + const mirrored = await mirrorSessionRoot({ sessionRoot, repoDir, mirrorDir: 'sessions' }) + assert.equal(mirrored.cwdMapped, 1) + assert.deepEqual(await fs.readFile(path.join(mirrorRoot, ...CANONICAL_REL.split('/'))), canonical) + await assert.rejects(fs.stat(path.join(mirrorRoot, projectKey(mappedCwd))), { code: 'ENOENT' }) +}) + +test('a session with no matching mapping lands read-only in the --unmapped-- placeholder', async (t) => { + const { root, clean } = await makeTemp() + t.after(clean) + const sessionRoot = path.join(root, 'sessions') + const repoDir = path.join(root, 'repo') + const mirrorRoot = path.join(repoDir, 'sessions') + await fs.mkdir(path.join(repoDir, '.git'), { recursive: true }) + await fs.mkdir(path.join(mirrorRoot, ...CANONICAL_REL.split('/').slice(0, -1)), { recursive: true }) + const canonical = sessionLog(headerLine()) + await fs.writeFile(path.join(mirrorRoot, ...CANONICAL_REL.split('/')), canonical) + + const result = await restoreSessionRoot({ repoDir, mirrorRoot, sessionRoot, cwdMap: normalizeCwdMap([]) }) + assert.equal(result.cwdUnmapped, 1) + assert.equal(result.cwdMapped, 0) + + const placeholderCwd = path.join(sessionRoot, '--unmapped--') + const localPath = path.join(sessionRoot, ...`${projectKey(placeholderCwd)}/${SESSION_ID}/session.v4.jsonl.zstd`.split('/')) + const parsed = readSessionHeader(await fs.readFile(localPath), true) + assert.equal(parsed?.header.cwd, placeholderCwd) + assert.equal((await fs.stat(placeholderCwd)).isDirectory(), true, 'the placeholder directory is created for workspace grouping') + if (process.platform !== 'win32') { + assert.equal((await fs.stat(localPath)).mode & 0o222, 0, 'the unmapped copy is best-effort read-only on disk') + } + + const host = await hostBackend(sessionRoot) + t.after(host.stop) + const stat = await host.persistence.stat(SESSION_ID) + assert.equal(stat?.header.cwd, placeholderCwd) + + // 只读视图永不作为推送源,也永不删除镜像里的原始会话。 + const before = await fs.readFile(path.join(mirrorRoot, ...CANONICAL_REL.split('/'))) + const mirrored = await mirrorSessionRoot({ sessionRoot, repoDir, mirrorDir: 'sessions' }) + assert.equal(mirrored.cwdUnmapped, 1) + assert.deepEqual(await fs.readFile(path.join(mirrorRoot, ...CANONICAL_REL.split('/'))), before) + await assert.rejects(fs.stat(path.join(mirrorRoot, projectKey(placeholderCwd))), { code: 'ENOENT' }) + + // 即便有人在占位副本上追加,推送端也不接管(只读视图语义)。 + if (process.platform !== 'win32') await fs.chmod(localPath, 0o644) + const appended = Buffer.concat([await fs.readFile(localPath), zstdFrame('{"type":"user/message","seq":1}\n')]) + await fs.writeFile(localPath, appended) + await mirrorSessionRoot({ sessionRoot, repoDir, mirrorDir: 'sessions' }) + assert.deepEqual(await fs.readFile(path.join(mirrorRoot, ...CANONICAL_REL.split('/'))), before) +}) + +test('appends to a mapped projection push as byte-identical appends to the origin header', async (t) => { + const { root, clean } = await makeTemp() + t.after(clean) + const sessionRoot = path.join(root, 'sessions') + const repoDir = path.join(root, 'repo') + const mirrorRoot = path.join(repoDir, 'sessions') + const mappedRoot = path.join(root, 'linux') + const mappedCwd = path.join(mappedRoot, 'proj') // from 'C:\Users\me' + remainder 'proj' + await fs.mkdir(path.join(repoDir, '.git'), { recursive: true }) + await fs.mkdir(path.join(mirrorRoot, ...CANONICAL_REL.split('/').slice(0, -1)), { recursive: true }) + const firstEvent = zstdFrame('{"type":"user/message","seq":0}\n') + const canonical = Buffer.concat([zstdFrame(headerLine()), firstEvent]) + await fs.writeFile(path.join(mirrorRoot, ...CANONICAL_REL.split('/')), canonical) + + await restoreSessionRoot({ + repoDir, + mirrorRoot, + sessionRoot, + cwdMap: normalizeCwdMap([{ from: 'C:\\Users\\me', to: mappedRoot }]), + }) + const localPath = path.join(sessionRoot, ...`${projectKey(mappedCwd)}/${SESSION_ID}/session.v4.jsonl.zstd`.split('/')) + const appendedFrame = zstdFrame('{"type":"assistant/message","seq":1}\n') + await fs.writeFile(localPath, Buffer.concat([await fs.readFile(localPath), appendedFrame])) + + const mirrored = await mirrorSessionRoot({ sessionRoot, repoDir, mirrorDir: 'sessions' }) + assert.equal(mirrored.mirrored, 1) + const pushed = await fs.readFile(path.join(mirrorRoot, ...CANONICAL_REL.split('/'))) + assert.deepEqual(pushed.subarray(0, canonical.length), canonical, 'the origin header frame is preserved byte-for-byte') + assert.deepEqual(pushed.subarray(canonical.length), appendedFrame, 'only the appended frames are added') + // 宿主读回镜像里的原会话(对端视角)仍然一致:header 仍是 Windows cwd。 + const origin = readSessionHeader(pushed, true) + assert.equal(origin?.header.cwd, WINDOWS_CWD) +}) + +test('projection is skipped when the directory does not encode the header id', () => { + const content = sessionLog(headerLine({ id: 'session-other' })) + const plan = planRestoreFile({ + content, + mirrorRel: CANONICAL_REL, + cwdMap: normalizeCwdMap([{ from: 'C:\\Users\\me', to: '/home/me/win' }]), + sessionRoot: '/root/sessions', + }) + assert.equal(plan.kind, 'skipped') + assert.equal(plan.rel, CANONICAL_REL) + assert.deepEqual(plan.content, content) +}) + +test('followSessionSymlinks: inside-root links are opt-in, outside links never follow', async (t) => { + if (process.platform === 'win32') return t.skip('symlink creation needs extra privileges on Windows') + const { root, clean } = await makeTemp() + t.after(clean) + const sessionRoot = path.join(root, 'sessions') + const repoDir = path.join(root, 'repo') + const outside = path.join(root, 'outside.jsonl') + await fs.mkdir(path.join(sessionRoot, 'proj'), { recursive: true }) + await fs.mkdir(path.join(repoDir, '.git'), { recursive: true }) + await fs.writeFile(path.join(sessionRoot, 'proj', 'real.jsonl'), 'real\n') + await fs.writeFile(outside, 'outside\n') + await fs.symlink(path.join(sessionRoot, 'proj', 'real.jsonl'), path.join(sessionRoot, 'proj', 'inside-link.jsonl')) + await fs.symlink(outside, path.join(sessionRoot, 'proj', 'outside-link.jsonl')) + + const strict = await mirrorSessionRoot({ sessionRoot, repoDir, mirrorDir: 'sessions' }) + assert.equal(strict.skippedLinks.length, 2, 'the default never follows symlinks') + await assert.rejects(fs.stat(path.join(repoDir, 'sessions', 'proj', 'inside-link.jsonl')), { code: 'ENOENT' }) + + const followed = await mirrorSessionRoot({ sessionRoot, repoDir, mirrorDir: 'sessions', followSessionSymlinks: true }) + assert.equal(followed.skippedLinks.length, 1, 'the outside link stays skipped') + assert.match(followed.skippedLinks[0], /outside-link\.jsonl$/u) + assert.equal(await fs.readFile(path.join(repoDir, 'sessions', 'proj', 'inside-link.jsonl'), 'utf8'), 'real\n') + assert.ok(followed.followedLinks.some(rel => rel.endsWith('inside-link.jsonl'))) +}) + +test('sync_status exposes skipped symlinks and cwd projection diagnostics', async () => { + const engine = { + status: async () => ({ + ok: true, + branch: 'main', + remote: '', + ahead: 0, + behind: 0, + dirty: [], + forks: [], + diffStat: '', + mergeInProgress: false, + lastCommits: [], + skippedSymlinks: 3, + skippedSymlinkPaths: ['/root/.dsh/sessions/x/session.v4.jsonl.zstd'], + followedSymlinks: 0, + cwdMapped: 1, + cwdUnmapped: 2, + cwdProjectionSkipped: 0, + cwdPlaceholder: '/root/.dsh/sessions/--unmapped--', + followSessionSymlinks: false, + warnings: ['3 file(s) under sessionRoot were skipped as symbolic links'], + }), + } + const tool = makeSyncStatusTool(engine, async () => ({})) + const value = await tool.execute({}, /** @type {any} */ ({})) + assert.equal(value.skippedSymlinks, 3) + assert.equal(value.cwdUnmapped, 2) + assert.equal(value.cwdPlaceholder, '/root/.dsh/sessions/--unmapped--') + assert.equal(value.followSessionSymlinks, false) + assert.ok(JSON.stringify(value).length > 0, 'the tool result stays lossless JSON') + + const text = renderStatus(value) + assert.match(text, /skipped symbolic links/u) + assert.match(text, /cwd projection: 1 mapped/u) + assert.match(text, /warning: 3 file\(s\) under sessionRoot/u) +}) + +test('resolveConfig validates cwdMap and followSessionSymlinks', () => { + const base = { sessionRoot: '/tmp/sessions', repoDir: '/tmp/repo' } + const resolved = resolveConfig({ ...base, cwdMap: [{ from: 'C:\\Users\\me', to: '/home/me' }] }) + assert.equal(resolved.cwdMap.length, 1) + assert.equal(resolved.followSessionSymlinks, false) + assert.throws(() => resolveConfig({ ...base, cwdMap: [{ from: 'C:\\me', to: 'relative' }] }), /to must be an absolute path/u) + assert.throws(() => resolveConfig(/** @type {any} */ ({ ...base, followSessionSymlinks: 'yes' })), /followSessionSymlinks must be a boolean/u) +}) + +test('prune maps a projected path back to the mirror and prunes remote deletions', async (t) => { + const { root, clean } = await makeTemp() + t.after(clean) + const sessionRoot = path.join(root, 'sessions') + const repoDir = path.join(root, 'repo') + const mirrorRoot = path.join(repoDir, 'sessions') + const mappedRoot = path.join(root, 'linux') + await fs.mkdir(path.join(repoDir, '.git'), { recursive: true }) + await fs.mkdir(path.join(mirrorRoot, ...CANONICAL_REL.split('/').slice(0, -1)), { recursive: true }) + await fs.writeFile(path.join(mirrorRoot, ...CANONICAL_REL.split('/')), sessionLog(headerLine())) + await restoreSessionRoot({ + repoDir, + mirrorRoot, + sessionRoot, + cwdMap: normalizeCwdMap([{ from: 'C:\\Users\\me', to: mappedRoot }]), + }) + const projectedRel = `${projectKey(path.join(mappedRoot, 'proj'))}/${SESSION_ID}/session.v4.jsonl.zstd` + const localPath = path.join(sessionRoot, ...projectedRel.split('/')) + assert.equal((await fs.stat(localPath)).isFile(), true) + + // 远端删除了原会话(镜像里已无该文件):本插件恢复出来的投影副本应被清理。 + await fs.unlink(path.join(mirrorRoot, ...CANONICAL_REL.split('/'))) + const pruned = await pruneRestoredSessions({ repoDir, mirrorRoot, sessionRoot }) + assert.deepEqual(pruned.pruned, [projectedRel]) + await assert.rejects(fs.stat(localPath), { code: 'ENOENT' }) +}) diff --git a/types.d.ts b/types.d.ts index 082824a..5536126 100644 --- a/types.d.ts +++ b/types.d.ts @@ -98,6 +98,19 @@ export interface Config { pullIntervalMinutes?: number /** 确认通道:auto(userQuestions 优先,其次 approval)· userQuestions · approval。 */ confirmVia?: 'auto' | 'userQuestions' | 'approval' + /** + * 恢复期 cwd 投影表(issue #28):`[{ from, to }]`,最长前缀优先,前缀按 + * 路径段边界匹配。命中时恢复出的会话以 `to` 下的本机路径可见;未命中的 + * 跨平台 cwd 归一到 `/--unmapped--` 并以只读视图呈现。 + * 同步仓库里的字节始终保留原设备的 cwd。 + */ + cwdMap?: ReadonlyArray<{ from: string, to: string }> + /** + * 镜像时是否跟随符号链接(issue #30;默认 false)。只有 realpath 仍落在 + * sessionRoot 内的链接才会被读取/递归;越界链接一律跳过并在 sync_status 里 + * 报告。默认值保持严格的"绝不跟随"。 + */ + followSessionSymlinks?: boolean /** git 子进程终止宽限(ms;默认 10000)。 */ graceMs?: number /** 单条 git 命令超时(ms;默认 120000)。 */ @@ -132,6 +145,22 @@ export interface StatusValue { lastPushAt?: number lastError?: string error?: string + /** 本次镜像跳过的符号链接数(未镜像;default 严格模式)。 */ + skippedSymlinks?: number + /** 跳过的符号链接路径样本(最多 20 条)。 */ + skippedSymlinkPaths?: string[] + /** 本次镜像跟随的根内符号链接数(followSessionSymlinks: true 时)。 */ + followedSymlinks?: number + /** 恢复期投影到本机 cwd 的会话数。 */ + cwdMapped?: number + /** 无 cwdMap 命中的跨平台会话数(占位只读视图)。 */ + cwdUnmapped?: number + /** 无法投影的会话文件数(header 不可解析/旧布局)。 */ + cwdProjectionSkipped?: number + /** 占位只读视图的目录(`/--unmapped--`)。 */ + cwdPlaceholder?: string + /** 是否开启符号链接跟随(诊断用)。 */ + followSessionSymlinks?: boolean warnings?: string[] } @@ -145,6 +174,9 @@ export interface PullValue { diverged?: number forks?: string[] head?: string + restored?: number + cwdMapped?: number + cwdUnmapped?: number error?: string warnings?: string[] } @@ -157,6 +189,8 @@ export interface PushValue { mirrored?: number deleted?: number remote?: string + skippedSymlinks?: number + skippedSymlinkPaths?: string[] error?: string warnings?: string[] } From a66edafa9f3e29d0c6782db2ec6aa1c32a97d98c Mon Sep 17 00:00:00 2001 From: PerryLink <255665900+PerryLink@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:48:38 +0800 Subject: [PATCH 2/3] chore(release): 0.3.0 --- CHANGELOG.md | 2 +- package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index db48b41..3a2b279 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## [Unreleased] +## [0.3.0] - 2026-11-13 ### Added diff --git a/package.json b/package.json index 5571908..2d68f56 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "dsh-session-sync", "description": "Cross-device sync for DeepSeek Harness sessions: a dedicated git mirror of the session store, append-only three-way merge with keep-both + fork conflict resolution, /sync command, sync_pull/sync_push/sync_status tools, and configurable auto push/pull", - "version": "0.2.33", + "version": "0.3.0", "repository": { "type": "git", "url": "git+https://github.com/PerryLink/dsh-session-sync.git" From 0b3692cfe943d227491689a958d3f9b38e22b14d Mon Sep 17 00:00:00 2001 From: PerryLink <255665900+PerryLink@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:52:06 +0800 Subject: [PATCH 3/3] test(cwdmap): make the projection tests platform-agnostic Windows CI failed because the unit tests hard-coded POSIX mapping targets and treated a Windows cwd as foreign on Windows (it is native there). Use a native temp target for every mapping and pick the foreign cwd per platform: the reverse direction (POSIX cwd on Windows) exercises the same projection path. Also clear a read-only placeholder bit before unlinking it so remote deletions prune on Windows too. --- lib/mirror.mjs | 17 +++++++-- test/cwdmap.test.mjs | 89 +++++++++++++++++++++++++------------------- 2 files changed, 64 insertions(+), 42 deletions(-) diff --git a/lib/mirror.mjs b/lib/mirror.mjs index f859f06..730d553 100644 --- a/lib/mirror.mjs +++ b/lib/mirror.mjs @@ -164,6 +164,17 @@ async function writeIfDifferent(target, content, root) { return true } +/** 删除文件;只读投影副本(占位目录 0o444)在 Windows 上先解开只读位再删。 */ +async function unlinkFile(target) { + try { + await fs.unlink(target) + } catch (error) { + if (error?.code !== 'EACCES' && error?.code !== 'EPERM') throw error + await fs.chmod(target, 0o644).catch(() => {}) + await fs.unlink(target) + } +} + /** 源快照状态文件:本地、不进提交、不随仓库同步。 */ export const SOURCE_SNAPSHOT_FILE = path.join('.git', 'dsh-session-sync-mirror.json') @@ -401,7 +412,7 @@ export async function pruneRestoredSessions(deps) { if (st.isSymbolicLink()) { state.delete(rel); continue } const content = await fs.readFile(target) if (hashContent(content) === expected) { - await fs.unlink(target) + await unlinkFile(target) pruned.push(rel) } else { keptEdited.push(rel) @@ -505,7 +516,7 @@ export async function restoreSessionRoot(deps) { const legacyContent = await fs.readFile(legacyTarget) const tracked = state.get(rel) if (legacyContent.equals(content) || (tracked !== undefined && hashContent(legacyContent) === tracked)) { - await fs.unlink(legacyTarget) + await unlinkFile(legacyTarget) state.delete(rel) } } @@ -529,7 +540,7 @@ export async function restoreSessionRoot(deps) { // 只删"本插件上次恢复、且此后没人改动"的副本:无哈希记录或字节已变都保留 // (用户改动优先,宁可留下一个可见副本也不误删数据)。 if (expected !== undefined && hashContent(oldContent) === expected) { - await fs.unlink(oldTarget) + await unlinkFile(oldTarget) state.delete(oldEntry.projectedRel) } } catch { diff --git a/test/cwdmap.test.mjs b/test/cwdmap.test.mjs index 29ea027..582eaeb 100644 --- a/test/cwdmap.test.mjs +++ b/test/cwdmap.test.mjs @@ -6,6 +6,9 @@ // `///`,因此这条断言同时钉住 // 我们的 projectKey 复刻、目录布局与 header 改写。 // +// 用例在两个方向上对称:非 Windows 用 `C:\Users\…`(另一平台的绝对路径), +// Windows 用 `/home/…`(同样在 win32 上 root 为 `/`,属于非本机绝对路径)。 +// // @module dsh-session-sync/test/cwdmap.test import { test } from 'node:test' @@ -30,8 +33,11 @@ import { makeSyncStatusTool, renderStatus, resolveConfig } from '../index.mjs' const ZSTD_OPTIONS = { params: { [constants.ZSTD_c_checksumFlag]: 1 } } const SESSION_ID = 'session-11111111-2222-3333-4444-555555555555' -const WINDOWS_CWD = 'C:\\Users\\me\\proj' -const CANONICAL_REL = `--C-Users-me-proj--/${SESSION_ID}/session.v4.jsonl.zstd` +const IS_WINDOWS = process.platform === 'win32' +// 另一平台的绝对路径:在 Linux 上是 Windows 盘符路径,在 Windows 上是 POSIX 路径。 +const FOREIGN_PREFIX = IS_WINDOWS ? '/home/me' : 'C:\\Users\\me' +const FOREIGN_CWD = IS_WINDOWS ? '/home/me/proj' : 'C:\\Users\\me\\proj' +const CANONICAL_REL = `${projectKey(FOREIGN_CWD)}/${SESSION_ID}/session.v4.jsonl.zstd` /** 一段合法的 V4 header 行(宿主 readHeader 只接受这些键)。 */ function headerLine(overrides = {}) { @@ -42,7 +48,7 @@ function headerLine(overrides = {}) { createdAt: 1_700_000_000_000, isSeeded: false, delegationDepth: 0, - cwd: WINDOWS_CWD, + cwd: FOREIGN_CWD, ...overrides, })}\n` } @@ -81,36 +87,41 @@ async function hostBackend(sessionRoot) { } test('normalizeCwdMap: longest prefix first, segment boundaries, Windows is case-insensitive', () => { + const target = path.resolve('local-win-root') + const deepTarget = path.join(target, 'proj') const maps = normalizeCwdMap([ - { from: 'C:\\Users\\me', to: '/home/me/win' }, - { from: 'C:\\Users\\me\\proj', to: '/home/me/win/proj' }, + { from: 'C:\\Users\\me', to: target }, + { from: 'C:\\Users\\me\\proj', to: deepTarget }, ]) assert.equal(maps.length, 2, 'both entries survive normalization') assert.equal(maps[0].from, 'C:\\Users\\me\\proj', 'the deeper prefix sorts first') const deep = matchCwdMap('C:\\Users\\me\\proj\\src', maps) assert.equal(deep?.remainder.join('/'), 'src') - assert.equal(deep?.entry.to, '/home/me/win/proj') + assert.equal(deep?.entry.to, deepTarget) // 段边界:me2 不是 me 的前缀命中。 assert.equal(matchCwdMap('C:\\Users\\me2\\proj', maps), undefined) assert.equal(matchCwdMap('C:\\Users\\me2', maps), undefined) // Windows 语义:大小写不敏感。 - assert.equal(matchCwdMap('c:\\users\\ME\\proj', maps)?.entry.to, '/home/me/win/proj') + assert.equal(matchCwdMap('c:\\users\\ME\\proj', maps)?.entry.to, deepTarget) // 前缀本身(无剩余段)。 assert.deepEqual(matchCwdMap('C:\\Users\\me', maps)?.remainder, []) - // 映射按段拼接,不会把 `/home/me/win` 变成 `/home/me/winproj`。 - assert.equal(projectCwd('C:\\Users\\me\\proj', { map: maps, sessionRoot: '/root/sessions' }).cwd, '/home/me/win/proj') - assert.equal(projectCwd('C:\\Users\\me\\other', { map: maps, sessionRoot: '/root/sessions' }).cwd, '/home/me/win/other') + // 映射按段拼接,不会把 target 变成 targetproj。 + assert.equal(projectCwd('C:\\Users\\me\\proj', { map: maps, sessionRoot: path.resolve('sessions-root') }).cwd, deepTarget) + assert.equal(projectCwd('C:\\Users\\me\\other', { map: maps, sessionRoot: path.resolve('sessions-root') }).cwd, path.join(target, 'other')) }) test('normalizeCwdMap rejects malformed entries loudly', () => { assert.throws(() => normalizeCwdMap('nope'), /cwdMap must be an array/u) - assert.throws(() => normalizeCwdMap([{ from: 'C:\\me', to: '/a' }, { from: 'c:\\ME', to: '/b' }]), /duplicate from/u) - assert.throws(() => normalizeCwdMap([{ from: 'relative/path', to: '/a' }]), /from must be an absolute path/u) + assert.throws( + () => normalizeCwdMap([{ from: 'C:\\me', to: path.resolve('a') }, { from: 'c:\\ME', to: path.resolve('b') }]), + /duplicate from/u, + ) + assert.throws(() => normalizeCwdMap([{ from: 'relative/path', to: path.resolve('a') }]), /from must be an absolute path/u) assert.throws(() => normalizeCwdMap([{ from: 'C:\\me', to: 'relative' }]), /to must be an absolute path/u) - assert.throws(() => normalizeCwdMap([{ from: 'C:\\me', to: '/a', extra: 1 }]), /unknown key/u) - assert.throws(() => normalizeCwdMap([{ from: '', to: '/a' }]), /from must be a non-empty string/u) + assert.throws(() => normalizeCwdMap([{ from: 'C:\\me', to: path.resolve('a'), extra: 1 }]), /unknown key/u) + assert.throws(() => normalizeCwdMap([{ from: '', to: path.resolve('a') }]), /from must be a non-empty string/u) }) test('projectKey matches the host layout formula (golden values)', () => { @@ -126,14 +137,14 @@ test('projectKey matches the host layout formula (golden values)', () => { assert.equal(projectedRelOf(`${SESSION_ID}/session.v4.jsonl.zstd`, '/home/me/proj'), undefined) }) -test('a Windows header becomes visible on Linux after restore (real host backend)', async (t) => { +test('a foreign-platform header becomes visible after restore (real host backend)', async (t) => { const { root, clean } = await makeTemp() t.after(clean) const sessionRoot = path.join(root, 'sessions') const repoDir = path.join(root, 'repo') const mirrorRoot = path.join(repoDir, 'sessions') - const mappedRoot = path.join(root, 'linux') - const mappedCwd = path.join(mappedRoot, 'proj') // from 'C:\Users\me' + remainder 'proj' + const mappedRoot = path.join(root, 'local') + const mappedCwd = path.join(mappedRoot, 'proj') // FOREIGN_PREFIX + remainder 'proj' await fs.mkdir(path.join(repoDir, '.git'), { recursive: true }) await fs.mkdir(path.join(mirrorRoot, ...CANONICAL_REL.split('/').slice(0, -1)), { recursive: true }) const canonical = sessionLog(headerLine(), `${JSON.stringify({ type: 'user/message', seq: 0 })}\n`) @@ -143,7 +154,7 @@ test('a Windows header becomes visible on Linux after restore (real host backend repoDir, mirrorRoot, sessionRoot, - cwdMap: normalizeCwdMap([{ from: 'C:\\Users\\me', to: mappedRoot }]), + cwdMap: normalizeCwdMap([{ from: FOREIGN_PREFIX, to: mappedRoot }]), }) assert.equal(result.restored, 1) assert.equal(result.cwdMapped, 1) @@ -193,7 +204,7 @@ test('a session with no matching mapping lands read-only in the --unmapped-- pla const parsed = readSessionHeader(await fs.readFile(localPath), true) assert.equal(parsed?.header.cwd, placeholderCwd) assert.equal((await fs.stat(placeholderCwd)).isDirectory(), true, 'the placeholder directory is created for workspace grouping') - if (process.platform !== 'win32') { + if (!IS_WINDOWS) { assert.equal((await fs.stat(localPath)).mode & 0o222, 0, 'the unmapped copy is best-effort read-only on disk') } @@ -210,7 +221,7 @@ test('a session with no matching mapping lands read-only in the --unmapped-- pla await assert.rejects(fs.stat(path.join(mirrorRoot, projectKey(placeholderCwd))), { code: 'ENOENT' }) // 即便有人在占位副本上追加,推送端也不接管(只读视图语义)。 - if (process.platform !== 'win32') await fs.chmod(localPath, 0o644) + await fs.chmod(localPath, 0o644).catch(() => {}) const appended = Buffer.concat([await fs.readFile(localPath), zstdFrame('{"type":"user/message","seq":1}\n')]) await fs.writeFile(localPath, appended) await mirrorSessionRoot({ sessionRoot, repoDir, mirrorDir: 'sessions' }) @@ -223,8 +234,8 @@ test('appends to a mapped projection push as byte-identical appends to the origi const sessionRoot = path.join(root, 'sessions') const repoDir = path.join(root, 'repo') const mirrorRoot = path.join(repoDir, 'sessions') - const mappedRoot = path.join(root, 'linux') - const mappedCwd = path.join(mappedRoot, 'proj') // from 'C:\Users\me' + remainder 'proj' + const mappedRoot = path.join(root, 'local') + const mappedCwd = path.join(mappedRoot, 'proj') await fs.mkdir(path.join(repoDir, '.git'), { recursive: true }) await fs.mkdir(path.join(mirrorRoot, ...CANONICAL_REL.split('/').slice(0, -1)), { recursive: true }) const firstEvent = zstdFrame('{"type":"user/message","seq":0}\n') @@ -235,7 +246,7 @@ test('appends to a mapped projection push as byte-identical appends to the origi repoDir, mirrorRoot, sessionRoot, - cwdMap: normalizeCwdMap([{ from: 'C:\\Users\\me', to: mappedRoot }]), + cwdMap: normalizeCwdMap([{ from: FOREIGN_PREFIX, to: mappedRoot }]), }) const localPath = path.join(sessionRoot, ...`${projectKey(mappedCwd)}/${SESSION_ID}/session.v4.jsonl.zstd`.split('/')) const appendedFrame = zstdFrame('{"type":"assistant/message","seq":1}\n') @@ -246,9 +257,9 @@ test('appends to a mapped projection push as byte-identical appends to the origi const pushed = await fs.readFile(path.join(mirrorRoot, ...CANONICAL_REL.split('/'))) assert.deepEqual(pushed.subarray(0, canonical.length), canonical, 'the origin header frame is preserved byte-for-byte') assert.deepEqual(pushed.subarray(canonical.length), appendedFrame, 'only the appended frames are added') - // 宿主读回镜像里的原会话(对端视角)仍然一致:header 仍是 Windows cwd。 + // 宿主读回镜像里的原会话(对端视角)仍然一致:header 仍是另一平台的 cwd。 const origin = readSessionHeader(pushed, true) - assert.equal(origin?.header.cwd, WINDOWS_CWD) + assert.equal(origin?.header.cwd, FOREIGN_CWD) }) test('projection is skipped when the directory does not encode the header id', () => { @@ -256,8 +267,8 @@ test('projection is skipped when the directory does not encode the header id', ( const plan = planRestoreFile({ content, mirrorRel: CANONICAL_REL, - cwdMap: normalizeCwdMap([{ from: 'C:\\Users\\me', to: '/home/me/win' }]), - sessionRoot: '/root/sessions', + cwdMap: normalizeCwdMap([{ from: FOREIGN_PREFIX, to: path.resolve('local-target') }]), + sessionRoot: path.resolve('sessions-root'), }) assert.equal(plan.kind, 'skipped') assert.equal(plan.rel, CANONICAL_REL) @@ -265,7 +276,7 @@ test('projection is skipped when the directory does not encode the header id', ( }) test('followSessionSymlinks: inside-root links are opt-in, outside links never follow', async (t) => { - if (process.platform === 'win32') return t.skip('symlink creation needs extra privileges on Windows') + if (IS_WINDOWS) return t.skip('symlink creation needs extra privileges on Windows') const { root, clean } = await makeTemp() t.after(clean) const sessionRoot = path.join(root, 'sessions') @@ -327,22 +338,13 @@ test('sync_status exposes skipped symlinks and cwd projection diagnostics', asyn assert.match(text, /warning: 3 file\(s\) under sessionRoot/u) }) -test('resolveConfig validates cwdMap and followSessionSymlinks', () => { - const base = { sessionRoot: '/tmp/sessions', repoDir: '/tmp/repo' } - const resolved = resolveConfig({ ...base, cwdMap: [{ from: 'C:\\Users\\me', to: '/home/me' }] }) - assert.equal(resolved.cwdMap.length, 1) - assert.equal(resolved.followSessionSymlinks, false) - assert.throws(() => resolveConfig({ ...base, cwdMap: [{ from: 'C:\\me', to: 'relative' }] }), /to must be an absolute path/u) - assert.throws(() => resolveConfig(/** @type {any} */ ({ ...base, followSessionSymlinks: 'yes' })), /followSessionSymlinks must be a boolean/u) -}) - test('prune maps a projected path back to the mirror and prunes remote deletions', async (t) => { const { root, clean } = await makeTemp() t.after(clean) const sessionRoot = path.join(root, 'sessions') const repoDir = path.join(root, 'repo') const mirrorRoot = path.join(repoDir, 'sessions') - const mappedRoot = path.join(root, 'linux') + const mappedRoot = path.join(root, 'local') await fs.mkdir(path.join(repoDir, '.git'), { recursive: true }) await fs.mkdir(path.join(mirrorRoot, ...CANONICAL_REL.split('/').slice(0, -1)), { recursive: true }) await fs.writeFile(path.join(mirrorRoot, ...CANONICAL_REL.split('/')), sessionLog(headerLine())) @@ -350,7 +352,7 @@ test('prune maps a projected path back to the mirror and prunes remote deletions repoDir, mirrorRoot, sessionRoot, - cwdMap: normalizeCwdMap([{ from: 'C:\\Users\\me', to: mappedRoot }]), + cwdMap: normalizeCwdMap([{ from: FOREIGN_PREFIX, to: mappedRoot }]), }) const projectedRel = `${projectKey(path.join(mappedRoot, 'proj'))}/${SESSION_ID}/session.v4.jsonl.zstd` const localPath = path.join(sessionRoot, ...projectedRel.split('/')) @@ -362,3 +364,12 @@ test('prune maps a projected path back to the mirror and prunes remote deletions assert.deepEqual(pruned.pruned, [projectedRel]) await assert.rejects(fs.stat(localPath), { code: 'ENOENT' }) }) + +test('resolveConfig validates cwdMap and followSessionSymlinks', () => { + const base = { sessionRoot: path.resolve('sessions'), repoDir: path.resolve('repo') } + const resolved = resolveConfig({ ...base, cwdMap: [{ from: 'C:\\Users\\me', to: path.resolve('home-me') }] }) + assert.equal(resolved.cwdMap.length, 1) + assert.equal(resolved.followSessionSymlinks, false) + assert.throws(() => resolveConfig({ ...base, cwdMap: [{ from: 'C:\\me', to: 'relative' }] }), /to must be an absolute path/u) + assert.throws(() => resolveConfig(/** @type {any} */ ({ ...base, followSessionSymlinks: 'yes' })), /followSessionSymlinks must be a boolean/u) +})