3 Commits

7 changed files with 749 additions and 100 deletions

View File

@@ -97,6 +97,7 @@ The UI provides:
- provider selector: `codex` or `claude` - provider selector: `codex` or `claude`
- run history from `AGENT_STATE_ROOT` - run history from `AGENT_STATE_ROOT`
- forms for runtime Discord webhook settings, security policy, and manager/resource limits - forms for runtime Discord webhook settings, security policy, and manager/resource limits
- hover help on form labels with short intent guidance for each field
- manifest editor/validator/saver for schema `"1"` manifests - manifest editor/validator/saver for schema `"1"` manifests
Provider mode notes: Provider mode notes:
@@ -237,6 +238,7 @@ jq -c 'select(.severity=="critical")' .ai_ops/events/runtime-events.ndjson
- Every actor execution input now includes `security` helpers (`rulesEngine`, `createCommandExecutor(...)`) so executors can enforce shell/tool policy at the execution boundary. - Every actor execution input now includes `security` helpers (`rulesEngine`, `createCommandExecutor(...)`) so executors can enforce shell/tool policy at the execution boundary.
- Every actor execution input now includes `mcp` helpers (`resolvedConfig`, `resolveConfig(...)`, `filterToolsForProvider(...)`, `createClaudeCanUseTool()`) so provider adapters are filtered against `executionContext.allowedTools` before SDK calls. - Every actor execution input now includes `mcp` helpers (`resolvedConfig`, `resolveConfig(...)`, `filterToolsForProvider(...)`, `createClaudeCanUseTool()`) so provider adapters are filtered against `executionContext.allowedTools` before SDK calls.
- For Claude-based executors, pass `input.mcp.filterToolsForProvider(...)` and `input.mcp.createClaudeCanUseTool()` into the SDK call path so unauthorized tools are never exposed and runtime bypass attempts trigger security violations. - For Claude-based executors, pass `input.mcp.filterToolsForProvider(...)` and `input.mcp.createClaudeCanUseTool()` into the SDK call path so unauthorized tools are never exposed and runtime bypass attempts trigger security violations.
- Claude `canUseTool` permission checks normalize provider casing (`Bash` vs `bash`) before enforcing persona allowlists.
- Pipeline behavior on `SecurityViolationError` is configurable: - Pipeline behavior on `SecurityViolationError` is configurable:
- `hard_abort` (default) - `hard_abort` (default)
- `validation_fail` (retry-unrolled remediation) - `validation_fail` (retry-unrolled remediation)

View File

@@ -40,6 +40,7 @@ This middleware provides a first-pass hardening layer for agent-executed shell c
- `registry`: resolved runtime `McpRegistry` - `registry`: resolved runtime `McpRegistry`
- `resolveConfig(...)`: centralized MCP config resolution with persona tool-clearance applied - `resolveConfig(...)`: centralized MCP config resolution with persona tool-clearance applied
- `createClaudeCanUseTool()`: helper for Claude SDK `canUseTool` callback so each tool invocation is allowlist/banlist-enforced before execution - `createClaudeCanUseTool()`: helper for Claude SDK `canUseTool` callback so each tool invocation is allowlist/banlist-enforced before execution
- Tool matching is case-insensitive at invocation time to handle provider-emitted names like `Bash` versus allowlist entries like `bash`.
## Known limits and TODOs ## Known limits and TODOs

View File

