claude-instance-manager 0.0.0-stage → 1.0.1

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,173 @@
1
+ const test = require('node:test');
2
+ const assert = require('node:assert/strict');
3
+ const fs = require('fs');
4
+ const os = require('os');
5
+ const path = require('path');
6
+ const { spawnSync } = require('child_process');
7
+ const { wipeInstances } = require('../wipe');
8
+
9
+ function setup() {
10
+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'cim-wipe-test-'));
11
+ const root = path.join(temp, 'appdata');
12
+ fs.mkdirSync(root);
13
+ return { temp, root };
14
+ }
15
+
16
+ function makeDirectory(root, name) {
17
+ const dir = path.join(root, name);
18
+ fs.mkdirSync(dir);
19
+ fs.writeFileSync(path.join(dir, 'data.txt'), 'keep or delete');
20
+ return dir;
21
+ }
22
+
23
+ test('wipes confirmed stopped instances while protecting default, running and linked directories', async () => {
24
+ const { temp, root } = setup();
25
+ const work = makeDirectory(root, 'Claude-Profile-Work');
26
+ const hidden = makeDirectory(root, 'CLAUDE-PROFILE-Hidden');
27
+ const running = makeDirectory(root, 'Claude-Profile-Running');
28
+ const reserved = makeDirectory(root, 'Claude-Profile-Default');
29
+ const defaultData = makeDirectory(root, 'Claude');
30
+ const outside = makeDirectory(temp, 'outside');
31
+ const link = path.join(root, 'Claude-Profile-Link');
32
+ fs.symlinkSync(outside, link, 'junction');
33
+ const logs = [];
34
+ let confirmed = false;
35
+ try {
36
+ await wipeInstances(root, {
37
+ checkRunning: async () => ({ instances: confirmed ? ['running', 'hidden'] : ['running'] }),
38
+ confirm: async ids => {
39
+ assert.deepEqual(new Set(ids), new Set(['Work', 'Hidden']));
40
+ confirmed = true;
41
+ return true;
42
+ },
43
+ log: message => logs.push(message)
44
+ });
45
+ assert.equal(fs.existsSync(work), false);
46
+ for (const dir of [hidden, running, reserved, defaultData, outside, link]) {
47
+ assert.equal(fs.existsSync(path.join(dir, 'data.txt')), true);
48
+ }
49
+ assert.ok(logs.some(message => /Skipped running instance: Running/.test(message)));
50
+ assert.ok(logs.some(message => /Skipped running instance: Hidden/.test(message)));
51
+ assert.ok(logs.some(message => /Claude-Profile-Default/.test(message)));
52
+ } finally {
53
+ fs.rmSync(temp, { recursive: true, force: true });
54
+ }
55
+ });
56
+
57
+ test('cancellation and unavailable running status never delete data', async () => {
58
+ const { temp, root } = setup();
59
+ const work = makeDirectory(root, 'Claude-Profile-Work');
60
+ try {
61
+ const logs = [];
62
+ await wipeInstances(root, {
63
+ checkRunning: async () => ({ instances: [] }),
64
+ confirm: async () => false,
65
+ log: message => logs.push(message)
66
+ });
67
+ assert.ok(fs.existsSync(work));
68
+ assert.ok(logs.some(message => /cancelled/i.test(message)));
69
+ await assert.rejects(wipeInstances(root, {
70
+ checkRunning: async () => { throw new Error('status unavailable'); },
71
+ confirm: async () => { throw new Error('should not prompt'); },
72
+ log: () => {}
73
+ }), /status unavailable/);
74
+ await assert.rejects(wipeInstances(root, {
75
+ checkRunning: async () => ({ instances: null }),
76
+ confirm: async () => { throw new Error('should not prompt'); },
77
+ log: () => {}
78
+ }), /status is unavailable/);
79
+ assert.ok(fs.existsSync(work));
80
+ } finally {
81
+ fs.rmSync(temp, { recursive: true, force: true });
82
+ }
83
+ });
84
+
85
+ test('protects Default data linked into managed directories, including links added after confirmation', async () => {
86
+ const { temp, root } = setup();
87
+ const local = path.join(temp, 'local');
88
+ const packaged = path.join(local, 'Claude-Data');
89
+ fs.mkdirSync(packaged, { recursive: true });
90
+ const legacyTarget = makeDirectory(root, 'Claude-Profile-LegacyDefault');
91
+ const packagedTarget = makeDirectory(root, 'Claude-Profile-PackagedDefault');
92
+ const lateTarget = makeDirectory(root, 'Claude-Profile-LateDefault');
93
+ fs.symlinkSync(legacyTarget, path.join(root, 'Claude'), 'junction');
94
+ fs.symlinkSync(packagedTarget, path.join(packaged, 'family'), 'junction');
95
+ const logs = [];
96
+ try {
97
+ await wipeInstances(root, {
98
+ localAppData: local,
99
+ checkRunning: async () => ({ instances: [] }),
100
+ confirm: async ids => {
101
+ assert.deepEqual(ids, ['LateDefault']);
102
+ fs.symlinkSync(lateTarget, path.join(packaged, 'new-family'), 'junction');
103
+ return true;
104
+ },
105
+ log: message => logs.push(message)
106
+ });
107
+ for (const dir of [legacyTarget, packagedTarget, lateTarget]) {
108
+ assert.ok(fs.existsSync(path.join(dir, 'data.txt')));
109
+ }
110
+ assert.equal(logs.filter(message => /Skipped instance containing Default data/.test(message)).length, 3);
111
+ } finally {
112
+ fs.rmSync(temp, { recursive: true, force: true });
113
+ }
114
+ });
115
+
116
+ test('stops and reports an error if status becomes unavailable after a partial wipe', async () => {
117
+ const { temp, root } = setup();
118
+ makeDirectory(root, 'Claude-Profile-One');
119
+ makeDirectory(root, 'Claude-Profile-Two');
120
+ let checks = 0;
121
+ const logs = [];
122
+ try {
123
+ await assert.rejects(wipeInstances(root, {
124
+ checkRunning: async () => {
125
+ if (++checks === 3) throw new Error('status unavailable');
126
+ return { instances: [] };
127
+ },
128
+ confirm: async () => true,
129
+ log: message => logs.push(message)
130
+ }), /status unavailable/);
131
+ assert.equal(logs.filter(message => message.startsWith('Deleted instance data:')).length, 1);
132
+ assert.equal(fs.readdirSync(root).length, 1);
133
+ } finally {
134
+ fs.rmSync(temp, { recursive: true, force: true });
135
+ }
136
+ });
137
+
138
+ test('refuses to delete a directory replaced after confirmation', async () => {
139
+ const { temp, root } = setup();
140
+ const work = makeDirectory(root, 'Claude-Profile-Work');
141
+ const original = path.join(root, 'backup');
142
+ try {
143
+ await assert.rejects(wipeInstances(root, {
144
+ checkRunning: async () => ({ instances: [] }),
145
+ confirm: async () => {
146
+ fs.renameSync(work, original);
147
+ makeDirectory(root, 'Claude-Profile-Work');
148
+ return true;
149
+ },
150
+ log: () => {}
151
+ }), /changed after confirmation/);
152
+ assert.ok(fs.existsSync(path.join(work, 'data.txt')));
153
+ assert.ok(fs.existsSync(path.join(original, 'data.txt')));
154
+ } finally {
155
+ fs.rmSync(temp, { recursive: true, force: true });
156
+ }
157
+ });
158
+
159
+ test('CLI refuses a wipe without an interactive terminal', { skip: process.platform !== 'win32' }, () => {
160
+ const { temp, root } = setup();
161
+ const work = makeDirectory(root, 'Claude-Profile-Work');
162
+ try {
163
+ const result = spawnSync(process.execPath, [path.join(__dirname, '..', 'cli.js'), 'wipe-instances'], {
164
+ encoding: 'utf8',
165
+ env: { ...process.env, APPDATA: root }
166
+ });
167
+ assert.equal(result.status, 1);
168
+ assert.match(result.stderr, /interactive terminal/);
169
+ assert.ok(fs.existsSync(work));
170
+ } finally {
171
+ fs.rmSync(temp, { recursive: true, force: true });
172
+ }
173
+ });
package/usage-cache.js ADDED
@@ -0,0 +1,109 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const zlib = require('zlib');
4
+
5
+ const cacheEntries = new Map();
6
+ const headerMagic = Buffer.from('305c72a71b6dfbfc', 'hex');
7
+ const zstdMagic = Buffer.from('28b52ffd', 'hex');
8
+ const cacheLifetime = 60 * 1000;
9
+ const sampleTolerance = 10 * 60 * 1000;
10
+ const fields = [
11
+ ['Five-hour', 'five_hour'],
12
+ ['Weekly all models', 'seven_day'],
13
+ ['Weekly Sonnet', 'seven_day_sonnet'],
14
+ ['Weekly Opus', 'seven_day_opus']
15
+ ];
16
+
17
+ function cacheKey(buffer) {
18
+ if (buffer.length < 24 || !buffer.subarray(0, 8).equals(headerMagic) || buffer.readUInt32LE(8) !== 5) return null;
19
+ const length = buffer.readUInt32LE(12);
20
+ if (length > 2048 || buffer.length < 24 + length) return null;
21
+ const key = buffer.subarray(24, 24 + length).toString('utf8');
22
+ const match = key.match(/(?:^|[\s]|_dk_|1\/0\/)https:\/\/claude\.ai\/api\/organizations\/([a-zA-Z0-9_-]+)\/usage(?:\?[^\s]*)?$/);
23
+ return match ? { organization: match[1], bodyOffset: 24 + length } : null;
24
+ }
25
+
26
+ async function findCachedResets(directory, sample, metrics) {
27
+ const cacheDirectory = path.join(directory, 'Cache', 'Cache_Data');
28
+ let entries;
29
+ try {
30
+ entries = await fs.promises.readdir(cacheDirectory, { withFileTypes: true });
31
+ } catch (error) {
32
+ if (error.code === 'ENOENT') return {};
33
+ throw error;
34
+ }
35
+
36
+ const files = entries.filter(entry => entry.isFile() && /^[a-f0-9]{16}_0$/.test(entry.name));
37
+ const matches = [];
38
+ let index = 0;
39
+ async function worker() {
40
+ while (index < files.length) {
41
+ const file = path.join(cacheDirectory, files[index++].name);
42
+ let handle;
43
+ try {
44
+ handle = await fs.promises.open(file, 'r');
45
+ const stat = await handle.stat();
46
+ if (stat.size > 1024 * 1024 || Math.abs(stat.mtimeMs - sample.t) > sampleTolerance) continue;
47
+ const prefix = Buffer.alloc(24);
48
+ const prefixRead = await handle.read(prefix, 0, prefix.length, 0);
49
+ if (prefixRead.bytesRead !== prefix.length || !prefix.subarray(0, 8).equals(headerMagic) ||
50
+ prefix.readUInt32LE(8) !== 5) continue;
51
+ const length = prefix.readUInt32LE(12);
52
+ if (length > 2048 || stat.size < 24 + length) continue;
53
+ const header = Buffer.alloc(24 + length);
54
+ prefix.copy(header);
55
+ const keyRead = await handle.read(header, 24, length, 24);
56
+ if (keyRead.bytesRead !== length) continue;
57
+ const key = cacheKey(header);
58
+ if (!key || key.organization !== sample.org) continue;
59
+
60
+ const data = await handle.readFile();
61
+ const afterRead = await handle.stat();
62
+ if (afterRead.mtimeMs !== stat.mtimeMs || afterRead.size !== stat.size) continue;
63
+ const currentKey = cacheKey(data);
64
+ if (!currentKey || currentKey.organization !== sample.org ||
65
+ !data.subarray(currentKey.bodyOffset, currentKey.bodyOffset + 4).equals(zstdMagic)) continue;
66
+ const body = zlib.zstdDecompressSync(data.subarray(currentKey.bodyOffset), { maxOutputLength: 1024 * 1024 });
67
+ const response = JSON.parse(body.toString('utf8'));
68
+ if (!response || typeof response !== 'object') continue;
69
+ for (const [label, field] of fields) {
70
+ const value = response[field];
71
+ if (metrics[label] === undefined || !value || value.utilization !== metrics[label] ||
72
+ typeof value.resets_at !== 'string' || !Number.isFinite(Date.parse(value.resets_at))) continue;
73
+ matches.push({ label, resetAt: value.resets_at, cachedAt: stat.mtimeMs });
74
+ }
75
+ } catch (error) {
76
+ if (error.code !== 'ENOENT') throw error;
77
+ } finally {
78
+ if (handle) await handle.close();
79
+ }
80
+ }
81
+ }
82
+ const results = await Promise.allSettled(Array.from({ length: Math.min(32, files.length) }, () => worker()));
83
+ const failed = results.find(result => result.status === 'rejected');
84
+ if (failed) throw failed.reason;
85
+ const resets = {};
86
+ for (const match of matches) {
87
+ if (!resets[match.label] || match.cachedAt > resets[match.label].cachedAt) {
88
+ resets[match.label] = { resetAt: match.resetAt, cachedAt: match.cachedAt };
89
+ }
90
+ }
91
+ return resets;
92
+ }
93
+
94
+ function getCachedResets(directory, sample, metrics) {
95
+ const identity = JSON.stringify([sample.t, sample.org, metrics]);
96
+ const current = cacheEntries.get(directory);
97
+ if (current && current.identity === identity && Date.now() - current.checkedAt < cacheLifetime) {
98
+ return current.result;
99
+ }
100
+ const entry = { identity, checkedAt: Date.now() };
101
+ entry.result = findCachedResets(directory, sample, metrics).catch(error => {
102
+ if (cacheEntries.get(directory) === entry) cacheEntries.delete(directory);
103
+ throw error;
104
+ });
105
+ cacheEntries.set(directory, entry);
106
+ return entry.result;
107
+ }
108
+
109
+ module.exports = { getCachedResets };
package/usage.js ADDED
@@ -0,0 +1,46 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { getCachedResets } = require('./usage-cache');
4
+
5
+ async function readUsageHistory(directory) {
6
+ const file = path.join(directory, 'plan-usage-history.json');
7
+ let contents;
8
+ try {
9
+ contents = await fs.promises.readFile(file, 'utf8');
10
+ } catch (error) {
11
+ if (error.code === 'ENOENT') return null;
12
+ throw error;
13
+ }
14
+
15
+ const history = JSON.parse(contents);
16
+ if (!history || ![1, 2].includes(history.version) || !Array.isArray(history.samples)) {
17
+ throw new Error('Unsupported local usage history format.');
18
+ }
19
+
20
+ let latest = null;
21
+ for (const sample of history.samples) {
22
+ if (!sample || !Number.isFinite(sample.t) || sample.t < 0 || sample.t > 8640000000000000 ||
23
+ (latest && sample.t <= latest.t)) continue;
24
+ const values = history.version === 1 ? sample : sample.u;
25
+ if (!values || typeof values !== 'object' || Array.isArray(values)) continue;
26
+ const metrics = {};
27
+ for (const [field, label] of [['fh', 'Five-hour'], ['sd', 'Weekly all models'], ['sn', 'Weekly Sonnet'], ['so', 'Weekly Opus']]) {
28
+ if (Number.isFinite(values[field]) && values[field] >= 0) metrics[label] = values[field];
29
+ }
30
+ if (Object.keys(metrics).length) latest = { t: sample.t, org: sample.org, metrics };
31
+ }
32
+ if (!latest) return null;
33
+ const result = { recordedAt: latest.t, metrics: latest.metrics };
34
+ if (history.version === 2 && typeof latest.org === 'string' && latest.org) {
35
+ try {
36
+ const resets = await getCachedResets(directory, latest, latest.metrics);
37
+ if (Object.keys(resets).length) result.resets = resets;
38
+ } catch (error) {
39
+ console.error('Could not read cached usage reset times:', error.code || error.name);
40
+ result.resetError = true;
41
+ }
42
+ }
43
+ return result;
44
+ }
45
+
46
+ module.exports = { readUsageHistory };
package/wipe.js ADDED
@@ -0,0 +1,128 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { instancePrefix, listInstanceEntries } = require('./instances');
4
+
5
+ async function directoryIdentity(directory, root) {
6
+ const stat = await fs.promises.lstat(directory, { bigint: true });
7
+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.ino === 0n || stat.dev === 0n) {
8
+ throw new Error('An instance directory cannot be verified safely.');
9
+ }
10
+ const resolved = await fs.promises.realpath(directory);
11
+ if (path.normalize(path.dirname(resolved)).toLowerCase() !== path.normalize(root).toLowerCase()) {
12
+ throw new Error('An instance directory is outside the managed data directory.');
13
+ }
14
+ return { dev: stat.dev, ino: stat.ino };
15
+ }
16
+
17
+ async function defaultDataPaths(appData, localAppData) {
18
+ const paths = [path.join(appData, 'Claude')];
19
+ if (localAppData) {
20
+ const packaged = path.join(localAppData, 'Claude-Data');
21
+ let stat;
22
+ try {
23
+ stat = await fs.promises.lstat(packaged);
24
+ } catch (error) {
25
+ if (error.code !== 'ENOENT') throw error;
26
+ }
27
+ if (stat) {
28
+ paths.push(packaged);
29
+ for (const name of await fs.promises.readdir(packaged)) paths.push(path.join(packaged, name));
30
+ }
31
+ }
32
+ const resolved = [];
33
+ for (const directory of paths) {
34
+ try {
35
+ await fs.promises.lstat(directory);
36
+ } catch (error) {
37
+ if (error.code === 'ENOENT') continue;
38
+ throw error;
39
+ }
40
+ resolved.push(await fs.promises.realpath(directory));
41
+ }
42
+ return resolved;
43
+ }
44
+
45
+ function containsPath(directory, target) {
46
+ const relative = path.relative(directory.toLowerCase(), target.toLowerCase());
47
+ return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
48
+ }
49
+
50
+ async function wipeInstances(appData, { checkRunning, confirm, log, localAppData }) {
51
+ if (typeof appData !== 'string' || !path.isAbsolute(appData)) {
52
+ throw new Error('The Windows application data directory is unavailable.');
53
+ }
54
+ if (localAppData && !path.isAbsolute(localAppData)) {
55
+ throw new Error('The Windows local application data directory is unavailable.');
56
+ }
57
+ const root = await fs.promises.realpath(appData);
58
+ const defaultPaths = await defaultDataPaths(appData, localAppData);
59
+ const entries = listInstanceEntries(appData);
60
+ const candidates = [];
61
+ for (const entry of entries) {
62
+ const id = entry.name.slice(instancePrefix.length);
63
+ if (!entry.isDirectory() || !id || id.toLowerCase() === 'default') {
64
+ log(`Skipped protected or non-directory entry: ${entry.name}`);
65
+ continue;
66
+ }
67
+ const directory = path.join(appData, entry.name);
68
+ const identity = await directoryIdentity(directory, root);
69
+ if (defaultPaths.some(target => containsPath(path.join(root, entry.name), target))) {
70
+ log(`Skipped instance containing Default data: ${id}`);
71
+ continue;
72
+ }
73
+ candidates.push({ id, directory, identity });
74
+ }
75
+
76
+ if (!candidates.length) {
77
+ log('No managed instance directories to wipe. Default was not touched.');
78
+ return;
79
+ }
80
+
81
+ async function runningIds() {
82
+ const state = await checkRunning();
83
+ if (!state || !Array.isArray(state.instances) || !state.instances.every(id => typeof id === 'string')) {
84
+ throw new Error('Running instance status is unavailable.');
85
+ }
86
+ return new Set(state.instances.map(id => id.toLowerCase()));
87
+ }
88
+
89
+ const running = await runningIds();
90
+ const stopped = candidates.filter(candidate => {
91
+ if (!running.has(candidate.id.toLowerCase())) return true;
92
+ log(`Skipped running instance: ${candidate.id}`);
93
+ return false;
94
+ });
95
+ if (!stopped.length) {
96
+ log('No stopped managed instances to wipe. Default was not touched.');
97
+ return;
98
+ }
99
+
100
+ if (await confirm(stopped.map(candidate => candidate.id)) !== true) {
101
+ log('Wipe cancelled. No instance data was deleted.');
102
+ return;
103
+ }
104
+
105
+ let deleted = 0;
106
+ for (const candidate of stopped) {
107
+ const currentRunning = await runningIds();
108
+ if (currentRunning.has(candidate.id.toLowerCase())) {
109
+ log(`Skipped running instance: ${candidate.id}`);
110
+ continue;
111
+ }
112
+ const identity = await directoryIdentity(candidate.directory, root);
113
+ if (identity.dev !== candidate.identity.dev || identity.ino !== candidate.identity.ino) {
114
+ throw new Error(`Instance "${candidate.id}" changed after confirmation; stopped without deleting it.`);
115
+ }
116
+ const currentDefaultPaths = await defaultDataPaths(appData, localAppData);
117
+ if (currentDefaultPaths.some(target => containsPath(path.join(root, path.basename(candidate.directory)), target))) {
118
+ log(`Skipped instance containing Default data: ${candidate.id}`);
119
+ continue;
120
+ }
121
+ await fs.promises.rm(candidate.directory, { recursive: true });
122
+ deleted++;
123
+ log(`Deleted instance data: ${candidate.id}`);
124
+ }
125
+ log(`Wiped ${deleted} managed instance(s). Default was not touched.`);
126
+ }
127
+
128
+ module.exports = { wipeInstances };