omp-config-crypt 0.3.0 → 0.4.0

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.
package/README.md CHANGED
@@ -1,50 +1,91 @@
1
- # omp-config-crypt
1
+ # omp-config-crypt (v0.4.0)
2
2
 
3
- Encrypted export/import of omp user config and instruction files, locally or
4
- through a cloud token. Secrets are included as-is; the archive itself is the
5
- only protection.
3
+ Universal, zero-repair cross-platform configuration encryption and synchronization engine for `omp` (Oh My Pi).
6
4
 
7
- ## Archive
5
+ Supports both **in-OMP slash commands** and an **independent standalone CLI (`omp-sync`)**. Seamlessly synchronizes configurations across Linux (root / non-root), macOS, and Windows WSL with zero manual post-restore adjustments.
8
6
 
9
- - AES-256-GCM, key = scrypt(passphrase, random salt)
10
- - gzip payload, single binary file (`OMPCFG1\0` magic)
11
- - written with mode `0600`
7
+ ---
12
8
 
13
- Included: `config.yml`, `models.yml`, `mcp.json`, `AGENTS.md`, `STYLE.md`,
14
- `RULES.md`, and everything under `memories/`.
9
+ ## Key Features
15
10
 
16
- ## Local commands
11
+ 1. **Adaptive Cross-Platform Remapping**:
12
+ - Automatically sanitizes machine-specific home paths (e.g., `/root`, `/home/user`, `/Users/alice`, `C:\Users\bob`) into a portable `{{OMP_HOME}}` placeholder.
13
+ - On import, dynamically remaps placeholders and source paths to the target host's actual `$HOME` and normalizes path separators.
14
+ 2. **Zero OMP Internal Dependency**:
15
+ - Built 100% on native Node.js built-ins (`node:crypto`, `node:fs`, `node:path`, `node:zlib`, `node:os`).
16
+ - Core `omp` binary upgrades never break or affect this tool.
17
+ 3. **Comprehensive Asset Synchronization**:
18
+ - **Core Configs**: `config.yml`, `models.yml`, `mcp.json`, `AGENTS.md`, `STYLE.md`, `RULES.md`.
19
+ - **Credentials & Tokens**: Automatic discovery and encryption of `opc-mcp-token` and `*.token` files.
20
+ - **User Extensions**: Full recursive synchronization of `~/.omp/extensions/**` (e.g. `agy.js`).
21
+ - **Skills & Knowledge**: Recursive sync of `managed-skills/**` and `memories/**`.
22
+ - **Plugins Manifest**: Syncs `plugins/omp-plugins.lock.json` for deterministic plugin tracking.
23
+ - **Strict Blacklist**: Automatically excludes SQLite runtime databases (`*.db`, `*.db-wal`, `*.db-shm`), session logs, and cache folders.
24
+ 4. **Safety & Instant Rollback**:
25
+ - Pre-existing files are automatically backed up to `.import-backup-<timestamp>/` prior to overwriting.
26
+ - One-command instant rollback (`omp-sync rollback` or `/config-rollback`).
27
+ - Non-destructive dry-run preview (`--dry-run`).
17
28
 
18
- ```
19
- /config-export [out.enc]
20
- /config-import <file.enc>
21
- ```
29
+ ---
22
30
 
23
- ## Cloud commands
31
+ ## Standalone CLI (`omp-sync`)
24
32
 
25
- ```
26
- /config-push gist:new # create a secret gist
27
- /config-push gist:<id> # update it
28
- /config-push https://… # PUT to any endpoint
29
- /config-pull gist:<id>
30
- /config-pull https://…
31
- ```
33
+ Run outside or before starting `omp` (ideal for fresh machine setup, Docker provisioning, and CI/CD):
32
34
 
33
- Token: asked by the command when `OMP_CFG_CLOUD_TOKEN` (or `GITHUB_TOKEN`) is
34
- unset, and never written into the archive or to disk. For plain HTTP targets the
35
- token is optional and an empty answer skips it, so presigned S3/R2 URLs work as-is.
35
+ ```bash
36
+ # Export configs locally
37
+ npx omp-config-crypt export my-backup.enc --pass "mysecret"
36
38
 
37
- GitHub needs a token with the `gist` scope. Plain HTTP targets receive
38
- `Authorization: Bearer <token>` when the variable is set, which covers WebDAV
39
- behind a bearer proxy and most object-storage gateways.
39
+ # Import configs locally with dry-run preview
40
+ npx omp-config-crypt import my-backup.enc --pass "mysecret" --dry-run
40
41
 
41
- Passphrase: `OMP_CONFIG_PASS`, or the prompt shown by the command.
42
+ # Import configs locally
43
+ npx omp-config-crypt import my-backup.enc --pass "mysecret"
42
44
 
43
- Import backs up every overwritten file to `<agent-dir>/.import-backup-<ts>/`
44
- and asks for a restart so settings reload.
45
+ # Cloud Push (GitHub Gist)
46
+ npx omp-config-crypt push gist:new --pass "mysecret" --token "$GITHUB_TOKEN"
45
47
 
46
- ## Install
48
+ # Cloud Pull (GitHub Gist)
49
+ npx omp-config-crypt pull gist:<id> --pass "mysecret" --token "$GITHUB_TOKEN"
47
50
 
51
+ # Rollback to previous configuration snapshot
52
+ npx omp-config-crypt rollback
48
53
  ```
49
- omp plugin install omp-config-crypt
54
+
55
+ ---
56
+
57
+ ## In-OMP Slash Commands
58
+
59
+ Inside any `omp` session:
60
+
61
+ ```text
62
+ /config-export [out.enc]
63
+ /config-import <file.enc> [--dry-run]
64
+ /config-push gist:new
65
+ /config-push gist:<id>
66
+ /config-push https://…
67
+ /config-pull gist:<id> [--dry-run]
68
+ /config-pull https://… [--dry-run]
69
+ /config-rollback
50
70
  ```
