clinkx 1.3.0 → 1.4.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 (123) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +13 -6
  3. package/clinkx-workflows/dist/child-env.d.ts +3 -0
  4. package/clinkx-workflows/dist/child-env.js +11 -0
  5. package/clinkx-workflows/dist/child-env.js.map +1 -1
  6. package/clinkx-workflows/dist/dashboard/api-routes.d.ts +21 -0
  7. package/clinkx-workflows/dist/dashboard/api-routes.js +27 -0
  8. package/clinkx-workflows/dist/dashboard/api-routes.js.map +1 -1
  9. package/clinkx-workflows/dist/dashboard/auth/challenge-store.d.ts +13 -0
  10. package/clinkx-workflows/dist/dashboard/auth/challenge-store.js.map +1 -1
  11. package/clinkx-workflows/dist/dashboard/auth/controller.d.ts +27 -0
  12. package/clinkx-workflows/dist/dashboard/auth/controller.js +262 -23
  13. package/clinkx-workflows/dist/dashboard/auth/controller.js.map +1 -1
  14. package/clinkx-workflows/dist/dashboard/auth/settings-step-up.d.ts +62 -0
  15. package/clinkx-workflows/dist/dashboard/auth/settings-step-up.js +70 -0
  16. package/clinkx-workflows/dist/dashboard/auth/settings-step-up.js.map +1 -0
  17. package/clinkx-workflows/dist/dashboard/request-admission.d.ts +6 -0
  18. package/clinkx-workflows/dist/dashboard/request-admission.js +9 -0
  19. package/clinkx-workflows/dist/dashboard/request-admission.js.map +1 -1
  20. package/clinkx-workflows/dist/dashboard/server-factory.js +15 -1
  21. package/clinkx-workflows/dist/dashboard/server-factory.js.map +1 -1
  22. package/clinkx-workflows/dist/dashboard/settings-contract.d.ts +1806 -0
  23. package/clinkx-workflows/dist/dashboard/settings-contract.js +630 -0
  24. package/clinkx-workflows/dist/dashboard/settings-contract.js.map +1 -0
  25. package/clinkx-workflows/dist/dashboard/settings-process-reader.d.ts +48 -0
  26. package/clinkx-workflows/dist/dashboard/settings-process-reader.js +195 -0
  27. package/clinkx-workflows/dist/dashboard/settings-process-reader.js.map +1 -0
  28. package/clinkx-workflows/dist/dashboard/settings-routes.d.ts +87 -0
  29. package/clinkx-workflows/dist/dashboard/settings-routes.js +690 -0
  30. package/clinkx-workflows/dist/dashboard/settings-routes.js.map +1 -0
  31. package/clinkx-workflows/dist/dashboard-ui/assets/index-DSOtuS0p.js +122 -0
  32. package/clinkx-workflows/dist/dashboard-ui/assets/style-C5guUjwN.css +1 -0
  33. package/clinkx-workflows/dist/dashboard-ui/index.html +2 -2
  34. package/clinkx-workflows/dist/durable-file-core.d.ts +76 -0
  35. package/clinkx-workflows/dist/durable-file-core.js +146 -0
  36. package/clinkx-workflows/dist/durable-file-core.js.map +1 -0
  37. package/clinkx-workflows/dist/durable-file.d.ts +8 -64
  38. package/clinkx-workflows/dist/durable-file.js +14 -137
  39. package/clinkx-workflows/dist/durable-file.js.map +1 -1
  40. package/clinkx-workflows/dist/index.js +68 -2
  41. package/clinkx-workflows/dist/index.js.map +1 -1
  42. package/clinkx-workflows/dist/settings/audit.d.ts +101 -0
  43. package/clinkx-workflows/dist/settings/audit.js +318 -0
  44. package/clinkx-workflows/dist/settings/audit.js.map +1 -0
  45. package/clinkx-workflows/dist/settings/bootstrap.d.ts +35 -0
  46. package/clinkx-workflows/dist/settings/bootstrap.js +52 -0
  47. package/clinkx-workflows/dist/settings/bootstrap.js.map +1 -0
  48. package/clinkx-workflows/dist/settings/codec.d.ts +51 -0
  49. package/clinkx-workflows/dist/settings/codec.js +410 -0
  50. package/clinkx-workflows/dist/settings/codec.js.map +1 -0
  51. package/clinkx-workflows/dist/settings/durable-write.d.ts +48 -0
  52. package/clinkx-workflows/dist/settings/durable-write.js +31 -0
  53. package/clinkx-workflows/dist/settings/durable-write.js.map +1 -0
  54. package/clinkx-workflows/dist/settings/index.d.ts +20 -0
  55. package/clinkx-workflows/dist/settings/index.js +23 -0
  56. package/clinkx-workflows/dist/settings/index.js.map +1 -0
  57. package/clinkx-workflows/dist/settings/loader.d.ts +80 -0
  58. package/clinkx-workflows/dist/settings/loader.js +577 -0
  59. package/clinkx-workflows/dist/settings/loader.js.map +1 -0
  60. package/clinkx-workflows/dist/settings/lock.d.ts +108 -0
  61. package/clinkx-workflows/dist/settings/lock.js +344 -0
  62. package/clinkx-workflows/dist/settings/lock.js.map +1 -0
  63. package/clinkx-workflows/dist/settings/paths.d.ts +65 -0
  64. package/clinkx-workflows/dist/settings/paths.js +173 -0
  65. package/clinkx-workflows/dist/settings/paths.js.map +1 -0
  66. package/clinkx-workflows/dist/settings/process-heartbeat.d.ts +47 -0
  67. package/clinkx-workflows/dist/settings/process-heartbeat.js +305 -0
  68. package/clinkx-workflows/dist/settings/process-heartbeat.js.map +1 -0
  69. package/clinkx-workflows/dist/settings/registry.d.ts +178 -0
  70. package/clinkx-workflows/dist/settings/registry.js +1285 -0
  71. package/clinkx-workflows/dist/settings/registry.js.map +1 -0
  72. package/clinkx-workflows/dist/settings/schema.d.ts +404 -0
  73. package/clinkx-workflows/dist/settings/schema.js +415 -0
  74. package/clinkx-workflows/dist/settings/schema.js.map +1 -0
  75. package/clinkx-workflows/dist/settings/store.d.ts +157 -0
  76. package/clinkx-workflows/dist/settings/store.js +842 -0
  77. package/clinkx-workflows/dist/settings/store.js.map +1 -0
  78. package/clinkx-workflows/dist/stdio-entry.d.ts +2 -0
  79. package/clinkx-workflows/dist/stdio-entry.js +52 -0
  80. package/clinkx-workflows/dist/stdio-entry.js.map +1 -0
  81. package/dist/dashboard-cli.js +50 -1
  82. package/dist/dashboard-cli.js.map +1 -1
  83. package/dist/dashboard-companion/protocol.js +17 -0
  84. package/dist/dashboard-companion/protocol.js.map +1 -1
  85. package/dist/dashboard-gateway/control-plane/contracts.d.ts +38 -38
  86. package/dist/dashboard-gateway/tunnel-http.js +20 -0
  87. package/dist/dashboard-gateway/tunnel-http.js.map +1 -1
  88. package/dist/elaris/config.d.ts +10 -0
  89. package/dist/elaris/config.js +27 -1
  90. package/dist/elaris/config.js.map +1 -1
  91. package/dist/elaris/tools.js +4 -1
  92. package/dist/elaris/tools.js.map +1 -1
  93. package/dist/index.d.ts +0 -31
  94. package/dist/index.js +41 -404
  95. package/dist/index.js.map +1 -1
  96. package/dist/lib.d.ts +17 -0
  97. package/dist/lib.js +17 -0
  98. package/dist/lib.js.map +1 -0
  99. package/dist/progress-report/lock.d.ts +17 -59
  100. package/dist/progress-report/lock.js +25 -329
  101. package/dist/progress-report/lock.js.map +1 -1
  102. package/dist/server.js +75 -4
  103. package/dist/server.js.map +1 -1
  104. package/dist/settings-cli/clients.d.ts +137 -0
  105. package/dist/settings-cli/clients.js +1124 -0
  106. package/dist/settings-cli/clients.js.map +1 -0
  107. package/dist/settings-cli/commands.d.ts +67 -0
  108. package/dist/settings-cli/commands.js +726 -0
  109. package/dist/settings-cli/commands.js.map +1 -0
  110. package/dist/settings-cli/format.d.ts +34 -0
  111. package/dist/settings-cli/format.js +40 -0
  112. package/dist/settings-cli/format.js.map +1 -0
  113. package/dist/settings-cli/main.d.ts +18 -0
  114. package/dist/settings-cli/main.js +256 -0
  115. package/dist/settings-cli/main.js.map +1 -0
  116. package/dist/stdio-main.d.ts +73 -0
  117. package/dist/stdio-main.js +455 -0
  118. package/dist/stdio-main.js.map +1 -0
  119. package/docs/configuration.md +340 -39
  120. package/docs/security.md +150 -6
  121. package/package.json +2 -2
  122. package/clinkx-workflows/dist/dashboard-ui/assets/index-DRId2DVA.js +0 -119
  123. package/clinkx-workflows/dist/dashboard-ui/assets/style-CHAw57y5.css +0 -1
