omp-config-crypt 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,236 @@
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
+ /\.local\./,
47
+ /\.local\//,
48
+ /^\.import-backup/,
49
+ /\/\.import-backup/,
50
+ /^\.rolled-back/,
51
+ /\/\.rolled-back/,
52
+ /(^|\/)\.git\//,
53
+ /(^|\/)cache\//,
54
+ /(^|\/)blobs\//,
55
+ /(^|\/)sessions\//,
56
+ /(^|\/)terminal-sessions\//,
57
+ /(^|\/)predict\//,
58
+ /(^|\/)node_modules\//,
59
+ ];
15
60
 
16
61
  /** User agent directory, or OMP_CFG_ROOT for tests. */
17
62
  export function configRoot() {
18
63
  return process.env.OMP_CFG_ROOT || path.join(os.homedir(), ".omp", "agent");
19
64
  }
20
65
 
66
+ /** Root .omp folder (parent of agent directory). */
67
+ export function ompHome(root = configRoot()) {
68
+ return process.env.OMP_HOME || path.dirname(root);
69
+ }
70
+
71
+ function shouldIgnore(relPath) {
72
+ const norm = relPath.replace(/\\/g, "/");
73
+ return BLACKLIST_PATTERNS.some((rx) => rx.test(norm));
74
+ }
75
+
76
+ function isText(buf) {
77
+ const len = Math.min(buf.length, 1024);
78
+ for (let i = 0; i < len; i++) {
79
+ if (buf[i] === 0) return false;
80
+ }
81
+ return true;
82
+ }
83
+
21
84
  function walk(dir, prefix = "") {
22
85
  const out = [];
86
+ if (!fs.existsSync(dir)) return out;
23
87
  for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
24
88
  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);
89
+ const abs = path.join(dir, ent.name);
90
+ if (ent.isDirectory()) {
91
+ if (!shouldIgnore(rel + "/")) {
92
+ out.push(...walk(abs, rel));
93
+ }
94
+ } else if (ent.isFile()) {
95
+ if (!shouldIgnore(rel)) {
96
+ out.push(rel);
97
+ }
98
+ }
27
99
  }
28
100
  return out;
29
101
  }
30
102
 
