@solidactions/cli 3.13.0 → 3.15.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.
@@ -0,0 +1,115 @@
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.isCwdInferredWorkspace = isCwdInferredWorkspace;
7
+ exports.getStateFilePath = getStateFilePath;
8
+ exports.readLastUsedWorkspace = readLastUsedWorkspace;
9
+ exports.writeLastUsedWorkspace = writeLastUsedWorkspace;
10
+ exports.decideWorkspaceGuard = decideWorkspaceGuard;
11
+ // src/utils/workspace-guard.ts
12
+ const fs_1 = __importDefault(require("fs"));
13
+ const os_1 = __importDefault(require("os"));
14
+ const path_1 = __importDefault(require("path"));
15
+ const STATE_DIR_NAME = '.solidactions';
16
+ const STATE_FILE_NAME = 'state.json';
17
+ /**
18
+ * True when the resolved workspaceId came from a project-local .solidactions/config.json
19
+ * discovered by walking up from the CWD — i.e. it was INFERRED from where the user happens
20
+ * to be standing, not stated explicitly.
21
+ *
22
+ * `sources.workspaceId` is one of:
23
+ * - 'cli' — the -w/--workspace-override flag -> not inferred
24
+ * - 'env' — SOLIDACTIONS_WORKSPACE_ID -> not inferred
25
+ * - the global config path -> not inferred (deliberately pinned via `workspace set`)
26
+ * - any OTHER filesystem path -> a project-local config found by the upward walk -> INFERRED
27
+ * - null -> nothing resolved -> not inferred
28
+ */
29
+ function isCwdInferredWorkspace(sources, globalConfigPath) {
30
+ const source = sources.workspaceId;
31
+ if (source === null || source === 'cli' || source === 'env') {
32
+ return false;
33
+ }
34
+ return path_1.default.resolve(source) !== path_1.default.resolve(globalConfigPath);
35
+ }
36
+ /** Path to the state file, given a home dir. */
37
+ function getStateFilePath(homeDir = os_1.default.homedir()) {
38
+ return path_1.default.join(homeDir, STATE_DIR_NAME, STATE_FILE_NAME);
39
+ }
40
+ /** Read the recorded last-written-to workspace. Returns null when absent, unreadable, or malformed. */
41
+ function readLastUsedWorkspace(homeDir = os_1.default.homedir()) {
42
+ const filePath = getStateFilePath(homeDir);
43
+ if (!fs_1.default.existsSync(filePath)) {
44
+ return null;
45
+ }
46
+ try {
47
+ const raw = JSON.parse(fs_1.default.readFileSync(filePath, 'utf-8'));
48
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
49
+ return null;
50
+ }
51
+ if (typeof raw.workspaceId !== 'string') {
52
+ return null;
53
+ }
54
+ return raw;
55
+ }
56
+ catch {
57
+ return null;
58
+ }
59
+ }
60
+ /**
61
+ * Record the workspace a command just wrote to. Callers must only invoke this for mutating
62
+ * commands — a read must never consume the change that gates a write confirmation. Never
63
+ * throws — a failure to persist must not break a command.
64
+ *
65
+ * Atomic write mirroring writeConfigFile in src/utils/config.ts: write to `<path>.tmp`, then
66
+ * fs.renameSync into place; create the parent dir with mode 0o700 if missing. Unlike config.json,
67
+ * this file holds no secret (just a workspace UUID and a cosmetic label), so it is written with
68
+ * the default file mode rather than 0o600.
69
+ */
70
+ function writeLastUsedWorkspace(entry, homeDir = os_1.default.homedir()) {
71
+ try {
72
+ const filePath = getStateFilePath(homeDir);
73
+ const dir = path_1.default.dirname(filePath);
74
+ if (!fs_1.default.existsSync(dir)) {
75
+ fs_1.default.mkdirSync(dir, { recursive: true, mode: 0o700 });
76
+ }
77
+ const tmp = `${filePath}.tmp`;
78
+ fs_1.default.writeFileSync(tmp, JSON.stringify(entry, null, 2));
79
+ fs_1.default.renameSync(tmp, filePath);
80
+ }
81
+ catch {
82
+ // Advisory state only — never let a persistence failure break a command.
83
+ }
84
+ }
85
+ /**
86
+ * Decision table:
87
+ * | condition | result |
88
+ * |------------------------------------------------------------------|--------------------|
89
+ * | resolvedWorkspaceId falsy | 'none' |
90
+ * | cwdInferred is false | 'none' |
91
+ * | lastUsedWorkspaceId falsy, mutating true (fresh install, first write) | 'warn-no-baseline' |
92
+ * | lastUsedWorkspaceId falsy, mutating false (reads stay frictionless) | 'none' |
93
+ * | resolved === lastUsed | 'none' |
94
+ * | resolved !== lastUsed, mutating false | 'warn' |
95
+ * | resolved !== lastUsed, mutating true | 'confirm' |
96
+ */
97
+ function decideWorkspaceGuard(input) {
98
+ if (!input.resolvedWorkspaceId) {
99
+ return 'none';
100
+ }
101
+ if (!input.cwdInferred) {
102
+ return 'none';
103
+ }
104
+ if (!input.lastUsedWorkspaceId) {
105
+ // Deliberate: readLastUsedWorkspace() returns null for an absent state.json AND for
106
+ // an unreadable/malformed one. Both mean "no baseline to compare against" — an
107
+ // unreadable baseline is an unknown baseline, not a known-safe one — so both take
108
+ // the same conservative branch: warn on a write rather than silently confirming.
109
+ return input.mutating ? 'warn-no-baseline' : 'none';
110
+ }
111
+ if (input.resolvedWorkspaceId === input.lastUsedWorkspaceId) {
112
+ return 'none';
113
+ }
114
+ return input.mutating ? 'confirm' : 'warn';
115
+ }
@@ -3,7 +3,8 @@ 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.matchWorkspace = matchWorkspace;
6
+ exports.classifyWorkspaceInput = classifyWorkspaceInput;
7
+ exports.describeWorkspaceMatchFailure = describeWorkspaceMatchFailure;
7
8
  exports.groupWorkspacesByOrg = groupWorkspacesByOrg;
