@tacitai/mcp-server 0.6.27 → 0.6.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,179 @@
1
+ /**
2
+ * MCP tools for user-authored workflow types (MV-1539 W7 Step 30).
3
+ *
4
+ * tacit_workflow_type_list — list system + user types for current workspace
5
+ * tacit_workflow_type_create — create a user-authored type (T2 approval gate)
6
+ * tacit_workflow_type_update — update an existing user type definition
7
+ */
8
+ import { z } from 'zod';
9
+ import { isUserWorkflowTypesActive } from '../flags.js';
10
+ import { validateUserTypeDef, SYSTEM_RESERVED_TYPE_NAMES } from '../workflow-type-schema.js';
11
+ const listSchema = z.object({});
12
+ const createSchema = z.object({
13
+ name: z.string().describe('Type name (lowercase, 3-64 chars, a-z0-9_)'),
14
+ definition: z.record(z.unknown()).describe('Full workflow type definition (prereqs, failDirection, etc.)'),
15
+ base_type: z.string().optional().describe('System type name to fork from (merges base with overrides)'),
16
+ });
17
+ const updateSchema = z.object({
18
+ id: z.string().uuid().describe('UUID of the user type to update'),
19
+ definition: z.record(z.unknown()).describe('Updated workflow type definition'),
20
+ });
21
+ function jsonResult(data, isError = false) {
22
+ return {
23
+ content: [{ type: 'text', text: JSON.stringify(data) }],
24
+ isError,
25
+ };
26
+ }
27
+ function rowToTypeDef(row) {
28
+ const def = row.definition;
29
+ return {
30
+ ...def,
31
+ name: row.name,
32
+ entryTool: def.entryTool ?? null,
33
+ failDirection: def.failDirection ?? 'open',
34
+ sharedToolPolicy: def.sharedToolPolicy ?? 'passthrough',
35
+ };
36
+ }
37
+ export function registerWorkflowTypeTools(server, getClient, registry) {
38
+ server.tool('tacit_workflow_type_list', 'List all workflow types (system + user-authored) for the current workspace.', listSchema.shape, async () => {
39
+ const client = await getClient();
40
+ const workspaceId = client.workspaceId;
41
+ if (!workspaceId) {
42
+ return jsonResult({ error: 'no_workspace', detail: 'No workspace context available' }, true);
43
+ }
44
+ const systemTypes = registry.list().map((t) => ({
45
+ name: t.name,
46
+ is_system: true,
47
+ guidance: t.guidance ?? null,
48
+ persistent: t.persistent ?? false,
49
+ maxInstances: t.maxInstances ?? 1,
50
+ }));
51
+ if (!isUserWorkflowTypesActive()) {
52
+ return jsonResult({ types: systemTypes });
53
+ }
54
+ try {
55
+ const result = await client.get('/api/v1/workflow-types', {
56
+ workspace_id: workspaceId,
57
+ });
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
+ }));
67
+ return jsonResult({ types: [...systemTypes, ...userTypes] });
68
+ }
69
+ catch {
70
+ return jsonResult({ types: systemTypes, _note: 'user types unavailable (backend unreachable)' });
71
+ }
72
+ });
73
+ server.tool('tacit_workflow_type_create', 'Create a user-authored workflow type for the current workspace.', createSchema.shape, async (args) => {
74
+ if (!isUserWorkflowTypesActive()) {
75
+ return jsonResult({ error: 'feature_disabled', detail: 'FEATURE_WORKFLOW_USER_TYPES is not enabled' }, true);
76
+ }
77
+ const parsed = createSchema.safeParse(args);
78
+ if (!parsed.success) {
79
+ return jsonResult({ error: 'invalid_input', detail: parsed.error.message }, true);
80
+ }
81
+ const { name, definition, base_type } = parsed.data;
82
+ const client = await getClient();
83
+ const workspaceId = client.workspaceId;
84
+ if (!workspaceId) {
85
+ return jsonResult({ error: 'no_workspace', detail: 'No workspace context available' }, true);
86
+ }
87
+ let mergedDef = { ...definition, name };
88
+ if (base_type) {
89
+ if (!SYSTEM_RESERVED_TYPE_NAMES.includes(base_type)) {
90
+ return jsonResult({ error: 'invalid_base_type', detail: `Base type '${base_type}' is not a system type` }, true);
91
+ }
92
+ const baseDef = registry.get(base_type);
93
+ if (!baseDef) {
94
+ return jsonResult({ error: 'base_type_not_found', detail: `System type '${base_type}' not found in registry` }, true);
95
+ }
96
+ const baseObj = JSON.parse(JSON.stringify(baseDef));
97
+ mergedDef = { ...baseObj, ...definition, name };
98
+ }
99
+ const validation = validateUserTypeDef(mergedDef);
100
+ if (!validation.valid) {
101
+ return jsonResult({ error: 'validation_failed', errors: validation.errors }, true);
102
+ }
103
+ try {
104
+ const result = await client.post('/api/v1/workflow-types', {
105
+ workspace_id: workspaceId,
106
+ name,
107
+ definition: mergedDef,
108
+ base_type: base_type ?? null,
109
+ });
110
+ registry.registerUserType(rowToTypeDef(result), workspaceId);
111
+ return jsonResult({
112
+ id: result.id,
113
+ name: result.name,
114
+ version: result.version,
115
+ created_at: result.created_at,
116
+ });
117
+ }
118
+ catch (err) {
119
+ const msg = err instanceof Error ? err.message : String(err);
120
+ if (msg.includes('reserved_type_name')) {
121
+ return jsonResult({ error: 'reserved_type_name', name }, true);
122
+ }
123
+ if (msg.includes('reserved_tool')) {
124
+ return jsonResult({ error: 'reserved_tool', detail: msg }, true);
125
+ }
126
+ 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);
128
+ }
129
+ return jsonResult({ error: 'backend_unreachable', detail: msg }, true);
130
+ }
131
+ });
132
+ server.tool('tacit_workflow_type_update', 'Update the definition of a user-authored workflow type.', updateSchema.shape, async (args) => {
133
+ if (!isUserWorkflowTypesActive()) {
134
+ return jsonResult({ error: 'feature_disabled', detail: 'FEATURE_WORKFLOW_USER_TYPES is not enabled' }, true);
135
+ }
136
+ const parsed = updateSchema.safeParse(args);
137
+ if (!parsed.success) {
138
+ return jsonResult({ error: 'invalid_input', detail: parsed.error.message }, true);
139
+ }
140
+ const { id, definition } = parsed.data;
141
+ const client = await getClient();
142
+ const workspaceId = client.workspaceId;
143
+ if (!workspaceId) {
144
+ return jsonResult({ error: 'no_workspace', detail: 'No workspace context available' }, true);
145
+ }
146
+ const defWithPolicy = {
147
+ ...definition,
148
+ failDirection: definition['failDirection'] ?? 'open',
149
+ sharedToolPolicy: definition['sharedToolPolicy'] ?? 'passthrough',
150
+ name: definition['name'] ?? 'placeholder_name',
151
+ };
152
+ const validation = validateUserTypeDef(defWithPolicy);
153
+ if (!validation.valid) {
154
+ const relevantErrors = validation.errors.filter((e) => !e.includes('placeholder_name'));
155
+ if (relevantErrors.length > 0) {
156
+ return jsonResult({ error: 'validation_failed', errors: relevantErrors }, true);
157
+ }
158
+ }
159
+ try {
160
+ const result = await client.put(`/api/v1/workflow-types/${id}`, {
161
+ definition: defWithPolicy,
162
+ });
163
+ registry.registerUserType(rowToTypeDef(result), workspaceId);
164
+ return jsonResult({
165
+ id: result.id,
166
+ name: result.name,
167
+ version: result.version,
168
+ updated_at: result.updated_at,
169
+ });
170
+ }
171
+ catch (err) {
172
+ const msg = err instanceof Error ? err.message : String(err);
173
+ if (msg.includes('TYPE_NOT_FOUND')) {
174
+ return jsonResult({ error: 'type_not_found', detail: `Type ${id} not found or is a system type` }, true);
175
+ }
176
+ return jsonResult({ error: 'backend_unreachable', detail: msg }, true);
177
+ }
178
+ });
179
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Workflow lifecycle MCP tools (MV-1539 W2 Step 6, W3 Step 11).
3
+ *
4
+ * W2: tacit_workflow_start, tacit_workflow_handoff, tacit_workflow_deactivate.
5
+ * W3: tacit_workflow_advance, tacit_workflow_resume, tacit_workflow_set_metadata.
6
+ */
7
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
8
+ import { WorkflowGate } from '../workflow-gate.js';
9
+ export declare function registerWorkflowTools(server: McpServer, gate: WorkflowGate): void;
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Workflow lifecycle MCP tools (MV-1539 W2 Step 6, W3 Step 11).
3
+ *
4
+ * W2: tacit_workflow_start, tacit_workflow_handoff, tacit_workflow_deactivate.
5
+ * W3: tacit_workflow_advance, tacit_workflow_resume, tacit_workflow_set_metadata.
6
+ */
7
+ import { z } from 'zod';
8
+ import { getRequestPrincipal } from '../client.js';
9
+ import { isWorkflowTypeActive } from '../flags.js';
10
+ const startSchema = z.object({
11
+ typeName: z.string().describe('The workflow type to start (e.g. cos_coordination, pyr_exec)'),
12
+ metadata: z.record(z.unknown()).optional().describe('Optional metadata for the workflow instance'),
13
+ });
14
+ const handoffSchema = z.object({
15
+ fromInstanceId: z.string().describe('The instance ID of the source workflow'),
16
+ targetTypeName: z.string().describe('The workflow type to hand off to'),
17
+ });
18
+ const deactivateSchema = z.object({
19
+ instanceId: z.string().describe('The instance ID to deactivate'),
20
+ });
21
+ const advanceSchema = z.object({
22
+ instanceId: z.string().describe('The instance ID whose phase to advance'),
23
+ });
24
+ const resumeSchema = z.object({
25
+ instanceId: z.string().describe('The instance ID to resume'),
26
+ approval: z.boolean().optional().describe('If true, sets phaseApproved before resuming'),
27
+ metadata: z.record(z.unknown()).optional().describe('Metadata to merge into the instance'),
28
+ });
29
+ const setMetadataSchema = z.object({
30
+ instanceId: z.string().describe('The instance ID to update metadata on'),
31
+ key: z.string().describe('The metadata key'),
32
+ value: z.unknown().describe('The metadata value'),
33
+ });
34
+ function jsonResult(data, isError = false) {
35
+ return {
36
+ content: [{ type: 'text', text: JSON.stringify(data) }],
37
+ isError,
38
+ };
39
+ }
40
+ export function registerWorkflowTools(server, gate) {
41
+ server.tool('tacit_workflow_start', 'Start a new workflow instance of the given type. Returns the instance ID.', startSchema.shape, async (args) => {
42
+ const parsed = startSchema.safeParse(args);
43
+ if (!parsed.success) {
44
+ return jsonResult({ error: 'invalid_input', detail: parsed.error.message }, true);
45
+ }
46
+ const { typeName, metadata } = parsed.data;
47
+ if (!gate.getRegistry().has(typeName)) {
48
+ return jsonResult({ error: 'type_not_found', detail: `Unknown workflow type: ${typeName}` }, true);
49
+ }
50
+ if (!isWorkflowTypeActive(typeName)) {
51
+ return jsonResult({ error: 'type_not_active', detail: `Workflow type ${typeName} is disabled by feature flag` }, true);
52
+ }
53
+ const principal = getRequestPrincipal();
54
+ const instance = gate.startWorkflowTyped(principal, typeName, { metadata });
55
+ return jsonResult({
56
+ instanceId: instance.instanceId,
57
+ typeName: instance.typeRef,
58
+ active: instance.active,
59
+ });
60
+ });
61
+ server.tool('tacit_workflow_handoff', 'Hand off from one workflow instance to a target workflow type. Validates targetTypes.', handoffSchema.shape, async (args) => {
62
+ const parsed = handoffSchema.safeParse(args);
63
+ if (!parsed.success) {
64
+ return jsonResult({ error: 'invalid_input', detail: parsed.error.message }, true);
65
+ }
66
+ const { fromInstanceId, targetTypeName } = parsed.data;
67
+ if (!isWorkflowTypeActive(targetTypeName)) {
68
+ return jsonResult({ error: 'type_not_active', detail: `Target type ${targetTypeName} is disabled by feature flag` }, true);
69
+ }
70
+ const principal = getRequestPrincipal();
71
+ const result = gate.handoff(principal, fromInstanceId, targetTypeName);
72
+ if ('error' in result) {
73
+ return jsonResult(result, true);
74
+ }
75
+ return jsonResult({
76
+ instanceId: result.instanceId,
77
+ typeName: result.typeRef,
78
+ parentInstanceId: result.parentInstanceId,
79
+ active: result.active,
80
+ });
81
+ });
82
+ server.tool('tacit_workflow_deactivate', 'Deactivate a workflow instance by ID.', deactivateSchema.shape, async (args) => {
83
+ const parsed = deactivateSchema.safeParse(args);
84
+ if (!parsed.success) {
85
+ return jsonResult({ error: 'invalid_input', detail: parsed.error.message }, true);
86
+ }
87
+ const { instanceId } = parsed.data;
88
+ const principal = getRequestPrincipal();
89
+ const ok = gate.deactivateWorkflow(principal, instanceId);
90
+ if (!ok) {
91
+ return jsonResult({ error: 'instance_not_found', detail: `Instance ${instanceId} not found` }, true);
92
+ }
93
+ return jsonResult({ deactivated: true, instanceId });
94
+ });
95
+ // ── W3 Step 11: Phase engine tools ────────────────────────────────────────
96
+ server.tool('tacit_workflow_advance', 'Advance the current phase of a workflow instance. Checks required tools and approval gates.', advanceSchema.shape, async (args) => {
97
+ const parsed = advanceSchema.safeParse(args);
98
+ if (!parsed.success) {
99
+ return jsonResult({ error: 'invalid_input', detail: parsed.error.message }, true);
100
+ }
101
+ const principal = getRequestPrincipal();
102
+ const result = gate.advancePhase(principal, parsed.data.instanceId);
103
+ if ('error' in result) {
104
+ return jsonResult(result, true);
105
+ }
106
+ return jsonResult(result);
107
+ });
108
+ server.tool('tacit_workflow_resume', 'Resume a paused workflow instance. Optionally sets approval and merges metadata.', resumeSchema.shape, async (args) => {
109
+ const parsed = resumeSchema.safeParse(args);
110
+ if (!parsed.success) {
111
+ return jsonResult({ error: 'invalid_input', detail: parsed.error.message }, true);
112
+ }
113
+ const { instanceId, approval, metadata } = parsed.data;
114
+ const principal = getRequestPrincipal();
115
+ const result = gate.resumeWorkflow(principal, instanceId, { approval, metadata });
116
+ if ('error' in result) {
117
+ return jsonResult(result, true);
118
+ }
119
+ return jsonResult({ resumed: result.resumed, instanceId: result.instanceId, resumeMode: result.resumeMode });
120
+ });
121
+ server.tool('tacit_workflow_set_metadata', 'Set a metadata key-value pair on a workflow instance.', setMetadataSchema.shape, async (args) => {
122
+ const parsed = setMetadataSchema.safeParse(args);
123
+ if (!parsed.success) {
124
+ return jsonResult({ error: 'invalid_input', detail: parsed.error.message }, true);
125
+ }
126
+ const { instanceId, key, value } = parsed.data;
127
+ const principal = getRequestPrincipal();
128
+ const result = gate.setInstanceMetadata(principal, instanceId, key, value);
129
+ if ('error' in result) {
130
+ return jsonResult(result, true);
131
+ }
132
+ return jsonResult(result);
133
+ });
134
+ }
@@ -1,31 +1,28 @@
1
1
  /**
2
- * WorkflowGate — Layer 1 server-side workflow enforcement (FEAT-249).
2
+ * WorkflowGate — Layer 1 server-side workflow enforcement (FEAT-249, MV-1539).
3
3
  *
4
- * Structural, model-agnostic drill-down prerequisites for the GM content-placement
5
- * workflow: `tacit_gm_approve` (pyramid) requires the four pyramid list tools to have
6
- * been called since the last `tacit_gm_ingest` (or a validated fast-track target_path);
7
- * `tacit_kb_promote_from_artifact` requires `tacit_kb_list_collections` — but only
8
- * while a GM workflow is active AND the artifact_id matches the workflow's artifact.
9
- * Standalone KB promotion (SOP-03, no active workflow) stays ungated.
4
+ * Instance-isolated state: `Map<principal, Map<instanceId, WorkflowInstance>>`.
5
+ * Type-scoped supersession (Axiom 3): starting a workflow of type T supersedes any
6
+ * existing instance of T for the same principal (types with maxInstances > 1 coexist
7
+ * up to their limit). Legacy 2-arg methods resolve to the principal's
8
+ * `gm_content_placement` instance for backwards compatibility.
10
9
  *
11
- * Scoping (AC-isolation): one instance per server process. State is keyed by caller
10
+ * Scoping (AC-isolation): one gate per server process. State is keyed by caller
12
11
  * principal — on the HTTP transport `getRequestPrincipal()` returns the bearer-token
13
12
  * principal (AsyncLocalStorage); on stdio it returns null and every call shares the
14
- * single '__stdio__' slot, which is correct because a stdio server is one connection.
15
- * NEVER store gate state inside the per-request AsyncLocalStorage context: it would
16
- * evaporate between HTTP requests and silently no-op the gate.
17
- *
18
- * Lifecycle: active from `tacit_gm_ingest` (which supersedes any prior workflow) until
19
- * the FINAL placement completes — approve for pyramid, promote of the workflow's own
20
- * artifact for KB (a promote of a DIFFERENT artifact is placement-unrelated and neither
21
- * gated nor completing). `cross_reference` keeps the workflow active for a second
22
- * placement cycle. `tacit_gm_reset` clears the call log and rearms ACTIVE whether or
23
- * not a placement had completed. Nothing persists across process restarts.
13
+ * single '__stdio__' slot.
24
14
  */
