nanocoder icon indicating copy to clipboard operation
nanocoder copied to clipboard

[Feature] Architecture: Compile repeated agent workflows into verified deterministic macros

Open akramcodez opened this issue 1 month ago • 7 comments

Description

Allow the harness to identify successfully repeated mechanical agent workflows (e.g., finding files -> reading lines -> extracting diagnostics) and convert them into parameterizable, local scripts that bypass LLM inference entirely.

Use Case

Agents waste massive amounts of compute and time repeating the exact same sequence of tool calls for standard tasks. For example, investigating a lint error always involves reading the file, finding the line, and reading the rule definition. Asking an LLM to orchestrate this every time is slow and prone to random failures.

Proposed Solution

  1. The harness tracks common tool sequences.
  2. It generates a macro (e.g., inspect_test_failure(target="auth")).
  3. On future turns, instead of the LLM doing 4 separate tool calls, it just calls the macro.
  4. The harness executes the sequence deterministically without inference, instantly returning the final formatted payload.
  5. If the macro fails (e.g., assumptions broke), it falls back to standard LLM tool selection.

Alternatives Considered

  • Writing hardcoded tools for every possible scenario (bloats the codebase).
  • Leaving it to the LLM (slow, expensive, unreliable).

Additional Context

  • [x] I have searched existing issues to ensure this is not a duplicate
  • [x] This feature aligns with the project's goals (local-first AI assistance)

akramcodez avatar Oct 05 '26 09:10 akramcodez

Taking this issue

rishu685 avatar Oct 07 '26 10:10 rishu685

Following up on the initial prototype in #1619 and feedback from @addyCooks, here is a concrete technical proposal:


1. Architectural Overview & Component Boundaries

The workflow macro engine consists of three decoupled layers:

  1. Tool Execution Loop (tool-executor.tsx): Records { toolName, inputArgs, success, timestamp } on every completed tool invocation.
  2. SequenceTracker (sequence-tracker.ts): Sliding-window tracker discovering contiguous successful tool chains of length 2 to 5 across the session.
  3. Macro Compiler (macro-compiler.ts): Converts discovered sequences into parameterized macro definitions with template bindings ({{param}}).
  4. Macro Runner (macro-runner.ts): Deterministic in-process execution engine that runs composite steps in a single turn without intermediate LLM roundtrips.

How this fits alongside existing primitives:

  • vs. ConversationStateManager.detectRepetition: ConversationStateManager detects immediate stuck repetition loops within a single turn to warn the model or abort spinning. SequenceTracker is passive, cross-turn, and identifies positive repeatable workflows over the entire session.
  • vs. Custom Tools (source/custom-tools/): Custom tools are standalone shell scripts executed in /bin/bash or cmd.exe. Macros are composite chains of in-process tools (read_file, grep_search, write_file, MCP tools) executed directly in-process via ToolManager without invoking a shell.

2. Design Details

A. Sequence Tracking & Realistic Parameter Extraction

  1. Runtime Hook:
    • In source/hooks/chat-handler/conversation/tool-executor.tsx, every completed tool call records { toolName, inputArgs, success, timestamp } into the global SequenceTracker.
  2. Exemplar History:
    • WorkflowPattern stores the actual exemplarRecords: ToolExecutionRecord[] from the most recent successful execution sequence.
    • When compiling, parameters and default values are extracted from real session inputs instead of empty dummy objects, generating typed bindings (e.g., read_file_filePath_0 with template {{read_file_filePath_0}}).

B. Storage & Tool Execution Model

There are two viable approaches for storing and executing compiled macros:

  • Option 1: Custom Tool Extension with runner: macro (Recommended)

    • Store macros as .nanocoder/tools/<name>.md with frontmatter declaring runner: macro:
      • name: inspect_lint_failure
      • description: "Read file lines and diagnostic rule definitions"
      • runner: macro
      • parameters: ...
    • In source/custom-tools/build-tool.ts, if runner === 'macro', it synthesizes a ToolEntry whose handler calls executeMacro in-process via toolManager.getToolHandler(step.tool).
    • Advantage: The model and /tools list discover macros alongside custom tools without introducing a separate storage subsystem.
  • Option 2: Dedicated .nanocoder/macros/ Directory

    • Store definitions as JSON schemas under .nanocoder/macros/<name>.json.
    • Add a dedicated MacroLoader in ToolManager that registers them as composite tools.

C. Dynamic Approval & Safety

  • Approval policy is calculated based on the constituent steps:
    • If all steps are read-only (read_file, grep_search, list_dir), set approval: never and readOnly: true.
    • If any step mutates files (write_file, diff_edit, execute_bash), inherit approval: destructive or approval: always.
  • If an intermediate step in a macro fails or returns an error, execution immediately halts and returns a diagnostic payload so the model can gracefully resume standard turn-by-turn resolution.

D. User Controls (/macros)

  • /macros: Displays discovered candidate sequences with occurrence and success counts.
  • /macros compile <pattern_id> [name]: Compiles candidate into a tool file (with existsSync overwrite guard requiring --force).
  • /macros clear: Clears in-memory sequence history.

3. Phased Implementation Plan

  1. Phase 1: Hook SequenceTracker into tool-executor.tsx with exemplar parameter retention and sliding-window candidate discovery.
  2. Phase 2: Add executeMacro in-process runner in ToolManager and update macro-compiler.ts to output compliant macro tool definitions with dynamic approval resolution.
  3. Phase 3: Wire the interactive /macros and /macros compile CLI commands with collision protection and full unit/integration test coverage.

