@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.
@@ -1,125 +1,745 @@
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
  */
25
- /** Drill-down tools required before `tacit_gm_approve` (pyramid surface). */
26
- export const PYRAMID_PREREQ_TOOLS = [
27
- 'tacit_pyramid_list_portfolios',
28
- 'tacit_pyramid_list_value_streams',
29
- 'tacit_pyramid_list_programs',
30
- 'tacit_pyramid_list_dossiers',
31
- ];
32
- /** Drill-down tool required before a GM-workflow KB promotion. */
33
- export const KB_PREREQ_TOOL = 'tacit_kb_list_collections';
15
+ import { createDefaultRegistry, PYRAMID_PREREQ_TOOLS as _PYRAMID_PREREQ_TOOLS, KB_PREREQ_TOOL as _KB_PREREQ_TOOL, } from './workflow-registry.js';
16
+ import { getCachedAutonomy as _getCachedAutonomyFromClient, autonomyAtLeast, } from './client.js';
17
+ /** Re-export from workflow-registry.ts (canonical source) for backwards compatibility. */
18
+ export const PYRAMID_PREREQ_TOOLS = _PYRAMID_PREREQ_TOOLS;
19
+ export const KB_PREREQ_TOOL = _KB_PREREQ_TOOL;
20
+ const GM_TYPE_NAME = 'gm_content_placement';
21
+ let instanceCounter = 0;
22
+ function generateInstanceId() {
23
+ return `wf_${Date.now().toString(36)}_${(++instanceCounter).toString(36)}`;
24
+ }
34
25
  function staleSurfaceHint(surface) {
35
26
  return `A ${surface} drill-down is already recorded for this workflow; to switch surface, call tacit_gm_reset first.`;
36
27
  }