71
+
72
+ ---
73
+
74
+ ## Environment Variables
75
+
76
+ | Variable | Description |
77
+ |---|---|
78
+ | `OMP_CONFIG_PASS` | Encryption/decryption passphrase for headless automation |
79
+ | `OMP_CFG_CLOUD_TOKEN` | Primary Cloud / GitHub API token (gist scope) |
80
+ | `GITHUB_TOKEN` | Fallback GitHub API token |
81
+ | `OMP_CFG_ROOT` | Override path to agent directory (default: `~/.omp/agent`) |
82
+ | `OMP_HOME` | Override path to omp root (default: `~/.omp`) |
83
+
84
+ ---
85
+
86
+ ## Security Specification
87
+
88
+ - **Cipher**: AES-256-GCM authenticated encryption.
89
+ - **Key Derivation**: `scrypt` with 16-byte cryptographically secure random salt (`N=16384, r=8, p=1`).
90
+ - **Archive Wire Magic**: `OMPCFG1\0` header + 16B salt + 12B IV + 16B GCM auth tag + gzip payload.
91
+ - **File Mode**: Preserves executable and read/write bits with standard `0600` / `0700` safety.
@@ -0,0 +1,254 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Universal Standalone CLI for OMP Config Crypt & Sync Engine
5
+ * Operates independently of OMP runtime; zero external dependencies.
6
+ */
7
+
8
+ import readline from "node:readline";
9
+ import process from "node:process";
10
+ import {
11
+ configRoot,
12
+ exportEncrypted,
13
+ importEncrypted,
14
+ pushGist,
15
+ pullGist,
16
+ pushHttp,
17
+ pullHttp,
18
+ rollback,
19
+ parseSpec,
20
+ rehydratePlugins,
21
+ } from "../index.js";
22
+
23
+ function printHelp() {
24
+ console.log(`
25
+ Universal OMP Configuration Sync & Crypt Engine (Standalone CLI)
26
+
27
+ Usage:
28
+ omp-sync <command> [arguments] [options]
29
+
30
+ Commands:
31
+ export <outFile> Encrypt and export local OMP configs to a file
32
+ import <srcFile> Decrypt and restore OMP configs from an archive
33
+ push <gist:id|url> Encrypt and push configs to GitHub Gist or HTTP URL
34
+ pull <gist:id|url> Download and restore configs from Gist or HTTP URL
35
+ rollback Revert the most recent config restore from its backup
36
+ rehydrate Rehydrate and repair locked/linked plugins in ~/.omp/plugins
37
+
38
+ Options:
39
+ -p, --pass <passphrase> Decryption/Encryption passphrase (or OMP_CONFIG_PASS)
40
+ -t, --token <token> Cloud token (or OMP_CFG_CLOUD_TOKEN / GITHUB_TOKEN)
41
+ -r, --root <path> Agent configuration root (default: ~/.omp/agent)
42
+ -d, --dry-run Simulate restore without modifying files
43
+ -h, --help Show this help message
44
+ --no-rehydrate Skip automatic plugin rehydration on import/pull
45
+ --rehydrate Enforce plugin rehydration (default: true)
46
+
47
+ Environment Variables:
48
+ OMP_CONFIG_PASS Passphrase for non-interactive automation
49
+ OMP_CFG_CLOUD_TOKEN Cloud / GitHub API Token
50
+ GITHUB_TOKEN Alternative GitHub API Token
51
+ OMP_CFG_ROOT Override path to ~/.omp/agent
52
+ OMP_HOME Override path to ~/.omp
53
+ `);
54
+ }
55
+
56
+ function parseCliArgs(argv) {
57
+ const args = argv.slice(2);
58
+ const options = {
59
+ command: null,
60
+ target: null,
61
+ pass: process.env.OMP_CONFIG_PASS || null,
62
+ token: process.env.OMP_CFG_CLOUD_TOKEN || process.env.GITHUB_TOKEN || null,
63
+ root: process.env.OMP_CFG_ROOT || null,
64
+ dryRun: false,
65
+ rehydrate: true,
66
+ help: false,
67
+ };
68
+
69
+ const positional = [];
70
+ for (let i = 0; i < args.length; i++) {
71
+ const a = args[i];
72
+ if (a === "-h" || a === "--help" || a === "help") {
73
+ options.help = true;
74
+ } else if (a === "-d" || a === "--dry-run") {
75
+ options.dryRun = true;
76
+ } else if (a === "-p" || a === "--pass") {
77
+ options.pass = args[++i];
78
+ } else if (a === "--no-rehydrate") {
79
+ options.rehydrate = false;
80
+ } else if (a === "--rehydrate") {
81
+ options.rehydrate = true;
82
+ } else if (a === "-t" || a === "--token") {
83
+ options.token = args[++i];
84
+ } else if (a === "-r" || a === "--root") {
85
+ options.root = args[++i];
86
+ } else if (a.startsWith("--pass=")) {
87
+ options.pass = a.slice(7);
88
+ } else if (a.startsWith("--token=")) {
89
+ options.token = a.slice(8);
90
+ } else if (a.startsWith("--root=")) {
91
+ options.root = a.slice(7);
92
+ } else {
93
+ positional.push(a);
94
+ }
95
+ }
96
+
97
+ options.command = positional[0] || null;
98
+ options.target = positional[1] || null;
99
+ return options;
100
+ }
101
+
102
+ async function promptText(query) {
103
+ return new Promise((resolve) => {
104
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
105
+ rl.question(query, (ans) => {
106
+ rl.close();
107
+ resolve(ans.trim());
108
+ });
109
+ });
110
+ }
111
+
112
+ async function resolvePass(pass) {
113
+ if (pass) return pass;
114
+ if (!process.stdin.isTTY) {
115
+ throw new Error("Passphrase required: specify --pass <passphrase> or set OMP_CONFIG_PASS");
116
+ }
117
+ return promptText("Enter passphrase: ");
118
+ }
119
+
120
+ async function resolveToken(token, required) {
121
+ if (token) return token;
122
+ if (!required) return null;
123
+ if (!process.stdin.isTTY) {
124
+ throw new Error("Token required: specify --token <token> or set OMP_CFG_CLOUD_TOKEN / GITHUB_TOKEN");
125
+ }
126
+ return promptText("Enter GitHub/Cloud token: ");
127
+ }
128
+
129
+ async function main() {
130
+ const options = parseCliArgs(process.argv);
131
+ if (options.help || !options.command) {
132
+ printHelp();
133
+ process.exit(options.help ? 0 : 1);
134
+ }
135
+
136
+ const root = options.root || configRoot();
137
+
138
+ try {
139
+ switch (options.command) {
140
+ case "export": {
141
+ if (!options.target) {
142
+ throw new Error("Usage: omp-sync export <outFile> [options]");
143
+ }
144
+ const pass = await resolvePass(options.pass);
145
+ const res = exportEncrypted(options.target, pass, root);
146
+ console.log(`[export] Successfully exported ${res.files} files (${res.bytes} bytes) -> ${res.outFile}`);
147
+ break;
148
+ }
149
+
150
+ case "import": {
151
+ if (!options.target) {
152
+ throw new Error("Usage: omp-sync import <srcFile> [options]");
153
+ }
154
+ const pass = await resolvePass(options.pass);
155
+ const res = importEncrypted(options.target, pass, root, {
156
+ dryRun: options.dryRun,
157
+ rehydrate: options.rehydrate,
158
+ });
159
+ if (options.dryRun) {
160
+ console.log(`[import-dry-run] Would restore ${res.files} files (0 written to disk).`);
161
+ for (const act of res.actions) {
162
+ console.log(` - ${act.path} -> ${act.dest}${act.remapped ? " [path remapped]" : ""}`);
163
+ }
164
+ } else {
165
+ console.log(`[import] Successfully restored ${res.files} files to ${root}.`);
166
+ if (res.backupDir) {
167
+ console.log(`[backup] Pre-existing files backed up to: ${res.backupDir}`);
168
+ }
169
+ if (res.rehydration) {
170
+ console.log(
171
+ `[rehydrate] Plugins processed: ${res.rehydration.rehydrated} rehydrated (installed: ${res.rehydration.npmInstalled.length}, links: ${res.rehydration.linksRepaired.length}).`
172
+ );
173
+ }
174
+ }
175
+ break;
176
+ }
177
+
178
+ case "push": {
179
+ if (!options.target) {
180
+ throw new Error("Usage: omp-sync push <gist:new|gist:<id>|https://...> [options]");
181
+ }
182
+ const target = parseSpec(options.target);
183
+ const pass = await resolvePass(options.pass);
184
+ const token = await resolveToken(options.token, target.kind === "gist");
185
+ const res =
186
+ target.kind === "gist"
187
+ ? await pushGist(target.id, pass, root, token)
188
+ : await pushHttp(target.url, pass, root, token);
189
+ const dest = res.url ? `${res.url} (id: ${res.id})` : res.url;
190
+ console.log(`[push] Pushed ${res.files} files (${res.bytes} bytes) -> ${dest}`);
191
+ break;
192
+ }
193
+
194
+ case "pull": {
195
+ if (!options.target) {
196
+ throw new Error("Usage: omp-sync pull <gist:<id>|https://...> [options]");
197
+ }
198
+ const target = parseSpec(options.target);
199
+ const pass = await resolvePass(options.pass);
200
+ const token = await resolveToken(options.token, target.kind === "gist");
201
+ const res =
202
+ target.kind === "gist"
203
+ ? await pullGist(target.id, pass, root, token, { dryRun: options.dryRun, rehydrate: options.rehydrate })
204
+ : await pullHttp(target.url, pass, root, token, { dryRun: options.dryRun, rehydrate: options.rehydrate });
205
+
206
+ if (options.dryRun) {
207
+ console.log(`[pull-dry-run] Would restore ${res.files} files (0 written to disk).`);
208
+ for (const act of res.actions) {
209
+ console.log(` - ${act.path} -> ${act.dest}${act.remapped ? " [path remapped]" : ""}`);
210
+ }
211
+ } else {
212
+ console.log(`[pull] Successfully restored ${res.files} files to ${root}.`);
213
+ if (res.backupDir) {
214
+ console.log(`[backup] Pre-existing files backed up to: ${res.backupDir}`);
215
+ }
216
+ if (res.rehydration) {
217
+ console.log(
218
+ `[rehydrate] Plugins processed: ${res.rehydration.rehydrated} rehydrated (installed: ${res.rehydration.npmInstalled.length}, links: ${res.rehydration.linksRepaired.length}).`
219
+ );
220
+ }
221
+ }
222
+ break;
223
+ }
224
+
225
+ case "rollback": {
226
+ const res = rollback(root);
227
+ console.log(`[rollback] Successfully rolled back ${res.files} files from snapshot ${res.rolledBackFrom}`);
228
+ break;
229
+ }
230
+ case "rehydrate": {
231
+ const res = rehydratePlugins(root, { dryRun: options.dryRun });
232
+ console.log(
233
+ `[rehydrate] Completed. Total rehydrated: ${res.rehydrated} (installed: ${res.npmInstalled.length}, links: ${res.linksRepaired.length}).`
234
+ );
235
+ if (res.errors.length > 0) {
236
+ for (const err of res.errors) {
237
+ console.warn(` [warning] ${err}`);
238
+ }
239
+ }
240
+ break;
241
+ }
242
+
243
+ default:
244
+ console.error(`Unknown command: ${options.command}`);
245
+ printHelp();
246
+ process.exit(1);
247
+ }
248
+ } catch (err) {
249
+ console.error(`[error] ${err.message || err}`);
250
+ process.exit(1);
251
+ }
252
+ }
253
+
254
+ main();
package/index.js CHANGED
@@ -1,54 +1,234 @@
1
1
  /**
2
- * Encrypted portability for omp user config and instruction files.
3
- * Exports a single AES-256-GCM blob (scrypt-derived key); import restores files
4
- * and keeps a backup of whatever it overwrites.
2
+ * Universal, Zero-Repair Cross-Platform OMP Sync & Portability Engine
3
+ * Exports an encrypted AES-256-GCM blob (scrypt-derived key); import restores files,
4
+ * remaps host paths adaptively, and maintains atomic backups for instant rollback.
5
5
  */