@@ -5,8 +5,147 @@
- can use any openai/anthropic models - can use any openai/anthropic models
- can use multiple sets of creds - can use multiple sets of creds
# in progress # in progress
# Scheduled
# other scheduled
- persona definitions
- product
- task
- coder
- tester
- git
- handle basic git validation/maintenance
- edit + merge when conflict is low
- pass to dev when conflict is big
- task management flow outline
- what is hard coded?
- anything that isnt 100% reliant on an llm
- complete task, next task, etc
- task dependency graph aka the next task to be assigned is x
- giga do not ever let the agent call something like this, ban it if you can
- task assignment
- task init
-
- what is sent to llm?
- the minimum possible relevant data
- task prioritization
- subtask explosion
- "clarification needed" process
- init
- planning
- prioritization
- dependency graph
- subtasks
- task/subtask status updates (pending, in progress, done, failed)
- remove todoist mcp
# Considering
- adding a similar testing methodology to the python script with playwright and visual automation + banning them from hacking it with curl and whatnot
- add instruction to tell the agent under which circumstances it should consider using context7 and if it decides to use it how it should write code to interact with it rather than calling it directly
- pretty colors on terminal uwu
- agent names
- consider adding google gemini 3.1, even though it costs money it is the best prd drafter by far. might be good at tasks too
- list/select models
- selection per task/session/agent
- git orchestration
- merging
- symlinks
# consider adding these libs
1. The Control Flow: Keep Yours, But Upgrade the Math
Right now, your PipelineExecutor (Feedback #5) is handling scheduling and topological fan-out manually. This is where homegrown DAGs usually start breaking down as relationships get complex.
What the big frameworks use: They rely on established graph theory libraries to handle the execution order.
What you should adopt: Do not write your own DAG traversal logic. Bring in a lightweight library like graphlib (or a modern TypeScript equivalent) to handle the topological sorting.
2. . Tooling and Transport: The MCP SDK
You already have a src/mcp directory, which puts you ahead of the curve. But managing the low-level JSON-RPC protocol over stdio or Server-Sent Events (SSE) is notoriously fragile.
What the big frameworks use: The official @modelcontextprotocol/sdk packages provided by Anthropic.
What you should adopt: If you aren't already, replace your custom src/mcp/converters.ts logic with the official SDK. Relying on the official standard ensures your orchestrator isn't permanently hard-coupled to your current Anthropic and OpenAI subscriptions. If you decide to point this engine at your local Ollama instance running behind Traefik, a standardized MCP transport layer guarantees your tools and context will work seamlessly across both your cloud models and your local open-weight ones.
3. Process Execution: Safer Shells
When your agents execute shell commands in that AGENT_WORKTREE_ROOT, using Node's raw child_process.exec is messy. It buffers stdout/stderr poorly and makes escaping arguments dangerous.
What the big frameworks use: zx (by Google) or execa.
What you should adopt: execa is fantastic for this. It handles process timeouts, cleans up orphaned child processes automatically (crucial for your retry-unrolled DAGs), and streams stdout natively so you can pipe it directly into your domain-events bus without memory bloat.
# Completed
1. boilerplate typescript project for claude
- mcp server support
- generic mcp handlers
- specific mcp handlers for
- context7
- claude task manager
- concurrency, configurable max agent and max depth
- Extensible Resource Provisioning
- hard constraints
- soft constraints
- basic hygeine run
# epic
- agent orchestration system improvements
# module 1
- schema driven execution engine
- specific definitions handled in AgentManifest schema
- persona registry
- templated system prompts injected with runtime context
- tool clearances (stub this for now, add TODO for security implementation)
- allowlist
- banlist
- behavioral event handlers
- define how personas react to specific events ie. onTaskComplete, onValidationFail
# module 2
- actor oriented pipeline constrained by a strict directed acyclic graph
- relationship + pipeline graphs
- multi level topology
- hierarchical ie parent spawns 3 coder children
- unrolled retry pipelines ie coder1 > QA1 > Coder2 > QA2
- sequential ie product > task > coder > QA > git
- support for constraint definition for each concept (relationship, pipeline, topology)
- ie max depth, max retries
- state dependent routings
- support branching logic based on project history or repository state ie. project init requires product agent to generate prd, then task agent needs to create roadmap, once those exist future sessions skip those agents and go straight to coder agents
# module 3
- state/context manager
- stateless handoffs
- state and context are passed forwards through payloads via worktree/storage, not conversational memory
- fresh context per node execution
# module 4
- resource provisioning
- hierarchical resource suballocation
- when a parent agent spawns children, handle local resource management
- branche/sub-worktree provisioning
- suballocating deterministic port range provisioning
- extensibility to support future resource types
# epic # epic
implementation of AgentManager.runRecursiveAgent implementation of AgentManager.runRecursiveAgent
@@ -68,109 +207,352 @@ implementation of AgentManager.runRecursiveAgent
- The Abort Test: Start a parent with a 5-second sleep task, cancel the session at 1 second. Assert that the underlying LLM SDK handles were aborted and resources were released. - The Abort Test: Start a parent with a 5-second sleep task, cancel the session at 1 second. Assert that the underlying LLM SDK handles were aborted and resources were released.
- The Isolation Test: Spawn two children concurrently. Assert they are assigned non-overlapping port ranges and isolated worktree paths. - The Isolation Test: Spawn two children concurrently. Assert they are assigned non-overlapping port ranges and isolated worktree paths.
# Scheduled
- security implementation
- persona definitions
- product
- task
- coder
- tester
- git
- handle basic git validation/maintenance
- edit + merge when conflict is low
- pass to dev when conflict is big
- need to untangle
- what goes where in terms of DAG definition vs app logic vs agent behavior
- events
- what events do we have
- what personas care about what events
- how should a persona respond to an event
- where is this defined
- success/failure/retry policy definitions
- where does this go?
- what are they?
- task management flow
- init
- planning
- prioritization
- dependency graph
- subtasks
- task/subtask status updates (pending, in progress, done, failed)
# Considering
- model selection per task/session/agent
- agent "notebook"
- agent run log
- agent persona support
- ping pong support - ie. product agent > dev agent, dev agent needs clarification = ping pong back to product. same with tester > dev.
- resume session aspect of this
- max ping pong length ie. tester can only pass back once otherwise mark as failed
- max ping pong length per relationship ie dev:git can ping pong 4 times, dev:product only once, etc
- git orchestration
- merging
- symlinks
- security
- whatever existing thing has
- banned commands (look up a git repo for this)
- front end
- list available models
- specific workflows
- ui
- ci/cd
- review
- testing
# Defer
# Won't Do
# Completed
1. boilerplate typescript project for claude
- mcp server support
- generic mcp handlers
- specific mcp handlers for
- context7
- claude task manager
- concurrency, configurable max agent and max depth
- Extensible Resource Provisioning
- hard constraints
- soft constraints
- basic hygeine run
# epic # epic
- agent orchestration system improvements
# module 1 # connecting pipeline engine and recursive agent management
- schema driven execution engine - The Pipeline Engine must be the single source of truth. The Recursive Manager should not be a separate way to run agents; it should be a Utility that the Pipeline Engine calls when it hits a node that requires a "Fan-out" (hierarchical or unrolled-retry topology).
- specific definitions handled in AgentManifest schema - deprecate the standalone CLI examples for runRecursiveAgent and instead wire the Manager directly inside SchemaDrivenExecutionEngine.runSession
- persona registry # execution driven topologies
- templated system prompts injected with runtime context - currently, manifest validates that a topology is, for example, "hierarchical." But at runtime, the code just ignores that label and runs everything sequentially
- tool clearances (stub this for now, add TODO for security implementation) - The execution loop needs a true DAG Runner
- allowlist - When the Orchestrator evaluates the next nodes to run, if it sees a "hierarchical" or "parallel" topology block, it must dispatch those nodes to the AgentManager concurrently using Promise.all(), rather than waiting for one to finish before starting the next
- banlist # project scoped data store
- behavioral event handlers - implement a ProjectContext store. Sessions should read from the global Project State on initialization, and write their metadata updates back to the Project State upon successful termination
- define how personas react to specific events ie. onTaskComplete, onValidationFail - store should contain these domains
# module 2 - global flags
- actor oriented pipeline constrained by a strict directed acyclic graph - artifact pointers
- relationship + pipeline graphs - task queue
- multi level topology - dag orchestrator reads file at init and writes to it upon node completion
- hierarchical ie parent spawns 3 coder children # typed domain event bus
- unrolled retry pipelines ie coder1 > QA1 > Coder2 > QA2 - Implement a strongly-typed Event Bus or a Domain Event schema.
- sequential ie product > task > coder > QA > git - Create a standard payload shape for events
- support for constraint definition for each concept (relationship, pipeline, topology) - The Pipeline should allow edges to trigger based on specific domain events, not just basic success/fail strings
- ie max depth, max retries - planning events - These events occur when the project state is empty or a new major feature is requested. They transition the system from "idea" to "actionable work."
- state dependent routings - requirements defined
- support branching logic based on project history or repository state ie. project init requires product agent to generate prd, then task agent needs to create roadmap, once those exist future sessions skip those agents and go straight to coder agents - product agent triggers upon prd completion > task agent consumes
# module 3 - tasks planned
- state/context manager - task agent triggers upon completion of dedicated claude-task-manager process > coder agent consumes
- stateless handoffs - execution events - These are the most common events. They handle the messy reality of writing code and the cyclical (but unrolled) retry pipelines.
- state and context are passed forwards through payloads via worktree/storage, not conversational memory - code committed
- fresh context per node execution - task blocked (needs clarification, impossible task, max retry etc)
# module 4 - validation events - These events dictate whether the DAG moves forward to integration or branches sideways into a retry pipeline.
- resource provisioning - validation passed
- hierarchical resource suballocation - validation failed
- when a parent agent spawns children, handle local resource management - integration events - This event closes the loop and updates the global state.
- branche/sub-worktree provisioning - branch merged (also tasks updated etc)
- suballocating deterministic port range provisioning # retry matrix and cancellation
- extensibility to support future resource types - Implement a Status Retry Matrix and enforce AbortSignal everywhere
- Validation_Fail: Trigger the unrolled retry pipeline (send the error back to a new agent instance)
- Hard_Failure (>=2 sequential API timeouts, network drops, 403, etc): Fail fast, do not burn tokens retrying. Bubble the error up to the user
- Pass standard AbortSignal objects down into the ActorExecutionInput so the pipeline can instantly kill rogue processes.
# code review epic
- Header alias inconsistency can break Claude MCP auth/config
- Normalize the config object immediately upon parsing in src/mcp/converters.ts, mapping both headers and http_headers to a single internal representation before either the Codex or Claude handlers touch them
- Update src/agents/pipeline.ts to compute an aggregate status. You should traverse the execution records and ensure all terminal nodes (leaves) in your DAG have a status of "success". If any node in the critical path fails, the whole session should be marked as a failure
- file persistence is not atomic, project-context serialization is process-local only
- Implement atomic writes
- Direct writes in state/context: src/agents/state-context.ts:203, src/agents/state-context.ts:251, src/agents/project-
context.ts:171, src/agents/project-context.ts:205.
- Queue in FileSystemProjectContextStore (src/agents/project-context.ts:145) protects only within one process.
- pipeline executor owns too many responsibilities
- Start extracting distinct policies.
- Move failure classification (hard vs soft fails) into a dedicated FailurePolicy class.
- Move persistence and event emissions into a LifecycleObserver or event bus listener rather than keeping them hardcoded in the execution loop
- Global mutable MCP handler registry limits extensibility/test isolation
- Refactor the registry into an instantiable class (e.g., McpRegistry)
- Pass this instance into your SchemaDrivenExecutionEngine and PipelineExecutor via dependency injection instead of relying on auto-installing imports
- Provider example entrypoints duplicate orchestration pattern
- Create a unified helper like createSessionContext(provider, config) that handles the provisioning, probing, and prompting loop, keeping the provider-specific code strictly limited to model initialization
- Config/env parsing is duplicated
- Create a single src/config.ts (or dedicated config service) that parses process.env, validates it, applies defaults, and freezes the object.
- Inject this single source of truth throughout the app
- Project context parsing is strict
- Update src/agents/project-context.ts:106 to merge parsed files with a set of default root keys
- Add a schemaVersion field to the JSON structure to allow for safe migrations later
# security middleware
- rely on an established AST (Abstract Syntax Tree) parser for shell scripts like bash-parser to handle tokenization
- Use an off-the-shelf parser to break commands down into executable binaries, flags, arguments, and environment variable assignments. We can scrub or inject specific environment variables securely at this layer
- focus specifically on extracting Command and Word nodes from the bash-parser output
- gives us a head start on exactly what part of the syntax tree matters for the allowlist
- AI agents frequently chain commands (&&, ||, |, >) to save turns. If your parser struggles with complex pipelines or subshells, it will artificially cripple the agents' ability to work efficiently
- rules engine
- For the simplest iteration, defining your allowlists and tool clearance schema via strictly typed Zod schemas is the most lightweight approach. You validate the AST output against the schema before passing it to the execution layer
- Implement strict binary allowlists (e.g., git, npm, node, cat) and enforce directory-bound execution (ensuring the cwd stays within AGENT_WORKTREE_ROOT)
- block path traversal attempts (e.g., ../). Even if the cwd starts in the worktree, an agent might try to read or write outside of it using relative paths in its arguments
- method for logging and profiling exactly what commands Codex and Claude are currently emitting to build a baseline allowlist for longer term best practices
- make clear todos around the need to replace/improve this
- sandbox/execution layer
- Execute commands using Node's child_process with explicitly dropped privileges (running as a non-root user via uid/gid), enforce timeouts, and stream stdout/stderr to your existing event bus for auditing.
- By default, Node child processes inherit the parent's environment variables. ensure that our env management policy is consistent and secure given this behavior
- A very modern pattern is to use your Node orchestrator to spawn a deno run child process. You can pass explicit flags like --allow-read=/target/worktree and --allow-run=git,npm. If the LLM tries to read an env file outside that directory, the Deno runtime instantly kills the process at the OS level.
- agents need to modify files in AGENT_WORKTREE_ROOT, but they must absolutely not have write access to AGENT_STATE_ROOT or AGENT_PROJECT_CONTEXT_PATH. The security middleware must strictly enforce this boundary.
- Your PipelineExecutor currently routes validation_fail into a retry-unrolled execution. You will need to define a new error class (e.g., SecurityViolationError). Should a security violation trigger a retry (telling the LLM "You can't do that, try another way"), or should it instantly hard-abort the pipeline?
- Your MCP tools currently have auto-installed builtins. The rules engine needs to apply not just to shell commands, but also to MCP tool calls. The schema for tool clearance (currently a TODO at src/agents/persona-registry.ts:79) needs to be unified with this new rules engine
- schema differences between claude and codex - no clue if we are doing anything for this
- MCP config boundary only verifies that the config is an "object" before casting it, risking late-stage crashes. Furthermore, the shared MCP type is missing the sdk (in-process) transport type supported by Claude
- Create a strict Zod schema for MCP configuration
- Define McpConfigSchema using Zod to strictly validate field shapes, ranges, and enums before handoff. Update src/mcp/types.ts to include sdk alongside stdio, http, and sse in your shared transport union
- Provider-specific MCP fields like enabled_tools and timeouts are used by Codex but silently dropped during conversion for Claude. This violates user expectations
- Fail fast or warn loudly: If the provider is set to Claude and these asymmetric fields are present in the parsed config, emit a clear warning log (e.g., [WARN] MCP field 'timeouts' is not supported by the Claude adapter and will be ignored)
- The SDK adapters are under-tested. The test suite covers converters and registries but misses the actual execution wiring, stream handling, and result parsing for Codex and Claude
- Implement integration/unit tests for the adapter boundaries
- add support CLAUDE_CODE_OAUTH_TOKEN instead of api key
- ensure your configuration schema can accept the new OAuth token. To keep it backward-compatible with standard API keys (in case you ever need to switch back), you can check for the OAuth token first, then fall back to the standard API key.
- runClaudePrompt drops the parsed config and lets the SDK auto-discover process.env.ANTHROPIC_API_KEY.
- You need to explicitly pass the anthropicToken from your configuration into the underlying Anthropic client constructor. Depending on how you are instantiating the Agent SDK, you will pass it via the authToken or apiKey property
- found evidence of this drift in src/agents/provisioning.ts#L94. You will need to apply the exact same explicit wiring pattern there. Any time you instantiate the Anthropic client or the Claude Agent in a worker node, pass { apiKey: config.provider.anthropicToken }.
- rip out legacy/deprecated interfaces ie legacy status triggers, deprecated subagent method, etc
- recursive agent deprecation thing
# epic
legacy/deprecated interfaces
# Phase 1: Safe & Focused Cleanups (Low/Medium Risk)
These can be bundled into a single PR or tackled as quick, independent tasks. They have minimal blast radius and clear mitigation paths.
Legacy status history duplication: * Action: Remove the historyEvent singular path in favor of the domain-event history. Migrate conditions from validation_fail to validation_failed.
Impact: Requires updating orchestration tests (tests/orchestration-engine.test.ts) and history semantics documentation.
Remove internal Claude token (anthropicToken):
Action: Simplify the resolver in src/config.ts to oauth/api only and drop the property.
Impact: Update config tests. Low risk, but constitutes an API shape change.
Remove MCP legacy header alias (http_headers):
Action: Drop from shared schema/type (src/mcp/types.ts) and converter merge logic (src/mcp/converters.ts).
Impact: Medium risk due to external config compatibility. Crucial: You must add a migration note for users utilizing external MCP configs.
Remove legacy edge trigger aliases (Alias-only):
Action: Remove the onTaskComplete and onValidationFail aliases only.
Impact: Safe to do now, as it shrinks the legacy surface area without breaking the core edge.on functionality currently heavily relied upon in tests.
# Phase 2: Staged Removals (Requires Care)
This item is deeply integrated and needs a multi-step replacement strategy rather than a direct deletion.
Deprecate runRecursiveAgent API:
Action: First, update the Pipeline (src/agents/pipeline.ts) to use the new private replacement call path for recursive execution. Only after the pipeline is successfully rerouted and the manager tests are updated should you remove the public deprecated wrapper.
README Impact: You will need to remove or update the note in the "Notes" section of your README that currently advertises AgentManager.runRecursiveAgent(...) for low-level testing.
# Phase 3 legacy/deprecated interfaces BIG AND SCARY
Switching to un-ts/sh-syntax is exactly the right move. It is a WebAssembly (WASM) wrapper around Go's highly respected mvdan/sh parser. It provides rigorous POSIX/Bash compliance and, crucially, ships with strict, native TypeScript definitions for its entire AST.
Here is the updated implementation guide tailored specifically to integrating un-ts/sh-syntax into your security middleware.
Phase 1: Dependency Migration
Remove the Legacy Code:
npm uninstall bash-parser
rm src/types/bash-parser.d.ts
Install the Replacement:
npm install sh-syntax
Phase 2: Rewrite the AST Adapter (src/security/shell-parser.ts)
The most significant architectural shift here is that sh-syntax is WASM-backed, making the parsing operation asynchronous. Your adapter and the calling security middleware must be updated to handle Promises.
You will also map your traversal logic to the mvdan/sh AST structures (e.g., File, Stmt, CallExpr, Word).
TypeScript
import { parse } from 'sh-syntax';
// Note: Depending on your runtime environment, you may need to configure the WASM loader
// via `import { getProcessor } from 'sh-syntax'` if standard Node resolution isn't sufficient.
export interface CommandTarget {
binary: string;
args: string[];
}
export async function extractExecutionTargets(shellInput: string): Promise<CommandTarget[]> {
const targets: CommandTarget[] = [];
// sh-syntax parsing is async due to WASM initialization
const ast = await parse(shellInput);
// Walk the AST. sh-syntax types closely mirror mvdan/sh Go types.
// The root is typically a 'File' containing a list of 'Stmt' (Statements).
if (!ast || !ast.StmtList || !ast.StmtList.Stmts) return targets;
for (const stmt of ast.StmtList.Stmts) {
const cmd = stmt.Cmd;
// Check if the command is a standard function/binary call
if (cmd && cmd.type === 'CallExpr') {
const args = cmd.Args;
if (args && args.length > 0) {
// The first argument in a CallExpr is the binary name
// You must strictly check that the binary is a literal (Word) and not computed
const binaryWord = args[0];
const binaryName = extractLiteralWord(binaryWord);
if (!binaryName) {
throw new SecurityViolationError("Dynamic or computed binary names are blocked.");
}
targets.push({
binary: binaryName,
args: args.slice(1).map(extractLiteralWord).filter(Boolean) as string[]
});
}
}
// Important: Explicitly reject subshells or commands your engine doesn't support
if (cmd && cmd.type === 'Subshell') {
throw new SecurityViolationError("Subshell execution is not permitted by security policy.");
}
// Analyze redirects to ensure they don't overwrite protected files (like state roots)
if (stmt.Redirs) {
enforceRedirectPolicy(stmt.Redirs);
}
}
return targets;
}
// Helper to safely extract string literals from Word nodes
function extractLiteralWord(wordNode: any): string | null {
// In sh-syntax, a Word contains Parts (Lit, SglQuoted, DblQuoted, ParamExp, etc.)
// You must enforce that the parts only consist of safe literals, rejecting ParamExp ($VAR).
// ...
}
Phase 3: Synchronize Orchestration & Middleware
Because extractExecutionTargets is now async:
Update SecureCommandExecutor: The constructor or initialization hook where you validate the command against your allowlists must await the parsing step.
Actor Execution Boundary: Ensure that wherever the LLM outputs a shell command during the DAG execution, the pipeline waits for the AST security validation before proceeding.
Phase 4: Strict Schema Alignment (src/security/schemas.ts)
Your Zod schemas do not need to validate the sh-syntax AST directly (since it is already strictly typed by the library). Instead, use Zod to validate the output array (CommandTarget[]) to ensure nothing slipped past the parser.
Update the execution schema: Ensure it enforces .strict() so that if extractExecutionTargets accidentally returns extraneous fields, the engine panics and fails closed.
Unified Allowlist validation: Ensure the extracted binary string is strictly validated against your AGENT_SECURITY_ALLOWED_BINARIES Zod array.
Phase 5: Revalidate Security Parity (tests/security-middleware.test.ts)
This is the final gate. The new AST structure handles complex bash semantics differently than the old untyped parser.
WASM Test Environment: Ensure your test runner (Jest, Vitest) is configured to load WebAssembly properly, or the parse function will throw an initialization error in CI.
Regression Threat Matrix:
echo $(unauthorized_bin) -> Must be caught and throw SecurityViolationError (Subshell).
allowed_bin && unauthorized_bin -> The StmtList must iterate over both commands and block the execution due to the second binary.
allowed_bin > /path/to/protected/file -> The Redirs property on the Stmt must trigger your boundary violation logic.
- review/update of readme, docs, and conf files where needed
- mvp for analytics + user notification logging
# giga model specific behavior and strict task agent control stuff
i am too dumb to understand it, but gemini 3.1 makes it sound like a really good idea
Architecture Brief: Deterministic Agent Execution & Policy Enforcement
Context & Goal
We are refactoring the execution layer to ensure low-level control over task agents (e.g., task_sync, task_plan_llm). The goal is to move away from open-ended, non-deterministic agent behavior and enforce a strict 4-layer control model where the LLM acts only as a bounded step within a hard-coded state machine.
The Problem Statement
We currently have a critical gap in our enforcement boundary that allows policy bypasses, compounded by provider-specific SDK quirks:
The Context Drop (The MCP Gap): The mcpRegistry (which defines our tool policies) is resolved globally at the orchestration layer, but it is not passed down into pipeline.ts or the ActorExecutor. As a result, the low-level execution nodes operate without awareness of the active tool clearance policies.
The Claude SDK Leakage: The Anthropic Claude SDK currently ignores the shared enabled_tools configuration in the MCP payload. If we rely solely on the shared MCP config, Claude can hallucinate and execute unauthorized tool calls.
The Anti-Pattern Risk: The initial proposal to fix this was to pass the entire mcpRegistry down into the ActorExecutor so it could self-regulate. This is a severe anti-pattern. It tightly couples our low-level execution sandbox with our high-level orchestration logic, forcing the "dumb" executor to parse topologies, phases, and complex registry configurations.
The Solution: The ResolvedExecutionContext Pattern
To close the enforcement gap without violating the Inversion of Control principle, we will implement a strict separation of concerns. The Orchestrator will handle the logic; the Executor will handle the enforcement.
Instead of passing down the full registry, the orchestration layer will pre-compute a flat, immutable policy payload for that specific node attempt and inject it into the executor.
Implementation Directives
Introduce ResolvedExecutionContext:
Create an interface that represents the fully resolved, un-negotiable constraints for a single execution step.
TypeScript
export interface ResolvedExecutionContext {
phase: string;
modelConstraint: string; // e.g., 'claude-3-haiku'
allowedTools: string[]; // Flat array of resolved tool names
security: {
dropUid: boolean;
worktreePath: string;
// ... other hard constraints
}
}
Update Orchestration (pipeline.ts):
Before invoking an actor, the pipeline must read the AgentManifest for the current node, cross-reference its toolClearance with the mcpRegistry, and generate the ResolvedExecutionContext.
Lock Down the Executor (executor.ts):
The ActorExecutor must accept this context and enforce it blindly:
Model Enforcement: Force the SDK initialization to strictly use context.modelConstraint.
Tool Enforcement (Claude Fix): Explicitly filter the tools passed into the provider SDK using context.allowedTools, physically preventing the Claude SDK from seeing tools outside its clearance.
Security Middleware: Pass context.allowedTools into the SecurityRulesEngine so any runtime attempt to bypass the SDK constraints results in an immediate AGENT_SECURITY_VIOLATION_MODE=hard_abort.
Expected Outcome
The execution nodes remain entirely decoupled from the orchestration state. The LLM cannot escalate its model tier or access unauthorized tools, and the provider SDK quirks are mitigated at the execution boundary.
# epic
# front end ui requirements
1. Graph Visualizer
Your initial thoughts on coloring by stage/agent and showing metadata (subtasks, tool calls, security violations) are spot-on. Because your backend relies heavily on DAG execution and a retry matrix, the visualizer will be the most critical piece of the UI.
What else is worth visualizing?
Based on your README, here are specific concepts you should expose on the graph:
Topology & Control Flow: Visually distinguish between sequential, parallel, hierarchical, and retry-unrolled branches. For example, a retry-unrolled node should visually indicate that it spawned a new child manager session to remediate a validation_fail.
Domain Event Edges: Since your pipeline edges route via typed events (requirements_defined, validation_failed), labeling the edges of the graph with the specific domain event that triggered the transition will make debugging orchestration loops much easier.
Economics & Performance (from Runtime Events): Your NDJSON events log tokenInput, tokenOutput, durationMs, and costUsd. Surfacing the "cost" or "time" of a specific DAG node directly on the graph helps identify inefficient prompts or agents.
the "Sandbox Payload": When a user clicks or hovers over a specific node (e.g., task_plan_llm), the UI must display the ResolvedExecutionContext payload that was injected into it
Critical Path & Abort Status: If a session fails due to two consecutive hard failures, visually highlighting the exact "critical path" that led to the AbortSignal cascading through the system will save hours of log-diving.
2. Notification / Webhook Interface
Your backend already has an elegant fan-out system (NDJSON analytics log + Discord webhook). The UI should act as a control panel and an in-app inbox for this.
Configuration: A form to manage AGENT_RUNTIME_DISCORD_WEBHOOK_URL, AGENT_RUNTIME_DISCORD_MIN_SEVERITY, and the ALWAYS_NOTIFY_TYPES CSV.
Live Event Feed: A real-time drawer or panel that tails the .ai_ops/events/runtime-events.ndjson file. You can parse the severity field to color-code the feed (e.g., flashing red for critical security mirror events like security.shell.command_blocked).
3. Job Trigger Interface
This is your execution entrypoint (SchemaDrivenExecutionEngine.runSession).
Inputs: A clean interface to provide the initial prompt/task, select the Manifest or Topology they want to run, and override global flags.
The "Kill Switch": Since every actor execution respects an AbortSignal, your UI needs a prominent, highly responsive "Cancel Run" button that immediately aborts child recursive work.
Run History: A table view summarizing aggregate session status from AGENT_STATE_ROOT, allowing users to click into past runs to view their graph state.
4. Definition Interface (Manifest, Config, Security)
You noted that anything secure stays on the backend. The frontend here should strictly be a client that reads/writes validated JSON or environment schemas.
Manifest Builder: A UI to visually build or edit the AgentManifest (Schema "1"), defining personas, tool-clearance policies, modelConstraint (or allowedModel), and setting maxDepth/maxRetries.
Security Policy Management: An interface mapped to src/security/schemas.ts. This allows admins to define AGENT_SECURITY_ALLOWED_BINARIES, toggle AGENT_SECURITY_VIOLATION_MODE (hard_abort vs validation_fail), and manage MCP tool allowlists/banlists.
Environment & Resource Limits: Simple forms to configure agent manager limits (AGENT_MAX_CONCURRENT) and port block sizing without manually editing the .env file.

View File

@@ -458,6 +458,38 @@ function toToolNameCandidates(toolName: string): string[] {
return dedupeStrings(candidates); return dedupeStrings(candidates);
} }
function buildCaseInsensitiveToolLookup(tools: readonly string[]): Map<string, string> {
const lookup = new Map<string, string>();
for (const tool of tools) {
const normalized = tool.trim().toLowerCase();
if (!normalized || lookup.has(normalized)) {
continue;
}
lookup.set(normalized, tool);
}
return lookup;
}
function resolveAllowedToolMatch(input: {
candidates: readonly string[];
allowset: ReadonlySet<string>;
caseInsensitiveLookup: ReadonlyMap<string, string>;
}): string | undefined {
const direct = input.candidates.find((candidate) => input.allowset.has(candidate));
if (direct) {
return direct;
}
for (const candidate of input.candidates) {
const match = input.caseInsensitiveLookup.get(candidate.toLowerCase());
if (match) {
return match;
}
}
return undefined;
}
function defaultEventPayloadForStatus(status: ActorResultStatus): DomainEventPayload { function defaultEventPayloadForStatus(status: ActorResultStatus): DomainEventPayload {
if (status === "success") { if (status === "success") {
return { return {
@@ -1177,6 +1209,7 @@ export class PipelineExecutor {
private createToolPermissionHandler(allowedTools: readonly string[]): ActorToolPermissionHandler { private createToolPermissionHandler(allowedTools: readonly string[]): ActorToolPermissionHandler {
const allowset = new Set(allowedTools); const allowset = new Set(allowedTools);
const caseInsensitiveAllowLookup = buildCaseInsensitiveToolLookup(allowedTools);
const rulesEngine = this.securityContext?.rulesEngine; const rulesEngine = this.securityContext?.rulesEngine;
const toolPolicy = toAllowedToolPolicy(allowedTools); const toolPolicy = toAllowedToolPolicy(allowedTools);
@@ -1192,7 +1225,11 @@ export class PipelineExecutor {
} }
const candidates = toToolNameCandidates(toolName); const candidates = toToolNameCandidates(toolName);
const allowMatch = candidates.find((candidate) => allowset.has(candidate)); const allowMatch = resolveAllowedToolMatch({
candidates,
allowset,
caseInsensitiveLookup: caseInsensitiveAllowLookup,
});
if (!allowMatch) { if (!allowMatch) {
rulesEngine?.assertToolInvocationAllowed({ rulesEngine?.assertToolInvocationAllowed({
tool: candidates[0] ?? toolName, tool: candidates[0] ?? toolName,

View File

@@ -120,6 +120,101 @@ const MANIFEST_EVENT_TRIGGERS = [
const RUN_MANIFEST_EDITOR_VALUE = "__editor__"; const RUN_MANIFEST_EDITOR_VALUE = "__editor__";
const RUN_MANIFEST_EDITOR_LABEL = "[Use Manifest Editor JSON]"; const RUN_MANIFEST_EDITOR_LABEL = "[Use Manifest Editor JSON]";
const LABEL_HELP_BY_CONTROL = Object.freeze({
"session-select": "Select which session the graph and feed should focus on.",
"graph-manifest-select": "Choose the manifest context used when rendering the selected session graph.",
"run-prompt": "Describe the task objective you want the run to complete.",
"run-manifest-select": "Choose a saved manifest or use the JSON currently in the editor.",
"run-execution-mode": "Use provider for live model execution or mock for simulated execution.",
"run-provider": "Choose which model provider backend handles provider-mode runs.",
"run-topology-hint": "Optional hint that nudges orchestration toward a topology strategy.",
"run-flags": "Optional JSON object passed in as initial run flags.",
"run-validation-nodes": "Optional comma-separated node IDs to simulate validation outcomes for.",
"events-limit": "Set how many recent runtime events are loaded per refresh.",
"cfg-webhook-url": "Webhook endpoint that receives runtime event notifications.",
"cfg-webhook-severity": "Minimum severity level that triggers webhook notifications.",
"cfg-webhook-always": "Event types that should always notify, regardless of severity.",
"cfg-security-mode": "Policy behavior used when a command violates security rules.",
"cfg-security-binaries": "Comma-separated command binaries permitted by policy.",
"cfg-security-timeout": "Maximum command execution time before forced timeout.",
"cfg-security-inherit": "Environment variable names to pass through to subprocesses.",
"cfg-security-scrub": "Environment variable names to strip before command execution.",
"cfg-limit-concurrent": "Maximum number of agents that can run concurrently across sessions.",
"cfg-limit-session": "Maximum number of agents that can run concurrently within a single session.",
"cfg-limit-depth": "Maximum recursive spawn depth allowed for agent tasks.",
"cfg-topology-depth": "Maximum orchestration graph depth permitted by topology rules.",
"cfg-topology-retries": "Maximum retry expansions allowed by topology orchestration.",
"cfg-relationship-children": "Maximum children each persona relationship can spawn.",
"cfg-port-base": "Starting port number for provisioning port allocations.",
"cfg-port-block-size": "Number of ports reserved per allocated block.",
"cfg-port-block-count": "Number of port blocks available for allocation.",
"cfg-port-primary-offset": "Offset within each block used for the primary service port.",
"manifest-path": "Workspace-relative manifest file path to load, validate, or save.",
"helper-topology-sequential": "Allow sequential execution topology in this manifest.",
"helper-topology-parallel": "Allow parallel execution topology in this manifest.",
"helper-topology-hierarchical": "Allow hierarchical parent-child execution topology.",
"helper-topology-retry-unrolled": "Allow retry-unrolled topology for explicit retry paths.",
"helper-topology-max-depth": "Top-level cap on orchestration depth in this manifest.",
"helper-topology-max-retries": "Top-level cap on retry attempts in this manifest.",
"helper-entry-node-id": "Node ID used as the pipeline entry point.",
"helper-persona-id": "Stable persona identifier referenced by nodes and relationships.",
"helper-persona-display-name": "Human-readable persona name shown in summaries and tooling.",
"helper-persona-model-constraint": "Optional model restriction for this persona only.",
"helper-persona-system-prompt": "Base prompt template that defines persona behavior.",
"helper-persona-allowlist": "Comma-separated tool names this persona may use.",
"helper-persona-banlist": "Comma-separated tool names this persona must not use.",
"helper-relationship-parent": "Parent persona ID that can spawn or delegate to the child.",
"helper-relationship-child": "Child persona ID allowed under the selected parent.",
"helper-relationship-max-depth": "Optional override limiting recursion depth for this relationship.",
"helper-relationship-max-children": "Optional override limiting child fan-out for this relationship.",
"helper-node-id": "Unique pipeline node identifier used by entry node and edges.",
"helper-node-actor-id": "Runtime actor identifier assigned to this node.",
"helper-node-persona-id": "Persona applied when this node executes.",
"helper-node-topology-kind": "Optional node-level topology override.",
"helper-node-block-id": "Optional topology block identifier for grouped scheduling logic.",
"helper-node-max-retries": "Optional node-level retry limit override.",
"helper-edge-from": "Source node where this edge starts.",
"helper-edge-to": "Target node activated when this edge condition matches.",
"helper-edge-trigger-kind": "Choose whether edge activation is status-based or event-based.",
"helper-edge-on": "Node status value that triggers this edge when using status mode.",
"helper-edge-event": "Domain event name that triggers this edge when using event mode.",
"helper-edge-when": "Optional JSON array of additional conditions required to follow the edge.",
});
function extractLabelText(label) {
const clone = label.cloneNode(true);
for (const field of clone.querySelectorAll("input, select, textarea")) {
field.remove();
}
return clone.textContent?.replace(/\s+/g, " ").trim() || "this field";
}
function applyLabelTooltips(root = document) {
for (const label of root.querySelectorAll("label")) {
const control = label.querySelector("input,select,textarea");
if (!control) {
continue;
}
let help = LABEL_HELP_BY_CONTROL[control.id] || "";
if (!help) {
for (const className of control.classList) {
help = LABEL_HELP_BY_CONTROL[className] || "";
if (help) {
break;
}
}
}
if (!help) {
const labelText = extractLabelText(label).toLowerCase();
help = `Set ${labelText} for this configuration.`;
}
label.title = help;
control.title = help;
}
}
function fmtMoney(value) { function fmtMoney(value) {
return `$${Number(value || 0).toFixed(4)}`; return `$${Number(value || 0).toFixed(4)}`;
} }
@@ -575,6 +670,8 @@ function renderManifestHelper() {
`; `;
}) })
.join(""); .join("");
applyLabelTooltips(dom.manifestForm);
} }
function readManifestDraftFromHelper() { function readManifestDraftFromHelper() {
@@ -1737,6 +1834,7 @@ async function refreshAll() {
async function initialize() { async function initialize() {
bindUiEvents(); bindUiEvents();
applyLabelTooltips();
try { try {
await apiRequest("/api/health"); await apiRequest("/api/health");

49
test_run.md Normal file
View File

@@ -0,0 +1,49 @@
• For this repo, a “test run” can mean 3 different things. Configure based on which one you want.
1. npm run verify (typecheck + tests + build)
- Required:
- Node + npm
- Dependencies installed: npm install
- Not required:
- API keys
- Command:
- npm run verify
2. UI dry run (no external model calls, safest first run)
- Required:
- npm install
- topologies, personas, relationships, topologyConstraints
- pipeline with entryNodeId, nodes, edges
3. Provider-backed run (Codex/Claude via CLI or UI executionMode=provider)
- Required:
- Everything in #2
- Auth for chosen provider:
- Codex/OpenAI: OPENAI_AUTH_MODE + (CODEX_API_KEY or OPENAI_API_KEY) or existing Codex login
- Claude: CLAUDE_CODE_OAUTH_TOKEN (preferred) or ANTHROPIC_API_KEY or existing Claude login
- git available and workspace is a valid git repo (runtime provisions git worktrees)
- Optional:
- mcp.config.json (default missing file is allowed if path is default)
- Important:
- If you set custom MCP_CONFIG_PATH, that file must exist.
Environment groups you can tune (defaults already exist)
- Provider/auth: keys, auth mode, base URL, model, MCP path
- Limits: AGENT_MAX_*, AGENT_TOPOLOGY_*, AGENT_RELATIONSHIP_MAX_CHILDREN
- Provisioning: worktree root/base ref, port range/locks, discovery relative path
- Security: violation mode, allowlisted binaries, timeout, audit path, env inherit/scrub
- Telemetry/UI: runtime event log + Discord settings, AGENT_UI_HOST/PORT
- Do not set runtime-injected vars manually (AGENT_WORKTREE_PATH, AGENT_PORT_RANGE_START, etc.).
Practical first-run sequence
1. npm install
2. cp .env.example .env
3. npm run verify
4. npm run ui
5. Start a run in mock mode with a valid manifest
6. Switch to provider mode after auth is confirmed

View File

@@ -939,6 +939,86 @@ test("propagates abort signal into actor execution and stops the run", async ()
assert.equal(observedAbort, true); assert.equal(observedAbort, true);
}); });
test("createClaudeCanUseTool accepts tool casing differences from providers", async () => {
const workspaceRoot = await mkdtemp(resolve(tmpdir(), "ai-ops-workspace-"));
const stateRoot = await mkdtemp(resolve(tmpdir(), "ai-ops-session-state-"));
const projectContextPath = resolve(stateRoot, "project-context.json");
const manifest = {
schemaVersion: "1",
topologies: ["sequential"],
personas: [
{
id: "coder",
displayName: "Coder",
systemPromptTemplate: "Coder",
toolClearance: {
allowlist: ["bash"],
banlist: [],
},
},
],
relationships: [],
topologyConstraints: {
maxDepth: 2,
maxRetries: 0,
},
pipeline: {
entryNodeId: "case-node",
nodes: [
{
id: "case-node",
actorId: "case_actor",
personaId: "coder",
},
],
edges: [],
},
} as const;
const engine = new SchemaDrivenExecutionEngine({
manifest,
settings: {
workspaceRoot,
stateRoot,
projectContextPath,
maxChildren: 1,
maxDepth: 2,
maxRetries: 0,
runtimeContext: {},
},
actorExecutors: {
case_actor: async (input) => {
const canUseTool = input.mcp.createClaudeCanUseTool();
const allow = await canUseTool("Bash", {}, {
signal: new AbortController().signal,
toolUseID: "allow-bash",
});
assert.deepEqual(allow, {
behavior: "allow",
toolUseID: "allow-bash",
});
return {
status: "success",
payload: {
ok: true,
},
};
},
},
});
const result = await engine.runSession({
sessionId: "session-claude-tool-casing",
initialPayload: {
task: "verify tool casing",
},
});
assert.equal(result.status, "success");
});
test("hard-aborts pipeline on security violations by default", async () => { test("hard-aborts pipeline on security violations by default", async () => {
const workspaceRoot = await mkdtemp(resolve(tmpdir(), "ai-ops-workspace-")); const workspaceRoot = await mkdtemp(resolve(tmpdir(), "ai-ops-workspace-"));
const stateRoot = await mkdtemp(resolve(tmpdir(), "ai-ops-session-state-")); const stateRoot = await mkdtemp(resolve(tmpdir(), "ai-ops-session-state-"));