chat-relink 0.0.0-stage → 0.1.3

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.
@@ -0,0 +1,378 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __importDefault = (this && this.__importDefault) || function (mod) {
4
+ return (mod && mod.__esModule) ? mod : { "default": mod };
5
+ };
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.run = run;
8
+ const node_fs_1 = __importDefault(require("node:fs"));
9
+ const node_path_1 = __importDefault(require("node:path"));
10
+ const node_util_1 = require("node:util");
11
+ const exportJson_1 = require("../core/exportJson");
12
+ const preview_1 = require("../core/preview");
13
+ const relink_1 = require("../core/relink");
14
+ const paths_1 = require("../core/paths");
15
+ const scan_1 = require("../core/scan");
16
+ const runningGuard_1 = require("../core/runningGuard");
17
+ const workspaceId_1 = require("../core/workspaceId");
18
+ const messages_1 = require("../i18n/messages");
19
+ const msg_1 = require("../core/msg");
20
+ const demo_1 = require("./demo");
21
+ const VERSION = '0.1.3';
22
+ /** Absolute path with symlinks resolved (macOS /tmp is /private/tmp); plain resolve when it does not exist. */
23
+ function realPath(p) {
24
+ const abs = node_path_1.default.resolve(p);
25
+ try {
26
+ return node_fs_1.default.realpathSync(abs);
27
+ }
28
+ catch {
29
+ return abs;
30
+ }
31
+ }
32
+ function resolveSlot(slots, ref) {
33
+ const exact = slots.filter((s) => s.id === ref);
34
+ const byPrefix = ref.length >= 4 ? slots.filter((s) => s.id.startsWith(ref)) : [];
35
+ const byPath = slots.filter((s) => s.fsPath !== undefined && node_path_1.default.resolve(s.fsPath) === node_path_1.default.resolve(ref));
36
+ const byName = slots.filter((s) => s.fsPath !== undefined && node_path_1.default.basename(s.fsPath) === ref);
37
+ for (const group of [exact, byPrefix, byPath, byName]) {
38
+ if (group.length === 1)
39
+ return { slot: group[0], matches: group };
40
+ if (group.length > 1)
41
+ return { matches: group };
42
+ }
43
+ return { matches: [] };
44
+ }
45
+ function statusText(m, s) {
46
+ const base = m(`status.${s.status}`);
47
+ return s.reason ? `${base}: ${m(`reason.${s.reason}`)}` : base;
48
+ }
49
+ function table(rows) {
50
+ const widths = rows.reduce((w, r) => r.map((c, i) => Math.max(w[i] ?? 0, c.length)), []);
51
+ return rows.map((r) => r.map((c, i) => (i === r.length - 1 ? c : c.padEnd(widths[i] ?? 0))).join(' '));
52
+ }
53
+ async function run(argv, io, env = process.env, deps = {}) {
54
+ // Look at `--lang` before full parsing so even usage errors come out in the right language.
55
+ const lang = (0, messages_1.resolveLang)({ argv, env });
56
+ const m = (0, messages_1.translator)(lang);
57
+ (0, msg_1.setCoreLang)(lang);
58
+ const real = (0, paths_1.currentPathEnv)();
59
+ const pe = { platform: deps.platform ?? real.platform, homedir: deps.homedir ?? real.homedir, env };
60
+ // every write command asks the same (injectable) question: is VS Code running?
61
+ const guarded = (dir) => (0, runningGuard_1.checkRunning)(dir, deps.guard);
62
+ const json = (value) => io.out(JSON.stringify(value, null, 2));
63
+ let parsed;
64
+ function parse() {
65
+ return (0, node_util_1.parseArgs)({
66
+ args: argv,
67
+ allowPositionals: true,
68
+ strict: true,
69
+ options: {
70
+ lang: { type: 'string' },
71
+ 'user-data-dir': { type: 'string' },
72
+ product: { type: 'string' },
73
+ current: { type: 'string' },
74
+ json: { type: 'boolean' },
75
+ from: { type: 'string' },
76
+ to: { type: 'string' },
77
+ sessions: { type: 'string' },
78
+ apply: { type: 'boolean' },
79
+ out: { type: 'string' },
80
+ keep: { type: 'boolean' },
81
+ help: { type: 'boolean', short: 'h' },
82
+ version: { type: 'boolean', short: 'v' },
83
+ },
84
+ });
85
+ }
86
+ const usage = (detail) => {
87
+ io.err(m('error.usage', { detail }));
88
+ return relink_1.EXIT.usage;
89
+ };
90
+ try {
91
+ parsed = parse();
92
+ }
93
+ catch (e) {
94
+ return usage(e.message);
95
+ }
96
+ const { values, positionals } = parsed;
97
+ if (values.lang !== undefined && !(0, messages_1.isLang)(values.lang))
98
+ return usage(m('error.badLang', { lang: values.lang }));
99
+ if (values.help) {
100
+ io.out(m('help.text'));
101
+ return relink_1.EXIT.ok;
102
+ }
103
+ if (values.version) {
104
+ io.out(VERSION);
105
+ return relink_1.EXIT.ok;
106
+ }
107
+ const command = positionals[0];
108
+ if (!command)
109
+ return usage(m('error.missingCommand'));
110
+ if (values.product !== undefined && !(0, paths_1.isProduct)(values.product)) {
111
+ return usage(m('error.badProduct', { product: values.product }));
112
+ }
113
+ const major = Number.parseInt(process.versions.node.split('.')[0] ?? '0', 10);
114
+ const minor = Number.parseInt(process.versions.node.split('.')[1] ?? '0', 10);
115
+ if (major < 22 || (major === 22 && minor < 13)) {
116
+ io.err(m('error.failure', { message: m('error.nodeVersion', { version: process.versions.node }) }));
117
+ return relink_1.EXIT.failure;
118
+ }
119
+ const userDataDir = (0, paths_1.resolveUserDataDir)({ userDataDir: values['user-data-dir'], product: values.product }, pe);
120
+ const storageDir = (0, paths_1.workspaceStorageDir)(userDataDir);
121
+ const needStorage = () => {
122
+ if (node_fs_1.default.existsSync(storageDir))
123
+ return true;
124
+ io.err(m('error.failure', { message: m('error.storageMissing', { dir: storageDir }) }));
125
+ return false;
126
+ };
127
+ const lookup = (slots, ref) => {
128
+ const { slot, matches } = resolveSlot(slots, ref);
129
+ if (slot)
130
+ return slot;
131
+ if (matches.length > 1) {
132
+ io.err(m('error.failure', { message: m('error.slotAmbiguous', { ref, count: matches.length, list: matches.map((s) => s.id.slice(0, 8)).join(', ') }) }));
133
+ }
134
+ else {
135
+ io.err(m('error.failure', { message: m('error.slotNotFound', { ref }) }));
136
+ }
137
+ return undefined;
138
+ };
139
+ try {
140
+ switch (command) {
141
+ case 'scan': {
142
+ if (!needStorage())
143
+ return relink_1.EXIT.failure;
144
+ const slots = (0, scan_1.scanStorage)(storageDir);
145
+ const current = node_path_1.default.resolve(values.current ?? process.cwd());
146
+ const ranked = (0, scan_1.rankCandidates)(slots, current).filter(scan_1.isRelevant);
147
+ const counts = {
148
+ orphans: slots.filter((s) => s.status === 'orphan' && s.sessions.length > 0).length,
149
+ skipped: slots.filter((s) => s.status === 'skipped').length,
150
+ ok: slots.filter((s) => s.status === 'ok').length,
151
+ };
152
+ if (values.json) {
153
+ json({
154
+ userDataDir,
155
+ slots: slots.map((s) => ({ id: s.id, folder: s.fsPath ?? s.uri ?? null, status: s.status, reason: s.reason ?? null, sessions: s.sessions.length })),
156
+ candidates: ranked.map((c) => ({ id: c.slot.id, nameScore: c.nameScore, evidence: c.evidence })),
157
+ ...counts,
158
+ });
159
+ return relink_1.EXIT.ok;
160
+ }
161
+ io.out(m('scan.header', { dir: storageDir }));
162
+ if (slots.length === 0) {
163
+ io.out(m('scan.none'));
164
+ return relink_1.EXIT.ok;
165
+ }
166
+ const header = m('scan.columns').trim().split(/\s{2,}/);
167
+ const body = slots.map((s) => [s.id.slice(0, 8), statusText(m, s), String(s.sessions.length), s.fsPath ?? s.uri ?? '-']);
168
+ for (const line of table([header, ...body])) {
169
+ io.out(line);
170
+ }
171
+ io.out(m('scan.summary', counts));
172
+ if (values.current !== undefined || ranked.length > 0) {
173
+ if (ranked.length > 0) {
174
+ io.out(m('scan.candidates', { folder: current }));
175
+ for (const c of ranked) {
176
+ io.out(m('scan.candidate', { id: c.slot.id.slice(0, 8), name: node_path_1.default.basename(c.slot.fsPath ?? c.slot.id), sessions: c.slot.sessions.length, nameScore: c.nameScore, evidence: c.evidence }));
177
+ }
178
+ }
179
+ else {
180
+ io.out(m('scan.noCandidates', { folder: current }));
181
+ }
182
+ }
183
+ if (counts.orphans > 0)
184
+ io.out(m('scan.next'));
185
+ return relink_1.EXIT.ok;
186
+ }
187
+ case 'show': {
188
+ const ref = positionals[1];
189
+ if (!ref)
190
+ return usage(m('error.missingArgument', { command: 'show', what: '<slot|path>' }));
191
+ if (!needStorage())
192
+ return relink_1.EXIT.failure;
193
+ const slot = lookup((0, scan_1.scanStorage)(storageDir), ref);
194
+ if (!slot)
195
+ return relink_1.EXIT.failure;
196
+ const previews = slot.sessions.map((s) => ({ s, p: (0, preview_1.previewFile)(s.file) }));
197
+ if (values.json) {
198
+ json({ id: slot.id, folder: slot.fsPath ?? slot.uri ?? null, status: slot.status, sessions: previews.map(({ s, p }) => ({ ...p, hasJsonTwin: s.hasJsonTwin, lastDate: p.lastDate ?? null })) });
199
+ return relink_1.EXIT.ok;
200
+ }
201
+ io.out(m('show.header', { id: slot.id.slice(0, 8), folder: slot.fsPath ?? slot.uri ?? '-' }));
202
+ if (previews.length === 0) {
203
+ io.out(m('show.empty'));
204
+ return relink_1.EXIT.ok;
205
+ }
206
+ io.out(m('show.columns'));
207
+ for (const { s, p } of previews) {
208
+ io.out(`${p.sessionId.slice(0, 8)} ${String(p.turns).padEnd(5)} ${(0, preview_1.formatDate)(p.lastDate)} ${p.format.padEnd(6)} ${p.title}`);
209
+ if (s.hasJsonTwin)
210
+ io.out(m('show.twin'));
211
+ if (p.error)
212
+ io.out(m('show.error', { text: p.error }));
213
+ for (const w of p.warnings)
214
+ io.out(m('show.warning', { text: w }));
215
+ }
216
+ return relink_1.EXIT.ok;
217
+ }
218
+ case 'relink': {
219
+ if (!values.from)
220
+ return usage(m('error.missingOption', { name: 'from' }));
221
+ if (!values.to)
222
+ return usage(m('error.missingOption', { name: 'to' }));
223
+ if (!needStorage())
224
+ return relink_1.EXIT.failure;
225
+ const slots = (0, scan_1.scanStorage)(storageDir);
226
+ const from = lookup(slots, values.from);
227
+ if (!from)
228
+ return relink_1.EXIT.usage;
229
+ const folder = realPath(values.to);
230
+ let to = (0, scan_1.findSlotByPath)(slots, folder);
231
+ if (!to && node_fs_1.default.existsSync(folder)) {
232
+ // no workspace.json names this folder: compute its id the way VS Code does
233
+ const id = (0, workspaceId_1.localFolderId)(folder, { platform: pe.platform });
234
+ to = slots.find((s) => s.id === id);
235
+ }
236
+ if (!to) {
237
+ io.err(m('error.failure', { message: m('error.targetNotFound', { folder }) }));
238
+ return relink_1.EXIT.noTarget;
239
+ }
240
+ const sessionIds = values.sessions ? values.sessions.split(',').map((x) => x.trim()).filter(Boolean) : undefined;
241
+ const plan = (0, relink_1.planRelink)({ from, to, ...(sessionIds ? { sessionIds } : {}) });
242
+ if (!values.apply) {
243
+ if (values.json)
244
+ json({ mode: 'dry-run', plan: summarizePlan(plan) });
245
+ else
246
+ printPlan(io, m, plan, from, to);
247
+ if (!values.json)
248
+ io.out(m('relink.dryRun'));
249
+ return relink_1.EXIT.ok;
250
+ }
251
+ if (!values.json)
252
+ printPlan(io, m, plan, from, to);
253
+ if (!plan.items.some((i) => i.action === 'copy')) {
254
+ io.out(m('relink.nothingToCopy'));
255
+ return relink_1.EXIT.ok;
256
+ }
257
+ const result = (0, relink_1.applyRelink)(plan, { userDataDir, toolHome: (0, paths_1.toolHomeDir)(pe), checkRunning: guarded });
258
+ if (values.json) {
259
+ json({ mode: 'applied', ...result });
260
+ return relink_1.EXIT.ok;
261
+ }
262
+ for (const w of result.warnings)
263
+ io.out(m('relink.warningRunning', { text: w }));
264
+ io.out(m('relink.applied', { count: result.copied.length }));
265
+ io.out(m('relink.backup', { path: result.backup }));
266
+ io.out(m('relink.integrity', { result: result.integrity }));
267
+ io.out(m('relink.journal', { path: result.journal }));
268
+ io.out(m('relink.undoHint', { path: result.journal }));
269
+ return relink_1.EXIT.ok;
270
+ }
271
+ case 'undo': {
272
+ const journal = positionals[1];
273
+ if (!journal)
274
+ return usage(m('error.missingArgument', { command: 'undo', what: '<journal>' }));
275
+ const res = (0, relink_1.undoRelink)(node_path_1.default.resolve(journal), { checkRunning: guarded });
276
+ if (values.json) {
277
+ json(res);
278
+ return relink_1.EXIT.ok;
279
+ }
280
+ io.out(m('undo.done', { mode: m(`undo.mode.${res.mode}`), files: res.removedFiles, entries: res.removedEntries }));
281
+ io.out(m(res.confirmed ? 'undo.confirmed' : 'undo.notConfirmed'));
282
+ return res.confirmed ? relink_1.EXIT.ok : relink_1.EXIT.failure;
283
+ }
284
+ case 'export': {
285
+ if (!values.from)
286
+ return usage(m('error.missingOption', { name: 'from' }));
287
+ if (!values.out)
288
+ return usage(m('error.missingOption', { name: 'out' }));
289
+ if (!needStorage())
290
+ return relink_1.EXIT.failure;
291
+ const slot = lookup((0, scan_1.scanStorage)(storageDir), values.from);
292
+ if (!slot)
293
+ return relink_1.EXIT.failure;
294
+ const outDir = node_path_1.default.resolve(values.out);
295
+ const written = (0, exportJson_1.exportSessions)(slot.sessions.map((s) => s.file), outDir);
296
+ io.err(m('export.warning'));
297
+ if (values.json) {
298
+ json({ outDir, files: written });
299
+ return relink_1.EXIT.ok;
300
+ }
301
+ io.out(m('export.wrote', { count: written.length, dir: outDir }));
302
+ for (const w of written)
303
+ io.out(m('export.line', { file: w.file, requests: w.requests }));
304
+ io.out(m('export.import'));
305
+ return relink_1.EXIT.ok;
306
+ }
307
+ case 'demo': {
308
+ (0, demo_1.runDemo)({ out: io.out }, lang, { keep: values.keep === true, ...(deps.guard ? { guard: deps.guard } : {}) });
309
+ return relink_1.EXIT.ok;
310
+ }
311
+ default:
312
+ return usage(m('error.unknownCommand', { command }));
313
+ }
314
+ }
315
+ catch (e) {
316
+ if (e instanceof relink_1.VerifyError) {
317
+ io.err(m('relink.verifyFailed', { detail: e.failures.join('; ') }));
318
+ return e.code;
319
+ }
320
+ if (e instanceof relink_1.RelinkError) {
321
+ io.err(m('error.failure', { message: e.i18n ? m(e.i18n.key, e.i18n.params) : e.message }));
322
+ return e.code;
323
+ }
324
+ io.err(m('error.failure', { message: e.message }));
325
+ return relink_1.EXIT.failure;
326
+ }
327
+ }
328
+ function summarizePlan(plan) {
329
+ return {
330
+ from: plan.from.id,
331
+ to: plan.to.id,
332
+ indexCountBefore: plan.indexCountBefore,
333
+ indexCountAfter: plan.indexCountAfter,
334
+ warnings: plan.warnings,
335
+ items: plan.items.map((i) => ({ sessionId: i.sessionId, action: i.action, reason: i.reason ?? null, title: i.title, turns: i.turns })),
336
+ };
337
+ }
338
+ function printPlan(io, m, plan, from, to) {
339
+ io.out(m('relink.planHeader', { from: from.fsPath ?? from.id.slice(0, 8), to: to.fsPath ?? to.id.slice(0, 8) }));
340
+ for (const i of plan.items) {
341
+ io.out(m('relink.item', { action: m(`relink.action.${i.action}`), id: i.sessionId.slice(0, 8), turns: i.turns, title: i.title }));
342
+ if (i.reason)
343
+ io.out(m('relink.itemReason', { reason: m(`relink.reason.${i.reason}`) }));
344
+ }
345
+ io.out(m('relink.indexCount', { before: plan.indexCountBefore, after: plan.indexCountAfter }));
346
+ for (const w of plan.warnings)
347
+ io.out(m('relink.warningRunning', { text: w }));
348
+ }
349
+ /**
350
+ * node:sqlite prints an ExperimentalWarning on some Node versions (22.13 does); hide only that one.
351
+ * This changes process-wide listeners, so only the real `chat-relink` process calls it
352
+ * (never `run()`, which tests and other callers use inside their own process).
353
+ */
354
+ function quietSqliteWarnings() {
355
+ process.removeAllListeners('warning');
356
+ process.on('warning', (w) => {
357
+ // every other warning is still shown
358
+ if (!/sqlite/i.test(w.message))
359
+ process.stderr.write(`${w.name}: ${w.message}\n`);
360
+ });
361
+ }
362
+ if (require.main === module) {
363
+ quietSqliteWarnings();
364
+ // `chat-relink scan | head` closes the pipe early; that is not an error.
365
+ process.stdout.on('error', (e) => {
366
+ if (e.code !== 'EPIPE')
367
+ throw e;
368
+ });
369
+ run(process.argv.slice(2), {
370
+ out: (s) => process.stdout.write(`${s}\n`),
371
+ err: (s) => process.stderr.write(`${s}\n`),
372
+ }).then((code) => {
373
+ process.exitCode = code;
374
+ }, (e) => {
375
+ process.stderr.write(`${e.message}\n`);
376
+ process.exitCode = relink_1.EXIT.failure;
377
+ });
378
+ }
@@ -0,0 +1,55 @@
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.isExportableSessionData = isExportableSessionData;
7
+ exports.toExportJson = toExportJson;
8
+ exports.exportSessions = exportSessions;
9
+ const node_fs_1 = __importDefault(require("node:fs"));
10
+ const node_path_1 = __importDefault(require("node:path"));
11
+ const sessionLog_1 = require("./sessionLog");
12
+ /**
13
+ * Mirror of the precondition VS Code applies before importing a file
14
+ * (`isExportableSessionData`): `requests` is an array and `responderUsername` a string.
15
+ */
16
+ function isExportableSessionData(data) {
17
+ if (data === null || typeof data !== 'object')
18
+ return false;
19
+ const d = data;
20
+ return Array.isArray(d.requests) && typeof d.responderUsername === 'string';
21
+ }
22
+ /** Convert a replayed session to the shape of `Chat: Export Chat...`. */
23
+ function toExportJson(state) {
24
+ const out = {
25
+ version: 3,
26
+ initialLocation: state.initialLocation ?? 1,
27
+ requests: state.requests,
28
+ responderUsername: typeof state.responderUsername === 'string' ? state.responderUsername : 'GitHub Copilot',
29
+ };
30
+ if (typeof state.requesterUsername === 'string')
31
+ out.requesterUsername = state.requesterUsername;
32
+ if (typeof state.sessionId === 'string')
33
+ out.sessionId = state.sessionId;
34
+ if (typeof state.creationDate === 'number')
35
+ out.creationDate = state.creationDate;
36
+ if (typeof state.customTitle === 'string')
37
+ out.customTitle = state.customTitle;
38
+ return out;
39
+ }
40
+ /** Write one export JSON per session file into `outDir`; returns what was written. */
41
+ function exportSessions(sessionFiles, outDir) {
42
+ node_fs_1.default.mkdirSync(outDir, { recursive: true });
43
+ const written = [];
44
+ for (const sf of sessionFiles) {
45
+ const r = (0, sessionLog_1.readSessionFile)(sf);
46
+ const exported = toExportJson(r.state);
47
+ if (!isExportableSessionData(exported))
48
+ continue;
49
+ const sessionId = node_path_1.default.basename(sf).replace(/\.jsonl?$/, '');
50
+ const file = node_path_1.default.join(outDir, `${sessionId}.json`);
51
+ node_fs_1.default.writeFileSync(file, JSON.stringify(exported, null, 2), { mode: 0o600 });
52
+ written.push({ sessionId, file, requests: exported.requests.length });
53
+ }
54
+ return written;
55
+ }
@@ -0,0 +1,158 @@
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.FIXTURE_STATS = exports.FIXTURE_SESSION_IDS = void 0;
7
+ exports.buildSessionLog = buildSessionLog;
8
+ exports.buildLegacyJson = buildLegacyJson;
9
+ exports.buildFixture = buildFixture;
10
+ exports.writeLock = writeLock;
11
+ /**
12
+ * Synthetic workspaceStorage builder. It powers the `demo` command and the test suite,
13
+ * and is the only place that creates fake data: your real VS Code folders are never read by it.
14
+ */
15
+ const node_fs_1 = __importDefault(require("node:fs"));
16
+ const node_path_1 = __importDefault(require("node:path"));
17
+ const node_url_1 = require("node:url");
18
+ const workspaceId_1 = require("./workspaceId");
19
+ const stateDb_1 = require("./stateDb");
20
+ exports.FIXTURE_SESSION_IDS = {
21
+ loginBug: '11111111-1111-4111-8111-111111111111',
22
+ cartRefactor: '22222222-2222-4222-8222-222222222222',
23
+ throwaway: '33333333-3333-4333-8333-333333333333',
24
+ };
25
+ const BASE_TIME = Date.parse('2026-10-01T09:00:00Z');
26
+ /** A `.jsonl` mutation log in the shape VS Code writes (kind 0 initial, 2 push, 1 set). */
27
+ function buildSessionLog(spec) {
28
+ const initial = {
29
+ version: 3,
30
+ sessionId: spec.id,
31
+ creationDate: BASE_TIME,
32
+ initialLocation: 1,
33
+ responderUsername: 'GitHub Copilot',
34
+ requests: [],
35
+ };
36
+ const lines = [{ kind: 0, v: initial }];
37
+ for (let i = 0; i < spec.turns; i++) {
38
+ const text = i === 0 && spec.mention ? `question 0 ${spec.mention}` : `question ${i}`;
39
+ lines.push({
40
+ kind: 2,
41
+ k: ['requests'],
42
+ v: [{ requestId: `request_${i}`, message: { text }, response: [], timestamp: BASE_TIME + i * 60_000 }],
43
+ });
44
+ lines.push({ kind: 1, k: ['requests', i, 'response'], v: [{ value: `answer ${i}` }] });
45
+ }
46
+ lines.push({ kind: 1, k: ['customTitle'], v: spec.title });
47
+ return { text: lines.map((l) => JSON.stringify(l)).join('\n') + '\n', lastDate: BASE_TIME + (spec.turns - 1) * 60_000 };
48
+ }
49
+ /** Same session as a legacy single-document `.json`. */
50
+ function buildLegacyJson(spec) {
51
+ const requests = Array.from({ length: spec.turns }, (_, i) => ({
52
+ requestId: `request_${i}`,
53
+ message: { text: `question ${i}` },
54
+ response: [{ value: `answer ${i}` }],
55
+ timestamp: BASE_TIME + i * 60_000,
56
+ }));
57
+ return JSON.stringify({
58
+ version: 3,
59
+ sessionId: spec.id,
60
+ creationDate: BASE_TIME,
61
+ initialLocation: 1,
62
+ responderUsername: 'GitHub Copilot',
63
+ customTitle: spec.title,
64
+ requests,
65
+ });
66
+ }
67
+ /**
68
+ * Fake birthtime/inode per project. A rename keeps both (same folder, new name),
69
+ * which is exactly why only the path part of the id changes.
70
+ */
71
+ exports.FIXTURE_STATS = {
72
+ 'shop-api': { birthtimeMs: Date.parse('2026-09-01T08:00:00.000Z'), ino: 424242 },
73
+ scratch: { birthtimeMs: Date.parse('2026-09-15T08:00:00.000Z'), ino: 515151 },
74
+ };
75
+ function writeSlot(dir, folderUri, key) {
76
+ node_fs_1.default.mkdirSync(node_path_1.default.join(dir, 'chatSessions'), { recursive: true });
77
+ if (folderUri)
78
+ node_fs_1.default.writeFileSync(node_path_1.default.join(dir, 'workspace.json'), JSON.stringify({ [key]: folderUri }));
79
+ }
80
+ function indexOf(entries) {
81
+ const out = { version: 1, entries: {} };
82
+ for (const e of entries) {
83
+ out.entries[e.spec.id] = { sessionId: e.spec.id, title: e.spec.title, lastMessageDate: e.last, isEmpty: false };
84
+ }
85
+ return out;
86
+ }
87
+ function buildFixture(opts) {
88
+ const platform = opts.platform ?? process.platform;
89
+ const userDataDir = node_path_1.default.join(opts.root, 'userdata');
90
+ const storageDir = node_path_1.default.join(userDataDir, 'User', 'workspaceStorage');
91
+ const projects = node_path_1.default.join(opts.root, 'projects');
92
+ node_fs_1.default.mkdirSync(storageDir, { recursive: true });
93
+ node_fs_1.default.mkdirSync(projects, { recursive: true });
94
+ // id = md5(path + salt from the injected stat): no real birthtime or inode is read
95
+ const statOf = opts.stat ?? ((project) => exports.FIXTURE_STATS[project]);
96
+ const idFor = (project, p) => (0, workspaceId_1.computeFolderId)(p, platform, statOf(project, p));
97
+ // The project as it was before the rename.
98
+ const oldFolder = node_path_1.default.join(projects, 'shop-api');
99
+ node_fs_1.default.mkdirSync(node_path_1.default.join(oldFolder, 'src'), { recursive: true });
100
+ node_fs_1.default.writeFileSync(node_path_1.default.join(oldFolder, 'src', 'login.ts'), 'export const login = 1;\n');
101
+ node_fs_1.default.writeFileSync(node_path_1.default.join(oldFolder, 'src', 'cart.ts'), 'export const cart = 2;\n');
102
+ const oldId = idFor('shop-api', oldFolder);
103
+ const specs = [
104
+ { id: exports.FIXTURE_SESSION_IDS.loginBug, title: 'Fix login bug', turns: 3, mention: `${oldFolder}/src/login.ts` },
105
+ { id: exports.FIXTURE_SESSION_IDS.cartRefactor, title: 'Refactor cart', turns: 2 },
106
+ ];
107
+ const oldDir = node_path_1.default.join(storageDir, oldId);
108
+ writeSlot(oldDir, (0, node_url_1.pathToFileURL)(oldFolder).href, 'folder');
109
+ const built = specs.map((spec) => ({ spec, ...buildSessionLog(spec) }));
110
+ for (const b of built)
111
+ node_fs_1.default.writeFileSync(node_path_1.default.join(oldDir, 'chatSessions', `${b.spec.id}.jsonl`), b.text);
112
+ // Same id as both .json and .jsonl: the scanner must count it once and prefer the .jsonl.
113
+ node_fs_1.default.writeFileSync(node_path_1.default.join(oldDir, 'chatSessions', `${exports.FIXTURE_SESSION_IDS.cartRefactor}.json`), buildLegacyJson(specs[1]));
114
+ (0, stateDb_1.createStateDb)(node_path_1.default.join(oldDir, 'state.vscdb'), indexOf(built.map((b) => ({ spec: b.spec, last: b.lastDate }))), { 'workbench.unrelated': '"old slot value"' });
115
+ let scratchId;
116
+ if (opts.includeScratch) {
117
+ const scratch = node_path_1.default.join(projects, 'scratch');
118
+ node_fs_1.default.mkdirSync(scratch);
119
+ scratchId = idFor('scratch', scratch);
120
+ const spec = { id: exports.FIXTURE_SESSION_IDS.throwaway, title: 'Throwaway experiment', turns: 1 };
121
+ const dir = node_path_1.default.join(storageDir, scratchId);
122
+ writeSlot(dir, (0, node_url_1.pathToFileURL)(scratch).href, 'folder');
123
+ const b = buildSessionLog(spec);
124
+ node_fs_1.default.writeFileSync(node_path_1.default.join(dir, 'chatSessions', `${spec.id}.jsonl`), b.text);
125
+ (0, stateDb_1.createStateDb)(node_path_1.default.join(dir, 'state.vscdb'), indexOf([{ spec, last: b.lastDate }]));
126
+ node_fs_1.default.rmSync(scratch, { recursive: true });
127
+ }
128
+ let remoteId;
129
+ let multiRootId;
130
+ if (opts.includeSkipped) {
131
+ const uri = 'vscode-remote://ssh-remote%2Bdevbox/home/dev/shop-api';
132
+ remoteId = (0, workspaceId_1.computeRemoteId)(uri);
133
+ writeSlot(node_path_1.default.join(storageDir, remoteId), uri, 'folder');
134
+ multiRootId = (0, workspaceId_1.computeRemoteId)('file:///workspaces/shop.code-workspace');
135
+ writeSlot(node_path_1.default.join(storageDir, multiRootId), 'file:///workspaces/shop.code-workspace', 'workspace');
136
+ }
137
+ // Rename: the path changes, so VS Code opens a brand-new, empty slot.
138
+ const currentFolder = node_path_1.default.join(projects, 'shop-api-v2');
139
+ node_fs_1.default.renameSync(oldFolder, currentFolder);
140
+ const currentId = idFor('shop-api', currentFolder);
141
+ const curDir = node_path_1.default.join(storageDir, currentId);
142
+ writeSlot(curDir, (0, node_url_1.pathToFileURL)(currentFolder).href, 'folder');
143
+ (0, stateDb_1.createStateDb)(node_path_1.default.join(curDir, 'state.vscdb'), { version: 1, entries: {} }, { 'workbench.unrelated': '"keep me"' });
144
+ const fx = { root: opts.root, userDataDir, storageDir, currentFolder, oldFolder, oldId, currentId };
145
+ if (scratchId)
146
+ fx.scratchId = scratchId;
147
+ if (remoteId)
148
+ fx.remoteId = remoteId;
149
+ if (multiRootId)
150
+ fx.multiRootId = multiRootId;
151
+ return fx;
152
+ }
153
+ /** Write a fake `code.lock` with the given PID (as a running VS Code would). */
154
+ function writeLock(userDataDir, pid) {
155
+ const file = node_path_1.default.join(userDataDir, 'code.lock');
156
+ node_fs_1.default.writeFileSync(file, String(pid));
157
+ return file;
158
+ }
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.setCoreLang = setCoreLang;
4
+ exports.getCoreLang = getCoreLang;
5
+ exports.cm = cm;
6
+ const messages_1 = require("../i18n/messages");
7
+ /**
8
+ * Language of the messages the core builds (errors, warnings, verification failures).
9
+ * The CLI and the extension set it once per run; library users get English by default.
10
+ */
11
+ let coreLang = 'en';
12
+ function setCoreLang(lang) {
13
+ coreLang = lang;
14
+ }
15
+ function getCoreLang() {
16
+ return coreLang;
17
+ }
18
+ /** Translate a core message into the current core language. */
19
+ function cm(key, params = {}) {
20
+ return (0, messages_1.t)(coreLang, key, params);
21
+ }