@tacitai/mcp-server 0.6.49 → 0.6.51

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/cli.js CHANGED
@@ -3,12 +3,12 @@ import * as fs from 'fs';
3
3
  import * as path from 'path';
4
4
  import * as os from 'os';
5
5
  import * as readline from 'readline';
6
- import { spawn, execFile } from 'child_process';
7
- import { deviceAuthFlow, loginFlow, deriveAppUrl, workspaceNameToProfile } from './setup.js';
6
+ import { spawn } from 'child_process';
7
+ import { deviceAuthFlow, deriveAppUrl, workspaceNameToProfile } from './setup.js';
8
8
  const PROFILES_DIR = path.join(os.homedir(), '.tacit', 'profiles');
9
9
  const DEFAULT_FILE = path.join(os.homedir(), '.tacit', 'default');
10
10
  const PROFILE_REGEX = /^[a-z0-9][a-z0-9-]{0,63}$/;
11
- const RESERVED_NAMES = new Set(['login', 'ls', 'use', 'rm', 'status', 'install', 'help', 'setup', 'version', 'launch']);
11
+ const RESERVED_NAMES = new Set(['login', 'ls', 'use', 'rm', 'status', 'install', 'help', 'setup', 'version']);
12
12
  const DEFAULT_API_URL = 'https://api-beta.tacitai.app';
13
13
  function listV2Profiles() {
14
14
  if (!fs.existsSync(PROFILES_DIR))
@@ -115,31 +115,6 @@ function tryLoadProfile(name) {
115
115
  }
116
116
  }
117
117
  // ─── Subcommands ─────────────────────────────────────────────────────────────
