@trailstep/sub-agents 0.2.0 → 0.2.1
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/dist/index.js +23 -23
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -633,8 +633,8 @@ var delegate = defineDelegateWorkflow({
|
|
|
633
633
|
id: "delegate",
|
|
634
634
|
description: "Runs delegated focused work while preserving run-local continuity.",
|
|
635
635
|
skillName: "trst-delegate",
|
|
636
|
-
skillDescription: "Use
|
|
637
|
-
skillFocus: "Use for general delegated work when the parent agent wants to choose the task, mode, turn budget, and context shape explicitly.",
|
|
636
|
+
skillDescription: "Use when you need to delegate a single bounded task and want to choose mode, turn budget, and context shape explicitly. General-purpose delegate for focused work.",
|
|
637
|
+
skillFocus: "Use for general delegated work when the parent agent wants to choose the task, mode, turn budget, and context shape explicitly. Prefer the specialized explore, implement, review, or debugger variants when they fit. If you have 2+ independent tasks, use trst-delegate-parallel instead of calling this sequentially.",
|
|
638
638
|
defaultMode: "general",
|
|
639
639
|
defaultMaxTurns: 10
|
|
640
640
|
});
|
|
@@ -642,8 +642,8 @@ var delegateExplore = defineDelegateWorkflow({
|
|
|
642
642
|
id: "delegateExplore",
|
|
643
643
|
description: "Runs read-oriented delegated exploration while preserving run-local continuity.",
|
|
644
644
|
skillName: "trst-delegate-explore",
|
|
645
|
-
skillDescription: "Use
|
|
646
|
-
skillFocus: "Explore mode is read-oriented: inspect code, commands, docs, and artifacts; summarize findings and avoid edits unless the task explicitly asks for them.",
|
|
645
|
+
skillDescription: "Use when you need to investigate the codebase, understand how code works, find where something lives, or trace a flow. Read-only exploration that summarizes findings without editing files.",
|
|
646
|
+
skillFocus: "Explore mode is read-oriented: when you need to investigate the codebase, inspect code, commands, docs, and artifacts; summarize findings and avoid edits unless the task explicitly asks for them. If you have 2+ independent exploration questions, use trst-delegate-parallel instead of calling this sequentially.",
|
|
647
647
|
defaultMode: "explore",
|
|
648
648
|
defaultMaxTurns: 6,
|
|
649
649
|
summarize: true
|
|
@@ -652,8 +652,8 @@ var delegateSimpleExplore = defineDelegateWorkflow({
|
|
|
652
652
|
id: "delegateSimpleExplore",
|
|
653
653
|
description: "Runs narrow, low-cost read-only exploration while preserving run-local continuity.",
|
|
654
654
|
skillName: "trst-delegate-simple-explore",
|
|
655
|
-
skillDescription: "Use
|
|
656
|
-
skillFocus: "Simple explore is read-only and narrow: answer focused repo
|
|
655
|
+
skillDescription: "Use when you need a quick low-cost answer to a narrow repo question like where is X, what calls Y, or what does this file do. Read-only single-area lookup.",
|
|
656
|
+
skillFocus: "Simple explore is read-only and narrow: when you need a quick answer to a focused repo question, inspect one area, summarize concise findings, and avoid edits. If you have 2+ independent lookup questions, use trst-delegate-parallel instead of calling this sequentially.",
|
|
657
657
|
defaultMode: "explore",
|
|
658
658
|
defaultMaxTurns: 4,
|
|
659
659
|
summarize: true,
|
|
@@ -664,8 +664,8 @@ var delegateArchitectPlanner = defineDelegateWorkflow({
|
|
|
664
664
|
id: "delegateArchitectPlanner",
|
|
665
665
|
description: "Scouts the codebase to identify the few files or seams likely needing edits.",
|
|
666
666
|
skillName: "trst-delegate-architect-planner",
|
|
667
|
-
skillDescription: "Use
|
|
668
|
-
skillFocus: "Architect planner is read-only: grep/read the repo, identify the 3-4 files or seams most likely to need edits, explain why, and do not write code.",
|
|
667
|
+
skillDescription: "Use when you have a bug report or feature request and need to map it to the 3-4 files or seams most likely to need edits before implementing. Read-only scouting, no code changes.",
|
|
668
|
+
skillFocus: "Architect planner is read-only: when you need to plan before changing files, grep/read the repo, identify the 3-4 files or seams most likely to need edits, explain why, and do not write code.",
|
|
669
669
|
defaultMode: "explore",
|
|
670
670
|
defaultMaxTurns: 6,
|
|
671
671
|
summarize: true,
|
|
@@ -676,8 +676,8 @@ var delegateReview = defineDelegateWorkflow({
|
|
|
676
676
|
id: "delegateReview",
|
|
677
677
|
description: "Runs delegated review work while preserving run-local continuity.",
|
|
678
678
|
skillName: "trst-delegate-review",
|
|
679
|
-
skillDescription: "Use
|
|
680
|
-
skillFocus: "Review mode
|
|
679
|
+
skillDescription: "Use when you need to review existing code, a plan, or a diff for concrete issues and risks. Inspects without editing unless a fix is explicitly requested.",
|
|
680
|
+
skillFocus: "Review mode: when you need a focused review of existing work, inspect it, identify concrete issues and risks, and avoid edits unless the parent task explicitly requests a fix. If you have 2+ independent reviews, use trst-delegate-parallel instead of calling this sequentially.",
|
|
681
681
|
defaultMode: "review",
|
|
682
682
|
defaultMaxTurns: 6,
|
|
683
683
|
summarize: false
|
|
@@ -686,8 +686,8 @@ var delegateImplement = defineDelegateWorkflow({
|
|
|
686
686
|
id: "delegateImplement",
|
|
687
687
|
description: "Runs delegated implementation work while preserving run-local continuity.",
|
|
688
688
|
skillName: "trst-delegate-implement",
|
|
689
|
-
skillDescription: "Use
|
|
690
|
-
skillFocus: "Implement mode may edit files
|
|
689
|
+
skillDescription: "Use when you need to change files to implement a bounded fix or feature. Makes edits, runs focused checks when practical, and reports changed files.",
|
|
690
|
+
skillFocus: "Implement mode may edit files: when you need to change files, make the smallest safe change, run focused checks when practical, and always report changedFiles/artifacts that were actually produced. If you have 2+ independent file changes, use trst-delegate-parallel instead of calling this sequentially.",
|
|
691
691
|
defaultMode: "implement",
|
|
692
692
|
defaultMaxTurns: 12,
|
|
693
693
|
summarize: false,
|
|
@@ -697,8 +697,8 @@ var delegateQuickImplementor = defineDelegateWorkflow({
|
|
|
697
697
|
id: "delegateQuickImplementor",
|
|
698
698
|
description: "Runs strict localized implementation work for mechanical changes.",
|
|
699
699
|
skillName: "trst-delegate-quick-implementor",
|
|
700
|
-
skillDescription: "Use
|
|
701
|
-
skillFocus: "Quick implementor is the typist:
|
|
700
|
+
skillDescription: "Use when instructions are already concrete and you need strict localized boilerplate edits with no architecture decisions. Mechanical typist that edits files.",
|
|
701
|
+
skillFocus: "Quick implementor is the typist: when the plan is already concrete and you need to change files, follow instructions, make localized edits only, avoid broad architecture decisions, run focused checks when practical, and report changedFiles. If you have 2+ independent mechanical edits, use trst-delegate-parallel instead of calling this sequentially.",
|
|
702
702
|
defaultMode: "implement",
|
|
703
703
|
defaultMaxTurns: 8,
|
|
704
704
|
summarize: false,
|
|
@@ -709,8 +709,8 @@ var delegateSmartImplementor = defineDelegateWorkflow({
|
|
|
709
709
|
id: "delegateSmartImplementor",
|
|
710
710
|
description: "Runs complex implementation, algorithmic work, or cross-file refactors.",
|
|
711
711
|
skillName: "trst-delegate-smart-implementor",
|
|
712
|
-
skillDescription: "Use
|
|
713
|
-
skillFocus: "Smart implementor is the heavy-lifter:
|
|
712
|
+
skillDescription: "Use when you need complex cross-file refactoring, algorithmic work, or interconnected system changes. Heavy-lifter that edits files and keeps scope bounded.",
|
|
713
|
+
skillFocus: "Smart implementor is the heavy-lifter: when you need complex logic, cross-file refactors, algorithms, or non-trivial systems, handle the interconnected changes, keep scope bounded, and report changedFiles. If you have 2+ independent complex changes, use trst-delegate-parallel instead of calling this sequentially.",
|
|
714
714
|
defaultMode: "implement",
|
|
715
715
|
defaultMaxTurns: 14,
|
|
716
716
|
summarize: false,
|
|
@@ -721,8 +721,8 @@ var delegateRelentlessDebugger = defineDelegateWorkflow({
|
|
|
721
721
|
id: "delegateRelentlessDebugger",
|
|
722
722
|
description: "Diagnoses and fixes validation, lint, test, or runtime failures.",
|
|
723
723
|
skillName: "trst-delegate-relentless-debugger",
|
|
724
|
-
skillDescription: "Use
|
|
725
|
-
skillFocus: "Relentless debugger is the
|
|
724
|
+
skillDescription: "Use when lint, typecheck, tests, or runtime are failing and you need to diagnose stack traces or diagnostics and fix them iteratively. Preserves intent while editing files.",
|
|
725
|
+
skillFocus: "Relentless debugger is the fixer: when validation, lint, tests, or runtime fail and you need to change files to fix them, consume diagnostics, preserve the intended change, fix failures iteratively, and avoid redesign unless required by the failure evidence.",
|
|
726
726
|
defaultMode: "implement",
|
|
727
727
|
defaultMaxTurns: 12,
|
|
728
728
|
summarize: false,
|
|
@@ -733,8 +733,8 @@ var delegateSchemaFormatter = defineDelegateWorkflow({
|
|
|
733
733
|
id: "delegateSchemaFormatter",
|
|
734
734
|
description: "Produces exact structured output for schema-bound handoffs.",
|
|
735
735
|
skillName: "trst-delegate-schema-formatter",
|
|
736
|
-
skillDescription: "Use
|
|
737
|
-
skillFocus: "Schema formatter is the translator:
|
|
736
|
+
skillDescription: "Use when you need exact JSON, XML, or schema-constrained output for a handoff. Formatting-only, prioritizes exact structure over prose.",
|
|
737
|
+
skillFocus: "Schema formatter is the translator: when you need exact structured output, prioritize the requested JSON/XML/schema structure, avoid extra prose, and do not perform broad implementation work unless explicitly requested.",
|
|
738
738
|
defaultMode: "general",
|
|
739
739
|
defaultMaxTurns: 4,
|
|
740
740
|
summarize: false,
|
|
@@ -855,7 +855,7 @@ var delegateParallelOutputShape = jsonSchema2({
|
|
|
855
855
|
// src/delegate-parallel/workflow.ts
|
|
856
856
|
var delegateParallel = defineWorkflow2({
|
|
857
857
|
id: "delegateParallel",
|
|
858
|
-
description: "Fans out required delegate tasks across parallel delegate workflows.",
|
|
858
|
+
description: "Use when you have 2+ independent codebase tasks that can run in parallel. Fans out required delegate tasks across parallel delegate workflows.",
|
|
859
859
|
skill: delegateParallelSkill(),
|
|
860
860
|
inputShape: delegateParallelInputShape,
|
|
861
861
|
outputShape: delegateParallelOutputShape,
|
|
@@ -1037,12 +1037,12 @@ function hashString(value) {
|
|
|
1037
1037
|
function delegateParallelSkill() {
|
|
1038
1038
|
return `---
|
|
1039
1039
|
name: trst-delegate-parallel
|
|
1040
|
-
description: Use
|
|
1040
|
+
description: Use when you have 2+ independent codebase tasks that can run in parallel, such as exploring multiple areas, implementing multiple files, or splitting explore plus implement plus review. Prefer this over running single explore, implement, or review delegates sequentially.
|
|
1041
1041
|
x-trailstep-user-facing: false
|
|
1042
1042
|
---
|
|
1043
1043
|
# TrailStep delegateParallel workflow
|
|
1044
1044
|
|
|
1045
|
-
Use this workflow when a parent agent already has a set of concrete, independent delegate tasks. It fans out directly to the existing delegate, delegateExplore, delegateReview, and delegateImplement workflows based on each task mode. It does not add a planning agent and does not merge results beyond returning the parallel branch outputs.
|
|
1045
|
+
Use this workflow when a parent agent already has a set of concrete, independent delegate tasks and wants to run them in parallel instead of sequentially. Reach for this when you need to investigate multiple areas, change multiple files, or split explore plus implement plus review work across delegates. It fans out directly to the existing delegate, delegateExplore, delegateReview, and delegateImplement workflows based on each task mode. It does not add a planning agent and does not merge results beyond returning the parallel branch outputs.
|
|
1046
1046
|
|
|
1047
1047
|
Each task must provide a stable \`id\`, \`mode\`, and \`task\` text. Shared \`context\`, \`cwd\`, \`maxTurns\`, \`summarize\`, and \`worktree\` values are applied as defaults; task-level values override them. Managed worktrees under \`worktree.enabled=true\` default per task to \`.trailstep/worktrees/<runName>/<taskId>\` and \`trailstep/delegate/<runName>/<taskId>\` to avoid collisions.`;
|
|
1048
1048
|
}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/delegate/workflow.ts","../src/delegate/schema.ts","../src/delegate/steps.ts","../src/delegate/prompts.ts","../src/delegate-parallel/workflow.ts","../src/delegate-parallel/schema.ts"],"sourcesContent":["import { defineWorkflow } from \"@trailstep/authoring\";\nimport {\n type DelegateInput,\n type DelegateMode,\n type DelegateOutput,\n delegateInputShape,\n delegateOutputShape,\n} from \"./schema.js\";\nimport { initializeDelegateStep } from \"./steps.js\";\n\nexport type {\n DelegateArtifact,\n DelegateInput,\n DelegateMode,\n DelegateOutput,\n DelegateTurnOutput,\n DelegateTurnStatus,\n DelegateWorktreeInput,\n} from \"./schema.js\";\n\nexport type DelegateWorkflowConfig = {\n readonly id: string;\n readonly description: string;\n readonly skillName: string;\n readonly skillDescription: string;\n readonly skillFocus: string;\n readonly defaultMode: DelegateMode;\n readonly defaultMaxTurns: number;\n readonly summarize?: boolean;\n readonly agentSize?: \"small\" | \"medium\" | \"large\";\n readonly agentThinking?: \"low\" | \"medium\" | \"high\";\n};\n\nexport function defineDelegateWorkflow(config: DelegateWorkflowConfig) {\n return defineWorkflow<DelegateInput, DelegateOutput>({\n id: config.id,\n description: config.description,\n skill: delegateSkill(config),\n inputShape: delegateInputShape,\n outputShape: delegateOutputShape,\n agents: {\n delegateAgent: {\n size: config.agentSize ?? \"medium\",\n thinking: config.agentThinking ?? \"medium\",\n description: config.description,\n },\n },\n start(input) {\n return initializeDelegateStep(input, {\n mode: config.defaultMode,\n maxTurns: config.defaultMaxTurns,\n ...(config.summarize === undefined ? {} : { summarize: config.summarize }),\n });\n },\n });\n}\n\nexport const delegate = defineDelegateWorkflow({\n id: \"delegate\",\n description: \"Runs delegated focused work while preserving run-local continuity.\",\n skillName: \"trst-delegate\",\n skillDescription:\n \"Use as a flexible sub-agent for focused TrailStep delegate work with run-local continuity.\",\n skillFocus:\n \"Use for general delegated work when the parent agent wants to choose the task, mode, turn budget, and context shape explicitly.\",\n defaultMode: \"general\",\n defaultMaxTurns: 10,\n});\n\nexport const delegateExplore = defineDelegateWorkflow({\n id: \"delegateExplore\",\n description: \"Runs read-oriented delegated exploration while preserving run-local continuity.\",\n skillName: \"trst-delegate-explore\",\n skillDescription:\n \"Use as a sub-agent for bounded read-oriented investigation and findings summaries.\",\n skillFocus:\n \"Explore mode is read-oriented: inspect code, commands, docs, and artifacts; summarize findings and avoid edits unless the task explicitly asks for them.\",\n defaultMode: \"explore\",\n defaultMaxTurns: 6,\n summarize: true,\n});\n\nexport const delegateSimpleExplore = defineDelegateWorkflow({\n id: \"delegateSimpleExplore\",\n description: \"Runs narrow, low-cost read-only exploration while preserving run-local continuity.\",\n skillName: \"trst-delegate-simple-explore\",\n skillDescription: \"Use as a sub-agent for quick, bounded read-only lookups and summaries.\",\n skillFocus:\n \"Simple explore is read-only and narrow: answer focused repo questions, inspect one area, summarize concise findings, and avoid edits.\",\n defaultMode: \"explore\",\n defaultMaxTurns: 4,\n summarize: true,\n agentSize: \"small\",\n agentThinking: \"low\",\n});\n\nexport const delegateArchitectPlanner = defineDelegateWorkflow({\n id: \"delegateArchitectPlanner\",\n description: \"Scouts the codebase to identify the few files or seams likely needing edits.\",\n skillName: \"trst-delegate-architect-planner\",\n skillDescription:\n \"Use as a read-only scout that maps a bug or feature request to likely edit targets.\",\n skillFocus:\n \"Architect planner is read-only: grep/read the repo, identify the 3-4 files or seams most likely to need edits, explain why, and do not write code.\",\n defaultMode: \"explore\",\n defaultMaxTurns: 6,\n summarize: true,\n agentSize: \"medium\",\n agentThinking: \"medium\",\n});\n\nexport const delegateReview = defineDelegateWorkflow({\n id: \"delegateReview\",\n description: \"Runs delegated review work while preserving run-local continuity.\",\n skillName: \"trst-delegate-review\",\n skillDescription:\n \"Use as a sub-agent for focused code, plan, or change review without unnecessary edits.\",\n skillFocus:\n \"Review mode should inspect existing work, identify concrete issues and risks, and avoid edits unless the parent task explicitly requests a fix.\",\n defaultMode: \"review\",\n defaultMaxTurns: 6,\n summarize: false,\n});\n\nexport const delegateImplement = defineDelegateWorkflow({\n id: \"delegateImplement\",\n description: \"Runs delegated implementation work while preserving run-local continuity.\",\n skillName: \"trst-delegate-implement\",\n skillDescription: \"Use as a sub-agent for bounded implementation tasks that may edit files.\",\n skillFocus:\n \"Implement mode may edit files. Make the smallest safe change, run focused checks when practical, and always report changedFiles/artifacts that were actually produced.\",\n defaultMode: \"implement\",\n defaultMaxTurns: 12,\n summarize: false,\n agentThinking: \"medium\",\n});\n\nexport const delegateQuickImplementor = defineDelegateWorkflow({\n id: \"delegateQuickImplementor\",\n description: \"Runs strict localized implementation work for mechanical changes.\",\n skillName: \"trst-delegate-quick-implementor\",\n skillDescription: \"Use as a sub-agent for strict, localized boilerplate implementation tasks.\",\n skillFocus:\n \"Quick implementor is the typist: follow concrete instructions, make localized edits only, avoid broad architecture decisions, run focused checks when practical, and report changedFiles.\",\n defaultMode: \"implement\",\n defaultMaxTurns: 8,\n summarize: false,\n agentSize: \"medium\",\n agentThinking: \"medium\",\n});\n\nexport const delegateSmartImplementor = defineDelegateWorkflow({\n id: \"delegateSmartImplementor\",\n description: \"Runs complex implementation, algorithmic work, or cross-file refactors.\",\n skillName: \"trst-delegate-smart-implementor\",\n skillDescription:\n \"Use as a sub-agent for complex logic, cross-file refactoring, or algorithmic design.\",\n skillFocus:\n \"Smart implementor is the heavy-lifter: handle complex interconnected changes, refactors, algorithms, and non-trivial systems; keep scope bounded and report changedFiles.\",\n defaultMode: \"implement\",\n defaultMaxTurns: 14,\n summarize: false,\n agentSize: \"large\",\n agentThinking: \"high\",\n});\n\nexport const delegateRelentlessDebugger = defineDelegateWorkflow({\n id: \"delegateRelentlessDebugger\",\n description: \"Diagnoses and fixes validation, lint, test, or runtime failures.\",\n skillName: \"trst-delegate-relentless-debugger\",\n skillDescription:\n \"Use as a sub-agent for repairing linter failures, test failures, stack traces, and diagnostics.\",\n skillFocus:\n \"Relentless debugger is the janitor: consume diagnostics, preserve the intended change, fix failures iteratively, and avoid redesign unless required by the failure evidence.\",\n defaultMode: \"implement\",\n defaultMaxTurns: 12,\n summarize: false,\n agentSize: \"large\",\n agentThinking: \"high\",\n});\n\nexport const delegateSchemaFormatter = defineDelegateWorkflow({\n id: \"delegateSchemaFormatter\",\n description: \"Produces exact structured output for schema-bound handoffs.\",\n skillName: \"trst-delegate-schema-formatter\",\n skillDescription: \"Use as a sub-agent for exact JSON/XML/schema-constrained formatting tasks.\",\n skillFocus:\n \"Schema formatter is the translator: prioritize exact requested structure, avoid extra prose, and do not perform broad implementation work unless explicitly requested.\",\n defaultMode: \"general\",\n defaultMaxTurns: 4,\n summarize: false,\n agentSize: \"small\",\n agentThinking: \"low\",\n});\n\nfunction delegateSkill(config: DelegateWorkflowConfig): string {\n return `---\nname: ${config.skillName}\ndescription: ${config.skillDescription}\nx-trailstep-user-facing: false\n---\n# TrailStep ${config.id} workflow\n\n${config.skillFocus}\n\nUse this workflow as a parent-agent/delegate tool when a parent agent needs bounded work in a repository. The delegate keeps continuity only inside one TrailStep run; separate runs do not share memory.\n\n## Parent-agent usage\n\n- For simple tasks, pass direct flags: \\`trailstep @trailstep/sub-agents#${config.id} --task \"...\"\\`.\n- For one-shot JSON, pipe it to \\`trailstep @trailstep/sub-agents#${config.id} --input-file -\\`; for long/reusable context, write an input JSON file and run \\`trailstep @trailstep/sub-agents#${config.id} --input-file delegate-input.json\\`.\n- Use unique run names for parallel delegates so their run-local state stays separate.\n- Use \\`cwd\\` for an existing worktree or subdirectory that TrailStep should not manage. Use \\`worktree.enabled=true\\` when the delegate should create a managed git worktree and safely clean it up/report it.\n- Do not pass both \\`cwd\\` and \\`worktree.enabled=true\\`; choose one execution location strategy.\n- If a delegate asks a question, answer with \\`trailstep answer <runName> parent-answer --json '{\"answer\":\"...\"}'\\`, then resume with \\`trailstep continue <runName>\\`.\n- Retry a failed turn with \\`trailstep retry <workflowRef> <runName>\\` when appropriate.\n- Read final typed output with \\`trailstep output <runName>\\`; read the terminal summary with \\`trailstep output <runName> --message\\`.\n- Package reference: \\`@trailstep/sub-agents#${config.id}\\`; built dist reference: \\`./packages/sub-agents/dist/index.js#${config.id}\\`.\n\nThis skill is intended for delegated working-agent use rather than direct end-user planning chat. Preserve the run-local memory supplied in the workflow prompt, keep work bounded to the requested turn, and return the JSON contract requested by the workflow prompt.`;\n}\n","import { jsonSchema } from \"@trailstep/authoring\";\n\nexport type DelegateMode = \"explore\" | \"implement\" | \"review\" | \"general\";\nexport type DelegateStatus = \"completed\" | \"blocked\" | \"cancelled\";\nexport type DelegateTurnStatus = \"completed\" | \"continue\" | \"question\" | \"blocked\";\n\nexport interface DelegateArtifact extends Record<string, unknown> {\n readonly name: string;\n readonly path: string;\n readonly mediaType?: string;\n}\n\nexport type DelegateWorktreeCleanup = \"auto\" | \"never\" | \"always\";\n\nexport interface DelegateWorktreeInput extends Record<string, unknown> {\n readonly enabled?: boolean;\n readonly path?: string;\n readonly baseRef?: string;\n /** @deprecated Use baseRef. */\n readonly baseBranch?: string;\n readonly branch?: string;\n readonly cleanup?: DelegateWorktreeCleanup;\n readonly forceCleanup?: boolean;\n}\n\nexport interface DelegateInput extends Record<string, unknown> {\n readonly task: string;\n readonly context?: string;\n readonly mode?: DelegateMode;\n readonly cwd?: string;\n readonly maxTurns?: number;\n readonly summarize?: boolean;\n readonly worktree?: DelegateWorktreeInput;\n}\n\nexport interface DelegateOutput extends Record<string, unknown> {\n readonly status: DelegateStatus;\n readonly summary: string;\n readonly result?: string;\n readonly changedFiles?: readonly string[];\n readonly artifacts?: readonly DelegateArtifact[];\n readonly worktreePath?: string;\n readonly worktreeBranch?: string;\n readonly worktreeCleanup?: DelegateWorktreeCleanupDetails;\n readonly questionsAsked: number;\n readonly turns: number;\n}\n\nexport interface DelegateTurnOutput extends Record<string, unknown> {\n readonly status: DelegateTurnStatus;\n readonly summary: string;\n readonly memoryPatch?: string;\n readonly question?: string;\n readonly result?: string;\n readonly changedFiles?: readonly string[];\n readonly artifacts?: readonly DelegateArtifact[];\n}\n\nexport interface ParentAnswerOutput extends Record<string, unknown> {\n readonly answer: string;\n}\n\nexport interface DelegateWorktreeCleanupDetails extends Record<string, unknown> {\n readonly requested: DelegateWorktreeCleanup;\n readonly status: \"not-managed\" | \"kept\" | \"removed\" | \"kept-dirty\" | \"failed\";\n readonly reason?: string;\n}\n\nexport interface DelegateWorktreeOptions extends Record<string, unknown> {\n readonly enabled: boolean;\n readonly path?: string;\n readonly baseRef?: string;\n /** @deprecated Use baseRef. */\n readonly baseBranch?: string;\n readonly branch?: string;\n readonly cleanup: DelegateWorktreeCleanup;\n readonly forceCleanup: boolean;\n}\n\nexport interface DelegateWorkflowDefaults extends Record<string, unknown> {\n readonly mode?: DelegateMode;\n readonly maxTurns?: number;\n readonly summarize?: boolean;\n}\n\nexport interface NormalizedDelegateInput extends Record<string, unknown> {\n readonly task: string;\n readonly context?: string;\n readonly mode: DelegateMode;\n readonly cwd?: string;\n readonly maxTurns: number;\n readonly summarize: boolean;\n readonly worktree: DelegateWorktreeOptions;\n}\n\nexport interface QuestionAnswer extends Record<string, unknown> {\n readonly question: string;\n readonly answer: string;\n}\n\nexport interface DelegateTurnInput extends Record<string, unknown> {\n readonly task: string;\n readonly context?: string;\n readonly mode: DelegateMode;\n readonly executionCwd: string;\n readonly worktreePath?: string;\n readonly memory: string;\n readonly questionsAndAnswers: readonly QuestionAnswer[];\n readonly latestSummary?: string;\n readonly turn: number;\n readonly maxTurns: number;\n readonly summarize: boolean;\n}\n\nexport interface PrepareDelegateTurnInput extends Record<string, unknown> {\n readonly turn: number;\n}\n\nexport interface AskParentInput extends Record<string, unknown> {\n readonly question: string;\n readonly nextTurn: number;\n}\n\nexport const delegateArtifactShape = {\n type: \"object\",\n properties: {\n name: { type: \"string\" },\n path: { type: \"string\" },\n mediaType: { type: \"string\" },\n },\n required: [\"name\", \"path\"],\n additionalProperties: false,\n} as const;\n\nexport const delegateInputShape = jsonSchema<DelegateInput>({\n type: \"object\",\n properties: {\n task: { type: \"string\" },\n context: { type: \"string\" },\n mode: { type: \"string\", enum: [\"explore\", \"implement\", \"review\", \"general\"] },\n cwd: { type: \"string\" },\n maxTurns: { type: \"number\" },\n summarize: { type: \"boolean\" },\n worktree: {\n type: \"object\",\n properties: {\n enabled: { type: \"boolean\" },\n path: { type: \"string\" },\n baseRef: { type: \"string\" },\n baseBranch: { type: \"string\" },\n branch: { type: \"string\" },\n cleanup: { type: \"string\", enum: [\"auto\", \"never\", \"always\"] },\n forceCleanup: { type: \"boolean\" },\n },\n additionalProperties: false,\n },\n },\n required: [\"task\"],\n additionalProperties: false,\n});\n\nexport const delegateOutputShape = jsonSchema<DelegateOutput>({\n type: \"object\",\n properties: {\n status: { type: \"string\", enum: [\"completed\", \"blocked\", \"cancelled\"] },\n summary: { type: \"string\" },\n result: { type: \"string\" },\n changedFiles: { type: \"array\", items: { type: \"string\" } },\n artifacts: { type: \"array\", items: delegateArtifactShape },\n worktreePath: { type: \"string\" },\n worktreeBranch: { type: \"string\" },\n worktreeCleanup: {\n type: \"object\",\n properties: {\n requested: { type: \"string\", enum: [\"auto\", \"never\", \"always\"] },\n status: {\n type: \"string\",\n enum: [\"not-managed\", \"kept\", \"removed\", \"kept-dirty\", \"failed\"],\n },\n reason: { type: \"string\" },\n },\n required: [\"requested\", \"status\"],\n additionalProperties: false,\n },\n questionsAsked: { type: \"number\" },\n turns: { type: \"number\" },\n },\n required: [\"status\", \"summary\", \"questionsAsked\", \"turns\"],\n additionalProperties: false,\n});\n\nexport const delegateTurnOutputShape = jsonSchema<DelegateTurnOutput>({\n type: \"object\",\n properties: {\n status: { type: \"string\", enum: [\"completed\", \"continue\", \"question\", \"blocked\"] },\n summary: { type: \"string\" },\n memoryPatch: { type: \"string\" },\n question: { type: \"string\" },\n result: { type: \"string\" },\n changedFiles: { type: \"array\", items: { type: \"string\" } },\n artifacts: { type: \"array\", items: delegateArtifactShape },\n },\n required: [\"status\", \"summary\"],\n additionalProperties: false,\n});\n\nexport const parentAnswerShape = jsonSchema<ParentAnswerOutput>({\n type: \"object\",\n properties: {\n answer: { type: \"string\" },\n },\n required: [\"answer\"],\n additionalProperties: false,\n});\n\nexport function normalizeDelegateInput(\n input: DelegateInput,\n defaults: DelegateWorkflowDefaults = {},\n): NormalizedDelegateInput {\n const mode = input.mode ?? defaults.mode ?? \"general\";\n return {\n task: input.task,\n ...(nonEmptyOptional(input.context) === undefined\n ? {}\n : { context: nonEmptyOptional(input.context) }),\n mode,\n ...(nonEmptyOptional(input.cwd) === undefined ? {} : { cwd: nonEmptyOptional(input.cwd) }),\n maxTurns: normalizeMaxTurns(input.maxTurns ?? defaults.maxTurns),\n summarize: input.summarize ?? defaults.summarize ?? (mode === \"explore\" || mode === \"general\"),\n worktree: {\n enabled: input.worktree?.enabled ?? false,\n ...(nonEmptyOptional(input.worktree?.path) === undefined\n ? {}\n : { path: nonEmptyOptional(input.worktree?.path) }),\n ...(nonEmptyOptional(input.worktree?.baseRef ?? input.worktree?.baseBranch) === undefined\n ? {}\n : { baseRef: nonEmptyOptional(input.worktree?.baseRef ?? input.worktree?.baseBranch) }),\n ...(nonEmptyOptional(input.worktree?.baseBranch) === undefined\n ? {}\n : { baseBranch: nonEmptyOptional(input.worktree?.baseBranch) }),\n ...(nonEmptyOptional(input.worktree?.branch) === undefined\n ? {}\n : { branch: nonEmptyOptional(input.worktree?.branch) }),\n cleanup: input.worktree?.cleanup ?? \"auto\",\n forceCleanup: input.worktree?.forceCleanup ?? false,\n },\n };\n}\n\nfunction normalizeMaxTurns(value: number | undefined): number {\n if (value === undefined) {\n return 10;\n }\n\n if (!Number.isFinite(value)) {\n return 10;\n }\n\n return Math.max(1, Math.floor(value));\n}\n\nfunction nonEmptyOptional(value: string | undefined): string | undefined {\n const trimmed = value?.trim();\n return trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n","import { execFile } from \"node:child_process\";\nimport { mkdir } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\nimport { promisify } from \"node:util\";\n\nimport { done, notify, type StepFactory, state, step } from \"@trailstep/authoring\";\nimport { delegateTurnPrompt } from \"./prompts.js\";\nimport {\n type AskParentInput,\n type DelegateArtifact,\n type DelegateInput,\n type DelegateOutput,\n type DelegateTurnInput,\n type DelegateTurnOutput,\n type DelegateWorkflowDefaults,\n type DelegateWorktreeCleanupDetails,\n delegateTurnOutputShape,\n type NormalizedDelegateInput,\n normalizeDelegateInput,\n type ParentAnswerOutput,\n type PrepareDelegateTurnInput,\n parentAnswerShape,\n type QuestionAnswer,\n} from \"./schema.js\";\n\nconst MEMORY_LIMIT = 12_000;\nconst execFileAsync = promisify(execFile);\n\nconst DELEGATE_STATE_KEYS = {\n initialized: \"delegate.initialized\",\n input: \"delegate.input\",\n memory: \"delegate.memory\",\n turns: \"delegate.turns\",\n questions: \"delegate.questions\",\n answers: \"delegate.answers\",\n latestSummary: \"delegate.latestSummary\",\n artifacts: \"delegate.artifacts\",\n changedFiles: \"delegate.changedFiles\",\n result: \"delegate.result\",\n worktreePath: \"delegate.worktreePath\",\n worktreeBranch: \"delegate.worktreeBranch\",\n worktreeCleanup: \"delegate.worktreeCleanup\",\n} as const;\n\ninterface InitializeDelegateInput extends Record<string, unknown> {\n readonly input: DelegateInput;\n readonly defaults: DelegateWorkflowDefaults;\n}\n\nexport function initializeDelegateStep(\n input: DelegateInput,\n defaults: DelegateWorkflowDefaults = {},\n): ReturnType<typeof initializeDelegateStepFactory> {\n return initializeDelegateStepFactory({ input, defaults });\n}\n\nconst initializeDelegateStepFactory = step({\n id: \"initialize-delegate\",\n title: \"Initialize delegate\",\n})\n .display(({ input }) => `Delegating: ${(input as InitializeDelegateInput).input.task}`)\n .do(async ({ input, defaults }: InitializeDelegateInput) => {\n const initialized = (await state.get<boolean>(DELEGATE_STATE_KEYS.initialized)) ?? false;\n if (initialized) {\n return prepareDelegateTurnStep({ turn: 1 });\n }\n\n const normalized = normalizeDelegateInput(input, defaults);\n\n if (normalized.cwd !== undefined && normalized.worktree.enabled) {\n return await finalDone({\n status: \"blocked\",\n summary:\n \"Delegate input cannot specify both cwd and worktree.enabled. Choose an existing cwd or managed worktree creation, not both.\",\n questionsAsked: 0,\n turns: 0,\n });\n }\n\n const managedWorktree = normalized.worktree.enabled\n ? await createManagedWorktree(normalized)\n : undefined;\n const executionCwd = managedWorktree?.path ?? resolveDelegateCwd(normalized.cwd);\n const normalizedInput = {\n ...normalized,\n ...(normalized.cwd !== undefined || managedWorktree !== undefined\n ? { cwd: executionCwd }\n : {}),\n };\n\n await state.set(DELEGATE_STATE_KEYS.initialized, true);\n await state.set(DELEGATE_STATE_KEYS.input, normalizedInput);\n await state.set(DELEGATE_STATE_KEYS.memory, \"\");\n await state.set(DELEGATE_STATE_KEYS.turns, 0);\n await state.set(DELEGATE_STATE_KEYS.questions, 0);\n await state.set(DELEGATE_STATE_KEYS.answers, []);\n await state.set(DELEGATE_STATE_KEYS.latestSummary, null);\n await state.set(DELEGATE_STATE_KEYS.artifacts, []);\n await state.set(DELEGATE_STATE_KEYS.changedFiles, []);\n await state.set(DELEGATE_STATE_KEYS.result, null);\n await state.set(DELEGATE_STATE_KEYS.worktreePath, managedWorktree?.path ?? null);\n await state.set(DELEGATE_STATE_KEYS.worktreeBranch, managedWorktree?.branch ?? null);\n await state.set(DELEGATE_STATE_KEYS.worktreeCleanup, null);\n\n await notify.progress(\"Initialized delegate memory\", {\n mode: normalizedInput.mode,\n maxTurns: normalizedInput.maxTurns,\n cwd: executionCwd,\n ...(managedWorktree === undefined\n ? {}\n : { worktreePath: managedWorktree.path, worktreeBranch: managedWorktree.branch }),\n });\n\n return prepareDelegateTurnStep({ turn: 1 });\n });\n\nexport const prepareDelegateTurnStep: StepFactory<\n PrepareDelegateTurnInput,\n PrepareDelegateTurnInput\n> = step({\n id: \"prepare-delegate-turn\",\n title: \"Prepare delegate turn\",\n}).do(async (turnRequest: PrepareDelegateTurnInput) => {\n const input = await requiredState<NormalizedDelegateInput>(DELEGATE_STATE_KEYS.input);\n const turns = (await state.get<number>(DELEGATE_STATE_KEYS.turns)) ?? 0;\n const questionsAsked = (await state.get<number>(DELEGATE_STATE_KEYS.questions)) ?? 0;\n\n if (turnRequest.turn > input.maxTurns) {\n await notify.warning(\"Delegate exceeded maxTurns\", { maxTurns: input.maxTurns, turns });\n return await finalDone({\n status: \"blocked\",\n summary: \"Delegate exceeded maxTurns without completing.\",\n ...(await finalOptionalOutputFields()),\n questionsAsked,\n turns,\n });\n }\n\n const executionCwd = input.cwd ?? state.executionCwd ?? state.cwd ?? process.cwd();\n const turnInput: DelegateTurnInput = {\n task: input.task,\n ...(input.context === undefined ? {} : { context: input.context }),\n mode: input.mode,\n executionCwd,\n ...(input.worktree.enabled ? { worktreePath: executionCwd } : {}),\n memory: (await state.get<string>(DELEGATE_STATE_KEYS.memory)) ?? \"\",\n questionsAndAnswers: (await state.get<QuestionAnswer[]>(DELEGATE_STATE_KEYS.answers)) ?? [],\n latestSummary: (await state.get<string | null>(DELEGATE_STATE_KEYS.latestSummary)) ?? undefined,\n turn: turnRequest.turn,\n maxTurns: input.maxTurns,\n summarize: input.summarize,\n };\n\n return delegateTurnStep(turnInput);\n});\n\nexport const delegateTurnStep: StepFactory<DelegateTurnInput, DelegateTurnOutput> = step({\n id: \"delegate-turn\",\n title: \"Delegate turn\",\n cwd: ({ input }) => (input as DelegateTurnInput).executionCwd,\n})\n .display(({ input }) => `Delegating: ${(input as DelegateTurnInput).task}`)\n .prompt<DelegateTurnInput, DelegateTurnOutput>(delegateTurnPrompt, {\n agent: \"delegateAgent\",\n output: delegateTurnOutputShape,\n })\n .display(({ output }) => output.summary)\n .do(async (turnOutput, input) => {\n const storedTurns = (await state.get<number>(DELEGATE_STATE_KEYS.turns)) ?? 0;\n const alreadyProcessed = storedTurns >= input.turn;\n const turns = alreadyProcessed ? storedTurns : storedTurns + 1;\n\n if (!alreadyProcessed) {\n await state.set(DELEGATE_STATE_KEYS.turns, turns);\n await state.set(DELEGATE_STATE_KEYS.latestSummary, turnOutput.summary);\n await appendMemory(turns, turnOutput);\n await mergeChangedFiles(turnOutput.changedFiles ?? []);\n await mergeArtifacts(turnOutput.artifacts ?? []);\n await state.set(DELEGATE_STATE_KEYS.result, turnOutput.result ?? null);\n\n await notify.progress(\"Updated delegate memory\", { turn: turns });\n for (const artifact of turnOutput.artifacts ?? []) {\n await notify.artifact(artifact.name, {\n path: artifact.path,\n ...(artifact.mediaType === undefined ? {} : { mediaType: artifact.mediaType }),\n });\n }\n }\n\n if (turnOutput.status === \"completed\") {\n const questionsAsked = (await state.get<number>(DELEGATE_STATE_KEYS.questions)) ?? 0;\n return await finalDone({\n status: \"completed\",\n summary: turnOutput.summary,\n ...(await finalOptionalOutputFields(turnOutput)),\n questionsAsked,\n turns,\n });\n }\n\n if (turnOutput.status === \"blocked\") {\n const questionsAsked = (await state.get<number>(DELEGATE_STATE_KEYS.questions)) ?? 0;\n return await finalDone({\n status: \"blocked\",\n summary: turnOutput.summary,\n ...(await finalOptionalOutputFields(turnOutput)),\n questionsAsked,\n turns,\n });\n }\n\n if (turnOutput.status === \"question\") {\n const question = turnOutput.question?.trim();\n if (!question) {\n const questionsAsked = (await state.get<number>(DELEGATE_STATE_KEYS.questions)) ?? 0;\n return await finalDone({\n status: \"blocked\",\n summary: \"Delegate requested a parent answer but did not provide a question.\",\n ...(await finalOptionalOutputFields(turnOutput)),\n questionsAsked,\n turns,\n });\n }\n\n const storedQuestions = (await state.get<number>(DELEGATE_STATE_KEYS.questions)) ?? 0;\n const questionsAsked = alreadyProcessed ? storedQuestions : storedQuestions + 1;\n if (!alreadyProcessed) {\n await state.set(DELEGATE_STATE_KEYS.questions, questionsAsked);\n await notify.progress(\"Delegate asked parent question\", {\n turn: input.turn,\n questionsAsked,\n });\n }\n return askParentStep({ question, nextTurn: input.turn + 1 });\n }\n\n return prepareDelegateTurnStep({ turn: input.turn + 1 });\n });\n\nexport const askParentStep: StepFactory<AskParentInput, AskParentInput> = step({\n id: \"ask-parent\",\n title: \"Ask parent\",\n})\n .display(({ input }) => (input as AskParentInput).question)\n .wait(({ input }) => ({\n id: \"parent-answer\",\n kind: \"input\",\n message: (input as AskParentInput).question,\n output: parentAnswerShape,\n }))\n .do(async (context, input: AskParentInput) => {\n const waitContext = context as unknown as AskParentInput & {\n readonly waits?: Readonly<Record<string, ParentAnswerOutput>>;\n };\n const answerOutput = waitContext.waits?.[\"parent-answer\"];\n const answer = answerOutput?.answer ?? \"\";\n const answers = (await state.get<QuestionAnswer[]>(DELEGATE_STATE_KEYS.answers)) ?? [];\n const alreadyRecorded = answers.some(\n (item) => item.question === input.question && item.answer === answer,\n );\n\n if (answerOutput !== undefined && !alreadyRecorded) {\n await state.set(DELEGATE_STATE_KEYS.answers, [\n ...answers,\n { question: input.question, answer },\n ]);\n await appendMemoryNote(`Parent answered: ${answer}`);\n await notify.progress(\"Recorded parent answer\", { questionsAnswered: answers.length + 1 });\n }\n\n return prepareDelegateTurnStep({ turn: input.nextTurn });\n });\n\nasync function createManagedWorktree(\n input: NormalizedDelegateInput,\n): Promise<{ path: string; branch: string }> {\n const base = state.projectCwd ?? state.executionCwd ?? state.cwd ?? process.cwd();\n const safeRunName = sanitizeRefSegment(state.name);\n const worktreePath = resolve(base, input.worktree.path ?? `.trailstep/worktrees/${safeRunName}`);\n const branch = input.worktree.branch ?? `trailstep/delegate/${safeRunName}`;\n const baseRef = input.worktree.baseRef ?? input.worktree.baseBranch ?? \"HEAD\";\n\n await mkdir(dirname(worktreePath), { recursive: true });\n await git(base, [\"worktree\", \"add\", \"-b\", branch, worktreePath, baseRef]);\n await notify.progress(\"Created delegate worktree\", { path: worktreePath, branch, baseRef });\n return { path: worktreePath, branch };\n}\n\nasync function cleanupManagedWorktree(\n finalStatus: DelegateOutput[\"status\"],\n): Promise<DelegateWorktreeCleanupDetails | undefined> {\n const input = await state.get<NormalizedDelegateInput>(DELEGATE_STATE_KEYS.input);\n const worktreePath = await state.get<string | null>(DELEGATE_STATE_KEYS.worktreePath);\n const worktreeBranch = await state.get<string | null>(DELEGATE_STATE_KEYS.worktreeBranch);\n if (input?.worktree.enabled !== true || worktreePath === undefined || worktreePath === null) {\n return undefined;\n }\n\n const requested = input.worktree.cleanup;\n const keep = async (status: DelegateWorktreeCleanupDetails[\"status\"], reason: string) => {\n const details = { requested, status, reason } satisfies DelegateWorktreeCleanupDetails;\n await state.set(DELEGATE_STATE_KEYS.worktreeCleanup, details);\n await notify.progress(\"Kept delegate worktree\", { path: worktreePath, reason });\n return details;\n };\n\n if (requested === \"never\") {\n return keep(\"kept\", \"cleanup=never\");\n }\n if (requested === \"auto\" && finalStatus !== \"completed\") {\n return keep(\"kept\", \"auto cleanup keeps worktree because delegate did not complete\");\n }\n\n let clean = false;\n try {\n clean = (await git(worktreePath, [\"status\", \"--porcelain\"])).trim().length === 0;\n } catch (error) {\n return keep(\"failed\", `could not prove worktree cleanliness: ${errorMessage(error)}`);\n }\n\n if (!clean && !input.worktree.forceCleanup) {\n return keep(\"kept-dirty\", \"worktree has changes and forceCleanup is false\");\n }\n\n const repoCwd = state.projectCwd ?? state.executionCwd ?? state.cwd ?? process.cwd();\n try {\n const args = [\n \"worktree\",\n \"remove\",\n ...(input.worktree.forceCleanup ? [\"--force\"] : []),\n worktreePath,\n ];\n await git(repoCwd, args);\n } catch (error) {\n return keep(\"failed\", `git worktree remove failed: ${errorMessage(error)}`);\n }\n\n const branchCleanupReason = await cleanupManagedWorktreeBranch({\n repoCwd,\n branch: worktreeBranch,\n createdByRun: input.worktree.branch === undefined,\n });\n const details = {\n requested,\n status: branchCleanupReason?.startsWith(\"managed branch cleanup failed\") ? \"failed\" : \"removed\",\n ...(branchCleanupReason === undefined ? {} : { reason: branchCleanupReason }),\n } satisfies DelegateWorktreeCleanupDetails;\n await state.set(DELEGATE_STATE_KEYS.worktreeCleanup, details);\n await notify.progress(\"Removed delegate worktree\", {\n path: worktreePath,\n reason: branchCleanupReason,\n });\n return details;\n}\n\nasync function cleanupManagedWorktreeBranch({\n repoCwd,\n branch,\n createdByRun,\n}: {\n readonly repoCwd: string;\n readonly branch: string | null | undefined;\n readonly createdByRun: boolean;\n}): Promise<string | undefined> {\n if (branch === undefined || branch === null) {\n return undefined;\n }\n if (!createdByRun) {\n return \"user-supplied branch retained\";\n }\n\n let currentBranch: string;\n try {\n currentBranch = (await git(repoCwd, [\"branch\", \"--show-current\"])).trim();\n } catch (error) {\n return `managed branch cleanup failed after worktree removal: could not determine current branch: ${errorMessage(error)}`;\n }\n if (currentBranch === branch) {\n return \"managed branch retained because it is currently checked out\";\n }\n\n try {\n await git(repoCwd, [\"branch\", \"-d\", branch]);\n return undefined;\n } catch (error) {\n return `managed branch cleanup failed after worktree removal: ${errorMessage(error)}`;\n }\n}\n\nasync function git(cwd: string, args: readonly string[]): Promise<string> {\n const { stdout } = await execFileAsync(\"git\", args, { cwd });\n return stdout;\n}\n\nfunction resolveDelegateCwd(cwd: string | undefined): string {\n const base = state.projectCwd ?? state.executionCwd ?? state.cwd ?? process.cwd();\n return cwd === undefined ? base : resolve(base, cwd);\n}\n\nfunction sanitizeRefSegment(value: string): string {\n return value.replace(/[^A-Za-z0-9._-]+/g, \"-\").replace(/^-+|-+$/g, \"\") || \"run\";\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nasync function appendMemory(turn: number, output: DelegateTurnOutput): Promise<void> {\n const lines = [`Turn ${turn}: ${output.summary}`];\n if (output.memoryPatch?.trim()) {\n lines.push(`Memory patch: ${output.memoryPatch.trim()}`);\n }\n await appendMemoryNote(lines.join(\"\\n\"));\n}\n\nasync function appendMemoryNote(note: string): Promise<void> {\n const existing = (await state.get<string>(DELEGATE_STATE_KEYS.memory)) ?? \"\";\n const updated = [existing.trim(), note.trim()].filter(Boolean).join(\"\\n\\n\");\n await state.set(DELEGATE_STATE_KEYS.memory, trimRollingMemory(updated));\n}\n\nfunction trimRollingMemory(memory: string): string {\n if (memory.length <= MEMORY_LIMIT) {\n return memory;\n }\n\n return `[older delegate memory trimmed]\\n${memory.slice(-MEMORY_LIMIT)}`;\n}\n\nasync function mergeChangedFiles(changedFiles: readonly string[]): Promise<void> {\n if (changedFiles.length === 0) {\n return;\n }\n\n const existing = (await state.get<string[]>(DELEGATE_STATE_KEYS.changedFiles)) ?? [];\n await state.set(DELEGATE_STATE_KEYS.changedFiles, uniqueStrings([...existing, ...changedFiles]));\n}\n\nasync function mergeArtifacts(artifacts: readonly DelegateArtifact[]): Promise<void> {\n if (artifacts.length === 0) {\n return;\n }\n\n const existing = (await state.get<DelegateArtifact[]>(DELEGATE_STATE_KEYS.artifacts)) ?? [];\n const byPath = new Map(existing.map((artifact) => [artifact.path, artifact]));\n for (const artifact of artifacts) {\n byPath.set(artifact.path, artifact);\n }\n await state.set(DELEGATE_STATE_KEYS.artifacts, [...byPath.values()]);\n}\n\nasync function finalOptionalOutputFields(\n latest?: DelegateTurnOutput,\n): Promise<Partial<DelegateOutput>> {\n const result = latest?.result ?? (await state.get<string | null>(DELEGATE_STATE_KEYS.result));\n const changedFiles = (await state.get<string[]>(DELEGATE_STATE_KEYS.changedFiles)) ?? [];\n const artifacts = (await state.get<DelegateArtifact[]>(DELEGATE_STATE_KEYS.artifacts)) ?? [];\n const worktreePath = await state.get<string | null>(DELEGATE_STATE_KEYS.worktreePath);\n const worktreeBranch = await state.get<string | null>(DELEGATE_STATE_KEYS.worktreeBranch);\n const worktreeCleanup = await state.get<DelegateWorktreeCleanupDetails | null>(\n DELEGATE_STATE_KEYS.worktreeCleanup,\n );\n\n return {\n ...(result === undefined || result === null ? {} : { result }),\n ...(changedFiles.length === 0 ? {} : { changedFiles }),\n ...(artifacts.length === 0 ? {} : { artifacts }),\n ...(worktreePath === undefined || worktreePath === null ? {} : { worktreePath }),\n ...(worktreeBranch === undefined || worktreeBranch === null ? {} : { worktreeBranch }),\n ...(worktreeCleanup === undefined || worktreeCleanup === null ? {} : { worktreeCleanup }),\n };\n}\n\nasync function finalDone(output: DelegateOutput) {\n const cleanup = await cleanupManagedWorktree(output.status);\n const finalOutput = cleanup === undefined ? output : { ...output, worktreeCleanup: cleanup };\n return done(finalOutput, { message: delegateTerminalMessage(finalOutput) });\n}\n\nfunction delegateTerminalMessage(output: DelegateOutput): string {\n const lines = [\n `Delegate ${output.status}: ${output.summary}`,\n `Turns: ${output.turns}; questions asked: ${output.questionsAsked}`,\n ];\n if (output.changedFiles && output.changedFiles.length > 0) {\n lines.push(`Changed files: ${output.changedFiles.join(\", \")}`);\n }\n if (output.worktreePath) {\n lines.push(`Worktree: ${output.worktreePath}`);\n }\n if (output.worktreeBranch) {\n lines.push(`Worktree branch: ${output.worktreeBranch}`);\n }\n if (output.worktreeCleanup) {\n lines.push(\n `Worktree cleanup: ${output.worktreeCleanup.status} (${output.worktreeCleanup.requested})${\n output.worktreeCleanup.reason ? ` - ${output.worktreeCleanup.reason}` : \"\"\n }`,\n );\n }\n if (output.result?.trim()) {\n lines.push(output.result.trim());\n }\n return lines.join(\"\\n\");\n}\n\nasync function requiredState<T>(key: string): Promise<T> {\n const value = await state.get<T>(key);\n if (value === undefined || value === null) {\n throw new Error(`Delegate state is missing required key: ${key}`);\n }\n return value;\n}\n\nfunction uniqueStrings(values: readonly string[]): string[] {\n return [...new Set(values.filter((value) => value.trim().length > 0))];\n}\n","import { list, promptSections, section } from \"@trailstep/authoring\";\nimport type { DelegateMode, DelegateTurnInput } from \"./schema.js\";\n\nexport function delegateTurnPrompt({ input }: { readonly input: DelegateTurnInput }): string {\n return promptSections(\n section(\n \"Role\",\n \"You are a continued delegate agent working inside one TrailStep run. Preserve continuity from the run-local memory below, but do not assume or use memory from any separate run.\",\n ),\n section(\"Original task\", input.task),\n section(\"Original context\", input.context),\n section(\"Mode\", `${input.mode}: ${modeGuidance(input.mode)}`),\n section(\n \"Execution location\",\n [\n `CWD/worktree path: ${input.worktreePath ?? input.executionCwd}`,\n \"Honor this directory for any project inspection or file edits.\",\n ].join(\"\\n\"),\n ),\n section(\"Accumulated run-local memory summary\", input.memory || \"No prior delegate memory.\"),\n section(\"Previous questions and parent/human answers\", formatQuestionsAndAnswers(input)),\n section(\"Latest summary\", input.latestSummary ?? \"No prior summary.\"),\n section(\n \"Current turn\",\n [\n `Turn: ${input.turn} of ${input.maxTurns}`,\n `Summarize mode: ${String(input.summarize)}`,\n ].join(\"\\n\"),\n ),\n section(\n \"Instructions\",\n list([\n \"Do one focused turn of delegated work; keep the work bounded and observable.\",\n \"Use the run-local memory summary and previous Q/A as continuity, not an unlimited transcript.\",\n \"If you can finish the task now, return status `completed` with a concise summary and final result.\",\n \"If more delegated work is needed and no parent answer is required, return status `continue` and a memory patch for the next turn.\",\n \"If blocked on a parent/human decision, return status `question`, include exactly one clear question, and summarize why it is needed.\",\n \"If the task cannot proceed safely, return status `blocked` with the reason in the summary/result.\",\n \"When you learn durable facts for this run, include a compact `memoryPatch`; do not copy large transcripts, files, or diffs.\",\n \"Report changed files and artifacts only when you actually changed or produced them.\",\n ]),\n ),\n section(\"Exact output contract\", outputContract),\n );\n}\n\nfunction modeGuidance(mode: DelegateMode): string {\n switch (mode) {\n case \"explore\":\n return \"investigate, summarize findings, and avoid code changes unless explicitly needed.\";\n case \"implement\":\n return \"make the smallest safe implementation progress and report changed files.\";\n case \"review\":\n return \"review existing work, identify issues, and avoid unnecessary edits.\";\n case \"general\":\n return \"use judgment to complete the delegated task with focused, bounded work.\";\n }\n}\n\nfunction formatQuestionsAndAnswers(input: DelegateTurnInput): string {\n if (input.questionsAndAnswers.length === 0) {\n return \"No parent/human questions have been asked in this run.\";\n }\n\n return input.questionsAndAnswers\n .map((item, index) =>\n [`${index + 1}. Question: ${item.question}`, ` Answer: ${item.answer}`].join(\"\\n\"),\n )\n .join(\"\\n\");\n}\n\nconst outputContract = `Return the structured JSON object requested by the wrapper.\n\nStatus meanings:\n- completed: the delegated task is finished; include result when useful.\n- continue: more bounded work is needed in another turn; include memoryPatch for durable continuity.\n- question: parent/human input is required; include exactly one clear question.\n- blocked: the task cannot proceed safely; summarize why and include result details when useful.\n\nOnly report changedFiles/artifacts that you actually changed or produced.`;\n","import { defineWorkflow, done, parallel, state, step } from \"@trailstep/authoring\";\nimport type { DelegateMode, DelegateWorktreeInput } from \"../delegate/schema.js\";\nimport {\n delegate,\n delegateArchitectPlanner,\n delegateExplore,\n delegateImplement,\n delegateQuickImplementor,\n delegateRelentlessDebugger,\n delegateReview,\n delegateSchemaFormatter,\n delegateSimpleExplore,\n delegateSmartImplementor,\n} from \"../delegate/workflow.js\";\nimport {\n type DelegateParallelDelegate,\n type DelegateParallelInput,\n type DelegateParallelOutput,\n delegateParallelInputShape,\n delegateParallelOutputShape,\n type NormalizedDelegateParallelTask,\n} from \"./schema.js\";\n\nexport type {\n DelegateParallelBranchOutput,\n DelegateParallelInput,\n DelegateParallelOutput,\n DelegateParallelTaskInput,\n NormalizedDelegateParallelTask,\n} from \"./schema.js\";\n\nexport const delegateParallel = defineWorkflow<DelegateParallelInput, DelegateParallelOutput>({\n id: \"delegateParallel\",\n description: \"Fans out required delegate tasks across parallel delegate workflows.\",\n skill: delegateParallelSkill(),\n inputShape: delegateParallelInputShape,\n outputShape: delegateParallelOutputShape,\n start(input) {\n return initializeDelegateParallelStep(input);\n },\n});\n\nconst initializeDelegateParallelStep = step({\n id: \"initialize-delegate-parallel\",\n title: \"Initialize parallel delegates\",\n})\n .display(({ input }) => `Preparing ${(input as DelegateParallelInput).tasks.length} delegates`)\n .do((input: DelegateParallelInput) => {\n const normalized = normalizeDelegateParallelTasks(input, state.name);\n if (normalized.status === \"blocked\") {\n return done({ status: \"blocked\", summary: normalized.summary });\n }\n\n return parallel<DelegateParallelOutput>(\n normalized.tasks.map((task) =>\n delegateWorkflowForTask(task)(task.input, { branchId: task.branchId }),\n ),\n );\n });\n\nexport function normalizeDelegateParallelTasks(\n input: DelegateParallelInput,\n runName: string,\n):\n | { readonly status: \"ready\"; readonly tasks: readonly NormalizedDelegateParallelTask[] }\n | { readonly status: \"blocked\"; readonly summary: string } {\n if (input.tasks.length === 0) {\n return { status: \"blocked\", summary: \"delegateParallel requires at least one task.\" };\n }\n\n const seenIds = new Set<string>();\n const seenBranches = new Set<string>();\n const tasks: NormalizedDelegateParallelTask[] = [];\n\n for (const task of input.tasks) {\n const id = task.id.trim();\n const taskText = task.task.trim();\n if (id.length === 0) {\n return { status: \"blocked\", summary: \"delegateParallel task ids must be non-empty.\" };\n }\n if (taskText.length === 0) {\n return {\n status: \"blocked\",\n summary: `delegateParallel task ${id} must include non-empty task text.`,\n };\n }\n if (seenIds.has(id)) {\n return { status: \"blocked\", summary: `delegateParallel task id '${id}' is duplicated.` };\n }\n seenIds.add(id);\n\n const branchId = `delegate-${stableSegment(id)}`;\n if (seenBranches.has(branchId)) {\n return {\n status: \"blocked\",\n summary: `delegateParallel task id '${id}' normalizes to duplicate branch id '${branchId}'.`,\n };\n }\n seenBranches.add(branchId);\n\n const delegateSelection = normalizeDelegateSelection(task.delegate);\n const mode = task.mode ?? defaultModeForDelegate(delegateSelection);\n const cwd = nonEmpty(task.cwd) ?? nonEmpty(input.cwd);\n const worktree = normalizeTaskWorktree({\n parent: input.worktree,\n task: task.worktree,\n cwd,\n runName,\n taskSegment: stableSegment(id),\n });\n const context = combineContext(input.context, task.context);\n const maxTurns = task.maxTurns ?? input.maxTurns;\n const summarize = task.summarize ?? input.summarize;\n\n tasks.push({\n id,\n mode,\n ...(delegateSelection === undefined ? {} : { delegate: delegateSelection }),\n branchId,\n input: {\n task: taskText,\n mode,\n ...(context === undefined ? {} : { context }),\n ...(cwd === undefined ? {} : { cwd }),\n ...(maxTurns === undefined ? {} : { maxTurns }),\n ...(summarize === undefined ? {} : { summarize }),\n ...(worktree === undefined ? {} : { worktree }),\n },\n });\n }\n\n return { status: \"ready\", tasks };\n}\n\nfunction delegateWorkflowForTask(task: NormalizedDelegateParallelTask): typeof delegate {\n switch (task.delegate) {\n case \"simple-explore\":\n return delegateSimpleExplore;\n case \"architect-planner\":\n return delegateArchitectPlanner;\n case \"quick-implementor\":\n return delegateQuickImplementor;\n case \"smart-implementor\":\n return delegateSmartImplementor;\n case \"relentless-debugger\":\n case \"fixer\":\n return delegateRelentlessDebugger;\n case \"schema-formatter\":\n return delegateSchemaFormatter;\n case \"delegate\":\n case undefined:\n return delegateWorkflowForMode(task.mode);\n }\n}\n\nfunction delegateWorkflowForMode(mode: DelegateMode): typeof delegate {\n switch (mode) {\n case \"explore\":\n return delegateExplore;\n case \"implement\":\n return delegateImplement;\n case \"review\":\n return delegateReview;\n case \"general\":\n return delegate;\n }\n}\n\nfunction normalizeDelegateSelection(\n value: DelegateParallelDelegate | undefined,\n): DelegateParallelDelegate | undefined {\n return value === undefined ? undefined : value;\n}\n\nfunction defaultModeForDelegate(\n delegateSelection: DelegateParallelDelegate | undefined,\n): DelegateMode {\n switch (delegateSelection) {\n case \"simple-explore\":\n case \"architect-planner\":\n return \"explore\";\n case \"quick-implementor\":\n case \"smart-implementor\":\n case \"relentless-debugger\":\n case \"fixer\":\n return \"implement\";\n case \"schema-formatter\":\n case \"delegate\":\n case undefined:\n return \"general\";\n }\n}\n\nfunction normalizeTaskWorktree(input: {\n readonly parent?: DelegateWorktreeInput;\n readonly task?: DelegateWorktreeInput;\n readonly cwd?: string;\n readonly runName: string;\n readonly taskSegment: string;\n}): DelegateWorktreeInput | undefined {\n if (input.cwd !== undefined) {\n return input.task?.enabled === true ? input.task : undefined;\n }\n\n const enabled = input.task?.enabled ?? input.parent?.enabled;\n if (enabled !== true) {\n return input.task ?? input.parent;\n }\n\n const merged = { ...input.parent, ...input.task, enabled: true };\n return {\n ...merged,\n path: nonEmpty(merged.path) ?? `.trailstep/worktrees/${input.runName}/${input.taskSegment}`,\n branch: nonEmpty(merged.branch) ?? `trailstep/delegate/${input.runName}/${input.taskSegment}`,\n };\n}\n\nfunction combineContext(parent: string | undefined, task: string | undefined): string | undefined {\n const parentContext = nonEmpty(parent);\n const taskContext = nonEmpty(task);\n if (parentContext === undefined) {\n return taskContext;\n }\n if (taskContext === undefined) {\n return parentContext;\n }\n return `${parentContext}\\n\\n${taskContext}`;\n}\n\nfunction nonEmpty(value: string | undefined): string | undefined {\n const trimmed = value?.trim();\n return trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction stableSegment(value: string): string {\n const segment = value\n .trim()\n .replace(/[^A-Za-z0-9._-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n return segment.length > 0 ? segment : `task-${hashString(value)}`;\n}\n\nfunction hashString(value: string): string {\n let hash = 0x811c9dc5;\n for (let index = 0; index < value.length; index += 1) {\n hash ^= value.charCodeAt(index);\n hash = Math.imul(hash, 0x01000193);\n }\n return (hash >>> 0).toString(16);\n}\n\nfunction delegateParallelSkill(): string {\n return `---\nname: trst-delegate-parallel\ndescription: Use as a parent-agent fan-out tool for required TrailStep delegate tasks that can run in parallel.\nx-trailstep-user-facing: false\n---\n# TrailStep delegateParallel workflow\n\nUse this workflow when a parent agent already has a set of concrete, independent delegate tasks. It fans out directly to the existing delegate, delegateExplore, delegateReview, and delegateImplement workflows based on each task mode. It does not add a planning agent and does not merge results beyond returning the parallel branch outputs.\n\nEach task must provide a stable \\`id\\`, \\`mode\\`, and \\`task\\` text. Shared \\`context\\`, \\`cwd\\`, \\`maxTurns\\`, \\`summarize\\`, and \\`worktree\\` values are applied as defaults; task-level values override them. Managed worktrees under \\`worktree.enabled=true\\` default per task to \\`.trailstep/worktrees/<runName>/<taskId>\\` and \\`trailstep/delegate/<runName>/<taskId>\\` to avoid collisions.`;\n}\n","import { jsonSchema } from \"@trailstep/authoring\";\nimport type {\n DelegateInput,\n DelegateMode,\n DelegateOutput,\n DelegateWorktreeInput,\n} from \"../delegate/schema.js\";\n\nexport type DelegateParallelDelegate =\n | \"delegate\"\n | \"simple-explore\"\n | \"architect-planner\"\n | \"quick-implementor\"\n | \"smart-implementor\"\n | \"relentless-debugger\"\n | \"fixer\"\n | \"schema-formatter\";\n\nexport interface DelegateParallelTaskInput extends Record<string, unknown> {\n readonly id: string;\n readonly mode?: DelegateMode;\n readonly delegate?: DelegateParallelDelegate;\n readonly task: string;\n readonly context?: string;\n readonly cwd?: string;\n readonly maxTurns?: number;\n readonly summarize?: boolean;\n readonly worktree?: DelegateWorktreeInput;\n}\n\nexport interface DelegateParallelInput extends Record<string, unknown> {\n readonly context?: string;\n readonly cwd?: string;\n readonly maxTurns?: number;\n readonly summarize?: boolean;\n readonly worktree?: DelegateWorktreeInput;\n readonly tasks: readonly DelegateParallelTaskInput[];\n}\n\nexport interface DelegateParallelBranchOutput extends Record<string, unknown> {\n readonly status: \"done\" | \"failed\" | \"cancelled\";\n readonly output?: DelegateOutput;\n}\n\nexport interface DelegateParallelOutput extends Record<string, unknown> {\n readonly status: \"completed\" | \"blocked\";\n readonly summary?: string;\n readonly branches?: Record<string, DelegateParallelBranchOutput>;\n}\n\nexport interface NormalizedDelegateParallelTask extends Record<string, unknown> {\n readonly id: string;\n readonly mode: DelegateMode;\n readonly delegate?: DelegateParallelDelegate;\n readonly branchId: string;\n readonly input: DelegateInput;\n}\n\nexport const delegateParallelInputShape = jsonSchema<DelegateParallelInput>({\n type: \"object\",\n properties: {\n context: { type: \"string\" },\n cwd: { type: \"string\" },\n maxTurns: { type: \"number\" },\n summarize: { type: \"boolean\" },\n worktree: {\n type: \"object\",\n properties: {\n enabled: { type: \"boolean\" },\n path: { type: \"string\" },\n baseRef: { type: \"string\" },\n baseBranch: { type: \"string\" },\n branch: { type: \"string\" },\n cleanup: { type: \"string\", enum: [\"auto\", \"never\", \"always\"] },\n forceCleanup: { type: \"boolean\" },\n },\n additionalProperties: false,\n },\n tasks: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n id: { type: \"string\" },\n mode: { type: \"string\", enum: [\"explore\", \"implement\", \"review\", \"general\"] },\n delegate: {\n type: \"string\",\n enum: [\n \"delegate\",\n \"simple-explore\",\n \"architect-planner\",\n \"quick-implementor\",\n \"smart-implementor\",\n \"relentless-debugger\",\n \"fixer\",\n \"schema-formatter\",\n ],\n },\n task: { type: \"string\" },\n context: { type: \"string\" },\n cwd: { type: \"string\" },\n maxTurns: { type: \"number\" },\n summarize: { type: \"boolean\" },\n worktree: {\n type: \"object\",\n properties: {\n enabled: { type: \"boolean\" },\n path: { type: \"string\" },\n baseRef: { type: \"string\" },\n baseBranch: { type: \"string\" },\n branch: { type: \"string\" },\n cleanup: { type: \"string\", enum: [\"auto\", \"never\", \"always\"] },\n forceCleanup: { type: \"boolean\" },\n },\n additionalProperties: false,\n },\n },\n anyOf: [{ required: [\"mode\"] }, { required: [\"delegate\"] }],\n required: [\"id\", \"task\"],\n additionalProperties: false,\n },\n },\n },\n required: [\"tasks\"],\n additionalProperties: false,\n});\n\nexport const delegateParallelOutputShape = jsonSchema<DelegateParallelOutput>({\n type: \"object\",\n properties: {\n status: { type: \"string\", enum: [\"completed\", \"blocked\"] },\n summary: { type: \"string\" },\n branches: { type: \"object\", additionalProperties: true },\n },\n required: [\"status\"],\n additionalProperties: false,\n});\n"],"mappings":";AAAA,SAAS,sBAAsB;;;ACA/B,SAAS,kBAAkB;AA2HpB,IAAM,wBAAwB;AAAA,EACnC,MAAM;AAAA,EACN,YAA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sonSchema","defineWorkflow","step","state","done"]}
|
|
1
|
+
{"version":3,"sources":["../src/delegate/workflow.ts","../src/delegate/schema.ts","../src/delegate/steps.ts","../src/delegate/prompts.ts","../src/delegate-parallel/workflow.ts","../src/delegate-parallel/schema.ts"],"sourcesContent":["import { defineWorkflow } from \"@trailstep/authoring\";\nimport {\n type DelegateInput,\n type DelegateMode,\n type DelegateOutput,\n delegateInputShape,\n delegateOutputShape,\n} from \"./schema.js\";\nimport { initializeDelegateStep } from \"./steps.js\";\n\nexport type {\n DelegateArtifact,\n DelegateInput,\n DelegateMode,\n DelegateOutput,\n DelegateTurnOutput,\n DelegateTurnStatus,\n DelegateWorktreeInput,\n} from \"./schema.js\";\n\nexport type DelegateWorkflowConfig = {\n readonly id: string;\n readonly description: string;\n readonly skillName: string;\n readonly skillDescription: string;\n readonly skillFocus: string;\n readonly defaultMode: DelegateMode;\n readonly defaultMaxTurns: number;\n readonly summarize?: boolean;\n readonly agentSize?: \"small\" | \"medium\" | \"large\";\n readonly agentThinking?: \"low\" | \"medium\" | \"high\";\n};\n\nexport function defineDelegateWorkflow(config: DelegateWorkflowConfig) {\n return defineWorkflow<DelegateInput, DelegateOutput>({\n id: config.id,\n description: config.description,\n skill: delegateSkill(config),\n inputShape: delegateInputShape,\n outputShape: delegateOutputShape,\n agents: {\n delegateAgent: {\n size: config.agentSize ?? \"medium\",\n thinking: config.agentThinking ?? \"medium\",\n description: config.description,\n },\n },\n start(input) {\n return initializeDelegateStep(input, {\n mode: config.defaultMode,\n maxTurns: config.defaultMaxTurns,\n ...(config.summarize === undefined ? {} : { summarize: config.summarize }),\n });\n },\n });\n}\n\nexport const delegate = defineDelegateWorkflow({\n id: \"delegate\",\n description: \"Runs delegated focused work while preserving run-local continuity.\",\n skillName: \"trst-delegate\",\n skillDescription:\n \"Use when you need to delegate a single bounded task and want to choose mode, turn budget, and context shape explicitly. General-purpose delegate for focused work.\",\n skillFocus:\n \"Use for general delegated work when the parent agent wants to choose the task, mode, turn budget, and context shape explicitly. Prefer the specialized explore, implement, review, or debugger variants when they fit. If you have 2+ independent tasks, use trst-delegate-parallel instead of calling this sequentially.\",\n defaultMode: \"general\",\n defaultMaxTurns: 10,\n});\n\nexport const delegateExplore = defineDelegateWorkflow({\n id: \"delegateExplore\",\n description: \"Runs read-oriented delegated exploration while preserving run-local continuity.\",\n skillName: \"trst-delegate-explore\",\n skillDescription:\n \"Use when you need to investigate the codebase, understand how code works, find where something lives, or trace a flow. Read-only exploration that summarizes findings without editing files.\",\n skillFocus:\n \"Explore mode is read-oriented: when you need to investigate the codebase, inspect code, commands, docs, and artifacts; summarize findings and avoid edits unless the task explicitly asks for them. If you have 2+ independent exploration questions, use trst-delegate-parallel instead of calling this sequentially.\",\n defaultMode: \"explore\",\n defaultMaxTurns: 6,\n summarize: true,\n});\n\nexport const delegateSimpleExplore = defineDelegateWorkflow({\n id: \"delegateSimpleExplore\",\n description: \"Runs narrow, low-cost read-only exploration while preserving run-local continuity.\",\n skillName: \"trst-delegate-simple-explore\",\n skillDescription:\n \"Use when you need a quick low-cost answer to a narrow repo question like where is X, what calls Y, or what does this file do. Read-only single-area lookup.\",\n skillFocus:\n \"Simple explore is read-only and narrow: when you need a quick answer to a focused repo question, inspect one area, summarize concise findings, and avoid edits. If you have 2+ independent lookup questions, use trst-delegate-parallel instead of calling this sequentially.\",\n defaultMode: \"explore\",\n defaultMaxTurns: 4,\n summarize: true,\n agentSize: \"small\",\n agentThinking: \"low\",\n});\n\nexport const delegateArchitectPlanner = defineDelegateWorkflow({\n id: \"delegateArchitectPlanner\",\n description: \"Scouts the codebase to identify the few files or seams likely needing edits.\",\n skillName: \"trst-delegate-architect-planner\",\n skillDescription:\n \"Use when you have a bug report or feature request and need to map it to the 3-4 files or seams most likely to need edits before implementing. Read-only scouting, no code changes.\",\n skillFocus:\n \"Architect planner is read-only: when you need to plan before changing files, grep/read the repo, identify the 3-4 files or seams most likely to need edits, explain why, and do not write code.\",\n defaultMode: \"explore\",\n defaultMaxTurns: 6,\n summarize: true,\n agentSize: \"medium\",\n agentThinking: \"medium\",\n});\n\nexport const delegateReview = defineDelegateWorkflow({\n id: \"delegateReview\",\n description: \"Runs delegated review work while preserving run-local continuity.\",\n skillName: \"trst-delegate-review\",\n skillDescription:\n \"Use when you need to review existing code, a plan, or a diff for concrete issues and risks. Inspects without editing unless a fix is explicitly requested.\",\n skillFocus:\n \"Review mode: when you need a focused review of existing work, inspect it, identify concrete issues and risks, and avoid edits unless the parent task explicitly requests a fix. If you have 2+ independent reviews, use trst-delegate-parallel instead of calling this sequentially.\",\n defaultMode: \"review\",\n defaultMaxTurns: 6,\n summarize: false,\n});\n\nexport const delegateImplement = defineDelegateWorkflow({\n id: \"delegateImplement\",\n description: \"Runs delegated implementation work while preserving run-local continuity.\",\n skillName: \"trst-delegate-implement\",\n skillDescription:\n \"Use when you need to change files to implement a bounded fix or feature. Makes edits, runs focused checks when practical, and reports changed files.\",\n skillFocus:\n \"Implement mode may edit files: when you need to change files, make the smallest safe change, run focused checks when practical, and always report changedFiles/artifacts that were actually produced. If you have 2+ independent file changes, use trst-delegate-parallel instead of calling this sequentially.\",\n defaultMode: \"implement\",\n defaultMaxTurns: 12,\n summarize: false,\n agentThinking: \"medium\",\n});\n\nexport const delegateQuickImplementor = defineDelegateWorkflow({\n id: \"delegateQuickImplementor\",\n description: \"Runs strict localized implementation work for mechanical changes.\",\n skillName: \"trst-delegate-quick-implementor\",\n skillDescription:\n \"Use when instructions are already concrete and you need strict localized boilerplate edits with no architecture decisions. Mechanical typist that edits files.\",\n skillFocus:\n \"Quick implementor is the typist: when the plan is already concrete and you need to change files, follow instructions, make localized edits only, avoid broad architecture decisions, run focused checks when practical, and report changedFiles. If you have 2+ independent mechanical edits, use trst-delegate-parallel instead of calling this sequentially.\",\n defaultMode: \"implement\",\n defaultMaxTurns: 8,\n summarize: false,\n agentSize: \"medium\",\n agentThinking: \"medium\",\n});\n\nexport const delegateSmartImplementor = defineDelegateWorkflow({\n id: \"delegateSmartImplementor\",\n description: \"Runs complex implementation, algorithmic work, or cross-file refactors.\",\n skillName: \"trst-delegate-smart-implementor\",\n skillDescription:\n \"Use when you need complex cross-file refactoring, algorithmic work, or interconnected system changes. Heavy-lifter that edits files and keeps scope bounded.\",\n skillFocus:\n \"Smart implementor is the heavy-lifter: when you need complex logic, cross-file refactors, algorithms, or non-trivial systems, handle the interconnected changes, keep scope bounded, and report changedFiles. If you have 2+ independent complex changes, use trst-delegate-parallel instead of calling this sequentially.\",\n defaultMode: \"implement\",\n defaultMaxTurns: 14,\n summarize: false,\n agentSize: \"large\",\n agentThinking: \"high\",\n});\n\nexport const delegateRelentlessDebugger = defineDelegateWorkflow({\n id: \"delegateRelentlessDebugger\",\n description: \"Diagnoses and fixes validation, lint, test, or runtime failures.\",\n skillName: \"trst-delegate-relentless-debugger\",\n skillDescription:\n \"Use when lint, typecheck, tests, or runtime are failing and you need to diagnose stack traces or diagnostics and fix them iteratively. Preserves intent while editing files.\",\n skillFocus:\n \"Relentless debugger is the fixer: when validation, lint, tests, or runtime fail and you need to change files to fix them, consume diagnostics, preserve the intended change, fix failures iteratively, and avoid redesign unless required by the failure evidence.\",\n defaultMode: \"implement\",\n defaultMaxTurns: 12,\n summarize: false,\n agentSize: \"large\",\n agentThinking: \"high\",\n});\n\nexport const delegateSchemaFormatter = defineDelegateWorkflow({\n id: \"delegateSchemaFormatter\",\n description: \"Produces exact structured output for schema-bound handoffs.\",\n skillName: \"trst-delegate-schema-formatter\",\n skillDescription:\n \"Use when you need exact JSON, XML, or schema-constrained output for a handoff. Formatting-only, prioritizes exact structure over prose.\",\n skillFocus:\n \"Schema formatter is the translator: when you need exact structured output, prioritize the requested JSON/XML/schema structure, avoid extra prose, and do not perform broad implementation work unless explicitly requested.\",\n defaultMode: \"general\",\n defaultMaxTurns: 4,\n summarize: false,\n agentSize: \"small\",\n agentThinking: \"low\",\n});\n\nfunction delegateSkill(config: DelegateWorkflowConfig): string {\n return `---\nname: ${config.skillName}\ndescription: ${config.skillDescription}\nx-trailstep-user-facing: false\n---\n# TrailStep ${config.id} workflow\n\n${config.skillFocus}\n\nUse this workflow as a parent-agent/delegate tool when a parent agent needs bounded work in a repository. The delegate keeps continuity only inside one TrailStep run; separate runs do not share memory.\n\n## Parent-agent usage\n\n- For simple tasks, pass direct flags: \\`trailstep @trailstep/sub-agents#${config.id} --task \"...\"\\`.\n- For one-shot JSON, pipe it to \\`trailstep @trailstep/sub-agents#${config.id} --input-file -\\`; for long/reusable context, write an input JSON file and run \\`trailstep @trailstep/sub-agents#${config.id} --input-file delegate-input.json\\`.\n- Use unique run names for parallel delegates so their run-local state stays separate.\n- Use \\`cwd\\` for an existing worktree or subdirectory that TrailStep should not manage. Use \\`worktree.enabled=true\\` when the delegate should create a managed git worktree and safely clean it up/report it.\n- Do not pass both \\`cwd\\` and \\`worktree.enabled=true\\`; choose one execution location strategy.\n- If a delegate asks a question, answer with \\`trailstep answer <runName> parent-answer --json '{\"answer\":\"...\"}'\\`, then resume with \\`trailstep continue <runName>\\`.\n- Retry a failed turn with \\`trailstep retry <workflowRef> <runName>\\` when appropriate.\n- Read final typed output with \\`trailstep output <runName>\\`; read the terminal summary with \\`trailstep output <runName> --message\\`.\n- Package reference: \\`@trailstep/sub-agents#${config.id}\\`; built dist reference: \\`./packages/sub-agents/dist/index.js#${config.id}\\`.\n\nThis skill is intended for delegated working-agent use rather than direct end-user planning chat. Preserve the run-local memory supplied in the workflow prompt, keep work bounded to the requested turn, and return the JSON contract requested by the workflow prompt.`;\n}\n","import { jsonSchema } from \"@trailstep/authoring\";\n\nexport type DelegateMode = \"explore\" | \"implement\" | \"review\" | \"general\";\nexport type DelegateStatus = \"completed\" | \"blocked\" | \"cancelled\";\nexport type DelegateTurnStatus = \"completed\" | \"continue\" | \"question\" | \"blocked\";\n\nexport interface DelegateArtifact extends Record<string, unknown> {\n readonly name: string;\n readonly path: string;\n readonly mediaType?: string;\n}\n\nexport type DelegateWorktreeCleanup = \"auto\" | \"never\" | \"always\";\n\nexport interface DelegateWorktreeInput extends Record<string, unknown> {\n readonly enabled?: boolean;\n readonly path?: string;\n readonly baseRef?: string;\n /** @deprecated Use baseRef. */\n readonly baseBranch?: string;\n readonly branch?: string;\n readonly cleanup?: DelegateWorktreeCleanup;\n readonly forceCleanup?: boolean;\n}\n\nexport interface DelegateInput extends Record<string, unknown> {\n readonly task: string;\n readonly context?: string;\n readonly mode?: DelegateMode;\n readonly cwd?: string;\n readonly maxTurns?: number;\n readonly summarize?: boolean;\n readonly worktree?: DelegateWorktreeInput;\n}\n\nexport interface DelegateOutput extends Record<string, unknown> {\n readonly status: DelegateStatus;\n readonly summary: string;\n readonly result?: string;\n readonly changedFiles?: readonly string[];\n readonly artifacts?: readonly DelegateArtifact[];\n readonly worktreePath?: string;\n readonly worktreeBranch?: string;\n readonly worktreeCleanup?: DelegateWorktreeCleanupDetails;\n readonly questionsAsked: number;\n readonly turns: number;\n}\n\nexport interface DelegateTurnOutput extends Record<string, unknown> {\n readonly status: DelegateTurnStatus;\n readonly summary: string;\n readonly memoryPatch?: string;\n readonly question?: string;\n readonly result?: string;\n readonly changedFiles?: readonly string[];\n readonly artifacts?: readonly DelegateArtifact[];\n}\n\nexport interface ParentAnswerOutput extends Record<string, unknown> {\n readonly answer: string;\n}\n\nexport interface DelegateWorktreeCleanupDetails extends Record<string, unknown> {\n readonly requested: DelegateWorktreeCleanup;\n readonly status: \"not-managed\" | \"kept\" | \"removed\" | \"kept-dirty\" | \"failed\";\n readonly reason?: string;\n}\n\nexport interface DelegateWorktreeOptions extends Record<string, unknown> {\n readonly enabled: boolean;\n readonly path?: string;\n readonly baseRef?: string;\n /** @deprecated Use baseRef. */\n readonly baseBranch?: string;\n readonly branch?: string;\n readonly cleanup: DelegateWorktreeCleanup;\n readonly forceCleanup: boolean;\n}\n\nexport interface DelegateWorkflowDefaults extends Record<string, unknown> {\n readonly mode?: DelegateMode;\n readonly maxTurns?: number;\n readonly summarize?: boolean;\n}\n\nexport interface NormalizedDelegateInput extends Record<string, unknown> {\n readonly task: string;\n readonly context?: string;\n readonly mode: DelegateMode;\n readonly cwd?: string;\n readonly maxTurns: number;\n readonly summarize: boolean;\n readonly worktree: DelegateWorktreeOptions;\n}\n\nexport interface QuestionAnswer extends Record<string, unknown> {\n readonly question: string;\n readonly answer: string;\n}\n\nexport interface DelegateTurnInput extends Record<string, unknown> {\n readonly task: string;\n readonly context?: string;\n readonly mode: DelegateMode;\n readonly executionCwd: string;\n readonly worktreePath?: string;\n readonly memory: string;\n readonly questionsAndAnswers: readonly QuestionAnswer[];\n readonly latestSummary?: string;\n readonly turn: number;\n readonly maxTurns: number;\n readonly summarize: boolean;\n}\n\nexport interface PrepareDelegateTurnInput extends Record<string, unknown> {\n readonly turn: number;\n}\n\nexport interface AskParentInput extends Record<string, unknown> {\n readonly question: string;\n readonly nextTurn: number;\n}\n\nexport const delegateArtifactShape = {\n type: \"object\",\n properties: {\n name: { type: \"string\" },\n path: { type: \"string\" },\n mediaType: { type: \"string\" },\n },\n required: [\"name\", \"path\"],\n additionalProperties: false,\n} as const;\n\nexport const delegateInputShape = jsonSchema<DelegateInput>({\n type: \"object\",\n properties: {\n task: { type: \"string\" },\n context: { type: \"string\" },\n mode: { type: \"string\", enum: [\"explore\", \"implement\", \"review\", \"general\"] },\n cwd: { type: \"string\" },\n maxTurns: { type: \"number\" },\n summarize: { type: \"boolean\" },\n worktree: {\n type: \"object\",\n properties: {\n enabled: { type: \"boolean\" },\n path: { type: \"string\" },\n baseRef: { type: \"string\" },\n baseBranch: { type: \"string\" },\n branch: { type: \"string\" },\n cleanup: { type: \"string\", enum: [\"auto\", \"never\", \"always\"] },\n forceCleanup: { type: \"boolean\" },\n },\n additionalProperties: false,\n },\n },\n required: [\"task\"],\n additionalProperties: false,\n});\n\nexport const delegateOutputShape = jsonSchema<DelegateOutput>({\n type: \"object\",\n properties: {\n status: { type: \"string\", enum: [\"completed\", \"blocked\", \"cancelled\"] },\n summary: { type: \"string\" },\n result: { type: \"string\" },\n changedFiles: { type: \"array\", items: { type: \"string\" } },\n artifacts: { type: \"array\", items: delegateArtifactShape },\n worktreePath: { type: \"string\" },\n worktreeBranch: { type: \"string\" },\n worktreeCleanup: {\n type: \"object\",\n properties: {\n requested: { type: \"string\", enum: [\"auto\", \"never\", \"always\"] },\n status: {\n type: \"string\",\n enum: [\"not-managed\", \"kept\", \"removed\", \"kept-dirty\", \"failed\"],\n },\n reason: { type: \"string\" },\n },\n required: [\"requested\", \"status\"],\n additionalProperties: false,\n },\n questionsAsked: { type: \"number\" },\n turns: { type: \"number\" },\n },\n required: [\"status\", \"summary\", \"questionsAsked\", \"turns\"],\n additionalProperties: false,\n});\n\nexport const delegateTurnOutputShape = jsonSchema<DelegateTurnOutput>({\n type: \"object\",\n properties: {\n status: { type: \"string\", enum: [\"completed\", \"continue\", \"question\", \"blocked\"] },\n summary: { type: \"string\" },\n memoryPatch: { type: \"string\" },\n question: { type: \"string\" },\n result: { type: \"string\" },\n changedFiles: { type: \"array\", items: { type: \"string\" } },\n artifacts: { type: \"array\", items: delegateArtifactShape },\n },\n required: [\"status\", \"summary\"],\n additionalProperties: false,\n});\n\nexport const parentAnswerShape = jsonSchema<ParentAnswerOutput>({\n type: \"object\",\n properties: {\n answer: { type: \"string\" },\n },\n required: [\"answer\"],\n additionalProperties: false,\n});\n\nexport function normalizeDelegateInput(\n input: DelegateInput,\n defaults: DelegateWorkflowDefaults = {},\n): NormalizedDelegateInput {\n const mode = input.mode ?? defaults.mode ?? \"general\";\n return {\n task: input.task,\n ...(nonEmptyOptional(input.context) === undefined\n ? {}\n : { context: nonEmptyOptional(input.context) }),\n mode,\n ...(nonEmptyOptional(input.cwd) === undefined ? {} : { cwd: nonEmptyOptional(input.cwd) }),\n maxTurns: normalizeMaxTurns(input.maxTurns ?? defaults.maxTurns),\n summarize: input.summarize ?? defaults.summarize ?? (mode === \"explore\" || mode === \"general\"),\n worktree: {\n enabled: input.worktree?.enabled ?? false,\n ...(nonEmptyOptional(input.worktree?.path) === undefined\n ? {}\n : { path: nonEmptyOptional(input.worktree?.path) }),\n ...(nonEmptyOptional(input.worktree?.baseRef ?? input.worktree?.baseBranch) === undefined\n ? {}\n : { baseRef: nonEmptyOptional(input.worktree?.baseRef ?? input.worktree?.baseBranch) }),\n ...(nonEmptyOptional(input.worktree?.baseBranch) === undefined\n ? {}\n : { baseBranch: nonEmptyOptional(input.worktree?.baseBranch) }),\n ...(nonEmptyOptional(input.worktree?.branch) === undefined\n ? {}\n : { branch: nonEmptyOptional(input.worktree?.branch) }),\n cleanup: input.worktree?.cleanup ?? \"auto\",\n forceCleanup: input.worktree?.forceCleanup ?? false,\n },\n };\n}\n\nfunction normalizeMaxTurns(value: number | undefined): number {\n if (value === undefined) {\n return 10;\n }\n\n if (!Number.isFinite(value)) {\n return 10;\n }\n\n return Math.max(1, Math.floor(value));\n}\n\nfunction nonEmptyOptional(value: string | undefined): string | undefined {\n const trimmed = value?.trim();\n return trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n","import { execFile } from \"node:child_process\";\nimport { mkdir } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\nimport { promisify } from \"node:util\";\n\nimport { done, notify, type StepFactory, state, step } from \"@trailstep/authoring\";\nimport { delegateTurnPrompt } from \"./prompts.js\";\nimport {\n type AskParentInput,\n type DelegateArtifact,\n type DelegateInput,\n type DelegateOutput,\n type DelegateTurnInput,\n type DelegateTurnOutput,\n type DelegateWorkflowDefaults,\n type DelegateWorktreeCleanupDetails,\n delegateTurnOutputShape,\n type NormalizedDelegateInput,\n normalizeDelegateInput,\n type ParentAnswerOutput,\n type PrepareDelegateTurnInput,\n parentAnswerShape,\n type QuestionAnswer,\n} from \"./schema.js\";\n\nconst MEMORY_LIMIT = 12_000;\nconst execFileAsync = promisify(execFile);\n\nconst DELEGATE_STATE_KEYS = {\n initialized: \"delegate.initialized\",\n input: \"delegate.input\",\n memory: \"delegate.memory\",\n turns: \"delegate.turns\",\n questions: \"delegate.questions\",\n answers: \"delegate.answers\",\n latestSummary: \"delegate.latestSummary\",\n artifacts: \"delegate.artifacts\",\n changedFiles: \"delegate.changedFiles\",\n result: \"delegate.result\",\n worktreePath: \"delegate.worktreePath\",\n worktreeBranch: \"delegate.worktreeBranch\",\n worktreeCleanup: \"delegate.worktreeCleanup\",\n} as const;\n\ninterface InitializeDelegateInput extends Record<string, unknown> {\n readonly input: DelegateInput;\n readonly defaults: DelegateWorkflowDefaults;\n}\n\nexport function initializeDelegateStep(\n input: DelegateInput,\n defaults: DelegateWorkflowDefaults = {},\n): ReturnType<typeof initializeDelegateStepFactory> {\n return initializeDelegateStepFactory({ input, defaults });\n}\n\nconst initializeDelegateStepFactory = step({\n id: \"initialize-delegate\",\n title: \"Initialize delegate\",\n})\n .display(({ input }) => `Delegating: ${(input as InitializeDelegateInput).input.task}`)\n .do(async ({ input, defaults }: InitializeDelegateInput) => {\n const initialized = (await state.get<boolean>(DELEGATE_STATE_KEYS.initialized)) ?? false;\n if (initialized) {\n return prepareDelegateTurnStep({ turn: 1 });\n }\n\n const normalized = normalizeDelegateInput(input, defaults);\n\n if (normalized.cwd !== undefined && normalized.worktree.enabled) {\n return await finalDone({\n status: \"blocked\",\n summary:\n \"Delegate input cannot specify both cwd and worktree.enabled. Choose an existing cwd or managed worktree creation, not both.\",\n questionsAsked: 0,\n turns: 0,\n });\n }\n\n const managedWorktree = normalized.worktree.enabled\n ? await createManagedWorktree(normalized)\n : undefined;\n const executionCwd = managedWorktree?.path ?? resolveDelegateCwd(normalized.cwd);\n const normalizedInput = {\n ...normalized,\n ...(normalized.cwd !== undefined || managedWorktree !== undefined\n ? { cwd: executionCwd }\n : {}),\n };\n\n await state.set(DELEGATE_STATE_KEYS.initialized, true);\n await state.set(DELEGATE_STATE_KEYS.input, normalizedInput);\n await state.set(DELEGATE_STATE_KEYS.memory, \"\");\n await state.set(DELEGATE_STATE_KEYS.turns, 0);\n await state.set(DELEGATE_STATE_KEYS.questions, 0);\n await state.set(DELEGATE_STATE_KEYS.answers, []);\n await state.set(DELEGATE_STATE_KEYS.latestSummary, null);\n await state.set(DELEGATE_STATE_KEYS.artifacts, []);\n await state.set(DELEGATE_STATE_KEYS.changedFiles, []);\n await state.set(DELEGATE_STATE_KEYS.result, null);\n await state.set(DELEGATE_STATE_KEYS.worktreePath, managedWorktree?.path ?? null);\n await state.set(DELEGATE_STATE_KEYS.worktreeBranch, managedWorktree?.branch ?? null);\n await state.set(DELEGATE_STATE_KEYS.worktreeCleanup, null);\n\n await notify.progress(\"Initialized delegate memory\", {\n mode: normalizedInput.mode,\n maxTurns: normalizedInput.maxTurns,\n cwd: executionCwd,\n ...(managedWorktree === undefined\n ? {}\n : { worktreePath: managedWorktree.path, worktreeBranch: managedWorktree.branch }),\n });\n\n return prepareDelegateTurnStep({ turn: 1 });\n });\n\nexport const prepareDelegateTurnStep: StepFactory<\n PrepareDelegateTurnInput,\n PrepareDelegateTurnInput\n> = step({\n id: \"prepare-delegate-turn\",\n title: \"Prepare delegate turn\",\n}).do(async (turnRequest: PrepareDelegateTurnInput) => {\n const input = await requiredState<NormalizedDelegateInput>(DELEGATE_STATE_KEYS.input);\n const turns = (await state.get<number>(DELEGATE_STATE_KEYS.turns)) ?? 0;\n const questionsAsked = (await state.get<number>(DELEGATE_STATE_KEYS.questions)) ?? 0;\n\n if (turnRequest.turn > input.maxTurns) {\n await notify.warning(\"Delegate exceeded maxTurns\", { maxTurns: input.maxTurns, turns });\n return await finalDone({\n status: \"blocked\",\n summary: \"Delegate exceeded maxTurns without completing.\",\n ...(await finalOptionalOutputFields()),\n questionsAsked,\n turns,\n });\n }\n\n const executionCwd = input.cwd ?? state.executionCwd ?? state.cwd ?? process.cwd();\n const turnInput: DelegateTurnInput = {\n task: input.task,\n ...(input.context === undefined ? {} : { context: input.context }),\n mode: input.mode,\n executionCwd,\n ...(input.worktree.enabled ? { worktreePath: executionCwd } : {}),\n memory: (await state.get<string>(DELEGATE_STATE_KEYS.memory)) ?? \"\",\n questionsAndAnswers: (await state.get<QuestionAnswer[]>(DELEGATE_STATE_KEYS.answers)) ?? [],\n latestSummary: (await state.get<string | null>(DELEGATE_STATE_KEYS.latestSummary)) ?? undefined,\n turn: turnRequest.turn,\n maxTurns: input.maxTurns,\n summarize: input.summarize,\n };\n\n return delegateTurnStep(turnInput);\n});\n\nexport const delegateTurnStep: StepFactory<DelegateTurnInput, DelegateTurnOutput> = step({\n id: \"delegate-turn\",\n title: \"Delegate turn\",\n cwd: ({ input }) => (input as DelegateTurnInput).executionCwd,\n})\n .display(({ input }) => `Delegating: ${(input as DelegateTurnInput).task}`)\n .prompt<DelegateTurnInput, DelegateTurnOutput>(delegateTurnPrompt, {\n agent: \"delegateAgent\",\n output: delegateTurnOutputShape,\n })\n .display(({ output }) => output.summary)\n .do(async (turnOutput, input) => {\n const storedTurns = (await state.get<number>(DELEGATE_STATE_KEYS.turns)) ?? 0;\n const alreadyProcessed = storedTurns >= input.turn;\n const turns = alreadyProcessed ? storedTurns : storedTurns + 1;\n\n if (!alreadyProcessed) {\n await state.set(DELEGATE_STATE_KEYS.turns, turns);\n await state.set(DELEGATE_STATE_KEYS.latestSummary, turnOutput.summary);\n await appendMemory(turns, turnOutput);\n await mergeChangedFiles(turnOutput.changedFiles ?? []);\n await mergeArtifacts(turnOutput.artifacts ?? []);\n await state.set(DELEGATE_STATE_KEYS.result, turnOutput.result ?? null);\n\n await notify.progress(\"Updated delegate memory\", { turn: turns });\n for (const artifact of turnOutput.artifacts ?? []) {\n await notify.artifact(artifact.name, {\n path: artifact.path,\n ...(artifact.mediaType === undefined ? {} : { mediaType: artifact.mediaType }),\n });\n }\n }\n\n if (turnOutput.status === \"completed\") {\n const questionsAsked = (await state.get<number>(DELEGATE_STATE_KEYS.questions)) ?? 0;\n return await finalDone({\n status: \"completed\",\n summary: turnOutput.summary,\n ...(await finalOptionalOutputFields(turnOutput)),\n questionsAsked,\n turns,\n });\n }\n\n if (turnOutput.status === \"blocked\") {\n const questionsAsked = (await state.get<number>(DELEGATE_STATE_KEYS.questions)) ?? 0;\n return await finalDone({\n status: \"blocked\",\n summary: turnOutput.summary,\n ...(await finalOptionalOutputFields(turnOutput)),\n questionsAsked,\n turns,\n });\n }\n\n if (turnOutput.status === \"question\") {\n const question = turnOutput.question?.trim();\n if (!question) {\n const questionsAsked = (await state.get<number>(DELEGATE_STATE_KEYS.questions)) ?? 0;\n return await finalDone({\n status: \"blocked\",\n summary: \"Delegate requested a parent answer but did not provide a question.\",\n ...(await finalOptionalOutputFields(turnOutput)),\n questionsAsked,\n turns,\n });\n }\n\n const storedQuestions = (await state.get<number>(DELEGATE_STATE_KEYS.questions)) ?? 0;\n const questionsAsked = alreadyProcessed ? storedQuestions : storedQuestions + 1;\n if (!alreadyProcessed) {\n await state.set(DELEGATE_STATE_KEYS.questions, questionsAsked);\n await notify.progress(\"Delegate asked parent question\", {\n turn: input.turn,\n questionsAsked,\n });\n }\n return askParentStep({ question, nextTurn: input.turn + 1 });\n }\n\n return prepareDelegateTurnStep({ turn: input.turn + 1 });\n });\n\nexport const askParentStep: StepFactory<AskParentInput, AskParentInput> = step({\n id: \"ask-parent\",\n title: \"Ask parent\",\n})\n .display(({ input }) => (input as AskParentInput).question)\n .wait(({ input }) => ({\n id: \"parent-answer\",\n kind: \"input\",\n message: (input as AskParentInput).question,\n output: parentAnswerShape,\n }))\n .do(async (context, input: AskParentInput) => {\n const waitContext = context as unknown as AskParentInput & {\n readonly waits?: Readonly<Record<string, ParentAnswerOutput>>;\n };\n const answerOutput = waitContext.waits?.[\"parent-answer\"];\n const answer = answerOutput?.answer ?? \"\";\n const answers = (await state.get<QuestionAnswer[]>(DELEGATE_STATE_KEYS.answers)) ?? [];\n const alreadyRecorded = answers.some(\n (item) => item.question === input.question && item.answer === answer,\n );\n\n if (answerOutput !== undefined && !alreadyRecorded) {\n await state.set(DELEGATE_STATE_KEYS.answers, [\n ...answers,\n { question: input.question, answer },\n ]);\n await appendMemoryNote(`Parent answered: ${answer}`);\n await notify.progress(\"Recorded parent answer\", { questionsAnswered: answers.length + 1 });\n }\n\n return prepareDelegateTurnStep({ turn: input.nextTurn });\n });\n\nasync function createManagedWorktree(\n input: NormalizedDelegateInput,\n): Promise<{ path: string; branch: string }> {\n const base = state.projectCwd ?? state.executionCwd ?? state.cwd ?? process.cwd();\n const safeRunName = sanitizeRefSegment(state.name);\n const worktreePath = resolve(base, input.worktree.path ?? `.trailstep/worktrees/${safeRunName}`);\n const branch = input.worktree.branch ?? `trailstep/delegate/${safeRunName}`;\n const baseRef = input.worktree.baseRef ?? input.worktree.baseBranch ?? \"HEAD\";\n\n await mkdir(dirname(worktreePath), { recursive: true });\n await git(base, [\"worktree\", \"add\", \"-b\", branch, worktreePath, baseRef]);\n await notify.progress(\"Created delegate worktree\", { path: worktreePath, branch, baseRef });\n return { path: worktreePath, branch };\n}\n\nasync function cleanupManagedWorktree(\n finalStatus: DelegateOutput[\"status\"],\n): Promise<DelegateWorktreeCleanupDetails | undefined> {\n const input = await state.get<NormalizedDelegateInput>(DELEGATE_STATE_KEYS.input);\n const worktreePath = await state.get<string | null>(DELEGATE_STATE_KEYS.worktreePath);\n const worktreeBranch = await state.get<string | null>(DELEGATE_STATE_KEYS.worktreeBranch);\n if (input?.worktree.enabled !== true || worktreePath === undefined || worktreePath === null) {\n return undefined;\n }\n\n const requested = input.worktree.cleanup;\n const keep = async (status: DelegateWorktreeCleanupDetails[\"status\"], reason: string) => {\n const details = { requested, status, reason } satisfies DelegateWorktreeCleanupDetails;\n await state.set(DELEGATE_STATE_KEYS.worktreeCleanup, details);\n await notify.progress(\"Kept delegate worktree\", { path: worktreePath, reason });\n return details;\n };\n\n if (requested === \"never\") {\n return keep(\"kept\", \"cleanup=never\");\n }\n if (requested === \"auto\" && finalStatus !== \"completed\") {\n return keep(\"kept\", \"auto cleanup keeps worktree because delegate did not complete\");\n }\n\n let clean = false;\n try {\n clean = (await git(worktreePath, [\"status\", \"--porcelain\"])).trim().length === 0;\n } catch (error) {\n return keep(\"failed\", `could not prove worktree cleanliness: ${errorMessage(error)}`);\n }\n\n if (!clean && !input.worktree.forceCleanup) {\n return keep(\"kept-dirty\", \"worktree has changes and forceCleanup is false\");\n }\n\n const repoCwd = state.projectCwd ?? state.executionCwd ?? state.cwd ?? process.cwd();\n try {\n const args = [\n \"worktree\",\n \"remove\",\n ...(input.worktree.forceCleanup ? [\"--force\"] : []),\n worktreePath,\n ];\n await git(repoCwd, args);\n } catch (error) {\n return keep(\"failed\", `git worktree remove failed: ${errorMessage(error)}`);\n }\n\n const branchCleanupReason = await cleanupManagedWorktreeBranch({\n repoCwd,\n branch: worktreeBranch,\n createdByRun: input.worktree.branch === undefined,\n });\n const details = {\n requested,\n status: branchCleanupReason?.startsWith(\"managed branch cleanup failed\") ? \"failed\" : \"removed\",\n ...(branchCleanupReason === undefined ? {} : { reason: branchCleanupReason }),\n } satisfies DelegateWorktreeCleanupDetails;\n await state.set(DELEGATE_STATE_KEYS.worktreeCleanup, details);\n await notify.progress(\"Removed delegate worktree\", {\n path: worktreePath,\n reason: branchCleanupReason,\n });\n return details;\n}\n\nasync function cleanupManagedWorktreeBranch({\n repoCwd,\n branch,\n createdByRun,\n}: {\n readonly repoCwd: string;\n readonly branch: string | null | undefined;\n readonly createdByRun: boolean;\n}): Promise<string | undefined> {\n if (branch === undefined || branch === null) {\n return undefined;\n }\n if (!createdByRun) {\n return \"user-supplied branch retained\";\n }\n\n let currentBranch: string;\n try {\n currentBranch = (await git(repoCwd, [\"branch\", \"--show-current\"])).trim();\n } catch (error) {\n return `managed branch cleanup failed after worktree removal: could not determine current branch: ${errorMessage(error)}`;\n }\n if (currentBranch === branch) {\n return \"managed branch retained because it is currently checked out\";\n }\n\n try {\n await git(repoCwd, [\"branch\", \"-d\", branch]);\n return undefined;\n } catch (error) {\n return `managed branch cleanup failed after worktree removal: ${errorMessage(error)}`;\n }\n}\n\nasync function git(cwd: string, args: readonly string[]): Promise<string> {\n const { stdout } = await execFileAsync(\"git\", args, { cwd });\n return stdout;\n}\n\nfunction resolveDelegateCwd(cwd: string | undefined): string {\n const base = state.projectCwd ?? state.executionCwd ?? state.cwd ?? process.cwd();\n return cwd === undefined ? base : resolve(base, cwd);\n}\n\nfunction sanitizeRefSegment(value: string): string {\n return value.replace(/[^A-Za-z0-9._-]+/g, \"-\").replace(/^-+|-+$/g, \"\") || \"run\";\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nasync function appendMemory(turn: number, output: DelegateTurnOutput): Promise<void> {\n const lines = [`Turn ${turn}: ${output.summary}`];\n if (output.memoryPatch?.trim()) {\n lines.push(`Memory patch: ${output.memoryPatch.trim()}`);\n }\n await appendMemoryNote(lines.join(\"\\n\"));\n}\n\nasync function appendMemoryNote(note: string): Promise<void> {\n const existing = (await state.get<string>(DELEGATE_STATE_KEYS.memory)) ?? \"\";\n const updated = [existing.trim(), note.trim()].filter(Boolean).join(\"\\n\\n\");\n await state.set(DELEGATE_STATE_KEYS.memory, trimRollingMemory(updated));\n}\n\nfunction trimRollingMemory(memory: string): string {\n if (memory.length <= MEMORY_LIMIT) {\n return memory;\n }\n\n return `[older delegate memory trimmed]\\n${memory.slice(-MEMORY_LIMIT)}`;\n}\n\nasync function mergeChangedFiles(changedFiles: readonly string[]): Promise<void> {\n if (changedFiles.length === 0) {\n return;\n }\n\n const existing = (await state.get<string[]>(DELEGATE_STATE_KEYS.changedFiles)) ?? [];\n await state.set(DELEGATE_STATE_KEYS.changedFiles, uniqueStrings([...existing, ...changedFiles]));\n}\n\nasync function mergeArtifacts(artifacts: readonly DelegateArtifact[]): Promise<void> {\n if (artifacts.length === 0) {\n return;\n }\n\n const existing = (await state.get<DelegateArtifact[]>(DELEGATE_STATE_KEYS.artifacts)) ?? [];\n const byPath = new Map(existing.map((artifact) => [artifact.path, artifact]));\n for (const artifact of artifacts) {\n byPath.set(artifact.path, artifact);\n }\n await state.set(DELEGATE_STATE_KEYS.artifacts, [...byPath.values()]);\n}\n\nasync function finalOptionalOutputFields(\n latest?: DelegateTurnOutput,\n): Promise<Partial<DelegateOutput>> {\n const result = latest?.result ?? (await state.get<string | null>(DELEGATE_STATE_KEYS.result));\n const changedFiles = (await state.get<string[]>(DELEGATE_STATE_KEYS.changedFiles)) ?? [];\n const artifacts = (await state.get<DelegateArtifact[]>(DELEGATE_STATE_KEYS.artifacts)) ?? [];\n const worktreePath = await state.get<string | null>(DELEGATE_STATE_KEYS.worktreePath);\n const worktreeBranch = await state.get<string | null>(DELEGATE_STATE_KEYS.worktreeBranch);\n const worktreeCleanup = await state.get<DelegateWorktreeCleanupDetails | null>(\n DELEGATE_STATE_KEYS.worktreeCleanup,\n );\n\n return {\n ...(result === undefined || result === null ? {} : { result }),\n ...(changedFiles.length === 0 ? {} : { changedFiles }),\n ...(artifacts.length === 0 ? {} : { artifacts }),\n ...(worktreePath === undefined || worktreePath === null ? {} : { worktreePath }),\n ...(worktreeBranch === undefined || worktreeBranch === null ? {} : { worktreeBranch }),\n ...(worktreeCleanup === undefined || worktreeCleanup === null ? {} : { worktreeCleanup }),\n };\n}\n\nasync function finalDone(output: DelegateOutput) {\n const cleanup = await cleanupManagedWorktree(output.status);\n const finalOutput = cleanup === undefined ? output : { ...output, worktreeCleanup: cleanup };\n return done(finalOutput, { message: delegateTerminalMessage(finalOutput) });\n}\n\nfunction delegateTerminalMessage(output: DelegateOutput): string {\n const lines = [\n `Delegate ${output.status}: ${output.summary}`,\n `Turns: ${output.turns}; questions asked: ${output.questionsAsked}`,\n ];\n if (output.changedFiles && output.changedFiles.length > 0) {\n lines.push(`Changed files: ${output.changedFiles.join(\", \")}`);\n }\n if (output.worktreePath) {\n lines.push(`Worktree: ${output.worktreePath}`);\n }\n if (output.worktreeBranch) {\n lines.push(`Worktree branch: ${output.worktreeBranch}`);\n }\n if (output.worktreeCleanup) {\n lines.push(\n `Worktree cleanup: ${output.worktreeCleanup.status} (${output.worktreeCleanup.requested})${\n output.worktreeCleanup.reason ? ` - ${output.worktreeCleanup.reason}` : \"\"\n }`,\n );\n }\n if (output.result?.trim()) {\n lines.push(output.result.trim());\n }\n return lines.join(\"\\n\");\n}\n\nasync function requiredState<T>(key: string): Promise<T> {\n const value = await state.get<T>(key);\n if (value === undefined || value === null) {\n throw new Error(`Delegate state is missing required key: ${key}`);\n }\n return value;\n}\n\nfunction uniqueStrings(values: readonly string[]): string[] {\n return [...new Set(values.filter((value) => value.trim().length > 0))];\n}\n","import { list, promptSections, section } from \"@trailstep/authoring\";\nimport type { DelegateMode, DelegateTurnInput } from \"./schema.js\";\n\nexport function delegateTurnPrompt({ input }: { readonly input: DelegateTurnInput }): string {\n return promptSections(\n section(\n \"Role\",\n \"You are a continued delegate agent working inside one TrailStep run. Preserve continuity from the run-local memory below, but do not assume or use memory from any separate run.\",\n ),\n section(\"Original task\", input.task),\n section(\"Original context\", input.context),\n section(\"Mode\", `${input.mode}: ${modeGuidance(input.mode)}`),\n section(\n \"Execution location\",\n [\n `CWD/worktree path: ${input.worktreePath ?? input.executionCwd}`,\n \"Honor this directory for any project inspection or file edits.\",\n ].join(\"\\n\"),\n ),\n section(\"Accumulated run-local memory summary\", input.memory || \"No prior delegate memory.\"),\n section(\"Previous questions and parent/human answers\", formatQuestionsAndAnswers(input)),\n section(\"Latest summary\", input.latestSummary ?? \"No prior summary.\"),\n section(\n \"Current turn\",\n [\n `Turn: ${input.turn} of ${input.maxTurns}`,\n `Summarize mode: ${String(input.summarize)}`,\n ].join(\"\\n\"),\n ),\n section(\n \"Instructions\",\n list([\n \"Do one focused turn of delegated work; keep the work bounded and observable.\",\n \"Use the run-local memory summary and previous Q/A as continuity, not an unlimited transcript.\",\n \"If you can finish the task now, return status `completed` with a concise summary and final result.\",\n \"If more delegated work is needed and no parent answer is required, return status `continue` and a memory patch for the next turn.\",\n \"If blocked on a parent/human decision, return status `question`, include exactly one clear question, and summarize why it is needed.\",\n \"If the task cannot proceed safely, return status `blocked` with the reason in the summary/result.\",\n \"When you learn durable facts for this run, include a compact `memoryPatch`; do not copy large transcripts, files, or diffs.\",\n \"Report changed files and artifacts only when you actually changed or produced them.\",\n ]),\n ),\n section(\"Exact output contract\", outputContract),\n );\n}\n\nfunction modeGuidance(mode: DelegateMode): string {\n switch (mode) {\n case \"explore\":\n return \"investigate, summarize findings, and avoid code changes unless explicitly needed.\";\n case \"implement\":\n return \"make the smallest safe implementation progress and report changed files.\";\n case \"review\":\n return \"review existing work, identify issues, and avoid unnecessary edits.\";\n case \"general\":\n return \"use judgment to complete the delegated task with focused, bounded work.\";\n }\n}\n\nfunction formatQuestionsAndAnswers(input: DelegateTurnInput): string {\n if (input.questionsAndAnswers.length === 0) {\n return \"No parent/human questions have been asked in this run.\";\n }\n\n return input.questionsAndAnswers\n .map((item, index) =>\n [`${index + 1}. Question: ${item.question}`, ` Answer: ${item.answer}`].join(\"\\n\"),\n )\n .join(\"\\n\");\n}\n\nconst outputContract = `Return the structured JSON object requested by the wrapper.\n\nStatus meanings:\n- completed: the delegated task is finished; include result when useful.\n- continue: more bounded work is needed in another turn; include memoryPatch for durable continuity.\n- question: parent/human input is required; include exactly one clear question.\n- blocked: the task cannot proceed safely; summarize why and include result details when useful.\n\nOnly report changedFiles/artifacts that you actually changed or produced.`;\n","import { defineWorkflow, done, parallel, state, step } from \"@trailstep/authoring\";\nimport type { DelegateMode, DelegateWorktreeInput } from \"../delegate/schema.js\";\nimport {\n delegate,\n delegateArchitectPlanner,\n delegateExplore,\n delegateImplement,\n delegateQuickImplementor,\n delegateRelentlessDebugger,\n delegateReview,\n delegateSchemaFormatter,\n delegateSimpleExplore,\n delegateSmartImplementor,\n} from \"../delegate/workflow.js\";\nimport {\n type DelegateParallelDelegate,\n type DelegateParallelInput,\n type DelegateParallelOutput,\n delegateParallelInputShape,\n delegateParallelOutputShape,\n type NormalizedDelegateParallelTask,\n} from \"./schema.js\";\n\nexport type {\n DelegateParallelBranchOutput,\n DelegateParallelInput,\n DelegateParallelOutput,\n DelegateParallelTaskInput,\n NormalizedDelegateParallelTask,\n} from \"./schema.js\";\n\nexport const delegateParallel = defineWorkflow<DelegateParallelInput, DelegateParallelOutput>({\n id: \"delegateParallel\",\n description:\n \"Use when you have 2+ independent codebase tasks that can run in parallel. Fans out required delegate tasks across parallel delegate workflows.\",\n skill: delegateParallelSkill(),\n inputShape: delegateParallelInputShape,\n outputShape: delegateParallelOutputShape,\n start(input) {\n return initializeDelegateParallelStep(input);\n },\n});\n\nconst initializeDelegateParallelStep = step({\n id: \"initialize-delegate-parallel\",\n title: \"Initialize parallel delegates\",\n})\n .display(({ input }) => `Preparing ${(input as DelegateParallelInput).tasks.length} delegates`)\n .do((input: DelegateParallelInput) => {\n const normalized = normalizeDelegateParallelTasks(input, state.name);\n if (normalized.status === \"blocked\") {\n return done({ status: \"blocked\", summary: normalized.summary });\n }\n\n return parallel<DelegateParallelOutput>(\n normalized.tasks.map((task) =>\n delegateWorkflowForTask(task)(task.input, { branchId: task.branchId }),\n ),\n );\n });\n\nexport function normalizeDelegateParallelTasks(\n input: DelegateParallelInput,\n runName: string,\n):\n | { readonly status: \"ready\"; readonly tasks: readonly NormalizedDelegateParallelTask[] }\n | { readonly status: \"blocked\"; readonly summary: string } {\n if (input.tasks.length === 0) {\n return { status: \"blocked\", summary: \"delegateParallel requires at least one task.\" };\n }\n\n const seenIds = new Set<string>();\n const seenBranches = new Set<string>();\n const tasks: NormalizedDelegateParallelTask[] = [];\n\n for (const task of input.tasks) {\n const id = task.id.trim();\n const taskText = task.task.trim();\n if (id.length === 0) {\n return { status: \"blocked\", summary: \"delegateParallel task ids must be non-empty.\" };\n }\n if (taskText.length === 0) {\n return {\n status: \"blocked\",\n summary: `delegateParallel task ${id} must include non-empty task text.`,\n };\n }\n if (seenIds.has(id)) {\n return { status: \"blocked\", summary: `delegateParallel task id '${id}' is duplicated.` };\n }\n seenIds.add(id);\n\n const branchId = `delegate-${stableSegment(id)}`;\n if (seenBranches.has(branchId)) {\n return {\n status: \"blocked\",\n summary: `delegateParallel task id '${id}' normalizes to duplicate branch id '${branchId}'.`,\n };\n }\n seenBranches.add(branchId);\n\n const delegateSelection = normalizeDelegateSelection(task.delegate);\n const mode = task.mode ?? defaultModeForDelegate(delegateSelection);\n const cwd = nonEmpty(task.cwd) ?? nonEmpty(input.cwd);\n const worktree = normalizeTaskWorktree({\n parent: input.worktree,\n task: task.worktree,\n cwd,\n runName,\n taskSegment: stableSegment(id),\n });\n const context = combineContext(input.context, task.context);\n const maxTurns = task.maxTurns ?? input.maxTurns;\n const summarize = task.summarize ?? input.summarize;\n\n tasks.push({\n id,\n mode,\n ...(delegateSelection === undefined ? {} : { delegate: delegateSelection }),\n branchId,\n input: {\n task: taskText,\n mode,\n ...(context === undefined ? {} : { context }),\n ...(cwd === undefined ? {} : { cwd }),\n ...(maxTurns === undefined ? {} : { maxTurns }),\n ...(summarize === undefined ? {} : { summarize }),\n ...(worktree === undefined ? {} : { worktree }),\n },\n });\n }\n\n return { status: \"ready\", tasks };\n}\n\nfunction delegateWorkflowForTask(task: NormalizedDelegateParallelTask): typeof delegate {\n switch (task.delegate) {\n case \"simple-explore\":\n return delegateSimpleExplore;\n case \"architect-planner\":\n return delegateArchitectPlanner;\n case \"quick-implementor\":\n return delegateQuickImplementor;\n case \"smart-implementor\":\n return delegateSmartImplementor;\n case \"relentless-debugger\":\n case \"fixer\":\n return delegateRelentlessDebugger;\n case \"schema-formatter\":\n return delegateSchemaFormatter;\n case \"delegate\":\n case undefined:\n return delegateWorkflowForMode(task.mode);\n }\n}\n\nfunction delegateWorkflowForMode(mode: DelegateMode): typeof delegate {\n switch (mode) {\n case \"explore\":\n return delegateExplore;\n case \"implement\":\n return delegateImplement;\n case \"review\":\n return delegateReview;\n case \"general\":\n return delegate;\n }\n}\n\nfunction normalizeDelegateSelection(\n value: DelegateParallelDelegate | undefined,\n): DelegateParallelDelegate | undefined {\n return value === undefined ? undefined : value;\n}\n\nfunction defaultModeForDelegate(\n delegateSelection: DelegateParallelDelegate | undefined,\n): DelegateMode {\n switch (delegateSelection) {\n case \"simple-explore\":\n case \"architect-planner\":\n return \"explore\";\n case \"quick-implementor\":\n case \"smart-implementor\":\n case \"relentless-debugger\":\n case \"fixer\":\n return \"implement\";\n case \"schema-formatter\":\n case \"delegate\":\n case undefined:\n return \"general\";\n }\n}\n\nfunction normalizeTaskWorktree(input: {\n readonly parent?: DelegateWorktreeInput;\n readonly task?: DelegateWorktreeInput;\n readonly cwd?: string;\n readonly runName: string;\n readonly taskSegment: string;\n}): DelegateWorktreeInput | undefined {\n if (input.cwd !== undefined) {\n return input.task?.enabled === true ? input.task : undefined;\n }\n\n const enabled = input.task?.enabled ?? input.parent?.enabled;\n if (enabled !== true) {\n return input.task ?? input.parent;\n }\n\n const merged = { ...input.parent, ...input.task, enabled: true };\n return {\n ...merged,\n path: nonEmpty(merged.path) ?? `.trailstep/worktrees/${input.runName}/${input.taskSegment}`,\n branch: nonEmpty(merged.branch) ?? `trailstep/delegate/${input.runName}/${input.taskSegment}`,\n };\n}\n\nfunction combineContext(parent: string | undefined, task: string | undefined): string | undefined {\n const parentContext = nonEmpty(parent);\n const taskContext = nonEmpty(task);\n if (parentContext === undefined) {\n return taskContext;\n }\n if (taskContext === undefined) {\n return parentContext;\n }\n return `${parentContext}\\n\\n${taskContext}`;\n}\n\nfunction nonEmpty(value: string | undefined): string | undefined {\n const trimmed = value?.trim();\n return trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction stableSegment(value: string): string {\n const segment = value\n .trim()\n .replace(/[^A-Za-z0-9._-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n return segment.length > 0 ? segment : `task-${hashString(value)}`;\n}\n\nfunction hashString(value: string): string {\n let hash = 0x811c9dc5;\n for (let index = 0; index < value.length; index += 1) {\n hash ^= value.charCodeAt(index);\n hash = Math.imul(hash, 0x01000193);\n }\n return (hash >>> 0).toString(16);\n}\n\nfunction delegateParallelSkill(): string {\n return `---\nname: trst-delegate-parallel\ndescription: Use when you have 2+ independent codebase tasks that can run in parallel, such as exploring multiple areas, implementing multiple files, or splitting explore plus implement plus review. Prefer this over running single explore, implement, or review delegates sequentially.\nx-trailstep-user-facing: false\n---\n# TrailStep delegateParallel workflow\n\nUse this workflow when a parent agent already has a set of concrete, independent delegate tasks and wants to run them in parallel instead of sequentially. Reach for this when you need to investigate multiple areas, change multiple files, or split explore plus implement plus review work across delegates. It fans out directly to the existing delegate, delegateExplore, delegateReview, and delegateImplement workflows based on each task mode. It does not add a planning agent and does not merge results beyond returning the parallel branch outputs.\n\nEach task must provide a stable \\`id\\`, \\`mode\\`, and \\`task\\` text. Shared \\`context\\`, \\`cwd\\`, \\`maxTurns\\`, \\`summarize\\`, and \\`worktree\\` values are applied as defaults; task-level values override them. Managed worktrees under \\`worktree.enabled=true\\` default per task to \\`.trailstep/worktrees/<runName>/<taskId>\\` and \\`trailstep/delegate/<runName>/<taskId>\\` to avoid collisions.`;\n}\n","import { jsonSchema } from \"@trailstep/authoring\";\nimport type {\n DelegateInput,\n DelegateMode,\n DelegateOutput,\n DelegateWorktreeInput,\n} from \"../delegate/schema.js\";\n\nexport type DelegateParallelDelegate =\n | \"delegate\"\n | \"simple-explore\"\n | \"architect-planner\"\n | \"quick-implementor\"\n | \"smart-implementor\"\n | \"relentless-debugger\"\n | \"fixer\"\n | \"schema-formatter\";\n\nexport interface DelegateParallelTaskInput extends Record<string, unknown> {\n readonly id: string;\n readonly mode?: DelegateMode;\n readonly delegate?: DelegateParallelDelegate;\n readonly task: string;\n readonly context?: string;\n readonly cwd?: string;\n readonly maxTurns?: number;\n readonly summarize?: boolean;\n readonly worktree?: DelegateWorktreeInput;\n}\n\nexport interface DelegateParallelInput extends Record<string, unknown> {\n readonly context?: string;\n readonly cwd?: string;\n readonly maxTurns?: number;\n readonly summarize?: boolean;\n readonly worktree?: DelegateWorktreeInput;\n readonly tasks: readonly DelegateParallelTaskInput[];\n}\n\nexport interface DelegateParallelBranchOutput extends Record<string, unknown> {\n readonly status: \"done\" | \"failed\" | \"cancelled\";\n readonly output?: DelegateOutput;\n}\n\nexport interface DelegateParallelOutput extends Record<string, unknown> {\n readonly status: \"completed\" | \"blocked\";\n readonly summary?: string;\n readonly branches?: Record<string, DelegateParallelBranchOutput>;\n}\n\nexport interface NormalizedDelegateParallelTask extends Record<string, unknown> {\n readonly id: string;\n readonly mode: DelegateMode;\n readonly delegate?: DelegateParallelDelegate;\n readonly branchId: string;\n readonly input: DelegateInput;\n}\n\nexport const delegateParallelInputShape = jsonSchema<DelegateParallelInput>({\n type: \"object\",\n properties: {\n context: { type: \"string\" },\n cwd: { type: \"string\" },\n maxTurns: { type: \"number\" },\n summarize: { type: \"boolean\" },\n worktree: {\n type: \"object\",\n properties: {\n enabled: { type: \"boolean\" },\n path: { type: \"string\" },\n baseRef: { type: \"string\" },\n baseBranch: { type: \"string\" },\n branch: { type: \"string\" },\n cleanup: { type: \"string\", enum: [\"auto\", \"never\", \"always\"] },\n forceCleanup: { type: \"boolean\" },\n },\n additionalProperties: false,\n },\n tasks: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n id: { type: \"string\" },\n mode: { type: \"string\", enum: [\"explore\", \"implement\", \"review\", \"general\"] },\n delegate: {\n type: \"string\",\n enum: [\n \"delegate\",\n \"simple-explore\",\n \"architect-planner\",\n \"quick-implementor\",\n \"smart-implementor\",\n \"relentless-debugger\",\n \"fixer\",\n \"schema-formatter\",\n ],\n },\n task: { type: \"string\" },\n context: { type: \"string\" },\n cwd: { type: \"string\" },\n maxTurns: { type: \"number\" },\n summarize: { type: \"boolean\" },\n worktree: {\n type: \"object\",\n properties: {\n enabled: { type: \"boolean\" },\n path: { type: \"string\" },\n baseRef: { type: \"string\" },\n baseBranch: { type: \"string\" },\n branch: { type: \"string\" },\n cleanup: { type: \"string\", enum: [\"auto\", \"never\", \"always\"] },\n forceCleanup: { type: \"boolean\" },\n },\n additionalProperties: false,\n },\n },\n anyOf: [{ required: [\"mode\"] }, { required: [\"delegate\"] }],\n required: [\"id\", \"task\"],\n additionalProperties: false,\n },\n },\n },\n required: [\"tasks\"],\n additionalProperties: false,\n});\n\nexport const delegateParallelOutputShape = jsonSchema<DelegateParallelOutput>({\n type: \"object\",\n properties: {\n status: { type: \"string\", enum: [\"completed\", \"blocked\"] },\n summary: { type: \"string\" },\n branches: { type: \"object\", additionalProperties: true },\n },\n required: [\"status\"],\n additionalProperties: false,\n});\n"],"mappings":";AAAA,SAAS,sBAAsB;;;ACA/B,SAAS,kBAAkB;AA2HpB,IAAM,wBAAwB;AAAA,EACnC,MAAM;AAAA,EACN,YAAY;AAAA,IACV,MAAM,EAAE,MAAM,SAAS;AAAA,IACvB,MAAM,EAAE,MAAM,SAAS;AAAA,IACvB,WAAW,EAAE,MAAM,SAAS;AAAA,EAC9B;AAAA,EACA,UAAU,CAAC,QAAQ,MAAM;AAAA,EACzB,sBAAsB;AACxB;AAEO,IAAM,qBAAqB,WAA0B;AAAA,EAC1D,MAAM;AAAA,EACN,YAAY;AAAA,IACV,MAAM,EAAE,MAAM,SAAS;AAAA,IACvB,SAAS,EAAE,MAAM,SAAS;AAAA,IAC1B,MAAM,EAAE,MAAM,UAAU,MAAM,CAAC,WAAW,aAAa,UAAU,SAAS,EAAE;AAAA,IAC5E,KAAK,EAAE,MAAM,SAAS;AAAA,IACtB,UAAU,EAAE,MAAM,SAAS;AAAA,IAC3B,WAAW,EAAE,MAAM,UAAU;AAAA,IAC7B,UAAU;AAAA,MACR,MAAM;AAAA,MACN,YAAY;AAAA,QACV,SAAS,EAAE,MAAM,UAAU;AAAA,QAC3B,MAAM,EAAE,MAAM,SAAS;AAAA,QACvB,SAAS,EAAE,MAAM,SAAS;AAAA,QAC1B,YAAY,EAAE,MAAM,SAAS;AAAA,QAC7B,QAAQ,EAAE,MAAM,SAAS;AAAA,QACzB,SAAS,EAAE,MAAM,UAAU,MAAM,CAAC,QAAQ,SAAS,QAAQ,EAAE;AAAA,QAC7D,cAAc,EAAE,MAAM,UAAU;AAAA,MAClC;AAAA,MACA,sBAAsB;AAAA,IACxB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AI,OAAO;AACX,WAAS,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS,GAAG;AACpD,YAAQ,MAAM,WAAW,KAAK;AAC9B,WAAO,KAAK,KAAK,MAAM,QAAU;AAAA,EACnC;AACA,UAAQ,SAAS,GAAG,SAAS,EAAE;AACjC;AAEA,SAAS,wBAAgC;AACvC,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAUT;","names":["questionsAsked","details","defineWorkflow","done","state","step","jsonSchema","defineWorkflow","step","state","done"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trailstep/sub-agents",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "Reusable TrailStep sub-agent workflows for delegated focused work.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -208,11 +208,11 @@
|
|
|
208
208
|
}
|
|
209
209
|
},
|
|
210
210
|
"dependencies": {
|
|
211
|
-
"@trailstep/authoring": "0.2.
|
|
211
|
+
"@trailstep/authoring": "0.2.1"
|
|
212
212
|
},
|
|
213
213
|
"devDependencies": {
|
|
214
214
|
"@biomejs/biome": "^2.5.8",
|
|
215
|
-
"@trailstep/core": "0.
|
|
215
|
+
"@trailstep/core": "0.3.0",
|
|
216
216
|
"@types/node": "^26.2.0",
|
|
217
217
|
"tsup": "^8.5.0",
|
|
218
218
|
"typescript": "^5.8.3",
|
|
@@ -227,7 +227,7 @@
|
|
|
227
227
|
"LICENSE"
|
|
228
228
|
],
|
|
229
229
|
"peerDependencies": {
|
|
230
|
-
"@trailstep/authoring": "^0.2.
|
|
230
|
+
"@trailstep/authoring": "^0.2.1"
|
|
231
231
|
},
|
|
232
232
|
"scripts": {
|
|
233
233
|
"build": "tsup src/index.ts --format esm --dts --sourcemap --clean",
|