@openpalm/lib 0.10.2 → 0.11.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +2 -2
  2. package/package.json +7 -3
  3. package/src/control-plane/admin-token.ts +73 -0
  4. package/src/control-plane/akm-vault.test.ts +105 -0
  5. package/src/control-plane/akm-vault.ts +307 -0
  6. package/src/control-plane/channels.ts +3 -3
  7. package/src/control-plane/cleanup-guardrails.test.ts +8 -9
  8. package/src/control-plane/compose-args.test.ts +25 -24
  9. package/src/control-plane/compose-errors.test.ts +106 -0
  10. package/src/control-plane/compose-errors.ts +117 -0
  11. package/src/control-plane/config-persistence.ts +103 -65
  12. package/src/control-plane/core-assets.test.ts +104 -0
  13. package/src/control-plane/core-assets.ts +54 -57
  14. package/src/control-plane/docker.ts +55 -21
  15. package/src/control-plane/env.test.ts +25 -1
  16. package/src/control-plane/env.ts +80 -0
  17. package/src/control-plane/home.ts +66 -69
  18. package/src/control-plane/host-opencode.test.ts +260 -0
  19. package/src/control-plane/host-opencode.ts +229 -0
  20. package/src/control-plane/install-edge-cases.test.ts +187 -289
  21. package/src/control-plane/install-lock.ts +157 -0
  22. package/src/control-plane/lifecycle.ts +34 -65
  23. package/src/control-plane/markdown-task.ts +200 -0
  24. package/src/control-plane/migrate-0110.test.ts +177 -0
  25. package/src/control-plane/migrate-0110.ts +99 -0
  26. package/src/control-plane/paths.ts +82 -0
  27. package/src/control-plane/provider-config.ts +2 -2
  28. package/src/control-plane/provider-models.ts +154 -0
  29. package/src/control-plane/registry-components.test.ts +105 -27
  30. package/src/control-plane/registry.test.ts +49 -47
  31. package/src/control-plane/registry.ts +71 -50
  32. package/src/control-plane/rollback.ts +17 -16
  33. package/src/control-plane/scheduler.ts +75 -262
  34. package/src/control-plane/secret-backend.test.ts +98 -111
  35. package/src/control-plane/secret-backend.ts +221 -181
  36. package/src/control-plane/secret-mappings.ts +4 -8
  37. package/src/control-plane/secrets.ts +93 -51
  38. package/src/control-plane/setup-config.schema.json +5 -17
  39. package/src/control-plane/setup-status.ts +9 -29
  40. package/src/control-plane/setup-validation.ts +23 -23
  41. package/src/control-plane/setup.test.ts +138 -239
  42. package/src/control-plane/setup.ts +215 -130
  43. package/src/control-plane/skeleton-guardrail.test.ts +151 -0
  44. package/src/control-plane/spec-to-env.test.ts +59 -58
  45. package/src/control-plane/spec-to-env.ts +52 -142
  46. package/src/control-plane/spec-validator.ts +2 -99
  47. package/src/control-plane/stack-spec.test.ts +21 -77
  48. package/src/control-plane/stack-spec.ts +7 -83
  49. package/src/control-plane/types.ts +12 -28
  50. package/src/control-plane/ui-assets.ts +349 -0
  51. package/src/control-plane/validate.ts +44 -79
  52. package/src/index.ts +86 -48
  53. package/src/logger.test.ts +228 -0
  54. package/src/logger.ts +71 -1
  55. package/src/provider-constants.ts +22 -1
  56. package/src/control-plane/audit.ts +0 -40
  57. package/src/control-plane/env-schema-validation.test.ts +0 -118
  58. package/src/control-plane/memory-config.ts +0 -298
  59. package/src/control-plane/redact-schema.ts +0 -50
@@ -5,35 +5,48 @@
5
5
  * This module does NOT include Docker operations (compose up, image pull, etc.)
6
6
  * — those happen separately in the caller after setup completes.
7
7
  */
8
- import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
9
- import { randomBytes } from "node:crypto";
8
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, renameSync } from "node:fs";
9
+ import { join } from "node:path";
10
10
  import { createLogger } from "../logger.js";
11
11
  import {
12
12
  PROVIDER_KEY_MAP,
13
- EMBEDDING_DIMS,
14
- OLLAMA_INSTACK_URL,
15
13
  } from "../provider-constants.js";
