@yunuseon/kayra 0.17.1 → 0.18.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 (91) hide show
  1. package/README.md +2 -0
  2. package/agent/skills/kayra-release/SKILL.md +6 -1
  3. package/ansible/roles/platform/tasks/main.yml +10 -2
  4. package/cli/dist/clients/api/api.js +6 -4
  5. package/cli/dist/clients/api/auth.js +1 -1
  6. package/cli/dist/clients/api/commands.js +1 -49
  7. package/cli/dist/clients/api/directories.js +1 -1
  8. package/cli/dist/clients/api/discovery.js +1 -1
  9. package/cli/dist/clients/api/{contract.js → openapi.js} +3 -52
  10. package/cli/dist/clients/api/protocol.js +1 -66
  11. package/cli/dist/clients/api/runs.js +1 -1
  12. package/cli/dist/clients/api/start.js +3 -3
  13. package/cli/dist/clients/cli/explain.js +1 -1
  14. package/cli/dist/clients/cli/framed.js +1 -1
  15. package/cli/dist/clients/cli/invocation.js +1 -1
  16. package/cli/dist/clients/cli/parser.js +4 -0
  17. package/cli/dist/clients/cli/questions.js +1 -1
  18. package/cli/dist/clients/cli/status.js +1 -1
  19. package/cli/dist/clients/cli/terminal.js +1 -1
  20. package/cli/dist/clients/cli/text.js +1 -1
  21. package/cli/dist/clients/cli/validate.js +1 -1
  22. package/cli/dist/clients/cli/values.js +1 -1
  23. package/cli/dist/clients/cli/views.js +1 -1
  24. package/cli/dist/clients/mcp/run.js +69 -0
  25. package/cli/dist/clients/mcp/server.js +130 -0
  26. package/cli/dist/clients/mcp/tools.js +101 -0
  27. package/cli/dist/clients/wire/contract.js +53 -0
  28. package/cli/dist/clients/{api → wire}/queries.js +1 -1
  29. package/cli/dist/clients/wire/schemas.js +67 -0
  30. package/cli/dist/clients/wire/words.js +48 -0
  31. package/cli/dist/core/adapters/fs.js +1 -1
  32. package/cli/dist/core/adapters/network.js +1 -1
  33. package/cli/dist/core/adapters/opentofu.js +1 -1
  34. package/cli/dist/core/fleet/brand.js +23 -14
  35. package/cli/dist/core/fleet/docs.js +2 -2
  36. package/cli/dist/core/fleet/load.js +3 -2
  37. package/cli/dist/core/fleet/parse.js +59 -91
  38. package/cli/dist/core/fleet/settings.js +38 -13
  39. package/cli/dist/core/fleet/shape.js +5 -20
  40. package/cli/dist/core/interpreter/events.js +1 -1
  41. package/cli/dist/core/interpreter/loop.js +1 -1
  42. package/cli/dist/core/interpreter/needs.js +1 -1
  43. package/cli/dist/core/interpreter/process.js +2 -2
  44. package/cli/dist/core/interpreter/progress.js +1 -1
  45. package/cli/dist/core/interpreter/pty.js +1 -1
  46. package/cli/dist/core/operations/dispatch.js +2 -2
  47. package/cli/dist/core/plan/model.js +1 -1
  48. package/cli/dist/core/recipes/app-check.js +5 -8
  49. package/cli/dist/core/recipes/apps.js +2 -2
  50. package/cli/dist/core/recipes/backup.js +1 -1
  51. package/cli/dist/core/recipes/certs.js +1 -1
  52. package/cli/dist/core/recipes/doctor.js +1 -1
  53. package/cli/dist/core/recipes/host.js +2 -2
  54. package/cli/dist/core/recipes/ssh.js +2 -2
  55. package/cli/dist/core/recipes/steps.js +2 -2
  56. package/cli/dist/core/status/look.js +1 -1
  57. package/cli/dist/core/text/spans.js +1 -1
  58. package/cli/dist/core/validation/facts.js +3 -2
  59. package/cli/dist/core/validation/findings.js +3 -3
  60. package/cli/dist/deployer/app.js +2 -2
  61. package/cli/dist/deployer/brand.js +1 -1
  62. package/cli/dist/deployer/build/builder.js +2 -2
  63. package/cli/dist/deployer/build/bundle.js +2 -2
  64. package/cli/dist/deployer/build/compose.js +1 -1
  65. package/cli/dist/deployer/cron.js +1 -1
  66. package/cli/dist/deployer/ctl/answers.js +1 -1
  67. package/cli/dist/deployer/deployer.js +7 -11
  68. package/cli/dist/deployer/forges/forge.js +1 -1
  69. package/cli/dist/deployer/forges/forgejo.js +1 -1
  70. package/cli/dist/deployer/forges/github.js +1 -1
  71. package/cli/dist/deployer/forges/gitlab.js +1 -1
  72. package/cli/dist/deployer/forges/issues.js +2 -2
  73. package/cli/dist/deployer/forges/notify.js +2 -2
  74. package/cli/dist/deployer/runs/queue.js +8 -1
  75. package/cli/dist/deployer/runs/records.js +1 -1
  76. package/cli/dist/deployer/runs/run.js +2 -2
  77. package/cli/dist/deployer/runs/store.js +1 -1
  78. package/cli/dist/lib/brand.js +2 -0
  79. package/cli/dist/lib/closest.js +17 -0
  80. package/cli/dist/lib/schema.js +7 -0
  81. package/cli/dist/lib/yaml.js +21 -0
  82. package/cli/dist/main.js +12 -4
  83. package/package.json +3 -1
  84. package/schema/app.json +4 -2
  85. package/schema/server.json +10 -5
  86. package/scripts/agent/guard.sh +28 -6
  87. /package/cli/dist/clients/{api → wire}/contract.gen.js +0 -0
  88. /package/cli/dist/clients/{api → wire}/status.js +0 -0
  89. /package/cli/dist/clients/{api → wire}/validate.js +0 -0
  90. /package/cli/dist/{result.js → lib/result.js} +0 -0
  91. /package/cli/dist/{typed.js → lib/typed.js} +0 -0
