@celilo/cli 1.14.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CELILO_CORE_MODULES.md +1 -1
  2. package/CELILO_SUBSYSTEMS.md +25 -3
  3. package/README.md +0 -2
  4. package/drizzle/0030_drop_module_builds_environment.sql +8 -0
  5. package/drizzle/meta/_journal.json +8 -1
  6. package/package.json +3 -3
  7. package/src/capabilities/public-web-publish.test.ts +18 -0
  8. package/src/cli/commands/alerts-sweep.ts +3 -0
  9. package/src/cli/commands/monitor.ts +15 -2
  10. package/src/cli/commands/system-doctor.test.ts +121 -1
  11. package/src/cli/commands/system-doctor.ts +151 -1
  12. package/src/cli/completion.ts +9 -2
  13. package/src/cli/index.ts +1 -1
  14. package/src/console/control-plane-boundary.test.ts +82 -4
  15. package/src/db/schema.ts +0 -1
  16. package/src/hooks/capability-loader.ts +14 -0
  17. package/src/hooks/executor.ts +110 -17
  18. package/src/hooks/hook-jail-toolchain-reach.test.ts +224 -0
  19. package/src/hooks/hook-jail-unreachability.test.ts +28 -2
  20. package/src/hooks/hook-protocol.ts +44 -0
  21. package/src/hooks/hook-runner-entry.ts +23 -0
  22. package/src/hooks/hook-runner.ts +10 -0
  23. package/src/hooks/hook-trespass.test.ts +9 -3
  24. package/src/hooks/jail-browser-launch-flags.test.ts +34 -0
  25. package/src/hooks/jail.test.ts +92 -0
  26. package/src/hooks/jail.ts +128 -11
  27. package/src/hooks/mount-set.test.ts +28 -6
  28. package/src/hooks/mount-set.ts +34 -20
  29. package/src/hooks/remote-broker.test.ts +350 -0
  30. package/src/hooks/remote-broker.ts +404 -0
  31. package/src/hooks/run-named-hook.ts +2 -0
  32. package/src/hooks/test-fixtures/jail-probe-hook.ts +14 -1
  33. package/src/hooks/test-fixtures/jail-toolchain-hook.ts +227 -0
  34. package/src/hooks/test-fixtures/remote-bridge-probe.ts +82 -0
  35. package/src/hooks/unjailed-lint.test.ts +251 -0
  36. package/src/hooks/unjailed-lint.ts +395 -0
  37. package/src/policy/module-business-baseline.ts +13 -1
  38. package/src/policy/module-script-scan.ts +60 -1
  39. package/src/policy/no-hand-built-ssh.test.ts +39 -1
  40. package/src/policy/no-module-business-in-core.test.ts +1 -1
  41. package/src/services/alerting/hook-jail.test.ts +66 -0
  42. package/src/services/alerting/hook-jail.ts +70 -0
  43. package/src/services/alerting/run-monitor.test.ts +62 -0
  44. package/src/services/alerting/run-monitor.ts +12 -0
  45. package/src/services/alerting/sweep-runner.test.ts +1 -0
  46. package/src/services/backup-create.ts +3 -0
  47. package/src/services/backup-restore.ts +2 -0
  48. package/src/services/deploy-ansible.ts +9 -1
  49. package/src/services/health-runner.ts +2 -0
  50. package/src/services/module-build.test.ts +1 -64
  51. package/src/services/module-build.ts +10 -86
  52. package/src/services/module-deploy.ts +20 -0
  53. package/src/services/remote-access.test.ts +139 -0
  54. package/src/services/remote-access.ts +98 -0
  55. package/src/services/restore-from-file.ts +6 -1
  56. package/src/services/static-content-converge.test.ts +338 -0
  57. package/src/services/static-content-converge.ts +299 -0