16
14
  import { mergeEnvContent } from "./env.js";
17
15
  import { ensureHomeDirs } from "./home.js";
16
+ import { acquireInstallLock, releaseInstallLock, type InstallLockHandle } from "./install-lock.js";
18
17
  import {
19
18
  ensureSecrets,
20
19
  updateSecretsEnv,
21
20
  updateSystemSecretsEnv,
22
21
  ensureOpenCodeConfig,
23
22
  readStackEnv,
23
+ writeAuthJsonProviderKeys,
24
24
  } from "./secrets.js";
25
- import { ensureOpenCodeSystemConfig, ensureMemoryDir } from "./core-assets.js";
26
- import { createState, writeSetupTokenFile } from "./lifecycle.js";
25
+ import { ensureOpenCodeSystemConfig } from "./core-assets.js";
26
+ import { createState } from "./lifecycle.js";
27
27
  import { writeStackSpec } from "./stack-spec.js";
28
- import type { StackSpec, StackSpecCapabilities } from "./stack-spec.js";
29
- import { writeCapabilityVars } from "./spec-to-env.js";
28
+ import { writeVoiceVars } from "./spec-to-env.js";
30
29
  import type { ControlPlaneState } from "./types.js";
31
30
  import { validateSetupSpec } from "./setup-validation.js";
32
- import { listEnabledAddonIds } from "./registry.js";
31
+ import { getRegistryAutomation, setAddonEnabled } from "./registry.js";
33
32
  export { validateSetupSpec } from "./setup-validation.js";
34
33
 
35
34
  const logger = createLogger("setup");
36
35
 
36
+ // ── Atomic write helper ──────────────────────────────────────────────────
37
+
38
+ /**
39
+ * Write `content` to `path` atomically: write to `path.tmp` first, then
40
+ * rename over the target. On POSIX this rename is atomic — a reader always
41
+ * sees either the old file or the new file, never a partially-written one.
42
+ * If the tmp write fails the original file is untouched.
43
+ */
44
+ function writeFileAtomic(path: string, content: string | Uint8Array, mode?: number): void {
45
+ const tmp = `${path}.tmp`;
46
+ writeFileSync(tmp, content, mode !== undefined ? { mode } : {});
47
+ renameSync(tmp, path);
48
+ }
49
+
37
50
  // ── Types ────────────────────────────────────────────────────────────────
38
51
 
