afyx-engineering-kit 0.0.0-stage → 0.1.0-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/.afyx-source-revision +1 -0
  2. package/LICENSE +21 -0
  3. package/README.md +377 -2
  4. package/SECURITY.md +74 -0
  5. package/afyx-context/LICENSE +21 -0
  6. package/afyx-context/README.md +155 -0
  7. package/afyx-context/afyx-context.json +30 -0
  8. package/afyx-context/contracts/integration-v1.schema.json +34 -0
  9. package/afyx-context/package-lock.json +53 -0
  10. package/afyx-context/package.json +34 -0
  11. package/afyx-context/scripts/benchmark.mjs +39 -0
  12. package/afyx-context/scripts/build.mjs +15 -0
  13. package/afyx-context/scripts/comparative-benchmark.mjs +342 -0
  14. package/afyx-context/scripts/comparative-worker.mjs +74 -0
  15. package/afyx-context/scripts/graph-integration-e2e.mjs +188 -0
  16. package/afyx-context/scripts/integrated-dogfood.mjs +309 -0
  17. package/afyx-context/src/budget.js +166 -0
  18. package/afyx-context/src/cli.js +110 -0
  19. package/afyx-context/src/coordination.js +343 -0
  20. package/afyx-context/src/engine.js +198 -0
  21. package/afyx-context/src/errors.js +14 -0
  22. package/afyx-context/src/graph-integration-worker.js +70 -0
  23. package/afyx-context/src/graph-integration.js +373 -0
  24. package/afyx-context/src/graph-mcp-bridge.js +103 -0
  25. package/afyx-context/src/index.js +25 -0
  26. package/afyx-context/src/integrations.js +87 -0
  27. package/afyx-context/src/memory.js +255 -0
  28. package/afyx-context/src/storage.js +364 -0
  29. package/afyx-context/test-fixtures/coordination-worker.mjs +52 -0
  30. package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/__init__.py +1 -0
  31. package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/__manifest__.py +4 -0
  32. package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/models/__init__.py +1 -0
  33. package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/models/sale_order.py +5 -0
  34. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/__init__.py +1 -0
  35. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/__manifest__.py +10 -0
  36. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/models/__init__.py +2 -0
  37. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/models/sale_order.py +20 -0
  38. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/models/sale_order_audit.py +11 -0
  39. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/security/ir.model.access.csv +2 -0
  40. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/views/sale_order_views.xml +14 -0
  41. package/afyx-forge/LICENSE +55 -0
  42. package/afyx-forge/README.md +126 -0
  43. package/afyx-forge/afyx-forge.json +28 -0
  44. package/afyx-forge/bin/afyx-forge +4 -0
  45. package/afyx-forge/bin/afyx-forge.cmd +3 -0
  46. package/afyx-forge/bin/afyx-forge.js +16 -0
  47. package/afyx-forge/contracts/forge-plan-v1.schema.json +172 -0
  48. package/afyx-forge/package.json +26 -0
  49. package/afyx-forge/src/classifier.js +190 -0
  50. package/afyx-forge/src/cli.js +111 -0
  51. package/afyx-forge/src/doctor.js +105 -0
  52. package/afyx-forge/src/guidance.js +120 -0
  53. package/afyx-forge/src/index.js +273 -0
  54. package/afyx-forge/src/planning.js +107 -0
  55. package/afyx-forge/src/policy.js +109 -0
  56. package/afyx-forge/src/workflow-refiner.js +151 -0
  57. package/afyx-graph/afyx-graph.json +20 -0
  58. package/afyx-graph/engine/LICENSE +21 -0
  59. package/afyx-graph/engine/README.md +104 -0
  60. package/afyx-graph/engine/release/RELEASE-MANIFEST.json +21 -0
  61. package/afyx-graph/engine/release/SHA256SUMS +2 -0
  62. package/afyx-graph/engine/release/afyx-graph-linux-x64.tar.gz +0 -0
  63. package/afyx-graph/engine/release/afyx-graph-win32-x64.zip +0 -0
  64. package/afyx-graph/engine/scripts/distribution-contract.mjs +212 -0
  65. package/afyx-graph/engine/scripts/distribution-product.json +33 -0
  66. package/bin/afyx-engineering-kit.mjs +61 -0
  67. package/install.ps1 +1053 -0
  68. package/install.sh +617 -0
  69. package/package.json +66 -4
  70. package/scripts/afyx-capability-orchestrator.mjs +752 -0
  71. package/scripts/afyx-claude-integration.mjs +547 -0
  72. package/scripts/afyx-context-artifact.mjs +105 -0
  73. package/scripts/afyx-credential-broker.mjs +75 -0
  74. package/scripts/afyx-doctor.ps1 +152 -0
  75. package/scripts/afyx-doctor.sh +146 -0
  76. package/scripts/afyx-forge-artifact.mjs +183 -0
  77. package/scripts/afyx-global-routing-policy.md +12 -0
  78. package/scripts/afyx-global-routing.mjs +168 -0
  79. package/scripts/afyx-graph-artifact.mjs +178 -0
  80. package/scripts/afyx-host-adapters.mjs +543 -0
  81. package/scripts/afyx-host-bridge-lifecycle.mjs +174 -0
  82. package/scripts/afyx-host-bridge.mjs +288 -0
  83. package/scripts/afyx-integration-contracts.mjs +825 -0
  84. package/scripts/afyx-mcp-integration.mjs +528 -0
  85. package/scripts/afyx-modular-integration.mjs +361 -0
  86. package/scripts/afyx-modular-runtime.mjs +451 -0
  87. package/scripts/afyx-native-skill-host.mjs +124 -0
  88. package/scripts/afyx-npm-installer.mjs +486 -0
  89. package/scripts/afyx-project.ps1 +205 -0
  90. package/scripts/afyx-project.sh +207 -0
  91. package/scripts/afyx-provider-backup.mjs +1206 -0
  92. package/scripts/afyx-provider-integration.mjs +724 -0
  93. package/scripts/afyx-provider-inventory.mjs +147 -0
  94. package/scripts/afyx-security-auditor.mjs +224 -0
  95. package/scripts/afyx-skill-engineering.mjs +354 -0
  96. package/scripts/afyx-tool-family-routing.mjs +64 -0
  97. package/scripts/afyx-universal-runtime.mjs +530 -0
  98. package/scripts/alpha_acceptance_preflight.py +240 -0
  99. package/scripts/benchmark-graph-memory.mjs +96 -0
  100. package/scripts/benchmark_capability_orchestrator.mjs +64 -0
  101. package/scripts/build-windows-installer.ps1 +259 -0
  102. package/scripts/build_forge_synthetic_image.py +328 -0
  103. package/scripts/check-reference-staleness.py +71 -0
  104. package/scripts/components.json +254 -0
  105. package/scripts/contracts/afyx-capability-request-v1.schema.json +189 -0
  106. package/scripts/contracts/afyx-capability-result-v1.schema.json +32 -0
  107. package/scripts/dogfood_engineering_comparison.mjs +303 -0
  108. package/scripts/engineering-assurance.json +28 -0
  109. package/scripts/install-afyx-context.ps1 +142 -0
  110. package/scripts/install-afyx-context.sh +126 -0
  111. package/scripts/install-afyx-forge.ps1 +265 -0
  112. package/scripts/install-afyx-forge.sh +273 -0
  113. package/scripts/install-afyx-graph.ps1 +571 -0
  114. package/scripts/install-afyx-graph.sh +438 -0
  115. package/scripts/install-codex-usage-tracker.ps1 +172 -0
  116. package/scripts/lib/AfyxComponents.psm1 +399 -0
  117. package/scripts/lib/AfyxSkillLifecycle.psm1 +289 -0
  118. package/scripts/lib/AfyxTerminal.psm1 +838 -0
  119. package/scripts/lib/afyx-components.sh +256 -0
  120. package/scripts/lib/afyx-skill-lifecycle.sh +271 -0
  121. package/scripts/link-global-dev.ps1 +193 -0
  122. package/scripts/link-global-dev.sh +130 -0
  123. package/scripts/phase8-paired-evidence.mjs +195 -0
  124. package/scripts/phase8-representative-workload.mjs +771 -0
  125. package/scripts/phase8-session-recorder.mjs +157 -0
  126. package/scripts/phase8_event_ledger.py +248 -0
  127. package/scripts/phase8_evidence_discovery.py +189 -0
  128. package/scripts/prepare-g6-package.mjs +349 -0
  129. package/scripts/resolve-git-release-artifacts.mjs +321 -0
  130. package/scripts/stage-npm-release.mjs +94 -0
  131. package/scripts/validate-afyx-graph.py +203 -0
  132. package/scripts/validate-components.py +194 -0
  133. package/scripts/validate-engineering-assurance.py +281 -0
  134. package/scripts/verify-graph-archive.mjs +64 -0
  135. package/skills/afyx-context/SKILL.md +26 -0
  136. package/skills/afyx-engineering-expert/README.md +42 -0
  137. package/skills/afyx-engineering-expert/SKILL.md +70 -0
  138. package/skills/afyx-engineering-expert/assets/result-template.md +15 -0
  139. package/skills/afyx-engineering-expert/references/ai-ml-engineer.md +17 -0
  140. package/skills/afyx-engineering-expert/references/business-analyst.md +17 -0
  141. package/skills/afyx-engineering-expert/references/clean-code-engineer.md +26 -0
  142. package/skills/afyx-engineering-expert/references/code-reviewer.md +24 -0
  143. package/skills/afyx-engineering-expert/references/cybersecurity-devsecops.md +17 -0
  144. package/skills/afyx-engineering-expert/references/data-analyst-bi.md +24 -0
  145. package/skills/afyx-engineering-expert/references/data-engineer.md +24 -0
  146. package/skills/afyx-engineering-expert/references/database-administrator.md +17 -0
  147. package/skills/afyx-engineering-expert/references/debugging-specialist.md +24 -0
  148. package/skills/afyx-engineering-expert/references/embedded-iot-engineer.md +24 -0
  149. package/skills/afyx-engineering-expert/references/erp-technical-specialist.md +17 -0
  150. package/skills/afyx-engineering-expert/references/hardware-diagnostics-auditor.md +24 -0
  151. package/skills/afyx-engineering-expert/references/hardware-electronics-engineer.md +24 -0
  152. package/skills/afyx-engineering-expert/references/integration-engineer.md +24 -0
  153. package/skills/afyx-engineering-expert/references/legacy-modernization-engineer.md +24 -0
  154. package/skills/afyx-engineering-expert/references/llmops-prompt-engineer.md +24 -0
  155. package/skills/afyx-engineering-expert/references/network-engineer.md +24 -0
  156. package/skills/afyx-engineering-expert/references/performance-benchmark-engineer.md +24 -0
  157. package/skills/afyx-engineering-expert/references/platform-engineer.md +24 -0
  158. package/skills/afyx-engineering-expert/references/product-manager.md +17 -0
  159. package/skills/afyx-engineering-expert/references/qa-engineer.md +17 -0
  160. package/skills/afyx-engineering-expert/references/site-reliability-engineer.md +17 -0
  161. package/skills/afyx-engineering-expert/references/software-engineer.md +17 -0
  162. package/skills/afyx-engineering-expert/references/solutions-architect.md +17 -0
  163. package/skills/afyx-engineering-expert/references/specialists-index.md +33 -0
  164. package/skills/afyx-engineering-expert/references/subject-matter-expert.md +17 -0
  165. package/skills/afyx-engineering-expert/references/system-analyst.md +17 -0
  166. package/skills/afyx-engineering-expert/references/technical-project-manager.md +24 -0
  167. package/skills/afyx-engineering-expert/references/technical-writer.md +24 -0
  168. package/skills/afyx-engineering-expert/references/ui-ux-designer.md +17 -0
  169. package/skills/afyx-engineering-expert/workflows/ai-data-erp.md +20 -0
  170. package/skills/afyx-engineering-expert/workflows/debugging.md +10 -0
  171. package/skills/afyx-engineering-expert/workflows/discovery-design.md +11 -0
  172. package/skills/afyx-engineering-expert/workflows/implementation.md +12 -0
  173. package/skills/afyx-engineering-expert/workflows/incident-reliability.md +12 -0
  174. package/skills/afyx-engineering-expert/workflows/review-audit.md +13 -0
  175. package/skills/afyx-forge/SKILL.md +43 -0
  176. package/skills/afyx-forge/references/adaptive-policy.md +19 -0
  177. package/skills/efficient-coding/SKILL.md +33 -0
  178. package/skills/efficient-coding/references/investigation.md +27 -0
  179. package/skills/efficient-coding/references/token-efficiency.md +25 -0
  180. package/skills/efficient-coding/references/tool-routing.md +13 -0
  181. package/skills/odoo-engineering/SKILL.md +33 -0
  182. package/skills/odoo-engineering/references/common.md +9 -0
  183. package/skills/odoo-engineering/references/odoo-10.md +32 -0
  184. package/skills/odoo-engineering/references/odoo-11.md +26 -0
  185. package/skills/odoo-engineering/references/odoo-12.md +31 -0
  186. package/skills/odoo-engineering/references/odoo-13.md +27 -0
  187. package/skills/odoo-engineering/references/odoo-14.md +31 -0
  188. package/skills/odoo-engineering/references/odoo-15.md +34 -0
  189. package/skills/odoo-engineering/references/odoo-16.md +37 -0
  190. package/skills/odoo-engineering/references/odoo-17.md +37 -0
  191. package/skills/odoo-engineering/references/odoo-18.md +48 -0
  192. package/skills/odoo-engineering/references/odoo-19.md +43 -0
  193. package/skills/odoo-engineering/references/odoo-20.md +39 -0
  194. package/skills/odoo-engineering/references/reference-schema.md +16 -0
  195. package/skills/odoo-engineering/references/version-detection.md +13 -0
  196. package/tools/codex-usage/CodexUsage.psm1 +496 -0
  197. package/tools/codex-usage/codex-usage-doctor.ps1 +150 -0
  198. package/tools/codex-usage/codex-usage-pricing.json +25 -0
  199. package/tools/codex-usage/codex-usage-stop.ps1 +167 -0
  200. package/tools/codex-usage/codex-usage-watch.ps1 +250 -0
  201. package/tools/codex-usage/vscode-user-task.json +31 -0
  202. package/tools/windows-setup/SetupBootstrapper.cs +258 -0
  203. package/uninstall.ps1 +189 -0
  204. package/uninstall.sh +167 -0
  205. package/update.ps1 +95 -0
  206. package/update.sh +67 -0
  207. package/verify.ps1 +411 -0
  208. package/verify.sh +265 -0