28
+ // MV-1539 W2 Step 9: tool-to-minimum-autonomy table
29
+ const TOOL_MIN_AUTONOMY = new Map([
30
+ ['tacit_dispatch_crew', 'MENTAT'],
31
+ ]);
32
+ const DEFAULT_TOOL_AUTONOMY = 'SCRIBE';
33
+ // ─── Gate class ─────────────────────────────────────────────────────────────
37
34
  export class WorkflowGate {
35
+ registry;
38
36
  maxPrincipals;
39
- /**
40
- * Safety valve (sec audit): cap distinct principals so the states Map cannot grow
41
- * unboundedly. A slot requires a valid credential to create, but unbounded is still
42
- * a leak. FIFO-evicts (Map insertion order) past the cap; constructor-injectable
43
- * for tests. Process restart clears everything regardless.
44
- */
45
- constructor(maxPrincipals = 10_000) {
46
- this.maxPrincipals = maxPrincipals;
47
- }
37
+ maxTotalInstances;
38
+ maxInstancesPerPrincipal;
39
+ onEvent;
40
+ persistencePort;
41
+ autonomyResolver;
48
42
  states = new Map();
43
+ totalInstances = 0;
44
+ restoredPrincipals = new Set();
45
+ principalMutex = new Map();
46
+ constructor(maxPrincipalsOrOpts) {
47
+ if (typeof maxPrincipalsOrOpts === 'number') {
48
+ this.registry = createDefaultRegistry();
49
+ this.maxPrincipals = maxPrincipalsOrOpts;
50
+ this.maxTotalInstances = 50_000;
51
+ this.maxInstancesPerPrincipal = 10;
52
+ this.onEvent = () => { };
53
+ }
54
+ else if (maxPrincipalsOrOpts) {
55
+ this.registry = maxPrincipalsOrOpts.registry;
56
+ this.maxPrincipals = maxPrincipalsOrOpts.maxPrincipals ?? 10_000;
57
+ this.maxTotalInstances = maxPrincipalsOrOpts.maxTotalInstances ?? 50_000;
58
+ this.maxInstancesPerPrincipal = maxPrincipalsOrOpts.maxInstancesPerPrincipal ?? 10;
59
+ this.onEvent = maxPrincipalsOrOpts.onEvent ?? (() => { });
60
+ this.persistencePort = maxPrincipalsOrOpts.persistence;
61
+ this.autonomyResolver = maxPrincipalsOrOpts.autonomyResolver;
62
+ }
63
+ else {
64
+ this.registry = createDefaultRegistry();
65
+ this.maxPrincipals = 10_000;
66
+ this.maxTotalInstances = 50_000;
67
+ this.maxInstancesPerPrincipal = 10;
68
+ this.onEvent = () => { };
69
+ }
70
+ }
71
+ getRegistry() {
72
+ return this.registry;
73
+ }
49
74
  keyOf(principal) {
50
75
  return principal ?? '__stdio__';
51
76
  }
52
- stateOf(principal) {
77
+ getCachedAutonomy(principal) {
78
+ if (this.autonomyResolver)
79
+ return this.autonomyResolver(principal);
80
+ return _getCachedAutonomyFromClient(principal);
81
+ }
82
+ async ensureRestored(principal, workspaceId) {
83
+ if (!this.persistencePort)
84
+ return;
85
+ const key = this.keyOf(principal);
86
+ const restoreKey = `${key}:${workspaceId}`;
87
+ if (this.restoredPrincipals.has(restoreKey))
88
+ return;
89
+ this.restoredPrincipals.add(restoreKey);
90
+ try {
91
+ const instances = await this.persistencePort.restore(key, workspaceId);
92
+ if (instances.length === 0)
93
+ return;
94
+ const map = this.ensurePrincipalMap(principal);
95
+ for (const inst of instances) {
96
+ if (map.has(inst.instanceId))
97
+ continue;
98
+ if (!(inst.callLog instanceof Map)) {
99
+ inst.callLog = new Map(Object.entries(inst.callLog ?? {}));
100
+ }
101
+ map.set(inst.instanceId, inst);
102
+ this.totalInstances++;
103
+ }
104
+ }
105
+ catch {
106
+ // restore failures are non-fatal
107
+ }
108
+ }
109
+ checkToolAutonomy(principal, toolName) {
53
110
  const key = this.keyOf(principal);
54
- let state = this.states.get(key);
55
- if (!state) {
111
+ const current = this.getCachedAutonomy(key);
112
+ if (!current)
113
+ return null; // not yet resolved — ensureAutonomy must be called first
114
+ if (!autonomyAtLeast(current, 'SCRIBE')) {
115
+ return { error: 'autonomy_insufficient', required: 'SCRIBE', current };
116
+ }
117
+ const required = TOOL_MIN_AUTONOMY.get(toolName) ?? DEFAULT_TOOL_AUTONOMY;
118
+ if (!autonomyAtLeast(current, required)) {
119
+ return { error: 'autonomy_insufficient', required, current };
120
+ }
121
+ return null;
122
+ }
123
+ ensurePrincipalMap(principal) {
124
+ const key = this.keyOf(principal);
125
+ let map = this.states.get(key);
126
+ if (!map) {
56
127
  while (this.states.size >= this.maxPrincipals) {
57
128
  const oldest = this.states.keys().next().value;
58
129
  if (oldest === undefined)
59
130
  break;
131
+ const evicted = this.states.get(oldest);
132
+ if (evicted) {
133
+ for (const inst of evicted.values()) {
134
+ this.totalInstances--;
135
+ this.emitEvent('workflow.instance.evicted', inst, key);
136
+ }
137
+ }
60
138
  this.states.delete(oldest);
61
139
  }
62
- state = {
63
- active: false,
64
- artifactId: null,
65
- catalogId: null,
66
- crossReference: false,
67
- placementsRemaining: 0,
68
- callLog: new Map(),
69
- fastTrackValidated: false,
70
- lastPlacementKey: null,
71
- };
72
- this.states.set(key, state);
73
- }
74
- return state;
75
- }
76
- /** Record a shared list-tool call. Counting is per tool; startWorkflow clears the log. */
140
+ map = new Map();
141
+ this.states.set(key, map);
142
+ }
143
+ return map;
144
+ }
145
+ findGmInstance(principal) {
146
+ const key = this.keyOf(principal);
147
+ const map = this.states.get(key);
148
+ if (!map)
149
+ return undefined;
150
+ for (const inst of map.values()) {
151
+ if (inst.typeRef === GM_TYPE_NAME)
152
+ return inst;
153
+ }
154
+ return undefined;
155
+ }
156
+ findOrCreateGmInstance(principal) {
157
+ const existing = this.findGmInstance(principal);
158
+ if (existing)
159
+ return existing;
160
+ const map = this.ensurePrincipalMap(principal);
161
+ const inst = {
162
+ instanceId: generateInstanceId(),
163
+ typeRef: GM_TYPE_NAME,
164
+ workspaceId: '',
165
+ active: false,
166
+ artifactId: null,
167
+ catalogId: null,
168
+ crossReference: false,
169
+ placementsRemaining: 0,
170
+ callLog: new Map(),
171
+ fastTrackValidated: false,
172
+ lastPlacementKey: null,
173
+ metadata: {},
174
+ currentPhase: 0,
175
+ paused: false,
176
+ phaseApproved: false,
177
+ parentInstanceId: null,
178
+ handoffCount: 0,
179
+ createdAt: Date.now(),
180
+ lastActivityAt: Date.now(),
181
+ };
182
+ map.set(inst.instanceId, inst);
183
+ this.totalInstances++;
184
+ return inst;
185
+ }
186
+ emitEvent(eventType, instance, principalKey, extra) {
187
+ try {
188
+ const metadata = { ...(extra ?? {}) };
189
+ if (eventType === 'workflow.instance.deactivated' || eventType === 'workflow.instance.evicted') {
190
+ metadata.callLog = Object.fromEntries(instance.callLog);
191
+ }
192
+ this.onEvent({
193
+ eventType,
194
+ instanceId: instance.instanceId,
195
+ typeName: instance.typeRef,
196
+ principal: principalKey,
197
+ workspaceId: instance.workspaceId,
198
+ timestamp: new Date().toISOString(),
199
+ metadata,
200
+ });
201
+ }
202
+ catch {
203
+ // Chronicle emission must never block workflow operations
204
+ }
205
+ }
206
+ // ── Instance-aware API (new, 3-arg) ──────────────────────────────────────
207
+ startWorkflowTyped(principal, typeName, opts) {
208
+ const key = this.keyOf(principal);
209
+ const map = this.ensurePrincipalMap(principal);
210
+ const typeDef = this.registry.get(typeName);
211
+ const maxInstances = typeDef?.maxInstances ?? 1;
212
+ // Type-scoped supersession: remove existing instances of the same type
213
+ // AR-2: handoff children (parentInstanceId set) are exempt from supersession
214
+ if (maxInstances === 1) {
215
+ for (const [id, inst] of map) {
216
+ if (inst.typeRef === typeName && !inst.parentInstanceId) {
217
+ map.delete(id);
218
+ this.totalInstances--;
219
+ this.emitEvent('workflow.instance.deactivated', inst, key, { reason: 'superseded' });
220
+ if (this.persistencePort) {
221
+ this.persistencePort.remove(key, id).catch(() => { });
222
+ }
223
+ }
224
+ }
225
+ }
226
+ else {
227
+ // For maxInstances > 1, check cap and evict oldest if exceeded
228
+ let typeCount = 0;
229
+ for (const inst of map.values()) {
230
+ if (inst.typeRef === typeName)
231
+ typeCount++;
232
+ }
233
+ if (typeCount >= maxInstances) {
234
+ let oldest = null;
235
+ for (const inst of map.values()) {
236
+ if (inst.typeRef === typeName) {
237
+ if (!oldest || inst.createdAt < oldest.createdAt)
238
+ oldest = inst;
239
+ }
240
+ }
241
+ if (oldest) {
242
+ map.delete(oldest.instanceId);
243
+ this.totalInstances--;
244
+ this.emitEvent('workflow.instance.evicted', oldest, key, { reason: 'max_instances' });
245
+ }
246
+ }
247
+ }
248
+ // LRU eviction at totalInstances cap
249
+ while (this.totalInstances >= this.maxTotalInstances) {
250
+ this.evictOldestGlobal();
251
+ }
252
+ // Per-principal cap
253
+ while (map.size >= this.maxInstancesPerPrincipal) {
254
+ let oldest = null;
255
+ for (const inst of map.values()) {
256
+ if (!oldest || inst.createdAt < oldest.createdAt)
257
+ oldest = inst;
258
+ }
259
+ if (!oldest)
260
+ break;
261
+ map.delete(oldest.instanceId);
262
+ this.totalInstances--;
263
+ this.emitEvent('workflow.instance.evicted', oldest, key, { reason: 'per_principal_cap' });
264
+ }
265
+ const budgetFn = typeDef?.terminalAction?.budget;
266
+ let budget = 1;
267
+ if (typeof budgetFn === 'function') {
268
+ budget = budgetFn(opts);
269
+ }
270
+ else if (typeof budgetFn === 'number') {
271
+ budget = budgetFn;
272
+ }
273
+ const instance = {
274
+ instanceId: generateInstanceId(),
275
+ typeRef: typeName,
276
+ workspaceId: opts?.workspaceId ?? '',
277
+ active: true,
278
+ artifactId: opts?.artifactId ?? null,
279
+ catalogId: opts?.catalogId ?? null,
280
+ crossReference: opts?.crossReference ?? false,
281
+ placementsRemaining: budget,
282
+ callLog: new Map(),
283
+ fastTrackValidated: false,
284
+ lastPlacementKey: null,
285
+ metadata: opts?.metadata ?? {},
286
+ currentPhase: 0,
287
+ paused: false,
288
+ phaseApproved: false,
289
+ parentInstanceId: null,
290
+ handoffCount: 0,
291
+ createdAt: Date.now(),
292
+ lastActivityAt: Date.now(),
293
+ };
294
+ map.set(instance.instanceId, instance);
295
+ this.totalInstances++;
296
+ this.emitEvent('workflow.instance.created', instance, key);
297
+ if (this.persistencePort && typeDef?.persistent) {
298
+ this.persistencePort.save(key, instance.workspaceId, instance).catch(() => { });
299
+ }
300
+ return instance;
301
+ }
302
+ getInstance(principal, instanceId) {
303
+ const map = this.states.get(this.keyOf(principal));
304
+ return map?.get(instanceId);
305
+ }
306
+ getInstancesByType(principal, typeName) {
307
+ const map = this.states.get(this.keyOf(principal));
308
+ if (!map)
309
+ return [];
310
+ const result = [];
311
+ for (const inst of map.values()) {
312
+ if (inst.typeRef === typeName)
313
+ result.push(inst);
314
+ }
315
+ return result;
316
+ }
317
+ deactivateWorkflow(principal, instanceId) {
318
+ const key = this.keyOf(principal);
319
+ const map = this.states.get(key);
320
+ if (!map)
321
+ return false;
322
+ const inst = map.get(instanceId);
323
+ if (!inst)
324
+ return false;
325
+ inst.active = false;
326
+ map.delete(instanceId);
327
+ this.totalInstances--;
328
+ this.emitEvent('workflow.instance.deactivated', inst, key, { reason: 'explicit' });
329
+ if (this.persistencePort) {
330
+ this.persistencePort.remove(key, instanceId).catch(() => { });
331
+ }
332
+ return true;
333
+ }
334
+ evictOldestGlobal() {
335
+ let oldestKey = null;
336
+ let oldestInst = null;
337
+ for (const [key, map] of this.states) {
338
+ for (const inst of map.values()) {
339
+ if (!oldestInst || inst.createdAt < oldestInst.createdAt) {
340
+ oldestInst = inst;
341
+ oldestKey = key;
342
+ }
343
+ }
344
+ }
345
+ if (oldestInst && oldestKey) {
346
+ const map = this.states.get(oldestKey);
347
+ if (map) {
348
+ map.delete(oldestInst.instanceId);
349
+ this.totalInstances--;
350
+ this.emitEvent('workflow.instance.evicted', oldestInst, oldestKey, { reason: 'global_cap' });
351
+ if (map.size === 0)
352
+ this.states.delete(oldestKey);
353
+ }
354
+ }
355
+ }
356
+ // ── Handoff (minimal W2 — extended in W4 Step 17) ────────────────────────
357
+ handoff(principal, fromInstanceId, targetTypeName, opts) {
358
+ const key = this.keyOf(principal);
359
+ const map = this.states.get(key);
360
+ const fromInst = map?.get(fromInstanceId);
361
+ if (!fromInst) {
362
+ return { error: 'instance_not_found', detail: `Instance ${fromInstanceId} not found` };
363
+ }
364
+ const fromType = this.registry.get(fromInst.typeRef);
365
+ if (!fromType?.handoff) {
366
+ return { error: 'handoff_not_supported', detail: `Type ${fromInst.typeRef} does not support handoff` };
367
+ }
368
+ if (!fromType.handoff.targetTypes.includes(targetTypeName)) {
369
+ return { error: 'invalid_handoff_target', detail: `${fromInst.typeRef} cannot hand off to ${targetTypeName}` };
370
+ }
371
+ if (!this.registry.has(targetTypeName)) {
372
+ return { error: 'type_not_found', detail: `Type ${targetTypeName} is not registered` };
373
+ }
374
+ const child = this.startWorkflowTyped(principal, targetTypeName, opts);
375
+ child.parentInstanceId = fromInstanceId;
376
+ fromInst.handoffCount++;
377
+ if (!fromType.handoff.preserveParent) {
378
+ fromInst.active = false;
379
+ map.delete(fromInstanceId);
380
+ this.totalInstances--;
381
+ this.emitEvent('workflow.instance.deactivated', fromInst, key, { reason: 'handoff' });
382
+ if (this.persistencePort) {
383
+ this.persistencePort.remove(key, fromInstanceId).catch(() => { });
384
+ }
385
+ }
386
+ this.emitEvent('workflow.handoff.initiated', fromInst, key, { targetType: targetTypeName, childInstanceId: child.instanceId });
387
+ this.emitEvent('workflow.handoff.completed', child, key, { parentInstanceId: fromInstanceId });
388
+ return child;
389
+ }
390
+ // ── Phase engine (W3 Step 11) ─────────────────────────────────────────────
391
+ advancePhase(principal, instanceId) {
392
+ const key = this.keyOf(principal);
393
+ const map = this.states.get(key);
394
+ const inst = map?.get(instanceId);
395
+ if (!inst)
396
+ return { error: 'instance_not_found', detail: `Instance ${instanceId} not found` };
397
+ if (!inst.active)
398
+ return { error: 'instance_not_active', detail: `Instance ${instanceId} is not active` };
399
+ const typeDef = this.registry.get(inst.typeRef);
400
+ if (!typeDef || typeDef.prereqs.kind !== 'phased') {
401
+ return { error: 'not_phased', detail: `Type ${inst.typeRef} does not use phased prerequisites` };
402
+ }
403
+ const phases = typeDef.prereqs.phases;
404
+ const currentPhase = phases[inst.currentPhase];
405
+ if (!currentPhase) {
406
+ return { error: 'phase_out_of_range', detail: `Phase index ${inst.currentPhase} out of range` };
407
+ }
408
+ // Check required tools
409
+ const missing = [];
410
+ for (const tool of currentPhase.requiredTools) {
411
+ if (!inst.callLog.has(tool))
412
+ missing.push(tool);
413
+ }
414
+ if (missing.length > 0) {
415
+ return { error: 'prereqs_incomplete', missing };
416
+ }
417
+ // Check approval gate
418
+ if (currentPhase.approvalGate && !inst.phaseApproved) {
419
+ return { error: 'phase_gate_pending', phase: currentPhase.name };
420
+ }
421
+ // Check required metadata (conditional: skip if metadataCondition is set and not truthy)
422
+ const metaConditionMet = !currentPhase.metadataCondition || !!inst.metadata[currentPhase.metadataCondition];
423
+ if (currentPhase.requiredMetadata && metaConditionMet) {
424
+ for (const [key, check] of Object.entries(currentPhase.requiredMetadata)) {
425
+ if (check === 'present') {
426
+ if (!inst.metadata[key]) {
427
+ return { error: 'receipt_verification_failed', detail: `Missing metadata: ${key}` };
428
+ }
429
+ }
430
+ else if (check === 'present-and-distinct') {
431
+ const parts = key.split(':');
432
+ if (parts.length !== 2)
433
+ continue;
434
+ const [a, b] = parts;
435
+ if (!inst.metadata[a] || !inst.metadata[b]) {
436
+ return { error: 'receipt_verification_failed', detail: `Missing metadata: ${a} or ${b}` };
437
+ }
438
+ if (inst.metadata[a] === inst.metadata[b]) {
439
+ return { error: 'receipt_verification_failed', detail: `${a} and ${b} must be distinct` };
440
+ }
441
+ }
442
+ }
443
+ }
444
+ // Advance to next phase
445
+ const nextIndex = inst.currentPhase + 1;
446
+ if (nextIndex >= phases.length) {
447
+ // Terminal — deactivate
448
+ inst.active = false;
449
+ map.delete(instanceId);
450
+ this.totalInstances--;
451
+ this.emitEvent('workflow.instance.deactivated', inst, key, { reason: 'completed' });
452
+ if (this.persistencePort) {
453
+ this.persistencePort.remove(key, instanceId).catch(() => { });
454
+ }
455
+ return { completed: true, instanceId };
456
+ }
457
+ inst.currentPhase = nextIndex;
458
+ inst.callLog.clear();
459
+ inst.handoffCount = 0;
460
+ inst.phaseApproved = false;
461
+ const nextPhase = phases[nextIndex];
462
+ if (nextPhase.approvalGate) {
463
+ inst.paused = true;
464
+ this.emitEvent('workflow.phase.paused', inst, key, { phase: nextPhase.name });
465
+ }
466
+ this.emitEvent('workflow.phase.advanced', inst, key, { phase: nextPhase.name });
467
+ const advTypeDef = this.registry.get(inst.typeRef);
468
+ if (this.persistencePort && advTypeDef?.persistent) {
469
+ this.persistencePort.save(key, inst.workspaceId, inst).catch(() => { });
470
+ }
471
+ return { phase: nextPhase.name, guidance: nextPhase.guidance };
472
+ }
473
+ resumeWorkflow(principal, instanceId, opts) {
474
+ const key = this.keyOf(principal);
475
+ const map = this.states.get(key);
476
+ const inst = map?.get(instanceId);
477
+ if (!inst)
478
+ return { error: 'instance_not_found', detail: `Instance ${instanceId} not found` };
479
+ if (!inst.paused)
480
+ return { error: 'not_paused', detail: `Instance ${instanceId} is not paused` };
481
+ if (opts?.metadata) {
482
+ Object.assign(inst.metadata, opts.metadata);
483
+ }
484
+ if (opts?.approval) {
485
+ inst.phaseApproved = true;
486
+ }
487
+ inst.paused = false;
488
+ this.emitEvent('workflow.phase.resumed', inst, key);
489
+ const typeDef = this.registry.get(inst.typeRef);
490
+ const resumeMode = typeDef?.resumeMode ?? 'tool';
491
+ return { resumed: true, instanceId, resumeMode };
492
+ }
493
+ setInstanceMetadata(principal, instanceId, key, value) {
494
+ const principalKey = this.keyOf(principal);
495
+ const map = this.states.get(principalKey);
496
+ const inst = map?.get(instanceId);
497
+ if (!inst)
498
+ return { error: 'instance_not_found', detail: `Instance ${instanceId} not found` };
499
+ inst.metadata[key] = value;
500
+ return { set: true };
501
+ }
502
+ getGuidance(principal, instanceId) {
503
+ const map = this.states.get(this.keyOf(principal));
504
+ const inst = map?.get(instanceId);
505
+ if (!inst)
506
+ return null;
507
+ const typeDef = this.registry.get(inst.typeRef);
508
+ if (!typeDef)
509
+ return null;
510
+ if (typeDef.prereqs.kind === 'phased') {
511
+ const phase = typeDef.prereqs.phases[inst.currentPhase];
512
+ return phase?.guidance ?? typeDef.guidance ?? null;
513
+ }
514
+ return typeDef.guidance ?? null;
515
+ }
516
+ getGuidanceAll(principal) {
517
+ const map = this.states.get(this.keyOf(principal));
518
+ if (!map)
519
+ return [];
520
+ const results = [];
521
+ for (const inst of map.values()) {
522
+ if (!inst.active)
523
+ continue;
524
+ const typeDef = this.registry.get(inst.typeRef);
525
+ if (!typeDef)
526
+ continue;
527
+ const guidance = this.getGuidance(principal, inst.instanceId);
528
+ if (!guidance)
529
+ continue;
530
+ let priority = inst.lastActivityAt;
531
+ if (typeDef.prereqs.kind === 'phased')
532
+ priority += 100;
533
+ if (typeDef.persistent)
534
+ priority += 50;
535
+ const phaseName = typeDef.prereqs.kind === 'phased'
536
+ ? (typeDef.prereqs.phases[inst.currentPhase]?.name ?? null)
537
+ : null;
538
+ results.push({ instanceId: inst.instanceId, typeName: inst.typeRef, phase: phaseName, guidance, priority });
539
+ }
540
+ results.sort((a, b) => b.priority - a.priority);
541
+ return results;
542
+ }
543
+ // ── B8 per-principal mutex ─────────────────────────────────────────────────
544
+ async withPrincipalLock(principal, fn) {
545
+ const key = this.keyOf(principal);
546
+ const prev = this.principalMutex.get(key) ?? Promise.resolve();
547
+ let release;
548
+ const next = new Promise(r => { release = r; });
549
+ this.principalMutex.set(key, next);
550
+ await prev;
551
+ try {
552
+ return await fn();
553
+ }
554
+ finally {
555
+ release();
556
+ if (this.principalMutex.get(key) === next) {
557
+ this.principalMutex.delete(key);
558
+ }
559
+ }
560
+ }
561
+ // ── Tool routing ──────────────────────────────────────────────────────────
562
+ /**
563
+ * Route a tool call to the correct workflow instance(s). Returns the instance
564
+ * that owns this tool, or undefined if no active instance claims it. For the
565
+ * GM type (bespoke gating), this returns the GM instance regardless.
566
+ */
567
+ routeToolCall(principal, toolName) {
568
+ const map = this.states.get(this.keyOf(principal));
569
+ if (!map)
570
+ return undefined;
571
+ for (const inst of map.values()) {
572
+ if (!inst.active)
573
+ continue;
574
+ const typeDef = this.registry.get(inst.typeRef);
575
+ if (!typeDef)
576
+ continue;
577
+ if (typeDef.entryTool === toolName)
578
+ return inst;
579
+ if (typeDef.terminalAction?.tool === toolName)
580
+ return inst;
581
+ if (typeDef.prereqs.kind === 'flat') {
582
+ if (typeDef.prereqs.tools.includes(toolName))
583
+ return inst;
584
+ }
585
+ else {
586
+ for (const phase of typeDef.prereqs.phases) {
587
+ if (phase.requiredTools.includes(toolName))
588
+ return inst;
589
+ if (phase.gatedTools.includes(toolName))
590
+ return inst;
591
+ }
592
+ }
593
+ }
594
+ return undefined;
595
+ }
596
+ /**
597
+ * Check if a tool is blocked by a pending approval gate. Returns an error
598
+ * object if blocked, or null if allowed.
599
+ */
600
+ checkToolBlock(principal, toolName) {
601
+ const map = this.states.get(this.keyOf(principal));
602
+ if (!map)
603
+ return null;
604
+ for (const inst of map.values()) {
605
+ if (!inst.active || !inst.paused)
606
+ continue;
607
+ const typeDef = this.registry.get(inst.typeRef);
608
+ if (!typeDef || typeDef.prereqs.kind !== 'phased')
609
+ continue;
610
+ const phase = typeDef.prereqs.phases[inst.currentPhase];
611
+ if (!phase)
612
+ continue;
613
+ if (phase.gatedTools.includes(toolName)) {
614
+ const chain = [...new Set(typeDef.prereqs.phases.flatMap(p => [...p.requiredTools, ...p.gatedTools]))];
615
+ const missing = phase.requiredTools.filter(t => !inst.callLog.has(t));
616
+ const next = missing[0] ?? 'approval of the current phase gate';
617
+ return {
618
+ error: 'phase_gate_pending',
619
+ phase: phase.name,
620
+ blockedTool: toolName,
621
+ allowed: false,
622
+ missing,
623
+ prereqChain: chain,
624
+ completed: chain.filter(t => inst.callLog.has(t)),
625
+ workflowType: typeDef.name,
626
+ currentPhase: phase.name,
627
+ userMessage: `Complete the ${phase.name} phase first. Next step: ${next}.`,
628
+ };
629
+ }
630
+ }
631
+ return null;
632
+ }
633
+ /**
634
+ * Check whether a tool is gated by any registered phased workflow type, even when
635
+ * the caller has no active instance (first-contact rejection).
636
+ */
637
+ checkColdToolBlock(toolName) {
638
+ for (const typeDef of this.registry.list()) {
639
+ if (typeDef.prereqs.kind !== 'phased')
640
+ continue;
641
+ const phases = typeDef.prereqs.phases;
642
+ for (const phase of phases) {
643
+ if (!phase.gatedTools.includes(toolName))
644
+ continue;
645
+ const chain = [...new Set(phases.flatMap(p => [...p.requiredTools, ...p.gatedTools]))];
646
+ const first = phases[0]?.requiredTools[0] ?? typeDef.entryTool ?? 'the first phase tool';
647
+ return {
648
+ allowed: false,
649
+ missing: [phase.requiredTools[0] ?? first],
650
+ prereqChain: chain,
651
+ completed: [],
652
+ workflowType: typeDef.name,
653
+ currentPhase: phase.name,
654
+ userMessage: `This tool requires the ${typeDef.name} workflow. Start with: ${first}.`,
655
+ message: `Tool ${toolName} is gated behind the ${typeDef.name} workflow (phase: ${phase.name}). Complete prerequisite phases first.`,
656
+ };
657
+ }
658
+ }
659
+ return null;
660
+ }
661
+ /**
662
+ * Record a tool call for ALL active instances that include this tool in their
663
+ * type definition. For legacy GM callers, the 2-arg recordCall below also works.
664
+ */
665
+ recordCallForAll(principal, toolName) {
666
+ const map = this.states.get(this.keyOf(principal));
667
+ if (!map)
668
+ return;
669
+ const now = Date.now();
670
+ for (const inst of map.values()) {
671
+ if (!inst.active)
672
+ continue;
673
+ inst.callLog.set(toolName, (inst.callLog.get(toolName) ?? 0) + 1);
674
+ inst.lastActivityAt = now;
675
+ }
676
+ }
677
+ // ── Legacy 2-arg API (GM backwards compatibility) ────────────────────────
77
678
  recordCall(principal, toolName) {
78
- const state = this.stateOf(principal);
79
- state.callLog.set(toolName, (state.callLog.get(toolName) ?? 0) + 1);
679
+ const inst = this.findOrCreateGmInstance(principal);
680
+ inst.callLog.set(toolName, (inst.callLog.get(toolName) ?? 0) + 1);
80
681
  }
81
- /** `tacit_gm_ingest` succeeded — arm the workflow, superseding any prior one. */
82
682
  startWorkflow(principal, opts) {
83
- const state = this.stateOf(principal);
84
- state.active = true;
85
- state.artifactId = opts.artifactId;
86
- state.catalogId = opts.catalogId;
87
- state.crossReference = opts.crossReference;
88
- state.placementsRemaining = opts.crossReference ? 2 : 1;
89
- state.callLog = new Map();
90
- state.fastTrackValidated = false;
91
- state.lastPlacementKey = null;
92
- }
93
- /** Guidance-attach predicate (Layer 2): true from ingest until the final placement completes. */
683
+ const key = this.keyOf(principal);
684
+ const map = this.ensurePrincipalMap(principal);
685
+ // Remove any existing GM instance (supersession)
686
+ for (const [id, inst] of map) {
687
+ if (inst.typeRef === GM_TYPE_NAME) {
688
+ map.delete(id);
689
+ this.totalInstances--;
690
+ this.emitEvent('workflow.instance.deactivated', inst, key, { reason: 'superseded' });
691
+ }
692
+ }
693
+ // LRU eviction at totalInstances cap
694
+ while (this.totalInstances >= this.maxTotalInstances) {
695
+ this.evictOldestGlobal();
696
+ }
697
+ const instance = {
698
+ instanceId: generateInstanceId(),
699
+ typeRef: GM_TYPE_NAME,
700
+ workspaceId: '',
701
+ active: true,
702
+ artifactId: opts.artifactId,
703
+ catalogId: opts.catalogId,
704
+ crossReference: opts.crossReference,
705
+ placementsRemaining: opts.crossReference ? 2 : 1,
706
+ callLog: new Map(),
707
+ fastTrackValidated: false,
708
+ lastPlacementKey: null,
709
+ metadata: {},
710
+ currentPhase: 0,
711
+ paused: false,
712
+ phaseApproved: false,
713
+ parentInstanceId: null,
714
+ handoffCount: 0,
715
+ createdAt: Date.now(),
716
+ lastActivityAt: Date.now(),
717
+ };
718
+ map.set(instance.instanceId, instance);
719
+ this.totalInstances++;
720
+ this.emitEvent('workflow.instance.created', instance, key);
721
+ }
94
722
  isGuidanceActive(principal) {
95
- const state = this.states.get(this.keyOf(principal));
96
- return state?.active === true;
723
+ const inst = this.findGmInstance(principal);
724
+ return inst?.active === true;
97
725
  }