8
9
  exports.fetchWorkspaces = fetchWorkspaces;
9
10
  exports.formatWorkspaceWithOrg = formatWorkspaceWithOrg;
@@ -13,13 +14,117 @@ const axios_1 = __importDefault(require("axios"));
13
14
  const chalk_1 = __importDefault(require("chalk"));
14
15
  const readline_1 = __importDefault(require("readline"));
15
16
  /**
16
- * Pure: given a list of workspaces and an input string, return the matching
17
- * workspace. Match order: id, slug, name (first match wins). Cross-tenant
18
- * collisions resolve to the first match in the list (pre-existing behavior;
19
- * see sol-r0b-test-todo.md for follow-up).
17
+ * Pure: given a list of workspaces and an input string, classify the match.
18
+ * Match order: id, slug, name — but unlike a bare first-match, NAME matches
19
+ * are checked for collisions before being trusted, because org names and
20
+ * workspace names share a namespace (#1196):
21
+ * - the input can be an org name that also happens to be one of that org's
22
+ * workspace names, silently landing the user in the org-wide workspace
23
+ * instead of the one they meant;
24
+ * - the input can be an org name that owns no workspace of that name at
25
+ * all, which a bare miss reports as "not found" even though it's right
26
+ * there on `workspace list`;
27
+ * - the same workspace name can exist in two different orgs.
28
+ * `id` and `slug` matches are exact handles (unique in practice) and stay
29
+ * ambiguity-free so scripted `workspace set <slug|uuid>` keeps working
30
+ * unprompted; only name matches get the extra checks.
20
31
  */
