@ptkl/toolkit 1.2.0 → 1.3.2

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.
Files changed (42) hide show
  1. package/dist/commands/forge.js +39 -7
  2. package/dist/lib/kortex/__tests__/fixtures/providers/conformance.test.js +120 -0
  3. package/dist/lib/kortex/__tests__/fixtures/sse-and-persistence.test.js +172 -0
  4. package/dist/lib/kortex/__tests__/legacy-compatibility.test.js +273 -0
  5. package/dist/lib/kortex/__tests__/phase-1-conversion.test.js +154 -0
  6. package/dist/lib/kortex/__tests__/phase-2-runtime.test.js +100 -0
  7. package/dist/lib/kortex/__tests__/phase-3-provider.test.js +48 -0
  8. package/dist/lib/kortex/config/loader.js +129 -0
  9. package/dist/lib/kortex/config/schema.js +60 -0
  10. package/dist/lib/kortex/controller.js +60 -0
  11. package/dist/lib/kortex/conversation/legacy-conversion.js +141 -0
  12. package/dist/lib/kortex/conversation/types.js +13 -0
  13. package/dist/lib/kortex/events/index.js +1 -0
  14. package/dist/lib/kortex/events/reducer.js +86 -0
  15. package/dist/lib/kortex/events/types.js +7 -0
  16. package/dist/lib/kortex/events/writer.js +76 -0
  17. package/dist/lib/kortex/mcp/index.js +1 -0
  18. package/dist/lib/kortex/orchestration/index.js +1 -0
  19. package/dist/lib/kortex/orchestration/manager-worker.js +88 -0
  20. package/dist/lib/kortex/orchestration/peer-collaboration.js +59 -0
  21. package/dist/lib/kortex/orchestration/plan.js +133 -0
  22. package/dist/lib/kortex/orchestration/scheduler.js +124 -0
  23. package/dist/lib/kortex/persistence/index.js +1 -0
  24. package/dist/lib/kortex/persistence/run-journal.js +94 -0
  25. package/dist/lib/kortex/providers/anthropic.js +34 -0
  26. package/dist/lib/kortex/providers/index.js +1 -0
  27. package/dist/lib/kortex/providers/openai-compatible.js +190 -0
  28. package/dist/lib/kortex/providers/protokol.js +204 -0
  29. package/dist/lib/kortex/providers/registry.js +61 -0
  30. package/dist/lib/kortex/providers/types.js +13 -0
  31. package/dist/lib/kortex/runtime/agent-runner.js +241 -0
  32. package/dist/lib/kortex/runtime/approval-queue.js +95 -0
  33. package/dist/lib/kortex/runtime/budget-controller.js +105 -0
  34. package/dist/lib/kortex/runtime/index.js +1 -0
  35. package/dist/lib/kortex/runtime/tool-runtime.js +66 -0
  36. package/dist/lib/kortex/runtime/workspace.js +52 -0
  37. package/dist/lib/kortex/tools/index.js +1 -0
  38. package/dist/lib/kortex/tools.js +226 -34
  39. package/dist/lib/kortex/types.js +7 -0
  40. package/dist/lib/kortex/ui/index.js +1 -0
  41. package/dist/lib/kortexDevPlugin.js +392 -21
  42. package/package.json +6 -4
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Conversion between the legacy StoredMessage format and the canonical Turn model.
3
+ *
4
+ * Used during migration so existing stored conversations remain readable
5
+ * while new code paths produce Turns.
6
+ */
7
+ import { randomUUID as uuid } from 'node:crypto';
8
+ /**
9
+ * Convert a single legacy StoredMessage to one or more Turns.
10
+ *
11
+ * Legacy messages have a single `content: string` and optional `tool_calls`.
12
+ * The canonical model uses ordered ContentBlocks — one text block for content,
13
+ * separate blocks for tool calls and tool results.
14
+ */
15
+ export function storedMessageToTurns(msg) {
16
+ const now = new Date().toISOString();
17
+ const turns = [];
18
+ if (msg.role === 'tool') {
19
+ // Legacy tool result messages: content is the output, tool_call_id links
20
+ // back to the original call.
21
+ turns.push({
22
+ id: uuid(),
23
+ role: 'tool',
24
+ createdAt: now,
25
+ blocks: [
26
+ {
27
+ type: 'tool_result',
28
+ callId: msg.tool_call_id ?? 'unknown',
29
+ name: '',
30
+ output: { text: msg.content, truncated: false },
31
+ isError: msg.content.startsWith('Error:'),
32
+ },
33
+ ],
34
+ });
35
+ }
36
+ else if (msg.role === 'assistant' && msg.tool_calls && msg.tool_calls.length > 0) {
37
+ // Legacy assistant messages with tool_calls: content + parallel tool calls.
38
+ const blocks = [];
39
+ if (msg.content) {
40
+ blocks.push({ type: 'text', text: msg.content });
41
+ }
42
+ for (const tc of msg.tool_calls) {
43
+ let args = {};
44
+ try {
45
+ args = JSON.parse(tc.function?.arguments ?? '{}');
46
+ }
47
+ catch { /* keep empty */ }
48
+ blocks.push({
49
+ type: 'tool_call',
50
+ id: tc.id ?? uuid(),
51
+ name: tc.function?.name ?? 'unknown',
52
+ arguments: args,
53
+ rawArguments: tc.function?.arguments,
54
+ });
55
+ }
56
+ turns.push({ id: uuid(), role: 'assistant', createdAt: now, blocks });
57
+ }
58
+ else if (msg.role === 'context') {
59
+ // Context messages become a system-role turn (not user)
60
+ turns.push({
61
+ id: uuid(),
62
+ role: 'system',
63
+ createdAt: now,
64
+ blocks: [{ type: 'text', text: msg.content }],
65
+ });
66
+ }
67
+ else {
68
+ // Standard user or assistant text message
69
+ turns.push({
70
+ id: uuid(),
71
+ role: msg.role === 'assistant' ? 'assistant' : 'user',
72
+ createdAt: now,
73
+ blocks: msg.content ? [{ type: 'text', text: msg.content }] : [],
74
+ });
75
+ }
76
+ return turns;
77
+ }
78
+ /**
79
+ * Convert a full array of legacy stored messages to canonical Turns.
80
+ */
81
+ export function storedMessagesToTurns(messages) {
82
+ return messages.flatMap(storedMessageToTurns);
83
+ }
84
+ /**
85
+ * Convert canonical Turns back to legacy StoredMessages (for backward compat saves).
86
+ * Collapses consecutive assistant+tool_calls+tool_result sequences.
87
+ */
88
+ export function turnsToStoredMessages(turns) {
89
+ const msgs = [];
90
+ for (const turn of turns) {
91
+ const textBlocks = turn.blocks.filter((b) => b.type === 'text');
92
+ const toolCallBlocks = turn.blocks.filter((b) => b.type === 'tool_call');
93
+ const toolResultBlocks = turn.blocks.filter((b) => b.type === 'tool_result');
94
+ const reasoningBlocks = turn.blocks.filter((b) => b.type === 'reasoning_summary');
95
+ if (turn.role === 'tool') {
96
+ // Each tool_result block becomes one tool message
97
+ for (const tr of toolResultBlocks) {
98
+ msgs.push({
99
+ role: 'tool',
100
+ content: tr.output.text,
101
+ tool_call_id: tr.callId,
102
+ });
103
+ }
104
+ }
105
+ else if (toolCallBlocks.length > 0) {
106
+ // Assistant message with tool calls
107
+ const combinedContent = textBlocks.map(b => b.text).join('\n');
108
+ const msg = {
109
+ role: 'assistant',
110
+ content: combinedContent,
111
+ tool_calls: toolCallBlocks.map(tc => ({
112
+ id: tc.id,
113
+ type: 'function',
114
+ function: {
115
+ name: tc.name,
116
+ arguments: tc.rawArguments ?? JSON.stringify(tc.arguments),
117
+ },
118
+ })),
119
+ };
120
+ msgs.push(msg);
121
+ }
122
+ else if (turn.role === 'system') {
123
+ // System turns become context messages
124
+ const content = textBlocks.map(b => b.text).join('\n');
125
+ if (content) {
126
+ msgs.push({ role: 'context', content });
127
+ }
128
+ }
129
+ else {
130
+ // Standard text turn
131
+ const content = [...textBlocks, ...reasoningBlocks].map(b => ('text' in b ? b.text : '')).join('\n');
132
+ if (content || turn.blocks.length === 0) {
133
+ msgs.push({
134
+ role: turn.role === 'assistant' ? 'assistant' : 'user',
135
+ content,
136
+ });
137
+ }
138
+ }
139
+ }
140
+ return msgs;
141
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Canonical conversation model — Turn and ContentBlock types.
3
+ *
4
+ * This is the provider-neutral intermediate representation for all LLM
5
+ * conversations. Every provider adapter converts to/from this model.
6
+ *
7
+ * Key design:
8
+ * - Ordered content blocks rather than a single content string.
9
+ * - ProviderState as an opaque escape hatch for provider-specific
10
+ * continuation tokens, thinking signatures, etc.
11
+ * - ArtifactRef for cross-worker file/result references.
12
+ */
13
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,86 @@
1
+ /**
2
+ * In-memory event reducer — builds a readable run summary from a stream of RunEvents.
3
+ *
4
+ * Usage:
5
+ * const reducer = new RunEventReducer()
6
+ * for (const envelope of eventStream) {
7
+ * reducer.apply(envelope)
8
+ * }
9
+ * console.log(reducer.summary())
10
+ */
11
+ export class RunEventReducer {
12
+ state = null;
13
+ apply(envelope) {
14
+ const { runId, event } = envelope;
15
+ if (!this.state || this.state.runId !== runId) {
16
+ this.state = this.createInitialState(runId);
17
+ }
18
+ const s = this.state;
19
+ switch (event.type) {
20
+ case 'plan.approved':
21
+ s.planApproved = true;
22
+ break;
23
+ case 'task.state': {
24
+ let ts = s.tasks.get(event.taskId);
25
+ if (!ts) {
26
+ ts = { taskId: event.taskId, state: event.state, attempt: event.attempt, toolCalls: 0 };
27
+ s.tasks.set(event.taskId, ts);
28
+ }
29
+ ts.state = event.state;
30
+ ts.attempt = event.attempt;
31
+ if (event.error)
32
+ ts.error = event.error;
33
+ break;
34
+ }
35
+ case 'tool.completed':
36
+ for (const ts of s.tasks.values()) {
37
+ if (ts.taskId === event.taskId)
38
+ ts.toolCalls++;
39
+ }
40
+ s.totalToolCalls++;
41
+ break;
42
+ case 'usage.updated':
43
+ s.totalTokens.input += event.usage.inputTokens ?? 0;
44
+ s.totalTokens.output += event.usage.outputTokens ?? 0;
45
+ break;
46
+ case 'run.finished':
47
+ s.status = 'finished';
48
+ s.outcome = event.outcome;
49
+ break;
50
+ case 'run.cancel_requested':
51
+ s.status = 'finished';
52
+ s.outcome = { kind: 'cancelled', by: 'user', reason: event.reason };
53
+ break;
54
+ }
55
+ s.lastEvent = event;
56
+ return s;
57
+ }
58
+ createInitialState(runId) {
59
+ return {
60
+ runId,
61
+ status: 'running',
62
+ planApproved: false,
63
+ tasks: new Map(),
64
+ totalTokens: { input: 0, output: 0 },
65
+ totalToolCalls: 0,
66
+ lastEvent: null,
67
+ };
68
+ }
69
+ summary() {
70
+ if (!this.state)
71
+ return 'No run data.';
72
+ const s = this.state;
73
+ const lines = [
74
+ `Run: ${s.runId.slice(0, 8)} Status: ${s.status}`,
75
+ `Plan approved: ${s.planApproved}`,
76
+ `Tasks: ${s.tasks.size} Tool calls: ${s.totalToolCalls}`,
77
+ `Tokens: ${s.totalTokens.input} in / ${s.totalTokens.output} out`,
78
+ ];
79
+ for (const ts of s.tasks.values()) {
80
+ lines.push(` ${ts.state.padEnd(20)} ${ts.taskId.slice(0, 8)} att:${ts.attempt} tc:${ts.toolCalls}`);
81
+ }
82
+ if (s.outcome)
83
+ lines.push(`Outcome: ${s.outcome.kind}`);
84
+ return lines.join('\n');
85
+ }
86
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * RunEvent types — the typed event system that drives the orchestrator.
3
+ *
4
+ * Every meaningful transition emits a typed RunEvent wrapped in a
5
+ * RunEventEnvelope with sequence numbering for durability.
6
+ */
7
+ export {};
@@ -0,0 +1,76 @@
1
+ /**
2
+ * JSONL event writer — append-only file-based persistence for RunEvents.
3
+ *
4
+ * Each line is a RunEventEnvelope JSON blob. Append semantics make it
5
+ * crash-tolerant: a partial last line is detected on read and discarded.
6
+ *
7
+ * Phase 1: in-memory + file append. Phase 5 adds snapshot/checksum/resume logic.
8
+ */
9
+ import { appendFileSync, readFileSync, existsSync } from 'node:fs';
10
+ export class EventJournal {
11
+ path;
12
+ sequence = 0;
13
+ lastWritten = '';
14
+ constructor(path) {
15
+ this.path = path;
16
+ }
17
+ /**
18
+ * Append one event to the journal file.
19
+ * Returns the assigned sequence number.
20
+ */
21
+ append(envelope) {
22
+ const seq = ++this.sequence;
23
+ const record = {
24
+ ...envelope,
25
+ sequence: seq,
26
+ at: envelope.at || new Date().toISOString(),
27
+ };
28
+ const line = JSON.stringify(record) + '\n';
29
+ try {
30
+ appendFileSync(this.path, line, 'utf-8');
31
+ this.lastWritten = line;
32
+ }
33
+ catch {
34
+ // Write failures are non-fatal during Phase 1 prototyping
35
+ }
36
+ return seq;
37
+ }
38
+ /**
39
+ * Read all events since a given sequence number.
40
+ * Detects and discards a trailing incomplete line on read.
41
+ */
42
+ readFrom(afterSequence = 0) {
43
+ if (!existsSync(this.path))
44
+ return [];
45
+ const content = readFileSync(this.path, 'utf-8').trimEnd();
46
+ if (!content)
47
+ return [];
48
+ const lines = content.split('\n');
49
+ const events = [];
50
+ for (let i = 0; i < lines.length; i++) {
51
+ const line = lines[i].trim();
52
+ if (!line)
53
+ continue;
54
+ try {
55
+ const parsed = JSON.parse(line);
56
+ // Skip trailing incomplete lines (last line may be partial on crash)
57
+ if (i === lines.length - 1 && line.length < 20)
58
+ continue;
59
+ if (parsed.sequence && parsed.sequence > afterSequence) {
60
+ events.push(parsed);
61
+ }
62
+ }
63
+ catch {
64
+ // Malformed line — skip (likely a partial write)
65
+ continue;
66
+ }
67
+ }
68
+ return events;
69
+ }
70
+ /**
71
+ * Get the last written event (for crash recovery checkpointing).
72
+ */
73
+ get lastSequence() {
74
+ return this.sequence;
75
+ }
76
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Manager-worker orchestration pattern.
3
+ *
4
+ * The orchestrator (manager) plans, dispatches to workers, and
5
+ * synthesizes results. Workers run independently with the tool loop.
6
+ */
7
+ import { Scheduler } from './scheduler.js';
8
+ import { validatePlan } from './plan.js';
9
+ import { AgentRunner } from '../runtime/agent-runner.js';
10
+ import { ToolRuntime } from '../runtime/tool-runtime.js';
11
+ import { ApprovalQueue } from '../runtime/approval-queue.js';
12
+ import { BudgetController, DEFAULT_RUN_BUDGETS } from '../runtime/budget-controller.js';
13
+ /**
14
+ * Run a manager-worker orchestration.
15
+ */
16
+ export async function runManagerWorker(opts) {
17
+ const { plan, agents, provider, tools, runId, signal } = opts;
18
+ const taskResults = new Map();
19
+ // Build available tools map
20
+ const toolMap = new Map(tools.map(t => [t.function.name, t]));
21
+ // Validate plan
22
+ const validation = validatePlan(plan, agents, toolMap, DEFAULT_RUN_BUDGETS.maxTasks);
23
+ if (!validation.valid) {
24
+ return {
25
+ taskResults,
26
+ status: 'failed',
27
+ summary: `Plan validation failed: ${validation.errors.join('; ')}`,
28
+ };
29
+ }
30
+ // Build runtime
31
+ const toolRuntime = new ToolRuntime();
32
+ const approvalQueue = new ApprovalQueue();
33
+ const budgetController = new BudgetController(DEFAULT_RUN_BUDGETS);
34
+ const agentRunner = new AgentRunner(toolRuntime, approvalQueue, budgetController);
35
+ // Create scheduler
36
+ const scheduler = new Scheduler(plan.tasks, DEFAULT_RUN_BUDGETS.maxConcurrency, async (task) => {
37
+ if (signal.aborted)
38
+ return 'cancelled';
39
+ const agent = agents.get(task.agent);
40
+ if (!agent)
41
+ return 'failed';
42
+ const result = await agentRunner.run({
43
+ runId,
44
+ task,
45
+ attempt: 1,
46
+ agent,
47
+ context: {
48
+ goal: plan.goal,
49
+ taskPrompt: task.prompt,
50
+ dependencySummaries: [],
51
+ constraints: [],
52
+ contextBudgetTokens: 64_000,
53
+ },
54
+ workspace: { id: 'shared', kind: 'shared', root: process.cwd(), writable: task.mode === 'write' },
55
+ budgets: budgetController.acquire({ modelCalls: 10 }),
56
+ signal,
57
+ }, provider);
58
+ taskResults.set(task.id, result);
59
+ if (result.status === 'budget_exceeded')
60
+ return 'budget_exceeded';
61
+ if (result.status === 'cancelled')
62
+ return 'cancelled';
63
+ if (result.status === 'failed')
64
+ return 'failed';
65
+ if (result.status === 'needs_user')
66
+ return 'failed';
67
+ return 'succeeded';
68
+ });
69
+ const records = await scheduler.run();
70
+ // Determine overall status
71
+ let allSucceeded = true;
72
+ let anyCancelled = false;
73
+ for (const [, r] of records) {
74
+ if (r.status === 'failed')
75
+ allSucceeded = false;
76
+ if (r.status === 'cancelled') {
77
+ allSucceeded = false;
78
+ anyCancelled = true;
79
+ }
80
+ }
81
+ const status = anyCancelled ? 'cancelled'
82
+ : allSucceeded ? 'succeeded'
83
+ : 'completed_with_issues';
84
+ const summary = `Manager-worker run completed: ${status}. Tasks: ${records.size} total, ` +
85
+ `${Array.from(records.values()).filter(r => r.status === 'succeeded').length} succeeded, ` +
86
+ `${Array.from(records.values()).filter(r => r.status === 'failed').length} failed.`;
87
+ return { taskResults, status, summary };
88
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Peer collaboration pattern — broadcast same task to multiple agents,
3
+ * collect independent analyses, synthesize results.
4
+ *
5
+ * Phase 8+.
6
+ */
7
+ import { AgentRunner } from '../runtime/agent-runner.js';
8
+ import { ToolRuntime } from '../runtime/tool-runtime.js';
9
+ import { ApprovalQueue } from '../runtime/approval-queue.js';
10
+ import { BudgetController, DEFAULT_RUN_BUDGETS } from '../runtime/budget-controller.js';
11
+ export async function runPeerCollab(opts) {
12
+ const { task, peers, provider, runId, signal, minSuccess = 1 } = opts;
13
+ const results = new Map();
14
+ const toolRuntime = new ToolRuntime();
15
+ const approvalQueue = new ApprovalQueue();
16
+ const budgetController = new BudgetController(DEFAULT_RUN_BUDGETS);
17
+ const agentRunner = new AgentRunner(toolRuntime, approvalQueue, budgetController);
18
+ // Run all peers in parallel
19
+ const promises = peers.map(async (agent) => {
20
+ const dummyTask = {
21
+ id: agent.name,
22
+ title: task.slice(0, 60),
23
+ agent: agent.name,
24
+ prompt: task,
25
+ dependsOn: [],
26
+ required: true,
27
+ mode: 'read',
28
+ tools: agent.tools.map(t => t.function.name),
29
+ expectedPaths: [],
30
+ deliverables: ['analysis'],
31
+ acceptanceCriteria: [],
32
+ };
33
+ return agentRunner.run({
34
+ runId,
35
+ task: dummyTask,
36
+ attempt: 1,
37
+ agent,
38
+ context: { goal: task, taskPrompt: task, dependencySummaries: [], constraints: [], contextBudgetTokens: 64_000 },
39
+ workspace: { id: 'shared', kind: 'shared', root: process.cwd(), writable: false },
40
+ budgets: budgetController.acquire({ modelCalls: 5 }),
41
+ signal,
42
+ }, provider).then(r => ({ agent: agent.name, result: r }));
43
+ });
44
+ const completed = await Promise.allSettled(promises);
45
+ for (const p of completed) {
46
+ if (p.status === 'fulfilled') {
47
+ results.set(p.value.agent, p.value.result);
48
+ }
49
+ }
50
+ const successCount = results.size;
51
+ const consensus = [];
52
+ const conflicts = [];
53
+ return {
54
+ results,
55
+ synthesis: `Peer collaboration completed: ${successCount}/${peers.length} agents responded.`,
56
+ consensus,
57
+ conflicts,
58
+ };
59
+ }
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Plan schema — the validated execution plan produced by the planner
3
+ * and consumed by the scheduler.
4
+ *
5
+ * Plan validation rejects cycles, invalid agents, missing dependencies,
6
+ * tool policy violations, and budget overruns before the plan is
7
+ * presented for user approval.
8
+ */
9
+ /**
10
+ * Validate a plan before approval.
11
+ */
12
+ export function validatePlan(plan, agents, availableTools, maxTasks) {
13
+ const errors = [];
14
+ const warnings = [];
15
+ const taskIds = new Set();
16
+ // Task count
17
+ if (plan.tasks.length > maxTasks) {
18
+ errors.push(`Plan has ${plan.tasks.length} tasks, exceeding the maximum of ${maxTasks}`);
19
+ }
20
+ // Validate each task
21
+ for (const task of plan.tasks) {
22
+ // Duplicate IDs
23
+ if (taskIds.has(task.id)) {
24
+ errors.push(`Duplicate task ID: "${task.id}"`);
25
+ }
26
+ taskIds.add(task.id);
27
+ // Reserved IDs
28
+ if (task.id === 'planner' || task.id === 'finalizer') {
29
+ errors.push(`Task ID "${task.id}" is reserved`);
30
+ }
31
+ // Agent exists
32
+ if (!agents.has(task.agent)) {
33
+ errors.push(`Task "${task.id}" references unknown agent "${task.agent}"`);
34
+ }
35
+ // Mode constraints
36
+ if (task.mode === 'write') {
37
+ const agent = agents.get(task.agent);
38
+ if (agent?.name && !agent.tools.some(t => getToolRisk(t.function.name) === 'write' || getToolRisk(t.function.name) === 'execute' || getToolRisk(t.function.name) === 'destructive')) {
39
+ warnings.push(`Task "${task.id}" is write mode but agent "${task.agent}" has no write-capable tools`);
40
+ }
41
+ }
42
+ // Tool references
43
+ for (const toolRef of task.tools) {
44
+ if (toolRef !== '*' && !availableTools.has(toolRef)) {
45
+ // toolRef might be a wildcard or MCP pattern — only flag if it doesn't match anything
46
+ const matches = Array.from(availableTools.keys()).filter(k => k.startsWith(toolRef.replace('*', '')));
47
+ if (matches.length === 0) {
48
+ errors.push(`Task "${task.id}" references unknown tool "${toolRef}"`);
49
+ }
50
+ }
51
+ }
52
+ }
53
+ // Dependency validation
54
+ for (const task of plan.tasks) {
55
+ for (const dep of task.dependsOn) {
56
+ if (!taskIds.has(dep.taskId)) {
57
+ errors.push(`Task "${task.id}" depends on unknown task "${dep.taskId}"`);
58
+ }
59
+ }
60
+ }
61
+ // Cycle detection
62
+ const cycle = detectCycle(plan.tasks);
63
+ if (cycle) {
64
+ errors.push(`Dependency cycle detected: ${cycle.join(' -> ')}`);
65
+ }
66
+ // Finalizer validation
67
+ if (!agents.has(plan.finalizer.agent)) {
68
+ errors.push(`Finalizer references unknown agent "${plan.finalizer.agent}"`);
69
+ }
70
+ return { valid: errors.length === 0, errors, warnings };
71
+ }
72
+ function getToolRisk(name) {
73
+ if (name.startsWith('mcp_'))
74
+ return 'external';
75
+ const riskMap = {
76
+ read_file: 'read', write_file: 'write', edit_file: 'write',
77
+ list_directory: 'read', search_files: 'read', bash: 'execute',
78
+ git_status: 'read', git_diff: 'read', git_log: 'read',
79
+ git_commit: 'destructive', git_branch: 'write',
80
+ };
81
+ return riskMap[name] ?? 'execute';
82
+ }
83
+ /**
84
+ * Detect a cycle in the dependency graph using DFS.
85
+ * Returns the cycle path or null.
86
+ */
87
+ export function detectCycle(tasks) {
88
+ const adj = new Map();
89
+ const taskMap = new Map(tasks.map(t => [t.id, t]));
90
+ for (const t of tasks) {
91
+ adj.set(t.id, t.dependsOn.map(d => d.taskId));
92
+ }
93
+ const WHITE = 0, GRAY = 1, BLACK = 2;
94
+ const color = new Map();
95
+ const parent = new Map();
96
+ for (const t of tasks)
97
+ color.set(t.id, WHITE);
98
+ function dfs(u) {
99
+ color.set(u, GRAY);
100
+ for (const v of adj.get(u) ?? []) {
101
+ if (!color.has(v))
102
+ continue;
103
+ if (color.get(v) === GRAY) {
104
+ // Cycle found: reconstruct path
105
+ const path = [v, u];
106
+ let cur = u;
107
+ while (cur !== v && parent.has(cur)) {
108
+ cur = parent.get(cur);
109
+ if (cur !== v)
110
+ path.push(cur);
111
+ }
112
+ path.push(v);
113
+ return path.reverse();
114
+ }
115
+ if (color.get(v) === WHITE) {
116
+ parent.set(v, u);
117
+ const result = dfs(v);
118
+ if (result)
119
+ return result;
120
+ }
121
+ }
122
+ color.set(u, BLACK);
123
+ return null;
124
+ }
125
+ for (const t of tasks) {
126
+ if (color.get(t.id) === WHITE) {
127
+ const result = dfs(t.id);
128
+ if (result)
129
+ return result;
130
+ }
131
+ }
132
+ return null;
133
+ }