98
- /** Read-only copy of the workflow state, or null when none exists. */
99
726
  getWorkflow(principal) {
100
- const state = this.states.get(this.keyOf(principal));
101
- if (!state)
727
+ const inst = this.findGmInstance(principal);
728
+ if (!inst)
102
729
  return null;
103
730
  return {
104
- active: state.active,
105
- artifactId: state.artifactId,
106
- catalogId: state.catalogId,
107
- crossReference: state.crossReference,
108
- placementsRemaining: state.placementsRemaining,
731
+ active: inst.active,
732
+ artifactId: inst.artifactId,
733
+ catalogId: inst.catalogId,
734
+ crossReference: inst.crossReference,
735
+ placementsRemaining: inst.placementsRemaining,
109
736
  };
110
737
  }
111
- /**
112
- * Pyramid gate for `tacit_gm_approve`. Applied whenever an approve is attempted:
113
- * the drill-down must have happened (call log since last ingest, or a validated
114
- * fast-track). Re-approving after a completed placement is allowed while the log
115
- * still satisfies the prerequisites (idempotent retries), but `tacit_gm_reset`
116
- * or a new ingest re-arms the requirement.
117
- */
118
738
  checkPyramidApprove(principal) {
119
- const state = this.stateOf(principal);
120
- if (state.fastTrackValidated)
739
+ const inst = this.findOrCreateGmInstance(principal);
740
+ if (inst.fastTrackValidated)
121
741
  return { allowed: true, missing: [] };
122
- const missing = PYRAMID_PREREQ_TOOLS.filter((t) => !state.callLog.has(t));
742
+ const missing = PYRAMID_PREREQ_TOOLS.filter((t) => !inst.callLog.has(t));
123
743
  if (missing.length === 0)
124
744
  return { allowed: true, missing: [] };
125
745
  const parts = [
@@ -127,106 +747,72 @@ export class WorkflowGate {
127
747
  `Missing: ${missing.join(', ')}.`,
128
748
  'Call every list tool, propose the specific location, and wait for the user to approve it before placing.',
129
749
  ];
130
- if (state.callLog.has(KB_PREREQ_TOOL)) {
750
+ if (inst.callLog.has(KB_PREREQ_TOOL)) {
131
751
  parts.push(staleSurfaceHint('KB'));
132
752
  }
133
- if (!state.active && state.artifactId === null) {
753
+ if (!inst.active && inst.artifactId === null) {
134
754
  parts.push('No GM workflow is active — start with tacit_gm_ingest (lake-first).');
135
755
  }
136
756
  return { allowed: false, missing: [...missing], message: parts.join(' ') };
137
757
  }
138
- /**
139
- * KB gate for `tacit_kb_promote_from_artifact` (and the catalog variant, which
140
- * resolves to the same artifact). Gated ONLY while a GM workflow is active AND
141
- * artifactId matches the workflow's artifact; a different artifact or a standalone
142
- * promotion (SOP-03) passes through ungated and does NOT complete the workflow.
143
- *
144
- * Restart asymmetry (ADR-202): a process restart mid-KB-workflow silently downgrades
145
- * to this ungated path (fail-open), while checkPyramidApprove re-requires the
146
- * drill-down (fail-closed). The gate is workflow hygiene, not a security boundary —
147
- * backend authorization (workspace scoping, capabilities) is unaffected either way.
148
- */
149
758
  checkKbPromote(principal, artifactId) {
150
- const state = this.states.get(this.keyOf(principal));
151
- if (!state?.active || state.artifactId !== artifactId) {
759
+ const inst = this.findGmInstance(principal);
760
+ if (!inst?.active || inst.artifactId !== artifactId) {
152
761
  return { allowed: true, missing: [] };
153
762
  }
154
- if (state.callLog.has(KB_PREREQ_TOOL))
763
+ if (inst.callLog.has(KB_PREREQ_TOOL))
155
764
  return { allowed: true, missing: [] };
156
765
  const parts = [
157
766
  'tacit_kb_promote_from_artifact rejected: this GM workflow has not listed KB collections.',
158
767
  `Missing: ${KB_PREREQ_TOOL}.`,
159
768
  'List the collections, propose the specific one, and wait for the user to approve it before promoting.',
160
769
  ];
161
- if (PYRAMID_PREREQ_TOOLS.some((t) => state.callLog.has(t))) {
770
+ if (PYRAMID_PREREQ_TOOLS.some((t) => inst.callLog.has(t))) {
162
771
  parts.push(staleSurfaceHint('pyramid'));
163
772
  }
164
773
  return { allowed: false, missing: [KB_PREREQ_TOOL], message: parts.join(' ') };
165
774
  }
166
- /**
167
- * Variation C fast-track: the handler validated target_path server-side against the
168
- * same endpoints the list tools wrap. Satisfies the drill-down prerequisite for this
169
- * cycle only; cleared by ingest supersession and by reset.
170
- */
171
775
  markFastTrackValidated(principal) {
172
- this.stateOf(principal).fastTrackValidated = true;
776
+ this.findOrCreateGmInstance(principal).fastTrackValidated = true;
173
777
  }
174
- /**
175
- * A final placement succeeded — `tacit_gm_approve` (pyramid) or a promote of the
176
- * workflow's own artifact (KB). With cross_reference set the workflow stays active
177
- * for the second cycle; otherwise it deactivates and shared-list guidance stops.
178
- *
179
- * `placementKey` makes completion idempotent: the backend is idempotent, so an
180
- * identical retry of an already-counted placement (same catalog+targets, or same
181
- * artifact+collection) must not consume a second budget slot — in a cross_reference
182
- * workflow a double-decrement would deactivate mid-flow and leave the second
183
- * surface ungated (and able to land PUBLISHED). A DIFFERENT placement still counts.
184
- */
185
778
  completePlacement(principal, placementKey) {
186
- const state = this.states.get(this.keyOf(principal));
187
- if (!state?.active)
779
+ const inst = this.findGmInstance(principal);
780
+ if (!inst?.active)
781
+ return;
782
+ if (inst.lastPlacementKey === placementKey)
188
783
  return;
189
- if (state.lastPlacementKey === placementKey)
190
- return; // idempotent retry — already counted
191
- state.lastPlacementKey = placementKey;
192
- state.placementsRemaining = Math.max(0, state.placementsRemaining - 1);
193
- // The fast-track satisfies the drill-down for THIS cycle only (Variation C).
194
- state.fastTrackValidated = false;
195
- if (state.placementsRemaining === 0) {
196
- state.active = false;
784
+ inst.lastPlacementKey = placementKey;
785
+ inst.placementsRemaining = Math.max(0, inst.placementsRemaining - 1);
786
+ inst.fastTrackValidated = false;
787
+ if (inst.placementsRemaining === 0) {
788
+ inst.active = false;
197
789
  }
198
790
  }
199
- /**
200
- * Variation D reset: clear the call log, rearm ACTIVE whether or not a placement had
201
- * completed, keep the workflow's artifact/catalog. The next surface starts its own
202
- * drill-down from scratch (call log is empty; fast-track is invalidated).
203
- */
204
791
  resetWorkflow(principal) {
205
- const state = this.stateOf(principal);
206
- state.active = state.artifactId !== null;
207
- state.placementsRemaining = state.active ? (state.crossReference ? 2 : 1) : 0;
208
- state.callLog = new Map();
209
- state.fastTrackValidated = false;
210
- state.lastPlacementKey = null;
792
+ const inst = this.findOrCreateGmInstance(principal);
793
+ inst.active = inst.artifactId !== null;
794
+ inst.placementsRemaining = inst.active ? (inst.crossReference ? 2 : 1) : 0;
795
+ inst.callLog = new Map();
796
+ inst.fastTrackValidated = false;
797
+ inst.lastPlacementKey = null;
211
798
  return {
212
- active: state.active,
213
- artifactId: state.artifactId,
214
- catalogId: state.catalogId,
215
- crossReference: state.crossReference,
216
- placementsRemaining: state.placementsRemaining,
799
+ active: inst.active,
800
+ artifactId: inst.artifactId,
801
+ catalogId: inst.catalogId,
802
+ crossReference: inst.crossReference,
803
+ placementsRemaining: inst.placementsRemaining,
217
804
  };
218
805
  }
219
- /** Full teardown for the principal (tests; production teardown is process exit). */
220
806
  clear(principal) {
221
- this.states.delete(this.keyOf(principal));
807
+ const key = this.keyOf(principal);
808
+ const map = this.states.get(key);
809
+ if (map) {
810
+ this.totalInstances -= map.size;
811
+ this.states.delete(key);
812
+ }
222
813
  }
223
814
  }
224
815
  // ─── Layer 2: workflow-scoped NEXT_STEP guidance (attached ONLY while active) ──
225
- /**
226
- * Guidance appended to shared list-tool results while a GM workflow is active.
227
- * Never attached when no workflow is active (Gap G2: COO audits and read-only
228
- * browses must not see GM placement instructions).
229
- */
230
816
  export const GM_LIST_TOOL_NEXT_STEP = {
231
817
  tacit_pyramid_list_portfolios: 'NEXT STEP (GM workflow): portfolios loaded. Continue the mandatory drill-down — ' +
232
818
  'list value streams next, then the programs of the chosen portfolio, then its dossiers. ' +
@@ -243,7 +829,6 @@ export const GM_LIST_TOOL_NEXT_STEP = {
243
829
  'with the workflow artifact_id, the collection UUID, and status "DRAFT" — the article ' +
244
830
  'lands as a draft the user can publish anytime.',
245
831
  };
246
- /** Appended to approve results when cross_reference is set and a second cycle remains. */
247
832
  export const GM_APPROVE_NEXT_STEP = 'NEXT STEP (GM workflow): first surface placed. cross_reference is set — run the second ' +
248
833
  'placement cycle for the other surface: drill down (tacit_kb_list_collections for KB, or the ' +
249
834
  'four pyramid list tools for pyramid), propose the specific location, and wait for approval ' +