@@ -1,5 +1,7 @@
1
1
  import { z } from "zod";
2
- import { typed } from "../../typed.js";
2
+ import { typed } from "../../lib/typed.js";
3
+ import { appNameSchema, domainSchema, repoPathSchema, repoUrlSchema, subdomainSchema } from "./brand.js";
4
+ import { serverTargets } from "./model.js";
3
5
  /** The server kinds, each with its playbook; settings say which kinds read them. */
4
6
  export const serverKinds = ["platform", "edge", "nas"];
5
7
  // eslint-disable-next-line functional/prefer-immutable-types -- holds a Zod schema: immutable once built, but a class the rule cannot see into
@@ -115,28 +117,51 @@ export const defaultsSchema = z.strictObject(shape(settings.filter((each) => !ea
115
117
  /** secrets.yml: the known secrets typed; other keys may be helpers that vars.yml references. */
116
118
  // eslint-disable-next-line functional/prefer-immutable-types -- a Zod schema: immutable once built, but a class the rule cannot see into
117
119
  export const secretsSchema = (kind) => z.looseObject(shape(settingsFor(kind, true)));
118
- /** server.yml: topology only. */
119
- export const serverSchema = z.strictObject({
120
- kind: z.enum(serverKinds).optional().describe("Which playbook: platform (default; Traefik, Authelia, the deployer, apps), edge or nas."),
121
- target: z.enum(["hetzner", "multipass", "home"]).describe("Where it runs: hetzner, multipass (a local VM) or home (a machine nothing creates)."),
122
- domain: z.string().describe("The server's domain; platform subdomains and the apps' hang off it."),
123
- vault: z.boolean().optional().describe("secrets.yml is vault-encrypted (required outside multipass)."),
120
+ /**
121
+ * A multipass server, a test machine by definition, may clone an app over
122
+ * plain HTTP too: the upgrade lab serves its fixture app that way.
123
+ */
124
+ const schemes = (target) => typed(target === "multipass" ? ["https://", "http://"] : ["https://"]);
125
+ /** server.yml: topology only. What it says is checked here, once: the parser, the editors' schema and the docs read it. */
126
+ export const serverSchema = z
127
+ .strictObject({
128
+ kind: z
129
+ .enum(serverKinds, { error: (issue) => `kind must be ${serverKinds.join(", ")}, not '${String(issue.input)}'` })
130
+ .default("platform")
131
+ .describe("Which playbook: platform (default; Traefik, Authelia, the deployer, apps), edge or nas."),
132
+ target: z
133
+ .enum(serverTargets, { error: (issue) => `target must be ${serverTargets.join(", ")}, not '${String(issue.input)}'` })
134
+ .describe("Where it runs: hetzner, multipass (a local VM) or home (a machine nothing creates)."),
135
+ domain: domainSchema.describe("The server's domain; platform subdomains and the apps' hang off it."),
136
+ vault: z.boolean().default(false).describe("secrets.yml is vault-encrypted (required outside multipass)."),
124
137
  vault_password_file: z.string().optional().describe("The vault password file; without it, Ansible asks."),
125
138
  apps: z
126
139
  .array(z.strictObject({
127
- name: z.string(),
128
- repo: z.string().describe("The app's repository, https://."),
140
+ name: appNameSchema,
141
+ repo: repoUrlSchema.describe("The app's repository, https://."),
129
142
  ref: z.string().optional().describe("The branch to build and deploy (default main)."),
130
- path: z.string().optional().describe("The app's root inside the repository (default .)."),
143
+ path: repoPathSchema.prefault(".").describe("The app's root inside the repository (default .)."),
131
144
  }))
132
- .optional()
145
+ .default([])
133
146
  .describe("The apps this server runs (platform only)."),
147
+ })
148
+ .superRefine((server, context) => {
149
+ if (server.kind !== "platform" && server.apps.length > 0)
150
+ context.addIssue({ code: "custom", path: ["apps"], message: "apps run on platform servers only" });
151
+ server.apps.forEach((app, index) => {
152
+ if (!schemes(server.target).some((scheme) => app.repo.startsWith(scheme)))
153
+ context.addIssue({
154
+ code: "custom",
155
+ path: ["apps", index, "repo"],
156
+ message: `repo must be an https:// URL${server.target === "multipass" ? " (or http:// on multipass)" : ""}`,
157
+ });
158
+ });
134
159
  });
135
160
  /** app.yml, at the root of an app's repository: the app contract. */
136
161
  export const appManifestSchema = z.strictObject({
137
- name: z.string().describe("The app's name, as in the server.yml entry."),
162
+ name: appNameSchema.describe("The app's name, as in the server.yml entry."),
138
163
  compose: z.array(z.string()).describe("Compose files, relative to the app root, in order."),
139
- subdomains: z.array(z.string()).describe("Hostnames the app claims: <sub>.<domain>."),
164
+ subdomains: z.array(subdomainSchema).describe("Hostnames the app claims: <sub>.<domain>."),
140
165
  secrets: z.array(z.string()).optional().describe("Secret keys; their values come from the fleet's apps/<app>.secrets.yml."),
141
166
  config: z.array(z.string()).optional().describe("Config keys; their values come from the fleet's apps/<app>.yml."),
142
167
  });
@@ -1,22 +1,6 @@
1
- import { err, ok } from "../../result.js";
1
+ import { err, ok } from "../../lib/result.js";
2
2
  import { isAnsibleVariable, settings } from "./settings.js";
3
- import { typed } from "../../typed.js";
4
- /** Edit distance, for "did you mean". */
5
- const indices = (length) => typed([...Array(length).keys()]);
6
- const distance = (a, b) => indices(b.length)
7
- .reduce((row, j) => indices(a.length).reduce((next, i) => Object.freeze([
8
- ...next,
9
- Math.min((row[i + 1] ?? 0) + 1, (next[i] ?? 0) + 1, (row[i] ?? 0) + (a.charAt(i) === b.charAt(j) ? 0 : 1)),
10
- ]), [j + 1]), indices(a.length + 1))
11
- .at(-1) ?? 0;
12
- /** The known name a key is most likely a typo of, if one is close enough. */
13
- export const closest = (key, known) => {
14
- const nearest = known
15
- .map((name) => ({ name, cost: distance(key, name) }))
16
- .toSorted((x, y) => x.cost - y.cost)
17
- .at(0);
18
- return nearest !== undefined && nearest.cost <= Math.max(2, Math.floor(key.length / 4)) ? nearest.name : undefined;
19
- };
3
+ import { closest } from "../../lib/closest.js";
20
4
  const suggestion = (key, known) => {
21
5
  const name = closest(key, known);
22
6
  return name === undefined ? "" : ` — did you mean '${name}'?`;
@@ -49,8 +33,9 @@ export const checkSettings = (file, values, schema, known) => {
49
33
  };
50
34
  /** The names a kind's vars.yml may set. */
51
35
  export const knownSettings = (kind) => Object.freeze(settings.filter((each) => !each.secret && (kind === undefined || each.kinds.includes(kind))).map((each) => each.name));
52
- /** A YAML document against a schema, for files whose keys are not settings (server.yml, app.yml). */
36
+ /** A YAML document against a schema, for files whose keys are not settings (app.yml): what the schema makes of it. */
37
+ // eslint-disable-next-line functional/prefer-immutable-types -- a Zod schema: immutable once built, but a class the rule cannot see into
53
38
  export const checkShape = (file, values, schema) => {
54
39
  const parsed = schema.safeParse(values);
55
- return parsed.success ? ok(values) : err(firstIssue(file, parsed.error, [], "is not a key it knows"));
40
+ return parsed.success ? ok(parsed.data) : err(firstIssue(file, parsed.error, [], "is not a key it knows"));
56
41
  };
@@ -4,7 +4,7 @@ import { duration } from "../text/time.js";
4
4
  import { parts, position } from "./progress.js";
5
5
  import { count } from "../text/plural.js";
6
6
  import { milliseconds } from "../fleet/brand.js";
7
- import { typed } from "../../typed.js";
7
+ import { typed } from "../../lib/typed.js";
8
8
  /** The heading for a command: as typed, what it runs on, which kayra. */
9
9
  export const heading = (command, target, version) => typed({
10
10
  command,
@@ -4,7 +4,7 @@ import { ask, isStopped } from "./io.js";
4
4
  import { answer, resolve, spawned } from "./process.js";
5
5
  import { meet, scratch } from "./needs.js";
6
6
  import { inPty } from "./pty.js";
7
- import { typed } from "../../typed.js";
7
+ import { typed } from "../../lib/typed.js";
8
8
  /** Lines as printing them one by one gives the text back: newline-ended, as a ctl writes. */
9
9
  const asItCame = (_answer, said) => (said === "" ? typed([]) : said.replace(/\n$/, "").split("\n"));
10
10
  const lines = (text) => Object.freeze(text
@@ -4,7 +4,7 @@ import { join } from "node:path";
4
4
  import { active, muted, strong } from "../text/spans.js";
5
5
  import { ask } from "./io.js";
6
6
  import { spawned } from "./process.js";
7
- import { typed } from "../../typed.js";
7
+ import { typed } from "../../lib/typed.js";
8
8
  const keyOf = (need) => (need.kind === "vault" ? `vault:${need.server}` : "sudo");
9
9
  const questionOf = (need) => typed(need.kind === "vault" ? { kind: "secret", text: [" ", active("?"), " ", strong(`${need.server}'s vault password`), muted(" (asked once, kept for this run): ")] } : { kind: "secret", text: [" ", active("?"), " ", strong("sudo's password"), muted(" (for this step only): ")] });
10
10
  /** Whether sudo would run without a password: a cached one, or none needed. */
@@ -1,9 +1,9 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { text } from "node:stream/consumers";
3
- import { all, err, flatMap, ok } from "../../result.js";
3
+ import { all, err, flatMap, ok } from "../../lib/result.js";
4
4
  import { isStopped } from "./io.js";
5
5
  import { exitCode } from "../fleet/brand.js";
6
- import { typed } from "../../typed.js";
6
+ import { typed } from "../../lib/typed.js";
7
7
  const terminal = {};
8
8
  /** A program that ignores SIGINT this long gets SIGTERM. */
9
9
  const patience = 10_000;
@@ -1,4 +1,4 @@
1
- import { typed } from "../../typed.js";
1
+ import { typed } from "../../lib/typed.js";
2
2
  /** Why a plan stopped before its end. */
3
3
  export const stopReasons = ["failed", "declined", "interrupted"];
4
4
  /** Nothing around the steps: for commands whose output is the point (ssh, logs), and for tests. */
@@ -1,5 +1,5 @@
1
1
  import { quote } from "../plan/describe.js";
2
- import { typed } from "../../typed.js";
2
+ import { typed } from "../../lib/typed.js";
3
3
  /** A step that talks with a person, given a pty: macOS's script, util-linux's elsewhere. */
4
4
  export const inPty = (argv, size) => {
5
5
  const { columns, rows } = size ?? { columns: 120, rows: 32 };
@@ -11,10 +11,10 @@ import { ssh } from "../recipes/ssh.js";
11
11
  import { look } from "../status/look.js";
12
12
  import { findings } from "../validation/findings.js";
13
13
  import { gather } from "../validation/facts.js";
14
- import { all, err, flatMap, map, ok } from "../../result.js";
14
+ import { all, err, flatMap, map, ok } from "../../lib/result.js";
15
15
  import { operations } from "./catalog.js";
16
16
  import { textAt } from "../adapters/fs.js";
17
- import { typed } from "../../typed.js";
17
+ import { typed } from "../../lib/typed.js";
18
18
  import { resolve as substitute, spawned } from "../interpreter/process.js";
19
19
  /** The context for a fleet, with the files read from disk: what every client runs the core with. */
20
20
  export const contextFor = (parts) => {
@@ -1,4 +1,4 @@
1
- import { typed } from "../../typed.js";
1
+ import { typed } from "../../lib/typed.js";
2
2
  /** The kayra commands a longer one is made of, each of which runs its part alone. */
3
3
  export const parts = ["provision", "setup", "apps", "verify", "hosts"];
4
4
  export const run = (title, argv, env = {}) => typed({
@@ -1,11 +1,11 @@
1
- import { appName, within } from "../fleet/brand.js";
2
- import { yamlOf } from "../fleet/parse.js";
1
+ import { within } from "../fleet/brand.js";
2
+ import { yamlOf } from "../../lib/yaml.js";
3
3
  import { run } from "../plan/model.js";
4
- import { err, flatMap, map, mapError } from "../../result.js";
4
+ import { err, flatMap, map, mapError } from "../../lib/result.js";
5
5
  import { appManifestSchema } from "../fleet/settings.js";
6
6
  import { checkShape } from "../fleet/shape.js";
7
7
  import { onPath } from "./steps.js";
8
- import { typed } from "../../typed.js";
8
+ import { typed } from "../../lib/typed.js";
9
9
  const tool = (program, hint) => onPath(`${program} is installed`, program, hint, "stop");
10
10
  /**
11
11
  * In an app's own repository, before a push: what the platform checks when it
@@ -16,10 +16,7 @@ const tool = (program, hint) => onPath(`${program} is installed`, program, hint,
16
16
  export const appCheck = (kayra, root, manifest) => {
17
17
  if (manifest === undefined)
18
18
  return err(`no app.yml in ${root}`);
19
- const shaped = flatMap(flatMap(mapError(yamlOf(manifest), (problem) => `app.yml ${problem}`), (values) => checkShape("app.yml", values, appManifestSchema)), (values) => {
20
- const parsed = appManifestSchema.safeParse(values);
21
- return parsed.success ? appName(parsed.data.name) : err("app.yml: invalid");
22
- });
19
+ const shaped = flatMap(mapError(yamlOf(manifest), (problem) => `app.yml ${problem}`), (values) => checkShape("app.yml", values, appManifestSchema));
23
20
  return map(shaped, () => typed([
24
21
  tool("git", "brew install git"),
25
22
  tool("jq", "brew install jq"),
@@ -1,8 +1,8 @@
1
1
  import { partOf, run } from "../plan/model.js";
2
- import { err, map, ok } from "../../result.js";
2
+ import { err, map, ok } from "../../lib/result.js";
3
3
  import { ansibleEnv, ansiblePath, collections, fromMain, inventory, vault, vaulted } from "./steps.js";
4
4
  import { sshTo } from "./ssh.js";
5
- import { typed } from "../../typed.js";
5
+ import { typed } from "../../lib/typed.js";
6
6
  /** Register every app in server.yml, then remove the rest (their data kept). */
7
7
  export const apps = (engine, server) => {
8
8
  const { env } = vault(server);
@@ -1,6 +1,6 @@
1
1
  import { within } from "../fleet/brand.js";
2
2
  import { run } from "../plan/model.js";
3
- import { err, ok } from "../../result.js";
3
+ import { err, ok } from "../../lib/result.js";
4
4
  import { ansibleEnv, inventory, reachable, vaulted } from "./steps.js";
5
5
  import { sshArgv } from "./ssh.js";
6
6
  /**
@@ -1,4 +1,4 @@
1
- import { ok } from "../../result.js";
1
+ import { ok } from "../../lib/result.js";
2
2
  import { certs } from "./steps.js";
3
3
  /** mkcert certs for a domain and its subdomains, for local dev and multipass. */
4
4
  export const certsFor = (engine, domain, subdomains) => ok([certs(engine, domain, subdomains)]);
@@ -1,6 +1,6 @@
1
1
  import { within } from "../fleet/brand.js";
2
2
  import { homeReach, onPath } from "./steps.js";
3
- import { typed } from "../../typed.js";
3
+ import { typed } from "../../lib/typed.js";
4
4
  const everyServer = () => true;
5
5
  const tools = [
6
6
  { program: "git", install: "brew install git", neededBy: everyServer },
@@ -1,8 +1,8 @@
1
1
  import { partOf, run } from "../plan/model.js";
2
- import { err, map, ok } from "../../result.js";
2
+ import { err, map, ok } from "../../lib/result.js";
3
3
  import { ansibleEnv, ansiblePath, appSubdomains, certs, collections, fleetEnv, fromMain, inventory, latestState, needing, reachable, script, sequence, terraform, vault, vaulted } from "./steps.js";
4
4
  import { apps } from "./apps.js";
5
- import { typed } from "../../typed.js";
5
+ import { typed } from "../../lib/typed.js";
6
6
  export const provision = (engine, server) => ok(partOf("provision", [
7
7
  fromMain(engine, server),
8
8
  ...(server.buildsVm ? [run("VM image and seed ISO", ["bash", script(engine, "home-image.sh"), server.name], fleetEnv(engine))] : []),
@@ -1,6 +1,6 @@
1
1
  import { run } from "../plan/model.js";
2
- import { err, map, ok } from "../../result.js";
3
- import { typed } from "../../typed.js";
2
+ import { err, map, ok } from "../../lib/result.js";
3
+ import { typed } from "../../lib/typed.js";
4
4
  /** ssh to a server as its inventory says, its host key trusted as `hostKeys` say. */
5
5
  export const sshArgv = (inventory, hostKeys, remote) => typed([
6
6
  "ssh",
@@ -1,7 +1,7 @@
1
1
  import { within } from "../fleet/brand.js";
2
2
  import { run } from "../plan/model.js";
3
- import { all, map } from "../../result.js";
4
- import { typed } from "../../typed.js";
3
+ import { all, map } from "../../lib/result.js";
4
+ import { typed } from "../../lib/typed.js";
5
5
  /** The local scripts that read the fleet's files find them here, not beside themselves. */
6
6
  export const fleetEnv = ({ fleet }) => typed({ FLEET_ROOT: fleet });
7
7
  export const script = ({ kayra }, name) => within(kayra, "scripts", "local", name);
@@ -1,6 +1,6 @@
1
1
  import { host, sshDefaultPort, within } from "../fleet/brand.js";
2
2
  import { isMachine } from "./model.js";
3
- import { typed } from "../../typed.js";
3
+ import { typed } from "../../lib/typed.js";
4
4
  /** The inventory names the address: hand-written at home, written by provision elsewhere. */
5
5
  export const listed = (server) => server.inventory === undefined
6
6
  ? undefined
@@ -1,6 +1,6 @@
1
1
  /** What a piece of text means, not how it looks: each client gives it a look (a terminal colour, a CSS class), or none. */
2
2
  export const tones = ["ok", "bad", "warn", "active", "muted", "strong", "accent"];
3
- import { typed } from "../../typed.js";
3
+ import { typed } from "../../lib/typed.js";
4
4
  const toned = (tone) => (text) => typed({ tone, text });
5
5
  export const ok = toned("ok");
6
6
  export const bad = toned("bad");
@@ -2,9 +2,10 @@ import { existsSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import { textAt } from "../adapters/fs.js";
5
- import { fields, isVaulted } from "../fleet/parse.js";
5
+ import { isVaulted } from "../fleet/parse.js";
6
+ import { fields } from "../../lib/yaml.js";
6
7
  import { capture } from "../interpreter/process.js";
7
- import { typed } from "../../typed.js";
8
+ import { typed } from "../../lib/typed.js";
8
9
  /** YAML as validate reads it: what it cannot read holds no values. */
9
10
  const valuesOf = (text) => {
10
11
  const parsed = text === undefined ? undefined : fields(text);
@@ -1,9 +1,9 @@
1
1
  import { appManifestSchema, secretsSchema, settings } from "../fleet/settings.js";
2
- import { closest } from "../fleet/shape.js";
2
+ import { closest } from "../../lib/closest.js";
3
3
  import { count } from "../text/plural.js";
4
- import { mapping as fields } from "../fleet/parse.js";
4
+ import { mapping as fields } from "../../lib/yaml.js";
5
5
  import { subdomain } from "../fleet/brand.js";
6
- import { typed } from "../../typed.js";
6
+ import { typed } from "../../lib/typed.js";
7
7
  /** How a check went: it found a problem, could not look, or holds. */
8
8
  export const verdicts = ["problem", "unchecked", "passed"];
9
9
  const finding = (result, text, hint) => typed({ result, text, ...(hint === undefined ? {} : { hint }) });
@@ -1,7 +1,7 @@
1
- import { typed } from "../typed.js";
1
+ import { typed } from "../lib/typed.js";
2
2
  import { existsSync, readFileSync } from "node:fs";
3
3
  import { join } from "node:path";
4
- import { err, ok } from "../result.js";
4
+ import { err, ok } from "../lib/result.js";
5
5
  import { appName } from "./brand.js";
6
6
  const strings = (value, pattern) => Array.isArray(value) && value.every((item) => typeof item === "string" && pattern.test(item))
7
7
  ? typed(value)
@@ -1,4 +1,4 @@
1
- import { err, ok } from "../result.js";
1
+ import { err, ok } from "../lib/result.js";
2
2
  export const appName = (value) => /^[a-z][a-z0-9-]*$/.test(value) ? ok(value) : err(`'${value}' is not an app name`);
3
3
  export const sha = (value) => /^[0-9a-f]{40}$/.test(value) ? ok(value) : err(`'${value}' is not a full commit id`);
4
4
  export const runId = (value) => /^\d{8}T\d{6}Z-[0-9a-f]{6}$/.test(value) ? ok(value) : err(`'${value}' is not a run id`);
@@ -1,7 +1,7 @@
1
1
  import { existsSync, mkdirSync, readFileSync } from "node:fs";
2
2
  import { createServer } from "node:http";
3
3
  import { join } from "node:path";
4
- import { err, ok } from "../../result.js";
4
+ import { err, ok } from "../../lib/result.js";
5
5
  import { field, registered } from "../app.js";
6
6
  import { owner, runId, sha } from "../brand.js";
7
7
  import { body, json, send } from "../http/http.js";
@@ -9,7 +9,7 @@ import { page, runPage } from "../http/page.js";
9
9
  import { spawnLines } from "../process.js";
10
10
  import { forgeRepo, signed } from "../forges/forge.js";
11
11
  import { pushedRef } from "../http/webhook.js";
12
- import { typed } from "../../typed.js";
12
+ import { typed } from "../../lib/typed.js";
13
13
  const fromFile = (path) => () => (existsSync(path) ? readFileSync(path, "utf8").trim() : "");
14
14
  const settings = (env) => {
15
15
  const platformDir = env["PLATFORM_DIR"] ?? "/opt/platform";
@@ -1,7 +1,7 @@
1
- import { err, ok } from "../../result.js";
1
+ import { err, ok } from "../../lib/result.js";
2
2
  import { field } from "../app.js";
3
3
  import { sha } from "../brand.js";
4
- import { typed } from "../../typed.js";
4
+ import { typed } from "../../lib/typed.js";
5
5
  const relative = (path) => path !== "" && !path.startsWith("/") && !path.split("/").some((segment) => segment === ".." || segment === "");
6
6
  export const parseBundle = (app, expected, json) => {
7
7
  if (typeof json !== "object" || json === null)
@@ -1,4 +1,4 @@
1
- import { typed } from "../../typed.js";
1
+ import { typed } from "../../lib/typed.js";
2
2
  /**
3
3
  * The app's compose project, run in the run's directory: its .env from the
4
4
  * platform (operator config), the image refs from this run, the compose files
@@ -1,4 +1,4 @@
1
- import { all, err, map, ok } from "../result.js";
1
+ import { all, err, map, ok } from "../lib/result.js";
2
2
  const range = (from, to, step) => Object.freeze(Array.from({ length: Math.floor((to - from) / step) + 1 }, (_, i) => from + i * step));
3
3
  const part = (text, min, max) => {
4
4
  const match = /^(\*|(\d+)(?:-(\d+))?)(?:\/(\d+))?$/.exec(text);
@@ -1,4 +1,4 @@
1
- import { typed } from "../../typed.js";
1
+ import { typed } from "../../lib/typed.js";
2
2
  /** A release record's compact UTC time, 20261018T101500Z, as ISO 8601. */
3
3
  const iso = (compact) => compact.replace(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/, "$1-$2-$3T$4:$5:$6Z");
4
4
  const deployed = (release) => typed({ sha: release.sha, time: iso(release.time) });
@@ -5,20 +5,20 @@ import { tmpdir } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
6
  import { createInterface } from "node:readline";
7
7
  import { Readable } from "node:stream";
8
- import { all, err, ok } from "../result.js";
8
+ import { all, err, ok } from "../lib/result.js";
9
9
  import { field, registered } from "./app.js";
10
- import { appName, appOwner, jobOwner, newRunId, sha } from "./brand.js";
10
+ import { appName, appOwner, newRunId, sha } from "./brand.js";
11
11
  import { matches, parseCron } from "./cron.js";
12
12
  import { forge, forgeRepo } from "./forges/forge.js";
13
13
  import { json, send } from "./http/http.js";
14
14
  import { spawnLines } from "./process.js";
15
- import { empty, enqueue, finish } from "./runs/queue.js";
15
+ import { describe, empty, enqueue, finish, jobRequest } from "./runs/queue.js";
16
16
  import { expired, moved, releaseName, releases } from "./runs/records.js";
17
17
  import { githubIssues } from "./forges/issues.js";
18
18
  import { decide, parseNotify, silent } from "./forges/notify.js";
19
19
  import { deploy, renovate } from "./runs/run.js";
20
20
  import { runsOf } from "./runs/store.js";
21
- import { typed } from "../typed.js";
21
+ import { typed } from "../lib/typed.js";
22
22
  const token = (name) => {
23
23
  const path = `/run/platform-secrets/${name}`;
24
24
  return existsSync(path) ? readFileSync(path, "utf8").trim() : "";
@@ -172,9 +172,6 @@ const effects = (s, who, id, log) => typed({
172
172
  log(`(commit status ${context} not posted: ${posted.error})`);
173
173
  },
174
174
  });
175
- const describe = (request) => request.work.kind === "deploy"
176
- ? typed({ what: `deploy ${request.work.ref}`, why: request.work.why })
177
- : typed({ what: `${request.work.job}${request.work.dryRun ? " (dry run)" : ""}`, why: "schedule" });
178
175
  const work = async (s, request, fx) => {
179
176
  if (request.work.kind === "deploy") {
180
177
  const app = registered(s.platformDir, request.work.app);
@@ -238,7 +235,6 @@ const deployRequest = (app, ref, why) => typed({
238
235
  owner: appOwner(app.name),
239
236
  work: { kind: "deploy", app: app.name, ref, why },
240
237
  });
241
- const jobRequest = (job, dryRun) => typed({ owner: jobOwner(job), work: { kind: "job", job, dryRun } });
242
238
  /** The webhook's fallback: an app whose ref moved to a commit no run has tried yet and no release runs (one migrated from Jenkins has releases but no runs). */
243
239
  const poll = async (s) => {
244
240
  await Promise.all(registeredApps(s).map(async (app) => {
@@ -254,9 +250,9 @@ const tick = (s, at) => {
254
250
  if (matches(s.poll, at))
255
251
  void poll(s);
256
252
  if (matches(s.gc, at))
257
- swap(s, (queue) => enqueue(queue, jobRequest("gc", false)));
253
+ swap(s, (queue) => enqueue(queue, jobRequest("gc", false, "schedule")));
258
254
  if (s.renovate !== undefined && matches(s.renovate, at))
259
- swap(s, (queue) => enqueue(queue, jobRequest("renovate", false)));
255
+ swap(s, (queue) => enqueue(queue, jobRequest("renovate", false, "schedule")));
260
256
  };
261
257
  const schedule = (s) => {
262
258
  const wait = 60_000 - (Date.now() % 60_000) + 500;
@@ -301,7 +297,7 @@ const control = async (s, request, response) => {
301
297
  send(response, 409, "this server has no renovate_repositories\n");
302
298
  return;
303
299
  }
304
- accept(s, response, jobRequest(job, field(input, "dryRun") === true));
300
+ accept(s, response, jobRequest(job, field(input, "dryRun") === true, "manual"));
305
301
  return;
306
302
  }
307
303
  send(response, 404, "not found\n");
@@ -1,7 +1,7 @@
1
1
  import { forgejo } from "./forgejo.js";
2
2
  import { github } from "./github.js";
3
3
  import { gitlab } from "./gitlab.js";
4
- import { typed } from "../../typed.js";
4
+ import { typed } from "../../lib/typed.js";
5
5
  const adapters = { github, forgejo, gitlab };
6
6
  const kinds = { "https://github.com": "github", "https://gitlab.com": "gitlab" };
7
7
  /** GitHub for https://github.com, GitLab for https://gitlab.com, a Forgejo for any other host; undefined for a URL none understands. */
@@ -1,4 +1,4 @@
1
- import { err, ok } from "../../result.js";
1
+ import { err, ok } from "../../lib/result.js";
2
2
  import { header, hmacMatches } from "../http/webhook.js";
3
3
  /** A Forgejo's API (Gitea's statuses endpoint); webhooks signed `X-Forgejo-Signature: <hex>` (or Gitea's, or GitHub's, which it sends too). */
4
4
  export const forgejo = {
@@ -1,4 +1,4 @@
1
- import { err, ok } from "../../result.js";
1
+ import { err, ok } from "../../lib/result.js";
2
2
  import { header, hmacMatches } from "../http/webhook.js";
3
3
  /** GitHub's REST API; webhooks signed `X-Hub-Signature-256: sha256=<hex>`. */
4
4
  export const github = {
@@ -1,4 +1,4 @@
1
- import { err, ok } from "../../result.js";
1
+ import { err, ok } from "../../lib/result.js";
2
2
  import { header, secretMatches } from "../http/webhook.js";
3
3
  /** GitLab knows no "failure" or "error", only "failed". */
4
4
  const states = { pending: "pending", success: "success", failure: "failed", error: "failed" };
@@ -1,7 +1,7 @@
1
1
  import { createSign } from "node:crypto";
2
- import { err, ok } from "../../result.js";
2
+ import { err, ok } from "../../lib/result.js";
3
3
  import { field } from "../app.js";
4
- import { typed } from "../../typed.js";
4
+ import { typed } from "../../lib/typed.js";
5
5
  const base64url = (data) => Buffer.from(data).toString("base64url");
6
6
  /** The app's own token: a JWT signed with its private key, valid nine minutes. */
7
7
  export const appJwt = (appId, privateKey, nowSeconds) => {
@@ -1,6 +1,6 @@
1
- import { err, ok } from "../../result.js";
1
+ import { err, ok } from "../../lib/result.js";
2
2
  import { field } from "../app.js";
3
- import { typed } from "../../typed.js";
3
+ import { typed } from "../../lib/typed.js";
4
4
  export const silent = {
5
5
  raise: () => Promise.resolve(ok(undefined)),
6
6
  resolve: () => Promise.resolve(ok(undefined)),
@@ -1,4 +1,11 @@
1
- import { typed } from "../../typed.js";
1
+ import { jobOwner } from "../brand.js";
2
+ import { typed } from "../../lib/typed.js";
3
+ export const jobRequest = (job, dryRun, why) => typed({ owner: jobOwner(job), work: { kind: "job", job, dryRun, why } });
4
+ /** A run's meta.json `what` and `why`. */
5
+ export const describe = (request) => Object.freeze({
6
+ what: request.work.kind === "deploy" ? `deploy ${request.work.ref}` : `${request.work.job}${request.work.dryRun ? " (dry run)" : ""}`,
7
+ why: request.work.why,
8
+ });
2
9
  export const empty = (limit) => typed({ running: [], waiting: [], limit });
3
10
  const exclusive = (request) => request.work.kind === "job" && request.work.job === "gc";
4
11
  /** Starts what may start, in order; a waiting exclusive request holds back everything behind it. */
@@ -1,6 +1,6 @@
1
1
  import { runId, sha } from "../brand.js";
2
2
  import { field } from "../app.js";
3
- import { typed } from "../../typed.js";
3
+ import { typed } from "../../lib/typed.js";
4
4
  /** A release record's name: releases/<app>/<UTC time>-<sha>.env. registry-gc.sh reads the same files. */
5
5
  export const releaseName = (at, commit) => `${at.toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z")}-${commit}.env`;
6
6
  /** Newest first, one per commit: the first is what runs now, the rest are what rollback offers. */
@@ -1,7 +1,7 @@
1
- import { err, ok } from "../../result.js";
1
+ import { err, ok } from "../../lib/result.js";
2
2
  import { imagesEnv, parseBundle } from "../build/bundle.js";
3
3
  import { config, policy, up } from "../build/compose.js";
4
- import { typed } from "../../typed.js";
4
+ import { typed } from "../../lib/typed.js";
5
5
  const step = async (fx, label, argv, options) => {
6
6
  fx.log(`── ${label}`);
7
7
  const exit = await fx.exec(argv, options);
@@ -2,7 +2,7 @@ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { owner as mintOwner, runId } from "../brand.js";
4
4
  import { parseMeta } from "./records.js";
5
- import { typed } from "../../typed.js";
5
+ import { typed } from "../../lib/typed.js";
6
6
  /** Reading runs/: <owner>/<id>/{meta.json,log}. Only the deployer writes there. */
7
7
  const entries = (dir) => (existsSync(dir) ? readdirSync(dir).toSorted() : typed([]));
8
8
  export const owners = (runs) => Object.freeze(entries(runs).flatMap((name) => {
@@ -0,0 +1,2 @@
1
+ /** For a schema's `.transform`: what passed it, branded B. The one place a brand is minted without a check of its own. */
2
+ export const branded = () => (value) => value;
@@ -0,0 +1,17 @@
1
+ import { typed } from "./typed.js";
2
+ /** Edit distance, for "did you mean". */
3
+ const indices = (length) => typed([...Array(length).keys()]);
4
+ const distance = (a, b) => indices(b.length)
5
+ .reduce((row, j) => indices(a.length).reduce((next, i) => Object.freeze([
6
+ ...next,
7
+ Math.min((row[i + 1] ?? 0) + 1, (next[i] ?? 0) + 1, (row[i] ?? 0) + (a.charAt(i) === b.charAt(j) ? 0 : 1)),
8
+ ]), [j + 1]), indices(a.length + 1))
9
+ .at(-1) ?? 0;
10
+ /** The known name a key is most likely a typo of, if one is close enough. */
11
+ export const closest = (key, known) => {
12
+ const nearest = known
13
+ .map((name) => ({ name, cost: distance(key, name) }))
14
+ .toSorted((x, y) => x.cost - y.cost)
15
+ .at(0);
16
+ return nearest !== undefined && nearest.cost <= Math.max(2, Math.floor(key.length / 4)) ? nearest.name : undefined;
17
+ };
@@ -0,0 +1,7 @@
1
+ import { err, ok } from "./result.js";
2
+ /** A schema as a constructor: its value, or the first problem it found. */
3
+ // eslint-disable-next-line functional/prefer-immutable-types -- a Zod schema: immutable once built, but a class the rule cannot see into
4
+ export const minting = (schema) => (value) => {
5
+ const parsed = schema.safeParse(value);
6
+ return parsed.success ? ok(parsed.data) : err(parsed.error.issues.at(0)?.message ?? "is invalid");
7
+ };