@foggy-projects/deepseek-harness-plugin 0.4.2-rc.5 → 0.4.5-rc.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.
Files changed (53) hide show
  1. package/README.md +224 -185
  2. package/THIRD-PARTY-RUNTIME-NOTICES.md +16 -16
  3. package/cordis.patch.yml +6 -6
  4. package/docs/COMMUNITY-MARKETPLACES.md +64 -64
  5. package/docs/PUBLIC-BETA-READINESS.md +109 -109
  6. package/docs/RELEASE-CANDIDATE-0.4.0-RC.2.md +38 -38
  7. package/docs/RELEASE-CANDIDATE-0.4.0-RC.3.md +18 -18
  8. package/docs/RELEASE-CANDIDATE-0.4.1-DSH-0.1.5-RC.1.md +60 -60
  9. package/docs/RELEASE-CANDIDATE-0.4.2-DSH-0.1.7-RC.1.md +62 -62
  10. package/docs/RELEASE-CANDIDATE-0.4.2-DSH-0.1.7-RC.2.md +50 -50
  11. package/docs/RELEASE-CANDIDATE-0.4.2-DSH-0.1.7-RC.3.md +34 -34
  12. package/docs/RELEASE-CANDIDATE-0.4.2-DSH-0.1.7-RC.4.md +32 -32
  13. package/docs/RELEASE-CANDIDATE-0.4.2-DSH-0.1.7-RC.5.md +27 -27
  14. package/docs/RELEASE-CANDIDATE-0.4.3-DSH-0.2.0-RC.1.md +96 -0
  15. package/docs/RELEASE-CANDIDATE-0.4.4-DSH-0.2.1-RC.1.md +135 -0
  16. package/docs/RELEASE-CANDIDATE-0.4.5-DSH-0.2.2-RC.1.md +45 -0
  17. package/docs/WINDOWS-BETA-ACCEPTANCE.md +113 -113
  18. package/experience/linux/README.md +53 -53
  19. package/experience/linux/prepare.sh +4 -4
  20. package/lib/atomic-json.js +41 -41
  21. package/lib/client.js +1222 -1031
  22. package/lib/component-manager.js +164 -0
  23. package/lib/component-releases.js +363 -0
  24. package/lib/diagnostics.js +86 -86
  25. package/lib/index.js +764 -698
  26. package/lib/operation-lock.js +139 -0
  27. package/lib/python-runtime.js +339 -339
  28. package/lib/query-tool.js +134 -131
  29. package/lib/remote-descriptor.js +74 -59
  30. package/lib/remote.js +8 -8
  31. package/lib/runtime-settings.js +89 -89
  32. package/lib/skill-provider.js +116 -116
  33. package/lib/typert.js +9 -9
  34. package/lib/version.js +20 -20
  35. package/lib/viewer-preview.js +50 -27
  36. package/package.json +20 -16
  37. package/skills/foggy-deepseek-onboarding/SKILL.md +149 -143
  38. package/skills/foggy-deepseek-onboarding/assets/connection.schema.json +48 -48
  39. package/skills/foggy-deepseek-onboarding/assets/datasource.example.json +14 -14
  40. package/skills/foggy-deepseek-onboarding/assets/env.example +14 -14
  41. package/skills/foggy-deepseek-onboarding/assets/onboarding-state.schema.json +71 -71
  42. package/skills/foggy-deepseek-onboarding/assets/semantic-plan.example.json +8 -8
  43. package/skills/foggy-deepseek-onboarding/assets/semantic-plan.schema.json +21 -21
  44. package/skills/foggy-deepseek-onboarding/assets/versions.json +24 -24
  45. package/skills/foggy-deepseek-onboarding/references/onboarding-workflow.md +168 -168
  46. package/skills/foggy-deepseek-onboarding/scripts/doctor.ps1 +4 -4
  47. package/skills/foggy-deepseek-onboarding/scripts/install.ps1 +4 -4
  48. package/skills/foggy-deepseek-onboarding/scripts/invoke-onboarding.ps1 +32 -32
  49. package/skills/foggy-deepseek-onboarding/scripts/onboard.ps1 +4 -4
  50. package/skills/foggy-deepseek-onboarding/scripts/onboarding.py +3721 -3697
  51. package/skills/foggy-deepseek-onboarding/scripts/runtime-start.ps1 +4 -4
  52. package/skills/foggy-deepseek-onboarding/scripts/runtime-stop.ps1 +4 -4
  53. package/skills/foggy-deepseek-onboarding/scripts/uninstall.ps1 +4 -4
