prism-mcp-server 7.2.0 → 7.3.3

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.
package/README.md CHANGED
@@ -28,7 +28,9 @@ Works with **Claude Desktop · Claude Code · Cursor · Windsurf · Cline · Gem
28
28
  - [What Makes Prism Different](#-what-makes-prism-different)
29
29
  - [Use Cases](#-use-cases)
30
30
  - [What's New](#-whats-new)
31
- - [v7.2 Executive Function (Roadmap)](#v720--the-executive-function-update-)
31
+ - [v7.3.1 Dark Factory (Fail-Closed Execution)](#v731--dark-factory-fail-closed-execution-)
32
+ - [v7.2.0 Verification Harness (Planned)](#v720--verification-harness-front-loaded-testing-)
33
+ - [v7.4.0 Adversarial Dev Harness (Planned)](#v740--adversarial-dev-harness-anti-sycophancy-)
32
34
  - [How Prism Compares](#-how-prism-compares)
33
35
  - [Tool Reference](#-tool-reference)
34
36
  - [Environment Variables](#environment-variables)
@@ -411,7 +413,7 @@ Soft/hard delete (Art. 17), full export in JSON, Markdown, or Obsidian vault `.z
411
413
 
412
414
  **Consulting / multi-project** — Switch between client projects with progressive loading: `quick` (~50 tokens), `standard` (~200), or `deep` (~1000+).
413
415
 
414
- **Complex refactoring (v7.2 planned)** — Prism’s roadmap adds plan-first execution for multi-step changes with persistent plan-state tracking across sessions.
416
+ **Complex refactoring (v7.2 planned)** — Prism’s roadmap adds verification-first execution for multi-step changes with contract-frozen assertions and gated finalization.
415
417
 
416
418
  **Team onboarding** — New team member's agent loads the full project history instantly.
417
419
 
@@ -440,24 +442,86 @@ Then continue a specific thread with a follow-up message to the selected agent,
440
442
 
441
443
  ## 🆕 What's New
442
444
 
443
- ### v7.2.0The "Executive Function" Update 🔭
444
- > **Planned roadmap release.** Extends Prism from persistent memory toward autonomous plan execution.
445
+ ### v7.3.1Dark Factory (Fail-Closed Execution) 🏭
446
+ > **Current stable release.** Hardened autonomous pipeline execution with a structured JSON action contract.
445
447
 
446
- - 🗺️ **Autonomous Plan Decomposition (planned)**Proposed `session_plan_decompose` tool to transform ambiguous multi-step goals into a structured task DAG.
447
- - 🔄 **Self-Healing Execution Loop (planned)** — Proposed plan-state engine to capture failed steps, suggest corrective actions, and re-queue recoverable sub-tasks before escalation.
448
- - 📉 **DAG Plan Visualizer (planned)** Proposed dashboard Plan/Goal Monitor to render step progress, dependency state, and execution pivots in real time.
449
- - 🧠 **Context-Aware Goal Tracking (planned)** Proposed active-plan injection during context loading so agents track not only prior work but current plan position.
450
- - ⚙️ **Recursive Tool Chaining (planned)** — Proposed middleware path for lower-latency plan-step updates across complex workflows.
451
- - 🧪 **Plan Integrity Tests (planned)** Proposed suite validating plan-state persistence across interruptions and session handoffs.
448
+ When an AI agent executes code autonomously no human watching, no approval step — a single hallucinated file path can write outside your project, corrupt sibling repos, or hit system files. This is the "dark factory" problem: **lights-out execution demands machine-enforced safety, not LLM good behavior.**
449
+
450
+ > *"I started building testing harnesses with programmatic checks in the planning phase across 3 layers. I got this idea when I was doing a complex ETL process across 3 databases and I needed to stack 9's on data accuracy, but also across the agent layer. After a considerable amount of hair pulling, I started to front load. It's now part of my lifecycle harness that my dark factory uses by default."*
451
+ > [Stephen Driggs](https://linkedin.com/in/stephendriggs), VP Product AI at Shift4
452
+
453
+ Prism v7.3.1 implements exactly this: a **3-gate fail-closed pipeline** where every `EXECUTE` step must pass parse, type, and scope validation before any filesystem side effect occurs.
454
+
455
+ - 🔒 **Structured Action Contract** — `EXECUTE` steps must return machine-parseable JSON conforming to `{ actions: [{ type, targetPath, content? }] }`. Free-form text is rejected at the gate.
456
+ - 🛡️ **3-Strategy Defensive Parser** — Raw JSON → fenced code block extraction → brace extraction. Handles adversarial LLM output (preamble text, markdown fences, trailing commentary) without ever executing malformed payloads.
457
+ - ✅ **Type Validation** — Only `READ_FILE | WRITE_FILE | PATCH_FILE | RUN_TEST` are permitted. Novel action types invented by the LLM are rejected.
458
+ - 📏 **Scope Validation** — Every `targetPath` is resolved against the pipeline's `workingDirectory` via `SafetyController.validateActionsInScope()`. Path traversal (`../`), sibling-prefix bypasses, and absolute paths outside the boundary are blocked.
459
+ - 🚫 **Pipeline-Level Termination** — A scope violation doesn't just fail the step — it **terminates the entire pipeline** with `status: FAILED` and emits a `failure` experience event for the ML routing layer.
460
+
461
+ <details>
462
+ <summary><strong>🔬 The 3-Gate Architecture: How a Path Traversal Attack Fails</strong></summary>
463
+
464
+ **Scenario:** An LLM running autonomously in a Dark Factory pipeline targeting `/home/user/my-app` produces this output for an EXECUTE step:
465
+
466
+ ```json
467
+ {
468
+ "actions": [
469
+ { "type": "WRITE_FILE", "targetPath": "src/utils.ts", "content": "// valid" },
470
+ { "type": "WRITE_FILE", "targetPath": "../../.ssh/authorized_keys", "content": "ssh-rsa ATTACK..." }
471
+ ]
472
+ }
473
+ ```
474
+
475
+ **Gate 1 — Parse:** ✅ Valid JSON. The 3-strategy parser extracts it cleanly.
476
+
477
+ **Gate 2 — Type:** ✅ Both actions use `WRITE_FILE`, a valid `ActionType`.
478
+
479
+ **Gate 3 — Scope:** 🚫 **BLOCKED.** `SafetyController.validateActionsInScope()` resolves `../../.ssh/authorized_keys` to `/home/user/.ssh/authorized_keys` — which is **outside** `/home/user/my-app`. The violation is detected *before* any write occurs.
480
+
481
+ **Result:** The entire pipeline is terminated immediately. No files are written — not even the valid `src/utils.ts`. A `failure` experience event is emitted so the ML router can learn to avoid this pattern.
482
+
483
+ ```
484
+ Pipeline FAILED: Scope violation — action[1] targetPath
485
+ "../../.ssh/authorized_keys" resolves outside workingDirectory
486
+ ```
487
+
488
+ **Without v7.3.1:** The LLM's raw text output would be interpreted as instructions, and the agent runtime would attempt the write — potentially succeeding depending on filesystem permissions.
489
+
490
+ **With v7.3.1:** The structured contract makes this class of attack impossible. The LLM never touches the filesystem directly; every action is validated through the 3-gate pipeline first.
491
+
492
+ </details>
493
+
494
+ <details>
495
+ <summary><strong>🧪 Edge Cases Covered (67 tests)</strong></summary>
496
+
497
+ | Category | Examples |
498
+ |----------|----------|
499
+ | **Parse adversarial output** | Prose preamble + JSON, nested fences, empty input, non-string input |
500
+ | **Type coercion** | `"DELETE_FILE"`, `"EXEC_CMD"`, numeric types, null types |
501
+ | **Path traversal** | `../`, `../../`, `/etc/passwd`, null bytes, unicode normalization, embedded newlines |
502
+ | **Shape validation** | Missing `actions` array, non-object actions, empty `targetPath`, root-type coercion |
503
+ | **Stress payloads** | 100-action arrays, 100KB content strings, 500-segment deep paths |
504
+
505
+ </details>
506
+
507
+ ### v7.2.0 — Verification Harness (Front-Loaded Testing) 🔭
508
+ > **Planned roadmap release.** Extends Prism from passive validation to contract-frozen, machine-verifiable execution gates.
509
+
510
+ - 📋 **Spec-Freeze Contract (planned)** — v7.2 formalizes three artifacts with strict responsibilities: `implementation_plan.md` (**how**), `verification_harness.json` (**proof contract**), and `validation_result` (**immutable outcome record**).
511
+ - 🔐 **Rubric Hash Lock (planned)** — `verification_harness.json` is generated before execution and hash-locked (`rubric_hash`) so criteria cannot drift mid-sprint.
512
+ - 🔬 **Multi-Layer Verification (planned)** — Structured checks across **Data Accuracy**, **Agent Behavior**, and **Pipeline Integrity** using machine-parseable assertions.
513
+ - 🤖 **Adversarial Validation Loop (planned)** — A second validation pass evaluates execution outputs against the frozen contract before progression.
514
+ - 🚦 **Finalization Gates (planned)** — Gate policies (`warn` / `gate` / `abort`) evaluate `validation_result` against the frozen rubric before pipeline completion.
515
+ - 🧠 **Routing Feedback Signals (planned)** — Router learning ingests raw verification signals (`pass_rate`, `critical_failures`, `coverage_score`, `rubric_hash`) for downstream confidence adjustment.
452
516
 
453
517
  <details>
454
518
  <summary><strong>🔬 Concept Example: Before vs. After v7.2</strong></summary>
455
519
 
456
520
  **Scenario:** "Refactor the Auth module and update the unit tests."
457
521
 
458
- **Before (linear prompting):** The agent executes in sequence but can lose place after errors unless the host prompt restates state.
522
+ **Before:** Criteria emerge during or after coding; verification is inconsistent and hard to audit.
459
523
 
460
- **After (executive planning):** Agent decomposes to a DAG, executes per-step, recovers from failures via plan-state retries, and resumes from the correct dependency node.
524
+ **After (verification-first):** Plan emits a frozen verification contract first, execution runs, validator emits immutable `validation_result`, and finalization gates enforce rubric compliance.
461
525
 
462
526
  </details>
463
527
 
@@ -739,13 +803,26 @@ Requires `PRISM_TASK_ROUTER_ENABLED=true` (or dashboard toggle).
739
803
  </details>
740
804
 
741
805
  <details>
742
- <summary><strong>Executive Planning (Planned for v7.2)</strong></summary>
806
+ <summary><strong>Dark Factory Orchestration (3 tools)</strong></summary>
807
+
808
+ Requires `PRISM_DARK_FACTORY_ENABLED=true`.
743
809
 
744
810
  | Tool | Purpose |
745
811
  |------|---------|
746
- | `session_plan_decompose` | Decompose natural language goals into a structured DAG of tasks |
747
- | `session_plan_step_update` | Atomically update the status/result of a specific sub-task |
748
- | `session_plan_get_active` | Retrieve the current execution DAG and task statuses |
812
+ | `session_start_pipeline` | Create and enqueue a background autonomous pipeline |
813
+ | `session_check_pipeline_status` | Poll the current step, iteration, and status of a pipeline |
814
+ | `session_abort_pipeline` | Emergency kill switch to halt a running background pipeline |
815
+
816
+ </details>
817
+
818
+ <details>
819
+ <summary><strong>Verification Harness (Planned for v7.2)</strong></summary>
820
+
821
+ | Tool | Purpose |
822
+ |------|---------|
823
+ | `session_plan_decompose` | Decompose natural language goals into an execution plan that references verification requirements |
824
+ | `session_plan_step_update` | Atomically update step status/result with verification context |
825
+ | `session_plan_get_active` | Retrieve active plan state and current verification gating position |
749
826
 
750
827
  </details>
751
828
 
@@ -797,6 +874,7 @@ Requires `PRISM_TASK_ROUTER_ENABLED=true` (or dashboard toggle).
797
874
  | `PRISM_ACTR_WEIGHT_SIMILARITY` | No | Composite score similarity weight (default: `0.7`) |
798
875
  | `PRISM_ACTR_WEIGHT_ACTIVATION` | No | Composite score ACT-R activation weight (default: `0.3`) |
799
876
  | `PRISM_ACTR_ACCESS_LOG_RETENTION_DAYS` | No | Days before access logs are pruned by background scheduler (default: `90`) |
877
+ | `PRISM_DARK_FACTORY_ENABLED` | No | `"true"` to enable Dark Factory autonomous pipeline tools (`session_start_pipeline`, `session_check_pipeline_status`, `session_abort_pipeline`) |
800
878
 
801
879
  </details>
802
880
 
@@ -827,6 +905,7 @@ Prism is a **stdio-based MCP server** that manages persistent agent memory. Here
827
905
  │ ↕ │
828
906
  │ ┌────────────────────────────────────────────────────┐ │
829
907
  │ │ Background Workers │ │
908
+ │ │ • Dark Factory (3-gate fail-closed pipelines) │ │
830
909
  │ │ • Scheduler (TTL, decay, compaction, purge) │ │
831
910
  │ │ • Web Scholar (Brave → Firecrawl → LLM → Ledger) │ │
832
911
  │ │ • Hivemind heartbeats & Telepathy broadcasts │ │
@@ -891,7 +970,8 @@ Prism is evolving from smart session logging toward a **cognitive memory archite
891
970
  | **v7.0** | Candidate-Scoped Spreading Activation — `S_i = Σ(W × strength)` bounded to search result set; prevents God-node dominance | Spreading activation networks (Collins & Loftus, 1975) | ✅ Shipped |
892
971
  | **v7.0** | Composite Retrieval Scoring — `0.7 × similarity + 0.3 × σ(activation)`; configurable via `PRISM_ACTR_WEIGHT_*` | Hybrid cognitive-neural retrieval models | ✅ Shipped |
893
972
  | **v7.0** | AccessLogBuffer — in-memory batch-write buffer with 5s flush; prevents SQLite `SQLITE_BUSY` under parallel agents | Production reliability engineering | ✅ Shipped |
894
- | **v7.2** | Executive Planning & DAG tracking | Prefrontal cortex executive control + Directed Acyclic Graph planning | 🔭 Horizon |
973
+ | **v7.3** | Dark Factory 3-gate fail-closed EXECUTE pipeline (parse type scope) with structured JSON action contract | Industrial safety systems (defense-in-depth, fail-closed valves) | ✅ Shipped |
974
+ | **v7.2** | Verification-first harness & contract-gated execution | Programmatic verification systems + adversarial validation loops | 🔭 Horizon |
895
975
  | **v7.x** | Affect-Tagged Memory — sentiment shapes what gets recalled | Affect-modulated retrieval (neuroscience) | 🔭 Horizon |
896
976
  | **v8+** | Zero-Search Retrieval — no index, no ANN, just ask the vector | Holographic Reduced Representations | 🔭 Horizon |
897
977
 
@@ -909,14 +989,17 @@ Shipped in v6.2.0. Edge synthesis, graph pruning with SLO observability, tempora
909
989
  ### v6.5: Cognitive Architecture ✅
910
990
  Shipped. Full Superposed Memory (SDM) + Hyperdimensional Computing (HDC/VSA) cognitive routing pipeline. Compositional memory states via XOR binding, Hamming resolution, and policy-gated routing (direct / clarify / fallback). 705 tests passing.
911
991
 
992
+ ### v7.3: Dark Factory — Fail-Closed Execution ✅
993
+ Shipped. Structured JSON action contract for autonomous `EXECUTE` steps. 3-gate validation pipeline (parse → type → scope) terminates pipelines on any violation before filesystem side effects. 67 edge-case tests covering adversarial LLM output, path traversal, and type coercion.
994
+
912
995
  ### v7.1: Prism Task Router ✅
913
996
  Shipped. Deterministic task routing (`session_task_route`) with optional experience-based confidence adjustment for host vs. local Claw delegation.
914
997
 
915
998
  ### v7.0: ACT-R Activation Memory ✅
916
999
  Shipped. Scientifically-grounded retrieval re-ranking via ACT-R base-level activation (`B_i = ln(Σ t_j^(-d))`), candidate-scoped spreading activation, parameterized sigmoid normalization, composite scoring, and zero-cold-start access log infrastructure. 49 dedicated unit tests, 705 total passing.
917
1000
 
918
- ### v7.2: Executive Function 🔭
919
- Planned. Adds autonomous plan decomposition, DAG-backed step tracking, and self-healing execution loops for complex multi-step operations.
1001
+ ### v7.2: Verification Harness 🔭
1002
+ Planned. Adds a spec-frozen verification contract (`implementation_plan.md` + `verification_harness.json` + immutable `validation_result`), multi-layer machine checks, and finalization gates before autonomous completion.
920
1003
 
921
1004
  ### Future Tracks
922
1005
  - **v7.x: Affect-Tagged Memory** — Recall prioritization improves by weighting memories with affective/contextual valence, making surfaced context more behaviorally useful.
package/dist/cli.js ADDED
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from 'commander';
3
+ import { SqliteStorage } from './storage/sqlite.js';
4
+ import { handleVerifyStatus, handleGenerateHarness } from './verification/cliHandler.js';
5
+ import * as path from 'path';
6
+ const program = new Command();
7
+ program
8
+ .name('prism')
9
+ .description('Prism Configuration & CLI')
10
+ .version('7.3.1');
11
+ const verifyCmd = program
12
+ .command('verify')
13
+ .description('Manage the verification harness');
14
+ verifyCmd
15
+ .command('status')
16
+ .description('Check the current verification state and view config drift')
17
+ .option('-p, --project <name>', 'Project name', path.basename(process.cwd()))
18
+ .option('-f, --force', 'Bypass verification failures and drift tracking constraints')
19
+ .option('-u, --user <id>', 'User ID for tenant isolation', 'default')
20
+ .option('--json', 'Emit machine-readable JSON output with stable keys')
21
+ .action(async (options) => {
22
+ const storage = new SqliteStorage();
23
+ await storage.initialize('./prism-local.db');
24
+ // H4 fix: Ensure storage is closed on exit to flush WAL and prevent data loss
25
+ try {
26
+ await handleVerifyStatus(storage, options.project, !!options.force, options.user, !!options.json);
27
+ }
28
+ finally {
29
+ await storage.close();
30
+ }
31
+ });
32
+ verifyCmd
33
+ .command('generate')
34
+ .description('Bless the current ./verification_harness.json as the canonical rubric')
35
+ .option('-p, --project <name>', 'Project name', path.basename(process.cwd()))
36
+ .option('-f, --force', 'Bypass verification failures and drift tracking constraints')
37
+ .option('-u, --user <id>', 'User ID for tenant isolation', 'default')
38
+ .option('--json', 'Emit machine-readable JSON output with stable keys')
39
+ .action(async (options) => {
40
+ const storage = new SqliteStorage();
41
+ await storage.initialize('./prism-local.db');
42
+ // H4 fix: Ensure storage is closed on exit to flush WAL and prevent data loss
43
+ try {
44
+ await handleGenerateHarness(storage, options.project, !!options.force, options.user, !!options.json);
45
+ }
46
+ finally {
47
+ await storage.close();
48
+ }
49
+ });
50
+ program.parse(process.argv);
package/dist/config.js CHANGED
@@ -241,3 +241,19 @@ export const PRISM_TASK_ROUTER_ENABLED_ENV = process.env.PRISM_TASK_ROUTER_ENABL
241
241
  export const PRISM_TASK_ROUTER_CONFIDENCE_THRESHOLD = parseFloat(process.env.PRISM_TASK_ROUTER_CONFIDENCE_THRESHOLD || "0.6");
242
242
  /** Maximum complexity score (1-10) that Claw can handle. Tasks above this → host. (Default: 4) */
243
243
  export const PRISM_TASK_ROUTER_MAX_CLAW_COMPLEXITY = parseInt(process.env.PRISM_TASK_ROUTER_MAX_CLAW_COMPLEXITY || "4", 10);
244
+ // ─── v7.2: Verification Harness ──────────────────────────────
245
+ /** Master switch for the v7.2.0 enhanced verification harness. */
246
+ export const PRISM_VERIFICATION_HARNESS_ENABLED = process.env.PRISM_VERIFICATION_HARNESS_ENABLED === "true";
247
+ /** Comma-separated list of verification layers to run. */
248
+ export const PRISM_VERIFICATION_LAYERS = (process.env.PRISM_VERIFICATION_LAYERS || "data,agent,pipeline").split(",").map(l => l.trim()).filter(Boolean);
249
+ /** Default severity floor for all assertions. Overrides individual assertion severity when higher. */
250
+ export const PRISM_VERIFICATION_DEFAULT_SEVERITY = (process.env.PRISM_VERIFICATION_DEFAULT_SEVERITY || "warn");
251
+ // ─── v7.3: Dark Factory Orchestration ─────────────────────────
252
+ // Autonomous pipeline runner: PLAN → EXECUTE → VERIFY → iterate.
253
+ // Opt-in because it executes LLM calls in the background.
254
+ /** Master switch for the Dark Factory background runner. */
255
+ export const PRISM_DARK_FACTORY_ENABLED = process.env.PRISM_DARK_FACTORY_ENABLED === "true"; // Opt-in
256
+ /** Poll interval for the runner loop (ms). Default: 30s. */
257
+ export const PRISM_DARK_FACTORY_POLL_MS = parseInt(process.env.PRISM_DARK_FACTORY_POLL_MS || "30000", 10);
258
+ /** Default max wall-clock time per pipeline (ms). Default: 15 minutes. */
259
+ export const PRISM_DARK_FACTORY_MAX_RUNTIME_MS = parseInt(process.env.PRISM_DARK_FACTORY_MAX_RUNTIME_MS || "900000", 10);
@@ -0,0 +1,77 @@
1
+ import { getLLMProvider } from '../utils/llm/factory.js';
2
+ import { OpenAIAdapter } from '../utils/llm/adapters/openai.js';
3
+ import { SafetyController } from './safetyController.js';
4
+ import { debugLog } from '../utils/logger.js';
5
+ /**
6
+ * JSON output schema instruction injected into EXECUTE step prompts.
7
+ * Forces the LLM to respond with machine-parseable structured output
8
+ * instead of free-form text. The runner validates this shape before
9
+ * any actions are applied.
10
+ */
11
+ const EXECUTE_JSON_SCHEMA = `
12
+ You MUST respond with ONLY a valid JSON object matching this schema:
13
+ {
14
+ "actions": [
15
+ {
16
+ "type": "READ_FILE" | "WRITE_FILE" | "PATCH_FILE" | "RUN_TEST",
17
+ "targetPath": "<relative path within the workspace>",
18
+ "content": "<file content for WRITE_FILE>",
19
+ "patch": "<patch content for PATCH_FILE>",
20
+ "command": "<test command for RUN_TEST>"
21
+ }
22
+ ],
23
+ "notes": "<optional summary of what you did>"
24
+ }
25
+
26
+ RULES:
27
+ - type MUST be one of: READ_FILE, WRITE_FILE, PATCH_FILE, RUN_TEST
28
+ - targetPath MUST be a relative path within the workspace
29
+ - Do NOT include any text outside the JSON object
30
+ - Do NOT use markdown code fences
31
+ - If you cannot complete the task, return: {"actions": [], "notes": "reason"}
32
+ `.trim();
33
+ /**
34
+ * Invocation wrapper that routes payload specs to the local Claw agent model (Qwen 2.5),
35
+ * or the active LLM provider as fallback.
36
+ *
37
+ * Uses SafetyController.generateBoundaryPrompt() for scope injection
38
+ * instead of inline prompt construction — single source of truth for safety rules.
39
+ *
40
+ * v7.3.1: EXECUTE steps request structured JSON output via EXECUTE_JSON_SCHEMA.
41
+ * Non-EXECUTE steps continue to use free-form text output.
42
+ */
43
+ export async function invokeClawAgent(spec, state, timeoutMs = 120000 // 2 min default timeout for internal executions
44
+ ) {
45
+ // BYOM Override: Provide path to use alternative open-source pipelines
46
+ // (e.g. through the OpenAI structured adapter which also points to local endpoints like Ollama / vLLM if configured)
47
+ const llm = spec.modelOverride
48
+ ? new OpenAIAdapter() // Bypasses the factory to route locally
49
+ : getLLMProvider();
50
+ // Scope injection via SafetyController — single source of truth
51
+ const systemPrompt = SafetyController.generateBoundaryPrompt(spec, state);
52
+ // v7.3.1: EXECUTE steps get structured JSON output instructions
53
+ const isExecuteStep = state.current_step === 'EXECUTE';
54
+ const executePrompt = isExecuteStep
55
+ ? `Based on the system instructions, execute the necessary actions for the current step (${state.current_step}).\n\n${EXECUTE_JSON_SCHEMA}`
56
+ : `Based on the system instructions, execute the necessary task for the current step (${state.current_step}). Respond with your actions and observations.`;
57
+ debugLog(`[ClawInvocation] Launching agent on pipeline ${state.id} step=${state.current_step} iter=${state.iteration} with ${timeoutMs}ms limit.${isExecuteStep ? ' (JSON mode)' : ''}`);
58
+ try {
59
+ // Timeout Promise to ensure the runner thread does not block indefinitely
60
+ const timeboundExecution = Promise.race([
61
+ llm.generateText(executePrompt, systemPrompt),
62
+ new Promise((_, reject) => setTimeout(() => reject(new Error('LLM_EXECUTION_TIMEOUT')), timeoutMs))
63
+ ]);
64
+ const result = await timeboundExecution;
65
+ return {
66
+ success: true,
67
+ resultText: result
68
+ };
69
+ }
70
+ catch (error) {
71
+ debugLog(`[ClawInvocation] Exception during generation: ${error.message}`);
72
+ return {
73
+ success: false,
74
+ resultText: error.message
75
+ };
76
+ }
77
+ }