@tacitai/mcp-server 0.8.1 → 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.
@@ -65,6 +65,8 @@ export declare function run(command: string, args: string[], opts?: {
65
65
  timeoutMs?: number;
66
66
  }): Promise<RunResult>;
67
67
  export declare function findOnPath(command: string, env?: NodeJS.ProcessEnv): string | null;
68
+ /** True when a resolved path lives inside an npx ephemeral install (`~/.npm/_npx/`). */
69
+ export declare function isNpxEphemeral(resolved: string): boolean;
68
70
  export type RegisterStatus = 'added' | 'already' | 'foreign' | 'no-claude' | 'failed';
69
71
  export interface RegisterResult {
70
72
  status: RegisterStatus;
@@ -146,6 +146,11 @@ export function findOnPath(command, env = process.env) {
146
146
  }
147
147
  return null;
148
148
  }
149
+ /** True when a resolved path lives inside an npx ephemeral install (`~/.npm/_npx/`). */
150
+ export function isNpxEphemeral(resolved) {
151
+ const sep = path.sep;
152
+ return resolved.includes(`${sep}_npx${sep}`) || resolved.includes('/_npx/');
153
+ }
149
154
  function brief(r) {
150
155
  return (r.stderr || r.stdout || `exit ${String(r.code)}`).trim().split('\n').slice(-2).join(' ').slice(0, 300);
151
156
  }
@@ -294,10 +299,6 @@ export async function scanLegacyEntries(folders, cwd) {
294
299
  continue;
295
300
  for (const [name, e] of Object.entries(servers(json['mcpServers'])))
296
301
  push(toLegacy('user', folder, folder.configFile, name, e));
297
- for (const [projectPath, p] of Object.entries(servers(json['projects']))) {
298
- for (const [name, e] of Object.entries(servers(p?.['mcpServers'])))
299
- push(toLegacy('local', folder, folder.configFile, name, e, projectPath));
300
- }
301
302
  }
302
303
  const home = os.homedir();
303
304
  const active = folders[0] ?? folderFor(null);
package/dist/flags.js CHANGED
@@ -16,6 +16,7 @@ const WORKFLOW_TYPE_FLAGS = {
16
16
  wiki_authoring: 'FEATURE_WORKFLOW_WIKI',
17
17
  kb_management: 'FEATURE_WORKFLOW_KB',
18
18
  lake_operations: 'FEATURE_WORKFLOW_LAKE',
19
+ gm_content_removal: 'FEATURE_CONTENT_REMOVAL',
19
20
  };