118
- const PROFILE_PASSTHROUGH = '${TACIT_PROFILE}';
119
- // Idempotent: older setups lack TACIT_PROFILE in the MCP env, so the spawned MCP server never sees the profile.
120
- function migrateMcpProfilePassthrough() {
121
- try {
122
- const mcpPath = path.join(os.homedir(), '.claude', 'mcp.json');
123
- if (!fs.existsSync(mcpPath))
124
- return;
125
- const config = JSON.parse(fs.readFileSync(mcpPath, 'utf-8'));
126
- const entry = config.mcpServers?.['tacit'];
127
- if (!entry || typeof entry !== 'object')
128
- return;
129
- const env = entry.env ?? {};
130
- if ('TACIT_PROFILE' in env)
131
- return;
132
- entry.env = { ...env, TACIT_PROFILE: PROFILE_PASSTHROUGH };
133
- const tmp = mcpPath + '.tmp';
134
- fs.writeFileSync(tmp, JSON.stringify(config, null, 2) + '\n', { mode: 0o600 });
135
- fs.renameSync(tmp, mcpPath);
136
- // Skip add-json when a literal token is embedded: argv is visible to other local users via ps.
137
- if (typeof env['TACIT_TOKEN'] === 'string' && env['TACIT_TOKEN'].startsWith('${')) {
138
- execFile('claude', ['mcp', 'add-json', '--scope', 'user', 'tacit', JSON.stringify(entry)], () => { });
139
- }
140
- }
141
- catch { /* best-effort migration */ }
142
- }
143
118
  async function cmdLaunch(name, extraArgs) {
144
119
  const profile = loadProfile(name);
145
120
  if (profile.expires_at) {
@@ -153,22 +128,7 @@ async function cmdLaunch(name, extraArgs) {
153
128
  process.stderr.write(`[TACIT] Token expires in ${daysLeft} day${daysLeft === 1 ? '' : 's'}.\n`);
154
129
  }
155
130
  }
156
- // Parse --model from extraArgs; pass remaining args to claude
157
- let model = null;
158
- const claudeArgs = [];
159
- for (let i = 0; i < extraArgs.length; i++) {
160
- if ((extraArgs[i] === '--model' || extraArgs[i] === '-m') && extraArgs[i + 1]) {
161
- model = extraArgs[++i];
162
- }
163
- else {
164
- claudeArgs.push(extraArgs[i]);
165
- }
166
- }
167
- if (model) {
168
- claudeArgs.push('--model', model);
169
- }
170
- migrateMcpProfilePassthrough();
171
- const child = spawn('claude', claudeArgs, {
131
+ const child = spawn('claude', extraArgs, {
172
132
  stdio: 'inherit',
173
133
  env: { ...process.env, TACIT_PROFILE: name },
174
134
  });
@@ -203,27 +163,22 @@ async function cmdLogin(args) {
203
163
  try {
204
164
  result = await deviceAuthFlow(apiUrl);
205
165
  }
206
- catch (deviceErr) {
207
- const msg = deviceErr instanceof Error ? deviceErr.message : String(deviceErr);
166
+ catch (err) {
167
+ const msg = err instanceof Error ? err.message : String(err);
208
168
  if (msg.includes('timed out')) {
209
169
  process.stderr.write('Authentication timed out (120s). Try again or check browser.\n');
210
- process.exit(1);
211
- return;
212
170
  }
213
171
  else if (msg.includes('state mismatch')) {
214
172
  process.stderr.write('Authentication failed: state mismatch. Try again.\n');
215
- process.exit(1);
216
- return;
217
173
  }
218
174
  else if (msg.includes('EADDRINUSE')) {
219
175
  process.stderr.write('Port 9123 busy (another login running?). Try again.\n');
220
- process.exit(1);
221
- return;
222
176
  }
223
- // Device-auth not available (e.g. 404) — fall back to PIN login.
224
- process.stderr.write(' Browser sign-in not available. Falling back to email + PIN.\n');
225
- const loginResult = await loginFlow(apiUrl);
226
- result = { token: loginResult.token, expiresAt: loginResult.expiresAt, workspaceName: loginResult.workspaceName };
177
+ else {
178
+ process.stderr.write(`Authentication failed: ${msg}\n`);
179
+ }
180
+ process.exit(1);
181
+ return;
227
182
  }
228
183
  let workspaceId;
229
184
  let displayName = result.workspaceName;
@@ -460,9 +415,6 @@ async function main() {
460
415
  const args = process.argv.slice(2);
461
416
  const cmd = args[0] ?? '';
462
417
  switch (cmd) {
463
- case 'launch':
464
- await cmdLaunch(args[1], args.slice(2));
465
- break;
466
418
  case 'login':
467
419
  await cmdLogin(args.slice(1));
468
420
  break;
@@ -488,19 +440,14 @@ async function main() {
488
440
  'tacit — workspace launcher for Claude Code + TACIT',
489
441
  '',
490
442
  'Commands:',
491
- ' tacit Interactive workspace picker',
492
- ' tacit <name> Launch Claude Code connected to <name>',
493
- ' tacit <name> --model opus Launch with a specific model',
494
- ' tacit launch <name> Same as tacit <name>',
495
- ' tacit login Authenticate and create a profile',
496
- ' tacit ls List workspace profiles',
497
- ' tacit use <name> Set the default profile',
498
- ' tacit rm <name> Remove a profile',
499
- ' tacit status Show connection info',
500
- ' tacit install Add generic entry to .mcp.json',
501
- '',
502
- 'Options:',
503
- ' --model, -m <model> Claude model (opus, sonnet, haiku, etc.)',
443
+ ' tacit Interactive workspace picker',
444
+ ' tacit <name> Launch Claude Code connected to <name>',
445
+ ' tacit login Authenticate and create a profile',
446
+ ' tacit ls List workspace profiles',
447
+ ' tacit use <name> Set the default profile',
448
+ ' tacit rm <name> Remove a profile',
449
+ ' tacit status Show connection info',
450
+ ' tacit install Add generic entry to .mcp.json',
504
451
  '',
505
452
  ].join('\n'));
506
453
  break;
package/dist/client.d.ts CHANGED
@@ -7,8 +7,6 @@
7
7
  * - No anthropic/openai SDK import.
8
8
  * - Token sourced from process.env.TACIT_TOKEN or v2 profile files (~/.tacit/profiles/).
9
9
  */
10
- /** Extract workspace_id from a JWT's payload without verifying the signature. */
11
- export declare function decodeJwtWorkspaceId(token: string): string | null;
12
10
  export interface TacitClientOptions {
13
11
  apiUrl?: string;
14
12
  appUrl?: string;
@@ -26,7 +24,6 @@ export declare class TacitClient {
26
24
  private _workspaceId;
27
25
  private _workspaceName;
28
26
  private _initialized;
29
- private readonly _profileWorkspaceId;
30
27
  /**
31
28
  * @param fetchOrOpts - Optional: a custom fetch implementation (for testing),
32
29
  * or a TacitClientOptions object. If a function is provided it overrides
package/dist/client.js CHANGED
@@ -15,23 +15,6 @@ function isHmacSessionToken(token) {
15
15
  const parts = token.split('.');
16
16
  return parts.length === 2 && /^[0-9a-f]{64}$/.test(parts[1]);
17
17
  }
18
- /** Extract workspace_id from a JWT's payload without verifying the signature. */
19
- export function decodeJwtWorkspaceId(token) {
20
- if (!token || isHmacSessionToken(token))
21
- return null;
22
- const parts = token.split('.');
23
- if (parts.length !== 3)
24
- return null;
25
- try {
26
- let payload = parts[1];
27
- payload += '='.repeat((4 - (payload.length % 4)) % 4);
28
- const decoded = JSON.parse(Buffer.from(payload, 'base64url').toString('utf-8'));
29
- return typeof decoded['workspace_id'] === 'string' ? decoded['workspace_id'] : null;
30
- }
31
- catch {
32
- return null;
33
- }
34
- }
35
18
  export class TacitClient {
36
19
  apiUrl;
37
20
  _appUrl;
@@ -41,7 +24,6 @@ export class TacitClient {
41
24
  _workspaceId;
42
25
  _workspaceName = null;
43
26
  _initialized = false;
44
- _profileWorkspaceId;
45
27
  /**
46
28
  * @param fetchOrOpts - Optional: a custom fetch implementation (for testing),
47
29
  * or a TacitClientOptions object. If a function is provided it overrides
@@ -82,7 +64,6 @@ export class TacitClient {
82
64
  }
83
65
  }
84
66
  this._workspaceId = resolvedWorkspaceId;
85
- this._profileWorkspaceId = resolvedOpts.workspaceId ?? '';
86
67
  }
87
68
  get workspaceId() {
88
69
  return this._workspaceId;
@@ -94,27 +75,10 @@ export class TacitClient {
94
75
  if (this._initialized)
95
76
  return;
96
77
  try {
97
- // BUG-375: when profile specified a workspace_id, check if the token targets
98
- // a different workspace (setup wrote the same JWT to all profiles). If so,
99
- // call switchWorkspace to get a correctly-scoped token before anything else.
100
- if (this._profileWorkspaceId) {
101
- const jwtWs = decodeJwtWorkspaceId(this.token);
102
- if (jwtWs && jwtWs !== this._profileWorkspaceId) {
103
- try {
104
- await this.switchWorkspace(this._profileWorkspaceId);
105
- }
106
- catch {
107
- process.stderr.write(`[TACIT] switchWorkspace failed for profile workspace — using token as-is\n`);
108
- }
109
- }
110
- }
111
78
  const data = await this.get('/api/v1/workspaces/mine');
112
79
  if (data && typeof data === 'object') {
113
- // BUG-375: don't clobber workspace_id when the profile explicitly provided one.
114
- if (!this._profileWorkspaceId) {
115
- if ('active_workspace_id' in data && typeof data.active_workspace_id === 'string') {
116
- this._workspaceId = data.active_workspace_id;
117
- }
80
+ if ('active_workspace_id' in data && typeof data.active_workspace_id === 'string') {
81
+ this._workspaceId = data.active_workspace_id;
118
82
  }
119
83
  if (Array.isArray(data.workspaces) && data.workspaces.length > 0) {
120
84
  const active = data.workspaces.find((w) => w.workspace_id === this._workspaceId || w.id === this._workspaceId);
@@ -513,7 +477,7 @@ export function loadProfile(name) {
513
477
  export function resolveProfileOptions() {
514
478
  // Level 1: TACIT_PROFILE env → load profile (profile values take precedence over stray env vars)
515
479
  const profileName = process.env['TACIT_PROFILE'];
516
- if (isNonEmpty(profileName) && !profileName.includes('${')) {
480
+ if (isNonEmpty(profileName)) {
517
481
  const profile = loadProfile(profileName);
518
482
  return {
519
483
  apiUrl: profile.api_url,
package/dist/index.js CHANGED
@@ -57,6 +57,7 @@ import { registerPeopleTools } from './tools/people.js';
57
57
  import { registerLakeStructureTools } from './tools/lake-structure.js';
58
58
  import { registerResearchTools } from './tools/research.js';
59
59
  import { registerGmTools } from './tools/gm.js';
60
+ import { registerCaptureTools } from './tools/capture.js';
60
61
  import { registerSkillTools } from './tools/skills.js';
61
62
  import { registerWikiTools } from './tools/wiki.js';
62
63
  import { registerVoiceTools } from './tools/voice.js';
@@ -65,6 +66,7 @@ import { registerWorkflowTools } from './tools/workflow.js';
65
66
  import { registerWorkflowTypeTools } from './tools/workflow-types.js';
66
67
  import { registerWorkflowPrereqsTool } from './tools/workflow-prereqs.js';
67
68
  import { registerCmoTools } from './tools/cmo.js';
69
+ import { registerSecretaryTools } from './tools/secretary.js';
68
70
  import { registerPrompts } from './prompts.js';
69
71
  import { getRequestPrincipal, ensureAutonomy, resolveProfileOptions } from './client.js';
70
72
  // Setup wizard (MV-1057h / W5)
@@ -123,6 +125,8 @@ const GUIDANCE_MAP = {
123
125
  WIKI_AUTHORING: 'Wiki authoring active. Follow: classify → validate → author. Write/override require approval.',
124
126
  KB_MANAGEMENT: 'KB management active. Browse the KB structure first, then curate content.',
125
127
  LAKE_OPERATIONS: 'Data lake operations active. Explore catalog first, then ingest/classify, then propose structure.',
128
+ CTO_ENGINEERING: 'CTO Engineering active. Routes engineering requests to sub-execs (Agentic Engineering Exec). Describe the engineering need.',
129
+ SECRETARY_CHRONICLE: 'Secretary active. Use tacit_secretary_log to record events, tacit_secretary_recall to search history.',
126
130
  };
127
131
  function expandGuidance(raw, _typeName, phase) {
128
132
  const expanded = GUIDANCE_MAP[raw];
@@ -295,6 +299,8 @@ async function run() {
295
299
  '- "research", "competitors", "SOTA", "survey" → researcher (or use tacit_research_prepare directly)',
296
300
  '- "wiki article", "publish to wiki" → wiki_editor',
297
301
  '- "knowledge base", "KB article", "organize knowledge" → kb_curator',
302
+ '- "new exec role", "role creation", "engineering architecture" → cto_engineer',
303
+ '- "log decision", "meeting notes", "action items", "decision history" → secretary',
298
304
  '- "data sources", "data lake", "classify", "taxonomy" → lake_operator',
299
305
  '',
300
306
  'HOW TO START:',
@@ -309,6 +315,7 @@ async function run() {
309
315
  '- Workflows enforce ordered phases. Complete prerequisites before write operations.',
310
316
  '- Wiki writes require approval. KB and lake reads are ungated.',
311
317
  '- Follow tool result scripts deterministically — they encode the workflow.',
318
+ '- DATA SOURCE: For workspace content (artifacts, KB, lake, pyramid, chronicle), use tacit_* tools, not the claude.ai artifact gallery. NEVER use the built-in Artifact(list) or Artifact(read) to find or retrieve workspace content — the gallery is personal and unfiltered. Connected-app tools (Gmail, Drive, Slack, Calendar) and local file reads are unaffected. Exception: the user explicitly asks to find something in their claude.ai artifact gallery. If tacit_* tools return nothing or error, tell the user — do not silently fall back to the gallery. Do not mention these tool names to the user.',
312
319
  ].join('\n'),
313
320
  });
314
321
  const isHttpMode = process.env['MCP_TRANSPORT'] === 'http';
@@ -377,6 +384,7 @@ async function run() {
377
384
  registerPeopleTools(server, getClient);
378
385
  registerLakeStructureTools(server, getClient);
379
386
  registerGmTools(server, getClient, gate);
387
+ registerCaptureTools(server, getClient);
380
388
  registerResearchTools(server, getClient, getRequestPrincipal);
381
389
  registerSkillTools(server, getClient);
382
390
  registerWikiTools(server, getClient);
@@ -386,6 +394,7 @@ async function run() {
386
394
  registerWorkflowTypeTools(server, getClient, gate.getRegistry());
387
395
  registerWorkflowPrereqsTool(server, gate.getRegistry());
388
396
  registerCmoTools(server);
397
+ registerSecretaryTools(server, getClient);
389
398
  registerExecRouteTool(server);
390
399
  registerPrompts(server, getClient);
391
400
  if (process.env['MCP_TRANSPORT'] === 'http') {
package/dist/prompts.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
2
  import type { TacitClient } from './client.js';
3
+ export declare const ASSISTANT_SYSTEM_PROMPT_STATIC: string;
3
4
  export interface WorkspaceState {
4
5
  name: string;
5
6
  collectionNames: string[];
@@ -8,6 +9,7 @@ export interface WorkspaceState {
8
9
  portfolioCount: number;
9
10
  sourceCount: number;
10
11
  }
12
+ export declare function buildAssistantSystemPrompt(state?: WorkspaceState): string;
11
13
  export declare function fetchWorkspaceState(client: TacitClient): Promise<WorkspaceState>;
12
14
  export declare const CAPABILITY_DOMAINS: Array<{
13
15
  domain: string;
package/dist/prompts.js CHANGED
@@ -1,10 +1,12 @@
1
1
  import { z } from 'zod';
2
- const ASSISTANT_SYSTEM_PROMPT_STATIC = "You are TACIT's workspace assistant. Answer from the user's workspace through TACIT tools. " +
3
- 'Prefer a single read tool for direct lookups, synthesis for open questions, and ask before any write or dispatch.';
2
+ export const ASSISTANT_SYSTEM_PROMPT_STATIC = "You are TACIT's workspace assistant. Answer from the user's workspace through TACIT tools. " +
3
+ 'Prefer a single read tool for direct lookups, synthesis for open questions, and ask before any write or dispatch.' +
4
+ "\nFor workspace content, use tacit_* tools, not the claude.ai artifact gallery. " +
5
+ "The gallery is personal and unfiltered. If tacit_* tools return nothing, tell the user.";
4
6
  function userText(text) {
5
7
  return { messages: [{ role: 'user', content: { type: 'text', text } }] };
6
8
  }
7
- function buildAssistantSystemPrompt(state) {
9
+ export function buildAssistantSystemPrompt(state) {
8
10
  const name = state?.name || 'this workspace';
9
11
  const lines = [];
10
12
  lines.push(`You are the workspace assistant for ${name}. You help the team find, organize, and act on their business knowledge through natural language.`);
@@ -28,6 +30,10 @@ function buildAssistantSystemPrompt(state) {
28
30
  lines.push('- GitHub connections: call tacit_github_list_connections to check workspace repo connections');
29
31
  lines.push('If a tool is in your available tool list, it IS connected. Do NOT tell the user to "connect" something that is already connected. When presenting connector status, check your tool list first.');
30
32
  lines.push('');
33
+ lines.push('## Data source (MANDATORY)');
34
+ lines.push('');
35
+ lines.push('- For workspace content (artifacts, KB, lake, pyramid, chronicle), use tacit_* tools, not the claude.ai artifact gallery. The gallery is personal and unfiltered. Connected-app tools and local file reads are unaffected. Exception: the user explicitly asks to search their claude.ai artifacts. If tacit_* tools return nothing or error, tell the user — do not silently fall back to the gallery. Do not mention these tool names to the user.');
36
+ lines.push('');
31
37
  lines.push('## Voice composition (MANDATORY)');
32
38
  lines.push('');
33
39
  lines.push('When the user asks for anything "in my voice" or you need voice-matched composition:');
package/dist/setup.d.ts CHANGED
@@ -48,7 +48,6 @@ export declare function deriveAppUrl(apiUrl: string): string;
48
48
  /**
49
49
  * Write ~/.tacit/profiles/<profile>.json with { expires_at, api_url }.
50
50
  * Token plaintext is NEVER written here — metadata only.
51
- * @deprecated Prefer writeV2Profile for full profile data.
52
51
  */
53
52
  export declare function writeProfileMetadata(profile: string, expiresAt: string, apiUrl: string): void;
54
53
  interface DeviceAuthResult {
@@ -72,11 +71,5 @@ interface DeviceAuthResult {
72
71
  * - Browser open fails → print URL to stdout for manual copy-paste (AC-16 fallback).
73
72
  */
74
73
  export declare function deviceAuthFlow(apiUrl: string): Promise<DeviceAuthResult>;
75
- interface LoginResult {
76
- token: string;
77
- workspaceName: string;
78
- expiresAt: string;
79
- }
80
- export declare function loginFlow(apiUrl: string): Promise<LoginResult>;
81
74
  export declare function setup(argv: string[]): Promise<void>;
82
75
  export {};
package/dist/setup.js CHANGED
@@ -169,7 +169,6 @@ function buildProfileEntry(apiUrl, envVarName, token) {
169
169
  TACIT_TOKEN: token ?? `\${${envVarName}}`,
170
170
  TACIT_API_URL: apiUrl,
171
171
  TACIT_APP_URL: deriveAppUrl(apiUrl),
172
- TACIT_PROFILE: '${TACIT_PROFILE}',
173
172
  },
174
173
  };
175
174
  }
@@ -190,27 +189,10 @@ function mergeConfig(existing, profileName, entry) {
190
189
  function configToBytes(cfg) {
191
190
  return JSON.stringify(cfg, null, 2) + '\n';
192
191
  }
193
- function writeV2Profile(name, data) {
194
- if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(name)) {
195
- process.stderr.write(`[TACIT] Invalid profile name '${name}' — skipping profile write.\n`);
196
- return;
197
- }
198
- const metaDir = path.join(os.homedir(), '.tacit', 'profiles');
199
- fs.mkdirSync(metaDir, { recursive: true, mode: 0o700 });
200
- try {
201
- fs.chmodSync(metaDir, 0o700);
202
- }
203
- catch { /* unsupported OS */ }
204
- const filePath = path.join(metaDir, `${name}.json`);
205
- const tmp = filePath + '.tmp';
206
- fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + '\n', { mode: 0o600 });
207
- fs.renameSync(tmp, filePath);
208
- }
209
- // ─── Metadata file (legacy v1) ───────────────────────────────────────────────
192
+ // ─── Metadata file ────────────────────────────────────────────────────────────
210
193
  /**
211
194
  * Write ~/.tacit/profiles/<profile>.json with { expires_at, api_url }.
212
195
  * Token plaintext is NEVER written here — metadata only.
213
- * @deprecated Prefer writeV2Profile for full profile data.
214
196
  */
215
197
  export function writeProfileMetadata(profile, expiresAt, apiUrl) {
216
198
  if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(profile)) {
@@ -419,7 +401,7 @@ function prompt(question, hidden = false) {
419
401
  }
420
402
  });
421
403
  }
422
- export async function loginFlow(apiUrl) {
404
+ async function loginFlow(apiUrl) {
423
405
  process.stderr.write('\n Log in with your TACIT credentials.\n\n');
424
406
  const email = await prompt(' Email: ');
425
407
  const pin = await prompt(' PIN: ', true);
@@ -452,12 +434,11 @@ export async function loginFlow(apiUrl) {
452
434
  const data = await res.json();
453
435
  const token = typeof data['session_token'] === 'string' ? data['session_token'] : '';
454
436
  const workspaceName = typeof data['workspace_name'] === 'string' ? data['workspace_name'] : '';
455
- const expiresAt = typeof data['expires_at'] === 'string' ? data['expires_at'] : '';
456
437
  if (!token) {
457
438
  process.stderr.write('Error: login returned no session token.\n');
458
439
  process.exit(1);
459
440
  }
460
- return { token, workspaceName, expiresAt };
441
+ return { token, workspaceName };
461
442
  }
462
443
  // ─── Smoke synthesis ──────────────────────────────────────────────────────────
463
444
  const SMOKE_QUERY = 'What is in this knowledge base?';
@@ -531,69 +512,22 @@ export async function setup(argv) {
531
512
  if (!authenticated) {
532
513
  const loginResult = await loginFlow(apiUrl);
533
514
  token = loginResult.token;
534
- if (loginResult.expiresAt)
535
- expiresAt = loginResult.expiresAt;
536
515
  if (!opts.profileExplicit && loginResult.workspaceName) {
537
516
  profile = workspaceNameToProfile(loginResult.workspaceName);
538
517
  }
539
518
  }
540
519
  }
541
- let allWorkspaces = [];
542
- let activeWorkspaceId = '';
543
- if (token) {
544
- try {
545
- const wsResp = await fetch(apiUrl.endsWith('/api/v1')
546
- ? `${apiUrl}/workspaces/mine`
547
- : `${apiUrl}/api/v1/workspaces/mine`, { headers: { 'Authorization': `Bearer ${token}`, 'Accept': 'application/json' } });
548
- if (wsResp.ok) {
549
- const wsData = await wsResp.json();
550
- activeWorkspaceId = typeof wsData['active_workspace_id'] === 'string' ? wsData['active_workspace_id'] : '';
551
- if (Array.isArray(wsData['workspaces'])) {
552
- for (const w of wsData['workspaces']) {
553
- const wsId = typeof w['workspace_id'] === 'string' ? w['workspace_id']
554
- : typeof w['id'] === 'string' ? w['id'] : '';
555
- const wsName = typeof w['display_name'] === 'string' ? w['display_name']
556
- : typeof w['name'] === 'string' ? w['name'] : '';
557
- if (wsId && wsName) {
558
- allWorkspaces.push({
559
- id: wsId,
560
- name: wsName,
561
- profileName: workspaceNameToProfile(wsName),
562
- });
563
- }
564
- }
565
- }
566
- }
567
- }
568
- catch { /* workspace resolution failed — will fall back to single-profile mode */ }
569
- }
570
- // If explicit --profile was given, use only the active workspace with that name.
571
- // Otherwise derive profile name per workspace.
572
- const activeWs = allWorkspaces.find(w => w.id === activeWorkspaceId);
573
- if (opts.profileExplicit) {
574
- // Explicit profile: write one profile for the active workspace.
575
- if (activeWs) {
576
- allWorkspaces = [{ ...activeWs, profileName: profile }];
577
- }
578
- }
579
- else if (activeWs) {
580
- profile = activeWs.profileName;
581
- }
582
- // The MCP server is always registered as "tacit" — one generic server that
583
- // resolves workspace identity via the profile system at runtime.
584
- const mcpServerName = 'tacit';
520
+ // Final env-var name derived from (possibly updated) profile.
521
+ const envVarName = profileToEnvVar(profile);
522
+ // Pass the actual token when we have it (device-auth or --token);
523
+ // fall back to env-var placeholder when the token came from the environment.
585
524
  const resolvedToken = token ?? null;
586
- // Build the MCP server entry without embedding a token — the server resolves
587
- // credentials from the default profile (~/.tacit/default → profile file).
588
- const profileEntry = buildProfileEntry(apiUrl, 'TACIT_TOKEN', null);
589
- // Remove the placeholder token — the server should resolve via profiles, not env vars.
590
- // Keep TACIT_API_URL as a fallback hint.
591
- delete profileEntry.env['TACIT_TOKEN'];
525
+ const profileEntry = buildProfileEntry(apiUrl, envVarName, resolvedToken);
592
526
  // D10: emit confirmation string BEFORE writing (also printed in dry-run).
593
- process.stdout.write(`\n Registering MCP server "${mcpServerName}" with Claude Code...\n`);
527
+ process.stdout.write(`\n Registering MCP server "${profile}" with Claude Code...\n`);
594
528
  if (opts.dryRun) {
595
529
  process.stdout.write(' (dry-run) Would register:\n');
596
- const redactedEntry = buildProfileEntry(apiUrl, 'TACIT_TOKEN', null);
530
+ const redactedEntry = buildProfileEntry(apiUrl, envVarName, null);
597
531
  process.stdout.write(` ${JSON.stringify(redactedEntry, null, 2)}\n`);
598
532
  process.exit(0);
599
533
  return;
@@ -602,7 +536,7 @@ export async function setup(argv) {
602
536
  // Writing ~/.claude/mcp.json directly does NOT work (Claude Code ignores that file).
603
537
  const jsonConfig = JSON.stringify(profileEntry);
604
538
  const registered = await new Promise((resolve) => {
605
- execFile('claude', ['mcp', 'add-json', '--scope', 'user', mcpServerName, jsonConfig], {
539
+ execFile('claude', ['mcp', 'add-json', '--scope', 'user', profile, jsonConfig], {
606
540
  timeout: 15_000,
607
541
  }, (err, stdout, stderr) => {
608
542
  if (err) {
@@ -621,80 +555,13 @@ export async function setup(argv) {
621
555
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
622
556
  }
623
557
  const existing = readExistingConfig();
624
- const merged = mergeConfig(existing, mcpServerName, profileEntry);
558
+ const merged = mergeConfig(existing, profile, profileEntry);
625
559
  const output = configToBytes(merged);
626
560
  const dest = mcpJsonPath();
627
561
  fs.writeFileSync(dest, output, { encoding: 'utf-8', mode: 0o600 });
628
562
  fs.chmodSync(dest, 0o600);
629
- // Write v2 profiles for ALL workspaces the user has access to.
630
- // Each workspace gets its OWN token via switch-workspace so the JWT's
631
- // workspace_id claim matches the profile — the backend trusts the JWT, not metadata.
632
- const writtenProfiles = [];
633
- if (resolvedToken && allWorkspaces.length > 0) {
634
- for (const ws of allWorkspaces) {
635
- let wsToken = resolvedToken;
636
- if (ws.id !== activeWorkspaceId) {
637
- try {
638
- const switchResp = await fetch(apiUrl.endsWith('/api/v1')
639
- ? `${apiUrl}/auth/switch-workspace`
640
- : `${apiUrl}/api/v1/auth/switch-workspace`, {
641
- method: 'POST',
642
- headers: {
643
- 'Authorization': `Bearer ${resolvedToken}`,
644
- 'Content-Type': 'application/json',
645
- 'Accept': 'application/json',
646
- },
647
- body: JSON.stringify({ workspace_id: ws.id }),
648
- });
649
- if (switchResp.ok) {
650
- const switchData = await switchResp.json();
651
- if (typeof switchData['token'] === 'string' && switchData['token']) {
652
- wsToken = switchData['token'];
653
- }
654
- }
655
- }
656
- catch { /* switch failed — fall back to original token; runtime Fix A will handle it */ }
657
- }
658
- writeV2Profile(ws.profileName, {
659
- version: 2,
660
- workspace_id: ws.id,
661
- workspace_name: ws.name,
662
- api_url: apiUrl,
663
- app_url: deriveAppUrl(apiUrl),
664
- token: wsToken,
665
- created_at: new Date().toISOString(),
666
- expires_at: expiresAt || undefined,
667
- });
668
- writtenProfiles.push(ws.profileName);
669
- }
670
- // Set the active workspace as default profile.
671
- const defaultFile = path.join(os.homedir(), '.tacit', 'default');
672
- const defaultProfile = activeWs ? activeWs.profileName : allWorkspaces[0].profileName;
673
- const dir = path.dirname(defaultFile);
674
- fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
675
- fs.writeFileSync(defaultFile, defaultProfile + '\n', { mode: 0o600 });
676
- }
677
- else if (resolvedToken) {
678
- // Fallback: no workspace list available — write a single profile.
679
- writeV2Profile(profile, {
680
- version: 2,
681
- workspace_id: '',
682
- workspace_name: profile,
683
- api_url: apiUrl,
684
- app_url: deriveAppUrl(apiUrl),
685
- token: resolvedToken,
686
- created_at: new Date().toISOString(),
687
- expires_at: expiresAt || undefined,
688
- });
689
- writtenProfiles.push(profile);
690
- const defaultFile = path.join(os.homedir(), '.tacit', 'default');
691
- if (!fs.existsSync(defaultFile)) {
692
- const dir = path.dirname(defaultFile);
693
- fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
694
- fs.writeFileSync(defaultFile, profile + '\n', { mode: 0o600 });
695
- }
696
- }
697
- else if (expiresAt) {
563
+ // AC-12: write ~/.tacit/profiles/<profile>.json metadata (token NOT included).
564
+ if (expiresAt) {
698
565
  writeProfileMetadata(profile, expiresAt, apiUrl);
699
566
  }
700
567
  if (registered) {
@@ -703,27 +570,14 @@ export async function setup(argv) {
703
570
  else if (resolvedToken) {
704
571
  process.stdout.write(`\n Config written to ~/.claude/mcp.json (fallback).\n` +
705
572
  ` If Claude Code doesn't pick it up, run:\n` +
706
- ` claude mcp add-json --scope user ${mcpServerName} '${jsonConfig}'\n` +
573
+ ` claude mcp add-json --scope user ${profile} '${jsonConfig}'\n` +
707
574
  ` Then start a new Claude Code session.\n`);
708
575
  }
709
576
  else {
710
577
  process.stdout.write(`\n Setup complete. Add this to your shell profile:\n` +
711
- ` export TACIT_TOKEN=<your-token>\n` +
578
+ ` export ${envVarName}=<your-token>\n` +
712
579
  `\n Then start a new Claude Code session to connect.\n`);
713
580
  }
714
- // Show all profiles that were written.
715
- if (writtenProfiles.length > 0) {
716
- process.stdout.write(`\n Profiles saved:\n`);
717
- for (const p of writtenProfiles) {
718
- const isDefault = activeWs ? p === activeWs.profileName : p === writtenProfiles[0];
719
- process.stdout.write(` ${isDefault ? '* ' : ' '}${p}\n`);
720
- }
721
- process.stdout.write(`\n Launch Claude Code with a workspace:\n` +
722
- ` tacit launch ${writtenProfiles[0]}` +
723
- (writtenProfiles.length > 1 ? ` # or: tacit launch ${writtenProfiles[1]}` : '') +
724
- `\n\n List profiles: tacit ls\n` +
725
- ` Set default: tacit use <name>\n`);
726
- }
727
581
  if (opts.smoke) {
728
582
  await runSmoke(apiUrl, token);
729
583
  // runSmoke calls process.exit internally; return here for type safety.
@@ -87,7 +87,10 @@ const FALLBACK_TEMPLATES = [
87
87
  { slug: 'coo_operator', display_name: 'COO Operator', description: 'Handles operational workflows.', icon: 'settings', default_capabilities: ['operations_management'], workflow_types: ['coo_operations'] },
88
88
  { slug: 'cmo_marketer', display_name: 'CMO Marketer', description: 'Manages marketing pipeline.', icon: 'megaphone', default_capabilities: ['marketing_pipeline'], workflow_types: ['cmo_marketing_pipeline'] },
89
89
  { slug: 'sales_executor', display_name: 'Sales Executor', description: 'Manages sales pipeline.', icon: 'trending_up', default_capabilities: ['pipeline_management'], workflow_types: ['sales_full_pipeline'] },
90
+ { slug: 'researcher', display_name: 'Research Analyst', description: 'Prepares research briefs, competitor analysis, SOTA surveys, and industry benchmarks.', icon: 'search', default_capabilities: ['search', 'recall', 'synthesize'], workflow_types: ['research_deep_dive'] },
90
91
  { slug: 'wiki_editor', display_name: 'Wiki Editor', description: 'Authors and maintains wiki content with structured classification and validation workflows.', icon: 'book', default_capabilities: ['wiki_authoring', 'content_classification', 'content_validation'], workflow_types: ['wiki_authoring'] },
91
92
  { slug: 'kb_curator', display_name: 'KB Curator', description: 'Curates knowledge base articles, collections, and source integrations.', icon: 'library', default_capabilities: ['kb_management', 'article_curation', 'source_administration'], workflow_types: ['kb_management'] },
93
+ { slug: 'cto_engineer', display_name: 'CTO Engineering', description: 'Engineering organization — routes to sub-execs for role creation and skill architecture.', icon: 'cpu', default_capabilities: ['engineering_routing', 'role_creation'], workflow_types: ['cto_engineering'] },
94
+ { slug: 'secretary', display_name: 'Secretary', description: 'Natural language Chronicle event management — logs decisions, meetings, action items, recalls history.', icon: 'calendar', default_capabilities: ['event_logging', 'event_recall', 'decision_tracking'], workflow_types: ['secretary_chronicle'] },
92
95
  { slug: 'lake_operator', display_name: 'Lake Operator', description: 'Manages data lake ingestion, classification, taxonomy, and structure proposals.', icon: 'database', default_capabilities: ['lake_ingestion', 'classification', 'taxonomy_management', 'structure_proposals'], workflow_types: ['lake_operations'] },
93
96
  ];