@@ -0,0 +1,1206 @@
1
+ /**
2
+ * Universal Provider Configuration Management & Backup Contract
3
+ *
4
+ * Principle: "Native Integration First. Backup Before Modification. Validate After Changes. Restore When Needed."
5
+ */
6
+
7
+ import {
8
+ chmodSync,
9
+ copyFileSync,
10
+ existsSync,
11
+ mkdirSync,
12
+ readdirSync,
13
+ readFileSync,
14
+ rmSync,
15
+ statSync,
16
+ writeFileSync,
17
+ } from 'node:fs';
18
+ import { basename, dirname, join, resolve } from 'node:path';
19
+ import { createHash, randomBytes } from 'node:crypto';
20
+ import { homedir } from 'node:os';
21
+
22
+ export const PROVIDER_BACKUP_SCHEMA_VERSION = 1;
23
+ export const DEFAULT_BACKUP_RETENTION_LIMIT = 20;
24
+
25
+ /**
26
+ * Returns the canonical root directory for Afyx backups outside the source repository.
27
+ */
28
+ export function getProviderBackupRoot(overrideRoot = '') {
29
+ if (overrideRoot) return resolve(overrideRoot);
30
+ if (process.env.AFYX_BACKUP_ROOT) return resolve(process.env.AFYX_BACKUP_ROOT);
31
+ const home = process.env.USERPROFILE || process.env.HOME || homedir();
32
+ return join(home, '.afyx', 'backups');
33
+ }
34
+
35
+ /**
36
+ * Calculates SHA-256 hex digest for a given Buffer or string.
37
+ */
38
+ export function sha256(data) {
39
+ if (data === null || data === undefined) return null;
40
+ return createHash('sha256').update(data).digest('hex');
41
+ }
42
+
43
+ /**
44
+ * Reads file bytes safely; returns null if file does not exist.
45
+ */
46
+ export function readFileBytes(filePath) {
47
+ if (!filePath || !existsSync(filePath)) return null;
48
+ return readFileSync(filePath);
49
+ }
50
+
51
+ /**
52
+ * Compares two byte buffers for exact equality.
53
+ */
54
+ export function byteEquals(a, b) {
55
+ if (a === null || b === null) return a === b;
56
+ return Buffer.isBuffer(a) && Buffer.isBuffer(b) ? a.equals(b) : a === b;
57
+ }
58
+
59
+ /**
60
+ * Applies retention limit to provider backups, keeping the newest N backups.
61
+ */
62
+ export function enforceBackupRetention(providerDir, limit = DEFAULT_BACKUP_RETENTION_LIMIT) {
63
+ if (!existsSync(providerDir)) return;
64
+ const max = Number.isSafeInteger(limit) && limit > 0 ? limit : DEFAULT_BACKUP_RETENTION_LIMIT;
65
+
66
+ const entries = readdirSync(providerDir, { withFileTypes: true })
67
+ .filter((e) => e.isFile() && e.name.endsWith('.meta.json'))
68
+ .map((e) => {
69
+ const metaPath = join(providerDir, e.name);
70
+ try {
71
+ const meta = JSON.parse(readFileSync(metaPath, 'utf8'));
72
+ const mtime = statSync(metaPath).mtimeMs;
73
+ return {
74
+ metaName: e.name,
75
+ metaPath,
76
+ backupPath: metaPath.slice(0, -'.meta.json'.length),
77
+ timestamp: meta.timestamp ? new Date(meta.timestamp).getTime() : mtime,
78
+ };
79
+ } catch {
80
+ return null;
81
+ }
82
+ })
83
+ .filter(Boolean)
84
+ .sort((a, b) => b.timestamp - a.timestamp); // Newest first
85
+
86
+ if (entries.length > max) {
87
+ const toRemove = entries.slice(max);
88
+ for (const item of toRemove) {
89
+ try {
90
+ if (existsSync(item.backupPath)) rmSync(item.backupPath, { force: true });
91
+ if (existsSync(item.metaPath)) rmSync(item.metaPath, { force: true });
92
+ } catch {
93
+ // Best-effort cleanup
94
+ }
95
+ }
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Creates an immutable, recoverable configuration backup before modification.
101
+ *
102
+ * @param {Object} params
103
+ * @param {string} params.provider - Provider identifier ('codex', 'antigravity', 'claude', etc.)
104
+ * @param {string} params.configPath - Absolute path to the configuration file
105
+ * @param {string} [params.operation='modify'] - Operation description ('mcp-register', 'mcp-remove', etc.)
106
+ * @param {string} [params.backupRoot=''] - Optional custom backup root directory
107
+ * @param {number} [params.retentionLimit=20] - Retention limit for backups
108
+ * @returns {Object} Backup handle
109
+ */
110
+ export function createConfigurationBackup({
111
+ provider,
112
+ configPath,
113
+ operation = 'modify',
114
+ backupRoot = '',
115
+ retentionLimit = DEFAULT_BACKUP_RETENTION_LIMIT,
116
+ }) {
117
+ if (!provider || typeof provider !== 'string') throw new Error('Provider identifier is required');
118
+ if (!configPath || typeof configPath !== 'string') throw new Error('Configuration path is required');
119
+
120
+ const absoluteConfig = resolve(configPath);
121
+ const existed = existsSync(absoluteConfig);
122
+ const originalBytes = existed ? readFileSync(absoluteConfig) : null;
123
+ const originalSha256 = existed ? sha256(originalBytes) : null;
124
+ let originalMode = null;
125
+
126
+ if (existed) {
127
+ try {
128
+ originalMode = statSync(absoluteConfig).mode;
129
+ } catch {
130
+ originalMode = null;
131
+ }
132
+ }
133
+
134
+ const root = getProviderBackupRoot(backupRoot);
135
+ const providerDir = join(root, 'provider-config', provider);
136
+ mkdirSync(providerDir, { recursive: true });
137
+
138
+ const now = new Date();
139
+ const timestampStr = now.toISOString().replace(/[:.]/g, '-');
140
+ const nonce = randomBytes(4).toString('hex');
141
+ const backupFileName = `${basename(absoluteConfig)}.${timestampStr}-${nonce}.bak`;
142
+ const backupPath = join(providerDir, backupFileName);
143
+ const metaPath = `${backupPath}.meta.json`;
144
+
145
+ if (existed && originalBytes !== null) {
146
+ writeFileSync(backupPath, originalBytes);
147
+ if (originalMode !== null) {
148
+ try {
149
+ chmodSync(backupPath, originalMode);
150
+ } catch {
151
+ // Platform permission fallback
152
+ }
153
+ }
154
+ // Verify backup integrity immediately
155
+ const verifyBytes = readFileSync(backupPath);
156
+ if (sha256(verifyBytes) !== originalSha256) {
157
+ rmSync(backupPath, { force: true });
158
+ throw new Error(`Backup integrity verification failed for ${absoluteConfig}`);
159
+ }
160
+ }
161
+
162
+ const metadata = {
163
+ schemaVersion: PROVIDER_BACKUP_SCHEMA_VERSION,
164
+ provider,
165
+ configPath: absoluteConfig,
166
+ operation,
167
+ timestamp: now.toISOString(),
168
+ existed,
169
+ sha256: originalSha256,
170
+ size: originalBytes ? originalBytes.length : 0,
171
+ backupFile: existed ? backupFileName : null,
172
+ };
173
+
174
+ writeFileSync(metaPath, JSON.stringify(metadata, null, 2), 'utf8');
175
+
176
+ // Enforce retention limit
177
+ enforceBackupRetention(providerDir, retentionLimit);
178
+
179
+ return {
180
+ provider,
181
+ configPath: absoluteConfig,
182
+ backupPath: existed ? backupPath : null,
183
+ metaPath,
184
+ existed,
185
+ originalSha256,
186
+ originalBytes,
187
+ lastKnownSha256: originalSha256,
188
+ lastKnownBytes: originalBytes,
189
+ operation,
190
+ };
191
+ }
192
+
193
+ /**
194
+ * Updates the last-known byte state on the backup handle after an intentional Afyx step.
195
+ */
196
+ export function updateKnownState(backupHandle, currentBytes = null) {
197
+ if (!backupHandle) return;
198
+ if (currentBytes !== null) {
199
+ backupHandle.lastKnownBytes = currentBytes;
200
+ backupHandle.lastKnownSha256 = sha256(currentBytes);
201
+ } else if (existsSync(backupHandle.configPath)) {
202
+ const bytes = readFileSync(backupHandle.configPath);
203
+ backupHandle.lastKnownBytes = bytes;
204
+ backupHandle.lastKnownSha256 = sha256(bytes);
205
+ } else {
206
+ backupHandle.lastKnownBytes = null;
207
+ backupHandle.lastKnownSha256 = null;
208
+ }
209
+ }
210
+
211
+ /**
212
+ * Attempts a safe rollback to the original configuration state.
213
+ * Refuses rollback and reports conflict if concurrent modifications occurred.
214
+ *
215
+ * @param {Object} backupHandle - Handle created by createConfigurationBackup
216
+ * @param {Object} [options]
217
+ * @param {string} [options.reason=''] - Diagnostic reason for rollback
218
+ * @param {boolean} [options.force=false] - Force rollback even if concurrent edits detected
219
+ * @returns {Object} Rollback result
220
+ */
221
+ export function rollbackConfiguration(backupHandle, { reason = '', force = false } = {}) {
222
+ if (!backupHandle || !backupHandle.configPath) {
223
+ return { restored: false, error: 'INVALID_BACKUP_HANDLE' };
224
+ }
225
+
226
+ const currentBytes = readFileBytes(backupHandle.configPath);
227
+ const currentSha = sha256(currentBytes);
228
+
229
+ // Check for concurrent modification:
230
+ // If target changed to something other than our last-known state or original state
231
+ const isConcurrentlyModified = currentSha !== null
232
+ && currentSha !== backupHandle.lastKnownSha256
233
+ && currentSha !== backupHandle.originalSha256;
234
+
235
+ if (isConcurrentlyModified && !force) {
236
+ // Preserve concurrent file as conflict evidence
237
+ const conflictNonce = randomBytes(3).toString('hex');
238
+ const conflictPath = `${backupHandle.configPath}.conflict-${Date.now()}-${conflictNonce}`;
239
+ try {
240
+ if (currentBytes !== null) writeFileSync(conflictPath, currentBytes);
241
+ } catch {
242
+ // Best-effort
243
+ }
244
+ return {
245
+ restored: false,
246
+ conflict: true,
247
+ conflictPath,
248
+ reason: `CONCURRENT_MODIFICATION_DETECTED: Target configuration changed externally during operation; original backup preserved at ${backupHandle.backupPath || 'none'}`,
249
+ };
250
+ }
251
+
252
+ try {
253
+ if (!backupHandle.existed) {
254
+ if (existsSync(backupHandle.configPath)) {
255
+ rmSync(backupHandle.configPath, { force: true });
256
+ }
257
+ } else {
258
+ if (backupHandle.backupPath && existsSync(backupHandle.backupPath)) {
259
+ mkdirSync(dirname(backupHandle.configPath), { recursive: true });
260
+ copyFileSync(backupHandle.backupPath, backupHandle.configPath);
261
+ } else if (backupHandle.originalBytes !== null) {
262
+ mkdirSync(dirname(backupHandle.configPath), { recursive: true });
263
+ writeFileSync(backupHandle.configPath, backupHandle.originalBytes);
264
+ } else {
265
+ return { restored: false, error: 'BACKUP_DATA_MISSING' };
266
+ }
267
+
268
+ // Verify restored content
269
+ const restoredBytes = readFileBytes(backupHandle.configPath);
270
+ if (sha256(restoredBytes) !== backupHandle.originalSha256) {
271
+ return { restored: false, error: 'RESTORE_VERIFICATION_FAILED' };
272
+ }
273
+ }
274
+
275
+ return {
276
+ restored: true,
277
+ conflict: false,
278
+ verified: true,
279
+ reason,
280
+ };
281
+ } catch (err) {
282
+ return {
283
+ restored: false,
284
+ conflict: false,
285
+ error: err instanceof Error ? err.message : String(err),
286
+ };
287
+ }
288
+ }
289
+
290
+ /**
291
+ * Restores configuration from a specific backup file and verifies integrity.
292
+ */
293
+ export function restoreFromBackup(backupPath, targetPath) {
294
+ if (!existsSync(backupPath)) throw new Error(`Backup file does not exist: ${backupPath}`);
295
+ const metaPath = `${backupPath}.meta.json`;
296
+ let expectedSha256 = null;
297
+
298
+ if (existsSync(metaPath)) {
299
+ try {
300
+ const meta = JSON.parse(readFileSync(metaPath, 'utf8'));
301
+ expectedSha256 = meta.sha256;
302
+ } catch {
303
+ expectedSha256 = null;
304
+ }
305
+ }
306
+
307
+ const backupBytes = readFileSync(backupPath);
308
+ if (expectedSha256 && sha256(backupBytes) !== expectedSha256) {
309
+ throw new Error(`Backup file checksum corrupted: ${backupPath}`);
310
+ }
311
+
312
+ mkdirSync(dirname(targetPath), { recursive: true });
313
+ copyFileSync(backupPath, targetPath);
314
+
315
+ const restoredBytes = readFileSync(targetPath);
316
+ if (sha256(restoredBytes) !== sha256(backupBytes)) {
317
+ throw new Error(`Restoration verification failed for ${targetPath}`);
318
+ }
319
+
320
+ return { restored: true, targetPath, sha256: sha256(restoredBytes) };
321
+ }
322
+
323
+ /**
324
+ * Parses basic and standard TOML strings into a JavaScript object without external dependencies.
325
+ * Fails closed on syntax errors or invalid TOML.
326
+ */
327
+ export function parseToml(input) {
328
+ if (typeof input !== 'string') {
329
+ throw new TypeError('TOML input must be a string');
330
+ }
331
+
332
+ // Strip UTF-8 BOM if present
333
+ const src = input.charCodeAt(0) === 0xFEFF ? input.slice(1) : input;
334
+ let pos = 0;
335
+ const len = src.length;
336
+
337
+ function skipWhitespace(includeNewlines = false) {
338
+ while (pos < len) {
339
+ const ch = src[pos];
340
+ if (ch === ' ' || ch === '\t' || ch === '\r') {
341
+ pos++;
342
+ } else if (includeNewlines && ch === '\n') {
343
+ pos++;
344
+ } else if (ch === '#') {
345
+ while (pos < len && src[pos] !== '\n') {
346
+ pos++;
347
+ }
348
+ } else {
349
+ break;
350
+ }
351
+ }
352
+ }
353
+
354
+ function skipWhitespaceAndCommentsInMultiline() {
355
+ while (pos < len) {
356
+ const ch = src[pos];
357
+ if (ch === ' ' || ch === '\t' || ch === '\r' || ch === '\n') {
358
+ pos++;
359
+ } else if (ch === '#') {
360
+ while (pos < len && src[pos] !== '\n') {
361
+ pos++;
362
+ }
363
+ } else {
364
+ break;
365
+ }
366
+ }
367
+ }
368
+
369
+ function expect(char) {
370
+ skipWhitespace(false);
371
+ if (src[pos] !== char) {
372
+ throw new Error(`Expected '${char}' at index ${pos}, found '${src[pos] || 'EOF'}'`);
373
+ }
374
+ pos++;
375
+ }
376
+
377
+ function parseBareKey() {
378
+ const start = pos;
379
+ while (pos < len && /[A-Za-z0-9_-]/.test(src[pos])) {
380
+ pos++;
381
+ }
382
+ if (pos === start) {
383
+ throw new Error(`Expected bare key at position ${pos}`);
384
+ }
385
+ return src.slice(start, pos);
386
+ }
387
+
388
+ function parseEscapeChar() {
389
+ if (pos >= len) throw new Error('Unexpected EOF in string escape');
390
+ const ch = src[pos++];
391
+ switch (ch) {
392
+ case '"': return '"';
393
+ case '\\': return '\\';
394
+ case 'b': return '\b';
395
+ case 'f': return '\f';
396
+ case 'n': return '\n';
397
+ case 'r': return '\r';
398
+ case 't': return '\t';
399
+ case 'u': {
400
+ const hex = src.slice(pos, pos + 4);
401
+ if (!/^[0-9a-fA-F]{4}$/.test(hex)) throw new Error(`Invalid unicode escape \\u${hex}`);
402
+ pos += 4;
403
+ return String.fromCharCode(parseInt(hex, 16));
404
+ }
405
+ case 'U': {
406
+ const hex = src.slice(pos, pos + 8);
407
+ if (!/^[0-9a-fA-F]{8}$/.test(hex)) throw new Error(`Invalid unicode escape \\U${hex}`);
408
+ pos += 8;
409
+ return String.fromCodePoint(parseInt(hex, 16));
410
+ }
411
+ default:
412
+ throw new Error(`Invalid escape sequence \\${ch}`);
413
+ }
414
+ }
415
+
416
+ function parseBasicString(isMultiline = false) {
417
+ if (isMultiline) {
418
+ if (src[pos] === '\r' && src[pos + 1] === '\n') pos += 2;
419
+ else if (src[pos] === '\n') pos++;
420
+
421
+ let result = '';
422
+ while (pos < len) {
423
+ if (src.startsWith('"""', pos)) {
424
+ pos += 3;
425
+ return result;
426
+ }
427
+ if (src[pos] === '\\') {
428
+ pos++;
429
+ if (pos >= len) throw new Error('Unterminated multiline string escape');
430
+ const nextCh = src[pos];
431
+ if (nextCh === '\r' || nextCh === '\n') {
432
+ if (nextCh === '\r' && src[pos + 1] === '\n') pos++;
433
+ pos++;
434
+ while (pos < len && (src[pos] === ' ' || src[pos] === '\t' || src[pos] === '\r' || src[pos] === '\n')) {
435
+ pos++;
436
+ }
437
+ continue;
438
+ }
439
+ result += parseEscapeChar();
440
+ } else {
441
+ result += src[pos++];
442
+ }
443
+ }
444
+ throw new Error('Unterminated multiline basic string');
445
+ }
446
+
447
+ let result = '';
448
+ while (pos < len) {
449
+ const ch = src[pos++];
450
+ if (ch === '"') {
451
+ return result;
452
+ }
453
+ if (ch === '\n' || ch === '\r') {
454
+ throw new Error('Unescaped newline in single-line basic string');
455
+ }
456
+ if (ch === '\\') {
457
+ result += parseEscapeChar();
458
+ } else {
459
+ result += ch;
460
+ }
461
+ }
462
+ throw new Error('Unterminated basic string');
463
+ }
464
+
465
+ function parseLiteralString(isMultiline = false) {
466
+ if (isMultiline) {
467
+ if (src[pos] === '\r' && src[pos + 1] === '\n') pos += 2;
468
+ else if (src[pos] === '\n') pos++;
469
+
470
+ let result = '';
471
+ while (pos < len) {
472
+ if (src.startsWith("'''", pos)) {
473
+ pos += 3;
474
+ return result;
475
+ }
476
+ result += src[pos++];
477
+ }
478
+ throw new Error('Unterminated multiline literal string');
479
+ }
480
+
481
+ let result = '';
482
+ while (pos < len) {
483
+ const ch = src[pos++];
484
+ if (ch === "'") return result;
485
+ if (ch === '\n' || ch === '\r') throw new Error('Unescaped newline in single-line literal string');
486
+ result += ch;
487
+ }
488
+ throw new Error('Unterminated literal string');
489
+ }
490
+
491
+ function parseKeySegment() {
492
+ skipWhitespace(false);
493
+ if (src[pos] === '"') {
494
+ pos++;
495
+ return parseBasicString(false);
496
+ }
497
+ if (src[pos] === "'") {
498
+ pos++;
499
+ return parseLiteralString(false);
500
+ }
501
+ return parseBareKey();
502
+ }
503
+
504
+ function parseKey() {
505
+ const keys = [parseKeySegment()];
506
+ while (true) {
507
+ skipWhitespace(false);
508
+ if (src[pos] === '.') {
509
+ pos++;
510
+ skipWhitespace(false);
511
+ keys.push(parseKeySegment());
512
+ } else {
513
+ break;
514
+ }
515
+ }
516
+ return keys;
517
+ }
518
+
519
+ function parseValue() {
520
+ skipWhitespace(false);
521
+ if (pos >= len) throw new Error('Unexpected EOF when expecting value');
522
+
523
+ // Strings
524
+ if (src.startsWith('"""', pos)) {
525
+ pos += 3;
526
+ return parseBasicString(true);
527
+ }
528
+ if (src[pos] === '"') {
529
+ pos++;
530
+ return parseBasicString(false);
531
+ }
532
+ if (src.startsWith("'''", pos)) {
533
+ pos += 3;
534
+ return parseLiteralString(true);
535
+ }
536
+ if (src[pos] === "'") {
537
+ pos++;
538
+ return parseLiteralString(false);
539
+ }
540
+
541
+ // Boolean
542
+ if (src.startsWith('true', pos) && !/[a-zA-Z0-9_-]/.test(src[pos + 4] || '')) {
543
+ pos += 4;
544
+ return true;
545
+ }
546
+ if (src.startsWith('false', pos) && !/[a-zA-Z0-9_-]/.test(src[pos + 5] || '')) {
547
+ pos += 5;
548
+ return false;
549
+ }
550
+
551
+ // Array
552
+ if (src[pos] === '[') {
553
+ pos++;
554
+ const arr = [];
555
+ while (pos < len) {
556
+ skipWhitespaceAndCommentsInMultiline();
557
+ if (src[pos] === ']') {
558
+ pos++;
559
+ return arr;
560
+ }
561
+ arr.push(parseValue());
562
+ skipWhitespaceAndCommentsInMultiline();
563
+ if (src[pos] === ',') {
564
+ pos++;
565
+ skipWhitespaceAndCommentsInMultiline();
566
+ if (src[pos] === ']') {
567
+ pos++;
568
+ return arr;
569
+ }
570
+ } else if (src[pos] === ']') {
571
+ pos++;
572
+ return arr;
573
+ } else {
574
+ throw new Error(`Expected ',' or ']' in array at pos ${pos}, found '${src[pos] || 'EOF'}'`);
575
+ }
576
+ }
577
+ throw new Error('Unterminated array');
578
+ }
579
+
580
+ // Inline Table
581
+ if (src[pos] === '{') {
582
+ pos++;
583
+ const tbl = {};
584
+ skipWhitespace(false);
585
+ if (src[pos] === '}') {
586
+ pos++;
587
+ return tbl;
588
+ }
589
+ while (pos < len) {
590
+ skipWhitespace(false);
591
+ const keyParts = parseKey();
592
+ skipWhitespace(false);
593
+ expect('=');
594
+ skipWhitespace(false);
595
+ const val = parseValue();
596
+
597
+ let cur = tbl;
598
+ for (let i = 0; i < keyParts.length - 1; i++) {
599
+ const k = keyParts[i];
600
+ if (!cur[k] || typeof cur[k] !== 'object' || Array.isArray(cur[k])) {
601
+ cur[k] = {};
602
+ }
603
+ cur = cur[k];
604
+ }
605
+ const lastKey = keyParts[keyParts.length - 1];
606
+ if (Object.prototype.hasOwnProperty.call(cur, lastKey)) {
607
+ throw new Error(`Duplicate key "${keyParts.join('.')}" in inline table`);
608
+ }
609
+ cur[lastKey] = val;
610
+
611
+ skipWhitespace(false);
612
+ if (src[pos] === ',') {
613
+ pos++;
614
+ skipWhitespace(false);
615
+ if (src[pos] === '}') {
616
+ pos++;
617
+ return tbl;
618
+ }
619
+ } else if (src[pos] === '}') {
620
+ pos++;
621
+ return tbl;
622
+ } else {
623
+ throw new Error(`Expected ',' or '}' in inline table at pos ${pos}, found '${src[pos] || 'EOF'}'`);
624
+ }
625
+ }
626
+ throw new Error('Unterminated inline table');
627
+ }
628
+
629
+ // Numbers & Dates
630
+ const valStart = pos;
631
+ while (pos < len && !/[ \t\r\n#,\]}]/.test(src[pos])) {
632
+ pos++;
633
+ }
634
+ const raw = src.slice(valStart, pos);
635
+ if (!raw) {
636
+ throw new Error(`Expected value at position ${valStart}`);
637
+ }
638
+
639
+ if (raw === 'inf' || raw === '+inf') return Infinity;
640
+ if (raw === '-inf') return -Infinity;
641
+ if (raw === 'nan' || raw === '+nan' || raw === '-nan') return NaN;
642
+
643
+ function parseInteger(cleanStr) {
644
+ const bi = BigInt(cleanStr);
645
+ if (bi >= BigInt(Number.MIN_SAFE_INTEGER) && bi <= BigInt(Number.MAX_SAFE_INTEGER)) {
646
+ return Number(bi);
647
+ }
648
+ return bi;
649
+ }
650
+
651
+ if (/^0x[0-9a-fA-F](_?[0-9a-fA-F])*$/.test(raw)) {
652
+ return parseInteger(raw.replace(/_/g, ''));
653
+ }
654
+ if (/^0o[0-7](_?[0-7])*$/.test(raw)) {
655
+ return parseInteger(raw.replace(/_/g, ''));
656
+ }
657
+ if (/^0b[01](_?[01])*$/.test(raw)) {
658
+ return parseInteger(raw.replace(/_/g, ''));
659
+ }
660
+
661
+ if (/^[+-]?(?:0|[1-9](?:_?\d)*)$/.test(raw)) {
662
+ return parseInteger(raw.replace(/_/g, ''));
663
+ }
664
+ if (/^[+-]?(?:0|[1-9](?:_?\d)*)(?:\.\d(?:_?\d)*)?(?:[eE][+-]?\d(?:_?\d)*)?$/.test(raw) ||
665
+ /^[+-]?0\.\d(?:_?\d)*(?:[eE][+-]?\d(?:_?\d)*)?$/.test(raw)) {
666
+ return parseFloat(raw.replace(/_/g, ''));
667
+ }
668
+
669
+ if (/^\d{4}-\d{2}-\d{2}/.test(raw)) {
670
+ return raw;
671
+ }
672
+
673
+ throw new Error(`Invalid TOML value: "${raw}" at pos ${valStart}`);
674
+ }
675
+
676
+ const root = {};
677
+ let currentTable = root;
678
+
679
+ while (pos < len) {
680
+ skipWhitespace(false);
681
+ if (pos >= len) break;
682
+
683
+ const ch = src[pos];
684
+ if (ch === '\n') {
685
+ pos++;
686
+ continue;
687
+ }
688
+ if (ch === '#') {
689
+ while (pos < len && src[pos] !== '\n') pos++;
690
+ continue;
691
+ }
692
+
693
+ if (ch === '[') {
694
+ if (src.startsWith('[[', pos)) {
695
+ pos += 2;
696
+ skipWhitespace(false);
697
+ const tableKeys = parseKey();
698
+ skipWhitespace(false);
699
+ if (!src.startsWith(']]', pos)) {
700
+ throw new Error(`Expected ']]' after table header at pos ${pos}`);
701
+ }
702
+ pos += 2;
703
+
704
+ let cur = root;
705
+ for (let i = 0; i < tableKeys.length - 1; i++) {
706
+ const k = tableKeys[i];
707
+ if (!cur[k] || typeof cur[k] !== 'object') cur[k] = {};
708
+ if (Array.isArray(cur[k])) cur = cur[k][cur[k].length - 1];
709
+ else cur = cur[k];
710
+ }
711
+ const lastKey = tableKeys[tableKeys.length - 1];
712
+ if (!cur[lastKey]) cur[lastKey] = [];
713
+ if (!Array.isArray(cur[lastKey])) {
714
+ throw new Error(`Cannot define array of tables on existing non-array table "${tableKeys.join('.')}"`);
715
+ }
716
+ const newTable = {};
717
+ cur[lastKey].push(newTable);
718
+ currentTable = newTable;
719
+ continue;
720
+ }
721
+
722
+ pos++;
723
+ skipWhitespace(false);
724
+ const tableKeys = parseKey();
725
+ skipWhitespace(false);
726
+ if (src[pos] !== ']') {
727
+ throw new Error(`Expected ']' after table header at pos ${pos}`);
728
+ }
729
+ pos++;
730
+
731
+ let cur = root;
732
+ for (let i = 0; i < tableKeys.length; i++) {
733
+ const k = tableKeys[i];
734
+ if (!cur[k] || typeof cur[k] !== 'object' || Array.isArray(cur[k])) {
735
+ cur[k] = {};
736
+ }
737
+ cur = cur[k];
738
+ }
739
+ currentTable = cur;
740
+ continue;
741
+ }
742
+
743
+ const keyParts = parseKey();
744
+ skipWhitespace(false);
745
+ expect('=');
746
+ skipWhitespace(false);
747
+ const value = parseValue();
748
+
749
+ skipWhitespace(false);
750
+ if (pos < len && src[pos] !== '\n' && src[pos] !== '\r' && src[pos] !== '#') {
751
+ throw new Error(`Unexpected character '${src[pos]}' after value at pos ${pos}`);
752
+ }
753
+
754
+ let cur = currentTable;
755
+ for (let i = 0; i < keyParts.length - 1; i++) {
756
+ const k = keyParts[i];
757
+ if (!cur[k] || typeof cur[k] !== 'object' || Array.isArray(cur[k])) {
758
+ cur[k] = {};
759
+ }
760
+ cur = cur[k];
761
+ }
762
+ const lastKey = keyParts[keyParts.length - 1];
763
+ if (Object.prototype.hasOwnProperty.call(cur, lastKey)) {
764
+ throw new Error(`Duplicate key "${keyParts.join('.')}" in table`);
765
+ }
766
+ cur[lastKey] = value;
767
+ }
768
+
769
+ return root;
770
+ }
771
+
772
+ /**
773
+ * Safely clones a configuration object supporting primitives, BigInt, arrays, and plain objects.
774
+ */
775
+ export function cloneConfig(val) {
776
+ if (val === null || typeof val !== 'object') return val;
777
+ if (Array.isArray(val)) return val.map(cloneConfig);
778
+ const result = {};
779
+ for (const [k, v] of Object.entries(val)) {
780
+ result[k] = cloneConfig(v);
781
+ }
782
+ return result;
783
+ }
784
+
785
+ /**
786
+ * Formats values safely for diagnostics without throwing on BigInt.
787
+ */
788
+ function formatValue(v) {
789
+ if (typeof v === 'bigint') return v.toString();
790
+ try {
791
+ return JSON.stringify(v);
792
+ } catch {
793
+ return String(v);
794
+ }
795
+ }
796
+
797
+ /**
798
+ * Recursively diffs two configuration objects and reports missing tables, missing keys,
799
+ * mutated key paths, and unexpectedly injected settings.
800
+ */
801
+ export function diffConfigObjects(before, after) {
802
+ const missingTables = [];
803
+ const missingKeys = [];
804
+ const mutatedKeys = [];
805
+ const addedTables = [];
806
+ const addedKeys = [];
807
+
808
+ function isObject(val) {
809
+ return val !== null && typeof val === 'object' && !Array.isArray(val);
810
+ }
811
+
812
+ function valuesEqual(a, b) {
813
+ if (a === b) return true;
814
+
815
+ // Both are BigInt
816
+ if (typeof a === 'bigint' && typeof b === 'bigint') {
817
+ return a === b;
818
+ }
819
+
820
+ // Mathematical integer comparison between BigInt and safe integer Number
821
+ if (typeof a === 'bigint' && typeof b === 'number') {
822
+ return Number.isSafeInteger(b) && a === BigInt(b);
823
+ }
824
+ if (typeof a === 'number' && typeof b === 'bigint') {
825
+ return Number.isSafeInteger(a) && BigInt(a) === b;
826
+ }
827
+
828
+ // Both are Number (floats and safe integers)
829
+ if (typeof a === 'number' && typeof b === 'number') {
830
+ if (Number.isNaN(a) && Number.isNaN(b)) return true;
831
+ return Object.is(a, b) || a === b;
832
+ }
833
+
834
+ // Unrelated types must not be conflated
835
+ if (a === null || b === null || typeof a !== typeof b) return false;
836
+
837
+ if (Array.isArray(a)) {
838
+ if (!Array.isArray(b) || a.length !== b.length) return false;
839
+ for (let i = 0; i < a.length; i++) {
840
+ if (!valuesEqual(a[i], b[i])) return false;
841
+ }
842
+ return true;
843
+ }
844
+
845
+ if (isObject(a)) {
846
+ if (!isObject(b)) return false;
847
+ const keysA = Object.keys(a);
848
+ const keysB = Object.keys(b);
849
+ if (keysA.length !== keysB.length) return false;
850
+ for (const k of keysA) {
851
+ if (!Object.prototype.hasOwnProperty.call(b, k)) return false;
852
+ if (!valuesEqual(a[k], b[k])) return false;
853
+ }
854
+ return true;
855
+ }
856
+
857
+ return false;
858
+ }
859
+
860
+ function walk(bObj, aObj, currentPath = '') {
861
+ for (const key of Object.keys(bObj)) {
862
+ const path = currentPath ? `${currentPath}.${key}` : key;
863
+ const bVal = bObj[key];
864
+
865
+ if (!Object.prototype.hasOwnProperty.call(aObj, key)) {
866
+ if (isObject(bVal) || (Array.isArray(bVal) && bVal.every(isObject))) {
867
+ missingTables.push(path);
868
+ } else {
869
+ missingKeys.push(path);
870
+ }
871
+ continue;
872
+ }
873
+
874
+ const aVal = aObj[key];
875
+ if (isObject(bVal)) {
876
+ if (!isObject(aVal)) {
877
+ mutatedKeys.push({ path, before: bVal, after: aVal });
878
+ } else {
879
+ walk(bVal, aVal, path);
880
+ }
881
+ } else {
882
+ if (!valuesEqual(bVal, aVal)) {
883
+ mutatedKeys.push({ path, before: bVal, after: aVal });
884
+ }
885
+ }
886
+ }
887
+
888
+ for (const key of Object.keys(aObj)) {
889
+ const path = currentPath ? `${currentPath}.${key}` : key;
890
+ if (!Object.prototype.hasOwnProperty.call(bObj, key)) {
891
+ const aVal = aObj[key];
892
+ if (isObject(aVal) || (Array.isArray(aVal) && aVal.every(isObject))) {
893
+ addedTables.push(path);
894
+ } else {
895
+ addedKeys.push(path);
896
+ }
897
+ }
898
+ }
899
+ }
900
+
901
+ walk(before, after);
902
+
903
+ return {
904
+ missingTables,
905
+ missingKeys,
906
+ mutatedKeys,
907
+ addedTables,
908
+ addedKeys,
909
+ };
910
+ }
911
+
912
+ /**
913
+ * Removes only the target MCP server table/entry from a configuration object,
914
+ * preserving all sibling servers and unrelated configuration.
915
+ */
916
+ function cleanTargetServer(obj, server) {
917
+ if (!obj || typeof obj !== 'object') return obj;
918
+ const clone = cloneConfig(obj);
919
+
920
+ if (clone.mcp_servers && typeof clone.mcp_servers === 'object' && !Array.isArray(clone.mcp_servers)) {
921
+ delete clone.mcp_servers[server];
922
+ if (Object.keys(clone.mcp_servers).length === 0) delete clone.mcp_servers;
923
+ }
924
+ if (clone.mcpServers && typeof clone.mcpServers === 'object' && !Array.isArray(clone.mcpServers)) {
925
+ delete clone.mcpServers[server];
926
+ if (Object.keys(clone.mcpServers).length === 0) delete clone.mcpServers;
927
+ }
928
+ if (clone[server]) {
929
+ delete clone[server];
930
+ }
931
+ // Single-server transport descriptor fallback (e.g. mock test harnesses)
932
+ if (clone.transport && (clone.transport.command || clone.transport.type)) {
933
+ delete clone.transport;
934
+ }
935
+
936
+ return clone;
937
+ }
938
+
939
+ /**
940
+ * Validates whether unrelated configuration entries were preserved during provider integration.
941
+ * Distinguishes harmless provider-native normalization (whitespace, quoting, comment stripping, table ordering,
942
+ * numeric representations) from destructive loss or unauthorized mutation of unrelated user settings.
943
+ */
944
+ export function validateUnrelatedPreserved({
945
+ format = 'toml',
946
+ beforeBytes,
947
+ afterBytes,
948
+ server = 'afyx_graph',
949
+ }) {
950
+ if (!beforeBytes) {
951
+ return {
952
+ preserved: true,
953
+ normalized: false,
954
+ code: 'INITIAL_CONFIG_CREATED',
955
+ missingTables: [],
956
+ missingKeys: [],
957
+ mutatedKeys: [],
958
+ detail: 'Initial configuration created.',
959
+ };
960
+ }
961
+
962
+ const exactSame = byteEquals(beforeBytes, afterBytes);
963
+ if (exactSame) {
964
+ return {
965
+ preserved: true,
966
+ normalized: false,
967
+ code: 'PRESERVED',
968
+ missingTables: [],
969
+ missingKeys: [],
970
+ mutatedKeys: [],
971
+ detail: 'Configuration bytes unchanged.',
972
+ };
973
+ }
974
+
975
+ if (format === 'json') {
976
+ let cleanBefore;
977
+ try {
978
+ const beforeObj = JSON.parse(beforeBytes.toString('utf8'));
979
+ cleanBefore = cleanTargetServer(beforeObj, server);
980
+ } catch (err) {
981
+ return {
982
+ preserved: false,
983
+ normalized: false,
984
+ code: 'INVALID_JSON',
985
+ missingTables: [],
986
+ missingKeys: [],
987
+ mutatedKeys: [],
988
+ detail: `Failed to parse JSON for semantic validation: ${err instanceof Error ? err.message : String(err)}`,
989
+ };
990
+ }
991
+
992
+ if (!afterBytes) {
993
+ const hadUnrelated = Object.keys(cleanBefore).length > 0;
994
+ return {
995
+ preserved: !hadUnrelated,
996
+ normalized: false,
997
+ code: hadUnrelated ? 'UNRELATED_CONFIG_DELETED' : 'PRESERVED',
998
+ missingTables: [],
999
+ missingKeys: [],
1000
+ mutatedKeys: [],
1001
+ detail: hadUnrelated
1002
+ ? 'Configuration file containing unrelated settings was deleted.'
1003
+ : 'Configuration file cleanly removed as no unrelated settings existed.',
1004
+ };
1005
+ }
1006
+
1007
+ let cleanAfter;
1008
+ try {
1009
+ const afterObj = JSON.parse(afterBytes.toString('utf8'));
1010
+ cleanAfter = cleanTargetServer(afterObj, server);
1011
+ } catch (err) {
1012
+ return {
1013
+ preserved: false,
1014
+ normalized: false,
1015
+ code: 'INVALID_JSON',
1016
+ missingTables: [],
1017
+ missingKeys: [],
1018
+ mutatedKeys: [],
1019
+ detail: `Failed to parse JSON for semantic validation: ${err instanceof Error ? err.message : String(err)}`,
1020
+ };
1021
+ }
1022
+
1023
+ const diff = diffConfigObjects(cleanBefore, cleanAfter);
1024
+ const unrelatedMatch = diff.missingTables.length === 0
1025
+ && diff.missingKeys.length === 0
1026
+ && diff.mutatedKeys.length === 0
1027
+ && diff.addedTables.length === 0
1028
+ && diff.addedKeys.length === 0;
1029
+
1030
+ let code = 'PRESERVED';
1031
+ let detail = 'Provider normalized JSON formatting; unrelated settings preserved.';
1032
+ if (!unrelatedMatch) {
1033
+ if (diff.mutatedKeys.length > 0) {
1034
+ code = 'UNRELATED_KEY_VALUE_MUTATED';
1035
+ detail = `UNRELATED_KEY_VALUE_MUTATED: Setting at "${diff.mutatedKeys[0].path}" was changed.`;
1036
+ } else if (diff.missingKeys.length > 0) {
1037
+ code = 'UNRELATED_KEY_DELETED';
1038
+ detail = `UNRELATED_KEY_DELETED: Unrelated key "${diff.missingKeys[0]}" was removed.`;
1039
+ } else if (diff.missingTables.length > 0) {
1040
+ code = 'UNRELATED_TABLE_DELETED';
1041
+ detail = `UNRELATED_TABLE_DELETED: Unrelated table "${diff.missingTables[0]}" was removed.`;
1042
+ } else {
1043
+ code = 'UNRELATED_SETTING_INJECTED';
1044
+ detail = 'Provider tooling altered unrelated JSON settings.';
1045
+ }
1046
+ }
1047
+
1048
+ return {
1049
+ preserved: unrelatedMatch,
1050
+ normalized: true,
1051
+ code,
1052
+ missingTables: diff.missingTables,
1053
+ missingKeys: diff.missingKeys,
1054
+ mutatedKeys: diff.mutatedKeys,
1055
+ detail,
1056
+ };
1057
+ }
1058
+
1059
+ if (format === 'toml') {
1060
+ let cleanBefore;
1061
+ try {
1062
+ const beforeStr = beforeBytes.toString('utf8');
1063
+ let beforeObj;
1064
+ try {
1065
+ beforeObj = parseToml(beforeStr);
1066
+ } catch (tomlErr) {
1067
+ if (beforeStr.trim().startsWith('{') && beforeStr.trim().endsWith('}')) {
1068
+ beforeObj = JSON.parse(beforeStr);
1069
+ } else {
1070
+ throw tomlErr;
1071
+ }
1072
+ }
1073
+ cleanBefore = cleanTargetServer(beforeObj, server);
1074
+ } catch (err) {
1075
+ return {
1076
+ preserved: false,
1077
+ normalized: false,
1078
+ code: 'INVALID_TOML',
1079
+ error: err instanceof Error ? err.message : String(err),
1080
+ missingTables: [],
1081
+ missingKeys: [],
1082
+ mutatedKeys: [],
1083
+ detail: `Failed to parse TOML for semantic validation: ${err instanceof Error ? err.message : String(err)}`,
1084
+ };
1085
+ }
1086
+
1087
+ if (!afterBytes) {
1088
+ const hadUnrelated = Object.keys(cleanBefore).length > 0;
1089
+ return {
1090
+ preserved: !hadUnrelated,
1091
+ normalized: false,
1092
+ code: hadUnrelated ? 'UNRELATED_CONFIG_DELETED' : 'PRESERVED',
1093
+ missingTables: [],
1094
+ missingKeys: [],
1095
+ mutatedKeys: [],
1096
+ detail: hadUnrelated
1097
+ ? 'Configuration file containing unrelated settings was deleted.'
1098
+ : 'Configuration file cleanly removed as no unrelated settings existed.',
1099
+ };
1100
+ }
1101
+
1102
+ let cleanAfter;
1103
+ try {
1104
+ const afterStr = afterBytes.toString('utf8');
1105
+ let afterObj;
1106
+ try {
1107
+ afterObj = parseToml(afterStr);
1108
+ } catch (tomlErr) {
1109
+ if (afterStr.trim().startsWith('{') && afterStr.trim().endsWith('}')) {
1110
+ afterObj = JSON.parse(afterStr);
1111
+ } else {
1112
+ throw tomlErr;
1113
+ }
1114
+ }
1115
+ cleanAfter = cleanTargetServer(afterObj, server);
1116
+ } catch (err) {
1117
+ return {
1118
+ preserved: false,
1119
+ normalized: false,
1120
+ code: 'INVALID_TOML',
1121
+ error: err instanceof Error ? err.message : String(err),
1122
+ missingTables: [],
1123
+ missingKeys: [],
1124
+ mutatedKeys: [],
1125
+ detail: `Failed to parse TOML for semantic validation: ${err instanceof Error ? err.message : String(err)}`,
1126
+ };
1127
+ }
1128
+
1129
+ const diff = diffConfigObjects(cleanBefore, cleanAfter);
1130
+ const preserved = diff.missingTables.length === 0
1131
+ && diff.missingKeys.length === 0
1132
+ && diff.mutatedKeys.length === 0
1133
+ && diff.addedTables.length === 0
1134
+ && diff.addedKeys.length === 0;
1135
+
1136
+ let code = 'PRESERVED';
1137
+ let detail = 'Provider normalized TOML formatting; unrelated tables and keys preserved.';
1138
+
1139
+ if (!preserved) {
1140
+ if (diff.mutatedKeys.length > 0) {
1141
+ const first = diff.mutatedKeys[0];
1142
+ code = 'UNRELATED_KEY_VALUE_MUTATED';
1143
+ detail = `UNRELATED_KEY_VALUE_MUTATED: Setting at "${first.path}" was changed from ${formatValue(first.before)} to ${formatValue(first.after)}`;
1144
+ } else if (diff.missingKeys.length > 0) {
1145
+ const first = diff.missingKeys[0];
1146
+ code = 'UNRELATED_KEY_DELETED';
1147
+ detail = `UNRELATED_KEY_DELETED: Unrelated key "${first}" was removed.`;
1148
+ } else if (diff.missingTables.length > 0) {
1149
+ const first = diff.missingTables[0];
1150
+ code = 'UNRELATED_TABLE_DELETED';
1151
+ detail = `UNRELATED_TABLE_DELETED: Unrelated table "${first}" was removed.`;
1152
+ } else if (diff.addedKeys.length > 0 || diff.addedTables.length > 0) {
1153
+ const first = diff.addedKeys[0] || diff.addedTables[0];
1154
+ code = 'UNRELATED_SETTING_INJECTED';
1155
+ detail = `UNRELATED_SETTING_INJECTED: Unrelated setting "${first}" was unexpectedly added.`;
1156
+ }
1157
+ }
1158
+
1159
+ return {
1160
+ preserved,
1161
+ normalized: true,
1162
+ code,
1163
+ missingTables: diff.missingTables,
1164
+ missingKeys: diff.missingKeys,
1165
+ mutatedKeys: diff.mutatedKeys,
1166
+ detail,
1167
+ };
1168
+ }
1169
+
1170
+ return {
1171
+ preserved: true,
1172
+ normalized: true,
1173
+ code: 'PRESERVED',
1174
+ missingTables: [],
1175
+ missingKeys: [],
1176
+ mutatedKeys: [],
1177
+ detail: 'Unrelated validation completed.',
1178
+ };
1179
+ }
1180
+
1181
+ /**
1182
+ * Lists existing backups for a specific provider.
1183
+ */
1184
+ export function listProviderBackups(provider, backupRoot = '') {
1185
+ const root = getProviderBackupRoot(backupRoot);
1186
+ const providerDir = join(root, 'provider-config', provider);
1187
+ if (!existsSync(providerDir)) return [];
1188
+
1189
+ return readdirSync(providerDir, { withFileTypes: true })
1190
+ .filter((e) => e.isFile() && e.name.endsWith('.meta.json'))
1191
+ .map((e) => {
1192
+ const metaPath = join(providerDir, e.name);
1193
+ try {
1194
+ const meta = JSON.parse(readFileSync(metaPath, 'utf8'));
1195
+ return {
1196
+ ...meta,
1197
+ metaPath,
1198
+ backupPath: metaPath.slice(0, -'.meta.json'.length),
1199
+ };
1200
+ } catch {
1201
+ return null;
1202
+ }
1203
+ })
1204
+ .filter(Boolean)
1205
+ .sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
1206
+ }