@tacitai/mcp-server 0.8.2 → 0.9.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.
@@ -8,6 +8,51 @@
8
8
  */
9
9
  import { z } from 'zod';
10
10
  import { createDefaultRegistry } from '../workflow-registry.js';
11
+ import { isUserWorkflowTypesActive, isWorkflowTypeActive } from '../flags.js';
12
+ // FEAT-272 D3: shared registry reference (set during tool registration)
13
+ let sharedRegistry;
14
+ // FEAT-272 D3: runtime user roles populated from DB-backed user types with role metadata.
15
+ // Keyed by workspaceId so HTTP-mode requests from different tenants stay isolated.
16
+ const userRolesByWorkspace = new Map();
17
+ function getUserRoles(workspaceId) {
18
+ if (!workspaceId)
19
+ return new Map();
20
+ let ws = userRolesByWorkspace.get(workspaceId);
21
+ if (!ws) {
22
+ ws = new Map();
23
+ userRolesByWorkspace.set(workspaceId, ws);
24
+ }
25
+ return ws;
26
+ }
27
+ export function registerUserRole(role, workspaceId) {
28
+ if (!workspaceId)
29
+ return;
30
+ const normalized = { ...role, keywords: role.keywords.map(k => k.toLowerCase().trim()) };
31
+ getUserRoles(workspaceId).set(normalized.slug, normalized);
32
+ }
33
+ export function removeUserRole(slug, workspaceId) {
34
+ if (!workspaceId)
35
+ return;
36
+ getUserRoles(workspaceId).delete(slug);
37
+ }
38
+ /** Case-insensitive word-level collision check against system + workspace user role keywords. Returns colliding keyword or null. */
39
+ export function checkKeywordCollision(keywords, workspaceId) {
40
+ const normalize = (kw) => kw.toLowerCase().trim();
41
+ const allExisting = new Set();
42
+ for (const route of ROLE_ROUTES) {
43
+ for (const kw of route.keywords)
44
+ allExisting.add(normalize(kw));
45
+ }
46
+ for (const route of getUserRoles(workspaceId).values()) {
47
+ for (const kw of route.keywords)
48
+ allExisting.add(normalize(kw));
49
+ }
50
+ for (const kw of keywords) {
51
+ if (allExisting.has(normalize(kw)))
52
+ return kw;
53
+ }
54
+ return null;
55
+ }
11
56
  export const ROLE_ROUTES = [
12
57
  {
13
58
  slug: 'general_manager',
@@ -54,8 +99,8 @@ export const ROLE_ROUTES = [
54
99
  {
55
100
  slug: 'researcher',
56
101
  present_as: 'Research Analyst',
57
- workflow_type: 'research_deep_dive',
58
- keywords: ['research', 'competitors', 'competitive analysis', 'market research', 'industry analysis', 'state of the art', 'benchmark'],
102
+ workflow_type: 'research_exec',
103
+ keywords: ['research', 'competitors', 'competitive analysis', 'market research', 'industry analysis', 'state of the art', 'benchmark', 'survey'],
59
104
  description: 'Prepares research briefs using tacit_research_prepare. For deep research topics, competitor analysis, and industry surveys.',
60
105
  },
61
106
  {
@@ -115,10 +160,21 @@ export const ROLE_ROUTES = [
115
160
  description: 'Manages career application pipeline — job search, campaign management, tailored resume and cover letter generation.',
116
161
  },
117
162
  ];
118
- export function matchRole(request) {
163
+ export function matchRole(request, workspaceId) {
119
164
  const lower = request.toLowerCase();
165
+ const wsRoles = getUserRoles(workspaceId);
166
+ // BUG-431: filing verbs co-occurring with research nouns route to GM, not researcher
167
+ const FILING_RESEARCH_RE = /\b(file|save|ingest|place|store)\b.*\b(research|report|assessment|analysis)\b/;
168
+ if (FILING_RESEARCH_RE.test(lower)) {
169
+ const gm = (isUserWorkflowTypesActive() ? [...ROLE_ROUTES, ...wsRoles.values()] : ROLE_ROUTES)
170
+ .find((r) => r.slug === 'general_manager');
171
+ return { primary: gm, alternatives: [] };
172
+ }
120
173
  const scores = [];
121
- for (const route of ROLE_ROUTES) {
174
+ const allRoutes = isUserWorkflowTypesActive()
175
+ ? [...ROLE_ROUTES, ...wsRoles.values()]
176
+ : ROLE_ROUTES;
177
+ for (const route of allRoutes) {
122
178
  let score = 0;
123
179
  for (const kw of route.keywords) {
124
180
  if (lower.includes(kw)) {
@@ -147,6 +203,28 @@ export function matchRole(request) {
147
203
  }
148
204
  /** BUG-418: "in my voice" requests route to the voice_compose overlay (ADR-212). */
149
205
  export const VOICE_INTENT_RE = /\b(in my voice|in my style|my writing voice)\b/i;
206
+ /**
207
+ * FEAT-271 W3: the GM role's content-removal intent routes to the gm_content_removal workflow type.
208
+ * Multi-word phrases only, so "remove from kb" (KB), "delete catalog item" (lake) and capture's
209
+ * remove/restore (SOP-10) keep their own routes. Checked before keyword scoring because removal
210
+ * requests often quote titles containing other roles' keywords (e.g. "proposal").
211
+ *
212
+ * Audit H1: a removal request must name content — a content noun or a quoted title — and must
213
+ * not name a person, member, membership, data source, connection or dossier (IAM, lake and
214
+ * pyramid own those). Use isContentRemovalIntent, not the scope pattern alone.
215
+ */
216
+ export const CONTENT_REMOVAL_INTENT_RE = /\b(remove\b.{0,80}\bfrom (the |this |my )?workspace|remove\b.{0,80}\beverywhere)\b/i;
217
+ /** Content nouns (or a quoted title) that make a "remove … from workspace" request a content removal. */
218
+ export const CONTENT_REMOVAL_NOUN_RE = /\b(artifacts?|documents?|docs?|files?|proposals?|(kb )?articles?|catalog items?|content|events?|links?)\b|"[^"]{2,}"|\u201c[^\u201d]{2,}\u201d|(^|\s)'[^']{2,}'(?=\s|$|[.,!?])/i;
219
+ /** People, membership, sources, connections and dossiers are not content removals. */
220
+ export const CONTENT_REMOVAL_EXCLUDE_RE = /\b(people|persons?|members?|membership|users?|teammates?|employees?|offboard\w*|him|her|data sources?|sources? connections?|connections?|connectors?|integrations?|dossiers?)\b|[\w.+-]+@[\w-]+\.[\w.]+/i;
221
+ /** "restore removal …" / "undo the removal" has its own script (list → restore → verify). */
222
+ export const RESTORE_REMOVAL_INTENT_RE = /\b(restore|undo|reverse) (a |the |this |that |my )?(content )?removal\b/i;
223
+ export function isContentRemovalIntent(request) {
224
+ return CONTENT_REMOVAL_INTENT_RE.test(request)
225
+ && CONTENT_REMOVAL_NOUN_RE.test(request)
226
+ && !CONTENT_REMOVAL_EXCLUDE_RE.test(request);
227
+ }
150
228
  /** The user is rewriting text they supplied, as opposed to asking for new material. */
151
229
  export const REWRITE_INTENT_RE = /\b(rewrit\w*|rephras\w*|revis\w*|edit(s|ed|ing)?|polish\w*|redo)\b/i;
152
230
  /** ADR-212: intent overlays. Adding one needs an amendment to the ADR. */
@@ -198,7 +276,16 @@ function overlayFirstTool(name) {
198
276
  return undefined;
199
277
  return def.prereqs.phases.flatMap((p) => p.requiredTools)[0];
200
278
  }
201
- function buildScript(role, workflowType = role.workflow_type) {
279
+ /** FEAT-271 W3 (audit M4): restoring a removal does not run footprint and starts no workflow. */
280
+ function buildRemovalRestoreScript() {
281
+ return [
282
+ '1. Call tacit_removal_list with removal_id and show the items: REVERSIBLE ones come back, IRREVERSIBLE ones do not. If you only have a title, call tacit_removal_list with state VERIFIED or EXECUTED and ask which request.',
283
+ '2. On explicit user approval (T3), call tacit_removal_restore with removal_id and confirm=true.',
284
+ '3. Call tacit_removal_verify with removal_id; it checks the restore because the request is RESTORED. Report the result.',
285
+ 'Do not call tacit_content_footprint for a restore; it would start a new removal workflow.',
286
+ ];
287
+ }
288
+ function buildScript(role, workflowType = role.workflow_type, workspaceId) {
202
289
  const steps = [];
203
290
  if (workflowType === 'voice_compose') {
204
291
  steps.push('1. Call tacit_voice_list_profiles and confirm a profile with voice_active true exists. If none exists, tell the user a voice profile needs 3+ samples and stop.');
@@ -207,6 +294,16 @@ function buildScript(role, workflowType = role.workflow_type) {
207
294
  steps.push('4. If the result has voice_match_degraded true, or the tool returns an error, show the user and stop for review. Never draft text yourself and claim it matches their voice.');
208
295
  return steps;
209
296
  }
297
+ if (workflowType === 'gm_content_removal') {
298
+ steps.push('1. Call tacit_content_footprint with the content id (kind artifact, catalog, data_object or chronicle_event). A successful call starts the gm_content_removal workflow; its guidance shows the instanceId. If you only have a title, find the id with tacit_search or tacit_artifact_list first.');
299
+ steps.push('2. Show the user every footprint item grouped by kind with its reversibility, the MANUAL_REQUIRED (SOURCE lake) items, similar_not_included, and which MCP server/workspace you are using. Then tacit_workflow_advance with the instanceId shown in the guidance.');
300
+ steps.push('3. Call tacit_removal_propose with root_kind, root_id and a distinctive verify_phrase (this binds the workflow to the new removal_id). Then tacit_workflow_advance with the instanceId shown in the guidance.');
301
+ steps.push('4. WAIT for the user to type the exact title. Call tacit_removal_approve with removal_id, confirm=true and typed_title. Then tacit_workflow_advance with the instanceId shown in the guidance.');
302
+ steps.push('5. Call tacit_removal_execute with confirm=true; poll tacit_removal_list with removal_id until EXECUTED or FAILED (retry=true resumes). Then tacit_workflow_advance with the instanceId shown in the guidance.');
303
+ steps.push('6. Call tacit_removal_verify and report VERIFIED or the remaining copies. Then tacit_workflow_advance with the instanceId shown in the guidance to finish. To undo later, ask to "restore removal <removal_id>".');
304
+ steps.push('Never use SQL or raw delete tools (tacit_artifact_delete, tacit_chronicle_exclude_event, tacit_lake_delete_catalog_item) for a removal; they are refused while the workflow is active.');
305
+ return steps;
306
+ }
210
307
  if (role.workflow_type === 'cto_engineering') {
211
308
  steps.push('CTO routes to the Agentic Engineering Exec. Call tacit_agent_delegate with role_slug="cto_engineer" and describe the engineering request.');
212
309
  steps.push('For new role creation: the AE Exec workflow guides through domain analysis → enforcement type selection → registration → verification.');
@@ -220,7 +317,7 @@ function buildScript(role, workflowType = role.workflow_type) {
220
317
  steps.push('To save a link/URL: call tacit_capture_save with { url, note, tags }. This saves to the link library (MV-1537), not Chronicle.');
221
318
  return steps;
222
319
  }
223
- if (role.workflow_type === 'research_deep_dive' && role.slug === 'researcher') {
320
+ if (role.workflow_type === 'research_exec' && role.slug === 'researcher') {
224
321
  steps.push('Call tacit_research_prepare with the research topic instead of tacit_agent_delegate.');
225
322
  steps.push('Review the prepared context, then call tacit_research_launch to execute the research.');
226
323
  steps.push('Check tacit_workflow_prereqs if a tool returns a workflow block — it shows required prior steps.');
@@ -232,6 +329,7 @@ function buildScript(role, workflowType = role.workflow_type) {
232
329
  steps.push('SOP-14 (career check first): if the request names a job, application, resume, or cover letter, call tacit_career_list_jobs to find the job card. If matched, propose attaching; on approval use tacit_career_attach_material directly (ADR-210 exempts career materials from lake-first). If no match or career not enabled, fall through to normal filing.');
233
330
  steps.push('For link saves (URL/bookmark): call tacit_capture_save with { url, note, tags } — this saves to the link library (MV-1537), NOT the data lake.');
234
331
  steps.push('For content placement (non-link): call tacit_gm_ingest first, then tacit_gm_approve to confirm placement.');
332
+ steps.push('FEAT-273 research routing: if the content is research (technology assessment, competitive analysis, survey, experiment report, academic paper), pass classification_hints: { content_type: "research.<kind>" } where <kind> is one of: technology_assessment, competitive, survey, paper, experiment. The backend auto-detects collection, audited gate, and pyramid exclusion from this hint.');
235
333
  }
236
334
  else if (role.workflow_type === 'wiki_authoring') {
237
335
  steps.push('Wiki writes require approval. The workflow enforces: draft → review → approve → publish.');
@@ -258,27 +356,59 @@ function buildScript(role, workflowType = role.workflow_type) {
258
356
  steps.push('Move jobs through pipeline stages: tacit_career_move_job (guarded statuses require confirm_user_instruction).');
259
357
  }
260
358
  steps.push('Check tacit_workflow_prereqs if a tool returns a workflow block — it shows required prior steps.');
359
+ // FEAT-272 D1: fall through to user type's scriptTemplate when no hardcoded handler matched
360
+ if (steps.length <= 3 && sharedRegistry) {
361
+ const def = sharedRegistry.get(workflowType, workspaceId);
362
+ if (def?.scriptTemplate) {
363
+ return def.scriptTemplate.split('\n').filter(Boolean);
364
+ }
365
+ }
261
366
  return steps;
262
367
  }
263
368
  /** Pure routing: role from role_hint or matchRole; workflow_type overridden to voice_compose on voice intent. */
264
- export function routeRequest(request, roleHint) {
369
+ export function routeRequest(request, roleHint, workspaceId) {
265
370
  let primary;
266
371
  let alternatives = [];
267
372
  let defaulted = false;
373
+ const wsRoles = getUserRoles(workspaceId);
268
374
  if (roleHint) {
269
- const found = ROLE_ROUTES.find((r) => r.slug === roleHint);
375
+ let found = ROLE_ROUTES.find((r) => r.slug === roleHint);
376
+ if (!found && isUserWorkflowTypesActive()) {
377
+ found = wsRoles.get(roleHint);
378
+ }
270
379
  if (!found) {
271
- const slugs = ROLE_ROUTES.map((r) => r.slug).join(', ');
272
- return { error: `Unknown role_hint: ${roleHint}. Available: ${slugs}` };
380
+ const allSlugs = [...ROLE_ROUTES.map((r) => r.slug), ...wsRoles.keys()];
381
+ return { error: `Unknown role_hint: ${roleHint}. Available: ${allSlugs.join(', ')}` };
273
382
  }
274
383
  primary = found;
275
384
  }
276
385
  else {
277
- const match = matchRole(request);
386
+ const match = matchRole(request, workspaceId);
278
387
  primary = match.primary;
279
388
  alternatives = match.alternatives;
280
389
  defaulted = match.defaulted === true;
281
390
  }
391
+ // FEAT-271 W3: removal intent belongs to the GM role and its gm_content_removal type
392
+ // (only while FEATURE_CONTENT_REMOVAL is on; keyword-scored alternatives are kept).
393
+ const removalRoutable = (!roleHint || roleHint === 'general_manager') && isWorkflowTypeActive('gm_content_removal');
394
+ if (removalRoutable && (RESTORE_REMOVAL_INTENT_RE.test(request) || isContentRemovalIntent(request))) {
395
+ const gm = ROLE_ROUTES.find((r) => r.slug === 'general_manager');
396
+ const restore = RESTORE_REMOVAL_INTENT_RE.test(request);
397
+ // The keyword-scored match (and its runners-up) stay visible as alternatives.
398
+ const scored = roleHint ? [] : [{ role_slug: primary.slug, reason: primary.description }, ...alternatives];
399
+ const alts = scored.filter((a) => a.role_slug !== gm.slug).slice(0, 3);
400
+ return {
401
+ role_slug: gm.slug,
402
+ present_as: gm.present_as,
403
+ workflow_type: 'gm_content_removal',
404
+ description: restore
405
+ ? 'Restores the REVERSIBLE items of an earlier content removal by removal id (list → restore → verify). IRREVERSIBLE items stay removed.'
406
+ : 'Removes one piece of content from everywhere in the workspace through the approval-gated, verifiable removal workflow (footprint → propose → approve → execute → verify; restore for reversible items).',
407
+ first_tool: restore ? 'tacit_removal_list' : 'tacit_content_footprint',
408
+ script: restore ? buildRemovalRestoreScript() : buildScript(gm, 'gm_content_removal', workspaceId),
409
+ ...(alts.length > 0 ? { alternatives: alts } : {}),
410
+ };
411
+ }
282
412
  // ADR-212 exception: no keyword matched, so GM is only the triage default, not a chosen gated role.
283
413
  const { overlay, skipped } = applyOverlay(request, primary.workflow_type, defaulted);
284
414
  const workflowType = overlay ? overlay.name : primary.workflow_type;
@@ -290,18 +420,21 @@ export function routeRequest(request, roleHint) {
290
420
  workflow_type: workflowType,
291
421
  description: primary.description,
292
422
  first_tool: firstTool,
293
- script: buildScript(primary, workflowType),
423
+ script: buildScript(primary, workflowType, workspaceId),
294
424
  ...(skipped ? { overlay_skipped: skipped } : {}),
295
425
  ...(alternatives.length > 0 ? { alternatives } : {}),
296
426
  };
297
427
  }
298
- export function registerExecRouteTool(server) {
428
+ export function registerExecRouteTool(server, registry, getClient) {
429
+ if (registry)
430
+ sharedRegistry = registry;
299
431
  server.tool('tacit_exec_route', 'Route a business request to the right executive role. Returns the role, workflow type, and a step-by-step script of tools to call. Use this as the first step for any business request.', {
300
432
  request: z.string().min(1).describe('Natural language description of what you want to do'),
301
433
  role_hint: z.string().optional().describe('If you already know the role slug, pass it here to skip matching'),
302
434
  }, async (args) => {
303
435
  const { request, role_hint } = args;
304
- const result = routeRequest(request, role_hint);
436
+ const wsId = getClient ? (await getClient()).workspaceId ?? undefined : undefined;
437
+ const result = routeRequest(request, role_hint, wsId);
305
438
  if ('error' in result) {
306
439
  return { content: [{ type: 'text', text: JSON.stringify(result) }], isError: true };
307
440
  }
@@ -51,6 +51,7 @@ export declare const gmIngestInputSchema: z.ZodObject<{
51
51
  domain?: string | undefined;
52
52
  content_type?: string | undefined;
53
53
  }>>;
54
+ file_name: z.ZodOptional<z.ZodString>;
54
55
  cross_reference: z.ZodOptional<z.ZodBoolean>;
55
56
  }, "strip", z.ZodTypeAny, {
56
57
  title: string;
@@ -62,6 +63,7 @@ export declare const gmIngestInputSchema: z.ZodObject<{
62
63
  domain?: string | undefined;
63
64
  content_type?: string | undefined;
64
65
  } | undefined;
66
+ file_name?: string | undefined;
65
67
  cross_reference?: boolean | undefined;
66
68
  }, {
67
69
  title: string;
@@ -73,6 +75,7 @@ export declare const gmIngestInputSchema: z.ZodObject<{
73
75
  domain?: string | undefined;
74
76
  content_type?: string | undefined;
75
77
  } | undefined;
78
+ file_name?: string | undefined;
76
79
  cross_reference?: boolean | undefined;
77
80
  }>;
78
81
  export type GmIngestInput = z.infer<typeof gmIngestInputSchema>;
@@ -114,6 +117,10 @@ export declare const GM_INGEST_TOOL_DEF: {
114
117
  };
115
118
  description: string;
116
119
  };
120
+ file_name: {
121
+ type: string;
122
+ description: string;
123
+ };
117
124
  cross_reference: {
118
125
  type: string;
119
126
  description: string;
package/dist/tools/gm.js CHANGED
@@ -31,6 +31,9 @@ function apiErrorResult(err, toolName) {
31
31
  export const GM_INGEST_NEXT_STEP = 'NEXT STEP: nothing has been placed yet. Tell the user in plain language what this was classified as and offer surface options ' +
32
32
  '(workspace structure, knowledge base, both, or data lake). Lead with the suggested_surface but let the user choose. ' +
33
33
  'If suggested_surface is "lake", say it is saved in the data lake and ask whether to file it in the workspace structure or the knowledge base; do not pick one yourself. ' +
34
+ 'RESEARCH ROUTING (FEAT-273): if the response includes research_kind, this is research content with automated placement rules. ' +
35
+ 'If audited is true, propose KB DRAFT in the suggested_collection_name. If audited is false, default to lake-only but let the user override to KB. ' +
36
+ 'Research content is never proposed for pyramid unless the operator explicitly named a decision_program in the ingest call. ' +
34
37
  'When the user picks a surface (e.g. "pyramid", "KB"), that is a SURFACE CHOICE, not a location approval. You must THEN drill down ' +
35
38
  '(list portfolios → programs → dossiers for pyramid, or list collections for KB), propose the SPECIFIC location ' +
36
39
  '(e.g. "I\'d file this under Product → GoodOps Site → GoodOps Site v1. Approve?"), and wait for the user to approve THAT location in a new message. ' +
@@ -182,6 +185,7 @@ export const gmIngestInputSchema = z.object({
182
185
  domain: z.string().optional(),
183
186
  content_type: z.string().optional(),
184
187
  }).optional().describe('Optional hints for the classifier'),
188
+ file_name: z.string().optional().describe('Original filename basename, used by the classifier for extension heuristics'),
185
189
  cross_reference: z.boolean().optional().describe('Set true when the user wants the content placed on two surfaces (pyramid AND KB) — chains a second placement cycle after the first completes'),
186
190
  });
187
191
  export const GM_INGEST_TOOL_DEF = {
@@ -209,6 +213,7 @@ export const GM_INGEST_TOOL_DEF = {
209
213
  },
210
214
  description: 'Optional hints for the classifier',
211
215
  },
216
+ file_name: { type: 'string', description: 'Original filename basename for classifier' },
212
217
  cross_reference: {
213
218
  type: 'boolean',
214
219
  description: 'Set true when the user wants the content placed on two surfaces (pyramid AND KB) — chains a second placement cycle after the first completes',
@@ -250,6 +255,12 @@ export function buildGmIngestRequest(client, input) {
250
255
  body['content_type'] = input.content_type;
251
256
  if (input.classification_hints !== undefined)
252
257
  body['classification_hints'] = input.classification_hints;
258
+ if (hasFile && input.file_path) {
259
+ body['file_name'] = input.file_path.split('/').pop() || input.file_path;
260
+ }
261
+ if (input.file_name && !body['file_name']) {
262
+ body['file_name'] = input.file_name;
263
+ }
253
264
  // cross_reference is deliberately NOT sent: it is an MCP-layer workflow flag
254
265
  // (FEAT-249) consumed by the WorkflowGate in registerGmTools, not a backend field.
255
266
  const result = (await client.post('/api/v1/gm/ingest', body));
@@ -92,6 +92,7 @@ export declare const moveInputSchema: z.ZodObject<{
92
92
  } | undefined;
93
93
  }>;
94
94
  }, "strip", z.ZodTypeAny, {
95
+ artifact_id: string;
95
96
  placement: {
96
97
  pyramid?: {
97
98
  portfolio_id?: string | undefined;
@@ -107,8 +108,8 @@ export declare const moveInputSchema: z.ZodObject<{
107
108
  })[];
108
109
  } | undefined;
109
110
  };
110
- artifact_id: string;
111
111
  }, {
112
+ artifact_id: string;
112
113
  placement: {
113
114
  pyramid?: {
114
115
  portfolio_id?: string | undefined;
@@ -124,7 +125,6 @@ export declare const moveInputSchema: z.ZodObject<{
124
125
  })[];
125
126
  } | undefined;
126
127
  };
127
- artifact_id: string;
128
128
  }>;
129
129
  export type MoveInput = z.infer<typeof moveInputSchema>;
130
130
  export declare const MOVE_TOOL_DEF: {
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Compile-time tool classification. Governs which tools may be called over HTTPS.
3
- * Partition: 6 stdio_only + 26 admin_only + 2 gate_only + 158 https = 192.
3
+ * Partition: 6 stdio_only + 26 admin_only + 2 gate_only + 181 https = 215.
4
4
  */
5
5
  export type ToolTransport = 'https' | 'stdio_only' | 'admin_only' | 'gate_only';
6
6
  export type ToolClass = 'read' | 'write' | 'admin' | 'dispatch';
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Compile-time tool classification. Governs which tools may be called over HTTPS.
3
- * Partition: 6 stdio_only + 26 admin_only + 2 gate_only + 158 https = 192.
3
+ * Partition: 6 stdio_only + 26 admin_only + 2 gate_only + 181 https = 215.
4
4
  */
5
5
  const STDIO_ONLY = [
6
6
  'tacit_ingest_file',
@@ -128,6 +128,9 @@ const READ_TOOLS = [
128
128
  'tacit_career_list_materials',
129
129
  'tacit_career_search_status',
130
130
  'tacit_career_generate_status',
131
+ 'tacit_content_footprint',
132
+ 'tacit_removal_verify',
133
+ 'tacit_removal_list',
131
134
  ];
132
135
  const DISPATCH_TOOLS = [
133
136
  'tacit_agent_delegate',
@@ -149,6 +152,7 @@ const WRITE_TOOLS = [
149
152
  'tacit_artifact_revise',
150
153
  'tacit_artifact_update',
151
154
  'tacit_connector_write_back',
155
+ 'tacit_chronicle_exclude_event',
152
156
  'tacit_create_event',
153
157
  'tacit_create_person',
154
158
  'tacit_edit_deliverable',
@@ -225,6 +229,10 @@ const WRITE_TOOLS = [
225
229
  'tacit_career_attach_material',
226
230
  'tacit_career_detach_material',
227
231
  'tacit_career_seed_pyramid',
232
+ 'tacit_removal_propose',
233
+ 'tacit_removal_approve',
234
+ 'tacit_removal_execute',
235
+ 'tacit_removal_restore',
228
236
  ];
229
237
  function build() {
230
238
  const map = new Map();
@@ -251,8 +259,8 @@ function build() {
251
259
  if (!exclusive.has(n))
252
260
  add(n, classOf(n), 'https', false);
253
261
  }
254
- if (map.size !== 207)
255
- throw new Error(`tool registry expected 207 tools, got ${map.size}`);
262
+ if (map.size !== 215)
263
+ throw new Error(`tool registry expected 215 tools, got ${map.size}`);
256
264
  return map;
257
265
  }
258
266
  export const TOOL_REGISTRY = build();
@@ -8,11 +8,15 @@
8
8
  import { z } from 'zod';
9
9
  import { isUserWorkflowTypesActive } from '../flags.js';
10
10
  import { validateUserTypeDef, SYSTEM_RESERVED_TYPE_NAMES } from '../workflow-type-schema.js';
11
+ import { registerUserRole, checkKeywordCollision } from './exec-route.js';
11
12
  const listSchema = z.object({});
12
13
  const createSchema = z.object({
13
14
  name: z.string().describe('Type name (lowercase, 3-64 chars, a-z0-9_)'),
14
15
  definition: z.record(z.unknown()).describe('Full workflow type definition (prereqs, failDirection, etc.)'),
15
16
  base_type: z.string().optional().describe('System type name to fork from (merges base with overrides)'),
17
+ role_slug: z.string().optional().describe('Exec routing slug (all-or-none with role_keywords + role_description)'),
18
+ role_keywords: z.array(z.string()).optional().describe('Keywords for matchRole() (all-or-none with role_slug + role_description)'),
19
+ role_description: z.string().optional().describe('Human-readable role description (all-or-none with role_slug + role_keywords)'),
16
20
  });
17
21
  const updateSchema = z.object({
18
22
  id: z.string().uuid().describe('UUID of the user type to update'),
@@ -32,6 +36,12 @@ function rowToTypeDef(row) {
32
36
  entryTool: def.entryTool ?? null,
33
37
  failDirection: def.failDirection ?? 'open',
34
38
  sharedToolPolicy: def.sharedToolPolicy ?? 'passthrough',
39
+ // FEAT-271: tool denial and phase-order enforcement are system-type only.
40
+ denyWhileActive: undefined,
41
+ enforcePhaseOrder: undefined,
42
+ startOnSuccess: undefined,
43
+ bindMetadataKey: undefined,
44
+ recordOnSuccess: undefined,
35
45
  };
36
46
  }
37
47
  export function registerWorkflowTypeTools(server, getClient, registry) {
@@ -55,15 +65,28 @@ export function registerWorkflowTypeTools(server, getClient, registry) {
55
65
  const result = await client.get('/api/v1/workflow-types', {
56
66
  workspace_id: workspaceId,
57
67
  });
58
- const userTypes = (result.types ?? []).map((row) => ({
59
- id: row.id,
60
- name: row.name,
61
- is_system: false,
62
- base_type: row.base_type,
63
- version: row.version,
64
- created_at: row.created_at,
65
- updated_at: row.updated_at,
66
- }));
68
+ const userTypes = (result.types ?? []).map((row) => {
69
+ // FEAT-272 D3: register role routes from DB-stored user types on list (covers startup)
70
+ if (row.role_slug && row.role_keywords && row.role_description) {
71
+ registerUserRole({
72
+ slug: row.role_slug,
73
+ present_as: row.role_description,
74
+ workflow_type: row.name,
75
+ keywords: row.role_keywords,
76
+ description: row.role_description,
77
+ }, workspaceId);
78
+ }
79
+ return {
80
+ id: row.id,
81
+ name: row.name,
82
+ is_system: false,
83
+ base_type: row.base_type,
84
+ version: row.version,
85
+ created_at: row.created_at,
86
+ updated_at: row.updated_at,
87
+ role_slug: row.role_slug,
88
+ };
89
+ });
67
90
  return jsonResult({ types: [...systemTypes, ...userTypes] });
68
91
  }
69
92
  catch {
@@ -78,12 +101,35 @@ export function registerWorkflowTypeTools(server, getClient, registry) {
78
101
  if (!parsed.success) {
79
102
  return jsonResult({ error: 'invalid_input', detail: parsed.error.message }, true);
80
103
  }
81
- const { name, definition, base_type } = parsed.data;
104
+ const { name, definition, base_type, role_slug, role_keywords, role_description } = parsed.data;
82
105
  const client = await getClient();
83
106
  const workspaceId = client.workspaceId;
84
107
  if (!workspaceId) {
85
108
  return jsonResult({ error: 'no_workspace', detail: 'No workspace context available' }, true);
86
109
  }
110
+ // FEAT-272 D4: all-or-none role fields
111
+ const hasAny = role_slug !== undefined || role_keywords !== undefined || role_description !== undefined;
112
+ const hasAll = role_slug !== undefined && role_keywords !== undefined && role_description !== undefined;
113
+ if (hasAny && !hasAll) {
114
+ return jsonResult({ error: 'incomplete_role', detail: 'role_slug, role_keywords, and role_description must all be provided or all omitted' }, true);
115
+ }
116
+ // FEAT-272: validate keywords (non-empty, min 2 chars trimmed, max 20 keywords)
117
+ if (role_keywords) {
118
+ if (role_keywords.length > 20) {
119
+ return jsonResult({ error: 'invalid_input', detail: 'role_keywords must have at most 20 entries' }, true);
120
+ }
121
+ const invalid = role_keywords.find((k) => k.trim().length < 2);
122
+ if (invalid !== undefined) {
123
+ return jsonResult({ error: 'invalid_input', detail: 'Each role_keyword must be at least 2 characters after trimming' }, true);
124
+ }
125
+ }
126
+ // FEAT-272 D3: keyword collision check
127
+ if (role_keywords && role_keywords.length > 0) {
128
+ const collision = checkKeywordCollision(role_keywords, workspaceId);
129
+ if (collision) {
130
+ return jsonResult({ error: 'keyword_collision', detail: `Keyword '${collision}' conflicts with an existing role` }, true);
131
+ }
132
+ }
87
133
  let mergedDef = { ...definition, name };
88
134
  if (base_type) {
89
135
  if (!SYSTEM_RESERVED_TYPE_NAMES.includes(base_type)) {
@@ -106,13 +152,27 @@ export function registerWorkflowTypeTools(server, getClient, registry) {
106
152
  name,
107
153
  definition: mergedDef,
108
154
  base_type: base_type ?? null,
155
+ role_slug: role_slug ?? null,
156
+ role_keywords: role_keywords ?? null,
157
+ role_description: role_description ?? null,
109
158
  });
110
159
  registry.registerUserType(rowToTypeDef(result), workspaceId);
160
+ // FEAT-272 D3: register the role route if role metadata was provided
161
+ if (result.role_slug && result.role_keywords && result.role_description) {
162
+ registerUserRole({
163
+ slug: result.role_slug,
164
+ present_as: result.role_description,
165
+ workflow_type: result.name,
166
+ keywords: result.role_keywords,
167
+ description: result.role_description,
168
+ }, workspaceId);
169
+ }
111
170
  return jsonResult({
112
171
  id: result.id,
113
172
  name: result.name,
114
173
  version: result.version,
115
174
  created_at: result.created_at,
175
+ role_slug: result.role_slug,
116
176
  });
117
177
  }
118
178
  catch (err) {
@@ -124,7 +184,11 @@ export function registerWorkflowTypeTools(server, getClient, registry) {
124
184
  return jsonResult({ error: 'reserved_tool', detail: msg }, true);
125
185
  }
126
186
  if (msg.includes('DUPLICATE_TYPE_NAME') || msg.includes('duplicate key')) {
127
- return jsonResult({ error: 'duplicate_type_name', detail: `Type '${name}' already exists in this workspace` }, true);
187
+ const isRoleSlug = msg.includes('role_slug_ws_uniq') || (role_slug && msg.includes(role_slug));
188
+ const detail = isRoleSlug
189
+ ? `Role slug '${role_slug}' already exists in this workspace`
190
+ : `Type '${name}' already exists in this workspace`;
191
+ return jsonResult({ error: isRoleSlug ? 'duplicate_role_slug' : 'duplicate_type_name', detail }, true);
128
192
  }
129
193
  return jsonResult({ error: 'backend_unreachable', detail: msg }, true);
130
194
  }
@@ -161,11 +225,22 @@ export function registerWorkflowTypeTools(server, getClient, registry) {
161
225
  definition: defWithPolicy,
162
226
  });
163
227
  registry.registerUserType(rowToTypeDef(result), workspaceId);
228
+ // FEAT-272 D3: re-register the role route on update (definition may affect scriptTemplate/guidanceText)
229
+ if (result.role_slug && result.role_keywords && result.role_description) {
230
+ registerUserRole({
231
+ slug: result.role_slug,
232
+ present_as: result.role_description,
233
+ workflow_type: result.name,
234
+ keywords: result.role_keywords,
235
+ description: result.role_description,
236
+ }, workspaceId);
237
+ }
164
238
  return jsonResult({
165
239
  id: result.id,
166
240
  name: result.name,
167
241
  version: result.version,
168
242
  updated_at: result.updated_at,
243
+ role_slug: result.role_slug,
169
244
  });
170
245
  }
171
246
  catch (err) {
@@ -6,4 +6,13 @@
6
6
  * only be attached to one transport at a time.
7
7
  */
8
8
  import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
9
+ import { type AuthResult } from './auth.js';
10
+ /**
11
+ * Workflow-gate / autonomy principal for an authenticated HTTP request (FEAT-271 M1).
12
+ * OAuth principals are scoped by workspace (`${user_email}:${workspace_id}`) so the same
13
+ * user in two workspaces never shares gate state; bearer tokens are already per workspace.
14
+ */
15
+ export declare function httpPrincipalOf(auth: Extract<AuthResult, {
16
+ type: 'oauth' | 'bearer';
17
+ }>): string;
9
18
  export declare function startHttpTransport(server: McpServer): Promise<void>;
package/dist/transport.js CHANGED
@@ -74,6 +74,18 @@ function getClientIp(req) {
74
74
  ?? req.socket.remoteAddress
75
75
  ?? 'unknown';
76
76
  }
77
+ /**
78
+ * Workflow-gate / autonomy principal for an authenticated HTTP request (FEAT-271 M1).
79
+ * OAuth principals are scoped by workspace (`${user_email}:${workspace_id}`) so the same
80
+ * user in two workspaces never shares gate state; bearer tokens are already per workspace.
81
+ */
82
+ export function httpPrincipalOf(auth) {
83
+ if (auth.type === 'oauth') {
84
+ const { user_email, workspace_id } = auth.info;
85
+ return workspace_id ? `${user_email}:${workspace_id}` : user_email;
86
+ }
87
+ return createHash('sha256').update(auth.token).digest('hex').slice(0, 16);
88
+ }
77
89
  export async function startHttpTransport(server) {
78
90
  const port = Number.parseInt(process.env['MCP_HTTPS_PORT'] ?? '8319', 10);
79
91
  const apiUrl = (process.env['TACIT_API_URL'] ?? 'http://127.0.0.1:7473').replace(/\/$/, '');
@@ -166,9 +178,7 @@ export async function startHttpTransport(server) {
166
178
  return;
167
179
  }
168
180
  const requestToken = auth.type === 'oauth' ? auth.info.tacit_token : auth.token;
169
- const principal = auth.type === 'oauth'
170
- ? auth.info.user_email
171
- : createHash('sha256').update(auth.token).digest('hex').slice(0, 16);
181
+ const principal = httpPrincipalOf(auth);
172
182
  const run = async () => {
173
183
  const transport = new StreamableHTTPServerTransport({
174
184
  sessionIdGenerator: undefined,