claude-dev-env 8.118.1 → 8.119.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.
@@ -18,12 +18,23 @@ export const SHIM_DOCSTRING = (
18
18
  const RENAME_RETRY_DELAYS_MS = Object.freeze([50, 100, 200]);
19
19
 
20
20
 
21
- function renameSyncWithWindowsRetry(sourcePath, destinationPath) {
21
+ /**
22
+ * Rename a file, retrying while Windows reports the destination as busy.
23
+ *
24
+ * A scanner or reader that holds the file open makes a Windows rename fail
25
+ * with EPERM or EBUSY for a moment. Each retry waits a little longer, and the
26
+ * last busy error is thrown once the waits run out.
27
+ *
28
+ * @param {string} sourcePath The file to move.
29
+ * @param {string} destinationPath The path it replaces.
30
+ * @returns {void}
31
+ */
32
+ export function renameSyncRetryingWhileBusy(sourcePath, destinationPath) {
22
33
  let lastError;
23
34
  for (const delayMs of [0, ...RENAME_RETRY_DELAYS_MS]) {
24
35
  if (delayMs > 0) {
25
36
  const deadline = Date.now() + delayMs;
26
- while (Date.now() < deadline) { /* spin */ }
37
+ while (Date.now() < deadline) { }
27
38
  }
28
39
  try {
29
40
  renameSync(sourcePath, destinationPath);
@@ -35,6 +46,19 @@ function renameSyncWithWindowsRetry(sourcePath, destinationPath) {
35
46
  lastError = renameError;
36
47
  }
37
48
  }
49
+ throw lastError;
50
+ }
51
+
52
+
53
+ function renameSyncWithWindowsRetry(sourcePath, destinationPath) {
54
+ try {
55
+ renameSyncRetryingWhileBusy(sourcePath, destinationPath);
56
+ return;
57
+ } catch (renameError) {
58
+ if (renameError.code !== 'EPERM' && renameError.code !== 'EBUSY') {
59
+ throw renameError;
60
+ }
61
+ }
38
62
  try {
39
63
  renameSync(sourcePath, destinationPath);
40
64
  return;
@@ -10,6 +10,7 @@ import {
10
10
  writeAllGitHookShims,
11
11
  configureGlobalGitHooksPath,
12
12
  KNOWN_GIT_HOOK_NAMES,
13
+ renameSyncRetryingWhileBusy,
13
14
  } from './git_hooks_installer.mjs';
14
15
 
15
16
 
@@ -375,3 +376,38 @@ test('generated advisory shim preserves KeyboardInterrupt cancellation', () => {
375
376
  assert.notEqual(shimResult.status, 0);
376
377
  assert.match(shimResult.stderr, /KeyboardInterrupt/);
377
378
  });
379
+
380
+
381
+ test('renameSyncRetryingWhileBusy should move the file over the destination', () => {
382
+ const { temporaryRoot, gitHooksDirectory } = makeTemporaryGitHooksDirectory();
383
+ try {
384
+ const sourcePath = join(gitHooksDirectory, 'next.tmp');
385
+ const destinationPath = join(gitHooksDirectory, 'current');
386
+ writeFileSync(sourcePath, 'next');
387
+ writeFileSync(destinationPath, 'prior');
388
+
389
+ renameSyncRetryingWhileBusy(sourcePath, destinationPath);
390
+
391
+ assert.equal(readFileSync(destinationPath, 'utf8'), 'next');
392
+ assert.equal(existsSync(sourcePath), false);
393
+ } finally {
394
+ rmSync(temporaryRoot, { recursive: true, force: true });
395
+ }
396
+ });
397
+
398
+
399
+ test('renameSyncRetryingWhileBusy should throw a missing source error without retrying it away', () => {
400
+ const { temporaryRoot, gitHooksDirectory } = makeTemporaryGitHooksDirectory();
401
+ try {
402
+ const destinationPath = join(gitHooksDirectory, 'current');
403
+ writeFileSync(destinationPath, 'prior');
404
+
405
+ assert.throws(
406
+ () => renameSyncRetryingWhileBusy(join(gitHooksDirectory, 'missing.tmp'), destinationPath),
407
+ (error) => error.code === 'ENOENT',
408
+ );
409
+ assert.equal(readFileSync(destinationPath, 'utf8'), 'prior');
410
+ } finally {
411
+ rmSync(temporaryRoot, { recursive: true, force: true });
412
+ }
413
+ });
@@ -20,6 +20,7 @@ import {
20
20
  lstatSync,
21
21
  mkdirSync,
22
22
  mkdtempSync,
23
+ readFileSync,
23
24
  readdirSync,
24
25
  readlinkSync,
25
26
  rmdirSync,
@@ -31,6 +32,7 @@ import {
31
32
  import { dirname, join } from 'node:path';
32
33
  import { execFileSync } from 'node:child_process';
33
34
  import { ADDITIONAL_SETTINGS_BLOB_PREFIX } from './install-constants.mjs';
35
+ import { writeFileAtomically } from './write-file-atomically.mjs';
34
36
 
35
37
  /** Env var that forces a throw after a named mutation phase (tests only). */
36
38
  export const INSTALL_FAULT_ENV = 'CLAUDE_DEV_ENV_INSTALL_FAULT';
@@ -341,7 +343,7 @@ export function restorePriorInstallSnapshot(snapshot, options = {}) {
341
343
  for (const eachSnapshot of settingsSnapshots) {
342
344
  if (eachSnapshot.existed) {
343
345
  mkdir(dirname(eachSnapshot.path), { recursive: true });
344
- copyFile(join(snapshot.journalRoot, eachSnapshot.blobName), eachSnapshot.path);
346
+ writeFileAtomically(eachSnapshot.path, readFileSync(join(snapshot.journalRoot, eachSnapshot.blobName)));
345
347
  } else if (exists(eachSnapshot.path)) {
346
348
  try {
347
349
  unlink(eachSnapshot.path);
package/bin/install.mjs CHANGED
@@ -153,6 +153,7 @@ import {
153
153
  unparsedSettingsMayHoldGate,
154
154
  } from './profile-stop-gate.mjs';
155
155
  import { pythonExecutableProbeCommand, pythonVersionMeetsFloor } from './python-probe.mjs';
156
+ import { writeFileAtomically } from './write-file-atomically.mjs';
156
157
 
157
158
  const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
158
159
  const INSTALL_ROOT_RESOLUTION = resolveInstallRoot({
@@ -523,7 +524,9 @@ function seedSubagentModelPolicy() {
523
524
  * Cursor. The pstack plugin now carries the SessionStart context the companion
524
525
  * supplied, so a registration left behind points every session at a deleted
525
526
  * script. Every install clears all three hosts; an uninstall passes the two the
526
- * settings block does not already own.
527
+ * settings block does not already own. An empty or blank configuration file
528
+ * holds no registration, so it is left as it is, the way the settings loader
529
+ * reads an empty settings.json as an empty object.
527
530
  *
528
531
  * @param {string[]} [hosts] The hosts to clear. Defaults to all three.
529
532
  * @returns {string[]} The host configuration paths this run changed.
@@ -535,10 +538,11 @@ function removeRetiredSessionContinuityHooks(hosts = ['claude', 'codex', 'cursor
535
538
  const configurationPath = configurationPaths[host];
536
539
  if (!existsSync(configurationPath)) continue;
537
540
  const configurationText = readFileSync(configurationPath, 'utf8');
541
+ if (!configurationText.trim()) continue;
538
542
  const configuration = JSON.parse(configurationText);
539
543
  if (removeContinuityHooks(configuration) === 0) continue;
540
544
  const indent = hostConfigurationIndent(configurationText);
541
- writeFileSync(configurationPath, JSON.stringify(configuration, null, indent) + '\n');
545
+ writeFileAtomically(configurationPath, JSON.stringify(configuration, null, indent) + '\n');
542
546
  changedPaths.push(configurationPath);
543
547
  console.log(` Session continuity: retired hook registrations removed from ${configurationPath}`);
544
548
  }
@@ -2097,7 +2101,7 @@ export function pruneRetiredHookEntriesFromSettings(
2097
2101
  );
2098
2102
  if (removedCount === 0) return 0;
2099
2103
  const settingsIndent = hostConfigurationIndent(settingsText);
2100
- writeFileSync(settingsPath, JSON.stringify(settings, null, settingsIndent) + '\n');
2104
+ writeFileAtomically(settingsPath, JSON.stringify(settings, null, settingsIndent) + '\n');
2101
2105
  return removedCount;
2102
2106
  }
2103
2107
 
@@ -2345,7 +2349,7 @@ function mergeHooksAtPath(
2345
2349
  const groupCount = mergeHooksIntoSettings(
2346
2350
  settings, hooksConfig, pluginRootDir, pythonCommand, realPathOrNull(settingsPath),
2347
2351
  );
2348
- writeFileSync(settingsPath, JSON.stringify(settings, null, indentation) + '\n');
2352
+ writeFileAtomically(settingsPath, JSON.stringify(settings, null, indentation) + '\n');
2349
2353
  return groupCount;
2350
2354
  }
2351
2355
 
@@ -2512,7 +2516,7 @@ function mergeManagedPermissions() {
2512
2516
  || mergeOutcome.addedCount > 0
2513
2517
  || (!settingsExisted && hasCurrentManagedPermissions);
2514
2518
  if (shouldWriteSettings) {
2515
- writeFileSync(settingsPath, JSON.stringify(settings, null, 4) + '\n');
2519
+ writeFileAtomically(settingsPath, JSON.stringify(settings, null, 4) + '\n');
2516
2520
  }
2517
2521
  return { ...mergeOutcome, removedCount: pruneOutcome.removedCount };
2518
2522
  }
@@ -2532,7 +2536,7 @@ function mergePackageSettingsDefaults() {
2532
2536
  const settings = loadClaudeSettingsObject(settingsPath);
2533
2537
  const mergeOutcome = mergeMissingSettingsDefaults(settings, settingsDefaults);
2534
2538
  if (mergeOutcome.addedKeys.length > 0) {
2535
- writeFileSync(settingsPath, JSON.stringify(settings, null, 4) + '\n');
2539
+ writeFileAtomically(settingsPath, JSON.stringify(settings, null, 4) + '\n');
2536
2540
  }
2537
2541
  return mergeOutcome;
2538
2542
  }
@@ -3649,7 +3653,7 @@ function pruneManagedHooksFromHostConfiguration(settingsPath, defaultIndentation
3649
3653
  managedPackageSourceRoots(),
3650
3654
  );
3651
3655
  pruneManagedHooksFromSettings(settings, managedHookRelativePaths);
3652
- writeFileSync(
3656
+ writeFileAtomically(
3653
3657
  settingsPath,
3654
3658
  JSON.stringify(settings, null, hostConfigurationIndent(settingsText) || defaultIndentation) + '\n',
3655
3659
  );
@@ -3725,7 +3729,7 @@ function executeUninstallPlan(plan, helpers = {}) {
3725
3729
  }
3726
3730
  }
3727
3731
  if (didSettingsChange) {
3728
- writeFileSync(plan.settingsPath, JSON.stringify(settings, null, 4) + '\n');
3732
+ writeFileAtomically(plan.settingsPath, JSON.stringify(settings, null, 4) + '\n');
3729
3733
  }
3730
3734
  }
3731
3735
  for (const eachChangedPath of removeOpenTasksGateFromProfiles({
@@ -2514,6 +2514,70 @@ test('pruneRetiredHookEntriesFromSettings leaves settings.json byte-identical wh
2514
2514
  });
2515
2515
 
2516
2516
 
2517
+ const FILE_SIZE_LIMIT_COMMAND = 'prlimit';
2518
+ const isFileSizeLimitAvailable = spawnSync(FILE_SIZE_LIMIT_COMMAND, ['--version']).status === 0;
2519
+
2520
+
2521
+ test(
2522
+ 'a settings.json write that fails part way through leaves the prior settings.json whole',
2523
+ { skip: isFileSizeLimitAvailable ? false : `${FILE_SIZE_LIMIT_COMMAND} is not on PATH` },
2524
+ () => {
2525
+ const settings = settingsRegisteringRetiredAndUserHooks(RETIRED_HOOK_RELATIVE_PATH);
2526
+ settings.userNotes = 'n'.repeat(8192);
2527
+ const { settingsPath, sandboxRoot } = createSettingsFixture(settings, 4);
2528
+ const pruneScriptPath = join(sandboxRoot, 'prune-under-limit.mjs');
2529
+ writeFileSync(pruneScriptPath, [
2530
+ `import { ownedHookRootComparisonKeys, pruneRetiredHookEntriesFromSettings } from ${JSON.stringify(new URL('./install.mjs', import.meta.url).href)};`,
2531
+ `const sandboxRoot = ${JSON.stringify(sandboxRoot)};`,
2532
+ `pruneRetiredHookEntriesFromSettings(${JSON.stringify(settingsPath)}, new Set([${JSON.stringify(RETIRED_HOOK_RELATIVE_PATH)}]), {`,
2533
+ ` allOwnedHookRootKeys: ownedHookRootComparisonKeys([${JSON.stringify(join(sandboxRoot, '.claude', 'hooks'))}]),`,
2534
+ ' homeDirectory: sandboxRoot,',
2535
+ '});',
2536
+ ].join('\n'));
2537
+ try {
2538
+ const settingsTextBefore = readFileSync(settingsPath, 'utf8');
2539
+ const fileSizeLimitBytes = Math.floor(settingsTextBefore.length / 2);
2540
+
2541
+ const limitedRun = spawnSync(
2542
+ FILE_SIZE_LIMIT_COMMAND,
2543
+ [`--fsize=${fileSizeLimitBytes}`, process.execPath, pruneScriptPath],
2544
+ { encoding: 'utf8', env: { ...process.env, HOME: sandboxRoot, USERPROFILE: sandboxRoot } },
2545
+ );
2546
+
2547
+ assert.notEqual(limitedRun.status, 0, 'the write past the file size limit fails the run');
2548
+ assert.match(limitedRun.stderr, /EFBIG/, 'the run fails on the file size limit');
2549
+ const settingsTextAfter = readFileSync(settingsPath, 'utf8');
2550
+ assert.equal(
2551
+ settingsTextAfter,
2552
+ settingsTextBefore,
2553
+ `expected settings.json to keep its prior ${settingsTextBefore.length} bytes after the failed write, found ${settingsTextAfter.length} bytes`,
2554
+ );
2555
+ assert.deepEqual(
2556
+ readdirSync(sandboxRoot).sort(),
2557
+ ['prune-under-limit.mjs', 'settings.json'],
2558
+ 'the failed write leaves no temporary file beside settings.json',
2559
+ );
2560
+
2561
+ const unlimitedRun = spawnSync(process.execPath, [pruneScriptPath], {
2562
+ encoding: 'utf8',
2563
+ env: { ...process.env, HOME: sandboxRoot, USERPROFILE: sandboxRoot },
2564
+ });
2565
+
2566
+ assert.equal(unlimitedRun.status, 0, unlimitedRun.stderr);
2567
+ const prunedSettings = JSON.parse(readFileSync(settingsPath, 'utf8'));
2568
+ assert.deepEqual(
2569
+ prunedSettings.hooks.PreToolUse[0].hooks.map(hook => hook.command),
2570
+ ['python3 my_own_gate.py --user-authored'],
2571
+ 'the next write completes and drops the retired entry',
2572
+ );
2573
+ assert.equal(prunedSettings.userNotes, settings.userNotes, 'the user key survives whole');
2574
+ } finally {
2575
+ rmSync(sandboxRoot, { recursive: true, force: true });
2576
+ }
2577
+ },
2578
+ );
2579
+
2580
+
2517
2581
  const ALL_HOST_CONFIGURATION_INDENT_WIDTHS = [2, 4];
2518
2582
 
2519
2583
 
@@ -3789,6 +3853,31 @@ test('a full install clears a retired session-continuity registration from every
3789
3853
  }
3790
3854
  });
3791
3855
 
3856
+ test('should install over an empty settings.json and leave a settings object', t => {
3857
+ const sandbox = pstackPluginSandbox(t);
3858
+ const settingsPath = join(sandbox.homeDirectory, '.claude', 'settings.json');
3859
+ mkdirSync(dirname(settingsPath), { recursive: true });
3860
+ writeFileSync(settingsPath, '');
3861
+
3862
+ runPstackInstaller(sandbox.homeDirectory, [], sandbox.environment);
3863
+
3864
+ const settings = JSON.parse(readFileSync(settingsPath, 'utf8'));
3865
+ assert.equal(typeof settings.hooks, 'object');
3866
+ });
3867
+
3868
+ test('should refuse a settings.json that holds malformed JSON and leave it unchanged', t => {
3869
+ const sandbox = pstackPluginSandbox(t);
3870
+ const settingsPath = join(sandbox.homeDirectory, '.claude', 'settings.json');
3871
+ mkdirSync(dirname(settingsPath), { recursive: true });
3872
+ writeFileSync(settingsPath, '{ "hooks": ');
3873
+
3874
+ assert.throws(
3875
+ () => runPstackInstaller(sandbox.homeDirectory, [], sandbox.environment),
3876
+ error => error.status === 1,
3877
+ );
3878
+ assert.equal(readFileSync(settingsPath, 'utf8'), '{ "hooks": ');
3879
+ });
3880
+
3792
3881
  function installWithGlobalPrefix(context, globalPrefix) {
3793
3882
  const homeDirectory = mkdtempSync(join(tmpdir(), 'cde-action-needed-'));
3794
3883
  context.after(() => rmSync(homeDirectory, { recursive: true, force: true }));
@@ -12,6 +12,7 @@ import {
12
12
  readFileSync,
13
13
  realpathSync,
14
14
  rmSync,
15
+ symlinkSync,
15
16
  writeFileSync,
16
17
  } from 'node:fs';
17
18
  import { tmpdir } from 'node:os';
@@ -143,6 +144,39 @@ test('capture and restore recover settings, manifest, files, and hooksPath', ()
143
144
  rmSync(box.root, { recursive: true, force: true });
144
145
  });
145
146
 
147
+ test(
148
+ 'restore should write the prior settings through a linked settings.json and keep the link',
149
+ { skip: process.platform === 'win32' ? 'creating a file link on Windows needs a privilege the runner may lack' : false },
150
+ () => {
151
+ const box = sandbox();
152
+ const gitConfigPath = join(box.root, '.gitconfig');
153
+ writeFileSync(gitConfigPath, '');
154
+ const io = { env: { ...process.env, HOME: box.root, USERPROFILE: box.root, GIT_CONFIG_GLOBAL: gitConfigPath }, execFileSync };
155
+ const sharedSettingsPath = join(box.root, 'shared', 'settings.json');
156
+ writeFileWithParents(sharedSettingsPath, '{"prior":true}\n');
157
+ symlinkSync(sharedSettingsPath, box.settingsPath);
158
+ try {
159
+ const snapshot = capturePriorInstallSnapshot({
160
+ managedRoot: box.managedRoot,
161
+ manifestFilePath: box.manifestFilePath,
162
+ settingsPath: box.settingsPath,
163
+ priorManifestFiles: [],
164
+ journalParentDirectory: box.journalParent,
165
+ io,
166
+ });
167
+ writeFileSync(sharedSettingsPath, '{"hooks":{"broken":true}}\n');
168
+
169
+ restorePriorInstallSnapshot(snapshot, { allWrittenPaths: [box.settingsPath], io });
170
+
171
+ assert.equal(lstatSync(box.settingsPath).isSymbolicLink(), true, 'settings.json is still a link');
172
+ assert.equal(readFileSync(sharedSettingsPath, 'utf8'), '{"prior":true}\n');
173
+ discardInstallTransactionJournal(snapshot);
174
+ } finally {
175
+ rmSync(box.root, { recursive: true, force: true });
176
+ }
177
+ },
178
+ );
179
+
146
180
  test('capture and restore recover an additional host settings file', () => {
147
181
  const box = sandbox();
148
182
  const gitConfigPath = join(box.root, '.gitconfig');
@@ -15,7 +15,7 @@
15
15
  * every profile on this machine without writing anything.
16
16
  */
17
17
 
18
- import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
18
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync } from 'node:fs';
19
19
  import { homedir } from 'node:os';
20
20
  import { dirname, join, resolve } from 'node:path';
21
21
  import { fileURLToPath } from 'node:url';
@@ -28,6 +28,7 @@ import {
28
28
  normalizePathForComparison,
29
29
  } from './resolve-install-root.mjs';
30
30
  import { resolveProfilesRootDirectory } from './select-install-targets.mjs';
31
+ import { writeFileAtomically } from './write-file-atomically.mjs';
31
32
 
32
33
  export const DRY_RUN_FLAG = '--dry-run';
33
34
  export const RETIRED_SESSION_TITLE_GATE_FILE_NAME = 'session_title_status_gate.py';
@@ -195,7 +196,7 @@ export function mergeProfileSettingsFile(settingsPath, options) {
195
196
  copyFileSync(settingsPath, backupPath);
196
197
  }
197
198
  mkdirSync(dirname(settingsPath), { recursive: true });
198
- writeFileSync(
199
+ writeFileAtomically(
199
200
  settingsPath,
200
201
  JSON.stringify(settings, null, hostConfigurationIndent(settingsText, DEFAULT_SETTINGS_INDENT)) + '\n',
201
202
  );
@@ -1,6 +1,6 @@
1
1
  import { test } from 'node:test';
2
2
  import { strict as assert } from 'node:assert';
3
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
3
+ import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, symlinkSync, writeFileSync } from 'node:fs';
4
4
  import { tmpdir } from 'node:os';
5
5
  import { join, resolve } from 'node:path';
6
6
 
@@ -73,6 +73,30 @@ test('a missing settings.json is created with every declared entry and no Stop h
73
73
  assert.deepEqual(outcome.gate.removedPaths, []);
74
74
  });
75
75
 
76
+ test('a linked profile settings.json keeps its link and the shared file gets every declared entry', (context) => {
77
+ const homeDirectory = makeHome();
78
+ const claudeDirectory = join(homeDirectory, '.claude');
79
+ mkdirSync(claudeDirectory);
80
+ const sharedSettingsPath = join(homeDirectory, 'shared', 'settings.json');
81
+ writeSettings(sharedSettingsPath, { outputStyle: 'plain' });
82
+ const linkedPath = join(claudeDirectory, 'settings.json');
83
+ try {
84
+ symlinkSync(sharedSettingsPath, linkedPath, 'file');
85
+ } catch (error) {
86
+ if (error.code === 'EPERM') return context.skip('this account cannot create symlinks');
87
+ throw error;
88
+ }
89
+
90
+ mergeProfileSettings([linkedPath], { dryRun: false, homeDirectory, now: FIXED_NOW });
91
+
92
+ assert.equal(lstatSync(linkedPath).isSymbolicLink(), true, 'the profile entry is still a link');
93
+ assert.deepEqual(readSettings(sharedSettingsPath), {
94
+ outputStyle: 'plain',
95
+ permissions: { allow: PERMISSION_ALLOW_ITEMS },
96
+ autoMode: { allow: AUTO_MODE_ALLOW_ITEMS },
97
+ });
98
+ });
99
+
76
100
  test('the retired profile gate leaves settings.json and ~/.claude, and another Stop hook stays', () => {
77
101
  const homeDirectory = makeHome();
78
102
  const claudeDirectory = join(homeDirectory, '.claude');
@@ -8,6 +8,7 @@ import {
8
8
  mergeProfileSettingsFile,
9
9
  } from './merge_profile_settings.mjs';
10
10
  import { normalizePathForComparison } from './resolve-install-root.mjs';
11
+ import { writeFileAtomically } from './write-file-atomically.mjs';
11
12
 
12
13
  const STOP_EVENT_NAME = 'Stop';
13
14
  const MANAGED_HOOKS_DIRECTORY_NAME = 'hooks';
@@ -235,7 +236,7 @@ export function removeOpenTasksGateFromProfiles(options) {
235
236
  );
236
237
  if (settings.hooks[STOP_EVENT_NAME].length === 0) delete settings.hooks[STOP_EVENT_NAME];
237
238
  if (Object.keys(settings.hooks).length === 0) delete settings.hooks;
238
- writeFileSync(eachPath, JSON.stringify(settings, null, hostConfigurationIndent(settingsText, SETTINGS_INDENT)) + '\n');
239
+ writeFileAtomically(eachPath, JSON.stringify(settings, null, hostConfigurationIndent(settingsText, SETTINGS_INDENT)) + '\n');
239
240
  allChangedPaths.push(eachPath);
240
241
  }
241
242
  return allChangedPaths;
@@ -1,6 +1,6 @@
1
1
  import { test } from 'node:test';
2
2
  import { strict as assert } from 'node:assert';
3
- import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
3
+ import { lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
4
4
  import { tmpdir } from 'node:os';
5
5
  import { join } from 'node:path';
6
6
 
@@ -68,6 +68,31 @@ test('a profile whose settings.json links to the main settings is left out', (co
68
68
  assert.deepEqual(otherProfileSettingsPaths({ homeDirectory, environment: {}, mainSettingsPath }), []);
69
69
  });
70
70
 
71
+ test('removal through a linked profile settings.json updates the shared file and keeps the link', (context) => {
72
+ const { homeDirectory, claudeHome, gateCommand } = makeHome(context);
73
+ const sharedSettingsPath = join(homeDirectory, 'shared', 'settings.json');
74
+ mkdirSync(join(homeDirectory, 'shared'));
75
+ writeFileSync(sharedSettingsPath, JSON.stringify({
76
+ hooks: { Stop: [{ hooks: [
77
+ { type: 'command', command: 'python3 /opt/own/stop.py' },
78
+ { type: 'command', command: gateCommand },
79
+ ] }] },
80
+ }, null, 4));
81
+ const linkedPath = writeProfile(homeDirectory, 'linked');
82
+ try {
83
+ symlinkSync(sharedSettingsPath, linkedPath, 'file');
84
+ } catch (error) {
85
+ if (error.code === 'EPERM') return context.skip('this account cannot create symlinks');
86
+ throw error;
87
+ }
88
+
89
+ const allChangedPaths = removeOpenTasksGateFromProfiles({ claudeHome, allProfileSettingsPaths: [linkedPath] });
90
+
91
+ assert.deepEqual(allChangedPaths, [linkedPath]);
92
+ assert.equal(lstatSync(linkedPath).isSymbolicLink(), true, 'the profile entry is still a link');
93
+ assert.deepEqual(stopCommands(sharedSettingsPath), ['python3 /opt/own/stop.py']);
94
+ });
95
+
71
96
  test('a second run adds nothing, and an older interpreter spelling is replaced', (context) => {
72
97
  const { homeDirectory, claudeHome, mainSettingsPath, gateCommand } = makeHome(context);
73
98
  const staleCommand = gateCommand.replace(/^python3/, '/usr/bin/python3.9');
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Replace a file's contents so a kill at any point leaves a whole file.
3
+ *
4
+ * The new contents go to a temporary file beside the target, and a rename
5
+ * moves that file over the target. A run that stops before the rename leaves
6
+ * the prior file as it was; a run that stops after it leaves the new file.
7
+ * A write that throws removes its temporary file before the error goes on.
8
+ * Each write first removes this target's stale temporary files, the ones a
9
+ * killed writer left behind.
10
+ *
11
+ * A target that is a symbolic link keeps the link: the write lands on the
12
+ * file the link resolves to. A target that already exists keeps its mode.
13
+ *
14
+ * ::
15
+ *
16
+ * writeFileAtomically(settingsPath, JSON.stringify(settings, null, 4) + '\n')
17
+ */
18
+
19
+ import { randomBytes } from 'node:crypto';
20
+ import { chmodSync, lstatSync, readdirSync, readlinkSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
21
+ import { basename, dirname, join, resolve } from 'node:path';
22
+
23
+ import { renameSyncRetryingWhileBusy } from './git_hooks_installer.mjs';
24
+
25
+ const TEMPORARY_NAME_RANDOM_BYTE_COUNT = 6;
26
+ const PERMISSION_BITS_MASK = 0o7777;
27
+ const STALE_TEMPORARY_FILE_AGE_MS = 10 * 60 * 1000;
28
+ const REGULAR_EXPRESSION_SPECIAL_CHARACTERS = /[.*+?^${}()|[\]\\]/g;
29
+ const MAXIMUM_LINK_COUNT = 40;
30
+
31
+
32
+ /**
33
+ * Say whether a process with this id runs on this machine now.
34
+ *
35
+ * @param {number} processId The process id a temporary file name carries.
36
+ * @returns {boolean} True when the process exists, or exists and belongs to another user.
37
+ */
38
+ function processIsRunning(processId) {
39
+ try {
40
+ process.kill(processId, 0);
41
+ return true;
42
+ } catch (probeError) {
43
+ return probeError.code === 'EPERM';
44
+ }
45
+ }
46
+
47
+
48
+ /**
49
+ * Remove temporary files that a killed write of this target left behind.
50
+ *
51
+ * A temporary file is stale when its name carries a process id that no
52
+ * longer runs and it is older than ten minutes::
53
+ *
54
+ * .settings.json.4242.a1b2c3d4e5f6.tmp process 4242 gone, an hour old -> removed
55
+ * .settings.json.4242.a1b2c3d4e5f6.tmp process 4242 gone, a minute old -> kept
56
+ * .settings.json.5151.a1b2c3d4e5f6.tmp process 5151 runs -> kept
57
+ *
58
+ * A file that cannot be read or removed stays.
59
+ *
60
+ * @param {string} writeTargetPath The file the write lands on.
61
+ * @returns {void}
62
+ */
63
+ function removeStaleTemporaryFiles(writeTargetPath) {
64
+ const targetDirectory = dirname(writeTargetPath);
65
+ const escapedName = basename(writeTargetPath).replace(REGULAR_EXPRESSION_SPECIAL_CHARACTERS, '\\$&');
66
+ const temporaryNamePattern = new RegExp(`^\\.${escapedName}\\.(\\d+)\\.[0-9a-f]+\\.tmp$`);
67
+ let allEntryNames;
68
+ try {
69
+ allEntryNames = readdirSync(targetDirectory);
70
+ } catch {
71
+ return;
72
+ }
73
+ for (const eachName of allEntryNames) {
74
+ const nameMatch = temporaryNamePattern.exec(eachName);
75
+ if (!nameMatch) {
76
+ continue;
77
+ }
78
+ const writerProcessId = Number(nameMatch[1]);
79
+ if (writerProcessId === process.pid || processIsRunning(writerProcessId)) {
80
+ continue;
81
+ }
82
+ const temporaryPath = join(targetDirectory, eachName);
83
+ try {
84
+ if (Date.now() - statSync(temporaryPath).mtimeMs > STALE_TEMPORARY_FILE_AGE_MS) {
85
+ rmSync(temporaryPath, { force: true });
86
+ }
87
+ } catch {
88
+ continue;
89
+ }
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Resolve the file a write to this path lands on.
95
+ *
96
+ * A chain of links is followed to its last entry, which may not exist yet::
97
+ *
98
+ * profile/settings.json -> dotfiles/settings.json -> store/settings.json (missing)
99
+ * -> store/settings.json
100
+ *
101
+ * @param {string} targetPath The path the caller names.
102
+ * @returns {string} The path itself, or the file its chain of links ends at.
103
+ * @throws {Error} With code ELOOP when the chain is longer than the link limit.
104
+ */
105
+ function resolveWriteTargetPath(targetPath) {
106
+ if (!lstatSync(targetPath, { throwIfNoEntry: false })?.isSymbolicLink()) {
107
+ return targetPath;
108
+ }
109
+ try {
110
+ return realpathSync(targetPath);
111
+ } catch {
112
+ let currentPath = targetPath;
113
+ for (let linkCount = 0; linkCount < MAXIMUM_LINK_COUNT; linkCount += 1) {
114
+ if (!lstatSync(currentPath, { throwIfNoEntry: false })?.isSymbolicLink()) {
115
+ return currentPath;
116
+ }
117
+ currentPath = resolve(dirname(currentPath), readlinkSync(currentPath));
118
+ }
119
+ throw Object.assign(new Error(`ELOOP: too many links to resolve '${targetPath}'`), { code: 'ELOOP' });
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Write contents to a path through a temporary file and a rename.
125
+ *
126
+ * @param {string} targetPath The file to create or replace.
127
+ * @param {string | Uint8Array} contents The complete new contents.
128
+ * @returns {void}
129
+ */
130
+ export function writeFileAtomically(targetPath, contents) {
131
+ const writeTargetPath = resolveWriteTargetPath(targetPath);
132
+ removeStaleTemporaryFiles(writeTargetPath);
133
+ const priorStats = statSync(writeTargetPath, { throwIfNoEntry: false });
134
+ const temporaryPath = join(
135
+ dirname(writeTargetPath),
136
+ `.${basename(writeTargetPath)}.${process.pid}.${randomBytes(TEMPORARY_NAME_RANDOM_BYTE_COUNT).toString('hex')}.tmp`,
137
+ );
138
+ try {
139
+ writeFileSync(temporaryPath, contents, { flag: 'wx' });
140
+ if (priorStats) {
141
+ chmodSync(temporaryPath, priorStats.mode & PERMISSION_BITS_MASK);
142
+ }
143
+ renameSyncRetryingWhileBusy(temporaryPath, writeTargetPath);
144
+ } catch (writeError) {
145
+ rmSync(temporaryPath, { force: true });
146
+ throw writeError;
147
+ }
148
+ }