20
21
  export function isWorkflowTypeActive(typeName) {
21
22
  const envVar = WORKFLOW_TYPE_FLAGS[typeName];
package/dist/index.js CHANGED
@@ -68,6 +68,7 @@ import { registerWorkflowPrereqsTool } from './tools/workflow-prereqs.js';
68
68
  import { registerCmoTools } from './tools/cmo.js';
69
69
  import { registerSecretaryTools } from './tools/secretary.js';
70
70
  import { registerIamTools, registerSecurityTools } from './tools/iam.js';
71
+ import { registerContentRemovalTools, CONTENT_REMOVAL_GUIDANCE, fillGuidance } from './tools/content-removal.js';
71
72
  import { registerPrompts } from './prompts.js';
72
73
  import { getRequestPrincipal } from './client.js';
73
74
  import { ensureAutonomy } from './autonomy.js';
@@ -79,11 +80,20 @@ import { WorkflowGate } from './workflow-gate.js';
79
80
  import { WorkflowPersistence } from './workflow-persistence.js';
80
81
  import { createDefaultRegistry } from './workflow-registry.js';
81
82
  // FEAT-249 / MV-1539: one WorkflowGate per server process — workflow state keyed
82
- // by request principal (stdio shares the single '__stdio__' slot). Never store gate
83
+ // by request principal (stdio: '__stdio__:<active workspace>'). Never store gate
83
84
  // state inside the per-request AsyncLocalStorage context; see workflow-gate.ts.
84
85
  const gate = new WorkflowGate({
85
86
  registry: createDefaultRegistry(),
86
87
  persistence: new WorkflowPersistence(async () => getModuleClient()),
88
+ // FEAT-271 M1: stdio gate state is per active workspace (tacit_switch_workspace moves the key).
89
+ stdioWorkspace: () => {
90
+ try {
91
+ return getModuleClient().workspaceId || null;
92
+ }
93
+ catch {
94
+ return null;
95
+ }
96
+ },
87
97
  onEvent: async (event) => {
88
98
  try {
89
99
  const client = await getModuleClient();
@@ -124,7 +134,7 @@ const GUIDANCE_MAP = {
124
134
  RESEARCH_PLAN_APPROVAL: 'Research: awaiting plan approval before launching.',
125
135
  RESEARCH_DISPATCH: 'Research: dispatch phase. Call tacit_research_launch to start execution.',
126
136
  RESEARCH_SYNTHESIS: 'Research: synthesis in progress.',
127
- RESEARCH_PLACEMENT: 'Research: placement phase. Call tacit_research_place to file the results.',
137
+ RESEARCH_HANDOFF: 'Research: handoff phase. Results route to GM for lake-first placement.',
128
138
  RESEARCH_EXEC: 'Research workflow active. Follow: prepare → approve → launch → synthesize → place.',
129
139
  WIKI_AUTHORING: 'Wiki authoring active. Follow: classify → validate → author. Write/override require approval.',
130
140
  KB_MANAGEMENT: 'KB management active. Browse the KB structure first, then curate content.',
@@ -137,11 +147,17 @@ const GUIDANCE_MAP = {
137
147
  VOICE_GROUND: 'Voice composition: assemble the grounded source text yourself (facts, draft, letter). Do not invent facts.',
138
148
  VOICE_COMPOSE_STEP: 'Voice composition: call tacit_compose_in_voice with the grounded text in content and the instruction in query.',
139
149
  VOICE_VERIFY: 'Voice composition: if voice_match_degraded is true, show the user and stop for review. Never claim a match you did not get.',
150
+ // FEAT-271 W3: removal guidance carries {instanceId}, filled in by fillGuidance below.
151
+ ...CONTENT_REMOVAL_GUIDANCE,
140
152
  };
141
- function expandGuidance(raw, _typeName, phase) {
153
+ function expandGuidance(raw, typeName, phase, workspaceId) {
142
154
  const expanded = GUIDANCE_MAP[raw];
143
155
  if (expanded)
144
156
  return expanded;
157
+ // FEAT-272 D2: fall through to user type's guidanceText from the registry
158
+ const def = gate.getRegistry().get(typeName, workspaceId);
159
+ if (def?.guidanceText)
160
+ return def.guidanceText;
145
161
  if (phase)
146
162
  return `Workflow phase: ${phase}. Check tacit_workflow_prereqs for required next steps.`;
147
163
  return `Active workflow. Check tacit_workflow_prereqs for required next steps.`;
@@ -169,15 +185,22 @@ function installPreCallHook(server) {
169
185
  if (autonomyBlock) {
170
186
  return { content: [{ type: 'text', text: JSON.stringify(autonomyBlock) }], isError: true };
171
187
  }
172
- gate.recordCallForAll(principal, toolName);
188
+ // FEAT-271 W3: deny-while-active and phase order, before the call is recorded or routed.
189
+ const toolArgs = (callArgs[0] && typeof callArgs[0] === 'object' ? callArgs[0] : undefined);
190
+ const denied = gate.checkDeniedWhileActive(principal, toolName, toolArgs);
191
+ if (denied) {
192
+ return { content: [{ type: 'text', text: JSON.stringify(denied) }], isError: true };
193
+ }
194
+ gate.recordCallForAll(principal, toolName, toolArgs);
173
195
  const block = gate.checkToolBlock(principal, toolName);
174
196
  if (block) {
175
197
  return { content: [{ type: 'text', text: JSON.stringify(block) }], isError: true };
176
198
  }
177
- if (!gate.routeToolCall(principal, toolName)) {
199
+ const routed = !!gate.routeToolCall(principal, toolName);
200
+ if (!routed) {
178
201
  const autoStarted = gate.autoStartForTool(principal, toolName);
179
202
  if (autoStarted) {
180
- gate.recordCallForAll(principal, toolName);
203
+ gate.recordCallForAll(principal, toolName, toolArgs);
181
204
  }
182
205
  else {
183
206
  const coldBlock = gate.checkColdToolBlock(toolName);
@@ -189,9 +212,16 @@ function installPreCallHook(server) {
189
212
  // F-12: inject post-call guidance from active workflows
190
213
  const handlerResult = await originalHandler(...callArgs);
191
214
  if (handlerResult && !handlerResult['isError']) {
215
+ // FEAT-271 W3: success-only starts and records (startOnSuccess / recordOnSuccess types).
216
+ if (!routed)
217
+ gate.autoStartAfterSuccess(principal, toolName, toolArgs);
218
+ gate.recordSuccessForAll(principal, toolName, toolArgs);
192
219
  const allGuidance = gate.getGuidanceAll(principal);
193
220
  if (allGuidance.length > 0) {
194
- const guidanceText = allGuidance.map((g) => expandGuidance(g.guidance, g.typeName, g.phase)).filter(Boolean);
221
+ const wsId = (await getModuleClient()).workspaceId ?? undefined;
222
+ const guidanceText = allGuidance
223
+ .map((g) => fillGuidance(expandGuidance(g.guidance, g.typeName, g.phase, wsId), g.instanceId))
224
+ .filter(Boolean);
195
225
  if (guidanceText.length > 0) {
196
226
  const content = handlerResult['content'];
197
227
  if (Array.isArray(content)) {
@@ -335,6 +365,7 @@ async function run() {
335
365
  registerWebUrlTools(server);
336
366
  registerWorkspaceTools(server, getClient);
337
367
  registerChronicleTools(server, getClient);
368
+ registerContentRemovalTools(server, getClient, gate);
338
369
  registerCrewTools(server, getClient);
339
370
  registerPeopleTools(server, getClient);
340
371
  registerLakeStructureTools(server, getClient);
@@ -353,7 +384,7 @@ async function run() {
353
384
  if (process.env['FEATURE_SECRETARY'] !== 'false') {
354
385
  registerSecretaryTools(server, getClient);
355
386
  }
356
- registerExecRouteTool(server);
387
+ registerExecRouteTool(server, gate.getRegistry(), getClient);
357
388
  registerIamTools(server, getClient);
358
389
  registerSecurityTools(server, getClient);
359
390
  registerPrompts(server, getClient);
package/dist/setup.js CHANGED
@@ -17,7 +17,7 @@
17
17
  import * as os from 'node:os';
18
18
  import * as readline from 'node:readline';
19
19
  import { TacitClient, TacitApiError } from './client.js';
20
- import { ENTRY_NAME, PACKAGE_NAME, activeConfigFolder, findOnPath, genericEntryJson, listConfigFolders, registerUserEntry, removeUserEntry, run, scanLegacyEntries, userEntryState, } from './claude-config.js';
20
+ import { ENTRY_NAME, PACKAGE_NAME, activeConfigFolder, findOnPath, isNpxEphemeral, genericEntryJson, listConfigFolders, registerUserEntry, removeUserEntry, run, scanLegacyEntries, userEntryState, } from './claude-config.js';
21
21
  import { ProfileError, getDefault, getDeviceLabel, isUsableProfileName, pickProfileSlug, setDefault, tryReadProfile, writeProfile, } from './profile-store.js';
22
22
  import { PromptError, promptHidden } from './prompt.js';
23
23
  import { SignInError, signIn } from './signin.js';
@@ -338,8 +338,9 @@ export async function runSetup(argv, deps = {}) {
338
338
  }
339
339
  else
340
340
  mode = (await io.choose('How should TACIT load in Claude Code?', ['Every session', 'Only when I start Claude Code with the tacit command'], 0)) === 1 ? 'on-demand' : 'always';
341
- // 6. install the tacit command
342
- if (findOnPath('tacit', env) === null) {
341
+ // 6. install the tacit command (npx ephemeral copies don't survive the session)
342
+ const tacitOnPath = findOnPath('tacit', env);
343
+ if (tacitOnPath === null || isNpxEphemeral(tacitOnPath)) {
343
344
  const wanted = o.install === 'yes' || (o.install === 'ask' && io.isTTY && (await io.confirm('Install the tacit command? (Y/n) ', true)));
344
345
  if (wanted) {
345
346
  if (!(await installCli(env, out, err)))
@@ -87,7 +87,7 @@ 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
+ { 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_exec'] },
91
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'] },
92
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
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'] },
@@ -1,3 +1,17 @@
1
1
  import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
2
  import type { TacitClient } from '../client.js';
3
+ /** FEAT-271 W1: request for POST /api/v1/chronicle/events/:id/search-exclusion. */
4
+ export declare function buildSearchExclusionRequest(args: {
5
+ event_id: string;
6
+ excluded: boolean;
7
+ reason: string;
8
+ }): {
9
+ method: 'POST';
10
+ path: string;
11
+ body: {
12
+ excluded: boolean;
13
+ reason: string;
14
+ confirm: true;
15
+ };
16
+ };
3
17
  export declare function registerChronicleTools(server: McpServer, getClient: () => Promise<TacitClient>): void;
@@ -1,6 +1,14 @@
1
1
  import { z } from 'zod';
2
2
  import { TacitApiError, TokenExpiredError } from '../client.js';
3
- import { success, error, featureDisabledResult } from './errors.js';
3
+ import { success, error, featureDisabledResult, apiErrorResult } from './errors.js';
4
+ /** FEAT-271 W1: request for POST /api/v1/chronicle/events/:id/search-exclusion. */
5
+ export function buildSearchExclusionRequest(args) {
6
+ return {
7
+ method: 'POST',
8
+ path: `/api/v1/chronicle/events/${encodeURIComponent(args.event_id)}/search-exclusion`,
9
+ body: { excluded: args.excluded, reason: args.reason, confirm: true },
10
+ };
11
+ }
4
12
  export function registerChronicleTools(server, getClient) {
5
13
  server.tool('tacit_chronicle_timeline', 'Query the Chronicle timeline with date range, scope, and text filters.', {
6
14
  from: z.string().optional().describe('RFC 3339 lower bound (inclusive)'),
@@ -162,4 +170,29 @@ export function registerChronicleTools(server, getClient) {
162
170
  return error(`Unexpected error: ${e instanceof Error ? e.message : String(e)}`);
163
171
  }
164
172
  });
173
+ server.tool('tacit_chronicle_exclude_event', 'T3 (removes content from retrieval; requires explicit user approval). Exclude a Chronicle event\'s content from search, or restore it. Reversible: call with excluded=false to restore. Requires confirm=true and a reason. Requires admin (auth.manage capability). Returns { event_id, excluded, rows_affected }. 404 = event not found in this workspace.', {
174
+ event_id: z.string().uuid().describe('Chronicle event UUID'),
175
+ excluded: z.boolean().describe('true = exclude from search; false = restore'),
176
+ reason: z.string().min(1).describe('Why the event is being excluded or restored (audit trail)'),
177
+ confirm: z.boolean().describe('Must be true. Confirms the user approved this T3 change'),
178
+ }, async (args) => {
179
+ if (args.confirm !== true) {
180
+ return error('confirm must be true: excluding or restoring an event changes what search returns (T3). Get explicit user approval, then call again with confirm=true.');
181
+ }
182
+ const req = buildSearchExclusionRequest(args);
183
+ try {
184
+ const client = await getClient();
185
+ const data = await client.request(req.method, req.path, req.body);
186
+ return success(data);
187
+ }
188
+ catch (e) {
189
+ if (e instanceof TacitApiError && e.statusCode === 404 && !featureDisabledResult(e)) {
190
+ return error(`Event ${args.event_id} not found in this workspace (404). Check the event ID and the active workspace.`);
191
+ }
192
+ if (e instanceof TacitApiError && e.statusCode === 403) {
193
+ return error(`Permission denied (403): excluding or restoring Chronicle events in search requires admin (auth.manage). ${e.body}`.trim());
194
+ }
195
+ return apiErrorResult(e, req.path);
196
+ }
197
+ });
165
198
  }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * FEAT-271 W2/W3 — content removal tools (footprint → propose → approve → execute → verify, plus restore).
3
+ *
4
+ * The backend state machine under /api/v1/content/removals is the enforcement: illegal
5
+ * transitions return 409. The `gm_content_removal` workflow type only orders the steps for
6
+ * an agent inside one MCP session. tacit_removal_approve releases that type's approve gate.
7
+ *
8
+ * Folded actions (brief §W2 item 4): cancel lives in tacit_removal_propose and
9
+ * tacit_removal_approve (action="cancel"); redact lives in tacit_removal_restore (action="redact").
10
+ *
11
+ * Binding (audit H3/M4): a successful propose stores the request id as the instance's removal_id.
12
+ * MCP phase order then applies only to calls on that request; retry, restore or cancel of any
13
+ * other request bypasses it (the backend enforces those requests' state).
14
+ */
15
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
16
+ import type { TacitClient } from '../client.js';
17
+ import type { WorkflowGate } from '../workflow-gate.js';
18
+ export declare const CONTENT_REMOVAL_TYPE_NAME = "gm_content_removal";
19
+ /**
20
+ * Post-call guidance for the gm_content_removal workflow (spread into the index.ts GUIDANCE_MAP).
21
+ * `{instanceId}` is filled in by fillGuidance so the agent can call tacit_workflow_advance.
22
+ */
23
+ export declare const CONTENT_REMOVAL_GUIDANCE: Readonly<Record<string, string>>;
24
+ /** Fill `{instanceId}` placeholders in workflow guidance text. */
25
+ export declare function fillGuidance(text: string, instanceId: string): string;
26
+ declare const ROOT_KINDS: readonly ["artifact", "catalog", "data_object", "chronicle_event"];
27
+ type RootKind = (typeof ROOT_KINDS)[number];
28
+ export interface RemovalRequestSpec {
29
+ method: 'GET' | 'POST';
30
+ path: string;
31
+ body?: Record<string, unknown>;
32
+ }
33
+ export declare function buildFootprintRequest(args: {
34
+ id: string;
35
+ kind?: RootKind;
36
+ }): RemovalRequestSpec;
37
+ export declare function buildProposeRequest(args: {
38
+ root_kind: RootKind;
39
+ root_id: string;
40
+ verify_phrase: string;
41
+ extra_targets?: Array<{
42
+ kind: RootKind;
43
+ id: string;
44
+ }>;
45
+ }): RemovalRequestSpec;
46
+ export declare function buildCancelRequest(removalId: string): RemovalRequestSpec;
47
+ export declare function buildApproveRequest(args: {
48
+ removal_id: string;
49
+ typed_title: string;
50
+ exclude_item_ids?: string[];
51
+ }): RemovalRequestSpec;
52
+ export declare function buildExecuteRequest(args: {
53
+ removal_id: string;
54
+ retry?: boolean;
55
+ }): RemovalRequestSpec;
56
+ /** Verify takes no mode: the backend checks removal or restore from the request's state. */
57
+ export declare function buildVerifyRequest(args: {
58
+ removal_id: string;
59
+ }): RemovalRequestSpec;
60
+ export declare function buildRestoreRequest(args: {
61
+ removal_id: string;
62
+ action?: 'restore' | 'redact';
63
+ }): RemovalRequestSpec;
64
+ export declare function buildListRequest(args: {
65
+ removal_id?: string;
66
+ state?: string;
67
+ limit?: number;
68
+ }): RemovalRequestSpec;
69
+ /**
70
+ * True when a 404/405 comes from a route that is not mounted (flag off) rather than from the
71
+ * removal handlers. The handlers always answer with a JSON error code (e.g. NOT_FOUND for a
72
+ * wrong id); an unmounted route falls through to the SPA/static fallback (empty or HTML body).
73
+ */
74
+ export declare function isUnmountedRouteError(e: unknown): boolean;
75
+ export declare function removalErrorResult(e: unknown, path: string): {
76
+ content: Array<{
77
+ type: "text";
78
+ text: string;
79
+ }>;
80
+ isError?: boolean;
81
+ } & {
82
+ isError: boolean;
83
+ };
84
+ export declare function registerContentRemovalTools(server: McpServer, getClient: () => Promise<TacitClient>, gate?: WorkflowGate): void;
85
+ export {};
@@ -0,0 +1,251 @@
1
+ /**
2
+ * FEAT-271 W2/W3 — content removal tools (footprint → propose → approve → execute → verify, plus restore).
3
+ *
4
+ * The backend state machine under /api/v1/content/removals is the enforcement: illegal
5
+ * transitions return 409. The `gm_content_removal` workflow type only orders the steps for
6
+ * an agent inside one MCP session. tacit_removal_approve releases that type's approve gate.
7
+ *
8
+ * Folded actions (brief §W2 item 4): cancel lives in tacit_removal_propose and
9
+ * tacit_removal_approve (action="cancel"); redact lives in tacit_removal_restore (action="redact").
10
+ *
11
+ * Binding (audit H3/M4): a successful propose stores the request id as the instance's removal_id.
12
+ * MCP phase order then applies only to calls on that request; retry, restore or cancel of any
13
+ * other request bypasses it (the backend enforces those requests' state).
14
+ */
15
+ import { z } from 'zod';
16
+ import { TacitApiError, getRequestPrincipal } from '../client.js';
17
+ import { success, error, featureDisabledResult, apiErrorResult, errorCodeOfBody } from './errors.js';
18
+ export const CONTENT_REMOVAL_TYPE_NAME = 'gm_content_removal';
19
+ const BASE = '/api/v1/content/removals';
20
+ const FEATURE_FLAG = 'FEATURE_CONTENT_REMOVAL';
21
+ /**
22
+ * Post-call guidance for the gm_content_removal workflow (spread into the index.ts GUIDANCE_MAP).
23
+ * `{instanceId}` is filled in by fillGuidance so the agent can call tacit_workflow_advance.
24
+ */
25
+ export const CONTENT_REMOVAL_GUIDANCE = {
26
+ GM_CONTENT_REMOVAL: 'Content removal active (instanceId {instanceId}). Follow: footprint → propose → approve (user types the title) → execute → verify, calling tacit_workflow_advance with instanceId "{instanceId}" between phases. Raw delete tools are refused until the workflow ends; never use SQL.',
27
+ CONTENT_REMOVAL_DISCOVER: 'Content removal: discover. Show the user the footprint grouped by kind with reversibility, plus similar_not_included. Then call tacit_workflow_advance with instanceId "{instanceId}", then tacit_removal_propose.',
28
+ CONTENT_REMOVAL_PROPOSE: 'Content removal: propose. Call tacit_removal_propose, present every item, the IRREVERSIBLE and MANUAL_REQUIRED items, similar_not_included and the MCP server in use. Then tacit_workflow_advance with instanceId "{instanceId}".',
29
+ CONTENT_REMOVAL_APPROVE: 'Content removal: approve. WAIT for the user to type the exact title, then call tacit_removal_approve with confirm=true and typed_title. Then tacit_workflow_advance with instanceId "{instanceId}".',
30
+ CONTENT_REMOVAL_EXECUTE: 'Content removal: execute. Call tacit_removal_execute with confirm=true, poll tacit_removal_list every few seconds until EXECUTED or FAILED (retry=true resumes a FAILED run). Then tacit_workflow_advance with instanceId "{instanceId}".',
31
+ CONTENT_REMOVAL_VERIFY: 'Content removal: verify. Call tacit_removal_verify; report VERIFIED or list the remaining copies (MANUAL_REQUIRED SOURCE items stay until handled per DOC-8). Then tacit_workflow_advance with instanceId "{instanceId}" to finish.',
32
+ };
33
+ /** Fill `{instanceId}` placeholders in workflow guidance text. */
34
+ export function fillGuidance(text, instanceId) {
35
+ return text.replace(/\{instanceId\}/g, instanceId);
36
+ }
37
+ const ROOT_KINDS = ['artifact', 'catalog', 'data_object', 'chronicle_event'];
38
+ const enc = (id) => encodeURIComponent(id);
39
+ // ─── Pure request builders (unit-tested) ────────────────────────────────────
40
+ export function buildFootprintRequest(args) {
41
+ return { method: 'GET', path: `/api/v1/content/${enc(args.id)}/footprint?kind=${args.kind ?? 'artifact'}` };
42
+ }
43
+ export function buildProposeRequest(args) {
44
+ const body = {
45
+ root_kind: args.root_kind,
46
+ root_id: args.root_id,
47
+ verify_phrase: args.verify_phrase,
48
+ };
49
+ if (args.extra_targets && args.extra_targets.length > 0)
50
+ body['extra_targets'] = args.extra_targets;
51
+ return { method: 'POST', path: BASE, body };
52
+ }
53
+ export function buildCancelRequest(removalId) {
54
+ return { method: 'POST', path: `${BASE}/${enc(removalId)}/cancel`, body: {} };
55
+ }
56
+ export function buildApproveRequest(args) {
57
+ const body = { confirm: true, typed_title: args.typed_title };
58
+ if (args.exclude_item_ids && args.exclude_item_ids.length > 0)
59
+ body['exclude_item_ids'] = args.exclude_item_ids;
60
+ return { method: 'POST', path: `${BASE}/${enc(args.removal_id)}/approve`, body };
61
+ }
62
+ export function buildExecuteRequest(args) {
63
+ const verb = args.retry ? 'retry' : 'execute';
64
+ return { method: 'POST', path: `${BASE}/${enc(args.removal_id)}/${verb}`, body: {} };
65
+ }
66
+ /** Verify takes no mode: the backend checks removal or restore from the request's state. */
67
+ export function buildVerifyRequest(args) {
68
+ return { method: 'POST', path: `${BASE}/${enc(args.removal_id)}/verify`, body: {} };
69
+ }
70
+ export function buildRestoreRequest(args) {
71
+ const verb = args.action === 'redact' ? 'redact' : 'restore';
72
+ return { method: 'POST', path: `${BASE}/${enc(args.removal_id)}/${verb}`, body: { confirm: true } };
73
+ }
74
+ export function buildListRequest(args) {
75
+ if (args.removal_id)
76
+ return { method: 'GET', path: `${BASE}/${enc(args.removal_id)}` };
77
+ const params = new URLSearchParams();
78
+ if (args.state)
79
+ params.set('state', args.state);
80
+ if (args.limit !== undefined)
81
+ params.set('limit', String(args.limit));
82
+ const qs = params.toString();
83
+ return { method: 'GET', path: qs ? `${BASE}?${qs}` : BASE };
84
+ }
85
+ // ─── Error mapping ──────────────────────────────────────────────────────────
86
+ const REMOVAL_DISABLED_MESSAGE = `Content removal is turned off on this server (${FEATURE_FLAG}). The removal routes are not mounted; enable the flag on this cell and restart, or use another MCP server.`;
87
+ /**
88
+ * True when a 404/405 comes from a route that is not mounted (flag off) rather than from the
89
+ * removal handlers. The handlers always answer with a JSON error code (e.g. NOT_FOUND for a
90
+ * wrong id); an unmounted route falls through to the SPA/static fallback (empty or HTML body).
91
+ */
92
+ export function isUnmountedRouteError(e) {
93
+ if (!(e instanceof TacitApiError))
94
+ return false;
95
+ if (e.statusCode !== 404 && e.statusCode !== 405)
96
+ return false;
97
+ return errorCodeOfBody(e.body) === null;
98
+ }
99
+ export function removalErrorResult(e, path) {
100
+ // A non-JSON 200 (SPA index.html served for an unmounted GET route) fails JSON parsing.
101
+ if (isUnmountedRouteError(e) || e instanceof SyntaxError)
102
+ return error(REMOVAL_DISABLED_MESSAGE);
103
+ if (e instanceof TacitApiError && !featureDisabledResult(e)) {
104
+ if (e.statusCode === 404) {
105
+ return error(`Not found (404) in this workspace: ${path}. Check the id and the active workspace (MCP server). ${e.body}`.trim());
106
+ }
107
+ if (e.statusCode === 403) {
108
+ return error(`Permission denied (403): content removal needs the content.remove capability (owners get it at their next login) plus the underlying delete/demote rights for every item. ${e.body}`.trim());
109
+ }
110
+ if (e.statusCode === 409) {
111
+ return error(`Refused by the removal state machine (409): this step is not allowed from the request's current state, or another active request exists for this root. Call tacit_removal_list with removal_id to see the state. ${e.body}`.trim());
112
+ }
113
+ if (e.statusCode === 422) {
114
+ return error(`Invalid removal input (422): ${e.body}`.trim());
115
+ }
116
+ }
117
+ return apiErrorResult(e, path);
118
+ }
119
+ async function sendRaw(getClient, req) {
120
+ try {
121
+ const client = await getClient();
122
+ const data = await client.request(req.method, req.path, req.body);
123
+ return { data, result: success(data) };
124
+ }
125
+ catch (e) {
126
+ return { data: undefined, result: removalErrorResult(e, req.path) };
127
+ }
128
+ }
129
+ async function send(getClient, req) {
130
+ return (await sendRaw(getClient, req)).result;
131
+ }
132
+ /**
133
+ * After cancel: deactivate only the removal workflow bound to this request, so its tool denials
134
+ * lift. Cancelling an unrelated request leaves the active workflow alone.
135
+ */
136
+ function endRemovalWorkflow(gate, removalId) {
137
+ if (!gate)
138
+ return;
139
+ gate.deactivateBound(getRequestPrincipal(), CONTENT_REMOVAL_TYPE_NAME, removalId);
140
+ }
141
+ /** The request id from a propose response (the backend returns the request row with `id`). */
142
+ function requestIdOf(data) {
143
+ if (!data || typeof data !== 'object')
144
+ return null;
145
+ const d = data;
146
+ const id = d['id'] ?? d['removal_id'];
147
+ return typeof id === 'string' && id !== '' ? id : null;
148
+ }
149
+ // ─── Tool registration ──────────────────────────────────────────────────────
150
+ const removalId = z.string().uuid().describe('Removal request UUID (from tacit_removal_propose)');
151
+ const t3Confirm = z.boolean().describe('Must be true. Confirms the user explicitly approved this T3 step');
152
+ export function registerContentRemovalTools(server, getClient, gate) {
153
+ server.tool('tacit_content_footprint', 'READ. List every copy of a piece of content in this workspace before removing it: artifact chain members, lake catalog rows, KB articles, dossier and vault memberships, linked Chronicle events, eligible search rows, and similar_not_included (look-alikes that will NOT be touched). Each item has {kind, id, title, location, state, action, reversibility}. Works on deleted roots too, so leftovers can be found. A successful call starts the gm_content_removal workflow (discover phase); the guidance shows its instanceId for tacit_workflow_advance.', {
154
+ id: z.string().uuid().describe('Root id (artifact, catalog item, data object or Chronicle event)'),
155
+ kind: z.enum(ROOT_KINDS).optional().describe('Root kind (default artifact)'),
156
+ }, async (args) => send(getClient, buildFootprintRequest(args)));
157
+ server.tool('tacit_removal_propose', 'WRITE (T2). Propose removing a piece of content everywhere in this workspace; creates a PROPOSED removal request from the footprint. Show the user every item with its reversibility, the MANUAL_REQUIRED (SOURCE lake) items, similar_not_included, and the MCP server you are using. action="cancel" with removal_id cancels a PROPOSED or APPROVED request and ends the removal workflow.', {
158
+ action: z.enum(['propose', 'cancel']).optional().describe('propose (default) or cancel'),
159
+ root_kind: z.enum(ROOT_KINDS).optional().describe('Root kind (required for propose)'),
160
+ root_id: z.string().uuid().optional().describe('Root id (required for propose)'),
161
+ verify_phrase: z.string().min(3).max(200).optional().describe('A distinctive phrase from the content; verify searches for it (required for propose)'),
162
+ extra_targets: z
163
+ .array(z.object({ kind: z.enum(ROOT_KINDS), id: z.string().uuid() }))
164
+ .optional()
165
+ .describe('Extra same-workspace ids to remove with the root'),
166
+ removal_id: z.string().uuid().optional().describe('Required for action="cancel"'),
167
+ }, async (args) => {
168
+ if (args.action === 'cancel') {
169
+ if (!args.removal_id)
170
+ return error('removal_id is required for action="cancel".');
171
+ const res = await send(getClient, buildCancelRequest(args.removal_id));
172
+ if (!res.isError)
173
+ endRemovalWorkflow(gate, args.removal_id);
174
+ return res;
175
+ }
176
+ if (!args.root_kind || !args.root_id || !args.verify_phrase) {
177
+ return error('root_kind, root_id and verify_phrase are required to propose a removal. Run tacit_content_footprint first.');
178
+ }
179
+ const { data, result } = await sendRaw(getClient, buildProposeRequest({
180
+ root_kind: args.root_kind,
181
+ root_id: args.root_id,
182
+ verify_phrase: args.verify_phrase,
183
+ extra_targets: args.extra_targets,
184
+ }));
185
+ // Bind the active (unbound) removal workflow to this request (audit H3).
186
+ const rid = result.isError ? null : requestIdOf(data);
187
+ if (rid && gate)
188
+ gate.bindInstance(getRequestPrincipal(), CONTENT_REMOVAL_TYPE_NAME, rid);
189
+ return result;
190
+ });
191
+ server.tool('tacit_removal_approve', 'WRITE (T3, requires explicit user approval). Approve a PROPOSED removal. The user must type the root title exactly (typed_title); confirm must be true. exclude_item_ids opts items out (never the root or an item another item depends on). The backend pre-checks every item and refuses with a per-item list if rights are missing. On success this releases the approve gate of the gm_content_removal workflow bound to this removal_id; then call tacit_workflow_advance with the instanceId shown in the guidance. action="cancel" cancels the request instead.', {
192
+ removal_id: removalId,
193
+ action: z.enum(['approve', 'cancel']).optional().describe('approve (default) or cancel'),
194
+ confirm: z.boolean().optional().describe('Must be true to approve (T3)'),
195
+ typed_title: z.string().optional().describe('The root title exactly as the user typed it (required to approve)'),
196
+ exclude_item_ids: z
197
+ .array(z.string().uuid())
198
+ .optional()
199
+ .describe('Items to leave in place: request item_id values from tacit_removal_propose or tacit_removal_list (removal_id) — not footprint ids'),
200
+ }, async (args) => {
201
+ if (args.action === 'cancel') {
202
+ const res = await send(getClient, buildCancelRequest(args.removal_id));
203
+ if (!res.isError)
204
+ endRemovalWorkflow(gate, args.removal_id);
205
+ return res;
206
+ }
207
+ if (args.confirm !== true) {
208
+ return error('confirm must be true: approving a removal is T3. Show the user the full proposal, get explicit approval, then call again with confirm=true.');
209
+ }
210
+ if (!args.typed_title || args.typed_title.trim() === '') {
211
+ return error('typed_title is required: ask the user to type the exact title of the content being removed.');
212
+ }
213
+ const res = await send(getClient, buildApproveRequest({ removal_id: args.removal_id, typed_title: args.typed_title, exclude_item_ids: args.exclude_item_ids }));
214
+ if (!res.isError && gate) {
215
+ gate.releaseApprovalGate(getRequestPrincipal(), CONTENT_REMOVAL_TYPE_NAME, 'approve', args.removal_id);
216
+ }
217
+ return res;
218
+ });
219
+ server.tool('tacit_removal_execute', 'WRITE (T3, requires explicit user approval). Execute an APPROVED removal, or retry a FAILED one (retry=true resumes from the first unfinished item). Runs in the background: returns 202, then poll tacit_removal_list with removal_id for per-item progress. Order: dossiers, KB demote, artifact chain, catalog rows, Chronicle events; SOURCE lake items are MANUAL_REQUIRED and not removed. Stops on the first error and names the item.', {
220
+ removal_id: removalId,
221
+ retry: z.boolean().optional().describe('true = retry a FAILED request'),
222
+ confirm: t3Confirm,
223
+ }, async (args) => {
224
+ if (args.confirm !== true) {
225
+ return error('confirm must be true: executing a removal deletes content (T3). Get explicit user approval, then call again with confirm=true.');
226
+ }
227
+ return send(getClient, buildExecuteRequest(args));
228
+ });
229
+ server.tool('tacit_removal_verify', 'READ. Verify a removal: re-runs the footprint plus search and recall for the verify phrase (with retries for embedding lag). The check follows the request state: after execute it checks the content is gone (zero eligible copies moves the request to VERIFIED; otherwise the remaining copies are recorded and you may verify again); after a restore it checks the pre-removal footprint is back.', {
230
+ removal_id: removalId,
231
+ }, async (args) => send(getClient, buildVerifyRequest(args)));
232
+ server.tool('tacit_removal_restore', 'WRITE (T3, requires explicit user approval). Restore a VERIFIED, EXECUTED or FAILED removal: reverses REVERSIBLE items in reverse order (artifact undeleted and re-indexed, catalog status, KB promotion, dossier lists). IRREVERSIBLE items stay removed. Then call tacit_removal_verify (it checks the restore because the request is RESTORED). action="redact" instead blanks the stored titles, phrase and before/after snapshots (terminal; restore is then refused; this is not erasure).', {
233
+ removal_id: removalId,
234
+ action: z.enum(['restore', 'redact']).optional().describe('restore (default) or redact'),
235
+ confirm: t3Confirm,
236
+ }, async (args) => {
237
+ if (args.confirm !== true) {
238
+ const what = args.action === 'redact' ? 'Redacting removal records is irreversible' : 'Restoring removed content';
239
+ return error(`confirm must be true: ${what} (T3). Get explicit user approval, then call again with confirm=true.`);
240
+ }
241
+ return send(getClient, buildRestoreRequest(args));
242
+ });
243
+ server.tool('tacit_removal_list', 'READ. List removal requests in this workspace (filter by state), or get one request by removal_id with per-item state, before/after, errors and the verification result. Use it to poll execute progress.', {
244
+ removal_id: z.string().uuid().optional().describe('Get one request with its items'),
245
+ state: z
246
+ .enum(['PROPOSED', 'APPROVED', 'EXECUTING', 'EXECUTED', 'FAILED', 'VERIFIED', 'RESTORED', 'CANCELLED', 'REDACTED'])
247
+ .optional()
248
+ .describe('Filter the list by state'),
249
+ limit: z.number().int().min(1).max(100).optional().describe('Max results, newest first (default 50, max 100)'),
250
+ }, async (args) => send(getClient, buildListRequest(args)));
251
+ }