Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand All @@ -36,9 +39,10 @@
$DSH_HOME/sessions ──byte mirror──▶ <repoDir>/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 `<projectKey(mapped cwd)>/<sessionId>/<file>` — 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 `<sessionRoot>/--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

Expand Down Expand Up @@ -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 (`<projectKey>/<sessionId>/<file>` 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
Expand Down
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
# Changelog

## [0.3.0] - 2026-11-13

### 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 `<projectKey(mapped cwd)>/<sessionId>/<file>`, 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 `<sessionRoot>/--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 `<root>/<projectKey(header.cwd)>/<sessionId>/<file>`, which pins our `projectKey` implementation and directory layout).

## [0.2.33] - 2026-11-13

### Fixed
Expand Down
27 changes: 26 additions & 1 deletion README.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<sessionRoot>/--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` |

<details>
<summary>Full configuration table (21 keys)</summary>
<summary>Full configuration table (23 keys)</summary>

| Key | Default | Meaning |
|---|---|---|
Expand All @@ -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 `<sessionRoot>/--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) |
Expand Down Expand Up @@ -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 `<sessionRoot>/--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.
Expand Down
27 changes: 26 additions & 1 deletion README.es.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<sessionRoot>/--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` |

<details>
<summary>Tabla de configuración completa (21 claves)</summary>
<summary>Tabla de configuración completa (23 claves)</summary>

| Clave | Valor por defecto | Significado |
|---|---|---|
Expand All @@ -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 `<sessionRoot>/--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) |
Expand Down Expand Up @@ -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 `<sessionRoot>/--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.
Expand Down
Loading
Loading