@@ -1,113 +1,113 @@
1
- # Native Windows Beta acceptance
2
-
3
- This runbook validates DeepSeek Harness `0.1.7-rc.2` with Foggy plugin
4
- `0.4.2-rc.5` on a clean 64-bit Windows 10 or Windows 11 machine. Use a local
5
- directory that is not synchronized by OneDrive.
6
-
7
- ## Prerequisites
8
-
9
- Install a system Node.js `>=24.0.0` and a system Java 17+
10
- JRE/JDK. Windows must also provide `tar` (included in supported Windows 10/11
11
- versions). A system Python is neither required nor used by default.
12
-
13
- ```powershell
14
- node --version
15
- npm --version
16
- java -version
17
- tar --version
18
- ```
19
-
20
- Foggy downloads a pinned private CPython 3.12.13 runtime during initialization.
21
- It remains below `%LOCALAPPDATA%\Foggy\DeepSeekHarness`, is not added to `PATH`,
22
- and is not registered as a system Python.
23
-
24
- ## Install and start
25
-
26
- ```powershell
27
- New-Item -ItemType Directory -Force C:\FoggyAcceptance | Out-Null
28
- Set-Location C:\FoggyAcceptance
29
-
30
- npx --yes --package=@deepseek-ai/dsh@0.1.7-rc.2 --package=pnpm@11.7.0 `
31
- dsh plugin --profile web add --workspace-root `
32
- "@foggy-projects/deepseek-harness-plugin@0.4.2-rc.5"
33
-
34
- npx --yes --package=@deepseek-ai/dsh@0.1.7-rc.2 --package=pnpm@11.7.0 dsh web
35
- ```
36
-
37
- If an immediate upgrade reports
38
- `ERR_PNPM_MINIMUM_RELEASE_AGE_VIOLATION`, use the exact DSH profile directory
39
- printed by the error, run `npx --yes pnpm@11.7.0 clean --lockfile` there, and
40
- repeat the same plugin-add command. The failed add normally records the new
41
- exact package version in that profile's `minimumReleaseAgeExclude`; if the
42
- error names an older installed Beta, confirm that exact version is listed too.
43
- Do not disable the policy globally.
44
-
45
- Let DSH open the browser automatically. If it does not, copy the complete URL
46
- printed by `dsh web`, including its `?token=...` query, into the browser. A new
47
- browser session cannot use the bare `http://127.0.0.1:3080/` URL until that
48
- token has established its local authentication cookie. Treat the launch URL as
49
- temporary local access material and do not paste it into chat or diagnostics.
50
-
51
- Configure an LLM provider, select the `C:\FoggyAcceptance` workspace, then open
52
- **Settings → Built-in plugins → Foggy Data Analysis** and choose
53
- **Initialize and start**. The settings page displays the current phase and
54
- step count while initialization runs. If an existing chat was opened before
55
- selecting this workspace, create a new chat in the selected workspace: changing
56
- the default workspace does not change an existing chat's working directory.
57
- `--workspace-root` in the install command is a pnpm resolution option, not a
58
- DSH workspace selector.
59
-
60
- Before starting Runtime, confirm the configured port in **Runtime connection
61
- settings**. A fresh profile defaults to `18166`. To use another port, enter an
62
- integer from `1024` through `65535` and choose **Save port**. The value remains
63
- stable across DSH restarts and cannot be changed while Runtime is running.
64
-
65
- Expected component state:
66
-
67
- - Python 3.12.13, source `Foggy private`;
68
- - CLI 0.1.23;
69
- - Launcher 0.1.23;
70
- - analysis/query Skills 0.1.18;
71
- - onboarding Skill 0.4.2-rc.5;
72
- - Java 17+ available;
73
- - native DSH Skill registration available.
74
-
75
- Runtime startup shows its current phase, elapsed time, and the 180-second
76
- readiness deadline. Typical startup is 15–30 seconds on the validated WSL2 host
77
- and may take up to 60 seconds on Windows with cold JVM or antivirus scanning.
78
- Initialization downloads a private Python and other managed components and can
79
- take longer than Runtime startup; follow the live phase/step display.
80
- The plugin monitors the Launcher PID and fails promptly when Java exits before
81
- readiness. On failure, export diagnostics before retrying; the report includes
82
- the startup phase, PID state, evidence directory, Runtime log locations, and
83
- bounded sanitized log tails.
84
-
85
- If the configured port is occupied, startup must fail during preflight instead
86
- of waiting for the readiness deadline. The settings page displays a red bordered
87
- alert naming the port conflict and tells the user to save another port or release
88
- the conflicting application or Windows port proxy. Saving a free port and
89
- starting again must clear the applicable conflict state.
90
-
91
- ## Database and semantic-layer acceptance
92
-
93
- Use a development or test database. For this local acceptance run, connection
94
- details and a password may be supplied directly in the prompt or in a local
95
- connection JSON file. The onboarding wrapper must configure the datasource
96
- online without stopping or restarting an already-running Runtime. It must not
97
- copy the password into onboarding state, evidence, TM/QM files, or Git.
98
-
99
- Use a natural prompt such as:
100
-
101
- ```text
102
- 请帮我用 Foggy 分析这个测试数据库:地址、数据库名、账号和密码分别是
103
- <连接信息>。直接创建开发数据源并绑定一个合适的 namespace,不要重启
104
- Runtime。读取表结构后,在当前工作目录创建订单语义模型,包含订单数量、
105
- 状态和开单时间,调试到模型通过,并执行一个不超过 20 行的只读查询。
106
- ```
107
-
108
- Pass only when Runtime readiness and capabilities succeed, datasource setup
109
- does not restart Runtime, metadata can be discovered, TM/QM models validate and
110
- become effective in the local Runtime, the bounded read-only query succeeds,
111
- diagnostics contain no credentials, and stopping Runtime frees the configured
112
- port (default `18166`). Recommend Git management for the completed model files;
113
- do not treat this acceptance run as production publication.
1
+ # Native Windows Beta acceptance
2
+
3
+ This runbook validates DeepSeek Harness `0.1.7-rc.2` with Foggy plugin
4
+ `0.4.2-rc.5` on a clean 64-bit Windows 10 or Windows 11 machine. Use a local
5
+ directory that is not synchronized by OneDrive.
6
+
7
+ ## Prerequisites
8
+
9
+ Install a system Node.js `>=24.0.0` and a system Java 17+
10
+ JRE/JDK. Windows must also provide `tar` (included in supported Windows 10/11
11
+ versions). A system Python is neither required nor used by default.
12
+
13
+ ```powershell
14
+ node --version
15
+ npm --version
16
+ java -version
17
+ tar --version
18
+ ```
19
+
20
+ Foggy downloads a pinned private CPython 3.12.13 runtime during initialization.
21
+ It remains below `%LOCALAPPDATA%\Foggy\DeepSeekHarness`, is not added to `PATH`,
22
+ and is not registered as a system Python.
23
+
24
+ ## Install and start
25
+
26
+ ```powershell
27
+ New-Item -ItemType Directory -Force C:\FoggyAcceptance | Out-Null
28
+ Set-Location C:\FoggyAcceptance
29
+
30
+ npx --yes --package=@deepseek-ai/dsh@0.1.7-rc.2 --package=pnpm@11.7.0 `
31
+ dsh plugin --profile web add --workspace-root `
32
+ "@foggy-projects/deepseek-harness-plugin@0.4.2-rc.5"
33
+
34
+ npx --yes --package=@deepseek-ai/dsh@0.1.7-rc.2 --package=pnpm@11.7.0 dsh web
35
+ ```
36
+
37
+ If an immediate upgrade reports
38
+ `ERR_PNPM_MINIMUM_RELEASE_AGE_VIOLATION`, use the exact DSH profile directory
39
+ printed by the error, run `npx --yes pnpm@11.7.0 clean --lockfile` there, and
40
+ repeat the same plugin-add command. The failed add normally records the new
41
+ exact package version in that profile's `minimumReleaseAgeExclude`; if the
42
+ error names an older installed Beta, confirm that exact version is listed too.
43
+ Do not disable the policy globally.
44
+
45
+ Let DSH open the browser automatically. If it does not, copy the complete URL
46
+ printed by `dsh web`, including its `?token=...` query, into the browser. A new
47
+ browser session cannot use the bare `http://127.0.0.1:3080/` URL until that
48
+ token has established its local authentication cookie. Treat the launch URL as
49
+ temporary local access material and do not paste it into chat or diagnostics.
50
+
51
+ Configure an LLM provider, select the `C:\FoggyAcceptance` workspace, then open
52
+ **Settings → Built-in plugins → Foggy Data Analysis** and choose
53
+ **Initialize and start**. The settings page displays the current phase and
54
+ step count while initialization runs. If an existing chat was opened before
55
+ selecting this workspace, create a new chat in the selected workspace: changing
56
+ the default workspace does not change an existing chat's working directory.
57
+ `--workspace-root` in the install command is a pnpm resolution option, not a
58
+ DSH workspace selector.
59
+
60
+ Before starting Runtime, confirm the configured port in **Runtime connection
61
+ settings**. A fresh profile defaults to `18166`. To use another port, enter an
62
+ integer from `1024` through `65535` and choose **Save port**. The value remains
63
+ stable across DSH restarts and cannot be changed while Runtime is running.
64
+
65
+ Expected component state:
66
+
67
+ - Python 3.12.13, source `Foggy private`;
68
+ - CLI 0.1.23;
69
+ - Launcher 0.1.23;
70
+ - analysis/query Skills 0.1.18;
71
+ - onboarding Skill 0.4.2-rc.5;
72
+ - Java 17+ available;
73
+ - native DSH Skill registration available.
74
+
75
+ Runtime startup shows its current phase, elapsed time, and the 180-second
76
+ readiness deadline. Typical startup is 15–30 seconds on the validated WSL2 host
77
+ and may take up to 60 seconds on Windows with cold JVM or antivirus scanning.
78
+ Initialization downloads a private Python and other managed components and can
79
+ take longer than Runtime startup; follow the live phase/step display.
80
+ The plugin monitors the Launcher PID and fails promptly when Java exits before
81
+ readiness. On failure, export diagnostics before retrying; the report includes
82
+ the startup phase, PID state, evidence directory, Runtime log locations, and
83
+ bounded sanitized log tails.
84
+
85
+ If the configured port is occupied, startup must fail during preflight instead
86
+ of waiting for the readiness deadline. The settings page displays a red bordered
87
+ alert naming the port conflict and tells the user to save another port or release
88
+ the conflicting application or Windows port proxy. Saving a free port and
89
+ starting again must clear the applicable conflict state.
90
+
91
+ ## Database and semantic-layer acceptance
92
+
93
+ Use a development or test database. For this local acceptance run, connection
94
+ details and a password may be supplied directly in the prompt or in a local
95
+ connection JSON file. The onboarding wrapper must configure the datasource
96
+ online without stopping or restarting an already-running Runtime. It must not
97
+ copy the password into onboarding state, evidence, TM/QM files, or Git.
98
+
99
+ Use a natural prompt such as:
100
+
101
+ ```text
102
+ 请帮我用 Foggy 分析这个测试数据库:地址、数据库名、账号和密码分别是
103
+ <连接信息>。直接创建开发数据源并绑定一个合适的 namespace,不要重启
104
+ Runtime。读取表结构后,在当前工作目录创建订单语义模型,包含订单数量、
105
+ 状态和开单时间,调试到模型通过,并执行一个不超过 20 行的只读查询。
106
+ ```
107
+
108
+ Pass only when Runtime readiness and capabilities succeed, datasource setup
109
+ does not restart Runtime, metadata can be discovered, TM/QM models validate and
110
+ become effective in the local Runtime, the bounded read-only query succeeds,
111
+ diagnostics contain no credentials, and stopping Runtime frees the configured
112
+ port (default `18166`). Recommend Git management for the completed model files;
113
+ do not treat this acceptance run as production publication.
@@ -1,53 +1,53 @@
1
- # Linux and WSL2 experience
2
-
3
- This entry prepares a clean, user-owned DeepSeek Harness web profile with the public Foggy Bundle.
4
- It has been designed for Ubuntu 22.04/24.04 x86_64 and WSL2.
5
-
6
- ## Prerequisites
7
-
8
- - Node.js `>=24.0.0` (the DSH 0.1.7-rc.2 compatibility candidate)
9
- - Java 17 or newer
10
- - Git, npm, and `tar`
11
- - At least 4 GiB free disk space and 2 GiB available memory; 4 GiB memory is recommended
12
-
13
- Keep the experience root on the Linux-native filesystem, such as under `$HOME`. In WSL2, do not
14
- put DSH, `node_modules`, Foggy's private Python environment, or Foggy data under `/mnt/c` or `/mnt/d`.
15
-
16
- ## Prepare
17
-
18
- ```bash
19
- git clone https://github.com/foggy-projects/foggy-deepseek-harness-plugin.git
20
- cd foggy-deepseek-harness-plugin
21
- bash experience/linux/prepare.sh --dry-run
22
- bash experience/linux/prepare.sh
23
- ```
24
-
25
- The script installs pinned pnpm and DeepSeek Harness 0.1.7-rc.2 inside
26
- `~/.local/share/foggy-deepseek-harness-experience`, clones and packs the public Foggy Bundle, and
27
- adds it to a clean DSH web profile. It does not use `sudo`, install operating-system packages, write
28
- model credentials, initialize Foggy components, or start the web process.
29
-
30
- Start the prepared profile with:
31
-
32
- ```bash
33
- ~/.local/share/foggy-deepseek-harness-experience/run.sh
34
- ```
35
-
36
- Open the URL printed by DSH, then choose **Settings → Built-in plugins → Foggy Data Analysis** and select
37
- **Initialize and start**. Private Python, the CLI, Launcher, and analysis Skill are downloaded from their
38
- pinned public Releases and verified before installation. A system Python is not required.
39
-
40
- Provider configuration remains a separate DSH setup step. Store API keys in a private environment
41
- file or secret manager; do not add them to the DSH settings document or the project repository.
42
-
43
- ## Custom roots
44
-
45
- ```bash
46
- bash experience/linux/prepare.sh \
47
- --experience-root "$HOME/.local/share/my-foggy-experience" \
48
- --project-root "$HOME/my-foggy-workspace"
49
- ```
50
-
51
- The script refuses a non-empty experience root. This prevents an existing profile from being
52
- silently overwritten. Remove an abandoned test root yourself after confirming that it contains no
53
- data you need, or choose a new root.
1
+ # Linux and WSL2 experience
2
+
3
+ This entry prepares a clean, user-owned DeepSeek Harness web profile with the public Foggy Bundle.
4
+ It has been designed for Ubuntu 22.04/24.04 x86_64 and WSL2.
5
+
6
+ ## Prerequisites
7
+
8
+ - Node.js `>=24.9.0` (the DSH 0.2.2-rc.3 compatibility candidate)
9
+ - Java 17 or newer
10
+ - Git, npm, and `tar`
11
+ - At least 4 GiB free disk space and 2 GiB available memory; 4 GiB memory is recommended
12
+
13
+ Keep the experience root on the Linux-native filesystem, such as under `$HOME`. In WSL2, do not
14
+ put DSH, `node_modules`, Foggy's private Python environment, or Foggy data under `/mnt/c` or `/mnt/d`.
15
+
16
+ ## Prepare
17
+
18
+ ```bash
19
+ git clone https://github.com/foggy-projects/foggy-deepseek-harness-plugin.git
20
+ cd foggy-deepseek-harness-plugin
21
+ bash experience/linux/prepare.sh --dry-run
22
+ bash experience/linux/prepare.sh
23
+ ```
24
+
25
+ The script installs pinned pnpm and DeepSeek Harness 0.2.2-rc.3 inside
26
+ `~/.local/share/foggy-deepseek-harness-experience`, clones and packs the public Foggy Bundle, and
27
+ adds it to a clean DSH web profile. It does not use `sudo`, install operating-system packages, write
28
+ model credentials, initialize Foggy components, or start the web process.
29
+
30
+ Start the prepared profile with:
31
+
32
+ ```bash
33
+ ~/.local/share/foggy-deepseek-harness-experience/run.sh
34
+ ```
35
+
36
+ Open the URL printed by DSH, then choose **Settings → Built-in plugins → Foggy Data Analysis** and select
37
+ **Initialize and start**. Private Python, the CLI, Launcher, and analysis Skill are downloaded from their
38
+ pinned public Releases and verified before installation. A system Python is not required.
39
+
40
+ Provider configuration remains a separate DSH setup step. Store API keys in a private environment
41
+ file or secret manager; do not add them to the DSH settings document or the project repository.
42
+
43
+ ## Custom roots
44
+
45
+ ```bash
46
+ bash experience/linux/prepare.sh \
47
+ --experience-root "$HOME/.local/share/my-foggy-experience" \
48
+ --project-root "$HOME/my-foggy-workspace"
49
+ ```
50
+
51
+ The script refuses a non-empty experience root. This prevents an existing profile from being
52
+ silently overwritten. Remove an abandoned test root yourself after confirming that it contains no
53
+ data you need, or choose a new root.
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env bash
2
2
  set -euo pipefail