@@ -0,0 +1,299 @@
1
+ /**
2
+ * The static-content converge (openspec/changes/capability-owned-tables,
3
+ * stage 4 / design D10).
4
+ *
5
+ * `/srv/www` on the public_web provider stops being whatever the last
6
+ * hand-built ssh upload left there and becomes convergent state: every
7
+ * declared static route's release directory exists, `/srv/www/<slug>` points
8
+ * at the current one through an atomic symlink swap, and everything past the
9
+ * retention count is pruned. One Ansible converge makes the host match.
10
+ *
11
+ * Two callers, one code path:
12
+ * - the `public_web` capability's publish (`convergeStaticContent` callback
13
+ * injected by capability-loader), which runs the whole converge including
14
+ * `executeAnsible`, so a publish returns only once the host matches; and
15
+ * - the provider's OWN deploy (module-deploy), which writes the same release
16
+ * set into its generated inventory and lets the deploy's existing
17
+ * `executeAnsible` run the same role tasks — that is how a rebuilt host
18
+ * recovers with no consumer involvement (design D10, task 4.5).
19
+ *
20
+ * The desired state is the declared `web_routes` release set plus the source
21
+ * directory core derived from `modules.source_path`. Nothing here writes into
22
+ * a module tree: reading a module's web root is safe, writing is what breaks
23
+ * `module verify` (celilo#1018, deliberately left to that thread).
24
+ */
25
+
26
+ import { existsSync, readFileSync } from 'node:fs';
27
+ import { mkdir, writeFile } from 'node:fs/promises';
28
+ import { join } from 'node:path';
29
+ import { and, eq, isNotNull } from 'drizzle-orm';
30
+ import { stringify as stringifyYaml } from 'yaml';
31
+ import type { DbClient } from '../db/client';
32
+ import { moduleConfigs, modules, webRoutes } from '../db/schema';
33
+ import { resolveModuleWebRoot } from '../module/web-root';
34
+ import { parseStoredConfigValue } from './module-config';
35
+
36
+ /** One content-hashed release the provider host must serve. */
37
+ export interface StaticRelease {
38
+ /** The `/srv/www/<slug>` key. Independent of hostname on purpose. */
39
+ slug: string;
40
+ /** Content hash of the release — the release directory's suffix. */
41
+ contentHash: string;
42
+ /** Every FQDN served by this slug's routes (a slug spans hostnames). */
43
+ hostnames: string[];
44
+ /** Absolute celilo-mgr path core derived: `<module source_path>/site/dist`. */
45
+ sourceDir: string;
46
+ }
47
+
48
+ export interface StaticContentPlan {
49
+ releases: StaticRelease[];
50
+ /** How many release directories to keep per slug after a converge. */
51
+ retention: number;
52
+ }
53
+
54
+ /**
55
+ * Retention when the operator has not set one. Mirrors the manifest default
56
+ * declared on the provider module (`static_release_retention`); the manifest
57
+ * is the operator-facing source of truth, this only covers a provider whose
58
+ * manifest predates the variable.
59
+ */
60
+ const DEFAULT_STATIC_RELEASE_RETENTION = 5;
61
+
62
+ export interface StaticContentConvergeResult {
63
+ success: boolean;
64
+ error?: string;
65
+ /** The written vars file, repo-absolute — for logs and tests. */
66
+ varsPath?: string;
67
+ }
68
+
69
+ /**
70
+ * Where the converge's desired state lands inside the provider's generated
71
+ * project. `group_vars/all/` is the existing auto-load directory (it already
72
+ * holds `secrets.yml`), so no playbook change is needed to read it.
73
+ */
74
+ export function staticContentVarsPath(generatedPath: string): string {
75
+ return join(generatedPath, 'ansible', 'inventory', 'group_vars', 'all', 'static_content.yml');
76
+ }
77
+
78
+ /**
79
+ * Resolve the retention count for the provider module.
80
+ *
81
+ * Operator config first (`static_release_retention` module config), then the
82
+ * manifest's declared default, then the constant above. ONE resolution — the
83
+ * role reads the variable bare and never carries a literal.
84
+ */
85
+ export function resolveStaticContentRetention(db: DbClient, providerModuleId: string): number {
86
+ const configRow = db
87
+ .select()
88
+ .from(moduleConfigs)
89
+ .where(
90
+ and(
91
+ eq(moduleConfigs.moduleId, providerModuleId),
92
+ eq(moduleConfigs.key, 'static_release_retention'),
93
+ ),
94
+ )
95
+ .get();
96
+ if (configRow) {
97
+ const parsed = parseStoredConfigValue(configRow);
98
+ const count = typeof parsed === 'number' ? parsed : Number.parseInt(String(parsed), 10);
99
+ if (Number.isInteger(count) && count >= 1) return count;
100
+ throw new Error(
101
+ `static_release_retention for ${providerModuleId} must be a positive integer, got: ${String(parsed)}`,
102
+ );
103
+ }
104
+
105
+ const module = db.select().from(modules).where(eq(modules.id, providerModuleId)).get();
106
+ if (module) {
107
+ const manifest = module.manifestData as {
108
+ variables?: { owns?: Array<{ name?: string; default?: unknown }> };
109
+ } | null;
110
+ const declared = manifest?.variables?.owns?.find((v) => v?.name === 'static_release_retention');
111
+ const fallback = typeof declared?.default === 'number' ? declared.default : undefined;
112
+ if (typeof fallback === 'number' && Number.isInteger(fallback) && fallback >= 1)
113
+ return fallback;
114
+ }
115
+
116
+ return DEFAULT_STATIC_RELEASE_RETENTION;
117
+ }
118
+
119
+ /**
120
+ * Build the release set from the declared `web_routes` rows.
121
+ *
122
+ * Pure: reads the DB, decides nothing on the host (Rule 10.4). Grouping is by
123
+ * slug, NOT by route — one slug is one release directory, and a slug can span
124
+ * hostnames (lunacycle's two routes, both at `/`). A group that spans modules
125
+ * or disagrees with itself about the hash is a contradiction the converge
126
+ * cannot express, so it fails here with both rows named rather than silently
127
+ * converging one of them.
128
+ */
129
+ export function planStaticContent(db: DbClient): StaticRelease[] {
130
+ const rows = db
131
+ .select()
132
+ .from(webRoutes)
133
+ .where(and(eq(webRoutes.type, 'static'), isNotNull(webRoutes.contentHash)))
134
+ .all();
135
+
136
+ const bySlug = new Map<string, typeof rows>();
137
+ for (const row of rows) {
138
+ const group = bySlug.get(row.slug) ?? [];
139
+ group.push(row);
140
+ bySlug.set(row.slug, group);
141
+ }
142
+
143
+ const releases: StaticRelease[] = [];
144
+ for (const [slug, group] of bySlug) {
145
+ const moduleIds = [...new Set(group.map((r) => r.moduleId))];
146
+ if (moduleIds.length > 1) {
147
+ throw new Error(
148
+ `Static route slug "${slug}" is claimed by ${moduleIds.length} modules (${moduleIds.join(', ')}). The slug is the release key — /srv/www/${slug} cannot serve two release sets. Fix the colliding modules' registered paths.`,
149
+ );
150
+ }
151
+ const moduleId = moduleIds[0];
152
+ if (!moduleId) continue;
153
+
154
+ const hashes = [...new Set(group.map((r) => r.contentHash))];
155
+ if (hashes.length > 1) {
156
+ throw new Error(
157
+ `Static route slug "${slug}" (module ${moduleId}) holds ${hashes.length} content hashes (${hashes.join(', ')}) — rows sharing a slug must share a release. Re-publish the module so every row carries the current hash.`,
158
+ );
159
+ }
160
+ const contentHash = hashes[0];
161
+ if (!contentHash) continue;
162
+
163
+ const sourceDir = resolveModuleWebRoot(moduleId, db);
164
+ if (!sourceDir) {
165
+ throw new Error(
166
+ `Static route slug "${slug}" belongs to module "${moduleId}", which is not installed — its release has no source to converge from.`,
167
+ );
168
+ }
169
+ if (!existsSync(sourceDir)) {
170
+ throw new Error(
171
+ `Static route slug "${slug}": no built site at ${sourceDir}. A module that serves a static site ships it at <module root>/site/dist. Redeploy the module.`,
172
+ );
173
+ }
174
+
175
+ releases.push({
176
+ slug,
177
+ contentHash,
178
+ hostnames: [...new Set(group.map((r) => r.hostname))].sort(),
179
+ sourceDir,
180
+ });
181
+ }
182
+
183
+ releases.sort((a, b) => a.slug.localeCompare(b.slug));
184
+ return releases;
185
+ }
186
+
187
+ /**
188
+ * The full desired state: the release set plus the retention count resolved
189
+ * for THIS provider module. The unit the vars file and the tests speak in.
190
+ */
191
+ export function buildStaticContentPlan(db: DbClient, providerModuleId: string): StaticContentPlan {
192
+ return {
193
+ releases: planStaticContent(db),
194
+ retention: resolveStaticContentRetention(db, providerModuleId),
195
+ };
196
+ }
197
+
198
+ /**
199
+ * Render the vars file. Presentation function (Rule 10.1) — deterministic
200
+ * YAML, keyed by slug, carrying what 4.1 names: slug, content_hash, the
201
+ * hostnames served, and the source directory core derived.
202
+ */
203
+ export function staticContentVarsYaml(plan: StaticContentPlan): string {
204
+ const vars = {
205
+ static_release_retention: plan.retention,
206
+ static_releases: plan.releases.map((r) => ({
207
+ slug: r.slug,
208
+ content_hash: r.contentHash,
209
+ hostnames: r.hostnames,
210
+ source_dir: r.sourceDir,
211
+ })),
212
+ };
213
+ const header =
214
+ '# Desired static-content state, generated by celilo (capability-owned-tables D10).\n' +
215
+ '# Hand edits are overwritten by the next converge. K = static_release_retention.\n';
216
+ return `${header}${stringifyYaml(vars, { lineWidth: 0, sortMapEntries: true })}`;
217
+ }
218
+
219
+ /**
220
+ * Plan the release set and write it into the provider's generated inventory.
221
+ *
222
+ * The shared half of both converge triggers: the capability's callback adds
223
+ * `executeAnsible` after this, and the provider's own deploy already runs it.
224
+ * Writing happens AFTER the deploy's staleness check (`refuseIfGeneratedIsStale`
225
+ * only inspects verbatim role assets), so an injected vars file never reads as
226
+ * a stale generation.
227
+ */
228
+ export async function writeStaticContentVars(
229
+ db: DbClient,
230
+ providerModuleId: string,
231
+ generatedPath: string,
232
+ ): Promise<StaticContentConvergeResult> {
233
+ const varsPath = staticContentVarsPath(generatedPath);
234
+
235
+ const plan = buildStaticContentPlan(db, providerModuleId);
236
+
237
+ await mkdir(join(varsPath, '..'), { recursive: true });
238
+ await writeFile(varsPath, staticContentVarsYaml(plan), 'utf-8');
239
+ return { success: true, varsPath };
240
+ }
241
+
242
+ /**
243
+ * The full converge: plan, write the desired state, run Ansible against the
244
+ * provider's generated project.
245
+ *
246
+ * `generatedPath` must already exist — it is the project the provider's last
247
+ * deploy generated. If the project predates the converge role tasks, the
248
+ * written state would be read by nothing and the transfer would silently
249
+ * never happen, so the playbook is checked for the converge's own variable
250
+ * first and a stale project fails loudly with the redeploy that fixes it.
251
+ */
252
+ export async function convergeStaticContent(
253
+ db: DbClient,
254
+ providerModuleId: string,
255
+ ): Promise<StaticContentConvergeResult> {
256
+ const module = db.select().from(modules).where(eq(modules.id, providerModuleId)).get();
257
+ if (!module) {
258
+ return { success: false, error: `Provider module '${providerModuleId}' is not installed` };
259
+ }
260
+ const generatedPath = join(module.sourcePath, 'generated');
261
+ if (!existsSync(generatedPath)) {
262
+ return {
263
+ success: false,
264
+ error:
265
+ `public_web provider '${providerModuleId}' has no generated deploy project at ${generatedPath}. ` +
266
+ `Run \`celilo module deploy ${providerModuleId}\` once, then retry the publish.`,
267
+ };
268
+ }
269
+
270
+ const written = await writeStaticContentVars(db, providerModuleId, generatedPath);
271
+
272
+ // A generated project that predates the converge role tasks would read the
273
+ // new vars file and converge nothing. `static_releases` appearing nowhere in
274
+ // the playbook is the tell. Generic string check — core names no module.
275
+ const playbookPath = join(generatedPath, 'ansible', 'playbook.yml');
276
+ if (
277
+ existsSync(playbookPath) &&
278
+ !readFileSync(playbookPath, 'utf-8').includes('static_releases')
279
+ ) {
280
+ return {
281
+ success: false,
282
+ error: `The generated project for '${providerModuleId}' predates the static-content converge (its playbook never reads static_releases). Redeploy the provider (\`celilo module deploy ${providerModuleId}\`) to regenerate it, then retry the publish.`,
283
+ };
284
+ }
285
+
286
+ const { executeAnsible } = await import('./deploy-ansible');
287
+ // Tag-scoped: the full playbook re-templates the bootstrap Caddyfile, which
288
+ // would replace the real config the provider's reconcile wrote and reload
289
+ // caddy into serving nothing. A publish converge touches /srv/www only.
290
+ const result = await executeAnsible(generatedPath, { tags: ['static_content'] });
291
+ if (!result.success) {
292
+ return {
293
+ success: false,
294
+ error: `Static-content converge failed on ${providerModuleId}: ${result.error ?? 'unknown error'}`,
295
+ varsPath: written.varsPath,
296
+ };
297
+ }
298
+ return { success: true, varsPath: written.varsPath };
299
+ }