@solidactions/cli 3.20.1 → 3.21.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.
package/dist/index.js CHANGED
@@ -104,12 +104,14 @@ const pkg = require('../package.json');
104
104
  exports.program = new commander_1.Command();
105
105
  if (process.env.SOLIDACTIONS_DEBUG === '1') {
106
106
  // eslint-disable-next-line @typescript-eslint/no-var-requires
107
- const { resolveConfig } = require('./utils/config');
107
+ const { resolveConfig, credentialConflictMessage } = require('./utils/config');
108
108
  const resolved = resolveConfig();
109
109
  if (resolved) {
110
110
  const fmt = (src) => {
111
111
  if (src === 'env')
112
112
  return '(from $SOLIDACTIONS_* env var)';
113
+ if (src === 'default')
114
+ return '(default)';
113
115
  if (src === null)
114
116
  return '(unset)';
115
117
  return `(from ${src})`;
@@ -119,6 +121,9 @@ if (process.env.SOLIDACTIONS_DEBUG === '1') {
119
121
  process.stderr.write(` apiKey: <redacted> ${fmt(resolved.sources.apiKey)}\n`);
120
122
  process.stderr.write(` workspaceId: ${resolved.config.workspaceId ?? ''} ${fmt(resolved.sources.workspaceId)}\n`);
121
123
  process.stderr.write(` activePath: ${resolved.activePath}\n`);
124
+ if (resolved.credentialConflict) {
125
+ process.stderr.write(` credentials: REFUSED — ${credentialConflictMessage(resolved.credentialConflict).split('\n')[0]}\n`);
126
+ }
122
127
  }
123
128
  else {
124
129
  process.stderr.write('[SOLIDACTIONS_DEBUG] no config resolvable\n');
@@ -1045,16 +1050,17 @@ role
1045
1050
  const doc = exports.program.command('doc').description('Manage docs in SA-Docs');
1046
1051
  doc
1047
1052
  .command('push')
1048
- .description('Recursively upload a local markdown tree into SA-Docs')
1049
- .argument('<dir>', 'Path to the directory containing markdown files')
1050
- .option('--on-conflict <mode>', 'Conflict resolution: skip|overwrite|rename (default: skip)', 'skip')
1051
- .option('--type <slug>', 'Doc-type slug to apply to all uploaded docs')
1053
+ .description('Upload docs from local files into SA-Docs: .md as markdown, .html as a visual doc, .canvas.json / .canvas as a canvas')
1054
+ .argument('<path>', 'A directory of .md / .html / .canvas.json / .canvas files (walked recursively), or one such file')
1055
+ .option('--on-conflict <mode>', 'Conflict resolution: skip|overwrite|rename (default: skip)')
1056
+ .option('--type <slug>', 'Doc-type slug to apply to all uploaded docs (.html and canvas files keep visual / canvas)')
1052
1057
  .option('--folder <base>', 'Nest the whole upload under this base folder path in SA-Docs')
1058
+ .option('--replace <doc-id>', 'Replace the body of an existing doc (numeric id) with a single file of the same kind')
1053
1059
  .option('--dry-run', 'Preview what would be created without writing')
1054
1060
  .option('--force', 'Overwrite tracked docs (from a prior doc pull) without a base-revision drift guard')
1055
1061
  .option('--json', 'Output result as JSON')
1056
- .action(async (dir, options) => {
1057
- await (0, doc_push_1.docPush)(dir, { onConflict: options.onConflict, type: options.type, folder: options.folder, dryRun: options.dryRun, force: options.force, json: options.json });
1062
+ .action(async (target, options) => {
1063
+ await (0, doc_push_1.docPush)(target, { onConflict: options.onConflict, type: options.type, folder: options.folder, replace: options.replace, dryRun: options.dryRun, force: options.force, json: options.json });
1058
1064
  });
1059
1065
  doc
1060
1066
  .command('pull')
package/dist/utils/api.js CHANGED
@@ -16,12 +16,14 @@ exports.formatValidationError = formatValidationError;
16
16
  exports.requireResolvedConfig = requireResolvedConfig;
17
17
  exports.requireConfig = requireConfig;
18
18
  exports.authFailureMessage = authFailureMessage;
19
+ exports.formatApiFailure = formatApiFailure;
19
20
  exports.ensureWorkspaceSelected = ensureWorkspaceSelected;
20
21
  exports.buildWorkspaceConfirmPrompt = buildWorkspaceConfirmPrompt;
21
22
  exports.applyWorkspaceGuard = applyWorkspaceGuard;
22
23
  exports.requireConfigWithWorkspace = requireConfigWithWorkspace;
23
24
  const axios_1 = __importDefault(require("axios"));
24
25
  const chalk_1 = __importDefault(require("chalk"));
26
+ const path_1 = __importDefault(require("path"));
25
27
  const prompts_1 = __importDefault(require("prompts"));
26
28
  const config_1 = require("./config");
27
29
  const workspace_lookup_1 = require("./workspace-lookup");
@@ -276,6 +278,10 @@ function formatValidationError(data) {
276
278
  */
277
279
  function requireResolvedConfig() {
278
280
  const resolved = (0, config_1.resolveConfig)();
281
+ if (resolved?.credentialConflict) {
282
+ console.error(chalk_1.default.red((0, config_1.credentialConflictMessage)(resolved.credentialConflict)));
283
+ process.exit(1);
284
+ }
279
285
  if (!resolved || !resolved.config.apiKey) {
280
286
  console.error(chalk_1.default.red('Not initialized. Run `solidactions login --global` first.'));
281
287
  process.exit(1);
@@ -294,6 +300,19 @@ function authFailureMessage(config, sources) {
294
300
  const keySource = sources?.apiKey ?? 'config';
295
301
  return `Authentication failed against ${config.host} (key from ${keySource}). Run \`solidactions login --global\` to re-configure.`;
296
302
  }
303
+ /**
304
+ * One line for a failed API response: the server's `message` when it sent one, else the
305
+ * status alone. Never the raw body — a debug-mode server returns the whole stack trace
306
+ * there (cli#114), and a proxy may return an HTML page.
307
+ */
308
+ function formatApiFailure(status, data) {
309
+ const message = data && typeof data === 'object' && !Array.isArray(data)
310
+ ? data.message
311
+ : undefined;
312
+ return typeof message === 'string' && message.trim() !== ''
313
+ ? `Failed: ${status} ${message.trim()}`
314
+ : `Failed: ${status}`;
315
+ }
297
316
  async function ensureWorkspaceSelected(config, dependencies = {}) {
298
317
  if (config.workspaceId) {
299
318
  return config;
@@ -302,6 +321,7 @@ async function ensureWorkspaceSelected(config, dependencies = {}) {
302
321
  const resolved = (0, config_1.resolveConfig)();
303
322
  const workspaceSource = resolved?.sources.workspaceId ?? null;
304
323
  let workspaces;
324
+ let responseScope = null;
305
325
  try {
306
326
  const response = await axios_1.default.get(`${config.host}/api/v1/workspaces`, {
307
327
  headers: {
@@ -331,6 +351,7 @@ async function ensureWorkspaceSelected(config, dependencies = {}) {
331
351
  if (scope) {
332
352
  config.scopeMode = scope.mode;
333
353
  config.scopedWorkspaceIds = scope.workspace_ids;
354
+ responseScope = scope;
334
355
  }
335
356
  }
336
357
  catch (error) {
@@ -371,8 +392,18 @@ async function ensureWorkspaceSelected(config, dependencies = {}) {
371
392
  config.workspaceId = selected.id;
372
393
  config.workspaceOrg = selected.org_name;
373
394
  if (workspaceSource !== 'env') {
395
+ // Persist ONLY the pin. Writing the merged config here copied host/apiKey (from env or
396
+ // the global file) into whichever file was active — a credential crossing layers (cli#124).
374
397
  const targetPath = resolved?.activePath ?? (0, config_1.getGlobalConfigPath)();
375
- (0, config_1.writeConfigFile)(targetPath, config);
398
+ (0, config_1.writeWorkspaceToFile)(targetPath, config.workspace, config.workspaceId, config.workspaceOrg);
399
+ // Correction (cli#124): the token's scope describes the API key, so it belongs in
400
+ // the file that holds that key — and only there. Never into a local pin file whose
401
+ // key lives in another file, and never for an env key.
402
+ const keySource = resolved?.sources.apiKey;
403
+ if (responseScope && keySource !== 'env' && keySource != null && path_1.default.resolve(keySource) === path_1.default.resolve(targetPath)) {
404
+ const existing = (0, config_1.readConfigFile)(targetPath) ?? {};
405
+ (0, config_1.writeConfigFile)(targetPath, { ...existing, scopeMode: responseScope.mode, scopedWorkspaceIds: responseScope.workspace_ids });
406
+ }
376
407
  }
377
408
  return config;
378
409
  }
@@ -484,7 +515,8 @@ async function applyWorkspaceGuard(config, sources, options, io = {}) {
484
515
  }
485
516
  }
486
517
  if (options.mutating && config.workspaceId) {
487
- announce(chalk_1.default.gray(`Workspace: ${describeWorkspace(config, sources)}`));
518
+ // Name the host too (cli#124): the same workspace name on two hosts confirms nothing.
519
+ announce(chalk_1.default.gray(`Workspace: ${describeWorkspace(config, sources)} on ${config.host}`));
488
520
  }
489
521
  // state.json means "the workspace you last WROTE to" — that is precisely what the write
490
522
  // confirmation above compares against. A read must never consume the change that gates a
@@ -3,6 +3,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.DEFAULT_HOST = void 0;
7
+ exports.normalizeHost = normalizeHost;
8
+ exports.credentialConflictMessage = credentialConflictMessage;
6
9
  exports.setCliWorkspaceOverride = setCliWorkspaceOverride;
7
10
  exports.getGlobalConfigPath = getGlobalConfigPath;
8
11
  exports.getLocalConfigPath = getLocalConfigPath;
@@ -17,6 +20,42 @@ exports.resolveConfig = resolveConfig;
17
20
  const fs_1 = __importDefault(require("fs"));
18
21
  const os_1 = __importDefault(require("os"));
19
22
  const path_1 = __importDefault(require("path"));
23
+ /** The host an env key goes to when no layer names one (PM ruling 10); the same default `login` uses. */
24
+ exports.DEFAULT_HOST = 'https://app.solidactions.com';
25
+ /** Hosts compare equal ignoring surrounding space, trailing slashes and case. */
26
+ function normalizeHost(host) {
27
+ return host.trim().replace(/\/+$/, '').toLowerCase();
28
+ }
29
+ function describeSource(source, envVar) {
30
+ return source === 'env' ? `$${envVar}` : String(source);
31
+ }
32
+ /** The refusal shown when a key would be sent to a host it was not configured with. Never includes the key. */
33
+ function credentialConflictMessage(conflict) {
34
+ if (conflict.keySource === 'env') {
35
+ // An env key with no SOLIDACTIONS_HOST may only go to the global config's host or the
36
+ // default host — never to a host a folder's config names (PM rulings 1 and 10).
37
+ const globalNote = conflict.otherHost !== undefined
38
+ ? ` (the global config names ${conflict.otherHost})`
39
+ : '';
40
+ return [
41
+ `Refusing to send the API key from $SOLIDACTIONS_API_KEY to ${conflict.host} (host from ${describeSource(conflict.hostSource, 'SOLIDACTIONS_HOST')}): without SOLIDACTIONS_HOST, a key from the environment only goes to the host in the global config or the default host ${exports.DEFAULT_HOST}${globalNote}.`,
42
+ 'Fix: set SOLIDACTIONS_HOST to the host that key belongs to.',
43
+ ].join('\n');
44
+ }
45
+ const hostFrom = describeSource(conflict.hostSource, 'SOLIDACTIONS_HOST');
46
+ const keyFrom = describeSource(conflict.keySource, 'SOLIDACTIONS_API_KEY');
47
+ const keyHome = conflict.keyHost ?? 'no host (that config sets none)';
48
+ const fixes = conflict.hostSource === 'env'
49
+ ? ['unset SOLIDACTIONS_HOST', 'or set SOLIDACTIONS_API_KEY to a key for that host as well']
50
+ : [`run \`solidactions login --local --host ${conflict.host}\` in this folder to store a key for ${conflict.host}`, `or remove "host" from ${hostFrom}`];
51
+ if (conflict.keyHost === undefined) {
52
+ fixes.push(`or add "host" to ${keyFrom}`);
53
+ }
54
+ return [
55
+ `Refusing to send the API key from ${keyFrom} to ${conflict.host} (host from ${hostFrom}): that key is configured for ${keyHome}.`,
56
+ `Fix: ${fixes.join(', ')}.`,
57
+ ].join('\n');
58
+ }
20
59
  const LOCAL_DIR_NAME = '.solidactions';
21
60
  const LOCAL_FILE_NAME = 'config.json';
22
61
  let cliWorkspaceOverride = undefined;
@@ -133,6 +172,13 @@ function readEnvOverrides() {
133
172
  * layer that defines it: env > local > global. Returns null only when no source
134
173
  * contributes a host or apiKey (i.e. nothing usable).
135
174
  *
175
+ * Credential-pair rule (cli#124): host and apiKey travel together. A host set in a
176
+ * layer ABOVE the layer that supplied the key must equal the key's own host, or the
177
+ * merge reports a `credentialConflict` and withholds the key (`apiKey: ''`) — a key
178
+ * is only ever sent to the host configured with it. An env key without
179
+ * SOLIDACTIONS_HOST may go only to the global config's host, or to DEFAULT_HOST when
180
+ * no file names a host; it never goes to a folder config's host.
181
+ *
136
182
  * Invariant the caller must uphold: if `local` is non-null, `localPath` must
137
183
  * also be non-null. (`local` is the parsed contents of a file at `localPath`;
138
184
  * the path is required for source attribution.) `global` may be null even when
@@ -177,10 +223,55 @@ function mergeConfigs(env, local, localPath, global, globalPath) {
177
223
  if (!host.value && !apiKey.value) {
178
224
  return null;
179
225
  }
226
+ // cli#124: host and apiKey are picked per field above, so a host set in a HIGHER layer
227
+ // than the key's layer would carry that key to a host it was never configured for.
228
+ // The key may only travel with the host of its own layer, or of a layer below it.
229
+ const layers = [{ cfg: env, source: 'env' }];
230
+ if (local)
231
+ layers.push({ cfg: local, source: localPath });
232
+ if (global)
233
+ layers.push({ cfg: global, source: globalPath });
234
+ const keyIndex = layers.findIndex((l) => l.cfg.apiKey !== undefined);
235
+ const hostIndex = layers.findIndex((l) => l.cfg.host !== undefined);
236
+ let credentialConflict;
237
+ if (keyIndex !== -1 && hostIndex !== -1 && hostIndex < keyIndex) {
238
+ const keyHost = layers.slice(keyIndex).find((l) => l.cfg.host !== undefined)?.cfg.host;
239
+ const resolvedHost = layers[hostIndex].cfg.host;
240
+ if (keyHost === undefined || normalizeHost(keyHost) !== normalizeHost(resolvedHost)) {
241
+ credentialConflict = {
242
+ host: resolvedHost,
243
+ hostSource: layers[hostIndex].source,
244
+ keyHost,
245
+ keySource: layers[keyIndex].source,
246
+ };
247
+ }
248
+ }
249
+ // PM rulings 1 and 10 (build card task-buildclitrust-bc78): a key from env with no
250
+ // SOLIDACTIONS_HOST has no host of its own, so the check above never fires for it. It may
251
+ // go only to the GLOBAL config's host or the default host — never to a host a folder's
252
+ // config names (a cloned repo's .solidactions/config.json must not receive an exported
253
+ // key), unless that host is the same as the global one.
254
+ let defaultHost = false;
255
+ if (keyIndex === 0 && env.host === undefined) {
256
+ const localHost = local?.host;
257
+ const globalHost = global?.host;
258
+ if (localHost !== undefined && (globalHost === undefined || normalizeHost(localHost) !== normalizeHost(globalHost))) {
259
+ credentialConflict = {
260
+ host: localHost,
261
+ hostSource: localPath,
262
+ keyHost: undefined,
263
+ keySource: 'env',
264
+ ...(globalHost !== undefined ? { otherHost: globalHost, otherHostSource: globalPath } : {}),
265
+ };
266
+ }
267
+ else if (localHost === undefined && globalHost === undefined) {
268
+ defaultHost = true;
269
+ }
270
+ }
180
271
  return {
181
272
  config: {
182
- host: (host.value ?? ''),
183
- apiKey: (apiKey.value ?? ''),
273
+ host: (defaultHost ? exports.DEFAULT_HOST : host.value ?? ''),
274
+ apiKey: (credentialConflict ? '' : apiKey.value ?? ''),
184
275
  workspace: workspace.value,
185
276
  workspaceId: workspaceId.value,
186
277
  workspaceOrg: workspaceId.org,
@@ -188,11 +279,12 @@ function mergeConfigs(env, local, localPath, global, globalPath) {
188
279
  scopedWorkspaceIds: scopedWorkspaceIds.value,
189
280
  },
190
281
  sources: {
191
- host: host.source,
282
+ host: defaultHost ? 'default' : host.source,
192
283
  apiKey: apiKey.source,
193
284
  workspace: workspace.source,
194
285
  workspaceId: workspaceId.source,
195
286
  },
287
+ ...(credentialConflict ? { credentialConflict } : {}),
196
288
  };
197
289
  }
198
290
  /**
@@ -223,5 +315,6 @@ function resolveConfig(cwd = process.cwd()) {
223
315
  config: merged.config,
224
316
  sources: merged.sources,
225
317
  activePath: localPath ?? globalPath,
318
+ credentialConflict: merged.credentialConflict,
226
319
  };
227
320
  }
package/dist/utils/mcp.js CHANGED
@@ -206,20 +206,24 @@ const CREWS_ROUTES = {
206
206
  sandbox_exec: { tool: 'crews_sandbox', action: 'role_exec', rename: { environment: 'role_exec_environment' } },
207
207
  },
208
208
  };
209
+ /** Own-property lookup: a route table must never resolve an inherited Object.prototype member (cli#155). */
210
+ function ownValue(table, key) {
211
+ return table !== undefined && Object.hasOwn(table, key) ? table[key] : undefined;
212
+ }
209
213
  /**
210
214
  * Map a CLI-level crews call (group + action) to the public MCP tool, action and
211
215
  * param names of the current catalog. Throws for an action the CLI has no route for.
212
216
  */
213
217
  function resolveCrewsCall(group, args) {
214
218
  const action = String(args.action ?? '');
215
- const route = CREWS_ROUTES[group][action];
219
+ const route = ownValue(CREWS_ROUTES[group], action);
216
220
  if (!route)
217
221
  throw new Error(`unsupported crews action: ${group}.${action}`);
218
222
  const out = {};
219
223
  for (const [k, v] of Object.entries(args)) {
220
224
  if (v === undefined)
221
225
  continue;
222
- out[route.rename?.[k] ?? k] = v;
226
+ out[ownValue(route.rename, k) ?? k] = v;
223
227
  }
224
228
  if (route.action)
225
229
  out.action = route.action;
@@ -256,7 +260,7 @@ const DOCS_ROUTES = {
256
260
  */
257
261
  function resolveDocsCall(args) {
258
262
  const action = String(args.action ?? '');
259
- const tool = DOCS_ROUTES[action];
263
+ const tool = ownValue(DOCS_ROUTES, action);
260
264
  if (!tool)
261
265
  throw new Error(`unsupported docs action: ${action}`);
262
266
  const out = {};
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.TERMINAL_RUN_STATUSES = void 0;
7
+ exports.getStatusColor = getStatusColor;
8
+ exports.formatRunStatusLabel = formatRunStatusLabel;
9
+ exports.describeAdmissionDenied = describeAdmissionDenied;
10
+ exports.describeTerminalRun = describeTerminalRun;
11
+ const chalk_1 = __importDefault(require("chalk"));
12
+ /** solidactions-app RunTrigger::TERMINAL_STATUSES — a run in one of these never changes again. */
13
+ exports.TERMINAL_RUN_STATUSES = ['completed', 'failed', 'cancelled', 'dispatch_failed', 'skipped_no_credit'];
14
+ function getStatusColor(status) {
15
+ switch (status?.toLowerCase()) {
16
+ case 'completed':
17
+ case 'success':
18
+ return chalk_1.default.green;
19
+ case 'running':
20
+ return chalk_1.default.blue;
21
+ case 'pending':
22
+ case 'queued':
23
+ case 'admission_pending':
24
+ return chalk_1.default.yellow;
25
+ case 'failed':
26
+ case 'error':
27
+ case 'dispatch_failed':
28
+ case 'skipped_no_credit':
29
+ return chalk_1.default.red;
30
+ case 'cancelled':
31
+ default:
32
+ return chalk_1.default.gray;
33
+ }
34
+ }
35
+ /** Status text for humans; `admission_pending` alone says nothing to a user (cli#99). */
36
+ function formatRunStatusLabel(status) {
37
+ return status === 'admission_pending' ? 'admission_pending (waiting for a free run slot)' : status;
38
+ }
39
+ /** Why a run never started, from the run payload's `admission_denied_reason`; null when there is none. */
40
+ function describeAdmissionDenied(reason) {
41
+ if (typeof reason !== 'string' || reason === '')
42
+ return null;
43
+ if (reason === 'ttl_expired') {
44
+ return 'Run never started: it waited for a free run slot longer than its time limit (admission_denied_reason: ttl_expired).';
45
+ }
46
+ return `Run never started (admission_denied_reason: ${reason}).`;
47
+ }
48
+ /** The outcome `run start --wait` reports for a terminal run, or null while the run can still change. */
49
+ function describeTerminalRun(run) {
50
+ const status = typeof run.status === 'string' ? run.status : '';
51
+ if (!exports.TERMINAL_RUN_STATUSES.includes(status))
52
+ return null;
53
+ if (status === 'completed')
54
+ return { exitCode: 0, message: 'Workflow completed successfully!' };
55
+ if (status === 'cancelled')
56
+ return { exitCode: 1, message: 'Workflow was cancelled.' };
57
+ if (status === 'failed') {
58
+ return { exitCode: 1, message: describeAdmissionDenied(run.admission_denied_reason) ?? 'Workflow failed!' };
59
+ }
60
+ return { exitCode: 1, message: `Workflow did not run (status: ${status}).` };
61
+ }
@@ -3,6 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.secretTempPath = secretTempPath;
6
7
  exports.writeSecretFileSync = writeSecretFileSync;
7
8
  exports.writeViaTempFileSync = writeViaTempFileSync;
8
9
  const crypto_1 = __importDefault(require("crypto"));
@@ -37,6 +38,29 @@ function resolveCreationPath(filePath) {
37
38
  error.code = 'ELOOP';
38
39
  throw error;
39
40
  }
41
+ /** Sibling temp path for `target`: `<basename>.<pid>.<hex>.tmp`, so a leaked `.env` temp still matches `.env*` ignores (cli#129). */
42
+ function secretTempPath(target) {
43
+ return path_1.default.join(path_1.default.dirname(target), `${path_1.default.basename(target)}.${process.pid}.${crypto_1.default.randomBytes(4).toString('hex')}.tmp`);
44
+ }
45
+ /**
46
+ * In-place write for a target rename(2) cannot replace (a file-level bind mount is a mount
47
+ * point: `docker run -v ./.env:/app/.env`). The mode is forced to 0600 BEFORE the old
48
+ * content is truncated or any new byte is written. Deliberately not atomic — see the
49
+ * cli-trust spec §6 "Deliberate consequences".
50
+ */
51
+ function writeInPlaceOwnerOnlySync(target, contents) {
52
+ // O_NOFOLLOW: never write a secret through a symlink (PM ruling 5). Rename replaces a link;
53
+ // an in-place open would follow it. Undefined on Windows, where this path never runs.
54
+ const fd = fs_1.default.openSync(target, fs_1.default.constants.O_RDWR | (fs_1.default.constants.O_NOFOLLOW ?? 0));
55
+ try {
56
+ fs_1.default.fchmodSync(fd, 0o600);
57
+ fs_1.default.ftruncateSync(fd, 0);
58
+ fs_1.default.writeFileSync(fd, contents);
59
+ }
60
+ finally {
61
+ fs_1.default.closeSync(fd);
62
+ }
63
+ }
40
64
  /**
41
65
  * Write a secret-bearing file so the result is owner-only, whether or not the
42
66
  * destination already exists.
@@ -50,6 +74,8 @@ function resolveCreationPath(filePath) {
50
74
  *
51
75
  * The mode is masked by the process umask, which can only subtract bits, so
52
76
  * the result is always <= 0600: never group- or world-readable.
77
+ *
78
+ * On `EBUSY` it falls back to an owner-only in-place write (not atomic).
53
79
  */
54
80
  function writeSecretFileSync(filePath, contents) {
55
81
  let stats;
@@ -71,7 +97,7 @@ function writeSecretFileSync(filePath, contents) {
71
97
  return;
72
98
  }
73
99
  const target = stats ? fs_1.default.realpathSync(filePath) : resolveCreationPath(filePath);
74
- const tempPath = path_1.default.join(path_1.default.dirname(target), `.${path_1.default.basename(target)}.${process.pid}.${crypto_1.default.randomBytes(4).toString('hex')}.tmp`);
100
+ const tempPath = secretTempPath(target);
75
101
  writeViaTempFileSync(target, tempPath, contents);
76
102
  }
77
103
  /**
@@ -80,15 +106,25 @@ function writeSecretFileSync(filePath, contents) {
80
106
  * Exported so tests can stage a collision at a known temp path; production
81
107
  * callers go through writeSecretFileSync, which randomizes that path.
82
108
  */
83
- function writeViaTempFileSync(target, tempPath, contents) {
109
+ function writeViaTempFileSync(target, tempPath, contents, rename = fs_1.default.renameSync) {
84
110
  let created = false;
85
111
  try {
86
112
  // 'wx' refuses to follow or clobber an existing (or planted) temp path.
87
113
  fs_1.default.writeFileSync(tempPath, contents, { flag: 'wx', mode: 0o600 });
88
114
  created = true;
89
- fs_1.default.renameSync(tempPath, target);
115
+ try {
116
+ rename(tempPath, target);
117
+ created = false; // the temp file IS the target now
118
+ return;
119
+ }
120
+ catch (error) {
121
+ if (error.code !== 'EBUSY') {
122
+ throw error;
123
+ }
124
+ }
125
+ writeInPlaceOwnerOnlySync(target, contents);
90
126
  }
91
- catch (error) {
127
+ finally {
92
128
  // Only our own temp file may be removed: a failed 'wx' means the path
93
129
  // holds someone else's file, which is not ours to delete.
94
130
  if (created) {
@@ -99,6 +135,5 @@ function writeViaTempFileSync(target, tempPath, contents) {
99
135
  // Nothing to clean up.
100
136
  }
101
137
  }
102
- throw error;
103
138
  }
104
139
  }
@@ -3,6 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.suggestWorkspaces = suggestWorkspaces;
6
7
  exports.classifyWorkspaceInput = classifyWorkspaceInput;
7
8
  exports.describeWorkspaceMatchFailure = describeWorkspaceMatchFailure;
8
9
  exports.groupWorkspacesByOrg = groupWorkspacesByOrg;
@@ -13,6 +14,23 @@ exports.resolveWorkspaceInput = resolveWorkspaceInput;
13
14
  const axios_1 = __importDefault(require("axios"));
14
15
  const chalk_1 = __importDefault(require("chalk"));
15
16
  const readline_1 = __importDefault(require("readline"));
17
+ /**
18
+ * Workspaces whose slug or name contains the input (or is contained in it), case-insensitively —
19
+ * offered after a miss, never selected (cli#112). Reverse containment only counts for
20
+ * slugs/names of 3+ characters, so a one-letter workspace isn't suggested for every miss.
21
+ */
22
+ function suggestWorkspaces(input, workspaces, limit = 5) {
23
+ const needle = input.trim().toLowerCase();
24
+ if (needle === '')
25
+ return [];
26
+ const similar = (value) => {
27
+ if (!value)
28
+ return false;
29
+ const hay = value.toLowerCase();
30
+ return hay.includes(needle) || (hay.length >= 3 && needle.includes(hay));
31
+ };
32
+ return workspaces.filter((w) => similar(w.slug) || similar(w.name)).slice(0, limit);
33
+ }
16
34
  /**
17
35
  * Pure: given a list of workspaces and an input string, classify the match.
18
36
  * Match order: id, slug, name — but unlike a bare first-match, NAME matches
@@ -47,7 +65,8 @@ function classifyWorkspaceInput(input, workspaces) {
47
65
  if (orgWorkspaces.length > 0) {
48
66
  return { kind: 'org-only', input, orgWorkspaces };
49
67
  }
50
- return { kind: 'not-found', input };
68
+ const suggestions = suggestWorkspaces(input, workspaces);
69
+ return suggestions.length > 0 ? { kind: 'not-found', input, suggestions } : { kind: 'not-found', input };
51
70
  }
52
71
  // Union name matches with same-named-org workspaces (not just when
53
72
  // there's exactly one name match): two workspaces can share the input's
@@ -120,8 +139,16 @@ function describeWorkspaceMatchFailure(result) {
120
139
  ];
121
140
  return lines.join('\n');
122
141
  }
123
- case 'not-found':
124
- return `Workspace "${result.input}" not found. Run \`solidactions workspace list\` to list available workspaces.`;
142
+ case 'not-found': {
143
+ const base = `Workspace "${result.input}" not found. Run \`solidactions workspace list\` to list available workspaces.`;
144
+ if (!result.suggestions?.length)
145
+ return base;
146
+ const names = result.suggestions.map((w) => {
147
+ const org = w.org_name || w.tenant_name;
148
+ return `${w.slug ?? w.name}${org ? ` (${org})` : ''}`;
149
+ });
150
+ return `${base}\nDid you mean: ${names.join(', ')}?`;
151
+ }
125
152
  case 'match':
126
153
  return '';
127
154
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@solidactions/cli",
3
- "version": "3.20.1",
3
+ "version": "3.21.0",
4
4
  "description": "SolidActions CLI - Deploy and manage workflow automation",
5
5
  "main": "dist/index.js",
6
6
  "bin": {