3
3
 
4
- DSH_VERSION="0.1.7-rc.2"
4
+ DSH_VERSION="0.2.2-rc.3"
5
5
  PNPM_VERSION="11.7.0"
6
- PLUGIN_VERSION="0.4.2-rc.5"
6
+ PLUGIN_VERSION="0.4.5-rc.1"
7
7
  PLUGIN_REF="v${PLUGIN_VERSION}"
8
8
  PLUGIN_REPOSITORY="https://github.com/foggy-projects/foggy-deepseek-harness-plugin.git"
9
9
 
@@ -73,8 +73,8 @@ require_command git
73
73
  require_command df
74
74
  require_command tar
75
75
 
76
- node -e 'const [major] = process.versions.node.split(".").map(Number); if (major < 24) process.exit(1)' \
77
- || fail "Node >=24 required for DeepSeek Harness ${DSH_VERSION}; detected $(node --version 2>/dev/null || echo unknown)"
76
+ node -e 'const [major, minor] = process.versions.node.split(".").map(Number); if (major < 24 || (major === 24 && minor < 9)) process.exit(1)' \
77
+ || fail "Node >=24.9 required for DeepSeek Harness ${DSH_VERSION}; detected $(node --version 2>/dev/null || echo unknown)"
78
78
 
79
79
  java_major="$(java -version 2>&1 | awk -F'[\".]' '/version/ { print $2; exit }')"