6
6
  import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from "node:crypto";
7
7
  import { gzipSync, gunzipSync } from "node:zlib";
8
8
  import fs from "node:fs";
9
9
  import os from "node:os";
10
10
  import path from "node:path";
11
+ import {
12
+ rehydratePlugins,
13
+ getPluginLinks,
14
+ savePluginLinks,
15
+ detectMissingPlugins,
16
+ } from "./src/rehydrator.js";
17
+
18
+ export {
19
+ rehydratePlugins,
20
+ getPluginLinks,
21
+ savePluginLinks,
22
+ detectMissingPlugins,
23
+ };
11
24
 
12
25
  const MAGIC = Buffer.from("OMPCFG1\0", "latin1");
13
- const FILES = ["config.yml", "models.yml", "mcp.json", "AGENTS.md", "STYLE.md", "RULES.md"];
14
- const DIRS = ["memories"];
26
+ const HOME_PLACEHOLDER = "{{OMP_HOME}}";
27
+
28
+ const FILES = [
29
+ "config.yml",
30
+ "config.yaml",
31
+ "models.yml",
32
+ "models.yaml",
33
+ "mcp.json",
34
+ "AGENTS.md",
35
+ "STYLE.md",
36
+ "RULES.md",
37
+ ];
38
+
39
+ const DIRS = ["memories", "managed-skills"];
40
+
41
+ const BLACKLIST_PATTERNS = [
42
+ /\.db$/,
43
+ /\.db-wal$/,
44
+ /\.db-shm$/,
45
+ /\.corrupt-/,
46
+ /^\.import-backup/,
47
+ /\/\.import-backup/,
48
+ /^\.rolled-back/,
49
+ /\/\.rolled-back/,
50
+ /(^|\/)\.git\//,
51
+ /(^|\/)cache\//,
52
+ /(^|\/)blobs\//,
53
+ /(^|\/)sessions\//,
54
+ /(^|\/)terminal-sessions\//,
55
+ /(^|\/)predict\//,
56
+ /(^|\/)node_modules\//,
57
+ ];
15
58
 
16
59
  /** User agent directory, or OMP_CFG_ROOT for tests. */
17
60
  export function configRoot() {
18
61
  return process.env.OMP_CFG_ROOT || path.join(os.homedir(), ".omp", "agent");
19
62
  }
20
63
 