Feedback on Option 1 vs. Option 2 for the storage format is welcome!

@addyCooks would love to have your feedback on this approach will proceed accordingly as per the plan!

rishu685 avatar Oct 09 '26 12:10 rishu685

Thanks @rishu685, this is a clearer plan. Feedback:

  1. Option 1 (runner: macro custom tool) is fine, but it needs parser, types and build-tool.ts changes. Today the parser requires a shell-script body and ignores unknown keys.
  2. v1 should be read-only sequences only. Use the registry's readOnly flag. The proposal's grep_search and list_dir aren't real tool ids. Steps should run through the normal gated path (pre-tool-use hooks), not getToolHandler() directly.
  3. The compiler makes every arg a model-supplied param and never binds one step's output to the next, so v1 is a batch of independent calls. Is that the intended scope?
  4. Compile only on an explicit /macros compile, with no overwrite without --force.
  5. Please split it. First PR is the tracker hook plus a read-only /macros listing, with no execution.

addyCooks avatar Oct 10 '26 06:10 addyCooks

Thanks for the feedback! @addyCooks! .

I will split this as requested:

Scope for PR 1 (Updating #1619):

  1. Remove execution & compilation: Drop macro-runner.ts, macro-compiler.ts, and the compile command from #1619 to keep this PR small, verifiable, and focused.
  2. Read-only tracking hook:
    • Hook SequenceTracker directly into tool-executor.tsx (displayExecutedTool and executeAgentBatch).
    • Use toolManager.isReadOnly(toolName) to restrict tracking strictly to contiguous read-only tools (read_file, search_file_contents, list_directory, find_files, etc.). Any mutating tool breaks the chain.
    • Retain exemplarRecords on WorkflowPattern so real argument shapes and values are preserved.
  3. Read-only /macros command:
    • /macros: Displays discovered read-only patterns with occurrence and pass counts.
    • /macros clear: Resets session pattern history.
  4. Full tests: Unit tests for sliding-window edge cases and integration tests verifying tool-executor.tsx feeds the tracker.

Scope for PR 2 (Follow-up):

  • Add runner: macro to custom-tools parser, types, and build-tool.ts.
  • Gated execution routed through pre-tool-use hooks.
  • Output-to-input parameter binding ({{steps.step_1.output}}).
  • Explicit /macros compile with --force overwrite protection.

I will update PR #1619 to match the PR 1 scope from now will keep on updating via this thread

rishu685 avatar Oct 10 '26 07:10 rishu685

Thanks @rishu685, this split works and the plan matches what I asked for. A few things to settle for PR 1:

  1. Chain breaks: the tracker only has recordExecution, so there's no way to break a chain. If you record only read-only calls, read → write → read looks like read → read. Please add a way to break the chain and call it for every non-read-only tool, failed call and agent batch. Agent batches skip displayExecutedTool, so executeAgentBatch is a fine place for that call.
  2. Counts: occurrences and successCount always go up together, so the "pass count" in /macros will always match. Please drop it or count failures.
  3. Parallel calls: read-only tools in one batch run together and are recorded in call order, but they are independent of each other. Please mark them or note it, so a later macro step doesn't treat them as a dependency chain.
  4. Coverage: only the TUI path would be tracked. ACP and --plain call processToolUse directly. Please say so in the PR.
  5. exemplarRecords isn't on WorkflowPattern yet, so that is new work in this PR.

Go ahead with PR 1 once these are in the plan.

addyCooks avatar Oct 10 '26 07:10 addyCooks

Thanks @addyCooks! for giving a feedback,here is my updated plan :

  1. Explicit breakChain(): Added an explicit breakChain() method to SequenceTracker. We will call breakChain() on every non-read-only tool, failed execution, and directly inside executeAgentBatch so that interleaved mutations (e.g. read -> write -> read) do not falsely collapse into contiguous read-only chains.
  2. Clean Occurrence Counts: Dropped the redundant pass count in /macros; it will now display clean occurrence counts (e.g. [pattern_123] find_files -> read_file — 3 times).
  3. Parallel Batch Tagging: Added a parallelBatch: boolean tag on ToolExecutionRecord. When consecutive read-only tools run concurrently in Promise.all, they will be flagged as parallel siblings so PR 2 does not infer false serial dependencies between them.
  4. Documenting Coverage Scope: Stated clearly in the PR description that tracking is scoped to the interactive TUI turn loop (tool-executor.tsx), while non-interactive paths (ACP and --plain) bypass tracking in v1.
  5. exemplarRecords on WorkflowPattern: Added exemplarRecords: ToolExecutionRecord[] to preserve the freshest argument shapes and values for PR 2's parameter compiler. Updating PR #1619 to this shape now!

rishu685 avatar Oct 10 '26 07:10 rishu685

Update: PR 1 (Runtime read-only sequence tracker and /macros listing) has been updated and rebased in #1619 per the discussion above.

  • Incorporates breakChain() for mutating actions, errors, and agent batches.
  • Tags parallel read-only batches with parallelBatch: true.
  • Displays clean occurrence counts in /macros.
  • Preserves exemplarRecords with real argument shapes for PR 2.
  • All CI checks (Biome, TypeScript, AVA tests) are passing.

Once #1619 is reviewed and merged, I will open PR 2 for the custom tool parser (runner: macro), macro compiler, parameter binding, and gated execution.

rishu685 avatar Oct 10 '26 08:10 rishu685