80
80
  [[ "$java_major" =~ ^[0-9]+$ ]] || fail "could not detect Java version"
@@ -1,41 +1,41 @@
1
- import { randomUUID } from 'node:crypto'
2
- import { mkdir, rename, rm, writeFile } from 'node:fs/promises'
3
- import { dirname } from 'node:path'
4
-
5
- const TRANSIENT_REPLACE_CODES = new Set(['EACCES', 'EBUSY', 'EPERM'])
6
- const TRANSIENT_WINERRORS = new Set([5, 32, 33])
7
-
8
- function wait(milliseconds) {
9
- return new Promise((resolve) => setTimeout(resolve, milliseconds))
10
- }
11
-
12
- function transientReplaceError(error) {
13
- return TRANSIENT_REPLACE_CODES.has(error?.code) || TRANSIENT_WINERRORS.has(error?.winerror)
14
- }
15
-
16
- export async function replaceWithRetry(source, destination, {
17
- replace = rename,
18
- sleep = wait,
19
- attempts = 12,
20
- } = {}) {
21
- for (let attempt = 0; attempt < attempts; attempt += 1) {
22
- try {
23
- await replace(source, destination)
24
- return
25
- } catch (error) {
26
- if (!transientReplaceError(error) || attempt === attempts - 1) throw error
27
- await sleep(Math.min(25 * (2 ** attempt), 400))
28
- }
29
- }
30
- }
31
-
32
- export async function writeJsonAtomic(path, payload, options = {}) {
33
- await mkdir(dirname(path), { recursive: true })
34
- const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`
35
- try {
36
- await writeFile(temporary, `${JSON.stringify(payload, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
37
- await replaceWithRetry(temporary, path, options)
38
- } finally {
39
- await rm(temporary, { force: true })
40
- }
41
- }
1
+ import { randomUUID } from 'node:crypto'
2
+ import { mkdir, rename, rm, writeFile } from 'node:fs/promises'
3
+ import { dirname } from 'node:path'
4
+
5
+ const TRANSIENT_REPLACE_CODES = new Set(['EACCES', 'EBUSY', 'EPERM'])
6
+ const TRANSIENT_WINERRORS = new Set([5, 32, 33])
7
+
8
+ function wait(milliseconds) {
9
+ return new Promise((resolve) => setTimeout(resolve, milliseconds))
10
+ }
11
+
12
+ function transientReplaceError(error) {
13
+ return TRANSIENT_REPLACE_CODES.has(error?.code) || TRANSIENT_WINERRORS.has(error?.winerror)
14
+ }
15
+
16
+ export async function replaceWithRetry(source, destination, {
17
+ replace = rename,
18
+ sleep = wait,
19
+ attempts = 12,
20
+ } = {}) {
21
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
22
+ try {
23
+ await replace(source, destination)
24
+ return
25
+ } catch (error) {
26
+ if (!transientReplaceError(error) || attempt === attempts - 1) throw error
27
+ await sleep(Math.min(25 * (2 ** attempt), 400))
28
+ }
29
+ }
30
+ }
31
+
32
+ export async function writeJsonAtomic(path, payload, options = {}) {
33
+ await mkdir(dirname(path), { recursive: true })
34
+ const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`
35
+ try {
36
+ await writeFile(temporary, `${JSON.stringify(payload, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
37
+ await replaceWithRetry(temporary, path, options)
38
+ } finally {
39
+ await rm(temporary, { force: true })
40
+ }
41
+ }