64
+ /** Root .omp folder (parent of agent directory). */
65
+ export function ompHome(root = configRoot()) {
66
+ return process.env.OMP_HOME || path.dirname(root);
67
+ }
68
+
69
+ function shouldIgnore(relPath) {
70
+ const norm = relPath.replace(/\\/g, "/");
71
+ return BLACKLIST_PATTERNS.some((rx) => rx.test(norm));
72
+ }
73
+
74
+ function isText(buf) {
75
+ const len = Math.min(buf.length, 1024);
76
+ for (let i = 0; i < len; i++) {
77
+ if (buf[i] === 0) return false;
78
+ }
79
+ return true;
80
+ }
81
+
21
82
  function walk(dir, prefix = "") {
22
83
  const out = [];
84
+ if (!fs.existsSync(dir)) return out;
23
85
  for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
24
86
  const rel = prefix ? `${prefix}/${ent.name}` : ent.name;
25
- if (ent.isDirectory()) out.push(...walk(path.join(dir, ent.name), rel));
26
- else if (ent.isFile()) out.push(rel);
87
+ const abs = path.join(dir, ent.name);
88
+ if (ent.isDirectory()) {
89
+ if (!shouldIgnore(rel + "/")) {
90
+ out.push(...walk(abs, rel));
91
+ }
92
+ } else if (ent.isFile()) {
93
+ if (!shouldIgnore(rel)) {
94
+ out.push(rel);
95
+ }
96
+ }
27
97
  }
28
98
  return out;
29
99
  }
30
100
 
