chat-relink 0.0.0-stage → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +55 -0
- package/LICENSE +21 -0
- package/README.ko.md +221 -0
- package/README.md +220 -2
- package/dist/cli/demo.js +112 -0
- package/dist/cli/index.js +394 -0
- package/dist/core/exportJson.js +55 -0
- package/dist/core/fixture.js +158 -0
- package/dist/core/msg.js +21 -0
- package/dist/core/paths.js +84 -0
- package/dist/core/preview.js +57 -0
- package/dist/core/relink.js +412 -0
- package/dist/core/runningGuard.js +82 -0
- package/dist/core/scan.js +208 -0
- package/dist/core/sessionLog.js +123 -0
- package/dist/core/stateDb.js +129 -0
- package/dist/core/workspaceId.js +44 -0
- package/dist/extension/extension.js +179 -0
- package/dist/extension/ui.js +122 -0
- package/dist/i18n/en.js +168 -0
- package/dist/i18n/ko.js +168 -0
- package/dist/i18n/messages.js +53 -0
- package/package.json +88 -4
- package/package.nls.json +5 -0
- package/package.nls.ko.json +5 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented in this file.
|
|
4
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
5
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
6
|
+
|
|
7
|
+
## [Unreleased]
|
|
8
|
+
|
|
9
|
+
## [0.1.4] - 2026-12-06
|
|
10
|
+
|
|
11
|
+
### Fixed
|
|
12
|
+
- Option errors (missing value, unknown option, value given to a flag) are now translated; `--lang ko` no longer shows Node's English text after "사용법 오류:".
|
|
13
|
+
|
|
14
|
+
## [0.1.3] - 2026-11-23
|
|
15
|
+
|
|
16
|
+
### Changed
|
|
17
|
+
- CI is now a single job: Ubuntu 24.04, Node 24, `npm ci` -> `npm run typecheck` -> `npm test` (no Node matrix, no weekly schedule, no demo step, no npm cache).
|
|
18
|
+
- `@vscode/vsce` is no longer a devDependency. `npm run package` downloads `@vscode/vsce@4.1.1` with `npx` at release time (needs network).
|
|
19
|
+
- devDependencies are pinned to exact versions (`typescript` 7.0.2, `vitest` 5.1.1, `@types/node` 24.19.2, `@types/vscode` 1.146.0); the lock file was updated in place.
|
|
20
|
+
- Environment inputs are injectable and the tests pass fixed values: folder id (`platform`, `stat`), user data paths (`platform`, `env`, `homedir`), running check (`readLock`, `isAlive`), language (`argv`, `env`). The practice fixture builds its ids from fixed fake birthtime/inode values.
|
|
21
|
+
- New script `npm run typecheck` (`tsc --noEmit`).
|
|
22
|
+
|
|
23
|
+
### Added
|
|
24
|
+
- `test/repoHygiene.test.ts`: offline checks of the CI workflow, lock file sync, install scripts, Linux binaries in the lock and host-dependent patterns in tests.
|
|
25
|
+
|
|
26
|
+
## [0.1.2] - 2026-11-23
|
|
27
|
+
|
|
28
|
+
### Fixed
|
|
29
|
+
- `run()` (the CLI entry used in-process by tests) no longer replaces the process-wide `warning` listeners; only the real `chat-relink` process hides the `node:sqlite` ExperimentalWarning, now for every command.
|
|
30
|
+
|
|
31
|
+
### Changed
|
|
32
|
+
- README: documented `CHAT_RELINK_HOME` and how to try commands on `demo --keep` data; test count 82.
|
|
33
|
+
|
|
34
|
+
## [0.1.1] - 2026-11-23
|
|
35
|
+
|
|
36
|
+
### Added
|
|
37
|
+
- Cross-platform tests: the full scan, relink and undo flow with the Linux (inode) and macOS (birthtime) id rules, and with reversed directory listings.
|
|
38
|
+
|
|
39
|
+
### Fixed
|
|
40
|
+
- Running-guard and undo tests no longer depend on the host platform (dead PID above Linux `pid_max`, sorted file lists).
|
|
41
|
+
- Preview output is now translated through the English and Korean messages.
|
|
42
|
+
|
|
43
|
+
### Changed
|
|
44
|
+
- CI runs on Ubuntu with Node 22.13 (the lowest supported version) and the current LTS.
|
|
45
|
+
- README: test count, section titles, refreshed screenshots, note on `npx` before the package is published.
|
|
46
|
+
|
|
47
|
+
## [0.1.0] - 2026-11-22
|
|
48
|
+
|
|
49
|
+
### Added
|
|
50
|
+
- Core: user data folder lookup (VS Code, Insiders, VSCodium, Cursor), workspace id rules for macOS, Windows, Linux and remote URIs, orphan scan with ranked candidates, `.jsonl` mutation log replay (kind 0-3, BOM, truncated last line) and legacy `.json` sessions, export JSON for the official `workbench.action.chat.import` command.
|
|
51
|
+
- State database handling with `node:sqlite`: `VACUUM INTO` backup, transactional index update, `integrity_check`, verification and automatic rollback.
|
|
52
|
+
- CLI `chat-relink`: `scan`, `show`, `relink` (dry run by default), `undo`, `export`, `demo`; exit codes 0-5; `--lang en|ko`, `CHAT_RELINK_LANG`.
|
|
53
|
+
- Running VS Code protection through `code.lock` (live PID blocks writes with exit code 3).
|
|
54
|
+
- Read-only VS Code extension: startup notification, `Chat Relink: Find Orphaned Chats`, QuickPick preview, open as imported copies, save a relink plan and copy the CLI command; `chatRelink.language` setting.
|
|
55
|
+
- English and Korean messages for the CLI and the extension.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 LeeGyeongPil
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.ko.md
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
# Chat Relink
|
|
2
|
+
|
|
3
|
+
[English](README.md) | **한국어**
|
|
4
|
+
|
|
5
|
+
Chat Relink 는 프로젝트 폴더 이름을 바꾸거나 옮기거나 다시 클론한 뒤 화면에서 사라진 VS Code 채팅 세션을 찾아 미리 보여 주고, 백업·검증·되돌리기와 함께 새 폴더에 다시 연결해 주는 도구입니다. 읽기 전용 VS Code 확장과 Node CLI 로 이루어져 있고, 둘은 런타임 의존성이 없는 TypeScript 코어 하나를 같이 씁니다.
|
|
6
|
+
|
|
7
|
+