@@ -0,0 +1,726 @@
1
+ /**
2
+ * `clinkx settings` command implementations (A3-1).
3
+ *
4
+ * Rules encoded here:
5
+ * - Writes go through the B1-2 SettingsStore under its lock with
6
+ * actor "cli" and auth "local-fs" (TASKS amendment 5); every save is audited
7
+ * by the store. The CLI may write every class, including policy.
8
+ * - Secret values are only ever accepted from stdin (`secret set`), are never
9
+ * written to stdout/stderr, and are never logged.
10
+ * - Exit codes: 0 ok, 2 usage/validation (the registry message), 1 runtime,
11
+ * 3 published-uncertain, 130 the secret prompt was interrupted (C6).
12
+ * - No import may reach the MCP runtime graph: only the settings modules and
13
+ * the dashboard process reader (which itself imports settings only).
14
+ */
15
+ import { chmod, mkdir } from "node:fs/promises";
16
+ import { createInterface } from "node:readline";
17
+ import { Writable } from "node:stream";
18
+ import { SETTINGS_OFF_ENV, classifySettingsEnvName, getSecretSettingKeys, getSettingDescriptor, isSecretSettingKey, } from "../../clinkx-workflows/dist/settings/registry.js";
19
+ import { validateSettingValue } from "../../clinkx-workflows/dist/settings/codec.js";
20
+ import { defaultSettingsDirFor, processesDirPath, resolveSettingsDir, } from "../../clinkx-workflows/dist/settings/paths.js";
21
+ import { SETTINGS_DIR_MODE, SettingsStoreError, } from "../../clinkx-workflows/dist/settings/store.js";
22
+ import { runStartupSettingsLoad } from "../../clinkx-workflows/dist/settings/loader.js";
23
+ import { createSettingsProcessReader } from "../../clinkx-workflows/dist/dashboard/settings-process-reader.js";
24
+ import { EXIT_FAILURE, EXIT_OK, EXIT_SIGINT, EXIT_UNCERTAIN, EXIT_USAGE, SECRET_SET, SECRET_UNSET, line, } from "./format.js";
25
+ /**
26
+ * L7: rendered instead of the value when a non-secret registry key is the
27
+ * target of the CLINKX_ELARIS_API_KEY_ENV indirection — its value is the
28
+ * Elaris credential and is never printed, nor replaced by the registry
29
+ * default (which would misreport the effective value).
30
+ */
31
+ const WITHHELD_CREDENTIAL_EFFECTIVE = "<withheld: credential-indirection target of CLINKX_ELARIS_API_KEY_ENV>";
32
+ // ---------------------------------------------------------------------------
33
+ // Shared helpers
34
+ // ---------------------------------------------------------------------------
35
+ function resolveDir(env) {
36
+ return resolveSettingsDir({ env });
37
+ }
38
+ function isOff(env) {
39
+ return env[SETTINGS_OFF_ENV] === "off";
40
+ }
41
+ function describeStoreError(error, io) {
42
+ if (error instanceof SettingsStoreError) {
43
+ io.err(line(`clinkx settings: ${error.message}`));
44
+ return error.code === "settings_invalid" ? EXIT_USAGE : EXIT_FAILURE;
45
+ }
46
+ io.err(line(`clinkx settings: failed: ${error instanceof Error ? error.message : String(error)}`));
47
+ return EXIT_FAILURE;
48
+ }
49
+ /** Read the settings document, exiting (by return code) on unusable states. */
50
+ function requireReadableDocument(read, io) {
51
+ if (read.state === "unreadable") {
52
+ io.err(line(`clinkx settings: the settings document is unreadable (${read.reason ?? "unknown reason"}); ` +
53
+ `a routine save refuses to overwrite it — run \`clinkx settings recover\` (it prints the digest to bind) ` +
54
+ `or fix/remove the file manually (digest ${read.digest.slice(0, 16)}…)`));
55
+ return { failed: EXIT_FAILURE };
56
+ }
57
+ return { revision: read.revision };
58
+ }
59
+ /**
60
+ * The one mutation-outcome report shared by every CLI write path (set, unset,
61
+ * secret, import). `published_uncertain` is a third outcome with its own text
62
+ * and exit code (3): the bytes are live on disk, but the store could not
63
+ * confirm the audit/durability step — neither success nor a clean failure.
64
+ */
65
+ export function reportMutation(io, result, successLine) {
66
+ io.out(line(successLine));
67
+ if (result.outcome === "published_uncertain") {
68
+ io.err(line("clinkx settings: published but durability is uncertain — the change is live on disk, " +
69
+ "but the store could not confirm its audit entry; run `clinkx settings validate` " +
70
+ "and re-read the document before trusting it"));
71
+ return EXIT_UNCERTAIN;
72
+ }
73
+ if (result.outcome !== "ok") {
74
+ io.err(line(`clinkx settings: unexpected save outcome: ${result.outcome}`));
75
+ return EXIT_FAILURE;
76
+ }
77
+ return EXIT_OK;
78
+ }
79
+ /** Values encoded in the consumer's legacy env spelling (never used for secrets). */
80
+ export function encodeForDisplay(descriptor, value) {
81
+ // encodeSettingValue throws only on a type mismatch the store already
82
+ // rejected; the store only returns registry-valid values.
83
+ if (descriptor.type === "bool" && typeof value === "boolean")
84
+ return value ? "true" : "false";
85
+ if (descriptor.type === "int" && typeof value === "number")
86
+ return String(value);
87
+ if (descriptor.type === "list" && Array.isArray(value))
88
+ return value.join(",");
89
+ if (typeof value === "string")
90
+ return value;
91
+ return String(value);
92
+ }
93
+ /**
94
+ * Strict argv-value parsing for `set`. Deliberately stricter than the
95
+ * consumer env grammar (which silently falls back to defaults): a CLI user
96
+ * typing an explicit value must get an error, not a silently stored default.
97
+ * The store's registry validation remains the authoritative second gate.
98
+ */
99
+ export function parseStrictArgvValue(descriptor, raw) {
100
+ switch (descriptor.type) {
101
+ case "bool":
102
+ if (raw === "true")
103
+ return { ok: true, value: true };
104
+ if (raw === "false")
105
+ return { ok: true, value: false };
106
+ return { ok: false, error: `${descriptor.key}: must be exactly "true" or "false"` };
107
+ case "int": {
108
+ const allowsDecimal = descriptor.grammar === "idle_timeout_seconds";
109
+ const pattern = allowsDecimal ? /^[0-9]+(?:\.[0-9]+)?$/ : /^[+-]?[0-9]+$/;
110
+ if (!pattern.test(raw)) {
111
+ return {
112
+ ok: false,
113
+ error: allowsDecimal
114
+ ? `${descriptor.key}: must be a non-negative number of seconds`
115
+ : `${descriptor.key}: must be an integer`,
116
+ };
117
+ }
118
+ return { ok: true, value: Number(raw) };
119
+ }
120
+ case "enum":
121
+ case "string":
122
+ case "url":
123
+ return { ok: true, value: raw };
124
+ case "list": {
125
+ if (raw === "") {
126
+ return { ok: false, error: `${descriptor.key}: to clear a list key use \`clinkx settings unset ${descriptor.key}\`` };
127
+ }
128
+ const entries = raw.split(",");
129
+ if (entries.some((entry) => entry === "")) {
130
+ return { ok: false, error: `${descriptor.key}: must not contain empty entries (check for double commas)` };
131
+ }
132
+ return { ok: true, value: entries };
133
+ }
134
+ }
135
+ }
136
+ // ---------------------------------------------------------------------------
137
+ // Commands
138
+ // ---------------------------------------------------------------------------
139
+ export function commandPath(ctx) {
140
+ if (isOff(ctx.env)) {
141
+ ctx.io.err(line("note: CLINKX_SETTINGS=off — servers ignore the settings file entirely"));
142
+ }
143
+ const resolution = resolveDir(ctx.env);
144
+ if (resolution.dir === "") {
145
+ ctx.io.err(line(`clinkx settings: the settings directory is not usable: ${resolution.warning ?? "unresolvable"}`));
146
+ return EXIT_FAILURE;
147
+ }
148
+ ctx.io.out(line(resolution.dir));
149
+ if (resolution.origin === "override") {
150
+ ctx.io.err(line(`source: CLINKX_SETTINGS_DIR override`));
151
+ }
152
+ else {
153
+ const home = ctx.env["HOME"] ?? "";
154
+ ctx.io.err(line(`source: default (${home === "" ? "HOME unset" : defaultSettingsDirFor(home)})`));
155
+ }
156
+ return EXIT_OK;
157
+ }
158
+ export async function commandInit(ctx) {
159
+ const resolution = resolveDir(ctx.env);
160
+ if (resolution.dir === "") {
161
+ ctx.io.err(line(`clinkx settings: the settings directory is not usable: ${resolution.warning ?? "unresolvable"}`));
162
+ return EXIT_FAILURE;
163
+ }
164
+ try {
165
+ await mkdir(resolution.dir, { recursive: true });
166
+ await chmod(resolution.dir, SETTINGS_DIR_MODE);
167
+ }
168
+ catch (error) {
169
+ ctx.io.err(line(`clinkx settings: could not create ${resolution.dir}: ${error instanceof Error ? error.message : String(error)}`));
170
+ return EXIT_FAILURE;
171
+ }
172
+ ctx.io.out(line(`initialized ${resolution.dir} (mode 0700)`));
173
+ return EXIT_OK;
174
+ }
175
+ export async function commandShow(ctx, effective) {
176
+ const resolution = resolveDir(ctx.env);
177
+ if (resolution.dir === "") {
178
+ ctx.io.err(line(`clinkx settings: the settings directory is not usable: ${resolution.warning ?? "unresolvable"}`));
179
+ return EXIT_FAILURE;
180
+ }
181
+ if (effective) {
182
+ return showEffective(ctx, resolution.dir);
183
+ }
184
+ const store = ctx.createStore(resolution.dir);
185
+ let read;
186
+ let secrets;
187
+ try {
188
+ read = await store.read();
189
+ secrets = await store.secretStatus();
190
+ }
191
+ catch (error) {
192
+ return describeStoreError(error, ctx.io);
193
+ }
194
+ if (read.state === "unreadable") {
195
+ ctx.io.err(line(`clinkx settings: the settings document is unreadable (${read.reason ?? "unknown reason"}); ` +
196
+ `digest ${read.digest.slice(0, 16)}… — treat as absent by servers; run \`clinkx settings recover\` or fix/remove the file`));
197
+ return EXIT_FAILURE;
198
+ }
199
+ if (read.state === "absent") {
200
+ ctx.io.out(line(`no settings document (${resolution.dir}/settings.json)`));
201
+ }
202
+ else {
203
+ const by = read.updatedBy == null ? "" : `, updated by ${read.updatedBy.actor}/${read.updatedBy.auth}`;
204
+ ctx.io.out(line(`settings: revision ${String(read.revision)}, updated ${read.updatedAt ?? "-"}${by}`));
205
+ for (const [key, value] of Object.entries(read.values)) {
206
+ const descriptor = getSettingDescriptor(key);
207
+ if (descriptor == null)
208
+ continue; // unknown keys cannot be in a present document
209
+ ctx.io.out(line(`${key} = ${encodeForDisplay(descriptor, value)}`));
210
+ }
211
+ }
212
+ if (read.externalEdit) {
213
+ ctx.io.err(line("warning: the settings document changed outside the store (external edit detected)"));
214
+ }
215
+ if (secrets.state === "unreadable") {
216
+ ctx.io.err(line(`clinkx settings: the secrets document is unreadable (${secrets.reason ?? "unknown reason"}); secret saves will require an explicit recover`));
217
+ }
218
+ else if (secrets.state === "present") {
219
+ ctx.io.out(line(`secrets: revision ${String(secrets.revision)}`));
220
+ // Every secret-class registry key is reported as set/unset; values never.
221
+ for (const key of getSecretSettingKeys()) {
222
+ const entry = secrets.entries[key];
223
+ ctx.io.out(line(`${key} = ${entry?.set === true ? SECRET_SET : SECRET_UNSET}`));
224
+ }
225
+ }
226
+ for (const warning of secrets.warnings) {
227
+ ctx.io.err(line(`warning: ${warning}`));
228
+ }
229
+ return EXIT_OK;
230
+ }
231
+ function showEffective(ctx, dir) {
232
+ if (isOff(ctx.env)) {
233
+ ctx.io.out(line("state: off (CLINKX_SETTINGS=off — the settings file is ignored)"));
234
+ }
235
+ // The loader mutates its env argument; pass a copy so this CLI process env
236
+ // is untouched. The same copy is the presence snapshot (this process's env
237
+ // IS the explicit-env tier).
238
+ const envCopy = { ...ctx.env };
239
+ const application = runStartupSettingsLoad(envCopy, { envSnapshot: envCopy });
240
+ if (!isOff(ctx.env)) {
241
+ ctx.io.out(line(`state: ${application.state}` +
242
+ (application.revision === undefined ? "" : `, revision ${String(application.revision)}`) +
243
+ (application.settingsDir === "" ? "" : ` (${application.settingsDir})`)));
244
+ }
245
+ for (const warning of application.warnings) {
246
+ ctx.io.err(line(`warning: ${warning}`));
247
+ }
248
+ for (const key of Object.keys(application.perKey)) {
249
+ const provenance = application.perKey[key];
250
+ if (provenance == null)
251
+ continue;
252
+ const descriptor = getSettingDescriptor(key);
253
+ if (descriptor == null)
254
+ continue;
255
+ if (isSecretSettingKey(key)) {
256
+ const state = provenance.source === "default" ? SECRET_UNSET : SECRET_SET;
257
+ ctx.io.out(line(`${key} = ${state} (${provenance.source})`));
258
+ continue;
259
+ }
260
+ if (provenance.withheld === true) {
261
+ ctx.io.out(line(`${key} = ${WITHHELD_CREDENTIAL_EFFECTIVE} (${provenance.source})`));
262
+ continue;
263
+ }
264
+ const value = provenance.effective ?? encodeForDisplay(descriptor, descriptor.default);
265
+ const equalsNote = provenance.envEqualsFile === true ? ", equals file" : "";
266
+ ctx.io.out(line(`${key} = ${value} (${provenance.source}${equalsNote})`));
267
+ }
268
+ for (const name of application.unknownEnvKeys) {
269
+ ctx.io.err(line(`warning: unknown CLINKX_* environment variable in this process: ${name}`));
270
+ }
271
+ if (application.settingsDir === "" && !isOff(ctx.env)) {
272
+ ctx.io.err(line("note: no settings directory is in use; only env and built-in defaults apply"));
273
+ }
274
+ return EXIT_OK;
275
+ }
276
+ export async function commandValidate(ctx) {
277
+ const resolution = resolveDir(ctx.env);
278
+ if (resolution.dir === "") {
279
+ ctx.io.err(line(`clinkx settings: the settings directory is not usable: ${resolution.warning ?? "unresolvable"}`));
280
+ return EXIT_FAILURE;
281
+ }
282
+ const store = ctx.createStore(resolution.dir);
283
+ let read;
284
+ let secrets;
285
+ try {
286
+ read = await store.read();
287
+ secrets = await store.secretStatus();
288
+ }
289
+ catch (error) {
290
+ return describeStoreError(error, ctx.io);
291
+ }
292
+ let failed = false;
293
+ if (read.state === "unreadable") {
294
+ ctx.io.err(line(`invalid: settings.json is unreadable: ${read.reason ?? "unknown reason"}`));
295
+ failed = true;
296
+ }
297
+ else if (read.state === "absent") {
298
+ ctx.io.out(line(`ok: no settings document (${resolution.dir}/settings.json)`));
299
+ }
300
+ else {
301
+ ctx.io.out(line(`ok: settings.json revision ${String(read.revision)}, ${String(Object.keys(read.values).length)} key(s)`));
302
+ }
303
+ if (secrets.state === "unreadable") {
304
+ ctx.io.err(line(`invalid: secrets.json is unreadable: ${secrets.reason ?? "unknown reason"}`));
305
+ failed = true;
306
+ }
307
+ else {
308
+ for (const warning of secrets.warnings) {
309
+ ctx.io.err(line(`warning: ${warning}`));
310
+ }
311
+ }
312
+ // File-level semantic checks the store cannot express (invalid values with
313
+ // per-key fallback, cross-key `requires`): run the real loader against a
314
+ // copy of this env with every managed key stripped, so ONLY file values
315
+ // apply — exactly what a server started with a clean environment would see.
316
+ if (!isOff(ctx.env) && resolution.dir !== "" && read.state !== "unreadable") {
317
+ const scrubbed = { ...ctx.env };
318
+ for (const name of Object.keys(scrubbed)) {
319
+ const classification = classifySettingsEnvName(name);
320
+ if (classification == null)
321
+ continue;
322
+ if (classification.kind === "key" || classification.kind === "alias") {
323
+ delete scrubbed[name];
324
+ }
325
+ }
326
+ const application = runStartupSettingsLoad(scrubbed, { envSnapshot: scrubbed });
327
+ for (const warning of application.warnings) {
328
+ ctx.io.err(line(`warning: ${warning}`));
329
+ }
330
+ }
331
+ return failed ? EXIT_USAGE : EXIT_OK;
332
+ }
333
+ export async function commandSet(ctx, key, rawValue) {
334
+ const descriptor = getSettingDescriptor(key);
335
+ if (descriptor == null) {
336
+ ctx.io.err(line(`clinkx settings: unknown settings key ${key} (see \`clinkx settings show --effective\` for the registry keys)`));
337
+ return EXIT_USAGE;
338
+ }
339
+ if (descriptor.class === "secret") {
340
+ ctx.io.err(line(`clinkx settings: ${key} is a secret-class key; use \`clinkx settings secret set ${key}\` (value from stdin)`));
341
+ return EXIT_USAGE;
342
+ }
343
+ const parsed = parseStrictArgvValue(descriptor, rawValue);
344
+ if (!parsed.ok) {
345
+ ctx.io.err(line(`clinkx settings: ${parsed.error}`));
346
+ return EXIT_USAGE;
347
+ }
348
+ const registryError = validateSettingValue(descriptor, parsed.value);
349
+ if (registryError != null) {
350
+ ctx.io.err(line(`clinkx settings: ${registryError}`));
351
+ return EXIT_USAGE;
352
+ }
353
+ const resolution = resolveDir(ctx.env);
354
+ if (resolution.dir === "") {
355
+ ctx.io.err(line(`clinkx settings: the settings directory is not usable: ${resolution.warning ?? "unresolvable"}`));
356
+ return EXIT_FAILURE;
357
+ }
358
+ const store = ctx.createStore(resolution.dir);
359
+ let read;
360
+ try {
361
+ read = await store.read();
362
+ }
363
+ catch (error) {
364
+ return describeStoreError(error, ctx.io);
365
+ }
366
+ const gate = requireReadableDocument(read, ctx.io);
367
+ if ("failed" in gate)
368
+ return gate.failed;
369
+ try {
370
+ const result = await store.save({
371
+ expectedRevision: gate.revision,
372
+ ops: [{ key, action: "set", value: parsed.value }],
373
+ actor: "cli",
374
+ auth: "local-fs",
375
+ });
376
+ return reportMutation(ctx.io, result, `set ${key} = ${encodeForDisplay(descriptor, parsed.value)} (revision ${String(result.revision)})`);
377
+ }
378
+ catch (error) {
379
+ return describeStoreError(error, ctx.io);
380
+ }
381
+ }
382
+ export async function commandUnset(ctx, key) {
383
+ const descriptor = getSettingDescriptor(key);
384
+ if (descriptor == null) {
385
+ ctx.io.err(line(`clinkx settings: unknown settings key ${key}`));
386
+ return EXIT_USAGE;
387
+ }
388
+ if (descriptor.class === "secret") {
389
+ ctx.io.err(line(`clinkx settings: ${key} is a secret-class key; use \`clinkx settings secret unset ${key}\``));
390
+ return EXIT_USAGE;
391
+ }
392
+ const resolution = resolveDir(ctx.env);
393
+ if (resolution.dir === "") {
394
+ ctx.io.err(line(`clinkx settings: the settings directory is not usable: ${resolution.warning ?? "unresolvable"}`));
395
+ return EXIT_FAILURE;
396
+ }
397
+ const store = ctx.createStore(resolution.dir);
398
+ let read;
399
+ try {
400
+ read = await store.read();
401
+ }
402
+ catch (error) {
403
+ return describeStoreError(error, ctx.io);
404
+ }
405
+ const gate = requireReadableDocument(read, ctx.io);
406
+ if ("failed" in gate)
407
+ return gate.failed;
408
+ try {
409
+ const result = await store.save({
410
+ expectedRevision: gate.revision,
411
+ ops: [{ key, action: "unset" }],
412
+ actor: "cli",
413
+ auth: "local-fs",
414
+ });
415
+ return reportMutation(ctx.io, result, `unset ${key} (revision ${String(result.revision)})`);
416
+ }
417
+ catch (error) {
418
+ return describeStoreError(error, ctx.io);
419
+ }
420
+ }
421
+ // ---------------------------------------------------------------------------
422
+ // Secrets
423
+ // ---------------------------------------------------------------------------
424
+ /**
425
+ * The interactive secret prompt was cancelled before a value was provided
426
+ * (C6): stdin closed (exit 2, like the empty-piped-value refusal) or the user
427
+ * pressed Ctrl-C (exit 130, the conventional 128+SIGINT). Nothing was written.
428
+ */
429
+ class SecretPromptCancelledError extends Error {
430
+ exitCode;
431
+ constructor(exitCode) {
432
+ super("secret prompt cancelled before a value was provided");
433
+ this.name = "SecretPromptCancelledError";
434
+ this.exitCode = exitCode;
435
+ }
436
+ }
437
+ /** Best-effort raw-mode restore so a cancelled prompt never leaves the TTY raw. */
438
+ function restoreTerminal(stdin) {
439
+ const tty = stdin;
440
+ if (tty.isTTY === true && typeof tty.setRawMode === "function") {
441
+ try {
442
+ tty.setRawMode(false);
443
+ }
444
+ catch {
445
+ // rl.close() already restored it; nothing further to do.
446
+ }
447
+ }
448
+ }
449
+ /**
450
+ * Read a secret value from stdin. Piped stdin reads to EOF; a TTY prompts
451
+ * once with echo suppressed (the prompt goes to stderr; the value never
452
+ * reaches any output stream). Returns "" when nothing was provided. A TTY
453
+ * prompt cancelled by close/Ctrl-C rejects (C6) — the pending `rl.question`
454
+ * promise alone would never settle, and the process would exit 0 having
455
+ * written nothing, which is indistinguishable from success.
456
+ */
457
+ export async function readSecretFromStdin(stdin, io) {
458
+ const tty = stdin.isTTY === true;
459
+ if (!tty) {
460
+ const chunks = [];
461
+ for await (const chunk of stdin) {
462
+ chunks.push(typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk);
463
+ }
464
+ const raw = Buffer.concat(chunks).toString("utf8");
465
+ return stripSingleTrailingNewline(raw);
466
+ }
467
+ const muted = new Writable({
468
+ write(_chunk, _encoding, callback) {
469
+ callback();
470
+ },
471
+ });
472
+ const rl = createInterface({ input: stdin, output: muted, terminal: true });
473
+ let settled = false;
474
+ try {
475
+ io.err("value: ");
476
+ const answer = await new Promise((resolve, reject) => {
477
+ const cancel = (exitCode, closed) => {
478
+ if (settled)
479
+ return;
480
+ settled = true;
481
+ // The muted prompt left the cursor mid-line; start a fresh line.
482
+ io.err("\n");
483
+ if (closed) {
484
+ io.err(line("clinkx settings: no value was provided; nothing was written"));
485
+ }
486
+ reject(new SecretPromptCancelledError(exitCode));
487
+ };
488
+ rl.on("close", () => cancel(EXIT_USAGE, true));
489
+ rl.on("SIGINT", () => cancel(EXIT_SIGINT, false));
490
+ rl.question("", (value) => {
491
+ if (settled)
492
+ return;
493
+ settled = true;
494
+ resolve(value);
495
+ });
496
+ });
497
+ return answer;
498
+ }
499
+ finally {
500
+ rl.close();
501
+ restoreTerminal(stdin);
502
+ }
503
+ }
504
+ function stripSingleTrailingNewline(raw) {
505
+ if (raw.endsWith("\r\n"))
506
+ return raw.slice(0, -2);
507
+ if (raw.endsWith("\n") || raw.endsWith("\r"))
508
+ return raw.slice(0, -1);
509
+ return raw;
510
+ }
511
+ export async function commandSecretSet(ctx, key) {
512
+ const descriptor = getSettingDescriptor(key);
513
+ if (descriptor == null) {
514
+ ctx.io.err(line(`clinkx settings: unknown settings key ${key}`));
515
+ return EXIT_USAGE;
516
+ }
517
+ if (descriptor.class !== "secret") {
518
+ ctx.io.err(line(`clinkx settings: ${key} is not a secret-class key; use \`clinkx settings set ${key} VALUE\``));
519
+ return EXIT_USAGE;
520
+ }
521
+ let value;
522
+ try {
523
+ value = await readSecretFromStdin(ctx.stdin, ctx.io);
524
+ }
525
+ catch (error) {
526
+ // A cancelled prompt is a deliberate exit (130/2), never a crash; the
527
+ // prompt already printed its newline and wrote nothing.
528
+ if (error instanceof SecretPromptCancelledError)
529
+ return error.exitCode;
530
+ throw error;
531
+ }
532
+ if (value.trim() === "") {
533
+ ctx.io.err(line("clinkx settings: refusing to store an empty secret value (stdin carried no value)"));
534
+ return EXIT_USAGE;
535
+ }
536
+ const resolution = resolveDir(ctx.env);
537
+ if (resolution.dir === "") {
538
+ ctx.io.err(line(`clinkx settings: the settings directory is not usable: ${resolution.warning ?? "unresolvable"}`));
539
+ return EXIT_FAILURE;
540
+ }
541
+ const store = ctx.createStore(resolution.dir);
542
+ try {
543
+ const status = await store.secretStatus();
544
+ if (status.state === "unreadable") {
545
+ ctx.io.err(line(`clinkx settings: the secrets document is unreadable (${status.reason ?? "unknown reason"}); a routine save refuses to overwrite it — run \`clinkx settings recover --secrets\` or fix/remove the file`));
546
+ return EXIT_FAILURE;
547
+ }
548
+ const result = await store.saveSecrets({
549
+ expectedRevision: status.revision,
550
+ ops: [{ key, action: "set", value }],
551
+ actor: "cli",
552
+ auth: "local-fs",
553
+ });
554
+ return reportMutation(ctx.io, result, `secret set ${key} (secrets revision ${String(result.revision)})`);
555
+ }
556
+ catch (error) {
557
+ return describeStoreError(error, ctx.io);
558
+ }
559
+ }
560
+ export async function commandSecretUnset(ctx, key) {
561
+ const descriptor = getSettingDescriptor(key);
562
+ if (descriptor == null) {
563
+ ctx.io.err(line(`clinkx settings: unknown settings key ${key}`));
564
+ return EXIT_USAGE;
565
+ }
566
+ if (descriptor.class !== "secret") {
567
+ ctx.io.err(line(`clinkx settings: ${key} is not a secret-class key; use \`clinkx settings unset ${key}\``));
568
+ return EXIT_USAGE;
569
+ }
570
+ const resolution = resolveDir(ctx.env);
571
+ if (resolution.dir === "") {
572
+ ctx.io.err(line(`clinkx settings: the settings directory is not usable: ${resolution.warning ?? "unresolvable"}`));
573
+ return EXIT_FAILURE;
574
+ }
575
+ const store = ctx.createStore(resolution.dir);
576
+ try {
577
+ const status = await store.secretStatus();
578
+ if (status.state === "unreadable") {
579
+ ctx.io.err(line(`clinkx settings: the secrets document is unreadable (${status.reason ?? "unknown reason"}); a routine save refuses to overwrite it — run \`clinkx settings recover --secrets\` or fix/remove the file`));
580
+ return EXIT_FAILURE;
581
+ }
582
+ const result = await store.saveSecrets({
583
+ expectedRevision: status.revision,
584
+ ops: [{ key, action: "unset" }],
585
+ actor: "cli",
586
+ auth: "local-fs",
587
+ });
588
+ return reportMutation(ctx.io, result, `secret unset ${key} (secrets revision ${String(result.revision)})`);
589
+ }
590
+ catch (error) {
591
+ return describeStoreError(error, ctx.io);
592
+ }
593
+ }
594
+ // ---------------------------------------------------------------------------
595
+ // Recover
596
+ // ---------------------------------------------------------------------------
597
+ /**
598
+ * A vacuous op so a recover save satisfies the store's "at least one op"
599
+ * rule while still writing an EMPTY valid document: the recover branch starts
600
+ * from an empty base, so unsetting a key that is not there changes nothing.
601
+ * The audit line records this key name under action "recover".
602
+ */
603
+ const RECOVER_SETTINGS_OP = { key: "CLINKX_LOG_LEVEL", action: "unset" };
604
+ const RECOVER_SECRETS_OP = { key: "CLINKX_ELARIS_API_KEY", action: "unset" };
605
+ /**
606
+ * `clinkx settings recover [--secrets] [--digest <sha256>]` (R5): the CLI
607
+ * counterpart of the dashboard's step-up-gated recover, shown by the
608
+ * dashboard in bearer/none auth mode. Without `--digest` (settings only) it
609
+ * reports the unreadable state and the digest a recover must bind to, then
610
+ * exits 2. With `--digest` it recovers through the store's recover path,
611
+ * which preserves the corrupt bytes beside the active file before replacing
612
+ * it. `--secrets` recovers the secrets document and needs no digest, because
613
+ * secret documents never expose one.
614
+ */
615
+ export async function commandRecover(ctx, opts) {
616
+ const resolution = resolveDir(ctx.env);
617
+ if (resolution.dir === "") {
618
+ ctx.io.err(line(`clinkx settings: the settings directory is not usable: ${resolution.warning ?? "unresolvable"}`));
619
+ return EXIT_FAILURE;
620
+ }
621
+ const store = ctx.createStore(resolution.dir);
622
+ if (opts.secrets) {
623
+ return recoverSecrets(ctx, store);
624
+ }
625
+ return recoverSettings(ctx, store, opts.digest);
626
+ }
627
+ async function recoverSettings(ctx, store, digest) {
628
+ let read;
629
+ try {
630
+ read = await store.read();
631
+ }
632
+ catch (error) {
633
+ return describeStoreError(error, ctx.io);
634
+ }
635
+ if (read.state !== "unreadable") {
636
+ ctx.io.out(line(read.state === "absent"
637
+ ? "settings.json is absent — nothing to recover"
638
+ : `settings.json is readable (revision ${String(read.revision)}) — nothing to recover`));
639
+ return EXIT_OK;
640
+ }
641
+ if (digest === undefined) {
642
+ ctx.io.err(line(`clinkx settings: settings.json is unreadable: ${read.reason ?? "unknown reason"}`));
643
+ ctx.io.err(line(`digest ${read.digest}`));
644
+ ctx.io.err(line(`recover with: clinkx settings recover --digest ${read.digest}`));
645
+ return EXIT_USAGE;
646
+ }
647
+ try {
648
+ const result = await store.save({
649
+ expectedRevision: 0,
650
+ ops: [RECOVER_SETTINGS_OP],
651
+ actor: "cli",
652
+ auth: "local-fs",
653
+ recover: true,
654
+ expectedDigest: digest,
655
+ });
656
+ return reportMutation(ctx.io, result, `recovered settings.json (revision ${String(result.revision)}); the previous bytes were preserved as settings.json.corrupt-* in the same directory`);
657
+ }
658
+ catch (error) {
659
+ return describeStoreError(error, ctx.io);
660
+ }
661
+ }
662
+ async function recoverSecrets(ctx, store) {
663
+ let status;
664
+ try {
665
+ status = await store.secretStatus();
666
+ }
667
+ catch (error) {
668
+ return describeStoreError(error, ctx.io);
669
+ }
670
+ if (status.state !== "unreadable") {
671
+ ctx.io.out(line(status.state === "absent"
672
+ ? "secrets.json is absent — nothing to recover"
673
+ : `secrets.json is readable (revision ${String(status.revision)}) — nothing to recover`));
674
+ return EXIT_OK;
675
+ }
676
+ try {
677
+ const result = await store.saveSecrets({
678
+ expectedRevision: 0,
679
+ ops: [RECOVER_SECRETS_OP],
680
+ actor: "cli",
681
+ auth: "local-fs",
682
+ recover: true,
683
+ });
684
+ return reportMutation(ctx.io, result, `recovered secrets.json (secrets revision ${String(result.revision)}); the previous bytes were preserved as secrets.json.corrupt-* in the same directory`);
685
+ }
686
+ catch (error) {
687
+ return describeStoreError(error, ctx.io);
688
+ }
689
+ }
690
+ // ---------------------------------------------------------------------------
691
+ // Processes
692
+ // ---------------------------------------------------------------------------
693
+ export async function commandProcesses(ctx) {
694
+ const resolution = resolveDir(ctx.env);
695
+ if (resolution.dir === "") {
696
+ ctx.io.err(line(`clinkx settings: the settings directory is not usable: ${resolution.warning ?? "unresolvable"}`));
697
+ return EXIT_FAILURE;
698
+ }
699
+ const processesDir = processesDirPath(resolution.dir);
700
+ const reader = createSettingsProcessReader();
701
+ let listing;
702
+ try {
703
+ listing = await reader.list(processesDir);
704
+ }
705
+ catch (error) {
706
+ ctx.io.err(line(`clinkx settings: could not read ${processesDir}: ${error instanceof Error ? error.message : String(error)}`));
707
+ return EXIT_FAILURE;
708
+ }
709
+ if (listing.processes.length === 0) {
710
+ ctx.io.out(line(`no process heartbeats (${processesDir})`));
711
+ return EXIT_OK;
712
+ }
713
+ for (const entry of listing.processes) {
714
+ const doc = entry.document;
715
+ const settings = doc.settings.state === "loaded" && doc.settings.revision !== undefined
716
+ ? `loaded@${String(doc.settings.revision)}`
717
+ : doc.settings.state;
718
+ ctx.io.out(line(`pid ${String(doc.pid)} host=${doc.hostname} entry=${doc.entry} version=${doc.version} ` +
719
+ `settings=${settings} liveness=${entry.liveness} heartbeat=${entry.lastSeenAt} started=${doc.started_at}`));
720
+ }
721
+ if (listing.truncated) {
722
+ ctx.io.err(line("warning: the process list was truncated by the scan cap"));
723
+ }
724
+ return EXIT_OK;
725
+ }
726
+ //# sourceMappingURL=commands.js.map