31
- function collect(root) {
103
+ export function collect(root) {
32
104
  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);
105
+ const seen = new Set();
106
+
107
+ function addItem(rel, abs) {
108
+ const norm = rel.replace(/\\/g, "/");
109
+ if (!seen.has(norm) && !shouldIgnore(norm) && fs.existsSync(abs) && fs.statSync(abs).isFile()) {
110
+ seen.add(norm);
111
+ out.push({ rel: norm, abs });
112
+ }
113
+ }
114
+
115
+ // 1. Files directly under root (agent/)
116
+ if (fs.existsSync(root)) {
117
+ for (const ent of fs.readdirSync(root, { withFileTypes: true })) {
118
+ if (ent.isFile()) {
119
+ const name = ent.name;
120
+ const isCore = FILES.includes(name);
121
+ const isToken = name.includes("token");
122
+ const isExtra = name.endsWith(".yml") || name.endsWith(".yaml") || name.endsWith(".json");
123
+ if (isCore || isToken || isExtra) {
124
+ addItem(name, path.join(root, name));
125
+ }
126
+ }
127
+ }
128
+
129
+ // 2. Category directories under root (memories, managed-skills)
130
+ for (const d of DIRS) {
131
+ const base = path.join(root, d);
132
+ if (fs.existsSync(base)) {
133
+ for (const file of walk(base)) {
134
+ addItem(`${d}/${file}`, path.join(base, file));
135
+ }
136
+ }
137
+ }
138
+ }
139
+
140
+ // 3. User extensions under ~/.omp/extensions/ (sibling to agent/)
141
+ const ompDir = ompHome(root);
142
+ const extDir = path.join(ompDir, "extensions");
143
+ if (fs.existsSync(extDir) && fs.statSync(extDir).isDirectory()) {
144
+ for (const file of walk(extDir)) {
145
+ addItem(`extensions/${file}`, path.join(extDir, file));
146
+ }
147
+ }
148
+
149
+ // 4. Installed plugins lockfile & manifest under ~/.omp/plugins/
150
+ const pluginsDir = path.join(ompDir, "plugins");
151
+ const links = getPluginLinks(pluginsDir);
152
+ if (Object.keys(links).length > 0) {
153
+ savePluginLinks(pluginsDir, links);
154
+ }
155
+ const linksFile = path.join(pluginsDir, ".plugin-links.json");
156
+ if (fs.existsSync(linksFile) && fs.statSync(linksFile).isFile()) {
157
+ addItem("plugins/.plugin-links.json", linksFile);
158
+ }
159
+ const lockFile = path.join(pluginsDir, "omp-plugins.lock.json");
160
+ if (fs.existsSync(lockFile) && fs.statSync(lockFile).isFile()) {
161
+ addItem("plugins/omp-plugins.lock.json", lockFile);
162
+ }
163
+ const pluginPkg = path.join(pluginsDir, "package.json");
164
+ if (fs.existsSync(pluginPkg) && fs.statSync(pluginPkg).isFile()) {
165
+ addItem("plugins/package.json", pluginPkg);
166
+ }
167
+ // 5. Global tools under ~/.omp/tools/
168
+ const toolsDir = path.join(ompDir, "tools");
169
+ if (fs.existsSync(toolsDir) && fs.statSync(toolsDir).isDirectory()) {
170
+ for (const file of walk(toolsDir)) {
171
+ addItem(`tools/${file}`, path.join(toolsDir, file));
172
+ }
36
173
  }
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}`);
174
+
175
+ // 6. Global hooks under ~/.omp/hooks/
176
+ const hooksDir = path.join(ompDir, "hooks");
177
+ if (fs.existsSync(hooksDir) && fs.statSync(hooksDir).isDirectory()) {
178
+ for (const file of walk(hooksDir)) {
179
+ addItem(`hooks/${file}`, path.join(hooksDir, file));
180
+ }
40
181
  }
182
+
41
183
  return out;
42
184
  }
43
185
 
44
- /** Build the encrypted archive in memory. */
186
+ /** Determine target path for relative archive key. */
187
+ export function resolveDestination(rel, root = configRoot()) {
188
+ const norm = rel.replace(/\\/g, "/");
189
+ if (
190
+ norm.startsWith("extensions/") ||
191
+ norm.startsWith("plugins/") ||
192
+ norm.startsWith("tools/") ||
193
+ norm.startsWith("hooks/")
194
+ ) {
195
+ return path.join(ompHome(root), norm);
196
+ }
197
+ return path.join(root, norm);
198
+ }
199
+
200
+ /** Build the encrypted archive in memory with path sanitization. */
45
201
  export function buildArchive(pass, root = configRoot()) {
46
202
  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 };
203
+ const items = collect(root);
204
+ const home = os.homedir();
205
+ const homePosix = home.replace(/\\/g, "/");
206
+
207
+ const files = items.map(({ rel, abs }) => {
208
+ const raw = fs.readFileSync(abs);
209
+ const mode = fs.statSync(abs).mode & 0o777;
210
+ let data;
211
+ if (isText(raw)) {
212
+ let str = raw.toString("utf8");
213
+ if (home) {
214
+ str = str.split(home).join(HOME_PLACEHOLDER);
215
+ if (homePosix !== home) {
216
+ str = str.split(homePosix).join(HOME_PLACEHOLDER);
217
+ }
218
+ }
219
+ data = Buffer.from(str, "utf8").toString("base64");
220
+ } else {
221
+ data = raw.toString("base64");
222
+ }
223
+ return { path: rel, data, mode };
50
224
  });
51
- const payload = { v: 1, createdAt: new Date().toISOString(), files };
225
+
226
+ const payload = {
227
+ v: 2,
228
+ createdAt: new Date().toISOString(),
229
+ sourceHome: home,
230
+ sourcePlatform: process.platform,
231
+ files,
232
+ };
233
+
52
234
  const plain = gzipSync(Buffer.from(JSON.stringify(payload)), { level: 9 });
53
235
  const salt = randomBytes(16);
54
236
  const iv = randomBytes(12);
@@ -59,10 +241,13 @@ export function buildArchive(pass, root = configRoot()) {
59
241
  return { blob, files: files.length };
60
242
  }
61
243
 
62
- /** Restore an encrypted archive buffer into the config tree. */
63
- export function restoreArchive(blob, pass, root = configRoot()) {
244
+ /** Restore an encrypted archive buffer into the config tree with adaptive remapping. */
245
+ export function restoreArchive(blob, pass, root = configRoot(), options = {}) {
64
246
  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");
247
+ if (!blob.subarray(0, MAGIC.length).equals(MAGIC)) {
248
+ throw new Error("not an omp-config-crypt archive");
249
+ }
250
+
66
251
  let o = MAGIC.length;
67
252
  const salt = blob.subarray(o, (o += 16));
68
253
  const iv = blob.subarray(o, (o += 12));
@@ -71,24 +256,115 @@ export function restoreArchive(blob, pass, root = configRoot()) {
71
256
  const key = scryptSync(pass, salt, 32);
72
257
  const decipher = createDecipheriv("aes-256-gcm", key, iv);
73
258
  decipher.setAuthTag(tag);
259
+
74
260
  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");
261
+ if (![1, 2].includes(payload.v) || !Array.isArray(payload.files)) {
262
+ throw new Error("unsupported archive payload");
263
+ }
264
+
265
+ const dryRun = Boolean(options.dryRun);
266
+ const targetHome = os.homedir();
267
+ const targetHomePosix = targetHome.replace(/\\/g, "/");
268
+ const sourceHome = payload.sourceHome;
76
269
  const backupDir = path.join(root, `.import-backup-${Date.now()}`);
270
+ const actions = [];
77
271
  let restored = 0;
272
+
78
273
  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);
274
+ const rel = String(f.path || "").replace(/\\/g, "/");
275
+ if (!rel || rel.includes("..") || path.isAbsolute(rel)) {
276
+ throw new Error(`unsafe path in archive: ${rel}`);
277
+ }
278
+
279
+ const dst = resolveDestination(rel, root);
280
+ let buf = Buffer.from(f.data, "base64");
281
+ let remapped = false;
282
+
283
+ if (payload.v >= 2 && isText(buf)) {
284
+ let str = buf.toString("utf8");
285
+ const orig = str;
286
+
287
+ const isJsonOrYaml = rel.endsWith(".json") || rel.endsWith(".yml") || rel.endsWith(".yaml");
288
+ const effectiveHome = process.platform === "win32" && isJsonOrYaml ? targetHomePosix : targetHome;
289
+
290
+ str = str.split(HOME_PLACEHOLDER).join(effectiveHome);
291
+ if (sourceHome) {
292
+ str = str.split(sourceHome).join(effectiveHome);
293
+ const sourceHomePosix = sourceHome.replace(/\\/g, "/");
294
+ if (sourceHomePosix !== sourceHome) {
295
+ str = str.split(sourceHomePosix).join(effectiveHome);
296
+ }
297
+ }
298
+
299
+ if (str !== orig) {
300
+ remapped = true;
301
+ buf = Buffer.from(str, "utf8");
302
+ }
303
+ }
304
+
305
+ const exists = fs.existsSync(dst);
306
+ actions.push({ path: rel, dest: dst, exists, remapped });
307
+
308
+ if (!dryRun) {
309
+ if (exists) {
310
+ const b = path.join(backupDir, rel);
311
+ fs.mkdirSync(path.dirname(b), { recursive: true });
312
+ fs.copyFileSync(dst, b);
313
+ }
314
+ fs.mkdirSync(path.dirname(dst), { recursive: true });
315
+ fs.writeFileSync(dst, buf, { mode: f.mode || 0o600 });
316
+ }
317
+ restored++;
318
+ }
319
+
320
+ let rehydration = null;
321
+ if (options.rehydrate !== false && !dryRun) {
322
+ const hasPluginChanges = actions.some((a) => a.path.startsWith("plugins/"));
323
+ if (hasPluginChanges || options.rehydrate === true) {
324
+ rehydration = rehydratePlugins(root, options);
86
325
  }
326
+ }
327
+
328
+ return {
329
+ files: restored,
330
+ dryRun,
331
+ actions,
332
+ backupDir: !dryRun && fs.existsSync(backupDir) ? backupDir : null,
333
+ rehydration,
334
+ };
335
+ }
336
+
337
+ /** Revert the most recent config restore from its backup. */
338
+ export function rollback(root = configRoot()) {
339
+ if (!fs.existsSync(root)) throw new Error(`Root directory does not exist: ${root}`);
340
+ const entries = fs.readdirSync(root, { withFileTypes: true });
341
+ const backups = entries
342
+ .filter((e) => e.isDirectory() && e.name.startsWith(".import-backup-"))
343
+ .map((e) => e.name)
344
+ .sort()
345
+ .reverse();
346
+
347
+ if (backups.length === 0) {
348
+ throw new Error("No import backup found to rollback");
349
+ }
350
+
351
+ const latest = backups[0];
352
+ const backupDir = path.join(root, latest);
353
+ const files = walk(backupDir);
354
+ let restored = 0;
355
+
356
+ for (const rel of files) {
357
+ const src = path.join(backupDir, rel);
358
+ const dst = resolveDestination(rel, root);
87
359
  fs.mkdirSync(path.dirname(dst), { recursive: true });
88
- fs.writeFileSync(dst, Buffer.from(f.data, "base64"), { mode: f.mode || 0o600 });
360
+ fs.copyFileSync(src, dst);
89
361
  restored++;
90
362
  }
91
- return { files: restored, backupDir: fs.existsSync(backupDir) ? backupDir : null };
363
+
364
+ const rolledBackDir = path.join(root, `.rolled-back-${latest.replace(".import-backup-", "")}`);
365
+ fs.renameSync(backupDir, rolledBackDir);
366
+
367
+ return { files: restored, rolledBackFrom: latest };
92
368
  }
93
369
 
94
370
  /** Write an encrypted archive of the config tree. */
@@ -101,8 +377,8 @@ export function exportEncrypted(outFile, pass, root = configRoot()) {
101
377
  }
102
378
 
103
379
  /** 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);
380
+ export function importEncrypted(srcFile, pass, root = configRoot(), options = {}) {
381
+ return restoreArchive(fs.readFileSync(srcFile), pass, root, options);
106
382
  }
107
383
 
108
384
  async function askPass(ctx, title) {
@@ -124,12 +400,10 @@ async function askPass(ctx, title) {
124
400
  throw new Error("no passphrase: set OMP_CONFIG_PASS or answer the prompt");
125
401
  }
126
402
 
127
- /** Token from the environment when present. */
128
403
  function envToken() {
129
404
  return process.env.OMP_CFG_CLOUD_TOKEN || process.env.GITHUB_TOKEN || null;
130
405
  }
131
406
 
132
- /** Token from env, else asked at command time (never persisted). */
133
407
  async function askToken(ctx, title, required) {
134
408
  const fromEnv = envToken();
135
409
  if (fromEnv) return fromEnv;
@@ -137,7 +411,11 @@ async function askToken(ctx, title, required) {
137
411
  if (typeof input === "function") {
138
412
  let value;
139
413
  try {
140
- value = await input.call(ctx.ui, { title, prompt: title, placeholder: required ? "token" : "token (empty = none)" });
414
+ value = await input.call(ctx.ui, {
415
+ title,
416
+ prompt: title,
417
+ placeholder: required ? "token" : "token (empty = none)",
418
+ });
141
419
  } catch {
142
420
  try {
143
421
  value = await input.call(ctx.ui, title);
@@ -171,26 +449,27 @@ async function gh(token, pathname, init = {}) {
171
449
 
172
450
  /** Push the archive to a secret gist; returns its id and URL. */
173
451
  export async function pushGist(id, pass, root = configRoot(), token = envToken()) {
174
- if (!token) throw new Error("GitHub token required");
452
+ if (!token) throw new Error("GitHub token required: set OMP_CFG_CLOUD_TOKEN or GITHUB_TOKEN");
175
453
  const { blob, files } = buildArchive(pass, root);
176
454
  const content = blob.toString("base64");
177
455
  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
- });
456
+ const data =
457
+ id && id !== "new"
458
+ ? await gh(token, `/gists/${id}`, { method: "PATCH", body: JSON.stringify(body) })
459
+ : await gh(token, `/gists`, {
460
+ method: "POST",
461
+ body: JSON.stringify({ description: "omp config (encrypted)", public: false, ...body }),
462
+ });
184
463
  return { id: data.id, url: data.html_url, files, bytes: blob.length };
185
464
  }
186
465
 
187
466
  /** 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");
467
+ export async function pullGist(id, pass, root = configRoot(), token = envToken(), options = {}) {
468
+ if (!token) throw new Error("GitHub token required: set OMP_CFG_CLOUD_TOKEN or GITHUB_TOKEN");
190
469
  const data = await gh(token, `/gists/${id}`);
191
470
  const content = data?.files?.[GIST_FILE]?.content;
192
471
  if (!content) throw new Error(`gist ${id} has no ${GIST_FILE}`);
193
- return restoreArchive(Buffer.from(content, "base64"), pass, root);
472
+ return restoreArchive(Buffer.from(content, "base64"), pass, root, options);
194
473
  }
195
474
 
196
475
  /** Push to any endpoint accepting PUT (presigned S3, WebDAV, custom). */
@@ -209,21 +488,28 @@ export async function pushHttp(url, pass, root = configRoot(), token = envToken(
209
488
  }
210
489
 
211
490
  /** Pull from any endpoint serving the archive. */
212
- export async function pullHttp(url, pass, root = configRoot(), token = envToken()) {
491
+ export async function pullHttp(url, pass, root = configRoot(), token = envToken(), options = {}) {
213
492
  const res = await fetch(url, {
214
493
  signal: AbortSignal.timeout(30_000),
215
494
  headers: token ? { authorization: `Bearer ${token}` } : {},
216
495
  });
217
496
  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);
497
+ return restoreArchive(Buffer.from(await res.arrayBuffer()), pass, root, options);
219
498
  }
220
499
 
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 };
500
+ export function parseSpec(spec) {
501
+ const s = spec.trim();
502
+ if (s.startsWith("gist:")) return { kind: "gist", id: s.slice(5) || "new" };
503
+ if (/^https?:\/\//.test(s)) return { kind: "http", url: s };
224
504
  throw new Error("expected gist:<id|new> or an https URL");
225
505
  }
226
506
 
507
+ function extractDryRun(str) {
508
+ const dryRun = /\b--dry-run\b/i.test(str);
509
+ const clean = str.replace(/\b--dry-run\b/gi, "").trim();
510
+ return { dryRun, clean };
511
+ }
512
+
227
513
  /** Plugin entry: local and cloud config portability. */
228
514
  export default function (pi) {
229
515
  pi.registerCommand("config-export", {
@@ -241,17 +527,21 @@ export default function (pi) {
241
527
  });
242
528
 
243
529
  pi.registerCommand("config-import", {
244
- description: "Decrypt and restore an omp config archive",
530
+ description: "Decrypt and restore an omp config archive (--dry-run to preview)",
245
531
  handler: async (args, ctx) => {
246
- const src = (args || "").trim();
532
+ const { dryRun, clean: src } = extractDryRun(args || "");
247
533
  if (!src) {
248
- ctx.ui.notify("usage: /config-import <file.enc>", "error");
534
+ ctx.ui.notify("usage: /config-import <file.enc> [--dry-run]", "error");
249
535
  return;
250
536
  }
251
537
  try {
252
538
  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");
539
+ const r = importEncrypted(src, pass, configRoot(), { dryRun });
540
+ if (dryRun) {
541
+ ctx.ui.notify(`[dry-run] would restore ${r.files} files; 0 written`, "info");
542
+ } else {
543
+ ctx.ui.notify(`restored ${r.files} files${r.backupDir ? ` (backup: ${r.backupDir})` : ""}; restart omp`, "info");
544
+ }
255
545
  } catch (error) {
256
546
  ctx.ui.notify(`config-import failed: ${error?.message ?? error}`, "error");
257
547
  }
@@ -282,11 +572,11 @@ export default function (pi) {
282
572
  });
283
573
 
284
574
  pi.registerCommand("config-pull", {
285
- description: "Download and decrypt config from gist:<id> or an https URL",
575
+ description: "Download and decrypt config from gist:<id> or an https URL (--dry-run to preview)",
286
576
  handler: async (args, ctx) => {
287
- const spec = (args || "").trim();
577
+ const { dryRun, clean: spec } = extractDryRun(args || "");
288
578
  if (!spec) {
289
- ctx.ui.notify("usage: /config-pull gist:<id> | https://…", "error");
579
+ ctx.ui.notify("usage: /config-pull gist:<id> | https://… [--dry-run]", "error");
290
580
  return;
291
581
  }
292
582
  try {
@@ -294,12 +584,30 @@ export default function (pi) {
294
584
  const pass = await askPass(ctx, "Pull passphrase");
295
585
  const token = await askToken(ctx, "Cloud token", target.kind === "gist");
296
586
  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");
587
+ ? await pullGist(target.id, pass, configRoot(), token, { dryRun })
588
+ : await pullHttp(target.url, pass, configRoot(), token, { dryRun });
589
+ if (dryRun) {
590
+ ctx.ui.notify(`[dry-run] would restore ${r.files} files; 0 written`, "info");
591
+ } else {
592
+ const rehydratedCount = r.rehydration?.rehydrated ?? 0;
593
+ const rehydratedMsg = rehydratedCount > 0 ? `, rehydrated ${rehydratedCount} plugins` : "";
594
+ ctx.ui.notify(`restored ${r.files} files${rehydratedMsg}${r.backupDir ? ` (backup: ${r.backupDir})` : ""}; restart omp`, "info");
595
+ }
300
596
  } catch (error) {
301
597
  ctx.ui.notify(`config-pull failed: ${error?.message ?? error}`, "error");
302
598
  }
303
599
  },
304
600
  });
601
+
602
+ pi.registerCommand("config-rollback", {
603
+ description: "Revert the latest config restore from its backup snapshot",
604
+ handler: async (_args, ctx) => {
605
+ try {
606
+ const r = rollback(configRoot());
607
+ ctx.ui.notify(`rolled back ${r.files} files from ${r.rolledBackFrom}`, "info");
608
+ } catch (error) {
609
+ ctx.ui.notify(`config-rollback failed: ${error?.message ?? error}`, "error");
610
+ }
611
+ },
612
+ });
305
613
  }
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.1",
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
+ }