39
52
  export type SetupConnection = {
@@ -52,35 +65,32 @@ export type SetupResult = {
52
65
 
53
66
  export type SetupSpec = {
54
67
  version: 2;
55
- capabilities: StackSpecCapabilities;
56
- security: { adminToken: string };
68
+ llm?: { provider: string; model: string; baseUrl?: string };
69
+ embedding?: { provider: string; model: string; dims: number; baseUrl?: string };
70
+ tts?: { enabled?: boolean; engine?: string; provider?: string; baseURL?: string; model?: string; voice?: string };
71
+ stt?: { enabled?: boolean; engine?: string; provider?: string; baseURL?: string; model?: string; language?: string };
72
+ /**
73
+ * Operator-supplied UI login password. Persisted to stack.env as
74
+ * `OP_UI_LOGIN_PASSWORD`. Replaces the legacy `adminToken` field
75
+ * (Phase 4 of docs/technical/auth-and-proxy-refactor-plan.md).
76
+ */
77
+ security: { uiLoginPassword: string };
57
78
  owner?: { name?: string; email?: string };
58
79
  connections: SetupConnection[];
59
80
  channelCredentials?: Record<string, Record<string, string>>;
81
+ addons?: Record<string, boolean>;
82
+ imageTag?: string;
83
+ hostAkm?: boolean;
60
84
  };
61
85
 
62
86
  // ── Secrets Builder ──────────────────────────────────────────────────────
63
87
 
64
88
  /**
65
- * Map provider id env var for a custom base URL override.
66
- * Allows writeCapabilityVars to resolve non-default endpoints.
89
+ * Build the stack.env update payload from a setup spec. Provider API
90
+ * keys are NOT included here — credentials live in OpenCode's auth.json
91
+ * (see buildAuthJsonFromSetup), not stack.env. This function returns
92
+ * only non-credential vars: owner identity and similar.
67
93
  */
68
- const PROVIDER_BASE_URL_ENV: Record<string, string> = {
69
- openai: "OPENAI_BASE_URL",
70
- anthropic: "ANTHROPIC_BASE_URL",
71
- groq: "GROQ_BASE_URL",
72
- mistral: "MISTRAL_BASE_URL",
73
- together: "TOGETHER_BASE_URL",
74
- deepseek: "DEEPSEEK_BASE_URL",
75
- xai: "XAI_BASE_URL",
76
- google: "GOOGLE_BASE_URL",
77
- huggingface: "HF_BASE_URL",
78
- ollama: "OLLAMA_BASE_URL",
79
- lmstudio: "LMSTUDIO_BASE_URL",
80
- "model-runner": "MODEL_RUNNER_BASE_URL",
81
- "openai-compatible": "OPENAI_COMPATIBLE_BASE_URL",
82
- };
83
-
84
94
  export function buildSecretsFromSetup(
85
95
  connections: SetupConnection[],
86
96
  owner?: { name?: string; email?: string },
@@ -90,60 +100,51 @@ export function buildSecretsFromSetup(
90
100
  const ownerEmail = (owner?.email?.trim() ?? "").replace(/[\r\n\0]/g, "").slice(0, 200);
91
101
  if (ownerName) updates.OWNER_NAME = ownerName;
92
102
  if (ownerEmail) updates.OWNER_EMAIL = ownerEmail;
93
-
94
- for (const cap of connections) {
95
- // API key: spec value takes precedence, then fall back to environment
96
- const envVar = PROVIDER_KEY_MAP[cap.provider];
97
- if (envVar) {
98
- const key = cap.apiKey || process.env[envVar] || "";
99
- if (key) updates[envVar] = key;
100
- }
101
- // Persist user-configured base URL for any provider so writeCapabilityVars can resolve it
102
- if (cap.baseUrl) {
103
- const urlEnv = PROVIDER_BASE_URL_ENV[cap.provider];
104
- if (urlEnv) updates[urlEnv] = cap.baseUrl;
105
- }
106
- }
103
+ void connections;
107
104
  return updates;
108
105
  }
109
106
 
110
107
  /**
111
- * Read auth.json and extract API keys for OAuth-authenticated providers.
112
- * This fills the gap where OAuth auth writes tokens to auth.json but
113
- * not to stack.env the memory service needs them as env vars.
108
+ * Build the auth.json payload from a setup spec. Returns a record of
109
+ * `{ providerId: apiKey }` ready to feed into writeAuthJsonProviderKeys.
110
+ * Pulls keys from the spec first, falling back to the host process
111
+ * environment for the canonical env var name (e.g. OPENAI_API_KEY for
112
+ * provider "openai") so operators can preload keys via env before
113
+ * running the wizard.
114
114
  */
115
- export function extractAuthJsonKeys(vaultDir: string): Record<string, string> {
116
- const authJsonPath = `${vaultDir}/stack/auth.json`;
117
- if (!existsSync(authJsonPath)) return {};
118
- try {
119
- const raw = readFileSync(authJsonPath, "utf-8").trim();
120
- if (!raw || raw === "{}") return {};
121
- const auth = JSON.parse(raw) as Record<string, unknown>;
122
- const updates: Record<string, string> = {};
123
- for (const [provider, entry] of Object.entries(auth)) {
124
- if (!entry || typeof entry !== "object") continue;
125
- const record = entry as Record<string, unknown>;
126
- // OpenCode stores API keys as { token: "..." } or { apiKey: "..." }
127
- const token = (record.token ?? record.apiKey ?? record.api_key ?? record.key) as string | undefined;
128
- if (token && typeof token === "string") {
129
- const envVar = PROVIDER_KEY_MAP[provider];
130
- if (envVar) updates[envVar] = token;
131
- }
132
- }
133
- return updates;
134
- } catch {
135
- return {};
115
+ export function buildAuthJsonFromSetup(
116
+ connections: SetupConnection[],
117
+ ): Record<string, string> {
118
+ const keys: Record<string, string> = {};
119
+ for (const cap of connections) {
120
+ const envVar = PROVIDER_KEY_MAP[cap.provider];
121
+ const key = cap.apiKey || (envVar ? process.env[envVar] : undefined) || "";
122
+ if (key) keys[cap.provider] = key;
136
123
  }
124
+ return keys;
137
125
  }
138
126
 
127
+ /**
128
+ * Build the system-secret env update for the wizard / CLI install path.
129
+ *
130
+ * Phase 4 of the auth/proxy refactor collapsed the legacy
131
+ * `OP_UI_TOKEN` / `OP_ASSISTANT_TOKEN` pair into a single operator login
132
+ * secret (`OP_UI_LOGIN_PASSWORD`). The browser stores the cookie value =
133
+ * password; `requireAdmin()` compares the cookie against
134
+ * `process.env.OP_UI_LOGIN_PASSWORD` via the existing `safeTokenCompare`.
135
+ *
136
+ * `OP_OPENCODE_PASSWORD` is generated by `ensureSystemSecrets()` on first
137
+ * run and persists across reruns — it is not regenerated here.
138
+ *
139
+ * `existingSystemEnv` is unused now but the parameter is kept so callers
140
+ * compile unchanged. It can be removed in a follow-up cleanup.
141
+ */
139
142
  export function buildSystemSecretsFromSetup(
140
- adminToken: string,
141
- existingSystemEnv: Record<string, string> = {}
143
+ uiLoginPassword: string,
144
+ _existingSystemEnv: Record<string, string> = {}
142
145
  ): Record<string, string> {
143
146
  return {
144
- OP_ADMIN_TOKEN: adminToken,
145
- OP_ASSISTANT_TOKEN: existingSystemEnv.OP_ASSISTANT_TOKEN || randomBytes(32).toString("hex"),
146
- OP_MEMORY_TOKEN: existingSystemEnv.OP_MEMORY_TOKEN || randomBytes(32).toString("hex"),
147
+ OP_UI_LOGIN_PASSWORD: uiLoginPassword,
147
148
  };
148
149
  }
149
150
 
@@ -192,75 +193,159 @@ export async function performSetup(
192
193
  const validation = validateSetupSpec(input);
193
194
  if (!validation.valid) return { ok: false, error: validation.errors.join("; ") };
194
195
 
195
- const { capabilities, security, owner, connections, channelCredentials } = input;
196
- const state = opts?.state ?? createState(security.adminToken);
197
- const ollamaEnabled = listEnabledAddonIds(state.homeDir).includes("ollama");
198
-
199
- logger.info("performing setup", { capabilityCount: connections.length, ollamaEnabled });
196
+ const { llm, embedding, tts, stt, security, owner, connections, channelCredentials, addons, imageTag, hostAkm } = input;
197
+ const state = opts?.state ?? createState();
200
198
 
201
- // Apply Ollama in-stack URL override when addon is enabled
202
- const effectiveConnections = ollamaEnabled
203
- ? connections.map((c) => c.provider === "ollama" ? { ...c, baseUrl: OLLAMA_INSTACK_URL } : c)
204
- : connections;
205
- const updates = buildSecretsFromSetup(effectiveConnections, owner);
206
-
207
- // Merge OAuth-authenticated provider keys from auth.json
208
- // (OAuth flows store tokens in auth.json, not in the setup payload)
209
- const oauthKeys = extractAuthJsonKeys(state.vaultDir);
210
- for (const [key, value] of Object.entries(oauthKeys)) {
211
- // Only fill in keys that weren't already provided via API key entry
212
- if (!updates[key]) updates[key] = value;
199
+ // Acquire install lock to prevent two concurrent setup runs from racing on
200
+ // the same config directory. The lock lives in stateDir so it is co-located
201
+ // with runtime state and the same path startDeploy uses.
202
+ const lockHandle: InstallLockHandle | null = acquireInstallLock(state.stateDir);
203
+ if (lockHandle === null) {
204
+ return {
205
+ ok: false,
206
+ error:
207
+ "install_in_progress: Another install is in progress. Wait for it to finish, or remove state/.install.lock if you're sure no install is running.",
208
+ };
213
209
  }
214
210
 
215
- // Persist vault env files
211
+ logger.info("performing setup", { connectionCount: connections.length });
212
+ const updates = buildSecretsFromSetup(connections, owner);
213
+ const providerKeys = buildAuthJsonFromSetup(connections);
214
+
215
+ // Wrap all persistence work in try/finally so the lock is ALWAYS released.
216
216
  try {
217
- ensureHomeDirs();
218
- ensureSecrets(state);
219
- const existingSystemEnv = readStackEnv(state.vaultDir);
220
- if (channelCredentials) Object.assign(updates, buildChannelCredentialEnvVars(channelCredentials));
221
- // Pick up channel credential env vars not already provided in the spec
222
- for (const mapping of Object.values(CHANNEL_CREDENTIAL_ENV_MAP)) {
223
- for (const envKey of Object.values(mapping)) {
224
- if (!updates[envKey] && process.env[envKey]) updates[envKey] = process.env[envKey];
217
+ // Persist vault env files + OpenCode auth.json
218
+ try {
219
+ ensureHomeDirs();
220
+ ensureSecrets(state);
221
+ const existingSystemEnv = readStackEnv(state.stackDir);
222
+ if (channelCredentials) Object.assign(updates, buildChannelCredentialEnvVars(channelCredentials));
223
+ // Pick up channel credential env vars not already provided in the spec
224
+ for (const mapping of Object.values(CHANNEL_CREDENTIAL_ENV_MAP)) {
225
+ for (const envKey of Object.values(mapping)) {
226
+ if (!updates[envKey] && process.env[envKey]) updates[envKey] = process.env[envKey];
227
+ }
225
228
  }
229
+ updateSecretsEnv(state, updates);
230
+ updateSystemSecretsEnv(state, buildSystemSecretsFromSetup(security.uiLoginPassword, existingSystemEnv));
231
+ // Provider API keys land in OpenCode's auth.json (bind-mounted into
232
+ // the assistant container) — never in stack.env.
233
+ writeAuthJsonProviderKeys(state, providerKeys);
234
+ } catch (err) {
235
+ const message = err instanceof Error ? err.message : String(err);
236
+ logger.error("failed to persist setup outputs", { error: message });
237
+ return { ok: false, error: `Failed to persist setup outputs: ${message}` };
226
238
  }
227
- updateSecretsEnv(state, updates);
228
- updateSystemSecretsEnv(state, buildSystemSecretsFromSetup(security.adminToken, existingSystemEnv));
229
- } catch (err) {
230
- const message = err instanceof Error ? err.message : String(err);
231
- logger.error("failed to update vault env files", { error: message });
232
- return { ok: false, error: `Failed to update vault env files: ${message}` };
233
- }
234
239
 
235
- state.adminToken = security.adminToken;
236
- state.assistantToken = readStackEnv(state.vaultDir).OP_ASSISTANT_TOKEN ?? state.assistantToken;
237
- writeSetupTokenFile(state);
240
+ // Everything from here through the OP_SETUP_COMPLETE write is wrapped in a
241
+ // single try/catch so that a disk-full or permission-denied mid-way returns a
242
+ // clean error rather than leaving a broken half-installed ~/.openpalm/.
243
+ try {
244
+ // Write stack.yml (version marker only)
245
+ writeStackSpec(state.stackDir, { version: 2 });
246
+
247
+ // Write image tag and AKM mount paths to stack.env — atomic to avoid
248
+ // partial writes if the process is interrupted mid-write.
249
+ const systemEnvForAkm = existsSync(`${state.stackDir}/stack.env`)
250
+ ? readFileSync(`${state.stackDir}/stack.env`, "utf-8")
251
+ : "";
252
+ const akmUpdates: Record<string, string> = {};
253
+ if (imageTag) akmUpdates.OP_IMAGE_TAG = imageTag;
254
+ if (hostAkm) {
255
+ const home = process.env.HOME ?? process.env.USERPROFILE ?? "";
256
+ if (home) {
257
+ akmUpdates.OP_AKM_STASH = `${home}/akm`;
258
+ akmUpdates.OP_AKM_DATA = `${home}/.local/share/akm`;
259
+ akmUpdates.OP_AKM_STATE = `${home}/.local/state/akm`;
260
+ akmUpdates.OP_AKM_CACHE = `${home}/.cache/akm`;
261
+ akmUpdates.OP_AKM_CONFIG = `${home}/.config/akm`;
262
+ }
263
+ }
264
+ if (Object.keys(akmUpdates).length > 0) {
265
+ writeFileAtomic(`${state.stackDir}/stack.env`, mergeEnvContent(systemEnvForAkm, akmUpdates), 0o600);
266
+ }
267
+
268
+ // Write akm config with LLM and embedding settings from setup — atomic.
269
+ if (llm || embedding) {
270
+ const akmConfigDir = join(state.configDir, "akm");
271
+ mkdirSync(akmConfigDir, { recursive: true });
272
+ const akmConfigPath = join(akmConfigDir, "config.json");
273
+ let existing: Record<string, unknown> = {};
274
+ if (existsSync(akmConfigPath)) {
275
+ try { existing = JSON.parse(readFileSync(akmConfigPath, "utf-8")); } catch { /* ignore corrupt */ }
276
+ }
277
+ const updated = { ...existing };
278
+ if (llm) {
279
+ const base = llm.baseUrl ? llm.baseUrl.replace(/\/+$/, "") : "";
280
+ updated.llm = {
281
+ ...((existing.llm as Record<string, unknown>) ?? {}),
282
+ endpoint: base ? `${base}/chat/completions` : "",
283
+ model: llm.model,
284
+ provider: llm.provider,
285
+ };
286
+ }
287
+ if (embedding) {
288
+ const base = embedding.baseUrl ? embedding.baseUrl.replace(/\/+$/, "") : "";
289
+ updated.embedding = {
290
+ ...((existing.embedding as Record<string, unknown>) ?? {}),
291
+ endpoint: base ? `${base}/embeddings` : "",
292
+ model: embedding.model,
293
+ provider: embedding.provider,
294
+ dimension: embedding.dims,
295
+ };
296
+ }
297
+ writeFileAtomic(akmConfigPath, JSON.stringify(updated, null, 2), 0o600);
298
+ }
238
299
 
239
- // Write stack.yml and OP_CAP_* capability vars to stack.env
240
- writeMemoryAndStackConfigs({ version: 2, capabilities }, state);
300
+ // Write TTS/STT vars to stack.env for the voice channel
301
+ if (tts || stt) {
302
+ writeVoiceVars({ tts, stt }, state.stackDir);
303
+ }
241
304
 
242
- ensureOpenCodeConfig();
243
- ensureOpenCodeSystemConfig();
244
- ensureMemoryDir();
305
+ // Enable requested addons (channels like discord, slack, etc.)
306
+ // setAddonEnabled copies the compose overlay AND generates CHANNEL_<NAME>_SECRET in guardian.env
307
+ if (addons) {
308
+ for (const [name, enabled] of Object.entries(addons)) {
309
+ if (enabled) setAddonEnabled(state.homeDir, state.stackDir, name, true);
310
+ }
311
+ }
245
312
 
246
- // Mark setup complete in vault/stack/stack.env (where isSetupComplete reads it)
247
- const systemEnvPath = `${state.vaultDir}/stack/stack.env`;
248
- const systemBase = existsSync(systemEnvPath) ? readFileSync(systemEnvPath, "utf-8") : "";
249
- writeFileSync(systemEnvPath, mergeEnvContent(systemBase, { OP_SETUP_COMPLETE: "true" }), { mode: 0o600 });
313
+ ensureOpenCodeConfig();
314
+ ensureOpenCodeSystemConfig();
250
315
 
251
- logger.info("setup complete", { capabilityCount: connections.length });
252
- return { ok: true };
253
- }
316
+ // Seed default automation into the AKM stash. Idempotent — existing files
317
+ // are left alone so user edits survive re-install and upgrade.
318
+ const tasksDir = join(state.stashDir, "tasks");
319
+ mkdirSync(tasksDir, { recursive: true });
320
+ const akmImproveDest = join(tasksDir, "akm-improve.md");
321
+ if (!existsSync(akmImproveDest)) {
322
+ const akmImproveMd = getRegistryAutomation("akm-improve");
323
+ if (akmImproveMd) {
324
+ writeFileSync(akmImproveDest, akmImproveMd);
325
+ logger.info("seeded default automation", { name: "akm-improve" });
326
+ } else {
327
+ logger.warn("default automation missing from registry; skipping seed", {
328
+ name: "akm-improve",
329
+ });
330
+ }
331
+ }
254
332
 
255
- /** Write stack.yml and OP_CAP_* capability vars to stack.env from the spec's capabilities. */
256
- function writeMemoryAndStackConfigs(spec: StackSpec, state: ControlPlaneState): void {
257
- const { provider: embProvider, model: embModel } = spec.capabilities.embeddings;
258
- const resolvedDims = spec.capabilities.embeddings.dims || EMBEDDING_DIMS[`${embProvider}/${embModel}`] || 1536;
333
+ // NOTE: OP_SETUP_COMPLETE is intentionally NOT written here. Writing it
334
+ // before the Docker deploy succeeds would mark setup "complete" even
335
+ // when containers fail to start, sending the user to a broken admin UI
336
+ // with no path back to the wizard. The flag is now written by
337
+ // setup-deploy.ts:startDeploy AFTER pollContainerHealth confirms every
338
+ // container is healthy.
339
+ } catch (err) {
340
+ const message = err instanceof Error ? err.message : String(err);
341
+ logger.error("failed to complete setup persistence", { error: message });
342
+ return { ok: false, error: `Setup persistence failed: ${message}` };
343
+ }
259
344
 
260
- const specToWrite: StackSpec = {
261
- ...spec,
262
- capabilities: { ...spec.capabilities, embeddings: { ...spec.capabilities.embeddings, dims: resolvedDims } },
263
- };
264
- writeStackSpec(state.configDir, specToWrite);
265
- writeCapabilityVars(specToWrite, state.vaultDir);
345
+ logger.info("setup complete", { connectionCount: connections.length });
346
+ return { ok: true };
347
+ } finally {
348
+ // Always release the install lock, whether setup succeeded or failed.
349
+ releaseInstallLock(lockHandle);
350
+ }
266
351
  }
@@ -0,0 +1,151 @@
1
+ /**
2
+ * Skeleton guardrail tests — validate .openpalm/ directory structure matches v0.11.0.
3
+ *
4
+ * The .openpalm/ directory is the repo-shipped OP_HOME skeleton. These tests
5
+ * prevent reintroduction of pre-v0.11.0 directories (stack/, registry/,
6
+ * stash-seeds/) and ensure the v0.11.0 structure stays intact.
7
+ */
8
+ import { describe, test, expect } from "bun:test";
9
+ import { readdirSync, statSync, existsSync } from "node:fs";
10
+ import { join, resolve } from "node:path";
11
+
12
+ const REPO_ROOT = resolve(import.meta.dir, "../../../..");
13
+ const SKELETON_DIR = join(REPO_ROOT, ".openpalm");
14
+
15
+ // Allowed top-level dirs in .openpalm/ — mirrors the OP_HOME runtime layout
16
+ const ALLOWED_SOURCE_DIRS = new Set([
17
+ "config", // seed files for config/ (assistant, guardian, stack/, akm/)
18
+ "stash", // stash source assets: skills/ and vaults/
19
+ "state", // state/registry/ + empty service dirs (.gitkeep)
20
+ "cache", // empty cache dirs (.gitkeep — regenerable at runtime)
21
+ "workspace", // empty workspace dir (.gitkeep)
22
+ ]);
23
+
24
+ // ── Top-level structure ───────────────────────────────────────────────
25
+
26
+ describe("skeleton: .openpalm/ top-level directories", () => {
27
+ test("only allowed directories exist", () => {
28
+ const entries = readdirSync(SKELETON_DIR);
29
+ const dirs = entries.filter(e => {
30
+ try { return statSync(join(SKELETON_DIR, e)).isDirectory(); } catch { return false; }
31
+ });
32
+ const unexpected = dirs.filter(d => !ALLOWED_SOURCE_DIRS.has(d));
33
+ expect(unexpected).toEqual([]);
34
+ });
35
+
36
+ test("stack/ no longer exists (moved to config/stack/)", () => {
37
+ expect(existsSync(join(SKELETON_DIR, "stack"))).toBe(false);
38
+ });
39
+
40
+ test("registry/ no longer exists (moved to state/registry/)", () => {
41
+ expect(existsSync(join(SKELETON_DIR, "registry"))).toBe(false);
42
+ });
43
+
44
+ test("stash-seeds/ no longer exists (moved to stash/)", () => {
45
+ expect(existsSync(join(SKELETON_DIR, "stash-seeds"))).toBe(false);
46
+ });
47
+ });
48
+
49
+ // ── config/ subdirectory ──────────────────────────────────────────────
50
+
51
+ describe("skeleton: .openpalm/config/ structure", () => {
52
+ test("config/stack/ exists with core.compose.yml and stack.yml", () => {
53
+ expect(existsSync(join(SKELETON_DIR, "config", "stack", "core.compose.yml"))).toBe(true);
54
+ expect(existsSync(join(SKELETON_DIR, "config", "stack", "stack.yml"))).toBe(true);
55
+ });
56
+
57
+ test("config/stack/addons/ exists", () => {
58
+ expect(existsSync(join(SKELETON_DIR, "config", "stack", "addons"))).toBe(true);
59
+ });
60
+
61
+ test("config/akm/ exists", () => {
62
+ expect(existsSync(join(SKELETON_DIR, "config", "akm"))).toBe(true);
63
+ });
64
+
65
+ test("config/assistant/ has seed files", () => {
66
+ expect(existsSync(join(SKELETON_DIR, "config", "assistant", "opencode.json"))).toBe(true);
67
+ });
68
+ });
69
+
70
+ // ── state/registry/ subdirectory ─────────────────────────────────────
71
+
72
+ describe("skeleton: .openpalm/state/registry/ structure", () => {
73
+ test("state/registry/addons/ exists with addon subdirectories", () => {
74
+ const addonsDir = join(SKELETON_DIR, "state", "registry", "addons");
75
+ expect(existsSync(addonsDir)).toBe(true);
76
+ const addons = readdirSync(addonsDir);
77
+ expect(addons).toContain("chat");
78
+ expect(addons).toContain("api");
79
+ expect(addons).toContain("discord");
80
+ });
81
+
82
+ test("state/registry/automations/ exists", () => {
83
+ expect(existsSync(join(SKELETON_DIR, "state", "registry", "automations"))).toBe(true);
84
+ });
85
+
86
+ test("each addon has compose.yml", () => {
87
+ const addonsDir = join(SKELETON_DIR, "state", "registry", "addons");
88
+ const addons = readdirSync(addonsDir).filter(e => {
89
+ try { return statSync(join(addonsDir, e)).isDirectory(); } catch { return false; }
90
+ });
91
+ for (const addon of addons) {
92
+ expect(existsSync(join(addonsDir, addon, "compose.yml"))).toBe(true);
93
+ }
94
+ });
95
+ });
96
+
97
+ // ── stash/ subdirectory ───────────────────────────────────────────────
98
+
99
+ describe("skeleton: .openpalm/stash/ structure", () => {
100
+ test("stash/skills/ exists with config-diagnostics skill", () => {
101
+ expect(existsSync(join(SKELETON_DIR, "stash", "skills", "config-diagnostics", "SKILL.md"))).toBe(true);
102
+ });
103
+
104
+ test("stash/vaults/ exists", () => {
105
+ expect(existsSync(join(SKELETON_DIR, "stash", "vaults"))).toBe(true);
106
+ });
107
+
108
+ test("stash/tasks/ exists", () => {
109
+ expect(existsSync(join(SKELETON_DIR, "stash", "tasks"))).toBe(true);
110
+ });
111
+ });
112
+
113
+ // ── state/ service dirs ───────────────────────────────────────────────
114
+
115
+ describe("skeleton: .openpalm/state/ service directories", () => {
116
+ const serviceDirs = ["assistant", "admin", "guardian", "logs", "backups"];
117
+
118
+ for (const dir of serviceDirs) {
119
+ test(`state/${dir}/ exists`, () => {
120
+ expect(existsSync(join(SKELETON_DIR, "state", dir))).toBe(true);
121
+ });
122
+ }
123
+
124
+ test("state/akm/data/ exists", () => {
125
+ expect(existsSync(join(SKELETON_DIR, "state", "akm", "data"))).toBe(true);
126
+ });
127
+
128
+ test("state/akm/state/ exists", () => {
129
+ expect(existsSync(join(SKELETON_DIR, "state", "akm", "state"))).toBe(true);
130
+ });
131
+
132
+ test("state/logs/opencode/ exists", () => {
133
+ expect(existsSync(join(SKELETON_DIR, "state", "logs", "opencode"))).toBe(true);
134
+ });
135
+ });
136
+
137
+ // ── cache/ and workspace/ ─────────────────────────────────────────────
138
+
139
+ describe("skeleton: .openpalm/cache/ and workspace/", () => {
140
+ test("cache/akm/ exists", () => {
141
+ expect(existsSync(join(SKELETON_DIR, "cache", "akm"))).toBe(true);
142
+ });
143
+
144
+ test("cache/rollback/ exists", () => {
145
+ expect(existsSync(join(SKELETON_DIR, "cache", "rollback"))).toBe(true);
146
+ });
147
+
148
+ test("workspace/ exists", () => {
149
+ expect(existsSync(join(SKELETON_DIR, "workspace"))).toBe(true);
150
+ });
151
+ });