@mostra/runtime 0.0.0-placeholder → 0.1.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 (114) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +38 -1
  3. package/dist/bin.d.ts +1 -0
  4. package/dist/bin.js +236 -0
  5. package/dist/bin.js.map +1 -0
  6. package/dist/builder/child/main.d.ts +1 -0
  7. package/dist/builder/child/main.js +1408 -0
  8. package/dist/builder/child/main.js.map +1 -0
  9. package/dist/child-xrHmytks.js +49 -0
  10. package/dist/child-xrHmytks.js.map +1 -0
  11. package/dist/deps/child/install.d.ts +1 -0
  12. package/dist/deps/child/install.js +33 -0
  13. package/dist/deps/child/install.js.map +1 -0
  14. package/dist/index.d.ts +221 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +3 -0
  17. package/dist/instance-D7_UVdoN.js +15752 -0
  18. package/dist/instance-D7_UVdoN.js.map +1 -0
  19. package/dist/types-NjNy7gXX.js +57 -0
  20. package/dist/types-NjNy7gXX.js.map +1 -0
  21. package/package.json +87 -4
  22. package/src/actions/index.ts +622 -0
  23. package/src/addressing/index.ts +281 -0
  24. package/src/bin.ts +240 -0
  25. package/src/builder/child/dev.ts +383 -0
  26. package/src/builder/child/fields.ts +363 -0
  27. package/src/builder/child/main.ts +47 -0
  28. package/src/builder/child/plugins.ts +195 -0
  29. package/src/builder/child/scan.ts +459 -0
  30. package/src/builder/child/spa.ts +348 -0
  31. package/src/builder/coverage.ts +72 -0
  32. package/src/builder/index.ts +406 -0
  33. package/src/builder/types.ts +180 -0
  34. package/src/deps/child/install.ts +30 -0
  35. package/src/deps/index.ts +918 -0
  36. package/src/deps/installer.ts +321 -0
  37. package/src/deps/lock.ts +82 -0
  38. package/src/deps/scan.ts +266 -0
  39. package/src/deps/specifier.ts +64 -0
  40. package/src/deps/warm.ts +57 -0
  41. package/src/dev/index.ts +518 -0
  42. package/src/faults.ts +65 -0
  43. package/src/gate.ts +55 -0
  44. package/src/gateway/actions.ts +268 -0
  45. package/src/gateway/browser.ts +650 -0
  46. package/src/gateway/capabilities.ts +739 -0
  47. package/src/gateway/controls.ts +91 -0
  48. package/src/gateway/dev.ts +119 -0
  49. package/src/gateway/http.ts +229 -0
  50. package/src/gateway/index.ts +1209 -0
  51. package/src/gateway/integrity.ts +117 -0
  52. package/src/gateway/listener.ts +217 -0
  53. package/src/gateway/routes.ts +197 -0
  54. package/src/gateway/serve.ts +138 -0
  55. package/src/gc/index.ts +451 -0
  56. package/src/home/acquire.ts +276 -0
  57. package/src/home/index.ts +16 -0
  58. package/src/home/paths.ts +192 -0
  59. package/src/home/platform.ts +34 -0
  60. package/src/home/record.ts +76 -0
  61. package/src/home/settings.ts +113 -0
  62. package/src/index.ts +30 -0
  63. package/src/instance/index.ts +942 -0
  64. package/src/interaction/ephemeral.ts +300 -0
  65. package/src/interaction/events.ts +355 -0
  66. package/src/interaction/fields.ts +392 -0
  67. package/src/interaction/index.ts +1009 -0
  68. package/src/interaction/outbox.ts +493 -0
  69. package/src/interaction/policy.ts +26 -0
  70. package/src/interaction/results.ts +341 -0
  71. package/src/interaction/runs.ts +313 -0
  72. package/src/interaction/signals.ts +120 -0
  73. package/src/interaction/submissions.ts +585 -0
  74. package/src/interaction/subscriptions.ts +258 -0
  75. package/src/interaction/viewers.ts +173 -0
  76. package/src/interaction/wait.ts +201 -0
  77. package/src/ledger/index.ts +442 -0
  78. package/src/ledger/migrations.ts +583 -0
  79. package/src/ledger/requests.ts +105 -0
  80. package/src/ledger/types.ts +28 -0
  81. package/src/live/index.ts +573 -0
  82. package/src/log.ts +316 -0
  83. package/src/processes/child.ts +67 -0
  84. package/src/processes/environment.ts +64 -0
  85. package/src/processes/identity.ts +191 -0
  86. package/src/processes/index.ts +19 -0
  87. package/src/processes/manager.ts +543 -0
  88. package/src/protocol-server/client.ts +94 -0
  89. package/src/protocol-server/index.ts +91 -0
  90. package/src/protocol-server/server.ts +509 -0
  91. package/src/protocol-server/streams.ts +81 -0
  92. package/src/publish/checks.ts +92 -0
  93. package/src/publish/digest.ts +87 -0
  94. package/src/publish/index.ts +23 -0
  95. package/src/publish/manifest.ts +409 -0
  96. package/src/publish/methods.ts +96 -0
  97. package/src/publish/publisher.ts +913 -0
  98. package/src/publish/source.ts +272 -0
  99. package/src/publish/tar.ts +110 -0
  100. package/src/registry/index.ts +481 -0
  101. package/src/registry/store.ts +136 -0
  102. package/src/secrets/index.ts +223 -0
  103. package/src/service/idle.ts +64 -0
  104. package/src/service/index.ts +3 -0
  105. package/src/service/unit.ts +250 -0
  106. package/src/verify/fields.ts +125 -0
  107. package/src/verify/index.ts +913 -0
  108. package/src/verify/regression.ts +157 -0
  109. package/src/verify/runner.ts +230 -0
  110. package/src/verify/sandbox.ts +407 -0
  111. package/src/verify/typecheck.ts +371 -0
  112. package/src/workers/index.ts +17 -0
  113. package/src/workers/launcher.ts +260 -0
  114. package/src/workers/pool.ts +708 -0
