[Feature] Architecture: Compile repeated agent workflows into verified deterministic macros
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
- The harness tracks common tool sequences.
- It generates a macro (e.g.,
inspect_test_failure(target="auth")). - On future turns, instead of the LLM doing 4 separate tool calls, it just calls the macro.
- The harness executes the sequence deterministically without inference, instantly returning the final formatted payload.
- 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)
Taking this issue
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:
- Tool Execution Loop (
tool-executor.tsx): Records{ toolName, inputArgs, success, timestamp }on every completed tool invocation. - SequenceTracker (
sequence-tracker.ts): Sliding-window tracker discovering contiguous successful tool chains of length 2 to 5 across the session. - Macro Compiler (
macro-compiler.ts): Converts discovered sequences into parameterized macro definitions with template bindings ({{param}}). - 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:ConversationStateManagerdetects immediate stuck repetition loops within a single turn to warn the model or abort spinning.SequenceTrackeris 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/bashorcmd.exe. Macros are composite chains of in-process tools (read_file,grep_search,write_file, MCP tools) executed directly in-process viaToolManagerwithout invoking a shell.
2. Design Details
A. Sequence Tracking & Realistic Parameter Extraction
- Runtime Hook:
- In
source/hooks/chat-handler/conversation/tool-executor.tsx, every completed tool call records{ toolName, inputArgs, success, timestamp }into the globalSequenceTracker.
- In
- Exemplar History:
WorkflowPatternstores the actualexemplarRecords: 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_0with 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>.mdwith frontmatter declaringrunner: macro:name: inspect_lint_failuredescription: "Read file lines and diagnostic rule definitions"runner: macroparameters: ...
- In
source/custom-tools/build-tool.ts, ifrunner === 'macro', it synthesizes aToolEntrywhose handler callsexecuteMacroin-process viatoolManager.getToolHandler(step.tool). - Advantage: The model and
/toolslist discover macros alongside custom tools without introducing a separate storage subsystem.
- Store macros as
-
Option 2: Dedicated
.nanocoder/macros/Directory- Store definitions as JSON schemas under
.nanocoder/macros/<name>.json. - Add a dedicated
MacroLoaderinToolManagerthat registers them as composite tools.
- Store definitions as JSON schemas under
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), setapproval: neverandreadOnly: true. - If any step mutates files (
write_file,diff_edit,execute_bash), inheritapproval: destructiveorapproval: always.
- If all steps are read-only (
- 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 (withexistsSyncoverwrite guard requiring--force)./macros clear: Clears in-memory sequence history.
3. Phased Implementation Plan
- Phase 1: Hook
SequenceTrackerintotool-executor.tsxwith exemplar parameter retention and sliding-window candidate discovery. - Phase 2: Add
executeMacroin-process runner inToolManagerand updatemacro-compiler.tsto output compliant macro tool definitions with dynamic approval resolution. - Phase 3: Wire the interactive
/macrosand/macros compileCLI 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!
Thanks @rishu685, this is a clearer plan. Feedback:
- Option 1 (
runner: macrocustom tool) is fine, but it needs parser, types andbuild-tool.tschanges. Today the parser requires a shell-script body and ignores unknown keys. - v1 should be read-only sequences only. Use the registry's
readOnlyflag. The proposal'sgrep_searchandlist_diraren't real tool ids. Steps should run through the normal gated path (pre-tool-use hooks), notgetToolHandler()directly. - 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?
- Compile only on an explicit
/macros compile, with no overwrite without--force. - Please split it. First PR is the tracker hook plus a read-only
/macroslisting, with no execution.
Thanks for the feedback! @addyCooks! .
I will split this as requested:
Scope for PR 1 (Updating #1619):
- Remove execution & compilation: Drop
macro-runner.ts,macro-compiler.ts, and thecompilecommand from #1619 to keep this PR small, verifiable, and focused. - Read-only tracking hook:
- Hook
SequenceTrackerdirectly intotool-executor.tsx(displayExecutedToolandexecuteAgentBatch). - 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
exemplarRecordsonWorkflowPatternso real argument shapes and values are preserved.
- Hook
- Read-only
/macroscommand:/macros: Displays discovered read-only patterns with occurrence and pass counts./macros clear: Resets session pattern history.
- Full tests: Unit tests for sliding-window edge cases and integration tests verifying
tool-executor.tsxfeeds the tracker.
Scope for PR 2 (Follow-up):
- Add
runner: macroto custom-tools parser, types, andbuild-tool.ts. - Gated execution routed through pre-tool-use hooks.
- Output-to-input parameter binding (
{{steps.step_1.output}}). - Explicit
/macros compilewith--forceoverwrite protection.
I will update PR #1619 to match the PR 1 scope from now will keep on updating via this thread
Thanks @rishu685, this split works and the plan matches what I asked for. A few things to settle for PR 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 → readlooks likeread → 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 skipdisplayExecutedTool, soexecuteAgentBatchis a fine place for that call. - Counts:
occurrencesandsuccessCountalways go up together, so the "pass count" in/macroswill always match. Please drop it or count failures. - 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.
- Coverage: only the TUI path would be tracked. ACP and
--plaincallprocessToolUsedirectly. Please say so in the PR. exemplarRecordsisn't onWorkflowPatternyet, so that is new work in this PR.
Go ahead with PR 1 once these are in the plan.
Thanks @addyCooks! for giving a feedback,here is my updated plan :
- Explicit
breakChain(): Added an explicitbreakChain()method toSequenceTracker. We will callbreakChain()on every non-read-only tool, failed execution, and directly insideexecuteAgentBatchso that interleaved mutations (e.g.read -> write -> read) do not falsely collapse into contiguous read-only chains. - 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). - Parallel Batch Tagging: Added a
parallelBatch: booleantag onToolExecutionRecord. When consecutive read-only tools run concurrently inPromise.all, they will be flagged as parallel siblings so PR 2 does not infer false serial dependencies between them. - 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 (ACPand--plain) bypass tracking in v1. exemplarRecordsonWorkflowPattern: AddedexemplarRecords: ToolExecutionRecord[]to preserve the freshest argument shapes and values for PR 2's parameter compiler. Updating PR #1619 to this shape now!
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
exemplarRecordswith 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.