31
- function collect(root) {
101
+ export function collect(root) {
32
102
  const out = [];
33
- for (const f of FILES) {
34
- const p = path.join(root, f);
35
- if (fs.existsSync(p) && fs.statSync(p).isFile()) out.push(f);
103
+ const seen = new Set();
104
+
105
+ function addItem(rel, abs) {
106
+ const norm = rel.replace(/\\/g, "/");
107
+ if (!seen.has(norm) && !shouldIgnore(norm) && fs.existsSync(abs) && fs.statSync(abs).isFile()) {
108
+ seen.add(norm);
109
+ out.push({ rel: norm, abs });
110
+ }
111
+ }
112
+
113
+ // 1. Files directly under root (agent/)
114
+ if (fs.existsSync(root)) {
115
+ for (const ent of fs.readdirSync(root, { withFileTypes: true })) {
116
+ if (ent.isFile()) {
117
+ const name = ent.name;
118
+ const isCore = FILES.includes(name);
119
+ const isToken = name.includes("token");
120
+ const isExtra = name.endsWith(".yml") || name.endsWith(".yaml") || name.endsWith(".json");
121
+ if (isCore || isToken || isExtra) {
122
+ addItem(name, path.join(root, name));
123
+ }
124
+ }
125
+ }
126
+
127
+ // 2. Category directories under root (memories, managed-skills)
128
+ for (const d of DIRS) {
129
+ const base = path.join(root, d);
130
+ if (fs.existsSync(base)) {
131
+ for (const file of walk(base)) {
132
+ addItem(`${d}/${file}`, path.join(base, file));
133
+ }
134
+ }
135
+ }
136
+ }
137
+
138
+ // 3. User extensions under ~/.omp/extensions/ (sibling to agent/)
139
+ const ompDir = ompHome(root);
140
+ const extDir = path.join(ompDir, "extensions");
141
+ if (fs.existsSync(extDir) && fs.statSync(extDir).isDirectory()) {
142
+ for (const file of walk(extDir)) {
143
+ addItem(`extensions/${file}`, path.join(extDir, file));
144
+ }
145
+ }
146
+
147
+ // 4. Installed plugins lockfile & manifest under ~/.omp/plugins/
148
+ const pluginsDir = path.join(ompDir, "plugins");
149
+ const links = getPluginLinks(pluginsDir);
150
+ if (Object.keys(links).length > 0) {
151
+ savePluginLinks(pluginsDir, links);
152
+ }
153
+ const linksFile = path.join(pluginsDir, ".plugin-links.json");
154
+ if (fs.existsSync(linksFile) && fs.statSync(linksFile).isFile()) {
155
+ addItem("plugins/.plugin-links.json", linksFile);
156
+ }
157
+ const lockFile = path.join(pluginsDir, "omp-plugins.lock.json");
158
+ if (fs.existsSync(lockFile) && fs.statSync(lockFile).isFile()) {
159
+ addItem("plugins/omp-plugins.lock.json", lockFile);
160
+ }
161
+ const pluginPkg = path.join(pluginsDir, "package.json");
162
+ if (fs.existsSync(pluginPkg) && fs.statSync(pluginPkg).isFile()) {
163
+ addItem("plugins/package.json", pluginPkg);
164
+ }
165
+ // 5. Global tools under ~/.omp/tools/
166
+ const toolsDir = path.join(ompDir, "tools");
167
+ if (fs.existsSync(toolsDir) && fs.statSync(toolsDir).isDirectory()) {
168
+ for (const file of walk(toolsDir)) {
169
+ addItem(`tools/${file}`, path.join(toolsDir, file));
170
+ }
36
171
  }
37
- for (const d of DIRS) {
38
- const base = path.join(root, d);
39
- if (fs.existsSync(base)) for (const rel of walk(base)) out.push(`${d}/${rel}`);
172
+
173
+ // 6. Global hooks under ~/.omp/hooks/
174
+ const hooksDir = path.join(ompDir, "hooks");
175
+ if (fs.existsSync(hooksDir) && fs.statSync(hooksDir).isDirectory()) {
176
+ for (const file of walk(hooksDir)) {
177
+ addItem(`hooks/${file}`, path.join(hooksDir, file));
178
+ }
40
179
  }
180
+
41
181
  return out;
42
182
  }
43
183
 
44
- /** Build the encrypted archive in memory. */
184
+ /** Determine target path for relative archive key. */
185
+ export function resolveDestination(rel, root = configRoot()) {
186
+ const norm = rel.replace(/\\/g, "/");
187
+ if (
188
+ norm.startsWith("extensions/") ||
189
+ norm.startsWith("plugins/") ||
190
+ norm.startsWith("tools/") ||
191
+ norm.startsWith("hooks/")
192
+ ) {
193
+ return path.join(ompHome(root), norm);
194
+ }
195
+ return path.join(root, norm);
196
+ }
197
+
198
+ /** Build the encrypted archive in memory with path sanitization. */
45
199
  export function buildArchive(pass, root = configRoot()) {
46
200
  if (!pass) throw new Error("empty passphrase");
47
- const files = collect(root).map((rel) => {
48
- const abs = path.join(root, rel);
49
- return { path: rel, data: fs.readFileSync(abs).toString("base64"), mode: fs.statSync(abs).mode & 0o777 };
201
+ const items = collect(root);
202
+ const home = os.homedir();
203
+ const homePosix = home.replace(/\\/g, "/");
204
+
205
+ const files = items.map(({ rel, abs }) => {
206
+ const raw = fs.readFileSync(abs);
207
+ const mode = fs.statSync(abs).mode & 0o777;
208
+ let data;
209
+ if (isText(raw)) {
210
+ let str = raw.toString("utf8");
211
+ if (home) {
212
+ str = str.split(home).join(HOME_PLACEHOLDER);
213
+ if (homePosix !== home) {
214
+ str = str.split(homePosix).join(HOME_PLACEHOLDER);
215
+ }
216
+ }
217
+ data = Buffer.from(str, "utf8").toString("base64");
218
+ } else {
219
+ data = raw.toString("base64");
220
+ }
221
+ return { path: rel, data, mode };
50
222
  });
51
- const payload = { v: 1, createdAt: new Date().toISOString(), files };
223
+
224
+ const payload = {
225
+ v: 2,
226
+ createdAt: new Date().toISOString(),
227
+ sourceHome: home,
228
+ sourcePlatform: process.platform,
229
+ files,
230
+ };
231
+
52
232
  const plain = gzipSync(Buffer.from(JSON.stringify(payload)), { level: 9 });
53
233
  const salt = randomBytes(16);
54
234
  const iv = randomBytes(12);
@@ -59,10 +239,13 @@ export function buildArchive(pass, root = configRoot()) {
59
239
  return { blob, files: files.length };
60
240
  }
61
241
 
62
- /** Restore an encrypted archive buffer into the config tree. */
63
- export function restoreArchive(blob, pass, root = configRoot()) {
242
+ /** Restore an encrypted archive buffer into the config tree with adaptive remapping. */
243
+ export function restoreArchive(blob, pass, root = configRoot(), options = {}) {
64
244
  if (!pass) throw new Error("empty passphrase");
65
- if (!blob.subarray(0, MAGIC.length).equals(MAGIC)) throw new Error("not an omp-config-crypt archive");
245
+ if (!blob.subarray(0, MAGIC.length).equals(MAGIC)) {
246
+ throw new Error("not an omp-config-crypt archive");
247
+ }
248
+
66
249
  let o = MAGIC.length;
67
250
  const salt = blob.subarray(o, (o += 16));
68
251
  const iv = blob.subarray(o, (o += 12));
@@ -71,24 +254,115 @@ export function restoreArchive(blob, pass, root = configRoot()) {
71
254
  const key = scryptSync(pass, salt, 32);
72
255
  const decipher = createDecipheriv("aes-256-gcm", key, iv);
73
256
  decipher.setAuthTag(tag);
257
+
74
258
  const payload = JSON.parse(gunzipSync(Buffer.concat([decipher.update(ct), decipher.final()])).toString("utf8"));
75
- if (payload.v !== 1 || !Array.isArray(payload.files)) throw new Error("unsupported archive payload");
259
+ if (![1, 2].includes(payload.v) || !Array.isArray(payload.files)) {
260
+ throw new Error("unsupported archive payload");
261
+ }
262
+
263
+ const dryRun = Boolean(options.dryRun);
264
+ const targetHome = os.homedir();
265
+ const targetHomePosix = targetHome.replace(/\\/g, "/");
266
+ const sourceHome = payload.sourceHome;
76
267
  const backupDir = path.join(root, `.import-backup-${Date.now()}`);
268
+ const actions = [];
77
269
  let restored = 0;
270
+
78
271
  for (const f of payload.files) {
79
- const rel = String(f.path || "");
80
- if (!rel || rel.includes("..") || path.isAbsolute(rel)) throw new Error(`unsafe path in archive: ${rel}`);
81
- const dst = path.join(root, rel);
82
- if (fs.existsSync(dst)) {
83
- const b = path.join(backupDir, rel);
84
- fs.mkdirSync(path.dirname(b), { recursive: true });
85
- fs.copyFileSync(dst, b);
272
+ const rel = String(f.path || "").replace(/\\/g, "/");
273
+ if (!rel || rel.includes("..") || path.isAbsolute(rel)) {
274
+ throw new Error(`unsafe path in archive: ${rel}`);
275
+ }
276
+
277
+ const dst = resolveDestination(rel, root);
278
+ let buf = Buffer.from(f.data, "base64");
279
+ let remapped = false;
280
+
281
+ if (payload.v >= 2 && isText(buf)) {
282
+ let str = buf.toString("utf8");
283
+ const orig = str;
284
+
285
+ const isJsonOrYaml = rel.endsWith(".json") || rel.endsWith(".yml") || rel.endsWith(".yaml");
286
+ const effectiveHome = process.platform === "win32" && isJsonOrYaml ? targetHomePosix : targetHome;
287
+
288
+ str = str.split(HOME_PLACEHOLDER).join(effectiveHome);
289
+ if (sourceHome) {
290
+ str = str.split(sourceHome).join(effectiveHome);
291
+ const sourceHomePosix = sourceHome.replace(/\\/g, "/");
292
+ if (sourceHomePosix !== sourceHome) {
293
+ str = str.split(sourceHomePosix).join(effectiveHome);
294
+ }
295
+ }
296
+
297
+ if (str !== orig) {
298
+ remapped = true;
299
+ buf = Buffer.from(str, "utf8");
300
+ }
301
+ }
302
+
303
+ const exists = fs.existsSync(dst);
304
+ actions.push({ path: rel, dest: dst, exists, remapped });
305
+
306
+ if (!dryRun) {
307
+ if (exists) {
308
+ const b = path.join(backupDir, rel);
309
+ fs.mkdirSync(path.dirname(b), { recursive: true });
310
+ fs.copyFileSync(dst, b);
311
+ }
312
+ fs.mkdirSync(path.dirname(dst), { recursive: true });
313
+ fs.writeFileSync(dst, buf, { mode: f.mode || 0o600 });
314
+ }
315
+ restored++;
316
+ }
317
+
318
+ let rehydration = null;
319
+ if (options.rehydrate !== false && !dryRun) {
320
+ const hasPluginChanges = actions.some((a) => a.path.startsWith("plugins/"));
321
+ if (hasPluginChanges || options.rehydrate === true) {
322
+ rehydration = rehydratePlugins(root, options);
86
323
  }
324
+ }
325
+
326
+ return {
327
+ files: restored,
328
+ dryRun,
329
+ actions,
330
+ backupDir: !dryRun && fs.existsSync(backupDir) ? backupDir : null,
331
+ rehydration,
332
+ };
333
+ }
334
+
335
+ /** Revert the most recent config restore from its backup. */
336
+ export function rollback(root = configRoot()) {
337
+ if (!fs.existsSync(root)) throw new Error(`Root directory does not exist: ${root}`);
338
+ const entries = fs.readdirSync(root, { withFileTypes: true });
339
+ const backups = entries
340
+ .filter((e) => e.isDirectory() && e.name.startsWith(".import-backup-"))
341
+ .map((e) => e.name)
342
+ .sort()
343
+ .reverse();
344
+
345
+ if (backups.length === 0) {
346
+ throw new Error("No import backup found to rollback");
347
+ }
348
+
349
+ const latest = backups[0];
350
+ const backupDir = path.join(root, latest);
351
+ const files = walk(backupDir);
352
+ let restored = 0;
353
+
354
+ for (const rel of files) {
355
+ const src = path.join(backupDir, rel);
356
+ const dst = resolveDestination(rel, root);
87
357
  fs.mkdirSync(path.dirname(dst), { recursive: true });
88
- fs.writeFileSync(dst, Buffer.from(f.data, "base64"), { mode: f.mode || 0o600 });
358
+ fs.copyFileSync(src, dst);
89
359
  restored++;
90
360
  }
91
- return { files: restored, backupDir: fs.existsSync(backupDir) ? backupDir : null };
361
+
362
+ const rolledBackDir = path.join(root, `.rolled-back-${latest.replace(".import-backup-", "")}`);
363
+ fs.renameSync(backupDir, rolledBackDir);
364
+
365
+ return { files: restored, rolledBackFrom: latest };
92
366
  }
93
367
 
94
368
  /** Write an encrypted archive of the config tree. */
@@ -101,8 +375,8 @@ export function exportEncrypted(outFile, pass, root = configRoot()) {
101
375
  }
102
376
 
103
377
  /** Restore files from an encrypted archive, backing up overwritten ones. */
104
- export function importEncrypted(srcFile, pass, root = configRoot()) {
105
- return restoreArchive(fs.readFileSync(srcFile), pass, root);
378
+ export function importEncrypted(srcFile, pass, root = configRoot(), options = {}) {
379
+ return restoreArchive(fs.readFileSync(srcFile), pass, root, options);
106
380
  }
107
381
 
108
382
  async function askPass(ctx, title) {
@@ -124,12 +398,10 @@ async function askPass(ctx, title) {
124
398
  throw new Error("no passphrase: set OMP_CONFIG_PASS or answer the prompt");
125
399
  }
126
400
 
127
- /** Token from the environment when present. */
128
401
  function envToken() {
129
402
  return process.env.OMP_CFG_CLOUD_TOKEN || process.env.GITHUB_TOKEN || null;
130
403
  }
131
404
 
132
- /** Token from env, else asked at command time (never persisted). */
133
405
  async function askToken(ctx, title, required) {
134
406
  const fromEnv = envToken();
135
407
  if (fromEnv) return fromEnv;
@@ -137,7 +409,11 @@ async function askToken(ctx, title, required) {
137
409
  if (typeof input === "function") {
138
410
  let value;
139
411
  try {
140
- value = await input.call(ctx.ui, { title, prompt: title, placeholder: required ? "token" : "token (empty = none)" });
412
+ value = await input.call(ctx.ui, {
413
+ title,
414
+ prompt: title,
415
+ placeholder: required ? "token" : "token (empty = none)",
416
+ });
141
417
  } catch {
142
418
  try {
143
419
  value = await input.call(ctx.ui, title);
@@ -171,26 +447,27 @@ async function gh(token, pathname, init = {}) {
171
447
 
172
448
  /** Push the archive to a secret gist; returns its id and URL. */
173
449
  export async function pushGist(id, pass, root = configRoot(), token = envToken()) {
174
- if (!token) throw new Error("GitHub token required");
450
+ if (!token) throw new Error("GitHub token required: set OMP_CFG_CLOUD_TOKEN or GITHUB_TOKEN");
175
451
  const { blob, files } = buildArchive(pass, root);
176
452
  const content = blob.toString("base64");
177
453
  const body = { files: { [GIST_FILE]: { content } } };
178
- const data = id && id !== "new"
179
- ? await gh(token, `/gists/${id}`, { method: "PATCH", body: JSON.stringify(body) })
180
- : await gh(token, `/gists`, {
181
- method: "POST",
182
- body: JSON.stringify({ description: "omp config (encrypted)", public: false, ...body }),
183
- });
454
+ const data =
455
+ id && id !== "new"
456
+ ? await gh(token, `/gists/${id}`, { method: "PATCH", body: JSON.stringify(body) })
457
+ : await gh(token, `/gists`, {
458
+ method: "POST",
459
+ body: JSON.stringify({ description: "omp config (encrypted)", public: false, ...body }),
460
+ });
184
461
  return { id: data.id, url: data.html_url, files, bytes: blob.length };
185
462
  }
186
463
 
187
464
  /** Pull the archive from a secret gist. */
188
- export async function pullGist(id, pass, root = configRoot(), token = envToken()) {
189
- if (!token) throw new Error("GitHub token required");
465
+ export async function pullGist(id, pass, root = configRoot(), token = envToken(), options = {}) {
466
+ if (!token) throw new Error("GitHub token required: set OMP_CFG_CLOUD_TOKEN or GITHUB_TOKEN");
190
467
  const data = await gh(token, `/gists/${id}`);
191
468
  const content = data?.files?.[GIST_FILE]?.content;
192
469
  if (!content) throw new Error(`gist ${id} has no ${GIST_FILE}`);
193
- return restoreArchive(Buffer.from(content, "base64"), pass, root);
470
+ return restoreArchive(Buffer.from(content, "base64"), pass, root, options);
194
471
  }
195
472
 
196
473
  /** Push to any endpoint accepting PUT (presigned S3, WebDAV, custom). */
@@ -209,21 +486,28 @@ export async function pushHttp(url, pass, root = configRoot(), token = envToken(
209
486
  }
210
487
 
211
488
  /** Pull from any endpoint serving the archive. */
212
- export async function pullHttp(url, pass, root = configRoot(), token = envToken()) {
489
+ export async function pullHttp(url, pass, root = configRoot(), token = envToken(), options = {}) {
213
490
  const res = await fetch(url, {
214
491
  signal: AbortSignal.timeout(30_000),
215
492
  headers: token ? { authorization: `Bearer ${token}` } : {},
216
493
  });
217
494
  if (!res.ok) throw new Error(`GET ${res.status}: ${(await res.text()).slice(0, 200)}`);
218
- return restoreArchive(Buffer.from(await res.arrayBuffer()), pass, root);
495
+ return restoreArchive(Buffer.from(await res.arrayBuffer()), pass, root, options);
219
496
  }
220
497
 
221
- function parseSpec(spec) {
222
- if (spec.startsWith("gist:")) return { kind: "gist", id: spec.slice(5) || "new" };
223
- if (/^https?:\/\//.test(spec)) return { kind: "http", url: spec };
498
+ export function parseSpec(spec) {
499
+ const s = spec.trim();
500
+ if (s.startsWith("gist:")) return { kind: "gist", id: s.slice(5) || "new" };
501
+ if (/^https?:\/\//.test(s)) return { kind: "http", url: s };
224
502
  throw new Error("expected gist:<id|new> or an https URL");
225
503
  }
226
504
 
505
+ function extractDryRun(str) {
506
+ const dryRun = /\b--dry-run\b/i.test(str);
507
+ const clean = str.replace(/\b--dry-run\b/gi, "").trim();
508
+ return { dryRun, clean };
509
+ }
510
+
227
511
  /** Plugin entry: local and cloud config portability. */
228
512
  export default function (pi) {
229
513
  pi.registerCommand("config-export", {
@@ -241,17 +525,21 @@ export default function (pi) {
241
525
  });
242
526
 
243
527
  pi.registerCommand("config-import", {
244
- description: "Decrypt and restore an omp config archive",
528
+ description: "Decrypt and restore an omp config archive (--dry-run to preview)",
245
529
  handler: async (args, ctx) => {
246
- const src = (args || "").trim();
530
+ const { dryRun, clean: src } = extractDryRun(args || "");
247
531
  if (!src) {
248
- ctx.ui.notify("usage: /config-import <file.enc>", "error");
532
+ ctx.ui.notify("usage: /config-import <file.enc> [--dry-run]", "error");
249
533
  return;
250
534
  }
251
535
  try {
252
536
  const pass = await askPass(ctx, "Import passphrase");
253
- const r = importEncrypted(src, pass);
254
- ctx.ui.notify(`restored ${r.files} files${r.backupDir ? ` (backup: ${r.backupDir})` : ""}; restart omp`, "info");
537
+ const r = importEncrypted(src, pass, configRoot(), { dryRun });
538
+ if (dryRun) {
539
+ ctx.ui.notify(`[dry-run] would restore ${r.files} files; 0 written`, "info");
540
+ } else {
541
+ ctx.ui.notify(`restored ${r.files} files${r.backupDir ? ` (backup: ${r.backupDir})` : ""}; restart omp`, "info");
542
+ }
255
543
  } catch (error) {
256
544
  ctx.ui.notify(`config-import failed: ${error?.message ?? error}`, "error");
257
545
  }
@@ -282,11 +570,11 @@ export default function (pi) {
282
570
  });
283
571
 
284
572
  pi.registerCommand("config-pull", {
285
- description: "Download and decrypt config from gist:<id> or an https URL",
573
+ description: "Download and decrypt config from gist:<id> or an https URL (--dry-run to preview)",
286
574
  handler: async (args, ctx) => {
287
- const spec = (args || "").trim();
575
+ const { dryRun, clean: spec } = extractDryRun(args || "");
288
576
  if (!spec) {
289
- ctx.ui.notify("usage: /config-pull gist:<id> | https://…", "error");
577
+ ctx.ui.notify("usage: /config-pull gist:<id> | https://… [--dry-run]", "error");
290
578
  return;
291
579
  }
292
580
  try {
@@ -294,12 +582,30 @@ export default function (pi) {
294
582
  const pass = await askPass(ctx, "Pull passphrase");
295
583
  const token = await askToken(ctx, "Cloud token", target.kind === "gist");
296
584
  const r = target.kind === "gist"
297
- ? await pullGist(target.id, pass, configRoot(), token)
298
- : await pullHttp(target.url, pass, configRoot(), token);
299
- ctx.ui.notify(`restored ${r.files} files${r.backupDir ? ` (backup: ${r.backupDir})` : ""}; restart omp`, "info");
585
+ ? await pullGist(target.id, pass, configRoot(), token, { dryRun })
586
+ : await pullHttp(target.url, pass, configRoot(), token, { dryRun });
587
+ if (dryRun) {
588
+ ctx.ui.notify(`[dry-run] would restore ${r.files} files; 0 written`, "info");
589
+ } else {
590
+ const rehydratedCount = r.rehydration?.rehydrated ?? 0;
591
+ const rehydratedMsg = rehydratedCount > 0 ? `, rehydrated ${rehydratedCount} plugins` : "";
592
+ ctx.ui.notify(`restored ${r.files} files${rehydratedMsg}${r.backupDir ? ` (backup: ${r.backupDir})` : ""}; restart omp`, "info");
593
+ }
300
594
  } catch (error) {
301
595
  ctx.ui.notify(`config-pull failed: ${error?.message ?? error}`, "error");
302
596
  }
303
597
  },
304
598
  });
599
+
600
+ pi.registerCommand("config-rollback", {
601
+ description: "Revert the latest config restore from its backup snapshot",
602
+ handler: async (_args, ctx) => {
603
+ try {
604
+ const r = rollback(configRoot());
605
+ ctx.ui.notify(`rolled back ${r.files} files from ${r.rolledBackFrom}`, "info");
606
+ } catch (error) {
607
+ ctx.ui.notify(`config-rollback failed: ${error?.message ?? error}`, "error");
608
+ }
609
+ },
610
+ });
305
611
  }
package/package.json CHANGED
@@ -1,19 +1,29 @@
1
1
  {
2
2
  "name": "omp-config-crypt",
3
- "version": "0.3.0",
4
- "description": "Encrypted export/import of omp config and instructions",
3
+ "version": "0.4.0",
4
+ "description": "Universal cross-platform encrypted portability for omp config, extensions, and instructions",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
+ "bin": {
8
+ "omp-sync": "./bin/omp-sync.js"
9
+ },
10
+ "scripts": {
11
+ "test": "node test/sync-portable.test.mjs"
12
+ },
7
13
  "keywords": [
8
14
  "omp",
9
15
  "oh-my-pi",
10
16
  "plugin",
11
17
  "config",
12
18
  "sync",
13
- "encryption"
19
+ "encryption",
20
+ "cross-platform",
21
+ "portable"
14
22
  ],
15
23
  "files": [
16
24
  "index.js",
25
+ "src",
26
+ "bin",
17
27
  "README.md",
18
28
  "LICENSE"
19
29
  ],
@@ -0,0 +1,220 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import os from "node:os";
4
+ import { execFileSync } from "node:child_process";
5
+ import { ompHome } from "../index.js";
6
+
7
+ const LINKS_FILE = ".plugin-links.json";
8
+
9
+ /**
10
+ * Scan plugins directory node_modules for symlinks and return a map of name -> targetPath.
11
+ */
12
+ export function getPluginLinks(pluginsDir) {
13
+ const nodeModules = path.join(pluginsDir, "node_modules");
14
+ const links = {};
15
+ if (!fs.existsSync(nodeModules)) return links;
16
+
17
+ function scan(dir, prefix = "") {
18
+ let entries = [];
19
+ try {
20
+ entries = fs.readdirSync(dir, { withFileTypes: true });
21
+ } catch {
22
+ return;
23
+ }
24
+ for (const ent of entries) {
25
+ const full = path.join(dir, ent.name);
26
+ if (ent.isSymbolicLink()) {
27
+ try {
28
+ const target = fs.realpathSync(full);
29
+ const pkgName = prefix ? `${prefix}/${ent.name}` : ent.name;
30
+ links[pkgName] = target;
31
+ } catch {
32
+ try {
33
+ const rawTarget = fs.readlinkSync(full);
34
+ const pkgName = prefix ? `${prefix}/${ent.name}` : ent.name;
35
+ links[pkgName] = path.resolve(dir, rawTarget);
36
+ } catch {}
37
+ }
38
+ } else if (ent.isDirectory() && ent.name.startsWith("@")) {
39
+ scan(full, ent.name);
40
+ }
41
+ }
42
+ }
43
+
44
+ scan(nodeModules);
45
+ return links;
46
+ }
47
+
48
+ /**
49
+ * Persist known plugin links into .plugin-links.json.
50
+ */
51
+ export function savePluginLinks(pluginsDir, links) {
52
+ if (!links || Object.keys(links).length === 0) return;
53
+ const filePath = path.join(pluginsDir, LINKS_FILE);
54
+ try {
55
+ let existing = {};
56
+ if (fs.existsSync(filePath)) {
57
+ try {
58
+ existing = JSON.parse(fs.readFileSync(filePath, "utf8"));
59
+ } catch {}
60
+ }
61
+ const merged = { ...existing, ...links };
62
+ fs.writeFileSync(filePath, JSON.stringify(merged, null, 2), "utf8");
63
+ } catch {}
64
+ }
65
+
66
+ /**
67
+ * Detect missing or broken plugins in plugins directory.
68
+ */
69
+ export function detectMissingPlugins(pluginsDir) {
70
+ const missing = {
71
+ npmDependencies: [],
72
+ linkedPlugins: [],
73
+ };
74
+
75
+ const lockPath = path.join(pluginsDir, "omp-plugins.lock.json");
76
+ const pkgPath = path.join(pluginsDir, "package.json");
77
+ const nodeModules = path.join(pluginsDir, "node_modules");
78
+
79
+ // 1. Check npm dependencies
80
+ if (fs.existsSync(pkgPath)) {
81
+ try {
82
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
83
+ const deps = pkg.dependencies || {};
84
+ for (const dep of Object.keys(deps)) {
85
+ const depPath = path.join(nodeModules, ...dep.split("/"));
86
+ if (!fs.existsSync(depPath)) {
87
+ missing.npmDependencies.push(dep);
88
+ }
89
+ }
90
+ } catch {}
91
+ }
92
+
93
+ // 2. Check locked plugins (including links)
94
+ if (fs.existsSync(lockPath)) {
95
+ try {
96
+ const lock = JSON.parse(fs.readFileSync(lockPath, "utf8"));
97
+ const plugins = lock.plugins || {};
98
+ for (const name of Object.keys(plugins)) {
99
+ const pluginPath = path.join(nodeModules, ...name.split("/"));
100
+ let exists = false;
101
+ try {
102
+ exists = fs.existsSync(pluginPath);
103
+ } catch {}
104
+ if (!exists) {
105
+ if (!missing.npmDependencies.includes(name)) {
106
+ missing.linkedPlugins.push(name);
107
+ }
108
+ }
109
+ }
110
+ } catch {}
111
+ }
112
+
113
+ return missing;
114
+ }
115
+
116
+ /**
117
+ * Perform autonomous rehydration: npm install + link repair.
118
+ */
119
+ export function rehydratePlugins(root, options = {}) {
120
+ const pluginsDir = path.join(ompHome(root), "plugins");
121
+ const dryRun = Boolean(options.dryRun);
122
+ const results = {
123
+ rehydrated: 0,
124
+ npmInstalled: [],
125
+ linksRepaired: [],
126
+ errors: [],
127
+ };
128
+
129
+ if (!fs.existsSync(pluginsDir)) {
130
+ return results;
131
+ }
132
+
133
+ const missing = detectMissingPlugins(pluginsDir);
134
+ const pkgPath = path.join(pluginsDir, "package.json");
135
+ const lockLinksPath = path.join(pluginsDir, LINKS_FILE);
136
+
137
+ // 1. Run npm install if npm dependencies are missing or package.json exists without node_modules
138
+ const nodeModules = path.join(pluginsDir, "node_modules");
139
+ const needsNpmInstall =
140
+ fs.existsSync(pkgPath) &&
141
+ (missing.npmDependencies.length > 0 || !fs.existsSync(nodeModules));
142
+
143
+ if (needsNpmInstall) {
144
+ if (dryRun) {
145
+ results.npmInstalled.push(...missing.npmDependencies);
146
+ } else {
147
+ try {
148
+ execFileSync("npm", ["install", "--omit=dev", "--no-audit", "--no-fund"], {
149
+ cwd: pluginsDir,
150
+ stdio: "pipe",
151
+ timeout: 60000,
152
+ });
153
+ results.npmInstalled.push(...missing.npmDependencies);
154
+ } catch (err) {
155
+ results.errors.push(`npm install failed: ${err.message}`);
156
+ }
157
+ }
158
+ }
159
+
160
+ // 2. Load stored link targets
161
+ let storedLinks = {};
162
+ if (fs.existsSync(lockLinksPath)) {
163
+ try {
164
+ storedLinks = JSON.parse(fs.readFileSync(lockLinksPath, "utf8"));
165
+ } catch {}
166
+ }
167
+
168
+ // Known candidate fallback directories for common local plugins
169
+ const candidateDirs = {
170
+ "@omp/plugin-rsi": ["/opt/project/omp-rsi", path.join(os.homedir(), "omp-rsi")],
171
+ "omp-config-crypt": ["/root/omp-config-crypt", path.join(os.homedir(), "omp-config-crypt")],
172
+ };
173
+
174
+ // 3. Resolve and repair linked plugins
175
+ const pluginsToLink = Array.from(
176
+ new Set([...missing.linkedPlugins, ...Object.keys(storedLinks)])
177
+ );
178
+
179
+ for (const name of pluginsToLink) {
180
+ const linkPath = path.join(nodeModules, ...name.split("/"));
181
+ let isHealthy = false;
182
+ try {
183
+ if (fs.existsSync(linkPath)) {
184
+ isHealthy = true;
185
+ }
186
+ } catch {}
187
+
188
+ if (isHealthy) continue;
189
+
190
+ // Find candidate target path
191
+ let targetDir = storedLinks[name];
192
+ if (!targetDir || !fs.existsSync(targetDir)) {
193
+ const candidates = candidateDirs[name] || [];
194
+ targetDir = candidates.find((c) => fs.existsSync(c)) || null;
195
+ }
196
+
197
+ if (!targetDir || !fs.existsSync(targetDir)) {
198
+ results.errors.push(`Target directory for plugin ${name} not found`);
199
+ continue;
200
+ }
201
+
202
+ if (dryRun) {
203
+ results.linksRepaired.push({ name, target: targetDir });
204
+ } else {
205
+ try {
206
+ fs.mkdirSync(path.dirname(linkPath), { recursive: true });
207
+ try {
208
+ fs.rmSync(linkPath, { force: true, recursive: true });
209
+ } catch {}
210
+ fs.symlinkSync(targetDir, linkPath, "dir");
211
+ results.linksRepaired.push({ name, target: targetDir });
212
+ } catch (err) {
213
+ results.errors.push(`Failed to link ${name} -> ${targetDir}: ${err.message}`);
214
+ }
215
+ }
216
+ }
217
+
218
+ results.rehydrated = results.npmInstalled.length + results.linksRepaired.length;
219
+ return results;
220
+ }