@@ -0,0 +1,223 @@
1
+ /**
2
+ * Secrets (D44, AC-06): named values server code reads with `secret(name)`, kept outside artifact
3
+ * source in the home's owner-only store, `secrets/<scope>/<name>` (mode 0600, directories 0700),
4
+ * where the scope is `home` for a secret every artifact shares or the artifact's ID for its own.
5
+ * A host may supply secrets through its `secrets` port instead (Jcode's credential store).
6
+ *
7
+ * Every value Mostra holds or hands out is registered with the instance's redactor, so it never
8
+ * reaches a log, a run log, an event, a diagnostic or a report. Nothing derived from a value is
9
+ * ever written to the ledger.
10
+ */
11
+ import {
12
+ chmodSync,
13
+ existsSync,
14
+ mkdirSync,
15
+ readdirSync,
16
+ readFileSync,
17
+ renameSync,
18
+ rmSync,
19
+ statSync,
20
+ writeFileSync,
21
+ } from "node:fs";
22
+ import { join } from "node:path";
23
+ import {
24
+ type ArtifactRef,
25
+ createDiagnostic,
26
+ RpcError,
27
+ SECRET_NAME_PATTERN,
28
+ SECRET_VALUE_MAX,
29
+ type SecretEntry,
30
+ secretDeleteMethod,
31
+ secretListMethod,
32
+ secretSetMethod,
33
+ } from "@mostra/protocol";
34
+ import type { Log, Redactor } from "../log.ts";
35
+ import { handler, type MethodHandler } from "../protocol-server/index.ts";
36
+
37
+ /** Where a secret lives: the home's shared store, or one artifact's. */
38
+ export type SecretScope =
39
+ | { readonly kind: "home" }
40
+ | { readonly kind: "artifact"; readonly artifactId: string };
41
+
42
+ /** Asks a host's `secrets` port; `null` when it has none, an error when it failed. */
43
+ export type SecretsPort = (request: { artifactId: string; name: string }) => Promise<string | null>;
44
+
45
+ /** The home's secrets. */
46
+ export interface Secrets {
47
+ /** Stores a secret, replacing an earlier value. */
48
+ set(name: string, value: string, scope: SecretScope): SecretEntry;
49
+ /** The names in the home's scope, and in the artifact's when one is named. */
50
+ list(artifactId?: string): SecretEntry[];
51
+ /** Deletes a secret; `false` when there was none. */
52
+ delete(name: string, scope: SecretScope): boolean;
53
+ /**
54
+ * The value server code of `artifactId` gets for `name`: the host's port first, then the
55
+ * artifact's own secret, then the home's shared one.
56
+ *
57
+ * @throws RpcError `MOSTRA_SECRET_MISSING` when no store holds it, or the port failed.
58
+ */
59
+ resolve(artifactId: string, name: string): Promise<string>;
60
+ }
61
+
62
+ /** Options for {@link openSecrets}. */
63
+ export interface SecretsOptions {
64
+ /** The home's real path. */
65
+ readonly home: string;
66
+ readonly redactor: Redactor;
67
+ readonly log: Log;
68
+ /** The host's `secrets` port, while a connected host registered it. */
69
+ readonly port?: () => SecretsPort | undefined;
70
+ }
71
+
72
+ const HOME_SCOPE = "home";
73
+ const ARTIFACT_SCOPE = /^art_[0-9A-HJKMNP-TV-Z]{26}$/;
74
+
75
+ function missing(name: string, detail?: string): RpcError {
76
+ return new RpcError(
77
+ createDiagnostic("MOSTRA_SECRET_MISSING", {
78
+ message: `No secret named ${name} is set${detail ? ` (${detail})` : ""}.`,
79
+ hint: `Set it with \`mostra secret set ${name}\`, reading the value from stdin.`,
80
+ }),
81
+ );
82
+ }
83
+
84
+ function invalidName(name: string): RpcError {
85
+ return new RpcError(
86
+ createDiagnostic("MOSTRA_HOST_INVALID_PARAMS", {
87
+ message: `${JSON.stringify(name).slice(0, 80)} isn't a secret name: a letter or "_", then up to 127 letters, digits, "_", "." and "-".`,
88
+ }),
89
+ );
90
+ }
91
+
92
+ /** Opens the home's secret store, registering every stored value with the redactor. */
93
+ export function openSecrets(options: SecretsOptions): Secrets {
94
+ const root = join(options.home, "secrets");
95
+ mkdirSync(root, { recursive: true, mode: 0o700 });
96
+ chmodSync(root, 0o700);
97
+
98
+ const dirOf = (scope: SecretScope): string =>
99
+ join(root, scope.kind === "home" ? HOME_SCOPE : scope.artifactId);
100
+
101
+ const read = (dir: string, name: string): string | undefined => {
102
+ try {
103
+ return readFileSync(join(dir, name), "utf8");
104
+ } catch (error) {
105
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
106
+ throw error;
107
+ }
108
+ };
109
+
110
+ // Every value already stored is protected before anything is logged.
111
+ for (const scope of existsSync(root) ? readdirSync(root) : []) {
112
+ if (scope !== HOME_SCOPE && !ARTIFACT_SCOPE.test(scope)) continue;
113
+ for (const name of readdirSync(join(root, scope))) {
114
+ if (!SECRET_NAME_PATTERN.test(name)) continue;
115
+ const value = read(join(root, scope), name);
116
+ if (value !== undefined) options.redactor.protectSecret(value);
117
+ }
118
+ }
119
+
120
+ const entry = (dir: string, name: string, scope: SecretScope): SecretEntry => ({
121
+ name,
122
+ scope: scope.kind,
123
+ ...(scope.kind === "artifact" ? { artifactId: scope.artifactId } : {}),
124
+ updatedAt: statSync(join(dir, name)).mtime.toISOString(),
125
+ });
126
+
127
+ const listScope = (scope: SecretScope): SecretEntry[] => {
128
+ const dir = dirOf(scope);
129
+ if (!existsSync(dir)) return [];
130
+ return readdirSync(dir)
131
+ .filter((name) => SECRET_NAME_PATTERN.test(name))
132
+ .sort()
133
+ .map((name) => entry(dir, name, scope));
134
+ };
135
+
136
+ return {
137
+ set(name, value, scope) {
138
+ if (!SECRET_NAME_PATTERN.test(name)) throw invalidName(name);
139
+ if (value.length === 0 || Buffer.byteLength(value, "utf8") > SECRET_VALUE_MAX) {
140
+ throw new RpcError(
141
+ createDiagnostic("MOSTRA_HOST_INVALID_PARAMS", {
142
+ message: `The value of the secret ${name} must be 1 byte to 64 KiB of UTF-8.`,
143
+ }),
144
+ );
145
+ }
146
+ options.redactor.protectSecret(value);
147
+ const dir = dirOf(scope);
148
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
149
+ chmodSync(dir, 0o700);
150
+ // Written beside it, then renamed: a reader never sees half a value.
151
+ const temporary = join(dir, `.${name}.${process.pid}.tmp`);
152
+ writeFileSync(temporary, value, { mode: 0o600, flag: "w" });
153
+ chmodSync(temporary, 0o600);
154
+ renameSync(temporary, join(dir, name));
155
+ options.log.info("secret.set", { name, scope: scope.kind });
156
+ return entry(dir, name, scope);
157
+ },
158
+ list(artifactId) {
159
+ return [
160
+ ...listScope({ kind: "home" }),
161
+ ...(artifactId ? listScope({ kind: "artifact", artifactId }) : []),
162
+ ];
163
+ },
164
+ delete(name, scope) {
165
+ if (!SECRET_NAME_PATTERN.test(name)) throw invalidName(name);
166
+ const file = join(dirOf(scope), name);
167
+ if (!existsSync(file)) return false;
168
+ rmSync(file, { force: true });
169
+ options.log.info("secret.deleted", { name, scope: scope.kind });
170
+ return true;
171
+ },
172
+ async resolve(artifactId, name) {
173
+ if (!SECRET_NAME_PATTERN.test(name)) throw missing(name, "not a secret name");
174
+ const port = options.port?.();
175
+ if (port) {
176
+ let value: string | null;
177
+ try {
178
+ value = await port({ artifactId, name });
179
+ } catch (error) {
180
+ options.log.warn("secret.port_failed", {
181
+ name,
182
+ error: String((error as Error)?.message ?? error),
183
+ });
184
+ throw missing(name, "the host's secrets port didn't answer");
185
+ }
186
+ if (typeof value === "string") {
187
+ options.redactor.protectSecret(value);
188
+ return value;
189
+ }
190
+ }
191
+ const value =
192
+ read(dirOf({ kind: "artifact", artifactId }), name) ?? read(dirOf({ kind: "home" }), name);
193
+ if (value === undefined) throw missing(name);
194
+ // A file written into the store by hand since start-up is protected before it leaves.
195
+ options.redactor.protectSecret(value);
196
+ return value;
197
+ },
198
+ };
199
+ }
200
+
201
+ /** The `secret/*` methods (D44): set by name from the value given, list names, delete. */
202
+ export function secretMethods(
203
+ secrets: Secrets,
204
+ resolveArtifact: (ref: ArtifactRef) => string,
205
+ ): MethodHandler[] {
206
+ const scopeOf = (artifact: ArtifactRef | undefined): SecretScope =>
207
+ artifact === undefined
208
+ ? { kind: "home" }
209
+ : { kind: "artifact", artifactId: resolveArtifact(artifact) };
210
+ return [
211
+ handler(secretSetMethod, (params) =>
212
+ secrets.set(params.name, params.value, scopeOf(params.artifact)),
213
+ ),
214
+ handler(secretListMethod, (params) => ({
215
+ secrets: secrets.list(
216
+ params.artifact === undefined ? undefined : resolveArtifact(params.artifact),
217
+ ),
218
+ })),
219
+ handler(secretDeleteMethod, (params) => ({
220
+ deleted: secrets.delete(params.name, scopeOf(params.artifact)),
221
+ })),
222
+ ];
223
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The daemon's idle exit (D62, RT-08): a daemon keeps running while it has open views, pending
3
+ * deliveries, running action runs, live producers, host subscriptions or attached clients, and
4
+ * otherwise exits after 30 idle minutes. A host-spawned instance lives exactly as long as its
5
+ * stdio, and a daemon started `--always-on` (the login service) never exits for lack of work.
6
+ */
7
+
8
+ /** What keeps a daemon running, as counts; any non-zero one is work. */
9
+ export type Busy = () => Readonly<Record<string, number>>;
10
+
11
+ /** The default idle time before a daemon exits. */
12
+ export const IDLE_EXIT_MS: number = 30 * 60_000;
13
+
14
+ /** The idle watch. */
15
+ export interface IdleWatch {
16
+ /** When the daemon exits if nothing happens, or `undefined` while it's busy or never exits. */
17
+ exitAt(): string | undefined;
18
+ stop(): void;
19
+ }
20
+
21
+ /** Options for {@link watchIdle}. */
22
+ export interface IdleOptions {
23
+ readonly busy: Busy;
24
+ /** Called once, when the daemon has been idle for `idleMs`. */
25
+ readonly onIdle: () => void;
26
+ readonly idleMs?: number;
27
+ /** How often the counts are read; default 5 s, or a tenth of `idleMs` when that is shorter. */
28
+ readonly checkMs?: number;
29
+ readonly now?: () => number;
30
+ }
31
+
32
+ /** Starts watching; the daemon exits through `onIdle` once nothing has kept it for `idleMs`. */
33
+ export function watchIdle(options: IdleOptions): IdleWatch {
34
+ const idleMs = options.idleMs ?? IDLE_EXIT_MS;
35
+ const now = options.now ?? Date.now;
36
+ let idleSince: number | undefined = now();
37
+ let fired = false;
38
+ const check = (): void => {
39
+ const counts = options.busy();
40
+ const busy = Object.values(counts).some((count) => count > 0);
41
+ if (busy) {
42
+ idleSince = undefined;
43
+ return;
44
+ }
45
+ idleSince ??= now();
46
+ if (!fired && now() - idleSince >= idleMs) {
47
+ fired = true;
48
+ options.onIdle();
49
+ }
50
+ };
51
+ const timer = setInterval(check, options.checkMs ?? Math.min(5_000, Math.max(50, idleMs / 10)));
52
+ timer.unref?.();
53
+ return {
54
+ exitAt() {
55
+ check();
56
+ return idleSince === undefined || fired
57
+ ? undefined
58
+ : new Date(idleSince + idleMs).toISOString();
59
+ },
60
+ stop() {
61
+ clearInterval(timer);
62
+ },
63
+ };
64
+ }
@@ -0,0 +1,3 @@
1
+ // The daemon's lifecycle (D62, RT-08): its login service and its idle exit.
2
+ export { type IdleWatch, watchIdle } from "./idle.ts";
3
+ export { hasLoginService, installService, serviceStatus, uninstallService } from "./unit.ts";
@@ -0,0 +1,250 @@
1
+ /**
2
+ * The home's login service (D62, D63, RT-08): `mostra daemon install` registers the home's daemon
3
+ * with the user's service manager, so an artifact answers at any hour, even after a reboot. A
4
+ * launchd agent on macOS, a systemd user unit on Linux; either runs `mostra-runtime daemon
5
+ * --always-on --home <home>`, which never exits for lack of work, and restarts it when it ends
6
+ * unexpectedly. The unit carries no secret: the daemon reads them from the home (D44).
7
+ */
8
+ import { execFileSync } from "node:child_process";
9
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
10
+ import { homedir } from "node:os";
11
+ import { dirname, join } from "node:path";
12
+ import { createDiagnostic, RpcError } from "@mostra/protocol";
13
+ import { homeHash } from "../home/index.ts";
14
+ import type { Environment } from "../log.ts";
15
+
16
+ /** Where a home's service is, and whether it is there. */
17
+ export interface ServiceStatus {
18
+ /** `launchd` (macOS) or `systemd` (Linux). */
19
+ readonly manager: "launchd" | "systemd";
20
+ /** The service's name: the launchd label, or the systemd unit. */
21
+ readonly name: string;
22
+ /** The file that defines it. */
23
+ readonly file: string;
24
+ /** Whether the file exists. */
25
+ readonly installed: boolean;
26
+ /** What it runs. */
27
+ readonly command: readonly string[];
28
+ }
29
+
30
+ /** What a service runs and where. */
31
+ export interface ServiceSpec {
32
+ /** The home's real path. */
33
+ readonly home: string;
34
+ /** The Node executable and the runtime's entry, `mostra-runtime`. */
35
+ readonly node: string;
36
+ readonly entry: string;
37
+ readonly env?: Environment;
38
+ /** `process.platform`. */
39
+ readonly platform?: string;
40
+ }
41
+
42
+ function failed(message: string): RpcError {
43
+ return new RpcError(createDiagnostic("MOSTRA_ENV_SERVICE_FAILED", { message }));
44
+ }
45
+
46
+ function userHome(env: Environment): string {
47
+ return env["HOME"] ?? homedir();
48
+ }
49
+
50
+ /** The service a home's daemon would be, installed or not. */
51
+ export function serviceFor(spec: ServiceSpec): ServiceStatus {
52
+ const env = spec.env ?? process.env;
53
+ const platform = spec.platform ?? process.platform;
54
+ const hash = homeHash(spec.home);
55
+ const command = [spec.node, spec.entry, "daemon", "--always-on", "--home", spec.home];
56
+ if (platform === "darwin") {
57
+ const name = `dev.mostra.daemon.${hash}`;
58
+ return {
59
+ manager: "launchd",
60
+ name,
61
+ file: join(userHome(env), "Library", "LaunchAgents", `${name}.plist`),
62
+ installed: existsSync(join(userHome(env), "Library", "LaunchAgents", `${name}.plist`)),
63
+ command,
64
+ };
65
+ }
66
+ if (platform === "linux") {
67
+ const config = env["XDG_CONFIG_HOME"] || join(userHome(env), ".config");
68
+ const name = `mostra-${hash.toLowerCase()}.service`;
69
+ const file = join(config, "systemd", "user", name);
70
+ return { manager: "systemd", name, file, installed: existsSync(file), command };
71
+ }
72
+ throw new RpcError(
73
+ createDiagnostic("MOSTRA_PLATFORM_UNSUPPORTED", {
74
+ message: `Mostra can't install a login service on ${platform}.`,
75
+ }),
76
+ );
77
+ }
78
+
79
+ /**
80
+ * Whether `home` has a login service installed: its daemon then never exits for lack of work,
81
+ * whoever started it, so a daemon started by hand before `install` keeps the artifacts answering.
82
+ */
83
+ export function hasLoginService(home: string, env: Environment = process.env): boolean {
84
+ try {
85
+ return serviceFor({ home, node: "", entry: "", env }).installed;
86
+ } catch {
87
+ return false;
88
+ }
89
+ }
90
+
91
+ const xml = (text: string): string =>
92
+ text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
93
+
94
+ /** systemd's quoting for one `ExecStart` word. */
95
+ const systemdWord = (word: string): string =>
96
+ /^[A-Za-z0-9_./:@=+-]+$/.test(word)
97
+ ? word
98
+ : `"${word
99
+ .replace(/\\/g, "\\\\")
100
+ .replace(/"/g, '\\"')
101
+ .replace(/\n/g, "\\n")
102
+ .replace(/%/g, "%%")
103
+ .replace(/\$/g, "$$$$")}"`;
104
+
105
+ /** The environment a service gets: what finding programs and the home needs, nothing secret. */
106
+ function serviceEnvironment(env: Environment): Record<string, string> {
107
+ const out: Record<string, string> = {
108
+ PATH: env["PATH"] ?? "/usr/local/bin:/usr/bin:/bin",
109
+ HOME: userHome(env),
110
+ };
111
+ for (const name of ["MOSTRA_RUNTIME_DIR", "LANG", "TZ"]) {
112
+ const value = env[name];
113
+ if (value) out[name] = value;
114
+ }
115
+ return out;
116
+ }
117
+
118
+ /** The text of the service's file. */
119
+ export function serviceFile(spec: ServiceSpec, status: ServiceStatus): string {
120
+ const env = serviceEnvironment(spec.env ?? process.env);
121
+ const log = join(spec.home, "logs", "service.log");
122
+ if (status.manager === "launchd") {
123
+ const args = status.command.map((word) => ` <string>${xml(word)}</string>`).join("\n");
124
+ const vars = Object.entries(env)
125
+ .map(([key, value]) => ` <key>${xml(key)}</key>\n <string>${xml(value)}</string>`)
126
+ .join("\n");
127
+ return `<?xml version="1.0" encoding="UTF-8"?>
128
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
129
+ <plist version="1.0">
130
+ <dict>
131
+ <key>Label</key>
132
+ <string>${xml(status.name)}</string>
133
+ <key>ProgramArguments</key>
134
+ <array>
135
+ ${args}
136
+ </array>
137
+ <key>EnvironmentVariables</key>
138
+ <dict>
139
+ ${vars}
140
+ </dict>
141
+ <key>RunAtLoad</key>
142
+ <true/>
143
+ <key>KeepAlive</key>
144
+ <dict>
145
+ <key>SuccessfulExit</key>
146
+ <false/>
147
+ </dict>
148
+ <key>ThrottleInterval</key>
149
+ <integer>10</integer>
150
+ <key>StandardOutPath</key>
151
+ <string>${xml(log)}</string>
152
+ <key>StandardErrorPath</key>
153
+ <string>${xml(log)}</string>
154
+ </dict>
155
+ </plist>
156
+ `;
157
+ }
158
+ const environment = Object.entries(env)
159
+ .map(([key, value]) => `Environment=${systemdWord(`${key}=${value}`)}`)
160
+ .join("\n");
161
+ return `[Unit]
162
+ Description=Mostra daemon for ${spec.home.replace(/\n/g, " ").replace(/%/g, "%%")}
163
+ After=network.target
164
+
165
+ [Service]
166
+ Type=simple
167
+ ExecStart=${status.command.map(systemdWord).join(" ")}
168
+ ${environment}
169
+ Restart=on-failure
170
+ RestartSec=10
171
+
172
+ [Install]
173
+ WantedBy=default.target
174
+ `;
175
+ }
176
+
177
+ /** Options of an install or uninstall. */
178
+ export interface ServiceOptions {
179
+ /** Write the file only, without asking the service manager to start it (tests). */
180
+ readonly noStart?: boolean;
181
+ }
182
+
183
+ function run(command: string, args: readonly string[]): void {
184
+ try {
185
+ execFileSync(command, [...args], { stdio: ["ignore", "pipe", "pipe"], timeout: 30_000 });
186
+ } catch (error) {
187
+ const failure = error as { stderr?: Buffer; message: string };
188
+ const detail = failure.stderr?.toString().trim() || failure.message;
189
+ throw failed(`${command} ${args.join(" ")} failed: ${detail.slice(0, 400)}`);
190
+ }
191
+ }
192
+
193
+ const uid = (): number => process.getuid?.() ?? 0;
194
+
195
+ /** Installs the home's daemon as a login service and starts it, replacing an earlier one. */
196
+ export function installService(spec: ServiceSpec, options: ServiceOptions = {}): ServiceStatus {
197
+ const status = serviceFor(spec);
198
+ const text = serviceFile(spec, status);
199
+ try {
200
+ mkdirSync(dirname(status.file), { recursive: true });
201
+ mkdirSync(join(spec.home, "logs"), { recursive: true, mode: 0o700 });
202
+ if (status.installed && !options.noStart) stopService(status);
203
+ writeFileSync(status.file, text, { mode: 0o644 });
204
+ } catch (error) {
205
+ if (error instanceof RpcError) throw error;
206
+ throw failed(`Writing ${status.file} failed: ${(error as Error).message}`);
207
+ }
208
+ if (!options.noStart) {
209
+ if (status.manager === "launchd") {
210
+ run("launchctl", ["bootstrap", `gui/${uid()}`, status.file]);
211
+ } else {
212
+ run("systemctl", ["--user", "daemon-reload"]);
213
+ run("systemctl", ["--user", "enable", "--now", status.name]);
214
+ }
215
+ }
216
+ return { ...status, installed: true };
217
+ }
218
+
219
+ function stopService(status: ServiceStatus): void {
220
+ try {
221
+ if (status.manager === "launchd") run("launchctl", ["bootout", `gui/${uid()}/${status.name}`]);
222
+ else run("systemctl", ["--user", "disable", "--now", status.name]);
223
+ } catch {
224
+ // Not loaded: nothing to stop.
225
+ }
226
+ }
227
+
228
+ /** Stops and removes the home's login service; a home without one is left as it is. */
229
+ export function uninstallService(spec: ServiceSpec, options: ServiceOptions = {}): ServiceStatus {
230
+ const status = serviceFor(spec);
231
+ if (!status.installed) return status;
232
+ if (!options.noStart) stopService(status);
233
+ rmSync(status.file, { force: true });
234
+ if (!options.noStart && status.manager === "systemd") {
235
+ try {
236
+ run("systemctl", ["--user", "daemon-reload"]);
237
+ } catch {
238
+ // The file is gone either way.
239
+ }
240
+ }
241
+ return { ...status, installed: false };
242
+ }
243
+
244
+ /** Whether the home has a login service whose file runs this home's daemon (`mostra doctor`). */
245
+ export function serviceStatus(spec: ServiceSpec): ServiceStatus & { readonly current: boolean } {
246
+ const status = serviceFor(spec);
247
+ if (!status.installed) return { ...status, current: false };
248
+ const text = readFileSync(status.file, "utf8");
249
+ return { ...status, current: text === serviceFile(spec, status) };
250
+ }
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Field-ID lint (AU-05, D52, D138 item 3): pure judgements over a version's static field scan
3
+ * (`registry.json`'s `fields`, D109) and what the field probe saw mounted.
4
+ *
5
+ * - **Duplicate IDs**: one ID used with another hook kind, another scope or an initial value of
6
+ * another type is an error, whether the static scan or the page shows it.
7
+ * - **Shared IDs**: the same ID mounted several times the same way is a deliberate shared value,
8
+ * a hint.
9
+ * - **Changing IDs**: two fresh boots with identical inputs and one fixed clock; an ID mounted in
10
+ * one and not the other, that no literal ID of the scan names, is an error.
11
+ */
12
+ import { createDiagnostic, type Diagnostic, type ProbedField } from "@mostra/protocol";
13
+ import type { FieldCoverage, FieldEntry } from "../builder/index.ts";
14
+
15
+ const where = (entry: FieldEntry): string =>
16
+ `${entry.location.file}:${entry.location.line}:${entry.location.column}`;
17
+
18
+ /** The literal IDs the static scan names with two hooks or two scopes, with the two entries. */
19
+ function staticConflicts(
20
+ coverage: FieldCoverage | undefined,
21
+ ): { readonly id: string; readonly first: FieldEntry; readonly other: FieldEntry }[] {
22
+ if (!coverage) return [];
23
+ const byId = new Map<string, FieldEntry[]>();
24
+ for (const entry of coverage.entries) {
25
+ if (entry.id === undefined) continue;
26
+ byId.set(entry.id, [...(byId.get(entry.id) ?? []), entry]);
27
+ }
28
+ const conflicts: { id: string; first: FieldEntry; other: FieldEntry }[] = [];
29
+ for (const [id, entries] of byId) {
30
+ const first = entries[0] as FieldEntry;
31
+ const other = entries.find(
32
+ (entry) =>
33
+ entry.hook !== first.hook || (entry.scope ?? "viewer") !== (first.scope ?? "viewer"),
34
+ );
35
+ if (other) conflicts.push({ id, first, other });
36
+ }
37
+ return conflicts;
38
+ }
39
+
40
+ const staticConflictIds = (coverage: FieldCoverage | undefined): ReadonlySet<string> =>
41
+ new Set(staticConflicts(coverage).map((conflict) => conflict.id));
42
+
43
+ /** Static duplicates: one literal ID named by two hooks, or with two literal scopes. */
44
+ export function staticFieldLint(coverage: FieldCoverage | undefined): Diagnostic[] {
45
+ const findings: Diagnostic[] = [];
46
+ for (const { id, first, other } of staticConflicts(coverage)) {
47
+ const how =
48
+ other.hook !== first.hook
49
+ ? `with ${first.hook} at ${where(first)} and ${other.hook} at ${where(other)}`
50
+ : `with scope ${first.scope ?? "viewer"} at ${where(first)} and scope ${other.scope ?? "viewer"} at ${where(other)}`;
51
+ findings.push(
52
+ createDiagnostic("MOSTRA_FIELD_DUPLICATE_ID", {
53
+ message: `The field ID "${id}" is used for two different fields: ${how}.`,
54
+ location: other.location,
55
+ }),
56
+ );
57
+ }
58
+ return findings;
59
+ }
60
+
61
+ /**
62
+ * What the probe saw: conflicting mounts (errors) and IDs mounted more than once (hints). An ID
63
+ * the static scan already reported as a duplicate isn't reported again.
64
+ */
65
+ export function probedFieldLint(
66
+ fields: readonly ProbedField[],
67
+ viewport: string,
68
+ coverage?: FieldCoverage,
69
+ ): Diagnostic[] {
70
+ const flagged = staticConflictIds(coverage);
71
+ const findings: Diagnostic[] = [];
72
+ for (const field of fields) {
73
+ if (field.conflicts.length > 0) {
74
+ if (flagged.has(field.id)) continue;
75
+ findings.push(
76
+ createDiagnostic("MOSTRA_FIELD_DUPLICATE_ID", {
77
+ message: `The page mounted the field ID "${field.id}" for two different fields: ${field.conflicts.join("; ")}.`,
78
+ location: { viewport },
79
+ }),
80
+ );
81
+ } else if (field.mounts > 1) {
82
+ findings.push(
83
+ createDiagnostic("MOSTRA_FIELD_SHARED", {
84
+ message: `${field.mounts} mounted components use the field ID "${field.id}" the same way, so they edit one saved value.`,
85
+ location: { viewport },
86
+ }),
87
+ );
88
+ }
89
+ }
90
+ return findings;
91
+ }
92
+
93
+ /** Whether a literal ID of the static scan names `id`. */
94
+ const literal = (coverage: FieldCoverage | undefined, id: string): boolean =>
95
+ coverage?.entries.some((entry) => entry.id === id) ?? false;
96
+
97
+ /**
98
+ * IDs that differ between two boots with identical inputs (D138 item 3): mounted in one and not
99
+ * the other, and named by no literal ID of the scan.
100
+ */
101
+ export function unstableFieldLint(
102
+ first: readonly ProbedField[],
103
+ second: readonly ProbedField[],
104
+ coverage: FieldCoverage | undefined,
105
+ viewport: string,
106
+ ): Diagnostic[] {
107
+ const mounted = (fields: readonly ProbedField[]): Set<string> =>
108
+ new Set(fields.filter((field) => field.mounts > 0).map((field) => field.id));
109
+ const a = mounted(first);
110
+ const b = mounted(second);
111
+ const changed = [...a].filter((id) => !b.has(id) && !literal(coverage, id));
112
+ const appeared = [...b].filter((id) => !a.has(id) && !literal(coverage, id));
113
+ if (changed.length === 0 && appeared.length === 0) return [];
114
+ const sample = (ids: string[]): string =>
115
+ ids
116
+ .slice(0, 3)
117
+ .map((id) => `"${id}"`)
118
+ .join(", ");
119
+ return [
120
+ createDiagnostic("MOSTRA_FIELD_ID_UNSTABLE", {
121
+ message: `Two loads of the page with identical inputs mounted different field IDs: ${sample(changed) || "none"} the first time, ${sample(appeared) || "none"} the second. A viewer's saved answers under them would be lost on reload.`,
122
+ location: { viewport },
123
+ }),
124
+ ];
125
+ }