15
+ import { WorkflowRegistry } from './workflow-registry.js';
16
+ import { type AutonomyLevel as _AutonomyLevel } from './client.js';
25
17
  export interface GateVerdict {
26
18
  allowed: boolean;
27
19
  missing: string[];
28
20
  message?: string;
21
+ prereqChain?: string[];
22
+ completed?: string[];
23
+ workflowType?: string;
24
+ currentPhase?: string;
25
+ userMessage?: string;
29
26
  }
30
27
  export interface WorkflowSnapshot {
31
28
  active: boolean;
@@ -34,86 +31,184 @@ export interface WorkflowSnapshot {
34
31
  crossReference: boolean;
35
32
  placementsRemaining: number;
36
33
  }
37
- /** Drill-down tools required before `tacit_gm_approve` (pyramid surface). */
34
+ export type { _AutonomyLevel as AutonomyLevel };
35
+ type AutonomyLevel = _AutonomyLevel;
36
+ export interface WorkflowInstance {
37
+ instanceId: string;
38
+ typeRef: string;
39
+ workspaceId: string;
40
+ active: boolean;
41
+ artifactId: string | null;
42
+ catalogId: string | null;
43
+ crossReference: boolean;
44
+ placementsRemaining: number;
45
+ callLog: Map<string, number>;
46
+ fastTrackValidated: boolean;
47
+ lastPlacementKey: string | null;
48
+ metadata: Record<string, unknown>;
49
+ currentPhase: number;
50
+ paused: boolean;
51
+ phaseApproved: boolean;
52
+ parentInstanceId: string | null;
53
+ handoffCount: number;
54
+ createdAt: number;
55
+ lastActivityAt: number;
56
+ }
57
+ export interface WorkflowPersistencePort {
58
+ save(principal: string, workspaceId: string, instance: WorkflowInstance): Promise<void>;
59
+ restore(principal: string, workspaceId: string): Promise<WorkflowInstance[]>;
60
+ remove(principal: string, instanceId: string): Promise<void>;
61
+ }
62
+ export interface WorkflowChronicleEvent {
63
+ eventType: 'workflow.instance.created' | 'workflow.instance.deactivated' | 'workflow.instance.evicted' | 'workflow.phase.advanced' | 'workflow.phase.paused' | 'workflow.phase.resumed' | 'workflow.handoff.initiated' | 'workflow.handoff.completed';
64
+ instanceId: string;
65
+ typeName: string;
66
+ principal: string;
67
+ workspaceId: string;
68
+ timestamp: string;
69
+ metadata: Record<string, unknown>;
70
+ }
71
+ export interface WorkflowGateOpts {
72
+ registry: WorkflowRegistry;
73
+ maxPrincipals?: number;
74
+ maxTotalInstances?: number;
75
+ maxInstancesPerPrincipal?: number;
76
+ onEvent?: (event: WorkflowChronicleEvent) => void;
77
+ persistence?: WorkflowPersistencePort;
78
+ autonomyResolver?: (principal: string) => AutonomyLevel;
79
+ }
80
+ export interface StartWorkflowOpts {
81
+ artifactId?: string;
82
+ catalogId?: string;
83
+ crossReference?: boolean;
84
+ workspaceId?: string;
85
+ metadata?: Record<string, unknown>;
86
+ }
87
+ export interface WorkflowGateContext {
88
+ states: Map<string, Map<string, WorkflowInstance>>;
89
+ registry: WorkflowRegistry;
90
+ persistence?: WorkflowPersistencePort;
91
+ onEvent: (event: WorkflowChronicleEvent) => void;
92
+ getCachedAutonomy: (principal: string) => AutonomyLevel | null;
93
+ startWorkflow: (principal: string | null, typeName: string, opts?: StartWorkflowOpts) => WorkflowInstance;
94
+ keyOf: (principal: string | null) => string;
95
+ maxInstancesPerPrincipal: number;
96
+ maxTotalInstances: number;
97
+ }
98
+ /** Re-export from workflow-registry.ts (canonical source) for backwards compatibility. */
38
99
  export declare const PYRAMID_PREREQ_TOOLS: readonly ["tacit_pyramid_list_portfolios", "tacit_pyramid_list_value_streams", "tacit_pyramid_list_programs", "tacit_pyramid_list_dossiers"];
39
- /** Drill-down tool required before a GM-workflow KB promotion. */
40
100
  export declare const KB_PREREQ_TOOL = "tacit_kb_list_collections";
41
101
  export declare class WorkflowGate {
102
+ private readonly registry;
42
103
  private readonly maxPrincipals;
104
+ private readonly maxTotalInstances;
105
+ private readonly maxInstancesPerPrincipal;
106
+ private readonly onEvent;
107
+ private readonly persistencePort?;
108
+ private readonly autonomyResolver?;
109
+ private readonly states;
110
+ private totalInstances;
111
+ private readonly restoredPrincipals;
112
+ private readonly principalMutex;
113
+ constructor(maxPrincipalsOrOpts?: number | WorkflowGateOpts);
114
+ getRegistry(): WorkflowRegistry;
115
+ keyOf(principal: string | null): string;
116
+ getCachedAutonomy(principal: string): AutonomyLevel | null;
117
+ ensureRestored(principal: string | null, workspaceId: string): Promise<void>;
118
+ checkToolAutonomy(principal: string | null, toolName: string): {
119
+ error: string;
120
+ required: AutonomyLevel;
121
+ current: AutonomyLevel;
122
+ } | null;
123
+ private ensurePrincipalMap;
124
+ private findGmInstance;
125
+ private findOrCreateGmInstance;
126
+ private emitEvent;
127
+ startWorkflowTyped(principal: string | null, typeName: string, opts?: StartWorkflowOpts): WorkflowInstance;
128
+ getInstance(principal: string | null, instanceId: string): WorkflowInstance | undefined;
129
+ getInstancesByType(principal: string | null, typeName: string): WorkflowInstance[];
130
+ deactivateWorkflow(principal: string | null, instanceId: string): boolean;
131
+ private evictOldestGlobal;
132
+ handoff(principal: string | null, fromInstanceId: string, targetTypeName: string, opts?: StartWorkflowOpts): WorkflowInstance | {
133
+ error: string;
134
+ detail?: string;
135
+ };
136
+ advancePhase(principal: string | null, instanceId: string): {
137
+ phase: string;
138
+ guidance: string;
139
+ } | {
140
+ completed: true;
141
+ instanceId: string;
142
+ } | {
143
+ error: string;
144
+ missing?: string[];
145
+ detail?: string;
146
+ };
147
+ resumeWorkflow(principal: string | null, instanceId: string, opts?: {
148
+ approval?: boolean;
149
+ metadata?: Record<string, unknown>;
150
+ }): {
151
+ resumed: true;
152
+ instanceId: string;
153
+ resumeMode: 'tool' | 'skill-preamble';
154
+ } | {
155
+ error: string;
156
+ detail?: string;
157
+ };
158
+ setInstanceMetadata(principal: string | null, instanceId: string, key: string, value: unknown): {
159
+ set: true;
160
+ } | {
161
+ error: string;
162
+ detail?: string;
163
+ };
164
+ getGuidance(principal: string | null, instanceId: string): string | null;
165
+ getGuidanceAll(principal: string | null): Array<{
166
+ instanceId: string;
167
+ typeName: string;
168
+ phase: string | null;
169
+ guidance: string;
170
+ priority: number;
171
+ }>;
172
+ withPrincipalLock(principal: string | null, fn: () => Promise<unknown>): Promise<unknown>;
43
173
  /**
44
- * Safety valve (sec audit): cap distinct principals so the states Map cannot grow
45
- * unboundedly. A slot requires a valid credential to create, but unbounded is still
46
- * a leak. FIFO-evicts (Map insertion order) past the cap; constructor-injectable
47
- * for tests. Process restart clears everything regardless.
174
+ * Route a tool call to the correct workflow instance(s). Returns the instance
175
+ * that owns this tool, or undefined if no active instance claims it. For the
176
+ * GM type (bespoke gating), this returns the GM instance regardless.
48
177
  */
49
- constructor(maxPrincipals?: number);
50
- private readonly states;
51
- private keyOf;
52
- private stateOf;
53
- /** Record a shared list-tool call. Counting is per tool; startWorkflow clears the log. */
178
+ routeToolCall(principal: string | null, toolName: string): WorkflowInstance | undefined;
179
+ /**
180
+ * Check if a tool is blocked by a pending approval gate. Returns an error
181
+ * object if blocked, or null if allowed.
182
+ */
183
+ checkToolBlock(principal: string | null, toolName: string): ({
184
+ error: string;
185
+ phase: string;
186
+ blockedTool: string;
187
+ } & Partial<GateVerdict>) | null;
188
+ /**
189
+ * Check whether a tool is gated by any registered phased workflow type, even when
190
+ * the caller has no active instance (first-contact rejection).
191
+ */
192
+ checkColdToolBlock(toolName: string): GateVerdict | null;
193
+ /**
194
+ * Record a tool call for ALL active instances that include this tool in their
195
+ * type definition. For legacy GM callers, the 2-arg recordCall below also works.
196
+ */
197
+ recordCallForAll(principal: string | null, toolName: string): void;
54
198
  recordCall(principal: string | null, toolName: string): void;
55
- /** `tacit_gm_ingest` succeeded — arm the workflow, superseding any prior one. */
56
199
  startWorkflow(principal: string | null, opts: {
57
200
  artifactId: string;
58
201
  catalogId: string;
59
202
  crossReference: boolean;
60
203
  }): void;
61
- /** Guidance-attach predicate (Layer 2): true from ingest until the final placement completes. */
62
204
  isGuidanceActive(principal: string | null): boolean;
63
- /** Read-only copy of the workflow state, or null when none exists. */
64
205
  getWorkflow(principal: string | null): WorkflowSnapshot | null;
65
- /**
66
- * Pyramid gate for `tacit_gm_approve`. Applied whenever an approve is attempted:
67
- * the drill-down must have happened (call log since last ingest, or a validated
68
- * fast-track). Re-approving after a completed placement is allowed while the log
69
- * still satisfies the prerequisites (idempotent retries), but `tacit_gm_reset`
70
- * or a new ingest re-arms the requirement.
71
- */
72
206
  checkPyramidApprove(principal: string | null): GateVerdict;
73
- /**
74
- * KB gate for `tacit_kb_promote_from_artifact` (and the catalog variant, which
75
- * resolves to the same artifact). Gated ONLY while a GM workflow is active AND
76
- * artifactId matches the workflow's artifact; a different artifact or a standalone
77
- * promotion (SOP-03) passes through ungated and does NOT complete the workflow.
78
- *
79
- * Restart asymmetry (ADR-202): a process restart mid-KB-workflow silently downgrades
80
- * to this ungated path (fail-open), while checkPyramidApprove re-requires the
81
- * drill-down (fail-closed). The gate is workflow hygiene, not a security boundary —
82
- * backend authorization (workspace scoping, capabilities) is unaffected either way.
83
- */
84
207
  checkKbPromote(principal: string | null, artifactId: string): GateVerdict;
85
- /**
86
- * Variation C fast-track: the handler validated target_path server-side against the
87
- * same endpoints the list tools wrap. Satisfies the drill-down prerequisite for this
88
- * cycle only; cleared by ingest supersession and by reset.
89
- */
90
208
  markFastTrackValidated(principal: string | null): void;
91
- /**
92
- * A final placement succeeded — `tacit_gm_approve` (pyramid) or a promote of the
93
- * workflow's own artifact (KB). With cross_reference set the workflow stays active
94
- * for the second cycle; otherwise it deactivates and shared-list guidance stops.
95
- *
96
- * `placementKey` makes completion idempotent: the backend is idempotent, so an
97
- * identical retry of an already-counted placement (same catalog+targets, or same
98
- * artifact+collection) must not consume a second budget slot — in a cross_reference
99
- * workflow a double-decrement would deactivate mid-flow and leave the second
100
- * surface ungated (and able to land PUBLISHED). A DIFFERENT placement still counts.
101
- */
102
209
  completePlacement(principal: string | null, placementKey: string): void;
103
- /**
104
- * Variation D reset: clear the call log, rearm ACTIVE whether or not a placement had
105
- * completed, keep the workflow's artifact/catalog. The next surface starts its own
106
- * drill-down from scratch (call log is empty; fast-track is invalidated).
107
- */
108
210
  resetWorkflow(principal: string | null): WorkflowSnapshot;
109
- /** Full teardown for the principal (tests; production teardown is process exit). */
110
211
  clear(principal: string | null): void;
111
212
  }
112
- /**
113
- * Guidance appended to shared list-tool results while a GM workflow is active.
114
- * Never attached when no workflow is active (Gap G2: COO audits and read-only
115
- * browses must not see GM placement instructions).
116
- */
117
213
  export declare const GM_LIST_TOOL_NEXT_STEP: Record<string, string>;
118
- /** Appended to approve results when cross_reference is set and a second cycle remains. */
119
214
  export declare const GM_APPROVE_NEXT_STEP: string;