mirror of
https://github.com/dtzp555-max/ocp.git
synced 2026-07-21 21:15:09 +00:00
Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
49c6d32e3b | ||
|
|
7766fa0868 | ||
|
|
70faeff067 | ||
|
|
7a69d72886 | ||
|
|
a8601a6d30 | ||
|
|
cd6ec2a212 | ||
|
|
ab03c13332 | ||
|
|
55c576bbb1 | ||
|
|
750b25ba77 | ||
|
|
fd6e875bd7 | ||
|
|
8c0b97f3ae | ||
|
|
68acf15373 |
+147
@@ -1,5 +1,152 @@
|
||||
# Changelog
|
||||
|
||||
## v3.16.3 — 2026-05-13
|
||||
|
||||
### Fixes — completes v3.16.2 port-drift revert
|
||||
|
||||
v3.16.2 reverted the plugin / `openclaw.plugin.json` / README / Mac mini
|
||||
plist back to `3456` (the historical source default since `593d0dc`), but
|
||||
missed three places in `scripts/` that still defaulted to `3478`. Those
|
||||
three lines were the residual cascade source: every time `ocp doctor` or
|
||||
`ocp upgrade` ran without `CLAUDE_PROXY_PORT` in the env, they probed
|
||||
`3478`, reported "OCP not responding" against a healthy 3456 instance,
|
||||
and (in the case of OpenClaw sync follow-ups on the maintainer's host)
|
||||
re-introduced 3478 into downstream config.
|
||||
|
||||
Changes:
|
||||
|
||||
- `scripts/upgrade.mjs:137` — default port `3478` → `3456`.
|
||||
- `scripts/doctor.mjs:84` — default port `3478` → `3456`.
|
||||
- `scripts/doctor.mjs:205` — default port `3478` → `3456`.
|
||||
|
||||
No behavior change for users who set `CLAUDE_PROXY_PORT` explicitly; env
|
||||
still takes precedence. The fix only affects the unset-env fallback,
|
||||
which now matches `server.mjs:126` and the rest of the codebase.
|
||||
|
||||
Test plan: existing `test-features.mjs` cases that pin
|
||||
`CLAUDE_PROXY_PORT=3478` continue to pass — they use the env path, not
|
||||
the default.
|
||||
|
||||
## v3.16.2 — 2026-05-12
|
||||
|
||||
### Fixes — corrects v3.16.1
|
||||
|
||||
The v3.16.1 fix was directionally correct (plugin now reads env first, falls back to a hardcoded default) but **the narrative and the hardcoded default were both wrong**.
|
||||
|
||||
What v3.16.1 said: "OCP server moved to 3478 default in v3.14+; plugin lagged at 3456."
|
||||
What is actually true:
|
||||
- **OCP server source default has been `3456` since `593d0dc` (initial release) and has never changed.** Every line in `server.mjs`, `setup.mjs`, and the `ocp` CLI still uses `3456` as the documented and code-level default.
|
||||
- The single OCP installation observed on `3478` is the maintainer's Mac mini, whose plist was rewritten with `--port 3478` during a PR #71 dogfood smoke-test accident on 2026-05-08 (see `~/.cc-rules/memory/learnings/subagent_setup_mjs_prod_host_collision.md`). The plist drift was never reconciled back to source default, and v3.16.1 incorrectly canonised the post-accident value as if it had been a release decision.
|
||||
|
||||
This release:
|
||||
- Restores the plugin fallback to `http://127.0.0.1:3456` to match server source default.
|
||||
- Updates `openclaw.plugin.json` `configSchema.proxyUrl.default` back to `3456`.
|
||||
- Restores README §"Environment Variables" `CLAUDE_PROXY_PORT` default to `3456`.
|
||||
- Plugin reads `OCP_PROXY_URL` env (full URL) first, then `CLAUDE_PROXY_PORT` env (port only), then falls back to `3456`. Hosts whose OCP plist injects a non-default port must also inject the same `CLAUDE_PROXY_PORT` into the OpenClaw plist for the plugin to follow.
|
||||
- Maintainer's Mac mini plist was reverted from `3478` to `3456` as part of this release deploy (no source change reflects this; it was a one-host correction).
|
||||
|
||||
### Governance
|
||||
|
||||
- No `cli.js` citation needed (no `server.mjs` change). ALIGNMENT.md Rule 2 not engaged.
|
||||
|
||||
## v3.16.1 — 2026-05-12 (superseded — narrative incorrect; see v3.16.2 erratum)
|
||||
|
||||
### Fixes (as shipped — note erratum above)
|
||||
|
||||
- **OCP plugin port lag** — `ocp-plugin/index.js` hard-coded `http://127.0.0.1:3456`. ~~While OCP server moved to 3478 in v3.14+,~~ **(corrected v3.16.2: no such move ever happened.)** The Mac mini's plist was on `3478` only as residue from a dogfood accident. Result: `/ocp` slash commands from the home Telegram bot returned "OCP error: fetch failed". v3.16.1 changed the plugin default to `3478` (wrong direction; v3.16.2 reverts to `3456`).
|
||||
|
||||
### Governance
|
||||
|
||||
- No `cli.js` citation needed (no `server.mjs` change). ALIGNMENT.md Rule 2 not engaged.
|
||||
|
||||
## v3.16.0 — 2026-05-10
|
||||
|
||||
### Features
|
||||
|
||||
- **`ocp doctor --check oauth`** (PR #93) — fast path that runs only the OAuth check, skipping
|
||||
version detection / from-version / git operations / models endpoint. ~50ms vs. full doctor's
|
||||
~200-500ms. Use cases: AI agent repair loops, post-`claude auth login` verify, quick health
|
||||
gates. Help text in `cmd_doctor_help` now reflects working behaviour.
|
||||
- **`ocp update --rollback --gc`** — manually garbage-collect old upgrade snapshots.
|
||||
Retention policy: keep last 5 snapshots OR snapshots newer than 30 days OR the single most
|
||||
recent (always-keep safety net). `--dry-run` previews. Successful `ocp update` runs auto-GC
|
||||
at the end of the full path; light path does not (no snapshot created there).
|
||||
|
||||
### Behavior changes
|
||||
|
||||
- After a successful cross-minor `ocp update`, the auto-GC emits `[gc] removed N old snapshots`
|
||||
to stderr if any were collected. Safe to ignore; manual gc is `ocp update --rollback --gc`.
|
||||
|
||||
### Governance
|
||||
|
||||
- No `cli.js` citation needed (no `server.mjs` change). ALIGNMENT.md Rule 2 not engaged.
|
||||
- PR #93 (--check oauth) merged separately; this release bundles it with the GC feature.
|
||||
|
||||
## v3.15.1 — 2026-05-10
|
||||
|
||||
### Fixes
|
||||
|
||||
- **doctor: dynamic `latest_version` from `origin/main:package.json`** — v3.15.0 doctor used a hard-coded `latest = "v3.14.0"` fallback, which made any v3.15.0+ install report `kind = upgrade` (against a stale value). `ocp update` would then attempt `git checkout v3.14.0` — a downgrade. Doctor now fetches `git -C ~/ocp show origin/main:package.json` to determine the actual latest version; on failure (offline, fresh clone with no remote), falls back to `currentVersion` so `kind = noop` instead of recommending a downgrade.
|
||||
|
||||
## v3.15.0 — 2026-05-10
|
||||
|
||||
### Features
|
||||
|
||||
- **`ocp doctor`** — health & upgrade-readiness check; primary entry for AI-driven debugging.
|
||||
`--json` mode emits a `next_action` with `ai_executable[]` for agents to run verbatim
|
||||
and `human_required[]` for steps requiring the user (typically only OAuth).
|
||||
- **`ocp update` cross-version path** — for cross-minor jumps (e.g. v3.10 → v3.14),
|
||||
`ocp update` now runs doctor → snapshot → `setup.mjs` (with the plist env-merge from
|
||||
PR #90) → service restart → post-flight `/health` + `/v1/models` verification.
|
||||
Same-patch updates retain the existing light path; users see no change for routine
|
||||
patch bumps.
|
||||
- **`ocp update --rollback`** — restore the most recent (or specified) upgrade snapshot.
|
||||
Snapshots are saved to `~/.ocp/upgrade-snapshot-<ISO-ts>/` and never auto-deleted.
|
||||
- **Fresh-install routing** — `ocp update` on installations < v3.4.0 routes to a fresh-install
|
||||
flow (with `--yes` to skip confirmation; AI agents pass this). OAuth survives via Claude
|
||||
Code's credential store; users do not re-OAuth unless their token was independently broken.
|
||||
- **AI prompt blocks in README** — §Installation, §Upgrading, and §Troubleshooting each
|
||||
start with a copy-paste prompt for Claude Code / Cursor / Copilot, so users can drive
|
||||
install / setup / upgrade through their existing AI assistant.
|
||||
|
||||
### Behavior changes
|
||||
|
||||
- `ocp update` may take 10–30s longer when a cross-minor jump triggers the full path
|
||||
(snapshot + post-flight). Patch bumps are unchanged.
|
||||
- Pre-v3.4.0 installs are routed to fresh-install rather than failing silently or
|
||||
half-migrating.
|
||||
|
||||
### Governance
|
||||
|
||||
- No `cli.js` citation needed (no `server.mjs` change). ALIGNMENT.md Rule 2 not engaged.
|
||||
- Depends on PR #90 (plist env merge bug fix; merged before this release).
|
||||
|
||||
## v3.14.0 — 2026-05-10
|
||||
|
||||
### Features (security hardening)
|
||||
|
||||
- **Per-key session isolation** (PR #86, S1) — the `sessions` Map in `server.mjs` is now keyed by `${keyName}|${conversationId}` instead of bare `conversationId`. Before this fix, two clients using distinct API keys but the same `session_id` value (e.g. both defaulting to `"default"`) would share the same `cli.js` subprocess and conversation history, creating a cross-tenant leak path. Post-fix each (key, session) pair is isolated end-to-end, extending the per-key cache isolation shipped in v3.13.0 D1 to the session layer.
|
||||
- **On-disk credential file modes 0700/0600** (PR #87, S2) — `setup.mjs` now creates `~/.ocp` at mode 0700 and both `admin-key` and `ocp.db` at mode 0600. An idempotent `reconcileFileModes()` call in `server.mjs` startup tightens any existing installation to these modes automatically on every launch, so existing prod boxes fix themselves without manual `chmod`. Before this fix, all three files were created at the process's default umask (typically world-readable 0644 / 0755), leaving plaintext credentials readable by other local users.
|
||||
- **`/api/usage` default scope = self; admin all-keys requires `?all=true`** (PR #88, S3) — the usage endpoint now applies a least-privilege default: anonymous callers receive only their own rows, non-admin authenticated callers receive only their own rows, and admin callers receive only their own rows unless they explicitly pass `?all=true`. When `?all=true` is used, an audit log line is emitted. Before this fix, any admin-token holder could silently enumerate usage data for every key on the server.
|
||||
|
||||
### Behavior changes
|
||||
|
||||
- **Breaking change for admin tooling**: `/api/usage` no longer returns all-keys data by default. Existing cron jobs, dashboards, or scripts that rely on the admin token seeing all-keys output must add `?all=true` to their request URL after upgrading to v3.14.0.
|
||||
- **File mode reconcile at server startup** logs a one-line notice per path when mode is tightened (e.g. `[security] tightened ~/.ocp/ocp.db → 0600`). No action is required from the operator; the reconcile is idempotent and silent when modes are already correct.
|
||||
- **`sessions` Map key is now `${keyName}|${conversationId}` internally.** No client-visible wire change — the `session_id` field in request/response is unchanged.
|
||||
|
||||
### Verification
|
||||
|
||||
- Stress-test pass: 11/11 phases including S1/S2/S3 security regression checks (Phase E, I, J). 35-minute sustained run, 60 calls, 0 errors, 0 timeouts. RSS dropped 51→47 MB across the window. Per-key cache isolation, singleflight, cache_control bypass, quota enforcement, file-mode reconcile, and scope guard against escalation all verified against running code.
|
||||
|
||||
### Governance
|
||||
|
||||
- All three PRs (#86, #87, #88) include the explicit `cli.js`-citation-not-applicable disclaimer (per PR #75 pattern) since they are OCP-internal access-control, session-state, and file-permission changes with no corresponding `cli.js` operation to cite.
|
||||
|
||||
### No new env vars / no public API surface change beyond the documented breaking change
|
||||
|
||||
This release adds no new env vars or endpoints. The only externally visible change is the `/api/usage` scope guard (breaking for admin all-keys consumers; see Behavior changes above).
|
||||
|
||||
## v3.13.0 — 2026-05-07
|
||||
|
||||
### Features (cache layer hardening)
|
||||
|
||||
@@ -69,6 +69,20 @@ Any tool that accepts `OPENAI_BASE_URL` works with OCP:
|
||||
|
||||
## Installation
|
||||
|
||||
The simplest path: ask your AI.
|
||||
|
||||
Paste this prompt to Claude Code / Cursor / Copilot:
|
||||
|
||||
```
|
||||
Install OCP for me. Read README §Manual Installation and follow it.
|
||||
Tell me when I need to run `claude auth login`.
|
||||
```
|
||||
|
||||
The AI will run `git clone`, `npm install`, `node setup.mjs`, and tell you
|
||||
when to OAuth.
|
||||
|
||||
### Manual Installation
|
||||
|
||||
OCP has two roles: **Server** (runs the proxy, needs Claude CLI) and **Client** (connects to a server, zero dependencies).
|
||||
|
||||
```
|
||||
@@ -392,6 +406,8 @@ ocp keys revoke son-ipad # Revoke a key
|
||||
| `shared` | `CLAUDE_AUTH_MODE=shared` + `PROXY_API_KEY=xxx` | Everyone shares one key |
|
||||
| `multi` | `CLAUDE_AUTH_MODE=multi` + `OCP_ADMIN_KEY=xxx` | Per-person keys with usage tracking (recommended) |
|
||||
|
||||
> **Usage scope (v3.14.0+):** `/api/usage` returns the caller's own rows by default. Admin callers must pass `?all=true` to retrieve data for all keys; doing so emits an audit log line.
|
||||
|
||||
### Anonymous Access (optional)
|
||||
|
||||
In `multi` mode, the admin can designate a single well-known "anonymous" key that bypasses `validateKey()` and grants public read/write access. This is useful for letting LAN users (or clients like OpenClaw multi-agent setups) connect without individual per-user keys.
|
||||
@@ -460,6 +476,7 @@ When a key exceeds its quota, OCP returns HTTP 429 with a structured error:
|
||||
- Keys are stored in `~/.ocp/ocp.db` (SQLite, zero external dependencies)
|
||||
- Admin key is required for key management API endpoints
|
||||
- The dashboard (`/dashboard`) and health check (`/health`) are always public
|
||||
- File modes for `~/.ocp` (0700), `admin-key` + `ocp.db` (0600) are auto-tightened at server startup as of v3.14.0
|
||||
|
||||
## Built-in Usage Monitoring
|
||||
|
||||
@@ -498,6 +515,7 @@ ocp keys List all API keys (multi mode)
|
||||
ocp keys add <name> Create a new API key
|
||||
ocp keys revoke <name> Revoke an API key
|
||||
ocp connect <ip> One-command LAN client setup
|
||||
ocp doctor Health & upgrade-readiness check; primary entry for AI-driven debugging. --json produces a next_action for AI agents.
|
||||
ocp lan Show LAN connection info & IP
|
||||
ocp settings View tunable settings
|
||||
ocp settings <k> <v> Update a setting at runtime
|
||||
@@ -524,17 +542,57 @@ ocp --help
|
||||
|
||||
> **Cloud/Linux servers:** If `ocp: command not found`, the binary isn't in PATH. Full path: `~/.openclaw/projects/ocp/ocp`
|
||||
|
||||
### Self-Update
|
||||
## Upgrading
|
||||
|
||||
The simplest path: ask your AI.
|
||||
|
||||
Paste this prompt:
|
||||
|
||||
```
|
||||
Upgrade my OCP. Run `ocp update` and follow whatever it says.
|
||||
If it tells me to run `claude auth login`, I'll do that.
|
||||
```
|
||||
|
||||
What `ocp update` does:
|
||||
|
||||
- **Patch bump** (e.g. `v3.14.0 → v3.14.1`):
|
||||
light path (git pull + npm install + restart).
|
||||
- **Cross-minor** (e.g. `v3.10 → v3.14`):
|
||||
full path: pre-flight check, snapshot, `setup.mjs` (with plist env-merge),
|
||||
service restart, post-flight `/health` and `/v1/models` verification.
|
||||
- **Old version** (< v3.4.0):
|
||||
fresh-install. Pre-v3.4 lacked admin-key/usage-db, so there is nothing to
|
||||
migrate. Your OAuth token (managed by the Claude Code CLI, not OCP) is
|
||||
preserved; you do not need to re-OAuth unless your token expired
|
||||
separately.
|
||||
|
||||
Snapshots are saved to `~/.ocp/upgrade-snapshot-<ISO-ts>/` and never
|
||||
auto-deleted. Clean old ones with `rm -rf ~/.ocp/upgrade-snapshot-*` once
|
||||
you're confident the upgrade is stable.
|
||||
|
||||
### Manual upgrade — same command, no AI
|
||||
|
||||
```bash
|
||||
# Check if a new version is available
|
||||
ocp update --check
|
||||
|
||||
# Pull latest, sync plugin, restart proxy — one command
|
||||
ocp update
|
||||
ocp update # smart-pick path
|
||||
ocp update --check # show available updates, don't apply
|
||||
ocp update --dry-run # preview plan
|
||||
ocp update --target v3.13.0 # pin a specific version
|
||||
ocp update --rollback --yes # restore most recent snapshot (--yes confirms)
|
||||
ocp update --rollback --list # list snapshots, no mutation
|
||||
ocp update --rollback --dry-run # preview rollback plan
|
||||
```
|
||||
|
||||
`ocp update` runs (in order): `git pull` → `npm install` → plugin sync → **OpenClaw model registry sync** (v3.11.0+) → proxy restart → health check.
|
||||
### When upgrade fails
|
||||
|
||||
`ocp update` prints a recovery line on failure. To restore from the snapshot:
|
||||
|
||||
```bash
|
||||
ocp update --rollback --yes # --yes confirms the destructive restore
|
||||
ocp doctor
|
||||
```
|
||||
|
||||
If `ocp doctor` still reports problems after rollback, open a GitHub issue
|
||||
with the snapshot path and the doctor JSON output (`ocp doctor --json`).
|
||||
|
||||
### OpenClaw Auto-Sync (v3.11.0+)
|
||||
|
||||
@@ -657,7 +715,7 @@ The canonical list lives in [`models.json`](./models.json) — the single source
|
||||
| `/api/keys` | GET/POST | List or create API keys (admin only) |
|
||||
| `/api/keys/:id` | DELETE | Revoke an API key (admin only) |
|
||||
| `/api/keys/:id/quota` | GET/PATCH | View or set per-key quota (admin only) |
|
||||
| `/api/usage` | GET | Per-key usage stats (`?since=&until=&hours=&limit=`) |
|
||||
| `/api/usage` | GET | Per-key usage stats (`?since=&until=&hours=&limit=`); returns self only by default — pass `?all=true` (admin only) for all-keys data |
|
||||
| `/cache/stats` | GET | Cache statistics (admin only) |
|
||||
| `/cache` | DELETE | Clear response cache (admin only) |
|
||||
|
||||
@@ -707,6 +765,21 @@ After installing the gateway plugin, use `/ocp` slash commands in your chat:
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
The simplest path: ask your AI.
|
||||
|
||||
Paste this prompt:
|
||||
|
||||
```
|
||||
Run `ocp doctor` and follow its `next_action`. Tell me if you hit
|
||||
anything that needs human input.
|
||||
```
|
||||
|
||||
The doctor produces a JSON `next_action` with `ai_executable[]` (commands
|
||||
the agent runs verbatim) and `human_required[]` (steps that need you,
|
||||
typically just OAuth).
|
||||
|
||||
### Manual debugging
|
||||
|
||||
### Setup fails with "claude: command not found"
|
||||
|
||||
`setup.mjs` requires the Claude CLI to be on `PATH`. Install it via the [official guide](https://docs.anthropic.com/en/docs/claude-cli), confirm with `which claude`, then run `claude auth login` before re-running `node setup.mjs`.
|
||||
@@ -782,7 +855,8 @@ Future `ocp update` invocations sync automatically.
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `CLAUDE_PROXY_PORT` | `3456` | Listen port |
|
||||
| `CLAUDE_PROXY_PORT` | `3456` | Listen port (server-side). Also consumed by the OpenClaw `ocp-plugin` to dial the local proxy. |
|
||||
| `OCP_PROXY_URL` | *(unset)* | Plugin-side full URL override (e.g. `http://10.0.0.5:3456`). Wins over `CLAUDE_PROXY_PORT` when both are set. Read by `ocp-plugin/index.js` only — server ignores it. |
|
||||
| `CLAUDE_BIND` | `127.0.0.1` | Bind address (`0.0.0.0` for LAN access) |
|
||||
| `CLAUDE_AUTH_MODE` | `none` | Auth mode: `none`, `shared`, or `multi` |
|
||||
| `OCP_ADMIN_KEY` | *(unset)* | Admin key for key management (multi mode) |
|
||||
|
||||
+21
-2
@@ -55,7 +55,13 @@
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<h2>Usage by Key</h2>
|
||||
<div class="flex" style="justify-content: space-between; align-items: center;">
|
||||
<h2 style="margin: 0;">Usage by Key</h2>
|
||||
<label id="usage-scope-toggle" class="flex" style="display:none; gap: 0.4rem; font-size: 0.8rem; color: #94a3b8; cursor: pointer;">
|
||||
<input type="checkbox" id="usage-show-all" style="cursor: pointer;">
|
||||
<span>Show all keys</span>
|
||||
</label>
|
||||
</div>
|
||||
<table id="key-usage-table">
|
||||
<thead><tr><th>Key</th><th>Requests</th><th>OK</th><th>Err</th><th>Avg Time</th><th>Last Request</th></tr></thead>
|
||||
<tbody></tbody>
|
||||
@@ -170,7 +176,8 @@ async function refreshStatus() {
|
||||
|
||||
async function refreshUsage() {
|
||||
try {
|
||||
const data = await api("/api/usage");
|
||||
const showAll = localStorage.getItem("ocp_usage_show_all") === "1";
|
||||
const data = await api(showAll ? "/api/usage?all=true" : "/api/usage");
|
||||
const tbody = document.querySelector("#key-usage-table tbody");
|
||||
tbody.innerHTML = (data.byKey || []).map(k => `
|
||||
<tr>
|
||||
@@ -204,6 +211,8 @@ async function refreshKeys() {
|
||||
try {
|
||||
const data = await api("/api/keys");
|
||||
document.getElementById("key-mgmt-section").style.display = "";
|
||||
// Admin-only "Show all keys" toggle for /api/usage scope.
|
||||
document.getElementById("usage-scope-toggle").style.display = "flex";
|
||||
const tbody = document.querySelector("#keys-table tbody");
|
||||
tbody.innerHTML = (data.keys || []).map(k => `
|
||||
<tr>
|
||||
@@ -240,6 +249,16 @@ async function refreshAll() {
|
||||
document.getElementById("refresh-indicator").textContent = `Updated ${new Date().toLocaleTimeString()}`;
|
||||
}
|
||||
|
||||
// Wire "Show all keys" toggle (visibility gated to admin via refreshKeys()).
|
||||
(function setupUsageScopeToggle() {
|
||||
const cb = document.getElementById("usage-show-all");
|
||||
cb.checked = localStorage.getItem("ocp_usage_show_all") === "1";
|
||||
cb.addEventListener("change", () => {
|
||||
localStorage.setItem("ocp_usage_show_all", cb.checked ? "1" : "0");
|
||||
refreshUsage();
|
||||
});
|
||||
})();
|
||||
|
||||
refreshAll();
|
||||
setInterval(refreshAll, 30000);
|
||||
</script>
|
||||
|
||||
@@ -3,11 +3,13 @@
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import { randomBytes, createHash } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
import { mkdirSync } from "node:fs";
|
||||
import { mkdirSync, chmodSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
|
||||
const OCP_DIR = join(homedir(), ".ocp");
|
||||
mkdirSync(OCP_DIR, { recursive: true });
|
||||
mkdirSync(OCP_DIR, { recursive: true, mode: 0o700 });
|
||||
// Tighten the directory mode in case it already existed with broader permissions.
|
||||
try { chmodSync(OCP_DIR, 0o700); } catch { /* ignore EPERM on pre-existing dirs */ }
|
||||
const DB_PATH = join(OCP_DIR, "ocp.db");
|
||||
|
||||
let db;
|
||||
@@ -18,6 +20,8 @@ export function getDb() {
|
||||
db.exec("PRAGMA journal_mode = WAL");
|
||||
db.exec("PRAGMA foreign_keys = ON");
|
||||
initSchema();
|
||||
// Tighten mode on the DB file (0600) after creation / first open.
|
||||
try { chmodSync(DB_PATH, 0o600); } catch { /* ignore — same-user access still works */ }
|
||||
}
|
||||
return db;
|
||||
}
|
||||
|
||||
@@ -692,25 +692,35 @@ for e in d.get('errors', []):
|
||||
# ── update ──────────────────────────────────────────────────────────────
|
||||
cmd_update_help() {
|
||||
cat <<'EOF'
|
||||
ocp update — Update OCP to the latest version
|
||||
ocp update — Smart upgrade dispatcher
|
||||
|
||||
Pulls the latest code from GitHub, restarts the proxy service,
|
||||
and optionally syncs the plugin to the OpenClaw extensions directory.
|
||||
Runs `ocp doctor` internally to choose the right path:
|
||||
• Patch bump (same minor): light path (git pull + npm install + restart)
|
||||
• Cross-minor (e.g. v3.10→v3.14): full path with snapshot + post-flight
|
||||
• Old version (< v3.4.0): fresh-install (asks first; AI passes --yes)
|
||||
|
||||
Usage:
|
||||
ocp update Pull latest and restart
|
||||
ocp update --check Check for updates without applying
|
||||
ocp update Smart auto-pick path
|
||||
ocp update --check Show available updates, don't apply
|
||||
ocp update --dry-run Preview the plan, don't mutate
|
||||
ocp update --target v3.13.0 Pin a specific version
|
||||
ocp update --yes Skip y/N prompts (AI agents pass this)
|
||||
ocp update --rollback Restore the most recent upgrade snapshot
|
||||
ocp update --rollback --list List available snapshots
|
||||
ocp update --rollback <path> Restore a specific snapshot
|
||||
ocp update --rollback --dry-run Preview rollback plan
|
||||
ocp update --rollback --gc Delete old snapshots (keep last 5, or <30 days)
|
||||
ocp update --rollback --gc --dry-run Preview what would be deleted
|
||||
EOF
|
||||
}
|
||||
|
||||
cmd_update() {
|
||||
local script_dir self
|
||||
self="${BASH_SOURCE[0]}"
|
||||
# Resolve symlinks (e.g. ~/.local/bin/ocp → real location)
|
||||
while [[ -L "$self" ]]; do self="$(readlink "$self")"; done
|
||||
script_dir="$(cd "$(dirname "$self")" && pwd)"
|
||||
|
||||
# Check-only mode
|
||||
# Pass through --check fast path (existing behaviour)
|
||||
if [[ "${1:-}" == "--check" ]]; then
|
||||
cd "$script_dir"
|
||||
git fetch origin main --quiet 2>/dev/null || true
|
||||
@@ -727,71 +737,104 @@ cmd_update() {
|
||||
echo " Status: ✓ Up to date"
|
||||
else
|
||||
echo " Status: $behind commit(s) behind"
|
||||
echo ""
|
||||
echo " Run 'ocp update' to apply."
|
||||
fi
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo "Updating OCP..."
|
||||
echo ""
|
||||
# Rollback path
|
||||
if [[ "${1:-}" == "--rollback" ]]; then
|
||||
shift
|
||||
exec node "$script_dir/scripts/upgrade.mjs" --rollback "$@"
|
||||
fi
|
||||
|
||||
# 1. Pull latest
|
||||
# Doctor-driven path selection
|
||||
local kind
|
||||
kind=$(node "$script_dir/scripts/doctor.mjs" --json 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin)['next_action']['kind'])" 2>/dev/null || echo "unknown")
|
||||
|
||||
case "$kind" in
|
||||
noop)
|
||||
echo "Already at latest. Nothing to do."
|
||||
return 0
|
||||
;;
|
||||
update)
|
||||
_cmd_update_light "$script_dir"
|
||||
;;
|
||||
upgrade|fresh_install)
|
||||
exec node "$script_dir/scripts/upgrade.mjs" "$@"
|
||||
;;
|
||||
fix_oauth|fix_service)
|
||||
echo "Pre-upgrade check failed: $kind"
|
||||
echo "Run \`ocp doctor\` for details and ai_executable steps."
|
||||
return 1
|
||||
;;
|
||||
*)
|
||||
echo "Unknown doctor kind: $kind. Run \`ocp doctor --json\` to inspect."
|
||||
return 1
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Existing light-path body extracted into a helper so cmd_update can call it conditionally.
|
||||
_cmd_update_light() {
|
||||
local script_dir="$1"
|
||||
echo "Updating OCP (light path)..."
|
||||
cd "$script_dir"
|
||||
local old_ver
|
||||
local old_ver new_ver
|
||||
old_ver=$(python3 -c "import json; print(json.load(open('package.json'))['version'])" 2>/dev/null || echo "?")
|
||||
|
||||
echo " Pulling latest from GitHub..."
|
||||
if ! git pull origin main --ff-only 2>&1 | sed 's/^/ /'; then
|
||||
echo " ✗ Git pull failed. Resolve conflicts manually in: $script_dir"
|
||||
return 1
|
||||
fi
|
||||
|
||||
local new_ver
|
||||
new_ver=$(python3 -c "import json; print(json.load(open('package.json'))['version'])" 2>/dev/null || echo "?")
|
||||
|
||||
if [[ "$old_ver" == "$new_ver" ]]; then
|
||||
echo " ✓ Already at latest (v$new_ver)"
|
||||
else
|
||||
echo " ✓ Updated v$old_ver → v$new_ver"
|
||||
fi
|
||||
|
||||
# 2. Sync plugin to extensions dir
|
||||
# Sync plugin (existing logic preserved)
|
||||
local ext_dir="$HOME/.openclaw/extensions/ocp"
|
||||
if [[ -d "$ext_dir" && -d "$script_dir/ocp-plugin" ]]; then
|
||||
echo ""
|
||||
echo " Syncing OCP plugin..."
|
||||
cp "$script_dir/ocp-plugin/index.js" "$ext_dir/index.js" 2>/dev/null
|
||||
cp "$script_dir/ocp-plugin/package.json" "$ext_dir/package.json" 2>/dev/null
|
||||
cp "$script_dir/ocp-plugin/openclaw.plugin.json" "$ext_dir/openclaw.plugin.json" 2>/dev/null
|
||||
echo " ✓ Plugin synced to $ext_dir"
|
||||
echo " ✓ Plugin synced"
|
||||
fi
|
||||
|
||||
# 3. Sync OpenClaw registry from models.json (non-fatal)
|
||||
if command -v node >/dev/null 2>&1 && [[ -f "$script_dir/scripts/sync-openclaw.mjs" ]]; then
|
||||
echo ""
|
||||
echo " Syncing OpenClaw registry..."
|
||||
if ! node "$script_dir/scripts/sync-openclaw.mjs" 2>&1 | sed 's/^/ /'; then
|
||||
echo " ⚠ OpenClaw sync failed (non-fatal, continuing)"
|
||||
fi
|
||||
node "$script_dir/scripts/sync-openclaw.mjs" 2>&1 | sed 's/^/ /' || echo " ⚠ OpenClaw sync failed (non-fatal)"
|
||||
fi
|
||||
|
||||
# 4. Restart proxy
|
||||
echo ""
|
||||
echo " Restarting proxy..."
|
||||
cmd_restart > /dev/null 2>&1
|
||||
sleep 2
|
||||
}
|
||||
|
||||
if curl -sf --max-time 5 "$PROXY/health" > /dev/null 2>&1; then
|
||||
local running_ver
|
||||
running_ver=$(curl -sf --max-time 5 "$PROXY/health" | python3 -c "import sys,json; print(json.loads(sys.stdin.read())['version'])" 2>/dev/null || echo "?")
|
||||
echo " ✓ Proxy running (v$running_ver)"
|
||||
else
|
||||
echo " ⚠ Proxy not responding — check: ocp health"
|
||||
fi
|
||||
cmd_doctor_help() {
|
||||
cat <<'EOF'
|
||||
ocp doctor — Health & upgrade-readiness check
|
||||
|
||||
echo ""
|
||||
echo "Done."
|
||||
Runs a series of checks (Node version, git state, service health,
|
||||
OAuth token, plist customisation, OpenClaw provider) and emits either
|
||||
human-readable PASS/WARN/FAIL output or a JSON next_action that
|
||||
AI agents can execute.
|
||||
|
||||
Usage:
|
||||
ocp doctor Human-readable output
|
||||
ocp doctor --json JSON for AI agents and ocp update internal use
|
||||
ocp doctor --check oauth Fast path: OAuth check only
|
||||
EOF
|
||||
}
|
||||
|
||||
cmd_doctor() {
|
||||
local script_dir self
|
||||
self="${BASH_SOURCE[0]}"
|
||||
while [[ -L "$self" ]]; do self="$(readlink "$self")"; done
|
||||
script_dir="$(cd "$(dirname "$self")" && pwd)"
|
||||
exec node "$script_dir/scripts/doctor.mjs" "$@"
|
||||
}
|
||||
|
||||
# ── help ─────────────────────────────────────────────────────────────────
|
||||
@@ -859,6 +902,7 @@ case "$subcmd" in
|
||||
lan) cmd_lan ;;
|
||||
connect) cmd_connect "$@" ;;
|
||||
restart) cmd_restart "${1:-}" ;;
|
||||
update) cmd_update "${1:-}" ;;
|
||||
doctor) cmd_doctor "$@" ;;
|
||||
update) cmd_update "$@" ;;
|
||||
*) echo "Unknown command: $subcmd"; echo ""; cmd_help; exit 1 ;;
|
||||
esac
|
||||
|
||||
+13
-3
@@ -1,9 +1,19 @@
|
||||
/**
|
||||
* OCP Plugin — registers /ocp as a native slash command in OpenClaw gateway.
|
||||
* Calls the local claude-proxy at http://127.0.0.1:3456 and formats the response.
|
||||
* Calls the local claude-proxy and formats the response.
|
||||
*
|
||||
* Port resolution (in priority order):
|
||||
* 1. OCP_PROXY_URL env (full URL, e.g. http://10.0.0.5:3456)
|
||||
* 2. CLAUDE_PROXY_PORT env (port only; localhost assumed)
|
||||
* 3. Fallback: http://127.0.0.1:3456 (OCP server source default since v1.0)
|
||||
*
|
||||
* If a particular host's OCP plist injects a non-default CLAUDE_PROXY_PORT,
|
||||
* the OpenClaw launchd plist for that host must also inject the same
|
||||
* CLAUDE_PROXY_PORT into the plugin's env, or the plugin will fall back to
|
||||
* 3456 and miss the server.
|
||||
*/
|
||||
|
||||
const PROXY = "http://127.0.0.1:3456";
|
||||
const PROXY = process.env.OCP_PROXY_URL
|
||||
|| (process.env.CLAUDE_PROXY_PORT ? `http://127.0.0.1:${process.env.CLAUDE_PROXY_PORT}` : "http://127.0.0.1:3456");
|
||||
|
||||
// Wrap output in monospace code block for Telegram/Discord alignment
|
||||
function mono(text) { return "```\n" + text + "\n```"; }
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"id": "ocp",
|
||||
"name": "OCP Commands",
|
||||
"description": "Slash commands for the OpenClaw Proxy — /ocp usage, /ocp settings, /ocp health, etc.",
|
||||
"version": "3.12.0",
|
||||
"version": "3.16.2",
|
||||
"configSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
@@ -10,7 +10,7 @@
|
||||
"proxyUrl": {
|
||||
"type": "string",
|
||||
"default": "http://127.0.0.1:3456",
|
||||
"description": "URL of the Claude proxy"
|
||||
"description": "URL of the Claude proxy. Overridable via OCP_PROXY_URL or CLAUDE_PROXY_PORT env."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "open-claude-proxy",
|
||||
"version": "3.13.0",
|
||||
"version": "3.16.3",
|
||||
"description": "OCP (Open Claude Proxy) — use your Claude Pro/Max subscription as an OpenAI-compatible API for any IDE. Works with Cline, OpenCode, Aider, Continue.dev, OpenClaw, and more.",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* scripts/doctor.mjs — OCP health & upgrade-readiness check.
|
||||
*
|
||||
* Usage:
|
||||
* ocp doctor human-readable PASS/WARN/FAIL
|
||||
* ocp doctor --json machine-readable JSON for AI agents + ocp update
|
||||
* ocp doctor --check oauth fast path: only OAuth check
|
||||
*
|
||||
* Exit codes:
|
||||
* 0 all PASS or WARN-only
|
||||
* 1 any FAIL
|
||||
*/
|
||||
import { readFileSync, existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { homedir } from "node:os";
|
||||
import { execSync } from "node:child_process";
|
||||
|
||||
const SCHEMA_VERSION = "1";
|
||||
|
||||
function semverParts(v) {
|
||||
const m = String(v).replace(/^v/, "").match(/^(\d+)\.(\d+)\.(\d+)/);
|
||||
if (!m) return null;
|
||||
return { major: +m[1], minor: +m[2], patch: +m[3] };
|
||||
}
|
||||
|
||||
function semverCompare(a, b) {
|
||||
const A = semverParts(a), B = semverParts(b);
|
||||
if (!A || !B) return 0;
|
||||
if (A.major !== B.major) return A.major - B.major;
|
||||
if (A.minor !== B.minor) return A.minor - B.minor;
|
||||
return A.patch - B.patch;
|
||||
}
|
||||
|
||||
export async function runDoctor(opts = {}) {
|
||||
const checks = [];
|
||||
const push = (id, level, message, extra = {}) =>
|
||||
checks.push({ id, level, message, ...extra });
|
||||
|
||||
// --- fast path: --check oauth ---
|
||||
if (opts.checkOnly === "oauth") {
|
||||
return runOauthOnly(opts, checks, push);
|
||||
}
|
||||
|
||||
// --- version detection ---
|
||||
const ocpDir = opts.ocpDir || join(homedir(), "ocp");
|
||||
let currentVersion = opts.mockVersion;
|
||||
if (!currentVersion) {
|
||||
try {
|
||||
const pkg = JSON.parse(readFileSync(join(ocpDir, "package.json"), "utf8"));
|
||||
currentVersion = `v${pkg.version}`;
|
||||
} catch {
|
||||
currentVersion = "unknown";
|
||||
}
|
||||
}
|
||||
// Resolve latest from origin/main (cheap: `git show origin/main:package.json`).
|
||||
// Falls back to current_version when network/git unavailable, so kind = noop instead
|
||||
// of recommending a downgrade against a stale hardcoded value.
|
||||
let latestVersion = opts.mockLatest;
|
||||
if (!latestVersion) {
|
||||
try {
|
||||
const out = execSync(`git -C ${ocpDir} show origin/main:package.json 2>/dev/null`, { stdio: ["pipe", "pipe", "pipe"] }).toString();
|
||||
const remotePkg = JSON.parse(out);
|
||||
latestVersion = `v${remotePkg.version}`;
|
||||
} catch {
|
||||
latestVersion = currentVersion;
|
||||
}
|
||||
}
|
||||
push("current_version", "PASS", `current=${currentVersion}`);
|
||||
|
||||
// --- from-version supported? ---
|
||||
const fromSupported = !!semverParts(currentVersion) && semverCompare(currentVersion, "v3.4.0") >= 0;
|
||||
push("from_version_supported", fromSupported ? "PASS" : "FAIL",
|
||||
fromSupported ? "≥ v3.4.0" : `${currentVersion} < v3.4.0; in-place upgrade not supported`);
|
||||
|
||||
// --- service health check (mockable) ---
|
||||
let healthOk = true, oauthOk = true;
|
||||
if (!opts.skipNetwork) {
|
||||
let health;
|
||||
if (opts.mockHealth !== undefined) {
|
||||
health = opts.mockHealth;
|
||||
} else {
|
||||
try {
|
||||
const port = process.env.CLAUDE_PROXY_PORT || "3456";
|
||||
const out = execSync(`curl -sf --max-time 3 http://127.0.0.1:${port}/health`, { stdio: ["pipe", "pipe", "pipe"] }).toString();
|
||||
health = { status: 200, body: JSON.parse(out) };
|
||||
} catch (e) {
|
||||
health = { error: String(e.message || e) };
|
||||
}
|
||||
}
|
||||
if (health.error || health.status !== 200) {
|
||||
healthOk = false;
|
||||
push("service_running", "FAIL", `service unreachable: ${health.error || `status ${health.status}`}`);
|
||||
} else if (!health.body || typeof health.body !== "object") {
|
||||
healthOk = false;
|
||||
push("service_running", "FAIL", "service /health returned 200 but empty/non-JSON body");
|
||||
} else {
|
||||
push("service_running", "PASS", "service responding on /health");
|
||||
const authOk = health.body?.auth?.ok;
|
||||
if (!authOk) {
|
||||
oauthOk = false;
|
||||
push("oauth_ok", "FAIL", `auth.ok=false: ${health.body?.auth?.message || "unknown"}`);
|
||||
} else {
|
||||
push("oauth_ok", "PASS", "OAuth token valid");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- determine next_action.kind (priority: fresh_install > fix_service > fix_oauth > noop > update > upgrade) ---
|
||||
let kind;
|
||||
if (!fromSupported) {
|
||||
kind = "fresh_install";
|
||||
} else if (!opts.skipNetwork && !healthOk) {
|
||||
kind = "fix_service";
|
||||
} else if (!opts.skipNetwork && !oauthOk) {
|
||||
kind = "fix_oauth";
|
||||
} else {
|
||||
const cur = semverParts(currentVersion), lat = semverParts(latestVersion);
|
||||
if (!cur) {
|
||||
kind = "fresh_install";
|
||||
} else if (semverCompare(currentVersion, latestVersion) === 0) {
|
||||
kind = "noop";
|
||||
} else if (lat && cur.major === lat.major && cur.minor === lat.minor) {
|
||||
kind = "update";
|
||||
} else {
|
||||
kind = "upgrade";
|
||||
}
|
||||
}
|
||||
|
||||
// --- next_action shape ---
|
||||
let next_action;
|
||||
if (kind === "fresh_install") {
|
||||
next_action = {
|
||||
kind,
|
||||
human_required: ["claude auth login (only if OAuth becomes invalid after reinstall)"],
|
||||
ai_executable: [
|
||||
`launchctl bootout gui/$(id -u)/ai.openclaw.proxy 2>/dev/null || true`,
|
||||
`launchctl bootout gui/$(id -u)/dev.ocp.proxy 2>/dev/null || true`,
|
||||
`mv ${join(homedir(), ".ocp")} ${join(homedir(), ".ocp.backup-")}$(date +%s) 2>/dev/null || true`,
|
||||
`rm -rf ${ocpDir}`,
|
||||
`git clone https://github.com/dtzp555-max/ocp ${ocpDir}`,
|
||||
`cd ${ocpDir} && npm install --no-audit --no-fund && node setup.mjs`,
|
||||
`${ocpDir}/ocp doctor`
|
||||
],
|
||||
verify: "ocp doctor expects PASS on all checks"
|
||||
};
|
||||
} else if (kind === "noop") {
|
||||
next_action = { kind, human_required: [], ai_executable: [], verify: "already at latest" };
|
||||
} else if (kind === "fix_oauth") {
|
||||
next_action = {
|
||||
kind,
|
||||
human_required: [],
|
||||
ai_executable: [
|
||||
`cd "$(npm root -g)/@anthropic-ai/claude-code" && node install.cjs`,
|
||||
`launchctl bootout gui/$(id -u)/dev.ocp.proxy 2>/dev/null || true`,
|
||||
`launchctl bootstrap gui/$(id -u) ${join(homedir(), "Library", "LaunchAgents", "dev.ocp.proxy.plist")}`,
|
||||
`${ocpDir}/ocp doctor`
|
||||
],
|
||||
verify: "ocp doctor expects oauth_ok=PASS",
|
||||
reference: "~/.cc-rules/memory/learnings/ocp_claude_native_binary_postinstall.md"
|
||||
};
|
||||
} else if (kind === "fix_service") {
|
||||
next_action = {
|
||||
kind,
|
||||
human_required: [],
|
||||
ai_executable: [
|
||||
`launchctl bootout gui/$(id -u)/dev.ocp.proxy 2>/dev/null || true`,
|
||||
`launchctl bootstrap gui/$(id -u) ${join(homedir(), "Library", "LaunchAgents", "dev.ocp.proxy.plist")}`,
|
||||
`${ocpDir}/ocp doctor`
|
||||
],
|
||||
verify: "ocp doctor expects service_running=PASS"
|
||||
};
|
||||
} else {
|
||||
next_action = {
|
||||
kind,
|
||||
human_required: [],
|
||||
ai_executable: [`${ocpDir}/ocp update --yes`],
|
||||
verify: "ocp doctor expects PASS on all checks"
|
||||
};
|
||||
}
|
||||
|
||||
const fail_count = checks.filter(c => c.level === "FAIL").length;
|
||||
const warn_count = checks.filter(c => c.level === "WARN").length;
|
||||
return {
|
||||
schema_version: SCHEMA_VERSION,
|
||||
timestamp: new Date().toISOString(),
|
||||
ready_to_upgrade: fail_count === 0,
|
||||
current_version: currentVersion,
|
||||
latest_version: latestVersion,
|
||||
from_version_supported: fromSupported,
|
||||
fail_count,
|
||||
warn_count,
|
||||
checks,
|
||||
next_action
|
||||
};
|
||||
}
|
||||
|
||||
function runOauthOnly(opts, checks, push) {
|
||||
let healthOk = true, oauthOk = true;
|
||||
let health;
|
||||
if (opts.mockHealth !== undefined) {
|
||||
health = opts.mockHealth;
|
||||
} else {
|
||||
try {
|
||||
const port = process.env.CLAUDE_PROXY_PORT || "3456";
|
||||
const out = execSync(`curl -sf --max-time 3 http://127.0.0.1:${port}/health`, { stdio: ["pipe", "pipe", "pipe"] }).toString();
|
||||
health = { status: 200, body: JSON.parse(out) };
|
||||
} catch (e) {
|
||||
health = { error: String(e.message || e) };
|
||||
}
|
||||
}
|
||||
|
||||
if (health.error || health.status !== 200) {
|
||||
healthOk = false;
|
||||
push("oauth_ok", "FAIL", `service unreachable: ${health.error || `status ${health.status}`}`);
|
||||
} else if (!health.body || typeof health.body !== "object") {
|
||||
healthOk = false;
|
||||
push("oauth_ok", "FAIL", "service /health returned 200 but empty/non-JSON body");
|
||||
} else if (!health.body?.auth?.ok) {
|
||||
oauthOk = false;
|
||||
push("oauth_ok", "FAIL", `auth.ok=false: ${health.body?.auth?.message || "unknown"}`);
|
||||
} else {
|
||||
push("oauth_ok", "PASS", "OAuth token valid");
|
||||
}
|
||||
|
||||
const kind = !healthOk ? "fix_service" : !oauthOk ? "fix_oauth" : "noop";
|
||||
|
||||
let next_action;
|
||||
const ocpDir = opts.ocpDir || join(homedir(), "ocp");
|
||||
if (kind === "noop") {
|
||||
next_action = { kind, human_required: [], ai_executable: [], verify: "OAuth healthy" };
|
||||
} else if (kind === "fix_oauth") {
|
||||
next_action = {
|
||||
kind,
|
||||
human_required: [],
|
||||
ai_executable: [
|
||||
`cd "$(npm root -g)/@anthropic-ai/claude-code" && node install.cjs`,
|
||||
`launchctl bootout gui/$(id -u)/dev.ocp.proxy 2>/dev/null || true`,
|
||||
`launchctl bootstrap gui/$(id -u) ${join(homedir(), "Library", "LaunchAgents", "dev.ocp.proxy.plist")}`,
|
||||
`${ocpDir}/ocp doctor --check oauth`
|
||||
],
|
||||
verify: "ocp doctor --check oauth expects PASS",
|
||||
reference: "~/.cc-rules/memory/learnings/ocp_claude_native_binary_postinstall.md"
|
||||
};
|
||||
} else {
|
||||
next_action = {
|
||||
kind,
|
||||
human_required: [],
|
||||
ai_executable: [
|
||||
`launchctl bootout gui/$(id -u)/dev.ocp.proxy 2>/dev/null || true`,
|
||||
`launchctl bootstrap gui/$(id -u) ${join(homedir(), "Library", "LaunchAgents", "dev.ocp.proxy.plist")}`,
|
||||
`${ocpDir}/ocp doctor --check oauth`
|
||||
],
|
||||
verify: "ocp doctor --check oauth expects service_running=PASS"
|
||||
};
|
||||
}
|
||||
|
||||
const fail_count = checks.filter(c => c.level === "FAIL").length;
|
||||
// "skipped" = --check oauth fast path intentionally omits version detection.
|
||||
// AI agents should NOT semver-compare against current_version/latest_version when
|
||||
// either equals "skipped"; the full path provides those fields when needed.
|
||||
return {
|
||||
schema_version: SCHEMA_VERSION,
|
||||
timestamp: new Date().toISOString(),
|
||||
ready_to_upgrade: fail_count === 0,
|
||||
current_version: opts.mockVersion || "skipped",
|
||||
latest_version: opts.mockLatest || "skipped",
|
||||
from_version_supported: true,
|
||||
fail_count,
|
||||
warn_count: 0,
|
||||
checks,
|
||||
next_action
|
||||
};
|
||||
}
|
||||
|
||||
// CLI entrypoint — use fileURLToPath + realpath to handle symlinked install paths
|
||||
// (e.g. /tmp/ → /private/tmp/ on macOS would otherwise miss the guard).
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { realpathSync } from "node:fs";
|
||||
function _isMain() {
|
||||
if (!process.argv[1]) return false;
|
||||
try {
|
||||
return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(process.argv[1]);
|
||||
} catch { return false; }
|
||||
}
|
||||
if (_isMain()) {
|
||||
const wantJson = process.argv.includes("--json");
|
||||
const checkIdx = process.argv.indexOf("--check");
|
||||
const checkOnly = checkIdx !== -1 ? process.argv[checkIdx + 1] : undefined;
|
||||
const result = await runDoctor({ checkOnly });
|
||||
if (wantJson) {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
} else {
|
||||
console.log(`OCP doctor — ${result.current_version} → ${result.latest_version}`);
|
||||
for (const c of result.checks) console.log(` [${c.level}] ${c.id}: ${c.message}`);
|
||||
console.log(`\nSummary: ${result.fail_count} FAIL, ${result.warn_count} WARN`);
|
||||
console.log(`Next action: ${result.next_action.kind}`);
|
||||
}
|
||||
process.exit(result.fail_count === 0 ? 0 : 1);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// scripts/lib/plist-merge.mjs
|
||||
//
|
||||
// Preserves user-customised env vars when setup.mjs rewrites the unit file.
|
||||
//
|
||||
// Rule:
|
||||
// - keys present in NEW template → template value wins (template is source of truth)
|
||||
// - keys ONLY in EXISTING (not in template) → preserved verbatim
|
||||
//
|
||||
// No new dependencies — regex-based, plist <key>X</key><string>Y</string> shape
|
||||
// is stable enough for our hand-written templates in setup.mjs.
|
||||
|
||||
const PLIST_KV_RE = /<key>([^<]+)<\/key>\s*<string>([^<]*)<\/string>/g;
|
||||
|
||||
export function parsePlistEnv(plistContent) {
|
||||
if (!plistContent) return {};
|
||||
if (Buffer.isBuffer(plistContent)) plistContent = plistContent.toString("utf8");
|
||||
// Restrict to the EnvironmentVariables dict to avoid catching Label, etc.
|
||||
const envBlock = plistContent.match(/<key>EnvironmentVariables<\/key>\s*<dict>([\s\S]*?)<\/dict>/);
|
||||
if (!envBlock) return {};
|
||||
const out = {};
|
||||
let m;
|
||||
PLIST_KV_RE.lastIndex = 0;
|
||||
while ((m = PLIST_KV_RE.exec(envBlock[1])) !== null) {
|
||||
out[m[1]] = m[2];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function mergePlistEnv(existing, template) {
|
||||
if (!existing) return template;
|
||||
const existingEnv = parsePlistEnv(existing);
|
||||
const templateEnv = parsePlistEnv(template);
|
||||
const KNOWN = new Set(Object.keys(templateEnv));
|
||||
|
||||
const preserved = {};
|
||||
for (const [k, v] of Object.entries(existingEnv)) {
|
||||
if (!KNOWN.has(k)) preserved[k] = v;
|
||||
}
|
||||
if (Object.keys(preserved).length === 0) return template;
|
||||
|
||||
const lines = Object.entries(preserved)
|
||||
.map(([k, v]) => ` <key>${k}</key>\n <string>${v}</string>`)
|
||||
.join("\n");
|
||||
|
||||
// Inject before the closing </dict> of EnvironmentVariables
|
||||
return template.replace(
|
||||
/(<key>EnvironmentVariables<\/key>\s*<dict>[\s\S]*?)(\n\s*<\/dict>)/,
|
||||
`$1\n${lines}$2`
|
||||
);
|
||||
}
|
||||
|
||||
const SYSTEMD_KV_RE = /^Environment=([^=]+)=(.*)$/gm;
|
||||
|
||||
export function parseSystemdEnv(serviceContent) {
|
||||
if (!serviceContent) return {};
|
||||
if (Buffer.isBuffer(serviceContent)) serviceContent = serviceContent.toString("utf8");
|
||||
const out = {};
|
||||
let m;
|
||||
SYSTEMD_KV_RE.lastIndex = 0;
|
||||
while ((m = SYSTEMD_KV_RE.exec(serviceContent)) !== null) {
|
||||
out[m[1]] = m[2];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function mergeSystemdEnv(existing, template) {
|
||||
if (!existing) return template;
|
||||
const existingEnv = parseSystemdEnv(existing);
|
||||
const templateEnv = parseSystemdEnv(template);
|
||||
const KNOWN = new Set(Object.keys(templateEnv));
|
||||
|
||||
const preservedLines = Object.entries(existingEnv)
|
||||
.filter(([k]) => !KNOWN.has(k))
|
||||
.map(([k, v]) => `Environment=${k}=${v}`);
|
||||
if (preservedLines.length === 0) return template;
|
||||
|
||||
// Guard: if template has no Environment= anchor, cannot inject — return template as-is.
|
||||
// (In practice the OCP systemd template always has Environment= lines.)
|
||||
if (!/^Environment=/m.test(template)) return template;
|
||||
|
||||
// Inject after the last existing Environment= line in the template
|
||||
return template.replace(
|
||||
/(^Environment=[^\n]+\n)((?!Environment=).*$)/ms,
|
||||
`$1${preservedLines.join("\n")}\n$2`
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { mkdirSync, writeFileSync, readFileSync, copyFileSync, existsSync, readdirSync, statSync, rmSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
export function writeSnapshot({ homeDir, fromCommit, fromVersion, toVersion, extraFiles = [] }) {
|
||||
const ts = new Date().toISOString().replace(/\.\d+Z$/, "Z");
|
||||
const root = join(homeDir, ".ocp", `upgrade-snapshot-${ts}`);
|
||||
mkdirSync(root, { recursive: true });
|
||||
|
||||
// Standard manifest files
|
||||
writeFileSync(join(root, "from-commit.txt"), fromCommit + "\n");
|
||||
writeFileSync(join(root, "from-version.txt"), fromVersion + "\n");
|
||||
writeFileSync(join(root, "to-version.txt"), toVersion + "\n");
|
||||
|
||||
// Optional captures (best-effort, never fatal)
|
||||
const tryCopy = (src, dst) => {
|
||||
try {
|
||||
if (existsSync(src)) copyFileSync(src, dst);
|
||||
} catch (err) {
|
||||
console.error(`[snapshot] warn: could not copy ${src} (${err.code || err.message})`);
|
||||
}
|
||||
};
|
||||
tryCopy(join(homeDir, "Library", "LaunchAgents", "dev.ocp.proxy.plist"), join(root, "plist"));
|
||||
tryCopy(join(homeDir, ".config", "systemd", "user", "ocp-proxy.service"), join(root, "service"));
|
||||
tryCopy(join(homeDir, ".ocp", "ocp.db"), join(root, "db.bak"));
|
||||
tryCopy(join(homeDir, ".ocp", "admin-key"), join(root, "admin-key"));
|
||||
tryCopy(join(homeDir, ".openclaw", "openclaw.json"), join(root, "openclaw.json"));
|
||||
|
||||
for (const { src, name } of extraFiles) tryCopy(src, join(root, name));
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
export function readSnapshot(snapshotPath) {
|
||||
const read = (n) => {
|
||||
try { return readFileSync(join(snapshotPath, n), "utf8").trim(); } catch { return null; }
|
||||
};
|
||||
return {
|
||||
path: snapshotPath,
|
||||
fromCommit: read("from-commit.txt"),
|
||||
fromVersion: read("from-version.txt"),
|
||||
toVersion: read("to-version.txt")
|
||||
};
|
||||
}
|
||||
|
||||
export function listSnapshots(homeDir) {
|
||||
const root = join(homeDir, ".ocp");
|
||||
if (!existsSync(root)) return [];
|
||||
return readdirSync(root)
|
||||
.filter(name => name.startsWith("upgrade-snapshot-"))
|
||||
.map(name => ({ name, path: join(root, name), mtime: statSync(join(root, name)).mtimeMs }))
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
/**
|
||||
* Garbage-collect old upgrade snapshots.
|
||||
*
|
||||
* Retention rule (a snapshot is KEPT if any of these is true):
|
||||
* - It is among the last `keepCount` snapshots (sorted oldest→newest)
|
||||
* - Its timestamp is within `keepDays` of `now`
|
||||
* - It is the single most-recent snapshot (always-keep safety net)
|
||||
*
|
||||
* @param {string} homeDir - Root containing ~/.ocp/
|
||||
* @param {object} opts
|
||||
* @param {number} [opts.keepCount=5] - Minimum count to keep
|
||||
* @param {number} [opts.keepDays=30] - Keep snapshots newer than N days
|
||||
* @param {boolean} [opts.dryRun=false] - If true, report plan but don't delete
|
||||
* @param {Date} [opts.now=new Date()] - Override clock for testing
|
||||
* @returns {{kept: Array, removed: Array, dryRun: boolean}}
|
||||
*/
|
||||
export function gcSnapshots(homeDir, opts = {}) {
|
||||
const keepCount = opts.keepCount ?? 5;
|
||||
const keepDays = opts.keepDays ?? 30;
|
||||
const dryRun = !!opts.dryRun;
|
||||
const now = opts.now || new Date();
|
||||
|
||||
const all = listSnapshots(homeDir); // sorted oldest→newest
|
||||
if (all.length === 0) return { kept: [], removed: [], dryRun };
|
||||
if (all.length === 1) return { kept: all, removed: [], dryRun }; // always keep most recent
|
||||
|
||||
const cutoffMs = now.getTime() - keepDays * 24 * 60 * 60 * 1000;
|
||||
const lastN = new Set(all.slice(-keepCount).map(s => s.path));
|
||||
|
||||
const kept = [], removed = [];
|
||||
for (let i = 0; i < all.length; i++) {
|
||||
const s = all[i];
|
||||
const isMostRecent = i === all.length - 1;
|
||||
const isInLastN = lastN.has(s.path);
|
||||
const isWithinDays = parseSnapshotTimestamp(s.name) >= cutoffMs;
|
||||
if (isMostRecent || isInLastN || isWithinDays) {
|
||||
kept.push(s);
|
||||
} else {
|
||||
removed.push(s);
|
||||
}
|
||||
}
|
||||
|
||||
if (!dryRun) {
|
||||
for (const s of removed) {
|
||||
try {
|
||||
rmSync(s.path, { recursive: true, force: true });
|
||||
} catch (err) {
|
||||
console.error(`[snapshot] warn: could not remove ${s.path} (${err.code || err.message})`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { kept, removed, dryRun };
|
||||
}
|
||||
|
||||
function parseSnapshotTimestamp(name) {
|
||||
// upgrade-snapshot-2026-05-11T08:30:00Z → epoch ms
|
||||
const m = name.match(/upgrade-snapshot-(.+)$/);
|
||||
if (!m) return 0;
|
||||
const t = Date.parse(m[1]);
|
||||
return Number.isFinite(t) ? t : 0;
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* scripts/upgrade.mjs — OCP unified upgrade dispatcher.
|
||||
*
|
||||
* Paths:
|
||||
* noop current == latest, exit 0
|
||||
* light same major.minor, patch bump only (existing fast path; delegated to bash)
|
||||
* full cross-minor (snapshot + setup.mjs + post-flight)
|
||||
* fresh_install from-version < v3.4.0 (--yes required for non-interactive)
|
||||
* rollback restore from snapshot
|
||||
*/
|
||||
import { runDoctor } from "./doctor.mjs";
|
||||
import { execSync } from "node:child_process";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { existsSync, copyFileSync } from "node:fs";
|
||||
import { writeSnapshot, listSnapshots, readSnapshot, gcSnapshots } from "./lib/snapshot.mjs";
|
||||
|
||||
export async function runUpgrade(opts = {}) {
|
||||
const dryRun = !!opts.dryRun;
|
||||
const yes = !!opts.yes;
|
||||
// yes is reserved for Bundle 3 (fresh-install / rollback interactive gate); not used in upgrade-path here.
|
||||
const plan = [];
|
||||
|
||||
// --- rollback path (no doctor needed; snapshot is authoritative) ---
|
||||
if (opts.rollback) {
|
||||
return await runRollback(opts);
|
||||
}
|
||||
|
||||
// --- doctor pre-flight ---
|
||||
const doctor = opts.mockDoctor || await runDoctor();
|
||||
if (!doctor.ready_to_upgrade && doctor.next_action.kind !== "fresh_install") {
|
||||
throw new Error(`doctor FAIL: ${doctor.next_action.kind} (run "ocp doctor" for details)`);
|
||||
}
|
||||
|
||||
const kind = doctor.next_action.kind;
|
||||
plan.push(`[doctor] from=${doctor.current_version} to=${doctor.latest_version} kind=${kind}`);
|
||||
|
||||
// --- noop ---
|
||||
if (kind === "noop") {
|
||||
plan.push(`[noop] already at latest (${doctor.latest_version})`);
|
||||
return { path: "noop", executed: true, changed: false, plan };
|
||||
}
|
||||
|
||||
// --- dry-run early exit ---
|
||||
if (dryRun) {
|
||||
plan.push(`[plan] would proceed with ${kind} path`);
|
||||
if (kind === "upgrade") {
|
||||
plan.push(`[plan] phase 1: snapshot to ~/.ocp/upgrade-snapshot-<ts>/`);
|
||||
plan.push(`[plan] phase 2: git checkout ${doctor.latest_version} && npm install`);
|
||||
plan.push(`[plan] phase 3: node setup.mjs`);
|
||||
plan.push(`[plan] phase 4: launchctl bootout/bootstrap`);
|
||||
plan.push(`[plan] phase 5: post-flight /health + /v1/models`);
|
||||
} else if (kind === "update") {
|
||||
plan.push(`[plan] light path: git pull + npm install + restart`);
|
||||
} else if (kind === "fresh_install") {
|
||||
plan.push(`[plan] fresh-install ai_executable[]:`);
|
||||
for (const cmd of doctor.next_action.ai_executable) plan.push(` - ${cmd}`);
|
||||
}
|
||||
return { path: kind, executed: false, plan };
|
||||
}
|
||||
|
||||
// --- non-dry-run paths ---
|
||||
if (kind === "update") {
|
||||
return { path: "update", executed: true, changed: true, plan: [...plan, "[light] delegated to bash cmd_update existing logic"] };
|
||||
}
|
||||
|
||||
if (kind === "upgrade") {
|
||||
return await runFullUpgrade({ doctor, opts });
|
||||
}
|
||||
|
||||
if (kind === "fresh_install") {
|
||||
return await runFreshInstall({ doctor, opts });
|
||||
}
|
||||
|
||||
throw new Error(`path ${kind} not yet implemented`);
|
||||
}
|
||||
|
||||
async function runFullUpgrade({ doctor, opts }) {
|
||||
const phases = [];
|
||||
let snapshotPath = null;
|
||||
const exec = (cmd, label) => {
|
||||
if (opts.mockExec) {
|
||||
phases.push({ name: label, cmd, status: "skipped-mock" });
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
const out = execSync(cmd, { stdio: ["pipe", "pipe", "pipe"] }).toString();
|
||||
phases.push({ name: label, cmd, status: "ok" });
|
||||
return out;
|
||||
} catch (err) {
|
||||
const detail = err.stderr?.toString().trim();
|
||||
phases.push({ name: label, cmd, status: "fail", stderr: detail });
|
||||
throw Object.assign(
|
||||
new Error(`phase ${label} failed: ${detail || err.message}`),
|
||||
{ phases, cmd }
|
||||
);
|
||||
}
|
||||
};
|
||||
const ocpDir = opts.ocpDir || join(homedir(), "ocp");
|
||||
|
||||
try {
|
||||
// phase 1: pre-flight (doctor already passed; just record)
|
||||
phases.push({ name: "pre-flight", status: "ok", note: `kind=upgrade from=${doctor.current_version} to=${doctor.latest_version}` });
|
||||
|
||||
// phase 2: snapshot
|
||||
const fromCommit = opts.mockExec
|
||||
? "mock-commit"
|
||||
: execSync(`git -C ${ocpDir} rev-parse HEAD`).toString().trim();
|
||||
snapshotPath = opts.mockExec
|
||||
? "/tmp/mock-snapshot"
|
||||
: writeSnapshot({ homeDir: homedir(), fromCommit, fromVersion: doctor.current_version, toVersion: doctor.latest_version });
|
||||
phases.push({ name: "snapshot", path: snapshotPath, status: "ok" });
|
||||
|
||||
// phase 3: fetch + install
|
||||
exec(`git -C ${ocpDir} fetch --tags --quiet`, "fetch+install");
|
||||
exec(`git -C ${ocpDir} checkout ${doctor.latest_version}`, "fetch+install");
|
||||
exec(`npm --prefix ${ocpDir} install --no-audit --no-fund`, "fetch+install");
|
||||
|
||||
// phase 4: reconfigure
|
||||
exec(`node ${ocpDir}/setup.mjs`, "reconfigure");
|
||||
|
||||
// phase 5: restart (heads-up note printed before invoking)
|
||||
if (!opts.mockExec) {
|
||||
console.error(`[heads-up] restarting OCP service in 3s — expect ~5–10s blip on requests in flight.`);
|
||||
await new Promise(r => setTimeout(r, 3000));
|
||||
}
|
||||
if (process.platform === "darwin") {
|
||||
exec(`launchctl bootout gui/$(id -u)/dev.ocp.proxy 2>/dev/null || true`, "restart");
|
||||
exec(`launchctl bootstrap gui/$(id -u) ${join(homedir(), "Library", "LaunchAgents", "dev.ocp.proxy.plist")}`, "restart");
|
||||
} else {
|
||||
exec(`systemctl --user restart ocp-proxy.service`, "restart");
|
||||
}
|
||||
|
||||
// phase 6: post-flight (10s budget; skipped under mockExec)
|
||||
if (!opts.mockExec) {
|
||||
const port = process.env.CLAUDE_PROXY_PORT || "3456";
|
||||
let ok = false;
|
||||
for (let i = 0; i < 10; i++) {
|
||||
try {
|
||||
const out = execSync(`curl -sf --max-time 2 http://127.0.0.1:${port}/health`).toString();
|
||||
const body = JSON.parse(out);
|
||||
if (body.auth?.ok === true) { ok = true; break; }
|
||||
} catch { /* retry */ }
|
||||
await new Promise(r => setTimeout(r, 1000));
|
||||
}
|
||||
if (!ok) {
|
||||
phases.push({ name: "post-flight", status: "fail", message: "health did not return auth.ok=true within 10s" });
|
||||
throw new Error("post-flight failed");
|
||||
}
|
||||
execSync(`curl -sf --max-time 3 http://127.0.0.1:${port}/v1/models > /dev/null`);
|
||||
phases.push({ name: "post-flight", status: "ok" });
|
||||
} else {
|
||||
phases.push({ name: "post-flight", status: "skipped-mock" });
|
||||
}
|
||||
|
||||
// Auto-GC old snapshots after successful upgrade (best-effort, never throws).
|
||||
try {
|
||||
const gc = gcSnapshots(homedir(), { keepCount: 5, keepDays: 30 });
|
||||
if (gc.removed.length > 0) {
|
||||
console.error(`[gc] removed ${gc.removed.length} old snapshots; kept ${gc.kept.length}`);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(`[gc] warn: snapshot GC failed: ${e.message}`);
|
||||
}
|
||||
|
||||
return { path: "upgrade", executed: true, changed: true, snapshotPath, phases };
|
||||
} catch (err) {
|
||||
if (snapshotPath && !err.snapshotPath) {
|
||||
Object.assign(err, {
|
||||
snapshotPath,
|
||||
phases,
|
||||
hint: "Working tree may be at new version. Run `ocp update --rollback` to restore from snapshot."
|
||||
});
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async function runFreshInstall({ doctor, opts }) {
|
||||
if (!opts.yes) {
|
||||
throw new Error("fresh_install requires --yes for non-interactive execution (or run interactively and answer y)");
|
||||
}
|
||||
const steps = [];
|
||||
for (const cmd of doctor.next_action.ai_executable) {
|
||||
if (opts.mockExec) {
|
||||
steps.push({ cmd, status: "skipped-mock" });
|
||||
} else {
|
||||
try {
|
||||
execSync(cmd, { stdio: "inherit" });
|
||||
steps.push({ cmd, status: "ok" });
|
||||
} catch (e) {
|
||||
const detail = e.stderr?.toString().trim() || e.message;
|
||||
steps.push({ cmd, status: "fail", error: String(detail) });
|
||||
throw Object.assign(new Error(`fresh_install step failed: ${cmd} — ${detail}`), { steps });
|
||||
}
|
||||
}
|
||||
}
|
||||
return { path: "fresh_install", executed: true, changed: true, steps };
|
||||
}
|
||||
|
||||
async function runRollback(opts) {
|
||||
const homeDir = opts.homeDir || homedir();
|
||||
const snapshots = opts.mockSnapshots ?? listSnapshots(homeDir);
|
||||
|
||||
if (opts.gc) {
|
||||
const result = gcSnapshots(homeDir, { dryRun: opts.dryRun });
|
||||
return { path: opts.dryRun ? "rollback-gc-dry-run" : "rollback-gc", ...result };
|
||||
}
|
||||
|
||||
if (opts.list) {
|
||||
return { path: "rollback-list", snapshots };
|
||||
}
|
||||
if (snapshots.length === 0) {
|
||||
throw new Error("no upgrade snapshots found in ~/.ocp/upgrade-snapshot-*");
|
||||
}
|
||||
|
||||
const target = opts.snapshotPath
|
||||
? snapshots.find(s => s.path === opts.snapshotPath)
|
||||
: snapshots[snapshots.length - 1];
|
||||
if (!target) throw new Error(`snapshot not found: ${opts.snapshotPath} (must be inside ~/.ocp/upgrade-snapshot-*)`);
|
||||
|
||||
const meta = opts.mockSnapshotMeta ?? readSnapshot(target.path);
|
||||
if (!meta.fromCommit) throw new Error(`snapshot ${target.path} has no from-commit.txt`);
|
||||
|
||||
const phases = [];
|
||||
if (opts.dryRun) {
|
||||
return {
|
||||
path: "rollback-dry-run",
|
||||
executed: false,
|
||||
target: target.path,
|
||||
plan: [
|
||||
`git checkout ${meta.fromCommit}`,
|
||||
`cp ${target.path}/plist ~/Library/LaunchAgents/dev.ocp.proxy.plist`,
|
||||
`cp ${target.path}/db.bak ~/.ocp/ocp.db`,
|
||||
`launchctl bootout/bootstrap`,
|
||||
`ocp doctor`
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
if (!opts.yes) throw new Error("rollback requires --yes for non-interactive execution");
|
||||
|
||||
const exec = (cmd, label) => {
|
||||
if (opts.mockExec) {
|
||||
phases.push({ name: label, cmd, status: "skipped-mock" });
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
execSync(cmd, { stdio: ["pipe", "pipe", "pipe"] });
|
||||
phases.push({ name: label, cmd, status: "ok" });
|
||||
} catch (err) {
|
||||
const detail = err.stderr?.toString().trim();
|
||||
phases.push({ name: label, cmd, status: "fail", stderr: detail });
|
||||
throw Object.assign(
|
||||
new Error(`rollback phase ${label} failed: ${detail || err.message}`),
|
||||
{ phases, target: target.path }
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const ocpDir = opts.ocpDir || join(homedir(), "ocp");
|
||||
exec(`git -C ${ocpDir} checkout ${meta.fromCommit}`, "git-checkout");
|
||||
|
||||
if (!opts.mockExec) {
|
||||
const tryCopy = (src, dst) => {
|
||||
try {
|
||||
if (existsSync(src)) copyFileSync(src, dst);
|
||||
} catch (err) {
|
||||
console.error(`[rollback] warn: could not restore ${src} → ${dst} (${err.code || err.message})`);
|
||||
}
|
||||
};
|
||||
tryCopy(join(target.path, "plist"), join(homeDir, "Library", "LaunchAgents", "dev.ocp.proxy.plist"));
|
||||
tryCopy(join(target.path, "service"), join(homeDir, ".config", "systemd", "user", "ocp-proxy.service"));
|
||||
tryCopy(join(target.path, "db.bak"), join(homeDir, ".ocp", "ocp.db"));
|
||||
tryCopy(join(target.path, "admin-key"), join(homeDir, ".ocp", "admin-key"));
|
||||
phases.push({ name: "restore-files", status: "ok" });
|
||||
} else {
|
||||
phases.push({ name: "restore-files", status: "skipped-mock" });
|
||||
}
|
||||
|
||||
exec(`npm --prefix ${ocpDir} install --no-audit --no-fund`, "npm-install");
|
||||
|
||||
if (!opts.mockExec) {
|
||||
console.error(`[heads-up] restarting OCP service in 3s — expect ~5–10s blip on requests in flight.`);
|
||||
await new Promise(r => setTimeout(r, 3000));
|
||||
}
|
||||
if (process.platform === "darwin") {
|
||||
exec(`launchctl bootout gui/$(id -u)/dev.ocp.proxy 2>/dev/null || true`, "restart");
|
||||
exec(`launchctl bootstrap gui/$(id -u) ${join(homedir(), "Library", "LaunchAgents", "dev.ocp.proxy.plist")}`, "restart");
|
||||
} else {
|
||||
exec(`systemctl --user restart ocp-proxy.service`, "restart");
|
||||
}
|
||||
|
||||
return { path: "rollback", executed: true, changed: true, target: target.path, phases };
|
||||
}
|
||||
|
||||
// CLI entrypoint — use fileURLToPath + realpath to handle symlinked install paths.
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { realpathSync } from "node:fs";
|
||||
function _isMain() {
|
||||
if (!process.argv[1]) return false;
|
||||
try {
|
||||
return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(process.argv[1]);
|
||||
} catch { return false; }
|
||||
}
|
||||
if (_isMain()) {
|
||||
const args = process.argv.slice(2);
|
||||
const dryRun = args.includes("--dry-run");
|
||||
const yes = args.includes("--yes");
|
||||
const rollback = args.includes("--rollback");
|
||||
const list = args.includes("--list");
|
||||
const gc = args.includes("--gc");
|
||||
const targetIdx = args.indexOf("--target");
|
||||
const target = targetIdx !== -1 ? args[targetIdx + 1] : undefined;
|
||||
// First non-flag positional after --rollback is the snapshot path
|
||||
let snapshotPath;
|
||||
if (rollback) {
|
||||
const rb = args.indexOf("--rollback");
|
||||
const cand = args[rb + 1];
|
||||
if (cand && !cand.startsWith("--")) snapshotPath = cand;
|
||||
}
|
||||
try {
|
||||
const result = await runUpgrade({ dryRun, yes, rollback, list, gc, snapshotPath, target });
|
||||
if (result.plan) for (const line of result.plan) console.log(line);
|
||||
if (result.phases) for (const p of result.phases) console.log(`[${p.name}] ${p.status}${p.cmd ? `: ${p.cmd}` : ""}`);
|
||||
if (result.steps) for (const s of result.steps) console.log(` ${s.status === "ok" ? "✓" : s.status === "skipped-mock" ? "·" : "✗"} ${s.cmd}`);
|
||||
if (result.snapshots) {
|
||||
console.log(`Found ${result.snapshots.length} snapshots:`);
|
||||
for (const s of result.snapshots) console.log(` ${s.name}`);
|
||||
}
|
||||
if (result.removed && result.kept) {
|
||||
console.log(`Snapshots: kept ${result.kept.length}, ${result.dryRun ? "would remove" : "removed"} ${result.removed.length}`);
|
||||
for (const s of result.removed) console.log(` - ${s.name}`);
|
||||
}
|
||||
process.exit(0);
|
||||
} catch (e) {
|
||||
console.error(`✗ ${e.message}`);
|
||||
if (e.snapshotPath) console.error(` snapshot: ${e.snapshotPath}`);
|
||||
if (e.target) console.error(` target: ${e.target}`);
|
||||
if (e.hint) console.error(` hint: ${e.hint}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
+114
-27
@@ -30,7 +30,7 @@
|
||||
import { createServer } from "node:http";
|
||||
import { spawn, execFileSync } from "node:child_process";
|
||||
import { randomUUID, timingSafeEqual } from "node:crypto";
|
||||
import { readFileSync, readdirSync, accessSync, existsSync, constants } from "node:fs";
|
||||
import { readFileSync, readdirSync, accessSync, existsSync, constants, chmodSync, statSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { dirname, join } from "node:path";
|
||||
import { homedir } from "node:os";
|
||||
@@ -167,6 +167,44 @@ function logEvent(level, event, data = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Startup file-mode reconciliation ───────────────────────────────────
|
||||
// Idempotently tightens OCP credential-bearing files to 700/600 so that
|
||||
// existing installs (created before this fix) are hardened on next restart.
|
||||
// Wrapped in try/catch — chmod failure must never crash startup.
|
||||
// Does NOT touch systemd units or launchd plists; those are managed by setup.mjs.
|
||||
function _tightenFileModesIfPossible() {
|
||||
const ocpDir = join(homedir(), ".ocp");
|
||||
const targets = [
|
||||
{ path: ocpDir, mode: 0o700, label: "~/.ocp (dir)" },
|
||||
{ path: join(ocpDir, "admin-key"), mode: 0o600, label: "~/.ocp/admin-key" },
|
||||
{ path: join(ocpDir, "ocp.db"), mode: 0o600, label: "~/.ocp/ocp.db" },
|
||||
];
|
||||
let tightened = 0;
|
||||
let alreadyOk = 0;
|
||||
for (const { path, mode, label } of targets) {
|
||||
try {
|
||||
const st = statSync(path);
|
||||
const current = st.mode & 0o777;
|
||||
if (current !== mode) {
|
||||
chmodSync(path, mode);
|
||||
tightened++;
|
||||
} else {
|
||||
alreadyOk++;
|
||||
}
|
||||
} catch (e) {
|
||||
if (e.code !== "ENOENT") {
|
||||
// File exists but chmod failed (e.g. EPERM) — log and move on
|
||||
logEvent("warn", "file_mode_tighten_failed", { path: label, error: e.message });
|
||||
}
|
||||
// ENOENT is fine — file doesn't exist yet
|
||||
}
|
||||
}
|
||||
if (tightened > 0) {
|
||||
logEvent("info", "file_modes_tightened", { tightened, alreadyOk });
|
||||
}
|
||||
}
|
||||
_tightenFileModesIfPossible();
|
||||
|
||||
// ── Circuit breaker (DISABLED) ──────────────────────────────────────────
|
||||
// Disabled: CLI proxy has its own retry logic, and the breaker was causing
|
||||
// cascading failures — once API got briefly slow, ALL agents lost connectivity
|
||||
@@ -202,25 +240,36 @@ const MODEL_MAP = Object.fromEntries([
|
||||
const MODELS = modelsConfig.models.map(m => ({ id: m.id, name: m.displayName }));
|
||||
|
||||
// ── Session management ──────────────────────────────────────────────────
|
||||
// Maps conversation IDs (from caller) to Claude CLI session UUIDs.
|
||||
// Maps namespaced session keys to Claude CLI session UUIDs.
|
||||
// Key format: "${keyName}|${conversationId}" — prevents cross-key collision
|
||||
// when two callers (different API keys or anon + authenticated) use the same
|
||||
// session_id string. Anonymous callers use "anon"; admin uses "admin".
|
||||
// Enables --resume for multi-turn conversations, reducing token waste.
|
||||
const sessions = new Map(); // conversationId → { uuid, messageCount, lastUsed, model }
|
||||
const sessions = new Map(); // `${keyName}|${conversationId}` → { uuid, messageCount, lastUsed, model }
|
||||
|
||||
// Build the namespaced key used for all sessions Map operations.
|
||||
// Returns null when conversationId is falsy (one-off requests bypass session tracking).
|
||||
function _sessionKey(conversationId, keyName) {
|
||||
return conversationId ? `${keyName || "anon"}|${conversationId}` : null;
|
||||
}
|
||||
|
||||
const sessionCleanupInterval = setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const [id, s] of sessions) {
|
||||
const idleMs = now - s.lastUsed;
|
||||
const ageMs = s.firstSeen ? now - s.firstSeen : null;
|
||||
// id is "${keyName}|${conversationId}"; strip prefix for log output
|
||||
const convIdShort = id.includes("|") ? id.slice(id.indexOf("|") + 1, id.indexOf("|") + 13) : id.slice(0, 12);
|
||||
if (idleMs > SESSION_TTL) {
|
||||
sessions.delete(id);
|
||||
console.log(`[session] expired ${id.slice(0, 12)}... (idle ${Math.round(idleMs / 60000)}m)`);
|
||||
logEvent("info", "session_expired", { conversationId: id.slice(0, 12) + "...", idleMs, ageMs });
|
||||
console.log(`[session] expired ${convIdShort}... (idle ${Math.round(idleMs / 60000)}m)`);
|
||||
logEvent("info", "session_expired", { conversationId: convIdShort + "...", idleMs, ageMs });
|
||||
} else if (ageMs !== null && ageMs > 4 * SESSION_TTL) {
|
||||
// #42 evidence-gathering: a session whose firstSeen is more than 4× TTL old
|
||||
// but whose lastUsed keeps getting bumped (never idle long enough to expire)
|
||||
// is the suspected bug. Log without action so the pattern can be confirmed
|
||||
// in /logs. Do NOT enforce an absolute age cap here speculatively.
|
||||
logEvent("warn", "session_long_lived", { conversationId: id.slice(0, 12) + "...", idleMs, ageMs });
|
||||
logEvent("warn", "session_long_lived", { conversationId: convIdShort + "...", idleMs, ageMs });
|
||||
}
|
||||
}
|
||||
}, 60000);
|
||||
@@ -427,7 +476,7 @@ function getModelTier(cliModel) {
|
||||
// ── Spawn claude CLI (shared setup) ─────────────────────────────────────
|
||||
// Resolves session logic, builds CLI args, spawns the process, and sets up
|
||||
// timeouts. Returns context object or throws synchronously.
|
||||
function spawnClaudeProcess(model, messages, conversationId) {
|
||||
function spawnClaudeProcess(model, messages, conversationId, keyName) {
|
||||
if (stats.activeRequests >= MAX_CONCURRENT) {
|
||||
throw new Error(`concurrency limit reached (${stats.activeRequests}/${MAX_CONCURRENT})`);
|
||||
}
|
||||
@@ -443,8 +492,11 @@ function spawnClaudeProcess(model, messages, conversationId) {
|
||||
let prompt;
|
||||
|
||||
// ── Session logic ──
|
||||
if (conversationId && sessions.has(conversationId)) {
|
||||
const session = sessions.get(conversationId);
|
||||
// sessionKey namespaces the Map key by keyName to prevent cross-caller collision
|
||||
// when two callers with different API keys share the same conversationId string.
|
||||
const sessionKey = _sessionKey(conversationId, keyName);
|
||||
if (sessionKey && sessions.has(sessionKey)) {
|
||||
const session = sessions.get(sessionKey);
|
||||
session.lastUsed = Date.now();
|
||||
sessionInfo = { uuid: session.uuid, resume: true };
|
||||
stats.sessionHits++;
|
||||
@@ -455,17 +507,17 @@ function spawnClaudeProcess(model, messages, conversationId) {
|
||||
: "";
|
||||
session.messageCount = messages.length;
|
||||
|
||||
console.log(`[session] resume conv=${conversationId.slice(0, 12)}... uuid=${session.uuid.slice(0, 8)}... msgs=${messages.length} prompt_chars=${prompt.length}`);
|
||||
console.log(`[session] resume conv=${conversationId.slice(0, 12)}... key=${keyName || "anon"} uuid=${session.uuid.slice(0, 8)}... msgs=${messages.length} prompt_chars=${prompt.length}`);
|
||||
|
||||
} else if (conversationId) {
|
||||
} else if (sessionKey) {
|
||||
const uuid = randomUUID();
|
||||
const now = Date.now();
|
||||
sessions.set(conversationId, { uuid, messageCount: messages.length, firstSeen: now, lastUsed: now, model: cliModel });
|
||||
sessions.set(sessionKey, { uuid, messageCount: messages.length, firstSeen: now, lastUsed: now, model: cliModel });
|
||||
sessionInfo = { uuid, resume: false };
|
||||
stats.sessionMisses++;
|
||||
prompt = messagesToPrompt(messages);
|
||||
|
||||
console.log(`[session] new conv=${conversationId.slice(0, 12)}... uuid=${uuid.slice(0, 8)}... msgs=${messages.length}`);
|
||||
console.log(`[session] new conv=${conversationId.slice(0, 12)}... key=${keyName || "anon"} uuid=${uuid.slice(0, 8)}... msgs=${messages.length}`);
|
||||
|
||||
} else {
|
||||
stats.oneOffRequests++;
|
||||
@@ -510,11 +562,11 @@ function spawnClaudeProcess(model, messages, conversationId) {
|
||||
proc.once("exit", cleanup);
|
||||
|
||||
function handleSessionFailure() {
|
||||
if (sessionInfo?.resume && conversationId) {
|
||||
if (sessionInfo?.resume && sessionKey) {
|
||||
console.warn(`[session] resume failed for ${conversationId.slice(0, 12)}..., removing stale session`);
|
||||
logEvent("warn", "session_failure", { mode: "resume", conversationId: conversationId.slice(0, 12) + "...", action: "deleted" });
|
||||
sessions.delete(conversationId);
|
||||
} else if (sessionInfo && !sessionInfo.resume && conversationId) {
|
||||
sessions.delete(sessionKey);
|
||||
} else if (sessionInfo && !sessionInfo.resume && sessionKey) {
|
||||
// #41 evidence-gathering: session-create failures currently leave a stale entry
|
||||
// in the sessions map. Log without action so the staleness pattern can be
|
||||
// confirmed in /logs before any code change. Do NOT delete here speculatively.
|
||||
@@ -557,11 +609,11 @@ function spawnClaudeProcess(model, messages, conversationId) {
|
||||
// On-demand spawning: each request spawns a fresh `claude -p` process.
|
||||
// No pool = no crash loops, no stale workers, no degraded states.
|
||||
// Stdin is written immediately so there's no 3s stdin timeout issue.
|
||||
function callClaude(model, messages, conversationId) {
|
||||
function callClaude(model, messages, conversationId, keyName) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let ctx;
|
||||
try {
|
||||
ctx = spawnClaudeProcess(model, messages, conversationId);
|
||||
ctx = spawnClaudeProcess(model, messages, conversationId, keyName);
|
||||
} catch (err) {
|
||||
return reject(err);
|
||||
}
|
||||
@@ -641,7 +693,7 @@ function callClaudeStreaming(model, messages, conversationId, res, authInfo = {}
|
||||
|
||||
let ctx;
|
||||
try {
|
||||
ctx = spawnClaudeProcess(model, messages, conversationId);
|
||||
ctx = spawnClaudeProcess(model, messages, conversationId, authInfo.keyName);
|
||||
} catch (err) {
|
||||
return jsonResponse(res, 500, { error: { message: err.message, type: "proxy_error" } });
|
||||
}
|
||||
@@ -1324,7 +1376,7 @@ async function handleChatCompletions(req, res) {
|
||||
// will re-read the freshly-populated cache entry here rather than spawning.
|
||||
const recheck = getCachedResponse(req._cacheHash, CACHE_TTL);
|
||||
if (recheck) return recheck.response;
|
||||
const c = await callClaude(model, messages, conversationId);
|
||||
const c = await callClaude(model, messages, conversationId, req._authKeyName);
|
||||
try { setCachedResponse(req._cacheHash, model, c); } catch (e) { logEvent("error", "cache_write_failed", { error: e.message }); }
|
||||
return c;
|
||||
});
|
||||
@@ -1346,7 +1398,7 @@ async function handleChatCompletions(req, res) {
|
||||
|
||||
// Fallback: cache disabled (CACHE_TTL=0) or no _cacheHash — original path untouched.
|
||||
try {
|
||||
const content = await callClaude(model, messages, conversationId);
|
||||
const content = await callClaude(model, messages, conversationId, req._authKeyName);
|
||||
const id = `chatcmpl-${randomUUID()}`;
|
||||
completionResponse(res, id, model, content);
|
||||
try { recordUsage({ keyId: req._authKeyId, keyName: req._authKeyName, model, promptChars, responseChars: content.length, elapsedMs: Date.now() - t0Usage, success: true }); } catch (e) { logEvent("error", "usage_record_failed", { error: e.message }); }
|
||||
@@ -1480,8 +1532,10 @@ const server = createServer(async (req, res) => {
|
||||
const uptimeMs = Date.now() - START_TIME;
|
||||
const sessionList = [];
|
||||
for (const [id, s] of sessions) {
|
||||
// id is "${keyName}|${conversationId}"; expose only the public-facing conversationId
|
||||
const convId = id.includes("|") ? id.slice(id.indexOf("|") + 1) : id;
|
||||
sessionList.push({
|
||||
id: id.slice(0, 12) + "...",
|
||||
id: convId.slice(0, 12) + "...",
|
||||
model: s.model,
|
||||
messages: s.messageCount,
|
||||
idleMs: Date.now() - s.lastUsed,
|
||||
@@ -1526,7 +1580,9 @@ const server = createServer(async (req, res) => {
|
||||
if (req.url === "/sessions" && req.method === "GET") {
|
||||
const list = [];
|
||||
for (const [id, s] of sessions) {
|
||||
list.push({ id, uuid: s.uuid, model: s.model, messages: s.messageCount, lastUsed: new Date(s.lastUsed).toISOString() });
|
||||
// id is "${keyName}|${conversationId}"; expose only the public-facing conversationId
|
||||
const convId = id.includes("|") ? id.slice(id.indexOf("|") + 1) : id;
|
||||
list.push({ id: convId, uuid: s.uuid, model: s.model, messages: s.messageCount, lastUsed: new Date(s.lastUsed).toISOString() });
|
||||
}
|
||||
return jsonResponse(res, 200, { sessions: list });
|
||||
}
|
||||
@@ -1616,14 +1672,45 @@ const server = createServer(async (req, res) => {
|
||||
}
|
||||
|
||||
if (req.url?.startsWith("/api/usage") && req.method === "GET") {
|
||||
if (!isAdmin) return jsonResponse(res, 403, { error: "Admin access required" });
|
||||
// Least-privilege scope rules (security audit follow-up):
|
||||
// - non-admin authenticated key → only own rows
|
||||
// - anonymous (PROXY_ANONYMOUS_KEY) → only "anonymous" rows; ?all=true ignored
|
||||
// - admin without ?all=true → only own ("admin") rows
|
||||
// - admin with ?all=true → full byKey/recent (legacy behavior); audited
|
||||
// Authenticated callers are required (anyone reaching here passed the auth gate above);
|
||||
// remote+no-auth requests would have been rejected before this point.
|
||||
const url = new URL(req.url, `http://${BIND_ADDRESS}:${PORT}`);
|
||||
const since = url.searchParams.get("since");
|
||||
const until = url.searchParams.get("until");
|
||||
const wantAll = url.searchParams.get("all") === "true";
|
||||
const callerName = req._authKeyName;
|
||||
|
||||
// Anonymous callers may never opt into all-keys view, even if they pass ?all=true.
|
||||
const isAnonCaller = callerName === "anonymous";
|
||||
const fullScope = isAdmin && wantAll && !isAnonCaller;
|
||||
|
||||
// scopeName === null when fullScope is true (no filter); otherwise the key_name to filter by.
|
||||
const scopeName = fullScope ? null : callerName;
|
||||
|
||||
if (fullScope) {
|
||||
logEvent("info", "admin_usage_full_scope", { caller: callerName, ip: req.socket.remoteAddress || null });
|
||||
}
|
||||
|
||||
const byKeyAll = getUsageByKey({ since, until });
|
||||
const recentAll = getRecentUsage(Math.min(parseInt(url.searchParams.get("limit") || "50", 10), 500));
|
||||
const timeline = getUsageTimeline({
|
||||
keyName: scopeName || undefined,
|
||||
hours: Math.min(parseInt(url.searchParams.get("hours") || "24", 10), 720),
|
||||
});
|
||||
|
||||
const byKey = scopeName ? byKeyAll.filter((row) => row.key_name === scopeName) : byKeyAll;
|
||||
const recent = scopeName ? recentAll.filter((row) => row.key_name === scopeName) : recentAll;
|
||||
|
||||
return jsonResponse(res, 200, {
|
||||
byKey: getUsageByKey({ since, until }),
|
||||
timeline: getUsageTimeline({ hours: Math.min(parseInt(url.searchParams.get("hours") || "24", 10), 720) }),
|
||||
recent: getRecentUsage(Math.min(parseInt(url.searchParams.get("limit") || "50", 10), 500)),
|
||||
byKey,
|
||||
timeline,
|
||||
recent,
|
||||
scope: { self: scopeName, all: fullScope },
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,8 @@
|
||||
* 4. Creates start.sh for easy launch
|
||||
* 5. Optionally starts the proxy
|
||||
*/
|
||||
import { readFileSync, writeFileSync, existsSync, mkdirSync, unlinkSync, readdirSync } from "node:fs";
|
||||
import { readFileSync, writeFileSync, existsSync, mkdirSync, unlinkSync, readdirSync, chmodSync } from "node:fs";
|
||||
import { mergePlistEnv, mergeSystemdEnv } from "./scripts/lib/plist-merge.mjs";
|
||||
import { execSync } from "node:child_process";
|
||||
import { join, dirname } from "node:path";
|
||||
import { homedir } from "node:os";
|
||||
@@ -424,8 +425,15 @@ if (!DRY_RUN) {
|
||||
</plist>
|
||||
`;
|
||||
|
||||
writeFileSync(plistPath, plistXml);
|
||||
log(`Plist written: ${plistPath}`);
|
||||
const existingPlist = existsSync(plistPath) ? readFileSync(plistPath, "utf8") : null;
|
||||
const finalPlistXml = mergePlistEnv(existingPlist, plistXml);
|
||||
writeFileSync(plistPath, finalPlistXml);
|
||||
chmodSync(plistPath, 0o600);
|
||||
if (existingPlist && finalPlistXml !== plistXml) {
|
||||
log(`Plist written: ${plistPath} (mode 600, preserved user env vars)`);
|
||||
} else {
|
||||
log(`Plist written: ${plistPath} (mode 600)`);
|
||||
}
|
||||
|
||||
// Bootout first (in case it was already loaded) then bootstrap
|
||||
try { execSync(`launchctl bootout gui/$(id -u) "${plistPath}" 2>/dev/null`); } catch { /* ignore */ }
|
||||
@@ -458,8 +466,15 @@ StandardError=append:${logPath}
|
||||
WantedBy=default.target
|
||||
`;
|
||||
|
||||
writeFileSync(servicePath, serviceUnit);
|
||||
log(`Service file written: ${servicePath}`);
|
||||
const existingService = existsSync(servicePath) ? readFileSync(servicePath, "utf8") : null;
|
||||
const finalServiceUnit = mergeSystemdEnv(existingService, serviceUnit);
|
||||
writeFileSync(servicePath, finalServiceUnit);
|
||||
chmodSync(servicePath, 0o600);
|
||||
if (existingService && finalServiceUnit !== serviceUnit) {
|
||||
log(`Service file written: ${servicePath} (mode 600, preserved user env vars)`);
|
||||
} else {
|
||||
log(`Service file written: ${servicePath} (mode 600)`);
|
||||
}
|
||||
|
||||
execSync(`systemctl --user daemon-reload`);
|
||||
execSync(`systemctl --user enable ocp-proxy`);
|
||||
|
||||
@@ -454,6 +454,503 @@ async function runSingleflightTests() {
|
||||
|
||||
await runSingleflightTests();
|
||||
|
||||
// ── Plist Env Merge Tests ──
|
||||
import { mergePlistEnv, mergeSystemdEnv } from "./scripts/lib/plist-merge.mjs";
|
||||
|
||||
console.log("\nPlist env merge:");
|
||||
|
||||
const SAMPLE_TEMPLATE_PLIST = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Label</key>
|
||||
<string>dev.ocp.proxy</string>
|
||||
<key>EnvironmentVariables</key>
|
||||
<dict>
|
||||
<key>CLAUDE_PROXY_PORT</key>
|
||||
<string>3478</string>
|
||||
<key>CLAUDE_BIND</key>
|
||||
<string>127.0.0.1</string>
|
||||
<key>CLAUDE_AUTH_MODE</key>
|
||||
<string>multi</string>
|
||||
</dict>
|
||||
</dict>
|
||||
</plist>`;
|
||||
|
||||
const SAMPLE_EXISTING_PLIST = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Label</key>
|
||||
<string>dev.ocp.proxy</string>
|
||||
<key>EnvironmentVariables</key>
|
||||
<dict>
|
||||
<key>CLAUDE_PROXY_PORT</key>
|
||||
<string>3456</string>
|
||||
<key>CLAUDE_BIND</key>
|
||||
<string>127.0.0.1</string>
|
||||
<key>CLAUDE_AUTH_MODE</key>
|
||||
<string>none</string>
|
||||
<key>CLAUDE_HEARTBEAT_INTERVAL</key>
|
||||
<string>2000</string>
|
||||
<key>CLAUDE_CACHE_TTL</key>
|
||||
<string>600</string>
|
||||
</dict>
|
||||
</dict>
|
||||
</plist>`;
|
||||
|
||||
test("mergePlistEnv preserves unknown user keys", () => {
|
||||
const merged = mergePlistEnv(SAMPLE_EXISTING_PLIST, SAMPLE_TEMPLATE_PLIST);
|
||||
assert.match(merged, /<key>CLAUDE_HEARTBEAT_INTERVAL<\/key>\s*<string>2000<\/string>/);
|
||||
assert.match(merged, /<key>CLAUDE_CACHE_TTL<\/key>\s*<string>600<\/string>/);
|
||||
});
|
||||
|
||||
test("mergePlistEnv overrides known template keys", () => {
|
||||
const merged = mergePlistEnv(SAMPLE_EXISTING_PLIST, SAMPLE_TEMPLATE_PLIST);
|
||||
assert.match(merged, /<key>CLAUDE_PROXY_PORT<\/key>\s*<string>3478<\/string>/);
|
||||
assert.match(merged, /<key>CLAUDE_AUTH_MODE<\/key>\s*<string>multi<\/string>/);
|
||||
});
|
||||
|
||||
test("mergePlistEnv first-install returns template unchanged when existing is null", () => {
|
||||
const merged = mergePlistEnv(null, SAMPLE_TEMPLATE_PLIST);
|
||||
assert.equal(merged, SAMPLE_TEMPLATE_PLIST);
|
||||
});
|
||||
|
||||
test("mergePlistEnv first-install returns template unchanged when existing is empty", () => {
|
||||
const merged = mergePlistEnv("", SAMPLE_TEMPLATE_PLIST);
|
||||
assert.equal(merged, SAMPLE_TEMPLATE_PLIST);
|
||||
});
|
||||
|
||||
const SAMPLE_TEMPLATE_SYSTEMD = `[Unit]
|
||||
Description=OCP — Open Claude Proxy
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
ExecStart=/usr/bin/node /home/u/ocp/server.mjs
|
||||
Environment=CLAUDE_PROXY_PORT=3478
|
||||
Environment=CLAUDE_BIND=127.0.0.1
|
||||
Environment=CLAUDE_AUTH_MODE=multi
|
||||
Restart=always
|
||||
`;
|
||||
|
||||
const SAMPLE_EXISTING_SYSTEMD = `[Unit]
|
||||
Description=OCP — Open Claude Proxy
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
ExecStart=/usr/bin/node /home/u/ocp/server.mjs
|
||||
Environment=CLAUDE_PROXY_PORT=3456
|
||||
Environment=CLAUDE_BIND=127.0.0.1
|
||||
Environment=CLAUDE_AUTH_MODE=none
|
||||
Environment=CLAUDE_HEARTBEAT_INTERVAL=2000
|
||||
Environment=CLAUDE_CACHE_TTL=600
|
||||
Restart=always
|
||||
`;
|
||||
|
||||
test("mergeSystemdEnv preserves unknown user Environment lines", () => {
|
||||
const merged = mergeSystemdEnv(SAMPLE_EXISTING_SYSTEMD, SAMPLE_TEMPLATE_SYSTEMD);
|
||||
assert.match(merged, /Environment=CLAUDE_HEARTBEAT_INTERVAL=2000/);
|
||||
assert.match(merged, /Environment=CLAUDE_CACHE_TTL=600/);
|
||||
});
|
||||
|
||||
test("mergeSystemdEnv overrides known template keys", () => {
|
||||
const merged = mergeSystemdEnv(SAMPLE_EXISTING_SYSTEMD, SAMPLE_TEMPLATE_SYSTEMD);
|
||||
assert.match(merged, /Environment=CLAUDE_PROXY_PORT=3478/);
|
||||
assert.match(merged, /Environment=CLAUDE_AUTH_MODE=multi/);
|
||||
});
|
||||
|
||||
test("mergeSystemdEnv first-install returns template unchanged", () => {
|
||||
assert.equal(mergeSystemdEnv(null, SAMPLE_TEMPLATE_SYSTEMD), SAMPLE_TEMPLATE_SYSTEMD);
|
||||
assert.equal(mergeSystemdEnv("", SAMPLE_TEMPLATE_SYSTEMD), SAMPLE_TEMPLATE_SYSTEMD);
|
||||
});
|
||||
|
||||
test("mergePlistEnv is idempotent", () => {
|
||||
const r1 = mergePlistEnv(SAMPLE_EXISTING_PLIST, SAMPLE_TEMPLATE_PLIST);
|
||||
assert.equal(mergePlistEnv(r1, SAMPLE_TEMPLATE_PLIST), r1);
|
||||
});
|
||||
|
||||
test("mergeSystemdEnv is idempotent", () => {
|
||||
const r1 = mergeSystemdEnv(SAMPLE_EXISTING_SYSTEMD, SAMPLE_TEMPLATE_SYSTEMD);
|
||||
assert.equal(mergeSystemdEnv(r1, SAMPLE_TEMPLATE_SYSTEMD), r1);
|
||||
});
|
||||
|
||||
// ── Doctor JSON Contract Tests ──
|
||||
import { runDoctor } from "./scripts/doctor.mjs";
|
||||
|
||||
console.log("\nDoctor:");
|
||||
|
||||
test("doctor --json shape: required top-level keys", async () => {
|
||||
const result = await runDoctor({ skipNetwork: true, mockVersion: "v3.10.0", mockLatest: "v3.14.0" });
|
||||
for (const k of ["schema_version", "ready_to_upgrade", "current_version", "latest_version",
|
||||
"from_version_supported", "fail_count", "warn_count", "checks", "next_action"]) {
|
||||
assert.ok(k in result, `missing key: ${k}`);
|
||||
}
|
||||
assert.equal(result.schema_version, "1");
|
||||
});
|
||||
|
||||
test("doctor detects from-version < v3.4.0 → fresh_install", async () => {
|
||||
const result = await runDoctor({ skipNetwork: true, mockVersion: "v3.2.0", mockLatest: "v3.14.0" });
|
||||
assert.equal(result.from_version_supported, false);
|
||||
assert.equal(result.next_action.kind, "fresh_install");
|
||||
assert.ok(Array.isArray(result.next_action.ai_executable));
|
||||
assert.ok(result.next_action.ai_executable.length > 0);
|
||||
});
|
||||
|
||||
test("doctor next_action.kind enum is one of allowed values", async () => {
|
||||
const result = await runDoctor({ skipNetwork: true, mockVersion: "v3.10.0", mockLatest: "v3.14.0" });
|
||||
const ALLOWED = ["noop", "update", "upgrade", "fresh_install", "fix_oauth", "fix_service"];
|
||||
assert.ok(ALLOWED.includes(result.next_action.kind), `kind=${result.next_action.kind} not in enum`);
|
||||
});
|
||||
|
||||
test("doctor noop when current==latest", async () => {
|
||||
const result = await runDoctor({ skipNetwork: true, mockVersion: "v3.14.0", mockLatest: "v3.14.0" });
|
||||
assert.equal(result.next_action.kind, "noop");
|
||||
assert.equal(result.ready_to_upgrade, true);
|
||||
});
|
||||
|
||||
test("doctor patch-bump same minor → update kind", async () => {
|
||||
const result = await runDoctor({ skipNetwork: true, mockVersion: "v3.14.0", mockLatest: "v3.14.1" });
|
||||
assert.equal(result.next_action.kind, "update");
|
||||
});
|
||||
|
||||
test("doctor cross-minor → upgrade kind", async () => {
|
||||
const result = await runDoctor({ skipNetwork: true, mockVersion: "v3.10.0", mockLatest: "v3.14.0" });
|
||||
assert.equal(result.next_action.kind, "upgrade");
|
||||
});
|
||||
|
||||
test("doctor OAuth FAIL → fix_oauth kind", async () => {
|
||||
const result = await runDoctor({
|
||||
skipNetwork: false,
|
||||
mockVersion: "v3.10.0",
|
||||
mockLatest: "v3.14.0",
|
||||
mockHealth: { status: 200, body: { auth: { ok: false, message: "ENOEXEC" } } }
|
||||
});
|
||||
assert.equal(result.next_action.kind, "fix_oauth");
|
||||
assert.ok(result.next_action.ai_executable.some(c => c.includes("install.cjs")));
|
||||
});
|
||||
|
||||
test("doctor service down → fix_service kind", async () => {
|
||||
const result = await runDoctor({
|
||||
skipNetwork: false,
|
||||
mockVersion: "v3.10.0",
|
||||
mockLatest: "v3.14.0",
|
||||
mockHealth: { error: "ECONNREFUSED" }
|
||||
});
|
||||
assert.equal(result.next_action.kind, "fix_service");
|
||||
});
|
||||
|
||||
test("doctor unparseable version → fresh_install", async () => {
|
||||
const result = await runDoctor({ skipNetwork: true, mockVersion: "garbage", mockLatest: "v3.14.0" });
|
||||
assert.equal(result.from_version_supported, false);
|
||||
assert.equal(result.next_action.kind, "fresh_install");
|
||||
});
|
||||
|
||||
test("doctor empty health body → fix_service (not fix_oauth)", async () => {
|
||||
const result = await runDoctor({
|
||||
skipNetwork: false,
|
||||
mockVersion: "v3.10.0",
|
||||
mockLatest: "v3.14.0",
|
||||
mockHealth: { status: 200, body: null }
|
||||
});
|
||||
assert.equal(result.next_action.kind, "fix_service");
|
||||
});
|
||||
|
||||
test("doctor falls back to currentVersion when origin/main unreachable (no stale latest)", async () => {
|
||||
// Use a non-existent ocpDir so git command fails; without the fix this would still
|
||||
// hard-code v3.14.0 as latest and recommend a downgrade for a future v3.15.0+ user.
|
||||
const result = await runDoctor({
|
||||
skipNetwork: true,
|
||||
mockVersion: "v3.15.0",
|
||||
ocpDir: "/nonexistent-ocp-dir-for-test"
|
||||
});
|
||||
assert.equal(result.latest_version, "v3.15.0");
|
||||
assert.equal(result.next_action.kind, "noop");
|
||||
});
|
||||
|
||||
// ── Upgrade Tests ──
|
||||
import { runUpgrade } from "./scripts/upgrade.mjs";
|
||||
|
||||
console.log("\nUpgrade:");
|
||||
|
||||
test("upgrade --dry-run prints plan, no side effects", async () => {
|
||||
const result = await runUpgrade({
|
||||
dryRun: true,
|
||||
yes: true,
|
||||
mockDoctor: { ready_to_upgrade: true, next_action: { kind: "upgrade" }, current_version: "v3.10.0", latest_version: "v3.14.0" }
|
||||
});
|
||||
assert.equal(result.executed, false);
|
||||
assert.ok(result.plan.length > 0);
|
||||
assert.ok(result.plan.some(line => line.toLowerCase().includes("snapshot")));
|
||||
});
|
||||
|
||||
test("upgrade noop returns early when current==latest", async () => {
|
||||
const result = await runUpgrade({
|
||||
yes: true,
|
||||
mockDoctor: { ready_to_upgrade: true, next_action: { kind: "noop" }, current_version: "v3.14.0", latest_version: "v3.14.0" }
|
||||
});
|
||||
assert.equal(result.path, "noop");
|
||||
assert.equal(result.executed, true);
|
||||
assert.equal(result.changed, false);
|
||||
});
|
||||
|
||||
test("upgrade aborts on doctor FAIL", async () => {
|
||||
await assert.rejects(async () => {
|
||||
await runUpgrade({
|
||||
yes: true,
|
||||
mockDoctor: { ready_to_upgrade: false, fail_count: 1, next_action: { kind: "fix_oauth" } }
|
||||
});
|
||||
}, /doctor FAIL/);
|
||||
});
|
||||
|
||||
test("upgrade full path executes 5 phases", async () => {
|
||||
const result = await runUpgrade({
|
||||
yes: true,
|
||||
dryRun: false,
|
||||
mockExec: true,
|
||||
mockDoctor: { ready_to_upgrade: true, next_action: { kind: "upgrade" },
|
||||
current_version: "v3.10.0", latest_version: "v3.14.0" }
|
||||
});
|
||||
assert.equal(result.path, "upgrade");
|
||||
// Plan asks for 6 phases by name; verify each appears as a phase entry
|
||||
const phaseNames = result.phases.map(p => p.name);
|
||||
for (const expected of ["pre-flight", "snapshot", "fetch+install", "reconfigure", "restart", "post-flight"]) {
|
||||
assert.ok(phaseNames.includes(expected), `missing phase: ${expected}; got ${phaseNames.join(",")}`);
|
||||
}
|
||||
});
|
||||
|
||||
// ── Snapshot Tests ──
|
||||
import { writeSnapshot, readSnapshot, listSnapshots, gcSnapshots } from "./scripts/lib/snapshot.mjs";
|
||||
import { mkdtempSync, rmSync, mkdirSync as tMkdirSync, writeFileSync as testWriteFile, existsSync as testExistsSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join as testJoin } from "node:path";
|
||||
|
||||
console.log("\nSnapshot:");
|
||||
|
||||
test("writeSnapshot creates dir + manifest files", () => {
|
||||
const root = mkdtempSync(testJoin(tmpdir(), "ocp-snap-test-"));
|
||||
const dotOcp = testJoin(root, ".ocp");
|
||||
tMkdirSync(dotOcp, { recursive: true });
|
||||
testWriteFile(testJoin(dotOcp, "ocp.db"), "fake-sqlite-bytes");
|
||||
|
||||
const path = writeSnapshot({
|
||||
homeDir: root,
|
||||
fromCommit: "abc1234",
|
||||
fromVersion: "v3.10.0",
|
||||
toVersion: "v3.14.0",
|
||||
extraFiles: []
|
||||
});
|
||||
const m = readSnapshot(path);
|
||||
assert.equal(m.fromCommit, "abc1234");
|
||||
assert.equal(m.fromVersion, "v3.10.0");
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("listSnapshots returns sorted by ISO timestamp", () => {
|
||||
const root = mkdtempSync(testJoin(tmpdir(), "ocp-snap-list-"));
|
||||
const dotOcp = testJoin(root, ".ocp");
|
||||
tMkdirSync(dotOcp, { recursive: true });
|
||||
for (const ts of ["2026-05-01T10:00:00Z", "2026-05-02T10:00:00Z", "2026-05-03T10:00:00Z"]) {
|
||||
tMkdirSync(testJoin(dotOcp, `upgrade-snapshot-${ts}`));
|
||||
}
|
||||
const list = listSnapshots(root);
|
||||
assert.equal(list.length, 3);
|
||||
assert.ok(list[0].path.includes("2026-05-01"));
|
||||
assert.ok(list[2].path.includes("2026-05-03"));
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("upgrade error after snapshot carries snapshotPath + hint", async () => {
|
||||
// Use mockExec=true so no real commands are run.
|
||||
// Verify the success path returns a snapshotPath (Fix B regression guard).
|
||||
const result = await runUpgrade({
|
||||
yes: true,
|
||||
dryRun: false,
|
||||
mockExec: true,
|
||||
mockDoctor: { ready_to_upgrade: true, next_action: { kind: "upgrade" },
|
||||
current_version: "v3.10.0", latest_version: "v3.14.0" }
|
||||
});
|
||||
assert.ok(result.snapshotPath, "successful upgrade returns snapshotPath");
|
||||
assert.equal(result.path, "upgrade");
|
||||
assert.equal(result.executed, true);
|
||||
});
|
||||
|
||||
test("upgrade fresh_install requires --yes for non-interactive", async () => {
|
||||
await assert.rejects(async () => {
|
||||
await runUpgrade({
|
||||
yes: false,
|
||||
mockExec: true,
|
||||
mockDoctor: { ready_to_upgrade: false, from_version_supported: false,
|
||||
next_action: { kind: "fresh_install", ai_executable: ["echo would-rm-rf"] },
|
||||
current_version: "v3.2.0", latest_version: "v3.14.0" }
|
||||
});
|
||||
}, /requires --yes/);
|
||||
});
|
||||
|
||||
test("upgrade fresh_install with --yes runs ai_executable", async () => {
|
||||
const result = await runUpgrade({
|
||||
yes: true,
|
||||
mockExec: true,
|
||||
mockDoctor: { ready_to_upgrade: false, from_version_supported: false,
|
||||
next_action: { kind: "fresh_install",
|
||||
ai_executable: ["echo step-1", "echo step-2", "echo step-3"] },
|
||||
current_version: "v3.2.0", latest_version: "v3.14.0" }
|
||||
});
|
||||
assert.equal(result.path, "fresh_install");
|
||||
assert.equal(result.steps.length, 3);
|
||||
});
|
||||
|
||||
test("rollback --list returns snapshots", async () => {
|
||||
const result = await runUpgrade({
|
||||
rollback: true,
|
||||
list: true,
|
||||
mockSnapshots: [
|
||||
{ name: "upgrade-snapshot-2026-05-01T10:00:00Z", path: "/tmp/snap-1" },
|
||||
{ name: "upgrade-snapshot-2026-05-02T10:00:00Z", path: "/tmp/snap-2" }
|
||||
]
|
||||
});
|
||||
assert.equal(result.path, "rollback-list");
|
||||
assert.equal(result.snapshots.length, 2);
|
||||
});
|
||||
|
||||
test("rollback with no snapshots fails clearly", async () => {
|
||||
await assert.rejects(async () => {
|
||||
await runUpgrade({ rollback: true, dryRun: true, mockSnapshots: [] });
|
||||
}, /no upgrade snapshots/);
|
||||
});
|
||||
|
||||
test("rollback --dry-run produces a plan without mutation", async () => {
|
||||
const result = await runUpgrade({
|
||||
rollback: true,
|
||||
dryRun: true,
|
||||
mockSnapshots: [{ name: "upgrade-snapshot-2026-05-11T08:30:00Z", path: "/tmp/snap-x" }],
|
||||
mockSnapshotMeta: { fromCommit: "abc1234", fromVersion: "v3.10.0", toVersion: "v3.14.0", path: "/tmp/snap-x" }
|
||||
});
|
||||
assert.equal(result.path, "rollback-dry-run");
|
||||
assert.equal(result.executed, false);
|
||||
assert.ok(result.plan.length > 0);
|
||||
});
|
||||
|
||||
test("rollback latest snapshot restores files (mockExec)", async () => {
|
||||
const result = await runUpgrade({
|
||||
rollback: true,
|
||||
yes: true,
|
||||
mockExec: true,
|
||||
mockSnapshots: [{ name: "upgrade-snapshot-2026-05-11T08:30:00Z", path: "/tmp/snap-x" }],
|
||||
mockSnapshotMeta: { fromCommit: "abc1234", fromVersion: "v3.10.0", toVersion: "v3.14.0", path: "/tmp/snap-x" }
|
||||
});
|
||||
assert.equal(result.path, "rollback");
|
||||
assert.equal(result.executed, true);
|
||||
assert.ok(result.phases.some(p => p.name === "git-checkout"));
|
||||
});
|
||||
|
||||
test("gcSnapshots keeps last N regardless of age", () => {
|
||||
const root = mkdtempSync(testJoin(tmpdir(), "ocp-gc-test-"));
|
||||
const dotOcp = testJoin(root, ".ocp");
|
||||
tMkdirSync(dotOcp, { recursive: true });
|
||||
for (const ts of ["2026-04-01T10:00:00Z", "2026-04-15T10:00:00Z", "2026-04-30T10:00:00Z", "2026-05-01T10:00:00Z", "2026-05-10T10:00:00Z"]) {
|
||||
tMkdirSync(testJoin(dotOcp, `upgrade-snapshot-${ts}`));
|
||||
}
|
||||
const result = gcSnapshots(root, { keepCount: 3, keepDays: 0, now: new Date("2026-05-11T00:00:00Z") });
|
||||
assert.equal(result.kept.length, 3);
|
||||
assert.equal(result.removed.length, 2);
|
||||
assert.ok(result.kept[0].name.includes("2026-04-30"));
|
||||
assert.ok(result.kept[2].name.includes("2026-05-10"));
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("gcSnapshots keeps snapshots newer than keepDays regardless of count", () => {
|
||||
const root = mkdtempSync(testJoin(tmpdir(), "ocp-gc-days-"));
|
||||
const dotOcp = testJoin(root, ".ocp");
|
||||
tMkdirSync(dotOcp, { recursive: true });
|
||||
for (const ts of ["2026-04-01T10:00:00Z", "2026-04-15T10:00:00Z", "2026-04-30T10:00:00Z", "2026-05-01T10:00:00Z", "2026-05-10T10:00:00Z"]) {
|
||||
tMkdirSync(testJoin(dotOcp, `upgrade-snapshot-${ts}`));
|
||||
}
|
||||
// keepCount=1 but keepDays=15 means anything from after 2026-04-26 is kept too
|
||||
const result = gcSnapshots(root, { keepCount: 1, keepDays: 15, now: new Date("2026-05-11T00:00:00Z") });
|
||||
// Kept: 2026-04-30 (within 15 days), 2026-05-01 (within 15 days), 2026-05-10 (within 15 days)
|
||||
assert.ok(result.kept.length >= 3);
|
||||
// Removed: 2026-04-01, 2026-04-15
|
||||
assert.ok(result.removed.some(s => s.name.includes("2026-04-01")));
|
||||
});
|
||||
|
||||
test("gcSnapshots never deletes the most recent snapshot", () => {
|
||||
const root = mkdtempSync(testJoin(tmpdir(), "ocp-gc-recent-"));
|
||||
const dotOcp = testJoin(root, ".ocp");
|
||||
tMkdirSync(dotOcp, { recursive: true });
|
||||
tMkdirSync(testJoin(dotOcp, "upgrade-snapshot-2026-01-01T10:00:00Z"));
|
||||
// Even with keepCount=0 and keepDays=0, the most recent must survive
|
||||
const result = gcSnapshots(root, { keepCount: 0, keepDays: 0, now: new Date("2026-05-11T00:00:00Z") });
|
||||
assert.equal(result.kept.length, 1);
|
||||
assert.equal(result.removed.length, 0);
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("gcSnapshots --dry-run reports plan without deleting", () => {
|
||||
const root = mkdtempSync(testJoin(tmpdir(), "ocp-gc-dryrun-"));
|
||||
const dotOcp = testJoin(root, ".ocp");
|
||||
tMkdirSync(dotOcp, { recursive: true });
|
||||
for (const ts of ["2026-04-01T10:00:00Z", "2026-04-15T10:00:00Z", "2026-05-10T10:00:00Z"]) {
|
||||
tMkdirSync(testJoin(dotOcp, `upgrade-snapshot-${ts}`));
|
||||
}
|
||||
const result = gcSnapshots(root, { keepCount: 1, keepDays: 0, dryRun: true, now: new Date("2026-05-11T00:00:00Z") });
|
||||
assert.equal(result.dryRun, true);
|
||||
assert.equal(result.removed.length, 2);
|
||||
// Files still exist
|
||||
assert.ok(testExistsSync(testJoin(dotOcp, "upgrade-snapshot-2026-04-01T10:00:00Z")));
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
// ── Doctor --check oauth fast path tests ──
|
||||
console.log("\nDoctor --check oauth:");
|
||||
|
||||
await asyncTest("doctor --check oauth runs only oauth check (skips version/from-version)", async () => {
|
||||
const result = await runDoctor({
|
||||
checkOnly: "oauth",
|
||||
mockVersion: "v3.10.0",
|
||||
mockLatest: "v3.14.0",
|
||||
mockHealth: { status: 200, body: { auth: { ok: true, message: "authenticated" } } }
|
||||
});
|
||||
// Should still produce a valid result object
|
||||
assert.equal(result.schema_version, "1");
|
||||
// checks[] should only contain oauth_ok (no current_version, no from_version_supported)
|
||||
const ids = result.checks.map(c => c.id);
|
||||
assert.deepEqual(ids, ["oauth_ok"]);
|
||||
assert.equal(result.next_action.kind, "noop");
|
||||
});
|
||||
|
||||
await asyncTest("doctor --check oauth + OAuth FAIL → fix_oauth", async () => {
|
||||
const result = await runDoctor({
|
||||
checkOnly: "oauth",
|
||||
mockHealth: { status: 200, body: { auth: { ok: false, message: "ENOEXEC" } } }
|
||||
});
|
||||
const ids = result.checks.map(c => c.id);
|
||||
assert.deepEqual(ids, ["oauth_ok"]);
|
||||
assert.equal(result.next_action.kind, "fix_oauth");
|
||||
assert.equal(result.fail_count, 1);
|
||||
});
|
||||
|
||||
await asyncTest("doctor --check oauth + service down → fix_service", async () => {
|
||||
const result = await runDoctor({
|
||||
checkOnly: "oauth",
|
||||
mockHealth: { error: "ECONNREFUSED" }
|
||||
});
|
||||
const ids = result.checks.map(c => c.id);
|
||||
assert.deepEqual(ids, ["oauth_ok"]);
|
||||
assert.equal(result.next_action.kind, "fix_service");
|
||||
assert.equal(result.fail_count, 1);
|
||||
});
|
||||
|
||||
await asyncTest("doctor --check oauth + 200 with null body → fix_service", async () => {
|
||||
const result = await runDoctor({
|
||||
checkOnly: "oauth",
|
||||
mockHealth: { status: 200, body: null }
|
||||
});
|
||||
const ids = result.checks.map(c => c.id);
|
||||
assert.deepEqual(ids, ["oauth_ok"]);
|
||||
assert.equal(result.next_action.kind, "fix_service");
|
||||
assert.equal(result.fail_count, 1);
|
||||
});
|
||||
|
||||
// ── Cleanup ──
|
||||
closeDb();
|
||||
|
||||
|
||||
Reference in New Issue
Block a user