|
|
8
|
+
*`npm start` 는 합성 연습용 데이터로 전체 흐름을 실행합니다. 내 VS Code 데이터는 읽지 않습니다.*
|
|
9
|
+
|
|
10
|
+
> **솔직한 현재 상태 (v0.1.4).** 테스트는 모두 합성 데이터와 `vscode` API 목(mock)으로 돌렸습니다. 확장은 **실제 VS Code 안에서 실행해 보지 못했고**, CLI 도 macOS 에서만 실행했습니다. 소중한 데이터에 쓰기 전에 [지원 레이아웃과 한계](#지원-레이아웃과-한계)를 읽어 주세요. CLI 는 `--apply` 없이는 아무것도 바꾸지 않고, 바꾸기 전에 항상 백업합니다.
|
|
11
|
+
|
|
12
|
+
## 무엇을 해 주나요
|
|
13
|
+
|
|
14
|
+
- **고아 채팅을 찾습니다.** `workspaceStorage/<id>/workspace.json` 을 읽어 폴더가 더는 없는 칸(slot)을 알려 줍니다.
|
|
15
|
+
- **미리 보여 줍니다.** 옮기기 전에 세션별 제목·턴 수·마지막 날짜·파일 형식을 보여 줍니다.
|
|
16
|
+
- **안전하게 다시 연결합니다(CLI).** 기본은 dry-run(계획만 출력)입니다. `--apply` 를 붙이면 상태 DB 를 백업하고, 세션 파일을 덮어쓰지 않고 복사하고, 색인 항목을 한 트랜잭션으로 추가하고, 결과를 검증하고, 실패하면 되돌립니다. `undo` 로 원상 복구합니다.
|
|
17
|
+
- **VS Code 안에서 엽니다(확장).** 알림이 고아 채팅을 알려 주면 QuickPick 에서 세션을 골라 공식 `Chat: Import Chat...` 명령으로 엽니다. VS Code 저장소에는 절대 쓰지 않습니다.
|
|
18
|
+
|
|
19
|
+
우편물 전달 서비스를 떠올리면 쉽습니다. 이사했는데 우체국은 아직 옛 우편함 번호로 배달합니다. 편지(채팅)는 사라진 것이 아니라 옛 주소에 있습니다. Chat Relink 는 옛 주소의 편지를 찾아 새 주소로 전달해 줍니다.
|
|
20
|
+
|
|
21
|
+
## 요구 사항
|
|
22
|
+
|
|
23
|
+
| 항목 | 확인한 버전 | 비고 |
|
|
24
|
+
|---|---|---|
|
|
25
|
+
| Node.js | 26.13.0 (`>=22.13` 필요) | CLI 는 내장 `node:sqlite` 를 쓰므로 따로 설치할 것이 없습니다 |
|
|
26
|
+
| npm | 11.20.0 | |
|
|
27
|
+
| OS | macOS (CLI 실행) | Windows·Linux 의 id 규칙은 고정값 단위 테스트만 했습니다 |
|
|
28
|
+
| VS Code | 실행해 보지 못함 | `engines.vscode` 는 `^1.146.0`, 확장은 목으로만 테스트했습니다 |
|
|
29
|
+
|
|
30
|
+
Node.js 는 패키지 관리자로 설치하세요. macOS 는 `brew install node`, Debian/Ubuntu 는 `sudo apt-get install nodejs npm` 입니다(`node --version` 이 22.13 이상인지 확인).
|
|
31
|
+
|
|
32
|
+
## 설치
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
git clone https://github.com/LeeGyeongPil/chat-relink.git
|
|
36
|
+
cd chat-relink
|
|
37
|
+
npm ci
|
|
38
|
+
npm run build
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
아래에서 `chat-relink` 는 `node dist/cli/index.js` 를 뜻합니다. 진짜 `chat-relink` 명령이 필요하면 `npm link` 를 한 번 실행하세요.
|
|
42
|
+
|
|
43
|
+
확장을 써 보려면 VSIX 를 만들어 설치합니다(패키징은 했지만 실제 VS Code 에 설치해 보지는 **못했습니다**).
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
npm run package # 릴리스 단계: npx 로 @vscode/vsce@4.1.1 을 받으므로 네트워크 필요
|
|
47
|
+
code --install-extension chat-relink-0.1.4.vsix
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## 빠르게 시작하기
|
|
51
|
+
|
|
52
|
+
연습 데모를 실행합니다. 임시 폴더에 합성 `workspaceStorage` 를 만들고 프로젝트 이름을 바꾼 뒤, 실제 파일과 실제 SQLite DB 로 모든 단계를 거칩니다. 내 데이터는 건드리지 않습니다.
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
npm start
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
마지막 줄들은 이렇게 보입니다(영어 출력, 실제 실행 결과):
|
|
59
|
+
|
|
60
|
+
```text
|
|
61
|
+
[6/8] Relink for real: backup, copy, update index, verify
|
|
62
|
+
relinked: 2
|
|
63
|
+
integrity: ok
|
|
64
|
+
[7/8] The lesson: why we never write while VS Code runs
|
|
65
|
+
a running VS Code caches the index and rewrites all of it on the next chat save
|
|
66
|
+
external entry lost after flush: true
|
|
67
|
+
[8/8] Undo with the journal
|
|
68
|
+
undo: restored
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
그다음 내 데이터에 써 봅니다. 영구 연결 단계에서는 VS Code 를 **종료**해야 합니다.
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
chat-relink scan --current ~/code/shop-api-v2
|
|
75
|
+
chat-relink show shop-api
|
|
76
|
+
chat-relink relink --from shop-api --to ~/code/shop-api-v2 # dry-run
|
|
77
|
+
chat-relink relink --from shop-api --to ~/code/shop-api-v2 --apply # 실제로 씀
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## 사용법
|
|
81
|
+
|
|
82
|
+
스크린샷은 데모의 합성 데이터입니다. 폴더 `shop-api` 를 `shop-api-v2` 로 바꾼 상황입니다.
|
|
83
|
+
|
|
84
|
+
### 1. 고아 찾기: `scan`
|
|
85
|
+
|
|
86
|
+

|
|
87
|
+
*한 줄이 `workspaceStorage` 칸 하나입니다. `고아` 는 폴더가 없어졌는데 채팅이 남은 칸입니다. 원격·멀티 루트 작업 영역은 이유와 함께 건너뜁니다.*
|
|
88
|
+
|
|
89
|
+
`--current <폴더>` 를 주면 그 폴더와 얼마나 비슷한지(이름 일치, 두 폴더에 같이 있는 파일)로 고아 칸의 순위를 매깁니다.
|
|
90
|
+
|
|
91
|
+
### 2. 미리보기: `show`
|
|
92
|
+
|
|
93
|
+

|
|
94
|
+
*복사하기 전에 제목·턴 수·날짜를 확인합니다. `.jsonl` 과 같은 id 의 구형 `.json` 이 있으면 알려 주고 `.jsonl` 을 씁니다.*
|
|
95
|
+
|
|
96
|
+
### 3. 계획: `--apply` 없는 `relink`
|
|
97
|
+
|
|
98
|
+

|
|
99
|
+
*dry-run 은 무엇을 복사하고 대상 색인 항목이 몇 개가 되는지 보여 줄 뿐 아무것도 쓰지 않습니다.*
|
|
100
|
+
|
|
101
|
+
### 4. 적용: `relink --apply`
|
|
102
|
+
|
|
103
|
+

|
|
104
|
+
*백업(`VACUUM INTO`)과 저널을 먼저 씁니다. 복사와 색인 갱신 뒤 `PRAGMA integrity_check` 를 돌리고, 색인을 다시 파싱하고, 파일이 있는지 확인합니다. 하나라도 실패하면 전부 되돌립니다(종료 코드 4).*
|
|
105
|
+
|
|
106
|
+
### 5. VS Code 실행 중에는 쓰지 않음
|
|
107
|
+
|
|
108
|
+

|
|
109
|
+
*`code.lock` 에 살아 있는 프로세스 id 가 있으면 CLI 는 종료 코드 3 으로 멈추고 아무것도 쓰지 않습니다.*
|
|
110
|
+
|
|
111
|
+
### 6. 되돌리기: `undo <저널>`
|
|
112
|
+
|
|
113
|
+

|
|
114
|
+
*저널 경로는 `--apply` 가 출력합니다. 되돌리기는 DB 를 복원하고, 그 사이 VS Code 가 새 채팅을 저장했다면 자기가 추가한 항목만 제거합니다.*
|
|
115
|
+
|
|
116
|
+
### VS Code 안에서
|
|
117
|
+
|
|
118
|
+
확장은 시작할 때 백그라운드로 `workspaceStorage` 를 훑습니다. 연 폴더에 채팅이 없는데 비슷한 고아 폴더에 있으면 **Review**·**Not now**·**Never for this folder** 가 있는 알림을 띄웁니다. 명령 팔레트에서 **Chat Relink: Find Orphaned Chats**(고아 채팅 찾기)를 직접 실행해도 됩니다.
|
|
119
|
+
|
|
120
|
+
- QuickPick 에서 세션(제목·턴 수·마지막 날짜)을 고르면 `workbench.action.chat.import` 로 하나씩 열립니다. 이것은 **가져온 사본**입니다. VS Code 의 import 는 원래 세션 id 와 날짜를 버리므로 사본은 새 id·날짜를 받을 수 있습니다.
|
|
121
|
+
- **Relink permanently...** 는 계획 파일을 쓰고 CLI 명령을 클립보드에 복사합니다. VS Code 를 완전히 종료한 뒤 터미널에 붙여 넣으세요. 원래 세션 id·제목·날짜가 유지되는 것은 이 경로뿐입니다.
|
|
122
|
+
- 복사된 명령은 `npx chat-relink relink ...` 로 시작하므로 `npx` 가 npm 에 게시된 `chat-relink` 패키지를 한 번 내려받아 실행합니다(네트워크 요청 1회, 클론한 코드가 아니라 게시된 버전). 클론해서 빌드했다면 `npx chat-relink` 대신 `node dist/cli/index.js` 로 바꿔 붙여 넣으세요. 패키지가 아직 npm 에 없으면 `npx` 가 404 로 실패하니 `node dist/cli/index.js` 형태를 쓰세요.
|
|
123
|
+
|
|
124
|
+
실제 VS Code 가 없는 환경이라 확장 스크린샷은 찍지 못했습니다. 그래서 여기에는 없습니다.
|
|
125
|
+
|
|
126
|
+
### 그 밖의 명령
|
|
127
|
+
|
|
128
|
+
| 명령 | 하는 일 |
|
|
129
|
+
|---|---|
|
|
130
|
+
| `chat-relink export --from <칸\|경로> --out <폴더>` | 공식 `Chat: Import Chat...` 용으로 세션마다 JSON 하나를 씁니다. 채팅에 붙여 넣은 비밀 값이 들어 있을 수 있으니 채팅 자체처럼 다루세요. |
|
|
131
|
+
| `chat-relink demo [--keep]` | 연습 데모. `--keep` 은 합성 폴더를 남겨 다른 명령을 시험해 볼 수 있게 합니다. |
|
|
132
|
+
| `chat-relink --version` / `--help` | `0.1.4` / 사용법을 출력합니다. |
|
|
133
|
+
|
|
134
|
+
종료 코드: 0 성공, 1 실패, 2 사용법 오류, 3 VS Code 실행 중, 4 검증 실패(되돌림), 5 대상 칸 없음.
|
|
135
|
+
|
|
136
|
+
공통 옵션: `--user-data-dir <폴더>`, `--product code|insiders|vscodium|cursor`, `--json`, `--lang en|ko`.
|
|
137
|
+
|
|
138
|
+
## 설정
|
|
139
|
+
|
|
140
|
+
| 키 | 기본값 | 설명 |
|
|
141
|
+
|---|---|---|
|
|
142
|
+
| `chatRelink.language` | `auto` | 확장 언어: `auto`(VS Code 표시 언어), `en`, `ko` |
|
|
143
|
+
| `chatRelink.scanOnStartup` | `true` | 폴더를 열 때 고아 채팅을 찾습니다 |
|
|
144
|
+
| `CHAT_RELINK_LANG` (환경 변수) | 없음 | CLI 언어 `en` 또는 `ko`. 우선순위: `--lang` > `CHAT_RELINK_LANG` > `LC_ALL`/`LC_MESSAGES`/`LANG`(`ko` 로 시작하면 한국어) > 영어 |
|
|
145
|
+
| `CHAT_RELINK_USER_DATA_DIR` (환경 변수) | 없음 | `--user-data-dir` 을 안 줬을 때 쓸 사용자 데이터 폴더 |
|
|
146
|
+
| `CHAT_RELINK_HOME` (환경 변수) | `~/.chat-relink` | 백업·저널·계획 파일을 쓰는 폴더 |
|
|
147
|
+
|
|
148
|
+
기본 사용자 데이터 폴더: `~/Library/Application Support/Code`(macOS), `%APPDATA%\Code`(Windows), `~/.config/Code`(Linux). `Code - Insiders`·`VSCodium`·`Cursor` 는 `--product` 로 고릅니다. 백업과 저널은 `~/.chat-relink/backups`, `~/.chat-relink/journals` 에 저장됩니다(기준 폴더는 `CHAT_RELINK_HOME` 으로 바꿉니다).
|
|
149
|
+
|
|
150
|
+
연습 데이터로 다른 명령을 시험하려면 `chat-relink demo --keep` 을 실행하세요. `연습 폴더를 남겼습니다: <dir>` 처럼 폴더를 알려 주면 `--user-data-dir <dir>/userdata` (예: `chat-relink scan --user-data-dir <dir>/userdata`)를 쓰고 `CHAT_RELINK_HOME=<dir>/tool-home` 으로 지정해 실제 홈 폴더에는 아무것도 쓰지 않게 합니다.
|
|
151
|
+
|
|
152
|
+
## 채팅이 사라지는 이유
|
|
153
|
+
|
|
154
|
+
VS Code 는 연 폴더마다 폴더 해시(경로와 생성 시각 또는 inode)로 이름 붙인 저장 칸을 둡니다. 폴더 이름을 바꾸거나 옮기거나 다시 클론하면 해시가 바뀌어 VS Code 는 새 빈 칸을 봅니다. 옛 칸은 디스크에 그대로 있습니다.
|
|
155
|
+
|
|
156
|
+
```mermaid
|
|
157
|
+
flowchart LR
|
|
158
|
+
A[옛 폴더: shop-api] -->|해시| B[칸 1: 채팅 2개]
|
|
159
|
+
C[이름 변경: shop-api-v2] -->|새 해시| D[칸 2: 비어 있음]
|
|
160
|
+
B -. Chat Relink 가 세션과 색인 항목을 복사 .-> D
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
## 동작 원리
|
|
164
|
+
|
|
165
|
+
1. 칸은 `workspaceStorage/<id>/` 입니다. `workspace.json`(어느 폴더인지), `chatSessions/`(세션마다 `.jsonl` 또는 구형 `.json` 하나), 그리고 공용 `state.vscdb` SQLite 파일 안의 색인(키 `chat.ChatSessionStore.index`)으로 이루어집니다.
|
|
166
|
+
2. 스캐너가 폴더가 없는 칸을 찾고, 세션 로그를 재생해 미리보기를 만들고, 후보 순위를 매깁니다.
|
|
167
|
+
3. 재연결기가 파일을 덮어쓰지 않고 복사하고 색인 항목을 추가합니다. 백업·저널·검증이 함께 따릅니다.
|
|
168
|
+
4. 테스트는 플랫폼·파일 stat·PID 생존·홈 폴더·로케일을 실제 값 대신 주입하므로 어느 OS 에서도 같게 동작합니다.
|
|
169
|
+
|
|
170
|
+
## 안전 설계
|
|
171
|
+
|
|
172
|
+
쓰기 전에 CLI 는 상태 DB 백업과 저널을 먼저 만듭니다. 파일은 덮어쓰지 않고 복사하고, 색인은 한 트랜잭션으로 갱신하고, 결과를 검증하고, 검사가 실패하면 되돌립니다. 끝난 재연결은 `undo` 로 되돌릴 수 있습니다.
|
|
173
|
+
|
|
174
|
+
**VS Code 실행 중에는 왜 쓰지 않나.** 실행 중인 VS Code 는 색인을 메모리에 두었다가 다음 채팅 저장 때 통째로 다시 씁니다. 밖에서 고친 내용은 그때 지워집니다. SQLite 잠금으로도 막을 수 없습니다. `npm test` 가 실제 SQLite 연결 두 개로 이것을 재현하고, 데모는 `external entry lost after flush: true` 로 보여 줍니다. 그래서 CLI 는 `code.lock` 에 살아 있는 PID 가 있으면 쓰기를 거부하고, 확장은 아예 쓰지 않습니다.
|
|
175
|
+
|
|
176
|
+
**접근 범위.** 모든 것이 로컬입니다. 네트워크 요청을 하지 않습니다. CLI 는 VS Code 사용자 데이터 폴더와 `~/.chat-relink/` 를 읽고(`--apply` 일 때만) 씁니다. 확장은 `workspaceStorage` 를 읽기만 하고, `~/.chat-relink/plans/` 아래 계획 파일만 씁니다.
|
|
177
|
+
|
|
178
|
+
## 언어
|
|
179
|
+
|
|
180
|
+
CLI 와 확장은 영어와 한국어를 지원합니다. CLI: `--lang en|ko`, 그다음 `CHAT_RELINK_LANG`, 그다음 `LC_ALL`/`LC_MESSAGES`/`LANG` 순이며 한국어가 아니면 영어입니다. 확장: `chatRelink.language` 설정(`auto` 는 VS Code 표시 언어를 따름).
|
|
181
|
+
|
|
182
|
+
## 지원 레이아웃과 한계
|
|
183
|
+
|
|
184
|
+
- 확장은 `vscode` API 목으로만 테스트했습니다. 실제 VS Code 에서 가져온 사본이 기록에 저장되는지, 제목이 유지되는지는 확인하지 못했습니다.
|
|
185
|
+
- Node 22.13 하한은 CI 가 아니라 로컬에서만 확인했습니다.
|
|
186
|
+
- Windows·Linux 의 workspace id 규칙은 고정값 단위 테스트로만 검증했고 그 OS 에서 실행하지 못했습니다. macOS CLI 실행도 실제 VS Code 프로필이 아니라 합성 데이터였습니다.
|
|
187
|
+
- `code.lock` 에 PID 가 들어 있다는 것은 VS Code 소스를 읽고 안 사실이며 실제 설치본에서 확인한 것이 아닙니다.
|
|
188
|
+
- 원격·멀티 루트·빈 창 칸은 재연결하지 않고 `건너뜀` 으로만 알려 줍니다.
|
|
189
|
+
- 세션 형식과 색인 키는 VS Code 버전마다 바뀔 수 있습니다. 색인 `version` 이 1 이 아니면 쓰기를 거부하고, 모르는 필드는 경고합니다.
|
|
190
|
+
- VS Code 는 칸(slot)마다 채팅 색인 항목을 최대 400개(`maxPersistedSessions`)까지만 보관합니다. 대상이 이 상한을 넘으면 relink 가 경고합니다.
|
|
191
|
+
|
|
192
|
+
## 언제 쓰나
|
|
193
|
+
|
|
194
|
+
- 잘 맞는 상황: 로컬 폴더 이름을 바꾸거나 옮기거나 다시 클론한 뒤 그 폴더의 VS Code 채팅을 미리 보기와 백업과 함께 되찾고 싶을 때.
|
|
195
|
+
- 다른 도구: 채팅 기록을 보기만 하려면 Visual Studio Marketplace 의 기록 뷰어 확장을 보세요. 상위 논의는 [microsoft/vscode#305818](https://github.com/microsoft/vscode/issues/305818)·[#257143](https://github.com/microsoft/vscode/issues/257143), 공식 기록 동기화는 [VS Code 세션 기록 문서](https://code.visualstudio.com/docs/agents/run/sessions/session-history)를 보세요.
|
|
196
|
+
|
|
197
|
+
## 자주 겪는 문제
|
|
198
|
+
|
|
199
|
+
| 증상 | 원인 | 해결 |
|
|
200
|
+
|---|---|---|
|
|
201
|
+
| `VS Code is running ... Nothing was written.` (종료 코드 3) | `code.lock` 에 살아 있는 PID 가 있음 | VS Code 를 모든 창까지 완전히 종료한 뒤 다시 실행 |
|
|
202
|
+
| `No slot found for the folder ...` (종료 코드 5) | 새 폴더를 한 번도 연 적 없거나 경로가 `workspace.json` 과 다름 | VS Code 에서 한 번 열고 종료한 뒤 다시 실행 |
|
|
203
|
+
| 종료 코드 4 | 검증 검사 하나가 실패 | 도구가 되돌렸습니다. 바뀐 것은 없습니다. 메시지와 함께 이슈를 올려 주세요 |
|
|
204
|
+
| 시작할 때 Node 버전 메시지 | Node 가 22.13 보다 오래됨 | Node 22.13 이상 설치 |
|
|
205
|
+
| 채팅이 보이는데 날짜가 새로움 | 공식 import 로 열었음 | 원래 id·제목·날짜를 유지하려면 CLI 로 재연결 |
|
|
206
|
+
|
|
207
|
+
## 개발
|
|
208
|
+
|
|
209
|
+
```bash
|
|
210
|
+
npm ci
|
|
211
|
+
npm run typecheck
|
|
212
|
+
npm test # 약 1초, 오프라인
|
|
213
|
+
npm run build
|
|
214
|
+
npm start # 빌드 후 연습 데모
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
CI 는 Ubuntu 24.04 잡 하나, Node 24 에서 `npm ci`, `npm run typecheck`, `npm test` 를 돌립니다(모두 오프라인). engines 하한인 Node 22.13 은 로컬에서만 확인했습니다. 변경 기록은 [CHANGELOG.md](CHANGELOG.md).
|
|
218
|
+
|
|
219
|
+
## 라이선스
|
|
220
|
+
|
|
221
|
+
MIT.
|
package/README.md
CHANGED
|
@@ -1,3 +1,221 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Chat Relink
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**English** | [한국어](https://github.com/LeeGyeongPil/chat-relink/blob/v0.1.4/README.ko.md)
|
|
4
|
+
|
|
5
|
+
Chat Relink finds the VS Code chat sessions that vanished after you renamed, moved or re-cloned a project folder, lets you preview them, and relinks them to the new folder with a backup, a verification step and an undo. It ships as a small read-only VS Code extension plus a Node CLI that share one TypeScript core with zero runtime dependencies.
|
|
6
|
+
|
|
7
|
+

|
|
8
|
+
*`npm start` runs the whole flow on a synthetic practice fixture. Your own VS Code data is not read.*
|
|
9
|
+
|
|
10
|
+
> **Honest status (v0.1.4).** All tests run against synthetic data and a mocked `vscode` API. The extension has **not** been run inside a real VS Code, and the CLI has only been run on macOS. See [Supported layouts & limits](#supported-layouts--limits) before pointing it at data you care about. The CLI never changes anything without `--apply`, and it backs up first.
|
|
11
|
+
|
|
12
|
+
## What it does
|
|
13
|
+
|
|
14
|
+
- **Finds orphaned chats.** It reads each `workspaceStorage/<id>/workspace.json`, and reports the slots whose folder no longer exists.
|
|
15
|
+
- **Previews them.** Title, number of turns, last date and file format per session, before you move anything.
|
|
16
|
+
- **Relinks them safely (CLI).** Dry run by default. With `--apply` it backs up the state database, copies the session files without overwriting, adds the index entries in one transaction, verifies the result and rolls back on failure. `undo` reverts it.
|
|
17
|
+
- **Opens them from inside VS Code (extension).** A notification offers the orphaned chats; you pick sessions in a QuickPick and open them through the official `Chat: Import Chat...` command. It never writes to VS Code's storage.
|
|
18
|
+
|
|
19
|
+
Think of it as a mail-forwarding service. You moved house and the post office still delivers to the old mailbox number. The letters (your chats) are not lost; they sit at the old address. Chat Relink looks for letters at old addresses and forwards them to the new one.
|
|
20
|
+
|
|
21
|
+
## Requirements
|
|
22
|
+
|
|
23
|
+
| Item | Version I checked | Note |
|
|
24
|
+
|---|---|---|
|
|
25
|
+
| Node.js | 26.13.0 (needs `>=22.13`) | The CLI uses the built-in `node:sqlite`, so there is nothing else to install |
|
|
26
|
+
| npm | 11.20.0 | |
|
|
27
|
+
| OS | macOS (CLI run) | Windows and Linux id rules are unit-tested with fixed values only |
|
|
28
|
+
| VS Code | not run | `engines.vscode` is `^1.146.0`; the extension was only tested against a mock |
|
|
29
|
+
|
|
30
|
+
Install Node.js with your package manager, for example `brew install node` on macOS or `sudo apt-get install nodejs npm` on Debian/Ubuntu (check that `node --version` is 22.13 or newer).
|
|
31
|
+
|
|
32
|
+
## Install
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
git clone https://github.com/LeeGyeongPil/chat-relink.git
|
|
36
|
+
cd chat-relink
|
|
37
|
+
npm ci
|
|
38
|
+
npm run build
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Below, `chat-relink` means `node dist/cli/index.js`. To get a real `chat-relink` command, run `npm link` once.
|
|
42
|
+
|
|
43
|
+
To try the extension, build a VSIX and install it (this step was packaged but **not** installed into a real VS Code):
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
npm run package # release step: downloads @vscode/vsce@4.1.1 with npx, needs network
|
|
47
|
+
code --install-extension chat-relink-0.1.4.vsix
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Quick start
|
|
51
|
+
|
|
52
|
+
Run the practice demo. It builds a synthetic `workspaceStorage` in a temporary folder, renames the project, and walks through every step on real files and a real SQLite database. You can run it without touching your own data.
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
npm start
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
The last lines look like this (English output, from a real run):
|
|
59
|
+
|
|
60
|
+
```text
|
|
61
|
+
[6/8] Relink for real: backup, copy, update index, verify
|
|
62
|
+
relinked: 2
|
|
63
|
+
integrity: ok
|
|
64
|
+
[7/8] The lesson: why we never write while VS Code runs
|
|
65
|
+
a running VS Code caches the index and rewrites all of it on the next chat save
|
|
66
|
+
external entry lost after flush: true
|
|
67
|
+
[8/8] Undo with the journal
|
|
68
|
+
undo: restored
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Then try it on your own data, with VS Code **closed** for the permanent step:
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
chat-relink scan --current ~/code/shop-api-v2
|
|
75
|
+
chat-relink show shop-api
|
|
76
|
+
chat-relink relink --from shop-api --to ~/code/shop-api-v2 # dry run
|
|
77
|
+
chat-relink relink --from shop-api --to ~/code/shop-api-v2 --apply # writes
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Usage
|
|
81
|
+
|
|
82
|
+
The screenshots use the synthetic fixture from the demo: the folder `shop-api` was renamed to `shop-api-v2`.
|
|
83
|
+
|
|
84
|
+
### 1. Find orphans: `scan`
|
|
85
|
+
|
|
86
|
+

|
|
87
|
+
*Each row is one `workspaceStorage` slot. `orphan` means its folder is gone and it still holds chats. Remote and multi-root workspaces are skipped with a reason.*
|
|
88
|
+
|
|
89
|
+
`--current <folder>` ranks the orphans by how well they match that folder (name match, plus files that exist in both folders).
|
|
90
|
+
|
|
91
|
+
### 2. Preview: `show`
|
|
92
|
+
|
|
93
|
+

|
|
94
|
+
*Check titles, turns and dates before copying. A legacy `.json` file with the same id as a `.jsonl` is noted, and the `.jsonl` is used.*
|
|
95
|
+
|
|
96
|
+
### 3. Plan: `relink` without `--apply`
|
|
97
|
+
|
|
98
|
+

|
|
99
|
+
*The dry run lists what would be copied and how many index entries the target would have. Nothing is written.*
|
|
100
|
+
|
|
101
|
+
### 4. Apply: `relink --apply`
|
|
102
|
+
|
|
103
|
+

|
|
104
|
+
*A backup (`VACUUM INTO`) and a journal are written first. After the copy and the index update, the tool checks `PRAGMA integrity_check`, re-parses the index and confirms the files exist. A failed check rolls everything back (exit code 4).*
|
|
105
|
+
|
|
106
|
+
### 5. Refusing to write while VS Code runs
|
|
107
|
+
|
|
108
|
+

|
|
109
|
+
*If `code.lock` holds a live process id, the CLI stops with exit code 3 and writes nothing.*
|
|
110
|
+
|
|
111
|
+
### 6. Undo: `undo <journal>`
|
|
112
|
+
|
|
113
|
+

|
|
114
|
+
*The journal path was printed by `--apply`. Undo restores the database, or, if VS Code saved new chats in between, removes only the entries it added.*
|
|
115
|
+
|
|
116
|
+
### In VS Code
|
|
117
|
+
|
|
118
|
+
On startup the extension scans `workspaceStorage` in the background. If the folder you opened has no chats but a similar orphaned folder does, it shows a notification with **Review**, **Not now** and **Never for this folder**. You can also run **Chat Relink: Find Orphaned Chats** from the Command Palette.
|
|
119
|
+
|
|
120
|
+
- Pick sessions in the QuickPick (title, turns, last date) and they open one by one through `workbench.action.chat.import`. These are **imported copies**: VS Code's import drops the original session id and dates, so a copy may get a new id and date.
|
|
121
|
+
- **Relink permanently...** writes a plan file and copies the CLI command to your clipboard. Quit VS Code completely and paste it into a terminal. Only that path keeps the original session id, title and date.
|
|
122
|
+
- The copied command starts with `npx chat-relink relink ...`, so `npx` downloads the published `chat-relink` package from npm once (one network request, and the published version, not your clone). If you built from a clone, paste it with `node dist/cli/index.js` in place of `npx chat-relink`. If the package is not on npm yet, `npx` fails with a 404; use the `node dist/cli/index.js` form.
|
|
123
|
+
|
|
124
|
+
I could not capture screenshots of the extension because no real VS Code was available in my environment, so there are none here.
|
|
125
|
+
|
|
126
|
+
### Other commands
|
|
127
|
+
|
|
128
|
+
| Command | What it does |
|
|
129
|
+
|---|---|
|
|
130
|
+
| `chat-relink export --from <slot\|path> --out <dir>` | Writes one JSON per session for the official `Chat: Import Chat...`. Exported files can contain secrets that were pasted into chats, so treat them like the chats themselves. |
|
|
131
|
+
| `chat-relink demo [--keep]` | The practice demo. `--keep` leaves the synthetic folder so you can try the other commands on it. |
|
|
132
|
+
| `chat-relink --version` / `--help` | Prints `0.1.4` / the usage. |
|
|
133
|
+
|
|
134
|
+
Exit codes: 0 ok, 1 failure, 2 usage, 3 VS Code is running, 4 verification failed (rolled back), 5 target slot not found.
|
|
135
|
+
|
|
136
|
+
Common options: `--user-data-dir <dir>`, `--product code|insiders|vscodium|cursor`, `--json`, `--lang en|ko`.
|
|
137
|
+
|
|
138
|
+
## Configuration
|
|
139
|
+
|
|
140
|
+
| Key | Default | Description |
|
|
141
|
+
|---|---|---|
|
|
142
|
+
| `chatRelink.language` | `auto` | Extension language: `auto` (VS Code display language), `en`, `ko` |
|
|
143
|
+
| `chatRelink.scanOnStartup` | `true` | Look for orphaned chats when a folder is opened |
|
|
144
|
+
| `CHAT_RELINK_LANG` (env) | unset | CLI language `en` or `ko`. Priority: `--lang` > `CHAT_RELINK_LANG` > `LC_ALL`/`LC_MESSAGES`/`LANG` (starts with `ko` gives Korean) > English |
|
|
145
|
+
| `CHAT_RELINK_USER_DATA_DIR` (env) | unset | User data folder when `--user-data-dir` is not given |
|
|
146
|
+
| `CHAT_RELINK_HOME` (env) | `~/.chat-relink` | Where backups, journals and plans are written |
|
|
147
|
+
|
|
148
|
+
Default user data folders: `~/Library/Application Support/Code` (macOS), `%APPDATA%\Code` (Windows), `~/.config/Code` (Linux); `Code - Insiders`, `VSCodium` and `Cursor` via `--product`. Backups and journals go to `~/.chat-relink/backups` and `~/.chat-relink/journals` (change the base folder with `CHAT_RELINK_HOME`).
|
|
149
|
+
|
|
150
|
+
To try the other commands on the practice data, run `chat-relink demo --keep`. It prints `Kept the practice folder: <dir>`; then use `--user-data-dir <dir>/userdata` (for example `chat-relink scan --user-data-dir <dir>/userdata`) and set `CHAT_RELINK_HOME=<dir>/tool-home` so nothing is written to your real home folder.
|
|
151
|
+
|
|
152
|
+
## Why chats disappear
|
|
153
|
+
|
|
154
|
+
Each opened folder gets a storage slot named by a hash of the folder (path plus its creation time or inode). Rename, move or re-clone the folder and the hash changes, so VS Code looks in a new, empty slot. The old slot is still on disk.
|
|
155
|
+
|
|
156
|
+
```mermaid
|
|
157
|
+
flowchart LR
|
|
158
|
+
A[Old folder: shop-api] -->|hash| B[Slot 1: 2 chats]
|
|
159
|
+
C[Renamed: shop-api-v2] -->|new hash| D[Slot 2: empty]
|
|
160
|
+
B -. Chat Relink copies sessions and index entries .-> D
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
## How it works
|
|
164
|
+
|
|
165
|
+
1. A slot is `workspaceStorage/<id>/` with a `workspace.json` (which folder), a `chatSessions/` folder (one `.jsonl` or legacy `.json` per session) and an index inside the shared `state.vscdb` SQLite file (key `chat.ChatSessionStore.index`).
|
|
166
|
+
2. The scanner finds slots whose folder does not exist, replays each session log for the preview and ranks candidates.
|
|
167
|
+
3. The relinker copies the files without overwriting and adds the index entries, with a backup, a journal and verification.
|
|
168
|
+
4. Tests inject the platform, file stat, PID liveness, home folder and locale instead of reading the real ones, so they behave the same on any OS.
|
|
169
|
+
|
|
170
|
+
## Safety design
|
|
171
|
+
|
|
172
|
+
Before anything is written, the CLI makes a backup of the state database and a journal. Files are copied without overwriting, the index is updated in one transaction, the result is verified, and a failed check rolls back. `undo` reverts a finished relink.
|
|
173
|
+
|
|
174
|
+
**Why it never writes while VS Code runs.** A running VS Code keeps the index in memory and rewrites all of it on its next chat save, which erases an outside edit. SQLite locking does not prevent this. `npm test` reproduces it with two real SQLite connections, and the demo shows it as `external entry lost after flush: true`. So the CLI refuses to write if `code.lock` holds a live PID, and the extension never writes at all.
|
|
175
|
+
|
|
176
|
+
**Access scope.** Everything is local. The tool makes no network requests. The CLI reads and (with `--apply`) writes the VS Code user data folder and `~/.chat-relink/`. The extension only reads `workspaceStorage`, plus a plan file under `~/.chat-relink/plans/`.
|
|
177
|
+
|
|
178
|
+
## Language
|
|
179
|
+
|
|
180
|
+
The CLI and the extension speak English and Korean. CLI: `--lang en|ko`, then `CHAT_RELINK_LANG`, then `LC_ALL`/`LC_MESSAGES`/`LANG`; anything not Korean gives English. Extension: the `chatRelink.language` setting (`auto` follows the VS Code display language).
|
|
181
|
+
|
|
182
|
+
## Supported layouts & limits
|
|
183
|
+
|
|
184
|
+
- The extension was tested only against a mocked `vscode` API. I have not confirmed in a real VS Code that an imported copy is saved to history or keeps its title.
|
|
185
|
+
- The Node 22.13 floor was checked locally only, not in CI.
|
|
186
|
+
- The workspace id rules for Windows and Linux are covered by unit tests with fixed values, not by runs on those systems. The macOS CLI run used the synthetic fixture, not a real VS Code profile.
|
|
187
|
+
- That `code.lock` contains a PID is taken from reading the VS Code source, not from a real installation.
|
|
188
|
+
- Remote, multi-root and empty-window slots are reported as `skipped`, not relinked.
|
|
189
|
+
- The session format and index key can change between VS Code versions. The tool refuses to write if the index `version` is not 1, and warns on unknown fields.
|
|
190
|
+
- VS Code keeps at most 400 chat index entries per slot (`maxPersistedSessions`); relink warns when the target would exceed it.
|
|
191
|
+
|
|
192
|
+
## When to use it
|
|
193
|
+
|
|
194
|
+
- Good fit: you renamed, moved or re-cloned a local folder and want its VS Code chats back, with a preview first and a backup.
|
|
195
|
+
- Other tools: for browsing chat history only, see the history viewers on the Visual Studio Marketplace. To follow the upstream discussions, see [microsoft/vscode#305818](https://github.com/microsoft/vscode/issues/305818) and [#257143](https://github.com/microsoft/vscode/issues/257143). For the official history sync, see the [VS Code session history docs](https://code.visualstudio.com/docs/agents/run/sessions/session-history).
|
|
196
|
+
|
|
197
|
+
## Troubleshooting
|
|
198
|
+
|
|
199
|
+
| Symptom | Cause | Fix |
|
|
200
|
+
|---|---|---|
|
|
201
|
+
| `Error: VS Code is running ... Nothing was written.` (exit 3) | `code.lock` holds a live PID | Quit VS Code completely (all windows), then run again |
|
|
202
|
+
| `No slot found for the folder ...` (exit 5) | The new folder was never opened, or the path differs from `workspace.json` | Open it in VS Code once, quit VS Code, run again |
|
|
203
|
+
| Exit code 4 | A verification check failed | The tool rolled back. Nothing changed; open an issue with the message |
|
|
204
|
+
| The node version message at start | Node is older than 22.13 | Install Node 22.13 or newer |
|
|
205
|
+
| Chats appear but have a new date | They were opened through the official import | Use the CLI relink to keep the original id, title and date |
|
|
206
|
+
|
|
207
|
+
## Development
|
|
208
|
+
|
|
209
|
+
```bash
|
|
210
|
+
npm ci
|
|
211
|
+
npm run typecheck
|
|
212
|
+
npm test # about a second, offline
|
|
213
|
+
npm run build
|
|
214
|
+
npm start # build, then the practice demo
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
CI is one Ubuntu 24.04 job on Node 24: `npm ci`, `npm run typecheck`, `npm test` (all offline). Node 22.13, the engines floor, was checked locally only. Changes are listed in [CHANGELOG.md](https://github.com/LeeGyeongPil/chat-relink/blob/v0.1.4/CHANGELOG.md).
|
|
218
|
+
|
|
219
|
+
## License
|
|
220
|
+
|
|
221
|
+
MIT.
|
package/dist/cli/demo.js
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.runDemo = runDemo;
|
|
7
|
+
const node_fs_1 = __importDefault(require("node:fs"));
|
|
8
|
+
const node_os_1 = __importDefault(require("node:os"));
|
|
9
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
10
|
+
const fixture_1 = require("../core/fixture");
|
|
11
|
+
const preview_1 = require("../core/preview");
|
|
12
|
+
const relink_1 = require("../core/relink");
|
|
13
|
+
const runningGuard_1 = require("../core/runningGuard");
|
|
14
|
+
const scan_1 = require("../core/scan");
|
|
15
|
+
const stateDb_1 = require("../core/stateDb");
|
|
16
|
+
const messages_1 = require("../i18n/messages");
|
|
17
|
+
function runDemo(io, lang, opts = {}) {
|
|
18
|
+
const m = (0, messages_1.translator)(lang);
|
|
19
|
+
const root = node_fs_1.default.mkdtempSync(node_path_1.default.join(node_fs_1.default.realpathSync(node_os_1.default.tmpdir()), 'chat-relink-demo-'));
|
|
20
|
+
const toolHome = node_path_1.default.join(root, 'tool-home');
|
|
21
|
+
const guarded = (dir) => (0, runningGuard_1.checkRunning)(dir, opts.guard);
|
|
22
|
+
try {
|
|
23
|
+
io.out(m('demo.banner'));
|
|
24
|
+
io.out('');
|
|
25
|
+
// 1. fixture + rename
|
|
26
|
+
io.out(`[1/8] ${m('demo.step1')}`);
|
|
27
|
+
const fx = (0, fixture_1.buildFixture)({ root, includeSkipped: true });
|
|
28
|
+
io.out(m('demo.step1.detail', {
|
|
29
|
+
from: node_path_1.default.basename(fx.oldFolder),
|
|
30
|
+
to: node_path_1.default.basename(fx.currentFolder),
|
|
31
|
+
oldId: fx.oldId.slice(0, 8),
|
|
32
|
+
newId: fx.currentId.slice(0, 8),
|
|
33
|
+
}));
|
|
34
|
+
// 2. scan
|
|
35
|
+
io.out(`[2/8] ${m('demo.step2')}`);
|
|
36
|
+
const slots = (0, scan_1.scanStorage)(fx.storageDir);
|
|
37
|
+
const orphans = slots.filter((s) => s.status === 'orphan' && s.sessions.length > 0);
|
|
38
|
+
const skipped = slots.filter((s) => s.status === 'skipped');
|
|
39
|
+
const ranked = (0, scan_1.rankCandidates)(slots, fx.currentFolder);
|
|
40
|
+
io.out(` orphans: ${orphans.length}`);
|
|
41
|
+
io.out(` skipped: ${skipped.length}`);
|
|
42
|
+
const from = ranked[0]?.slot;
|
|
43
|
+
const to = (0, scan_1.findSlotByPath)(slots, fx.currentFolder);
|
|
44
|
+
if (!from || !to)
|
|
45
|
+
throw new relink_1.RelinkError('demo fixture is inconsistent', 1);
|
|
46
|
+
// 3. preview
|
|
47
|
+
io.out(`[3/8] ${m('demo.step3')}`);
|
|
48
|
+
for (const s of from.sessions) {
|
|
49
|
+
const pv = (0, preview_1.previewFile)(s.file);
|
|
50
|
+
io.out(` - ${pv.title} | ${pv.turns} | ${(0, preview_1.formatDate)(pv.lastDate)} | ${pv.format}`);
|
|
51
|
+
}
|
|
52
|
+
// 4. dry run
|
|
53
|
+
io.out(`[4/8] ${m('demo.step4')}`);
|
|
54
|
+
const plan = (0, relink_1.planRelink)({ from, to });
|
|
55
|
+
const treeBefore = node_fs_1.default.readdirSync(node_path_1.default.join(to.dir, 'chatSessions')).length;
|
|
56
|
+
io.out(` plan: copy ${plan.items.filter((i) => i.action === 'copy').length}, skip ${plan.items.filter((i) => i.action === 'skip').length}`);
|
|
57
|
+
// 5. running guard
|
|
58
|
+
io.out(`[5/8] ${m('demo.step5')}`);
|
|
59
|
+
// this demo process plays "VS Code": its own PID goes into code.lock
|
|
60
|
+
const lock = (0, fixture_1.writeLock)(fx.userDataDir, process.pid);
|
|
61
|
+
let guardExit = 0;
|
|
62
|
+
try {
|
|
63
|
+
(0, relink_1.applyRelink)(plan, { userDataDir: fx.userDataDir, toolHome, checkRunning: guarded });
|
|
64
|
+
}
|
|
65
|
+
catch (e) {
|
|
66
|
+
if (e instanceof relink_1.RelinkError)
|
|
67
|
+
guardExit = e.code;
|
|
68
|
+
}
|
|
69
|
+
io.out(m('demo.step5.detail'));
|
|
70
|
+
io.out(` running guard: ${guarded(fx.userDataDir).state}, exit ${guardExit}`);
|
|
71
|
+
node_fs_1.default.rmSync(lock);
|
|
72
|
+
// 6. real apply
|
|
73
|
+
io.out(`[6/8] ${m('demo.step6')}`);
|
|
74
|
+
const result = (0, relink_1.applyRelink)(plan, { userDataDir: fx.userDataDir, toolHome, checkRunning: guarded });
|
|
75
|
+
io.out(` relinked: ${result.copied.length}`);
|
|
76
|
+
io.out(` integrity: ${result.integrity}`);
|
|
77
|
+
// 7. the cache race, on a throwaway copy of the target database
|
|
78
|
+
io.out(`[7/8] ${m('demo.step7')}`);
|
|
79
|
+
const raceCopy = node_path_1.default.join(root, 'race.vscdb');
|
|
80
|
+
node_fs_1.default.copyFileSync(node_path_1.default.join(to.dir, 'state.vscdb'), raceCopy);
|
|
81
|
+
const race = (0, runningGuard_1.simulateRunningFlush)(raceCopy);
|
|
82
|
+
io.out(m('demo.step7.detail'));
|
|
83
|
+
io.out(` external entry lost after flush: ${race.externalLostAfterFlush}`);
|
|
84
|
+
// 8. undo
|
|
85
|
+
io.out(`[8/8] ${m('demo.step8')}`);
|
|
86
|
+
const undo = (0, relink_1.undoRelink)(result.journal, { checkRunning: guarded });
|
|
87
|
+
const db = (0, stateDb_1.openDb)(node_path_1.default.join(to.dir, 'state.vscdb'), { readOnly: true });
|
|
88
|
+
const indexAfter = Object.keys((0, stateDb_1.readIndex)(db).entries).length;
|
|
89
|
+
db.close();
|
|
90
|
+
const restored = undo.confirmed && indexAfter === 0 && node_fs_1.default.readdirSync(node_path_1.default.join(to.dir, 'chatSessions')).length === treeBefore;
|
|
91
|
+
const undoLabel = restored ? 'restored' : 'incomplete';
|
|
92
|
+
io.out(` undo: ${undoLabel}`);
|
|
93
|
+
return {
|
|
94
|
+
orphans: orphans.length,
|
|
95
|
+
relinked: result.copied.length,
|
|
96
|
+
integrity: result.integrity,
|
|
97
|
+
externalLostAfterFlush: race.externalLostAfterFlush,
|
|
98
|
+
undo: undoLabel,
|
|
99
|
+
guardExit,
|
|
100
|
+
dir: root,
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
finally {
|
|
104
|
+
if (opts.keep) {
|
|
105
|
+
io.out(m('demo.kept', { dir: root }));
|
|
106
|
+
}
|
|
107
|
+
else {
|
|
108
|
+
node_fs_1.default.rmSync(root, { recursive: true, force: true });
|
|
109
|
+
io.out(m('demo.cleanup'));
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|