21
- function matchWorkspace(input, workspaces) {
22
- return workspaces.find((w) => w.id === input || w.slug === input || w.name === input);
32
+ function classifyWorkspaceInput(input, workspaces) {
33
+ const idMatch = workspaces.find((w) => w.id === input);
34
+ if (idMatch) {
35
+ return { kind: 'match', workspace: idMatch };
36
+ }
37
+ const slugMatches = workspaces.filter((w) => w.slug === input);
38
+ if (slugMatches.length === 1) {
39
+ return { kind: 'match', workspace: slugMatches[0] };
40
+ }
41
+ if (slugMatches.length > 1) {
42
+ return { kind: 'ambiguous', input, candidates: slugMatches };
43
+ }
44
+ const nameMatches = workspaces.filter((w) => w.name === input);
45
+ const orgWorkspaces = workspaces.filter((w) => (w.org_name || w.tenant_name) === input);
46
+ if (nameMatches.length === 0) {
47
+ if (orgWorkspaces.length > 0) {
48
+ return { kind: 'org-only', input, orgWorkspaces };
49
+ }
50
+ return { kind: 'not-found', input };
51
+ }
52
+ // Union name matches with same-named-org workspaces (not just when
53
+ // there's exactly one name match): two workspaces can share the input's
54
+ // name AND that name can also be an org that owns a third workspace, and
55
+ // all three belong in the ambiguity list. Filtering the original array by
56
+ // the merged id set (rather than concatenating) both dedupes by id and
57
+ // preserves payload order.
58
+ const candidateIds = new Set([...nameMatches.map((w) => w.id), ...orgWorkspaces.map((w) => w.id)]);
59
+ if (candidateIds.size > 1) {
60
+ const candidates = workspaces.filter((w) => candidateIds.has(w.id));
61
+ return { kind: 'ambiguous', input, candidates };
62
+ }
63
+ return { kind: 'match', workspace: nameMatches[0] };
64
+ }
65
+ /** One candidate's identifying details, for ambiguity/org-only listings. */
66
+ function describeCandidate(ws) {
67
+ const orgName = ws.org_name || ws.tenant_name;
68
+ const parts = [ws.name];
69
+ if (orgName) {
70
+ parts.push(`organization: ${orgName}`);
71
+ }
72
+ if (ws.role) {
73
+ parts.push(`role: ${ws.role}`);
74
+ }
75
+ if (ws.slug) {
76
+ parts.push(`slug: ${ws.slug}`);
77
+ }
78
+ parts.push(`id: ${ws.id}`);
79
+ return ` - ${parts.join(', ')}`;
80
+ }
81
+ /**
82
+ * Pure: build the plain (uncoloured) failure message body for a
83
+ * non-`match` classification. Callers wrap this in `chalk.red` at the call
84
+ * site. `not-found` returns the pre-existing message text so error copy
85
+ * doesn't regress for the common miss case.
86
+ */
87
+ function describeWorkspaceMatchFailure(result) {
88
+ switch (result.kind) {
89
+ case 'ambiguous': {
90
+ // The org-collision case (input is a name AND an org, e.g. #1196's
91
+ // 10TC/10TC Sales) only has ONE workspace actually named the
92
+ // input — "matches more than one workspace" would be false there.
93
+ // The plain cross-name case (two+ workspaces genuinely sharing a
94
+ // name) keeps that wording because it's true.
95
+ const isAlsoOrgName = result.candidates.some((w) => (w.org_name || w.tenant_name) === result.input);
96
+ const headline = isAlsoOrgName
97
+ ? `"${result.input}" is both an organization name and a workspace name — it could mean any of the following workspaces:`
98
+ : `"${result.input}" is ambiguous — it matches more than one workspace:`;
99
+ // Slugs are unique per tenant, not globally, so they can't always
100
+ // separate the candidates — telling the user to retry with the slug
101
+ // when the ambiguity IS slug-level (or when two candidates share a
102
+ // slug, or one has none) sends them back to what just failed.
103
+ const slugs = result.candidates.map((w) => w.slug);
104
+ const slugsDisambiguate = slugs.every((slug) => !!slug) && new Set(slugs).size === slugs.length;
105
+ const lines = [
106
+ headline,
107
+ ...result.candidates.map(describeCandidate),
108
+ slugsDisambiguate
109
+ ? 'Re-run with the workspace\'s slug or ID instead.'
110
+ : 'Re-run with the workspace\'s ID instead.',
111
+ ];
112
+ return lines.join('\n');
113
+ }
114
+ case 'org-only': {
115
+ const lines = [
116
+ `"${result.input}" is an organization, not a workspace.`,
117
+ 'Its workspaces:',
118
+ ...result.orgWorkspaces.map(describeCandidate),
119
+ 'Pick one by name, slug or ID.',
120
+ ];
121
+ return lines.join('\n');
122
+ }
123
+ case 'not-found':
124
+ return `Workspace "${result.input}" not found. Run \`solidactions workspace list\` to list available workspaces.`;
125
+ case 'match':
126
+ return '';
127
+ }
23
128
  }
24
129
  /**
25
130
  * Pure: group workspaces by tenant for display, preserving payload order.
@@ -87,12 +192,14 @@ function formatWorkspaceWithOrg(ws) {
87
192
  return ws.org_name ? `${ws.name} — organization ${ws.org_name}` : ws.name;
88
193
  }
89
194
  async function selectWorkspaceInteractively(workspaces, dependencies = {}) {
195
+ // Status text, not a command's own output — stdout is reserved for machine-parseable
196
+ // output (e.g. `--json`), same reasoning as the workspace banner in api.ts.
90
197
  if (workspaces.length === 0) {
91
- console.log(chalk_1.default.yellow('No workspaces found. Create one at your SolidActions dashboard, then run `solidactions workspace set <name>`.'));
198
+ console.error(chalk_1.default.yellow('No workspaces found. Create one at your SolidActions dashboard, then run `solidactions workspace set <name>`.'));
92
199
  return undefined;
93
200
  }
94
201
  if (workspaces.length === 1) {
95
- console.log(chalk_1.default.gray(`Auto-selected workspace: ${formatWorkspaceWithOrg(workspaces[0])}`));
202
+ console.error(chalk_1.default.gray(`Auto-selected workspace: ${formatWorkspaceWithOrg(workspaces[0])}`));
96
203
  return workspaces[0];
97
204
  }
98
205
  const label = dependencies.label ?? ((ws) => (ws.role ? `${ws.name} (${ws.role})` : ws.name));
@@ -146,7 +253,8 @@ async function selectWorkspaceInteractively(workspaces, dependencies = {}) {
146
253
  const index = parseInt(answer, 10) - 1;
147
254
  if (!isNaN(index) && index >= 0 && index < workspaces.length) {
148
255
  const selected = workspaces[index];
149
- console.log(chalk_1.default.green(`Selected: ${formatWorkspaceWithOrg(selected)}`));
256
+ // Status text, not a command's own output — same reasoning as above.
257
+ console.error(chalk_1.default.green(`Selected: ${formatWorkspaceWithOrg(selected)}`));
150
258
  return selected;
151
259
  }
152
260
  console.error(chalk_1.default.red('Invalid selection. Enter one of the numbers shown.'));
@@ -170,21 +278,25 @@ async function resolveWorkspaceInput(config, input) {
170
278
  console.error(chalk_1.default.red('Failed to list workspaces:'), error.response?.data?.message || error.message);
171
279
  process.exit(1);
172
280
  }
173
- const match = matchWorkspace(input, workspaces);
174
- if (!match) {
175
- // A scoped (single/subset) session only ever lists the workspaces its
176
- // OAuth grant covers, so a miss can mean either "doesn't exist" OR
177
- // "exists but out of this session's scope" — disambiguate so the user
178
- // knows re-auth with broader scope may be the fix, not a typo.
179
- if (scope && (scope.mode === 'single' || scope.mode === 'subset')) {
180
- console.error(chalk_1.default.red(`Workspace "${input}" not found in this session's authorized workspaces `
181
- + `(scope: ${scope.mode}${scope.workspace_ids.length ? `, covering ${scope.workspace_ids.join(', ')}` : ''}). `
182
- + 'If it exists but is out of scope, re-authenticate with broader scope: `solidactions login --device`.'));
183
- }
184
- else {
185
- console.error(chalk_1.default.red(`Workspace "${input}" not found. Run \`solidactions workspace list\` to list available workspaces.`));
186
- }
281
+ const result = classifyWorkspaceInput(input, workspaces);
282
+ if (result.kind === 'match') {
283
+ return result.workspace;
284
+ }
285
+ if (result.kind === 'ambiguous' || result.kind === 'org-only') {
286
+ console.error(chalk_1.default.red(describeWorkspaceMatchFailure(result)));
187
287
  process.exit(1);
188
288
  }
189
- return match;
289
+ // A scoped (single/subset) session only ever lists the workspaces its
290
+ // OAuth grant covers, so a miss can mean either "doesn't exist" OR
291
+ // "exists but out of this session's scope" — disambiguate so the user
292
+ // knows re-auth with broader scope may be the fix, not a typo.
293
+ if (scope && (scope.mode === 'single' || scope.mode === 'subset')) {
294
+ console.error(chalk_1.default.red(`Workspace "${input}" not found in this session's authorized workspaces `
295
+ + `(scope: ${scope.mode}${scope.workspace_ids.length ? `, covering ${scope.workspace_ids.join(', ')}` : ''}). `
296
+ + 'If it exists but is out of scope, re-authenticate with broader scope: `solidactions login --device`.'));
297
+ }
298
+ else {
299
+ console.error(chalk_1.default.red(describeWorkspaceMatchFailure(result)));
300
+ }
301
+ process.exit(1);
190
302
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@solidactions/cli",
3
- "version": "3.13.0",
3
+ "version": "3.15.0",
4
4
  "description": "SolidActions CLI - Deploy and manage workflow automation",
5
5
  "main": "dist/index.js",
6
6
  "bin": {