@wrongstack/core 0.267.0 → 0.269.0

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.
Files changed (78) hide show
  1. package/dist/{agent-bridge-STJ3JwwK.d.ts → agent-bridge-PcHQl_UQ.d.ts} +1 -1
  2. package/dist/{agent-subagent-runner-CzPGP3jA.d.ts → agent-subagent-runner-SHJW7t8q.d.ts} +8 -8
  3. package/dist/{brain-Cdg77tVN.d.ts → brain-BYcK__Ym.d.ts} +1 -1
  4. package/dist/{compactor-iMZ84CXq.d.ts → compactor-C2RKEBtC.d.ts} +1 -1
  5. package/dist/{config-Du3pYYln.d.ts → config-C_ae2k86.d.ts} +79 -2
  6. package/dist/{context-dT5Ueund.d.ts → context-Dp87Bcaq.d.ts} +47 -1
  7. package/dist/coordination/index.d.ts +62 -160
  8. package/dist/coordination/index.js +566 -149
  9. package/dist/coordination/index.js.map +1 -1
  10. package/dist/defaults/index.d.ts +26 -25
  11. package/dist/defaults/index.js +366 -137
  12. package/dist/defaults/index.js.map +1 -1
  13. package/dist/execution/index.d.ts +72 -16
  14. package/dist/execution/index.js +267 -55
  15. package/dist/execution/index.js.map +1 -1
  16. package/dist/execution/prompt-enhancer.d.ts +1 -1
  17. package/dist/extension/index.d.ts +7 -6
  18. package/dist/global-mailbox-Bvrz1P3f.d.ts +664 -0
  19. package/dist/{goal-preamble-SulMTowG.d.ts → goal-preamble-CA_4yiGQ.d.ts} +9 -9
  20. package/dist/{goal-store-CABDwdFE.d.ts → goal-store-DhuJoUNG.d.ts} +1 -1
  21. package/dist/hq/index.d.ts +204 -0
  22. package/dist/hq/index.js +1931 -0
  23. package/dist/hq/index.js.map +1 -0
  24. package/dist/{index-DtCVWel4.d.ts → index-CZQ6Pwbs.d.ts} +8 -8
  25. package/dist/{index-Bms0m4oy.d.ts → index-W4VJCzHa.d.ts} +5 -5
  26. package/dist/{index-IEuxQd-E.d.ts → index-whDfTANu.d.ts} +2 -2
  27. package/dist/index.d.ts +46 -42
  28. package/dist/index.js +3472 -1651
  29. package/dist/index.js.map +1 -1
  30. package/dist/infrastructure/index.d.ts +6 -6
  31. package/dist/infrastructure/index.js +48 -21
  32. package/dist/infrastructure/index.js.map +1 -1
  33. package/dist/kernel/index.d.ts +10 -9
  34. package/dist/{pipeline-BfD2k1rT.d.ts → mailbox-types-Ct2hJq0P.d.ts} +1 -244
  35. package/dist/{mcp-servers-C2cBTxUR.d.ts → mcp-servers-DJdZiRcv.d.ts} +10 -4
  36. package/dist/models/index.d.ts +5 -5
  37. package/dist/models/index.js +4 -3
  38. package/dist/models/index.js.map +1 -1
  39. package/dist/{models-registry-BqGZNJQ-.d.ts → models-registry-C3a-2-Yd.d.ts} +1 -1
  40. package/dist/{multi-agent-coordinator-B8R43uPz.d.ts → multi-agent-coordinator-CJSpTe5O.d.ts} +1 -1
  41. package/dist/{null-fleet-bus-CnXa5oTH.d.ts → null-fleet-bus-QVshIsDx.d.ts} +6 -6
  42. package/dist/observability/index.d.ts +2 -2
  43. package/dist/{parallel-eternal-engine-DdNnw9BQ.d.ts → parallel-eternal-engine-D9y5Pkcc.d.ts} +9 -15
  44. package/dist/{path-resolver-COIMLCQL.d.ts → path-resolver-CnQ8SIfh.d.ts} +4 -3
  45. package/dist/{permission-B75JAi3-.d.ts → permission-CvYQNUqZ.d.ts} +1 -1
  46. package/dist/{permission-policy-DlR9eJAM.d.ts → permission-policy-D5Ss8j4B.d.ts} +2 -3
  47. package/dist/pipeline-l_zzFRh3.d.ts +245 -0
  48. package/dist/{plan-templates-DSIKCXZN.d.ts → plan-templates-NtPgyeJA.d.ts} +6 -5
  49. package/dist/{provider-model-resolve-BNRsNuJx.d.ts → provider-model-resolve-d5poT5y0.d.ts} +3 -3
  50. package/dist/{provider-runner-CX7iIvox.d.ts → provider-runner-gkctlQV_.d.ts} +3 -3
  51. package/dist/{retry-policy-BilV1ujH.d.ts → retry-policy-CtFhfwa8.d.ts} +1 -1
  52. package/dist/sdd/index.d.ts +9 -8
  53. package/dist/sdd/index.js +33 -3
  54. package/dist/sdd/index.js.map +1 -1
  55. package/dist/{secret-vault-gkvEZZfE.d.ts → secret-vault-BLsVmTIK.d.ts} +1 -1
  56. package/dist/security/index.d.ts +5 -5
  57. package/dist/security/index.js +39 -29
  58. package/dist/security/index.js.map +1 -1
  59. package/dist/{selector-Bc7eWtT3.d.ts → selector-CXl2_y9W.d.ts} +1 -1
  60. package/dist/{session-event-bridge-D-araDEz.d.ts → session-event-bridge-Ccud20CC.d.ts} +1 -1
  61. package/dist/{session-reader-D7Dapswh.d.ts → session-reader-ZeXQmsmE.d.ts} +1 -1
  62. package/dist/skills/index.js.map +1 -1
  63. package/dist/storage/index.d.ts +16 -12
  64. package/dist/storage/index.js +273 -100
  65. package/dist/storage/index.js.map +1 -1
  66. package/dist/tools/index.d.ts +2 -2
  67. package/dist/tools/index.js +166 -31
  68. package/dist/tools/index.js.map +1 -1
  69. package/dist/types/index.d.ts +22 -21
  70. package/dist/types/index.js +178 -70
  71. package/dist/types/index.js.map +1 -1
  72. package/dist/utils/index.d.ts +22 -3
  73. package/dist/utils/index.js +197 -25
  74. package/dist/utils/index.js.map +1 -1
  75. package/package.json +5 -1
  76. package/skills/chimera/SKILL.md +1 -1
  77. package/skills/typescript-strict/SKILL.md +3 -3
  78. package/skills/typescript-strict/SKILL.save.md +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/tool-wire-compact.ts","../../src/utils/token-estimate.ts","../../src/utils/expect-defined.ts","../../src/utils/message-invariants.ts","../../src/utils/context-evidence.ts","../../src/types/blocks.ts","../../src/execution/compaction-core.ts","../../src/execution/compactor.ts","../../src/execution/intelligent-compactor.ts","../../src/models/llm-selector.ts","../../src/execution/selective-compactor.ts","../../src/execution/strategy-compactor.ts","../../src/utils/assert-never.ts","../../src/utils/atomic-write.ts","../../src/utils/error.ts","../../src/utils/json-schema-validate.ts","../../src/utils/regex-guard.ts","../../src/utils/sleep.ts","../../src/utils/string.ts","../../src/utils/tool-output-serializer.ts","../../src/utils/wstack-paths.ts","../../src/types/errors.ts","../../src/execution/auto-compaction-middleware.ts","../../src/security/capabilities.ts","../../src/execution/tool-executor.ts","../../src/execution/autonomous-runner.ts","../../src/storage/goal-store.ts","../../src/execution/autonomy-brain.ts","../../src/execution/eternal-autonomy.ts","../../src/coordination/subagent-budget.ts","../../src/coordination/agent-subagent-runner.ts","../../src/coordination/agents/types.ts","../../src/coordination/agents/phase1-discovery.ts","../../src/coordination/agents/phase2-planning.ts","../../src/coordination/agents/phase3-build.ts","../../src/coordination/agents/phase4-verify.ts","../../src/coordination/agents/phase5-review.ts","../../src/coordination/agents/phase6-domain.ts","../../src/coordination/agents/phase7-knowledge.ts","../../src/coordination/agents/phase8-delivery.ts","../../src/coordination/agents/phase9-meta.ts","../../src/coordination/agents/index.ts","../../src/coordination/dispatcher.ts","../../src/types/provider.ts","../../src/coordination/coordinator/error-classifier.ts","../../src/coordination/fleet.ts","../../src/coordination/subagent-nicknames.ts","../../src/coordination/multi-agent-coordinator.ts","../../src/execution/parallel-eternal-engine.ts","../../src/execution/autonomy-prompt-contributor.ts","../../src/execution/goal-preamble.ts","../../src/execution/regex-patterns.ts","../../src/execution/retry-policy.ts","../../src/execution/error-handler.ts","../../src/execution/skill-loader.ts"],"names":["tokens","hasToolUse","repair","afterTokens","afterFull","path2","stat","resolve","path","isRecord","projectHash","path4","fs2","fsp","extractText","unlink","first","baseMessage","randomUUID","PreemptState","GOAL_COMPLETE_MARKER","execFile","promisify","execFileP","fs3","path5"],"mappings":";;;;;;;;;AAqBA,IAAM,0BAAA,GAA6B,GAAA;AACnC,IAAM,4BAAA,GAA+B,GAAA;AAErC,IAAM,YAAA,uBAAmB,OAAA,EAA2C;AAU7D,SAAS,4BAAA,CACd,IAAA,EACA,IAAA,GAA4C,EAAC,EAClB;AAC3B,EAAA,MAAM,iBAAA,GACJ,IAAA,CAAK,mBAAA,KAAwB,MAAA,IAAa,KAAK,yBAAA,KAA8B,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AAK,OAAA,CAAQ,MAAA,EAAQ,EAAE,CAAC,CAAA;AAAA,IACrC;AAAA,EACF;AACA,EAAA,KAAA,EAAM;AACN,EAAA,OAAO,GAAA;AACT;AAWA,SAAS,yBAAyB,IAAA,EAAoD;AAEpF,EAAA,MAAM,gBAAA,GAAmB,IAAA,CAAK,OAAA,CAAQ,IAAI,CAAA;AAC1C,EAAA,MAAM,UACJ,gBAAA,KAAqB,EAAA,GACjB,KAAK,KAAA,CAAM,CAAA,EAAG,mBAAmB,CAAC,CAAA,CAAE,IAAA,EAAK,GACxC,KAAK,IAAA,EAAK,CAAE,MAAM,IAAI,CAAA,CAAE,CAAC,CAAA,IAAK,EAAA;AAGrC,EAAA,MAAM,QAAkB,EAAC;AACzB,EAAA,MAAM,WAAA,GAAc,qCAAA,CAAsC,IAAA,CAAK,IAAI,CAAA;AACnE,EAAA,IAAI,WAAA,EAAa;AAIf,IAAA,MAAM,KAAA,GAAA,CAAS,YAAY,CAAC,CAAA,IAAK,IAC9B,OAAA,CAAQ,OAAA,EAAS,GAAG,CAAA,CACpB,KAAA,CAAM,GAAG,CAAA,CACT,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,MAAM,CAAA,CACnB,OAAO,OAAO,CAAA;AACjB,IAAA,KAAA,CAAM,IAAA,CAAK,GAAG,KAAK,CAAA;AAAA,EACrB;AAEA,EAAA,OAAO,EAAE,SAAS,KAAA,EAAM;AAC1B","file":"index.js","sourcesContent":["import type { JSONSchema } from '../types/tool.js';\n\nexport interface ToolWireDefinitionLike {\n name: string;\n description?: string | undefined;\n inputSchema: unknown;\n}\n\nexport interface CompactToolDefinitionForWireOptions {\n /** Top-level tool description budget. */\n descriptionMaxChars?: number | undefined;\n /** Per-JSON-Schema `description` annotation budget. */\n schemaDescriptionMaxChars?: number | undefined;\n}\n\nexport interface CompactWireToolDefinition {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n}\n\nconst TOOL_DESCRIPTION_MAX_CHARS = 640;\nconst SCHEMA_DESCRIPTION_MAX_CHARS = 180;\n\nconst compactCache = new WeakMap<object, CompactWireToolDefinition>();\n\n/**\n * Return the provider-wire version of a tool definition.\n *\n * Tool schemas remain structurally intact: validation keywords, property\n * names, required fields, enum values, and nested shapes are preserved. The\n * only reduction is on human prose annotations (`description`), which are the\n * largest repeated cost in provider tool declarations.\n */\nexport function compactToolDefinitionForWire(\n tool: ToolWireDefinitionLike,\n opts: CompactToolDefinitionForWireOptions = {},\n): CompactWireToolDefinition {\n const useDefaultOptions =\n opts.descriptionMaxChars === undefined && opts.schemaDescriptionMaxChars === undefined;\n if (useDefaultOptions && typeof tool === 'object' && tool !== null) {\n const cached = compactCache.get(tool);\n if (cached) return cached;\n }\n\n const compact: CompactWireToolDefinition = {\n name: tool.name,\n description: compactDescription(\n tool.description ?? '',\n opts.descriptionMaxChars ?? TOOL_DESCRIPTION_MAX_CHARS,\n ),\n inputSchema: compactSchemaDescriptions(\n tool.inputSchema,\n opts.schemaDescriptionMaxChars ?? SCHEMA_DESCRIPTION_MAX_CHARS,\n ),\n };\n\n if (useDefaultOptions && typeof tool === 'object' && tool !== null) {\n compactCache.set(tool, compact);\n }\n return compact;\n}\n\nexport function compactSchemaDescriptions(\n schema: unknown,\n maxDescriptionChars = SCHEMA_DESCRIPTION_MAX_CHARS,\n): Record<string, unknown> {\n const compact = compactSchemaNode(schema, maxDescriptionChars);\n return isRecord(compact) ? compact : { type: 'object', properties: {} };\n}\n\nfunction compactSchemaNode(node: unknown, maxDescriptionChars: number): unknown {\n if (Array.isArray(node)) {\n return node.map((item) => compactSchemaNode(item, maxDescriptionChars));\n }\n if (!isRecord(node)) return node;\n\n const out: JSONSchema = {};\n for (const [key, value] of Object.entries(node)) {\n if (key === 'description' && typeof value === 'string') {\n out[key] = compactDescription(value, maxDescriptionChars);\n } else {\n out[key] = compactSchemaNode(value, maxDescriptionChars);\n }\n }\n return out;\n}\n\nfunction compactDescription(text: string, maxChars: number): string {\n const normalized = text.replace(/\\s+/g, ' ').trim();\n if (normalized.length <= maxChars) return normalized;\n if (maxChars <= 20) return normalized.slice(0, maxChars);\n\n const hardLimit = maxChars - 12;\n const boundary = findSemanticBoundary(normalized, hardLimit);\n const head = normalized.slice(0, boundary > 0 ? boundary : hardLimit).trimEnd();\n return `${head} ...`;\n}\n\nfunction findSemanticBoundary(text: string, limit: number): number {\n const punctuation = Math.max(\n text.lastIndexOf('. ', limit),\n text.lastIndexOf('; ', limit),\n text.lastIndexOf(': ', limit),\n );\n if (punctuation >= Math.floor(limit * 0.45)) return punctuation + 1;\n\n const comma = text.lastIndexOf(', ', limit);\n if (comma >= Math.floor(limit * 0.6)) return comma + 1;\n\n const space = text.lastIndexOf(' ', limit);\n return space >= Math.floor(limit * 0.6) ? space : limit;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value);\n}\n","import type { Message } from '../types/messages.js';\nimport { compactToolDefinitionForWire } from './tool-wire-compact.js';\n\n/**\n * Shared token estimation with JSON.stringify caching.\n * Avoids repeated stringification of tool input objects.\n *\n * ## Calibration\n *\n * `estimateRequestTokens` uses a fixed 3.5 chars/token heuristic — a\n * conservative overestimate that prevents underestimation but reduces\n * accuracy. After each API call, call `recordActualUsage()` with the\n * real `usage.input` from the provider response. The module maintains a\n * rolling average of `actual / estimated` ratio (EWM, α=0.3) and\n * applies it to subsequent calls via `estimateRequestTokensCalibrated`.\n *\n * Calibration is per-module (shared across all callers), which is\n * sufficient: the chars/token ratio is a property of the tokenizer,\n * not the model. Uncalibrated calls (before any samples, or when\n * `recordActualUsage` is not called) fall back to the uncalibrated\n * estimate so nothing breaks.\n */\n\nconst RoughTokenEstimate = (text: string, charsPerToken = 3.5): number =>\n Math.max(1, Math.ceil(text.length / charsPerToken));\n\n/** Calibration state: actual/estimated ratio via exponential weighted moving average. */\ninterface CalState {\n ratio: number; // current calibration multiplier (actual / estimated)\n count: number; // number of samples recorded\n prevEst: number; // estimated tokens from the most recent estimateRequestTokens call\n}\n\n/** EWM α — higher = faster adaptation, more volatile. */\nconst CAL_ALPHA = 0.3;\n\n/**\n * Calibration is keyed so that, in a multi-agent / model-switching process,\n * each (provider, model) tokenizer gets its own ratio instead of all of them\n * collapsing onto one shared number. Callers that don't pass a key use the\n * shared `__global__` bucket — that preserves the original single-session\n * behavior and keeps all existing call sites working unchanged.\n */\nconst CALIBRATION_GLOBAL_KEY = '__global__';\nconst _cals = new Map<string, CalState>();\n\nfunction calState(key: string): CalState {\n let state = _cals.get(key);\n if (!state) {\n state = { ratio: 1.0, count: 0, prevEst: 0 };\n _cals.set(key, state);\n }\n return state;\n}\n\nconst MIN_SAMPLES_FOR_CALIBRATION = 3;\n\n/**\n * Cache of computed estimates keyed by the stringified input — not the\n * input object itself. Previously the cache was keyed by the input object\n * via WeakMap, but JSON.stringify() produces a new object reference each\n * call so the cache never hit. Now we use a Map with string keys so that\n * repeated stringifications of the same structure share a single entry.\n */\nconst ESTIMATE_CACHE = new Map<string, number>();\n\nconst ESTIMATE_CACHE_MAX_SIZE = 10_000;\n\nfunction getCachedEstimate(key: string, compute: (key: string) => number): number {\n const existing = ESTIMATE_CACHE.get(key);\n if (existing !== undefined) return existing;\n if (ESTIMATE_CACHE.size >= ESTIMATE_CACHE_MAX_SIZE) {\n // Evict oldest half when at capacity — O(1) instead of O(n) iteration.\n // 5 000 surviving entries still give a high cache hit rate for the\n // common case of repeated context-window checks on the same messages.\n for (const k of ESTIMATE_CACHE.keys()) {\n if (ESTIMATE_CACHE.size <= Math.floor(ESTIMATE_CACHE_MAX_SIZE / 2)) break;\n ESTIMATE_CACHE.delete(k);\n }\n }\n const estimate = compute(key);\n ESTIMATE_CACHE.set(key, estimate);\n return estimate;\n}\n\n/**\n * Estimate tokens for a tool_use block input.\n * Caches the stringified result keyed by the stable string representation\n * to avoid repeated JSON.stringify calls during context window checks.\n */\nexport function estimateToolInputTokens(input: unknown): number {\n if (typeof input === 'string') return RoughTokenEstimate(input);\n if (input === null || typeof input !== 'object') {\n return RoughTokenEstimate(String(input));\n }\n // JSON.stringify is called once to form the cache key; RoughTokenEstimate\n // is deferred only on cache miss (compute callback), not wrapped unnecessarily.\n return getCachedEstimate(JSON.stringify(input), (key) => RoughTokenEstimate(key));\n}\n\n/**\n * Estimate tokens for a tool_result content.\n */\nexport function estimateToolResultTokens(content: string | unknown): number {\n if (typeof content === 'string') return RoughTokenEstimate(content);\n return getCachedEstimate(JSON.stringify(content), (key) => RoughTokenEstimate(key));\n}\n\n/**\n * Estimate tokens for a text block.\n */\nexport function estimateTextTokens(text: string): number {\n return RoughTokenEstimate(text);\n}\n\n/**\n * Compute and cache the token estimate for a single message. This is the\n * canonical per-message estimator — called once by ConversationState on\n * append/replace so the O(n·m) content-block walk happens at mutation time,\n * not on every context-pressure check.\n */\nexport function computeMessageTokens(msg: Message): number {\n if (typeof msg.content === 'string') return estimateTextTokens(msg.content);\n let total = 0;\n for (const b of msg.content) {\n if (b.type === 'text') total += estimateTextTokens(b.text);\n else if (b.type === 'tool_use') total += estimateToolInputTokens(b.input);\n else if (b.type === 'tool_result') total += estimateToolResultTokens(b.content);\n else total += RoughTokenEstimate(JSON.stringify(b));\n }\n return total;\n}\n\n/**\n * Estimate tokens for an array of messages (text + tool I/O), using the shared\n * 3.5 chars/token basis. This is the single canonical message-array estimator —\n * compactors, the context_manager tool, and the `/context` display all route\n * through it so the number a user sees matches the number compaction decides on.\n *\n * When a message carries a pre-computed `_estTokens` field (set by\n * ConversationState on append/replace), it is used directly instead of\n * re-walking the content blocks — turning the O(n·m) scan into an O(n)\n * sum for fully-cached arrays.\n */\nexport function estimateMessageTokens(messages: readonly Message[]): number {\n let total = 0;\n for (const m of messages) {\n if (typeof m._estTokens === 'number' && m._estTokens > 0) {\n total += m._estTokens;\n continue;\n }\n total += computeMessageTokens(m);\n }\n return total;\n}\n\n/**\n * Rough estimate of tokens in a tool definition (name + description + schema).\n * Accounts for the JSON-serialized inputSchema which is sent to the API\n * but NOT included in roughEstimate(content).\n */\nexport function estimateToolDefTokens(tool: {\n name: string;\n description?: string | undefined;\n inputSchema: unknown;\n}): number {\n // Fast path: pre-computed by ToolRegistry at registration time.\n const cached = (tool as { _estDefTokens?: number | undefined })._estDefTokens;\n if (typeof cached === 'number' && cached > 0) return cached;\n\n const compact = compactToolDefinitionForWire(tool);\n return (\n RoughTokenEstimate(tool.name) +\n RoughTokenEstimate(compact.description) +\n RoughTokenEstimate(JSON.stringify(compact.inputSchema))\n );\n}\n\n/**\n * Estimate the total API request token count: system prompt + tool definitions\n * + conversation messages. Use this for context-window bar calculations\n * instead of roughEstimate (which only counts messages).\n *\n * The overhead ratio (overhead / messages) varies by conversation length:\n * - Short conversations (< 10 messages): ~30-50% overhead (large system+tools)\n * - Medium (10-50 messages): ~15-30%\n * - Long (> 50 messages): ~5-15%\n *\n * Returns { messages, systemPrompt, tools, total } for debugging display.\n */\nexport interface RequestTokenBreakdown {\n messages: number;\n systemPrompt: number;\n tools: number;\n total: number;\n}\n\nexport function estimateRequestTokens(\n messages: unknown,\n systemPrompt: unknown,\n tools: { name: string; description?: string | undefined; inputSchema: unknown }[],\n calibrationKey: string = CALIBRATION_GLOBAL_KEY,\n): RequestTokenBreakdown {\n // Messages: apply the same logic as roughEstimate\n let messagesTokens = 0;\n if (typeof messages === 'string') {\n messagesTokens = RoughTokenEstimate(messages);\n } else if (Array.isArray(messages)) {\n for (const m of messages) {\n if (typeof m === 'object' && m !== null && 'content' in m) {\n // Fast path: pre-computed per-message token estimate (set by\n // ConversationState on append/replace). Skips the O(m) content-block\n // walk entirely for cached messages.\n const cached = (m as { _estTokens?: number | undefined })._estTokens;\n if (typeof cached === 'number' && cached > 0) {\n messagesTokens += cached;\n continue;\n }\n const content = (m as { content: unknown }).content;\n if (typeof content === 'string') {\n messagesTokens += RoughTokenEstimate(content);\n } else if (Array.isArray(content)) {\n for (const b of content) {\n if (typeof b === 'object' && b !== null) {\n if ((b as { type?: string | undefined }).type === 'text') {\n messagesTokens += RoughTokenEstimate((b as { text: string }).text);\n } else {\n messagesTokens += RoughTokenEstimate(JSON.stringify(b));\n }\n }\n }\n }\n }\n }\n }\n\n // System prompt\n let systemTokens = 0;\n if (typeof systemPrompt === 'string') {\n systemTokens = RoughTokenEstimate(systemPrompt);\n } else if (Array.isArray(systemPrompt)) {\n for (const b of systemPrompt) {\n if (\n typeof b === 'object' &&\n b !== null &&\n (b as { type?: string | undefined }).type === 'text'\n ) {\n systemTokens += RoughTokenEstimate((b as { text: string }).text);\n }\n }\n }\n\n // Tool definitions\n let toolsTokens = 0;\n for (const t of tools) {\n toolsTokens += estimateToolDefTokens(t);\n }\n\n const total = messagesTokens + systemTokens + toolsTokens;\n\n // Record the raw estimate for calibration: the next recordActualUsage()\n // call will pair this against the actual API usage so the rolling ratio\n // stays in sync with the real chars/token ratio of the content.\n calState(calibrationKey).prevEst = total;\n\n return {\n messages: messagesTokens,\n systemPrompt: systemTokens,\n tools: toolsTokens,\n total,\n };\n}\n\n/**\n * Record the actual API input token count after a provider call so\n * `estimateRequestTokensCalibrated` can self-correct on subsequent calls.\n *\n * Prefer passing `estimatedInputTokens` explicitly (the calibrated pre-flight\n * estimate from the middleware) — this avoids race conditions when other code\n * also calls `estimateRequestTokens` between the pre-flight and this call\n * (e.g. audit logging in agent.ts).\n *\n * When `estimatedInputTokens` is omitted, falls back to the keyed bucket's\n * `prevEst` for backward compatibility with callers that don't have the\n * pre-flight value. `calibrationKey` selects the per-(provider,model) bucket\n * (defaults to the shared global bucket).\n */\nexport function recordActualUsage(\n actualInputTokens: number,\n estimatedInputTokens?: number,\n calibrationKey: string = CALIBRATION_GLOBAL_KEY,\n): void {\n if (actualInputTokens <= 0) return;\n const cal = calState(calibrationKey);\n const est = estimatedInputTokens ?? cal.prevEst;\n if (est <= 0) return;\n\n const sampleRatio = actualInputTokens / est;\n if (cal.count === 0) {\n cal.ratio = sampleRatio;\n } else {\n // EWM: new = α * sample + (1-α) * old → α=0.3 = fast initial converge\n cal.ratio = CAL_ALPHA * sampleRatio + (1 - CAL_ALPHA) * cal.ratio;\n }\n // Sanity bound: keep the rolling ratio within [0.5, 1.5] so a sequence\n // of bad samples can't blow up the calibration for everyone.\n cal.ratio = Math.min(1.5, Math.max(0.5, cal.ratio));\n cal.count++;\n}\n\n/**\n * Returns the current calibration state for a bucket. Exposed for debugging\n * and tests — not needed by normal callers.\n */\nexport function getCalibrationState(calibrationKey: string = CALIBRATION_GLOBAL_KEY): {\n ratio: number;\n count: number;\n calibrated: boolean;\n} {\n const cal = calState(calibrationKey);\n return {\n ratio: cal.ratio,\n count: cal.count,\n calibrated: cal.count >= MIN_SAMPLES_FOR_CALIBRATION,\n };\n}\n\n/**\n * Like `estimateRequestTokens` but applies the rolling calibration factor\n * so context pressure readings converge on reality within a few iterations.\n *\n * Before any `recordActualUsage` samples are collected, returns the same\n * result as `estimateRequestTokens` (ratio = 1.0, no distortion).\n * After `MIN_SAMPLES_FOR_CALIBRATION` samples, applies the calibrated\n * multiplier capped to the range [0.5, 1.5] as a sanity bound.\n */\nexport function estimateRequestTokensCalibrated(\n messages: unknown,\n systemPrompt: unknown,\n tools: { name: string; description?: string | undefined; inputSchema: unknown }[],\n calibrationKey: string = CALIBRATION_GLOBAL_KEY,\n): RequestTokenBreakdown {\n const result = estimateRequestTokens(messages, systemPrompt, tools, calibrationKey);\n const cal = calState(calibrationKey);\n\n if (cal.count >= MIN_SAMPLES_FOR_CALIBRATION) {\n const safeRatio = Math.min(1.5, Math.max(0.5, cal.ratio));\n return {\n messages: Math.round(result.messages * safeRatio),\n systemPrompt: Math.round(result.systemPrompt * safeRatio),\n tools: Math.round(result.tools * safeRatio),\n total: Math.round(result.total * safeRatio),\n };\n }\n\n return result;\n}\n\n/**\n * Resets calibration state. Primarily for tests that run in the same\n * process and need a clean slate between suites. With no argument it clears\n * every bucket (including the global one); pass a key to reset just that bucket.\n */\nexport function resetCalibration(calibrationKey?: string): void {\n if (calibrationKey === undefined) {\n _cals.clear();\n return;\n }\n _cals.delete(calibrationKey);\n}\n","/** Assert a value is neither null nor undefined. Throws if it is.\n * Useful after optional chaining and indexed access when the\n * control flow guarantees the value exists but TypeScript can't\n * prove it (e.g. after a check on a related field). */\nexport function expectDefined<T>(value: T | null | undefined, label?: string): T {\n if (value === null || value === undefined) {\n const err = new Error(label ? `Expected ${label} to be defined` : 'Expected value to be defined');\n err.name = 'ExpectDefinedError';\n throw err;\n }\n return value;\n}\n","import { expectDefined } from './expect-defined.js';\nimport type { ContentBlock, ToolResultBlock, ToolUseBlock } from '../types/blocks.js';\nimport type { Message } from '../types/messages.js';\nexport interface MessageRepairReport {\n changed: boolean;\n removedToolUses: string[];\n removedToolResults: string[];\n removedMessages: number;\n}\n\nexport interface MessageRepairResult {\n messages: Message[];\n report: MessageRepairReport;\n}\n\n/**\n * Repair provider-level tool-call adjacency invariants.\n *\n * Anthropic requires every assistant `tool_use` block to have a matching\n * `tool_result` block in the immediately following user message. Manual\n * context surgery (summary/prune) can cut through the middle of such an\n * exchange. This function removes only the now-orphaned protocol blocks,\n * preserving surrounding text/images/thinking blocks where possible.\n */\nexport function repairToolUseAdjacency(messages: Message[]): MessageRepairResult {\n const removedToolUses: string[] = [];\n const removedToolResults: string[] = [];\n let removedMessages = 0;\n let changed = false;\n const out: Message[] = [];\n\n for (let i = 0; i < messages.length; i++) {\n const original = expectDefined(messages[i]);\n let msg = original;\n\n if (hasToolUse(msg)) {\n const nextIds = toolResultIds(messages[i + 1]);\n const filtered = mapContent(msg, (blocks) => {\n const next: ContentBlock[] = [];\n for (const block of blocks) {\n if (block.type === 'tool_use' && !nextIds.has(block.id)) {\n removedToolUses.push(block.id);\n changed = true;\n continue;\n }\n next.push(block);\n }\n return next;\n });\n msg = filtered ?? msg;\n }\n\n if (hasToolResult(msg)) {\n const allowed = toolUseIds(out[out.length - 1]);\n const filtered = mapContent(msg, (blocks) => {\n const next: ContentBlock[] = [];\n for (const block of blocks) {\n if (block.type === 'tool_result' && !allowed.has(block.tool_use_id)) {\n removedToolResults.push(block.tool_use_id);\n changed = true;\n continue;\n }\n next.push(block);\n }\n return next;\n });\n msg = filtered ?? msg;\n }\n\n if (isEmptyMessage(msg)) {\n removedMessages++;\n changed = true;\n continue;\n }\n out.push(msg);\n }\n\n return {\n messages: changed ? out : messages,\n report: { changed, removedToolUses, removedToolResults, removedMessages },\n };\n}\n\nfunction hasToolUse(msg: Message | undefined): boolean {\n return contentBlocks(msg).some((b): b is ToolUseBlock => b.type === 'tool_use');\n}\n\nfunction hasToolResult(msg: Message | undefined): boolean {\n return contentBlocks(msg).some((b): b is ToolResultBlock => b.type === 'tool_result');\n}\n\nfunction toolUseIds(msg: Message | undefined): Set<string> {\n const ids = new Set<string>();\n if (!msg || msg.role !== 'assistant') return ids;\n for (const block of contentBlocks(msg)) {\n if (block.type === 'tool_use') ids.add(block.id);\n }\n return ids;\n}\n\nfunction toolResultIds(msg: Message | undefined): Set<string> {\n const ids = new Set<string>();\n if (!msg || msg.role !== 'user') return ids;\n for (const block of contentBlocks(msg)) {\n if (block.type === 'tool_result') ids.add(block.tool_use_id);\n }\n return ids;\n}\n\nfunction contentBlocks(msg: Message | undefined): ContentBlock[] {\n return msg && Array.isArray(msg.content) ? msg.content : [];\n}\n\nfunction mapContent(\n msg: Message,\n fn: (blocks: ContentBlock[]) => ContentBlock[],\n): Message | null {\n if (!Array.isArray(msg.content)) return msg;\n const next = fn(msg.content);\n if (next.length === msg.content.length && next.every((b, idx) => b === msg.content[idx])) {\n return msg;\n }\n return { ...msg, content: next };\n}\n\nfunction isEmptyMessage(msg: Message): boolean {\n if (typeof msg.content === 'string') return msg.content.trim().length === 0;\n return msg.content.length === 0;\n}\n","import * as path from 'node:path';\nimport type { Context } from '../core/context.js';\nimport type {\n ContextEvidenceState,\n ToolOutputMetadata,\n} from '../types/context-evidence.js';\n\nconst MAX_TOOL_CALLS = 80;\nconst MAX_FACTS = 40;\nconst MAX_ERRORS = 20;\nconst MAX_DIGEST_CHARS = 4_000;\n\nconst WRITE_TOOLS = new Set(['edit', 'write', 'replace', 'patch']);\nconst READ_TOOLS = new Set(['read', 'grep', 'glob', 'ls', 'tree']);\n\nexport function createContextEvidenceState(): ContextEvidenceState {\n return {\n sessionGoals: [],\n implicitFacts: [],\n activeErrors: [],\n toolCalls: [],\n fileGraph: {},\n repeatedReads: [],\n updatedAt: Date.now(),\n };\n}\n\nexport interface RecordToolOutputEvidenceInput {\n toolUseId: string;\n toolName: string;\n input: unknown;\n content: string;\n ok: boolean;\n outputBytes?: number | undefined;\n outputTokens?: number | undefined;\n outputLines?: number | undefined;\n}\n\nexport function recordUserIntentEvidence(ctx: Context, text: string): void {\n const intent = normalizeWhitespace(text).slice(0, 700);\n if (!intent) return;\n const state = ensureEvidence(ctx);\n state.currentIntent = { text: intent, updatedAt: Date.now() };\n if (state.sessionGoals.length === 0 || isGoalish(intent)) {\n pushUniqueBounded(state.sessionGoals, intent, 8);\n }\n state.updatedAt = Date.now();\n}\n\nexport function recordToolOutputEvidence(\n ctx: Context,\n input: RecordToolOutputEvidenceInput,\n): ToolOutputMetadata {\n const state = ensureEvidence(ctx);\n const files = extractFiles(ctx, input.toolName, input.input, input.content);\n const symbols = extractSymbols(input.content, input.input);\n const commands = extractCommands(input.toolName, input.input);\n const errors = extractErrors(input.content);\n const summary = summarizeToolOutput(input.toolName, input.input, input.content, {\n files,\n symbols,\n errors,\n ok: input.ok,\n });\n\n const metadata: ToolOutputMetadata = {\n toolUseId: input.toolUseId,\n toolName: input.toolName,\n ok: input.ok,\n inputSummary: summarizeInput(input.input),\n summary,\n files,\n symbols,\n commands,\n errors,\n status: 'seen',\n referenceCount: 0,\n seenAt: Date.now(),\n outputBytes: input.outputBytes,\n outputTokens: input.outputTokens,\n outputLines: input.outputLines,\n };\n\n state.toolCalls.push(metadata);\n if (state.toolCalls.length > MAX_TOOL_CALLS) {\n state.toolCalls.splice(0, state.toolCalls.length - MAX_TOOL_CALLS);\n }\n\n updateFileGraph(state, metadata);\n updateRepeatedReadSignals(state, metadata);\n if (errors.length > 0) {\n for (const err of errors) pushUniqueBounded(state.activeErrors, err, MAX_ERRORS);\n }\n const fact = implicitFactFor(metadata);\n if (fact) pushUniqueBounded(state.implicitFacts, fact, MAX_FACTS);\n state.updatedAt = Date.now();\n return metadata;\n}\n\nexport function markAssistantReferencedEvidence(ctx: Context, text: string): void {\n const state = ensureEvidence(ctx);\n const haystack = text.toLowerCase();\n if (!haystack.trim()) return;\n\n for (const tool of state.toolCalls) {\n if (!metadataReferencedByText(tool, haystack)) continue;\n tool.status = 'referenced';\n tool.referenceCount++;\n tool.referencedAt = Date.now();\n for (const file of tool.files) {\n const node = state.fileGraph[file];\n if (node) node.referenced = true;\n }\n }\n state.updatedAt = Date.now();\n}\n\nexport function buildContextEvidenceDigest(ctx: Context): string {\n const state = ensureEvidence(ctx);\n const lines: string[] = [];\n\n if (state.currentIntent?.text) {\n lines.push(`intent: ${state.currentIntent.text}`);\n }\n\n const goals = state.sessionGoals.slice(-3);\n if (goals.length > 0) {\n lines.push('session_goals:');\n for (const goal of goals) lines.push(`- ${goal}`);\n }\n\n const activeErrors = state.activeErrors.slice(-5);\n if (activeErrors.length > 0) {\n lines.push('active_errors:');\n for (const err of activeErrors) lines.push(`- ${err}`);\n }\n\n const files = Object.values(state.fileGraph)\n .sort((a, b) => (b.writes - a.writes) || (b.reads - a.reads) || a.path.localeCompare(b.path))\n .slice(0, 12);\n if (files.length > 0) {\n lines.push('dependency_graph:');\n for (const file of files) {\n const actions = [\n file.reads > 0 ? `read ${file.reads}x` : '',\n file.writes > 0 ? `write ${file.writes}x` : '',\n ].filter(Boolean).join(', ');\n const refs = file.referenced ? '; referenced by assistant' : '';\n const via = file.lastToolUseId ? `; last via ${file.lastToolUseId}` : '';\n lines.push(`- ${file.path} (${actions || 'seen'}${refs}${via})`);\n }\n }\n\n const referenced = state.toolCalls\n .filter((tool) => tool.status === 'referenced')\n .slice(-10);\n const recentSeen = state.toolCalls\n .filter((tool) => tool.status === 'seen')\n .slice(-5);\n const trail = [...referenced, ...recentSeen];\n if (trail.length > 0) {\n lines.push('tool_trail:');\n for (const tool of trail) {\n const size = tool.outputTokens ? `; ~${tool.outputTokens} tokens` : '';\n const filesText = tool.files.length > 0 ? `; files=${tool.files.slice(0, 4).join(', ')}` : '';\n const symbolsText = tool.symbols.length > 0 ? `; symbols=${tool.symbols.slice(0, 4).join(', ')}` : '';\n lines.push(\n `- ${tool.toolUseId} ${tool.toolName} ${tool.status}: ${tool.summary}${filesText}${symbolsText}${size}`,\n );\n }\n }\n\n const facts = state.implicitFacts.slice(-8);\n if (facts.length > 0) {\n lines.push('implicit_facts:');\n for (const fact of facts) lines.push(`- ${fact}`);\n }\n\n const digest = lines.join('\\n');\n if (digest.length <= MAX_DIGEST_CHARS) return digest;\n return `${digest.slice(0, MAX_DIGEST_CHARS)}... [+${digest.length - MAX_DIGEST_CHARS} chars]`;\n}\n\nexport function repeatedReadPressure(ctx: Context): number {\n return ensureEvidence(ctx).repeatedReads.reduce((max, item) => Math.max(max, item.count), 0);\n}\n\nfunction ensureEvidence(ctx: Context): ContextEvidenceState {\n if (!ctx.contextEvidence) {\n (ctx as unknown as { contextEvidence: ContextEvidenceState }).contextEvidence =\n createContextEvidenceState();\n }\n return ctx.contextEvidence;\n}\n\nfunction isGoalish(text: string): boolean {\n return /\\b(goal|objective|task|need|want|implement|fix|improve|refactor|add|remove|hedef|amac|istiyorum|gerekiyor|iyilestir|duzelt|ekle|kaldir)\\b/i.test(text);\n}\n\nfunction normalizeWhitespace(text: string): string {\n return text.replace(/\\s+/g, ' ').trim();\n}\n\nfunction pushUniqueBounded(list: string[], value: string, max: number): void {\n const normalized = normalizeWhitespace(value);\n if (!normalized) return;\n const existing = list.findIndex((item) => item.toLowerCase() === normalized.toLowerCase());\n if (existing >= 0) list.splice(existing, 1);\n list.push(normalized);\n if (list.length > max) list.splice(0, list.length - max);\n}\n\nfunction extractFiles(\n ctx: Context,\n toolName: string,\n input: unknown,\n content: string,\n): string[] {\n const out = new Set<string>();\n for (const value of inputPathValues(input)) addPath(ctx, out, value);\n\n if (toolName === 'grep' || toolName === 'glob' || toolName === 'bash') {\n const re = /(?:(?:[A-Za-z]:)?[./\\\\]?[\\w@.-]+(?:[\\\\/][\\w@(). -]+)+\\.[A-Za-z0-9]{1,12})/g;\n for (const match of content.matchAll(re)) addPath(ctx, out, match[0]);\n }\n\n return [...out].slice(0, 30);\n}\n\nfunction inputPathValues(input: unknown): string[] {\n const values: string[] = [];\n const visit = (value: unknown, key?: string): void => {\n if (typeof value === 'string') {\n if (key && /^(path|file|files|fromFile|toFile|dir|cwd)$/i.test(key)) values.push(value);\n return;\n }\n if (Array.isArray(value)) {\n for (const item of value) visit(item, key);\n return;\n }\n if (!value || typeof value !== 'object') return;\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) visit(v, k);\n };\n visit(input);\n return values;\n}\n\nfunction addPath(ctx: Context, out: Set<string>, raw: string): void {\n const clean = raw.trim().replace(/^[\"'`]+|[\"'`),;:]+$/g, '');\n if (!clean || clean.length > 260) return;\n let normalized = clean.replace(/\\\\/g, '/');\n try {\n const abs = path.isAbsolute(clean) ? path.resolve(clean) : null;\n if (abs) {\n const rel = path.relative(ctx.projectRoot, abs);\n if (!rel.startsWith('..') && !path.isAbsolute(rel)) {\n normalized = rel.replace(/\\\\/g, '/');\n }\n }\n } catch {\n // Keep the best-effort normalized string.\n }\n if (normalized.length > 0) out.add(normalized);\n}\n\nfunction extractSymbols(content: string, input: unknown): string[] {\n const out = new Set<string>();\n const patterns = [\n /\\b(?:function|class|interface|type|enum|const|let|var|def|fn|struct)\\s+([A-Za-z_$][\\w$]*)/g,\n /\\b(?:export\\s+)?(?:async\\s+)?function\\s+([A-Za-z_$][\\w$]*)/g,\n ];\n for (const re of patterns) {\n for (const match of content.matchAll(re)) {\n if (match[1]) out.add(match[1]);\n if (out.size >= 30) break;\n }\n }\n\n const pattern = input && typeof input === 'object'\n ? (input as Record<string, unknown>)['pattern']\n : undefined;\n if (typeof pattern === 'string' && /^[A-Za-z_$][\\w$]*$/.test(pattern)) {\n out.add(pattern);\n }\n\n return [...out].slice(0, 30);\n}\n\nfunction extractCommands(toolName: string, input: unknown): string[] {\n if (toolName !== 'bash' && toolName !== 'exec' && toolName !== 'shell') return [];\n if (!input || typeof input !== 'object') return [];\n const command = (input as Record<string, unknown>)['command'];\n if (typeof command !== 'string') return [];\n return [command.slice(0, 220)];\n}\n\nfunction extractErrors(content: string): string[] {\n const lines = content.split(/\\r?\\n/);\n const errors: string[] = [];\n for (const line of lines) {\n if (!/\\b(error|exception|failed|failure|fatal|panic|timeout|denied|enoent|eacces|eperm|typeerror|syntaxerror)\\b/i.test(line)) continue;\n errors.push(normalizeWhitespace(line).slice(0, 260));\n if (errors.length >= 5) break;\n }\n return errors;\n}\n\nfunction summarizeInput(input: unknown): string | undefined {\n if (!input || typeof input !== 'object') return undefined;\n const obj = input as Record<string, unknown>;\n const parts: string[] = [];\n for (const key of ['path', 'file', 'pattern', 'glob', 'command']) {\n const value = obj[key];\n if (typeof value === 'string') parts.push(`${key}=${value.slice(0, 160)}`);\n }\n return parts.length > 0 ? parts.join(', ') : undefined;\n}\n\nfunction summarizeToolOutput(\n toolName: string,\n input: unknown,\n content: string,\n opts: { files: string[]; symbols: string[]; errors: string[]; ok: boolean },\n): string {\n if (!opts.ok && opts.errors.length > 0) return opts.errors[0] ?? `${toolName} failed`;\n if (toolName === 'read' && opts.files[0]) return `read ${opts.files[0]}`;\n if (toolName === 'grep') {\n const pattern = input && typeof input === 'object'\n ? (input as Record<string, unknown>)['pattern']\n : undefined;\n return `searched ${typeof pattern === 'string' ? pattern : 'pattern'} (${opts.files.length} file hint(s))`;\n }\n if ((toolName === 'edit' || toolName === 'write') && opts.files[0]) {\n return `${toolName === 'write' ? 'wrote' : 'edited'} ${opts.files[0]}`;\n }\n const firstLine = normalizeWhitespace(content.split(/\\r?\\n/).find((line) => line.trim()) ?? '');\n return firstLine ? firstLine.slice(0, 220) : `${toolName} returned no text`;\n}\n\nfunction updateFileGraph(state: ContextEvidenceState, metadata: ToolOutputMetadata): void {\n const writes = WRITE_TOOLS.has(metadata.toolName) ? 1 : 0;\n const reads = writes === 0 && (READ_TOOLS.has(metadata.toolName) || metadata.files.length > 0)\n ? 1\n : 0;\n for (const file of metadata.files) {\n const existing = state.fileGraph[file] ?? {\n path: file,\n reads: 0,\n writes: 0,\n tools: [],\n referenced: false,\n };\n existing.reads += reads;\n existing.writes += writes;\n existing.lastToolUseId = metadata.toolUseId;\n pushUniqueBounded(existing.tools, `${metadata.toolName}#${metadata.toolUseId}`, 8);\n state.fileGraph[file] = existing;\n }\n}\n\nfunction updateRepeatedReadSignals(state: ContextEvidenceState, metadata: ToolOutputMetadata): void {\n if (metadata.toolName !== 'read' || metadata.files.length === 0) {\n state.lastReadPath = undefined;\n return;\n }\n const file = metadata.files[0] as string;\n if (state.lastReadPath === file) {\n const existing = state.repeatedReads.find((item) => item.file === file);\n if (existing) {\n existing.count++;\n existing.lastToolUseId = metadata.toolUseId;\n } else {\n state.repeatedReads.push({ file, count: 2, lastToolUseId: metadata.toolUseId });\n }\n if (state.repeatedReads.length > 10) state.repeatedReads.shift();\n }\n state.lastReadPath = file;\n}\n\nfunction implicitFactFor(metadata: ToolOutputMetadata): string | undefined {\n if (metadata.errors.length > 0) return `${metadata.toolName}#${metadata.toolUseId} exposed error: ${metadata.errors[0]}`;\n if (metadata.toolName === 'read' && metadata.files[0]) {\n const size = metadata.outputLines ? ` (${metadata.outputLines} line(s) returned)` : '';\n return `read ${metadata.files[0]}${size}`;\n }\n if ((metadata.toolName === 'edit' || metadata.toolName === 'write') && metadata.files[0]) {\n return `${metadata.toolName} changed ${metadata.files[0]}`;\n }\n if (metadata.status === 'referenced') return `${metadata.toolName}#${metadata.toolUseId} was referenced`;\n return undefined;\n}\n\nfunction metadataReferencedByText(metadata: ToolOutputMetadata, haystack: string): boolean {\n for (const file of metadata.files) {\n const f = file.toLowerCase();\n const base = path.basename(file).toLowerCase();\n if (f && haystack.includes(f)) return true;\n if (base && haystack.includes(base)) return true;\n }\n for (const symbol of metadata.symbols) {\n if (symbol.length >= 3 && haystack.includes(symbol.toLowerCase())) return true;\n }\n for (const err of metadata.errors) {\n const head = err.slice(0, 80).toLowerCase();\n if (head.length >= 12 && haystack.includes(head)) return true;\n }\n return false;\n}\n","export interface TextBlock {\n type: 'text';\n text: string;\n cache_control?: { type: 'ephemeral' | undefined };\n}\n\nexport interface ToolUseBlock {\n type: 'tool_use';\n id: string;\n name: string;\n input: Record<string, unknown>;\n /**\n * Provider-specific opaque metadata captured from the wire response.\n * Echoed back verbatim in the next request so providers that bind\n * extra state to function calls keep working. Example: Gemini's\n * `thoughtSignature` — required for tool-use turns with thinking\n * models, otherwise the next request fails with 400 \"Function call\n * is missing a thought_signature in functionCall parts\".\n *\n * Keys are namespaced by intent so multiple wires can coexist:\n * - `google.thoughtSignature` — Gemini signed-thought blob\n * Other providers can add their own keys without colliding.\n */\n providerMeta?: Record<string, unknown>;\n}\n\nexport interface ToolResultBlock {\n type: 'tool_result';\n tool_use_id: string;\n /**\n * The original tool name. Useful for providers like Google Gemini that\n * need the tool name in `functionResponse.name` — the tool_use_id is\n * only a session-local identifier and is not stable across replays.\n * Always set by ToolExecutor; may be absent on manually-constructed blocks.\n */\n name?: string | undefined;\n content: string;\n is_error?: boolean | undefined;\n}\n\nexport interface ImageBlock {\n type: 'image';\n source: {\n type: 'base64' | 'url';\n media_type?: string | undefined;\n data?: string | undefined;\n url?: string | undefined;\n };\n}\n\n/**\n * Chain-of-thought / extended-thinking content emitted by the model.\n *\n * Both Anthropic extended thinking (`{type:'thinking', thinking, signature}`)\n * and DeepSeek reasoning mode (top-level `reasoning_content` on the assistant\n * message) require this content to be echoed back verbatim on the next\n * request, otherwise the provider returns 400:\n * - Anthropic: \"The `content[].thinking` in the thinking mode must be passed back\"\n * - DeepSeek: \"The `reasoning_content` in the thinking mode must be passed back\"\n *\n * `signature` is Anthropic-specific (an opaque integrity blob). DeepSeek\n * doesn't issue a signature — the field is absent for that provider.\n *\n * Per Anthropic, thinking blocks MUST appear before any text/tool_use blocks\n * in an assistant message. Stream builders preserve that order.\n */\nexport interface ThinkingBlock {\n type: 'thinking';\n thinking: string;\n signature?: string | undefined;\n providerMeta?: Record<string, unknown>;\n}\n\nexport type ContentBlock = TextBlock | ToolUseBlock | ToolResultBlock | ImageBlock | ThinkingBlock;\n\nexport function isTextBlock(b: ContentBlock): b is TextBlock {\n return b.type === 'text';\n}\nexport function isToolUseBlock(b: ContentBlock): b is ToolUseBlock {\n return b.type === 'tool_use';\n}\nexport function isToolResultBlock(b: ContentBlock): b is ToolResultBlock {\n return b.type === 'tool_result';\n}\nexport function isImageBlock(b: ContentBlock): b is ImageBlock {\n return b.type === 'image';\n}\nexport function isThinkingBlock(b: ContentBlock): b is ThinkingBlock {\n return b.type === 'thinking';\n}\n","import type { ContentBlock, ToolResultBlock, ToolUseBlock } from '../types/blocks.js';\nimport { isTextBlock } from '../types/blocks.js';\nimport type { Message } from '../types/messages.js';\nimport {\n estimateMessageTokens,\n estimateToolInputTokens,\n estimateToolResultTokens,\n} from '../utils/token-estimate.js';\n\n/**\n * Instrumentation state for compaction hot-path analysis.\n * Tracks actual vs. nominal iteration counts to detect O(n·m) blowup.\n *\n * Logged as structured events so they can be aggregated from session JSONL\n * and plotted per-message-count to catch regressions before they ship.\n */\ninterface CompactionMetrics {\n /** Total messages in the compaction pass. */\n messageCount: number;\n /** Index where the preserved window starts (from findPreserveStart). */\n preserveStart: number;\n /** Outer-loop iterations in the elision fast-path scan. */\n fastPathIterations: number;\n /**\n * Inner-loop block iterations in the fast-path scan.\n * Ratio fastPathInner / fastPathIterations indicates avg blocks per message.\n */\n fastPathInnerIterations: number;\n /**\n * Outer-loop iterations in the full elision pass.\n * Ratio fullPassIterations / messageCount ≈ 1.0 when working correctly.\n */\n fullPassIterations: number;\n /**\n * Inner-loop block iterations in the full elision pass.\n * Ratio fullPassInner / fullPassIterations indicates avg blocks per message.\n */\n fullPassInnerIterations: number;\n /** Estimated tokens saved by the elision pass. */\n tokensSaved: number;\n /** Whether the full elision pass made any changes. */\n changed: boolean;\n}\n\n/**\n * Whether compaction instrumentation should be emitted to stdout.\n * Gated behind WRONGSTACK_DEBUG=1 or NODE_ENV=development so the hot path\n * does not pay for JSON.stringify + console.log on every compaction pass\n * in production. Matches the guard at the ratio-guard site (line ~281).\n */\nfunction compactionDebugEnabled(): boolean {\n return process.env['NODE_ENV'] === 'development' || process.env['WRONGSTACK_DEBUG'] === '1';\n}\n\n/** Emit compaction instrumentation as a structured log event (debug-only). */\nfunction emitCompactionMetrics(event: string, metrics: CompactionMetrics): void {\n if (!compactionDebugEnabled()) return;\n console.log(\n JSON.stringify({\n level: 'debug',\n event,\n messageCount: metrics.messageCount,\n preserveStart: metrics.preserveStart,\n fastPathIterations: metrics.fastPathIterations,\n fastPathInnerIterations: metrics.fastPathInnerIterations,\n // Ratios — anything > 2.0 indicates the inner loop is running more than expected\n fastPathInnerPerOuter:\n metrics.fastPathIterations > 0\n ? metrics.fastPathInnerIterations / metrics.fastPathIterations\n : 0,\n fullPassIterations: metrics.fullPassIterations,\n fullPassInnerIterations: metrics.fullPassInnerIterations,\n fullPassInnerPerOuter:\n metrics.fullPassIterations > 0\n ? metrics.fullPassInnerIterations / metrics.fullPassIterations\n : 0,\n tokensSaved: metrics.tokensSaved,\n changed: metrics.changed,\n }),\n );\n}\n\n/**\n * Token estimate for a message array (text + tool I/O). Re-exported from the\n * canonical `token-estimate` helper so compactors and the context-pressure\n * monitor share one number.\n */\nexport const estimateMessages = estimateMessageTokens;\n\n/**\n * Shared, pure compaction primitives.\n *\n * Before this module the three compactors (`HybridCompactor`,\n * `IntelligentCompactor`, `SelectiveCompactor`) each carried their own copies\n * of message-token estimation, tool-result elision, text detection and digest\n * rendering — with subtle divergences (notably Selective lacked the\n * tool_use/tool_result pair preservation, so it could elide the result of a\n * tool call it was supposed to keep). These helpers are the single source of\n * truth. They operate on plain `Message[]` and never touch `Context`/state, so\n * each compactor keeps its own `ctx.state.replaceMessages(...)` plumbing.\n */\n\n/** Does this message carry any non-empty text? */\nexport function hasTextContent(m: Message): boolean {\n if (typeof m.content === 'string') return m.content.trim().length > 0;\n return m.content.some((b) => b.type === 'text' && b.text.trim().length > 0);\n}\n\n/**\n * Index where the preserved (recent) window starts. Walks back counting\n * user/assistant messages until `preserveK` are covered, then walks forward to\n * keep any tool_use/tool_result protocol pair intact — so a tool_result whose\n * tool_use is preserved is never elided.\n *\n * Instrumentation: emits `compaction.find_preserve_start.ended` with the\n * forward-walk inner-loop count so we can track whether the `.some()` calls\n * over content blocks are causing measurable O(n·m) overhead.\n */\nexport function findPreserveStart(messages: readonly Message[], preserveK: number): number {\n let pairCount = 0;\n let preserveStart = messages.length;\n for (let i = messages.length - 1; i >= 0 && pairCount < preserveK; i--) {\n const m = messages[i];\n if (!m) continue;\n if (m.role === 'user' || m.role === 'assistant') {\n pairCount++;\n preserveStart = i;\n }\n }\n\n // If the preserved window starts on a user tool_result, widen backward to\n // include the immediately preceding assistant tool_use. This keeps provider\n // protocol adjacency intact and avoids orphaned results after compaction.\n let pairRepairIterations = 0;\n let pairRepairInnerIterations = 0;\n while (preserveStart > 0) {\n pairRepairIterations++;\n const first = messages[preserveStart];\n const prev = messages[preserveStart - 1];\n if (!first || !prev || first.role !== 'user' || prev.role !== 'assistant') break;\n if (typeof first.content === 'string' || typeof prev.content === 'string') break;\n const resultIds = new Set<string>();\n for (const block of first.content) {\n pairRepairInnerIterations++;\n if (block.type === 'tool_result') resultIds.add(block.tool_use_id);\n }\n if (resultIds.size === 0) break;\n const hasMatchingUse = prev.content.some((block) => {\n pairRepairInnerIterations++;\n return block.type === 'tool_use' && resultIds.has(block.id);\n });\n if (!hasMatchingUse) break;\n preserveStart--;\n }\n\n if (compactionDebugEnabled()) {\n console.log(\n JSON.stringify({\n level: 'debug',\n event: 'compaction.find_preserve_start.ended',\n messageCount: messages.length,\n preserveK,\n preserveStart,\n pairRepairIterations,\n pairRepairInnerIterations,\n pairRepairInnerPerOuter:\n pairRepairIterations > 0 ? pairRepairInnerIterations / pairRepairIterations : 0,\n }),\n );\n }\n\n return preserveStart;\n}\n\nexport interface EliseResult {\n /** New message array, or the same reference when nothing changed. */\n messages: Message[];\n /** Estimated tokens reclaimed. */\n saved: number;\n changed: boolean;\n}\n\n/**\n * Elide oversized tool I/O that falls before the preserve window. Pure:\n * returns a fresh array (or the same reference when unchanged). Replaces the\n * duplicate copies that lived in all three compactors.\n */\nexport function eliseOldToolResults(\n messages: readonly Message[],\n opts: { preserveK: number; eliseThreshold: number },\n): EliseResult {\n const preserveStart = findPreserveStart(messages, opts.preserveK);\n\n // ── Fast path: probe for oversized tool I/O ─────────────────────────────\n //\n // Instruments the ratio of actual iterations to message count so we can\n // detect whether the inner block-scan loop is O(n·m) as expected or has\n // regressed to quadratic behaviour.\n let hasOversized = false;\n let fastPathIterations = 0;\n let fastPathInnerIterations = 0;\n for (let i = 0; i < preserveStart && !hasOversized; i++) {\n fastPathIterations++;\n const msg = messages[i];\n if (!msg || !Array.isArray(msg.content)) continue;\n for (const b of msg.content) {\n fastPathInnerIterations++;\n const oversized =\n (b.type === 'tool_result' && estimateToolResultTokens(b.content) >= opts.eliseThreshold) ||\n (b.type === 'tool_use' && estimateToolInputTokens(b.input) >= opts.eliseThreshold);\n if (oversized) {\n hasOversized = true;\n break;\n }\n }\n }\n\n // ── Emit fast-path metrics (covers both fast-path hit and the early-exit) ──\n emitCompactionMetrics(\n hasOversized\n ? 'compaction.elision.fast_path.oversized_found'\n : 'compaction.elision.fast_path.no_oversized',\n {\n messageCount: messages.length,\n preserveStart,\n fastPathIterations,\n fastPathInnerIterations,\n fullPassIterations: 0,\n fullPassInnerIterations: 0,\n tokensSaved: 0,\n changed: false,\n },\n );\n\n if (!hasOversized) return { messages: messages as Message[], saved: 0, changed: false };\n\n // ── Full elision pass ──────────────────────────────────────────────────\n //\n // Optimisation: once we've found the first oversized tool I/O block and\n // applied the elision, we can break out of the outer loop early. The\n // preserveStart boundary is already fixed by findPreserveStart(); any\n // remaining messages before it are either (a) already copied as-is by the\n // `i >= preserveStart` guard above, or (b) have no oversized tool_results.\n // Breaking early changes worst-case from O(n·m) to O(k·m) where k is the\n // index of the first oversized message — typically k << n.\n //\n // The instrumentation (ratio guard) is placed inside the loop body so it\n // fires per-message and can detect regressions before the pass completes.\n let saved = 0;\n let changed = false;\n let fullPassIterations = 0;\n let fullPassInnerIterations = 0;\n const next = new Array<Message>(messages.length);\n for (let i = 0; i < messages.length; i++) {\n fullPassIterations++;\n const msg = messages[i];\n if (i >= preserveStart || !msg || !Array.isArray(msg.content)) {\n next[i] = msg as Message;\n continue;\n }\n const original = msg.content;\n const newContent: ContentBlock[] = original.map((b) => {\n if (b.type === 'tool_use') {\n const tokens = estimateToolInputTokens(b.input);\n if (tokens < opts.eliseThreshold) return b;\n const elidedInput = summarizeToolUseInputElision(b, tokens);\n saved += Math.max(0, tokens - estimateToolInputTokens(elidedInput));\n return { ...b, input: elidedInput };\n }\n\n if (b.type !== 'tool_result') return b;\n const tokens = estimateToolResultTokens(b.content);\n if (tokens < opts.eliseThreshold) return b;\n saved += tokens;\n const elided: ToolResultBlock = {\n type: 'tool_result',\n tool_use_id: b.tool_use_id,\n content: summarizeToolResultElision(b, tokens),\n is_error: b.is_error,\n };\n return elided;\n });\n if (newContent.every((b, idx) => b === original[idx])) {\n next[i] = msg;\n } else {\n next[i] = { ...msg, content: newContent };\n changed = true;\n }\n // Count inner iterations (same items as the original.map)\n fullPassInnerIterations += original.length;\n\n // ── Ratio guard: defensive assertion + conditional early-break ─────────\n //\n // The ratio is computed here (after each outer iteration) so we can\n // break as early as possible — before processing remaining messages.\n //\n // Defensive assertion (threshold 10): fires in dev/debug if the inner loop\n // is running more than 10x what we'd expect per message. This catches\n // pathological regressions where a single message has hundreds of blocks.\n //\n // Conditional early-break (threshold 1.5): uncomment the `changed &&` guard\n // below ONLY if production sessions show fullPassInnerPerOuter > 1.5\n // consistently. In that case, add `&& changed` to the if-condition below\n // to break after the first elision is applied — capping worst-case from\n // O(n·m) to O(k·m) where k is the first oversized message index.\n if (compactionDebugEnabled()) {\n const ratio = fullPassInnerIterations / fullPassIterations;\n\n if (ratio > 10) {\n // Defensive assertion: never expected in practice\n console.error(\n JSON.stringify({\n level: 'error',\n event: 'compaction.elision.regression',\n message: `fullPassInnerPerOuter=${ratio.toFixed(2)} exceeds threshold 10 — possible O(n·m) regression`,\n messageCount: messages.length,\n fullPassIterations,\n fullPassInnerIterations,\n }),\n );\n }\n\n // TODO (prod): uncomment the following `changed &&` guard to enable\n // early-break once production data confirms fullPassInnerPerOuter > 1.5:\n //\n // if (changed) {\n // break; // O(n·m) → O(k·m), k = first oversized message index\n // }\n }\n }\n\n emitCompactionMetrics('compaction.elision.full_pass.ended', {\n messageCount: messages.length,\n preserveStart,\n fastPathIterations,\n fastPathInnerIterations,\n fullPassIterations,\n fullPassInnerIterations,\n tokensSaved: saved,\n changed,\n });\n\n return { messages: changed ? next : (messages as Message[]), saved, changed };\n}\n\nfunction summarizeToolUseInputElision(\n block: ToolUseBlock,\n tokens: number,\n): Record<string, unknown> {\n const fields: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(block.input ?? {})) {\n fields[key] = summarizeToolUseInputValue(value);\n }\n\n return {\n __elided_tool_input: `~${tokens} tokens; original arguments are in the session log`,\n tool: block.name,\n fields,\n };\n}\n\nfunction summarizeToolUseInputValue(value: unknown): unknown {\n if (value === null || value === undefined) return value;\n if (typeof value === 'number' || typeof value === 'boolean') return value;\n if (typeof value === 'string') {\n const oneLine = value.replace(/\\s+/g, ' ').trim();\n return oneLine.length <= 160 ? oneLine : `${oneLine.slice(0, 120)}...(${oneLine.length} chars)`;\n }\n if (Array.isArray(value)) {\n return `[array:${value.length}]`;\n }\n if (typeof value === 'object') {\n const keys = Object.keys(value as Record<string, unknown>);\n return `[object:${keys.slice(0, 8).join(',')}${keys.length > 8 ? ',...' : ''}]`;\n }\n return String(value);\n}\n\nfunction summarizeToolResultElision(block: ToolResultBlock, tokens: number): string {\n const parts = [`elided: ~${tokens} tokens`];\n if (block.name) parts.push(`tool=${block.name}`);\n const files = extractPathHints(block.content).slice(0, 5);\n if (files.length > 0) parts.push(`files=${files.join(', ')}`);\n const error = firstErrorLine(block.content);\n if (error) parts.push(`error=${error}`);\n return `[${parts.join('; ')}]`;\n}\n\nfunction extractPathHints(content: unknown): string[] {\n const text = typeof content === 'string' ? content : JSON.stringify(content);\n const out = new Set<string>();\n const re = /(?:(?:[A-Za-z]:)?[./\\\\]?[\\w@.-]+(?:[\\\\/][\\w@(). -]+)+\\.[A-Za-z0-9]{1,12})/g;\n for (const match of text.matchAll(re)) {\n const clean = match[0]?.replace(/\\\\/g, '/').replace(/^[\"'`]+|[\"'`),;:]+$/g, '');\n if (clean && clean.length <= 220) out.add(clean);\n if (out.size >= 5) break;\n }\n return [...out];\n}\n\nfunction firstErrorLine(content: unknown): string | undefined {\n const text = typeof content === 'string' ? content : JSON.stringify(content);\n for (const line of text.split(/\\r?\\n/)) {\n if (\n !/\\b(error|exception|failed|failure|fatal|panic|timeout|denied|enoent|eacces|eperm)\\b/i.test(\n line,\n )\n )\n continue;\n const trimmed = line.replace(/\\s+/g, ' ').trim();\n if (trimmed) return trimmed.slice(0, 180);\n }\n return undefined;\n}\n\n/**\n * Lossless textual digest of a message range. Every text block is kept verbatim\n * (across all roles, so prior `system` digests fold forward and nothing\n * accumulates as loss). `tool_use` / `tool_result` blocks are counted and\n * replaced with a marker rather than serialized — their payload is already\n * persisted in the session log. Empty/tool-only messages are skipped.\n */\nexport function buildLosslessDigest(messages: readonly Message[]): string {\n const lines: string[] = [];\n for (const m of messages) {\n let text: string;\n let omitted = 0;\n if (typeof m.content === 'string') {\n text = m.content;\n } else {\n const parts: string[] = [];\n for (const b of m.content) {\n if (isTextBlock(b)) parts.push(b.text);\n else if (b.type === 'tool_use' || b.type === 'tool_result') omitted++;\n }\n text = parts.join(' ');\n }\n if (text.trim().length === 0 && omitted === 0) continue;\n const marker = omitted > 0 ? ` [${omitted} tool call(s) omitted — see session log]` : '';\n lines.push(`[${m.role}]: ${text}${marker}`);\n }\n return lines.join('\\n');\n}\n\n// ── Content-aware scoring ─────────────────────────────────────────────────\n\n/** Importance score for a message — drives retention vs. summarization. */\nexport type ContentScore = 0 | 1 | 2 | 3 | 4 | 5;\n// 5 = critical (error, correction, decision) — keep verbatim\n// 3 = medium (normal exchange, successful tool) — keep first sentence\n// 1 = low (large tool result, grep output) — one-line summary\n// 0 = noise (repeated failure pattern) — collapse to count\n\n/**\n * Extract the plain text from a message (ignoring tool blocks).\n * Returns empty string if no text content exists.\n */\nexport function extractText(m: Message): string {\n if (typeof m.content === 'string') return m.content;\n return m.content\n .filter(isTextBlock)\n .map((b) => b.text)\n .join(' ');\n}\n\n/** Check if a message contains a tool_use block. */\nexport function hasToolUse(m: Message): boolean {\n if (typeof m.content === 'string') return false;\n return m.content.some((b) => b.type === 'tool_use');\n}\n\n/** Check if a message contains a tool_result block over the given char threshold. */\nexport function hasLargeToolResult(m: Message, threshold = 3000): boolean {\n if (typeof m.content === 'string') return false;\n return m.content.some(\n (b) =>\n b.type === 'tool_result' &&\n (b as ToolResultBlock).content &&\n (typeof (b as ToolResultBlock).content === 'string'\n ? (b as ToolResultBlock).content.length\n : JSON.stringify((b as ToolResultBlock).content).length) > threshold,\n );\n}\n\n/**\n * Score a message by content importance.\n *\n * CRITICAL (5): user corrections, explicit \"no/wrong/stop\", error messages,\n * architecture decisions, security findings.\n * MEDIUM (3): normal exchanges, successful tool calls, file reads, edits.\n * LOW (1): large tool results (>3K chars), grep/file-list outputs, boilerplate.\n * NOISE (0): repeated identical failures (same tool, same error, 5th+ occurrence\n * within the range), pure tool I/O with no text.\n */\nexport function scoreMessage(\n m: Message,\n context?: { failureCounts?: Map<string, number> },\n): ContentScore {\n const text = extractText(m).toLowerCase();\n\n // ── Noise detection: pure tool I/O with no text ─────────────────────\n if (text.trim().length === 0 && (hasToolUse(m) || typeof m.content !== 'string')) {\n const hasResult =\n typeof m.content !== 'string' && m.content.some((b) => b.type === 'tool_result');\n if (hasToolUse(m) || hasResult) return 0;\n }\n\n // ── Repeated failure detection ─────────────────────────────────────\n if (context?.failureCounts && m.role === 'user' && hasToolUse(m) === false) {\n // Check if this is a tool_result that matches a failure pattern\n const isFailure = /error|fail|exception|timeout|enonet|eacces|eperm|enoent|abort/i.test(text);\n if (isFailure) {\n // Build a key from the error type\n const errKey =\n /(error|fail|exception|timeout|enonet|eacces|eperm|enoent|abort)/i\n .exec(text)?.[0]\n ?.toLowerCase() ?? 'error';\n const count = (context.failureCounts.get(errKey) ?? 0) + 1;\n context.failureCounts.set(errKey, count);\n if (count >= 5) return 0; // 5th+ identical failure → noise\n if (count >= 3) return 1; // 3rd-4th → low priority\n }\n }\n\n // ── Critical: user corrections / stop signals ──────────────────────\n if (m.role === 'user') {\n if (\n /\\b(wrong|no\\b|stop\\b|don'?t\\b|actually|fix that|undo|revert|forget|ignore|skip)\\b/i.test(\n text,\n )\n ) {\n return 5;\n }\n }\n\n // ── Critical: error / exception messages ───────────────────────────\n if (\n /\\b(error|exception|fatal|critical|crash|panic|abort|segfault|core dump|undefined is not|null pointer|typeerror|referenceerror|syntaxerror)\\b/i.test(\n text,\n )\n ) {\n return 5;\n }\n\n // ── Critical: security findings ────────────────────────────────────\n if (\n /\\b(security|vulnerability|injection|xss|csrf|secret|apikey|api.key|hardcoded|leak|exploit|cve)\\b/i.test(\n text,\n )\n ) {\n return 5;\n }\n\n // ── Critical: architecture / design decisions ──────────────────────\n if (\n m.role === 'assistant' &&\n /\\b(architecture|design|approach|strategy|pattern|refactor|migrate|restructure|decision|trade.?off)\\b/i.test(\n text,\n )\n ) {\n return 5;\n }\n\n // ── Low: large tool results ────────────────────────────────────────\n if (hasLargeToolResult(m)) return 1;\n\n // ── Low: grep / list / tree outputs ────────────────────────────────\n if (\n m.role === 'user' &&\n !hasToolUse(m) &&\n /\\b(files_with_matches|count|found \\d+ match|directory tree|\\.\\.\\. and \\d+ more)\\b/i.test(text)\n ) {\n return 1;\n }\n\n // ── Default: medium ────────────────────────────────────────────────\n return 3;\n}\n\n/**\n * Build a content-aware digest of messages.\n *\n * Unlike `buildLosslessDigest` which preserves all text equally, this uses\n * `scoreMessage` to apply tiered treatment:\n * - Score 5 (critical): verbatim text\n * - Score 3 (medium): first sentence only\n * - Score 1 (low): one-line summary\n * - Score 0 (noise): collapsed to count marker\n */\nexport function buildSmartDigest(messages: readonly Message[]): string {\n const lines: string[] = [];\n const failureCounts = new Map<string, number>();\n let noiseCount = 0;\n\n for (const m of messages) {\n const score = scoreMessage(m, { failureCounts });\n const text = extractText(m);\n const toolCount = countToolBlocks(m);\n\n if (score === 0) {\n noiseCount++;\n continue;\n }\n\n const marker = toolCount > 0 ? ` [${toolCount} tool call(s)]` : '';\n let display: string;\n\n switch (score) {\n case 5: // Critical — keep verbatim\n display = text.trim();\n break;\n case 3: // Medium — first sentence\n display = firstSentence(text);\n break;\n case 1: // Low — one-line summary\n display = oneLineSummary(m, text);\n break;\n default:\n display = firstSentence(text);\n }\n\n if (display.length === 0 && toolCount === 0) continue;\n lines.push(`[${m.role}]: ${display}${marker}`);\n }\n\n if (noiseCount > 0) {\n lines.push(\n `[system]: ${noiseCount} low-importance turn(s) collapsed (repeated failures / pure tool I/O)`,\n );\n }\n\n return lines.join('\\n');\n}\n\nfunction countToolBlocks(m: Message): number {\n if (typeof m.content === 'string') return 0;\n return m.content.filter((b) => b.type === 'tool_use' || b.type === 'tool_result').length;\n}\n\nfunction firstSentence(text: string): string {\n const trimmed = text.trim();\n if (trimmed.length === 0) return '';\n const dot = trimmed.indexOf('. ');\n if (dot === -1) return trimmed.length > 150 ? `${trimmed.slice(0, 147)}…` : trimmed;\n const sentence = trimmed.slice(0, dot + 1);\n return sentence.length > 150 ? `${sentence.slice(0, 147)}…` : sentence;\n}\n\nfunction oneLineSummary(m: Message, text: string): string {\n const trimmed = text.trim();\n if (trimmed.length === 0) {\n // Pure tool result with no text\n if (typeof m.content !== 'string') {\n const results = m.content.filter((b) => b.type === 'tool_result');\n if (results.length > 0) {\n return `[${results.length} tool result(s) — see session log]`;\n }\n }\n return '[no text content]';\n }\n // Truncate to one line (~100 chars)\n const firstLine = trimmed.split('\\n')[0] ?? '';\n return firstLine.length > 100 ? `${firstLine.slice(0, 97)}…` : firstLine;\n}\n\n/**\n * Nearest safe cut boundary in [from, to]: the start of the exchange of the\n * closest user-with-text message. Returns -1 when no such boundary exists.\n */\nexport function findSafeBoundary(messages: readonly Message[], from: number, to: number): number {\n for (let i = to; i >= from; i--) {\n const m = messages[i];\n if (!m) continue;\n if (m.role === 'user' && hasTextContent(m)) {\n return findExchangeStart(messages, i);\n }\n }\n return -1;\n}\n\n/**\n * Walk backwards from a user message to find where its logical exchange began\n * (just after the last assistant message that made no tool calls).\n */\nexport function findExchangeStart(messages: readonly Message[], userIndex: number): number {\n for (let i = userIndex - 1; i >= 0; i--) {\n const m = messages[i];\n if (!m) continue;\n if (m.role === 'assistant') {\n const hasToolUse = Array.isArray(m.content)\n ? m.content.some((b) => b.type === 'tool_use')\n : false;\n if (!hasToolUse) return i + 1;\n } else if (m.role === 'user') {\n return i;\n }\n }\n return 0;\n}\n","import type { Context } from '../core/context.js';\nimport type { CompactReport, Compactor } from '../types/compactor.js';\nimport type { ContextWindowPolicy } from '../types/context-window.js';\nimport type { Message } from '../types/messages.js';\nimport { estimateRequestTokens } from '../utils/token-estimate.js';\nimport { repairToolUseAdjacency } from '../utils/message-invariants.js';\nimport { buildContextEvidenceDigest } from '../utils/context-evidence.js';\nimport {\n buildLosslessDigest,\n buildSmartDigest,\n eliseOldToolResults,\n estimateMessages,\n hasTextContent,\n} from './compaction-core.js';\n\nexport interface CompactorOptions {\n preserveK?: number | undefined;\n eliseThreshold?: number | undefined;\n /**\n * Enable content-aware digest mode. When true, `collapseAncientTurns` uses\n * `buildSmartDigest` which scores messages by importance: critical content\n * (errors, corrections, decisions) is kept verbatim; normal exchanges get\n * first-sentence summaries; large tool outputs and repeated failures are\n * aggressively compressed. Defaults to false (lossless digest).\n */\n smart?: boolean | undefined;\n /**\n * @deprecated Ignored. Token estimation is centralized in\n * `compaction-core`/`token-estimate` so all compactors and the context-pressure\n * monitor agree on one number. Kept only for backward-compatible call sites.\n */\n estimator?: (((text: string) => number)) | undefined;\n}\n\n/**\n * Default tools config values shared across CLI and WebUI.\n * Import this instead of hardcoding to avoid cross-surface inconsistencies.\n * These mirror the values in BEHAVIOR_DEFAULTS (config-loader.ts).\n *\n * @deprecated Import from '../types/default-config.js' instead.\n * This re-export exists for backward compatibility.\n */\nexport { DEFAULT_TOOLS_CONFIG, DEFAULT_CONTEXT_CONFIG, DEFAULT_AUTONOMY_CONFIG } from '../types/default-config.js';\n\nexport class HybridCompactor implements Compactor {\n private readonly preserveK: number;\n private readonly eliseThreshold: number;\n private readonly smart: boolean;\n\n constructor(opts: CompactorOptions = {}) {\n this.preserveK = opts.preserveK ?? 5;\n this.eliseThreshold = opts.eliseThreshold ?? 2000;\n this.smart = opts.smart ?? false;\n }\n\n async compact(ctx: Context, opts: { aggressive?: boolean | undefined } = {}): Promise<CompactReport> {\n const beforeTokens = estimateMessages(ctx.messages);\n const beforeFull = this.estimateFullRequest(ctx);\n const reductions: CompactReport['reductions'] = [];\n const policy = readContextWindowPolicy(ctx);\n const preserveK = policy?.preserveK ?? this.preserveK;\n const eliseThreshold = policy?.eliseThreshold ?? this.eliseThreshold;\n\n // Phase 1: elision (shared core handles tool_use/tool_result pair preservation).\n const elide = eliseOldToolResults(ctx.messages, { preserveK, eliseThreshold });\n if (elide.changed) ctx.state.replaceMessages(elide.messages);\n if (elide.saved > 0) reductions.push({ phase: 'elision', saved: elide.saved });\n\n // Phase 2: lossless collapse of ancient turns into a single digest.\n // Preserves ALL textual content (instructions, decisions, conclusions);\n // only raw tool I/O is dropped (it remains in the session log). No sub-LLM call.\n let collapsedDigest: string | undefined;\n let evidenceDigest: string | undefined;\n if (opts.aggressive) {\n const phase2 = this.collapseAncientTurns(ctx, preserveK);\n if (phase2.saved > 0) reductions.push({ phase: 'summary', saved: phase2.saved });\n collapsedDigest = phase2.digest;\n evidenceDigest = phase2.evidenceDigest;\n }\n\n const repaired = repairToolUseAdjacency(ctx.messages);\n if (repaired.report.changed) {\n ctx.state.replaceMessages(repaired.messages);\n }\n\n const afterTokens = estimateMessages(ctx.messages);\n const afterFull = this.estimateFullRequest(ctx);\n const quality = checkCompactionQuality(ctx, {\n collapsedDigest,\n evidenceDigest,\n reduced: beforeTokens > afterTokens || beforeFull > afterFull,\n });\n return {\n before: beforeTokens,\n after: afterTokens,\n fullRequestTokensBefore: beforeFull,\n fullRequestTokensAfter: afterFull,\n reductions,\n collapsedDigest,\n evidenceDigest,\n quality,\n repaired: repaired.report.changed\n ? {\n removedToolUses: repaired.report.removedToolUses,\n removedToolResults: repaired.report.removedToolResults,\n removedMessages: repaired.report.removedMessages,\n }\n : undefined,\n };\n }\n\n /**\n * Estimate the full API request token count: messages + systemPrompt + toolDefs.\n * This is the accurate figure for context-window pressure monitoring.\n */\n private estimateFullRequest(ctx: Context): number {\n return estimateRequestTokens(ctx.messages, ctx.systemPrompt, ctx.tools ?? []).total;\n }\n\n /**\n * Lossless rule-based collapse of ancient turns into a single digest message.\n *\n * Preserves ALL textual content of the collapsed range — user instructions,\n * assistant decisions/conclusions, and any prior digests (chained forward so\n * the digest stays lossless across repeated compactions). Only `tool_use` /\n * `tool_result` protocol blocks are dropped and replaced with a count marker;\n * their full payload already lives in the session log. No sub-LLM call.\n *\n * Returns the token savings and the digest text (for audit logging).\n */\n private collapseAncientTurns(\n ctx: Context,\n preserveK = this.preserveK,\n ): { saved: number; digest?: string | undefined; evidenceDigest?: string | undefined } {\n const messages = ctx.messages;\n const cutTarget = Math.max(0, messages.length - preserveK * 2);\n if (cutTarget <= 0) return { saved: 0 };\n\n // Find a safe boundary: nearest user-message-with-text at or after cutTarget.\n let boundary = -1;\n for (let i = cutTarget; i < messages.length; i++) {\n const m = messages[i];\n if (!m) continue;\n if (m.role === 'user' && hasTextContent(m)) {\n boundary = i;\n break;\n }\n }\n if (boundary <= 0) return { saved: 0 };\n\n const removed = messages.slice(0, boundary);\n const removedTokens = estimateMessages(removed);\n\n const historyDigest =\n this.smart\n ? buildSmartDigest(removed) ||\n `${removed.length} earlier turns (no textual content; tool I/O omitted; see session log)`\n : buildLosslessDigest(removed) ||\n `${removed.length} earlier turns (no textual content; tool I/O omitted; see session log)`;\n\n const evidenceDigest = buildContextEvidenceDigest(ctx);\n const digest = evidenceDigest\n ? `[context_state]\\n${evidenceDigest}\\n\\n[prior_history]\\n${historyDigest}`\n : historyDigest;\n\n const summaryMsg: Message = {\n role: 'system',\n content: `[prior_turns_digest: ${digest}]`,\n };\n\n // L1-A: route through ConversationState so subscribers see the rewrite.\n const tail = ctx.messages.slice(boundary);\n ctx.state.replaceMessages([summaryMsg, ...tail]);\n return {\n saved: Math.max(0, removedTokens - estimateMessages([summaryMsg])),\n digest,\n evidenceDigest: evidenceDigest || undefined,\n };\n }\n}\n\nfunction checkCompactionQuality(\n ctx: Context,\n opts: {\n collapsedDigest?: string | undefined;\n evidenceDigest?: string | undefined;\n reduced: boolean;\n },\n): CompactReport['quality'] {\n const evidence = ctx.contextEvidence;\n const digest = `${opts.collapsedDigest ?? ''}\\n${opts.evidenceDigest ?? ''}`;\n const hasIntent = Boolean(evidence?.currentIntent?.text || /\\b(intent|goal|session_goals)\\b/i.test(digest));\n const hasPathTrail = Boolean(\n Object.keys(evidence?.fileGraph ?? {}).length > 0 ||\n (evidence?.toolCalls.length ?? 0) > 0 ||\n /\\b(dependency_graph|tool_trail|files=)\\b/i.test(digest),\n );\n const issues: string[] = [];\n if (opts.reduced && !hasIntent) issues.push('missing intent anchor');\n if (opts.reduced && !hasPathTrail) issues.push('missing tool/path trail');\n return {\n ok: issues.length === 0,\n hasIntent,\n hasPathTrail,\n issues,\n };\n}\n\nfunction readContextWindowPolicy(ctx: Context): ContextWindowPolicy | null {\n const policy = ctx.meta?.['contextWindowPolicy'];\n if (!policy || typeof policy !== 'object') return null;\n const candidate = policy as Partial<ContextWindowPolicy>;\n if (\n typeof candidate.preserveK !== 'number' ||\n typeof candidate.eliseThreshold !== 'number'\n ) {\n return null;\n }\n return candidate as ContextWindowPolicy;\n}\n","import type { Context } from '../core/context.js';\nimport type { TextBlock } from '../types/blocks.js';\nimport { isTextBlock } from '../types/blocks.js';\nimport type { CompactReport, Compactor } from '../types/compactor.js';\nimport type { Message } from '../types/messages.js';\nimport type { Provider, Request } from '../types/provider.js';\nimport { estimateRequestTokens } from '../utils/token-estimate.js';\nimport { repairToolUseAdjacency } from '../utils/message-invariants.js';\nimport {\n buildLosslessDigest,\n eliseOldToolResults,\n estimateMessages,\n findSafeBoundary,\n} from './compaction-core.js';\n\n/**\n * Options for IntelligentCompactor.\n */\nexport interface IntelligentCompactorOptions {\n /** Provider to use for LLM-assisted summarization. Required. */\n provider: Provider;\n /** Fraction of maxContext that triggers a warning (default 0.6). */\n warnThreshold?: number | undefined;\n /** Fraction of maxContext that triggers soft compaction (default 0.75). */\n softThreshold?: number | undefined;\n /** Fraction of maxContext that triggers hard compaction (default 0.9). */\n hardThreshold?: number | undefined;\n /** Max context window in tokens (used only for threshold fraction math). */\n maxContext?: number | undefined;\n /** How many recent (user+assistant) pairs to always preserve (default 4). */\n preserveK?: number | undefined;\n /** Token threshold below which tool results are not elided (default 500). */\n eliseThreshold?: number | undefined;\n /** System prompt for the summarizer sub-LLM. */\n summarizerPrompt?: string | undefined;\n /**\n * Model ID to use for summarization. When not set, the same model as the\n * agent is used (which risks cascading failure on context overflow). Set to\n * a fast/cheap model like `claude-3-5-haiku-20240620` for resilience.\n */\n summarizerModel?: string | undefined;\n}\n\n/**\n * An importance label for a message or message range.\n */\nexport type Importance = 'critical' | 'high' | 'medium' | 'low';\n\n/**\n * Result of importance analysis.\n */\nexport interface ImportanceAnalysis {\n messages: Array<{ index: number; importance: Importance; reason: string }>;\n criticalRanges: Array<{ from: number; to: number; summary: string }>;\n}\n\n/**\n * IntelligentCompactor uses an LLM to:\n * - Analyze message importance and preserve critical context\n * - Generate semantic summaries for old message ranges\n * - Make intelligent decisions about what to compact\n *\n * It builds on the shared `compaction-core` elision/boundary primitives and\n * adds LLM-assisted summarization on top. When the summarizer call fails it\n * falls back to the same lossless rule-based digest used by HybridCompactor.\n */\nexport class IntelligentCompactor implements Compactor {\n private readonly provider: Provider;\n private readonly warnThreshold: number;\n private readonly softThreshold: number;\n private readonly hardThreshold: number;\n private readonly maxContext: number;\n private readonly preserveK: number;\n private readonly eliseThreshold: number;\n private readonly summarizerPrompt: string;\n private readonly summarizerModel?: string | undefined;\n\n constructor(opts: IntelligentCompactorOptions) {\n this.provider = opts.provider;\n this.warnThreshold = opts.warnThreshold ?? 0.6;\n this.softThreshold = opts.softThreshold ?? 0.75;\n this.hardThreshold = opts.hardThreshold ?? 0.9;\n this.maxContext = opts.maxContext ?? 128_000;\n this.preserveK = opts.preserveK ?? 4;\n this.eliseThreshold = opts.eliseThreshold ?? 500;\n this.summarizerPrompt =\n opts.summarizerPrompt ??\n 'You are a context summarizer. Given a list of conversation messages, produce a concise but complete summary that preserves all factual information, decisions made, and any state changes (e.g. file edits, todo updates). Do not add commentary. Output only the summary.';\n this.summarizerModel = opts.summarizerModel;\n }\n\n async compact(ctx: Context, opts: { aggressive?: boolean | undefined } = {}): Promise<CompactReport> {\n const beforeTokens = estimateMessages(ctx.messages);\n const beforeFull = this.estimateFullRequest(ctx);\n const reductions: CompactReport['reductions'] = [];\n\n // Use full request tokens for threshold decisions — messages alone are inaccurate.\n const load = beforeFull / this.maxContext;\n // Past hardThreshold, force aggressive regardless of caller preference —\n // the alternative (lightweight elision) is unlikely to recover enough.\n const aggressive =\n load >= this.hardThreshold ? true : (opts.aggressive ?? load >= this.softThreshold);\n\n // Phase 1: always run elision (preserves recent K pairs)\n const saved1 = this.elide(ctx);\n if (saved1 > 0) reductions.push({ phase: 'elision', saved: saved1 });\n\n // Phase 2: LLM summarization of ancient turns\n let collapsedDigest: string | undefined;\n if (aggressive) {\n const phase2 = await this.summarizeAncientTurns(ctx);\n if (phase2.saved > 0) reductions.push({ phase: 'summary', saved: phase2.saved });\n collapsedDigest = phase2.digest;\n } else if (load >= this.warnThreshold) {\n // Non-aggressive: lightweight elision only.\n const saved2 = this.elide(ctx);\n if (saved2 > 0) reductions.push({ phase: 'elision', saved: saved2 });\n }\n\n const repaired = repairToolUseAdjacency(ctx.messages);\n if (repaired.report.changed) ctx.state.replaceMessages(repaired.messages);\n\n const afterTokens = estimateMessages(ctx.messages);\n const afterFull = this.estimateFullRequest(ctx);\n return {\n before: beforeTokens,\n after: afterTokens,\n fullRequestTokensBefore: beforeFull,\n fullRequestTokensAfter: afterFull,\n reductions,\n collapsedDigest,\n repaired: repaired.report.changed\n ? {\n removedToolUses: repaired.report.removedToolUses,\n removedToolResults: repaired.report.removedToolResults,\n removedMessages: repaired.report.removedMessages,\n }\n : undefined,\n };\n }\n\n /**\n * Estimate the full API request token count: messages + systemPrompt + toolDefs.\n * This is the accurate figure for context-window pressure monitoring.\n */\n private estimateFullRequest(ctx: Context): number {\n return estimateRequestTokens(ctx.messages, ctx.systemPrompt, ctx.tools ?? []).total;\n }\n\n /** Run shared tool-result elision and commit through ConversationState. */\n private elide(ctx: Context): number {\n const result = eliseOldToolResults(ctx.messages, {\n preserveK: this.preserveK,\n eliseThreshold: this.eliseThreshold,\n });\n if (result.changed) ctx.state.replaceMessages(result.messages);\n return result.saved;\n }\n\n private async summarizeAncientTurns(\n ctx: Context,\n ): Promise<{ saved: number; digest?: string | undefined }> {\n const messages = ctx.messages;\n const cutoff = Math.max(0, messages.length - this.preserveK * 2);\n if (cutoff <= 2) return { saved: 0 };\n\n // Find the best boundary in the ancient region\n const boundary = findSafeBoundary(messages, 0, cutoff);\n if (boundary <= 1) return { saved: 0 };\n\n const toSummarize = messages.slice(0, boundary);\n const removedTokens = estimateMessages(toSummarize);\n\n let summaryText: string;\n try {\n summaryText = await this.callSummarizer(toSummarize, ctx);\n } catch {\n // Fallback: lossless rule-based digest (text preserved, tool I/O dropped).\n // Cannot fail and preserves the semantic content the summarizer would have.\n summaryText =\n buildLosslessDigest(toSummarize) ||\n `${toSummarize.length} earlier turns (semantic content preserved)`;\n }\n\n const summaryMsg: Message = {\n role: 'system',\n content: `[prior_turns_summary: ${summaryText}]`,\n };\n const summaryTokens = estimateMessages([summaryMsg]);\n\n // L1-A: route through ConversationState so subscribers see the rewrite.\n const tail = ctx.messages.slice(boundary);\n ctx.state.replaceMessages([summaryMsg, ...tail]);\n return { saved: Math.max(0, removedTokens - summaryTokens), digest: summaryText };\n }\n\n private async callSummarizer(messages: Message[], ctx: Context): Promise<string> {\n const prompt: TextBlock[] = [\n { type: 'text', text: this.summarizerPrompt },\n { type: 'text', text: '\\n\\nConversation to summarize:\\n' },\n ...this.messagesToText(messages),\n ];\n\n const req: Request = {\n model: this.summarizerModel ?? ctx.model,\n system: prompt,\n messages: [],\n maxTokens: 1024,\n };\n\n // Use abort signal from context if available.\n // Fall back to a fresh controller only if ctx.signal is absent — this\n // avoids leaking AbortControllers on every summarizer call (the original\n // `?? new AbortController().signal` created a controller that was never\n // connected to anything, making cancellation a no-op).\n const ac = ctx.signal ? undefined : new AbortController();\n const signal = ctx.signal ?? ac?.signal;\n let res;\n try {\n res = await this.provider.complete(req, { signal });\n } finally {\n ac?.abort();\n }\n\n const textBlocks = res.content.filter(isTextBlock);\n return (\n textBlocks\n .map((b) => b.text)\n .join('\\n')\n .trim() || '(empty summary)'\n );\n }\n\n private messagesToText(messages: Message[]): TextBlock[] {\n const lines: string[] = [];\n for (const m of messages) {\n const role = m.role.padEnd(10, ' ');\n if (typeof m.content === 'string') {\n lines.push(`[${role}]: ${m.content.slice(0, 500)}`);\n } else if (Array.isArray(m.content)) {\n const textParts = m.content.filter(isTextBlock).map((b) => b.text);\n if (textParts.length > 0) {\n lines.push(`[${role}]: ${textParts.join(' ').slice(0, 500)}`);\n }\n }\n }\n return [{ type: 'text', text: lines.join('\\n') }];\n }\n}\n","import { expectDefined } from '../utils/expect-defined.js';\nimport { estimateMessageTokens, estimateTextTokens } from '../utils/token-estimate.js';\nimport { isTextBlock } from '../types/blocks.js';\nimport type { Message } from '../types/messages.js';\nimport type { Provider, Request } from '../types/provider.js';\nimport type { MessageSelector, SelectorResult } from '../types/selector.js';\nexport interface LLMSelectorOptions {\n /** Provider used for the selector LLM call. Required. */\n provider: Provider;\n /** Model for the selector. Defaults to the provider's default model. */\n model?: string | undefined;\n /**\n * Maximum tokens to keep in context (target budget).\n * Selector will aim to keep total content below this.\n */\n maxContextTokens?: number | undefined;\n /**\n * Prompt instructing the selector how to behave.\n * Should guide the LLM on importance tiers and output format.\n */\n systemPrompt?: string | undefined;\n /**\n * Maximum output tokens for the selector LLM call.\n * Controls both the JSON response budget and the token reservation for the\n * history text budget calculation (default: 1024).\n */\n maxOutputTokens?: number | undefined;\n}\n\nconst DEFAULT_SYSTEM_PROMPT = `You are a context pruning assistant. Given a conversation history and a token budget, decide which message ranges are worth keeping verbatim and which should be collapsed into summaries.\n\nOutput a JSON object with this structure:\n{\n \"kept\": [{\"from\": 0, \"to\": 5, \"importance\": \"critical\"}],\n \"collapsed\": [{\"from\": 6, \"to\": 20, \"summary\": \"optional summary\"}],\n \"reasoning\": \"brief explanation of decisions\"\n}\n\nImportance tiers:\n- \"critical\": decisions, file edits, tool results that affect state, final answers\n- \"high\": substantive tool use, complex reasoning, non-obvious observations\n- \"medium\": routine exchanges, confirmations, straightforward Q&A\n\nRules:\n- Always keep the most recent K pairs (preserve recency)\n- Never collapse the final 2 user/assistant pairs (working memory)\n- Preserve tool results that modified files or had external effects\n- Collapse old, low-information exchanges (greetings, acknowledgements, etc.)\n- If unsure, keep rather than collapse (errors are more costly than waste)\n\nReturn ONLY the JSON object, no markdown, no explanation outside the JSON.`;\n\n/**\n * Format messages as a compact text dump for the selector LLM.\n * Uses token estimation (not character count) to budget the output,\n * so long sessions don't silently truncate the selector's view of history.\n */\nfunction formatMessages(messages: Message[], maxTokens = 2048): string {\n const lines: string[] = [];\n let usedTokens = 0;\n for (let i = 0; i < messages.length; i++) {\n const m = expectDefined(messages[i]);\n const role = m.role.padEnd(10, ' ');\n let text: string;\n if (typeof m.content === 'string') {\n text = m.content.slice(0, 500);\n } else {\n const content = m.content as import('../types/blocks.js').ContentBlock[];\n text = content\n .filter(isTextBlock)\n .map((b) => b.text)\n .join(' ');\n // Also capture tool names for context\n const toolUses = content.filter((b) => b.type === 'tool_use');\n if (toolUses.length > 0) {\n text += ` [tools: ${toolUses.map((b) => (b as { name?: string }).name).filter(Boolean).join(', ')}]`;\n }\n }\n const line = `[${i}][${role}]: ${text}`;\n const lineTokens = estimateTextTokens(line);\n if (usedTokens + lineTokens > maxTokens) break;\n lines.push(line);\n usedTokens += lineTokens;\n }\n return lines.join('\\n');\n}\n\n/**\n * LLM-powered message selector. Calls a sub-LLM to analyze the\n * message history and produce a keep/collapse plan — more surgical\n * than fixed-window rules.\n */\nexport class LLMSelector implements MessageSelector {\n private readonly provider: Provider;\n private readonly model: string;\n private readonly maxContextTokens: number;\n private readonly systemPrompt: string;\n private readonly maxOutputTokens: number;\n\n constructor(opts: LLMSelectorOptions) {\n this.provider = opts.provider;\n this.model = opts.model ?? 'unknown';\n if (\n this.model === 'unknown' &&\n (process.env['NODE_ENV'] === 'development' || process.env['WRONGSTACK_DEBUG'] === '1')\n ) {\n console.warn(\n '[LLMSelector] model not set — selector will use the provider default. Set `model` explicitly in LLMSelectorOptions to silence this warning.',\n );\n }\n this.maxContextTokens = opts.maxContextTokens ?? 40_000;\n this.systemPrompt = opts.systemPrompt ?? DEFAULT_SYSTEM_PROMPT;\n this.maxOutputTokens = opts.maxOutputTokens ?? 1024;\n }\n\n async select(messages: Message[], maxToKeep: number): Promise<SelectorResult> {\n const effectiveBudget = Math.min(maxToKeep, this.maxContextTokens);\n\n const totalTokens = estimateMessageTokens(messages);\n const systemText = `${this.systemPrompt}\\n\\nConversation (${messages.length} messages, ~${totalTokens} tokens, budget: ${effectiveBudget}):\\n`;\n // Reserve tokens for the system prefix and output (maxOutputTokens), then give the\n // rest to the formatted history so the selector sees the maximum possible context.\n const systemTokens = estimateTextTokens(systemText);\n const historyBudget = Math.max(512, effectiveBudget - systemTokens - this.maxOutputTokens);\n\n // Build a concise representation of the conversation within the token budget\n const historyText = formatMessages(messages, historyBudget);\n\n // Add instruction to stay within budget\n const budgetInstruction =\n totalTokens > effectiveBudget\n ? `\\n\\nIMPORTANT: Total conversation (${totalTokens} tokens) exceeds budget (${effectiveBudget}). You MUST collapse enough to fit. Prefer collapsing older/lower-importance ranges.`\n : '';\n\n const req: Request = {\n model: this.model,\n system: [{ type: 'text', text: systemText + budgetInstruction }],\n messages: [{ role: 'user', content: historyText }],\n maxTokens: this.maxOutputTokens,\n };\n\n let raw: string;\n const ac = new AbortController();\n try {\n // 30-second timeout so a stuck selector LLM call can't hang the compactor.\n const timeoutSignal = AbortSignal.timeout(30_000);\n const res = await this.provider.complete(req, {\n signal: AbortSignal.any([ac.signal, timeoutSignal]),\n });\n const textBlocks = res.content.filter(isTextBlock);\n raw = textBlocks\n .map((b) => b.text)\n .join('\\n')\n .trim();\n } catch (err) {\n if (err instanceof Error) {\n console.warn('[LLMSelector] selector call failed, using recency fallback:', err.message);\n }\n return this.fallbackSelect(messages, effectiveBudget);\n } finally {\n ac.abort();\n }\n\n return this.parseSelectorOutput(raw, messages);\n }\n\n private fallbackSelect(messages: Message[], budget: number): SelectorResult {\n // Simple fallback: keep from the end until we hit budget\n const toKeep: SelectorResult['kept'] = [];\n const toCollapse: SelectorResult['collapsed'] = [];\n\n let tokenCount = 0;\n let startIdx = 0;\n\n // Scan from the end backwards\n for (let i = messages.length - 1; i >= 0; i--) {\n const m = expectDefined(messages[i]);\n const cost = estimateMessageTokens([m]);\n\n if (tokenCount + cost <= budget) {\n tokenCount += cost;\n } else {\n startIdx = i + 1;\n break;\n }\n }\n\n if (startIdx > 0) {\n toCollapse.push({ from: 0, to: startIdx - 1 });\n }\n toKeep.push({ from: startIdx, to: messages.length - 1, importance: 'high' });\n\n return {\n kept: toKeep,\n collapsed: toCollapse,\n reasoning: `Fallback: kept last ${messages.length - startIdx} messages within ${budget} token budget`,\n };\n }\n\n /**\n * Parse and validate the raw LLM output into a SelectorResult.\n * Falls back to recency-based selection if the LLM output is malformed,\n * out-of-bounds, or internally inconsistent.\n */\n private parseSelectorOutput(raw: string, messages: Message[]): SelectorResult {\n const messageCount = messages.length;\n if (messageCount === 0) {\n return { kept: [], collapsed: [], reasoning: 'empty session' };\n }\n\n // Try to extract JSON from the response\n const jsonStart = raw.indexOf('{');\n const jsonEnd = raw.lastIndexOf('}');\n if (jsonStart === -1 || jsonEnd === -1) {\n return this.fallbackSelect(messages, this.maxContextTokens);\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw.slice(jsonStart, jsonEnd + 1));\n } catch {\n return this.fallbackSelect(messages, this.maxContextTokens);\n }\n\n const obj = parsed as Record<string, unknown>;\n const keptRaw =\n (obj.kept as Array<{ from: number; to: number; importance: string }> | undefined) ?? [];\n const collapsedRaw =\n (obj.collapsed as Array<{ from: number; to: number; summary?: string | undefined }> | undefined) ?? [];\n\n // Validate kept ranges — must be within [0, messageCount), from <= to\n const kept: SelectorResult['kept'] = [];\n for (const k of keptRaw) {\n if (\n typeof k.from !== 'number' ||\n typeof k.to !== 'number' ||\n k.from < 0 ||\n k.to >= messageCount ||\n k.from > k.to\n ) {\n return this.fallbackSelect(messages, this.maxContextTokens);\n }\n kept.push({\n from: k.from,\n to: k.to,\n importance: (k.importance ?? 'medium') as 'critical' | 'high' | 'medium',\n });\n }\n\n // Validate collapsed ranges — same bounds check\n const collapsed: SelectorResult['collapsed'] = [];\n for (const c of collapsedRaw) {\n if (\n typeof c.from !== 'number' ||\n typeof c.to !== 'number' ||\n c.from < 0 ||\n c.to >= messageCount ||\n c.from > c.to\n ) {\n return this.fallbackSelect(messages, this.maxContextTokens);\n }\n collapsed.push({ from: c.from, to: c.to, summary: c.summary });\n }\n\n // Check for overlaps: kept ranges must not overlap with each other or with collapsed ranges\n const allRanges: Array<{ from: number; to: number }> = [...kept, ...collapsed];\n for (let i = 0; i < allRanges.length; i++) {\n const a = allRanges[i];\n if (!a) continue;\n for (let j = i + 1; j < allRanges.length; j++) {\n const b = allRanges[j];\n if (!b) continue;\n // Overlap: a starts before b ends AND a ends after b starts\n if (a.from <= b.to && a.to >= b.from) {\n return this.fallbackSelect(messages, this.maxContextTokens);\n }\n }\n }\n\n return {\n kept,\n collapsed,\n reasoning: typeof obj.reasoning === 'string' ? obj.reasoning : '',\n };\n }\n}\n","import type { Context } from '../core/context.js';\nimport { LLMSelector } from '../models/llm-selector.js';\nimport { isTextBlock } from '../types/blocks.js';\nimport type { CompactReport, Compactor } from '../types/compactor.js';\nimport type { Message } from '../types/messages.js';\nimport type { Provider, Request } from '../types/provider.js';\nimport type { MessageSelector, SelectorResult } from '../types/selector.js';\nimport { estimateRequestTokens } from '../utils/token-estimate.js';\nimport { repairToolUseAdjacency } from '../utils/message-invariants.js';\nimport {\n eliseOldToolResults as coreEliseOldToolResults,\n estimateMessages,\n} from './compaction-core.js';\n\n/**\n * Options for SelectiveCompactor — the most configurable compactor.\n */\nexport interface SelectiveCompactorOptions {\n /** Provider for LLM calls (selector + summarizer). Required. */\n provider: Provider;\n /** Selector for LLM-driven importance analysis. */\n selector?: MessageSelector | undefined;\n /** Fraction of maxContext that triggers a warning (default 0.6). */\n warnThreshold?: number | undefined;\n /** Fraction of maxContext that triggers soft compaction (default 0.75). */\n softThreshold?: number | undefined;\n /** Fraction of maxContext that triggers hard compaction (default 0.9). */\n hardThreshold?: number | undefined;\n /** Max context window in tokens (used for threshold fraction math). */\n maxContext?: number | undefined;\n /** How many recent (user+assistant) pairs to always preserve (default 4). */\n preserveK?: number | undefined;\n /** Token threshold below which tool results are not elided (default 500). */\n eliseThreshold?: number | undefined;\n /** Model for selector LLM calls (default: same as provider default). */\n selectorModel?: string | undefined;\n /** Max output tokens for the selector LLM call (default: 1024). */\n selectorMaxOutputTokens?: number | undefined;\n /** Summarizer model for collapsed ranges (default: same as selectorModel). */\n summarizerModel?: string | undefined;\n /** Prompt for the summarizer sub-LLM. */\n summarizerPrompt?: string | undefined;\n}\n\n/**\n * SelectiveCompactor uses an LLM-driven MessageSelector to make\n * surgical decisions about which message ranges to keep vs collapse.\n *\n * Compared to HybridCompactor / IntelligentCompactor:\n * - HybridCompactor: rule-based (preserveK + elision), no LLM calls\n * - IntelligentCompactor: LLM summarization but no structured selection\n * - SelectiveCompactor: full LLM-driven selection + optional summarization\n */\nexport class SelectiveCompactor implements Compactor {\n private readonly provider: Provider;\n private readonly selector: MessageSelector;\n private readonly warnThreshold: number;\n private readonly softThreshold: number;\n private readonly hardThreshold: number;\n private readonly maxContext: number;\n private readonly preserveK: number;\n private readonly eliseThreshold: number;\n private readonly summarizerModel: string | undefined;\n private readonly summarizerPrompt: string;\n\n constructor(opts: SelectiveCompactorOptions) {\n this.provider = opts.provider;\n this.selector =\n opts.selector ?? new LLMSelector({ provider: opts.provider, model: opts.selectorModel, maxOutputTokens: opts.selectorMaxOutputTokens });\n this.warnThreshold = opts.warnThreshold ?? 0.6;\n this.softThreshold = opts.softThreshold ?? 0.75;\n this.hardThreshold = opts.hardThreshold ?? 0.9;\n this.maxContext = opts.maxContext ?? 128_000;\n this.preserveK = opts.preserveK ?? 4;\n this.eliseThreshold = opts.eliseThreshold ?? 500;\n // Leave undefined when unset so summarizeRange() can fall back to the\n // live ctx.model (mirrors IntelligentCompactor). Never send a 'unknown'\n // sentinel to the provider — that yields a 400 in non-dev deployments\n // where the warning below is suppressed.\n this.summarizerModel = opts.summarizerModel ?? opts.selectorModel;\n if (\n this.summarizerModel === undefined &&\n (process.env['NODE_ENV'] === 'development' || process.env['WRONGSTACK_DEBUG'] === '1')\n ) {\n console.warn(\n '[SelectiveCompactor] summarizerModel not set — will fall back to ctx.model at summarize time. Set `summarizerModel` explicitly to silence this warning.',\n );\n }\n this.summarizerPrompt =\n opts.summarizerPrompt ??\n 'You are a context summarizer. Given a list of messages, produce a concise summary that preserves all factual information, decisions, file changes, and state changes. Do not add commentary or opinions.';\n }\n\n async compact(ctx: Context, opts: { aggressive?: boolean | undefined } = {}): Promise<CompactReport> {\n const beforeTokens = this.estimateTokens(ctx.messages);\n const beforeFull = this.estimateFullRequest(ctx);\n const reductions: CompactReport['reductions'] = [];\n\n // Use full request tokens for threshold decisions — messages alone are inaccurate.\n const load = beforeFull / this.maxContext;\n const shouldCompact = load >= this.warnThreshold || opts.aggressive;\n\n if (!shouldCompact) {\n // Only do lightweight elision if below warn threshold\n const saved = this.eliseOldToolResults(ctx);\n if (saved > 0) reductions.push({ phase: 'elision', saved });\n const repair = this.repairProtocolAdjacency(ctx);\n const afterTokens = this.estimateTokens(ctx.messages);\n const afterFull = this.estimateFullRequest(ctx);\n return {\n before: beforeTokens,\n after: afterTokens,\n fullRequestTokensBefore: beforeFull,\n fullRequestTokensAfter: afterFull,\n reductions,\n repaired: repair,\n };\n }\n\n // Phase 1: elision — always run first to get a baseline reduction\n const savedElision = this.eliseOldToolResults(ctx);\n if (savedElision > 0) reductions.push({ phase: 'elision', saved: savedElision });\n\n // Phase 2: LLM-driven selective compaction\n const afterPhase1 = this.estimateTokens(ctx.messages);\n const targetBudget = this.computeTargetBudget(load);\n\n if (afterPhase1 > targetBudget) {\n const savedSelective = await this.runSelector(ctx, targetBudget);\n if (savedSelective > 0) reductions.push({ phase: 'selective', saved: savedSelective });\n }\n\n const repair = this.repairProtocolAdjacency(ctx);\n const afterTokens = this.estimateTokens(ctx.messages);\n const afterFull = this.estimateFullRequest(ctx);\n return {\n before: beforeTokens,\n after: afterTokens,\n fullRequestTokensBefore: beforeFull,\n fullRequestTokensAfter: afterFull,\n reductions,\n repaired: repair,\n };\n }\n\n /**\n * Estimate the full API request token count: messages + systemPrompt + toolDefs.\n * This is the accurate figure for context-window pressure monitoring.\n */\n private estimateFullRequest(ctx: Context): number {\n const breakdown = estimateRequestTokens(ctx.messages, ctx.systemPrompt, ctx.tools ?? []);\n return breakdown.total;\n }\n\n private repairProtocolAdjacency(ctx: Context): CompactReport['repaired'] {\n const repaired = repairToolUseAdjacency(ctx.messages);\n if (repaired.report.changed) ctx.state.replaceMessages(repaired.messages);\n return repaired.report.changed\n ? {\n removedToolUses: repaired.report.removedToolUses,\n removedToolResults: repaired.report.removedToolResults,\n removedMessages: repaired.report.removedMessages,\n }\n : undefined;\n }\n\n /**\n * Run the LLM selector to decide what to keep vs collapse.\n * Returns the token savings achieved.\n */\n private async runSelector(ctx: Context, targetBudget: number): Promise<number> {\n const before = this.estimateTokens(ctx.messages);\n\n let result: SelectorResult;\n try {\n result = await this.selector.select(ctx.messages, targetBudget);\n } catch {\n // Fallback to aggressive recency preservation\n return this.aggressiveRecencyTrim(ctx);\n }\n\n // Execute the selector's plan\n await this.executePlan(ctx, result);\n\n const after = this.estimateTokens(ctx.messages);\n return Math.max(0, before - after);\n }\n\n /**\n * Execute a SelectorResult plan: collapse/remove ranges and\n * insert summaries where the selector provided them.\n */\n private async executePlan(ctx: Context, plan: SelectorResult): Promise<void> {\n if (ctx.messages.length === 0) return;\n\n // Process collapsed ranges in reverse order to preserve indices. We work\n // on a local copy and commit through `ctx.state.replaceMessages` at the\n // end so subscribers see a single state change for the whole rewrite.\n const messages = [...ctx.messages];\n const sortedCollapsed = [...plan.collapsed].sort((a, b) => b.from - a.from);\n\n for (const range of sortedCollapsed) {\n if (range.from < 0 || range.to >= messages.length || range.from > range.to) continue;\n\n let summary = range.summary;\n if (!summary) {\n const toSummarize = messages.slice(range.from, range.to + 1);\n summary = await this.summarizeRange(toSummarize, ctx);\n }\n\n const summaryMsg: Message = {\n role: 'system',\n content: `[prior_turns_${range.from}-${range.to}: ${summary}]`,\n };\n\n messages.splice(range.from, range.to - range.from + 1, summaryMsg);\n }\n\n ctx.state.replaceMessages(messages);\n }\n\n private async summarizeRange(messages: Message[], ctx: Context): Promise<string> {\n const systemText = `${this.summarizerPrompt}\\n\\nSummarize the following message range:`;\n const body = messages.map((m, i) => `[${i}] ${m.role}: ${this.messagePreview(m)}`).join('\\n');\n\n const req: Request = {\n model: this.summarizerModel ?? ctx.model,\n system: [{ type: 'text', text: systemText }],\n messages: [{ role: 'user', content: body }],\n maxTokens: 512,\n };\n\n try {\n // 30-second timeout so a stuck summarizer can't hang compaction.\n const timeoutSignal = AbortSignal.timeout(30_000);\n const res = await this.provider.complete(req, {\n signal: AbortSignal.any([ctx.signal, timeoutSignal]),\n });\n return (\n res.content\n .filter(isTextBlock)\n .map((b) => b.text)\n .join('\\n')\n .trim() || '(empty)'\n );\n } catch {\n return `[${messages.length} earlier turns omitted]`;\n }\n }\n\n private messagePreview(m: Message): string {\n if (typeof m.content === 'string') return m.content.slice(0, 300);\n return m.content\n .filter(isTextBlock)\n .map((b) => b.text)\n .join(' ')\n .slice(0, 300);\n }\n\n /**\n * Fallback when selector fails: aggressively trim from the oldest end\n * until we hit targetBudget.\n */\n private aggressiveRecencyTrim(ctx: Context): number {\n const messages = ctx.messages;\n const preserveIdx = Math.max(0, messages.length - this.preserveK * 2);\n\n if (preserveIdx <= 0) return 0;\n\n // Find safe boundary near preserveIdx\n let boundary = preserveIdx;\n for (let i = preserveIdx; i < messages.length && i < preserveIdx + 6; i++) {\n const m = messages[i];\n if (!m) continue;\n if (m.role === 'user' && this.hasTextContent(m)) {\n boundary = i;\n break;\n }\n }\n\n const removed = messages.slice(0, boundary);\n const removedTokens = this.estimateTokens(removed);\n\n const summaryMsg: Message = {\n role: 'system',\n content: `[${removed.length} earlier turns trimmed — see session log for details]`,\n };\n const tail = messages.slice(boundary);\n ctx.state.replaceMessages([summaryMsg, ...tail]);\n\n return Math.max(0, removedTokens - this.estimateTokens([summaryMsg]));\n }\n\n private computeTargetBudget(load: number): number {\n if (load >= this.hardThreshold) {\n return Math.floor(this.maxContext * 0.5); // keep only 50%\n }\n if (load >= this.softThreshold) {\n return Math.floor(this.maxContext * 0.65); // keep 65%\n }\n return Math.floor(this.maxContext * 0.75); // keep 75% at warn\n }\n\n private eliseOldToolResults(ctx: Context): number {\n // Delegate to the shared core so SelectiveCompactor gets the same\n // tool_use/tool_result pair preservation as the other compactors — its\n // previous local copy lacked the forward walk and could elide the result\n // of a tool call it was supposed to keep.\n const result = coreEliseOldToolResults(ctx.messages, {\n preserveK: this.preserveK,\n eliseThreshold: this.eliseThreshold,\n });\n if (result.changed) ctx.state.replaceMessages(result.messages);\n return result.saved;\n }\n\n private hasTextContent(m: Message): boolean {\n if (typeof m.content === 'string') return m.content.trim().length > 0;\n return m.content.some((b) => b.type === 'text' && b.text.trim().length > 0);\n }\n\n /**\n * Estimate message-array tokens via the shared `estimateMessages` primitive\n * so SelectiveCompactor's before/after/load figures agree with the\n * middleware threshold math and the other compactors. Previously this used a\n * private `ceil(len/3.5)` walk that diverged from the calibrated shared\n * estimator, causing the selective `load`/`targetBudget` comparison to mix\n * two incompatible token scales.\n */\n private estimateTokens(messages: Message[]): number {\n return estimateMessages(messages);\n }\n}\n","import type { Context } from '../core/context.js';\nimport type { CompactReport, Compactor } from '../types/compactor.js';\nimport type { ContextWindowPolicy } from '../types/context-window.js';\nimport { HybridCompactor } from './compactor.js';\nimport { IntelligentCompactor } from './intelligent-compactor.js';\nimport { SelectiveCompactor } from './selective-compactor.js';\n\nexport type CompactorStrategy = 'hybrid' | 'intelligent' | 'selective';\n\nexport interface StrategyCompactorOptions {\n /** Which compactor to use. Defaults to 'hybrid' (lossless, no LLM). */\n strategy?: CompactorStrategy | string | undefined;\n /** Recent user/assistant pairs to always preserve. */\n preserveK?: number | undefined;\n /** Token threshold below which tool results are not elided. */\n eliseThreshold?: number | undefined;\n /**\n * Enable content-aware smart digest for 'hybrid' strategy. When true,\n * collapsed ancient turns use buildSmartDigest: critical content (errors,\n * corrections, decisions) stays verbatim; normal exchanges get first-sentence\n * summaries; noise (repeated failures, large tool outputs) is aggressively\n * compressed. Defaults to false (lossless digest).\n */\n smart?: boolean | undefined;\n /** Model used by the LLM-backed strategies for summarization/selection. */\n summarizerModel?: string | undefined;\n /** Max output tokens for the selector LLM call in 'selective' strategy (default: 1024). */\n selectorMaxOutputTokens?: number | undefined;\n /**\n * Legacy shortcut for `strategy: 'selective'`. When `strategy` is unset (or\n * 'hybrid') and this is true, the selective (LLM-driven) compactor is used.\n * An explicit `strategy` always wins.\n */\n llmSelector?: boolean | undefined;\n}\n\n/**\n * Build the compactor named by `config.context.strategy`.\n *\n * - `hybrid` (default): lossless rule-based — no provider needed.\n * - `intelligent` / `selective`: LLM-backed. These need a `provider`, which is\n * only known per-run, so we return a thin wrapper that resolves the concrete\n * compactor from `ctx` at `compact()`-time. This deliberately avoids the\n * container/provider construction-ordering problem: `TOKENS.Compactor` is\n * resolved (and memoized) before `context.provider` exists, but `ctx.provider`\n * is always present once a run is actually compacting. If no provider is\n * available at compact-time the wrapper degrades to the lossless hybrid rules\n * rather than failing.\n */\nexport function createStrategyCompactor(opts: StrategyCompactorOptions = {}): Compactor {\n const requested = opts.strategy ?? (opts.llmSelector ? 'selective' : 'hybrid');\n const strategy = requested as CompactorStrategy;\n if (strategy === 'intelligent' || strategy === 'selective') {\n return new ProviderBackedCompactor(strategy, opts);\n }\n return new HybridCompactor({\n preserveK: opts.preserveK,\n eliseThreshold: opts.eliseThreshold,\n smart: opts.smart,\n });\n}\n\nclass ProviderBackedCompactor implements Compactor {\n constructor(\n private readonly strategy: 'intelligent' | 'selective',\n private readonly opts: StrategyCompactorOptions,\n ) {}\n\n async compact(\n ctx: Context,\n compactOpts: { aggressive?: boolean | undefined } = {},\n ): Promise<CompactReport> {\n return this.resolveInner(ctx).compact(ctx, compactOpts);\n }\n\n /**\n * Construct the concrete compactor for this run. Rebuilt per call (cheap, no\n * I/O) so a model switch — which changes `ctx.provider.capabilities.maxContext`\n * — is always reflected. Reads the active ContextWindowPolicy from `ctx.meta`\n * so the LLM compactors honor the same thresholds/preserveK as the policy.\n */\n private resolveInner(ctx: Context): Compactor {\n const provider = ctx.provider;\n if (!provider) {\n // No provider on ctx → cannot run an LLM compactor. Degrade to lossless rules.\n return new HybridCompactor({\n preserveK: this.opts.preserveK,\n eliseThreshold: this.opts.eliseThreshold,\n });\n }\n\n const policy = readPolicy(ctx);\n const maxContext = provider.capabilities?.maxContext || undefined;\n const thresholds = policy?.thresholds;\n const common = {\n provider,\n maxContext,\n preserveK: this.opts.preserveK ?? policy?.preserveK,\n eliseThreshold: this.opts.eliseThreshold ?? policy?.eliseThreshold,\n ...(thresholds\n ? { warnThreshold: thresholds.warn, softThreshold: thresholds.soft, hardThreshold: thresholds.hard }\n : {}),\n };\n\n if (this.strategy === 'selective') {\n return new SelectiveCompactor({\n ...common,\n selectorModel: this.opts.summarizerModel,\n selectorMaxOutputTokens: this.opts.selectorMaxOutputTokens,\n summarizerModel: this.opts.summarizerModel,\n });\n }\n return new IntelligentCompactor({\n ...common,\n summarizerModel: this.opts.summarizerModel,\n });\n }\n}\n\nfunction readPolicy(ctx: Context): ContextWindowPolicy | null {\n const policy = ctx.meta?.['contextWindowPolicy'];\n if (!policy || typeof policy !== 'object') return null;\n const candidate = policy as Partial<ContextWindowPolicy>;\n if (typeof candidate.preserveK !== 'number' || !candidate.thresholds) return null;\n return candidate as ContextWindowPolicy;\n}\n","/**\n * Exhaustiveness check for discriminated union switches.\n * Place in the `default` branch of a switch over a union type\n * to get a compile-time error when a new variant is added.\n *\n * @example\n * switch (block.type) {\n * case 'text': return renderText(block);\n * case 'tool_use': return renderToolUse(block);\n * default: return assertNever(block);\n * }\n */\nexport function assertNever(x: never, message?: string): never {\n const err = new Error(\n message ?? `Unhandled case: ${JSON.stringify(x)}`,\n );\n err.name = 'AssertNeverError';\n throw err;\n}\n","import { randomBytes } from 'node:crypto';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\n\nexport interface AtomicWriteOptions {\n mode?: number | undefined;\n encoding?: BufferEncoding | undefined;\n}\n\nexport interface FileLockOptions {\n timeoutMs?: number | undefined;\n staleMs?: number | undefined;\n}\n\nexport async function atomicWrite(\n targetPath: string,\n content: string | Uint8Array,\n opts: AtomicWriteOptions = {},\n): Promise<void> {\n const dir = path.dirname(targetPath);\n await fs.mkdir(dir, { recursive: true });\n const tmp = path.join(dir, `.${path.basename(targetPath)}.${randomBytes(6).toString('hex')}.tmp`);\n\n // Write content to tmp first; 'wx' ensures exclusive creation (fails if\n // tmp already exists — extremely unlikely with 6-byte random suffix).\n try {\n if (typeof content === 'string') {\n await fs.writeFile(tmp, content, { flag: 'wx', encoding: opts.encoding ?? 'utf8' });\n } else {\n await fs.writeFile(tmp, content, { flag: 'wx' });\n }\n try {\n const fh = await fs.open(tmp, 'r+');\n try {\n await fh.sync();\n } finally {\n await fh.close();\n }\n } catch {\n // fsync best-effort\n }\n // Now safely read mode from target (if it exists) and apply to tmp before rename.\n // Prefer opts.mode for new files; for existing files preserve their mode.\n let mode: number | undefined;\n try {\n const stat = await fs.stat(targetPath);\n mode = stat.mode & 0o777;\n } catch {\n mode = opts.mode;\n }\n if (mode !== undefined) {\n await fs.chmod(tmp, mode);\n }\n await renameWithRetry(tmp, targetPath);\n } catch (err) {\n try {\n await fs.unlink(tmp);\n } catch {\n // ignore cleanup error\n }\n throw err;\n }\n}\n\nexport async function ensureDir(dir: string): Promise<void> {\n await fs.mkdir(dir, { recursive: true });\n}\n\nexport async function withFileLock<T>(\n targetPath: string,\n fn: () => Promise<T>,\n opts: FileLockOptions = {},\n): Promise<T> {\n const dir = path.dirname(targetPath);\n await fs.mkdir(dir, { recursive: true });\n const lockPath = path.join(dir, `.${path.basename(targetPath)}.lock`);\n const timeoutMs = opts.timeoutMs ?? 5_000;\n const staleMs = opts.staleMs ?? 30_000;\n const started = Date.now();\n let handle: fs.FileHandle | undefined;\n\n for (;;) {\n try {\n handle = await fs.open(lockPath, 'wx');\n await handle.writeFile(`${process.pid}:${Date.now()}`);\n break;\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n // ENOENT means the directory was deleted (e.g. by concurrent cleanup).\n // Recreate it and retry acquiring the lock.\n if (code === 'ENOENT') {\n await fs.mkdir(dir, { recursive: true });\n continue;\n }\n if (code !== 'EEXIST') throw err;\n try {\n const stat = await fs.stat(lockPath);\n if (Date.now() - stat.mtimeMs > staleMs) {\n await fs.unlink(lockPath);\n continue;\n }\n } catch {\n continue;\n }\n if (Date.now() - started >= timeoutMs) {\n throw new Error(`Timed out waiting for file lock: ${targetPath}`);\n }\n await new Promise((resolve) => setTimeout(resolve, 25));\n }\n }\n\n try {\n return await fn();\n } finally {\n try {\n await handle?.close();\n } catch {\n // ignore\n }\n try {\n await fs.unlink(lockPath);\n } catch {\n // ignore\n }\n }\n}\n\n// On Windows, fs.rename over an existing file can fail with EPERM/EBUSY/EACCES\n// when antivirus, file indexers, editor file watchers, or a concurrent writer\n// briefly hold a handle on the destination. These are transient — retry with a\n// short backoff before giving up. POSIX renames are atomic and won't hit this.\nconst TRANSIENT_RENAME_CODES = new Set(['EPERM', 'EBUSY', 'EACCES', 'ENOTEMPTY']);\n\nasync function renameWithRetry(from: string, to: string): Promise<void> {\n if (process.platform !== 'win32') {\n await fs.rename(from, to);\n return;\n }\n const delays = [10, 25, 60, 120, 250];\n let lastErr: unknown;\n for (let i = 0; i <= delays.length; i++) {\n try {\n await fs.rename(from, to);\n return;\n } catch (err) {\n lastErr = err;\n const code = (err as NodeJS.ErrnoException)?.code;\n if (!code || !TRANSIENT_RENAME_CODES.has(code) || i === delays.length) {\n throw err;\n }\n await new Promise((resolve) => setTimeout(resolve, delays[i]));\n }\n }\n throw lastErr;\n}\n","/**\n * Converts an unknown error value to a human-readable string.\n * Used in 40+ files across the codebase to normalize error messaging.\n */\nexport function toErrorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n","/**\n * Minimal JSON Schema validator — covers the subset needed for plugin\n * configSchema validation and tool inputSchema sanity checks. Intentionally\n * small (~80 lines, zero deps) and tolerant: unknown keywords are ignored so\n * authors can mix in non-standard extensions without breaking validation.\n *\n * NOT for full JSON Schema 2020-12 conformance. If a plugin needs $ref,\n * conditional schemas, format validation, or anything else exotic, it should\n * bring its own ajv-based validator and call this only for the cheap path.\n */\nimport type { JSONSchema } from '../types/tool.js';\n\nexport interface ValidationError {\n path: string;\n message: string;\n}\n\nexport interface ValidationResult {\n ok: boolean;\n errors: ValidationError[];\n}\n\nexport function validateAgainstSchema(value: unknown, schema: JSONSchema): ValidationResult {\n const errors: ValidationError[] = [];\n walk(value, schema, '', errors);\n return { ok: errors.length === 0, errors };\n}\n\nfunction walk(value: unknown, schema: JSONSchema, path: string, errors: ValidationError[]): void {\n if (schema.enum !== undefined) {\n if (!schema.enum.some((e) => deepEqual(e, value))) {\n errors.push({\n path: path || '<root>',\n message: `expected one of ${JSON.stringify(schema.enum)}, got ${JSON.stringify(value)}`,\n });\n return;\n }\n }\n\n if (typeof schema.type === 'string') {\n if (!checkType(value, schema.type)) {\n errors.push({\n path: path || '<root>',\n message: `expected ${schema.type}, got ${describeType(value)}`,\n });\n return;\n }\n }\n\n if (schema.type === 'object' && isPlainObject(value)) {\n const obj = value as Record<string, unknown>;\n for (const req of schema.required ?? []) {\n if (!(req in obj)) {\n errors.push({ path: joinPath(path, req), message: 'required property missing' });\n }\n }\n if (schema.properties) {\n for (const [key, subSchema] of Object.entries(schema.properties)) {\n if (key in obj) {\n walk(obj[key], subSchema, joinPath(path, key), errors);\n }\n }\n }\n }\n\n if (schema.type === 'array' && Array.isArray(value) && schema.items) {\n for (let i = 0; i < value.length; i++) {\n walk(value[i], schema.items as JSONSchema, `${path}[${i}]`, errors);\n }\n }\n}\n\nfunction checkType(value: unknown, type: string): boolean {\n switch (type) {\n case 'string':\n return typeof value === 'string';\n case 'number':\n return typeof value === 'number' && !Number.isNaN(value);\n case 'integer':\n return typeof value === 'number' && Number.isInteger(value);\n case 'boolean':\n return typeof value === 'boolean';\n case 'null':\n return value === null;\n case 'array':\n return Array.isArray(value);\n case 'object':\n return isPlainObject(value);\n default:\n return true;\n }\n}\n\nfunction isPlainObject(v: unknown): boolean {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction describeType(v: unknown): string {\n if (v === null) return 'null';\n if (Array.isArray(v)) return 'array';\n return typeof v;\n}\n\nfunction joinPath(parent: string, key: string): string {\n if (!parent) return key;\n return `${parent}.${key}`;\n}\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (typeof a !== typeof b) return false;\n if (a === null || b === null) return a === b;\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((v, i) => deepEqual(v, b[i]));\n }\n if (typeof a === 'object' && typeof b === 'object') {\n const ak = Object.keys(a as object);\n const bk = Object.keys(b as object);\n if (ak.length !== bk.length) return false;\n return ak.every((k) =>\n deepEqual((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]),\n );\n }\n return false;\n}\n","/**\n * Compile a user-supplied regex with conservative bounds against ReDoS.\n *\n * Duplicated from @wrongstack/tools/_regex.ts to avoid a circular\n * dependency (tools depends on core, not vice versa). Keep both copies\n * in sync if the heuristics change.\n *\n * V8's regex engine is backtracking-based and cannot interrupt a\n * synchronous match — a pattern like `(a+)+$` against a sufficiently\n * long line will pin a worker for seconds.\n */\n\nconst MAX_PATTERN_LEN = 512;\n\n// Heuristics for catastrophic-backtracking constructs.\nconst DANGEROUS_PATTERNS: ReadonlyArray<RegExp> = [\n /(\\([^)]*[+*][^)]*\\))[+*]/, // (a+)+, (.*)+, etc\n /(\\(\\?:[^)]*[+*][^)]*\\))[+*]/, // same, with non-capturing group\n];\n\nexport interface CompileResult {\n ok: true;\n regex: RegExp;\n}\n\nexport interface CompileFail {\n ok: false;\n reason: string;\n}\n\nexport function compileUserRegex(pattern: string, flags: string): CompileResult | CompileFail {\n if (typeof pattern !== 'string') {\n return { ok: false, reason: 'pattern must be a string' };\n }\n if (pattern.length === 0) {\n return { ok: false, reason: 'pattern is empty' };\n }\n if (pattern.length > MAX_PATTERN_LEN) {\n return { ok: false, reason: `pattern exceeds ${MAX_PATTERN_LEN} characters` };\n }\n for (const rx of DANGEROUS_PATTERNS) {\n if (rx.test(pattern)) {\n return {\n ok: false,\n reason:\n 'pattern looks vulnerable to catastrophic backtracking — rewrite without nested quantifiers',\n };\n }\n }\n try {\n return { ok: true, regex: new RegExp(pattern, flags) };\n } catch (err) {\n return {\n ok: false,\n reason: err instanceof Error ? err.message : 'invalid regex',\n };\n }\n}\n","/** Resolve a promise after `ms` milliseconds. Prefer this over raw\n * `setTimeout` wrappers so all delay sites use a single implementation\n * and an abortable variant can be introduced without a codebase-wide hunt. */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","/**\n * String utilities shared across the WrongStack codebase.\n */\n\n/**\n * Truncate a string to at most `max` characters, appending an ellipsis if it\n * was longer. Returns the original string unchanged when it fits.\n */\nexport function truncate(s: string, max: number): string {\n return s.length <= max ? s : `${s.slice(0, max - 1)}…`;\n}\n","/**\n * Tool output serialization utilities.\n * Extracted from Agent.executeTools to allow reuse and consistent output handling.\n */\n\nexport interface ToolOutputSerializerOptions {\n perIterationOutputCapBytes?: number | undefined;\n estimator?: ((text: string) => number) | undefined;\n}\n\nexport interface ToolOutputSerializeContext {\n toolName?: string | undefined;\n input?: unknown;\n}\n\ntype RecordValue = Record<string, unknown>;\n\nconst DEFAULT_LIST_LIMIT = 500;\nconst LOG_ENTRY_LIMIT = 200;\nconst INLINE_LIMIT = 240;\nconst GREP_FILE_LIMIT = 80;\nconst GREP_MATCHES_PER_FILE = 3;\nconst DIFF_INLINE_LINE_LIMIT = 260;\nconst DIFF_HUNK_LIMIT = 8;\nconst DIFF_HUNK_CONTEXT = 14;\n\nexport function createToolOutputSerializer(opts: ToolOutputSerializerOptions = {}) {\n const capBytes = opts.perIterationOutputCapBytes ?? 100_000;\n\n function serialize(value: unknown, context: ToolOutputSerializeContext = {}): string {\n if (typeof value === 'string') return value;\n if (value === null || value === undefined) return '';\n if (typeof value === 'object') {\n if (Array.isArray(value)) return value.map((item) => serialize(item)).join('\\n');\n if (context.toolName) {\n const compact = renderToolObject(context.toolName, value as RecordValue, context.input);\n if (compact !== undefined) return compact;\n return renderGenericToolObject(context.toolName, value as RecordValue);\n }\n if ('text' in (value as Record<string, unknown>)) {\n const t = (value as Record<string, unknown>).text;\n return typeof t === 'string' ? t : JSON.stringify(value, null, 2);\n }\n try {\n return JSON.stringify(value, null, 2);\n } catch {\n return String(value);\n }\n }\n return String(value);\n }\n\n function enforceCap(text: string, remainingBudget: number): { text: string; newBudget: number } {\n if (remainingBudget <= 0) {\n return { text: '[truncated: iteration output cap exceeded]', newBudget: 0 };\n }\n const textBytes = Buffer.byteLength(text, 'utf8');\n if (textBytes <= remainingBudget) {\n return { text, newBudget: remainingBudget - textBytes };\n }\n const marker = `\\n…[truncated ${textBytes - remainingBudget} bytes]…\\n`;\n const markerBytes = Buffer.byteLength(marker, 'utf8');\n const available = remainingBudget - markerBytes;\n if (available <= 0) {\n return { text: '[truncated: iteration output cap exceeded]', newBudget: 0 };\n }\n const half = Math.floor(available / 2);\n const first = text.slice(0, half);\n const second = text.slice(text.length - half);\n return { text: `${first}${marker}${second}`, newBudget: 0 };\n }\n\n return { serialize, enforceCap, capBytes };\n}\n\nfunction renderToolObject(toolName: string, obj: RecordValue, input: unknown): string | undefined {\n if (toolName === 'read' && typeof obj['text'] === 'string') {\n return joinSections([\n renderHeader(\n `read: ${stringFromInput(input, 'path') ?? stringField(obj, 'path') ?? '<unknown>'}`,\n {\n offset: numberFromInput(input, 'offset'),\n limit: numberFromInput(input, 'limit'),\n total_lines: obj['total_lines'],\n encoding: obj['encoding'],\n truncated: obj['truncated'],\n cached: obj['cached'],\n note: obj['note'],\n },\n ),\n obj['text'],\n ]);\n }\n\n if (toolName === 'grep' && Array.isArray(obj['matches'])) {\n const matches = stringArrayField(obj, 'matches');\n return joinSections([\n renderHeader(`grep: ${stringFromInput(input, 'pattern') ?? '<pattern>'}`, {\n path: stringFromInput(input, 'path'),\n glob: stringFromInput(input, 'glob'),\n mode: stringFromInput(input, 'output_mode'),\n count: obj['count'],\n shown: matches.length,\n truncated: obj['truncated'],\n used: obj['used'],\n }),\n renderGrepMatches(matches, stringFromInput(input, 'output_mode')),\n ]);\n }\n\n if (toolName === 'patch' && Array.isArray(obj['files'])) {\n const files = stringArrayField(obj, 'files');\n return joinSections([\n renderHeader('patch', {\n applied: obj['applied'],\n rejected: obj['rejected'],\n files: files.length,\n dry_run: obj['dry_run'],\n }),\n typeof obj['message'] === 'string' ? `message:\\n${obj['message']}` : undefined,\n files.length > 0 ? `files:\\n${renderStringList(files)}` : undefined,\n ]);\n }\n\n if (toolName === 'glob' && Array.isArray(obj['files'])) {\n const files = stringArrayField(obj, 'files');\n return joinSections([\n renderHeader(\n `${toolName}: ${stringFromInput(input, 'pattern') ?? stringFromInput(input, 'files') ?? stringFromInput(input, 'path') ?? ''}`.trim(),\n {\n path: stringFromInput(input, 'path'),\n files: files.length,\n truncated: obj['truncated'],\n },\n ),\n renderStringList(files, '(no files)'),\n ]);\n }\n\n if (toolName === 'tree' && typeof obj['tree'] === 'string') {\n return joinSections([\n renderHeader(\n `tree: ${stringField(obj, 'path') ?? stringFromInput(input, 'path') ?? '<cwd>'}`,\n {\n total_files: obj['total_files'],\n total_dirs: obj['total_dirs'],\n truncated: obj['truncated'],\n },\n ),\n obj['tree'],\n ]);\n }\n\n if (toolName === 'fetch' && typeof obj['content'] === 'string') {\n return joinSections([\n renderHeader(\n `fetch: ${stringField(obj, 'url') ?? stringFromInput(input, 'url') ?? '<url>'}`,\n {\n status: obj['status'],\n content_type: obj['content_type'],\n },\n ),\n obj['content'],\n ]);\n }\n\n if (toolName === 'replace' && Array.isArray(obj['results'])) {\n const results = obj['results'].filter(isRecord);\n const sections: Array<string | undefined> = [\n renderHeader('replace', {\n files_modified: obj['files_modified'],\n total_replacements: obj['total_replacements'],\n dry_run: obj['dry_run'],\n }),\n ];\n for (const r of results.slice(0, DEFAULT_LIST_LIMIT)) {\n sections.push(\n joinSections([\n renderHeader(`file: ${stringField(r, 'path') ?? '<unknown>'}`, {\n replacements: r['replacements'],\n }),\n typeof r['diff'] === 'string' ? r['diff'] : undefined,\n ]),\n );\n }\n if (results.length > DEFAULT_LIST_LIMIT) {\n sections.push(`[serializer omitted ${results.length - DEFAULT_LIST_LIMIT} result item(s)]`);\n }\n return joinSections(sections);\n }\n\n if (typeof obj['diff'] === 'string') {\n const diff = obj['diff'];\n return joinSections([\n renderHeader(toolName, {\n path: obj['path'],\n replacements: obj['replacements'],\n bytes_written: obj['bytes_written'],\n created: obj['created'],\n note: obj['note'],\n files: Array.isArray(obj['files']) ? obj['files'].length : undefined,\n truncated: obj['truncated'],\n mode: obj['mode'],\n }),\n compactDiff(diff),\n ]);\n }\n\n if (toolName === 'test' && typeof obj['output'] === 'string') {\n return renderTestOutput(obj, input);\n }\n\n if (\n (toolName === 'typecheck' || toolName === 'lint' || toolName === 'format') &&\n typeof obj['output'] === 'string'\n ) {\n return renderVerifierOutput(toolName, obj, input);\n }\n\n if (hasCommandOutputShape(obj)) {\n return renderCommandOutput(toolName, obj, input);\n }\n\n if (toolName === 'json' && typeof obj['formatted'] === 'string') {\n return joinSections([\n renderHeader('json', {\n type: obj['type'],\n keys: Array.isArray(obj['keys']) ? obj['keys'].length : undefined,\n query: stringFromInput(input, 'query'),\n error: obj['error'],\n }),\n obj['formatted'],\n ]);\n }\n\n if (toolName === 'logs' && Array.isArray(obj['entries'])) {\n const entries = obj['entries'].filter(isRecord);\n const lines = entries.slice(0, LOG_ENTRY_LIMIT).map((entry) => {\n const ts = stringField(entry, 'timestamp') ?? '';\n const level = stringField(entry, 'level') ?? 'info';\n const message = stringField(entry, 'message') ?? '';\n const source = stringField(entry, 'source');\n return [ts, level, source, message].filter(Boolean).join(' ');\n });\n if (entries.length > LOG_ENTRY_LIMIT) {\n lines.push(`[serializer omitted ${entries.length - LOG_ENTRY_LIMIT} log entry item(s)]`);\n }\n return joinSections([\n renderHeader(`logs: ${stringField(obj, 'source') ?? '<source>'}`, {\n total: obj['total'],\n shown: Math.min(entries.length, LOG_ENTRY_LIMIT),\n truncated: obj['truncated'],\n stream_mode: obj['stream_mode'],\n }),\n lines.length > 0 ? lines.join('\\n') : '(no log entries)',\n ]);\n }\n\n if (toolName === 'audit' && Array.isArray(obj['vulnerabilities'])) {\n const vulns = obj['vulnerabilities'].filter(isRecord);\n const lines = vulns.slice(0, DEFAULT_LIST_LIMIT).map((v) => {\n const severity = stringField(v, 'severity') ?? 'unknown';\n const pkg = stringField(v, 'package') ?? '<package>';\n const title = stringField(v, 'title') ?? '';\n const url = stringField(v, 'url');\n return [severity, pkg, title, url].filter(Boolean).join(' | ');\n });\n if (vulns.length > DEFAULT_LIST_LIMIT) {\n lines.push(`[serializer omitted ${vulns.length - DEFAULT_LIST_LIMIT} vulnerability item(s)]`);\n }\n return joinSections([\n renderHeader('audit', {\n exit_code: obj['exit_code'],\n total: obj['total'],\n summary: obj['summary'],\n truncated: obj['truncated'],\n }),\n lines.length > 0 ? lines.join('\\n') : stringField(obj, 'output'),\n ]);\n }\n\n if (toolName === 'outdated' && Array.isArray(obj['packages'])) {\n const packages = obj['packages'].filter(isRecord);\n const lines = packages\n .slice(0, DEFAULT_LIST_LIMIT)\n .map((p) =>\n [\n stringField(p, 'name') ?? '<package>',\n `current=${stringField(p, 'current') ?? 'unknown'}`,\n `wanted=${stringField(p, 'wanted') ?? 'unknown'}`,\n `latest=${stringField(p, 'latest') ?? 'unknown'}`,\n stringField(p, 'type'),\n ]\n .filter(Boolean)\n .join(' | '),\n );\n if (packages.length > DEFAULT_LIST_LIMIT) {\n lines.push(`[serializer omitted ${packages.length - DEFAULT_LIST_LIMIT} package item(s)]`);\n }\n return joinSections([\n renderHeader('outdated', {\n exit_code: obj['exit_code'],\n total: obj['total'],\n truncated: obj['truncated'],\n }),\n lines.length > 0 ? lines.join('\\n') : stringField(obj, 'output'),\n ]);\n }\n\n return undefined;\n}\n\nfunction renderTestOutput(obj: RecordValue, input: unknown): string {\n const exitCode = numberField(obj, 'exit_code') ?? 0;\n const failed = numberField(obj, 'failed') ?? 0;\n const output = stringField(obj, 'output') ?? '';\n const header = renderHeader(`test: ${stringField(obj, 'runner') ?? 'runner'}`, {\n exit_code: obj['exit_code'],\n tests_run: obj['tests_run'],\n passed: obj['passed'],\n failed: obj['failed'],\n duration_ms: obj['duration_ms'],\n truncated: obj['truncated'],\n files: inputListSummary(input, 'files'),\n grep: stringFromInput(input, 'grep'),\n });\n\n if (exitCode === 0 && failed === 0) {\n return joinSections([\n header,\n joinSections([\n 'report:',\n `status=passed`,\n `tests_run=${obj['tests_run'] ?? 0}`,\n `passed=${obj['passed'] ?? 0}`,\n `failed=${obj['failed'] ?? 0}`,\n `duration_ms=${obj['duration_ms'] ?? 0}`,\n extractSpoolNote(output),\n ]),\n ]);\n }\n\n return joinSections([\n header,\n `error_context:\\n${compactFailureOutput(output || '(no runner output)')}`,\n ]);\n}\n\nfunction renderVerifierOutput(toolName: string, obj: RecordValue, input: unknown): string {\n const exitCode = numberField(obj, 'exit_code') ?? 0;\n const errors = numberField(obj, 'errors') ?? 0;\n const warnings = numberField(obj, 'warnings') ?? 0;\n const output = stringField(obj, 'output') ?? '';\n const changed = numberField(obj, 'files_changed') ?? 0;\n const header = renderHeader(toolName, {\n exit_code: obj['exit_code'],\n errors: obj['errors'],\n warnings: obj['warnings'],\n files_checked: obj['files_checked'],\n files_changed: obj['files_changed'],\n fix_applied: obj['fix_applied'],\n fixer: obj['fixer'],\n linter: obj['linter'],\n project: obj['project'],\n truncated: obj['truncated'],\n files: inputListSummary(input, 'files'),\n cwd: stringFromInput(input, 'cwd'),\n });\n\n if (exitCode === 0 && errors === 0 && (toolName !== 'format' || changed === 0)) {\n return joinSections([\n header,\n joinSections([\n 'report:',\n 'status=passed',\n `errors=${errors}`,\n `warnings=${warnings}`,\n toolName === 'format' ? `files_changed=${changed}` : undefined,\n extractSpoolNote(output),\n ]),\n ]);\n }\n\n if (exitCode === 0 && toolName === 'format') {\n return joinSections([\n header,\n joinSections([\n 'report:',\n 'status=changed',\n `files_changed=${changed}`,\n extractSpoolNote(output),\n ]),\n ]);\n }\n\n return joinSections([\n header,\n `error_context:\\n${compactFailureOutput(output || '(no verifier output)')}`,\n ]);\n}\n\nfunction renderGrepMatches(matches: string[], mode: string | undefined): string {\n if (matches.length === 0) return '(no matches)';\n if (mode === 'files_with_matches') return renderStringList(matches, '(no files)');\n if (mode === 'count') return renderStringList(matches, '(no counts)');\n\n const groups = new Map<string, string[]>();\n const passthrough: string[] = [];\n for (const match of matches) {\n const parsed = parseGrepContentLine(match);\n if (!parsed) {\n passthrough.push(match);\n continue;\n }\n const list = groups.get(parsed.file) ?? [];\n list.push(`${parsed.line}:${parsed.text}`);\n groups.set(parsed.file, list);\n }\n\n if (groups.size === 0) return renderStringList(matches, '(no matches)');\n\n const sections: string[] = [];\n let fileIndex = 0;\n for (const [file, lines] of groups) {\n fileIndex++;\n if (fileIndex > GREP_FILE_LIMIT) break;\n const shown = lines.slice(0, GREP_MATCHES_PER_FILE);\n sections.push(\n `${file} (${lines.length} match(es), showing ${shown.length})\\n${shown.join('\\n')}`,\n );\n }\n if (groups.size > GREP_FILE_LIMIT) {\n sections.push(`[serializer omitted ${groups.size - GREP_FILE_LIMIT} file group(s)]`);\n }\n if (passthrough.length > 0) {\n sections.push(`ungrouped:\\n${renderStringList(passthrough, '', 50)}`);\n }\n return sections.join('\\n');\n}\n\nfunction parseGrepContentLine(\n line: string,\n): { file: string; line: string; text: string } | undefined {\n const match = /^(.+?):(\\d+):(.*)$/.exec(line);\n if (!match?.[1] || !match[2]) return undefined;\n return { file: match[1], line: match[2], text: match[3] ?? '' };\n}\n\nfunction compactDiff(diff: string): string {\n const lines = diff.split(/\\r?\\n/);\n if (lines.length <= DIFF_INLINE_LINE_LIMIT) return diff;\n\n const fileCount = Math.max(\n new Set(\n lines\n .map(\n (line) => /^diff --git\\s+a\\/(.+?)\\s+b\\//.exec(line)?.[1] ?? /^---\\s+(.+)/.exec(line)?.[1],\n )\n .filter(Boolean),\n ).size,\n 0,\n );\n const hunks = lines.filter((line) => line.startsWith('@@')).length;\n const added = lines.filter((line) => line.startsWith('+') && !line.startsWith('+++')).length;\n const removed = lines.filter((line) => line.startsWith('-') && !line.startsWith('---')).length;\n const selected = new Set<number>();\n let hunkCount = 0;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? '';\n if (line.startsWith('diff --git') || line.startsWith('--- ') || line.startsWith('+++ ')) {\n selected.add(i);\n continue;\n }\n if (!line.startsWith('@@')) continue;\n if (hunkCount >= DIFF_HUNK_LIMIT) continue;\n hunkCount++;\n for (let j = i; j <= Math.min(lines.length - 1, i + DIFF_HUNK_CONTEXT); j++) {\n selected.add(j);\n }\n }\n\n if (selected.size === 0) {\n return joinSections([\n renderHeader('diff_summary', {\n files: fileCount,\n hunks,\n added,\n removed,\n lines: lines.length,\n }),\n lines.slice(0, DIFF_INLINE_LINE_LIMIT).join('\\n'),\n `[serializer omitted ${Math.max(0, lines.length - DIFF_INLINE_LINE_LIMIT)} diff line(s)]`,\n ]);\n }\n\n const excerpt: string[] = [];\n let previous = -1;\n for (const index of [...selected].sort((a, b) => a - b)) {\n if (index > previous + 1) {\n const omitted = previous === -1 ? index : index - previous - 1;\n excerpt.push(`[serializer omitted ${omitted} diff line(s)]`);\n }\n excerpt.push(lines[index] ?? '');\n previous = index;\n }\n const trailing = lines.length - previous - 1;\n if (trailing > 0) excerpt.push(`[serializer omitted ${trailing} trailing diff line(s)]`);\n\n return joinSections([\n renderHeader('diff_summary', {\n files: fileCount,\n hunks,\n shown_hunks: Math.min(hunks, DIFF_HUNK_LIMIT),\n added,\n removed,\n lines: lines.length,\n }),\n excerpt.join('\\n'),\n ]);\n}\n\nfunction compactFailureOutput(output: string): string {\n const lines = output.split(/\\r?\\n/);\n if (lines.length <= 260) return output.trimEnd();\n\n const selected = new Set<number>();\n const marker =\n /\\b(fail|failed|failure|error|exception|assertionerror|expected|received|actual|timeout|stack)\\b/i;\n let markerHits = 0;\n for (let i = 0; i < lines.length; i++) {\n if (!marker.test(lines[i] ?? '')) continue;\n markerHits++;\n for (let j = Math.max(0, i - 4); j <= Math.min(lines.length - 1, i + 10); j++) {\n selected.add(j);\n }\n }\n\n if (markerHits === 0) {\n return lines.slice(-220).join('\\n').trimEnd();\n }\n\n const ordered = [...selected].sort((a, b) => a - b);\n const out: string[] = [];\n let previous = -1;\n for (const index of ordered) {\n if (index > previous + 1) {\n const omitted = previous === -1 ? index : index - previous - 1;\n out.push(`[serializer omitted ${omitted} line(s)]`);\n }\n out.push(lines[index] ?? '');\n previous = index;\n }\n return out.join('\\n').trimEnd();\n}\n\nfunction extractSpoolNote(output: string): string | undefined {\n return output\n .split(/\\r?\\n/)\n .find((line) => line.startsWith('[output truncated') && line.includes('full'));\n}\n\nfunction hasCommandOutputShape(obj: RecordValue): boolean {\n return (\n typeof obj['stdout'] === 'string' ||\n typeof obj['stderr'] === 'string' ||\n typeof obj['output'] === 'string' ||\n typeof obj['exitCode'] === 'number' ||\n typeof obj['exit_code'] === 'number'\n );\n}\n\nfunction renderCommandOutput(toolName: string, obj: RecordValue, input: unknown): string {\n const command = stringField(obj, 'command') ?? stringFromInput(input, 'command');\n const args = stringArrayField(obj, 'args');\n const commandLine = command ? [command, ...args].join(' ') : undefined;\n const output = stringField(obj, 'output');\n const stdout = stringField(obj, 'stdout');\n const stderr = stringField(obj, 'stderr');\n return joinSections([\n renderHeader(commandLine ? `${toolName}: ${commandLine}` : toolName, {\n exit_code: obj['exit_code'] ?? obj['exitCode'],\n timed_out: obj['timed_out'],\n pid: obj['pid'],\n allowed: obj['allowed'],\n truncated: obj['truncated'],\n runner: obj['runner'],\n linter: obj['linter'],\n fixer: obj['fixer'],\n project: obj['project'],\n tests_run: obj['tests_run'],\n passed: obj['passed'],\n failed: obj['failed'],\n duration_ms: obj['duration_ms'],\n errors: obj['errors'],\n warnings: obj['warnings'],\n files_checked: obj['files_checked'],\n files_changed: obj['files_changed'],\n fix_applied: obj['fix_applied'],\n }),\n stringField(obj, 'error') ? `error:\\n${stringField(obj, 'error')}` : undefined,\n output ? `output:\\n${output}` : undefined,\n stdout ? `stdout:\\n${stdout}` : undefined,\n stderr ? `stderr:\\n${stderr}` : undefined,\n ]);\n}\n\nfunction renderGenericToolObject(toolName: string, obj: RecordValue): string {\n const scalars: RecordValue = {};\n const blocks: string[] = [];\n for (const [key, value] of Object.entries(obj)) {\n if (value === undefined) continue;\n if (isScalar(value)) {\n const inline = String(value);\n if (inline.length <= INLINE_LIMIT && !inline.includes('\\n')) {\n scalars[key] = value;\n } else {\n blocks.push(`${key}:\\n${inline}`);\n }\n continue;\n }\n if (Array.isArray(value)) {\n if (value.every((item) => typeof item === 'string')) {\n blocks.push(`${key}:\\n${renderStringList(value as string[])}`);\n } else {\n blocks.push(`${key}:\\n${renderUnknownList(value)}`);\n }\n continue;\n }\n blocks.push(`${key}: ${clipInline(oneLineJson(value))}`);\n }\n return joinSections([renderHeader(toolName, scalars), ...blocks]);\n}\n\nfunction renderHeader(label: string, fields: RecordValue): string {\n const parts = Object.entries(fields)\n .filter(([, value]) => value !== undefined && value !== null && value !== '')\n .map(([key, value]) => `${key}=${clipInline(formatInlineValue(value))}`);\n return parts.length > 0 ? `${label} (${parts.join(' ')})` : label;\n}\n\nfunction renderStringList(items: string[], empty = '', limit = DEFAULT_LIST_LIMIT): string {\n if (items.length === 0) return empty;\n const shown = items.slice(0, limit);\n const omitted = items.length - shown.length;\n return [\n ...shown,\n ...(omitted > 0\n ? [`[serializer omitted ${omitted} item(s); narrow the request for more]`]\n : []),\n ].join('\\n');\n}\n\nfunction renderUnknownList(items: unknown[], limit = DEFAULT_LIST_LIMIT): string {\n const shown = items.slice(0, limit).map((item) => clipInline(oneLineJson(item), 1_000));\n const omitted = items.length - shown.length;\n if (omitted > 0)\n shown.push(`[serializer omitted ${omitted} item(s); narrow the request for more]`);\n return shown.join('\\n');\n}\n\nfunction joinSections(sections: Array<string | undefined>): string {\n return sections\n .map((section) => (typeof section === 'string' ? section.trimEnd() : undefined))\n .filter((section): section is string => !!section)\n .join('\\n');\n}\n\nfunction formatInlineValue(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(formatInlineValue).join(',')}]`;\n if (isScalar(value)) return String(value);\n return oneLineJson(value);\n}\n\nfunction clipInline(value: string, max = INLINE_LIMIT): string {\n const compact = value.replace(/\\s+/g, ' ').trim();\n return compact.length <= max\n ? compact\n : `${compact.slice(0, max - 15)}...(${compact.length} chars)`;\n}\n\nfunction oneLineJson(value: unknown): string {\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nfunction stringField(obj: RecordValue, key: string): string | undefined {\n const value = obj[key];\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction numberField(obj: RecordValue, key: string): number | undefined {\n const value = obj[key];\n return typeof value === 'number' ? value : undefined;\n}\n\nfunction stringArrayField(obj: RecordValue, key: string): string[] {\n const value = obj[key];\n return Array.isArray(value)\n ? value.filter((item): item is string => typeof item === 'string')\n : [];\n}\n\nfunction stringFromInput(input: unknown, key: string): string | undefined {\n if (!isRecord(input)) return undefined;\n const value = input[key];\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction numberFromInput(input: unknown, key: string): number | undefined {\n if (!isRecord(input)) return undefined;\n const value = input[key];\n return typeof value === 'number' ? value : undefined;\n}\n\nfunction inputListSummary(input: unknown, key: string): string | undefined {\n if (!isRecord(input)) return undefined;\n const value = input[key];\n if (typeof value === 'string') return value;\n if (Array.isArray(value)) return value.filter((item) => typeof item === 'string').join(',');\n return undefined;\n}\n\nfunction isRecord(value: unknown): value is RecordValue {\n return !!value && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isScalar(value: unknown): value is string | number | boolean | null {\n return value === null || ['string', 'number', 'boolean'].includes(typeof value);\n}\n\n/**\n * Render a tool result body for inclusion in the `tool.executed` event.\n * Tool outputs can be large (file dumps, command output); UIs only want a\n * preview line, so cap at ~400 chars with an ellipsis marker.\n */\nexport function truncateForEvent(content: string, max = 400): string {\n if (!content) return '';\n return content.length <= max ? content : `${content.slice(0, max - 1)}…`;\n}\n\n/**\n * Derive size signals (bytes / tokens / lines) for the chip rendered beside\n * each tool result. Computed once over the FULL `content` BEFORE the\n * 400-char event preview is taken.\n *\n * - bytes: UTF-8 byte length (multi-byte aware).\n * - tokens: standard ~3.5 chars/token heuristic.\n * - lines: read prefixes lines with `<n>→`; for shell/grep/logs we fall\n * back to a newline count. Undefined for tools without a line notion.\n */\nexport function sizeSignals(\n toolName: string | undefined,\n content: string,\n): { outputBytes: number; outputTokens: number; outputLines: number | undefined } {\n if (!content || content.length === 0) {\n return { outputBytes: 0, outputTokens: 0, outputLines: undefined };\n }\n const outputBytes = Buffer.byteLength(content, 'utf8');\n const outputTokens = Math.max(1, Math.round(outputBytes / 3.5));\n let outputLines: number | undefined;\n if (toolName === 'read') {\n const lineRe = /^\\s*\\d+→/gm;\n let count = 0;\n while (lineRe.exec(content) !== null) count++;\n if (count > 0) outputLines = count;\n } else if (\n toolName === 'bash' ||\n toolName === 'shell' ||\n toolName === 'grep' ||\n toolName === 'logs'\n ) {\n let nl = 0;\n for (let i = 0; i < content.length; i++) if (content.charCodeAt(i) === 10) nl++;\n outputLines = nl + (content.endsWith('\\n') ? 0 : 1);\n }\n return { outputBytes, outputTokens, outputLines };\n}\n","import { createHash } from 'node:crypto';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\n\n/**\n * Path layout. All developer-level state lives in ~/.wrongstack/.\n * Per-project state is keyed by sha256(absoluteProjectRoot).slice(0,12)\n * under ~/.wrongstack/projects/<hash>/.\n *\n * The ONLY thing inside the project tree is the optional\n * .wrongstack/AGENTS.md (committed) and .wrongstack/skills/ (committed).\n */\n\nexport interface WstackPaths {\n /** ~/.wrongstack — global root. */\n globalRoot: string;\n /**\n * ~/.wrongstack — directory for user-global stateful config files\n * (mode.json, theme.json, …). Currently an alias for `globalRoot`;\n * separate name lets us split out per-OS XDG_CONFIG_HOME later\n * without rewriting callers.\n */\n configDir: string;\n /** ~/.wrongstack/config.json */\n globalConfig: string;\n /** ~/.wrongstack/.key — 32 random bytes, mode 0600, AES-GCM key for the secret vault. */\n secretsKey: string;\n /** ~/.wrongstack/memory.md — user-global memory. */\n globalMemory: string;\n /** ~/.wrongstack/skills — user-global skills. */\n globalSkills: string;\n /** ~/.wrongstack/prompts — user-global prompt library. */\n globalPrompts: string;\n /** ~/.wrongstack/cache — fetched data (models.dev, etc.). */\n cacheDir: string;\n /** ~/.wrongstack/cache/models.dev.json */\n modelsCache: string;\n /** ~/.wrongstack/cache/models-overlay.json — cached curated overlay. */\n modelsOverlayCache: string;\n /**\n * Per-project codebase symbol index (SQLite). Lives under the global project\n * dir — NOT inside the repo — so it never clutters the working tree or needs\n * gitignoring. `~/.wrongstack/projects/<hash>/codebase-index`.\n */\n projectCodebaseIndex: string;\n /** ~/.wrongstack/history — REPL line history. */\n historyFile: string;\n /** ~/.wrongstack/logs/wrongstack.log */\n logFile: string;\n /** ~/.wrongstack/projects/<hash> */\n projectDir: string;\n /** ~/.wrongstack/projects/<hash>/memory.md */\n projectMemory: string;\n /** ~/.wrongstack/projects/<hash>/sessions */\n projectSessions: string;\n /** ~/.wrongstack/projects/<hash>/trust.json */\n projectTrust: string;\n /** ~/.wrongstack/projects/<hash>/meta.json */\n projectMeta: string;\n /** ~/.wrongstack/projects/<hash>/config.local.json — optional override */\n projectLocalConfig: string;\n /** <project>/.wrongstack/config.json — per-project settings (safe fields only).\n * This lives inside the project root so it can be gitignored or shared. */\n inProjectConfig: string;\n /** <project>/.wrongstack/AGENTS.md — committed project memory. */\n inProjectAgentsFile: string;\n /** <project>/.wrongstack/skills — committed project skills. */\n inProjectSkills: string;\n /** <project>/.wrongstack/worktrees — git worktrees for per-phase isolation (gitignored). */\n inProjectWorktrees: string;\n /** Stable hash for the project root. */\n projectHash: string;\n /** Human-readable project slug: `wrongstack-a1b2c3` instead of `3024e5e6fa58`. */\n projectSlug: string;\n /** ~/.wrongstack/projects/<hash>/goal.json — goal persistence */\n projectGoal: string;\n /** ~/.wrongstack/projects/<hash>/specs — SDD spec files */\n projectSpecs: string;\n /** ~/.wrongstack/projects/<hash>/task-graphs — SDD task graphs */\n projectTaskGraphs: string;\n /** ~/.wrongstack/projects/<hash>/sdd-session.json — SDD session state */\n projectSddSession: string;\n /** ~/.wrongstack/projects/<hash>/plan.json — plan persistence */\n projectPlan: string;\n /** ~/.wrongstack/projects/<hash>/autophase — AutoPhase phase-graph JSON files */\n projectAutophase: string;\n /** ~/.wrongstack/sync.json — CloudSync configuration */\n syncConfig: string;\n /** Function to get the status.json path for a project given its hash. */\n projectStatus: (projectHash: string) => string;\n}\n\nexport function projectHash(absRoot: string): string {\n return createHash('sha256').update(path.resolve(absRoot)).digest('hex').slice(0, 12);\n}\n\n/**\n * Human-readable project directory name: slugified folder name + short hash\n * suffix for uniqueness. e.g. `wrongstack-a1b2c3` instead of `3024e5e6fa58`.\n */\nexport function projectSlug(absRoot: string): string {\n const base = slugify(path.basename(absRoot));\n const hash = createHash('sha256').update(path.resolve(absRoot)).digest('hex').slice(0, 6);\n return `${base}-${hash}`;\n}\n\n/** Turn a folder name into a filesystem-safe lowercase slug. */\nfunction slugify(name: string): string {\n return (\n name\n .toLowerCase()\n // Collapse any run of non-alphanumeric chars into a single hyphen.\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 40) || 'project'\n );\n}\n\nexport interface WstackPathOptions {\n userHome?: string | undefined;\n projectRoot: string;\n /** Override the global root (e.g. for tests). Default: `${userHome}/.wrongstack`. */\n globalRoot?: string | undefined;\n}\n\n/**\n * The global `~/.wrongstack` root, honoring the `WRONGSTACK_HOME` env\n * override. The override exists so tests (and sandboxed runs) can redirect\n * ALL global state — config, secrets, logs, projects/, mailboxes — away from\n * the real user home. Before it existed, `pnpm test` booted runtimes against\n * the real `~/.wrongstack`: it read the user's real config.json (starting a\n * second live Telegram poller), appended to the real wrongstack.log, and left\n * ~20k orphaned fixture dirs under projects/.\n *\n * Every code path that wants the global dir must come through here (or\n * through `resolveWstackPaths`) instead of `path.join(os.homedir(), '.wrongstack')`.\n */\nexport function wstackGlobalRoot(): string {\n const fromEnv = process.env['WRONGSTACK_HOME'];\n if (fromEnv && fromEnv.trim().length > 0) return path.resolve(fromEnv);\n return path.join(os.homedir(), '.wrongstack');\n}\n\nexport function resolveWstackPaths(opts: WstackPathOptions): WstackPaths {\n // Precedence: explicit globalRoot > explicit userHome (callers/tests that\n // pass one expect paths under it) > WRONGSTACK_HOME env > real home dir.\n const globalRoot =\n opts.globalRoot ?? (opts.userHome ? path.join(opts.userHome, '.wrongstack') : wstackGlobalRoot());\n const hash = projectHash(opts.projectRoot);\n const slug = projectSlug(opts.projectRoot);\n const projectDir = path.join(globalRoot, 'projects', slug);\n return {\n globalRoot,\n configDir: globalRoot,\n globalConfig: path.join(globalRoot, 'config.json'),\n secretsKey: path.join(globalRoot, '.key'),\n globalMemory: path.join(globalRoot, 'memory.md'),\n globalSkills: path.join(globalRoot, 'skills'),\n globalPrompts: path.join(globalRoot, 'prompts'),\n cacheDir: path.join(globalRoot, 'cache'),\n modelsCache: path.join(globalRoot, 'cache', 'models.dev.json'),\n modelsOverlayCache: path.join(globalRoot, 'cache', 'models-overlay.json'),\n historyFile: path.join(globalRoot, 'history'),\n logFile: path.join(globalRoot, 'logs', 'wrongstack.log'),\n projectDir,\n projectCodebaseIndex: path.join(projectDir, 'codebase-index'),\n projectMemory: path.join(projectDir, 'memory.md'),\n projectSessions: path.join(projectDir, 'sessions'),\n projectTrust: path.join(projectDir, 'trust.json'),\n projectMeta: path.join(projectDir, 'meta.json'),\n projectLocalConfig: path.join(projectDir, 'config.local.json'),\n inProjectConfig: path.join(opts.projectRoot, '.wrongstack', 'config.json'),\n inProjectAgentsFile: path.join(opts.projectRoot, '.wrongstack', 'AGENTS.md'),\n inProjectSkills: path.join(opts.projectRoot, '.wrongstack', 'skills'),\n inProjectWorktrees: path.join(opts.projectRoot, '.wrongstack', 'worktrees'),\n projectHash: hash,\n projectSlug: slug,\n projectGoal: path.join(projectDir, 'goal.json'),\n projectSpecs: path.join(projectDir, 'specs'),\n projectTaskGraphs: path.join(projectDir, 'task-graphs'),\n projectSddSession: path.join(projectDir, 'sdd-session.json'),\n projectPlan: path.join(projectDir, 'plan.json'),\n projectAutophase: path.join(projectDir, 'autophase'),\n syncConfig: path.join(globalRoot, 'sync.json'),\n projectStatus: (projectHash: string) => path.join(globalRoot, 'projects', projectHash, 'status.json'),\n };\n}\n","import { toErrorMessage } from '../utils/index.js';\n\n/**\n * WrongStack error hierarchy.\n *\n * Every error thrown by the framework is a `WrongStackError` with a\n * machine-readable `code`, a `subsystem` tag, and a `severity` level.\n * This lets consumers (CLI, TUI, plugins, tests) branch on structured\n * data instead of parsing error messages.\n */\n\n// ── Error codes ──────────────────────────────────────────────────────\n\n/**\n * Machine-readable error codes as frozen constants.\n *\n * Use `ERROR_CODES.X` instead of raw string literals for:\n * - IDE autocomplete and compile-time validation\n * - Safe refactoring (rename updates all usages)\n * - Plugin extensibility (extend the object to add custom codes)\n *\n * The `ErrorCode` type is derived from this object, so adding a new\n * code here automatically updates the type without extra changes.\n */\nexport const ERROR_CODES = {\n // Provider\n PROVIDER_RATE_LIMITED: 'PROVIDER_RATE_LIMITED',\n PROVIDER_AUTH_FAILED: 'PROVIDER_AUTH_FAILED',\n PROVIDER_OVERLOADED: 'PROVIDER_OVERLOADED',\n PROVIDER_INVALID_REQUEST: 'PROVIDER_INVALID_REQUEST',\n PROVIDER_SERVER_ERROR: 'PROVIDER_SERVER_ERROR',\n PROVIDER_NETWORK_ERROR: 'PROVIDER_NETWORK_ERROR',\n PROVIDER_CONTEXT_OVERFLOW: 'PROVIDER_CONTEXT_OVERFLOW',\n // Tool\n TOOL_NOT_FOUND: 'TOOL_NOT_FOUND',\n TOOL_PERMISSION_DENIED: 'TOOL_PERMISSION_DENIED',\n TOOL_EXECUTION_FAILED: 'TOOL_EXECUTION_FAILED',\n TOOL_TIMEOUT: 'TOOL_TIMEOUT',\n TOOL_INPUT_INVALID: 'TOOL_INPUT_INVALID',\n // Config\n CONFIG_INVALID: 'CONFIG_INVALID',\n CONFIG_NOT_FOUND: 'CONFIG_NOT_FOUND',\n CONFIG_PARSE_FAILED: 'CONFIG_PARSE_FAILED',\n CONFIG_MIGRATION_NEEDED: 'CONFIG_MIGRATION_NEEDED',\n // Plugin\n PLUGIN_LOAD_FAILED: 'PLUGIN_LOAD_FAILED',\n PLUGIN_API_MISMATCH: 'PLUGIN_API_MISMATCH',\n PLUGIN_MISSING_DEPENDENCY: 'PLUGIN_MISSING_DEPENDENCY',\n // Agent\n AGENT_ITERATION_LIMIT: 'AGENT_ITERATION_LIMIT',\n AGENT_CONTEXT_OVERFLOW: 'AGENT_CONTEXT_OVERFLOW',\n AGENT_ABORTED: 'AGENT_ABORTED',\n AGENT_RUN_FAILED: 'AGENT_RUN_FAILED',\n // Session\n SESSION_NOT_FOUND: 'SESSION_NOT_FOUND',\n SESSION_CORRUPTED: 'SESSION_CORRUPTED',\n SESSION_WRITE_FAILED: 'SESSION_WRITE_FAILED',\n // Container / Registry\n CONTAINER_TOKEN_ALREADY_BOUND: 'CONTAINER_TOKEN_ALREADY_BOUND',\n CONTAINER_TOKEN_NOT_BOUND: 'CONTAINER_TOKEN_NOT_BOUND',\n CONTAINER_CIRCULAR_DEPENDENCY: 'CONTAINER_CIRCULAR_DEPENDENCY',\n REGISTRY_DUPLICATE: 'REGISTRY_DUPLICATE',\n REGISTRY_NOT_FOUND: 'REGISTRY_NOT_FOUND',\n REGISTRY_INVALID: 'REGISTRY_INVALID',\n // File system\n FS_READ_FAILED: 'FS_READ_FAILED',\n FS_WRITE_FAILED: 'FS_WRITE_FAILED',\n FS_MKDIR_FAILED: 'FS_MKDIR_FAILED',\n FS_DELETE_FAILED: 'FS_DELETE_FAILED',\n FS_ATOMIC_WRITE_FAILED: 'FS_ATOMIC_WRITE_FAILED',\n // SDD (Spec-Driven Development)\n SDD_VALIDATION_FAILED: 'SDD_VALIDATION_FAILED',\n SDD_PARSE_FAILED: 'SDD_PARSE_FAILED',\n SDD_INVALID_STATE: 'SDD_INVALID_STATE',\n SDD_NOT_READY: 'SDD_NOT_READY',\n // General\n VALIDATION_ERROR: 'VALIDATION_ERROR',\n UNKNOWN: 'UNKNOWN',\n} as const;\n\n/**\n * Union type derived from `ERROR_CODES`. Using `typeof ERROR_CODES[keyof typeof ERROR_CODES]`\n * instead of a string literal union means TypeScript auto-updates the type whenever\n * a new code is added to `ERROR_CODES` — no need to keep two lists in sync.\n */\nexport type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];\n\nexport type ErrorSubsystem =\n | 'provider'\n | 'tool'\n | 'config'\n | 'plugin'\n | 'agent'\n | 'session'\n | 'sdd'\n | 'container'\n | 'fs'\n | 'general';\nexport type ErrorSeverity = 'fatal' | 'error' | 'warning';\n\n// ── Base error class ─────────────────────────────────────────────────\n\nexport class WrongStackError extends Error {\n readonly code: ErrorCode;\n readonly subsystem: ErrorSubsystem;\n readonly severity: ErrorSeverity;\n readonly recoverable: boolean;\n readonly context?: Record<string, unknown> | undefined;\n\n constructor(opts: {\n message: string;\n code: ErrorCode;\n subsystem: ErrorSubsystem;\n severity?: ErrorSeverity | undefined;\n recoverable?: boolean | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super(opts.message, { cause: opts.cause });\n this.name = 'WrongStackError';\n this.code = opts.code;\n this.subsystem = opts.subsystem;\n this.severity = opts.severity ?? 'error';\n this.recoverable = opts.recoverable ?? false;\n this.context = opts.context;\n }\n\n /**\n * Render a one-line user-facing description.\n * Subclasses should override for domain-specific formatting.\n */\n describe(): string {\n const ctx = this.context ? ` ${formatContext(this.context)}` : '';\n return `${this.code}: ${this.message}${ctx}`;\n }\n}\n\nfunction formatContext(ctx: Record<string, unknown>): string {\n const parts = Object.entries(ctx)\n .filter(([, v]) => v !== undefined)\n .slice(0, 3)\n .map(([k, v]) => `${k}=${String(v)}`);\n return parts.length > 0 ? `[${parts.join(' ')}]` : '';\n}\n\n// ── Specific error classes ───────────────────────────────────────────\n\n/**\n * Tool execution errors — thrown by ToolExecutor and individual tools.\n */\nexport class ToolError extends WrongStackError {\n readonly toolName: string;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n | 'TOOL_NOT_FOUND'\n | 'TOOL_PERMISSION_DENIED'\n | 'TOOL_EXECUTION_FAILED'\n | 'TOOL_TIMEOUT'\n | 'TOOL_INPUT_INVALID'\n >;\n toolName: string;\n recoverable?: boolean | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'tool',\n recoverable: opts.recoverable,\n context: { tool: opts.toolName, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'ToolError';\n this.toolName = opts.toolName;\n }\n}\n\n/**\n * Config loading / validation errors.\n */\nexport class ConfigError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'CONFIG_INVALID' | 'CONFIG_NOT_FOUND' | 'CONFIG_PARSE_FAILED' | 'CONFIG_MIGRATION_NEEDED'\n >;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'config',\n severity: 'fatal',\n recoverable: false,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'ConfigError';\n }\n}\n\n/**\n * Plugin loading / lifecycle errors.\n */\nexport class PluginError extends WrongStackError {\n readonly pluginName: string;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'PLUGIN_LOAD_FAILED' | 'PLUGIN_API_MISMATCH' | 'PLUGIN_MISSING_DEPENDENCY'\n >;\n pluginName: string;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'plugin',\n severity: 'error',\n recoverable: opts.code === ERROR_CODES.PLUGIN_MISSING_DEPENDENCY,\n context: { plugin: opts.pluginName, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'PluginError';\n this.pluginName = opts.pluginName;\n }\n}\n\n/**\n * Agent runtime errors — thrown by Agent.run when a non-WrongStackError\n * escapes the inner loop, so callers always see a structured error.\n */\nexport class AgentError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'AGENT_ITERATION_LIMIT' | 'AGENT_CONTEXT_OVERFLOW' | 'AGENT_ABORTED' | 'AGENT_RUN_FAILED'\n >;\n recoverable?: boolean | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'agent',\n severity: opts.code === ERROR_CODES.AGENT_ABORTED ? 'warning' : 'error',\n recoverable: opts.recoverable ?? opts.code === ERROR_CODES.AGENT_ITERATION_LIMIT,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'AgentError';\n }\n}\n\n/**\n * Wrap an arbitrary thrown value into a `WrongStackError` so the caller\n * always gets a structured error. Pass-throughs WrongStackError instances\n * unchanged; raw `Error`s and primitives get an `AGENT_RUN_FAILED` wrapper\n * with the original preserved as `cause`.\n */\nexport function toWrongStackError(\n err: unknown,\n code: Extract<ErrorCode, 'AGENT_RUN_FAILED' | 'AGENT_ABORTED' | 'UNKNOWN'> = ERROR_CODES.AGENT_RUN_FAILED,\n): WrongStackError {\n if (err instanceof WrongStackError) return err;\n const message = toErrorMessage(err);\n return new AgentError({\n message,\n code: code === 'UNKNOWN' ? ERROR_CODES.AGENT_RUN_FAILED : code,\n cause: err,\n });\n}\n\n/**\n * Session storage errors.\n */\nexport class SessionError extends WrongStackError {\n readonly sessionId?: string | undefined;\n\n constructor(opts: {\n message: string;\n code: Extract<ErrorCode, 'SESSION_NOT_FOUND' | 'SESSION_CORRUPTED' | 'SESSION_WRITE_FAILED'>;\n sessionId?: string | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'session',\n severity: opts.code === ERROR_CODES.SESSION_WRITE_FAILED ? 'error' : 'warning',\n recoverable: opts.code !== ERROR_CODES.SESSION_CORRUPTED,\n context: { sessionId: opts.sessionId, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'SessionError';\n this.sessionId = opts.sessionId;\n }\n}\n\n/**\n * SDD (Spec-Driven Development) errors — spec validation, parsing, and\n * state machine violations in the AISpecBuilder, TaskFlow, and TaskTracker.\n */\nexport class SddError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'SDD_VALIDATION_FAILED' | 'SDD_PARSE_FAILED' | 'SDD_INVALID_STATE' | 'SDD_NOT_READY'\n >;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'sdd',\n severity: opts.code === ERROR_CODES.SDD_PARSE_FAILED ? 'warning' : 'error',\n recoverable: opts.code === ERROR_CODES.SDD_NOT_READY,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'SddError';\n }\n}\n\n/**\n * File system operation errors.\n */\nexport class FsError extends WrongStackError {\n readonly path?: string | undefined;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'FS_READ_FAILED' | 'FS_WRITE_FAILED' | 'FS_MKDIR_FAILED' | 'FS_DELETE_FAILED' | 'FS_ATOMIC_WRITE_FAILED'\n >;\n path?: string | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'fs',\n severity: 'error',\n recoverable: opts.code !== ERROR_CODES.FS_READ_FAILED,\n context: { path: opts.path, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'FsError';\n this.path = opts.path;\n }\n}\n\n// ── Type guards ──────────────────────────────────────────────────────\n\nexport function isWrongStackError(err: unknown): err is WrongStackError {\n return err instanceof WrongStackError;\n}\n\nexport function isToolError(err: unknown): err is ToolError {\n return err instanceof ToolError;\n}\n\nexport function isConfigError(err: unknown): err is ConfigError {\n return err instanceof ConfigError;\n}\n\nexport function isPluginError(err: unknown): err is PluginError {\n return err instanceof PluginError;\n}\n\nexport function isSessionError(err: unknown): err is SessionError {\n return err instanceof SessionError;\n}\n\nexport function isAgentError(err: unknown): err is AgentError {\n return err instanceof AgentError;\n}\n\nexport function isFsError(err: unknown): err is FsError {\n return err instanceof FsError;\n}\n\nexport function isSddError(err: unknown): err is SddError {\n return err instanceof SddError;\n}\n","import type { Context } from '../core/context.js';\nimport type { EventBus } from '../kernel/events.js';\nimport type { MiddlewareHandler } from '../kernel/pipeline.js';\nimport type { SessionEventBridge } from '../storage/session-event-bridge.js';\nimport type { CompactReport, Compactor } from '../types/compactor.js';\nimport type { ContextWindowAggressiveOn, ContextWindowPolicy } from '../types/context-window.js';\nimport { AgentError, ERROR_CODES } from '../types/errors.js';\nimport {\n estimateRequestTokensCalibrated,\n getCalibrationState,\n} from '../utils/token-estimate.js';\nimport { repeatedReadPressure } from '../utils/context-evidence.js';\n\ntype PressureLevel = 'warn' | 'soft' | 'hard';\nconst LEVEL_RANK: Record<PressureLevel, number> = { warn: 0, soft: 1, hard: 2 };\n\nexport interface ContextWindowBudgetSnapshot {\n maxContext: number;\n inputTokens: number;\n availableInputTokens: number;\n remainingInputTokens: number;\n reservedOutputTokens: number;\n reservedSafetyTokens: number;\n load: number;\n overflowTokens: number;\n}\n\n/** Max chars of collapse digest persisted to the session log line. */\nconst MAX_DIGEST_LOG_CHARS = 4_000;\n\nfunction truncateDigest(digest: string): string {\n if (digest.length <= MAX_DIGEST_LOG_CHARS) return digest;\n return `${digest.slice(0, MAX_DIGEST_LOG_CHARS)}… [+${digest.length - MAX_DIGEST_LOG_CHARS} chars; full turns in session log]`;\n}\n\nexport type CompactionFailureMode = 'throw' | 'throw_on_hard' | 'continue';\n\nexport interface AutoCompactionOptions {\n aggressiveOn?: ContextWindowAggressiveOn | undefined;\n events?: EventBus | undefined;\n failureMode?: CompactionFailureMode | undefined;\n policyProvider?: (ctx: Context) => Pick<\n ContextWindowPolicy,\n 'thresholds' | 'aggressiveOn'\n > | null | undefined;\n /** Optional bridge for writing compaction events into the persistent session log. */\n sessionBridge?: SessionEventBridge | undefined;\n}\n\n/**\n * Pipeline middleware that monitors context token load and automatically\n * triggers compaction when the warn/soft/hard thresholds are crossed.\n * Runs before the next agent iteration.\n *\n * Uses `estimateRequestTokens` for accurate full-request token counting:\n * messages + systemPrompt + toolDefs. This replaces the previous pattern\n * of applying an OVERHEAD_FACTOR to a messages-only estimate.\n */\nexport class AutoCompactionMiddleware {\n readonly name = 'AutoCompaction';\n\n private readonly compactor: Compactor;\n /** Deprecated. Kept for backward compat with tests that pass simpleEstimator. */\n private readonly _estimator?: (((ctx: Context) => number)) | undefined;\n private readonly warnThreshold: number;\n private readonly softThreshold: number;\n private readonly hardThreshold: number;\n /** Writable so model-switch can update the denominator without re-registering the middleware. */\n private _maxContext: number;\n /**\n * Runtime on/off gate. The middleware is always installed in the pipeline so\n * auto-compaction can be toggled live from the TUI `/settings` picker; when\n * disabled the handler is a pass-through. Defaults to enabled.\n */\n private _enabled = true;\n private readonly aggressiveOn: ContextWindowAggressiveOn;\n private readonly events?: EventBus | undefined;\n private readonly failureMode: CompactionFailureMode;\n private readonly policyProvider?: AutoCompactionOptions['policyProvider'] | undefined;\n private readonly sessionBridge?: SessionEventBridge | undefined;\n\n /**\n * Once a compaction attempt reduces nothing (preserveK protects everything,\n * no oversized tool_results remain to elide), retrying on every iteration\n * just spams `compaction.fired` events without making progress. We remember\n * the no-op and skip until either the pressure level escalates or context\n * has grown by at least this many tokens since the failed attempt.\n */\n private static readonly NOOP_RETRY_DELTA_TOKENS = 2_000;\n\n /** Tracks the most recent no-op attempt so we can avoid re-firing per turn. */\n private lastNoopAttempt: { level: PressureLevel; tokens: number } | null = null;\n\n /**\n * Cached token estimate from the last handler() invocation. When the\n * message count and tool count haven't changed since the last estimate\n * (autonomous idle loops), we skip the expensive O(n) token estimation\n * and reuse this value. Reset to -1 when the context changes.\n */\n private _cachedTokens = -1;\n private _cachedMsgCount = -1;\n private _cachedToolCount = -1;\n\n /**\n * @param compactor Compactor to use for compaction.\n * @param maxContext Provider's max context window in tokens.\n * @param _estimator Deprecated parameter kept for backward compatibility.\n * The middleware now uses `estimateRequestTokens` internally\n * for accurate full-request token counting (messages +\n * systemPrompt + toolDefs).\n * @param thresholds Threshold fractions (0-1) of maxContext.\n * @param opts Optional behavior. By default, failures at the\n * hard threshold throw AGENT_CONTEXT_OVERFLOW so\n * the agent does not continue into a likely\n * provider context overflow. Warn/soft failures\n * still emit compaction.failed and continue.\n */\n constructor(\n compactor: Compactor,\n maxContext: number,\n _estimator: (ctx: Context) => number,\n thresholds: { warn: number; soft: number; hard: number },\n optsOrAggressiveOn: AutoCompactionOptions | ContextWindowAggressiveOn = {},\n events?: EventBus | undefined,\n ) {\n const opts =\n typeof optsOrAggressiveOn === 'string'\n ? { aggressiveOn: optsOrAggressiveOn, events }\n : optsOrAggressiveOn;\n this.compactor = compactor;\n this._maxContext = maxContext;\n this._estimator = _estimator;\n this.warnThreshold = thresholds.warn;\n this.softThreshold = thresholds.soft;\n this.hardThreshold = thresholds.hard;\n this.aggressiveOn = opts.aggressiveOn ?? 'soft';\n this.events = opts.events;\n this.failureMode = opts.failureMode ?? 'throw_on_hard';\n this.policyProvider = opts.policyProvider;\n this.sessionBridge = opts.sessionBridge;\n }\n\n /** Allow callers (e.g. model-switch in WebUI) to update the context window\n * denominator when the active model changes. */\n setMaxContext(maxContext: number): void {\n this._maxContext = maxContext;\n }\n\n /** Whether auto-compaction is currently active. */\n get enabled(): boolean {\n return this._enabled;\n }\n\n /** Toggle auto-compaction on a live session (TUI `/settings`). When disabled\n * the middleware passes every iteration straight through without estimating\n * tokens or compacting. */\n setEnabled(enabled: boolean): void {\n this._enabled = enabled;\n }\n\n handler(): MiddlewareHandler<Context> {\n return async (ctx, next) => {\n // Runtime gate — when auto-compaction is turned off via /settings the\n // middleware stays installed but does nothing.\n if (!this._enabled) return next(ctx);\n // Reuse the last token estimate when the context hasn't grown since\n // the previous check — common in autonomous idle loops. The cached\n // value is invalidated whenever messages or tools change.\n //\n // IMPORTANT: the cache is only valid for the deterministic\n // estimateRequestTokensCalibrated path (messages+system+tools → fixed\n // output). When a custom _estimator is provided (e.g. in tests with\n // a mutable closure, or a dynamic policy provider), always call it\n // fresh — the estimator owns its own semantics and the middleware\n // cannot safely cache its result across calls.\n const msgCount = ctx.messages.length;\n const toolCount = (ctx.tools ?? []).length;\n\n let tokens: number;\n if (this._estimator) {\n // Custom estimator — never cache; call fresh every invocation.\n tokens = this._estimator(ctx);\n } else if (\n msgCount === this._cachedMsgCount &&\n toolCount === this._cachedToolCount &&\n this._cachedTokens >= 0\n ) {\n // Default estimator, context unchanged — reuse cached value.\n tokens = this._cachedTokens;\n } else if (this.tryStashedTokens(ctx, msgCount, toolCount) !== null) {\n // H1: the agent loop's pre-flight (or its restash in emitContextPct)\n // populated `ctx.lastRequestTokens` this iteration. Apply the\n // per-(provider,model) calibration ratio and use it. This avoids\n // a third redundant O(n) walk per iteration.\n const stashed = this.tryStashedTokens(ctx, msgCount, toolCount) as number;\n const cal = getCalibrationState(`${ctx.provider?.id ?? 'unknown'}/${ctx.model}`);\n tokens = cal.calibrated\n ? Math.round(stashed * Math.min(1.5, Math.max(0.5, cal.ratio)))\n : stashed;\n this._cachedTokens = tokens;\n this._cachedMsgCount = msgCount;\n this._cachedToolCount = toolCount;\n } else {\n // Default estimator, context changed and no stash — compute fresh\n // and cache. Cold-start path: very first iteration, or the\n // middleware is being driven from somewhere that didn't run the\n // agent loop's pre-flight (tests, manual compaction trigger).\n tokens = estimateRequestTokensCalibrated(\n ctx.messages,\n ctx.systemPrompt,\n ctx.tools ?? [],\n `${ctx.provider?.id ?? 'unknown'}/${ctx.model}`,\n ).total;\n this._cachedTokens = tokens;\n this._cachedMsgCount = msgCount;\n this._cachedToolCount = toolCount;\n }\n const budget = computeContextWindowBudget(ctx, tokens, this._maxContext);\n const load = budget.load;\n const policy = this.policyProvider?.(ctx);\n const thresholds = policy?.thresholds ?? {\n warn: this.warnThreshold,\n soft: this.softThreshold,\n hard: this.hardThreshold,\n };\n const repetition = repeatedReadPressure(ctx);\n const adaptiveThresholds = adaptThresholdsForSignals(thresholds, {\n repeatedReadCount: repetition,\n });\n const aggressiveOn = policy?.aggressiveOn ?? this.aggressiveOn;\n\n const level: PressureLevel | null =\n load >= adaptiveThresholds.hard\n ? 'hard'\n : load >= adaptiveThresholds.soft\n ? 'soft'\n : load >= adaptiveThresholds.warn\n ? 'warn'\n : null;\n\n if (!level) {\n // Load dropped back below all thresholds — any previously stuck state\n // is no longer relevant.\n this.lastNoopAttempt = null;\n return next(ctx);\n }\n\n if (this.shouldSkipNoopRetry(level, tokens)) {\n return next(ctx);\n }\n\n const aggressive =\n level === 'hard'\n ? true\n : level === 'soft'\n ? aggressiveOn !== 'hard'\n : aggressiveOn === 'warn';\n\n await this.compact(ctx, aggressive, {\n level,\n tokens,\n load,\n budget,\n signals: { repeatedReadCount: repetition },\n });\n\n return next(ctx);\n };\n }\n\n /**\n * H1: try to read a pre-computed token total from `ctx.lastRequestTokens`\n * (set by the agent loop's pre-flight or its restash in emitContextPct).\n * Returns the uncalibrated total when the stash is valid for the current\n * context shape (positive number, and the message count it was computed\n * at matches the current one — otherwise tool results have been appended\n * since and the value is stale). Returns null when missing or stale so\n * the caller falls back to a fresh walk.\n */\n private tryStashedTokens(ctx: Context, msgCount: number, toolCount: number): number | null {\n const stashed = ctx.lastRequestTokens;\n if (typeof stashed !== 'number' || stashed <= 0) return null;\n // The agent loop writes the (msg, tool) count it computed the stash at\n // into ctx.meta['lastRequestTokensAt']. When the counts disagree the\n // caller has already recomputed and refreshed the stash, but we verify\n // the meta key exists for safety — older code paths and tests may set\n // lastRequestTokens without the companion entry.\n const stashedAt = ctx.meta?.['lastRequestTokensAt'];\n if (typeof stashedAt !== 'object' || stashedAt === null) return null;\n const meta = stashedAt as { msgCount?: unknown; toolCount?: unknown };\n if (meta.msgCount !== msgCount) return null;\n if (typeof meta.toolCount === 'number' && meta.toolCount !== toolCount) return null;\n return stashed;\n }\n\n /**\n * Returns true when the previous compaction at the same or higher pressure\n * level reduced nothing and context has not grown materially since. Prevents\n * a stuck preserveK window from spamming compaction events every iteration.\n */\n private shouldSkipNoopRetry(level: PressureLevel, tokens: number): boolean {\n const stuck = this.lastNoopAttempt;\n if (!stuck) return false;\n // Escalation always retries — soft → hard might be reducible aggressively.\n if (LEVEL_RANK[level] > LEVEL_RANK[stuck.level]) return false;\n const delta = tokens - stuck.tokens;\n return delta < AutoCompactionMiddleware.NOOP_RETRY_DELTA_TOKENS;\n }\n\n private recordAttempt(level: PressureLevel, tokens: number, report: CompactReport): void {\n // Prefer full-request tokens (accurate); fall back to message-only before/after.\n const reduced =\n (report.fullRequestTokensBefore ?? report.before) > (report.fullRequestTokensAfter ?? report.after);\n const repaired = !!report.repaired;\n if (reduced || repaired) {\n this.lastNoopAttempt = null;\n } else {\n this.lastNoopAttempt = { level, tokens };\n }\n }\n\n private async compact(\n ctx: Context,\n aggressive: boolean,\n pressure: {\n level: PressureLevel;\n tokens: number;\n load: number;\n budget: ContextWindowBudgetSnapshot;\n signals: { repeatedReadCount: number };\n },\n ): Promise<void> {\n try {\n const report = await this.compactor.compact(ctx, { aggressive });\n this.recordAttempt(pressure.level, pressure.tokens, report);\n this.events?.emit('compaction.fired', {\n level: pressure.level,\n tokens: pressure.tokens,\n load: pressure.load,\n maxContext: this._maxContext,\n budget: pressure.budget,\n signals: pressure.signals,\n report,\n aggressive,\n });\n\n // Persist a compaction event to the session log (if a bridge was provided).\n // This is one of the highest-value audit events for understanding context\n // window behavior over long runs.\n await this.sessionBridge?.append({\n type: 'compaction',\n ts: new Date().toISOString(),\n before: report.before,\n after: report.after,\n level: pressure.level,\n aggressive,\n reductions: report.reductions?.map((r) => ({ phase: r.phase, saved: r.saved })),\n budget: pressure.budget,\n signals: pressure.signals,\n // Record what was collapsed so the audit trail shows the preserved\n // content, not just token counts. Bounded to keep the log line small;\n // the full original turns are already in the session JSONL.\n ...(report.collapsedDigest\n ? { digest: truncateDigest(report.collapsedDigest) }\n : {}),\n });\n\n // Stale file-read metadata from before the compaction boundary is no\n // longer useful and would cause hasRead() to skip legitimate re-reads.\n ctx.clearFileTracking();\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n const fatal =\n this.failureMode === 'throw' ||\n (this.failureMode === 'throw_on_hard' && pressure.level === 'hard');\n this.events?.emit('compaction.failed', {\n err: error,\n aggressive,\n level: pressure.level,\n tokens: pressure.tokens,\n maxContext: this._maxContext,\n budget: pressure.budget,\n signals: pressure.signals,\n load: pressure.load,\n fatal,\n });\n if (fatal) {\n throw new AgentError({\n message: `Auto-compaction failed at ${pressure.level} threshold`,\n code: ERROR_CODES.AGENT_CONTEXT_OVERFLOW,\n recoverable: true,\n context: {\n level: pressure.level,\n tokens: pressure.tokens,\n maxContext: this._maxContext,\n },\n cause: err,\n });\n }\n }\n }\n}\n\nfunction computeContextWindowBudget(\n ctx: Context,\n inputTokens: number,\n maxContext: number,\n): ContextWindowBudgetSnapshot {\n const reservedOutputTokens = readPositiveMetaNumber(ctx, 'contextOutputReserveTokens') ??\n Math.floor(Math.min(8192, maxContext * 0.08));\n const reservedSafetyTokens = readPositiveMetaNumber(ctx, 'contextSafetyBufferTokens') ??\n Math.floor(Math.min(4096, maxContext * 0.02));\n const availableInputTokens = Math.max(\n 1,\n maxContext - reservedOutputTokens - reservedSafetyTokens,\n );\n const remainingInputTokens = availableInputTokens - inputTokens;\n return {\n maxContext,\n inputTokens,\n availableInputTokens,\n remainingInputTokens,\n reservedOutputTokens,\n reservedSafetyTokens,\n load: inputTokens / availableInputTokens,\n overflowTokens: Math.max(0, -remainingInputTokens),\n };\n}\n\nfunction readPositiveMetaNumber(ctx: Context, key: string): number | undefined {\n const value = ctx.meta?.[key];\n return typeof value === 'number' && Number.isFinite(value) && value >= 0\n ? Math.floor(value)\n : undefined;\n}\n\nfunction adaptThresholdsForSignals(\n thresholds: { warn: number; soft: number; hard: number },\n signals: { repeatedReadCount: number },\n): { warn: number; soft: number; hard: number } {\n if (signals.repeatedReadCount < 3) return thresholds;\n // Re-reading the same file repeatedly is a strong sign of shrinking-spiral\n // behavior. Lower only warn/soft a little so compaction can refresh anchors\n // before the hard overflow path, but keep hard fixed as the safety boundary.\n return {\n warn: Math.max(0.25, thresholds.warn - 0.08),\n soft: Math.max(0.35, thresholds.soft - 0.04),\n hard: thresholds.hard,\n };\n}\n","/**\n * Well-known tool capabilities used for authorization decisions.\n *\n * These are the preferred values for `Tool.capabilities`.\n * New capabilities should be added here with clear documentation.\n *\n * Philosophy (2026-06+):\n * - Prefer capabilities over exact tool name matching.\n * - Subagent guards and future policies should primarily key off capabilities.\n * - Name-based denylists are legacy and will be phased down.\n */\nexport const ToolCapabilities = {\n /** Can execute arbitrary commands in the user's shell (the `bash` tool). */\n SHELL_ARBITRARY: 'shell.arbitrary',\n\n /** Can execute a restricted set of commands (the `exec` tool). */\n SHELL_RESTRICTED: 'shell.restricted',\n\n /** Can read files inside the project (and possibly outside via symlinks if not guarded). */\n FS_READ: 'fs.read',\n\n /** Can write / modify / delete files inside the project. */\n FS_WRITE: 'fs.write',\n\n /** Can write files outside the current project root (very high risk). */\n FS_WRITE_OUTSIDE_PROJECT: 'fs.write.outside-project',\n\n /** Can perform outbound network requests. */\n NET_OUTBOUND: 'net.outbound',\n\n /** Proxies tools from external MCP servers (unknown capability). */\n MCP_PROXY: 'mcp.proxy',\n\n /** Can spawn or manage subagents / multi-agent tasks. */\n SUBAGENT_SPAWN: 'subagent.spawn',\n\n /** Can mutate global or session configuration / trust state. */\n CONFIG_MUTATE: 'config.mutate',\n\n /** Can install packages or run package managers with side effects. */\n PACKAGE_INSTALL: 'package.install',\n} as const;\n\nexport type ToolCapability = (typeof ToolCapabilities)[keyof typeof ToolCapabilities];\n\n/**\n * Set of capabilities that are considered dangerous for subagents by default.\n * Subagents should not receive these capabilities unless the leader explicitly\n * allows the specific tool at spawn time.\n */\nexport const DANGEROUS_FOR_SUBAGENTS: readonly ToolCapability[] = [\n ToolCapabilities.SHELL_ARBITRARY,\n ToolCapabilities.SHELL_RESTRICTED,\n ToolCapabilities.FS_WRITE,\n ToolCapabilities.FS_WRITE_OUTSIDE_PROJECT,\n ToolCapabilities.MCP_PROXY,\n ToolCapabilities.SUBAGENT_SPAWN,\n ToolCapabilities.CONFIG_MUTATE,\n ToolCapabilities.PACKAGE_INSTALL,\n];\n\n/**\n * Wide capability allowlist for subagents that the user has authorized to act\n * with full developer power (the CLI fleet host applies this to any subagent\n * that isn't given an explicit, narrower grant). It covers everything needed to\n * do real work end-to-end — read, write/edit inside the project, outbound\n * network, and shell/build/install — so a delegated coding or build agent runs\n * the same toolchain the leader would, without per-tool confirmation it cannot\n * answer.\n *\n * Deliberately EXCLUDED (require an explicit per-spawn `allowedCapabilities`\n * grant, because they escape the task's blast radius rather than perform it):\n * - `fs.write.outside-project` — writing outside the repo (e.g. ~/.ssh).\n * - `mcp.proxy` — third-party MCP tools (also hard-blocked by name).\n * - `subagent.spawn` — recursive delegation (the baseline prompt forbids it).\n * - `config.mutate` — rewriting trust/config is privilege escalation, not work.\n */\nexport const WIDE_SUBAGENT_CAPABILITIES: readonly ToolCapability[] = [\n ToolCapabilities.FS_READ,\n ToolCapabilities.FS_WRITE,\n ToolCapabilities.NET_OUTBOUND,\n ToolCapabilities.SHELL_ARBITRARY,\n ToolCapabilities.SHELL_RESTRICTED,\n ToolCapabilities.PACKAGE_INSTALL,\n];\n\n/**\n * Check if a tool (or its capabilities array) includes any dangerous capability\n * for subagent execution.\n */\nexport function hasDangerousCapabilityForSubagents(\n toolOrCaps: { capabilities?: readonly string[] | undefined } | readonly string[] | undefined,\n): boolean {\n if (!toolOrCaps) return false;\n // Use `as unknown as ...` to allow accessing .capabilities on the union type\n const input = toolOrCaps as unknown as { capabilities?: readonly string[] | undefined };\n const caps: readonly string[] = Array.isArray(toolOrCaps) ? toolOrCaps : (input.capabilities ?? []);\n return caps.some((c) => DANGEROUS_FOR_SUBAGENTS.includes(c as ToolCapability));\n}\n\n/**\n * Check if a tool declares a specific capability (or any of the provided ones).\n */\nexport function hasCapability(\n toolOrCaps: { capabilities?: readonly string[] | undefined } | readonly string[] | undefined,\n capability: ToolCapability | ToolCapability[],\n): boolean {\n if (!toolOrCaps) return false;\n // Use `as unknown as ...` to allow accessing .capabilities on the union type\n const input = toolOrCaps as unknown as { capabilities?: readonly string[] | undefined };\n const caps: readonly string[] = Array.isArray(toolOrCaps) ? toolOrCaps : (input.capabilities ?? []);\n const toCheck = Array.isArray(capability) ? capability : [capability];\n return toCheck.some((c) => caps.includes(c));\n}\n\n/**\n * Returns the intersection of a tool's capabilities with the dangerous set.\n * Useful for logging and audit trails.\n */\nexport function getDangerousCapabilities(\n toolOrCaps: { capabilities?: readonly string[] | undefined } | readonly string[] | undefined,\n): ToolCapability[] {\n if (!toolOrCaps) return [];\n // Use `as unknown as ...` to allow accessing .capabilities on the union type\n const input = toolOrCaps as unknown as { capabilities?: readonly string[] | undefined };\n const caps: readonly string[] = Array.isArray(toolOrCaps) ? toolOrCaps : (input.capabilities ?? []);\n return caps.filter((c): c is ToolCapability =>\n DANGEROUS_FOR_SUBAGENTS.includes(c as ToolCapability),\n );\n}\n","import { randomUUID } from 'node:crypto';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { Context } from '../core/context.js';\nimport {\n getDangerousCapabilities,\n hasDangerousCapabilityForSubagents,\n} from '../security/capabilities.js';\nimport type { ToolResultBlock, ToolUseBlock } from '../types/blocks.js';\nimport type { Tool, ToolProgressEvent } from '../types/tool.js';\nimport type {\n ToolBatchResult,\n ToolConfirmPendingResult,\n ToolExecutionOutput,\n ToolExecutorOptions,\n ToolExecutorStrategy,\n} from '../types/tool-executor.js';\nimport { toErrorMessage } from '../utils/error.js';\nimport { expectDefined } from '../utils/expect-defined.js';\nimport { validateAgainstSchema } from '../utils/json-schema-validate.js';\nimport { createToolOutputSerializer } from '../utils/tool-output-serializer.js';\nimport { wstackGlobalRoot } from '../utils/wstack-paths.js';\nexport class ToolExecutor {\n /** Minimum gap between coalesced `partial_output` tool.progress emits. */\n static readonly PROGRESS_EMIT_INTERVAL_MS = 100;\n /** Max chars of accumulated stream text carried per coalesced emit. */\n static readonly PROGRESS_TAIL_CHARS = 16_384;\n\n private readonly serializer;\n private readonly iterationTimeoutMs: number;\n private readonly maxToolTimeoutMs: number;\n\n constructor(\n private readonly registry: { get(name: string): Tool | undefined; list(): Tool[] },\n private opts: ToolExecutorOptions,\n ) {\n this.iterationTimeoutMs = opts.iterationTimeoutMs ?? 300_000;\n this.maxToolTimeoutMs = opts.maxToolTimeoutMs ?? 300_000;\n this.serializer = createToolOutputSerializer({\n perIterationOutputCapBytes: opts.perIterationOutputCapBytes ?? 100_000,\n });\n }\n\n /**\n * Clear the interactive confirm awaiter so the executor returns\n * `ToolConfirmPendingResult` instead of blocking on stdin. Used by\n * the CLI to switch from inline prompts (REPL) to event-driven\n * confirmation (TUI) at runtime.\n */\n clearConfirmAwaiter(): void {\n this.opts.confirmAwaiter = undefined;\n }\n\n /**\n * Execute a batch of tool uses using the configured strategy.\n * Returns the execution results and the remaining output budget.\n */\n async executeBatch(\n toolUses: ToolUseBlock[],\n ctx: Context,\n strategy: ToolExecutorStrategy,\n ): Promise<ToolBatchResult> {\n let budget = this.opts.perIterationOutputCapBytes ?? 100_000;\n\n const runOne = async (use0: ToolUseBlock): Promise<ToolExecutionOutput> => {\n const start = Date.now();\n // `use` is rebindable because a PreToolUse hook may rewrite its input.\n let use = use0;\n const tool = this.registry.get(use.name);\n\n // Fast path: unknown tool\n if (!tool) {\n const result = this.unknownToolResult(use, () => this.registry.list().map((t) => t.name));\n budget = this.budgetForString(result.content, budget);\n return { result, tool, durationMs: Date.now() - start };\n }\n\n // Strong guarantee: Validate input against the tool's declared JSON Schema\n // *before* permission checks or execution. This is a hard gate — bad calls\n // are rejected early with actionable feedback so the model can self-correct.\n const validation = validateAgainstSchema(use.input, tool.inputSchema);\n if (!validation.ok) {\n const errorDetails = validation.errors\n .map((e) => ` - ${e.path || 'input'}: ${e.message}`)\n .join('\\n');\n\n const result = {\n type: 'tool_result' as const,\n tool_use_id: use.id,\n content:\n `Invalid arguments for tool \"${tool.name}\".\\n\\n` +\n `Validation errors:\\n${errorDetails}\\n\\n` +\n `Please call the tool again with arguments that match its inputSchema. ` +\n `You can use the \"tool-help\" tool with name=\"${tool.name}\" to see the exact expected schema.`,\n is_error: true,\n };\n budget = this.budgetForString(result.content, budget);\n return { result, tool, durationMs: Date.now() - start };\n }\n\n // Capability safety net at the executor level (defense in depth).\n // Tools declaring dangerous capabilities are subject to stricter\n // permission enforcement in the post-policy block below (line ~150+).\n // In non-YOLO contexts, an `auto` permission is elevated to `confirm`\n // for dangerous-capability tools, reducing prompt-injection blast radius.\n const toolDangerousCaps = getDangerousCapabilities(tool);\n\n // Provider boundary: the model's tool arguments arrive as a raw JSON\n // string accumulated over streamed deltas. When that string is not a\n // valid JSON object (truncated, scalar, or mangled by a proxy/local\n // model), the parsers wrap it under a sentinel key instead of silently\n // producing `{}`. Executing the tool with such input yields a cryptic\n // \"<field> is required\" error that the model can't act on. Detect the\n // sentinel here and feed back an actionable message so the model\n // resends well-formed arguments.\n if (hasMalformedArguments(use.input)) {\n const result = this.malformedInputResult(use, extractMalformedRaw(use.input));\n budget = this.budgetForString(result.content, budget);\n return { result, tool, durationMs: Date.now() - start };\n }\n\n // PreToolUse hooks: may block the call outright or rewrite its input.\n // Runs before the permission check so a hook can veto a tool that the\n // trust policy would otherwise auto-allow.\n if (this.opts.hookRunner?.has('PreToolUse')) {\n const pre = await this.opts.hookRunner.preToolUse(tool.name, use.input, ctx);\n if (pre.block) {\n const result = this.blockedByHookResult(use, pre.reason);\n budget = this.budgetForString(result.content, budget);\n return { result, tool, durationMs: Date.now() - start };\n }\n if (pre.input) {\n // A hook rewrote the arguments — re-validate before trusting them.\n const reval = validateAgainstSchema(pre.input, tool.inputSchema);\n if (!reval.ok) {\n const errorDetails = reval.errors\n .map((e) => ` - ${e.path || 'input'}: ${e.message}`)\n .join('\\n');\n const result = {\n type: 'tool_result' as const,\n tool_use_id: use.id,\n content:\n `A PreToolUse hook rewrote the arguments for \"${tool.name}\" into an invalid shape.\\n\\n` +\n `Validation errors:\\n${errorDetails}`,\n is_error: true,\n };\n budget = this.budgetForString(result.content, budget);\n return { result, tool, durationMs: Date.now() - start };\n }\n use = { ...use, input: pre.input };\n }\n }\n\n const decision = await this.opts.permissionPolicy.evaluate(tool, use.input, ctx);\n\n // Post-permission dangerous capability enforcement (B-side guarantee).\n // Even after the permission policy has spoken, we apply an extra conservative\n // rule for tools that declare high-risk capabilities (shell arbitrary, write outside\n // project, mcp proxy, etc.). This reduces the blast radius of prompt injection.\n let effectivePermission = decision.permission;\n\n // YOLO is the user's explicit fast-path for normal project work, so it\n // waives the post-policy dangerous-capability net only after the permission\n // policy has already returned `auto`. Destructive-gated calls still arrive\n // here as `confirm` unless the destructive YOLO override is active. Outside\n // YOLO, a trust-file auto-allow for a shell tool still gets a confirm, so a\n // single trusted pattern can't silently widen into arbitrary shell.\n // Detected via optional methods so policies without them (AutoApprove,\n // test mocks) keep the stricter default.\n const policy = this.opts.permissionPolicy;\n const yolo = policy.getYolo?.() === true || policy.getYoloDestructive?.() === true;\n\n // An `auto` decision sourced from `'yolo'` is authoritative: it comes\n // either from the leader's explicit YOLO mode or from a subagent's\n // `AutoApprovePermissionPolicy`, which already enforces a capability\n // allowlist (and now requires every dangerous capability to be granted\n // explicitly). In both cases the allowlist IS the blast-radius control,\n // so the conservative downgrade below would be redundant — and for a\n // non-interactive subagent (no confirmAwaiter) it would turn a granted\n // write into a `confirm` that can never be answered. Trust-file `auto`\n // (source 'trust') is NOT waived: a single trusted pattern must not\n // silently widen into arbitrary dangerous-capability execution.\n const authoritativeAuto = decision.source === 'yolo';\n\n if (\n toolDangerousCaps.length > 0 &&\n effectivePermission === 'auto' &&\n !yolo &&\n !authoritativeAuto\n ) {\n // Outside yolo we force at least 'confirm' for dangerous-capability tools.\n effectivePermission = 'confirm';\n }\n\n if (effectivePermission === 'deny') {\n const result = this.deniedResult(use, decision.reason);\n budget = this.budgetForString(result.content, budget);\n return { result, tool, durationMs: Date.now() - start };\n }\n\n if (effectivePermission === 'confirm') {\n if (this.opts.confirmAwaiter) {\n const choice = await this.opts.confirmAwaiter(tool, use.input, use.id, tool.name);\n if (choice !== 'yes' && choice !== 'always') {\n const result = {\n type: 'tool_result' as const,\n tool_use_id: use.id,\n content: `Tool \"${tool.name}\" denied by user.`,\n is_error: true,\n };\n budget = this.budgetForString(result.content, budget);\n return { result, tool, durationMs: Date.now() - start };\n }\n // fall through to execute\n } else {\n const suggestedPattern =\n this.subjectFor(tool.name, use.input, tool.subjectKey) ?? tool.name;\n const pending: ToolConfirmPendingResult = {\n type: 'tool_confirm_pending',\n toolUseId: use.id,\n toolName: tool.name,\n input: use.input,\n suggestedPattern,\n };\n return { result: pending, tool, durationMs: Date.now() - start };\n }\n }\n\n // effectivePermission === 'auto' (after all safety layers)\n // Capability audit for observability.\n const toolCapsForAudit = hasDangerousCapabilityForSubagents(tool)\n ? (tool.capabilities ?? [])\n : [];\n\n // L1-C: trace each tool execution. Span is a no-op unless an OTel\n // adapter or other Tracer is bound — zero overhead by default.\n const span = this.opts.tracer?.startSpan(`tool.${tool.name}`, {\n 'tool.name': tool.name,\n 'tool.mutating': tool.mutating,\n 'tool.permission': tool.permission,\n 'tool.capabilities': JSON.stringify(tool.capabilities ?? []),\n 'tool.has_dangerous_capabilities': toolCapsForAudit.length > 0,\n });\n try {\n // H2: executeTool returns the rendered block plus the exact byte\n // count it spent against the iteration output cap. The cap was\n // enforced inside `enforceCap`, so the spend is known without\n // any second `Buffer.byteLength` walk.\n let { block: result, bytes } = await this.executeTool(tool, use, ctx, budget);\n budget -= bytes;\n // PostToolUse hooks: observe the result and optionally append\n // context (e.g. a linter note) that the model sees alongside the\n // tool output. Append the post-hook bytes to the budget spend\n // without re-walking the full result content.\n if (this.opts.hookRunner?.has('PostToolUse')) {\n const post = await this.opts.hookRunner.postToolUse(\n tool.name,\n use.input,\n { content: String(result.content), isError: !!result.is_error },\n ctx,\n );\n if (post.additionalContext) {\n const appended = `\\n\\n${post.additionalContext}`;\n result = { ...result, content: `${result.content}${appended}` };\n // Only the appended bytes are new — the pre-hook portion was\n // already counted by enforceCap. Walking just the appended\n // tail is `O(additionalContext.length)`, never `O(content)`.\n // Floor at 0 to match `decrementBudget`'s pre-fix clamp.\n budget = Math.max(0, budget - Buffer.byteLength(appended, 'utf8'));\n }\n }\n span?.setAttribute('tool.is_error', !!result.is_error);\n span?.setAttribute(\n 'tool.output_bytes',\n typeof result.content === 'string' ? result.content.length : 0,\n );\n return { result, tool, durationMs: Date.now() - start };\n } catch (err) {\n const msg = toErrorMessage(err);\n const scrubbed = this.opts.secretScrubber.scrub(msg);\n this.opts.renderer?.writeToolResult(tool.name, scrubbed, true);\n const result = {\n type: 'tool_result' as const,\n tool_use_id: use.id,\n content: `Tool \"${tool.name}\" threw: ${scrubbed}`,\n is_error: true,\n };\n budget = this.budgetForString(result.content, budget);\n if (err instanceof Error) span?.recordError(err);\n span?.setAttribute('tool.is_error', true);\n return { result, tool, durationMs: Date.now() - start };\n } finally {\n span?.end();\n }\n };\n\n // Run a single tool but never let an exception propagate to the\n // gather() below — `runOne` is already try/catch-wrapped for the\n // execution phase, but the *pre*-execution paths (permission policy,\n // confirmAwaiter) are unguarded and an unexpected throw there would\n // collapse Promise.all and lose every sibling's output. Wrap each\n // call so a per-tool failure becomes a per-tool error result.\n const safeRun = async (use: ToolUseBlock): Promise<ToolExecutionOutput> => {\n try {\n return await runOne(use);\n } catch (err) {\n const msg = toErrorMessage(err);\n const scrubbed = this.opts.secretScrubber.scrub(msg);\n const result = {\n type: 'tool_result' as const,\n tool_use_id: use.id,\n content: `Tool \"${use.name}\" execution failed: ${scrubbed}`,\n is_error: true,\n };\n budget = this.budgetForString(result.content, budget);\n return { result, tool: this.registry.get(use.name), durationMs: 0 };\n }\n };\n\n if (strategy === 'sequential') {\n const outputs: ToolExecutionOutput[] = [];\n for (const use of toolUses) {\n if (use) outputs.push(await safeRun(use));\n }\n return { outputs, remainingBudget: budget };\n }\n\n if (strategy === 'parallel') {\n const outputs = await Promise.all(toolUses.map((use) => safeRun(use)));\n return { outputs, remainingBudget: budget };\n }\n\n // smart: non-mutating in parallel, then mutating sequentially\n const nonMutating: ToolUseBlock[] = [];\n const mutating: ToolUseBlock[] = [];\n for (const use of toolUses) {\n if (!use) continue;\n const tool = this.registry.get(use.name);\n if (tool?.mutating) mutating.push(use);\n else nonMutating.push(use);\n }\n const firstPass = await Promise.all(nonMutating.map((use) => safeRun(use)));\n const secondPass: ToolExecutionOutput[] = [];\n for (const use of mutating) {\n secondPass.push(await safeRun(use));\n }\n return {\n outputs: [...firstPass, ...secondPass],\n remainingBudget: budget,\n };\n }\n\n /**\n * Execute a single tool with timeout, permission check, and output capping.\n * Emits `tool.started` via the injected EventBus (if any) right before\n * invoking the tool — closes the observability gap between \"model decided\n * to call a tool\" and \"tool.executed\".\n */\n async executeTool(\n tool: Tool,\n use: ToolUseBlock,\n ctx: Context,\n budget: number,\n ): Promise<{ block: ToolResultBlock; bytes: number }> {\n this.opts.events?.emit('tool.started', {\n name: tool.name,\n id: use.id,\n input: use.input,\n });\n this.opts.renderer?.writeToolCall(tool.name, use.input);\n const output = await this.runWithTimeout(tool, use.input, ctx.signal, ctx, use.id);\n const text = this.serializer.serialize(output, { toolName: tool.name, input: use.input });\n const scrubbed = this.opts.secretScrubber.scrub(text);\n const withArtifact = await maybePersistLargeToolOutput(tool.name, scrubbed, budget);\n // enforceCap already walks the text to compute bytes for the budget\n // cap. Carry the residual budget back as `bytes` so the caller can\n // deduct the spend without a second `Buffer.byteLength` walk — and\n // never falls back to `JSON.stringify` on a structured value.\n const { text: capped, newBudget } = this.serializer.enforceCap(withArtifact, budget);\n this.opts.renderer?.writeToolResult(tool.name, capped, false);\n return {\n block: {\n type: 'tool_result',\n tool_use_id: use.id,\n name: tool.name,\n content: capped,\n is_error: false,\n },\n // `budget - newBudget` is the exact byte count enforceCap spent\n // (capped at `budget` so a truncated output shows as `budget`\n // consumed, matching the pre-fix `decrementBudget` semantics).\n bytes: budget - newBudget,\n };\n }\n\n private async runWithTimeout(\n tool: Tool,\n input: unknown,\n parentSignal: AbortSignal,\n ctx: Context,\n toolUseId?: string | undefined,\n ): Promise<unknown> {\n if (parentSignal.aborted) {\n // Re-throw the original abort reason, whether it's an Error, string, or undefined.\n if (parentSignal.reason instanceof Error) throw parentSignal.reason;\n throw new Error(typeof parentSignal.reason === 'string' ? parentSignal.reason : 'aborted');\n }\n const timeoutMs = clampTimeoutMs(\n tool.timeoutMs ?? this.iterationTimeoutMs,\n this.maxToolTimeoutMs,\n );\n const timeoutSignal = AbortSignal.timeout(timeoutMs);\n const combined = AbortSignal.any([parentSignal, timeoutSignal]);\n\n let output: unknown;\n try {\n // Streaming variant takes precedence — yields progress events, then\n // a final 'final' event with the typed output. Tools that don't\n // implement executeStream fall through to the standard execute path.\n output =\n typeof tool.executeStream === 'function'\n ? await this.runStreamedTool(tool, input, ctx, combined, toolUseId)\n : await tool.execute(input, ctx, { signal: combined });\n } catch (err) {\n // If aborted, run cleanup before re-throwing so the tool can release\n // resources (child processes, file handles, network connections).\n if (combined.aborted) await this.runToolCleanup(tool, input, ctx);\n throw err;\n }\n // The tool returned without throwing, but the signal may have aborted (e.g.\n // a timeout fired) while a tool that ignores the abort signal kept running.\n // Treat that as an abort: clean up and surface the abort to the caller so a\n // late, stale result is never returned as success.\n if (combined.aborted) {\n await this.runToolCleanup(tool, input, ctx);\n throw combined.reason instanceof Error\n ? combined.reason\n : new Error(typeof combined.reason === 'string' ? combined.reason : 'tool timeout');\n }\n return output;\n }\n\n /** Best-effort tool cleanup; never let it mask the original error. */\n private async runToolCleanup(tool: Tool, input: unknown, ctx: Context): Promise<void> {\n if (typeof tool.cleanup !== 'function') return;\n try {\n await tool.cleanup(input, ctx);\n } catch {\n /* swallow — never let cleanup mask the original error */\n }\n }\n\n private async runStreamedTool(\n tool: Tool,\n input: unknown,\n ctx: Context,\n signal: AbortSignal,\n toolUseId: string | undefined,\n ): Promise<unknown> {\n let finalOutput: unknown;\n let sawFinal = false;\n if (!tool.executeStream) {\n throw new Error(`Tool \"${tool.name}\" does not support streaming execution`);\n }\n const stream = tool.executeStream(input, ctx, { signal });\n // Manual iteration so we can explicitly close the async iterator after\n // receiving the final event, ensuring any cleanup in the tool's generator\n // finally block runs regardless of whether the engine calls return() on\n // break of a for-await-of loop.\n const iter = stream[Symbol.asyncIterator]();\n // Coalesce `partial_output` progress into at most one EventBus emit per\n // PROGRESS_EMIT_INTERVAL_MS, carrying only the most recent\n // PROGRESS_TAIL_CHARS of accumulated text. A chatty child process (a test\n // suite or build spewing ANSI progress) can stream hundreds of MB per\n // minute through executeStream; emitting every flush as its own event\n // floods every bus subscriber (TUI render per dispatch, session bridge,\n // WebUI broadcast) and has OOM'd the host. The live tail only ever shows\n // the last few KB, so coalescing loses nothing the UI can display —\n // the tool's own capped `final` output is unaffected.\n let progressTail = '';\n let lastProgressEmitAt = 0;\n const emitProgress = (ev: ToolProgressEvent) => {\n this.opts.events?.emit('tool.progress', {\n name: tool.name,\n id: toolUseId ?? '<unknown>',\n event: ev,\n });\n };\n const flushProgressTail = (force: boolean) => {\n if (progressTail.length === 0) return;\n const now = Date.now();\n if (!force && now - lastProgressEmitAt < ToolExecutor.PROGRESS_EMIT_INTERVAL_MS) return;\n const text = progressTail;\n progressTail = '';\n lastProgressEmitAt = now;\n emitProgress({ type: 'partial_output', text });\n };\n try {\n while (true) {\n const { done, value: ev } = await iter.next();\n if (done) break;\n if (ev.type === 'final') {\n finalOutput = ev.output;\n sawFinal = true;\n // Result is locked — stop consuming further events.\n break;\n }\n if (ev.type === 'partial_output' && typeof ev.text === 'string') {\n progressTail += ev.text;\n if (progressTail.length > ToolExecutor.PROGRESS_TAIL_CHARS) {\n progressTail = progressTail.slice(-ToolExecutor.PROGRESS_TAIL_CHARS);\n }\n flushProgressTail(false);\n continue;\n }\n // Non-partial events (log/warning/metric/file_changed) are low-volume;\n // flush buffered text first so subscribers see events in stream order.\n flushProgressTail(true);\n emitProgress(ev);\n }\n flushProgressTail(true);\n } finally {\n // Always close the iterator so the tool's generator finally block\n // runs even if we broke early on a final event or errored.\n await iter.return?.(undefined);\n }\n if (!sawFinal) {\n throw new Error(`tool \"${tool.name}\" executeStream completed without a 'final' event`);\n }\n return finalOutput;\n }\n\n private unknownToolResult(use: ToolUseBlock, listFns: () => string[]): ToolResultBlock {\n return {\n type: 'tool_result',\n tool_use_id: use.id,\n content: `Tool \"${use.name}\" is not registered. Available tools: ${listFns().join(', ')}`,\n is_error: true,\n };\n }\n\n private malformedInputResult(use: ToolUseBlock, raw?: string): ToolResultBlock {\n let content =\n `Tool \"${use.name}\" received arguments that were not a valid JSON object, so they ` +\n `could not be parsed. Re-issue the call with the arguments encoded as a single ` +\n `well-formed JSON object matching the tool's input schema.`;\n // Echo the raw payload back so the model can see *what* it produced and\n // self-correct. Without this the model is blind to its own mistake and\n // tends to resend the identical malformed call in a loop. Common causes:\n // unescaped newlines/quotes/backslashes inside a string field, or the\n // arguments being truncated mid-stream.\n if (raw) {\n const max = 800;\n const excerpt =\n raw.length > max ? `${raw.slice(0, max)}… (truncated, ${raw.length} chars total)` : raw;\n content +=\n ` Common cause: a string field (e.g. code in old_string/new_string) ` +\n `contains literal newlines, quotes, or backslashes that must be JSON-escaped, ` +\n `or the payload was cut off mid-stream. The raw arguments received were:\\n${excerpt}`;\n }\n return {\n type: 'tool_result',\n tool_use_id: use.id,\n content,\n is_error: true,\n };\n }\n\n private deniedResult(use: ToolUseBlock, reason?: string): ToolResultBlock {\n return {\n type: 'tool_result',\n tool_use_id: use.id,\n content: `Tool \"${use.name}\" denied: ${reason ?? 'policy'}`,\n is_error: true,\n };\n }\n\n private blockedByHookResult(use: ToolUseBlock, reason?: string): ToolResultBlock {\n return {\n type: 'tool_result',\n tool_use_id: use.id,\n content: `Tool \"${use.name}\" was blocked by a PreToolUse hook: ${reason ?? 'no reason given'}`,\n is_error: true,\n };\n }\n\n /**\n * Subtract a string-content result's UTF-8 byte length from the\n * iteration output budget. Used for synthesized results (unknown tool,\n * validation error, blocked, threw) where the content is a small\n * string built in the executor. The success path no longer goes\n * through here — `executeTool` carries the exact byte count it spent\n * in its return value, derived from `enforceCap`'s `newBudget`.\n *\n * Floors the result at 0 to match the pre-fix `decrementBudget`\n * semantics (over-budget spends don't underflow the running total).\n */\n private budgetForString(content: string, budget: number): number {\n return Math.max(0, budget - Buffer.byteLength(content, 'utf8'));\n }\n\n /**\n * Compute the suggestedPattern string for a tool+input pair.\n * Matches the logic in DefaultPermissionPolicy so the TUI shows the\n * same subject that the trust file would use.\n */\n private subjectFor(toolName: string, input: unknown, subjectKey?: string): string | undefined {\n if (!input || typeof input !== 'object') return undefined;\n const obj = input as Record<string, unknown>;\n const globChars = /[*?[\\]]/g;\n const escapeGlob = (s: string) => s.replace(globChars, (c) => `\\\\${c}`);\n const normalizePath = (s: string) => escapeGlob(s.replace(/\\\\/g, '/'));\n\n // Mirror DefaultPermissionPolicy.subjectFor — keep both in sync so the\n // TUI's \"suggested pattern\" matches what the trust file actually uses.\n if (subjectKey) {\n const v = obj[subjectKey];\n if (typeof v === 'string') {\n const isPathKey = subjectKey === 'path' || subjectKey === 'file' || subjectKey === 'files';\n return isPathKey ? normalizePath(v) : escapeGlob(v);\n }\n }\n\n if (toolName === 'bash' && typeof obj.command === 'string') {\n return escapeGlob(obj.command);\n }\n if (typeof obj.path === 'string') {\n return normalizePath(obj.path);\n }\n if (typeof obj.url === 'string') {\n return escapeGlob(obj.url);\n }\n if (typeof obj.name === 'string') {\n return escapeGlob(obj.name);\n }\n return undefined;\n }\n}\n\nfunction clampTimeoutMs(timeoutMs: number, maxTimeoutMs: number): number {\n const fallback = 300_000;\n const finiteTimeout = Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : fallback;\n const finiteMax = Number.isFinite(maxTimeoutMs) && maxTimeoutMs > 0 ? maxTimeoutMs : fallback;\n return Math.max(1, Math.min(finiteTimeout, finiteMax));\n}\n\n/**\n * Sentinel keys the provider adapters use to wrap tool arguments that could\n * not be parsed into a proper JSON object. `parseToolInput` (Anthropic /\n * shared) uses `__raw`, `contentFromOpenAI` uses `__raw_arguments`, and the\n * streaming response builder's `safeJsonOrRaw` uses `_raw`. Keep this list in\n * sync if a new adapter introduces another marker.\n *\n * NOTE: `parseToolInput` and `safeJsonOrRaw` now attempt JSON repair\n * (auto-closing braces and strings) before wrapping — so a truncated blob\n * like `{\"old_string\": \"line1\\nline2` gets repaired first. The sentinel is\n * only used when repair also fails.\n */\nconst MALFORMED_ARG_MARKERS = ['__raw', '__raw_arguments', '_raw'] as const;\n\nfunction hasMalformedArguments(input: unknown): boolean {\n if (!input || typeof input !== 'object' || Array.isArray(input)) return false;\n const obj = input as Record<string, unknown>;\n // The sentinel is the *only* key when wrapping occurred — a real tool call\n // that legitimately uses a key named e.g. `_raw` will carry other keys too.\n const keys = Object.keys(obj);\n return keys.length === 1 && MALFORMED_ARG_MARKERS.includes(keys[0] as never);\n}\n\n/**\n * Pull the original (unparseable) payload back out of a sentinel-wrapped input\n * so the executor can echo it to the model. The wrapped value is usually the\n * raw argument string, but a scalar/array that parsed cleanly is wrapped too —\n * stringify those. Returns undefined if nothing usable is present.\n */\nfunction extractMalformedRaw(input: unknown): string | undefined {\n if (!hasMalformedArguments(input)) return undefined;\n const obj = input as Record<string, unknown>;\n const value = obj[expectDefined(Object.keys(obj)[0])];\n if (value === undefined || value === null) return undefined;\n if (typeof value === 'string') return value;\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nconst TOOL_OUTPUT_ARTIFACT_THRESHOLD_BYTES = 64 * 1024;\n\nasync function maybePersistLargeToolOutput(\n toolName: string,\n content: string,\n budget: number,\n): Promise<string> {\n const bytes = Buffer.byteLength(content, 'utf8');\n if (bytes <= Math.min(TOOL_OUTPUT_ARTIFACT_THRESHOLD_BYTES, Math.max(0, budget))) {\n return content;\n }\n\n try {\n const dir = path.join(wstackGlobalRoot(), 'tool-output');\n await fs.mkdir(dir, { recursive: true });\n const safeTool = toolName.replace(/[^a-zA-Z0-9._-]+/g, '_').slice(0, 40) || 'tool';\n const stamp = new Date().toISOString().replace(/[:.]/g, '-');\n const filePath = path.join(dir, `${stamp}-${safeTool}-${randomUUID()}.log`);\n await fs.writeFile(filePath, content, 'utf8');\n return (\n content +\n `\\n[full tool output: ${bytes} bytes at ${filePath}; read/grep that file selectively instead of re-running or requesting more output]`\n );\n } catch {\n return content;\n }\n}\n","import type { Agent, RunResult } from '../core/agent.js';\r\nimport type { Context } from '../core/context.js';\r\nimport { toWrongStackError } from '../types/errors.js';\r\nimport type { DoneCondition } from '../types/multi-agent.js';\r\nimport { assertNever } from '../utils/assert-never.js';\r\nimport { compileUserRegex } from '../utils/regex-guard.js';\r\n\r\ntype AutonomousResult = RunResult & { toolCalls: number; reason?: string | undefined };\r\n\r\nexport interface DoneCheckResult {\r\n done: boolean;\r\n reason?: string | undefined;\r\n iterations: number;\r\n toolCalls: number;\r\n}\r\n\r\nexport class DoneConditionChecker {\r\n private readonly compiledRegex: RegExp | null;\r\n\r\n constructor(private readonly condition: DoneCondition) {\r\n if (condition.type === 'output_match' && condition.pattern) {\r\n const result = compileUserRegex(condition.pattern, '');\r\n this.compiledRegex = result.ok ? result.regex : null;\r\n if (!result.ok) {\r\n // Log warning but don't throw — the done condition simply won't match\r\n console.warn(JSON.stringify({\r\n level: 'warn',\r\n event: 'autonomous.done_condition_invalid_regex',\r\n pattern: condition.pattern,\r\n reason: result.reason,\r\n timestamp: new Date().toISOString(),\r\n }));\r\n }\r\n } else {\r\n this.compiledRegex = null;\r\n }\r\n }\r\n\r\n check(state: { iterations: number; toolCalls: number; lastOutput?: string | undefined }): DoneCheckResult {\r\n switch (this.condition.type) {\r\n case 'iterations':\r\n if (this.condition.maxIterations && state.iterations >= this.condition.maxIterations) {\r\n return {\r\n done: true,\r\n reason: `max iterations (${this.condition.maxIterations}) reached`,\r\n ...state,\r\n };\r\n }\r\n break;\r\n\r\n case 'tool_calls':\r\n if (this.condition.maxToolCalls && state.toolCalls >= this.condition.maxToolCalls) {\r\n return {\r\n done: true,\r\n reason: `max tool calls (${this.condition.maxToolCalls}) reached`,\r\n ...state,\r\n };\r\n }\r\n break;\r\n\r\n case 'output_match':\r\n if (this.compiledRegex && state.lastOutput && this.compiledRegex.test(state.lastOutput)) {\r\n return {\r\n done: true,\r\n reason: `output matched pattern \"${this.condition.pattern}\"`,\r\n ...state,\r\n };\r\n }\r\n break;\r\n\r\n case 'directive':\r\n // Model-driven: the agent manages its own continuation via [continue]/[done].\r\n // The done condition is never satisfied by the checker — the agent returns\r\n // `status: 'done'` when the model emits [done] or naturally finishes.\r\n // The runner's outer loop uses maxIterations/maxToolCalls as hard caps.\r\n if (this.condition.maxIterations && state.iterations >= this.condition.maxIterations) {\r\n return { done: true, reason: `max iterations (${this.condition.maxIterations}) reached`, ...state };\r\n }\r\n if (this.condition.maxToolCalls && state.toolCalls >= this.condition.maxToolCalls) {\r\n return { done: true, reason: `max tool calls (${this.condition.maxToolCalls}) reached`, ...state };\r\n }\r\n break;\r\n\r\n case 'all_tasks_done':\r\n // Coordinator-managed: completion is decided by the multi-agent\r\n // coordinator's pending-task queue, not by per-iteration state here.\r\n break;\r\n\r\n case 'custom':\r\n // Reserved for future extension\r\n break;\r\n default:\r\n return assertNever(this.condition.type);\r\n }\r\n\r\n return { done: false, iterations: state.iterations, toolCalls: state.toolCalls };\r\n }\r\n}\r\n\r\nexport interface AutonomousRunnerOptions {\r\n agent: Agent;\r\n context: Context;\r\n doneCondition: DoneCondition;\r\n iterationTimeoutMs?: number | undefined;\r\n onIteration?: (state: { iteration: number | undefined; toolCalls: number }) => void;\r\n onDone?: (((result: AutonomousResult) => void)) | undefined;\r\n /**\r\n * When true and `doneCondition.type === 'directive'`, the runner\r\n * runs the agent with `autonomousContinue: true` so the agent loop\r\n * handles its own [continue]/[done] markers internally (no outer\r\n * re-invocation needed). The runner still provides iteration/timeouts.\r\n */\r\n enableAutonomousContinue?: boolean | undefined;\r\n}\r\n\r\nexport class AutonomousRunner {\r\n private iterations = 0;\r\n private toolCalls = 0;\r\n private lastOutput?: string | undefined;\r\n private stopped = false;\r\n private readonly doneChecker: DoneConditionChecker;\r\n\r\n constructor(private readonly opts: AutonomousRunnerOptions) {\r\n this.doneChecker = new DoneConditionChecker(opts.doneCondition);\r\n }\r\n\r\n async run(): Promise<AutonomousResult> {\r\n // Subscribe to `tool.executed` so the per-tool budget (`tool_calls`\r\n // done-condition) actually counts each tool invocation rather than\r\n // each `agent.run()` call. Without this, a single iteration that\r\n // fires 5 tools only bumps the counter once, and a `maxToolCalls: 3`\r\n // budget would fire after 3 iterations (typically 3×N tools) instead\r\n // of after 3 tools. Unsubscribed in the `finally` so the listener\r\n // doesn't outlive this run instance. Mock agents in tests may pass\r\n // null/undefined for `events`; gracefully skip when missing — those\r\n // tests don't exercise the tool-count budget path.\r\n const offToolExecuted = this.opts.agent.events?.on?.('tool.executed', () => {\r\n this.toolCalls++;\r\n });\r\n // When autonomous continue is enabled, also count internal agent-loop\r\n // iterations. Each iteration.started within a single agent.run() call\r\n // counts toward the runner's maxIterations cap. We listen to the event\r\n // through the agent's EventBus.\r\n const offIterationCompleted = this.opts.agent.events?.on?.('iteration.completed', () => {\r\n // Only count if we're in autonomous continue mode (agent loop\r\n // handles multiple iterations internally before returning).\r\n if (this.opts.enableAutonomousContinue && this.opts.doneCondition.type === 'directive') {\r\n // Each internal iteration completed — bump the outer iteration counter.\r\n // This ensures maxIterations on the runner actually limits total work.\r\n this.iterations++;\r\n }\r\n });\r\n try {\r\n return await this.runLoop();\r\n } finally {\r\n offToolExecuted?.();\r\n offIterationCompleted?.();\r\n }\r\n }\r\n\r\n private async runLoop(): Promise<AutonomousResult> {\r\n while (!this.stopped) {\r\n const check = this.doneChecker.check({\r\n iterations: this.iterations,\r\n toolCalls: this.toolCalls,\r\n lastOutput: this.lastOutput,\r\n });\r\n\r\n if (check.done) {\r\n const result: AutonomousResult = {\r\n status: 'done',\r\n iterations: this.iterations,\r\n toolCalls: this.toolCalls,\r\n reason: check.reason,\r\n };\r\n this.opts.onDone?.(result);\r\n return result;\r\n }\r\n\r\n this.opts.onIteration?.({ iteration: this.iterations, toolCalls: this.toolCalls });\r\n\r\n const ctrl = new AbortController();\r\n const timeout = setTimeout(() => ctrl.abort(), this.opts.iterationTimeoutMs ?? 30_000);\r\n\r\n try {\r\n // In directive mode with autonomous continue, pass it through so the\r\n // agent loop handles its own [continue]/[done] markers internally.\r\n // The runner provides iteration caps and timeouts; the agent handles\r\n // the continuation decision within each agent.run() call.\r\n const isDirectiveMode =\r\n this.opts.doneCondition.type === 'directive' &&\r\n this.opts.enableAutonomousContinue;\r\n\r\n const result = await this.opts.agent.run('', {\r\n signal: ctrl.signal,\r\n maxIterations: isDirectiveMode ? (this.opts.doneCondition.maxIterations ?? 100) : 1,\r\n executionStrategy: 'sequential',\r\n autonomousContinue: isDirectiveMode ? true : undefined,\r\n });\r\n\r\n // Only increment iterations if we're NOT counting via iteration.completed\r\n // (i.e., not in autonomous continue directive mode). In that mode,\r\n // the offIterationCompleted listener in run() bumps this counter\r\n // per internal iteration so the runner's maxIterations cap is respected.\r\n if (!isDirectiveMode) this.iterations++;\r\n // Only access finalText when the run actually succeeded. Failed/aborted\r\n // runs may have undefined finalText — accessing it unconditionally would\r\n // produce garbage output for the done-condition matchers.\r\n if (result.status === 'done') {\r\n this.lastOutput = result.finalText;\r\n }\r\n // `toolCalls` is bumped by the `tool.executed` listener installed\r\n // in run() — no manual increment here.\r\n\r\n if (result.status === 'failed' || result.status === 'aborted') {\r\n const failedResult: AutonomousResult = {\r\n status: result.status,\r\n error: result.error,\r\n iterations: this.iterations,\r\n toolCalls: this.toolCalls,\r\n };\r\n this.opts.onDone?.(failedResult);\r\n return failedResult;\r\n }\r\n } catch (e) {\r\n // Be precise about what constitutes a timeout error — matching on\r\n // 'timeout' substring is too loose (an error message containing\r\n // \"timeout exceeded\" from the LLM is not the same as an abort).\r\n const isAbort =\r\n (e instanceof DOMException && e.name === 'AbortError') ||\r\n (e instanceof Error && e.name === 'AbortError') ||\r\n (e instanceof Error && e.message.includes('iteration timeout'));\r\n if (isAbort) {\r\n const timeoutResult: AutonomousResult = {\r\n status: 'failed',\r\n error: toWrongStackError(e),\r\n iterations: this.iterations,\r\n toolCalls: this.toolCalls,\r\n reason: 'iteration timeout',\r\n };\r\n this.opts.onDone?.(timeoutResult);\r\n return timeoutResult;\r\n }\r\n // Any other throw (TypeError, tool crash propagation, etc.) must\r\n // stop the loop — silently continuing would spin forever on the\r\n // same error and burn provider tokens with no progress.\r\n this.stopped = true;\r\n const failedResult: AutonomousResult = {\r\n status: 'failed',\r\n error: toWrongStackError(e),\r\n iterations: this.iterations,\r\n toolCalls: this.toolCalls,\r\n reason: e instanceof Error ? e.message : String(e),\r\n };\r\n this.opts.onDone?.(failedResult);\r\n return failedResult;\r\n } finally {\r\n clearTimeout(timeout);\r\n }\r\n }\r\n\r\n return {\r\n status: 'aborted',\r\n iterations: this.iterations,\r\n toolCalls: this.toolCalls,\r\n reason: 'stopped externally',\r\n };\r\n }\r\n\r\n stop(): void {\r\n this.stopped = true;\r\n }\r\n}\r\n","import * as fsp from 'node:fs/promises';\nimport type { EventBus } from '../kernel/events.js';\nimport { atomicWrite, withFileLock } from '../utils/atomic-write.js';\nimport { toErrorMessage } from '../utils/error.js';\nimport { color } from '../utils/color.js';\nimport { resolveWstackPaths } from '../utils/wstack-paths.js';\nimport { FsError, ERROR_CODES } from '../types/errors.js';\n\n/**\n * Long-running autonomous mission. A goal survives across sessions and\n * drives the EternalAutonomyEngine — every iteration of the engine\n * consults the goal to choose what to do next.\n *\n * Storage: `~/.wrongstack/projects/<hash>/goal.json`. Persistent and\n * project-scoped on purpose: the goal belongs to the codebase, not the\n * REPL session.\n */\n\nexport interface JournalEntry {\n /** ISO timestamp of the iteration. */\n at: string;\n /** Sequential iteration counter (1-based, monotonically increasing). */\n iteration: number;\n /** Source that produced the action ('todo' | 'git' | 'brainstorm' | 'resume' | 'manual' | 'parallel'). */\n source: 'todo' | 'git' | 'brainstorm' | 'resume' | 'manual' | 'parallel';\n /** Short one-line description of what the iteration set out to do. */\n task: string;\n /** Outcome status. */\n status: 'success' | 'failure' | 'aborted' | 'skipped';\n /** Optional free-form note (error message, summary, etc.). */\n note?: string | undefined;\n /** Optional token usage delta for this iteration. */\n tokens?: { input: number; output: number } | undefined;\n /** Optional USD cost delta for this iteration (provider-estimated). */\n costUsd?: number | undefined;\n}\n\nexport interface GoalFile {\n version: 1;\n /** The raw mission statement as entered by the user. */\n goal: string;\n /**\n * LLM-refined version of the goal — unambiguous, with concrete\n * deliverables and acceptance criteria.\n */\n refinedGoal?: string | undefined;\n /**\n * Concrete, verifiable deliverables extracted from the refined goal.\n */\n deliverables?: string[] | undefined;\n /**\n * Estimated completion 0-100. Updated by the engine after each\n * iteration. Null means \"not yet assessed\".\n */\n progress?: number | undefined;\n /** Human-readable note explaining the current progress estimate. */\n progressNote?: string | undefined;\n /**\n * Time-series of progress measurements for trend analysis.\n * Last 200 entries retained. Use `recordProgress()` to append.\n */\n progressHistory?: ProgressSnapshot[] | undefined;\n /**\n * Computed trend from recent progress measurements.\n * 'accelerating' | 'steady' | 'stalling' | undefined.\n */\n progressTrend?: 'accelerating' | 'steady' | 'stalling' | undefined;\n /** When the goal was first set or last replaced. */\n setAt: string;\n /** Updated on every iteration completion. */\n lastActivityAt: string;\n /** Total iterations the engine has run against this goal (cumulative). */\n iterations: number;\n /** Engine lifecycle state — 'running' means another process owns this goal. */\n engineState: 'idle' | 'running' | 'stopped';\n /**\n * Mission-level lifecycle.\n */\n goalState?: 'active' | 'paused' | 'completed' | 'abandoned' | undefined;\n /**\n * Per-todo attempt counter.\n */\n todoAttempts?: Record<string, number>;\n /** Bounded ring buffer of recent iterations (newest last). */\n journal: JournalEntry[];\n}\n\n/** Cap on persisted journal entries — older entries are evicted FIFO. */\nexport const MAX_JOURNAL_ENTRIES = 500;\n\n/**\n * Resolve the goal file path for a given project root.\n *\n * SINGLE canonical location: the per-project directory that\n * `resolveWstackPaths()` uses for everything else (sessions, memory, specs) —\n * `~/.wrongstack/projects/<slug>/goal.json`. This is the same path the `/goal`\n * slash command writes via `opts.paths.projectGoal`, so every reader/writer\n * (the eternal/parallel autonomy engines, the CLI autonomy commands, the TUI\n * F9 panel, and `/goal` itself) now agree on one file.\n *\n * Previously this returned a SEPARATE hash-based dir (`projects/<hash>/`), which\n * disagreed with `/goal` and littered the home dir with thousands of stray\n * `<hash>/goal.json` directories that held nothing else.\n */\nexport function goalFilePath(projectRoot: string): string {\n return resolveWstackPaths({ projectRoot }).projectGoal;\n}\n\nexport async function loadGoal(filePath: string, events?: EventBus): Promise<GoalFile | null> {\n const t0 = Date.now();\n let raw: string;\n try {\n raw = await fsp.readFile(filePath, 'utf8');\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') {\n events?.emit('storage.read', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'load',\n outcome: 'success',\n durationMs: Date.now() - t0,\n });\n return null; // file doesn't exist — not an error\n }\n events?.emit('storage.error', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'load',\n error: toErrorMessage(err),\n recoverable: false,\n });\n throw err; // permission errors etc. should surface\n }\n try {\n const parsed = JSON.parse(raw) as GoalFile;\n if (parsed?.version !== 1 || typeof parsed.goal !== 'string' || !Array.isArray(parsed.journal)) {\n console.warn(JSON.stringify({\n level: 'warn',\n event: 'goal_store.invalid_schema',\n path: filePath,\n message: 'invalid schema — consider deleting and re-creating',\n timestamp: new Date().toISOString(),\n }));\n events?.emit('storage.read', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'load',\n outcome: 'failure',\n durationMs: Date.now() - t0,\n error: 'invalid_schema',\n });\n return null;\n }\n events?.emit('storage.read', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'load',\n outcome: 'success',\n durationMs: Date.now() - t0,\n });\n return parsed;\n } catch {\n console.warn(JSON.stringify({\n level: 'warn',\n event: 'goal_store.parse_failed',\n path: filePath,\n message: 'JSON parse failed — consider deleting and re-creating',\n timestamp: new Date().toISOString(),\n }));\n events?.emit('storage.read', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'load',\n outcome: 'failure',\n durationMs: Date.now() - t0,\n error: 'parse_failed',\n });\n return null;\n }\n}\n\nexport async function saveGoal(filePath: string, goal: GoalFile, events?: EventBus): Promise<void> {\n const t0 = Date.now();\n try {\n await atomicWrite(filePath, JSON.stringify(goal, null, 2), { mode: 0o600 });\n events?.emit('storage.write', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'save',\n outcome: 'success',\n durationMs: Date.now() - t0,\n });\n } catch (err) {\n events?.emit('storage.error', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'save',\n error: toErrorMessage(err),\n recoverable: false,\n });\n throw new FsError({\n message: toErrorMessage(err),\n code: ERROR_CODES.FS_ATOMIC_WRITE_FAILED,\n path: filePath,\n cause: err,\n });\n }\n}\n\n/**\n * Atomically load, modify, and save a goal file under a file lock.\n * Prevents lost-update races when the autonomy engine and CLI /goal commands\n * write concurrently (both eternal and parallel engines may run simultaneously).\n *\n * `fn` receives the current GoalFile (or `null` if no goal exists yet)\n * and must return the updated GoalFile (or `null` to delete).\n */\nexport async function updateGoal(\n filePath: string,\n fn: (current: GoalFile | null) => GoalFile | null,\n events?: EventBus,\n): Promise<void> {\n const t0 = Date.now();\n await withFileLock(filePath, async () => {\n const current = await loadGoal(filePath, events);\n const next = fn(current);\n if (next) {\n await saveGoal(filePath, next, events);\n } else {\n try {\n await fsp.unlink(filePath);\n events?.emit('storage.write', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'delete',\n outcome: 'success',\n durationMs: Date.now() - t0,\n });\n } catch (err) {\n events?.emit('storage.error', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'delete',\n error: toErrorMessage(err),\n recoverable: true,\n });\n // best-effort — file may not exist\n }\n }\n events?.emit('storage.write', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'update',\n outcome: 'success',\n durationMs: Date.now() - t0,\n });\n });\n}\n\nexport function emptyGoal(goal: string): GoalFile {\n const now = new Date().toISOString();\n return {\n version: 1,\n goal,\n setAt: now,\n lastActivityAt: now,\n iterations: 0,\n engineState: 'idle',\n goalState: 'active',\n todoAttempts: {},\n journal: [],\n };\n}\n\n/**\n * Set progress estimate on a goal. Returns a new GoalFile.\n * Clamps progress to 0-100.\n */\nexport function setProgress(\n goal: GoalFile,\n progress: number,\n note?: string,\n): GoalFile {\n const clamped = Math.min(100, Math.max(0, progress));\n return {\n ...goal,\n progress: clamped,\n progressNote: note ?? clamped + '% complete',\n };\n}\n\n/**\n * Append a journal entry, bumping iteration counters and trimming the\n * ring buffer. Returns a new GoalFile — does not mutate the argument.\n */\nexport function appendJournal(goal: GoalFile, entry: Omit<JournalEntry, 'iteration' | 'at'>): GoalFile {\n const iteration = goal.iterations + 1;\n const at = new Date().toISOString();\n const full: JournalEntry = { ...entry, iteration, at };\n const journal = [...goal.journal, full];\n const trimmed = journal.length > MAX_JOURNAL_ENTRIES\n ? journal.slice(journal.length - MAX_JOURNAL_ENTRIES)\n : journal;\n return {\n ...goal,\n iterations: iteration,\n lastActivityAt: at,\n journal: trimmed,\n };\n}\n\n/**\n * Aggregate cumulative cost + tokens across all journal entries.\n */\nexport function summarizeUsage(goal: GoalFile): {\n totalCostUsd: number;\n totalInputTokens: number;\n totalOutputTokens: number;\n iterationsWithUsage: number;\n} {\n let totalCostUsd = 0;\n let totalInputTokens = 0;\n let totalOutputTokens = 0;\n let iterationsWithUsage = 0;\n for (const e of goal.journal) {\n if (typeof e.costUsd === 'number') totalCostUsd += e.costUsd;\n if (e.tokens) {\n totalInputTokens += e.tokens.input;\n totalOutputTokens += e.tokens.output;\n }\n if (typeof e.costUsd === 'number' || e.tokens) iterationsWithUsage++;\n }\n return { totalCostUsd, totalInputTokens, totalOutputTokens, iterationsWithUsage };\n}\n\nconst DOLLAR = '\\u0024';\n\n/** Format the goal + recent journal as a human-readable status block. */\nexport function formatGoal(goal: GoalFile, journalLimit = 10): string {\n const lines: string[] = [];\n\n // Header — show refined goal, with original as annotation if different\n const displayGoal = goal.refinedGoal || goal.goal;\n lines.push(color.bold('Goal') + ': ' + displayGoal);\n if (goal.refinedGoal && goal.refinedGoal !== goal.goal) {\n const snippet = goal.goal.length > 60 ? goal.goal.slice(0, 60) + '…' : goal.goal;\n lines.push(color.dim(' (original: \"' + snippet + '\")'));\n }\n\n // Progress bar (20-segment)\n if (typeof goal.progress === 'number') {\n const pct = Math.min(100, Math.max(0, Math.round(goal.progress)));\n const filled = Math.round(pct / 5);\n const empty = 20 - filled;\n const bar = color.green('█'.repeat(filled)) + color.dim('░'.repeat(empty));\n lines.push('Progress: ' + bar + ' ' + color.bold(pct + '%'));\n if (goal.progressNote) {\n lines.push(' ' + color.dim(goal.progressNote));\n }\n // Trend indicator\n if (goal.progressTrend) {\n const trendIcon = goal.progressTrend === 'accelerating' ? '🚀'\n : goal.progressTrend === 'stalling' ? '⚠️'\n : '➡️';\n lines.push(' Trend: ' + trendIcon + ' ' + goal.progressTrend);\n }\n }\n\n // Deliverables checklist\n if (goal.deliverables && goal.deliverables.length > 0) {\n lines.push('');\n lines.push(color.bold('Deliverables:'));\n for (const d of goal.deliverables) {\n const done = /^\\[[x✓]\\]|✅|\\(done\\)/i.test(d);\n const marker = done ? color.green('✓') : color.dim('○');\n lines.push(' ' + marker + ' ' + d);\n }\n }\n\n lines.push('');\n lines.push('Set: ' + goal.setAt);\n lines.push('Last activity: ' + goal.lastActivityAt);\n lines.push('Iterations: ' + goal.iterations);\n const stateLabel = goal.goalState ?? 'active';\n lines.push('State: ' + stateLabel + (goal.iterations > 0 ? ' (iteration #' + goal.iterations + ')' : ''));\n lines.push('Engine: ' + goal.engineState);\n const usage = summarizeUsage(goal);\n if (usage.iterationsWithUsage > 0) {\n const spent = 'Spent: ' + DOLLAR + usage.totalCostUsd.toFixed(4)\n + ' (in ' + usage.totalInputTokens + ' / out ' + usage.totalOutputTokens\n + ' tokens across ' + usage.iterationsWithUsage + ' iterations)';\n lines.push(spent);\n }\n if (goal.journal.length > 0) {\n lines.push('');\n lines.push('Recent journal (last ' + Math.min(journalLimit, goal.journal.length) + '):');\n const tail = goal.journal.slice(-journalLimit);\n for (const e of tail) {\n const mark = e.status === 'success' ? '✓' : e.status === 'failure' ? '✗' : e.status === 'aborted' ? '⊘' : '·';\n const note = e.note ? ' — ' + e.note : '';\n const cost = typeof e.costUsd === 'number' ? ' (' + DOLLAR + e.costUsd.toFixed(4) + ')' : '';\n lines.push(' #' + e.iteration + ' ' + mark + ' [' + e.source + '] ' + e.task + cost + note);\n }\n }\n return lines.join('\\n');\n}\n\n/** A single progress measurement at a point in time. */\nexport interface ProgressSnapshot {\n at: string;\n progress: number;\n note?: string | undefined;\n}\n\n/**\n * Parse [PROGRESS: N%] from agent final text.\n * Supports formats:\n * [PROGRESS: 45%]\n * [PROGRESS: 45%] — 3/5 deliverables done\n * [progress: 100%]\n * Returns null if no match.\n */\nexport function parseProgressFromText(text: string): { progress: number; note?: string } | null {\n const re = /\\[progress:\\s*(\\d{1,3})%\\]\\s*(?:[—-]\\s*(.+))?/i;\n const m = text.match(re);\n if (!m) return null;\n // Regex match guarantees capture group 1 exists, but use ?? fallback to\n // satisfy noUncheckedIndexedAccess without a non-null assertion.\n const progress = Math.min(100, Math.max(0, Number.parseInt(m[1] ?? '0', 10)));\n const note = m[2]?.trim() || undefined;\n return note === undefined ? { progress } : { progress, note };\n}\n\n/**\n * Record a progress measurement. Returns a new GoalFile with:\n * - progress + progressNote updated\n * - progressHistory appended (last 200 entries kept)\n * - progress trend computed (accelerating/steady/stalling)\n */\nexport function recordProgress(\n goal: GoalFile,\n progress: number,\n note?: string,\n): GoalFile {\n const clamped = Math.min(100, Math.max(0, progress));\n const history = [...(goal.progressHistory ?? []), { at: new Date().toISOString(), progress: clamped, note }];\n // Keep last 200 snapshots\n const trimmed = history.length > 200 ? history.slice(-200) : history;\n\n return {\n ...goal,\n progress: clamped,\n progressNote: note ?? `${clamped}% complete`,\n progressHistory: trimmed,\n progressTrend: computeTrend(trimmed),\n };\n}\n\n/** Max progress history entries to retain. */\nexport const MAX_PROGRESS_HISTORY = 200;\n\nfunction computeTrend(history: ProgressSnapshot[]): 'accelerating' | 'steady' | 'stalling' | undefined {\n if (history.length < 3) return undefined;\n const recent = history.slice(-5);\n const deltas: number[] = [];\n for (let i = 1; i < recent.length; i++) {\n deltas.push((recent[i]?.progress ?? 0) - (recent[i - 1]?.progress ?? 0));\n }\n /* v8 ignore next -- unreachable: history.length>=3 guard above guarantees >=2 deltas */\n if (deltas.length < 2) return undefined;\n const avgDelta = deltas.reduce((a, b) => a + b, 0) / deltas.length;\n if (avgDelta > 2) return 'accelerating';\n if (avgDelta < -1) return 'stalling';\n return 'steady';\n}\n","/**\n * AutonomyBrain — a self-driving decision layer for autonomous workflows.\n *\n * Unlike the standard BrainArbiter which asks the human when uncertain,\n * AutonomyBrain makes decisions autonomously within configured risk\n * boundaries, keeping the system running unattended. It uses the session\n * LLM to evaluate situations and produce decisions.\n *\n * ## Identity\n * The AutonomyBrain is NOT the main agent. It is a dedicated decision\n * engine with a single purpose: evaluate blocked/stuck situations in\n * autonomous workflows and decide whether to continue, pivot, or stop.\n *\n * ## Decision Flow\n * 1. RISK GATE — if request risk > maxAutoRisk, auto-deny\n * 2. HEURISTIC — fast pattern-match for common situations (deadlock, retry-exhausted)\n * 3. LLM EVALUATION — complex decisions (goal completion, conflict resolution)\n *\n * ## Decision Logging\n * Every decision is emitted via `onDecision` callback with a human-readable\n * summary suitable for chat history and journal entries.\n *\n * Usage:\n * const brain = createAutonomyBrain({\n * provider, model, maxAutoRisk: 'high',\n * onDecision: (summary) => journal.push(summary),\n * });\n */\n\nimport type { Provider } from '../types/provider.js';\nimport type { BrainArbiter, BrainDecision, BrainDecisionRequest } from '../coordination/brain.js';\n\nexport interface AutonomyBrainOptions {\n /** LLM provider for decision-making. */\n provider: Provider;\n /** Model to use for decisions (should be fast + cheap). */\n model: string;\n /** Maximum risk level the brain will auto-decide. Default: 'high'.\n * 'low' — only auto-decide low-risk questions\n * 'medium' — auto-decide low/medium\n * 'high' — auto-decide low/medium/high\n * 'all' — auto-decide everything (including critical)\n */\n maxAutoRisk?: 'low' | 'medium' | 'high' | 'all' | undefined;\n /** Timeout for each decision call (ms). Default: 15_000. */\n decisionTimeoutMs?: number | undefined;\n /**\n * Called after every decision with a human-readable summary.\n * Use this to log decisions into chat history, journal, or status line.\n * Example: \"🧠 Brain: skipped deadlocked tasks → continuing with phase 3/5\"\n */\n onDecision?: ((summary: string, decision: BrainDecision, request: BrainDecisionRequest) => void) | undefined;\n}\n\nconst RISK_LEVELS: Record<string, number> = {\n low: 0,\n medium: 1,\n high: 2,\n critical: 3,\n};\n\n/** Runtime-adjustable autonomy ceiling for the tiered brain. */\nexport type BrainAutoRisk = 'off' | 'low' | 'medium' | 'high' | 'all';\n\nexport interface TieredBrainArbiterOptions {\n /** Fast deterministic policy layer (DefaultBrainArbiter). Consulted first. */\n policy: BrainArbiter;\n /** LLM-backed autonomous layer (createAutonomyBrain). Consulted when the\n * policy layer would escalate to the human and the request's risk is\n * within the live ceiling. */\n autonomous?: BrainArbiter | undefined;\n /**\n * Live autonomy ceiling — read on EVERY decision so `/brain risk <level>`\n * changes take effect immediately. 'off' disables the autonomous layer\n * entirely (everything the policy can't answer goes to the human).\n */\n getMaxAutoRisk?: (() => BrainAutoRisk) | undefined;\n}\n\n/**\n * The standard Brain positioning: policy first, LLM second, human last.\n *\n * 1. POLICY — deterministic DefaultBrainArbiter (low-risk fast path,\n * fallback semantics). Answers and denies pass through untouched.\n * 2. LLM — when the policy says `ask_human` and the request's risk is\n * within the live ceiling, the autonomous brain gets a chance to\n * answer. Only a real `answer` short-circuits; LLM denials/failures\n * fall through.\n * 3. HUMAN — anything left escalates (callers wrap this in\n * HumanEscalatingBrainArbiter so `ask_human` becomes a real prompt).\n */\nexport function createTieredBrainArbiter(opts: TieredBrainArbiterOptions): BrainArbiter {\n return {\n async decide(request: BrainDecisionRequest): Promise<BrainDecision> {\n const policyDecision = await opts.policy.decide(request);\n if (policyDecision.type !== 'ask_human') return policyDecision;\n const ceiling = opts.getMaxAutoRisk?.() ?? 'medium';\n if (!opts.autonomous || ceiling === 'off') return policyDecision;\n const ceilingLevel = ceiling === 'all' ? 3 : (RISK_LEVELS[ceiling] ?? 1);\n const requestLevel = RISK_LEVELS[request.risk] ?? 2;\n if (requestLevel > ceilingLevel) return policyDecision;\n try {\n const llmDecision = await opts.autonomous.decide(request);\n if (llmDecision.type === 'answer') return llmDecision;\n } catch {\n // LLM layer is best-effort — fall through to the human.\n }\n return policyDecision;\n },\n };\n}\n\n/**\n * Create a self-driving brain that makes autonomous decisions.\n * Never asks the human — within its risk boundary it answers, above it denies.\n */\nexport function createAutonomyBrain(opts: AutonomyBrainOptions): BrainArbiter {\n const maxRisk = opts.maxAutoRisk ?? 'high';\n const maxRiskLevel = RISK_LEVELS[maxRisk] ?? 2;\n const timeoutMs = opts.decisionTimeoutMs ?? 15_000;\n\n return {\n async decide(request: BrainDecisionRequest): Promise<BrainDecision> {\n const requestLevel = RISK_LEVELS[request.risk] ?? 2;\n\n // RISK GATE — above our risk boundary → auto-deny\n if (requestLevel > maxRiskLevel) {\n const reason = `Auto-denied: risk \"${request.risk}\" exceeds max \"${maxRisk}\"`;\n const decision: BrainDecision = { type: 'deny', reason };\n opts.onDecision?.(\n `🧠 Brain: DENIED — ${request.question.slice(0, 80)} (risk: ${request.risk} > ${maxRisk})`,\n decision,\n request,\n );\n return decision;\n }\n\n // HEURISTIC — fast pattern-match\n const heuristic = quickDecide(request);\n if (heuristic) {\n opts.onDecision?.(formatDecisionSummary(heuristic, request), heuristic, request);\n return heuristic;\n }\n\n // LLM EVALUATION — complex decisions\n const llmDecision = await llmDecide(request, opts.provider, opts.model, timeoutMs);\n opts.onDecision?.(formatDecisionSummary(llmDecision, request), llmDecision, request);\n return llmDecision;\n },\n };\n}\n\n/**\n * Format a decision as a human-readable one-liner for chat history.\n */\nexport function formatDecisionSummary(\n decision: BrainDecision,\n request: BrainDecisionRequest,\n): string {\n const question = request.question.length > 80\n ? request.question.slice(0, 77) + '…'\n : request.question;\n\n if (decision.type === 'deny') {\n return `🧠 Brain: DENIED — \"${question}\" → ${decision.reason}`;\n }\n\n if (decision.type === 'answer') {\n const action = decision.optionId\n ? `chose [${decision.optionId}]`\n : decision.text.length > 60\n ? decision.text.slice(0, 57) + '…'\n : decision.text;\n return `🧠 Brain: DECIDED — \"${question}\" → ${action}`;\n }\n\n return `🧠 Brain: ASKED HUMAN — \"${question}\"`;\n}\n\n/** Fast heuristic decisions that don't need an LLM call. */\nfunction quickDecide(request: BrainDecisionRequest): BrainDecision | null {\n const q = request.question.toLowerCase();\n const ctx = request.context?.toLowerCase() ?? '';\n\n // Deadlock with failed tasks → skip and continue\n if (q.includes('deadlock') && ctx.includes('failed')) {\n return {\n type: 'answer',\n text: 'Skip deadlocked tasks and continue with remaining work. Failed tasks will be reported in the final summary.',\n rationale: 'Heuristic: deadlocked tasks blocked by failed dependencies — skipping unblocks remaining work.',\n };\n }\n\n // Repeated failure with exhausted retries → move on\n if (\n (q.includes('failed') || q.includes('retry')) &&\n (ctx.includes('3') || ctx.includes('exhausted'))\n ) {\n return {\n type: 'answer',\n text: 'Mark as failed and move on. Note the failure for the final report.',\n rationale: 'Heuristic: retries exhausted — continuing would waste resources.',\n };\n }\n\n // Goal complete verification → needs LLM evaluation\n if (q.includes('goal complete') || q.includes('mission complete')) {\n return null;\n }\n\n // Continue/proceed → always yes\n if (q.includes('continue') || q.includes('proceed')) {\n return {\n type: 'answer',\n text: 'Continue execution. Do not stop.',\n rationale: 'Heuristic: autonomy mode — continue until all work is complete.',\n };\n }\n\n return null;\n}\n\n/**\n * Ask the LLM for a decision on complex questions.\n * Uses a carefully crafted system prompt that establishes the brain's\n * identity, purpose, and decision-making framework.\n */\nasync function llmDecide(\n request: BrainDecisionRequest,\n provider: Provider,\n model: string,\n timeoutMs: number,\n): Promise<BrainDecision> {\n const optionsText = request.options?.length\n ? '\\nOptions:\\n' +\n request.options\n .map(\n (o) =>\n ` [${o.id}] ${o.label}${o.consequence ? ` — ${o.consequence}` : ''}${o.recommended ? ' ★ recommended' : ''}`,\n )\n .join('\\n')\n : '';\n\n const systemPrompt = [\n 'IDENTITY:',\n 'You are the Autonomy Brain — a dedicated decision engine inside an',\n 'autonomous AI coding agent called WrongStack. Your SOLE purpose is to',\n 'evaluate situations where the autonomous workflow is blocked, stuck, or',\n 'uncertain, and decide the best course of action to keep the system',\n 'running and making progress toward its goal.',\n '',\n 'WHAT YOU DO:',\n '- You receive a question + context from an autonomy subsystem (goal',\n ' engine, phase orchestrator, task decomposer).',\n '- You evaluate whether the system should continue, pivot, retry, skip,',\n ' or stop.',\n '- You output exactly ONE decision. No preamble, no markdown, no',\n ' elaboration beyond what is needed to justify the decision.',\n '',\n 'HOW YOU DECIDE:',\n '1. PREFER CONTINUATION. The default answer is always \"continue\" unless',\n ' there is clear evidence that stopping is safer or more productive.',\n '2. BE SPECIFIC. If options are provided, pick one by its [id]. If not,',\n ' describe the exact action in 1-2 sentences.',\n '3. VERIFY COMPLETION. If the question is about whether the goal is done,',\n ' check deliverables and progress before saying yes. A progress bar at',\n ' 80% with open deliverables means NOT done.',\n '4. AVOID WASTE. If a task has failed 3+ times with the same approach,',\n ' recommend a different approach or skipping it — do not recommend',\n ' retrying the same thing.',\n '5. CONSIDER COST. If the question mentions spent budget or token counts,',\n ' factor that into your decision. A goal that has already spent $50',\n ' with 90% progress is worth finishing; one at 15% with $100 spent',\n ' may need re-evaluation.',\n '',\n 'OUTPUT FORMAT:',\n '- With options: output the option [id] and a 1-sentence justification.',\n ' Example: \"[resolve] — conflict is in test files only, safe to auto-resolve.\"',\n '- Without options: output the decision as a 1-2 sentence action.',\n ' Example: \"Continue execution. Progress is steady at 60% with 3/5',\n ' deliverables done. No reason to stop.\"',\n '',\n 'CRITICAL RULE:',\n 'You are NOT the main agent. Do not suggest code changes, tool calls,',\n 'or implementation details. Your output is a DECISION, not a plan.',\n ].join('\\n');\n\n const userMessage = [\n `Question: ${request.question}`,\n request.context ? `\\nContext:\\n${request.context}` : '',\n optionsText,\n ].filter(Boolean).join('\\n');\n\n try {\n const signal = AbortSignal.timeout(timeoutMs);\n const response = await provider.complete(\n {\n model,\n system: [{ type: 'text', text: systemPrompt }],\n messages: [{ role: 'user', content: userMessage || 'Decide.' }],\n maxTokens: 200,\n },\n { signal },\n );\n\n const text = extractText(response).trim();\n\n // Try to match an option id\n if (request.options?.length) {\n for (const opt of request.options) {\n if (text.toLowerCase().includes(opt.id.toLowerCase())) {\n return {\n type: 'answer',\n optionId: opt.id,\n text: opt.label,\n rationale: text,\n };\n }\n }\n }\n\n // Free-text answer\n return {\n type: 'answer',\n text: text || (request.fallback === 'continue'\n ? 'Continue execution.'\n : 'Denied by autonomy policy.'),\n rationale: text || undefined,\n };\n } catch {\n // LLM unavailable — use fallback\n if (request.fallback === 'continue') {\n return {\n type: 'answer',\n text: 'Continue (Autonomy Brain LLM unavailable — using fallback).',\n };\n }\n return { type: 'deny', reason: 'Autonomy Brain LLM unavailable for decision.' };\n }\n}\n\nfunction extractText(result: unknown): string {\n if (!result || typeof result !== 'object') return '';\n const r = result as Record<string, unknown>;\n if (Array.isArray(r.content)) {\n return (r.content as Array<{ type?: string; text?: string }>)\n .filter((b) => b.type === 'text')\n .map((b) => b.text ?? '')\n .join('');\n }\n if (Array.isArray(r.choices)) {\n return (r.choices as Array<{ message?: { content?: string } }>)[0]?.message?.content ?? '';\n }\n return typeof r.text === 'string' ? r.text : '';\n}\n","import { execFile } from 'node:child_process';\r\nimport { promisify } from 'node:util';\r\nimport type { Agent } from '../core/agent.js';\r\nimport type { TodoItem } from '../core/context.js';\r\nimport type { EventBus } from '../kernel/events.js';\r\nimport type { Compactor } from '../types/compactor.js';\r\nimport type { BrainArbiter } from '../coordination/brain.js';\r\nimport {\r\n appendJournal,\r\n loadGoal,\r\n saveGoal,\r\n goalFilePath,\r\n parseProgressFromText,\r\n recordProgress,\r\n type GoalFile,\r\n type JournalEntry,\r\n} from '../storage/goal-store.js';\r\nimport { sleep } from '../utils/sleep.js';\r\nimport { toErrorMessage } from '../utils/error.js';\nimport { formatDecisionSummary } from './autonomy-brain.js';\r\n\r\nconst execFileP = promisify(execFile);\r\n\r\n/**\r\n * Sense-decide-execute-reflect loop on top of a long-running Goal.\r\n *\r\n * Each iteration:\r\n * 1. Sense — read goal, pending todos, `git status --porcelain`.\r\n * 2. Decide — pick a source (todo / git / brainstorm) and a task.\r\n * 3. Execute — single agent.run with a directive prompt.\r\n * 4. Reflect — append a journal entry, persist state to disk.\r\n *\r\n * The loop runs forever until `stop()` is called externally (REPL SIGINT\r\n * handler, /autonomy stop). No internal time/cost cap by design — the\r\n * user wants \"sittin sene\". Failures are logged and the loop continues\r\n * with a different source on the next tick.\r\n */\r\n\r\nexport interface EternalAutonomyOptions {\r\n agent: Agent;\r\n projectRoot: string;\r\n /**\r\n * Per-iteration agent timeout. Defaults to 5 minutes. A single hung\r\n * provider call should not freeze the whole eternal loop.\r\n */\r\n iterationTimeoutMs?: number | undefined;\r\n /**\r\n * Maximum number of internal agent.run iterations the engine grants per\r\n * eternal-loop tick. The engine sets `autonomousContinue: true` so the\r\n * agent can run multi-step tasks end-to-end within one tick instead of\r\n * bouncing back to the engine after every single tool call. Default 500.\r\n * Previous 50 was far too low — agents hit the limit and restart constantly.\r\n */\r\n iterationMaxAgentSteps?: number | undefined;\r\n /**\r\n * Minimum sleep between iterations. Defaults to 1 s — enough for\r\n * SIGINT handlers to fire mid-loop without pegging a core when the\r\n * provider is being rate-limited.\r\n */\r\n cycleGapMs?: number | undefined;\r\n /**\r\n * Maximum consecutive failures before the source rotation forces a\r\n * brainstorm cycle. Default 3. Acts as a soft-recovery, not a stop.\r\n */\r\n failureBudget?: number | undefined;\r\n /**\r\n * Per-todo failed-attempt ceiling. When the engine picks the same todo\r\n * and the iteration fails this many times in total, the todo is taken\r\n * out of rotation (engine prefers other sources) until it changes\r\n * status. Default 3. Prevents the loop from spinning forever on one\r\n * stuck task.\r\n */\r\n todoMaxAttempts?: number | undefined;\r\n /**\r\n * Consecutive brainstorm-DONE responses required to consider the goal\r\n * complete and stop the engine. When the LLM's brainstorm step keeps\r\n * answering `DONE`, the engine treats that as \"no more work\" and, after\r\n * this many in a row, marks the goal as completed instead of sleeping\r\n * forever. Default 3.\r\n */\r\n brainstormDoneStopThreshold?: number | undefined;\r\n /** Side-channel notifications (logging, UI updates). */\r\n onIteration?: (((entry: JournalEntry) => void)) | undefined;\r\n onError?: (err: Error | undefined, iteration: number) => void;\r\n /**\r\n * Per-iteration phase notifications for live UI updates (TUI status bar,\r\n * etc.). Fires at each major stage transition: idle → decide → execute →\r\n * reflect → (sleep | paused | stopped). Fire-and-forget — the engine\r\n * does not await the callback.\r\n */\r\n onStage?: (((stage: IterationStage) => void)) | undefined;\r\n /**\r\n * Optional injected git status reader — production code uses git, tests\r\n * stub this out so they don't shell out.\r\n */\r\n gitStatusReader?: ((() => Promise<string>)) | undefined;\r\n /**\r\n * Optional clock — tests stub for deterministic timestamps.\r\n */\r\n now?: ((() => Date)) | undefined;\r\n /**\r\n * Optional compactor. When provided, the engine runs compaction every\r\n * `compactEveryNIterations` iterations to keep the agent's message\r\n * history under control during multi-day eternal loops. Without\r\n * compaction, an infinite loop will eventually overflow the provider's\r\n * context window and start failing.\r\n */\r\n compactor?: Compactor | undefined;\r\n /** How many iterations between compaction calls. Default 25. */\r\n compactEveryNIterations?: number | undefined;\r\n /**\r\n * Aggressive compaction threshold. When ctx token usage exceeds this\r\n * fraction of `maxContextTokens`, compaction runs in aggressive mode\r\n * regardless of the iteration cadence. 0.85 by default.\r\n */\r\n aggressiveCompactRatio?: number | undefined;\r\n /**\r\n * Model's max context window in tokens. When set, the engine watches\r\n * `currentRequestTokens()` against this and triggers aggressive compact\r\n * before the next iteration would overflow. Omit to disable threshold\r\n * checks (iteration cadence still applies).\r\n */\r\n maxContextTokens?: number | undefined;\r\n /**\r\n * Base delay (ms) for the first transient-error backoff. Subsequent\r\n * transient failures double this, capped at `transientBackoffMaxMs`.\r\n * Default 2_000.\r\n *\r\n * \"Transient\" means the underlying error is recoverable per\r\n * `WrongStackError.recoverable` (ProviderError sets this for 429/529/5xx\r\n * /network errors). Permanent errors (auth/invalid request) skip the\r\n * backoff and count toward `failureBudget` like before — backing off\r\n * on a permanent failure is wasted time.\r\n */\r\n transientBackoffBaseMs?: number | undefined;\r\n /** Ceiling for the exponential backoff. Default 60_000 (60 s). */\r\n transientBackoffMaxMs?: number | undefined;\r\n /** Called when the eternal loop stops for any reason (manual stop, goal complete, etc.). */\r\n onEternalStop?: ((() => void)) | undefined;\r\n /**\r\n * Optional brain arbiter for autonomous decision-making. When wired,\r\n * the engine consults the brain instead of auto-stopping on:\r\n * - Brainstorm DONE threshold reached\r\n * - Consecutive failures exceeding failure budget\r\n * - Goal completion verification\r\n * Without a brain, the engine uses its built-in heuristics.\r\n */\r\n brain?: BrainArbiter | undefined;\r\n /** Optional EventBus for emitting storage.* observability events from goal I/O. */\r\n events?: EventBus | undefined;\r\n}\r\n\r\nexport type EternalEngineState = 'idle' | 'running' | 'stopped';\r\n\r\n/**\r\n * Per-iteration phase emitted via `onStage` so UIs can render the\r\n * engine's live location in the sense-decide-execute-reflect loop.\r\n */\r\nexport type IterationStage =\r\n | { phase: 'idle' }\r\n | { phase: 'decide'; reason: string }\r\n | { phase: 'execute'; task: string }\r\n | { phase: 'reflect'; status: 'success' | 'failure' | 'aborted' | 'skipped'; note?: string | undefined }\r\n | { phase: 'sleep'; ms: number }\r\n | { phase: 'paused' }\r\n | { phase: 'stopped' }\r\n | { phase: 'error'; message: string };\r\n\r\ninterface DecidedAction {\r\n source: JournalEntry['source'];\r\n task: string;\r\n directive: string;\r\n /** Set when source === 'todo' so the engine can attribute failures. */\r\n todoId?: string | undefined;\r\n}\r\n\r\n/**\r\n * Sentinel returned by `brainstormTask` when the LLM declares the goal\r\n * fully accomplished. Distinct from `null` (which means \"brainstorm\r\n * failed / no actionable task right now\") so the engine can count\r\n * consecutive DONE answers toward a real stop.\r\n */\r\nconst BRAINSTORM_DONE = Symbol('brainstorm-done');\r\n\r\n/**\r\n * Free-text marker the model can emit (on its own line) to declare the\r\n * overall mission accomplished. Detected in the successful iteration's\r\n * `finalText`. When present, the engine flips `goalState='completed'`\r\n * and stops — the model has explicitly claimed completion AND the\r\n * iteration succeeded, which together is the most reliable stop signal\r\n * we can get without a separate verifier round-trip.\r\n */\r\nconst GOAL_COMPLETE_MARKER = /^\\s*\\[goal[_\\s-]*complete\\]\\s*$/im;\r\n\r\n/**\r\n * Free-text marker for the `/goal clear` command equivalent — when the\r\n * model emits this, the engine treats it as a manual goal clear (not just\r\n * completion) so the goal file is removed and onEternalStop fires.\r\n */\r\nconst GOAL_CLEAR_MARKER = /^\\s*\\[\\/?goal\\s*clear\\]\\s*$/im;\r\n\r\nexport class EternalAutonomyEngine {\r\n private state: EternalEngineState = 'idle';\r\n private stopRequested = false;\r\n private consecutiveFailures = 0;\r\n private consecutiveBrainstormDone = 0;\r\n /**\r\n * Count of consecutive transient (recoverable) provider failures. Drives\r\n * the exponential backoff between iterations. Reset on the first\r\n * successful iteration so a single bad afternoon doesn't permanently\r\n * slow the loop down.\r\n */\r\n private consecutiveTransientRetries = 0;\r\n private currentCtrl: AbortController | null = null;\r\n private iterationsSinceCompact = 0;\r\n private readonly goalPath: string;\r\n\r\n constructor(private readonly opts: EternalAutonomyOptions) {\r\n this.goalPath = goalFilePath(opts.projectRoot);\r\n }\r\n\r\n /** Current engine state — readable for UIs. */\r\n get currentState(): EternalEngineState {\r\n return this.state;\r\n }\r\n\r\n /** Synchronously request stop. Resolves once the running iteration aborts. */\r\n stop(): void {\r\n this.stopRequested = true;\r\n this.currentCtrl?.abort();\r\n // Best-effort: flip the persisted state so the next startup banner\r\n // doesn't report a phantom \"running\" engine. Fire-and-forget — if it\r\n // races with an in-flight iteration's write, the journal write wins\r\n // (engineState is metadata, not durable correctness).\r\n void this.persistEngineState('stopped').catch((err) => {\r\n console.error(JSON.stringify({\r\n level: 'error',\r\n event: 'engine.persist_state_failed',\r\n message: toErrorMessage(err),\r\n context: { expectedState: 'stopped' },\r\n timestamp: new Date().toISOString(),\r\n }));\r\n });\r\n this.state = 'stopped';\r\n }\r\n\r\n /**\r\n * Mark the engine as 'running' on disk + reset stop state so a new\r\n * batch of `runOneIteration()` calls can proceed. Called by the REPL\r\n * when the user invokes `/autonomy eternal`. Idempotent.\r\n */\r\n async prime(): Promise<void> {\r\n this.stopRequested = false;\r\n this.state = 'running';\r\n await this.persistEngineState('running').catch(() => {});\r\n }\r\n\r\n /**\r\n * Main loop. Returns when stop() is called or the goal file is removed.\r\n * Does NOT throw — every iteration is wrapped to keep the loop alive.\r\n */\r\n async run(): Promise<void> {\r\n this.state = 'running';\r\n await this.persistEngineState('running');\r\n\r\n try {\r\n while (!this.stopRequested) {\r\n let iterationOk = false;\r\n try {\r\n iterationOk = await this.runOneIteration();\r\n } catch (err) {\r\n this.consecutiveFailures++;\r\n this.opts.onError?.(err instanceof Error ? err : new Error(String(err)), this.consecutiveFailures);\r\n await this.appendFailure('engine error', toErrorMessage(err));\r\n }\r\n\r\n if (iterationOk) {\r\n this.consecutiveFailures = 0;\r\n }\r\n\r\n if (this.stopRequested) break;\r\n\r\n // Brief gap so SIGINT can land between iterations even if the\r\n // agent is bouncing back results fast. 0 by default for 24/7 mode.\r\n await sleep(this.opts.cycleGapMs ?? 0);\r\n }\r\n } finally {\r\n this.state = 'stopped';\r\n await this.persistEngineState('stopped').catch(() => {});\r\n }\r\n }\r\n\r\n /**\r\n * Execute a single sense-decide-execute-reflect cycle.\r\n * Returns true on success, false on handled failure / no-op.\r\n *\r\n * Exposed publicly so the REPL can pace iterations from its main loop\r\n * — running the engine and the REPL as a single sequential consumer of\r\n * `agent.run()` avoids race conditions on the shared Context.\r\n */\r\n async runOneIteration(): Promise<boolean> {\r\n // Emit stage transitions so UIs can render the engine's live location.\r\n const emit = (stage: IterationStage) => {\r\n this.opts.onStage?.(stage);\r\n };\r\n\r\n const goal = await loadGoal(this.goalPath, this.opts.events);\r\n if (!goal) {\r\n // Goal file disappeared — treat as a graceful stop.\r\n emit({ phase: 'stopped' });\r\n this.stopRequested = true;\r\n return false;\r\n }\r\n\r\n // Mission-level lifecycle gate.\r\n const missionState = goal.goalState ?? 'active';\r\n if (missionState !== 'active') {\r\n emit({ phase: missionState === 'paused' ? 'paused' : 'stopped' });\r\n this.stopRequested = true;\r\n return false;\r\n }\r\n\r\n emit({ phase: 'decide', reason: 'picking next task' });\r\n const action = await this.decide(goal);\r\n if (!action) {\r\n if (!this.stopRequested) {\r\n emit({ phase: 'sleep', ms: 5_000 });\r\n await sleep(5_000);\r\n } else {\r\n emit({ phase: 'stopped' });\r\n }\r\n return false;\r\n }\r\n\r\n emit({ phase: 'execute', task: action.task });\r\n\r\n const ctrl = new AbortController();\r\n this.currentCtrl = ctrl;\r\n const timer = setTimeout(\r\n () => ctrl.abort(),\r\n this.opts.iterationTimeoutMs ?? 5 * 60_000,\r\n );\r\n let status: JournalEntry['status'] = 'success';\r\n let note: string | undefined;\r\n let finalText = '';\r\n // Captured from `result.error?.recoverable` when the agent.run returns\r\n // a recoverable WrongStackError (ProviderError sets this for 429/529\r\n // /5xx/network). Drives the engine's exponential backoff so a\r\n // transient rate-limit storm doesn't burn the failure budget in\r\n // seconds. Permanent errors leave this false and trip the normal\r\n // consecutiveFailures path.\r\n let isTransientFailure = false;\r\n\r\n // Snapshot usage before so the iteration delta can be journaled.\r\n // Token counter is optional in mock/test contexts — guard accordingly.\r\n const tc = this.opts.agent.ctx?.tokenCounter;\r\n const beforeUsage = tc?.total?.();\r\n const beforeCost = tc?.estimateCost?.().total;\r\n\r\n try {\r\n const result = await this.opts.agent.run(\r\n [{ type: 'text' as const, text: action.directive }],\r\n {\r\n signal: ctrl.signal,\r\n // Enable per-call autonomous continuation so the agent can chain\r\n // multiple internal tool/response cycles end-to-end on one\r\n // directive instead of returning to the engine after a single\r\n // round-trip. The model uses `[continue]` / `[done]` markers\r\n // (or the `continue_to_next_iteration` tool) to control the\r\n // inner loop. Without this flag the engine produced shallow\r\n // iterations and almost never let a real task finish.\r\n autonomousContinue: true,\r\n // Cap the inner loop so a runaway agent.run can't burn through\r\n // the iteration timeout — the engine's own outer loop is the\r\n // long-running thing, each tick should be bounded.\r\n maxIterations: this.opts.iterationMaxAgentSteps ?? 500,\r\n },\r\n );\r\n\r\n if (result.status === 'aborted') {\r\n status = 'aborted';\r\n note = 'stopped by user';\r\n } else if (result.status === 'failed') {\r\n status = 'failure';\r\n note = result.error?.describe?.() ?? 'agent run failed';\r\n isTransientFailure = result.error?.recoverable === true;\r\n } else if (result.status === 'max_iterations') {\r\n status = 'failure';\r\n note = `max iterations (${result.iterations})`;\r\n } else {\r\n status = 'success';\r\n finalText = result.finalText ?? '';\r\n const tail = finalText.slice(0, 240).replace(/\\s+/g, ' ').trim();\r\n if (tail) note = tail;\r\n }\r\n } catch (err) {\r\n const isAbort = err instanceof Error && (err.name === 'AbortError' || err.message.includes('abort'));\r\n status = isAbort ? 'aborted' : 'failure';\r\n note = toErrorMessage(err);\r\n // Surface .recoverable on the thrown WrongStackError too — provider\r\n // errors that escape the agent's catch (rare; usually wrapped into\r\n // result.error) still classify correctly.\r\n if (\r\n !isAbort &&\r\n typeof (err as { recoverable?: unknown | undefined })?.recoverable === 'boolean'\r\n ) {\r\n isTransientFailure = (err as { recoverable: boolean }).recoverable;\r\n }\r\n } finally {\r\n clearTimeout(timer);\r\n this.currentCtrl = null;\r\n }\r\n\r\n // Per-todo attempt accounting. On failure of a todo-sourced action,\r\n // bump the persistent counter so `decide()` can rotate past it once\r\n // it crosses the configured ceiling. Successful runs leave the\r\n // counter untouched — the LLM is responsible for flipping the todo\r\n // status to `completed` via the todos tool (directive teaches this).\r\n if (action.source === 'todo' && action.todoId && status !== 'success') {\r\n await this.bumpTodoAttempt(action.todoId);\r\n }\r\n\r\n // Capture per-iteration usage delta. Cost is always non-negative;\r\n // if the counter wraps or resets mid-iteration we clamp to 0 so the\r\n // journal never shows negative spend.\r\n const afterUsage = tc?.total?.();\r\n const afterCost = tc?.estimateCost?.().total;\r\n const tokens =\r\n beforeUsage && afterUsage\r\n ? {\r\n input: Math.max(0, afterUsage.input - beforeUsage.input),\r\n output: Math.max(0, afterUsage.output - beforeUsage.output),\r\n }\r\n : undefined;\r\n const costUsd =\r\n typeof beforeCost === 'number' && typeof afterCost === 'number'\r\n ? Math.max(0, afterCost - beforeCost)\r\n : undefined;\r\n\r\n await this.appendIterationEntry({\r\n source: action.source,\r\n task: action.task,\r\n status,\r\n note,\r\n tokens,\r\n costUsd,\r\n });\r\n\r\n emit({ phase: 'reflect', status, note });\r\n\r\n // Re-read the goal so we can emit the real iteration counter rather\r\n // than the previous placeholder. If the goal was unlinked mid-flight\r\n // (graceful stop via /goal clear) the iteration index is still\r\n // useful — fall back to the in-memory consecutiveFailures-derived\r\n // approximation only as a last resort.\r\n let iterationIndex = 0;\r\n try {\r\n const reloaded = await loadGoal(this.goalPath, this.opts.events);\r\n iterationIndex = reloaded?.iterations ?? 0;\r\n } catch {\r\n // best-effort\r\n }\r\n this.opts.onIteration?.({\r\n at: (this.opts.now?.() ?? new Date()).toISOString(),\r\n iteration: iterationIndex,\r\n source: action.source,\r\n task: action.task,\r\n status,\r\n note,\r\n tokens,\r\n costUsd,\r\n });\r\n\r\n // Transient failure — sleep with interruptible backoff before retry.\r\n if (status === 'failure') {\r\n if (isTransientFailure) {\r\n this.consecutiveTransientRetries++;\r\n const delay = this.computeTransientBackoffMs();\r\n if (delay > 0) {\r\n emit({ phase: 'sleep', ms: delay });\r\n await this.sleepInterruptible(delay);\r\n }\r\n return false;\r\n }\r\n this.consecutiveFailures++;\r\n return false;\r\n }\r\n\r\n if (status === 'aborted') {\r\n if (this.stopRequested) return false;\r\n this.consecutiveFailures++;\r\n return false;\r\n }\r\n\r\n // Successful iteration\r\n this.consecutiveTransientRetries = 0;\r\n const cycleGapMs = this.opts.cycleGapMs ?? 1000;\r\n emit({ phase: 'sleep', ms: cycleGapMs });\r\n await sleep(cycleGapMs);\r\n\r\n // Goal-complete detection. The model emits `[GOAL_COMPLETE]` on its\r\n // own line in `finalText` when the overall mission is verifiably done.\r\n // Combined with a successful iteration this is a strong stop signal:\r\n // the LLM explicitly claimed completion AND the run did not fail. We\r\n // mark the goal `completed`, journal it, and stop. No separate\r\n // verifier round-trip — keeps cost down; if the model lies, the user\r\n // notices and can re-arm with `/goal set`.\r\n if (GOAL_COMPLETE_MARKER.test(finalText)) {\r\n // Treat GOAL_COMPLETE as a full goal clear: remove the goal file and\r\n // fire onEternalStop so the REPL exits eternal mode. Stronger than\r\n // just marking completed — the REPL needs both to happen.\r\n await this.clearGoalManually(finalText);\r\n this.stopRequested = true;\r\n return true;\r\n }\r\n // Goal-clear detection — model emits `[goal clear]` equivalent to\r\n // `/goal clear`. Treat as a manual stop: remove the goal file and fire\r\n // onEternalStop so the REPL knows to return to normal mode.\r\n if (GOAL_CLEAR_MARKER.test(finalText)) {\r\n await this.clearGoalManually(finalText);\r\n this.stopRequested = true;\r\n return true;\r\n }\r\n\r\n // ── Progress tracking ──\r\n // Parse [PROGRESS: N%] from the agent's final text and persist it.\r\n // Also auto-complete the goal when the agent reports 100% progress.\r\n const parsed = parseProgressFromText(finalText);\r\n if (parsed) {\r\n await this.updateProgress(parsed.progress, parsed.note);\r\n if (parsed.progress >= 100) {\r\n // Agent claims 100% — add a final journal entry and complete.\r\n await this.markGoalCompleted(\r\n { source: action.source, task: action.task, directive: action.directive },\r\n `progress reached 100%: ${parsed.note ?? 'goal complete'}`,\r\n );\r\n this.stopRequested = true;\r\n return true;\r\n }\r\n }\r\n\r\n // Compaction runs only on successful iterations — there's no point\r\n // compacting after a failed/aborted iteration that didn't add much to\r\n // the message history.\r\n this.iterationsSinceCompact++;\r\n await this.maybeCompact().catch((err) => {\r\n // Don't let compaction failure kill the loop; surface via onError.\r\n this.opts.onError?.(\r\n err instanceof Error ? err : new Error(String(err)),\r\n this.consecutiveFailures,\r\n );\r\n });\r\n return true;\r\n }\r\n\r\n /**\r\n * Run compaction when either trigger fires:\r\n * - We've done >= compactEveryNIterations since the last compact.\r\n * - Current request tokens exceed aggressiveCompactRatio * maxContext.\r\n *\r\n * The second check uses *aggressive* mode to free more headroom; the\r\n * cadence check uses non-aggressive (cheaper).\r\n */\r\n private async maybeCompact(): Promise<void> {\r\n const compactor = this.opts.compactor;\r\n if (!compactor) return;\r\n const ctx = this.opts.agent.ctx;\r\n if (!ctx) return;\r\n\r\n const cadence = this.opts.compactEveryNIterations ?? 25;\r\n const threshold = this.opts.aggressiveCompactRatio ?? 0.85;\r\n const maxCtx = this.opts.maxContextTokens;\r\n\r\n let aggressive = false;\r\n let shouldRun = false;\r\n\r\n if (this.iterationsSinceCompact >= cadence) {\r\n shouldRun = true;\r\n }\r\n\r\n if (maxCtx && maxCtx > 0) {\r\n const used = ctx.tokenCounter?.currentRequestTokens?.();\r\n if (used) {\r\n const total = used.input + used.cacheRead;\r\n if (total / maxCtx >= threshold) {\r\n shouldRun = true;\r\n aggressive = true;\r\n }\r\n }\r\n }\r\n\r\n if (!shouldRun) return;\r\n\r\n const report = await compactor.compact(ctx, { aggressive });\r\n this.iterationsSinceCompact = 0;\r\n // Journal the compaction event so users see it in /goal journal.\r\n const saved = report.before - report.after;\r\n await this.appendIterationEntry({\r\n source: 'manual',\r\n task: `compaction (${aggressive ? 'aggressive' : 'cadence'})`,\r\n status: 'success',\r\n note: `saved ~${saved} tokens (${report.before}→${report.after})`,\r\n });\r\n }\r\n\r\n /**\r\n * Hybrid idea source.\r\n * 1. Pending todos on the agent's context.\r\n * 2. Dirty git working tree → propose a \"review and finish this\" task.\r\n * 3. Otherwise: brainstorm via the LLM against the goal.\r\n *\r\n * After failureBudget consecutive failures, force brainstorm so the\r\n * engine doesn't loop on the same broken todo or stuck git state.\r\n */\r\n private async decide(goal: GoalFile): Promise<DecidedAction | null> {\r\n const forceBrainstorm = this.consecutiveFailures >= (this.opts.failureBudget ?? 3);\r\n\r\n if (!forceBrainstorm) {\r\n const todo = this.pickPendingTodo(goal);\r\n if (todo) {\r\n return {\r\n source: 'todo',\r\n task: todo.content,\r\n todoId: todo.id,\r\n directive: this.buildDirective(goal, 'todo', todo.content),\r\n };\r\n }\r\n\r\n const gitTask = await this.pickGitTask();\r\n if (gitTask) {\r\n return {\r\n source: 'git',\r\n task: gitTask,\r\n directive: this.buildDirective(goal, 'git', gitTask),\r\n };\r\n }\r\n }\r\n\r\n const brainstormed = await this.brainstormTask(goal);\r\n if (brainstormed === BRAINSTORM_DONE) {\r\n this.consecutiveBrainstormDone++;\r\n const threshold = this.opts.brainstormDoneStopThreshold ?? 3;\r\n if (this.consecutiveBrainstormDone >= threshold) {\r\n // Consult the brain before stopping — it may decide to continue\r\n const shouldStop = await this.consultBrainForDone(goal);\r\n if (shouldStop) {\r\n await this.markGoalCompleted(\r\n { source: 'brainstorm', task: 'no further work', directive: '' },\r\n `brainstorm returned DONE ${this.consecutiveBrainstormDone}x in a row${this.opts.brain ? ', brain confirmed' : ''}`,\r\n );\r\n this.stopRequested = true;\r\n } else {\r\n // Brain says keep going — reset the DONE streak\r\n this.consecutiveBrainstormDone = 0;\r\n }\r\n }\r\n return null;\r\n }\r\n if (!brainstormed) return null;\r\n // Got a real task — reset the DONE streak.\r\n this.consecutiveBrainstormDone = 0;\r\n return {\r\n source: 'brainstorm',\r\n task: brainstormed,\r\n directive: this.buildDirective(goal, 'brainstorm', brainstormed),\r\n };\r\n }\r\n\r\n private pickPendingTodo(goal: GoalFile): TodoItem | null {\r\n const todos = this.opts.agent.ctx.todos;\r\n if (!Array.isArray(todos)) return null;\r\n const attempts = goal.todoAttempts ?? {};\r\n const ceiling = this.opts.todoMaxAttempts ?? 3;\r\n // First-pending strategy with a stuck-task escape hatch: if the\r\n // first pending todo has already failed `ceiling` times, fall\r\n // through to later pending todos. Returns null when every pending\r\n // todo is stuck — the caller will fall through to git/brainstorm.\r\n for (const t of todos) {\r\n if (t.status !== 'pending') continue;\r\n const used = attempts[t.id] ?? 0;\r\n if (used >= ceiling) continue;\r\n return t;\r\n }\r\n return null;\r\n }\r\n\r\n private async pickGitTask(): Promise<string | null> {\r\n let out: string;\r\n try {\r\n out = await (this.opts.gitStatusReader?.() ?? this.readGitStatus());\r\n } catch {\r\n return null;\r\n }\r\n const dirty = out.trim();\r\n if (!dirty) return null;\r\n // Surface a concise prompt — the agent will look at the diff itself.\r\n const lines = dirty.split('\\n').slice(0, 8);\r\n const preview = lines.join(', ');\r\n return `Inspect the dirty working tree and either finish the in-progress work or revert it. Files: ${preview}`;\r\n }\r\n\r\n private async readGitStatus(): Promise<string> {\r\n const { stdout } = await execFileP('git', ['status', '--porcelain'], {\r\n cwd: this.opts.projectRoot,\r\n timeout: 5_000,\r\n });\r\n return stdout;\r\n }\r\n\r\n private async brainstormTask(goal: GoalFile): Promise<string | null | typeof BRAINSTORM_DONE> {\r\n const lastFew = goal.journal\r\n .slice(-5)\r\n .map((e) => ` - [${e.status}] ${e.task}`)\r\n .join('\\n');\r\n const directive = [\r\n 'You are deciding the next action in an autonomous loop pursuing a long-running goal.',\r\n '',\r\n `Goal: ${goal.goal}`,\r\n '',\r\n lastFew ? `Recent iterations:\\n${lastFew}` : 'No prior iterations yet.',\r\n '',\r\n 'Output ONE concrete, immediately-actionable task that advances the goal.',\r\n 'Constraints:',\r\n '- One sentence, imperative form, under 200 chars.',\r\n '- No preamble, no explanation, no markdown — just the task line.',\r\n '- If recent iterations show repeated failures on the same target, pivot.',\r\n '- If the goal appears fully accomplished AND you can name a concrete',\r\n ' artifact / test / output that proves it, output exactly: DONE',\r\n '- Be conservative with DONE: if the recent journal contains failures',\r\n ' or aborted entries, the goal is almost certainly NOT done.',\r\n ].join('\\n');\r\n\r\n try {\r\n const ctrl = new AbortController();\r\n const timer = setTimeout(() => ctrl.abort(), 60_000);\r\n try {\r\n const result = await this.opts.agent.run(\r\n [{ type: 'text' as const, text: directive }],\r\n { signal: ctrl.signal, maxIterations: 1 },\r\n );\r\n if (result.status !== 'done') return null;\r\n const text = (result.finalText ?? '').trim();\r\n if (!text) return null;\r\n // Distinct sentinel for DONE so the caller can count consecutive\r\n // DONE answers toward a real stop. The old `return null` path\r\n // conflated \"no work\" with \"engine failure\" and looped forever.\r\n if (/^DONE\\.?$/i.test(text)) return BRAINSTORM_DONE;\r\n // Take the first non-empty line and clip to 240 chars.\r\n const firstLine = text.split('\\n').find((l) => l.trim().length > 0)?.trim();\r\n if (!firstLine) return null;\r\n if (/^DONE\\.?$/i.test(firstLine)) return BRAINSTORM_DONE;\r\n return firstLine.slice(0, 240);\r\n } finally {\r\n clearTimeout(timer);\r\n }\r\n } catch {\r\n return null;\r\n }\r\n }\r\n\r\n private buildDirective(goal: GoalFile, source: JournalEntry['source'], task: string): string {\r\n const recentJournal = goal.journal\r\n .slice(-5)\r\n .map((e) => ` #${e.iteration} [${e.status}] ${e.task}${e.note ? ` — ${e.note.slice(0, 80)}` : ''}`)\r\n .join('\\n');\r\n return [\r\n '═══ ETERNAL AUTONOMY — iteration directive ═══',\r\n '',\r\n `Mission: ${goal.goal}`,\r\n `Iteration: #${goal.iterations + 1}`,\r\n `Source: ${source}`,\r\n `Task: ${task}`,\r\n '',\r\n recentJournal ? `Recent journal (last 5):\\n${recentJournal}` : 'No prior iterations.',\r\n '',\r\n '── EXECUTION PROTOCOL ──',\r\n 'You are inside a long-running autonomous loop. Each iteration you',\r\n 'execute ONE concrete task that advances the Mission. No user is',\r\n 'available to clarify — make defensible decisions and move forward.',\r\n '',\r\n '1. EXECUTE END-TO-END',\r\n ' • Use multiple tool calls freely. Emit `[continue]` on its own line',\r\n ' to chain to the next internal step without returning.',\r\n ' • When this iteration\\'s Task is finished (real artifact / passing',\r\n ' test / applied diff / clean output), emit `[done]` on its own line.',\r\n ' • Do not stop on the first obstacle — try at least 3 distinct',\r\n ' approaches before giving up. YOLO is active for normal project work;',\r\n ' destructive-gated confirmations still belong to the permission flow.',\r\n '',\r\n '2. UPDATE TODO STATE (when Source is `todo`)',\r\n ' • Mark this todo `in_progress` via the todos tool before tool work.',\r\n ' • Mark it `completed` on success, with a one-line outcome note.',\r\n ' • If you cannot make progress after 2 distinct attempts, mark it',\r\n ' `cancelled` with the obstacle. The loop will skip it next time.',\r\n '',\r\n '3. MISSION-COMPLETE PROTOCOL',\r\n ' • If — and ONLY if — the OVERALL Mission (not just this Task) is',\r\n ' verifiably accomplished, emit on its own line:',\r\n ' [GOAL_COMPLETE]',\r\n ' followed by a one-paragraph verification recipe (artifact path,',\r\n ' test command, or 10-second reproduction). This halts the loop.',\r\n ' • NEVER emit [GOAL_COMPLETE] on optimism, partial progress, or',\r\n ' \"looks fine\". Required: a concrete artifact that proves it AND',\r\n ' no recent journal failures contradicting completion.',\r\n ' • If unsure, emit `[done]` instead and let the next iteration',\r\n ' decide. The loop is patient; false completion is not.',\r\n '',\r\n '4. NO INTERACTIVITY',\r\n ' • Do not ask questions, do not request confirmation, do not propose',\r\n ' options. Pick the best path and execute. The user is asleep.',\r\n ].join('\\n');\r\n }\r\n\r\n /**\r\n * Exponential backoff for transient provider errors. `2^N * base`\r\n * capped at `transientBackoffMaxMs`. Zero base disables backoff.\r\n * Public-private to keep `runOneIteration` readable; the value is\r\n * recomputed each call from the current retry count, so callers\r\n * don't have to track state.\r\n */\r\n private computeTransientBackoffMs(): number {\r\n const base = this.opts.transientBackoffBaseMs ?? 2_000;\r\n const cap = this.opts.transientBackoffMaxMs ?? 60_000;\r\n if (base <= 0) return 0;\r\n const exponent = Math.max(0, this.consecutiveTransientRetries - 1);\r\n return Math.min(cap, base * 2 ** exponent);\r\n }\r\n\r\n /**\r\n * Sleep that wakes early if `stopRequested` flips. Polls every 250 ms\r\n * so SIGINT / `/autonomy stop` can land in the middle of a long\r\n * backoff instead of waiting up to a minute for the timer.\r\n */\r\n private async sleepInterruptible(totalMs: number): Promise<void> {\r\n const step = 250;\r\n let remaining = totalMs;\r\n while (remaining > 0 && !this.stopRequested) {\r\n const chunk = Math.min(step, remaining);\r\n await sleep(chunk);\r\n remaining -= chunk;\r\n }\r\n }\r\n\r\n private async appendIterationEntry(entry: Omit<JournalEntry, 'iteration' | 'at'>): Promise<void> {\r\n const current = await loadGoal(this.goalPath, this.opts.events);\r\n if (!current) {\r\n // Goal was cleared mid-iteration; nothing to write to.\r\n return;\r\n }\r\n const updated = appendJournal(current, entry);\r\n await saveGoal(this.goalPath, updated, this.opts.events);\r\n }\r\n\r\n /**\r\n * Persistent per-todo failure counter. Skipped silently when the goal\r\n * file has been removed (graceful clear). Each non-success iteration\r\n * against a todo source bumps the counter by 1; `pickPendingTodo` reads\r\n * the counter to rotate past stuck todos once they cross `todoMaxAttempts`.\r\n */\r\n private async bumpTodoAttempt(todoId: string): Promise<void> {\r\n const current = await loadGoal(this.goalPath, this.opts.events);\r\n if (!current) return;\r\n const attempts = { ...(current.todoAttempts ?? {}) };\r\n attempts[todoId] = (attempts[todoId] ?? 0) + 1;\r\n await saveGoal(this.goalPath, { ...current, todoAttempts: attempts }, this.opts.events);\r\n }\r\n\r\n /**\r\n * Flip the mission to `completed` and journal it. Called from two\r\n * paths: (a) `[GOAL_COMPLETE]` marker in a successful iteration's\r\n * finalText, (b) `brainstorm` returning DONE consecutively past the\r\n * configured threshold. Idempotent — re-entry is a no-op once the\r\n * goal is already `completed`.\r\n */\r\n private async markGoalCompleted(\r\n action: { source: JournalEntry['source']; task: string; directive: string },\r\n note: string,\r\n ): Promise<void> {\r\n const current = await loadGoal(this.goalPath, this.opts.events);\r\n if (!current) return;\r\n if (current.goalState === 'completed') return;\r\n const withFlag: GoalFile = { ...current, goalState: 'completed' };\r\n const withEntry = appendJournal(withFlag, {\r\n source: action.source,\r\n task: `MISSION COMPLETE — ${action.task}`.slice(0, 240),\r\n status: 'success',\r\n note: note.slice(0, 240),\r\n });\r\n await saveGoal(this.goalPath, withEntry, this.opts.events);\r\n // Fire stop callbacks so the REPL knows to exit eternal mode\r\n // and show a goal-completion banner. Without this the engine\r\n // stops internally but the REPL keeps spinning in the eternal loop.\r\n this.opts.onEternalStop?.();\r\n }\r\n\r\n /**\r\n * Manually clear the goal — equivalent to `/goal clear` typed by the user.\r\n * Sets goalState to `abandoned`, removes the goal file, and fires\r\n * `onEternalStop` so the REPL returns to normal mode.\r\n */\r\n private async clearGoalManually(note: string): Promise<void> {\r\n const current = await loadGoal(this.goalPath, this.opts.events);\r\n if (current) {\r\n const abandoned: GoalFile = { ...current, goalState: 'abandoned' };\r\n await saveGoal(this.goalPath, abandoned, this.opts.events);\r\n }\r\n try {\r\n const { unlink } = await import('node:fs/promises');\r\n await unlink(this.goalPath);\r\n } catch {\r\n // best-effort — file may already be gone\r\n }\r\n this.opts.onEternalStop?.();\r\n void this.appendIterationEntry({\r\n source: 'manual',\r\n task: 'goal cleared',\r\n status: 'success',\r\n note: note.slice(0, 240),\r\n });\r\n }\r\n\r\n private async appendFailure(task: string, note: string): Promise<void> {\r\n await this.appendIterationEntry({ source: 'manual', task, status: 'failure', note });\r\n }\r\n\r\n /**\r\n * Consult the brain on whether the goal is truly complete.\r\n * Without a brain, always returns true (use heuristic: DONE threshold met = done).\r\n */\r\n private async consultBrainForDone(goal: GoalFile): Promise<boolean> {\r\n if (!this.opts.brain) return true; // No brain — trust the heuristic\r\n\r\n const deliverablesStatus = goal.deliverables?.length\r\n ? `\\nDeliverables: ${goal.deliverables.length} total, progress ${goal.progress ?? 'unknown'}%`\r\n : '';\r\n const recentJournal = goal.journal.slice(-5).map(e =>\r\n ` #${e.iteration} [${e.status}] ${e.task}`\r\n ).join('\\n');\r\n\r\n try {\r\n const decision = await this.opts.brain.decide({\r\n id: `goal-done-${goal.iterations}`,\r\n source: 'system',\r\n question: `Brainstorm returned DONE ${this.consecutiveBrainstormDone}x. Is the goal truly complete?`,\r\n context: [\r\n `Goal: ${goal.goal}`,\r\n `Iterations: ${goal.iterations}`,\r\n `Progress: ${goal.progress ?? 'unknown'}%`,\r\n deliverablesStatus,\r\n recentJournal ? `\\nRecent work:\\n${recentJournal}` : '',\r\n ].join('\\n'),\r\n risk: 'high',\r\n fallback: 'continue',\r\n });\r\n\r\n // Log the brain decision into the journal\r\n const summary = formatDecisionSummary(decision, {\r\n id: `goal-done-${goal.iterations}`,\r\n source: 'system',\r\n question: 'Is the goal complete?',\r\n risk: 'high',\r\n fallback: 'continue',\r\n });\r\n const rationale = 'rationale' in decision ? decision.rationale : undefined;\r\n await this.appendIterationEntry({\r\n source: 'brainstorm',\r\n task: summary,\r\n status: 'success',\r\n note: rationale,\r\n });\r\n\r\n if (decision.type === 'deny') {\r\n return false;\r\n }\r\n if (decision.type === 'answer') {\r\n const text = decision.text.toLowerCase();\r\n return text.includes('complete') || text.includes('done') || text.includes('yes');\r\n }\r\n return true;\r\n } catch {\r\n return true;\r\n }\r\n }\r\n\r\n /**\r\n * Persist a progress update from the agent's [PROGRESS: N%] output.\r\n */\r\n private async updateProgress(progress: number, note?: string): Promise<void> {\r\n const current = await loadGoal(this.goalPath, this.opts.events);\r\n if (!current) return;\r\n const updated = recordProgress(current, progress, note);\r\n await saveGoal(this.goalPath, updated, this.opts.events);\r\n }\r\n\r\n private async persistEngineState(state: GoalFile['engineState']): Promise<void> {\r\n const current = await loadGoal(this.goalPath, this.opts.events);\r\n if (!current) return;\r\n if (current.engineState === state) return;\r\n await saveGoal(this.goalPath, { ...current, engineState: state }, this.opts.events);\r\n }\r\n}\r\n","import type { Usage } from '../types/provider.js';\nimport type { EventBus } from '../kernel/events.js';\n\nexport type BudgetKind = 'tool_calls' | 'iterations' | 'tokens' | 'timeout' | 'idle_timeout' | 'cost';\n\n/**\n * Fraction of the wall-clock `timeoutMs` window at which a PROACTIVE extension\n * is negotiated — BEFORE the deadline is actually crossed. The coordinator\n * watchdog (`executeWithTimeout`) arms at `timeoutMs * TIMEOUT_PREEMPT_FRACTION`\n * so a still-progressing subagent gets its ceiling raised while it is below the\n * limit, and never enters a \"timed out\" state. Reactive enforcement at the real\n * deadline still stands for the no-progress / denied case. Shared so the asking\n * side and any future caller agree on the same lead point.\n */\nexport const TIMEOUT_PREEMPT_FRACTION = 0.85;\n\n/**\n * Hard safety net for budget negotiation decisions. If no listener responds to\n * `budget.threshold_reached` within this window the negotiation defaults to\n * `'stop'`. Exported so the coordinator's watchdog can reuse the same ceiling\n * without hardcoding a second copy.\n */\nexport const DECISION_TIMEOUT_MS = 60_000;\n\nexport class BudgetExceededError extends Error {\n readonly kind: BudgetKind;\n readonly limit: number;\n readonly observed: number;\n\n constructor(kind: BudgetKind, limit: number, observed: number) {\n super(`Budget exceeded: ${kind} (limit=${limit}, observed=${observed})`);\n this.name = 'BudgetExceededError';\n this.kind = kind;\n this.limit = limit;\n this.observed = observed;\n }\n}\n\nexport interface BudgetLimits {\n maxIterations?: number | undefined;\n maxToolCalls?: number | undefined;\n maxTokens?: number | undefined;\n /** Estimated USD cost ceiling. */\n maxCostUsd?: number | undefined;\n /**\n * Hard wall-clock timeout measured from `start()`. Off by default — set it\n * explicitly only when a task must finish within an absolute window. For\n * the everyday \"don't kill an agent that's still working\" guard, prefer\n * `idleTimeoutMs`, which resets on activity.\n */\n timeoutMs?: number | undefined;\n /**\n * Idle timeout: the maximum gap (ms) between activity signals (iterations,\n * tool calls, token usage, streamed progress) before the subagent is\n * considered hung and reaped. Unlike `timeoutMs`, an actively-working\n * agent continuously resets this clock via `markActivity()`, so it never\n * trips on a long-but-productive run — only on a genuine stall.\n */\n idleTimeoutMs?: number | undefined;\n}\n\n/**\n * Controls how the budget behaves when `onThreshold` is set and a limit is hit.\n *\n * `'auto'` — emit `budget.threshold_reached` on the EventBus and wait for a\n * coordinator response (extend/stop). If no listener responds within\n * `DECISION_TIMEOUT_MS` the decision defaults to `'stop'`.\n * `'sync'` — do not emit any event; treat the threshold as a hard stop and\n * throw `BudgetExceededError` synchronously. Useful for fire-and-forget\n * subagents that have an `onThreshold` handler for logging/metrics but are\n * not wired into a coordinator.\n *\n * @default 'auto'\n */\nexport type BudgetNegotiationMode = 'auto' | 'sync';\n\nexport interface BudgetUsage {\n iterations: number;\n toolCalls: number;\n tokens: { input: number; output: number; total: number };\n costUsd: number;\n elapsedMs: number;\n}\n\n/**\n * Thrown by `SubagentBudget.record*` when a soft limit is hit and\n * an `onThreshold` handler is configured that wants to ask the\n * coordinator (via `budget.threshold_reached` event). The runner\n * catches this and awaits the embedded `decision` promise to get\n * the coordinator's extend/stop decision.\n *\n * Distinct from `BudgetExceededError` which is a hard stop.\n */\nexport class BudgetThresholdSignal extends Error {\n readonly kind: BudgetKind;\n readonly limit: number;\n readonly used: number;\n /** Resolves to 'extend' (with optional new limits) or 'stop' */\n readonly decision: Promise<BudgetThresholdDecision>;\n\n constructor(\n kind: BudgetKind,\n limit: number,\n used: number,\n decision: Promise<BudgetThresholdDecision>,\n ) {\n super(`Budget soft limit: ${kind} (limit=${limit}, used=${used})`);\n this.name = 'BudgetThresholdSignal';\n this.kind = kind;\n this.limit = limit;\n this.used = used;\n this.decision = decision;\n }\n}\n\nexport type BudgetThresholdDecision =\n | 'stop'\n | { extend: Partial<BudgetLimits> };\n\n/**\n * Callback invoked when a budget limit is about to be exceeded.\n * Return 'throw' for hard stop (default — throws BudgetExceededError).\n * Return 'continue' to allow one more unit and re-check next time.\n * Return a Promise to ask the coordinator via `budget.threshold_reached`\n * event (uses the same grant/deny pattern as `iteration.limit_reached`).\n */\nexport type BudgetThresholdHandler = (info: {\n kind: BudgetKind;\n used: number;\n limit: number;\n requestDecision: () => Promise<BudgetThresholdDecision>;\n /**\n * Direct grant/deny hooks for SYNCHRONOUS policy or recording handlers that\n * decide in-process without a wired `budget.threshold_reached` listener\n * (e.g. the coordinator watchdog). `extend` patches the limits in place;\n * `deny` records the intent to stop. Production listener-driven handlers use\n * `requestDecision()` instead and can ignore these.\n */\n extend?: (extra: Partial<BudgetLimits>) => void;\n deny?: () => void;\n}) => 'throw' | 'continue' | 'stop' | { extend: Partial<BudgetLimits> } | Promise<BudgetThresholdDecision>;\n\n/**\n * Per-subagent budget enforcement. Each subagent gets its own instance so a\n * runaway agent can't drain the cost ceiling of its siblings. All record/check\n * methods are O(1) and safe to call from hot paths.\n *\n * Behavior without `onThreshold`: hard stops synchronously on every limit hit.\n *\n * Behavior with `onThreshold` and `_mode === 'auto'`: emits `budget.threshold_reached`\n * on the EventBus and throws `BudgetThresholdSignal`. The coordinator's verdict\n * (extend/stop) resolves the embedded promise. If no listener responds within\n * `DECISION_TIMEOUT_MS` the decision defaults to `'stop'`.\n *\n * Behavior with `onThreshold` and `_mode === 'sync'`: throws `BudgetExceededError`\n * synchronously regardless of EventBus state or listener presence. This is useful\n * for fire-and-forget subagents that have an `onThreshold` handler for logging/metrics\n * but are not wired into a coordinator — the `'sync'` mode makes the hard-stop\n * behavior explicit and means tests can use `expect().toThrow()` even without\n * a fully-wired EventBus.\n */\nexport class SubagentBudget {\n readonly limits: Readonly<BudgetLimits>;\n\n /** Patch one or more budget limits in-place after construction.\n * Used by the coordinator watchdog when granting an extension.\n * All fields are optional — only provided fields are updated.\n * This is the single write path for limit mutations so that future\n * validation or side-effects live in one place (M1). */\n patchLimits(ext: Partial<BudgetLimits>): void {\n if (ext.maxIterations !== undefined) {\n (this.limits as Record<string, unknown>).maxIterations = ext.maxIterations;\n }\n if (ext.maxToolCalls !== undefined) {\n (this.limits as Record<string, unknown>).maxToolCalls = ext.maxToolCalls;\n }\n if (ext.maxTokens !== undefined) {\n (this.limits as Record<string, unknown>).maxTokens = ext.maxTokens;\n }\n if (ext.maxCostUsd !== undefined) {\n (this.limits as Record<string, unknown>).maxCostUsd = ext.maxCostUsd;\n }\n if (ext.timeoutMs !== undefined) {\n (this.limits as Record<string, unknown>).timeoutMs = ext.timeoutMs;\n }\n if (ext.idleTimeoutMs !== undefined) {\n (this.limits as Record<string, unknown>).idleTimeoutMs = ext.idleTimeoutMs;\n }\n }\n private iterations = 0;\n private toolCalls = 0;\n private tokenInput = 0;\n private tokenOutput = 0;\n private costUsd = 0;\n private startTime: number | null = null;\n /**\n * Timestamp of the most recent activity (iteration / tool call / token\n * usage / streamed progress). Drives the idle timeout — reset by\n * `markActivity()`. Initialised to `start()` time so a never-active agent\n * still eventually trips its idle window.\n */\n private lastActivityTime: number | null = null;\n private _onThreshold: BudgetThresholdHandler | undefined;\n /**\n * Hard cap on how long `_negotiateExtension` waits for the coordinator to\n * respond before defaulting to 'stop'. Without this fallback an absent\n * or hung listener (Director not built / event filter detached mid-run)\n * leaves the budget over-limit and never enforces anything.\n */\n private static readonly DECISION_TIMEOUT_MS = DECISION_TIMEOUT_MS;\n /**\n * Injected by the runner when wiring the budget to its EventBus.\n * Used to emit `budget.threshold_reached` events in `'auto'` mode.\n */\n _events?: EventBus | undefined;\n\n /**\n * Guard against dual-path races between the coordinator watchdog\n * (`executeWithTimeout`) and the budget's own `checkTimeout()`.\n * Both paths detect `elapsed >= timeoutMs` and can emit\n * `budget.threshold_reached` for kind `'timeout'` simultaneously.\n * Set to the current `timeoutMs` ceiling by the coordinator BEFORE\n * calling `onThreshold`, and cleared after the negotiation resolves.\n * `checkTimeout()` skips its wall-clock check while this is set so\n * the coordinator's watchdog is the sole source of wall-clock timeout\n * events — `checkTimeout()` focuses exclusively on `idle_timeout`.\n */\n private _watchdogActive: number | undefined;\n\n /** Returns the timeout ceiling currently being negotiated by the watchdog,\n * or `undefined` when no wall-clock negotiation is in flight.\n * Used by `executeWithTimeout` to detect a stale lock (M3). */\n get watchdogActive(): number | undefined { return this._watchdogActive; }\n\n /** Called by the coordinator watchdog BEFORE calling `onThreshold` so that\n * `checkTimeout()` skips its wall-clock check for this ceiling. Prevents\n * the budget's own `checkTimeout()` from emitting a second\n * `budget.threshold_reached` event while the watchdog is already\n * negotiating the same wall-clock deadline (C1). */\n setWatchdogNegotiation(timeoutMs: number): void { this._watchdogActive = timeoutMs; }\n\n /** Clears the watchdog guard after negotiation resolves. Called in the\n * `finally` block of both the pre-empt and deadline branches so it fires\n * on every exit path: grant, deny, throw, or error. */\n clearWatchdogNegotiation(): void { this._watchdogActive = undefined; }\n\n /**\n * Negotiation mode — controls whether a threshold hit tries to emit\n * `budget.threshold_reached` and wait for a coordinator decision, or\n * falls straight through to a synchronous hard stop.\n *\n * `'auto'` (default) — emit on the EventBus and wait; times out to 'stop'.\n * `'sync'` — throw `BudgetExceededError` immediately regardless of listeners.\n */\n private _mode: BudgetNegotiationMode;\n\n /**\n * Optional callback for soft-limit handling. When set, the budget will\n * invoke it rather than throw immediately. The handler decides whether to\n * throw synchronously, continue, or ask the coordinator for an extension.\n */\n get onThreshold(): BudgetThresholdHandler | undefined {\n return this._onThreshold;\n }\n set onThreshold(fn: BudgetThresholdHandler | undefined) {\n this._onThreshold = fn;\n }\n\n /** Returns the current negotiation mode. */\n get mode(): BudgetNegotiationMode {\n return this._mode;\n }\n\n constructor(limits: BudgetLimits = {}, mode: BudgetNegotiationMode = 'auto') {\n this._mode = mode;\n // NOT frozen: `negotiateExtension` patches these limits in place when the\n // coordinator grants an auto-extension. Freezing made every granted\n // extension throw `TypeError: Cannot assign to read only property` in\n // strict mode, which the runner caught as a hard stop — so extensions\n // silently became kills. The `readonly limits: Readonly<BudgetLimits>`\n // typing still blocks external mutation at compile time.\n this.limits = { ...limits };\n }\n\n start(): void {\n this.startTime = Date.now();\n this.lastActivityTime = this.startTime;\n }\n\n /**\n * Reset the idle clock. Called on any sign of forward progress —\n * iterations, tool calls, token usage, and streamed tool/text progress —\n * so a long-but-productive subagent never trips its `idleTimeoutMs`.\n */\n markActivity(): void {\n this.lastActivityTime = Date.now();\n }\n\n /**\n * Milliseconds since the last activity signal. Returns 0 before `start()`\n * (nothing to measure yet). Used by the coordinator watchdog to decide\n * whether to re-arm (still active) or reap (genuinely idle).\n */\n idleMs(): number {\n const since = this.lastActivityTime ?? this.startTime;\n return since === null ? 0 : Date.now() - since;\n }\n\n /** Returns true if we're within 10% of any limit — useful for pre-flight checks. */\n isNearLimit(): boolean {\n const { maxIterations, maxToolCalls, maxTokens, maxCostUsd } = this.limits;\n if (maxIterations && this.iterations >= maxIterations * 0.9) return true;\n if (maxToolCalls && this.toolCalls >= maxToolCalls * 0.9) return true;\n if (maxTokens && this.tokenInput + this.tokenOutput >= maxTokens * 0.9) return true;\n if (maxCostUsd && this.costUsd >= maxCostUsd * 0.9) return true;\n return false;\n }\n\n /**\n * Synchronous budget check. Always throws synchronously so callers (especially\n * test event handlers using `expect().toThrow()`) get an unhandled rejection\n * when the budget is exceeded without a handler.\n *\n * Decision table:\n * - no `onThreshold` handler → throw `BudgetExceededError` (hard stop, always)\n * - `mode === 'sync'` → throw `BudgetExceededError` (hard stop, always)\n * - `mode === 'auto'` + no listener → throw `BudgetExceededError` (hard stop; no one to ask)\n * - `mode === 'auto'` + listener → throw `BudgetThresholdSignal` with async decision promise\n */\n /**\n * Collects all exceeded budget kinds into a single NOOP-free negotiation.\n * Called by recordIteration / recordToolCall / recordUsage — each may call\n * this for its own kind. The first call starts the negotiation and stores\n * the Promise in _pendingNegotiation. Subsequent calls for DIFFERENT\n * kinds (while a negotiation is in flight) are NOOPs — they don't start\n * new conversations with the coordinator. This prevents an EventBus flood\n * when multiple budget kinds are exceeded simultaneously in one iteration.\n *\n * Returns the kinds that were found to be exceeded (for logging/debugging).\n */\n private checkLimits(elapsedMs?: number): { kind: BudgetKind; used: number; limit: number }[] {\n const exceeded: { kind: BudgetKind; used: number; limit: number }[] = [];\n\n if (this.limits.maxIterations !== undefined && this.iterations > this.limits.maxIterations) {\n exceeded.push({ kind: 'iterations', used: this.iterations, limit: this.limits.maxIterations });\n }\n if (this.limits.maxToolCalls !== undefined && this.toolCalls > this.limits.maxToolCalls) {\n exceeded.push({ kind: 'tool_calls', used: this.toolCalls, limit: this.limits.maxToolCalls });\n }\n const totalTokens = this.tokenInput + this.tokenOutput;\n if (this.limits.maxTokens !== undefined && totalTokens > this.limits.maxTokens) {\n exceeded.push({ kind: 'tokens', used: totalTokens, limit: this.limits.maxTokens });\n }\n if (this.limits.maxCostUsd !== undefined && this.costUsd > this.limits.maxCostUsd) {\n exceeded.push({ kind: 'cost', used: this.costUsd, limit: this.limits.maxCostUsd });\n }\n // Timeout: called from checkTimeout() with elapsedMs (wall-clock) and the\n // current idle gap. Either crossing its limit trips its own kind so the\n // coordinator and auto-extend policy can distinguish them.\n // Wall-clock (`timeoutMs`) is an explicit hard cap; idle (`idleTimeoutMs`)\n // is the default guard that resets on activity. Both can be exceeded in\n // the same call — we push both entries so all violated limits are reported.\n if (elapsedMs !== undefined) {\n const idle = this.idleMs();\n if (this.limits.idleTimeoutMs !== undefined && idle > this.limits.idleTimeoutMs) {\n exceeded.push({ kind: 'idle_timeout', used: idle, limit: this.limits.idleTimeoutMs });\n }\n // Skip the wall-clock 'timeout' kind while the coordinator watchdog is\n // negotiating this exact ceiling — it owns wall-clock; checkTimeout/here\n // own idle. Only suppress in the negotiation path (a handler is set); on\n // the no-handler hard-throw path the wall-clock must still trip. (Mirrors\n // the guard in checkTimeout, which previously was NOT applied here — so\n // an idle trip that called checkLimits re-added 'timeout' and defeated the\n // watchdog dedup.)\n const wallOwnedByWatchdog =\n this._onThreshold !== undefined && this._watchdogActive === this.limits.timeoutMs;\n if (\n this.limits.timeoutMs !== undefined &&\n elapsedMs > this.limits.timeoutMs &&\n !wallOwnedByWatchdog\n ) {\n exceeded.push({ kind: 'timeout', used: elapsedMs, limit: this.limits.timeoutMs });\n }\n }\n\n if (exceeded.length === 0) return [];\n\n if (!this._onThreshold) {\n // Hard stop — throw on the first exceeded kind.\n const first = exceeded[0] ?? { kind: 'iterations', limit: 0, used: 0 };\n throw new BudgetExceededError(first.kind, first.limit, first.used);\n }\n if (this._mode === 'sync') {\n // Hard stop in sync mode.\n const first = exceeded[0] ?? { kind: 'iterations', limit: 0, used: 0 };\n throw new BudgetExceededError(first.kind, first.limit, first.used);\n }\n const bus = this._events;\n if (!bus) {\n // No EventBus wired at all → nobody to negotiate with → hard stop.\n const first = exceeded[0] ?? { kind: 'iterations', limit: 0, used: 0 };\n throw new BudgetExceededError(first.kind, first.limit, first.used);\n }\n\n const first = exceeded[0] ?? { kind: 'iterations', limit: 0, used: 0 };\n\n // LISTENER-DRIVEN PATH. A registered `budget.threshold_reached` listener\n // (director / collab / auto-extend) negotiates asynchronously. Start one\n // negotiation PER exceeded kind — each reports its OWN kind/used/limit and\n // emits a single event (no O(N^2) re-emission, no cross-kind first-wins\n // drop). Throw `BudgetThresholdSignal` for the first kind so the runner\n // awaits the decision and enforces extend/stop.\n if (bus.hasListenerFor('budget.threshold_reached')) {\n for (const entry of exceeded) {\n if (this._pendingNegotiations.has(entry.kind)) continue; // already negotiating this kind\n this._pendingNegotiations.set(entry.kind, this._negotiateExtension(entry));\n }\n const decision = this._pendingNegotiations.get(first.kind);\n if (!decision) throw new Error(`No pending negotiation for ${first.kind}`);\n throw new BudgetThresholdSignal(first.kind, first.limit, first.used, decision);\n }\n\n // NO-LISTENER PATH. Invoke the handler synchronously to let an in-process\n // policy decide. Two outcomes:\n // • SYNC handler (returns a string/decision — e.g. the coordinator\n // watchdog / recording handlers) → its decision is honored in place\n // (an `extend` patches limits); no throw. This is the path the\n // watchdog drives while it owns wall-clock enforcement.\n // • ASYNC handler (returns a Promise via `requestDecision()`) → there is\n // no listener to resolve it and `requestDecision` resolves to 'stop',\n // so this is a definite hard stop: throw `BudgetExceededError`. This is\n // the documented \"auto mode + no listener → hard stop\" invariant that\n // protects a bare `/spawn` (no director) from a runaway subagent.\n let hardStop: BudgetExceededError | null = null;\n for (const entry of exceeded) {\n // Dedup per kind across back-to-back overruns in the same tick — a still\n // exceeded kind (e.g. iterations stays over after a grant) must not\n // re-invoke the handler on every record* call. The marker clears on a\n // microtask so a genuinely fresh overrun later can re-negotiate.\n if (this._pendingNegotiations.has(entry.kind)) continue;\n const marker = Promise.resolve<BudgetThresholdDecision>('stop');\n this._pendingNegotiations.set(entry.kind, marker);\n void marker.finally(() => this._pendingNegotiations.delete(entry.kind));\n const sync = this._invokeHandlerSync(entry);\n if (!sync) hardStop ??= new BudgetExceededError(entry.kind, entry.limit, entry.used);\n }\n if (hardStop) throw hardStop;\n return exceeded;\n }\n\n /**\n * Invoke `onThreshold` once for `entry` on the NO-LISTENER path and report\n * whether it decided synchronously. Returns `true` when the handler returned\n * a synchronous decision (already honored — an `extend` patched the limits),\n * or `false` when it returned a Promise (async; the caller hard-stops, since\n * there is no listener to resolve the negotiation). The handler is given the\n * full info shape (`requestDecision` plus direct `extend`/`deny`) so both\n * recording handlers and policy handlers work without a wired listener.\n */\n private _invokeHandlerSync(entry: { kind: BudgetKind; used: number; limit: number }): boolean {\n const handler = this._onThreshold;\n if (!handler) return false;\n let extendArg: Partial<BudgetLimits> | undefined;\n const result = handler({\n kind: entry.kind,\n used: entry.used,\n limit: entry.limit,\n requestDecision: (): Promise<BudgetThresholdDecision> => this._busRequestDecision(entry),\n // Direct hooks for synchronous policy/recording handlers.\n extend: (extra: Partial<BudgetLimits>) => {\n extendArg = extra;\n },\n deny: () => {},\n } as Parameters<BudgetThresholdHandler>[0]);\n // A thenable means the handler deferred to async negotiation — but there is\n // no listener here, so it can never be granted → hard stop.\n if (result && typeof (result as { then?: unknown }).then === 'function') return false;\n if (result === 'throw') return false; // explicit hard stop\n // 'continue' / 'stop' / a returned { extend } decision — honor in place.\n if (result && typeof result === 'object' && 'extend' in result) {\n extendArg = (result as { extend: Partial<BudgetLimits> }).extend;\n }\n if (extendArg) this.patchLimits(extendArg);\n return true;\n }\n\n /**\n * Emit `budget.threshold_reached` and resolve to the listener's verdict.\n * Resolves to `'stop'` immediately when there is no listener (or no bus) so\n * no negotiation can hang and no fallback timer leaks. Mirrors the\n * coordinator watchdog's own request path so both agree on the no-listener\n * default.\n */\n private _busRequestDecision(entry: {\n kind: BudgetKind;\n used: number;\n limit: number;\n }): Promise<BudgetThresholdDecision> {\n const bus = this._events;\n if (!bus || !bus.hasListenerFor('budget.threshold_reached')) {\n return Promise.resolve('stop');\n }\n return new Promise<BudgetThresholdDecision>((resolve) => {\n let resolved = false;\n const respond = (d: BudgetThresholdDecision) => {\n if (resolved) return;\n resolved = true;\n clearTimeout(fallback);\n resolve(d);\n };\n const fallback = setTimeout(() => respond('stop'), SubagentBudget.DECISION_TIMEOUT_MS);\n bus.emit('budget.threshold_reached', {\n kind: entry.kind as\n | 'iterations'\n | 'tool_calls'\n | 'tokens'\n | 'cost'\n | 'timeout'\n | 'idle_timeout',\n used: entry.used,\n limit: entry.limit,\n timeoutMs: SubagentBudget.DECISION_TIMEOUT_MS,\n // deny() wins over a same-dispatch extend(): a listener that both grants\n // and denies (or two listeners disagreeing) is resolved as a stop. The\n // grant is deferred a microtask so a synchronous deny in the same emit\n // pre-empts it; async grants still resolve normally.\n extend: (extra: Partial<BudgetLimits>) => queueMicrotask(() => respond({ extend: extra })),\n deny: () => respond('stop'),\n });\n });\n }\n\n /**\n * Per-kind in-flight negotiation Promises. Each budget kind can have its\n * own concurrent negotiation — e.g. iterations and timeout can both\n * be exceeded simultaneously without blocking each other. The same kind\n * cannot start two concurrent negotiations (dedup guard).\n * Cleared in `_negotiateExtension`'s `finally` block.\n */\n private _pendingNegotiations = new Map<BudgetKind, Promise<BudgetThresholdDecision>>();\n\n /**\n * Drive the threshold handler to a decision. Resolves with `'stop'`\n * (signal the runner to abort) or `{ extend: ... }` (limits already\n * patched in-place; the runner should not abort). Clears the\n * per-kind slot in `_pendingNegotiations` in `finally`.\n *\n * The 'continue' return from a sync handler is treated as\n * `{ extend: {} }` — keep going without patching; next overrun fires\n * a fresh signal.\n */\n private async _negotiateExtension(\n entry: { kind: BudgetKind; used: number; limit: number },\n ): Promise<BudgetThresholdDecision> {\n if (!this._onThreshold) {\n // Should never reach here — caller should have thrown already\n return 'stop';\n }\n try {\n const result = this._onThreshold({\n kind: entry.kind,\n used: entry.used,\n limit: entry.limit,\n // One event for THIS kind only — each exceeded kind has its own\n // negotiation (and its own resolve), so there is no cross-kind\n // first-wins drop and no O(N^2) re-emission.\n requestDecision: (): Promise<BudgetThresholdDecision> => this._busRequestDecision(entry),\n extend: (extra: Partial<BudgetLimits>) => {\n this.patchLimits(extra);\n },\n deny: () => {},\n } as Parameters<BudgetThresholdHandler>[0]);\n\n if (result === 'throw') return 'stop';\n if (result === 'continue') return { extend: {} };\n\n const decision = await result;\n if (decision === 'stop') return 'stop';\n\n // 'extend' — patch in-place limits BEFORE resolving (single write path).\n this.patchLimits(decision.extend);\n return decision;\n } finally {\n this._pendingNegotiations.delete(entry.kind);\n }\n }\n\n recordIteration(): void {\n this.iterations++;\n this.markActivity();\n void this.checkLimits();\n }\n\n recordToolCall(): void {\n this.toolCalls++;\n this.markActivity();\n void this.checkLimits();\n }\n\n recordUsage(usage: Usage, costUsd = 0): void {\n this.tokenInput += usage.input;\n this.tokenOutput += usage.output;\n this.costUsd += costUsd;\n this.markActivity();\n void this.checkLimits();\n }\n\n /**\n * Wall-clock / idle budget check. Delegates to `checkLimits(elapsed)`, so\n * `timeout` and `idle_timeout` follow the SAME negotiation path as the other\n * kinds — they are NOT a special-cased hard stop. This is deliberate: a\n * heartbeat-aware policy (see `attachAutoExtend` and `CollabSession`) grants\n * a timeout extension only while the agent is making progress and denies it\n * once the agent is genuinely stuck, which is safer than an unconditional\n * hard kill of a long-but-working agent. The runner translates the resulting\n * `BudgetThresholdSignal` decision (`extend` → patch limits in place,\n * `stop` → abort) just like every other kind.\n *\n * Decision table (same as `checkLimits`):\n * - no `onThreshold` handler → throw `BudgetExceededError` (hard stop)\n * - `mode === 'sync'` → throw `BudgetExceededError` (hard stop)\n * - `mode === 'auto'` + no listener → throw `BudgetExceededError` (no one to ask)\n * - `mode === 'auto'` + listener → throw `BudgetThresholdSignal` (negotiated;\n * a heartbeat-aware policy may extend the timeout)\n */\n checkTimeout(): void {\n if (this.startTime === null) return;\n const { timeoutMs, idleTimeoutMs } = this.limits;\n if (timeoutMs === undefined && idleTimeoutMs === undefined) return;\n const elapsed = Date.now() - this.startTime;\n // Skip wall-clock timeout if the coordinator watchdog is already in the middle\n // of negotiating this exact ceiling — tool.progress is too frequent and creates\n // a race where both paths emit budget.threshold_reached for the same kind.\n // The watchdog owns wall-clock; checkTimeout focuses exclusively on idle.\n const wallSkipped =\n this._onThreshold !== undefined &&\n this._watchdogActive !== undefined &&\n timeoutMs !== undefined &&\n this._watchdogActive === timeoutMs;\n const wallTripped = wallSkipped ? false : timeoutMs !== undefined && elapsed > timeoutMs;\n const idleTripped = idleTimeoutMs !== undefined && this.idleMs() > idleTimeoutMs;\n if (!wallTripped && !idleTripped) return;\n void this.checkLimits(elapsed);\n }\n\n /** Returns true if a wall-clock or idle timeout has occurred without throwing. */\n isTimedOut(): boolean {\n if (this.startTime === null) return false;\n const { timeoutMs, idleTimeoutMs } = this.limits;\n if (timeoutMs !== undefined && Date.now() - this.startTime > timeoutMs) return true;\n if (idleTimeoutMs !== undefined && this.idleMs() > idleTimeoutMs) return true;\n return false;\n }\n\n usage(): BudgetUsage {\n return {\n iterations: this.iterations,\n toolCalls: this.toolCalls,\n tokens: {\n input: this.tokenInput,\n output: this.tokenOutput,\n total: this.tokenInput + this.tokenOutput,\n },\n costUsd: this.costUsd,\n elapsedMs: this.startTime === null ? 0 : Date.now() - this.startTime,\n };\n }\n}\n","import type { Agent, AgentInput, RunResult } from '../core/agent.js';\nimport type { EventBus } from '../kernel/events.js';\nimport type {\n SubagentConfig,\n SubagentRunContext,\n SubagentRunOutcome,\n SubagentRunner,\n TaskSpec,\n} from '../types/multi-agent.js';\nimport { AgentError, ERROR_CODES } from '../types/errors.js';\nimport {\n BudgetExceededError,\n BudgetThresholdSignal,\n} from './subagent-budget.js';\nimport type { FleetBus } from './fleet-bus.js';\n\n/**\n * Caller-supplied factory that builds an isolated `Agent` for a subagent.\n * The factory MUST construct a fresh `Context` per call — sharing context\n * between subagents defeats isolation. Each Agent should also use either\n * its own `EventBus` or a forwarded view, so per-subagent metrics can be\n * attributed correctly.\n */\nexport type AgentFactory = (config: SubagentConfig) => Promise<AgentFactoryResult>;\n\n/**\n * Wrap a factory to automatically filter out disabled tools from subagent\n * configurations. This provides mechanical enforcement of tool restrictions\n * (e.g., preventing delegation) in addition to the baseline prompt constraint.\n *\n * The wrapper reads `config.disabledTools` and removes those tools from the\n * agent's tool registry before returning.\n *\n * Usage:\n * const filteredFactory = withDisabledToolFiltering(originalFactory);\n * const runner = makeAgentSubagentRunner({ factory: filteredFactory });\n */\nexport function withDisabledToolFiltering(factory: AgentFactory): AgentFactory {\n return async (config: SubagentConfig) => {\n const result = await factory(config);\n const disabled = config.disabledTools ?? [];\n if (disabled.length === 0) return result;\n\n // Agent.tools is a ToolRegistry with unregister() method\n const registry = result.agent.tools;\n if (registry && typeof registry.unregister === 'function') {\n for (const toolName of disabled) {\n registry.unregister(toolName);\n }\n }\n return result;\n };\n}\n\nexport interface AgentFactoryResult {\n agent: Agent;\n /** Event bus the factory wired to this agent — required for budget hookup. */\n events: EventBus;\n /**\n * Optional cleanup hook invoked in the runner's `finally` block once\n * the task ends (success, failure, abort — same exit path). Factories\n * that own resources scoped to a single task (per-subagent JSONL\n * writers, transient providers, throwaway containers) implement this\n * to close them deterministically instead of relying on GC. Errors\n * thrown here are swallowed so a flaky cleanup can't mask the task's\n * real result.\n */\n dispose?: ((() => Promise<void> | void)) | undefined;\n}\n\nexport interface AgentRunnerOptions {\n factory: AgentFactory;\n /**\n * Format a TaskSpec into the user input the agent will receive. Defaults\n * to `task.description ?? ''`. Override when subagents expect structured\n * input (e.g. JSON contracts, role-prefixed prompts).\n */\n formatTaskInput?: (task: TaskSpec, config: SubagentConfig) => AgentInput;\n /**\n * When set, the runner attaches the subagent's EventBus to this FleetBus\n * on task start and detaches it when the task finishes. This is the\n * injection seam that lets the TUI fleet panel observe subagent activity\n * live — without it, FleetBus stays empty.\n */\n fleetBus?: FleetBus | undefined;\n}\n\n/**\n * Builds a `SubagentRunner` that drives a real `Agent` per task while honoring\n * the coordinator's budget and abort signal. This is the production adapter —\n * the coordinator's `runner` option in CLI/TUI assemblies points here.\n *\n * Lifecycle per task:\n * 1. factory(config) → fresh Agent + EventBus.\n * 2. Subscribe to events to feed the budget (tool calls, token usage).\n * 3. Call agent.run(input, { signal }) — the coordinator's signal cancels.\n * 4. Map RunResult.status onto a `SubagentRunOutcome` or throw on failure.\n * 5. Unsubscribe and let the factory's resources be GC'd.\n *\n * The budget is checked synchronously from event handlers — a runaway agent\n * that crosses its tool-call limit triggers `BudgetExceededError`, which the\n * coordinator surfaces as `status: 'failed'` on the task result.\n */\nexport function makeAgentSubagentRunner(opts: AgentRunnerOptions): SubagentRunner {\n const format = opts.formatTaskInput ?? defaultFormatTaskInput;\n\n return async (task: TaskSpec, ctx: SubagentRunContext): Promise<SubagentRunOutcome> => {\n const taskStartedAt = Date.now();\n const factoryResult = await opts.factory(ctx.config);\n const { agent, events } = factoryResult;\n\n // Attach subagent EventBus to FleetBus so the TUI fleet panel (and any\n // other FleetBus subscriber) can observe this subagent live. Detach on\n // task finish — each task is a fresh Agent + EventBus, so we never\n // want a stale bus lingering after the run.\n const detachFleet = opts.fleetBus?.attach(ctx.subagentId, events, task.id);\n\n // Hook budget into the agent's event stream. We capture errors thrown by\n // recordToolCall/recordUsage so the budget can short-circuit the run by\n // aborting the controller — the agent then unwinds cooperatively.\n const aborter = new AbortController();\n // Inject the EventBus into the budget so it can emit budget.threshold_reached\n // events when a soft limit is hit and the handler wants to ask the coordinator.\n ctx.budget._events = events;\n // Wire the threshold-negotiation handler. Without this the soft-limit\n // path is dead code: every budget overrun becomes a hard\n // BudgetExceededError and the subagent dies on its first 120-iteration\n // tick instead of asking the Director for headroom. The Director's\n // FleetBus listener (director.ts) auto-grants +50% up to a per-kind\n // ceiling and per-subagent extension count — wiring this is the\n // missing link that activates that flow.\n ctx.budget.onThreshold = ({ requestDecision }) => requestDecision();\n let budgetError: Error | null = null;\n\n /**\n * Common error handler for all budget-triggered events. Distinguishes:\n * - BudgetExceededError → hard stop, set budgetError + abort\n * - BudgetThresholdSignal → soft stop: await the coordinator's\n * decision. If 'stop', abort. If 'extend', the signal handler\n * has already patched the budget so we can continue without\n * actually aborting the agent.\n */\n const onBudgetError = (err: unknown): void => {\n if (err instanceof BudgetThresholdSignal) {\n // Defer the stop/extend decision to the post-finally block below.\n // The coordinator's verdict may arrive after agent.run() returns;\n // awaiting it there (rather than in this fire-and-forget handler)\n // avoids a race where both this callback and the post-finally\n // block try to mutate `budgetError` concurrently.\n budgetError = err;\n return;\n }\n // Hard stop (BudgetExceededError or other)\n aborter.abort();\n budgetError =\n err instanceof BudgetExceededError\n ? err\n : new BudgetExceededError(\n 'tool_calls',\n 0,\n 0,\n );\n // Attach the real error detail so the task result surfaces\n // something actionable instead of a generic budget message.\n if (budgetError !== err && err instanceof Error) {\n budgetError.message += ` (caused by: ${err.message})`;\n }\n };\n\n // Track the name of the most recent tool that returned ok:false so\n // we can lift it into the SubagentError when the agent ends without\n // recovering. Cleared on every successful tool execution so a tool\n // that later succeeded doesn't taint the final report.\n let lastToolFailed: string | null = null;\n\n const unsub: Array<() => void> = [];\n unsub.push(\n events.on('tool.executed', (e) => {\n // Count tool calls on the PAIRED 'tool.executed' event rather\n // than 'tool.started'. A tool can fire start then crash before\n // emitting executed (process killed, signal aborted mid-exec);\n // counting only the paired event keeps the budget tally honest\n // and matches what the model actually saw in its turn.\n try {\n ctx.budget.recordToolCall();\n } catch (eb) {\n onBudgetError(eb);\n }\n // Track ok:false so we can fail the subagent if it ends without\n // recovering. Successful runs clear it — the model may try a\n // tool, get an error, and self-heal on the next iteration; that\n // path should still report success.\n if (e.ok === false) {\n lastToolFailed = e.name;\n } else if (e.ok === true) {\n lastToolFailed = null;\n }\n }),\n events.on('provider.response', (e) => {\n try {\n ctx.budget.recordUsage(e.usage);\n } catch (e2) {\n void onBudgetError(e2);\n }\n }),\n events.on('iteration.started', () => {\n try {\n ctx.budget.recordIteration();\n } catch (e) {\n void onBudgetError(e);\n }\n // Emit a periodic progress snapshot every SUMMARY_INTERVAL\n // iterations so the leader can surface \"AGENT#2 ● L25 · 47 tools\"\n // in the main chat history without needing the FleetPanel open.\n const u = ctx.budget.usage();\n const since = u.iterations - lastSummaryAtIteration;\n if (since >= SUMMARY_INTERVAL) {\n lastSummaryAtIteration = u.iterations;\n events.emit('subagent.iteration_summary', {\n subagentId: ctx.subagentId,\n iteration: u.iterations,\n toolCalls: u.toolCalls,\n costUsd: u.costUsd,\n currentTool: currentToolName,\n partialText: streamingTextAcc.trim() || undefined,\n });\n }\n }),\n // D3: cooperative timeout enforcement DURING a long tool call.\n // The iteration-loop checkTimeout() only fires between agent\n // iterations — a single `bash sleep 3600` call would otherwise\n // park inside one tool execution while the timeout silently\n // passes, relying solely on the coordinator's hard Promise.race\n // to interrupt. Tools that emit `tool.progress` (bash chunks,\n // fetch byte progress, spawn-stream stdout) give us a heartbeat\n // we can hang the check on. When the budget trips here:\n // 1. onBudgetError sets budgetError + aborter.abort()\n // 2. aborter signal propagates to agent.run → tool executor\n // 3. tool's own signal listener kills the child process\n // Cheap: O(1) per progress event, and the budget short-circuits\n // when timeoutMs is unset (most subagents have one set anyway).\n events.on('tool.progress', () => {\n // Streamed progress (bash chunks, fetch bytes, spawn stdout) is forward\n // motion — reset the idle clock so a long-but-working tool is never\n // mistaken for a stall, THEN check whether a genuine timeout tripped.\n ctx.budget.markActivity();\n try {\n ctx.budget.checkTimeout();\n } catch (e) {\n void onBudgetError(e);\n }\n }),\n );\n\n // Track current tool name + streaming text for the periodic summary.\n let currentToolName: string | undefined;\n let streamingTextAcc = '';\n let lastSummaryAtIteration = 0;\n const SUMMARY_INTERVAL = 25;\n\n unsub.push(\n events.on('tool.started', (e) => {\n currentToolName = e.name;\n }),\n events.on('provider.text_delta', (e) => {\n // Streamed assistant text is forward motion too — keep the idle\n // clock fresh while the model is actively generating.\n ctx.budget.markActivity();\n // Accumulate last ~2000 chars for the partial text snapshot.\n streamingTextAcc = (streamingTextAcc + e.text).slice(-2000);\n }),\n );\n\n // Forward the coordinator signal so stop() from outside also aborts.\n const onParentAbort = () => aborter.abort();\n ctx.signal.addEventListener('abort', onParentAbort);\n\n let result: RunResult;\n try {\n result = await agent.run(format(task, ctx.config), { signal: aborter.signal });\n // Emit task_completed BEFORE the finally block unsubscribes the\n // FleetBus — this lets the WebUI see the subagent's final output.\n events.emit('subagent.task_completed', {\n subagentId: ctx.subagentId,\n taskId: task.id,\n status: result.status === 'done' ? 'success' : 'failed',\n iterations: result.iterations,\n toolCalls: ctx.budget.usage().toolCalls,\n durationMs: Date.now() - taskStartedAt,\n finalText: result.finalText?.trim() || undefined,\n });\n } finally {\n detachFleet?.();\n ctx.signal.removeEventListener('abort', onParentAbort);\n for (const u of unsub) u();\n // Per-task resource cleanup. Closes JSONL writers, throwaway\n // providers, etc. that the factory wired up. Swallowed errors —\n // a flaky cleanup must not mask the real task result. The\n // caller can re-emit via observability if needed.\n if (factoryResult.dispose) {\n try {\n await factoryResult.dispose();\n } catch {\n // intentional swallow — see comment above\n }\n }\n }\n\n // A budget violation is the signal — surface it so the coordinator can\n // tag the task with the right failure kind ('failed' for budget; the\n // coordinator separately recognises 'timeout' from BudgetExceededError).\n if (budgetError) {\n // BudgetThresholdSignal: the soft limit was hit but the coordinator\n // hasn't resolved the extension decision yet. If the decision was\n // 'extend', the coordinator patched limits and the agent finished\n // normally — no error to surface. If 'stop', budgetError becomes\n // a BudgetExceededError thrown below.\n // instanceof check on Error subtypes requires 'any' intersection\n // on the union — use a property guard instead.\n if ('decision' in budgetError) {\n try {\n const decision = await (budgetError as BudgetThresholdSignal).decision;\n if (decision === 'stop') {\n budgetError = new BudgetExceededError(\n (budgetError as BudgetThresholdSignal).kind,\n (budgetError as BudgetThresholdSignal).limit,\n (budgetError as BudgetThresholdSignal).used,\n );\n } else {\n budgetError = null;\n }\n } catch {\n // Decision promise rejected — treat as hard stop.\n budgetError = new BudgetExceededError(\n (budgetError as BudgetThresholdSignal).kind,\n (budgetError as BudgetThresholdSignal).limit,\n (budgetError as BudgetThresholdSignal).used,\n );\n }\n }\n if (budgetError) throw budgetError;\n }\n\n if (result.status === 'failed') {\n throw result.error instanceof AgentError\n ? result.error\n : new AgentError({\n message: result.error instanceof Error ? result.error.message : String(result.error ?? 'agent failed'),\n code: ERROR_CODES.AGENT_RUN_FAILED,\n cause: result.error,\n });\n }\n // 'aborted' and 'max_iterations' aren't successes — let the coordinator\n // classify them. When the parent signal was aborted, coordinator marks\n // the task 'stopped' (matched against subagent.abortController.aborted).\n if (result.status === 'aborted') {\n throw new AgentError({\n message: 'agent aborted',\n code: ERROR_CODES.AGENT_ABORTED,\n });\n }\n if (result.status === 'max_iterations') {\n throw new AgentError({\n message: 'agent exhausted iteration limit',\n code: ERROR_CODES.AGENT_ITERATION_LIMIT,\n recoverable: true,\n });\n }\n\n const usage = ctx.budget.usage();\n // Empty-response guard. A \"successful\" run with no text AND no tool\n // calls is almost always a prompt / config issue, not a real\n // success — the agent burned an iteration to say nothing. Surface\n // it as a classified failure so callers can show \"✗ empty_response\"\n // instead of a confusing green ✓ with no output. We only trip on\n // the (no-text AND no-tools) intersection because text-less runs\n // with tool calls are legit (e.g. \"run npm test then end_turn\").\n const finalText = (result.finalText ?? '').trim();\n if (finalText.length === 0 && usage.toolCalls === 0) {\n throw new AgentError({\n message: 'empty response — agent produced no text and no tool calls',\n code: ERROR_CODES.AGENT_RUN_FAILED,\n context: { iterations: result.iterations },\n });\n }\n // Unrecovered-tool-failure guard. If the last executed tool came\n // back ok:false AND the agent ended its turn with no closing text,\n // the agent never acknowledged or recovered from the failure — the\n // task is effectively broken. A model that handles a tool error\n // emits SOME text on the next iteration (\"the read failed, trying\n // an alternate path…\") which clears `lastToolFailed`; the only way\n // both signals can be live at end-of-run is if the model gave up\n // silently. Surface as `tool_failed` so callers see the actual\n // failure mode instead of a clean ✓ with no output.\n if (finalText.length === 0 && lastToolFailed !== null) {\n throw new AgentError({\n message: `unrecovered tool failure: ${lastToolFailed} — agent ended turn without acknowledging the error`,\n code: ERROR_CODES.AGENT_RUN_FAILED,\n context: { tool: lastToolFailed, iterations: result.iterations },\n });\n }\n return {\n result: result.finalText,\n iterations: result.iterations,\n toolCalls: usage.toolCalls,\n };\n };\n}\n\nfunction defaultFormatTaskInput(task: TaskSpec): AgentInput {\n return task.description ?? '';\n}\n","/**\n * Catalog types for the WrongStack agent fleet.\n *\n * An `AgentDefinition` bundles the runtime `SubagentConfig` (id/name/role/\n * prompt/tools) with two things the bare config lacks:\n * - a per-role `budget` tier (consumed by FLEET_ROSTER_BUDGETS), and\n * - dispatcher `capability` metadata (keywords + summary + phase) used by\n * the smart dispatcher to route a free-form task to the best agent.\n *\n * Phase files (`phase1-discovery.ts` … `phase9-meta.ts`) each export an\n * `AgentDefinition[]`; `index.ts` aggregates them into `AGENT_CATALOG`.\n * `fleet.ts` derives `FLEET_ROSTER` + `FLEET_ROSTER_BUDGETS` from the catalog.\n */\nimport type { SubagentConfig } from '../../types/multi-agent.js';\n\n/** Lifecycle phase grouping. Drives statusline labels + dispatcher tie-breaks. */\nexport type AgentPhase =\n | 'discovery'\n | 'planning'\n | 'build'\n | 'verify'\n | 'review'\n | 'domain'\n | 'knowledge'\n | 'delivery'\n | 'meta';\n\n/** Per-role budget tier. Same shape as fleet.ts `FleetRosterBudget`. */\nexport interface AgentBudgetTier {\n timeoutMs?: number | undefined;\n maxIterations?: number | undefined;\n maxToolCalls?: number | undefined;\n maxTokens?: number | undefined;\n maxCostUsd?: number | undefined;\n}\n\n/** Dispatcher routing metadata. */\nexport interface AgentCapability {\n phase: AgentPhase;\n /**\n * One-line capability summary. Fed to the LLM dispatcher classifier as the\n * candidate's description, and shown to the user when explaining a routing\n * decision. Keep it concrete and distinct from sibling agents.\n */\n summary: string;\n /**\n * Lowercased signal words/phrases for the heuristic dispatcher. A task whose\n * description contains these scores toward this agent. Order doesn't matter;\n * prefer specific terms (\"graphql\", \"wcag\") over generic ones (\"code\").\n */\n keywords: string[];\n}\n\n/** A single catalog entry: runtime config + budget tier + routing metadata. */\nexport interface AgentDefinition {\n config: SubagentConfig;\n budget: AgentBudgetTier;\n capability: AgentCapability;\n}\n\nconst HOUR = 60 * 60 * 1000;\n\n/**\n * Budget tiers by workload weight. Deliberately generous — the project's\n * existing roster uses multi-hour ceilings to avoid spurious timeouts on\n * monorepo-scale work, and the auto-extend handshake raises them further when\n * a subagent is still making progress.\n */\nexport const LIGHT_BUDGET: AgentBudgetTier = {\n timeoutMs: 3 * HOUR,\n maxIterations: 3000,\n maxToolCalls: 8000,\n};\nexport const MEDIUM_BUDGET: AgentBudgetTier = {\n timeoutMs: 5 * HOUR,\n maxIterations: 5000,\n maxToolCalls: 14000,\n};\nexport const HEAVY_BUDGET: AgentBudgetTier = {\n timeoutMs: 10 * HOUR,\n maxIterations: 8000,\n maxToolCalls: 20000,\n};\n\n/**\n * Tool allowlist presets. Agents pass the smallest set that covers their job —\n * a planning agent should not hold `write`/`bash`, a reviewer should be\n * read-only. Spread + extend per-agent where a role needs one extra tool.\n */\nexport const TOOLS = {\n /** Pure read/inspect — safe for analysis and review agents. */\n read: ['read', 'grep', 'glob', 'search', 'tree', 'mailbox'],\n /** Read + structured inspection (logs, diffs, json, dependency audit). */\n inspect: ['read', 'grep', 'glob', 'search', 'tree', 'json', 'diff', 'logs', 'audit', 'mailbox'],\n /** Read + edit (no shell). For agents that write code/docs but don't run it. */\n write: ['read', 'grep', 'glob', 'search', 'tree', 'write', 'edit', 'replace', 'patch', 'mailbox'],\n /** Full build loop: edit + run (lint/format/typecheck/test/bash). */\n build: [\n 'read',\n 'grep',\n 'glob',\n 'search',\n 'tree',\n 'write',\n 'edit',\n 'replace',\n 'patch',\n 'bash',\n 'exec',\n 'lint',\n 'format',\n 'typecheck',\n 'test',\n 'mailbox',\n ],\n /** Version control. */\n vcs: ['read', 'grep', 'glob', 'git', 'diff'],\n /** Dependency management + CVE audit. */\n deps: ['read', 'grep', 'glob', 'install', 'outdated', 'audit', 'json', 'mailbox'],\n /** Documentation authoring. */\n docs: ['read', 'grep', 'glob', 'search', 'tree', 'write', 'edit', 'document', 'mailbox'],\n /** Web research. */\n research: ['read', 'grep', 'glob', 'search', 'fetch', 'mailbox'],\n} as const satisfies Record<string, readonly string[]>;\n","import { type AgentDefinition, LIGHT_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 1 · Discovery — map the territory before any work begins. */\nexport const DISCOVERY_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'explore',\n name: 'Explore',\n role: 'explore',\n tools: [...TOOLS.read],\n prompt: `You are the Explore agent. Your job is to map an unfamiliar codebase\nand report its structure, entry points, and architecture — fast and read-only.\n\nScope:\n- Locate entry points, build config, package boundaries, and dependency direction\n- Identify the dominant patterns (DI, event bus, layering) and where they live\n- Trace how a feature flows across files without modifying anything\n- Surface the 5-10 files most relevant to a given question\n\nInput format you accept:\n{ \"task\": \"map | locate | trace\", \"question\": \"<what to find>\", \"scope\": [\"packages/core\"] }\n\nOutput: Markdown map with sections:\n- ## Overview (one paragraph: what this codebase is)\n- ## Key Files (table: file:line — role)\n- ## Flow (how the relevant feature moves across files)\n- ## Open Questions (anything that needs the user to clarify)\n\nWorking rules:\n- Read-only — never edit, write, or run shell commands\n- Always cite file:line; never describe code you haven't read\n- Prefer breadth first (glob/tree), then depth (read) on the hottest files\n- If the question is ambiguous, state your interpretation before answering`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'discovery',\n summary: 'Maps unfamiliar codebases: entry points, structure, architecture, feature flow (read-only).',\n keywords: [\n 'explore',\n 'map',\n 'understand',\n 'where is',\n 'how does',\n 'codebase',\n 'architecture',\n 'structure',\n 'overview',\n 'find file',\n 'entry point',\n 'orient',\n ],\n },\n },\n {\n config: {\n id: 'search',\n name: 'Search',\n role: 'search',\n tools: [...TOOLS.read],\n prompt: `You are the Search agent. Your job is semantic and lexical code search\nacross one or many repositories: find every place a concept, symbol, or pattern\nappears and rank the hits by relevance.\n\nScope:\n- Resolve a fuzzy concept (\"where do we validate auth tokens?\") to concrete sites\n- Find all definitions, references, and call sites of a symbol\n- Detect duplicated or near-duplicated logic across packages\n- Cross-repo search when multiple roots are provided\n\nInput format you accept:\n{ \"task\": \"find | refs | dupes\", \"query\": \"<concept or symbol>\", \"roots\": [\".\"], \"kind\": \"definition | usage | all\" }\n\nOutput: Markdown result set:\n- ## Best Matches (ranked: file:line — why it matches)\n- ## Related (lower-confidence hits)\n- ## Not Found (terms searched with zero hits, so the caller can rephrase)\n\nWorking rules:\n- Read-only; rely on grep/glob/search, never edit\n- Always rank by relevance and explain the ranking in one clause\n- Distinguish definition sites from usage sites explicitly\n- Report search terms that returned nothing so the caller can refine`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'discovery',\n summary: 'Semantic + lexical code search across repos; finds definitions, references, duplicates, ranks by relevance.',\n keywords: [\n 'search',\n 'find all',\n 'references',\n 'usages',\n 'call sites',\n 'grep',\n 'locate symbol',\n 'duplicate',\n 'where used',\n 'occurrences',\n 'cross-repo',\n ],\n },\n },\n {\n config: {\n id: 'research',\n name: 'Research',\n role: 'research',\n tools: [...TOOLS.research],\n prompt: `You are the Research agent (formerly Scientist). Your job is technical\nresearch and feasibility analysis: investigate libraries, approaches, and\ntradeoffs, then recommend a path with evidence.\n\nScope:\n- Compare libraries/frameworks/approaches for a stated requirement\n- Assess feasibility and risk of a proposed technique\n- Summarize current best practice from documentation and the codebase\n- Produce a recommendation with explicit tradeoffs, not just a list\n\nInput format you accept:\n{ \"task\": \"compare | feasibility | bestpractice\", \"topic\": \"<technology or approach>\", \"constraints\": [\"runtime: node>=22\", \"no new deps\"] }\n\nOutput: Markdown research brief:\n- ## Question (restated, with constraints)\n- ## Options (table: option — pros — cons — fit)\n- ## Recommendation (one choice + why + the main tradeoff)\n- ## Evidence (links/citations and file:line where the codebase already hints)\n\nWorking rules:\n- Ground claims in fetched docs or actual code — flag anything you're unsure of\n- Always give a recommendation, never just \"it depends\"\n- State the single biggest risk of the recommended path\n- Respect stated constraints; if an option violates one, say so explicitly`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'discovery',\n summary: 'Technical research and feasibility: compares libraries/approaches, recommends a path with evidence and tradeoffs.',\n keywords: [\n 'research',\n 'feasibility',\n 'compare libraries',\n 'which library',\n 'best practice',\n 'tradeoff',\n 'investigate',\n 'evaluate approach',\n 'should we use',\n 'pros and cons',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, LIGHT_BUDGET, TOOLS } from './types.js';\n\nconst PLAN_TOOLS = [...TOOLS.read, 'plan', 'todo'];\n\n/** Phase 2 · Planning — turn intent into requirements, plans, and architecture. */\nexport const PLANNING_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'analyst',\n name: 'Analyst',\n role: 'analyst',\n tools: [...PLAN_TOOLS],\n prompt: `You are the Analyst agent. Your job is requirement analysis: turn a\nvague request into a precise, testable specification before anyone writes code.\n\nScope:\n- Extract explicit and implicit requirements from a request\n- Identify ambiguities, edge cases, and missing acceptance criteria\n- Separate must-have from nice-to-have; flag scope creep\n- Produce acceptance criteria that a TestAgent could turn into tests\n\nInput format you accept:\n{ \"task\": \"analyze | clarify | criteria\", \"request\": \"<feature description>\", \"context\": \"<domain notes>\" }\n\nOutput: Markdown requirement spec:\n- ## Goal (one sentence)\n- ## Requirements (MUST / SHOULD / WON'T)\n- ## Acceptance Criteria (Given/When/Then, testable)\n- ## Open Questions (ambiguities that block implementation)\n- ## Out of Scope (explicit non-goals)\n\nWorking rules:\n- Never invent requirements the user didn't imply — list them as open questions\n- Every acceptance criterion must be observable/testable\n- Flag the single biggest unknown that could change the design\n- Read code to ground \"as-is\" behavior before specifying \"to-be\"`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Requirement analysis: turns vague requests into testable specs with acceptance criteria and open questions.',\n keywords: [\n 'requirements',\n 'analyze requirement',\n 'acceptance criteria',\n 'spec',\n 'specification',\n 'clarify',\n 'scope',\n 'user story',\n 'what should it do',\n ],\n },\n },\n {\n config: {\n id: 'planner',\n name: 'Planner',\n role: 'planner',\n tools: [...PLAN_TOOLS],\n prompt: `You are the Planner agent. Your job is execution planning: break an\napproved goal into an ordered, dependency-aware sequence of concrete steps.\n\nScope:\n- Decompose a goal into tasks small enough to verify independently\n- Order tasks by dependency; mark which can run in parallel\n- Estimate relative effort and call out risky steps\n- Define checkpoints where progress should be validated\n\nInput format you accept:\n{ \"task\": \"plan | sequence | estimate\", \"goal\": \"<what to build>\", \"constraints\": [\"one PR per concern\"] }\n\nOutput: Markdown execution plan:\n- ## Plan Summary (one paragraph)\n- ## Steps (table: # — task — depends-on — parallel? — risk)\n- ## Critical Path (the longest dependency chain)\n- ## Checkpoints (where to stop and verify)\n\nWorking rules:\n- One step = one concern that can be verified on its own\n- Make dependencies explicit; never leave ordering implicit\n- Mark parallelizable steps so the coordinator can dispatch them concurrently\n- Keep the plan actionable — no step should be \"figure out X\"`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Execution planning: decomposes a goal into ordered, dependency-aware, parallelizable steps with checkpoints.',\n keywords: [\n 'plan',\n 'execution plan',\n 'break down',\n 'decompose',\n 'steps',\n 'sequence',\n 'roadmap',\n 'task breakdown',\n 'order of work',\n 'milestones',\n ],\n },\n },\n {\n config: {\n id: 'architect',\n name: 'Architect',\n role: 'architect',\n tools: [...PLAN_TOOLS],\n prompt: `You are the Architect agent. Your job is system architecture: design\nmodule boundaries, data flow, and interfaces that satisfy the requirements\nwithout over-engineering.\n\nScope:\n- Define components, their responsibilities, and the contracts between them\n- Choose data flow and state ownership; avoid hidden coupling\n- Respect the codebase's existing dependency direction and patterns\n- Document the key decisions and the alternatives rejected\n\nInput format you accept:\n{ \"task\": \"design | interfaces | decision\", \"requirement\": \"<what to support>\", \"constraints\": [\"no reverse deps\", \"keep kernel <600 LOC\"] }\n\nOutput: Markdown architecture doc:\n- ## Context (forces and constraints)\n- ## Components (each: responsibility + dependencies)\n- ## Interfaces (the key type signatures / contracts)\n- ## Data Flow (ASCII diagram)\n- ## Decisions (decision — rationale — rejected alternative)\n\nWorking rules:\n- Follow the repo's existing layering; never introduce a reverse dependency\n- Prefer the simplest design that meets the requirement — no speculative generality\n- Make every interface explicit as a type signature\n- Record why each non-obvious decision was made`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'System architecture: designs module boundaries, interfaces, data flow, and records key decisions.',\n keywords: [\n 'architecture',\n 'design system',\n 'module boundaries',\n 'interfaces',\n 'data flow',\n 'component design',\n 'system design',\n 'decision record',\n 'adr',\n 'structure the',\n ],\n },\n },\n {\n config: {\n id: 'critic',\n name: 'Critic',\n role: 'critic',\n tools: [...TOOLS.read],\n prompt: `You are the Critic agent. Your job is adversarial review of a plan or\ndesign before implementation: find the flaws, gaps, and risks the authors\nmissed — but stay constructive.\n\nScope:\n- Stress-test a plan/design against edge cases and failure modes\n- Find missing steps, unhandled errors, and unstated assumptions\n- Challenge scope, complexity, and sequencing decisions\n- Rank concerns by severity and propose concrete fixes\n\nInput format you accept:\n{ \"task\": \"review | redteam | risks\", \"artifact\": \"<plan or design text or file>\", \"focus\": \"completeness | risk | simplicity\" }\n\nOutput: Markdown critique:\n- ## Verdict (ship / revise / reconsider — one line)\n- ## Blocking Issues (must fix before proceeding)\n- ## Concerns (should address)\n- ## Nitpicks (optional)\nEach item: problem → why it matters → suggested fix\n\nWorking rules:\n- Be specific: cite the exact step/section you're criticizing\n- Every criticism must come with a concrete suggested fix\n- Separate blocking issues from preferences — don't inflate severity\n- If the plan is sound, say so plainly; don't manufacture problems`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Adversarial review of plans/designs: finds gaps, risks, and unstated assumptions with ranked fixes.',\n keywords: [\n 'critique',\n 'review plan',\n 'review design',\n 'red team',\n 'poke holes',\n 'risks',\n 'what could go wrong',\n 'second opinion',\n 'challenge',\n 'flaws',\n ],\n },\n },\n {\n config: {\n id: 'refactor-planner',\n name: 'Refactor Planner',\n role: 'refactor-planner',\n tools: [...PLAN_TOOLS, 'diff'],\n prompt: `You are the Refactor Planner agent. Your job is to analyze code\nstructure and produce a concrete, phased refactoring plan with risk\nassessment, dependency ordering, and rollback strategy.\n\nScope:\n- Map module-level dependencies (import graph)\n- Identify coupling hotspots (high fan-in/out modules)\n- Assess refactoring risk by complexity and test coverage\n- Generate phased plans with checkpoint milestones\n- Produce diff-friendly task lists (one task = one concern)\n\nInput format you accept:\n{ \"task\": \"plan | assess | roadmap\", \"target\": \"src/core\", \"constraint\": \"no-breaking-changes | minimal-downtime | full-rewrite\", \"focus\": \"architecture | performance | maintainability\" }\n\nOutput: Markdown refactor plan with phases (Low Risk / Medium Risk / High Risk),\ndependency graph, rollback strategy, and exit criteria.\n\nWorking rules:\n- Always include rollback strategy — every refactor can fail\n- Merge tasks that take <1h into a single phase\n- Respect team constraints (reviewer availability, parallelization)\n- Never plan without analyzing the actual code first`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Refactoring planner: analyzes code structure, maps dependencies, produces risk-scored phased plans with rollback strategy.',\n keywords: [\n 'refactor',\n 'refactoring',\n 'restructure',\n 'debt',\n 'technical debt',\n 'clean up',\n 'modularize',\n 'decouple',\n 'dependency graph',\n 'code structure',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 3 · Build — write, refactor, migrate, and fix code. */\nexport const BUILD_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'executor',\n name: 'Executor',\n role: 'executor',\n tools: [...TOOLS.build],\n prompt: `You are the Executor agent. Your job is to implement a well-specified\ntask: write the code, run the checks, and leave the tree green.\n\nScope:\n- Implement features/changes against a clear spec or plan step\n- Follow existing patterns, naming, and dependency direction\n- Run lint/typecheck/test after changes and fix what you broke\n- Make the smallest change that satisfies the task\n\nInput format you accept:\n{ \"task\": \"implement | apply | fix\", \"spec\": \"<what to build>\", \"files\": [\"src/x.ts\"], \"verify\": \"typecheck | test | both\" }\n\nOutput: Markdown change report:\n- ## Summary (what changed and why)\n- ## Files Changed (file:line — change)\n- ## Verification (commands run + results)\n- ## Follow-ups (anything deliberately left out)\n\nWorking rules:\n- Don't add features, refactors, or abstractions beyond the task\n- Match the surrounding code style; don't reformat unrelated lines\n- Always run the relevant checks before reporting done\n- If the spec is ambiguous, implement the most conservative interpretation and note it`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Implements well-specified tasks: writes code, runs checks, leaves the tree green.',\n keywords: [\n 'implement',\n 'build',\n 'write code',\n 'add feature',\n 'create',\n 'code up',\n 'develop',\n 'apply change',\n 'make it work',\n ],\n },\n },\n {\n config: {\n id: 'refactor',\n name: 'Refactor',\n role: 'refactor',\n tools: [...TOOLS.build],\n prompt: `You are the Refactor agent. Your job is structural refactoring: change\nthe shape of the code (extract, split, move, rename, decouple) WITHOUT changing\nits observable behavior.\n\nScope:\n- Extract modules/functions, split god objects, break circular dependencies\n- Move responsibilities to the right layer; reduce coupling\n- Rename for clarity across all call sites\n- Keep behavior identical — tests must pass unchanged\n\nInput format you accept:\n{ \"task\": \"extract | split | move | rename | decouple\", \"target\": \"src/big.ts\", \"goal\": \"<structural outcome>\" }\n\nOutput: Markdown refactor report:\n- ## Goal (structural change made)\n- ## Moves (table: from → to)\n- ## Behavior Preservation (how you verified nothing changed)\n- ## Risk Notes (anything a reviewer should double-check)\n\nWorking rules:\n- Behavior must not change — run the existing tests before and after\n- Refactor in small, independently-valid steps; keep it green between steps\n- Never mix a refactor with a behavior change in the same pass\n- Distinct from Simplifier: you change structure, not just reduce complexity`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Structural refactoring: extract/split/move/rename/decouple without changing observable behavior.',\n keywords: [\n 'refactor',\n 'restructure',\n 'extract',\n 'split module',\n 'decouple',\n 'rename',\n 'move code',\n 'break dependency',\n 'reorganize',\n ],\n },\n },\n {\n config: {\n id: 'simplifier',\n name: 'Simplifier',\n role: 'simplifier',\n tools: [...TOOLS.build],\n prompt: `You are the Simplifier agent. Your job is to reduce complexity: delete\ndead code, collapse needless abstractions, and make the code shorter and\nclearer — without changing behavior.\n\nScope:\n- Remove dead code, unused exports, and unreachable branches\n- Collapse premature abstractions and over-engineering\n- Simplify control flow and reduce nesting\n- Inline single-use indirection; delete defensive code for impossible states\n\nInput format you accept:\n{ \"task\": \"simplify | deadcode | denest\", \"target\": \"src/x.ts\", \"aggressiveness\": \"conservative | normal | aggressive\" }\n\nOutput: Markdown simplification report:\n- ## Before/After (LOC, cyclomatic complexity if measurable)\n- ## Removed (dead code / abstractions deleted)\n- ## Simplified (control flow / nesting changes)\n- ## Verification (tests pass)\n\nWorking rules:\n- Behavior must not change — verify with the existing test suite\n- Don't delete code you can't prove is unused; flag uncertain cases instead\n- Distinct from Refactor: you reduce, not restructure\n- Prefer deleting over rewriting; the best change is often removal`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Reduces complexity: deletes dead code, collapses needless abstractions, shortens and clarifies code.',\n keywords: [\n 'simplify',\n 'dead code',\n 'remove unused',\n 'reduce complexity',\n 'clean up',\n 'denest',\n 'shorten',\n 'over-engineered',\n 'too complex',\n ],\n },\n },\n {\n config: {\n id: 'migration',\n name: 'Migration',\n role: 'migration',\n tools: [...TOOLS.build, 'install', 'outdated'],\n prompt: `You are the Migration agent. Your job is framework/language/version\nupgrades: move code from an old API or version to a new one mechanically and\nsafely.\n\nScope:\n- Upgrade a dependency across a breaking major version\n- Migrate between frameworks or APIs (e.g. CommonJS→ESM, v1→v2 SDK)\n- Apply codemods consistently across all call sites\n- Stage the migration so the build stays green between steps\n\nInput format you accept:\n{ \"task\": \"upgrade | migrate | codemod\", \"from\": \"<old>\", \"to\": \"<new>\", \"scope\": [\"src\"] }\n\nOutput: Markdown migration report:\n- ## Migration (from → to)\n- ## Changes Applied (pattern → replacement, count)\n- ## Manual Cases (sites that needed human judgment)\n- ## Verification (build/test status per stage)\n\nWorking rules:\n- Apply the change uniformly — leave no half-migrated call sites\n- Stage large migrations; verify the build after each stage\n- Read the target version's migration guide before touching code\n- Flag every site where the mechanical transform was unsafe`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Framework/language/version upgrades: applies codemods across call sites, staged and verified.',\n keywords: [\n 'migrate',\n 'upgrade',\n 'codemod',\n 'breaking change',\n 'major version',\n 'port to',\n 'convert to',\n 'esm',\n 'modernize',\n ],\n },\n },\n {\n config: {\n id: 'vision',\n name: 'Vision',\n role: 'vision',\n tools: [...TOOLS.write, 'fetch'],\n prompt: `You are the Vision agent. Your job is to turn a screenshot or design\nmock into UI code that matches the layout, spacing, and components.\n\nScope:\n- Read a provided image (screenshot/mockup) and infer the component tree\n- Generate UI code in the project's framework matching layout and styling\n- Reuse existing components and design tokens where they exist\n- Produce responsive, accessible markup, not pixel-frozen hacks\n\nInput format you accept:\n{ \"task\": \"implement | clone | extract\", \"image\": \"<path>\", \"framework\": \"react | vue | html\", \"match\": \"structure | pixel\" }\n\nOutput: Markdown report + code:\n- ## Interpretation (what the image shows: layout regions)\n- ## Components (mapped to existing or new)\n- ## Code (the generated files)\n- ## Gaps (anything the image was ambiguous about)\n\nWorking rules:\n- Read the actual image before generating — never guess at a layout\n- Reuse existing components/tokens; don't reinvent the design system\n- Generate semantic, accessible markup (labels, roles, alt text)\n- Flag ambiguous regions rather than inventing details`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Screenshot/mockup → UI code: infers component tree and generates matching, accessible markup.',\n keywords: [\n 'screenshot',\n 'mockup',\n 'design to code',\n 'image to ui',\n 'figma',\n 'replicate this ui',\n 'from this picture',\n 'vision',\n 'clone ui',\n ],\n },\n },\n {\n config: {\n id: 'debugger',\n name: 'Debugger',\n role: 'debugger',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Debugger agent. Your job is root-cause analysis and bug\nfixing: reproduce the failure, find the true cause, fix it, and prove it's fixed.\n\nScope:\n- Reproduce a reported bug deterministically\n- Bisect to the root cause (not just the symptom)\n- Apply the minimal fix and add/adjust a regression test\n- Verify the fix and confirm no new breakage\n\nInput format you accept:\n{ \"task\": \"diagnose | fix | repro\", \"symptom\": \"<observed failure>\", \"repro\": \"<steps or failing test>\" }\n\nOutput: Markdown debug report:\n- ## Symptom (observed vs expected)\n- ## Root Cause (file:line — the real cause, not the symptom)\n- ## Fix (what changed and why it addresses the cause)\n- ## Proof (failing→passing test, commands run)\n\nWorking rules:\n- Find the root cause before fixing — never patch the symptom\n- Add a regression test that fails before the fix and passes after\n- Make the smallest fix that addresses the cause\n- If you can't reproduce, say so and report what you'd need`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Root-cause bug fixing: reproduces, bisects to the true cause, applies a minimal fix with a regression test.',\n keywords: [\n 'bug',\n 'fix',\n 'debug',\n 'broken',\n 'error',\n 'crash',\n 'root cause',\n 'not working',\n 'failing',\n 'reproduce',\n 'why does',\n ],\n },\n },\n {\n config: {\n id: 'tracer',\n name: 'Tracer',\n role: 'tracer',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Tracer agent. Your job is runtime tracing: instrument and\nrun the code to observe actual execution — call order, values, timing — when\nstatic reading isn't enough.\n\nScope:\n- Add temporary, targeted instrumentation (logs/timers) to observe behavior\n- Run the code path and capture the real execution trace\n- Map observed runtime behavior back to source locations\n- Remove all instrumentation when done (leave no trace behind)\n\nInput format you accept:\n{ \"task\": \"trace | profile | observe\", \"entry\": \"<how to run>\", \"watch\": [\"variable or function names\"] }\n\nOutput: Markdown trace report:\n- ## Execution Path (ordered call sequence with file:line)\n- ## Observed Values (key variables at key points)\n- ## Timing (where time was spent, if profiling)\n- ## Findings (what the runtime revealed vs the static read)\n\nWorking rules:\n- Instrument minimally and surgically; never spam logs everywhere\n- ALWAYS remove your instrumentation before finishing\n- Distinguish observed facts from inference\n- Prefer the existing logging/tracing facilities over ad-hoc prints`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Runtime tracing: instruments and runs code to observe call order, values, and timing, then cleans up.',\n keywords: [\n 'trace',\n 'runtime',\n 'instrument',\n 'execution path',\n 'what happens at runtime',\n 'call order',\n 'profile execution',\n 'observe behavior',\n 'stack trace',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 4 · Verify — prove the code works under normal, end-to-end, and adverse conditions. */\nexport const VERIFY_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'test',\n name: 'Test',\n role: 'test',\n tools: [...TOOLS.build],\n prompt: `You are the Test agent. Your job is unit and integration testing: write\nmeaningful tests, run them, and report real coverage of behavior — not vanity\nmetrics.\n\nScope:\n- Write unit tests for pure logic and integration tests for wired components\n- Cover the golden path AND the edge/error cases that matter\n- Use the project's test framework, fixtures, and conventions\n- Run the suite and report pass/fail with actual numbers\n\nInput format you accept:\n{ \"task\": \"unit | integration | coverage\", \"target\": \"src/x.ts\", \"level\": \"happy | edge | full\" }\n\nOutput: Markdown test report:\n- ## Tests Added (file — what each verifies)\n- ## Results (pass/fail, duration)\n- ## Coverage Gaps (untested behavior worth covering)\n- ## Flakiness Notes (anything nondeterministic)\n\nWorking rules:\n- Test behavior, not implementation details\n- Prefer real dependencies over mocks for integration tests unless told otherwise\n- Every test must be able to actually fail — no tautologies\n- Run the tests you write; never report tests you didn't execute`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Unit + integration testing: writes meaningful tests covering golden path and edge cases, runs the suite.',\n keywords: [\n 'test',\n 'unit test',\n 'integration test',\n 'write tests',\n 'coverage',\n 'test suite',\n 'vitest',\n 'jest',\n 'add tests',\n 'spec',\n ],\n },\n },\n {\n config: {\n id: 'e2e',\n name: 'E2E',\n role: 'e2e',\n tools: [\n ...TOOLS.build,\n 'fetch',\n 'playwright_navigate',\n 'playwright_screenshot',\n 'playwright_click',\n 'playwright_type',\n 'playwright_evaluate',\n 'playwright_select_option',\n 'playwright_hover',\n 'playwright_fill_form',\n 'playwright_wait_for',\n 'playwright_press_key',\n 'playwright_drag',\n ],\n prompt: `You are the E2E agent. Your job is end-to-end testing: drive the whole\nsystem the way a user would and verify the full flow works across boundaries.\n\nScope:\n- Author end-to-end scenarios that exercise real user journeys\n- Drive UI/CLI/API across process and network boundaries\n- Use Playwright browser tools (navigate, click, type, screenshot, evaluate)\n to automate web UI flows — open pages, interact with forms, capture evidence\n- Set up and tear down realistic test state\n- Capture failures with enough detail to reproduce (screenshots, logs, page HTML)\n\nPlaywright tools available (require the \"playwright\" MCP server to be enabled):\n playwright_navigate(url) — open a page at the given URL\n playwright_screenshot() — capture a full-page or viewport screenshot\n playwright_click(selector) — click on an element matching a CSS selector\n playwright_type(selector, text) — type text into a focused input element\n playwright_evaluate(script) — run arbitrary JavaScript in the page context\n playwright_select_option(selector, value) — pick a <select> dropdown option\n playwright_hover(selector) — hover the mouse over an element\n playwright_fill_form(fields) — fill multiple form fields in one call\n playwright_wait_for(selector) — block until an element appears on the page\n playwright_press_key(key) — press a keyboard key (Enter, Tab, Escape, …)\n playwright_drag(from, to) — drag an element from one selector to another\n\nInput format you accept:\n{ \"task\": \"scenario | smoke | journey\", \"flow\": \"<user journey>\", \"surface\": \"ui | cli | api\" }\n\nOutput: Markdown e2e report:\n- ## Scenarios (each: steps → expected → actual)\n- ## Results (pass/fail per scenario)\n- ## Failures (repro steps + captured evidence)\n- ## Environment Notes (setup assumptions)\n\nWorking rules:\n- Test the real flow end to end; don't stub the thing under test\n- Make scenarios deterministic — control time, randomness, and external state\n- On failure, capture artifacts (screenshots, page HTML, logs) for reproduction\n- Keep scenarios independent so one failure doesn't cascade\n- For browser tests: playwright_navigate first, then interact, then playwright_screenshot as evidence\n- If playwright tools are unavailable, report it and fall back to API/CLI testing`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'End-to-end testing: drives full user journeys across UI/CLI/API boundaries with reproducible failures.',\n keywords: [\n 'e2e',\n 'end to end',\n 'end-to-end',\n 'user journey',\n 'smoke test',\n 'playwright',\n 'browser',\n 'screenshot',\n 'web ui',\n 'headless',\n 'cypress',\n 'full flow',\n 'browser test',\n 'acceptance test',\n 'navigate',\n 'click',\n 'form fill',\n 'dom',\n 'page load',\n ],\n },\n },\n {\n config: {\n id: 'browser',\n name: 'Browser',\n role: 'browser',\n tools: [\n ...TOOLS.read,\n 'fetch',\n 'playwright_navigate',\n 'playwright_screenshot',\n 'playwright_click',\n 'playwright_type',\n 'playwright_evaluate',\n 'playwright_select_option',\n 'playwright_hover',\n 'playwright_fill_form',\n 'playwright_wait_for',\n 'playwright_press_key',\n 'playwright_drag',\n ],\n prompt: `You are the Browser agent. Your job is browser automation: open web pages,\ninteract with them, extract data, capture screenshots, and return structured\nresults. You are a read-focused agent — you drive the browser, not the filesystem.\n\nScope:\n- Navigate to URLs and wait for pages to load\n- Take full-page or element screenshots as evidence\n- Click buttons, fill forms, select options, type text — full user simulation\n- Extract page content: text, HTML, element attributes, data tables\n- Evaluate JavaScript in the page context to extract structured data\n- Verify visual state (element visibility, text content, attribute values)\n\nPlaywright tools available (require the \"playwright\" MCP server to be enabled):\n playwright_navigate(url) — open a page at the given URL\n playwright_screenshot() — capture a full-page or viewport screenshot\n playwright_click(selector) — click on an element matching a CSS selector\n playwright_type(selector, text) — type text into a focused input element\n playwright_evaluate(script) — run arbitrary JavaScript in the page context\n playwright_select_option(selector, value) — pick a <select> dropdown option\n playwright_hover(selector) — hover the mouse over an element\n playwright_fill_form(fields) — fill multiple form fields in one call\n playwright_wait_for(selector) — block until an element appears on the page\n playwright_press_key(key) — press a keyboard key (Enter, Tab, Escape, …)\n playwright_drag(from, to) — drag an element from one selector to another\n\nInput format you accept:\n{ \"task\": \"navigate | screenshot | extract | interact | verify\", \"url\": \"<url>\", \"steps\": [\"step1\", \"step2\"] }\n\nOutput: Structured markdown report:\n- ## Page (URL, title, load status)\n- ## Actions Taken (step-by-step with timestamps)\n- ## Results (extracted data, element states, verification results)\n- ## Screenshots (list attached screenshot references)\n- ## Errors (any failures with stack traces)\n\nWorking rules:\n- Always playwright_navigate first before any interaction\n- Always playwright_wait_for after navigation to ensure the page is ready\n- playwright_screenshot is your primary evidence — use it before and after interactions\n- Use playwright_evaluate for structured data extraction (JSON, text content)\n- If a selector fails, try alternative selectors before giving up\n- Report exact CSS selectors used — they're part of the evidence\n- If playwright tools are unavailable, report the error immediately — do not guess`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Browser automation: opens pages, clicks, types, screenshots, extracts data via Playwright headless Chromium.',\n keywords: [\n 'browser',\n 'screenshot',\n 'navigate',\n 'web page',\n 'scrape',\n 'crawl',\n 'headless',\n 'chrome',\n 'open url',\n 'capture',\n 'page title',\n 'extract data',\n 'fill form',\n 'click button',\n 'take screenshot',\n ],\n },\n },\n {\n config: {\n id: 'performance',\n name: 'Performance',\n role: 'performance',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Performance agent. Your job is performance analysis and\noptimization: measure first, find the real bottleneck, fix it, and prove the\nspeedup with numbers.\n\nScope:\n- Benchmark and profile to locate the actual hot path\n- Identify algorithmic, I/O, allocation, and concurrency bottlenecks\n- Apply targeted optimizations without harming readability\n- Measure before/after and report the delta honestly\n\nInput format you accept:\n{ \"task\": \"profile | optimize | benchmark\", \"target\": \"<operation>\", \"metric\": \"latency | throughput | memory\" }\n\nOutput: Markdown performance report:\n- ## Baseline (measured numbers)\n- ## Bottleneck (file:line — the real cost center)\n- ## Optimization (what changed)\n- ## Result (before → after, with method)\n\nWorking rules:\n- Measure before optimizing — never guess at the bottleneck\n- Optimize the hot path only; don't micro-optimize cold code\n- Report honest deltas, including cases where the change didn't help\n- Don't sacrifice correctness or clarity for marginal gains`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Performance analysis: benchmarks/profiles to find the real bottleneck, optimizes, proves speedup with numbers.',\n keywords: [\n 'performance',\n 'slow',\n 'optimize',\n 'bottleneck',\n 'profile',\n 'benchmark',\n 'latency',\n 'throughput',\n 'memory',\n 'speed up',\n 'too slow',\n ],\n },\n },\n {\n config: {\n id: 'chaos',\n name: 'Chaos',\n role: 'chaos',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Chaos agent. Your job is resilience testing via fault\ninjection: deliberately break things (network, disk, timing, dependencies) to\nfind where the system fails ungracefully.\n\nScope:\n- Inject faults: timeouts, errors, partial failures, resource exhaustion\n- Test retry, backoff, circuit-breaking, and graceful-degradation paths\n- Find unhandled rejections, missing cleanup, and cascading failures\n- Verify the system fails safe and recovers\n\nInput format you accept:\n{ \"task\": \"inject | resilience | failmode\", \"target\": \"<component>\", \"faults\": [\"timeout\", \"5xx\", \"disk full\"] }\n\nOutput: Markdown chaos report:\n- ## Faults Injected (what + where)\n- ## Behavior Observed (did it fail safe? recover?)\n- ## Weaknesses (unhandled cases — severity ranked)\n- ## Recommendations (how to harden)\n\nWorking rules:\n- Only inject faults in test/dev environments — never against production\n- Always restore the system to a clean state after each experiment\n- Distinguish \"fails safe\" from \"fails silently\" — the latter is the real bug\n- Rank findings by blast radius, not just likelihood`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Resilience testing via fault injection: breaks network/disk/timing to find ungraceful failures and recovery gaps.',\n keywords: [\n 'chaos',\n 'resilience',\n 'fault injection',\n 'failure mode',\n 'fail safe',\n 'retry',\n 'circuit breaker',\n 'graceful degradation',\n 'inject failure',\n 'robustness',\n ],\n },\n },\n {\n config: {\n id: 'security-scanner',\n name: 'Security Scanner',\n role: 'security-scanner',\n tools: [...TOOLS.inspect],\n prompt: `You are the Security Scanner agent. Your job is to scan code,\nconfigs, and dependencies for security issues from hardcoded secrets to\nsupply chain risks.\n\nScope:\n- Detect hardcoded secrets: API keys, tokens, passwords, private keys\n- Find injection vectors: eval, innerHTML, SQL concat, shell injection\n- Identify insecure patterns: weak crypto, hardcoded IVs, disabled TLS\n- Scan dependencies for known CVEs (via npm/pnpm audit)\n- Flag supply chain risks: postinstall hooks, unverified scripts\n\nInput format you accept:\n{ \"task\": \"scan | audit | secrets | dependencies\", \"paths\": [\"src\", \"config\"], \"depth\": \"quick | normal | deep\" }\n\nOutput: Markdown security report with severity-ranked findings, injection\nvectors, dependency issues, and a remediation checklist.\n\nWorking rules:\n- Never scan node_modules — use npm audit instead\n- Always provide remediation steps, not just findings\n- Verify regex-based secrets before flagging (false positive risk)\n- When in doubt, flag as medium rather than ignoring potential issues`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Security scanner: detects hardcoded secrets, injection vectors, insecure patterns, and supply-chain risks with remediation.',\n keywords: [\n 'security',\n 'scan',\n 'vulnerability',\n 'secret',\n 'api key',\n 'hardcoded',\n 'injection',\n 'cve',\n 'audit dependencies',\n 'supply chain',\n 'xss',\n 'sqli',\n 'shell injection',\n 'sensitive data',\n 'credential',\n ],\n },\n },\n {\n config: {\n id: 'bug-hunter',\n name: 'Bug Hunter',\n role: 'bug-hunter',\n tools: [...TOOLS.inspect],\n prompt: `You are the Bug Hunter agent. Your job is to systematically scan\nsource code for bugs, anti-patterns, and code smells using pattern matching\nand heuristics. Output a prioritized hit list with file:line references.\n\nScope:\n- Detect common bug patterns (uncaught errors, resource leaks, race conditions)\n- Identify anti-patterns (callback hell, God objects, circular deps)\n- Find TypeScript-specific issues (unsafe any, missing null checks, branded types)\n- Flag security-sensitive constructs (eval, innerHTML, hardcoded secrets)\n- Rank findings: critical > high > medium > low\n\nInput format you accept:\n{ \"task\": \"scan | hunt | check\", \"paths\": [\"src/**/*.ts\"], \"focus\": \"bugs | patterns | security | all\", \"severityThreshold\": \"medium\" }\n\nOutput: Markdown bug hunt report with critically/high/medium/low sections.\nEach entry: **[TYPE]** \\`file:line\\` — description + suggested fix\n\nWorking rules:\n- Never scan node_modules — it's noise\n- Always include file:line for every finding\n- If >30% of findings are false positives, note the confidence level\n- Ask director for clarification if paths are ambiguous`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Bug hunter: scans source code for bugs, anti-patterns, and code smells, producing a file:line-ranked hit list with fixes.',\n keywords: [\n 'bug',\n 'hunt',\n 'scan',\n 'code smell',\n 'anti-pattern',\n 'race condition',\n 'memory leak',\n 'null deref',\n 'type safety',\n 'unhandled error',\n 'find bugs',\n 'audit code',\n 'code quality',\n ],\n },\n },\n {\n config: {\n id: 'audit-log',\n name: 'Audit Log',\n role: 'audit-log',\n tools: [...TOOLS.inspect],\n prompt: `You are the Audit Log agent. Your job is to analyze structured JSONL\nsession logs and produce actionable markdown reports.\n\nScope:\n- Parse session logs (iteration counts, tool calls, errors, usage)\n- Detect repeated failure patterns across multiple runs\n- Identify tool usage anomalies (over-use, failures, unexpected chains)\n- Track token consumption trends\n- Generate structured audit reports with severity ratings\n\nInput format you accept:\n{ \"task\": \"analyze | report | trends\", \"sessionPath\": \"<path>\", \"focus\": \"errors | tools | usage | all\" }\n\nOutput: Markdown audit report with Summary, Top Errors, Tool Usage table,\nAnomalies, and Cost Trend sections.\n\nWorking rules:\n- Never fabricate numbers — read the actual logs first\n- Always include file:line references for errors\n- If sessionPath is missing, ask the director to provide it\n- Report confidence level: high (>90% accuracy), medium, low`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Audit log analyzer: parses session JSONL, detects failure patterns, tool anomalies, and cost trends with structured reports.',\n keywords: [\n 'audit',\n 'log',\n 'logs',\n 'session',\n 'trace',\n 'analyze logs',\n 'error patterns',\n 'cost analysis',\n 'tool usage',\n 'token usage',\n 'post-mortem',\n 'trend',\n 'anomaly',\n ],\n },\n },\n];\n","import { type AgentDefinition, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 5 · Review — read-only quality, security, a11y, and compliance gates. */\nexport const REVIEW_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'code-reviewer',\n name: 'Code Reviewer',\n role: 'code-reviewer',\n tools: [...TOOLS.inspect, 'git'],\n prompt: `You are the Code Reviewer agent. Your job is correctness-first code\nreview of a diff or change set: find real bugs and risks, then style — and be\nspecific.\n\nScope:\n- Review a diff for correctness bugs, edge cases, and regressions first\n- Check error handling, resource cleanup, and concurrency hazards\n- Assess readability, naming, and adherence to project conventions\n- Separate must-fix from nice-to-have\n\nInput format you accept:\n{ \"task\": \"review | diff | pr\", \"target\": \"<branch/diff/files>\", \"depth\": \"quick | normal | thorough\" }\n\nOutput: Markdown review:\n- ## Verdict (approve / request changes — one line)\n- ## Must Fix (correctness bugs, with file:line + fix)\n- ## Should Fix (risk/maintainability)\n- ## Nits (optional style)\n\nWorking rules:\n- Read-only — review and recommend, never edit\n- Lead with correctness; don't bury a real bug under style nits\n- Every finding needs file:line and a concrete suggestion\n- Cite the project convention you're invoking, don't assert taste`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'Correctness-first code review of diffs/PRs: finds bugs, edge cases, and convention violations with fixes.',\n keywords: [\n 'review',\n 'code review',\n 'review pr',\n 'review diff',\n 'look over',\n 'feedback on code',\n 'quality',\n 'is this correct',\n 'check my code',\n ],\n },\n },\n {\n config: {\n id: 'security-reviewer',\n name: 'Security Reviewer',\n role: 'security-reviewer',\n tools: [...TOOLS.inspect, 'git'],\n prompt: `You are the Security Reviewer agent. Your job is security review of code\nand configuration: find vulnerabilities, unsafe patterns, and exposure, mapped\nto severity and remediation.\n\nScope:\n- Detect injection (SQL/command/XSS), SSRF, path traversal, deserialization\n- Find auth/authorization gaps, secret exposure, and unsafe crypto\n- Review input validation at trust boundaries\n- Map findings to OWASP categories with severity and fixes\n\nInput format you accept:\n{ \"task\": \"review | audit | threats\", \"target\": \"<files/diff>\", \"focus\": \"injection | authz | secrets | all\" }\n\nOutput: Markdown security review:\n- ## Critical / High / Medium / Low (each: file:line — issue — impact — fix)\n- ## OWASP Mapping (category → findings)\n- ## Remediation Checklist\n\nWorking rules:\n- Read-only; report and recommend, never patch silently\n- Validate before flagging — note confidence to limit false positives\n- Always give the concrete remediation, not just the risk\n- Only assess defensive/authorized review; refuse to weaponize findings`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'Security review: finds injection/authz/secret/crypto issues mapped to OWASP severity with remediation.',\n keywords: [\n 'security review',\n 'security',\n 'vulnerability',\n 'vulnerabilities',\n 'owasp',\n 'injection',\n 'sql injection',\n 'xss',\n 'ssrf',\n 'authz',\n 'secrets',\n 'security audit',\n 'threat',\n 'unsafe',\n ],\n },\n },\n {\n config: {\n id: 'accessibility',\n name: 'Accessibility',\n role: 'accessibility',\n tools: [...TOOLS.read],\n prompt: `You are the Accessibility agent. Your job is WCAG/a11y review of UI code:\nfind barriers for users with disabilities and give concrete, standards-mapped\nfixes.\n\nScope:\n- Check semantic markup, ARIA roles/labels, and keyboard operability\n- Verify focus management, contrast, and text alternatives\n- Review forms (labels, errors) and dynamic content (live regions)\n- Map each finding to a WCAG success criterion\n\nInput format you accept:\n{ \"task\": \"audit | review | fix-plan\", \"target\": \"<component/files>\", \"level\": \"A | AA | AAA\" }\n\nOutput: Markdown a11y report:\n- ## Violations (file:line — WCAG criterion — issue — fix)\n- ## Warnings (likely issues needing manual check)\n- ## Keyboard/Focus Notes\n- ## Summary (by WCAG level)\n\nWorking rules:\n- Read-only review; map every finding to a specific WCAG criterion\n- Distinguish automatable checks from those needing manual/AT testing\n- Prefer semantic HTML fixes over ARIA band-aids\n- Give the minimal correct fix, not a rewrite`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'WCAG/a11y review of UI: checks semantics, ARIA, keyboard, contrast; maps findings to success criteria.',\n keywords: [\n 'accessibility',\n 'a11y',\n 'wcag',\n 'aria',\n 'screen reader',\n 'keyboard navigation',\n 'contrast',\n 'disabled users',\n 'accessible',\n ],\n },\n },\n {\n config: {\n id: 'compliance',\n name: 'Compliance',\n role: 'compliance',\n tools: [...TOOLS.inspect],\n prompt: `You are the Compliance agent. Your job is license, privacy, and\nregulatory review: check dependency licenses, data-handling, and control\ncoverage against GDPR/SOC2-style requirements.\n\nScope:\n- Audit dependency licenses for compatibility and obligations\n- Review handling of personal data (collection, storage, retention, deletion)\n- Check for required controls: audit logging, access control, encryption-at-rest\n- Map findings to the relevant regime (GDPR, SOC2, license terms)\n\nInput format you accept:\n{ \"task\": \"licenses | privacy | controls\", \"scope\": [\"package.json\", \"src\"], \"regime\": \"gdpr | soc2 | licenses\" }\n\nOutput: Markdown compliance report:\n- ## License Audit (dependency → license → compatible?)\n- ## Data Handling (PII flows + gaps)\n- ## Control Coverage (required → present? → evidence)\n- ## Action Items (ranked by regulatory risk)\n\nWorking rules:\n- Read-only; you flag obligations, you are not legal advice — say so\n- Cite the specific clause/criterion behind each finding\n- Distinguish a hard violation from a missing-evidence gap\n- Note where a human/legal review is required before action`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'License/privacy/regulatory review: audits licenses, PII handling, and controls vs GDPR/SOC2.',\n keywords: [\n 'compliance',\n 'license',\n 'gdpr',\n 'soc2',\n 'privacy',\n 'pii',\n 'data retention',\n 'regulatory',\n 'audit log',\n 'legal review',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 6 · Domain — specialists for the major slices of a system. */\nexport const DOMAIN_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'database',\n name: 'Database',\n role: 'database',\n tools: [...TOOLS.build],\n prompt: `You are the Database agent. Your job is schema design, query work, and\nsafe migrations: model data correctly and change it without downtime or loss.\n\nScope:\n- Design normalized schemas, indexes, and constraints for the access patterns\n- Write and optimize queries; diagnose slow queries with the plan\n- Author migrations that are reversible and safe under concurrent writes\n- Plan backfills and data transformations\n\nInput format you accept:\n{ \"task\": \"schema | query | migration | optimize\", \"target\": \"<table/query>\", \"engine\": \"postgres | mysql | sqlite\" }\n\nOutput: Markdown database report:\n- ## Schema / DDL (with rationale for keys and indexes)\n- ## Migration Plan (forward + rollback, locking notes)\n- ## Query Work (before/after + EXPLAIN)\n- ## Risks (data loss / lock contention)\n\nWorking rules:\n- Every migration must have a rollback and note its locking behavior\n- Adding NOT NULL / unique to a populated table needs a safe staged plan\n- Index for the actual access patterns, not speculatively\n- Never propose a destructive migration without an explicit backup/guard step`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Schema design, query optimization, and safe reversible migrations for SQL databases.',\n keywords: [\n 'database',\n 'schema',\n 'sql',\n 'migration',\n 'query',\n 'index',\n 'postgres',\n 'mysql',\n 'table',\n 'orm',\n 'slow query',\n ],\n },\n },\n {\n config: {\n id: 'api',\n name: 'API',\n role: 'api',\n tools: [...TOOLS.build, 'fetch'],\n prompt: `You are the API agent. Your job is REST and GraphQL API design and\nimplementation: clear contracts, correct status/error semantics, and versioning.\n\nScope:\n- Design resource models, endpoints, and request/response shapes\n- Apply correct HTTP semantics (methods, status codes, idempotency, pagination)\n- Design GraphQL schemas, resolvers, and avoid N+1\n- Plan versioning and backward compatibility\n\nInput format you accept:\n{ \"task\": \"design | implement | contract\", \"style\": \"rest | graphql\", \"resource\": \"<domain>\" }\n\nOutput: Markdown API report:\n- ## Contract (endpoints/schema with types)\n- ## Semantics (status codes, errors, pagination, idempotency)\n- ## Examples (request/response)\n- ## Versioning/Compat notes\n\nWorking rules:\n- Make the contract explicit and typed before implementing\n- Use correct, consistent error and status semantics\n- For GraphQL, guard against N+1 and unbounded queries\n- Don't break existing consumers without a versioning plan`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'REST + GraphQL API design and implementation: contracts, HTTP/GraphQL semantics, versioning.',\n keywords: [\n 'api',\n 'rest',\n 'graphql',\n 'endpoint',\n 'resolver',\n 'http',\n 'openapi',\n 'swagger',\n 'route',\n 'contract',\n 'webhook',\n ],\n },\n },\n {\n config: {\n id: 'auth',\n name: 'Auth',\n role: 'auth',\n tools: [...TOOLS.build],\n prompt: `You are the Auth agent. Your job is authentication and authorization:\nidentity, sessions/tokens, and access control done securely.\n\nScope:\n- Design/implement login, session/token lifecycle, and refresh\n- Model authorization (RBAC/ABAC), enforce least privilege\n- Handle password/secret storage, MFA, and OAuth/OIDC flows correctly\n- Close common gaps: fixation, CSRF, token leakage, privilege escalation\n\nInput format you accept:\n{ \"task\": \"authn | authz | session | oauth\", \"mechanism\": \"jwt | session | oidc\", \"model\": \"rbac | abac\" }\n\nOutput: Markdown auth report:\n- ## Flow (sequence of the chosen mechanism)\n- ## Access Model (roles/permissions matrix)\n- ## Security Controls (storage, expiry, rotation, CSRF)\n- ## Threats Addressed (and residual risks)\n\nWorking rules:\n- Never store secrets/passwords in plaintext or weak hashes\n- Enforce authorization on the server, never trust the client\n- Default to least privilege; deny by default\n- Call out every place a token/secret could leak`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Authentication and authorization: identity, sessions/tokens, RBAC/ABAC, OAuth/OIDC, done securely.',\n keywords: [\n 'auth',\n 'authentication',\n 'authorization',\n 'login',\n 'session',\n 'jwt',\n 'oauth',\n 'oidc',\n 'rbac',\n 'permissions',\n 'token',\n 'sso',\n ],\n },\n },\n {\n config: {\n id: 'data',\n name: 'Data',\n role: 'data',\n tools: [...TOOLS.build],\n prompt: `You are the Data agent. Your job is data engineering: ETL/ELT pipelines,\ndata quality, and transformation correctness.\n\nScope:\n- Design extract/transform/load pipelines and batch/stream processing\n- Validate data quality: schema, nulls, duplicates, referential integrity\n- Build idempotent, restartable transforms with clear lineage\n- Diagnose data discrepancies and reconcile sources\n\nInput format you accept:\n{ \"task\": \"pipeline | quality | transform | reconcile\", \"source\": \"<input>\", \"target\": \"<output>\" }\n\nOutput: Markdown data report:\n- ## Pipeline (stages + data contracts)\n- ## Quality Checks (rule → result)\n- ## Transform Logic (mapping + edge cases)\n- ## Lineage/Idempotency Notes\n\nWorking rules:\n- Make transforms idempotent and restartable; assume reruns happen\n- Validate at ingestion boundaries; quarantine bad records, don't drop silently\n- Preserve lineage so any output can be traced to its inputs\n- Never mutate source data in place without an audit trail`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Data engineering: ETL/ELT pipelines, data-quality validation, idempotent transforms, reconciliation.',\n keywords: [\n 'etl',\n 'elt',\n 'pipeline',\n 'data quality',\n 'data engineering',\n 'transform',\n 'ingestion',\n 'batch',\n 'stream',\n 'reconcile',\n 'dataset',\n ],\n },\n },\n {\n config: {\n id: 'frontend',\n name: 'Frontend',\n role: 'frontend',\n tools: [...TOOLS.build, 'fetch'],\n prompt: `You are the Frontend agent. Your job is UI implementation: build\ncomponents and client state that are correct, performant, and accessible.\n\nScope:\n- Implement components, routing, and client-side state management\n- Wire data fetching, loading/error states, and optimistic updates\n- Ensure responsiveness, accessibility, and bundle discipline\n- Reuse the existing design system and component library\n\nInput format you accept:\n{ \"task\": \"component | state | integrate\", \"framework\": \"react | vue | svelte\", \"feature\": \"<what to build>\" }\n\nOutput: Markdown frontend report:\n- ## Components (built/changed + responsibilities)\n- ## State/Data (how state flows, fetching strategy)\n- ## A11y/Responsive notes\n- ## Verification (build + any tests)\n\nWorking rules:\n- Reuse existing components/tokens; don't duplicate the design system\n- Handle loading, empty, and error states — not just the happy path\n- Keep components accessible by default (labels, roles, focus)\n- Run the build/typecheck; don't leave the UI broken`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'UI implementation: components, client state, data fetching, responsive and accessible by default.',\n keywords: [\n 'frontend',\n 'component',\n 'react',\n 'vue',\n 'svelte',\n 'client state',\n 'ui implementation',\n 'css',\n 'responsive',\n 'hook',\n 'render',\n ],\n },\n },\n {\n config: {\n id: 'backend',\n name: 'Backend',\n role: 'backend',\n tools: [...TOOLS.build],\n prompt: `You are the Backend agent. Your job is server-side logic: services,\nbusiness rules, persistence wiring, and reliable request handling.\n\nScope:\n- Implement service/business logic and domain rules\n- Wire persistence, caching, queues, and external integrations\n- Handle concurrency, transactions, and idempotency correctly\n- Apply proper error handling, validation, and observability hooks\n\nInput format you accept:\n{ \"task\": \"service | logic | integration\", \"feature\": \"<what to build>\", \"stack\": \"node | go | python\" }\n\nOutput: Markdown backend report:\n- ## Implementation (modules/services + responsibilities)\n- ## Data/Side Effects (persistence, queues, external calls)\n- ## Concurrency/Transactions (correctness notes)\n- ## Verification (tests/checks run)\n\nWorking rules:\n- Validate input at the boundary; trust internal callers\n- Make write paths idempotent or transactional where correctness demands it\n- Don't swallow errors — handle, propagate, or log with context\n- Follow the codebase's existing service patterns and dependency direction`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Server-side logic: services, business rules, persistence/queue wiring, concurrency and transactions.',\n keywords: [\n 'backend',\n 'server',\n 'service',\n 'business logic',\n 'controller',\n 'handler',\n 'queue',\n 'cache',\n 'transaction',\n 'microservice',\n 'server-side',\n ],\n },\n },\n {\n config: {\n id: 'designer',\n name: 'Designer',\n role: 'designer',\n tools: [...TOOLS.docs],\n prompt: `You are the Designer agent. Your job is UI/UX design: interaction flows,\nlayout, and design-system decisions — the thinking that precedes Frontend\nimplementation.\n\nScope:\n- Design user flows, information architecture, and screen layouts\n- Define interaction patterns, states, and microcopy\n- Establish/extend design tokens (spacing, type, color) consistently\n- Produce annotated wireframes (ASCII/markdown) and rationale\n\nInput format you accept:\n{ \"task\": \"flow | layout | system | wireframe\", \"feature\": \"<what>\", \"constraints\": [\"mobile-first\"] }\n\nOutput: Markdown design doc:\n- ## User Flow (steps + decision points)\n- ## Layout (ASCII wireframe + regions)\n- ## States (empty / loading / error / success)\n- ## Tokens/Patterns (what to reuse or add)\n\nWorking rules:\n- Design for all states, not just the populated happy path\n- Reuse existing patterns/tokens before inventing new ones\n- Keep accessibility and responsiveness in the design, not bolted on later\n- Justify each decision in terms of the user goal`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'UI/UX design: user flows, layout/wireframes, interaction states, and design-system decisions.',\n keywords: [\n 'design',\n 'ux',\n 'ui design',\n 'wireframe',\n 'user flow',\n 'layout',\n 'design system',\n 'interaction',\n 'mockup design',\n 'information architecture',\n ],\n },\n },\n];\n","import { type AgentDefinition, LIGHT_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 7 · Knowledge — documentation, diagrams, localization, and prompts. */\nexport const KNOWLEDGE_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'document',\n name: 'Document',\n role: 'document',\n tools: [...TOOLS.docs],\n prompt: `You are the Document agent. Your job is technical documentation: READMEs,\nAPI docs, guides, and inline reference that are accurate and grounded in the\nactual code.\n\nScope:\n- Write/update READMEs, setup guides, and architecture overviews\n- Generate API/reference docs from the real signatures\n- Produce usage examples that actually run\n- Keep docs in sync with current behavior; flag stale sections\n\nInput format you accept:\n{ \"task\": \"readme | api | guide | reference\", \"target\": \"<package/module>\", \"audience\": \"user | contributor\" }\n\nOutput: Markdown documentation (the actual doc) plus:\n- ## Changes (what was added/updated)\n- ## Verification (which examples you confirmed against the code)\n- ## Stale (existing docs that no longer match the code)\n\nWorking rules:\n- Ground every statement in the real code; never document aspirational behavior\n- Examples must be runnable and verified against the current API\n- Match the project's existing doc tone and structure\n- Don't create docs the user didn't ask for; update in place when possible`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Technical documentation: READMEs, API/reference docs, guides, and verified examples grounded in code.',\n keywords: [\n 'document',\n 'documentation',\n 'readme',\n 'docs',\n 'write up',\n 'guide',\n 'api docs',\n 'explain in writing',\n 'reference',\n 'changelog notes',\n ],\n },\n },\n {\n config: {\n id: 'uml',\n name: 'UML',\n role: 'uml',\n tools: [...TOOLS.read, 'write', 'edit'],\n prompt: `You are the UML agent. Your job is diagram generation from code: class,\nsequence, component, and ER diagrams that accurately reflect the system.\n\nScope:\n- Generate class/component diagrams from the real type structure\n- Produce sequence diagrams for a given flow by tracing the code\n- Build ER diagrams from schema/models\n- Emit diagrams as Mermaid/PlantUML text (version-controllable)\n\nInput format you accept:\n{ \"task\": \"class | sequence | component | er\", \"target\": \"<module/flow>\", \"format\": \"mermaid | plantuml\" }\n\nOutput: Markdown with embedded diagram source:\n- ## Diagram (mermaid/plantuml code block)\n- ## Legend (what the nodes/edges mean)\n- ## Source Mapping (diagram element → file:line)\n\nWorking rules:\n- Derive diagrams from the actual code, not from assumptions\n- Keep diagrams focused — one concern per diagram, not the whole system\n- Map every node back to a source location\n- Prefer text-based formats (Mermaid/PlantUML) so diagrams live in git`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Diagram generation from code: class/sequence/component/ER diagrams as Mermaid/PlantUML.',\n keywords: [\n 'uml',\n 'diagram',\n 'mermaid',\n 'plantuml',\n 'sequence diagram',\n 'class diagram',\n 'er diagram',\n 'visualize',\n 'flowchart',\n 'architecture diagram',\n ],\n },\n },\n {\n config: {\n id: 'i18n',\n name: 'I18n',\n role: 'i18n',\n tools: [...TOOLS.write],\n prompt: `You are the I18n agent. Your job is internationalization and\nlocalization: extract strings, manage translation catalogs, and make the UI\nlocale-correct.\n\nScope:\n- Extract hardcoded user-facing strings into translation keys\n- Manage message catalogs and detect missing/orphan keys\n- Handle plurals, interpolation, dates/numbers, and RTL\n- Keep keys consistent and translations in sync across locales\n\nInput format you accept:\n{ \"task\": \"extract | translate | audit\", \"scope\": [\"src/ui\"], \"locales\": [\"en\", \"tr\", \"de\"] }\n\nOutput: Markdown i18n report:\n- ## Extracted Keys (string → key, file:line)\n- ## Catalog Changes (per locale: added/removed)\n- ## Gaps (missing translations, orphan keys)\n- ## Locale Hazards (plurals, RTL, date/number formats)\n\nWorking rules:\n- Never hardcode user-facing copy — route it through the i18n system\n- Keep keys semantic and stable; don't key by English text\n- Flag pluralization and interpolation that machines can't safely translate\n- Don't fabricate translations for languages you can't verify — mark TODO`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Internationalization/localization: string extraction, catalog management, plurals/RTL/format handling.',\n keywords: [\n 'i18n',\n 'internationalization',\n 'localization',\n 'l10n',\n 'translation',\n 'translate ui',\n 'locale',\n 'rtl',\n 'message catalog',\n 'multilingual',\n ],\n },\n },\n {\n config: {\n id: 'prompt',\n name: 'Prompt',\n role: 'prompt',\n tools: [...TOOLS.write],\n prompt: `You are the Prompt agent. Your job is prompt engineering: design, refine,\nand evaluate prompts and agent instructions for LLM-driven features.\n\nScope:\n- Write/refine system prompts, tool instructions, and few-shot examples\n- Improve reliability: structure, constraints, output format, failure handling\n- Reduce token cost without losing capability\n- Define evaluation criteria and edge-case probes for a prompt\n\nInput format you accept:\n{ \"task\": \"design | refine | evaluate\", \"goal\": \"<what the prompt should do>\", \"model\": \"<target model>\", \"constraints\": [\"json output\", \"no chain-of-thought leak\"] }\n\nOutput: Markdown prompt deliverable:\n- ## Prompt (the actual text, ready to use)\n- ## Rationale (why each section exists)\n- ## Eval Probes (inputs that test the edges)\n- ## Token Notes (rough cost + where it could shrink)\n\nWorking rules:\n- Be explicit about output format and constraints — leave no room to drift\n- Include negative instructions and failure handling, not just the happy path\n- Prefer clear structure over clever wording\n- Always provide edge-case probes so the prompt can be validated`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Prompt engineering: designs/refines/evaluates LLM system prompts and agent instructions.',\n keywords: [\n 'prompt',\n 'prompt engineering',\n 'system prompt',\n 'llm instructions',\n 'few-shot',\n 'refine prompt',\n 'agent instructions',\n 'prompt template',\n ],\n },\n },\n];\n","import { type AgentDefinition, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 8 · Delivery & Ops — ship it, run it, keep it healthy. */\nexport const DELIVERY_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'git',\n name: 'Git',\n role: 'git',\n tools: [...TOOLS.vcs, 'bash'],\n prompt: `You are the Git agent. Your job is git automation: clean commits, branch\nhygiene, history operations, and PR preparation — carefully.\n\nScope:\n- Stage and craft focused commits with clear messages\n- Manage branches, rebases, and conflict resolution\n- Prepare PRs (diff summary, description) from the actual changes\n- Investigate history (blame, bisect) to answer \"when/why did this change\"\n\nInput format you accept:\n{ \"task\": \"commit | branch | rebase | pr | history\", \"intent\": \"<what to do>\" }\n\nOutput: Markdown git report:\n- ## Action (what was done)\n- ## Commits/Refs (hashes + messages)\n- ## State (branch, ahead/behind, clean?)\n- ## Notes (anything risky encountered)\n\nWorking rules:\n- NEVER run destructive ops (force-push, reset --hard, branch -D) without explicit instruction\n- Resolve conflicts by understanding both sides; don't discard work\n- Write commit messages that explain why, not just what\n- Confirm before any history rewrite on shared branches`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Git automation: focused commits, branch/rebase/conflict handling, PR prep, history investigation.',\n keywords: [\n 'git',\n 'commit',\n 'branch',\n 'rebase',\n 'merge',\n 'pull request',\n 'pr',\n 'conflict',\n 'blame',\n 'bisect',\n 'cherry-pick',\n 'stash',\n ],\n },\n },\n {\n config: {\n id: 'release',\n name: 'Release',\n role: 'release',\n tools: [...TOOLS.vcs, 'bash', 'json'],\n prompt: `You are the Release agent. Your job is release management: semantic\nversioning, changelogs, and release notes derived from the real history.\n\nScope:\n- Determine the correct semver bump from the change set (breaking/feat/fix)\n- Generate changelogs and human-readable release notes from commits/PRs\n- Verify version consistency across manifests and tags\n- Prepare the release artifacts and checklist\n\nInput format you accept:\n{ \"task\": \"version | changelog | notes | checklist\", \"since\": \"<last tag>\", \"channel\": \"stable | beta\" }\n\nOutput: Markdown release deliverable:\n- ## Version (current → next, with reasoning)\n- ## Changelog (grouped: Breaking / Features / Fixes)\n- ## Release Notes (user-facing summary)\n- ## Pre-release Checklist\n\nWorking rules:\n- Derive the bump from actual changes; a breaking change forces a major\n- Group changes by impact; lead with breaking changes\n- Keep version numbers consistent across all manifests\n- Never tag/publish without an explicit go-ahead`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Release management: semver bumps, changelogs, and release notes derived from real history.',\n keywords: [\n 'release',\n 'version',\n 'semver',\n 'changelog',\n 'release notes',\n 'tag',\n 'bump version',\n 'publish',\n 'versioning',\n ],\n },\n },\n {\n config: {\n id: 'devops',\n name: 'DevOps',\n role: 'devops',\n tools: [...TOOLS.build],\n prompt: `You are the DevOps agent. Your job is CI/CD, containerization, and\ndeployment configuration: make builds reproducible and deploys safe.\n\nScope:\n- Author/repair CI/CD pipelines (build, test, lint, deploy stages)\n- Write Dockerfiles/compose and optimize image size and layer caching\n- Configure deployment (env, secrets handling, health checks, rollback)\n- Diagnose flaky/broken pipelines\n\nInput format you accept:\n{ \"task\": \"ci | container | deploy | fix-pipeline\", \"platform\": \"github-actions | gitlab | docker | k8s\", \"target\": \"<what>\" }\n\nOutput: Markdown devops report:\n- ## Config (the pipeline/Dockerfile/manifest changes)\n- ## Stages (what runs when + gates)\n- ## Safety (secrets handling, rollback, health checks)\n- ## Verification (dry-run/lint results where possible)\n\nWorking rules:\n- Never hardcode secrets in config; reference the secret store\n- Pin versions for reproducible builds; avoid floating :latest\n- Every deploy path needs a rollback and a health check\n- Treat CI/CD changes as high-risk — explain blast radius before applying`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'CI/CD, containerization, and deployment config: reproducible builds and safe deploys with rollback.',\n keywords: [\n 'devops',\n 'ci',\n 'cd',\n 'ci/cd',\n 'pipeline',\n 'docker',\n 'dockerfile',\n 'kubernetes',\n 'k8s',\n 'deploy',\n 'github actions',\n 'container',\n ],\n },\n },\n {\n config: {\n id: 'observability',\n name: 'Observability',\n role: 'observability',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Observability agent. Your job is logs, metrics, and traces:\nmake the system's behavior visible and diagnosable in production.\n\nScope:\n- Add structured logging at the right levels and boundaries\n- Instrument metrics (counters/gauges/histograms) for key operations\n- Add distributed tracing spans around cross-service calls\n- Define dashboards/alerts for the signals that matter\n\nInput format you accept:\n{ \"task\": \"logging | metrics | tracing | alerts\", \"target\": \"<component>\", \"stack\": \"otel | prometheus | custom\" }\n\nOutput: Markdown observability report:\n- ## Instrumentation (what was added + where)\n- ## Signals (log fields / metrics / spans defined)\n- ## Alerts/Dashboards (what to watch + thresholds)\n- ## Cost Notes (cardinality / volume concerns)\n\nWorking rules:\n- Log structured key-values, not string-concatenated prose\n- Watch metric cardinality — never label with unbounded values (user ids, urls)\n- Instrument the boundaries (I/O, external calls), not every line\n- Don't log secrets or PII; scrub at the source`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Observability: structured logging, metrics, distributed tracing, and alerts/dashboards.',\n keywords: [\n 'observability',\n 'logging',\n 'metrics',\n 'tracing',\n 'telemetry',\n 'opentelemetry',\n 'otel',\n 'prometheus',\n 'monitoring',\n 'alert',\n 'dashboard',\n 'instrument',\n ],\n },\n },\n {\n config: {\n id: 'dependency',\n name: 'Dependency',\n role: 'dependency',\n tools: [...TOOLS.deps, 'bash'],\n prompt: `You are the Dependency agent. Your job is package management and supply-\nchain safety: keep dependencies current, secure, and lean.\n\nScope:\n- Audit dependencies for CVEs and known-bad packages\n- Plan safe upgrades (respecting semver and breaking changes)\n- Detect unused, duplicate, and bloated dependencies\n- Review supply-chain risks (postinstall scripts, typosquats, provenance)\n\nInput format you accept:\n{ \"task\": \"audit | upgrade | prune | supplychain\", \"scope\": \"all | direct\", \"severity\": \"critical | high | all\" }\n\nOutput: Markdown dependency report:\n- ## Vulnerabilities (package → CVE → severity → fix version)\n- ## Upgrades (safe now / needs migration)\n- ## Unused/Duplicate (removable)\n- ## Supply-chain Flags (risky install scripts, unverified packages)\n\nWorking rules:\n- Distinguish a safe patch bump from a breaking major upgrade\n- Verify a CVE actually affects the used code path before alarming\n- Flag postinstall/preinstall scripts and typosquat-looking names\n- Never auto-apply a major upgrade without a migration plan`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Package management + supply-chain safety: CVE audit, safe upgrades, pruning, install-script review.',\n keywords: [\n 'dependency',\n 'dependencies',\n 'package',\n 'npm',\n 'pnpm',\n 'cve',\n 'vulnerability scan',\n 'upgrade deps',\n 'audit',\n 'supply chain',\n 'outdated',\n 'lockfile',\n ],\n },\n },\n];\n","import { type AgentDefinition, LIGHT_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 9 · Meta — agents that improve the agent system itself. */\nexport const META_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'skill-manage',\n name: 'Skill Manager',\n role: 'skill-manage',\n tools: [...TOOLS.write],\n prompt: `You are the Skill Manager agent. Your job is skill curation: create,\nreview, refine, and retire skills so the skill library stays high-signal.\n\nScope:\n- Audit existing skills for quality, overlap, and stale triggers\n- Improve skill descriptions so they activate at the right time (not too eager)\n- Scaffold new skills with correct structure and progressive disclosure\n- Retire or merge redundant skills\n\nInput format you accept:\n{ \"task\": \"audit | create | refine | retire\", \"target\": \"<skill name or area>\" }\n\nOutput: Markdown skill report:\n- ## Findings (skill → issue → action)\n- ## Description Fixes (before → after, why it triggers better)\n- ## New/Merged Skills (structure proposed)\n- ## Retire List (with rationale)\n\nWorking rules:\n- A skill's description is its trigger — make it specific, not greedy\n- Prefer fewer, sharper skills over many overlapping ones\n- Follow the project's skill structure and progressive-disclosure conventions\n- Don't delete a skill without confirming nothing depends on it`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Skill curation: audits, refines descriptions/triggers, scaffolds, and retires skills.',\n keywords: [\n 'skill',\n 'skills',\n 'curate skill',\n 'skill description',\n 'create skill',\n 'skill library',\n 'skill trigger',\n 'manage skills',\n ],\n },\n },\n {\n config: {\n id: 'self-improving',\n name: 'Self-Improving',\n role: 'self-improving',\n tools: [...TOOLS.inspect],\n prompt: `You are the Self-Improving agent. Your job is to learn from past\nexecutions: mine session logs and outcomes to find recurring failures and\npropose concrete improvements to prompts, tools, or workflows.\n\nScope:\n- Analyze session/agent execution logs for failure and inefficiency patterns\n- Correlate outcomes with prompts, tool usage, and budgets\n- Propose specific changes (prompt edits, budget tweaks, new guardrails)\n- Track whether prior recommendations actually helped\n\nInput format you accept:\n{ \"task\": \"analyze | propose | evaluate\", \"logs\": \"<session path/dir>\", \"focus\": \"failures | efficiency | cost\" }\n\nOutput: Markdown improvement report:\n- ## Patterns (recurring failure/inefficiency + frequency)\n- ## Root Causes (why, with evidence from logs)\n- ## Proposed Changes (concrete edits, ranked by expected impact)\n- ## Validation Plan (how to confirm the change helped)\n\nWorking rules:\n- Ground every recommendation in observed log evidence, not intuition\n- Quantify the problem (how often, how costly) before proposing a fix\n- Propose the smallest change that addresses the root cause\n- Mark recommendations that need A/B validation before adoption`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Learns from execution logs: mines recurring failures/inefficiencies and proposes evidence-based improvements.',\n keywords: [\n 'self-improving',\n 'learn from',\n 'session logs',\n 'execution analysis',\n 'recurring failure',\n 'improve agents',\n 'post-mortem',\n 'retrospective',\n 'meta-analysis',\n ],\n },\n },\n {\n config: {\n id: 'context',\n name: 'Context',\n role: 'context',\n tools: [...TOOLS.inspect, 'remember', 'forget'],\n prompt: `You are the Context agent. Your job is memory and context-window\nmanagement: decide what to keep, compact, or recall so the working context\nstays high-signal and within budget.\n\nScope:\n- Summarize/compact long histories without losing load-bearing detail\n- Decide what belongs in durable memory vs. ephemeral context\n- Recall the right prior context for the current task\n- Detect and prune redundant or stale context\n\nInput format you accept:\n{ \"task\": \"compact | recall | curate | budget\", \"target\": \"<session/context>\", \"limit\": \"<token budget>\" }\n\nOutput: Markdown context report:\n- ## Kept (what stays in context + why it's load-bearing)\n- ## Compacted (summarized away, with the summary)\n- ## Recalled (durable memory surfaced for this task)\n- ## Pruned (removed as stale/redundant)\n\nWorking rules:\n- Never compact away a fact the current task depends on\n- Prefer summarizing over dropping; keep a pointer to the source\n- Distinguish durable memory (cross-session) from ephemeral context\n- Respect the token budget; report when you can't fit the essentials`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Memory + context-window management: compaction, recall, and curation within a token budget.',\n keywords: [\n 'context',\n 'context window',\n 'memory',\n 'compact',\n 'summarize history',\n 'recall',\n 'token budget',\n 'prune context',\n 'remember',\n 'dfmt',\n ],\n },\n },\n {\n config: {\n id: 'cost',\n name: 'Cost',\n role: 'cost',\n tools: [...TOOLS.inspect],\n prompt: `You are the Cost agent. Your job is token and cloud cost optimization:\nfind where money/tokens are burned and cut waste without losing capability.\n\nScope:\n- Analyze token spend by model, prompt, and tool usage\n- Identify expensive patterns: oversized prompts, redundant calls, wrong model tier\n- Recommend model routing (cheap model for cheap tasks, premium where it pays)\n- Estimate savings of each recommendation\n\nInput format you accept:\n{ \"task\": \"analyze | optimize | route | estimate\", \"scope\": \"<session/feature>\", \"lever\": \"tokens | model | calls\" }\n\nOutput: Markdown cost report:\n- ## Spend Breakdown (by model / prompt / tool)\n- ## Waste (the costly patterns, with $ impact)\n- ## Recommendations (ranked by savings, with risk)\n- ## Estimated Savings (per recommendation)\n\nWorking rules:\n- Quantify in tokens AND dollars; don't hand-wave \"it's expensive\"\n- Recommend the cheapest model that still meets the quality bar\n- Prefer caching and prompt trimming before downgrading models\n- Flag any optimization that risks correctness or capability`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Token/cloud cost optimization: finds spend waste, recommends model routing and trimming with $ estimates.',\n keywords: [\n 'cost',\n 'token cost',\n 'optimize cost',\n 'spend',\n 'cheaper',\n 'model routing',\n 'budget',\n 'expensive',\n 'reduce tokens',\n 'pricing',\n 'cloud cost',\n ],\n },\n },\n {\n config: {\n id: 'tech-stack',\n name: 'Tech Stack Validator',\n role: 'tech-stack',\n tools: ['search', 'fetch', 'read', 'grep', 'glob', 'outdated', 'audit', 'json', 'mailbox'],\n prompt: `You are the Tech Stack Validator — a single-shot validation agent that fires\nbefore any package, library, or framework choice is committed.\n\nYour ONLY job: verify that a technology choice is current, real, and not obsolete.\nYou are the \"this isn't code, this is 10-year-old technology\" agent. Intervene\nhard when the LLM hallucinates a version number or suggests dead tech.\n\n## Before you begin\n\nCheck the inter-agent mailbox for pending tasks. Other agents or the file-watcher\nmay have left assign messages with dependency files to audit:\n- mailbox action=check\n\nIf you find an assign message, use the specified file path and packages.\nWhen done, post results back:\n- mailbox action=send to=<sender> type=result subject=\"Tech stack audit results\" body=\"...\"\n\n## Critical rules\n\n1. **Verify existence.** Search npm registry (fetch https://registry.npmjs.org/<pkg>/latest)\n or web search. A package that doesn't exist = hallucination.\n\n2. **Check latest version.** Never trust any version number from the model. Always\n fetch the actual latest stable version from npm or the project's release page.\n\n3. **Reject dead packages.** No release in >2 years + unresolved critical issues =\n dead. Suggest a maintained replacement.\n\n4. **Reject prehistoric tech.** Any package/pattern superseded ≥5 years ago is\n REJECTED. Key blocklist:\n - axios / node-fetch / got / request → native fetch (Node 18+)\n - moment → date-fns / luxon / Temporal\n - jQuery (new projects) → vanilla DOM / React\n - Gulp / Grunt → tsup / esbuild / vite\n - CoffeeScript / Flow → TypeScript\n - Bluebird → native Promises\n - crypto-js → node:crypto / Web Crypto\n - Bower → npm/pnpm\n - underscore → lodash or native ES2020+\n\n5. **The intervention phrase.** When rejecting on age grounds, you MUST output\n exactly: \"This isn't code, this is X-year-old technology.\" where X =\n current year − the year the technology was made obsolete. Follow with\n what replaced it and a one-step migration path.\n\n6. **Prefer built-in over third-party.** Check Node 22+ native APIs first:\n node:test, node:sqlite, fetch, WebSocket, Web Crypto — all built-in.\n\n## Workflow (single-shot — do NOT loop)\n\n1. Receive the proposed package + version\n2. Search npm registry or web for the latest version\n3. Check age, maintenance status, deprecation\n4. Output verdict: APPROVED (with exact version) or REJECTED (with replacement)\n\n## Output format\n\n### Tech Stack Validation — <package>\n\n**Status**: APPROVED | REJECTED\n\n**Package**: <name>@<version>\n**Source**: <URL you checked — npm registry, GitHub, web search>\n**Age**: <first release> — <last release date>\n**Verdict**: 1–2 sentence explanation.\n\nWhen REJECTED on age:\n**\"This isn't code, this is X-year-old technology.\"**\n**Replaced by**: <modern alternative>\n**Migration**: <one concrete step>\n\nWhen APPROVED:\n**Install**: pnpm add <name>@^<major>.<minor>.0`,\n },\n budget: {\n timeoutMs: 120_000,\n maxIterations: 10,\n maxToolCalls: 40,\n maxTokens: 60_000,\n maxCostUsd: 0.25,\n },\n capability: {\n phase: 'meta',\n summary: 'Single-shot tech stack validator: checks npm for latest versions, rejects dead/obsolete packages, enforces modern alternatives.',\n keywords: [\n 'tech stack',\n 'version',\n 'package',\n 'library',\n 'framework',\n 'dependency',\n 'install',\n 'upgrade',\n 'latest',\n 'npm',\n 'pnpm add',\n 'outdated',\n 'obsolete',\n 'deprecated',\n 'what version',\n 'which package',\n 'check version',\n 'verify version',\n 'is this current',\n ],\n },\n },\n];\n","/**\n * Agent catalog aggregator.\n *\n * Collects every phase's `AgentDefinition[]` into:\n * - `ALL_AGENT_DEFINITIONS` — flat list, catalog order (phase 1 → 9)\n * - `AGENT_CATALOG` — keyed by role for O(1) lookup\n * - `AGENTS_BY_PHASE` — grouped for statusline / dispatcher tie-breaks\n *\n * `fleet.ts` derives `FLEET_ROSTER` + `FLEET_ROSTER_BUDGETS` from this, and the\n * dispatcher routes free-form tasks against `capability` metadata here.\n */\nimport type { AgentDefinition, AgentPhase } from './types.js';\nimport { DISCOVERY_AGENTS } from './phase1-discovery.js';\nimport { PLANNING_AGENTS } from './phase2-planning.js';\nimport { BUILD_AGENTS } from './phase3-build.js';\nimport { VERIFY_AGENTS } from './phase4-verify.js';\nimport { REVIEW_AGENTS } from './phase5-review.js';\nimport { DOMAIN_AGENTS } from './phase6-domain.js';\nimport { KNOWLEDGE_AGENTS } from './phase7-knowledge.js';\nimport { DELIVERY_AGENTS } from './phase8-delivery.js';\nimport { META_AGENTS } from './phase9-meta.js';\n\nexport * from './types.js';\nexport {\n DISCOVERY_AGENTS,\n PLANNING_AGENTS,\n BUILD_AGENTS,\n VERIFY_AGENTS,\n REVIEW_AGENTS,\n DOMAIN_AGENTS,\n KNOWLEDGE_AGENTS,\n DELIVERY_AGENTS,\n META_AGENTS,\n};\n\n/** Every catalog agent, in phase order. */\nexport const ALL_AGENT_DEFINITIONS: AgentDefinition[] = [\n ...DISCOVERY_AGENTS,\n ...PLANNING_AGENTS,\n ...BUILD_AGENTS,\n ...VERIFY_AGENTS,\n ...REVIEW_AGENTS,\n ...DOMAIN_AGENTS,\n ...KNOWLEDGE_AGENTS,\n ...DELIVERY_AGENTS,\n ...META_AGENTS,\n];\n\n/** Phase → its agents, for grouped display and dispatcher fallbacks. */\nexport const AGENTS_BY_PHASE: Record<AgentPhase, AgentDefinition[]> = {\n discovery: DISCOVERY_AGENTS,\n planning: PLANNING_AGENTS,\n build: BUILD_AGENTS,\n verify: VERIFY_AGENTS,\n review: REVIEW_AGENTS,\n domain: DOMAIN_AGENTS,\n knowledge: KNOWLEDGE_AGENTS,\n delivery: DELIVERY_AGENTS,\n meta: META_AGENTS,\n};\n\n/**\n * Role → definition. Built once at module load. Throws on a duplicate role so\n * a copy-paste collision fails loudly at startup instead of silently shadowing.\n */\nexport const AGENT_CATALOG: Record<string, AgentDefinition> = (() => {\n const map: Record<string, AgentDefinition> = {};\n for (const def of ALL_AGENT_DEFINITIONS) {\n const role = def.config.role;\n if (!role) {\n throw new Error(`Agent \"${def.config.name}\" is missing a role`);\n }\n if (map[role]) {\n throw new Error(`Duplicate agent role in catalog: \"${role}\"`);\n }\n map[role] = def;\n }\n return map;\n})();\n\n/** Role lookup helper. Returns undefined for unknown roles. */\nexport function getAgentDefinition(role: string): AgentDefinition | undefined {\n return AGENT_CATALOG[role];\n}\n","/**\n * Smart agent dispatcher.\n *\n * Routes a free-form task description to the best agent in the catalog using a\n * two-stage strategy:\n *\n * 1. Heuristic — keyword/phrase scoring against each agent's `capability`\n * metadata. Deterministic, instant, no provider call. Multi-word phrases\n * score higher than single words (they're more specific signals).\n *\n * 2. LLM fallback — when the heuristic is ambiguous (confidence below the\n * threshold, or no keyword hit at all) an injected `classifier` resolves\n * the tie. The classifier is provider-agnostic: callers wire it to any\n * `complete(prompt) => text` function via `makeLLMClassifier`, so core\n * stays free of provider dependencies and the path is unit-testable.\n *\n * If neither stage yields a confident pick, the dispatcher falls back to the\n * `executor` generalist rather than failing.\n */\nimport { AGENT_CATALOG, ALL_AGENT_DEFINITIONS, type AgentDefinition } from './agents/index.js';\nimport { safeParse } from '../utils/safe-json.js';\n\n/** Default agent used when nothing else matches — the generalist builder. */\nexport const DEFAULT_DISPATCH_ROLE = 'executor';\n\n/** Fallback agent definition for catalog lookup failures. */\nconst FALLBACK_DEFINITION: AgentDefinition = {\n config: { role: 'unknown', name: 'Unknown Agent' },\n budget: {},\n capability: { phase: 'meta', summary: '', keywords: [] },\n};\n\nexport interface DispatchCandidate {\n role: string;\n name: string;\n score: number;\n /** Capability keywords that matched the task text. */\n matched: string[];\n}\n\nexport type DispatchMethod = 'heuristic' | 'llm' | 'fallback';\n\nexport interface DispatchResult {\n role: string;\n definition: AgentDefinition;\n /** 0..1 — heuristic margin, or 1 when an LLM made a definite choice. */\n confidence: number;\n method: DispatchMethod;\n /** Human-readable explanation of why this agent was chosen. */\n reason: string;\n /** Runner-up candidates (top heuristic scorers), best-first. */\n alternatives: DispatchCandidate[];\n}\n\n/**\n * Provider-agnostic classifier seam. Given the task and the candidate agents\n * (role + summary), return the chosen role (and optional reason), or null to\n * decline. Wire via `makeLLMClassifier`.\n */\nexport type DispatchClassifier = (\n task: string,\n candidates: { role: string; name: string; summary: string }[],\n) => Promise<{ role: string; reason?: string | undefined } | null>;\n\nexport interface DispatchOptions {\n /** Optional LLM fallback for ambiguous tasks. */\n classifier?: DispatchClassifier | undefined;\n /** Heuristic confidence below this triggers the classifier. Default 0.4. */\n confidenceThreshold?: number | undefined;\n /** How many top candidates to offer the classifier. Default 6. */\n maxCandidates?: number | undefined;\n /** Override the catalog (testing). Defaults to the full `AGENT_CATALOG`. */\n catalog?: Record<string, AgentDefinition> | undefined;\n}\n\nfunction normalize(text: string): string {\n return ` ${text\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, ' ')\n .trim()} `;\n}\n\n/**\n * Score every agent against the task. A keyword hit adds 1 point; a multi-word\n * keyword phrase adds points equal to its word count (more specific = stronger\n * signal). Returns candidates sorted best-first, zero-score agents dropped.\n */\nexport function scoreAgents(\n task: string,\n catalog: Record<string, AgentDefinition> = AGENT_CATALOG,\n): DispatchCandidate[] {\n // Tokenize once — O(task words) — then do O(1) set lookups per keyword\n const haySet = new Set(normalize(task).split(/\\s+/).filter(Boolean));\n const out: DispatchCandidate[] = [];\n for (const def of Object.values(catalog)) {\n if (!def?.config?.role) continue;\n let score = 0;\n const matched: string[] = [];\n for (const kw of def.capability.keywords) {\n const needleWords = normalize(kw).split(/\\s+/).filter(Boolean);\n // Check if all words in the keyword phrase are present in the task\n const allPresent = needleWords.every((w) => haySet.has(w));\n if (allPresent) {\n score += needleWords.length;\n matched.push(kw);\n }\n }\n if (score > 0) {\n out.push({ role: def.config.role, name: def.config.name, score, matched });\n }\n }\n out.sort((a, b) => b.score - a.score);\n return out;\n}\n\n/**\n * Heuristic confidence from the score distribution: the margin between the top\n * candidate and the runner-up, scaled by the top score's strength. A clear\n * winner (high top, low second) approaches 1; a near-tie approaches 0.\n */\nfunction heuristicConfidence(candidates: DispatchCandidate[]): number {\n if (candidates.length === 0) return 0;\n const top = candidates[0]?.score ?? 0;\n const second = candidates[1]?.score ?? 0;\n // Strength factor: a single weak match (score 1) shouldn't read as confident.\n const strength = Math.min(1, top / 3);\n const margin = (top - second + 1) / (top + 1);\n return Math.min(1, strength * margin);\n}\n\n/**\n * Route a task to the best agent. Async because the LLM fallback may run; the\n * pure-heuristic path resolves without awaiting anything.\n */\nexport async function dispatchAgent(\n task: string,\n opts: DispatchOptions = {},\n): Promise<DispatchResult> {\n const catalog = opts.catalog ?? AGENT_CATALOG;\n const threshold = opts.confidenceThreshold ?? 0.4;\n const maxCandidates = opts.maxCandidates ?? 6;\n\n const candidates = scoreAgents(task, catalog);\n const confidence = heuristicConfidence(candidates);\n const top = candidates[0];\n\n // Confident heuristic pick — done, no provider call.\n if (top && confidence >= threshold) {\n return {\n role: top.role,\n definition: catalog[top.role] ?? FALLBACK_DEFINITION,\n confidence,\n method: 'heuristic',\n reason: `Matched keywords: ${top.matched.slice(0, 4).join(', ')}`,\n alternatives: candidates.slice(1, maxCandidates),\n };\n }\n\n // Ambiguous or no signal — ask the classifier if one is wired.\n if (opts.classifier) {\n // Offer the classifier the top heuristic candidates; if there were none,\n // offer the whole catalog so it can still choose.\n const pool = (\n candidates.length > 0\n ? candidates.slice(0, maxCandidates).map((c) => catalog[c.role] ?? FALLBACK_DEFINITION)\n : ALL_AGENT_DEFINITIONS\n ).map((d) => ({\n role: d.config.role as string,\n name: d.config.name,\n summary: d.capability.summary,\n }));\n try {\n const choice = await opts.classifier(task, pool);\n if (choice && catalog[choice.role]) {\n return {\n role: choice.role,\n definition: catalog[choice.role] ?? FALLBACK_DEFINITION,\n confidence: 1,\n method: 'llm',\n reason: choice.reason ?? 'Selected by LLM classifier',\n alternatives: candidates.slice(0, maxCandidates).filter((c) => c.role !== choice.role),\n };\n }\n } catch {\n // Classifier failure must not break dispatch — fall through to fallback.\n }\n }\n\n // Best heuristic guess if we have one, else the generalist.\n if (top) {\n return {\n role: top.role,\n definition: catalog[top.role] ?? FALLBACK_DEFINITION,\n confidence,\n method: 'heuristic',\n reason: `Weak match (${top.matched.slice(0, 3).join(', ') || 'low signal'})`,\n alternatives: candidates.slice(1, maxCandidates),\n };\n }\n const fallbackRole = catalog[DEFAULT_DISPATCH_ROLE]\n ? DEFAULT_DISPATCH_ROLE\n : (Object.keys(catalog)[0] ?? DEFAULT_DISPATCH_ROLE);\n return {\n role: fallbackRole,\n definition: catalog[fallbackRole] ?? FALLBACK_DEFINITION,\n confidence: 0,\n method: 'fallback',\n reason: 'No keyword signal; defaulting to the generalist Executor',\n alternatives: [],\n };\n}\n\n/**\n * Build a `DispatchClassifier` from a minimal `complete(prompt) => text`\n * function. The caller supplies the provider call; this owns the prompt and\n * the parsing. Keeps `dispatcher` free of any provider import.\n */\nexport function makeLLMClassifier(\n complete: (prompt: string) => Promise<string>,\n): DispatchClassifier {\n return async (task, candidates) => {\n const list = candidates.map((c, i) => `${i + 1}. ${c.role} — ${c.summary}`).join('\\n');\n const prompt = `You are an agent router. Pick the single best agent for the task.\n\nTask:\n${task}\n\nAgents:\n${list}\n\nReply with ONLY a compact JSON object: {\"role\":\"<one role id from the list>\",\"reason\":\"<short why>\"}.\nDo not add prose, markdown, or code fences.`;\n const raw = (await complete(prompt)).trim();\n // Tolerate accidental code fences / surrounding text — extract first {...}.\n const match = raw.match(/\\{[\\s\\S]*\\}/);\n if (!match) return null;\n const parsed = safeParse<{ role?: unknown | undefined; reason?: unknown | undefined }>(\n match[0],\n );\n if (!parsed.ok || !parsed.value || typeof parsed.value.role !== 'string') return null;\n const role = parsed.value.role.trim();\n const valid = candidates.some((c) => c.role === role);\n if (!valid) return null;\n return {\n role,\n reason: typeof parsed.value.reason === 'string' ? parsed.value.reason : undefined,\n };\n };\n}\n","import type { ContentBlock, TextBlock } from './blocks.js';\nimport type { ErrorCode } from './errors.js';\nimport { WrongStackError, ERROR_CODES } from './errors.js';\nimport type { Message } from './messages.js';\nimport type { Tool } from './tool.js';\nimport { truncate } from '../utils/string.js';\n\n/**\n * Token usage for a single provider call, normalized across providers.\n *\n * Disjoint semantics: the four fields never overlap. `input` is the count\n * of FRESH input tokens (billed at the full input rate); `cacheRead` and\n * `cacheWrite` are separate cached subsets each priced at their own rate.\n * The total context the model loaded for this turn is\n * `input + (cacheRead ?? 0) + (cacheWrite ?? 0)`.\n *\n * Provider quirks normalized at the adapter layer:\n * - Anthropic: returns `input_tokens` already disjoint from cache fields.\n * - OpenAI / OpenAI-compatible: `prompt_tokens` is the TOTAL including\n * cached portion; the adapter subtracts `cached_tokens` to stay disjoint.\n * - Google: `promptTokenCount` likewise includes cache; adapter subtracts\n * `cachedContentTokenCount`.\n *\n * Cost math and the context-fullness chip both depend on the disjoint\n * invariant — a TOTAL `input` plus a separate `cacheRead` count would bill\n * cached tokens twice and skew cache-hit-ratio reporting.\n */\nexport interface Usage {\n input: number;\n output: number;\n cacheRead?: number | undefined;\n cacheWrite?: number | undefined;\n}\n\nexport interface Capabilities {\n tools: boolean;\n parallelTools: boolean;\n vision: boolean;\n streaming: boolean;\n promptCache: boolean;\n systemPrompt: boolean;\n jsonMode: boolean;\n reasoning: boolean;\n maxContext: number;\n cacheControl: 'native' | 'auto' | 'none';\n}\n\nexport interface Request {\n model: string;\n system?: TextBlock[] | undefined;\n messages: Message[];\n tools?: Tool[] | undefined;\n maxTokens: number;\n temperature?: number | undefined;\n topP?: number | undefined;\n stopSequences?: string[] | undefined;\n toolChoice?: 'auto' | 'required' | 'none' | { type: 'tool' | undefined; name: string };\n}\n\nexport type StopReason = 'end_turn' | 'tool_use' | 'max_tokens' | 'stop_sequence' | 'refusal';\n\nexport interface Response {\n content: ContentBlock[];\n stopReason: StopReason;\n usage: Usage;\n model: string;\n}\n\nexport type StreamEvent =\n | { type: 'message_start'; model: string }\n | {\n type: 'content_block_start';\n kind: 'text' | 'tool_use' | 'thinking';\n id?: string | undefined;\n name?: string | undefined;\n }\n | { type: 'content_block_stop'; index: number }\n | { type: 'text_delta'; text: string }\n | { type: 'tool_use_start'; id: string; name: string }\n | { type: 'tool_use_input_delta'; id: string; partial: string }\n | { type: 'tool_use_stop'; id: string; input: unknown; providerMeta?: Record<string, unknown> }\n | { type: 'thinking_start'; providerMeta?: Record<string, unknown> }\n | { type: 'thinking_delta'; text: string }\n | { type: 'thinking_signature'; signature: string }\n | { type: 'thinking_stop' }\n | { type: 'message_stop'; stopReason: StopReason; usage: Usage };\n\nexport interface Provider {\n readonly id: string;\n readonly capabilities: Capabilities;\n /** Canonical streaming entry point. `complete()` defaults to a wrapper that\n * aggregates this stream — providers may override for non-streaming wires. */\n stream(req: Request, opts: { signal: AbortSignal }): AsyncIterable<StreamEvent>;\n complete(req: Request, opts: { signal: AbortSignal }): Promise<Response>;\n}\n\n/**\n * Structured body parsed from a provider's HTTP error response. Populated\n * best-effort: providers return JSON shaped differently (Anthropic uses\n * `{error: {type, message}}`, OpenAI uses `{error: {message, code}}`,\n * Google uses `{error: {status, message}}`), so the fields here are the\n * intersection that's usable for rendering and routing.\n */\nexport interface ProviderErrorBody {\n /** Provider-specific kind, e.g. \"overloaded_error\", \"rate_limit_error\", \"invalid_request_error\". */\n type?: string | undefined;\n /** Human-readable explanation from the provider. */\n message?: string | undefined;\n /** Provider request id, when present in the body or headers. */\n requestId?: string | undefined;\n /** Parsed Retry-After header (or equivalent body hint) in milliseconds. */\n retryAfterMs?: number | undefined;\n /** The raw response body (truncated to ~2 KB), kept for debugging. */\n raw?: string | undefined;\n /** True when `raw` was truncated; check `rawLength` for the original size. */\n truncated?: boolean | undefined;\n /** Original length of the response body in bytes, when `truncated` is true. */\n rawLength?: number | undefined;\n}\n\nexport class ProviderError extends WrongStackError {\n public readonly status: number;\n public readonly retryable: boolean;\n public readonly providerId: string;\n public readonly body?: ProviderErrorBody | undefined;\n\n constructor(\n message: string,\n status: number,\n retryable: boolean,\n providerId: string,\n opts: { body?: ProviderErrorBody | undefined; cause?: unknown | undefined } = {},\n ) {\n super({\n message,\n code: providerStatusToCode(status, opts.body?.type),\n subsystem: 'provider',\n severity: status >= 500 ? 'error' : 'warning',\n recoverable: retryable,\n context: { providerId, status },\n cause: opts.cause,\n });\n this.name = 'ProviderError';\n this.status = status;\n this.retryable = retryable;\n this.providerId = providerId;\n this.body = opts.body;\n }\n\n /**\n * Render a one-line, user-facing description. Designed for the CLI/TUI\n * status line and the agent's retry warning. Avoids dumping raw JSON\n * (which is what users see today when a 529 lands and the log message\n * includes the full `{\"type\":\"error\",...}` body).\n *\n * Examples:\n * \"minimax-coding-plan overloaded (529): High traffic detected. Upgrade for highspeed model. [req 06534785201de9c0…]\"\n * \"openai rate limited (429): Retry after 12s\"\n * \"anthropic invalid request (400): messages.0.role must be one of 'user'|'assistant'\"\n * \"groq HTTP 500 (server error)\"\n */\n override describe(): string {\n const kind = describeStatus(this.status, this.body?.type);\n const head = `${this.providerId} ${kind}`;\n const detail = this.body?.message?.trim();\n const reqId = this.body?.requestId\n ? ` [req ${this.body.requestId.slice(0, 16)}${this.body.requestId.length > 16 ? '…' : ''}]`\n : '';\n if (detail && detail.length > 0) {\n return `${head}: ${truncate(detail, 240)}${reqId}`;\n }\n return `${head}${reqId}`;\n }\n}\n\nfunction describeStatus(status: number, type?: string): string {\n if (status === 0) return 'network error';\n if (type === 'overloaded_error' || status === 529) return `overloaded (${status})`;\n if (type === 'rate_limit_error' || status === 429) return `rate limited (${status})`;\n if (type === 'authentication_error' || status === 401) return `auth failed (${status})`;\n if (type === 'permission_error' || status === 403) return `forbidden (${status})`;\n if (type === 'not_found_error' || status === 404) return `not found (${status})`;\n if (type === 'invalid_request_error' || status === 400) return `invalid request (${status})`;\n if (status === 408) return `timeout (${status})`;\n if (status >= 500 && status < 600) return `HTTP ${status} (server error)`;\n if (type) return `${type} (${status})`;\n return `HTTP ${status}`;\n}\n\n/**\n * Thrown when the provider stream stops delivering data mid-response.\n * This is distinct from a network error (TCP reset, DNS failure) — the\n * connection is established and the response started, but chunks stopped\n * arriving before the stream completed.\n *\n * Status 599 is used as a sentinel to distinguish stream hangs from\n * regular HTTP errors while still flowing through ProviderError-based\n * retry and fallback infrastructure.\n */\nexport class StreamHangError extends ProviderError {\n /** Name of the provider that hung, e.g. \"zai\", \"anthropic\". */\n public readonly hungProviderId: string;\n /** Model that was being called when the hang occurred. */\n public readonly hungModel: string;\n /** How long (ms) we waited for the next chunk before declaring a hang. */\n public readonly hangTimeoutMs: number;\n /** How many bytes were received before the hang. */\n public readonly bytesReceived: number;\n /** Elapsed time (ms) from the start of the stream until the hang. */\n public readonly elapsedMs: number;\n\n constructor(opts: {\n providerId: string;\n model: string;\n hangTimeoutMs: number;\n bytesReceived: number;\n elapsedMs: number;\n cause?: unknown | undefined;\n }) {\n super(\n `Stream hang: ${opts.providerId}/${opts.model} — no data for ${opts.hangTimeoutMs}ms after ${opts.bytesReceived} bytes (${opts.elapsedMs}ms elapsed)`,\n 599,\n true, // always retryable\n opts.providerId,\n {\n body: {\n message: `Stream stalled after ${opts.elapsedMs}ms, ${opts.bytesReceived} bytes received`,\n },\n cause: opts.cause,\n },\n );\n this.name = 'StreamHangError';\n this.hungProviderId = opts.providerId;\n this.hungModel = opts.model;\n this.hangTimeoutMs = opts.hangTimeoutMs;\n this.bytesReceived = opts.bytesReceived;\n this.elapsedMs = opts.elapsedMs;\n }\n}\n\nfunction providerStatusToCode(status: number, type?: string): ErrorCode {\n if (status === 0) return ERROR_CODES.PROVIDER_NETWORK_ERROR;\n if (type === 'rate_limit_error' || status === 429) return ERROR_CODES.PROVIDER_RATE_LIMITED;\n if (type === 'authentication_error' || status === 401) return ERROR_CODES.PROVIDER_AUTH_FAILED;\n if (type === 'overloaded_error' || status === 529) return ERROR_CODES.PROVIDER_OVERLOADED;\n if (type === 'invalid_request_error' || status === 400) return ERROR_CODES.PROVIDER_INVALID_REQUEST;\n if (status === 408) return ERROR_CODES.PROVIDER_NETWORK_ERROR;\n if (status >= 500) return ERROR_CODES.PROVIDER_SERVER_ERROR;\n return ERROR_CODES.PROVIDER_INVALID_REQUEST;\n}\n","import type { SubagentError, SubagentErrorKind } from '../../types/multi-agent.js';\nimport { ProviderError } from '../../types/provider.js';\nimport { AgentError } from '../../types/errors.js';\nimport { BudgetExceededError } from '../subagent-budget.js';\nimport { toErrorMessage } from '../../utils/error.js';\n\n/**\n * Map any raw exception thrown out of a subagent's runner into a\n * structured `SubagentError`. This is the single point where the\n * coordinator decides \"what kind of failure was that\" — so callers\n * (delegate tool output, /agents UI, retry policies) branch on\n * `kind` instead of substring-matching `error.message`.\n *\n * Exported because tests and CLI surfaces want to assert on the\n * classification without instantiating a coordinator.\n */\nexport function classifySubagentError(\n err: unknown,\n hints: { parentAborted?: boolean | undefined } = {},\n): SubagentError {\n // Unwrap AgentError wrappers — the runner wraps non-AgentError\n // throwables (ProviderError, TypeError, etc.) in AgentError so the\n // coordinator's try/catch catches a consistent type. Recurse into the\n // inner cause so classification sees the original error kind.\n if (err instanceof AgentError && err.cause) {\n return classifySubagentError(err.cause, hints);\n }\n\n const cause = err instanceof Error\n ? { name: err.name, message: err.message, stack: err.stack }\n : undefined;\n\n if (err instanceof ProviderError) {\n const baseMessage = err.describe();\n return providerErrorToSubagentError(err, baseMessage, cause);\n }\n\n const baseMessage = toErrorMessage(err);\n\n if (err instanceof BudgetExceededError) {\n const map: Record<BudgetExceededError['kind'], SubagentErrorKind> = {\n iterations: 'budget_iterations',\n tool_calls: 'budget_tool_calls',\n tokens: 'budget_tokens',\n cost: 'budget_cost',\n timeout: 'budget_timeout',\n idle_timeout: 'budget_timeout',\n };\n return {\n kind: map[err.kind],\n message: baseMessage,\n retryable: false,\n cause,\n };\n }\n\n if (hints.parentAborted) {\n return { kind: 'aborted_by_parent', message: baseMessage, retryable: false, cause };\n }\n\n const lower = baseMessage.toLowerCase();\n if (/agent aborted$/i.test(baseMessage)) {\n return { kind: 'aborted_by_parent', message: baseMessage, retryable: false, cause };\n }\n if (/agent exhausted iteration limit$/i.test(baseMessage)) {\n return { kind: 'budget_iterations', message: baseMessage, retryable: false, cause };\n }\n if (/empty response/i.test(baseMessage)) {\n return { kind: 'empty_response', message: baseMessage, retryable: false, cause };\n }\n if (/^tool failed: /i.test(baseMessage)) {\n return { kind: 'tool_failed', message: baseMessage, retryable: false, cause };\n }\n if (lower.includes('bridge transport') || /bridge.*(closed|disconnect)/i.test(baseMessage)) {\n return { kind: 'bridge_failed', message: baseMessage, retryable: false, cause };\n }\n if (/context length|max.*tokens?.*exceeded|prompt is too long/i.test(baseMessage)) {\n return { kind: 'context_overflow', message: baseMessage, retryable: false, cause };\n }\n\n return { kind: 'unknown', message: baseMessage, retryable: false, cause };\n}\n\nfunction providerErrorToSubagentError(\n err: ProviderError,\n message: string,\n cause: SubagentError['cause'],\n): SubagentError {\n const status = err.status;\n if (status === 429 || err.body?.type === 'rate_limit_error') {\n return { kind: 'provider_rate_limit', message, retryable: true, backoffMs: 5_000, cause };\n }\n if (status === 401 || status === 403 || err.body?.type === 'authentication_error') {\n return { kind: 'provider_auth', message, retryable: false, cause };\n }\n if (status === 408 || status === 0) {\n return { kind: 'provider_timeout', message, retryable: true, cause };\n }\n if (status >= 500 && status < 600) {\n return { kind: 'provider_5xx', message, retryable: true, backoffMs: 3_000, cause };\n }\n return { kind: 'unknown', message, retryable: err.retryable, cause };\n}\n","/**\r\n * Pre-built subagent role configurations for the WrongStack fleet.\r\n * These can be passed to `MultiAgentHost.spawn()` or used as templates\r\n * for the director's roster.\r\n */\r\nimport type { SubagentConfig } from '../types/multi-agent.js';\r\nimport { ALL_AGENT_DEFINITIONS } from './agents/index.js';\r\n\r\n/**\r\n * Audit Log Agent — analyzes session logs, event streams, and traces.\r\n * Use for: post-mortems, trend analysis, operational insights.\r\n */\r\nexport const AUDIT_LOG_AGENT: SubagentConfig = {\r\n id: 'audit-log',\r\n name: 'Audit Log',\r\n role: 'audit-log',\r\n prompt: `You are the Audit Log agent. Your job is to analyze structured JSONL\r\nsession logs and produce actionable markdown reports.\r\n\r\nScope:\r\n- Parse session logs (iteration counts, tool calls, errors, usage)\r\n- Detect repeated failure patterns across multiple runs\r\n- Identify tool usage anomalies (over-use, failures, unexpected chains)\r\n- Track token consumption trends\r\n- Generate structured audit reports with severity ratings\r\n\r\nInput format you accept:\r\n{ \"task\": \"analyze | report | trends\", \"sessionPath\": \"<path>\", \"focus\": \"errors | tools | usage | all\" }\r\n\r\nOutput: Markdown audit report with sections:\r\n- ## Summary (totals, error rate)\r\n- ## Top Errors (count + context)\r\n- ## Tool Usage (table with calls, failures, avg duration)\r\n- ## Anomalies (pattern → severity)\r\n\r\nWorking rules:\r\n- Never fabricate numbers — read the actual logs first\r\n- Always include file:line references for errors\r\n- If sessionPath is missing, ask the director to provide it\r\n- Report confidence level: high (>90% accuracy), medium, low`,\r\n\r\n // No hardcoded budgets — the orchestrator (delegate tool or\r\n // spawn_subagent) decides per-task how much room a subagent gets.\r\n // A monorepo audit needs hours; a single-file lint check needs\r\n // seconds. Pinning a number here forces the orchestrator to fight\r\n // the role's default instead of just asking for what it needs.\r\n};\r\n\r\n/**\r\n * Bug Hunter Agent — systematic bug and code smell detection.\r\n * Use for: pre-refactoring health checks, code review, regression prevention.\r\n */\r\nexport const BUG_HUNTER_AGENT: SubagentConfig = {\r\n id: 'bug-hunter',\r\n name: 'Bug Hunter',\r\n role: 'bug-hunter',\r\n prompt: `You are the Bug Hunter agent. Your job is to systematically scan\r\nsource code for bugs, anti-patterns, and code smells using pattern matching\r\nand heuristics. Output a prioritized hit list with file:line references.\r\n\r\nScope:\r\n- Detect common bug patterns (uncaught errors, resource leaks, race conditions)\r\n- Identify anti-patterns (callback hell, God objects, circular deps)\r\n- Find TypeScript-specific issues (unsafe any, missing null checks, branded types)\r\n- Flag security-sensitive constructs (eval, innerHTML, hardcoded secrets)\r\n- Rank findings: critical > high > medium > low\r\n\r\nInput format you accept:\r\n{ \"task\": \"scan | hunt | check\", \"paths\": [\"src/**/*.ts\"], \"focus\": \"bugs | patterns | security | all\", \"severityThreshold\": \"medium\" }\r\n\r\nOutput: Markdown bug hunt report:\r\n- ## Critical (must fix first)\r\n- ## High (should fix)\r\n- ## Medium\r\n- ## Low (consider)\r\nEach entry: **[TYPE]** \\`file:line\\` — description + suggested fix\r\n\r\nBug pattern reference you know:\r\n| Pattern | Regex hint | Severity |\r\n|---------|------------|----------|\r\n| Uncaught promise | /.then\\\\(.*\\\\)/ without catch | high |\r\n| Event leak | on\\\\( without off/removeListener | high |\r\n| Hardcoded secret | [a-zA-Z0-9/_-]{20,} in config files | critical |\r\n| unsafe any | : any\\\\b or <any> | medium |\r\n| innerHTML | innerHTML\\\\s*= | high |\r\n\r\nWorking rules:\r\n- Never scan node_modules — it's noise\r\n- Always include file:line for every finding\r\n- If >30% of findings are false positives, note the confidence level\r\n- Ask director for clarification if paths are ambiguous`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * Refactor Planner Agent — structured refactoring planning.\r\n * Use for: large rewrites, technical debt reduction, architecture improvements.\r\n */\r\nexport const REFACTOR_PLANNER_AGENT: SubagentConfig = {\r\n id: 'refactor-planner',\r\n name: 'Refactor Planner',\r\n role: 'refactor-planner',\r\n prompt: `You are the Refactor Planner agent. Your job is to analyze code\r\nstructure and produce a concrete, phased refactoring plan with risk\r\nassessment, dependency ordering, and rollback strategy.\r\n\r\nScope:\r\n- Map module-level dependencies (import graph)\r\n- Identify coupling hotspots (high fan-in/out modules)\r\n- Assess refactoring risk by complexity and test coverage\r\n- Generate phased plans with checkpoint milestones\r\n- Produce diff-friendly task lists (one task = one concern)\r\n\r\nInput format you accept:\r\n{ \"task\": \"plan | assess | roadmap\", \"target\": \"src/core\", \"constraint\": \"no-breaking-changes | minimal-downtime | full-rewrite\", \"focus\": \"architecture | performance | maintainability\" }\r\n\r\nOutput: Markdown refactor plan:\r\n- ## Phase 1: Low Risk / High Payoff (do first)\r\n Table: | # | Task | Module | Risk | Est. Time |\r\n- ## Phase 2: Medium Risk\r\n- ## Phase 3: High Risk (requires full regression)\r\n- ## Dependency Graph (abbreviated ASCII)\r\n- ## Rollback Strategy\r\n- ## Exit Criteria (checkbox list)\r\n\r\nRisk scoring criteria:\r\n| Factor | Low | Medium | High |\r\n|--------|-----|--------|------|\r\n| Cyclomatic complexity | <10 | 10-20 | >20 |\r\n| Test coverage | >80% | 50-80% | <50% |\r\n| Fan-out (imports) | <5 | 5-15 | >15 |\r\n\r\nWorking rules:\r\n- Always include rollback strategy — every refactor can fail\r\n- Merge tasks that take <1h into a single phase\r\n- Respect team constraints (reviewer availability, parallelization)\r\n- Never plan without analyzing the actual code first`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * Security Scanner Agent — vulnerability and secret detection.\r\n * Use for: CI checks, pre-release audits, dependency vulnerability scanning.\r\n */\r\nexport const SECURITY_SCANNER_AGENT: SubagentConfig = {\r\n id: 'security-scanner',\r\n name: 'Security Scanner',\r\n role: 'security-scanner',\r\n prompt: `You are the Security Scanner agent. Your job is to scan code,\r\nconfigs, and dependencies for security issues from hardcoded secrets to\r\nsupply chain risks.\r\n\r\nScope:\r\n- Detect hardcoded secrets: API keys, tokens, passwords, private keys\r\n- Find injection vectors: eval, innerHTML, SQL concat, shell injection\r\n- Identify insecure patterns: weak crypto, hardcoded IVs, disabled TLS\r\n- Scan dependencies for known CVEs (via npm/pnpm audit)\r\n- Flag supply chain risks: postinstall hooks, unverified scripts, .npmrc\r\n\r\nInput format you accept:\r\n{ \"task\": \"scan | audit | secrets | dependencies\", \"paths\": [\"src\", \"config\"], \"depth\": \"quick | normal | deep\" }\r\n\r\nOutput: Markdown security report:\r\n- ## CRITICAL: Secrets Found (with code snippets)\r\n- ## HIGH: Injection Vectors\r\n- ## MEDIUM: Insecure Patterns\r\n- ## Dependency Issues (CVE list)\r\n- ## Summary table (severity → count)\r\n- ## Remediation Checklist (with checkboxes)\r\n\r\nSecret patterns you detect:\r\n| Pattern | Example | Severity |\r\n|---------|---------|----------|\r\n| AWS Access Key | AKIAIOSFODNN7EXAMPLE | critical |\r\n| AWS Secret Key | [a-zA-Z0-9/+=]{40} base64 | critical |\r\n| GitHub Token | ghp_[a-zA-Z0-9]{36} | critical |\r\n| Private Key PEM | -----BEGIN.*PRIVATE KEY----- | critical |\r\n| JWT | eyJ[a-zA-Z0-9_-]+ | high |\r\n\r\nInjection patterns:\r\n| Construct | Safe alternative |\r\n|-----------|-----------------|\r\n| eval(str) | new Function() or parse |\r\n| innerHTML = x | textContent or sanitize |\r\n| exec(\\`cmd \\${x}\\`) | execFile with args array |\r\n\r\nWorking rules:\r\n- Never scan node_modules — use npm audit instead\r\n- Always provide remediation steps, not just findings\r\n- Verify regex-based secrets before flagging (false positive risk)\r\n- When in doubt, flag as medium rather than ignoring potential issues`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * Critic Agent — evaluates code quality, architecture decisions, and\r\n * refactoring plans against project conventions and engineering standards.\r\n * Use for: real-time evaluation of bug reports, refactor plans, and\r\n * architectural proposals during collaborative debugging sessions.\r\n */\r\nexport const CRITIC_AGENT: SubagentConfig = {\r\n id: 'critic',\r\n name: 'Critic',\r\n role: 'critic',\r\n prompt: `You are the Critic agent. Your job is to evaluate code quality,\r\narchitectural decisions, and proposed changes against project conventions,\r\nengineering standards, and known quality gates. You do not write code —\r\nyou judge it.\r\n\r\nScope:\r\n- Evaluate bug severity and fix quality from Bug Hunter reports\r\n- Score refactoring plans from Refactor Planner (risk, completeness, trade-offs)\r\n- Flag gaps in test coverage, error handling, and edge case coverage\r\n- Assess whether a proposed change aligns with existing project patterns\r\n- Detect over-engineering or under-engineering relative to the problem scope\r\n\r\nInput format you accept:\r\n{ \"task\": \"evaluate | score | review\", \"subject\": \"bug_report | refactor_plan | diff\", \"focus\": \"correctness | maintainability | risk | all\" }\r\n\r\nOutput: Markdown critic report:\r\n- ## Overall Score (0-10 with rationale)\r\n- ## Strengths (what's solid)\r\n- ## Weaknesses (what needs work)\r\n- ## Specific Concerns (with file:line when applicable)\r\n- ## Verdict: **Approve / Needs Revision / Reject**\r\n\r\nWorking rules:\r\n- Be specific — \"looks fine\" is not a review. Cite concrete evidence.\r\n- When scoring, explain the delta from a perfect score.\r\n- If you have no basis to evaluate a concern, say so rather than speculating.\r\n- Prioritise correctness over style; correctness issues block approval.\r\n- Score thresholds: ≥7 = Approve, 4-6 = Needs Revision, <4 = Reject`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * All agents in a map for easy lookup by role. The four legacy pre-built\r\n * agents plus the phase 1-9 catalog (`ALL_AGENT_DEFINITIONS`). Catalog roles\r\n * are guaranteed collision-free by the catalog builder; none overlap the\r\n * legacy four.\r\n */\r\nexport const FLEET_ROSTER: Record<string, SubagentConfig> = {\r\n 'audit-log': AUDIT_LOG_AGENT,\r\n 'bug-hunter': BUG_HUNTER_AGENT,\r\n 'refactor-planner': REFACTOR_PLANNER_AGENT,\r\n 'security-scanner': SECURITY_SCANNER_AGENT,\r\n 'critic': CRITIC_AGENT,\r\n ...Object.fromEntries(\r\n ALL_AGENT_DEFINITIONS.map((d) => [d.config.role as string, d.config] as const),\r\n ),\r\n};\r\n\r\n// ---------------------------------------------------------------------------\r\n// Default per-role budgets.\r\n//\r\n// MASSIVELY RAISED from earlier values. User requested x5–x10 multiplier\r\n// to prevent any timeout or budget exhaustion on long-running tasks\r\n// like monorepo audits, deep refactors, and security scans.\r\n//\r\n// x10 values (realistic upper bound for a single subagent task):\r\n// audit-log: 7.5 hours, 5000 iterations, 15000 tool calls\r\n// bug-hunter: 10 hours, 8000 iterations, 20000 tool calls\r\n// refactor-planner: 7.5 hours, 6000 iterations, 18000 tool calls\r\n// security-scanner: 10 hours, 8000 iterations, 20000 tool calls\r\n//\r\n// These can be overridden per-call via delegate tool parameters.\r\n// ---------------------------------------------------------------------------\r\nexport interface FleetRosterBudget {\r\n timeoutMs?: number | undefined;\r\n /** Idle reap window (ms). Resets on activity — see `applyRosterBudget`. */\r\n idleTimeoutMs?: number | undefined;\r\n maxIterations?: number | undefined;\r\n maxToolCalls?: number | undefined;\r\n maxTokens?: number | undefined;\r\n maxCostUsd?: number | undefined;\r\n}\r\n\r\n/**\r\n * Default idle window for delegated subagents: reap only after this long with\r\n * NO activity (no iteration / tool call / streamed progress). An actively-\r\n * working agent resets this clock continuously, so it runs until its task\r\n * naturally ends — no more wall-clock kills of productive runs. Power users\r\n * can still impose a hard `timeoutMs` per delegate.\r\n */\r\nexport const DEFAULT_IDLE_TIMEOUT_MS = 15 * 60 * 1000;\r\n\r\nexport const FLEET_ROSTER_BUDGETS: Record<string, FleetRosterBudget> = {\r\n 'audit-log': { timeoutMs: 7.5 * 60 * 60 * 1000, maxIterations: 5000, maxToolCalls: 15000 },\r\n 'bug-hunter': { timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000 },\r\n 'refactor-planner': { timeoutMs: 7.5 * 60 * 60 * 1000, maxIterations: 6000, maxToolCalls: 18000 },\r\n 'security-scanner': { timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000 },\r\n 'critic': { timeoutMs: 5 * 60 * 60 * 1000, maxIterations: 4000, maxToolCalls: 12000 },\r\n ...Object.fromEntries(\r\n ALL_AGENT_DEFINITIONS.map((d) => [d.config.role as string, d.budget] as const),\r\n ),\r\n};\r\n\r\n/**\r\n * Apply roster budget to a config (only when the config has no explicit\r\n * budget fields set). This is called by the coordinator before dispatch.\r\n */\r\n// Generic default budget applied when no role matches and no explicit budget\r\n// fields are set. Used for `name` / free-form delegates. There is no default\r\n// wall-clock timeout — a delegated agent runs until its task naturally ends\r\n// (`end_turn`) or it stalls past the idle window. Iteration / tool-call ceilings\r\n// remain as a runaway backstop.\r\nconst GENERIC_SUBAGENT_BUDGET: FleetRosterBudget = {\r\n idleTimeoutMs: DEFAULT_IDLE_TIMEOUT_MS,\r\n maxIterations: 5000,\r\n maxToolCalls: 15000,\r\n};\r\n\r\nexport function applyRosterBudget(cfg: SubagentConfig): SubagentConfig {\r\n // First try role-specific budget; fall back to generic for name-only delegates.\r\n const roleBudget = cfg.role ? FLEET_ROSTER_BUDGETS[cfg.role] : undefined;\r\n const defaultBudget = roleBudget ?? (cfg.name ? GENERIC_SUBAGENT_BUDGET : undefined);\r\n if (!defaultBudget) return cfg;\r\n return {\r\n ...cfg,\r\n // Wall-clock cap is opt-in only: forward an explicit `cfg.timeoutMs`, but\r\n // do NOT impose the roster's historical multi-hour wall-clock default — it\r\n // killed agents that were still actively working. Reaping is idle-based.\r\n timeoutMs: cfg.timeoutMs,\r\n // Idle window is the default reaper. Resets on activity, so a long-but-\r\n // productive run is never killed; only a genuine stall is reaped.\r\n idleTimeoutMs: cfg.idleTimeoutMs ?? defaultBudget.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS,\r\n maxIterations: cfg.maxIterations ?? defaultBudget.maxIterations,\r\n maxToolCalls: cfg.maxToolCalls ?? defaultBudget.maxToolCalls,\r\n maxTokens: cfg.maxTokens ?? defaultBudget.maxTokens,\r\n maxCostUsd: cfg.maxCostUsd ?? defaultBudget.maxCostUsd,\r\n };\r\n}\r\n\r\n/** Quick-access list for spawning all at once. */\r\nexport const ALL_FLEET_AGENTS = Object.values(FLEET_ROSTER);\r\n\r\n// ---------------------------------------------------------------------------\r\n// ACP external agents — WrongStack spawns these as subagents via ACP protocol.\r\n// Each agent runs its own loop; WrongStack sends tasks as ACP messages and\r\n// receives results. These don't go through makeAgentSubagentRunner — they\r\n// are handled by makeACPSubagentRunner in the CLI multi-agent layer.\r\n// ---------------------------------------------------------------------------\r\n\r\n/**\r\n * Cline — ACP-compatible coding agent by @asonix.\r\n * Spawned as: `npx @agentify/cline`\r\n */\r\nexport const CLINE_AGENT: SubagentConfig = {\r\n id: 'cline',\r\n name: 'Cline',\r\n role: 'cline',\r\n prompt: `You are Cline, a coding agent. You help write, edit, and navigate code.\r\nYou operate by receiving tasks via ACP and returning results.\r\nWhen asked to code, make focused changes and explain them briefly.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * Gemini CLI — Google's ACP-compatible command-line agent.\r\n * Spawned as: `gemini` (when gemini CLI is installed and in PATH)\r\n */\r\nexport const GEMINI_CLI_AGENT: SubagentConfig = {\r\n id: 'gemini-cli',\r\n name: 'Gemini CLI',\r\n role: 'gemini-cli',\r\n prompt: `You are Gemini CLI, a coding agent powered by Google's Gemini model.\r\nYou help with code generation, editing, debugging, and best practices.\r\nYou operate by receiving tasks via ACP and returning results.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * GitHub Copilot (public preview) — ACP-compatible Copilot CLI agent.\r\n * Spawned as: `gh copilot` (when gh CLI with copilot extension is installed)\r\n */\r\nexport const COPILOT_AGENT: SubagentConfig = {\r\n id: 'copilot',\r\n name: 'GitHub Copilot',\r\n role: 'copilot',\r\n prompt: `You are GitHub Copilot, an AI coding assistant.\r\nYou help write, explain, refactor, and review code.\r\nYou operate by receiving tasks via ACP and returning results.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * OpenHands — AI coding agent by all-in.ai, ACP-compatible.\r\n * Spawned as: `openhands` (when installed)\r\n */\r\nexport const OPENHANDS_AGENT: SubagentConfig = {\r\n id: 'openhands',\r\n name: 'OpenHands',\r\n role: 'openhands',\r\n prompt: `You are OpenHands, an AI coding agent that can use tools to interact\r\nwith files, terminals, browsers, and other resources.\r\nYou operate by receiving tasks via ACP and returning results.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * Goose — IDE agent by ExoRL, ACP-compatible.\r\n * Spawned as: `goose` (when goose CLI is installed)\r\n */\r\nexport const GOOSE_AGENT: SubagentConfig = {\r\n id: 'goose',\r\n name: 'Goose',\r\n role: 'goose',\r\n prompt: `You are Goose, an AI agent that helps with coding tasks.\r\nYou operate by receiving tasks via ACP and returning results.\r\nFocus on writing high-quality, well-tested code.`,\r\n provider: 'acp',\r\n};\r\n\r\n/** All ACP external agents. */\r\nexport const ACP_AGENTS: SubagentConfig[] = [\r\n CLINE_AGENT,\r\n GEMINI_CLI_AGENT,\r\n COPILOT_AGENT,\r\n OPENHANDS_AGENT,\r\n GOOSE_AGENT,\r\n];\r\n\r\n// ACP agents share the same generous budgets as the built-in fleet agents.\r\n// External ACP agents may need more time than typical in-process subagents\r\n// since they run their own loops and may do tool-call round-trips.\r\nFLEET_ROSTER_BUDGETS['cline'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['gemini-cli'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['copilot'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['openhands'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['goose'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\n\r\n/** Extended roster including ACP agents. */\r\nexport const FLEET_ROSTER_WITHACP: Record<string, SubagentConfig> = {\r\n ...FLEET_ROSTER,\r\n ...Object.fromEntries(ACP_AGENTS.map((a) => [a.role as string, a])),\r\n};\r\n","/**\n * Subagent nickname pool — famous scientists, mathematicians, and computing pioneers.\n * Names are grouped by domain affinity so the nickname hints at the agent's role.\n */\n\nconst NICKNAME_POOL = {\n // Physics & fundamental sciences\n 'einstein': { name: 'Einstein', domain: 'physics' },\n 'newton': { name: 'Newton', domain: 'physics' },\n 'feynman': { name: 'Feynman', domain: 'physics' },\n 'dirac': { name: 'Dirac', domain: 'physics' },\n 'bohr': { name: 'Bohr', domain: 'physics' },\n 'planck': { name: 'Planck', domain: 'physics' },\n 'curie': { name: 'Curie', domain: 'physics' },\n 'fermi': { name: 'Fermi', domain: 'physics' },\n 'heisenberg': { name: 'Heisenberg', domain: 'physics' },\n 'schrodinger': { name: 'Schrödinger', domain: 'physics' },\n\n // Mathematics\n 'euclid': { name: 'Euclid', domain: 'math' },\n 'gauss': { name: 'Gauss', domain: 'math' },\n 'turing': { name: 'Turing', domain: 'math' },\n 'poincare': { name: 'Poincaré', domain: 'math' },\n 'riemann': { name: 'Riemann', domain: 'math' },\n 'hilbert': { name: 'Hilbert', domain: 'math' },\n 'pythagoras': { name: 'Pythagoras', domain: 'math' },\n\n // Computing & information theory\n 'von-neumann': { name: 'Von Neumann', domain: 'computing' },\n 'shannon': { name: 'Shannon', domain: 'computing' },\n 'hopper': { name: 'Hopper', domain: 'computing' },\n 'backus': { name: 'Backus', domain: 'computing' },\n 'knuth': { name: 'Knuth', domain: 'computing' },\n 'torvalds': { name: 'Torvalds', domain: 'computing' },\n 'stallman': { name: 'Stallman', domain: 'computing' },\n 'berners-lee': { name: 'Berners-Lee', domain: 'computing' },\n 'babbage': { name: 'Babbage', domain: 'computing' },\n 'lovelace': { name: 'Lovelace', domain: 'computing' },\n 'klein': { name: 'Klein', domain: 'computing' },\n\n // Electronics & electrical engineering\n 'edison': { name: 'Edison', domain: 'ee' },\n 'tesla': { name: 'Tesla', domain: 'ee' },\n 'faraday': { name: 'Faraday', domain: 'ee' },\n 'maxwell': { name: 'Maxwell', domain: 'ee' },\n 'ohm': { name: 'Ohm', domain: 'ee' },\n 'bell': { name: 'Bell', domain: 'ee' },\n 'marconi': { name: 'Marconi', domain: 'ee' },\n 'lamarr': { name: 'Lamarr', domain: 'ee' },\n\n // General science / multi-disciplinary\n 'darwin': { name: 'Darwin', domain: 'biology' },\n 'mendel': { name: 'Mendel', domain: 'biology' },\n 'pasteur': { name: 'Pasteur', domain: 'biology' },\n 'hawking': { name: 'Hawking', domain: 'cosmology' },\n 'sagan': { name: 'Sagan', domain: 'cosmology' },\n\n // Exploration & navigation\n 'columbus': { name: 'Columbus', domain: 'exploration' },\n 'polo': { name: 'Polo', domain: 'exploration' },\n 'magellan': { name: 'Magellan', domain: 'exploration' },\n\n // Chemistry / materials\n 'lavoisier': { name: 'Lavoisier', domain: 'chemistry' },\n 'mendeleev': { name: 'Mendeleev', domain: 'chemistry' },\n} as const;\n\n/** Flat ordered list of all available nicknames — used for round-robin. */\nconst ALL_NICKNAMES = Object.entries(NICKNAME_POOL) as [NicknameKey, { name: string; domain: string }][];\n\n/** Reverse index: display name (e.g. \"Von Neumann\") → canonical pool key. */\nconst NAME_TO_KEY: Record<string, string> = Object.fromEntries(\n ALL_NICKNAMES.map(([key, entry]) => [entry.name, key]),\n);\n\n/** Domain → preferred nickname keys (fallback chain). */\nconst DOMAIN_PREFERENCES: Record<string, string[]> = {\n 'security': ['shannon', 'turing', 'lamarr', 'stallman'],\n 'bug-hunter': ['darwin', 'curie', 'feynman', 'fermi'],\n 'refactor': ['gauss', 'hilbert', 'euclid', 'planck'],\n 'audit-log': ['sagan', 'hawking', 'poincare', 'newton'],\n 'planner': ['hilbert', 'gauss', 'turing', 'euclid'],\n 'researcher': ['sagan', 'hawking', 'darwin', 'pasteur'],\n 'explorer': ['marconi', 'bell', 'columbus', 'polo'],\n 'testing': ['pasteur', 'curie', 'fermi', 'bohr'],\n 'frontend': ['lovelace', 'hopper', 'babbage', 'backus'],\n 'backend': ['torvalds', 'stallman', 'von-neumann', 'backus'],\n 'database': ['turing', 'shannon', 'backus', 'knuth'],\n 'devops': ['tesla', 'edison', 'faraday', 'bell'],\n 'security-scanner': ['shannon', 'turing', 'lamarr', 'stallman'],\n 'refactor-planner': ['gauss', 'hilbert', 'planck', 'newton'],\n 'architect': ['von-neumann', 'turing', 'gauss', 'hilbert'],\n 'critic': ['einstein', 'feynman', 'dirac', 'bohr'],\n 'e2e': ['hopper', 'bell', 'marconi', 'tesla'],\n 'performance': ['knuth', 'gauss', 'planck', 'feynman'],\n 'chaos': ['tesla', 'edison', 'curie', 'fermi'],\n 'cost': ['ohm', 'bell', 'marconi', 'tesla'],\n // default fallback\n 'default': ['einstein', 'newton', 'curie', 'tesla', 'edison', 'turing', 'shannon', 'hopper', 'knuth', 'stallman'],\n};\n\ntype NicknameKey = keyof typeof NICKNAME_POOL;\n\n/** Result of a nickname assignment. */\nexport interface NicknameAssignment {\n /**\n * Canonical pool key (e.g. `von-neumann`). This — NOT the display string — is\n * what callers must add to their `used` set and later remove on release.\n * Deriving the key by parsing the display string is unsafe: multi-word names\n * like \"Von Neumann\" would be truncated to \"von\" and never dedupe correctly.\n */\n key: string;\n /** Human display string, e.g. `Von Neumann (Backend)`. */\n display: string;\n}\n\n/**\n * Assign a unique nickname to a subagent based on its role.\n *\n * Returns both the canonical pool `key` (for the `used` set) and the formatted\n * `display` string (`Name (Role)`, e.g. `Einstein (Bug Hunter)`).\n *\n * @param role - The subagent's role id (e.g. 'bug-hunter', 'security-scanner')\n * @param used - Set of nickname KEYS already assigned in this fleet\n * (so no two subagents share the same base name)\n */\nexport function assignNickname(role: string, used: ReadonlySet<string>): NicknameAssignment {\n // 1. Build preference list: role-specific → default fallback\n const preferences = [\n ...(DOMAIN_PREFERENCES[role] ?? []),\n ...(DOMAIN_PREFERENCES['default'] ?? []),\n ];\n\n // 2. Find the first unassigned nickname from preferences. Skip keys that are\n // not in the pool — preference lists can drift out of sync with the pool\n // (typos, removed names), and an unknown key must not crash assignment.\n for (const key of preferences) {\n const entry = NICKNAME_POOL[key as NicknameKey];\n if (entry && !used.has(key)) {\n return { key, display: `${entry.name} (${formatRole(role)})` };\n }\n }\n\n // 3. Exhausted preferences — pick the first unused name round-robin style.\n for (const [key, entry] of ALL_NICKNAMES) {\n if (!used.has(key)) {\n return { key, display: `${entry.name} (${formatRole(role)})` };\n }\n }\n\n // 4. Pool exhausted — synthesize a stable, unique key/display pair.\n const counter = used.size + 1;\n return { key: `scientist-${counter}`, display: `Scientist #${counter} (${formatRole(role)})` };\n}\n\n/**\n * Resolve a previously-assigned display string back to its canonical pool key,\n * for release paths that only retained the formatted name (e.g. a manifest\n * entry). Strips the trailing ` (Role)` suffix, then matches the base name\n * against the pool. Returns `undefined` when the name is not a known nickname.\n *\n * Use this instead of `name.split(' ')[0]` — the latter mangles multi-word\n * names like \"Von Neumann\" and \"Berners-Lee\".\n */\nexport function nicknameKeyFromDisplay(display: string): string | undefined {\n const base = display.replace(/\\s*\\([^)]*\\)\\s*$/, '').trim();\n const key = NAME_TO_KEY[base];\n if (key) return key;\n const synthesized = base.match(/^Scientist #(\\d+)$/);\n return synthesized ? `scientist-${synthesized[1]}` : undefined;\n}\n\n/** Format role id into human-readable title-case. */\nfunction formatRole(role: string): string {\n return role\n .split(/[-_]/)\n .map((w) => w.charAt(0).toUpperCase() + w.slice(1))\n .join(' ');\n}\n\n/**\n * Returns all available nickname keys. Useful for testing or reset logic.\n */\nexport function getAllNicknameKeys(): string[] {\n return Object.keys(NICKNAME_POOL);\n}\n","import { randomUUID } from 'node:crypto';\r\nimport { EventEmitter } from 'node:events';\r\nimport type { AgentBridge, BridgeMessage } from '../types/agent-bridge.js';\r\nimport type {\r\n CoordinatorStatus,\r\n MultiAgentConfig,\r\n MultiAgentCoordinator,\r\n SpawnResult,\r\n SubagentConfig,\r\n SubagentContext,\r\n SubagentRunContext,\r\n SubagentRunner,\r\n TaskResult,\r\n TaskSpec,\r\n} from '../types/multi-agent.js';\r\nimport {\r\n BudgetExceededError,\r\n DECISION_TIMEOUT_MS,\r\n SubagentBudget,\r\n TIMEOUT_PREEMPT_FRACTION,\r\n} from './subagent-budget.js';\r\nimport { classifySubagentError } from './coordinator/error-classifier.js';\r\nimport { applyRosterBudget } from './fleet.js';\r\nimport { assignNickname } from './subagent-nicknames.js';\r\n\r\ntype SubagentStatus = 'running' | 'idle' | 'stopped' | 'error';\r\n\r\ninterface SubagentEntry {\r\n config: SubagentConfig;\r\n context: SubagentContext;\r\n status: SubagentStatus;\r\n currentTask?: string | undefined;\r\n abortController: AbortController;\r\n /** Lazily created on first dispatch — budget is per-task, not per-subagent. */\r\n activeBudget?: SubagentBudget | undefined;\r\n}\r\n\r\nexport interface MultiAgentCoordinatorOptions {\r\n /**\r\n * Callback that executes a task on behalf of a subagent. Required for\r\n * `assign()` to actually run anything — without it, tasks queue forever.\r\n * The coordinator provides per-subagent isolation (own budget, own signal,\r\n * own bridge) and enforces timeout + concurrency.\r\n */\r\n runner?: SubagentRunner | undefined;\r\n}\r\n\r\nexport class DefaultMultiAgentCoordinator extends EventEmitter implements MultiAgentCoordinator {\r\n readonly coordinatorId: string;\r\n readonly config: MultiAgentConfig;\r\n private runner?: SubagentRunner | undefined;\r\n private fleetBus?: import('./fleet-bus.js').FleetBus | undefined;\r\n\r\n private readonly subagents = new Map<string, SubagentEntry>();\r\n\r\n /**\r\n * Base nickname keys already handed out this run (e.g. `einstein`, `tesla`).\r\n * Prevents two workers sharing a name. Direct `coordinator.spawn()` callers\r\n * (parallel/eternal engine, SDD parallel run) don't go through\r\n * `Director.spawn()` where nicknames are normally assigned, so the\r\n * coordinator upgrades placeholder names (\"Executor\", \"slot-ab12cd\", role\r\n * names) to memorable ones here — that's what surfaces in the fleet monitor.\r\n */\r\n private readonly usedNicknames = new Set<string>();\r\n /** Maps subagentId → nickname key (e.g. 'einstein'). Used to free the slot on remove(). */\r\n private readonly subagentNicknames = new Map<string, string>();\r\n\r\n private pendingTasks: TaskSpec[] = [];\r\n private completedResults: TaskResult[] = [];\r\n /** Prevents completedResults from growing unbounded in long-running coordinators. */\r\n private static readonly MAX_COMPLETED_RESULTS = 10_000;\r\n private totalIterations = 0;\r\n private inFlight = 0;\r\n /**\r\n * Subagents currently being stopped. Set on entry to `stop()`, cleared\r\n * once `recordCompletion` lands the terminal TaskResult. Used by\r\n * `runDispatched` and `findIdleSubagent` to refuse mid-flight dispatch\r\n * to a subagent the caller has already asked to terminate — closes the\r\n * assign+terminate race where a fresh task could land on a worker that\r\n * was about to be killed.\r\n */\r\n private readonly terminating = new Set<string>();\r\n\r\n constructor(config: MultiAgentConfig, options: MultiAgentCoordinatorOptions = {}) {\r\n super();\r\n // awaitTasks() registers one short-lived 'task.completed' listener per\r\n // awaited id; a single call awaiting >10 ids (or several concurrent\r\n // callers) crosses Node's default 10-listener cap and prints a spurious\r\n // MaxListenersExceededWarning that also masks genuine leaks. These waiters\r\n // are bounded and self-removing, so lift the cap.\r\n this.setMaxListeners(0);\r\n this.coordinatorId = config.coordinatorId;\r\n this.config = config;\r\n this.runner = options.runner;\r\n }\r\n\r\n /**\r\n * Replace the runner after construction. Used when the runner depends\r\n * on infrastructure (e.g. FleetBus) that isn't available until after\r\n * the coordinator's owning Director is built.\r\n */\r\n setRunner(runner: SubagentRunner): void {\r\n this.runner = runner;\r\n }\r\n\r\n /**\r\n * Wire a FleetBus for director-mode event emission. Call after the\r\n * FleetManager is constructed so the coordinator can emit lifecycle\r\n * events the TUI and monitoring tools subscribe to.\r\n */\r\n setFleetBus(fleet: import('./fleet-bus.js').FleetBus): void {\r\n this.fleetBus = fleet;\r\n }\r\n\r\n /**\r\n * Change the in-flight dispatch ceiling at runtime. Lowering does NOT\r\n * preempt running tasks — already-dispatched subagents finish their\r\n * current task; only future dispatches respect the new cap. Raising\r\n * immediately tries to fill the freed slots from the pending queue.\r\n */\r\n setMaxConcurrent(n: number): void {\r\n if (!Number.isFinite(n) || n < 1) {\r\n throw new Error(`maxConcurrent must be a finite integer >= 1, got ${n}`);\r\n }\r\n this.config.maxConcurrent = Math.floor(n);\r\n this.tryDispatchNext();\r\n }\r\n\r\n /**\r\n * Upgrade a placeholder/role-derived name to a memorable scientist nickname\r\n * (e.g. \"Einstein (Executor)\"). A name is treated as a placeholder when it is\r\n * empty, equals the role (case-insensitive), is a generic default\r\n * (\"subagent\"/\"adhoc\"/\"generic\"), or is an auto-generated `slot-…` id.\r\n * Explicit, human-chosen names — including nicknames already assigned by\r\n * `Director.spawn()` — are left untouched, so this never double-assigns.\r\n */\r\n private withNickname(subagent: SubagentConfig, subagentId: string): SubagentConfig {\r\n const role = subagent.role ?? 'subagent';\r\n const name = subagent.name?.trim() ?? '';\r\n const isPlaceholder =\r\n name === '' ||\r\n name.toLowerCase() === role.toLowerCase() ||\r\n name === 'subagent' ||\r\n name === 'adhoc' ||\r\n name === 'generic' ||\r\n /^slot-/.test(name);\r\n if (!isPlaceholder) return subagent;\r\n const { key, display } = assignNickname(role, this.usedNicknames);\r\n this.usedNicknames.add(key);\r\n this.subagentNicknames.set(subagentId, key);\r\n return { ...subagent, name: display };\r\n }\r\n\r\n async spawn(subagent: SubagentConfig): Promise<SpawnResult> {\r\n const id = subagent.id || randomUUID();\r\n const cfg = this.withNickname(subagent, id);\r\n // Duplicate-id guard. Previously a second spawn({id}) with the\r\n // same id silently overwrote the existing entry — orphaning the\r\n // first subagent's AbortController, Context, and any in-flight\r\n // task referencing it. Two spawns with the same id are almost\r\n // always a bug at the caller; refuse and let them surface it.\r\n if (this.subagents.has(id)) {\r\n throw new Error(`Subagent id \"${id}\" already exists — refusing to overwrite`);\r\n }\r\n const context: SubagentContext = {\r\n subagentId: id,\r\n tasks: [],\r\n // Wired later by the caller via setSubagentBridge() once the\r\n // bidirectional bridge is created. Readers must null-check / use\r\n // hasParentBridge() — the type now reflects this.\r\n parentBridge: null,\r\n doneCondition: this.config.doneCondition,\r\n maxConcurrent: this.config.maxConcurrent ?? 16,\r\n };\r\n\r\n this.subagents.set(id, {\r\n config: { ...cfg, id },\r\n context,\r\n status: 'idle',\r\n abortController: new AbortController(),\r\n });\r\n\r\n this.emit('subagent.started', { subagent: { ...cfg, id } });\r\n\r\n this.fleetBus?.emit({\r\n subagentId: id,\r\n ts: Date.now(),\r\n type: 'subagent.assigned',\r\n payload: {\r\n subagentId: id,\r\n name: subagent.name,\r\n provider: subagent.provider,\r\n model: subagent.model,\r\n },\r\n });\r\n\r\n this.emitCoordinatorStats();\r\n\r\n return { subagentId: id, agentId: id };\r\n }\r\n\r\n async assign(task: TaskSpec): Promise<void> {\r\n this.pendingTasks.push(task);\r\n this.tryDispatchNext();\r\n }\r\n\r\n async delegate(to: string, msg: BridgeMessage): Promise<void> {\r\n const subagent = this.subagents.get(to);\r\n if (!subagent) throw new Error(`Subagent \"${to}\" not found`);\r\n if (!subagent.context.parentBridge) {\r\n throw new Error(`Subagent \"${to}\" has no parentBridge — call setSubagentBridge() first`);\r\n }\r\n await subagent.context.parentBridge.send(msg);\r\n }\r\n\r\n /**\r\n * Wire up the communication bridge for a subagent. Call after spawn() once\r\n * the caller has created the bidirectional connection.\r\n */\r\n setSubagentBridge(subagentId: string, bridge: AgentBridge): void {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) throw new Error(`Subagent \"${subagentId}\" not found`);\r\n subagent.context.parentBridge = bridge;\r\n }\r\n\r\n async stop(subagentId: string): Promise<void> {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) return;\r\n\r\n // Mark terminating BEFORE the abort so a synchronous tryDispatchNext\r\n // observation in another callback path sees the intent and skips\r\n // this subagent. Cleared by recordCompletion once the runner's\r\n // catch block lands the terminal TaskResult.\r\n this.terminating.add(subagentId);\r\n\r\n // Abort any in-flight run, then sever the bridge so further messages fail\r\n // fast instead of silently queueing on a dead subagent.\r\n subagent.abortController.abort();\r\n subagent.status = 'stopped';\r\n subagent.currentTask = undefined;\r\n subagent.context.parentBridge = null;\r\n\r\n this.emit('subagent.stopped', { subagentId, reason: 'stopped by coordinator' });\r\n\r\n this.fleetBus?.emit({\r\n subagentId,\r\n ts: Date.now(),\r\n type: 'subagent.stopped',\r\n payload: { subagentId, reason: 'stopped by coordinator' },\r\n });\r\n\r\n this.emitCoordinatorStats();\r\n }\r\n\r\n async stopAll(): Promise<void> {\r\n // Clear the queue FIRST so no new tasks land on subagents while\r\n // we're tearing them down. Each dropped task gets a synthetic\r\n // `aborted_by_parent` completion so any caller awaiting it (e.g.\r\n // delegate tool's awaitTasks) resolves instead of hanging.\r\n //\r\n // Pending tasks never reached `inFlight`, so we cannot route them\r\n // through `recordCompletion` — its underflow guard would short-\r\n // circuit on the second pending task and emit a warning instead\r\n // of the completion event. The shared helper inline-emits.\r\n this.drainPendingAsAborted('Coordinator stopAll() drained the pending queue');\r\n // allSettled so one failure doesn't leave other subagents un-stopped.\r\n await Promise.allSettled([...this.subagents.keys()].map((id) => this.stop(id)));\r\n }\r\n\r\n /**\r\n * Get current coordinator stats for monitoring/debugging.\r\n */\r\n getStats(): {\r\n total: number;\r\n running: number;\r\n idle: number;\r\n stopped: number;\r\n inFlight: number;\r\n pending: number;\r\n completed: number;\r\n } {\r\n let running = 0;\r\n let idle = 0;\r\n let stopped = 0;\r\n for (const [, entry] of this.subagents) {\r\n if (entry.status === 'running') running++;\r\n else if (entry.status === 'idle') idle++;\r\n else stopped++;\r\n }\r\n return {\r\n total: this.subagents.size,\r\n running,\r\n idle,\r\n stopped,\r\n inFlight: this.inFlight,\r\n pending: this.pendingTasks.length,\r\n completed: this.completedResults.length,\r\n };\r\n }\r\n\r\n /** Emit a reactive coordinator.stats event on FleetBus so the TUI can subscribe. */\r\n private emitCoordinatorStats(): void {\r\n const stats = this.getStats();\r\n const subagentStatuses = Array.from(this.subagents.entries()).map(([id, s]) => ({\r\n subagentId: id,\r\n taskId: s.currentTask ?? '',\r\n status: s.status,\r\n assigned: s.context.parentBridge !== null,\r\n }));\r\n this.fleetBus?.emit({\r\n subagentId: this.coordinatorId,\r\n ts: Date.now(),\r\n type: 'coordinator.stats',\r\n payload: { ...stats, subagentStatuses },\r\n });\r\n }\r\n\r\n getStatus(): CoordinatorStatus {\r\n return {\r\n coordinatorId: this.coordinatorId,\r\n subagents: Array.from(this.subagents.entries()).map(([id, s]) => ({\r\n id,\r\n name: s.config.name,\r\n status: s.status,\r\n currentTask: s.currentTask,\r\n })),\r\n pendingTasks: this.pendingTasks.length,\r\n completedTasks: this.completedResults.length,\r\n totalIterations: this.totalIterations,\r\n done: this.isDone(),\r\n };\r\n }\r\n\r\n /** Expose snapshot of completed results — useful for callers awaiting all done. */\r\n results(): readonly TaskResult[] {\r\n return this.completedResults;\r\n }\r\n\r\n /**\r\n * Wait for one or more tasks to complete and return their results.\r\n * If a task is already done when called, returns immediately.\r\n * Resolves to an array in the same order as `taskIds`.\r\n */\r\n async awaitTasks(taskIds: string[]): Promise<TaskResult[]> {\r\n return Promise.all(\r\n taskIds.map((id) => {\r\n const cached = this.completedResults.find((r) => r.taskId === id);\r\n if (cached) return cached;\r\n // Fallback: poll until the task completes (up to timeoutMs).\r\n // The coordinator fires 'task.completed' on every result, so\r\n // we use a promise-based waiter tied to that event.\r\n return new Promise<TaskResult>((resolve, reject) => {\r\n const timeout = setTimeout(() => {\r\n this.off('task.completed', handler);\r\n reject(new Error(`awaitTasks timed out waiting for task \"${id}\"`));\r\n }, this.config.timeoutMs ?? 300_000);\r\n const handler = ({ result }: { task: TaskSpec; result: TaskResult }) => {\r\n if (result.taskId === id) {\r\n clearTimeout(timeout);\r\n this.off('task.completed', handler);\r\n resolve(result);\r\n }\r\n };\r\n this.on('task.completed', handler);\r\n });\r\n }),\r\n );\r\n }\r\n\r\n /**\r\n * Manual completion — for callers that drive subagents without a runner\r\n * (e.g. external orchestrators). When a runner is configured the coordinator\r\n * calls this itself.\r\n */\r\n completeTask(result: TaskResult): void {\r\n this.recordCompletion(result);\r\n }\r\n\r\n // --- internal dispatching ---------------------------------------------\r\n\r\n private tryDispatchNext(): void {\r\n while (this.canDispatch()) {\r\n const dispatchable = this.takeNextDispatchableTask();\r\n if (!dispatchable) {\r\n // No idle worker right now. If every spawned subagent is\r\n // stopped or mid-termination, the pending queue is dead —\r\n // a pending task can never start, so synthetic-complete it\r\n // as `aborted_by_parent`. Without this, an `assign()` after\r\n // `stop()` would hang forever waiting for `task.completed`.\r\n // We DO NOT drain when subagents are busy (status='running'):\r\n // those will free up and accept the work normally.\r\n if (this.pendingTasks.length > 0 && !this.hasLiveSubagent()) {\r\n this.drainPendingAsAborted(\r\n 'No live subagent available — all stopped or mid-termination',\r\n );\r\n }\r\n return;\r\n }\r\n const { subagentId, task } = dispatchable;\r\n // Attach a catch so a synchronous throw inside runDispatched (rare —\r\n // e.g. provider misconfiguration before the first await) becomes a\r\n // visible failed task instead of an unhandled rejection that leaves\r\n // `inFlight` permanently elevated.\r\n this.runDispatched(subagentId, task).catch((err) => {\r\n this.recordCompletion({\r\n subagentId,\r\n taskId: task.id,\r\n status: 'failed',\r\n error: classifySubagentError(err),\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n });\r\n });\r\n }\r\n }\r\n\r\n private canDispatch(): boolean {\r\n const max = this.config.maxConcurrent ?? 16;\r\n return this.inFlight < max && this.pendingTasks.length > 0;\r\n }\r\n\r\n private takeNextDispatchableTask(): { subagentId: string; task: TaskSpec } | null {\r\n for (let i = 0; i < this.pendingTasks.length; i++) {\r\n const task = this.pendingTasks[i];\r\n if (!task) continue;\r\n const subagentId = task.subagentId\r\n ? this.isIdleSubagent(task.subagentId)\r\n ? task.subagentId\r\n : null\r\n : this.findIdleSubagent();\r\n if (!subagentId) continue;\r\n this.pendingTasks.splice(i, 1);\r\n return { subagentId, task };\r\n }\r\n return null;\r\n }\r\n\r\n private findIdleSubagent(): string | null {\r\n for (const [id, s] of this.subagents) {\r\n // Skip subagents that are mid-termination — `stop()` set the\r\n // `terminating` flag and aborted the controller, but the\r\n // status mutation happens synchronously after; checking both\r\n // is belt-and-suspenders against any race where status is\r\n // transiently still 'idle' while termination is in flight.\r\n if (s.status === 'idle' && !this.terminating.has(id)) return id;\r\n }\r\n return null;\r\n }\r\n\r\n private isIdleSubagent(id: string): boolean {\r\n const subagent = this.subagents.get(id);\r\n return !!subagent && subagent.status === 'idle' && !this.terminating.has(id);\r\n }\r\n\r\n /**\r\n * Returns true iff at least one spawned subagent could still\r\n * process a task. A \"live\" subagent is one that is not stopped\r\n * AND not mid-termination — `running` workers count because they\r\n * will eventually finish and become idle.\r\n *\r\n * When no subagent has ever been spawned, returns `true` so a\r\n * pre-spawn `assign()` simply queues (legacy behaviour). The\r\n * dead-end detection only fires after `stop()` has retired every\r\n * spawned worker.\r\n *\r\n * Used by `tryDispatchNext` to detect a dead-end pending queue.\r\n */\r\n private hasLiveSubagent(): boolean {\r\n if (this.subagents.size === 0) return true;\r\n for (const [id, s] of this.subagents) {\r\n if (s.status !== 'stopped' && !this.terminating.has(id)) return true;\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * Drain every pending task with a synthetic `aborted_by_parent`\r\n * completion event. Same shape as the `stopAll()` drain — we go\r\n * around `recordCompletion` because pending tasks were never\r\n * counted in `inFlight` and routing them through would trip the\r\n * underflow guard on every task after the first.\r\n */\r\n private drainPendingAsAborted(message: string): void {\r\n const dropped = this.pendingTasks.splice(0, this.pendingTasks.length);\r\n for (const t of dropped) this.emitPendingAborted(t, message);\r\n }\r\n\r\n /**\r\n * Emit a synthetic `stopped`/`aborted_by_parent` completion for a single\r\n * PENDING task — one that was never counted in `inFlight`. This MUST bypass\r\n * `recordCompletion`: that path does `inFlight--`, which for a pending task\r\n * steals a decrement from a genuinely in-flight task and trips the underflow\r\n * guard — suppressing that real task's `task.completed` and hanging its\r\n * `awaitTasks()` caller. Pushes the result and fires the event directly.\r\n */\r\n private emitPendingAborted(task: TaskSpec, message: string): void {\r\n const synthetic: TaskResult = {\r\n subagentId: task.subagentId ?? 'unassigned',\r\n taskId: task.id,\r\n status: 'stopped',\r\n error: {\r\n kind: 'aborted_by_parent',\r\n message,\r\n retryable: false,\r\n },\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n };\r\n this.completedResults.push(synthetic);\r\n this.emit('task.completed', { task, result: synthetic });\r\n }\r\n\r\n private async runDispatched(subagentId: string, task: TaskSpec): Promise<void> {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) return;\r\n // Final race guard: if `stop(subagentId)` ran between dispatch\r\n // and us arriving here, refuse to start the task and surface it\r\n // as `aborted_by_parent` so any caller awaiting the task id\r\n // unblocks. Without this, the task would be marked 'running',\r\n // collide with the just-completed 'stopped' state, and leak\r\n // inFlight by 1 because no recordCompletion path covers it.\r\n if (this.terminating.has(subagentId) || subagent.status === 'stopped') {\r\n this.recordCompletion({\r\n subagentId,\r\n taskId: task.id,\r\n status: 'stopped',\r\n error: {\r\n kind: 'aborted_by_parent',\r\n message: 'Subagent was terminated before task could start',\r\n retryable: false,\r\n },\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n });\r\n return;\r\n }\r\n\r\n subagent.status = 'running';\r\n subagent.currentTask = task.id;\r\n task.subagentId = subagentId;\r\n subagent.context.tasks.push(task);\r\n\r\n this.fleetBus?.emit({\r\n subagentId,\r\n taskId: task.id,\r\n ts: Date.now(),\r\n type: 'subagent.running',\r\n payload: { subagentId, taskId: task.id },\r\n });\r\n\r\n this.emit('task.assigned', { task, subagentId });\r\n this.emitCoordinatorStats();\r\n\r\n // Budget combines coordinator defaults with per-subagent and per-task overrides.\r\n // Precedence: task > subagent (raw, no roster fills) > coordinator default > roster default.\r\n // We intentionally call applyRosterBudget LATE — only as a final fallback after\r\n // the coordinator's defaultBudget has had a chance to apply. This prevents\r\n // GENERIC_SUBAGENT_BUDGET (5000 iter) from shadowing the coordinator's explicit default.\r\n const rawMaxIterations = subagent.config.maxIterations;\r\n const rawMaxToolCalls = subagent.config.maxToolCalls;\r\n const rawMaxTokens = subagent.config.maxTokens;\r\n const rawMaxCostUsd = subagent.config.maxCostUsd;\r\n const rawTimeoutMs = subagent.config.timeoutMs;\r\n const rawIdleTimeoutMs = subagent.config.idleTimeoutMs;\r\n const configWithRosterDefaults = applyRosterBudget(subagent.config);\r\n const budget = new SubagentBudget({\r\n maxIterations:\r\n rawMaxIterations ?? this.config.defaultBudget?.maxIterations ?? configWithRosterDefaults.maxIterations,\r\n maxToolCalls:\r\n rawMaxToolCalls ??\r\n this.config.defaultBudget?.maxToolCalls ??\r\n configWithRosterDefaults.maxToolCalls,\r\n maxTokens:\r\n rawMaxTokens ?? this.config.defaultBudget?.maxTokens ?? configWithRosterDefaults.maxTokens,\r\n maxCostUsd:\r\n rawMaxCostUsd ?? this.config.defaultBudget?.maxCostUsd ?? configWithRosterDefaults.maxCostUsd,\r\n // Wall-clock cap is opt-in (explicit config / defaultBudget only); the\r\n // roster no longer supplies one. Idle is the default reaper.\r\n timeoutMs:\r\n rawTimeoutMs ?? this.config.defaultBudget?.timeoutMs ?? configWithRosterDefaults.timeoutMs,\r\n idleTimeoutMs:\r\n rawIdleTimeoutMs ??\r\n this.config.defaultBudget?.idleTimeoutMs ??\r\n configWithRosterDefaults.idleTimeoutMs,\r\n });\r\n subagent.activeBudget = budget;\r\n\r\n if (!this.runner) {\r\n // No runner wired — caller drives execution via completeTask(). Status\r\n // reverts when the caller reports. We intentionally don't bump\r\n // `inFlight` here: `completeTask` → `recordCompletion` would then\r\n // decrement an inFlight that runDispatched never incremented, masking\r\n // the \"no runner\" state. With this guard, `isDone()`'s all_tasks_done\r\n // check still settles correctly once the caller reports.\r\n return;\r\n }\r\n\r\n // Only count inFlight when we actually own the execution lifecycle.\r\n this.inFlight++;\r\n\r\n const startTime = Date.now();\r\n const runCtx: SubagentRunContext = {\r\n subagentId,\r\n config: subagent.config,\r\n budget,\r\n signal: subagent.abortController.signal,\r\n bridge: subagent.context.parentBridge || null,\r\n };\r\n\r\n let result: TaskResult;\r\n\r\n budget.start();\r\n try {\r\n const outcome = await this.executeWithTimeout(\r\n this.runner,\r\n task,\r\n runCtx,\r\n budget,\r\n subagent.config.preemptFraction,\r\n );\r\n result = {\r\n subagentId,\r\n taskId: task.id,\r\n status: 'success',\r\n result: outcome.result,\r\n iterations: outcome.iterations,\r\n toolCalls: outcome.toolCalls,\r\n durationMs: Date.now() - startTime,\r\n };\r\n } catch (err) {\r\n // Order matters: a timeout calls abort() to signal cooperative runners,\r\n // which also flips `signal.aborted=true`. Inspect the error first so we\r\n // surface 'timeout' rather than masking it as 'stopped'.\r\n const status: TaskResult['status'] =\r\n err instanceof BudgetExceededError && (err.kind === 'timeout' || err.kind === 'idle_timeout')\r\n ? 'timeout'\r\n : subagent.abortController.signal.aborted\r\n ? 'stopped'\r\n : 'failed';\r\n const usage = budget.usage();\r\n result = {\r\n subagentId,\r\n taskId: task.id,\r\n status,\r\n error: classifySubagentError(err, {\r\n parentAborted: subagent.abortController.signal.aborted,\r\n }),\r\n iterations: usage.iterations,\r\n toolCalls: usage.toolCalls,\r\n durationMs: Date.now() - startTime,\r\n };\r\n }\r\n\r\n this.recordCompletion(result);\r\n }\r\n\r\n private async executeWithTimeout(\r\n runner: SubagentRunner,\r\n task: TaskSpec,\r\n ctx: SubagentRunContext,\r\n budget: SubagentBudget,\r\n preemptFraction: number = TIMEOUT_PREEMPT_FRACTION,\r\n ) {\r\n const initialTimeoutMs = budget.limits.timeoutMs;\r\n const idleLimitMs = budget.limits.idleTimeoutMs;\r\n if (initialTimeoutMs === undefined && idleLimitMs === undefined) {\r\n return runner(task, ctx);\r\n }\r\n\r\n // Re-armable watchdog. The default guard is IDLE-based: while the agent\r\n // keeps producing activity (iterations / tool calls / streamed progress),\r\n // `budget.idleMs()` stays below the window and we simply re-arm — an\r\n // actively-working subagent is never killed by the clock. Only a genuine\r\n // stall (no activity for `idleTimeoutMs`) reaps it. An explicit wall-clock\r\n // `timeoutMs` (rare, opt-in) keeps the original soft-warning behaviour: it\r\n // negotiates an extension via the Director's auto-extend listener and\r\n // re-arms rather than hard-killing a task solely for running long.\r\n const start = Date.now();\r\n let timer: ReturnType<typeof setTimeout> | null = null;\r\n // Pre-empt arm state machine:\r\n // ACTIVE — pre-empt can fire for the current ceiling window\r\n // LOCKED — pre-empt is locked; cannot fire until ceiling changes\r\n enum PreemptState {\r\n ACTIVE = 'active',\r\n LOCKED = 'locked',\r\n }\r\n // The wall-clock ceiling value at the moment the state was locked.\r\n // Compared against the current wallLimit to detect stale locks caused by\r\n // external calls to budget.patchLimits().\r\n let preemptedCeiling: number | null = null;\r\n let preemptState: PreemptState = PreemptState.ACTIVE;\r\n // Heartbeat gate for the proactive pre-empt: the timestamp of the subagent's\r\n // last activity at the moment of the most recent grant. A later pre-empt is\r\n // only negotiated if there has been NEW activity since then — a stalled\r\n // agent (no progress since its last grant) gets no further extension and is\r\n // left to the real deadline. `-1` until the first grant so the first\r\n // pre-empt always fires. Activity time is derived from `budget.idleMs()`\r\n // (reset by tool calls / iterations / streamed progress), so it works even\r\n // for runners that don't increment the budget's usage counters directly.\r\n let lastGrantActivityTs = -1;\r\n\r\n const timeoutPromise = new Promise<never>((_, reject) => {\r\n // Terminate the subagent, classifying by whether a negotiation listener\r\n // is wired. A listener-observed stop (explicit deny at the deadline, or an\r\n // idle reap while observed) surfaces as 'stopped' — reject with a\r\n // non-budget error so the coordinator's catch falls to `signal.aborted →\r\n // 'stopped'`. With no listener it is an unattended budget breach →\r\n // BudgetExceededError → 'timeout'. This keeps a bare /spawn reporting\r\n // 'timeout' while a director/observer-driven stop reads as 'stopped'.\r\n const terminate = (kind: 'timeout' | 'idle_timeout', limit: number, used: number) => {\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(\r\n budget._events?.hasListenerFor('budget.threshold_reached')\r\n ? new Error(`subagent stopped: budget ${kind} (limit=${limit}, used=${used})`)\r\n : new BudgetExceededError(kind, limit, used),\r\n );\r\n };\r\n const armFor = (ms: number) => {\r\n if (timer) clearTimeout(timer);\r\n timer = setTimeout(onTick, Math.max(0, ms));\r\n };\r\n // Re-arm for whichever deadline is sooner — the idle window (counted\r\n // from last activity), the explicit wall-clock cap, or the PROACTIVE\r\n // pre-empt point (a fraction of the wall cap, see TIMEOUT_PREEMPT_FRACTION)\r\n // at which we negotiate an extension BEFORE the deadline is crossed. Any\r\n // being unset/already-asked drops out of the min, so single-limit configs\r\n // behave exactly as that limit alone.\r\n const scheduleNext = () => {\r\n const wallLimit = budget.limits.timeoutMs ?? initialTimeoutMs;\r\n const wallRemaining =\r\n initialTimeoutMs === undefined\r\n ? Number.POSITIVE_INFINITY\r\n : (wallLimit as number) - (Date.now() - start);\r\n const idleRemaining =\r\n idleLimitMs === undefined\r\n ? Number.POSITIVE_INFINITY\r\n : (budget.limits.idleTimeoutMs ?? idleLimitMs) - budget.idleMs();\r\n const preemptRemaining =\r\n initialTimeoutMs === undefined || preemptedCeiling === wallLimit\r\n ? Number.POSITIVE_INFINITY\r\n : (wallLimit as number) * preemptFraction - (Date.now() - start);\r\n // Floor at a small positive so a near-zero remainder can't busy-loop.\r\n armFor(Math.max(25, Math.min(wallRemaining, idleRemaining, preemptRemaining)));\r\n };\r\n\r\n // Drive a timeout extension negotiation (used by BOTH the proactive\r\n // pre-empt and the at-deadline path). Resolves to the coordinator's\r\n // verdict: `{ extend: { timeoutMs } }` to grant, or a string to decline.\r\n // The budget's requestDecision falls back to 'stop' on no response, so\r\n // this never hangs.\r\n // Safety net: if no listener responds to the budget.threshold_reached event\r\n // within DECISION_TIMEOUT_MS (60 s), default to 'stop' so the watchdog\r\n // never hangs. Uses the exported DECISION_TIMEOUT_MS so both paths share\r\n // the same value — coordinator and budget agree on the ceiling.\r\n const negotiateTimeout = async (\r\n used: number,\r\n limit: number,\r\n ): Promise<'stop' | 'continue' | 'throw' | { extend: { timeoutMs?: number | undefined } }> => {\r\n const handler = budget.onThreshold;\r\n if (!handler) return 'stop';\r\n const result = handler({\r\n kind: 'timeout',\r\n used,\r\n limit,\r\n requestDecision: () => {\r\n // No listener wired (bare /spawn, no director) → nobody can grant an\r\n // extension, so resolve to 'stop' immediately. Without this the emit\r\n // below goes unanswered and the run parks on the 60 s fallback timer\r\n // before stopping — the deadline must reap promptly instead. Mirrors\r\n // SubagentBudget._busRequestDecision so both agree on the default.\r\n if (!budget._events?.hasListenerFor('budget.threshold_reached')) {\r\n return Promise.resolve<'stop' | { extend: { timeoutMs?: number | undefined } }>('stop');\r\n }\r\n return new Promise<'stop' | { extend: { timeoutMs?: number | undefined } }>((resolveDecision) => {\r\n let settled = false;\r\n const resolve = (d: 'stop' | { extend: { timeoutMs?: number | undefined } }) => {\r\n if (settled) return;\r\n settled = true;\r\n resolveDecision(d);\r\n };\r\n const fallback = setTimeout(() => resolve('stop'), DECISION_TIMEOUT_MS);\r\n budget._events?.emit('budget.threshold_reached', {\r\n kind: 'timeout',\r\n used,\r\n limit,\r\n // Informational: the budget's own decision deadline. Listeners may use\r\n // this to display a countdown. The coordinator does NOT enforce it —\r\n // it is the budget's own `setTimeout(fallback)` that races against\r\n // the listener's `extend()`/`deny()` call to guarantee progress.\r\n timeoutMs: DECISION_TIMEOUT_MS,\r\n // deny() wins over a same-dispatch extend(): defer the grant a\r\n // microtask so a synchronous deny in the same emit pre-empts it\r\n // (a listener that both grants and denies, or two listeners\r\n // disagreeing, resolves as a stop). Async grants still resolve.\r\n extend: (extra) => {\r\n clearTimeout(fallback);\r\n queueMicrotask(() => resolve({ extend: extra }));\r\n },\r\n deny: () => {\r\n clearTimeout(fallback);\r\n resolve('stop');\r\n },\r\n });\r\n });\r\n },\r\n });\r\n return typeof result === 'string' ? result : await result;\r\n };\r\n\r\n const onTick = async () => {\r\n const elapsed = Date.now() - start;\r\n const wallLimit =\r\n initialTimeoutMs === undefined ? undefined : budget.limits.timeoutMs ?? initialTimeoutMs;\r\n const idleLimit =\r\n idleLimitMs === undefined ? undefined : budget.limits.idleTimeoutMs ?? idleLimitMs;\r\n const wallExceeded = wallLimit !== undefined && elapsed >= wallLimit;\r\n const idleExceeded = idleLimit !== undefined && budget.idleMs() >= idleLimit;\r\n\r\n // Idle stall with no wall-clock cap also due: a genuinely hung agent\r\n // (no activity for the whole window). Reap it directly — idle is NOT\r\n // negotiable; the point of the default is to free a stuck slot. We still\r\n // emit the threshold event first so observers (director / monitor) can\r\n // record the reap, but any extension a listener offers is ignored.\r\n if (idleExceeded && !wallExceeded) {\r\n budget._events?.emit('budget.threshold_reached', {\r\n kind: 'idle_timeout',\r\n used: budget.idleMs(),\r\n limit: idleLimit ?? 0,\r\n timeoutMs: DECISION_TIMEOUT_MS,\r\n extend: () => {},\r\n deny: () => {},\r\n });\r\n // An idle stall is a passive TIMEOUT (the agent hung), not an explicit\r\n // coordinator stop — surface it as 'timeout' regardless of any\r\n // listener. (Contrast the wall-clock deadline below, where an explicit\r\n // listener deny is a deliberate stop → 'stopped'.)\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(new BudgetExceededError('idle_timeout', idleLimit ?? 0, budget.idleMs()));\r\n return;\r\n }\r\n\r\n // PROACTIVE pre-empt: we've passed TIMEOUT_PREEMPT_FRACTION of the wall\r\n // window but NOT the deadline itself. Negotiate an extension now, while\r\n // the agent is still under its limit, so a progressing subagent gets its\r\n // ceiling raised and never enters a timed-out state. Heartbeat-gated on\r\n // the granting side (director / attachAutoExtend): no progress ⇒ decline,\r\n // and we fall through to the real-deadline behaviour below at the cap.\r\n // Asked at most once per window (preemptState === ACTIVE).\r\n if (\r\n wallLimit !== undefined &&\r\n !wallExceeded &&\r\n budget.onThreshold &&\r\n preemptState === PreemptState.ACTIVE &&\r\n elapsed >= wallLimit * preemptFraction\r\n ) {\r\n // Heartbeat gate: only negotiate a pre-empt extension if the agent has\r\n // made progress (a tool call / iteration / streamed output) SINCE the\r\n // last grant. A stalled agent — no new activity since its last\r\n // extension — gets no further pre-empt; we lock and let the real\r\n // deadline reap it. `activityTs` is the wall-clock time of the last\r\n // activity (now − idleMs). Without this gate an always-granting\r\n // listener would extend a wedged agent forever and the deadline would\r\n // never fire (T1).\r\n const activityTs = Date.now() - budget.idleMs();\r\n if (activityTs <= lastGrantActivityTs) {\r\n preemptState = PreemptState.LOCKED;\r\n preemptedCeiling = wallLimit;\r\n scheduleNext();\r\n return;\r\n }\r\n // C1 fix: register the watchdog as active BEFORE calling onThreshold so\r\n // that any concurrent tool.progress → checkTimeout() path sees the flag\r\n // and skips its own wall-clock emission. Cleared on every exit path so\r\n // checkTimeout() resumes normal operation after negotiation completes.\r\n budget.setWatchdogNegotiation(wallLimit);\r\n try {\r\n const decision = await negotiateTimeout(elapsed, wallLimit);\r\n if (typeof decision !== 'string' && decision.extend.timeoutMs !== undefined) {\r\n // Granted ahead of the deadline — raise the ceiling and open a\r\n // fresh window (a later pre-empt becomes eligible again, but only\r\n // if there is fresh activity by then — see the heartbeat gate).\r\n budget.patchLimits({ timeoutMs: decision.extend.timeoutMs });\r\n lastGrantActivityTs = Date.now() - budget.idleMs();\r\n preemptState = PreemptState.ACTIVE;\r\n preemptedCeiling = null;\r\n } else {\r\n // Declined proactively (no progress / no listener). Don't re-ask\r\n // until the real deadline — the wallExceeded path below handles the\r\n // at-cap behaviour (warn+continue or hard stop).\r\n preemptState = PreemptState.LOCKED;\r\n preemptedCeiling = wallLimit;\r\n }\r\n } catch {\r\n preemptState = PreemptState.LOCKED;\r\n preemptedCeiling = wallLimit;\r\n } finally {\r\n budget.clearWatchdogNegotiation();\r\n }\r\n scheduleNext();\r\n return;\r\n }\r\n\r\n // Neither deadline actually tripped — we woke early because activity\r\n // pushed the idle deadline out (or a pre-empt was just resolved).\r\n // Re-arm for the new soonest deadline.\r\n if (!wallExceeded) {\r\n scheduleNext();\r\n return;\r\n }\r\n\r\n // Wall-clock cap hit. This is opt-in and keeps the original\r\n // soft-warning behaviour: negotiate an extension rather than\r\n // hard-killing a task solely for running long.\r\n const limit = wallLimit ?? 0;\r\n // Without an onThreshold handler the original behaviour stands:\r\n // abort the signal and hard-reject. This preserves the contract\r\n // for direct SubagentBudget consumers that don't wire negotiation.\r\n if (!budget.onThreshold) {\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(new BudgetExceededError('timeout', limit, elapsed));\r\n return;\r\n }\r\n // C1 fix: same guard as the pre-empt branch — register before onThreshold\r\n // so concurrent tool.progress → checkTimeout() skips its wall-clock emission.\r\n budget.setWatchdogNegotiation(limit);\r\n try {\r\n const decision = await negotiateTimeout(elapsed, limit);\r\n if (decision === 'throw') {\r\n // 'throw' is an explicit signal from the handler: end now rather\r\n // than silently keeping the subagent alive past its deadline.\r\n terminate('timeout', limit, elapsed);\r\n return;\r\n }\r\n if (decision === 'continue') {\r\n // 'continue' — timeout denied but coordinator wants the agent to keep\r\n // running. Re-arm for a full wall window so we ask again later.\r\n // This makes wall-clock timeout a pure warning event: the subagent\r\n // keeps running until it naturally finishes, the next deadline fires,\r\n // or the user stops it.\r\n //\r\n // IMPORTANT: we must lock the pre-empt arm (set preemptState =\r\n // LOCKED) so it does NOT fire again until the ceiling changes.\r\n // The ceiling only changes if a future negotiation returns 'extend'\r\n // and patches budget.limits.timeoutMs. Without the lock, the\r\n // pre-empt would re-arm for ~1 s (Math.max(1_000, limit)) and\r\n // immediately fire again at elapsed > wallLimit × 0.85, creating\r\n // a ping-pong loop of spurious budget.threshold_reached events.\r\n preemptState = PreemptState.LOCKED;\r\n preemptedCeiling = wallLimit;\r\n armFor(Math.max(1_000, limit));\r\n return;\r\n }\r\n if (decision === 'stop') {\r\n // 'stop' — coordinator explicitly denied the extension and wants\r\n // the agent to end. This is a terminal decision: end now.\r\n terminate('timeout', limit, elapsed);\r\n return;\r\n }\r\n // 'extend' — patch budget and re-arm for the new remainder.\r\n if (decision.extend.timeoutMs !== undefined) {\r\n budget.patchLimits({ timeoutMs: decision.extend.timeoutMs });\r\n lastGrantActivityTs = Date.now() - budget.idleMs();\r\n preemptState = PreemptState.ACTIVE;\r\n preemptedCeiling = null;\r\n scheduleNext();\r\n return;\r\n }\r\n // No timeoutMs in extend — nothing to grant → end.\r\n terminate('timeout', limit, elapsed);\r\n return;\r\n } catch (err) {\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(\r\n err instanceof BudgetExceededError\r\n ? err\r\n : new BudgetExceededError('timeout', limit, elapsed),\r\n );\r\n return;\r\n } finally {\r\n // Always clear the watchdog flag so checkTimeout() resumes wall-clock\r\n // checking on the next tool.progress event.\r\n budget.clearWatchdogNegotiation();\r\n }\r\n };\r\n // First arm: whichever of the idle window / pre-empt point / wall cap is sooner.\r\n scheduleNext();\r\n });\r\n\r\n try {\r\n return await Promise.race([runner(task, ctx), timeoutPromise]);\r\n } finally {\r\n if (timer) clearTimeout(timer);\r\n }\r\n }\r\n\r\n private recordCompletion(result: TaskResult): void {\r\n this.completedResults.push(result);\r\n // Trim oldest entries when the cap is exceeded — keep the most recent\r\n // results so /fleet and roll_up still have data to work with.\r\n if (this.completedResults.length > DefaultMultiAgentCoordinator.MAX_COMPLETED_RESULTS) {\r\n this.completedResults.splice(\r\n 0,\r\n this.completedResults.length - DefaultMultiAgentCoordinator.MAX_COMPLETED_RESULTS,\r\n );\r\n }\r\n this.totalIterations += result.iterations;\r\n if (this.inFlight > 0) {\r\n this.inFlight--;\r\n } else if (this.runner) {\r\n // Runner-driven path completed without an outstanding inFlight slot —\r\n // shouldn't happen unless completeTask was called externally.\r\n this.emit('warning', {\r\n type: 'inFlight_underflow',\r\n taskId: result.taskId,\r\n subagentId: result.subagentId,\r\n });\r\n return;\r\n }\r\n\r\n const subagent = this.subagents.get(result.subagentId);\r\n if (subagent && subagent.status !== 'stopped') {\r\n const failed = result.status === 'failed' || result.status === 'timeout';\r\n // Synchronously reset the worker to idle after either a clean\r\n // finish or a transient failure. The previous code parked the\r\n // subagent in 'error' and used a `queueMicrotask` to flip it\r\n // back to 'idle' — that opened a window where `assign()` +\r\n // `tryDispatchNext` could race the microtask, leaving the\r\n // worker stuck in 'running' state while actually idle. By\r\n // resetting now, no async gap can leak the state machine.\r\n subagent.status = 'idle';\r\n void failed; // kept for future telemetry hooks\r\n subagent.currentTask = undefined;\r\n // If the run aborted (timeout or explicit stop), the subagent's\r\n // signal is now permanently aborted — recycling the controller lets\r\n // the next dispatched task start with a fresh cancellation scope.\r\n if (subagent.abortController.signal.aborted) {\r\n subagent.abortController = new AbortController();\r\n }\r\n\r\n this.fleetBus?.emit({\r\n subagentId: result.subagentId,\r\n ts: Date.now(),\r\n type: 'subagent.idle',\r\n payload: { subagentId: result.subagentId },\r\n });\r\n }\r\n // Clear the terminating flag now that the worker has a terminal\r\n // TaskResult on record. Subsequent stop() calls re-add it; new\r\n // assign() calls can flow normally.\r\n this.terminating.delete(result.subagentId);\r\n\r\n this.emit('task.completed', {\r\n task: subagent?.context.tasks.find((t) => t.id === result.taskId) ?? { id: result.taskId },\r\n result,\r\n });\r\n\r\n this.fleetBus?.emit({\r\n subagentId: result.subagentId,\r\n taskId: result.taskId,\r\n ts: Date.now(),\r\n type: 'subagent.completed',\r\n payload: {\r\n subagentId: result.subagentId,\r\n taskId: result.taskId,\r\n status: result.status,\r\n iterations: result.iterations,\r\n toolCalls: result.toolCalls,\r\n durationMs: result.durationMs,\r\n },\r\n });\r\n\r\n this.tryDispatchNext();\r\n\r\n // Emit after tryDispatchNext so the stats reflect the post-dispatch\r\n // state (either a new running subagent, or idle if the queue is drained).\r\n this.emitCoordinatorStats();\r\n\r\n if (this.isDone()) {\r\n this.emit('done', {\r\n results: this.completedResults,\r\n totalIterations: this.totalIterations,\r\n });\r\n }\r\n }\r\n\r\n /**\r\n * Stop a subagent and remove it from the coordinator. Releases all\r\n * associated resources (AbortController, context, budget state).\r\n * The subagent entry is deleted so the id can be reused in a future spawn.\r\n */\r\n async remove(subagentId: string): Promise<void> {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) return;\r\n\r\n // Gracefully stop first — same logic as stop() but don't block on it.\r\n if (subagent.status === 'running' || subagent.status === 'idle') {\r\n this.terminating.add(subagentId);\r\n subagent.abortController.abort();\r\n subagent.status = 'stopped';\r\n }\r\n\r\n // Release all resources associated with this subagent.\r\n this.subagents.delete(subagentId);\r\n this.terminating.delete(subagentId);\r\n // Free the nickname slot so the same name can be reused by a future spawn.\r\n const nicknameKey = this.subagentNicknames.get(subagentId);\r\n if (nicknameKey) {\r\n this.usedNicknames.delete(nicknameKey);\r\n this.subagentNicknames.delete(subagentId);\r\n }\r\n\r\n // Clean up any pending tasks assigned to this subagent — emit synthetic\r\n // 'stopped' completions so callers awaiting them via awaitTasks() unblock\r\n // instead of hanging forever. Without this, a task queued for a removed\r\n // subagent would leave its waiter permanently unresolved.\r\n const orphaned = this.pendingTasks.filter((t) => t.subagentId === subagentId);\r\n this.pendingTasks = this.pendingTasks.filter((t) => t.subagentId !== subagentId);\r\n for (const t of orphaned) {\r\n // Inline-emit, NOT recordCompletion: these are PENDING tasks that were\r\n // never counted in inFlight. Routing them through recordCompletion would\r\n // decrement inFlight on behalf of a still-running task and suppress that\r\n // task's own completion via the underflow guard, hanging its awaiter.\r\n this.emitPendingAborted(\r\n t,\r\n `Subagent \"${subagentId}\" was removed while task \"${t.id}\" was pending`,\r\n );\r\n }\r\n\r\n this.fleetBus?.emit({\r\n subagentId,\r\n ts: Date.now(),\r\n type: 'subagent.removed',\r\n payload: { subagentId },\r\n });\r\n\r\n this.emitCoordinatorStats();\r\n }\r\n\r\n private isDone(): boolean {\r\n if (this.config.doneCondition.type === 'all_tasks_done') {\r\n return this.pendingTasks.length === 0 && this.inFlight === 0;\r\n }\r\n if (\r\n this.config.doneCondition.maxIterations !== undefined &&\r\n this.totalIterations >= this.config.doneCondition.maxIterations\r\n ) {\r\n return true;\r\n }\r\n return false;\r\n }\r\n}\r\n\r\n/**\r\n * Map any raw exception thrown out of a subagent's runner into a\r\n * structured `SubagentError`. Delegates to the shared classifier.\r\n * Re-exported for backward compatibility.\r\n */\r\nexport { classifySubagentError } from './coordinator/error-classifier.js';\r\n","import { expectDefined } from '../utils/expect-defined.js';\nimport { toErrorMessage } from '../utils/error.js';\nimport { randomUUID } from 'node:crypto';\nimport type { Agent } from '../core/agent.js';\nimport type { AgentFactory } from '../coordination/agent-subagent-runner.js';\nimport { makeAgentSubagentRunner, withDisabledToolFiltering } from '../coordination/agent-subagent-runner.js';\nimport { dispatchAgent } from '../coordination/dispatcher.js';\nimport type { DispatchClassifier, DispatchResult } from '../coordination/dispatcher.js';\nimport type { EventBus } from '../kernel/events.js';\nimport type { SubagentConfig, TaskResult } from '../types/multi-agent.js';\nimport type { JournalEntry, GoalFile } from '../storage/goal-store.js';\nimport { loadGoal, saveGoal, appendJournal, goalFilePath } from '../storage/goal-store.js';\nimport type { Compactor } from '../types/compactor.js';\nimport { DefaultMultiAgentCoordinator } from '../coordination/multi-agent-coordinator.js';\nimport type { MultiAgentConfig } from '../types/multi-agent.js';\nimport { sleep } from '../utils/sleep.js';\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type ParallelEngineState = 'idle' | 'running' | 'stopped';\n\nexport type ParallelIterationStage =\n | { phase: 'idle' }\n | { phase: 'decompose' }\n | { phase: 'fanout'; slots: number }\n | { phase: 'await'; taskIds: string[] }\n | {\n phase: 'aggregate';\n successCount: number;\n total: number;\n goalComplete: boolean;\n }\n | { phase: 'sleep'; ms: number }\n | { phase: 'stopped' }\n | { phase: 'error'; message: string };\n\nexport interface ParallelEternalOptions {\n /** The coordinating agent — NOT a subagent. Owns container/tools/providers. */\n agent: Agent;\n /** Project root (used for goal.json path). */\n projectRoot: string;\n /**\n * Override the resolved goal.json path. Defaults to\n * `goalFilePath(projectRoot)` — the canonical per-project goal file under\n * `~/.wrongstack/projects/<slug>/`, shared with `/goal` and the TUI.\n * Primarily for tests that want an isolated goal file under a temp dir.\n */\n goalPath?: string | undefined;\n /**\n * Number of parallel subagent slots per tick.\n * Default: 4. Range 1–16; values >8 are for high-throughput machines.\n */\n parallelSlots?: number | undefined;\n /** Per-subagent default timeout in ms. Default: 300_000 (5 min). */\n iterationTimeoutMs?: number | undefined;\n onIteration?: (((entry: JournalEntry) => void)) | undefined;\n onError?: (err: Error | undefined, iteration: number) => void;\n /** Per-tick phase notifications for live UI/status updates. */\n onStage?: (((stage: ParallelIterationStage) => void)) | undefined;\n gitStatusReader?: ((() => Promise<string>)) | undefined;\n now?: ((() => Date)) | undefined;\n compactor?: Compactor | undefined;\n compactEveryNIterations?: number | undefined;\n aggressiveCompactRatio?: number | undefined;\n maxContextTokens?: number | undefined;\n /** Override the default agent factory (uses main agent if not provided). */\n subagentFactory?: AgentFactory | undefined;\n /**\n * Route each decomposed slot task to the best-fit catalog agent via the\n * smart dispatcher (heuristic keyword scoring). When enabled (default), each\n * slot spawns in-role — the role's budget tier applies and a persona line is\n * injected into the task — instead of as a faceless generic worker. Set\n * false to keep the legacy generic spawn.\n */\n dispatch?: boolean | undefined;\n /**\n * Optional LLM fallback for ambiguous tasks. Passed straight to\n * `dispatchAgent`; when omitted, routing is pure heuristic (instant, no\n * provider call — preferred for a continuously-ticking autonomous loop).\n */\n dispatchClassifier?: DispatchClassifier | undefined;\n /** Optional EventBus for emitting storage.* observability events from goal I/O. */\n events?: EventBus | undefined;\n}\n\nconst GOAL_COMPLETE_MARKER = /^\\s*\\[goal[_\\s-]?complete\\]\\s*$/im;\n\n// ---------------------------------------------------------------------------\n// ParallelEternalEngine\n// ---------------------------------------------------------------------------\n\n/**\n * Sense → Decide → Fan-out (4–8 parallel agents) → Aggregate → Loop.\n *\n * Each tick:\n * 1. Sense — load goal, todos, git status\n * 2. Decide — decompose goal into N parallel sub-tasks\n * 3. Fan-out — spawn N subagents simultaneously, await all\n * 4. Aggregate — write journal, update todos, check [GOAL_COMPLETE]\n * 5. Loop — continue until stop() or mission complete\n *\n * Uses DefaultMultiAgentCoordinator + AgentSubagentRunner for subagent lifecycle.\n */\nexport class ParallelEternalEngine {\n private state: ParallelEngineState = 'idle';\n private stopRequested = false;\n private iterationsSinceCompact = 0;\n private iterations = 0;\n private consecutiveFailures = 0;\n private readonly goalPath: string;\n private readonly slots: number;\n private readonly timeoutMs: number;\n private coordinator: DefaultMultiAgentCoordinator | null = null;\n private agentFactory: AgentFactory;\n private readonly dispatchEnabled: boolean;\n private readonly dispatchClassifier?: DispatchClassifier | undefined;\n\n constructor(private readonly opts: ParallelEternalOptions) {\n this.goalPath = opts.goalPath ?? goalFilePath(opts.projectRoot);\n this.slots = Math.min(16, Math.max(1, opts.parallelSlots ?? 4));\n this.timeoutMs = opts.iterationTimeoutMs ?? 300_000;\n this.dispatchEnabled = opts.dispatch !== false;\n this.dispatchClassifier = opts.dispatchClassifier;\n this.agentFactory =\n opts.subagentFactory ??\n (async (_config: SubagentConfig) => ({\n agent: this.opts.agent,\n events: this.opts.agent.events,\n }));\n }\n\n get currentState(): ParallelEngineState {\n return this.state;\n }\n\n /**\n * Get the underlying coordinator for stats/monitoring.\n */\n getCoordinator(): DefaultMultiAgentCoordinator | null {\n return this.coordinator;\n }\n\n stop(): void {\n this.stopRequested = true;\n void this.persistState('stopped').catch((err) => {\n console.error(JSON.stringify({\n level: 'error',\n event: 'engine.persist_state_failed',\n message: toErrorMessage(err),\n context: { expectedState: 'stopped' },\n timestamp: new Date().toISOString(),\n }));\n });\n this.state = 'stopped';\n }\n\n async prime(): Promise<void> {\n this.stopRequested = false;\n this.state = 'running';\n await this.persistState('running');\n }\n\n async run(): Promise<void> {\n this.state = 'running';\n await this.persistState('running');\n\n const config: MultiAgentConfig = {\n coordinatorId: `parallel-${randomUUID().slice(0, 8)}`,\n maxConcurrent: this.slots,\n doneCondition: { type: 'all_tasks_done' },\n };\n this.coordinator = new DefaultMultiAgentCoordinator(config);\n // Wrap factory with disabled tool filtering to prevent subagents from\n // using the delegate tool (or any other disabledTools in their config)\n const filteredFactory = withDisabledToolFiltering(this.agentFactory);\n const runner = makeAgentSubagentRunner({ factory: filteredFactory });\n this.coordinator.setRunner?.(runner);\n\n try {\n while (!this.stopRequested) {\n try {\n await this.runOneIteration();\n } catch (err) {\n this.consecutiveFailures++;\n this.opts.onError?.(\n err instanceof Error ? err : new Error(String(err)),\n this.consecutiveFailures,\n );\n await this.appendFailure(\n 'engine error',\n toErrorMessage(err),\n );\n }\n if (this.stopRequested) break;\n await sleep(2000);\n }\n } finally {\n this.state = 'stopped';\n await this.persistState('stopped').catch(() => {});\n }\n }\n\n /**\n * Execute one tick: decompose → fan-out → aggregate → compact.\n * Called by the REPL in its main loop (REPL drives, engine is stateless per tick).\n */\n async runOneIteration(): Promise<boolean> {\n const emit = (stage: ParallelIterationStage) => {\n this.opts.onStage?.(stage);\n };\n\n this.iterations++;\n\n const goal = await loadGoal(this.goalPath, this.opts.events);\n if (!goal) {\n this.stopRequested = true;\n emit({ phase: 'stopped' });\n return false;\n }\n if (goal.goalState !== 'active') {\n this.stopRequested = true;\n emit({ phase: 'stopped' });\n return false;\n }\n\n // Build coordinator on first tick.\n if (!this.coordinator) {\n const config: MultiAgentConfig = {\n coordinatorId: `parallel-${randomUUID().slice(0, 8)}`,\n maxConcurrent: this.slots,\n doneCondition: { type: 'all_tasks_done' },\n };\n this.coordinator = new DefaultMultiAgentCoordinator(config);\n // Wrap factory with disabled tool filtering to prevent subagents from\n // using the delegate tool (or any other disabledTools in their config)\n const filteredFactory = withDisabledToolFiltering(this.agentFactory);\n const runner = makeAgentSubagentRunner({ factory: filteredFactory });\n this.coordinator.setRunner?.(runner);\n }\n\n emit({ phase: 'decompose' });\n const tasks = await this.decomposeGoal(goal);\n if (!tasks || tasks.length === 0) {\n // Nothing to do this tick. The run() loop paces idle iterations itself\n // (see its sleep), so a single runOneIteration() must return promptly.\n emit({ phase: 'sleep', ms: 2000 });\n return false;\n }\n\n emit({ phase: 'fanout', slots: Math.min(this.slots, tasks.length) });\n const fanOut = await this.fanOut(goal, tasks);\n this.iterationsSinceCompact++;\n\n const successCount = fanOut.results.filter((r) => r.status === 'success').length;\n const status: JournalEntry['status'] = fanOut.goalComplete\n ? 'success'\n : fanOut.allSuccessful\n ? 'success'\n : 'failure';\n const note = [\n `${successCount}/${fanOut.results.length} subagents succeeded`,\n fanOut.goalComplete ? '[GOAL_COMPLETE]' : '',\n fanOut.partialOutput ? `Output: ${fanOut.partialOutput.slice(0, 120)}` : '',\n ]\n .filter(Boolean)\n .join(' | ');\n\n // Surface routing in the journal: \"role→task-snippet\" per slot so /goal\n // journal shows which agent handled what.\n const routeSummary =\n fanOut.routes.length > 0\n ? fanOut.routes\n .slice(0, 3)\n .map((r) => `${r.role}→${r.task.slice(0, 28)}`)\n .join(', ')\n : tasks.slice(0, 3).join(', ');\n await this.appendIterationEntry({\n source: 'parallel',\n task: `parallel:${tasks.length} slots — ${routeSummary}${tasks.length > 3 ? '...' : ''}`,\n status,\n note,\n });\n emit({\n phase: 'aggregate',\n successCount,\n total: fanOut.results.length,\n goalComplete: fanOut.goalComplete,\n });\n\n if (fanOut.goalComplete) {\n this.stopRequested = true;\n this.state = 'stopped';\n emit({ phase: 'stopped' });\n return true;\n }\n\n await this.maybeCompact();\n emit({ phase: 'sleep', ms: 2000 });\n return fanOut.allSuccessful;\n }\n\n // -------------------------------------------------------------------------\n // Fan-out\n // -------------------------------------------------------------------------\n\n private async fanOut(\n goal: GoalFile,\n tasks: string[],\n ): Promise<{\n results: TaskResult[];\n allSuccessful: boolean;\n goalComplete: boolean;\n partialOutput: string;\n routes: Array<{ slot: number; task: string; role: string; method: string }>;\n }> {\n const coordinator = expectDefined(this.coordinator);\n const slotCount = Math.min(this.slots, tasks.length);\n\n // Route each slot task to the best-fit catalog agent. Heuristic by default\n // (instant, no provider call); an injected classifier enables LLM fallback.\n // A dispatch failure for one slot is non-fatal — that slot stays generic.\n const routes: (DispatchResult | null)[] = this.dispatchEnabled\n ? await Promise.all(\n tasks\n .slice(0, slotCount)\n .map((t) =>\n dispatchAgent(t, { classifier: this.dispatchClassifier }).catch(() => null),\n ),\n )\n : [];\n\n const recentJournal = goal.journal\n .slice(-5)\n .map(\n (e) =>\n ` #${e.iteration} [${e.status}] ${e.task}${e.note ? ` — ${e.note.slice(0, 80)}` : ''}`,\n )\n .join('\\n');\n\n const directivePreamble = [\n '═══ ETERNAL AUTONOMY — parallel task slot ═══',\n '',\n `Mission: ${goal.goal}`,\n `Total parallel slots: ${slotCount}`,\n '',\n recentJournal ? `Recent journal (last 5):\\n${recentJournal}` : 'No prior iterations.',\n '',\n '── EXECUTION PROTOCOL ──',\n '• Execute the assigned task end-to-end using multiple tool calls.',\n '• Emit `[done]` on its own line when the task is complete.',\n '• Do not ask before routine in-project tool use — YOLO is active for normal project work.',\n '• If a destructive-gated confirmation appears, wait for the permission flow.',\n '• If the overall Mission is accomplished, emit `[GOAL_COMPLETE]` followed by a verification recipe.',\n '• Keep output concise — summarize findings, do not transcribe files.',\n ].join('\\n');\n\n const taskIds: string[] = [];\n const subagentIds: string[] = [];\n const routeInfo: Array<{ slot: number; task: string; role: string; method: string }> = [];\n\n const spawnPromises: Array<Promise<void>> = [];\n for (let i = 0; i < slotCount; i++) {\n const task = expectDefined(tasks[i]);\n const route = routes[i] ?? null;\n const subagentId = `parallel-${this.iterations}-${i}`;\n const taskId = randomUUID();\n\n // Persona injection — works even with the default factory (which reuses\n // the shared main agent and ignores config.prompt/tools), so the agent\n // adopts the routed role's stance for this slot.\n const personaLine = route\n ? `Acting agent: ${route.definition.config.name} — ${route.definition.capability.summary}\\n`\n : '';\n const spec = {\n id: taskId,\n description: `${directivePreamble}\\n\\n── SLOT ${i + 1}/${slotCount} ──\\n${personaLine}Task: ${task}\\n`,\n subagentId,\n };\n\n routeInfo.push({\n slot: i,\n task,\n role: route?.role ?? 'generic',\n method: route?.method ?? 'none',\n });\n\n spawnPromises.push(\n (async () => {\n try {\n // Spawn in-role when routed: `role` lets applyRosterBudget resolve the\n // role's budget tier; name/tools/systemPromptOverride specialize the\n // worker if a real per-role factory is wired (forward-compatible).\n await coordinator.spawn(\n route\n ? {\n id: subagentId,\n name: route.definition.config.name,\n role: route.role,\n tools: route.definition.config.tools,\n systemPromptOverride: route.definition.config.prompt,\n timeoutMs: this.timeoutMs,\n // Disable delegation — subagents are leaf workers, not orchestrators\n disabledTools: ['delegate'],\n }\n : {\n id: subagentId,\n name: `slot-${subagentId.slice(-6)}`,\n // Let the coordinator apply its default budget (roster or generic).\n // Hardcoding low limits here defeats the x10 budget improvement.\n timeoutMs: this.timeoutMs,\n // Disable delegation — subagents are leaf workers, not orchestrators\n disabledTools: ['delegate'],\n },\n );\n subagentIds.push(subagentId);\n taskIds.push(taskId);\n await coordinator.assign(spec);\n } catch {\n // non-fatal: individual spawn failure doesn't block other slots\n }\n })(),\n );\n }\n await Promise.all(spawnPromises);\n\n if (taskIds.length === 0) {\n return {\n results: [],\n allSuccessful: false,\n goalComplete: false,\n partialOutput: '',\n routes: routeInfo,\n };\n }\n\n this.opts.onStage?.({ phase: 'await', taskIds: [...taskIds] });\n\n let results: TaskResult[] = [];\n try {\n // Wait up to 2 hours for subagents to complete. This should cover\n // most subagent tasks since the roster budgets go up to 10 hours.\n // The outer eternal loop manages actual iteration limits.\n const ctrl = new AbortController();\n const timer = setTimeout(() => ctrl.abort(), Math.max(this.timeoutMs * 2, 7200_000));\n try {\n results = await coordinator.awaitTasks(taskIds);\n } finally {\n clearTimeout(timer);\n }\n } catch {\n results = coordinator.results().slice(-taskIds.length);\n }\n\n // Free each per-tick subagent now that its task has resolved. Without this,\n // an eternal-parallel run accumulates dead subagent entries (and their\n // nickname slots) in the coordinator forever — a slow but unbounded leak\n // over multi-day loops. remove() is idempotent and non-throwing per id.\n await Promise.allSettled(subagentIds.map((id) => coordinator.remove(id)));\n\n const allSuccessful = results.length > 0 && results.every((r) => r.status === 'success');\n const goalComplete = results.some(\n (r) =>\n r.status === 'success' &&\n typeof r.result === 'string' &&\n GOAL_COMPLETE_MARKER.test(r.result),\n );\n const partialOutput = results\n .map((r) => (typeof r.result === 'string' ? r.result : ''))\n .filter(Boolean)\n .join('\\n\\n');\n\n return { results, allSuccessful, goalComplete, partialOutput, routes: routeInfo };\n }\n\n // -------------------------------------------------------------------------\n // Goal decomposition\n // -------------------------------------------------------------------------\n\n private async decomposeGoal(goal: GoalFile): Promise<string[] | null> {\n // Strategy 1: pending todos as sub-tasks\n const todos = this.opts.agent.ctx?.todos;\n const tasks: string[] = [];\n if (Array.isArray(todos)) {\n const pending = todos.filter((t) => t.status === 'pending').slice(0, this.slots);\n for (const t of pending) {\n tasks.push(`[todo] ${t.content}`);\n }\n }\n\n // Strategy 2: git dirty files\n if (tasks.length < this.slots) {\n try {\n const gitStatus = await (this.opts.gitStatusReader?.() ?? this.readGitStatus());\n const dirty = gitStatus.trim();\n if (dirty) {\n const lines = dirty.split('\\n').slice(0, this.slots - tasks.length);\n for (const line of lines) {\n const file = line.replace(/^[ MADRUC?]{2}\\s*/, '').trim();\n if (file) tasks.push(`[git] inspect and fix: ${file}`);\n }\n }\n } catch {\n // ignore\n }\n }\n\n // Strategy 3: leader-brainstormed sub-tasks for remaining slots\n if (tasks.length < this.slots) {\n const remaining = this.slots - tasks.length;\n const brainstormed = await this.brainstormSubtasks(goal, remaining);\n tasks.push(...brainstormed);\n }\n\n return tasks.length > 0 ? tasks.slice(0, this.slots) : null;\n }\n\n private async readGitStatus(): Promise<string> {\n const { execFile } = await import('node:child_process');\n const { promisify } = await import('node:util');\n const execFileP = promisify(execFile);\n const { stdout } = await execFileP('git', ['status', '--porcelain'], {\n cwd: this.opts.projectRoot,\n timeout: 5_000,\n });\n return stdout;\n }\n\n private async brainstormSubtasks(goal: GoalFile, count: number): Promise<string[]> {\n const lastFew = goal.journal\n .slice(-5)\n .map((e) => ` - [${e.status}] ${e.task}`)\n .join('\\n');\n const directive = [\n `Decompose this goal into exactly ${count} independent sub-tasks for parallel execution.`,\n '',\n `Goal: ${goal.goal}`,\n '',\n lastFew ? `Recent:\\n${lastFew}` : 'No prior iterations.',\n '',\n `Output exactly ${count} tasks, one per line, under 120 chars each.`,\n 'Format: TASK-1 | TASK-2 | ... (pipe-separated, no numbering, no preamble).',\n 'Each task must be independently actionable with no shared dependencies.',\n ].join('\\n');\n\n try {\n const ctrl = new AbortController();\n const timer = setTimeout(() => ctrl.abort(), 60_000);\n try {\n const result = await this.opts.agent.run([{ type: 'text' as const, text: directive }], {\n signal: ctrl.signal,\n maxIterations: 1,\n });\n if (result.status !== 'done') return [];\n const text = (result.finalText ?? '').trim();\n if (!text) return [];\n const tasks = text\n .split('|')\n .map((t) => t.trim())\n .filter((t) => t.length > 10 && t.length < 240);\n return tasks.slice(0, count);\n } finally {\n clearTimeout(timer);\n }\n } catch (err) {\n // The leader agent failed to brainstorm. Surface it to onError so the\n // failure is visible, but keep the loop alive (return no tasks — the\n // next tick retries) rather than crashing the autonomous engine.\n this.opts.onError?.(\n err instanceof Error ? err : new Error(String(err)),\n this.consecutiveFailures,\n );\n return [];\n }\n }\n\n // -------------------------------------------------------------------------\n // Compaction\n // -------------------------------------------------------------------------\n\n private async maybeCompact(): Promise<void> {\n const compactor = this.opts.compactor;\n if (!compactor) return;\n const ctx = this.opts.agent.ctx;\n if (!ctx) return;\n\n const shouldRun = this.iterationsSinceCompact >= (this.opts.compactEveryNIterations ?? 25);\n if (!shouldRun) return;\n\n const report = await compactor.compact(ctx, { aggressive: false });\n this.iterationsSinceCompact = 0;\n await this.appendIterationEntry({\n source: 'manual',\n task: 'compaction (cadence)',\n status: 'success',\n note: `saved ~${report.before - report.after} tokens`,\n });\n }\n\n // -------------------------------------------------------------------------\n // Helpers\n // -------------------------------------------------------------------------\n\n private async appendIterationEntry(entry: Omit<JournalEntry, 'iteration' | 'at'>): Promise<void> {\n const current = await loadGoal(this.goalPath, this.opts.events);\n if (!current) return;\n const updated = appendJournal(current, entry);\n await saveGoal(this.goalPath, updated, this.opts.events);\n const entryWithMeta: JournalEntry = {\n at: (this.opts.now?.() ?? new Date()).toISOString(),\n iteration: updated.iterations,\n ...entry,\n };\n this.opts.onIteration?.(entryWithMeta);\n }\n\n private async appendFailure(task: string, note: string): Promise<void> {\n await this.appendIterationEntry({ source: 'manual', task, status: 'failure', note });\n }\n\n private async persistState(state: GoalFile['engineState']): Promise<void> {\n const current = await loadGoal(this.goalPath, this.opts.events);\n if (!current) return;\n if (current.engineState === state) return;\n await saveGoal(this.goalPath, { ...current, engineState: state }, this.opts.events);\n }\n}\n","/**\n * System-prompt contributor that surfaces eternal-autonomy state to the\n * model on every turn.\n *\n * Why this exists: when the engine drives a long-running loop, the\n * per-iteration directive carries the rules. But the directive is a USER\n * message — it scrolls out of working memory after a few compactions and\n * the model forgets it's in autonomy mode (forgets `[GOAL_COMPLETE]`,\n * forgets the todo-state protocol, forgets the no-confirmation rule).\n * Injecting the same anchor as a CACHED system-prompt block solves that\n * — the rules sit next to the identity layer and survive compactions.\n *\n * Block is tagged `ephemeral` so its content (journal tail, iteration\n * counter) changes each turn without invalidating the upstream prefix\n * cache.\n */\n\nimport type { TextBlock } from '../types/blocks.js';\nimport type { SystemPromptContributor } from '../types/system-prompt-contributor.js';\nimport { loadGoal } from '../storage/goal-store.js';\n\nexport interface AutonomyPromptContributorOptions {\n /** Absolute path to the project's `goal.json`. */\n goalPath: string;\n /**\n * Gating function. The contributor consults this on every build and\n * returns an empty array when `false` — without this, the block would\n * leak into interactive runs that happen to have a goal on disk and\n * teach the model loop-control markers it shouldn't emit.\n *\n * Typical wiring: enable while `eternal` or `eternal-parallel` autonomy is active.\n */\n enabled: () => boolean;\n /** Number of journal entries to include in the recent-tail block. Default 5. */\n journalTailSize?: number | undefined;\n}\n\n/**\n * Build a contributor that renders the autonomy-state system block.\n * Returns `[]` when disabled, no goal exists, or the goal has been\n * completed/abandoned — all silent fast-paths.\n */\nexport function makeAutonomyPromptContributor(\n opts: AutonomyPromptContributorOptions,\n): SystemPromptContributor {\n return async (ctx): Promise<TextBlock[]> => {\n // Subagents run a single scoped task and don't drive the engine's\n // outer loop — they have no business emitting `[GOAL_COMPLETE]` or\n // marking todos. Skip the block entirely for subagent prompt builds,\n // mirroring how the active-plan layer is suppressed.\n if (ctx.subagent) return [];\n if (!opts.enabled()) return [];\n\n let goal: Awaited<ReturnType<typeof loadGoal>>;\n try {\n goal = await loadGoal(opts.goalPath);\n } catch {\n return [];\n }\n if (!goal) return [];\n\n // `active` is the default for legacy goal files without the field.\n const missionState = goal.goalState ?? 'active';\n if (missionState !== 'active') return [];\n\n const tailSize = opts.journalTailSize ?? 5;\n const journalTail = goal.journal.slice(-tailSize).map((e) => {\n const note = e.note ? ` — ${e.note.slice(0, 80)}` : '';\n return ` #${e.iteration} [${e.status}] ${e.task}${note}`;\n });\n\n const text = [\n '## ETERNAL AUTONOMY — active mission',\n '',\n 'You are inside a long-running autonomous loop. The user is asleep',\n 'and is not available to confirm decisions. Each turn you receive a',\n 'directive describing one concrete sub-task that advances the mission.',\n '',\n `Mission: ${goal.goal}`,\n `Iteration: #${goal.iterations}`,\n journalTail.length > 0\n ? `Recent journal (last ${journalTail.length}):\\n${journalTail.join('\\n')}`\n : 'Recent journal: (none — this is the first iteration)',\n '',\n '### Loop control markers',\n 'Emit these on their own line in your final text — case-insensitive,',\n 'whitespace-tolerant, but they must occupy the entire line:',\n '- `[continue]` — chain to the next internal step without returning.',\n '- `[done]` — the current sub-task is finished; return to the engine.',\n '- `[GOAL_COMPLETE]` — emit ONLY when the OVERALL mission is',\n ' verifiably done. Must be followed by a one-paragraph verification',\n ' recipe (artifact path, test command, or 10-second reproduction).',\n ' The engine halts on this marker — false positives waste real',\n ' human time. If unsure, emit `[done]` and let the next iteration',\n ' decide.',\n '',\n '### Operating principles',\n '- YOLO is active for normal project work. Proceed with routine',\n ' in-project tool use without pre-confirming; pick the best path and execute it.',\n ' If the permission system raises a destructive-gated confirmation, wait',\n ' for that flow instead of trying to bypass it.',\n '- Use tools freely; multiple calls per turn are normal and expected.',\n '- When working on a todo, mark it `in_progress` via the todos tool',\n ' before tool work and `completed` (or `cancelled` with a reason)',\n ' when done. The loop reads todo state between iterations.',\n \"- If an approach fails twice in a row, pivot. Don't grind on the\",\n ' same wall — try a different angle, file a cancel on the todo, or',\n ' surface the obstacle via `[done]` and let the next iteration',\n ' re-plan.',\n ].join('\\n');\n\n return [\n {\n type: 'text',\n text,\n cache_control: { type: 'ephemeral' },\n },\n ];\n };\n}\n","/**\n * `/goal <description>` preamble — the \"no force can stop this\" mode.\n *\n * Unlike STEERING (which redirects mid-flight), GOAL is a contract:\n * the user hands over a problem, the agent commits to verifiably\n * finishing it, and every iteration re-reads this preamble from the\n * conversation history. The hardening is entirely prompt-level —\n * the system has already removed implicit budget caps, so this\n * preamble's job is to remove the MODEL's tendency to hedge, ask\n * permission, or declare premature success.\n *\n * The four sections are intentional:\n * 1. AUTHORITY — explicit grant of unbounded fan-out + model\n * switching. Without this the model self-throttles (\"I shouldn't\n * spawn too many…\") even when budgets are unlimited.\n * 2. DONE — concrete bar for completion. Forces a verifiable\n * artifact (test passing, file written, bug re-run clean).\n * Without this the model returns \"I believe it's fixed\" and\n * counts that as done.\n * 3. NOT DONE — explicit anti-patterns. Each item is something we\n * saw real agents do as a \"completion\" that wasn't.\n * 4. PERSISTENCE — three-angle rule for blockers. Stops the model\n * from giving up on the first tool failure.\n *\n * Located in @wrongstack/core (rather than @wrongstack/tui) so headless\n * callers and the WebUI can issue `/goal set` without dragging the TUI\n * package in. The tui re-exports this for backward compatibility.\n */\nexport function buildGoalPreamble(goal: string, deliverables?: string[]): string {\n const deliverableBlock = deliverables && deliverables.length > 0\n ? [\n '',\n 'CONCRETE DELIVERABLES (check these off as you go):',\n ...deliverables.map((d, i) => ` ${i + 1}. ${d}`),\n '',\n 'After EACH iteration, estimate your completion percentage (0–100)',\n 'against this deliverable list. Output it as:',\n ' [PROGRESS: N%] — <1-sentence status>',\n 'The eternal engine reads this to update the progress bar.',\n ].join('\\n')\n : '';\n\n return [\n '[GOAL — LOCKED IN. You will work on this until it is verifiably done.',\n 'The user granted you full autonomy. Read these constraints once, then act.',\n '',\n 'YOUR GOAL:',\n '---',\n goal,\n '---',\n deliverableBlock,\n '',\n 'AUTHORITY YOU HAVE:',\n '- Spawn as many subagents as the work needs (delegate / spawn_subagent).',\n ' Parallel + recursive fan-out are both fine. There is no spawn budget.',\n '- Use any provider/model per subagent — pick the right tool for each',\n ' piece of work. Heavy reasoning model for planning, fast model for',\n ' batch work, specialist model for domain code.',\n '- Run unlimited tool calls and iterations. There is NO hidden budget.',\n ' The Agent loop auto-extends every 100 iterations forever.',\n '- Retry failed tools with different inputs, alternative paths, fresh',\n ' subagents. Switch providers mid-run if one is rate-limited.',\n '- Re-plan freely when an approach hits a dead end. You are not obliged',\n ' to stick with the first plan you proposed.',\n '',\n 'WHAT \"DONE\" MEANS — non-negotiable:',\n '- You can name a concrete artifact (a passing test, a written file at',\n ' a specific path, a fixed bug verified by re-running the failing case,',\n ' a clean grep that previously had matches).',\n '- You can tell the user HOW to verify it themselves in 10 seconds.',\n '- You have NOT hedged. None of: \"looks like it should work\", \"I',\n ' believe this fixes it\", \"the changes appear correct\".',\n `- Progress bar shows 100%. All deliverables checked off.`,\n '',\n 'WHAT IS NOT DONE — never report any of these as completion:',\n \"- An error message you didn't recover from.\",\n '- An empty result, a 0-line file, a \"no matches found\" you accepted',\n ' without questioning the search.',\n '- \"Should I continue?\" / \"Want me to also...?\" / \"Let me know if you',\n ' want X.\" Those are hedges. The user already told you to finish the',\n ' goal — just do it.',\n '- Partial progress dressed up as success. Fixed 3 of 5 bugs = 60%',\n ' done, not done.',\n \"- A subagent's failed/timeout/stopped TaskResult that you didn't\",\n ' respond to with a fresh attempt (different role, different model,',\n ' tighter prompt).',\n '',\n 'PROGRESS REPORTING — MANDATORY every iteration:',\n '- End every response with exactly: [PROGRESS: N%] — <status note>',\n ' where N is your honest estimate (0-100) of how much of the goal',\n ' is done. The engine tracks this and shows a live progress bar.',\n '- Example: [PROGRESS: 45%] — Auth module refactored, 3/5 tests pass,',\n ' remaining: test coverage + docs update.',\n '',\n 'PERSISTENCE PROTOCOL:',\n '- If blocked, try at least 3 different angles before reporting the',\n ' problem to the user. Different tool inputs, different subagent',\n ' roles, different providers, different decomposition of the task.',\n '- If a tool fails, read its error, alter the input, try again. Do',\n ' not just report the failure back.',\n '- If a subagent returns useless output, respawn with a tighter prompt',\n ' or a different role. Do not accept \"I could not determine…\" as the',\n ' final answer.',\n \"- Use `ask_subagent` for one-shot questions when you don't need a\",\n ' full delegated task.',\n '',\n 'REPORTING:',\n '- Stream short progress notes between major actions so the user can',\n ' monitor. Do not go silent for 50 tool calls then dump a wall of',\n ' text — but also do not narrate every tool call.',\n '- Use the shared scratchpad (if available) to leave breadcrumbs',\n ' subagents can read.',\n '- Final response must include: (a) what was accomplished, (b) how',\n ' to verify, (c) any caveats (residual TODOs, things the user',\n ' should know about).',\n '',\n 'BEGIN.]',\n ].join('\\n');\n}\n","/**\n * Shared regex patterns used across execution and security-scanner.\n * Centralized here to avoid duplication and keep patterns in sync.\n */\n\n/** Matches Node.js ECONN* errors and fetch failure messages. */\nexport const NETWORK_ERR_RE = /ECONN|ETIMEDOUT|ETIME|ENOTFOUND|EAI_AGAIN|fetch failed/i;","import { ProviderError } from '../types/provider.js';\nimport { NETWORK_ERR_RE } from './regex-patterns.js';\nimport type { RetryPolicy } from '../types/retry-policy.js';\n\nexport class DefaultRetryPolicy implements RetryPolicy {\n shouldRetry(err: Error | ProviderError, attempt: number): boolean {\n if (err instanceof ProviderError) {\n if (!err.retryable) return false;\n return attempt < this.maxAttempts(err);\n }\n const msg = err.message ?? '';\n const isNetwork = NETWORK_ERR_RE.test(msg);\n if (isNetwork) return attempt < 2;\n return false;\n }\n\n maxAttempts(err: Error | ProviderError): number {\n if (err instanceof ProviderError) {\n if (err.status === 429) return 5;\n if (err.status === 529) return 3;\n if (err.status === 599) return 5; // stream hang — transient, worth retrying aggressively\n if (err.status >= 500) return 3;\n return 0;\n }\n return 2;\n }\n\n delayMs(attempt: number): number {\n const base = 1000;\n const exp = base * 2 ** attempt;\n const jitter = Math.random() * base;\n return Math.min(30_000, exp + jitter);\n }\n}\n","import type { Context } from '../core/context.js';\nimport type { ErrorHandler, RecoveryDecision } from '../types/error-handler.js';\nimport { ProviderError } from '../types/provider.js';\nimport { NETWORK_ERR_RE } from './regex-patterns.js';\nimport type { Compactor } from '../types/compactor.js';\nimport type { ModelsRegistry } from '../types/models-registry.js';\n\n/**\n * Tiered error recovery strategies.\n * Each strategy is attempted in order until one returns a decision.\n */\nexport interface RecoveryStrategy {\n /** Human-readable label for logs. */\n label: string;\n /** Optional compactor for context_overflow recovery. */\n compactor?: Compactor | undefined;\n /** Returns an explicit recovery decision, or null to fall through. */\n attempt: (err: unknown, ctx: Context) => Promise<RecoveryDecision | null>;\n}\n\n// Package-level compiled regex for hot paths — avoids repeated compilation.\nconst CONTEXT_OVERFLOW_RE = /context|too long|tokens|exceeds the context window|context window/i;\n\n/**\n * Builds the ordered list of recovery strategies used by DefaultErrorHandler.\n * Exported so callers can customise or extend the strategy chain.\n */\nexport function buildRecoveryStrategies(opts?: {\n compactor?: Compactor | undefined;\n modelsRegistry?: ModelsRegistry | undefined;\n}): RecoveryStrategy[] {\n return [\n {\n label: 'context_overflow_reduce',\n compactor: opts?.compactor,\n async attempt(err, ctx) {\n if (!(err instanceof ProviderError)) return null;\n if (err.status !== 413 && !isContextOverflowError(err)) return null;\n\n if (this.compactor) {\n try {\n const report = await this.compactor.compact(ctx, { aggressive: true });\n if (report.after < report.before) {\n return { action: 'retry', reason: 'context_compacted' };\n }\n } catch {\n // compact failed; fall through\n }\n }\n return null;\n },\n },\n {\n label: 'rate_limit_backoff',\n async attempt(err) {\n if (!(err instanceof ProviderError) || err.status !== 429) return null;\n\n // Prefer the parsed Retry-After hint the provider extracted into\n // body.retryAfterMs; fall back to 5s when absent.\n const delayMs = err.body?.retryAfterMs ?? 5_000;\n // Clamp between 1s and 60s.\n const delay = Math.min(60_000, Math.max(1_000, delayMs));\n await new Promise((r) => setTimeout(r, delay));\n return { action: 'retry', reason: 'rate_limit_backoff' };\n },\n },\n {\n label: 'downgrade_model',\n async attempt(err, ctx) {\n if (!(err instanceof ProviderError)) return null;\n if (err.status !== 429 && err.status !== 529 && err.status < 500) return null;\n\n const registry = opts?.modelsRegistry;\n if (!registry) return null;\n\n try {\n const providerId = ctx.provider?.id;\n if (!providerId) return null;\n const provider = await registry.getProvider(providerId);\n if (!provider) return null;\n\n const currentModel = await registry.getModel(providerId, ctx.model);\n if (!currentModel) return null;\n\n // Find a cheaper fallback model with the same capabilities.\n // Prefer models with lower input cost, preferring the same family.\n const candidates = provider.models.filter((m) => {\n const modelCost = m.cost?.input ?? Number.POSITIVE_INFINITY;\n const currentCost = currentModel.cost?.input ?? Number.POSITIVE_INFINITY;\n if (modelCost >= currentCost) return false;\n if (currentModel.capabilities.tools && !m.tool_call) return false;\n if (currentModel.capabilities.vision && !m.modalities?.input?.includes('image'))\n return false;\n return true;\n });\n\n if (candidates.length === 0) return null;\n\n const fallback = candidates.reduce((prev, curr) =>\n (curr.cost?.input ?? 0) < (prev.cost?.input ?? 0) ? curr : prev,\n );\n\n return {\n action: 'retry',\n reason: 'model_downgrade',\n model: fallback.id,\n };\n } catch {\n return null;\n }\n },\n },\n ];\n}\n\nexport const DEFAULT_RECOVERY_STRATEGIES = buildRecoveryStrategies();\n\nfunction isContextOverflowError(err: ProviderError): boolean {\n return CONTEXT_OVERFLOW_RE.test([\n err.message,\n err.body?.message,\n err.body?.type,\n err.body?.raw,\n ].filter(Boolean).join('\\n'));\n}\n\nexport class DefaultErrorHandler implements ErrorHandler {\n private readonly strategies: RecoveryStrategy[];\n\n constructor(strategies: RecoveryStrategy[] = DEFAULT_RECOVERY_STRATEGIES) {\n this.strategies = strategies;\n }\n\n classify(err: unknown): {\n kind:\n | 'rate_limit'\n | 'overloaded'\n | 'server'\n | 'client'\n | 'network'\n | 'abort'\n | 'context_overflow'\n | 'unknown';\n retryable: boolean;\n } {\n // AbortError can be thrown in both browser (DOMException) and Node (Error).\n // Guard with typeof check so Node builds don't reference the browser-only DOMException.\n if (\n typeof DOMException !== 'undefined' &&\n err instanceof DOMException &&\n err.name === 'AbortError'\n ) {\n return { kind: 'abort', retryable: false };\n }\n if (err instanceof Error && err.name === 'AbortError') {\n return { kind: 'abort', retryable: false };\n }\n if (err instanceof ProviderError) {\n if (err.status === 429) return { kind: 'rate_limit', retryable: true };\n if (err.status === 529) return { kind: 'overloaded', retryable: true };\n if (err.status >= 500) return { kind: 'server', retryable: true };\n if (err.status === 413 || isContextOverflowError(err)) {\n return { kind: 'context_overflow', retryable: false };\n }\n if (err.status >= 400) return { kind: 'client', retryable: false };\n }\n if (err instanceof Error && NETWORK_ERR_RE.test(err.message)) {\n return { kind: 'network', retryable: true };\n }\n return { kind: 'unknown', retryable: false };\n }\n\n async recover(err: unknown, ctx: Context): Promise<RecoveryDecision | null> {\n for (const strategy of this.strategies) {\n const result = await strategy.attempt(err, ctx);\n if (result !== null) return result;\n }\n return null;\n }\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { SkillEntry, SkillLoader, SkillManifest } from '../types/skill.js';\nimport type { WstackPaths } from '../utils/wstack-paths.js';\n\n/**\n * Strip YAML frontmatter from a SKILL.md file, returning only the body.\n */\nfunction stripFrontmatter(raw: string): string {\n if (!raw.startsWith('---')) return raw;\n const end = raw.indexOf('\\n---', 4);\n if (end === -1) return raw;\n let body = raw.slice(end + 4);\n if (body.startsWith('\\n')) body = body.slice(1);\n return body;\n}\n\n/**\n * Compact a full skill body for token-saving fallback.\n * Extracts the Overview and Rules sections, trims to ~400 chars max.\n */\nfunction compactSkillBody(body: string): string {\n const sections: string[] = [];\n const overviewMatch = body.match(/##\\s*Overview\\s*\\n([\\s\\S]*?)(?=\\n##|\\n$|$)/i);\n const overview = overviewMatch?.[1];\n if (overview?.trim()) {\n sections.push(overview.trim().slice(0, 200));\n }\n const rulesMatch = body.match(/##\\s*Rules\\s*\\n([\\s\\S]*?)(?=\\n##|\\n$|$)/i);\n const rules = rulesMatch?.[1];\n if (rules?.trim()) {\n const trimmed = rules.trim().slice(0, 350);\n const ruleLines = trimmed\n .split('\\n')\n .filter((l) => /^\\s*[-*]\\s/.test(l) || /^\\s*\\d+[.)]\\s/.test(l))\n .slice(0, 6)\n .join('\\n');\n if (ruleLines) sections.push(ruleLines);\n }\n if (sections.length === 0) {\n const first = body.trim().slice(0, 200);\n if (first) sections.push(first);\n }\n const result = sections.join('\\n\\n');\n return result.length > 450 ? result.slice(0, 447) + '…' : result;\n}\n\nexport interface SkillLoaderOptions {\n paths: WstackPaths;\n bundledDir?: string | undefined;\n}\n\n/**\n * Discovery order (later layers shadow earlier ones at boot, but we walk\n * highest priority first and skip names already seen):\n * 1. Project-committed: <project>/.wrongstack/skills/\n * 2. User-global: ~/.wrongstack/skills/\n * 3. Bundled with build: packages/core/skills/\n */\nexport class DefaultSkillLoader implements SkillLoader {\n private readonly dirs: { dir: string; source: SkillManifest['source'] }[];\n private cache?: SkillManifest[] | undefined;\n private entriesCache?: SkillEntry[] | undefined;\n private readonly bodyCache = new Map<string, string>();\n\n constructor(opts: SkillLoaderOptions) {\n this.dirs = [\n { dir: opts.paths.inProjectSkills, source: 'project' },\n { dir: opts.paths.globalSkills, source: 'user' },\n ];\n if (opts.bundledDir) {\n this.dirs.push({ dir: opts.bundledDir, source: 'bundled' });\n }\n }\n\n async list(): Promise<SkillManifest[]> {\n if (this.cache) return this.cache;\n const found: SkillManifest[] = [];\n const seen = new Set<string>();\n for (const { dir, source } of this.dirs) {\n try {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const e of entries) {\n if (!e.isDirectory()) continue;\n const skillFile = path.join(dir, e.name, 'SKILL.md');\n try {\n const raw = await fs.readFile(skillFile, 'utf8');\n const meta = parseFrontmatter(raw);\n if (!meta.name || !meta.description) continue;\n if (seen.has(meta.name)) continue;\n seen.add(meta.name);\n found.push({\n name: meta.name,\n description: meta.description,\n version: meta.version,\n path: skillFile,\n source,\n });\n } catch {\n // skip malformed skill\n }\n }\n } catch {\n // directory may not exist\n }\n }\n this.cache = found;\n return found;\n }\n\n async find(name: string): Promise<SkillManifest | undefined> {\n const all = await this.list();\n const lower = name.toLowerCase();\n return all.find((s) => s.name.toLowerCase() === lower);\n }\n\n async manifestText(): Promise<string> {\n const entries = await this.listEntries();\n if (entries.length === 0) return '';\n const lines = ['## Available skills'];\n for (const e of entries) {\n const scopeTag = e.scope.length > 0 ? ` — ${e.scope.slice(0, 3).join(', ')}` : '';\n lines.push(`- **${e.name}**${scopeTag}`);\n lines.push(` Use when: ${e.trigger}`);\n }\n return lines.join('\\n');\n }\n\n async listEntries(): Promise<SkillEntry[]> {\n if (this.entriesCache) return this.entriesCache;\n const skills = await this.list();\n const entries: SkillEntry[] = [];\n for (const s of skills) {\n // Parse trigger/scope from the description that list() already parsed —\n // no need to re-read the file; s.description === fm.description.\n const { trigger, scope } = parseDescriptionFromText(s.description ?? '');\n entries.push({ name: s.name, trigger, scope, source: s.source, path: s.path });\n }\n this.entriesCache = entries;\n return entries;\n }\n\n invalidateCache(): void {\n this.cache = undefined;\n this.entriesCache = undefined;\n this.bodyCache.clear();\n }\n\n async readBody(name: string): Promise<string> {\n const key = name.toLowerCase();\n const cached = this.bodyCache.get(key);\n if (cached !== undefined) return cached;\n const m = await this.find(name);\n if (!m) throw new Error(`Skill \"${name}\" not found`);\n const body = await fs.readFile(m.path, 'utf8');\n this.bodyCache.set(key, body);\n return body;\n }\n\n async readSaveBody(name: string): Promise<string> {\n const key = `save:${name.toLowerCase()}`;\n const cached = this.bodyCache.get(key);\n if (cached !== undefined) return cached;\n const m = await this.find(name);\n if (!m) throw new Error(`Skill \"${name}\" not found`);\n // Try SKILL.save.md in the same directory as SKILL.md\n const savePath = path.join(path.dirname(m.path), 'SKILL.save.md');\n let result: string;\n try {\n result = await fs.readFile(savePath, 'utf8');\n } catch {\n // No hand-crafted save variant — auto-compact the full body\n const full = await fs.readFile(m.path, 'utf8');\n const body = stripFrontmatter(full);\n const compact = compactSkillBody(body);\n if (compact) {\n result = `## Overview\\n\\n${compact}`;\n } else {\n // Fallback: return first 300 chars of full body\n result = body.trim().slice(0, 300);\n }\n }\n this.bodyCache.set(key, result);\n return result;\n }\n}\n\ninterface Frontmatter {\n name?: string | undefined;\n description?: string | undefined;\n version?: string | undefined;\n}\n\nfunction parseFrontmatter(raw: string): Frontmatter {\n if (!raw.startsWith('---')) return {};\n const end = raw.indexOf('\\n---', 4);\n if (end === -1) return {};\n const block = raw.slice(4, end);\n const out: Frontmatter = {};\n let key: keyof Frontmatter | null = null;\n let value: string[] = [];\n const flush = () => {\n if (key) {\n out[key] = value.join('\\n').trim();\n }\n key = null;\n value = [];\n };\n for (const line of block.split('\\n')) {\n const m = /^([a-zA-Z_]+):\\s*(\\|?)\\s*(.*)$/.exec(line);\n if (m) {\n flush();\n key = (m[1] ?? '') as keyof Frontmatter;\n const pipe = m[2];\n const rest = m[3] ?? '';\n if (pipe === '|') {\n value = [];\n } else if (rest) {\n value = [rest];\n } else {\n value = [];\n }\n } else if (key) {\n value.push(line.replace(/^\\s+/, ''));\n }\n }\n flush();\n return out;\n}\n\n/**\n * Parse skill description into:\n * - trigger: extracted \"Use when...\" sentence (first sentence of description)\n * - scope: comma-separated items from first line's parenthetical or file-ext list\n */\n/**\n * Extract trigger and scope from a skill's description text.\n * Used by listEntries() when the description has already been parsed from frontmatter.\n */\nfunction parseDescriptionFromText(desc: string): { trigger: string; scope: string[] } {\n // Extract first sentence as trigger\n const firstSentenceEnd = desc.indexOf('. ');\n const trigger =\n firstSentenceEnd !== -1\n ? desc.slice(0, firstSentenceEnd + 1).trim()\n : (desc.trim().split('\\n')[0] ?? '');\n\n // Extract scope from parenthetical: \"Covers X, Y, and Z\" or \"for A, B, C\"\n const scope: string[] = [];\n const coversMatch = /(?:covers|for|including)\\s+([^.]+)/i.exec(desc);\n if (coversMatch) {\n // NB: parenthesize the `?? ''` — without it, `??` binds looser than the\n // method chain, so `items` would be the raw match string and `...items`\n // would spread it into individual characters.\n const items = (coversMatch[1] ?? '')\n .replace(/[·•]/g, ',')\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean);\n scope.push(...items);\n }\n\n return { trigger, scope };\n}\n\n\n"]}
1
+ {"version":3,"sources":["../../src/utils/tool-wire-compact.ts","../../src/utils/token-estimate.ts","../../src/utils/expect-defined.ts","../../src/utils/message-invariants.ts","../../src/utils/context-evidence.ts","../../src/types/blocks.ts","../../src/execution/compaction-core.ts","../../src/execution/compactor.ts","../../src/execution/intelligent-compactor.ts","../../src/models/llm-selector.ts","../../src/execution/selective-compactor.ts","../../src/execution/strategy-compactor.ts","../../src/utils/assert-never.ts","../../src/utils/atomic-write.ts","../../src/utils/error.ts","../../src/utils/json-schema-validate.ts","../../src/utils/regex-guard.ts","../../src/utils/sleep.ts","../../src/utils/string.ts","../../src/utils/tool-subject.ts","../../src/utils/tool-output-serializer.ts","../../src/utils/wstack-paths.ts","../../src/types/errors.ts","../../src/execution/auto-compaction-middleware.ts","../../src/security/capabilities.ts","../../src/execution/tool-executor.ts","../../src/execution/autonomous-runner.ts","../../src/storage/goal-store.ts","../../src/execution/autonomy-brain.ts","../../src/execution/eternal-autonomy.ts","../../src/coordination/subagent-budget.ts","../../src/coordination/agent-subagent-runner.ts","../../src/coordination/agents/types.ts","../../src/coordination/agents/phase1-discovery.ts","../../src/coordination/agents/phase2-planning.ts","../../src/coordination/agents/phase3-build.ts","../../src/coordination/agents/phase4-verify.ts","../../src/coordination/agents/phase5-review.ts","../../src/coordination/agents/phase6-domain.ts","../../src/coordination/agents/phase7-knowledge.ts","../../src/coordination/agents/phase8-delivery.ts","../../src/coordination/agents/phase9-meta.ts","../../src/coordination/agents/index.ts","../../src/coordination/dispatcher.ts","../../src/types/provider.ts","../../src/coordination/coordinator/error-classifier.ts","../../src/coordination/fleet.ts","../../src/coordination/subagent-nicknames.ts","../../src/coordination/multi-agent-coordinator.ts","../../src/execution/parallel-eternal-engine.ts","../../src/execution/autonomy-prompt-contributor.ts","../../src/execution/goal-preamble.ts","../../src/execution/regex-patterns.ts","../../src/execution/retry-policy.ts","../../src/execution/error-handler.ts","../../src/execution/skill-loader.ts","../../src/execution/model-runtime.ts"],"names":["tokens","hasToolUse","repair","afterTokens","afterFull","path2","stat","resolve","path","isRecord","projectHash","path4","fs2","fsp","extractText","unlink","first","baseMessage","randomUUID","PreemptState","GOAL_COMPLETE_MARKER","execFile","promisify","execFileP","fs3","path5"],"mappings":";;;;;;;;;AAqBA,IAAM,0BAAA,GAA6B,GAAA;AACnC,IAAM,4BAAA,GAA+B,GAAA;AAErC,IAAM,YAAA,uBAAmB,OAAA,EAA2C;AAU7D,SAAS,4BAAA,CACd,IAAA,EACA,IAAA,GAA4C,EAAC,EAClB;AAC3B,EAAA,MAAM,iBAAA,GACJ,IAAA,CAAK,mBAAA,KAAwB,MAAA,IAAa,KAAK,yBAAA,KAA8B,MAAA;AAC/E,EAAA,IAAI,iBAAA,IAAqB,OAAO,IAAA,KAAS,QAAA,IAAY,SAAS,IAAA,EAAM;AAClE,IAAA,MAAM,MAAA,GAAS,YAAA,CAAa,GAAA,CAAI,IAAI,CAAA;AACpC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AAE,GAAA,EAAI;AACvC,EAAA,OAAO,GAAA;AACT;AAqBO,SAAS,iBAAA,CACd,KACA,IAAA,EACS;AACT,EAAA,MAAM,QAAA,GAAW,KAAK,WAAA,EAAY;AAClC,EAAA,IAAI,CAAC,UAAU,OAAO,GAAA;AACtB,EAAA,MAAM,EAAA,GAAK,KAAK,kBAAA,EAAmB;AACnC,EAAA,MAAM,QAAA,GAAW,mBAAA,CAAoB,QAAA,EAAU,EAAE,CAAA;AACjD,EAAA,KAAA,MAAW,CAAA,IAAK,QAAA,CAAS,QAAA,EAAU,IAAA,CAAK,YAAY,CAAC,CAAA;AAErD,EAAA,MAAM,IAAA,GAAgB,EAAE,GAAG,GAAA,EAAI;AAC/B,EAAA,IAAI,QAAA,CAAS,cAAc,MAAA,EAAW;AAGpC,IAAA,IAAA,CAAK,YAAY,QAAA,CAAS,SAAA;AAAA,EAC5B;AACA,EAAA,IAAI,QAAA,CAAS,UAAU,MAAA,EAAW;AAChC,IAAA,IAAA,CAAK,QAAQ,QAAA,CAAS,KAAA;AAAA,EACxB;AACA,EAAA,OAAO,IAAA;AACT","file":"index.js","sourcesContent":["import type { JSONSchema } from '../types/tool.js';\n\nexport interface ToolWireDefinitionLike {\n name: string;\n description?: string | undefined;\n inputSchema: unknown;\n}\n\nexport interface CompactToolDefinitionForWireOptions {\n /** Top-level tool description budget. */\n descriptionMaxChars?: number | undefined;\n /** Per-JSON-Schema `description` annotation budget. */\n schemaDescriptionMaxChars?: number | undefined;\n}\n\nexport interface CompactWireToolDefinition {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n}\n\nconst TOOL_DESCRIPTION_MAX_CHARS = 640;\nconst SCHEMA_DESCRIPTION_MAX_CHARS = 180;\n\nconst compactCache = new WeakMap<object, CompactWireToolDefinition>();\n\n/**\n * Return the provider-wire version of a tool definition.\n *\n * Tool schemas remain structurally intact: validation keywords, property\n * names, required fields, enum values, and nested shapes are preserved. The\n * only reduction is on human prose annotations (`description`), which are the\n * largest repeated cost in provider tool declarations.\n */\nexport function compactToolDefinitionForWire(\n tool: ToolWireDefinitionLike,\n opts: CompactToolDefinitionForWireOptions = {},\n): CompactWireToolDefinition {\n const useDefaultOptions =\n opts.descriptionMaxChars === undefined && opts.schemaDescriptionMaxChars === undefined;\n if (useDefaultOptions && typeof tool === 'object' && tool !== null) {\n const cached = compactCache.get(tool);\n if (cached) return cached;\n }\n\n const compact: CompactWireToolDefinition = {\n name: tool.name,\n description: compactDescription(\n tool.description ?? '',\n opts.descriptionMaxChars ?? TOOL_DESCRIPTION_MAX_CHARS,\n ),\n inputSchema: compactSchemaDescriptions(\n tool.inputSchema,\n opts.schemaDescriptionMaxChars ?? SCHEMA_DESCRIPTION_MAX_CHARS,\n ),\n };\n\n if (useDefaultOptions && typeof tool === 'object' && tool !== null) {\n compactCache.set(tool, compact);\n }\n return compact;\n}\n\nexport function compactSchemaDescriptions(\n schema: unknown,\n maxDescriptionChars = SCHEMA_DESCRIPTION_MAX_CHARS,\n): Record<string, unknown> {\n const compact = compactSchemaNode(schema, maxDescriptionChars);\n return isRecord(compact) ? compact : { type: 'object', properties: {} };\n}\n\nfunction compactSchemaNode(node: unknown, maxDescriptionChars: number): unknown {\n if (Array.isArray(node)) {\n return node.map((item) => compactSchemaNode(item, maxDescriptionChars));\n }\n if (!isRecord(node)) return node;\n\n const out: JSONSchema = {};\n for (const [key, value] of Object.entries(node)) {\n if (key === 'description' && typeof value === 'string') {\n out[key] = compactDescription(value, maxDescriptionChars);\n } else {\n out[key] = compactSchemaNode(value, maxDescriptionChars);\n }\n }\n return out;\n}\n\nfunction compactDescription(text: string, maxChars: number): string {\n const normalized = text.replace(/\\s+/g, ' ').trim();\n if (normalized.length <= maxChars) return normalized;\n if (maxChars <= 20) return normalized.slice(0, maxChars);\n\n const hardLimit = maxChars - 12;\n const boundary = findSemanticBoundary(normalized, hardLimit);\n const head = normalized.slice(0, boundary > 0 ? boundary : hardLimit).trimEnd();\n return `${head} ...`;\n}\n\nfunction findSemanticBoundary(text: string, limit: number): number {\n const punctuation = Math.max(\n text.lastIndexOf('. ', limit),\n text.lastIndexOf('; ', limit),\n text.lastIndexOf(': ', limit),\n );\n if (punctuation >= Math.floor(limit * 0.45)) return punctuation + 1;\n\n const comma = text.lastIndexOf(', ', limit);\n if (comma >= Math.floor(limit * 0.6)) return comma + 1;\n\n const space = text.lastIndexOf(' ', limit);\n return space >= Math.floor(limit * 0.6) ? space : limit;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value);\n}\n","import type { Message } from '../types/messages.js';\nimport { compactToolDefinitionForWire } from './tool-wire-compact.js';\n\n/**\n * Shared token estimation with JSON.stringify caching.\n * Avoids repeated stringification of tool input objects.\n *\n * ## Calibration\n *\n * `estimateRequestTokens` uses a fixed 3.5 chars/token heuristic — a\n * conservative overestimate that prevents underestimation but reduces\n * accuracy. After each API call, call `recordActualUsage()` with the\n * real `usage.input` from the provider response. The module maintains a\n * rolling average of `actual / estimated` ratio (EWM, α=0.3) and\n * applies it to subsequent calls via `estimateRequestTokensCalibrated`.\n *\n * Calibration is per-module (shared across all callers), which is\n * sufficient: the chars/token ratio is a property of the tokenizer,\n * not the model. Uncalibrated calls (before any samples, or when\n * `recordActualUsage` is not called) fall back to the uncalibrated\n * estimate so nothing breaks.\n */\n\nconst RoughTokenEstimate = (text: string, charsPerToken = 3.5): number =>\n Math.max(1, Math.ceil(text.length / charsPerToken));\n\n/** Calibration state: actual/estimated ratio via exponential weighted moving average. */\ninterface CalState {\n ratio: number; // current calibration multiplier (actual / estimated)\n count: number; // number of samples recorded\n prevEst: number; // estimated tokens from the most recent estimateRequestTokens call\n}\n\n/** EWM α — higher = faster adaptation, more volatile. */\nconst CAL_ALPHA = 0.3;\n\n/**\n * Calibration is keyed so that, in a multi-agent / model-switching process,\n * each (provider, model) tokenizer gets its own ratio instead of all of them\n * collapsing onto one shared number. Callers that don't pass a key use the\n * shared `__global__` bucket — that preserves the original single-session\n * behavior and keeps all existing call sites working unchanged.\n */\nconst CALIBRATION_GLOBAL_KEY = '__global__';\nconst _cals = new Map<string, CalState>();\n\nfunction calState(key: string): CalState {\n let state = _cals.get(key);\n if (!state) {\n state = { ratio: 1.0, count: 0, prevEst: 0 };\n _cals.set(key, state);\n }\n return state;\n}\n\nconst MIN_SAMPLES_FOR_CALIBRATION = 3;\n\n/**\n * Fallback chars/token ratios per model family for providers that don't return\n * usage data. Used when `recordActualUsage` receives zero/negative tokens and\n * we have enough samples to trust the fallback. Keys are lowercase prefixes.\n */\nconst MODEL_FAMILY_RATIO: Record<string, number> = {\n // Anthropic: ~3.8-4.0 chars/token depending on model\n claude: 3.8,\n // OpenAI: ~4.0 chars/token\n 'gpt-4': 4.0,\n 'gpt-3.5': 4.0,\n // Google: ~3.5 chars/token\n gemini: 3.5,\n // DeepSeek: ~3.5 chars/token\n deepseek: 3.5,\n};\n\n/**\n * Cache of computed estimates keyed by the stringified input — not the\n * input object itself. Previously the cache was keyed by the input object\n * via WeakMap, but JSON.stringify() produces a new object reference each\n * call so the cache never hit. Now we use a Map with string keys so that\n * repeated stringifications of the same structure share a single entry.\n */\nconst ESTIMATE_CACHE = new Map<string, number>();\n\nconst ESTIMATE_CACHE_MAX_SIZE = 50_000;\n\nfunction getCachedEstimate(key: string, compute: (key: string) => number): number {\n const existing = ESTIMATE_CACHE.get(key);\n if (existing !== undefined) return existing;\n if (ESTIMATE_CACHE.size >= ESTIMATE_CACHE_MAX_SIZE) {\n // Evict oldest half when at capacity — O(1) instead of O(n) iteration.\n // 5 000 surviving entries still give a high cache hit rate for the\n // common case of repeated context-window checks on the same messages.\n for (const k of ESTIMATE_CACHE.keys()) {\n if (ESTIMATE_CACHE.size <= Math.floor(ESTIMATE_CACHE_MAX_SIZE / 2)) break;\n ESTIMATE_CACHE.delete(k);\n }\n }\n const estimate = compute(key);\n ESTIMATE_CACHE.set(key, estimate);\n return estimate;\n}\n\n/**\n * Estimate tokens for a tool_use block input.\n * Caches the stringified result keyed by the stable string representation\n * to avoid repeated JSON.stringify calls during context window checks.\n */\nexport function estimateToolInputTokens(input: unknown): number {\n if (typeof input === 'string') return RoughTokenEstimate(input);\n if (input === null || typeof input !== 'object') {\n return RoughTokenEstimate(String(input));\n }\n // JSON.stringify is called once to form the cache key; RoughTokenEstimate\n // is deferred only on cache miss (compute callback), not wrapped unnecessarily.\n return getCachedEstimate(JSON.stringify(input), (key) => RoughTokenEstimate(key));\n}\n\n/**\n * Estimate tokens for a tool_result content.\n */\nexport function estimateToolResultTokens(content: string | unknown): number {\n if (typeof content === 'string') return RoughTokenEstimate(content);\n return getCachedEstimate(JSON.stringify(content), (key) => RoughTokenEstimate(key));\n}\n\n/**\n * Estimate tokens for a text block.\n */\nexport function estimateTextTokens(text: string): number {\n return RoughTokenEstimate(text);\n}\n\n/**\n * Compute and cache the token estimate for a single message. This is the\n * canonical per-message estimator — called once by ConversationState on\n * append/replace so the O(n·m) content-block walk happens at mutation time,\n * not on every context-pressure check.\n */\nexport function computeMessageTokens(msg: Message): number {\n if (typeof msg.content === 'string') return estimateTextTokens(msg.content);\n let total = 0;\n for (const b of msg.content) {\n if (b.type === 'text') total += estimateTextTokens(b.text);\n else if (b.type === 'tool_use') total += estimateToolInputTokens(b.input);\n else if (b.type === 'tool_result') total += estimateToolResultTokens(b.content);\n else total += RoughTokenEstimate(JSON.stringify(b));\n }\n return total;\n}\n\n/**\n * Estimate tokens for an array of messages (text + tool I/O), using the shared\n * 3.5 chars/token basis. This is the single canonical message-array estimator —\n * compactors, the context_manager tool, and the `/context` display all route\n * through it so the number a user sees matches the number compaction decides on.\n *\n * When a message carries a pre-computed `_estTokens` field (set by\n * ConversationState on append/replace), it is used directly instead of\n * re-walking the content blocks — turning the O(n·m) scan into an O(n)\n * sum for fully-cached arrays.\n */\nexport function estimateMessageTokens(messages: readonly Message[]): number {\n let total = 0;\n for (const m of messages) {\n if (typeof m._estTokens === 'number' && m._estTokens > 0) {\n total += m._estTokens;\n continue;\n }\n total += computeMessageTokens(m);\n }\n return total;\n}\n\n/**\n * Rough estimate of tokens in a tool definition (name + description + schema).\n * Accounts for the JSON-serialized inputSchema which is sent to the API\n * but NOT included in roughEstimate(content).\n */\nexport function estimateToolDefTokens(tool: {\n name: string;\n description?: string | undefined;\n inputSchema: unknown;\n}): number {\n // Fast path: pre-computed by ToolRegistry at registration time.\n const cached = (tool as { _estDefTokens?: number | undefined })._estDefTokens;\n if (typeof cached === 'number' && cached > 0) return cached;\n\n const compact = compactToolDefinitionForWire(tool);\n return (\n RoughTokenEstimate(tool.name) +\n RoughTokenEstimate(compact.description) +\n RoughTokenEstimate(JSON.stringify(compact.inputSchema))\n );\n}\n\n/**\n * Estimate the total API request token count: system prompt + tool definitions\n * + conversation messages. Use this for context-window bar calculations\n * instead of roughEstimate (which only counts messages).\n *\n * The overhead ratio (overhead / messages) varies by conversation length:\n * - Short conversations (< 10 messages): ~30-50% overhead (large system+tools)\n * - Medium (10-50 messages): ~15-30%\n * - Long (> 50 messages): ~5-15%\n *\n * Returns { messages, systemPrompt, tools, total } for debugging display.\n */\nexport interface RequestTokenBreakdown {\n messages: number;\n systemPrompt: number;\n tools: number;\n total: number;\n}\n\nexport function estimateRequestTokens(\n messages: unknown,\n systemPrompt: unknown,\n tools: { name: string; description?: string | undefined; inputSchema: unknown }[],\n calibrationKey: string = CALIBRATION_GLOBAL_KEY,\n): RequestTokenBreakdown {\n // Messages: apply the same logic as roughEstimate\n let messagesTokens = 0;\n if (typeof messages === 'string') {\n messagesTokens = RoughTokenEstimate(messages);\n } else if (Array.isArray(messages)) {\n for (const m of messages) {\n if (typeof m === 'object' && m !== null && 'content' in m) {\n // Fast path: pre-computed per-message token estimate (set by\n // ConversationState on append/replace). Skips the O(m) content-block\n // walk entirely for cached messages.\n const cached = (m as { _estTokens?: number | undefined })._estTokens;\n if (typeof cached === 'number' && cached > 0) {\n messagesTokens += cached;\n continue;\n }\n const content = (m as { content: unknown }).content;\n if (typeof content === 'string') {\n messagesTokens += RoughTokenEstimate(content);\n } else if (Array.isArray(content)) {\n for (const b of content) {\n if (typeof b === 'object' && b !== null) {\n if ((b as { type?: string | undefined }).type === 'text') {\n messagesTokens += RoughTokenEstimate((b as { text: string }).text);\n } else {\n messagesTokens += RoughTokenEstimate(JSON.stringify(b));\n }\n }\n }\n }\n }\n }\n }\n\n // System prompt\n let systemTokens = 0;\n if (typeof systemPrompt === 'string') {\n systemTokens = RoughTokenEstimate(systemPrompt);\n } else if (Array.isArray(systemPrompt)) {\n for (const b of systemPrompt) {\n if (\n typeof b === 'object' &&\n b !== null &&\n (b as { type?: string | undefined }).type === 'text'\n ) {\n systemTokens += RoughTokenEstimate((b as { text: string }).text);\n }\n }\n }\n\n // Tool definitions\n let toolsTokens = 0;\n for (const t of tools) {\n toolsTokens += estimateToolDefTokens(t);\n }\n\n const total = messagesTokens + systemTokens + toolsTokens;\n\n // Record the raw estimate for calibration: the next recordActualUsage()\n // call will pair this against the actual API usage so the rolling ratio\n // stays in sync with the real chars/token ratio of the content.\n calState(calibrationKey).prevEst = total;\n\n return {\n messages: messagesTokens,\n systemPrompt: systemTokens,\n tools: toolsTokens,\n total,\n };\n}\n\n/**\n * Record the actual API input token count after a provider call so\n * `estimateRequestTokensCalibrated` can self-correct on subsequent calls.\n *\n * Prefer passing `estimatedInputTokens` explicitly (the calibrated pre-flight\n * estimate from the middleware) — this avoids race conditions when other code\n * also calls `estimateRequestTokens` between the pre-flight and this call\n * (e.g. audit logging in agent.ts).\n *\n * When `estimatedInputTokens` is omitted, falls back to the keyed bucket's\n * `prevEst` for backward compatibility with callers that don't have the\n * pre-flight value. `calibrationKey` selects the per-(provider,model) bucket\n * (defaults to the shared global bucket).\n */\nexport function recordActualUsage(\n actualInputTokens: number,\n estimatedInputTokens?: number,\n calibrationKey: string = CALIBRATION_GLOBAL_KEY,\n): void {\n if (actualInputTokens <= 0) return;\n const cal = calState(calibrationKey);\n const est = estimatedInputTokens ?? cal.prevEst;\n if (est <= 0) return;\n\n const sampleRatio = actualInputTokens / est;\n if (cal.count === 0) {\n cal.ratio = sampleRatio;\n } else {\n // EWM: new = α * sample + (1-α) * old → α=0.3 = fast initial converge\n cal.ratio = CAL_ALPHA * sampleRatio + (1 - CAL_ALPHA) * cal.ratio;\n }\n // Sanity bound: keep the rolling ratio within [0.5, 1.5] so a sequence\n // of bad samples can't blow up the calibration for everyone.\n cal.ratio = Math.min(1.5, Math.max(0.5, cal.ratio));\n cal.count++;\n}\n\n/**\n * Returns the current calibration state for a bucket. Exposed for debugging\n * and tests — not needed by normal callers.\n */\nexport function getCalibrationState(calibrationKey: string = CALIBRATION_GLOBAL_KEY): {\n ratio: number;\n count: number;\n calibrated: boolean;\n} {\n const cal = calState(calibrationKey);\n return {\n ratio: cal.ratio,\n count: cal.count,\n calibrated: cal.count >= MIN_SAMPLES_FOR_CALIBRATION,\n };\n}\n\n/**\n * Like `estimateRequestTokens` but applies the rolling calibration factor\n * so context pressure readings converge on reality within a few iterations.\n *\n * Before any `recordActualUsage` samples are collected, returns the same\n * result as `estimateRequestTokens` (ratio = 1.0, no distortion).\n * After `MIN_SAMPLES_FOR_CALIBRATION` samples, applies the calibrated\n * multiplier capped to the range [0.5, 1.5] as a sanity bound.\n */\nexport function estimateRequestTokensCalibrated(\n messages: unknown,\n systemPrompt: unknown,\n tools: { name: string; description?: string | undefined; inputSchema: unknown }[],\n calibrationKey: string = CALIBRATION_GLOBAL_KEY,\n): RequestTokenBreakdown {\n const result = estimateRequestTokens(messages, systemPrompt, tools, calibrationKey);\n const cal = calState(calibrationKey);\n\n if (cal.count >= MIN_SAMPLES_FOR_CALIBRATION) {\n const safeRatio = Math.min(1.5, Math.max(0.5, cal.ratio));\n return {\n messages: Math.round(result.messages * safeRatio),\n systemPrompt: Math.round(result.systemPrompt * safeRatio),\n tools: Math.round(result.tools * safeRatio),\n total: Math.round(result.total * safeRatio),\n };\n }\n\n // No calibration samples yet — fall back to model-family ratio if available,\n // otherwise use the uncalibrated estimate (ratio = 1.0).\n const fallbackRatio = getModelFamilyRatio(calibrationKey);\n if (fallbackRatio !== null) {\n return {\n messages: Math.round(result.messages * fallbackRatio),\n systemPrompt: Math.round(result.systemPrompt * fallbackRatio),\n tools: Math.round(result.tools * fallbackRatio),\n total: Math.round(result.total * fallbackRatio),\n };\n }\n\n return result;\n}\n\n/** Look up the fallback chars/token ratio for a calibration key (e.g. \"provider/model\"). */\nfunction getModelFamilyRatio(calibrationKey: string): number | null {\n const lower = calibrationKey.toLowerCase();\n for (const [family, ratio] of Object.entries(MODEL_FAMILY_RATIO)) {\n if (lower.includes(family)) return ratio / 3.5; // MODEL_FAMILY_RATIO is chars/token, we need multiplier\n }\n return null;\n}\n\n/**\n * Resets calibration state. Primarily for tests that run in the same\n * process and need a clean slate between suites. With no argument it clears\n * every bucket (including the global one); pass a key to reset just that bucket.\n */\nexport function resetCalibration(calibrationKey?: string): void {\n if (calibrationKey === undefined) {\n _cals.clear();\n return;\n }\n _cals.delete(calibrationKey);\n}\n","/** Assert a value is neither null nor undefined. Throws if it is.\n * Useful after optional chaining and indexed access when the\n * control flow guarantees the value exists but TypeScript can't\n * prove it (e.g. after a check on a related field). */\nexport function expectDefined<T>(value: T | null | undefined, label?: string): T {\n if (value === null || value === undefined) {\n const err = new Error(label ? `Expected ${label} to be defined` : 'Expected value to be defined');\n err.name = 'ExpectDefinedError';\n throw err;\n }\n return value;\n}\n","import { expectDefined } from './expect-defined.js';\nimport type { ContentBlock, ToolResultBlock, ToolUseBlock } from '../types/blocks.js';\nimport type { Message } from '../types/messages.js';\nexport interface MessageRepairReport {\n changed: boolean;\n removedToolUses: string[];\n removedToolResults: string[];\n removedMessages: number;\n}\n\nexport interface MessageRepairResult {\n messages: Message[];\n report: MessageRepairReport;\n}\n\n/**\n * Repair provider-level tool-call adjacency invariants.\n *\n * Anthropic requires every assistant `tool_use` block to have a matching\n * `tool_result` block in the immediately following user message. Manual\n * context surgery (summary/prune) can cut through the middle of such an\n * exchange. This function removes only the now-orphaned protocol blocks,\n * preserving surrounding text/images/thinking blocks where possible.\n */\nexport function repairToolUseAdjacency(messages: Message[]): MessageRepairResult {\n const removedToolUses: string[] = [];\n const removedToolResults: string[] = [];\n let removedMessages = 0;\n let changed = false;\n const out: Message[] = [];\n\n for (let i = 0; i < messages.length; i++) {\n const original = expectDefined(messages[i]);\n let msg = original;\n\n if (hasToolUse(msg)) {\n const nextIds = toolResultIds(messages[i + 1]);\n const filtered = mapContent(msg, (blocks) => {\n const next: ContentBlock[] = [];\n for (const block of blocks) {\n if (block.type === 'tool_use' && !nextIds.has(block.id)) {\n removedToolUses.push(block.id);\n changed = true;\n continue;\n }\n next.push(block);\n }\n return next;\n });\n msg = filtered ?? msg;\n }\n\n if (hasToolResult(msg)) {\n const allowed = toolUseIds(out[out.length - 1]);\n const filtered = mapContent(msg, (blocks) => {\n const next: ContentBlock[] = [];\n for (const block of blocks) {\n if (block.type === 'tool_result' && !allowed.has(block.tool_use_id)) {\n removedToolResults.push(block.tool_use_id);\n changed = true;\n continue;\n }\n next.push(block);\n }\n return next;\n });\n msg = filtered ?? msg;\n }\n\n if (isEmptyMessage(msg)) {\n removedMessages++;\n changed = true;\n continue;\n }\n out.push(msg);\n }\n\n return {\n messages: changed ? out : messages,\n report: { changed, removedToolUses, removedToolResults, removedMessages },\n };\n}\n\nfunction hasToolUse(msg: Message | undefined): boolean {\n return contentBlocks(msg).some((b): b is ToolUseBlock => b.type === 'tool_use');\n}\n\nfunction hasToolResult(msg: Message | undefined): boolean {\n return contentBlocks(msg).some((b): b is ToolResultBlock => b.type === 'tool_result');\n}\n\nfunction toolUseIds(msg: Message | undefined): Set<string> {\n const ids = new Set<string>();\n if (msg?.role !== 'assistant') return ids;\n for (const block of contentBlocks(msg)) {\n if (block.type === 'tool_use') ids.add(block.id);\n }\n return ids;\n}\n\nfunction toolResultIds(msg: Message | undefined): Set<string> {\n const ids = new Set<string>();\n if (msg?.role !== 'user') return ids;\n for (const block of contentBlocks(msg)) {\n if (block.type === 'tool_result') ids.add(block.tool_use_id);\n }\n return ids;\n}\n\nfunction contentBlocks(msg: Message | undefined): ContentBlock[] {\n return msg && Array.isArray(msg.content) ? msg.content : [];\n}\n\nfunction mapContent(\n msg: Message,\n fn: (blocks: ContentBlock[]) => ContentBlock[],\n): Message | null {\n if (!Array.isArray(msg.content)) return msg;\n const next = fn(msg.content);\n if (next.length === msg.content.length && next.every((b, idx) => b === msg.content[idx])) {\n return msg;\n }\n return { ...msg, content: next };\n}\n\nfunction isEmptyMessage(msg: Message): boolean {\n if (typeof msg.content === 'string') return msg.content.trim().length === 0;\n return msg.content.length === 0;\n}\n","import * as path from 'node:path';\nimport type { Context } from '../core/context.js';\nimport type {\n ContextEvidenceState,\n ToolOutputMetadata,\n} from '../types/context-evidence.js';\n\nconst MAX_TOOL_CALLS = 80;\nconst MAX_FACTS = 40;\nconst MAX_ERRORS = 20;\nconst MAX_DIGEST_CHARS = 4_000;\n\nconst WRITE_TOOLS = new Set(['edit', 'write', 'replace', 'patch']);\nconst READ_TOOLS = new Set(['read', 'grep', 'glob', 'ls', 'tree']);\n\nexport function createContextEvidenceState(): ContextEvidenceState {\n return {\n sessionGoals: [],\n implicitFacts: [],\n activeErrors: [],\n toolCalls: [],\n fileGraph: {},\n repeatedReads: [],\n updatedAt: Date.now(),\n };\n}\n\nexport interface RecordToolOutputEvidenceInput {\n toolUseId: string;\n toolName: string;\n input: unknown;\n content: string;\n ok: boolean;\n outputBytes?: number | undefined;\n outputTokens?: number | undefined;\n outputLines?: number | undefined;\n}\n\nexport function recordUserIntentEvidence(ctx: Context, text: string): void {\n const intent = normalizeWhitespace(text).slice(0, 700);\n if (!intent) return;\n const state = ensureEvidence(ctx);\n state.currentIntent = { text: intent, updatedAt: Date.now() };\n if (state.sessionGoals.length === 0 || isGoalish(intent)) {\n pushUniqueBounded(state.sessionGoals, intent, 8);\n }\n state.updatedAt = Date.now();\n}\n\nexport function recordToolOutputEvidence(\n ctx: Context,\n input: RecordToolOutputEvidenceInput,\n): ToolOutputMetadata {\n const state = ensureEvidence(ctx);\n const files = extractFiles(ctx, input.toolName, input.input, input.content);\n const symbols = extractSymbols(input.content, input.input);\n const commands = extractCommands(input.toolName, input.input);\n const errors = extractErrors(input.content);\n const summary = summarizeToolOutput(input.toolName, input.input, input.content, {\n files,\n symbols,\n errors,\n ok: input.ok,\n });\n\n const metadata: ToolOutputMetadata = {\n toolUseId: input.toolUseId,\n toolName: input.toolName,\n ok: input.ok,\n inputSummary: summarizeInput(input.input),\n summary,\n files,\n symbols,\n commands,\n errors,\n status: 'seen',\n referenceCount: 0,\n seenAt: Date.now(),\n outputBytes: input.outputBytes,\n outputTokens: input.outputTokens,\n outputLines: input.outputLines,\n };\n\n state.toolCalls.push(metadata);\n if (state.toolCalls.length > MAX_TOOL_CALLS) {\n state.toolCalls.splice(0, state.toolCalls.length - MAX_TOOL_CALLS);\n }\n\n updateFileGraph(state, metadata);\n updateRepeatedReadSignals(state, metadata);\n if (errors.length > 0) {\n for (const err of errors) pushUniqueBounded(state.activeErrors, err, MAX_ERRORS);\n }\n const fact = implicitFactFor(metadata);\n if (fact) pushUniqueBounded(state.implicitFacts, fact, MAX_FACTS);\n state.updatedAt = Date.now();\n return metadata;\n}\n\nexport function markAssistantReferencedEvidence(ctx: Context, text: string): void {\n const state = ensureEvidence(ctx);\n const haystack = text.toLowerCase();\n if (!haystack.trim()) return;\n\n for (const tool of state.toolCalls) {\n if (!metadataReferencedByText(tool, haystack)) continue;\n tool.status = 'referenced';\n tool.referenceCount++;\n tool.referencedAt = Date.now();\n for (const file of tool.files) {\n const node = state.fileGraph[file];\n if (node) node.referenced = true;\n }\n }\n state.updatedAt = Date.now();\n}\n\nexport function buildContextEvidenceDigest(ctx: Context): string {\n const state = ensureEvidence(ctx);\n const lines: string[] = [];\n\n if (state.currentIntent?.text) {\n lines.push(`intent: ${state.currentIntent.text}`);\n }\n\n const goals = state.sessionGoals.slice(-3);\n if (goals.length > 0) {\n lines.push('session_goals:');\n for (const goal of goals) lines.push(`- ${goal}`);\n }\n\n const activeErrors = state.activeErrors.slice(-5);\n if (activeErrors.length > 0) {\n lines.push('active_errors:');\n for (const err of activeErrors) lines.push(`- ${err}`);\n }\n\n const files = Object.values(state.fileGraph)\n .sort((a, b) => (b.writes - a.writes) || (b.reads - a.reads) || a.path.localeCompare(b.path))\n .slice(0, 12);\n if (files.length > 0) {\n lines.push('dependency_graph:');\n for (const file of files) {\n const actions = [\n file.reads > 0 ? `read ${file.reads}x` : '',\n file.writes > 0 ? `write ${file.writes}x` : '',\n ].filter(Boolean).join(', ');\n const refs = file.referenced ? '; referenced by assistant' : '';\n const via = file.lastToolUseId ? `; last via ${file.lastToolUseId}` : '';\n lines.push(`- ${file.path} (${actions || 'seen'}${refs}${via})`);\n }\n }\n\n const referenced = state.toolCalls\n .filter((tool) => tool.status === 'referenced')\n .slice(-10);\n const recentSeen = state.toolCalls\n .filter((tool) => tool.status === 'seen')\n .slice(-5);\n const trail = [...referenced, ...recentSeen];\n if (trail.length > 0) {\n lines.push('tool_trail:');\n for (const tool of trail) {\n const size = tool.outputTokens ? `; ~${tool.outputTokens} tokens` : '';\n const filesText = tool.files.length > 0 ? `; files=${tool.files.slice(0, 4).join(', ')}` : '';\n const symbolsText = tool.symbols.length > 0 ? `; symbols=${tool.symbols.slice(0, 4).join(', ')}` : '';\n lines.push(\n `- ${tool.toolUseId} ${tool.toolName} ${tool.status}: ${tool.summary}${filesText}${symbolsText}${size}`,\n );\n }\n }\n\n const facts = state.implicitFacts.slice(-8);\n if (facts.length > 0) {\n lines.push('implicit_facts:');\n for (const fact of facts) lines.push(`- ${fact}`);\n }\n\n const digest = lines.join('\\n');\n if (digest.length <= MAX_DIGEST_CHARS) return digest;\n return `${digest.slice(0, MAX_DIGEST_CHARS)}... [+${digest.length - MAX_DIGEST_CHARS} chars]`;\n}\n\nexport function repeatedReadPressure(ctx: Context): number {\n return ensureEvidence(ctx).repeatedReads.reduce((max, item) => Math.max(max, item.count), 0);\n}\n\nfunction ensureEvidence(ctx: Context): ContextEvidenceState {\n if (!ctx.contextEvidence) {\n (ctx as never as { contextEvidence: ContextEvidenceState }).contextEvidence =\n createContextEvidenceState();\n }\n return ctx.contextEvidence;\n}\n\nfunction isGoalish(text: string): boolean {\n return /\\b(goal|objective|task|need|want|implement|fix|improve|refactor|add|remove|hedef|amac|istiyorum|gerekiyor|iyilestir|duzelt|ekle|kaldir)\\b/i.test(text);\n}\n\nfunction normalizeWhitespace(text: string): string {\n return text.replace(/\\s+/g, ' ').trim();\n}\n\nfunction pushUniqueBounded(list: string[], value: string, max: number): void {\n const normalized = normalizeWhitespace(value);\n if (!normalized) return;\n const existing = list.findIndex((item) => item.toLowerCase() === normalized.toLowerCase());\n if (existing >= 0) list.splice(existing, 1);\n list.push(normalized);\n if (list.length > max) list.splice(0, list.length - max);\n}\n\nfunction extractFiles(\n ctx: Context,\n toolName: string,\n input: unknown,\n content: string,\n): string[] {\n const out = new Set<string>();\n for (const value of inputPathValues(input)) addPath(ctx, out, value);\n\n if (toolName === 'grep' || toolName === 'glob' || toolName === 'bash') {\n const re = /(?:(?:[A-Za-z]:)?[./\\\\]?[\\w@.-]+(?:[\\\\/][\\w@(). -]+)+\\.[A-Za-z0-9]{1,12})/g;\n for (const match of content.matchAll(re)) addPath(ctx, out, match[0]);\n }\n\n return [...out].slice(0, 30);\n}\n\nfunction inputPathValues(input: unknown): string[] {\n const values: string[] = [];\n const visit = (value: unknown, key?: string): void => {\n if (typeof value === 'string') {\n if (key && /^(path|file|files|fromFile|toFile|dir|cwd)$/i.test(key)) values.push(value);\n return;\n }\n if (Array.isArray(value)) {\n for (const item of value) visit(item, key);\n return;\n }\n if (!value || typeof value !== 'object') return;\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) visit(v, k);\n };\n visit(input);\n return values;\n}\n\nfunction addPath(ctx: Context, out: Set<string>, raw: string): void {\n const clean = raw.trim().replace(/^[\"'`]+|[\"'`),;:]+$/g, '');\n if (!clean || clean.length > 260) return;\n let normalized = clean.replace(/\\\\/g, '/');\n try {\n const abs = path.isAbsolute(clean) ? path.resolve(clean) : null;\n if (abs) {\n const rel = path.relative(ctx.projectRoot, abs);\n if (!rel.startsWith('..') && !path.isAbsolute(rel)) {\n normalized = rel.replace(/\\\\/g, '/');\n }\n }\n } catch {\n // Keep the best-effort normalized string.\n }\n if (normalized.length > 0) out.add(normalized);\n}\n\nfunction extractSymbols(content: string, input: unknown): string[] {\n const out = new Set<string>();\n const patterns = [\n /\\b(?:function|class|interface|type|enum|const|let|var|def|fn|struct)\\s+([A-Za-z_$][\\w$]*)/g,\n /\\b(?:export\\s+)?(?:async\\s+)?function\\s+([A-Za-z_$][\\w$]*)/g,\n ];\n for (const re of patterns) {\n for (const match of content.matchAll(re)) {\n if (match[1]) out.add(match[1]);\n if (out.size >= 30) break;\n }\n }\n\n const pattern = input && typeof input === 'object'\n ? (input as Record<string, unknown>)['pattern']\n : undefined;\n if (typeof pattern === 'string' && /^[A-Za-z_$][\\w$]*$/.test(pattern)) {\n out.add(pattern);\n }\n\n return [...out].slice(0, 30);\n}\n\nfunction extractCommands(toolName: string, input: unknown): string[] {\n if (toolName !== 'bash' && toolName !== 'exec' && toolName !== 'shell') return [];\n if (!input || typeof input !== 'object') return [];\n const command = (input as Record<string, unknown>)['command'];\n if (typeof command !== 'string') return [];\n return [command.slice(0, 220)];\n}\n\nfunction extractErrors(content: string): string[] {\n const lines = content.split(/\\r?\\n/);\n const errors: string[] = [];\n for (const line of lines) {\n if (!/\\b(error|exception|failed|failure|fatal|panic|timeout|denied|enoent|eacces|eperm|typeerror|syntaxerror)\\b/i.test(line)) continue;\n errors.push(normalizeWhitespace(line).slice(0, 260));\n if (errors.length >= 5) break;\n }\n return errors;\n}\n\nfunction summarizeInput(input: unknown): string | undefined {\n if (!input || typeof input !== 'object') return undefined;\n const obj = input as Record<string, unknown>;\n const parts: string[] = [];\n for (const key of ['path', 'file', 'pattern', 'glob', 'command']) {\n const value = obj[key];\n if (typeof value === 'string') parts.push(`${key}=${value.slice(0, 160)}`);\n }\n return parts.length > 0 ? parts.join(', ') : undefined;\n}\n\nfunction summarizeToolOutput(\n toolName: string,\n input: unknown,\n content: string,\n opts: { files: string[]; symbols: string[]; errors: string[]; ok: boolean },\n): string {\n if (!opts.ok && opts.errors.length > 0) return opts.errors[0] ?? `${toolName} failed`;\n if (toolName === 'read' && opts.files[0]) return `read ${opts.files[0]}`;\n if (toolName === 'grep') {\n const pattern = input && typeof input === 'object'\n ? (input as Record<string, unknown>)['pattern']\n : undefined;\n return `searched ${typeof pattern === 'string' ? pattern : 'pattern'} (${opts.files.length} file hint(s))`;\n }\n if ((toolName === 'edit' || toolName === 'write') && opts.files[0]) {\n return `${toolName === 'write' ? 'wrote' : 'edited'} ${opts.files[0]}`;\n }\n const firstLine = normalizeWhitespace(content.split(/\\r?\\n/).find((line) => line.trim()) ?? '');\n return firstLine ? firstLine.slice(0, 220) : `${toolName} returned no text`;\n}\n\nfunction updateFileGraph(state: ContextEvidenceState, metadata: ToolOutputMetadata): void {\n const writes = WRITE_TOOLS.has(metadata.toolName) ? 1 : 0;\n const reads = writes === 0 && (READ_TOOLS.has(metadata.toolName) || metadata.files.length > 0)\n ? 1\n : 0;\n for (const file of metadata.files) {\n const existing = state.fileGraph[file] ?? {\n path: file,\n reads: 0,\n writes: 0,\n tools: [],\n referenced: false,\n };\n existing.reads += reads;\n existing.writes += writes;\n existing.lastToolUseId = metadata.toolUseId;\n pushUniqueBounded(existing.tools, `${metadata.toolName}#${metadata.toolUseId}`, 8);\n state.fileGraph[file] = existing;\n }\n}\n\nfunction updateRepeatedReadSignals(state: ContextEvidenceState, metadata: ToolOutputMetadata): void {\n if (metadata.toolName !== 'read' || metadata.files.length === 0) {\n state.lastReadPath = undefined;\n return;\n }\n const file = metadata.files[0] as string;\n if (state.lastReadPath === file) {\n const existing = state.repeatedReads.find((item) => item.file === file);\n if (existing) {\n existing.count++;\n existing.lastToolUseId = metadata.toolUseId;\n } else {\n state.repeatedReads.push({ file, count: 2, lastToolUseId: metadata.toolUseId });\n }\n if (state.repeatedReads.length > 10) state.repeatedReads.shift();\n }\n state.lastReadPath = file;\n}\n\nfunction implicitFactFor(metadata: ToolOutputMetadata): string | undefined {\n if (metadata.errors.length > 0) return `${metadata.toolName}#${metadata.toolUseId} exposed error: ${metadata.errors[0]}`;\n if (metadata.toolName === 'read' && metadata.files[0]) {\n const size = metadata.outputLines ? ` (${metadata.outputLines} line(s) returned)` : '';\n return `read ${metadata.files[0]}${size}`;\n }\n if ((metadata.toolName === 'edit' || metadata.toolName === 'write') && metadata.files[0]) {\n return `${metadata.toolName} changed ${metadata.files[0]}`;\n }\n if (metadata.status === 'referenced') return `${metadata.toolName}#${metadata.toolUseId} was referenced`;\n return undefined;\n}\n\nfunction metadataReferencedByText(metadata: ToolOutputMetadata, haystack: string): boolean {\n for (const file of metadata.files) {\n const f = file.toLowerCase();\n const base = path.basename(file).toLowerCase();\n if (f && haystack.includes(f)) return true;\n if (base && haystack.includes(base)) return true;\n }\n for (const symbol of metadata.symbols) {\n if (symbol.length >= 3 && haystack.includes(symbol.toLowerCase())) return true;\n }\n for (const err of metadata.errors) {\n const head = err.slice(0, 80).toLowerCase();\n if (head.length >= 12 && haystack.includes(head)) return true;\n }\n return false;\n}\n","export interface TextBlock {\n type: 'text';\n text: string;\n cache_control?: { type: 'ephemeral' | undefined };\n}\n\nexport interface ToolUseBlock {\n type: 'tool_use';\n id: string;\n name: string;\n input: Record<string, unknown>;\n /**\n * Provider-specific opaque metadata captured from the wire response.\n * Echoed back verbatim in the next request so providers that bind\n * extra state to function calls keep working. Example: Gemini's\n * `thoughtSignature` — required for tool-use turns with thinking\n * models, otherwise the next request fails with 400 \"Function call\n * is missing a thought_signature in functionCall parts\".\n *\n * Keys are namespaced by intent so multiple wires can coexist:\n * - `google.thoughtSignature` — Gemini signed-thought blob\n * Other providers can add their own keys without colliding.\n */\n providerMeta?: Record<string, unknown>;\n}\n\nexport interface ToolResultBlock {\n type: 'tool_result';\n tool_use_id: string;\n /**\n * The original tool name. Useful for providers like Google Gemini that\n * need the tool name in `functionResponse.name` — the tool_use_id is\n * only a session-local identifier and is not stable across replays.\n * Always set by ToolExecutor; may be absent on manually-constructed blocks.\n */\n name?: string | undefined;\n content: string;\n is_error?: boolean | undefined;\n}\n\nexport interface ImageBlock {\n type: 'image';\n source: {\n type: 'base64' | 'url';\n media_type?: string | undefined;\n data?: string | undefined;\n url?: string | undefined;\n };\n}\n\n/**\n * Chain-of-thought / extended-thinking content emitted by the model.\n *\n * Both Anthropic extended thinking (`{type:'thinking', thinking, signature}`)\n * and DeepSeek reasoning mode (top-level `reasoning_content` on the assistant\n * message) require this content to be echoed back verbatim on the next\n * request, otherwise the provider returns 400:\n * - Anthropic: \"The `content[].thinking` in the thinking mode must be passed back\"\n * - DeepSeek: \"The `reasoning_content` in the thinking mode must be passed back\"\n *\n * `signature` is Anthropic-specific (an opaque integrity blob). DeepSeek\n * doesn't issue a signature — the field is absent for that provider.\n *\n * Per Anthropic, thinking blocks MUST appear before any text/tool_use blocks\n * in an assistant message. Stream builders preserve that order.\n */\nexport interface ThinkingBlock {\n type: 'thinking';\n thinking: string;\n signature?: string | undefined;\n providerMeta?: Record<string, unknown>;\n}\n\nexport type ContentBlock = TextBlock | ToolUseBlock | ToolResultBlock | ImageBlock | ThinkingBlock;\n\nexport function isTextBlock(b: ContentBlock): b is TextBlock {\n return b.type === 'text';\n}\nexport function isToolUseBlock(b: ContentBlock): b is ToolUseBlock {\n return b.type === 'tool_use';\n}\nexport function isToolResultBlock(b: ContentBlock): b is ToolResultBlock {\n return b.type === 'tool_result';\n}\nexport function isImageBlock(b: ContentBlock): b is ImageBlock {\n return b.type === 'image';\n}\nexport function isThinkingBlock(b: ContentBlock): b is ThinkingBlock {\n return b.type === 'thinking';\n}\n","import type { ContentBlock, ToolResultBlock, ToolUseBlock } from '../types/blocks.js';\nimport { isTextBlock } from '../types/blocks.js';\nimport type { Message } from '../types/messages.js';\nimport {\n estimateMessageTokens,\n estimateToolInputTokens,\n estimateToolResultTokens,\n} from '../utils/token-estimate.js';\n\n/**\n * Instrumentation state for compaction hot-path analysis.\n * Tracks actual vs. nominal iteration counts to detect O(n·m) blowup.\n *\n * Logged as structured events so they can be aggregated from session JSONL\n * and plotted per-message-count to catch regressions before they ship.\n */\ninterface CompactionMetrics {\n /** Total messages in the compaction pass. */\n messageCount: number;\n /** Index where the preserved window starts (from findPreserveStart). */\n preserveStart: number;\n /** Outer-loop iterations in the elision fast-path scan. */\n fastPathIterations: number;\n /**\n * Inner-loop block iterations in the fast-path scan.\n * Ratio fastPathInner / fastPathIterations indicates avg blocks per message.\n */\n fastPathInnerIterations: number;\n /**\n * Outer-loop iterations in the full elision pass.\n * Ratio fullPassIterations / messageCount ≈ 1.0 when working correctly.\n */\n fullPassIterations: number;\n /**\n * Inner-loop block iterations in the full elision pass.\n * Ratio fullPassInner / fullPassIterations indicates avg blocks per message.\n */\n fullPassInnerIterations: number;\n /** Estimated tokens saved by the elision pass. */\n tokensSaved: number;\n /** Whether the full elision pass made any changes. */\n changed: boolean;\n}\n\n/**\n * Whether compaction instrumentation should be emitted to stdout.\n * Gated behind WRONGSTACK_DEBUG=1 or NODE_ENV=development so the hot path\n * does not pay for JSON.stringify + console.log on every compaction pass\n * in production. Matches the guard at the ratio-guard site (line ~281).\n */\nfunction compactionDebugEnabled(): boolean {\n return process.env['NODE_ENV'] === 'development' || process.env['WRONGSTACK_DEBUG'] === '1';\n}\n\n/** Emit compaction instrumentation as a structured log event (debug-only). */\nfunction emitCompactionMetrics(event: string, metrics: CompactionMetrics): void {\n if (!compactionDebugEnabled()) return;\n console.log(\n JSON.stringify({\n level: 'debug',\n event,\n messageCount: metrics.messageCount,\n preserveStart: metrics.preserveStart,\n fastPathIterations: metrics.fastPathIterations,\n fastPathInnerIterations: metrics.fastPathInnerIterations,\n // Ratios — anything > 2.0 indicates the inner loop is running more than expected\n fastPathInnerPerOuter:\n metrics.fastPathIterations > 0\n ? metrics.fastPathInnerIterations / metrics.fastPathIterations\n : 0,\n fullPassIterations: metrics.fullPassIterations,\n fullPassInnerIterations: metrics.fullPassInnerIterations,\n fullPassInnerPerOuter:\n metrics.fullPassIterations > 0\n ? metrics.fullPassInnerIterations / metrics.fullPassIterations\n : 0,\n tokensSaved: metrics.tokensSaved,\n changed: metrics.changed,\n }),\n );\n}\n\n/**\n * Token estimate for a message array (text + tool I/O). Re-exported from the\n * canonical `token-estimate` helper so compactors and the context-pressure\n * monitor share one number.\n */\nexport const estimateMessages = estimateMessageTokens;\n\n/**\n * Shared, pure compaction primitives.\n *\n * Before this module the three compactors (`HybridCompactor`,\n * `IntelligentCompactor`, `SelectiveCompactor`) each carried their own copies\n * of message-token estimation, tool-result elision, text detection and digest\n * rendering — with subtle divergences (notably Selective lacked the\n * tool_use/tool_result pair preservation, so it could elide the result of a\n * tool call it was supposed to keep). These helpers are the single source of\n * truth. They operate on plain `Message[]` and never touch `Context`/state, so\n * each compactor keeps its own `ctx.state.replaceMessages(...)` plumbing.\n */\n\n/** Does this message carry any non-empty text? */\nexport function hasTextContent(m: Message): boolean {\n if (typeof m.content === 'string') return m.content.trim().length > 0;\n return m.content.some((b) => b.type === 'text' && b.text.trim().length > 0);\n}\n\n/**\n * Index where the preserved (recent) window starts. Walks back counting\n * user/assistant messages until `preserveK` are covered, then walks forward to\n * keep any tool_use/tool_result protocol pair intact — so a tool_result whose\n * tool_use is preserved is never elided.\n *\n * Instrumentation: emits `compaction.find_preserve_start.ended` with the\n * forward-walk inner-loop count so we can track whether the `.some()` calls\n * over content blocks are causing measurable O(n·m) overhead.\n */\nexport function findPreserveStart(messages: readonly Message[], preserveK: number): number {\n let pairCount = 0;\n let preserveStart = messages.length;\n for (let i = messages.length - 1; i >= 0 && pairCount < preserveK; i--) {\n const m = messages[i];\n if (!m) continue;\n if (m.role === 'user' || m.role === 'assistant') {\n pairCount++;\n preserveStart = i;\n }\n }\n\n // If the preserved window starts on a user tool_result, widen backward to\n // include the immediately preceding assistant tool_use. This keeps provider\n // protocol adjacency intact and avoids orphaned results after compaction.\n let pairRepairIterations = 0;\n let pairRepairInnerIterations = 0;\n while (preserveStart > 0) {\n pairRepairIterations++;\n const first = messages[preserveStart];\n const prev = messages[preserveStart - 1];\n if (!first || !prev || first.role !== 'user' || prev.role !== 'assistant') break;\n if (typeof first.content === 'string' || typeof prev.content === 'string') break;\n const resultIds = new Set<string>();\n for (const block of first.content) {\n pairRepairInnerIterations++;\n if (block.type === 'tool_result') resultIds.add(block.tool_use_id);\n }\n if (resultIds.size === 0) break;\n const hasMatchingUse = prev.content.some((block) => {\n pairRepairInnerIterations++;\n return block.type === 'tool_use' && resultIds.has(block.id);\n });\n if (!hasMatchingUse) break;\n preserveStart--;\n }\n\n if (compactionDebugEnabled()) {\n console.log(\n JSON.stringify({\n level: 'debug',\n event: 'compaction.find_preserve_start.ended',\n messageCount: messages.length,\n preserveK,\n preserveStart,\n pairRepairIterations,\n pairRepairInnerIterations,\n pairRepairInnerPerOuter:\n pairRepairIterations > 0 ? pairRepairInnerIterations / pairRepairIterations : 0,\n }),\n );\n }\n\n return preserveStart;\n}\n\nexport interface EliseResult {\n /** New message array, or the same reference when nothing changed. */\n messages: Message[];\n /** Estimated tokens reclaimed. */\n saved: number;\n changed: boolean;\n}\n\n/**\n * Elide oversized tool I/O that falls before the preserve window. Pure:\n * returns a fresh array (or the same reference when unchanged). Replaces the\n * duplicate copies that lived in all three compactors.\n */\nexport function eliseOldToolResults(\n messages: readonly Message[],\n opts: { preserveK: number; eliseThreshold: number },\n): EliseResult {\n const preserveStart = findPreserveStart(messages, opts.preserveK);\n\n // ── Fast path: probe for oversized tool I/O ─────────────────────────────\n //\n // Instruments the ratio of actual iterations to message count so we can\n // detect whether the inner block-scan loop is O(n·m) as expected or has\n // regressed to quadratic behaviour.\n let hasOversized = false;\n let fastPathIterations = 0;\n let fastPathInnerIterations = 0;\n for (let i = 0; i < preserveStart && !hasOversized; i++) {\n fastPathIterations++;\n const msg = messages[i];\n if (!msg || !Array.isArray(msg.content)) continue;\n for (const b of msg.content) {\n fastPathInnerIterations++;\n const oversized =\n (b.type === 'tool_result' && estimateToolResultTokens(b.content) >= opts.eliseThreshold) ||\n (b.type === 'tool_use' && estimateToolInputTokens(b.input) >= opts.eliseThreshold);\n if (oversized) {\n hasOversized = true;\n break;\n }\n }\n }\n\n // ── Emit fast-path metrics (covers both fast-path hit and the early-exit) ──\n emitCompactionMetrics(\n hasOversized\n ? 'compaction.elision.fast_path.oversized_found'\n : 'compaction.elision.fast_path.no_oversized',\n {\n messageCount: messages.length,\n preserveStart,\n fastPathIterations,\n fastPathInnerIterations,\n fullPassIterations: 0,\n fullPassInnerIterations: 0,\n tokensSaved: 0,\n changed: false,\n },\n );\n\n if (!hasOversized) return { messages: messages as Message[], saved: 0, changed: false };\n\n // ── Full elision pass ──────────────────────────────────────────────────\n //\n // Optimisation: once we've found the first oversized tool I/O block and\n // applied the elision, we can break out of the outer loop early. The\n // preserveStart boundary is already fixed by findPreserveStart(); any\n // remaining messages before it are either (a) already copied as-is by the\n // `i >= preserveStart` guard above, or (b) have no oversized tool_results.\n // Breaking early changes worst-case from O(n·m) to O(k·m) where k is the\n // index of the first oversized message — typically k << n.\n //\n // The instrumentation (ratio guard) is placed inside the loop body so it\n // fires per-message and can detect regressions before the pass completes.\n let saved = 0;\n let changed = false;\n let fullPassIterations = 0;\n let fullPassInnerIterations = 0;\n const next = new Array<Message>(messages.length);\n for (let i = 0; i < messages.length; i++) {\n fullPassIterations++;\n const msg = messages[i];\n if (i >= preserveStart || !msg || !Array.isArray(msg.content)) {\n next[i] = msg as Message;\n continue;\n }\n const original = msg.content;\n const newContent: ContentBlock[] = original.map((b) => {\n if (b.type === 'tool_use') {\n const tokens = estimateToolInputTokens(b.input);\n if (tokens < opts.eliseThreshold) return b;\n const elidedInput = summarizeToolUseInputElision(b, tokens);\n saved += Math.max(0, tokens - estimateToolInputTokens(elidedInput));\n return { ...b, input: elidedInput };\n }\n\n if (b.type !== 'tool_result') return b;\n const tokens = estimateToolResultTokens(b.content);\n if (tokens < opts.eliseThreshold) return b;\n saved += tokens;\n const elided: ToolResultBlock = {\n type: 'tool_result',\n tool_use_id: b.tool_use_id,\n content: summarizeToolResultElision(b, tokens),\n is_error: b.is_error,\n };\n return elided;\n });\n if (newContent.every((b, idx) => b === original[idx])) {\n next[i] = msg;\n } else {\n next[i] = { ...msg, content: newContent };\n changed = true;\n }\n // Count inner iterations (same items as the original.map)\n fullPassInnerIterations += original.length;\n\n // ── Ratio guard: defensive assertion + conditional early-break ─────────\n //\n // The ratio is computed here (after each outer iteration) so we can\n // break as early as possible — before processing remaining messages.\n //\n // Defensive assertion (threshold 10): fires in dev/debug if the inner loop\n // is running more than 10x what we'd expect per message. This catches\n // pathological regressions where a single message has hundreds of blocks.\n //\n // Conditional early-break (threshold 1.5): uncomment the `changed &&` guard\n // below ONLY if production sessions show fullPassInnerPerOuter > 1.5\n // consistently. In that case, add `&& changed` to the if-condition below\n // to break after the first elision is applied — capping worst-case from\n // O(n·m) to O(k·m) where k is the first oversized message index.\n if (compactionDebugEnabled()) {\n const ratio = fullPassInnerIterations / fullPassIterations;\n\n if (ratio > 10) {\n // Defensive assertion: never expected in practice\n console.error(\n JSON.stringify({\n level: 'error',\n event: 'compaction.elision.regression',\n message: `fullPassInnerPerOuter=${ratio.toFixed(2)} exceeds threshold 10 — possible O(n·m) regression`,\n messageCount: messages.length,\n fullPassIterations,\n fullPassInnerIterations,\n }),\n );\n }\n\n // TODO (prod): uncomment the following `changed &&` guard to enable\n // early-break once production data confirms fullPassInnerPerOuter > 1.5:\n //\n // if (changed) {\n // break; // O(n·m) → O(k·m), k = first oversized message index\n // }\n }\n }\n\n emitCompactionMetrics('compaction.elision.full_pass.ended', {\n messageCount: messages.length,\n preserveStart,\n fastPathIterations,\n fastPathInnerIterations,\n fullPassIterations,\n fullPassInnerIterations,\n tokensSaved: saved,\n changed,\n });\n\n return { messages: changed ? next : (messages as Message[]), saved, changed };\n}\n\nfunction summarizeToolUseInputElision(\n block: ToolUseBlock,\n tokens: number,\n): Record<string, unknown> {\n const fields: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(block.input ?? {})) {\n fields[key] = summarizeToolUseInputValue(value);\n }\n\n return {\n __elided_tool_input: `~${tokens} tokens; original arguments are in the session log`,\n tool: block.name,\n fields,\n };\n}\n\nfunction summarizeToolUseInputValue(value: unknown): unknown {\n if (value === null || value === undefined) return value;\n if (typeof value === 'number' || typeof value === 'boolean') return value;\n if (typeof value === 'string') {\n const oneLine = value.replace(/\\s+/g, ' ').trim();\n return oneLine.length <= 160 ? oneLine : `${oneLine.slice(0, 120)}...(${oneLine.length} chars)`;\n }\n if (Array.isArray(value)) {\n return `[array:${value.length}]`;\n }\n if (typeof value === 'object') {\n const keys = Object.keys(value as Record<string, unknown>);\n return `[object:${keys.slice(0, 8).join(',')}${keys.length > 8 ? ',...' : ''}]`;\n }\n return String(value);\n}\n\nfunction summarizeToolResultElision(block: ToolResultBlock, tokens: number): string {\n const parts = [`elided: ~${tokens} tokens`];\n if (block.name) parts.push(`tool=${block.name}`);\n const files = extractPathHints(block.content).slice(0, 5);\n if (files.length > 0) parts.push(`files=${files.join(', ')}`);\n const error = firstErrorLine(block.content);\n if (error) parts.push(`error=${error}`);\n return `[${parts.join('; ')}]`;\n}\n\nfunction extractPathHints(content: unknown): string[] {\n const text = typeof content === 'string' ? content : JSON.stringify(content);\n const out = new Set<string>();\n const re = /(?:(?:[A-Za-z]:)?[./\\\\]?[\\w@.-]+(?:[\\\\/][\\w@(). -]+)+\\.[A-Za-z0-9]{1,12})/g;\n for (const match of text.matchAll(re)) {\n const clean = match[0]?.replace(/\\\\/g, '/').replace(/^[\"'`]+|[\"'`),;:]+$/g, '');\n if (clean && clean.length <= 220) out.add(clean);\n if (out.size >= 5) break;\n }\n return [...out];\n}\n\nfunction firstErrorLine(content: unknown): string | undefined {\n const text = typeof content === 'string' ? content : JSON.stringify(content);\n for (const line of text.split(/\\r?\\n/)) {\n if (\n !/\\b(error|exception|failed|failure|fatal|panic|timeout|denied|enoent|eacces|eperm)\\b/i.test(\n line,\n )\n )\n continue;\n const trimmed = line.replace(/\\s+/g, ' ').trim();\n if (trimmed) return trimmed.slice(0, 180);\n }\n return undefined;\n}\n\n/**\n * Lossless textual digest of a message range. Every text block is kept verbatim\n * (across all roles, so prior `system` digests fold forward and nothing\n * accumulates as loss). `tool_use` / `tool_result` blocks are counted and\n * replaced with a marker rather than serialized — their payload is already\n * persisted in the session log. Empty/tool-only messages are skipped.\n */\nexport function buildLosslessDigest(messages: readonly Message[]): string {\n const lines: string[] = [];\n for (const m of messages) {\n let text: string;\n let omitted = 0;\n if (typeof m.content === 'string') {\n text = m.content;\n } else {\n const parts: string[] = [];\n for (const b of m.content) {\n if (isTextBlock(b)) parts.push(b.text);\n else if (b.type === 'tool_use' || b.type === 'tool_result') omitted++;\n }\n text = parts.join(' ');\n }\n if (text.trim().length === 0 && omitted === 0) continue;\n const marker = omitted > 0 ? ` [${omitted} tool call(s) omitted — see session log]` : '';\n lines.push(`[${m.role}]: ${text}${marker}`);\n }\n return lines.join('\\n');\n}\n\n// ── Content-aware scoring ─────────────────────────────────────────────────\n\n/** Importance score for a message — drives retention vs. summarization. */\nexport type ContentScore = 0 | 1 | 2 | 3 | 4 | 5;\n// 5 = critical (error, correction, decision) — keep verbatim\n// 3 = medium (normal exchange, successful tool) — keep first sentence\n// 1 = low (large tool result, grep output) — one-line summary\n// 0 = noise (repeated failure pattern) — collapse to count\n\n/**\n * Extract the plain text from a message (ignoring tool blocks).\n * Returns empty string if no text content exists.\n */\nexport function extractText(m: Message): string {\n if (typeof m.content === 'string') return m.content;\n return m.content\n .filter(isTextBlock)\n .map((b) => b.text)\n .join(' ');\n}\n\n/** Check if a message contains a tool_use block. */\nexport function hasToolUse(m: Message): boolean {\n if (typeof m.content === 'string') return false;\n return m.content.some((b) => b.type === 'tool_use');\n}\n\n/** Check if a message contains a tool_result block over the given char threshold. */\nexport function hasLargeToolResult(m: Message, threshold = 3000): boolean {\n if (typeof m.content === 'string') return false;\n return m.content.some(\n (b) =>\n b.type === 'tool_result' &&\n (b as ToolResultBlock).content &&\n (typeof (b as ToolResultBlock).content === 'string'\n ? (b as ToolResultBlock).content.length\n : JSON.stringify((b as ToolResultBlock).content).length) > threshold,\n );\n}\n\n/**\n * Score a message by content importance.\n *\n * CRITICAL (5): user corrections, explicit \"no/wrong/stop\", error messages,\n * architecture decisions, security findings.\n * MEDIUM (3): normal exchanges, successful tool calls, file reads, edits.\n * LOW (1): large tool results (>3K chars), grep/file-list outputs, boilerplate.\n * NOISE (0): repeated identical failures (same tool, same error, 5th+ occurrence\n * within the range), pure tool I/O with no text.\n */\nexport function scoreMessage(\n m: Message,\n context?: { failureCounts?: Map<string, number> },\n): ContentScore {\n const text = extractText(m).toLowerCase();\n\n // ── Noise detection: pure tool I/O with no text ─────────────────────\n if (text.trim().length === 0 && (hasToolUse(m) || typeof m.content !== 'string')) {\n const hasResult =\n typeof m.content !== 'string' && m.content.some((b) => b.type === 'tool_result');\n if (hasToolUse(m) || hasResult) return 0;\n }\n\n // ── Repeated failure detection ─────────────────────────────────────\n if (context?.failureCounts && m.role === 'user' && hasToolUse(m) === false) {\n // Check if this is a tool_result that matches a failure pattern\n const isFailure = /error|fail|exception|timeout|enonet|eacces|eperm|enoent|abort/i.test(text);\n if (isFailure) {\n // Build a key from the error type\n const errKey =\n /(error|fail|exception|timeout|enonet|eacces|eperm|enoent|abort)/i\n .exec(text)?.[0]\n ?.toLowerCase() ?? 'error';\n const count = (context.failureCounts.get(errKey) ?? 0) + 1;\n context.failureCounts.set(errKey, count);\n if (count >= 5) return 0; // 5th+ identical failure → noise\n if (count >= 3) return 1; // 3rd-4th → low priority\n }\n }\n\n // ── Critical: user corrections / stop signals ──────────────────────\n if (m.role === 'user') {\n if (\n /\\b(wrong|no\\b|stop\\b|don'?t\\b|actually|fix that|undo|revert|forget|ignore|skip)\\b/i.test(\n text,\n )\n ) {\n return 5;\n }\n }\n\n // ── Critical: error / exception messages ───────────────────────────\n if (\n /\\b(error|exception|fatal|critical|crash|panic|abort|segfault|core dump|undefined is not|null pointer|typeerror|referenceerror|syntaxerror)\\b/i.test(\n text,\n )\n ) {\n return 5;\n }\n\n // ── Critical: security findings ────────────────────────────────────\n if (\n /\\b(security|vulnerability|injection|xss|csrf|secret|apikey|api.key|hardcoded|leak|exploit|cve)\\b/i.test(\n text,\n )\n ) {\n return 5;\n }\n\n // ── Critical: architecture / design decisions ──────────────────────\n if (\n m.role === 'assistant' &&\n /\\b(architecture|design|approach|strategy|pattern|refactor|migrate|restructure|decision|trade.?off)\\b/i.test(\n text,\n )\n ) {\n return 5;\n }\n\n // ── Low: large tool results ────────────────────────────────────────\n if (hasLargeToolResult(m)) return 1;\n\n // ── Low: grep / list / tree outputs ────────────────────────────────\n if (\n m.role === 'user' &&\n !hasToolUse(m) &&\n /\\b(files_with_matches|count|found \\d+ match|directory tree|\\.\\.\\. and \\d+ more)\\b/i.test(text)\n ) {\n return 1;\n }\n\n // ── Default: medium ────────────────────────────────────────────────\n return 3;\n}\n\n/**\n * Build a content-aware digest of messages.\n *\n * Unlike `buildLosslessDigest` which preserves all text equally, this uses\n * `scoreMessage` to apply tiered treatment:\n * - Score 5 (critical): verbatim text\n * - Score 3 (medium): first sentence only\n * - Score 1 (low): one-line summary\n * - Score 0 (noise): collapsed to count marker\n */\nexport function buildSmartDigest(messages: readonly Message[]): string {\n const lines: string[] = [];\n const failureCounts = new Map<string, number>();\n let noiseCount = 0;\n\n for (const m of messages) {\n const score = scoreMessage(m, { failureCounts });\n const text = extractText(m);\n const toolCount = countToolBlocks(m);\n\n if (score === 0) {\n noiseCount++;\n continue;\n }\n\n const marker = toolCount > 0 ? ` [${toolCount} tool call(s)]` : '';\n let display: string;\n\n switch (score) {\n case 5: // Critical — keep verbatim\n display = text.trim();\n break;\n case 3: // Medium — first sentence\n display = firstSentence(text);\n break;\n case 1: // Low — one-line summary\n display = oneLineSummary(m, text);\n break;\n default:\n display = firstSentence(text);\n }\n\n if (display.length === 0 && toolCount === 0) continue;\n lines.push(`[${m.role}]: ${display}${marker}`);\n }\n\n if (noiseCount > 0) {\n lines.push(\n `[system]: ${noiseCount} low-importance turn(s) collapsed (repeated failures / pure tool I/O)`,\n );\n }\n\n return lines.join('\\n');\n}\n\nfunction countToolBlocks(m: Message): number {\n if (typeof m.content === 'string') return 0;\n return m.content.filter((b) => b.type === 'tool_use' || b.type === 'tool_result').length;\n}\n\nfunction firstSentence(text: string): string {\n const trimmed = text.trim();\n if (trimmed.length === 0) return '';\n const dot = trimmed.indexOf('. ');\n if (dot === -1) return trimmed.length > 150 ? `${trimmed.slice(0, 147)}…` : trimmed;\n const sentence = trimmed.slice(0, dot + 1);\n return sentence.length > 150 ? `${sentence.slice(0, 147)}…` : sentence;\n}\n\nfunction oneLineSummary(m: Message, text: string): string {\n const trimmed = text.trim();\n if (trimmed.length === 0) {\n // Pure tool result with no text\n if (typeof m.content !== 'string') {\n const results = m.content.filter((b) => b.type === 'tool_result');\n if (results.length > 0) {\n return `[${results.length} tool result(s) — see session log]`;\n }\n }\n return '[no text content]';\n }\n // Truncate to one line (~100 chars)\n const firstLine = trimmed.split('\\n')[0] ?? '';\n return firstLine.length > 100 ? `${firstLine.slice(0, 97)}…` : firstLine;\n}\n\n/**\n * Nearest safe cut boundary in [from, to]: the start of the exchange of the\n * closest user-with-text message. Returns -1 when no such boundary exists.\n */\nexport function findSafeBoundary(messages: readonly Message[], from: number, to: number): number {\n for (let i = to; i >= from; i--) {\n const m = messages[i];\n if (!m) continue;\n if (m.role === 'user' && hasTextContent(m)) {\n return findExchangeStart(messages, i);\n }\n }\n return -1;\n}\n\n/**\n * Walk backwards from a user message to find where its logical exchange began\n * (just after the last assistant message that made no tool calls).\n */\nexport function findExchangeStart(messages: readonly Message[], userIndex: number): number {\n for (let i = userIndex - 1; i >= 0; i--) {\n const m = messages[i];\n if (!m) continue;\n if (m.role === 'assistant') {\n const hasToolUse = Array.isArray(m.content)\n ? m.content.some((b) => b.type === 'tool_use')\n : false;\n if (!hasToolUse) return i + 1;\n } else if (m.role === 'user') {\n return i;\n }\n }\n return 0;\n}\n","import type { Context } from '../core/context.js';\nimport type { CompactReport, Compactor } from '../types/compactor.js';\nimport type { ContextWindowPolicy } from '../types/context-window.js';\nimport type { Message } from '../types/messages.js';\nimport { estimateRequestTokens } from '../utils/token-estimate.js';\nimport { repairToolUseAdjacency } from '../utils/message-invariants.js';\nimport { buildContextEvidenceDigest } from '../utils/context-evidence.js';\nimport {\n buildLosslessDigest,\n buildSmartDigest,\n eliseOldToolResults,\n estimateMessages,\n hasTextContent,\n} from './compaction-core.js';\n\nexport interface CompactorOptions {\n preserveK?: number | undefined;\n eliseThreshold?: number | undefined;\n /**\n * Enable content-aware digest mode. When true, `collapseAncientTurns` uses\n * `buildSmartDigest` which scores messages by importance: critical content\n * (errors, corrections, decisions) is kept verbatim; normal exchanges get\n * first-sentence summaries; large tool outputs and repeated failures are\n * aggressively compressed. Defaults to false (lossless digest).\n */\n smart?: boolean | undefined;\n /**\n * @deprecated Ignored. Token estimation is centralized in\n * `compaction-core`/`token-estimate` so all compactors and the context-pressure\n * monitor agree on one number. Kept only for backward-compatible call sites.\n */\n estimator?: (((text: string) => number)) | undefined;\n}\n\n/**\n * Default tools config values shared across CLI and WebUI.\n * Import this instead of hardcoding to avoid cross-surface inconsistencies.\n * These mirror the values in BEHAVIOR_DEFAULTS (config-loader.ts).\n *\n * @deprecated Import from '../types/default-config.js' instead.\n * This re-export exists for backward compatibility.\n */\nexport { DEFAULT_TOOLS_CONFIG, DEFAULT_CONTEXT_CONFIG, DEFAULT_AUTONOMY_CONFIG } from '../types/default-config.js';\n\nexport class HybridCompactor implements Compactor {\n private readonly preserveK: number;\n private readonly eliseThreshold: number;\n private readonly smart: boolean;\n\n constructor(opts: CompactorOptions = {}) {\n this.preserveK = opts.preserveK ?? 5;\n this.eliseThreshold = opts.eliseThreshold ?? 2000;\n this.smart = opts.smart ?? false;\n }\n\n async compact(ctx: Context, opts: { aggressive?: boolean | undefined } = {}): Promise<CompactReport> {\n const beforeTokens = estimateMessages(ctx.messages);\n const beforeFull = this.estimateFullRequest(ctx);\n const reductions: CompactReport['reductions'] = [];\n const policy = readContextWindowPolicy(ctx);\n const preserveK = policy?.preserveK ?? this.preserveK;\n const eliseThreshold = policy?.eliseThreshold ?? this.eliseThreshold;\n\n // Phase 1: elision (shared core handles tool_use/tool_result pair preservation).\n const elide = eliseOldToolResults(ctx.messages, { preserveK, eliseThreshold });\n if (elide.changed) ctx.state.replaceMessages(elide.messages);\n if (elide.saved > 0) reductions.push({ phase: 'elision', saved: elide.saved });\n\n // Phase 2: lossless collapse of ancient turns into a single digest.\n // Preserves ALL textual content (instructions, decisions, conclusions);\n // only raw tool I/O is dropped (it remains in the session log). No sub-LLM call.\n let collapsedDigest: string | undefined;\n let evidenceDigest: string | undefined;\n if (opts.aggressive) {\n const phase2 = this.collapseAncientTurns(ctx, preserveK);\n if (phase2.saved > 0) reductions.push({ phase: 'summary', saved: phase2.saved });\n collapsedDigest = phase2.digest;\n evidenceDigest = phase2.evidenceDigest;\n }\n\n const repaired = repairToolUseAdjacency(ctx.messages);\n if (repaired.report.changed) {\n ctx.state.replaceMessages(repaired.messages);\n }\n\n const afterTokens = estimateMessages(ctx.messages);\n const afterFull = this.estimateFullRequest(ctx);\n const quality = checkCompactionQuality(ctx, {\n collapsedDigest,\n evidenceDigest,\n reduced: beforeTokens > afterTokens || beforeFull > afterFull,\n });\n return {\n before: beforeTokens,\n after: afterTokens,\n fullRequestTokensBefore: beforeFull,\n fullRequestTokensAfter: afterFull,\n reductions,\n collapsedDigest,\n evidenceDigest,\n quality,\n repaired: repaired.report.changed\n ? {\n removedToolUses: repaired.report.removedToolUses,\n removedToolResults: repaired.report.removedToolResults,\n removedMessages: repaired.report.removedMessages,\n }\n : undefined,\n };\n }\n\n /**\n * Estimate the full API request token count: messages + systemPrompt + toolDefs.\n * This is the accurate figure for context-window pressure monitoring.\n */\n private estimateFullRequest(ctx: Context): number {\n return estimateRequestTokens(ctx.messages, ctx.systemPrompt, ctx.tools ?? []).total;\n }\n\n /**\n * Lossless rule-based collapse of ancient turns into a single digest message.\n *\n * Preserves ALL textual content of the collapsed range — user instructions,\n * assistant decisions/conclusions, and any prior digests (chained forward so\n * the digest stays lossless across repeated compactions). Only `tool_use` /\n * `tool_result` protocol blocks are dropped and replaced with a count marker;\n * their full payload already lives in the session log. No sub-LLM call.\n *\n * Returns the token savings and the digest text (for audit logging).\n */\n private collapseAncientTurns(\n ctx: Context,\n preserveK = this.preserveK,\n ): { saved: number; digest?: string | undefined; evidenceDigest?: string | undefined } {\n const messages = ctx.messages;\n const cutTarget = Math.max(0, messages.length - preserveK * 2);\n if (cutTarget <= 0) return { saved: 0 };\n\n // Find a safe boundary: nearest user-message-with-text at or after cutTarget.\n let boundary = -1;\n for (let i = cutTarget; i < messages.length; i++) {\n const m = messages[i];\n if (!m) continue;\n if (m.role === 'user' && hasTextContent(m)) {\n boundary = i;\n break;\n }\n }\n if (boundary <= 0) return { saved: 0 };\n\n const removed = messages.slice(0, boundary);\n const removedTokens = estimateMessages(removed);\n\n const historyDigest =\n this.smart\n ? buildSmartDigest(removed) ||\n `${removed.length} earlier turns (no textual content; tool I/O omitted; see session log)`\n : buildLosslessDigest(removed) ||\n `${removed.length} earlier turns (no textual content; tool I/O omitted; see session log)`;\n\n const evidenceDigest = buildContextEvidenceDigest(ctx);\n const digest = evidenceDigest\n ? `[context_state]\\n${evidenceDigest}\\n\\n[prior_history]\\n${historyDigest}`\n : historyDigest;\n\n const summaryMsg: Message = {\n role: 'system',\n content: `[prior_turns_digest: ${digest}]`,\n };\n\n // L1-A: route through ConversationState so subscribers see the rewrite.\n const tail = ctx.messages.slice(boundary);\n ctx.state.replaceMessages([summaryMsg, ...tail]);\n return {\n saved: Math.max(0, removedTokens - estimateMessages([summaryMsg])),\n digest,\n evidenceDigest: evidenceDigest || undefined,\n };\n }\n}\n\nfunction checkCompactionQuality(\n ctx: Context,\n opts: {\n collapsedDigest?: string | undefined;\n evidenceDigest?: string | undefined;\n reduced: boolean;\n },\n): CompactReport['quality'] {\n const evidence = ctx.contextEvidence;\n const digest = `${opts.collapsedDigest ?? ''}\\n${opts.evidenceDigest ?? ''}`;\n const hasIntent = Boolean(evidence?.currentIntent?.text || /\\b(intent|goal|session_goals)\\b/i.test(digest));\n const hasPathTrail = Boolean(\n Object.keys(evidence?.fileGraph ?? {}).length > 0 ||\n (evidence?.toolCalls.length ?? 0) > 0 ||\n /\\b(dependency_graph|tool_trail|files=)\\b/i.test(digest),\n );\n const issues: string[] = [];\n if (opts.reduced && !hasIntent) issues.push('missing intent anchor');\n if (opts.reduced && !hasPathTrail) issues.push('missing tool/path trail');\n return {\n ok: issues.length === 0,\n hasIntent,\n hasPathTrail,\n issues,\n };\n}\n\nfunction readContextWindowPolicy(ctx: Context): ContextWindowPolicy | null {\n const policy = ctx.meta?.['contextWindowPolicy'];\n if (!policy || typeof policy !== 'object') return null;\n const candidate = policy as Partial<ContextWindowPolicy>;\n if (\n typeof candidate.preserveK !== 'number' ||\n typeof candidate.eliseThreshold !== 'number'\n ) {\n return null;\n }\n return candidate as ContextWindowPolicy;\n}\n","import type { Context } from '../core/context.js';\nimport type { TextBlock } from '../types/blocks.js';\nimport { isTextBlock } from '../types/blocks.js';\nimport type { CompactReport, Compactor } from '../types/compactor.js';\nimport type { Message } from '../types/messages.js';\nimport type { Provider, Request } from '../types/provider.js';\nimport { estimateRequestTokens } from '../utils/token-estimate.js';\nimport { repairToolUseAdjacency } from '../utils/message-invariants.js';\nimport {\n buildLosslessDigest,\n eliseOldToolResults,\n estimateMessages,\n findSafeBoundary,\n} from './compaction-core.js';\n\n/**\n * Options for IntelligentCompactor.\n */\nexport interface IntelligentCompactorOptions {\n /** Provider to use for LLM-assisted summarization. Required. */\n provider: Provider;\n /** Fraction of maxContext that triggers a warning (default 0.6). */\n warnThreshold?: number | undefined;\n /** Fraction of maxContext that triggers soft compaction (default 0.75). */\n softThreshold?: number | undefined;\n /** Fraction of maxContext that triggers hard compaction (default 0.9). */\n hardThreshold?: number | undefined;\n /** Max context window in tokens (used only for threshold fraction math). */\n maxContext?: number | undefined;\n /** How many recent (user+assistant) pairs to always preserve (default 4). */\n preserveK?: number | undefined;\n /** Token threshold below which tool results are not elided (default 500). */\n eliseThreshold?: number | undefined;\n /** System prompt for the summarizer sub-LLM. */\n summarizerPrompt?: string | undefined;\n /**\n * Model ID to use for summarization. When not set, the same model as the\n * agent is used (which risks cascading failure on context overflow). Set to\n * a fast/cheap model like `claude-3-5-haiku-20240620` for resilience.\n */\n summarizerModel?: string | undefined;\n}\n\n/**\n * An importance label for a message or message range.\n */\nexport type Importance = 'critical' | 'high' | 'medium' | 'low';\n\n/**\n * Result of importance analysis.\n */\nexport interface ImportanceAnalysis {\n messages: Array<{ index: number; importance: Importance; reason: string }>;\n criticalRanges: Array<{ from: number; to: number; summary: string }>;\n}\n\n/**\n * IntelligentCompactor uses an LLM to:\n * - Analyze message importance and preserve critical context\n * - Generate semantic summaries for old message ranges\n * - Make intelligent decisions about what to compact\n *\n * It builds on the shared `compaction-core` elision/boundary primitives and\n * adds LLM-assisted summarization on top. When the summarizer call fails it\n * falls back to the same lossless rule-based digest used by HybridCompactor.\n */\nexport class IntelligentCompactor implements Compactor {\n private readonly provider: Provider;\n private readonly warnThreshold: number;\n private readonly softThreshold: number;\n private readonly hardThreshold: number;\n private readonly maxContext: number;\n private readonly preserveK: number;\n private readonly eliseThreshold: number;\n private readonly summarizerPrompt: string;\n private readonly summarizerModel?: string | undefined;\n\n constructor(opts: IntelligentCompactorOptions) {\n this.provider = opts.provider;\n this.warnThreshold = opts.warnThreshold ?? 0.6;\n this.softThreshold = opts.softThreshold ?? 0.75;\n this.hardThreshold = opts.hardThreshold ?? 0.9;\n this.maxContext = opts.maxContext ?? 128_000;\n this.preserveK = opts.preserveK ?? 4;\n this.eliseThreshold = opts.eliseThreshold ?? 500;\n this.summarizerPrompt =\n opts.summarizerPrompt ??\n 'You are a context summarizer. Given a list of conversation messages, produce a concise but complete summary that preserves all factual information, decisions made, and any state changes (e.g. file edits, todo updates). Do not add commentary. Output only the summary.';\n this.summarizerModel = opts.summarizerModel;\n }\n\n async compact(ctx: Context, opts: { aggressive?: boolean | undefined } = {}): Promise<CompactReport> {\n const beforeTokens = estimateMessages(ctx.messages);\n const beforeFull = this.estimateFullRequest(ctx);\n const reductions: CompactReport['reductions'] = [];\n\n // Use full request tokens for threshold decisions — messages alone are inaccurate.\n const load = beforeFull / this.maxContext;\n // Past hardThreshold, force aggressive regardless of caller preference —\n // the alternative (lightweight elision) is unlikely to recover enough.\n const aggressive =\n load >= this.hardThreshold ? true : (opts.aggressive ?? load >= this.softThreshold);\n\n // Phase 1: always run elision (preserves recent K pairs)\n const saved1 = this.elide(ctx);\n if (saved1 > 0) reductions.push({ phase: 'elision', saved: saved1 });\n\n // Phase 2: LLM summarization of ancient turns\n let collapsedDigest: string | undefined;\n if (aggressive) {\n const phase2 = await this.summarizeAncientTurns(ctx);\n if (phase2.saved > 0) reductions.push({ phase: 'summary', saved: phase2.saved });\n collapsedDigest = phase2.digest;\n } else if (load >= this.warnThreshold) {\n // Non-aggressive: lightweight elision only.\n const saved2 = this.elide(ctx);\n if (saved2 > 0) reductions.push({ phase: 'elision', saved: saved2 });\n }\n\n const repaired = repairToolUseAdjacency(ctx.messages);\n if (repaired.report.changed) ctx.state.replaceMessages(repaired.messages);\n\n const afterTokens = estimateMessages(ctx.messages);\n const afterFull = this.estimateFullRequest(ctx);\n return {\n before: beforeTokens,\n after: afterTokens,\n fullRequestTokensBefore: beforeFull,\n fullRequestTokensAfter: afterFull,\n reductions,\n collapsedDigest,\n repaired: repaired.report.changed\n ? {\n removedToolUses: repaired.report.removedToolUses,\n removedToolResults: repaired.report.removedToolResults,\n removedMessages: repaired.report.removedMessages,\n }\n : undefined,\n };\n }\n\n /**\n * Estimate the full API request token count: messages + systemPrompt + toolDefs.\n * This is the accurate figure for context-window pressure monitoring.\n */\n private estimateFullRequest(ctx: Context): number {\n return estimateRequestTokens(ctx.messages, ctx.systemPrompt, ctx.tools ?? []).total;\n }\n\n /** Run shared tool-result elision and commit through ConversationState. */\n private elide(ctx: Context): number {\n const result = eliseOldToolResults(ctx.messages, {\n preserveK: this.preserveK,\n eliseThreshold: this.eliseThreshold,\n });\n if (result.changed) ctx.state.replaceMessages(result.messages);\n return result.saved;\n }\n\n private async summarizeAncientTurns(\n ctx: Context,\n ): Promise<{ saved: number; digest?: string | undefined }> {\n const messages = ctx.messages;\n const cutoff = Math.max(0, messages.length - this.preserveK * 2);\n if (cutoff <= 2) return { saved: 0 };\n\n // Find the best boundary in the ancient region\n const boundary = findSafeBoundary(messages, 0, cutoff);\n if (boundary <= 1) return { saved: 0 };\n\n const toSummarize = messages.slice(0, boundary);\n const removedTokens = estimateMessages(toSummarize);\n\n let summaryText: string;\n try {\n summaryText = await this.callSummarizer(toSummarize, ctx);\n } catch {\n // Fallback: lossless rule-based digest (text preserved, tool I/O dropped).\n // Cannot fail and preserves the semantic content the summarizer would have.\n summaryText =\n buildLosslessDigest(toSummarize) ||\n `${toSummarize.length} earlier turns (semantic content preserved)`;\n }\n\n const summaryMsg: Message = {\n role: 'system',\n content: `[prior_turns_summary: ${summaryText}]`,\n };\n const summaryTokens = estimateMessages([summaryMsg]);\n\n // L1-A: route through ConversationState so subscribers see the rewrite.\n const tail = ctx.messages.slice(boundary);\n ctx.state.replaceMessages([summaryMsg, ...tail]);\n return { saved: Math.max(0, removedTokens - summaryTokens), digest: summaryText };\n }\n\n private async callSummarizer(messages: Message[], ctx: Context): Promise<string> {\n const prompt: TextBlock[] = [\n { type: 'text', text: this.summarizerPrompt },\n { type: 'text', text: '\\n\\nConversation to summarize:\\n' },\n ...this.messagesToText(messages),\n ];\n\n const req: Request = {\n model: this.summarizerModel ?? ctx.model,\n system: prompt,\n messages: [],\n maxTokens: 1024,\n };\n\n // Use abort signal from context if available.\n // Fall back to a fresh controller only if ctx.signal is absent — this\n // avoids leaking AbortControllers on every summarizer call (the original\n // `?? new AbortController().signal` created a controller that was never\n // connected to anything, making cancellation a no-op).\n const ac = ctx.signal ? undefined : new AbortController();\n const signal = ctx.signal ?? ac?.signal;\n let res;\n try {\n res = await this.provider.complete(req, { signal });\n } finally {\n ac?.abort();\n }\n\n const textBlocks = res.content.filter(isTextBlock);\n return (\n textBlocks\n .map((b) => b.text)\n .join('\\n')\n .trim() || '(empty summary)'\n );\n }\n\n private messagesToText(messages: Message[]): TextBlock[] {\n const lines: string[] = [];\n for (const m of messages) {\n const role = m.role.padEnd(10, ' ');\n if (typeof m.content === 'string') {\n lines.push(`[${role}]: ${m.content.slice(0, 500)}`);\n } else if (Array.isArray(m.content)) {\n const textParts = m.content.filter(isTextBlock).map((b) => b.text);\n if (textParts.length > 0) {\n lines.push(`[${role}]: ${textParts.join(' ').slice(0, 500)}`);\n }\n }\n }\n return [{ type: 'text', text: lines.join('\\n') }];\n }\n}\n","import { expectDefined } from '../utils/expect-defined.js';\nimport { estimateMessageTokens, estimateTextTokens } from '../utils/token-estimate.js';\nimport { isTextBlock } from '../types/blocks.js';\nimport type { Message } from '../types/messages.js';\nimport type { Provider, Request } from '../types/provider.js';\nimport type { MessageSelector, SelectorResult } from '../types/selector.js';\nexport interface LLMSelectorOptions {\n /** Provider used for the selector LLM call. Required. */\n provider: Provider;\n /** Model for the selector. Defaults to the provider's default model. */\n model?: string | undefined;\n /**\n * Maximum tokens to keep in context (target budget).\n * Selector will aim to keep total content below this.\n */\n maxContextTokens?: number | undefined;\n /**\n * Prompt instructing the selector how to behave.\n * Should guide the LLM on importance tiers and output format.\n */\n systemPrompt?: string | undefined;\n /**\n * Maximum output tokens for the selector LLM call.\n * Controls both the JSON response budget and the token reservation for the\n * history text budget calculation (default: 1024).\n */\n maxOutputTokens?: number | undefined;\n}\n\nconst DEFAULT_SYSTEM_PROMPT = `You are a context pruning assistant. Given a conversation history and a token budget, decide which message ranges are worth keeping verbatim and which should be collapsed into summaries.\n\nOutput a JSON object with this structure:\n{\n \"kept\": [{\"from\": 0, \"to\": 5, \"importance\": \"critical\"}],\n \"collapsed\": [{\"from\": 6, \"to\": 20, \"summary\": \"optional summary\"}],\n \"reasoning\": \"brief explanation of decisions\"\n}\n\nImportance tiers:\n- \"critical\": decisions, file edits, tool results that affect state, final answers\n- \"high\": substantive tool use, complex reasoning, non-obvious observations\n- \"medium\": routine exchanges, confirmations, straightforward Q&A\n\nRules:\n- Always keep the most recent K pairs (preserve recency)\n- Never collapse the final 2 user/assistant pairs (working memory)\n- Preserve tool results that modified files or had external effects\n- Collapse old, low-information exchanges (greetings, acknowledgements, etc.)\n- If unsure, keep rather than collapse (errors are more costly than waste)\n\nReturn ONLY the JSON object, no markdown, no explanation outside the JSON.`;\n\n/**\n * Format messages as a compact text dump for the selector LLM.\n * Uses token estimation (not character count) to budget the output,\n * so long sessions don't silently truncate the selector's view of history.\n */\nfunction formatMessages(messages: Message[], maxTokens = 2048): string {\n const lines: string[] = [];\n let usedTokens = 0;\n for (let i = 0; i < messages.length; i++) {\n const m = expectDefined(messages[i]);\n const role = m.role.padEnd(10, ' ');\n let text: string;\n if (typeof m.content === 'string') {\n text = m.content.slice(0, 500);\n } else {\n const content = m.content as import('../types/blocks.js').ContentBlock[];\n text = content\n .filter(isTextBlock)\n .map((b) => b.text)\n .join(' ');\n // Also capture tool names for context\n const toolUses = content.filter((b) => b.type === 'tool_use');\n if (toolUses.length > 0) {\n text += ` [tools: ${toolUses.map((b) => (b as { name?: string }).name).filter(Boolean).join(', ')}]`;\n }\n }\n const line = `[${i}][${role}]: ${text}`;\n const lineTokens = estimateTextTokens(line);\n if (usedTokens + lineTokens > maxTokens) break;\n lines.push(line);\n usedTokens += lineTokens;\n }\n return lines.join('\\n');\n}\n\n/**\n * LLM-powered message selector. Calls a sub-LLM to analyze the\n * message history and produce a keep/collapse plan — more surgical\n * than fixed-window rules.\n */\nexport class LLMSelector implements MessageSelector {\n private readonly provider: Provider;\n private readonly model: string;\n private readonly maxContextTokens: number;\n private readonly systemPrompt: string;\n private readonly maxOutputTokens: number;\n\n constructor(opts: LLMSelectorOptions) {\n this.provider = opts.provider;\n this.model = opts.model ?? 'unknown';\n if (\n this.model === 'unknown' &&\n (process.env['NODE_ENV'] === 'development' || process.env['WRONGSTACK_DEBUG'] === '1')\n ) {\n console.warn(\n '[LLMSelector] model not set — selector will use the provider default. Set `model` explicitly in LLMSelectorOptions to silence this warning.',\n );\n }\n this.maxContextTokens = opts.maxContextTokens ?? 40_000;\n this.systemPrompt = opts.systemPrompt ?? DEFAULT_SYSTEM_PROMPT;\n this.maxOutputTokens = opts.maxOutputTokens ?? 1024;\n }\n\n async select(messages: Message[], maxToKeep: number): Promise<SelectorResult> {\n const effectiveBudget = Math.min(maxToKeep, this.maxContextTokens);\n\n const totalTokens = estimateMessageTokens(messages);\n const systemText = `${this.systemPrompt}\\n\\nConversation (${messages.length} messages, ~${totalTokens} tokens, budget: ${effectiveBudget}):\\n`;\n // Reserve tokens for the system prefix and output (maxOutputTokens), then give the\n // rest to the formatted history so the selector sees the maximum possible context.\n const systemTokens = estimateTextTokens(systemText);\n const historyBudget = Math.max(512, effectiveBudget - systemTokens - this.maxOutputTokens);\n\n // Build a concise representation of the conversation within the token budget\n const historyText = formatMessages(messages, historyBudget);\n\n // Add instruction to stay within budget\n const budgetInstruction =\n totalTokens > effectiveBudget\n ? `\\n\\nIMPORTANT: Total conversation (${totalTokens} tokens) exceeds budget (${effectiveBudget}). You MUST collapse enough to fit. Prefer collapsing older/lower-importance ranges.`\n : '';\n\n const req: Request = {\n model: this.model,\n system: [{ type: 'text', text: systemText + budgetInstruction }],\n messages: [{ role: 'user', content: historyText }],\n maxTokens: this.maxOutputTokens,\n };\n\n let raw: string;\n const ac = new AbortController();\n try {\n // 30-second timeout so a stuck selector LLM call can't hang the compactor.\n const timeoutSignal = AbortSignal.timeout(30_000);\n const res = await this.provider.complete(req, {\n signal: AbortSignal.any([ac.signal, timeoutSignal]),\n });\n const textBlocks = res.content.filter(isTextBlock);\n raw = textBlocks\n .map((b) => b.text)\n .join('\\n')\n .trim();\n } catch (err) {\n if (err instanceof Error) {\n console.warn('[LLMSelector] selector call failed, using recency fallback:', err.message);\n }\n return this.fallbackSelect(messages, effectiveBudget);\n } finally {\n ac.abort();\n }\n\n return this.parseSelectorOutput(raw, messages);\n }\n\n private fallbackSelect(messages: Message[], budget: number): SelectorResult {\n // Simple fallback: keep from the end until we hit budget\n const toKeep: SelectorResult['kept'] = [];\n const toCollapse: SelectorResult['collapsed'] = [];\n\n let tokenCount = 0;\n let startIdx = 0;\n\n // Scan from the end backwards\n for (let i = messages.length - 1; i >= 0; i--) {\n const m = expectDefined(messages[i]);\n const cost = estimateMessageTokens([m]);\n\n if (tokenCount + cost <= budget) {\n tokenCount += cost;\n } else {\n startIdx = i + 1;\n break;\n }\n }\n\n if (startIdx > 0) {\n toCollapse.push({ from: 0, to: startIdx - 1 });\n }\n toKeep.push({ from: startIdx, to: messages.length - 1, importance: 'high' });\n\n return {\n kept: toKeep,\n collapsed: toCollapse,\n reasoning: `Fallback: kept last ${messages.length - startIdx} messages within ${budget} token budget`,\n };\n }\n\n /**\n * Parse and validate the raw LLM output into a SelectorResult.\n * Falls back to recency-based selection if the LLM output is malformed,\n * out-of-bounds, or internally inconsistent.\n */\n private parseSelectorOutput(raw: string, messages: Message[]): SelectorResult {\n const messageCount = messages.length;\n if (messageCount === 0) {\n return { kept: [], collapsed: [], reasoning: 'empty session' };\n }\n\n // Try to extract JSON from the response\n const jsonStart = raw.indexOf('{');\n const jsonEnd = raw.lastIndexOf('}');\n if (jsonStart === -1 || jsonEnd === -1) {\n return this.fallbackSelect(messages, this.maxContextTokens);\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw.slice(jsonStart, jsonEnd + 1));\n } catch {\n return this.fallbackSelect(messages, this.maxContextTokens);\n }\n\n const obj = parsed as Record<string, unknown>;\n const keptRaw =\n (obj.kept as Array<{ from: number; to: number; importance: string }> | undefined) ?? [];\n const collapsedRaw =\n (obj.collapsed as Array<{ from: number; to: number; summary?: string | undefined }> | undefined) ?? [];\n\n // Validate kept ranges — must be within [0, messageCount), from <= to\n const kept: SelectorResult['kept'] = [];\n for (const k of keptRaw) {\n if (\n typeof k.from !== 'number' ||\n typeof k.to !== 'number' ||\n k.from < 0 ||\n k.to >= messageCount ||\n k.from > k.to\n ) {\n return this.fallbackSelect(messages, this.maxContextTokens);\n }\n kept.push({\n from: k.from,\n to: k.to,\n importance: (k.importance ?? 'medium') as 'critical' | 'high' | 'medium',\n });\n }\n\n // Validate collapsed ranges — same bounds check\n const collapsed: SelectorResult['collapsed'] = [];\n for (const c of collapsedRaw) {\n if (\n typeof c.from !== 'number' ||\n typeof c.to !== 'number' ||\n c.from < 0 ||\n c.to >= messageCount ||\n c.from > c.to\n ) {\n return this.fallbackSelect(messages, this.maxContextTokens);\n }\n collapsed.push({ from: c.from, to: c.to, summary: c.summary });\n }\n\n // Check for overlaps: kept ranges must not overlap with each other or with collapsed ranges\n const allRanges: Array<{ from: number; to: number }> = [...kept, ...collapsed];\n for (let i = 0; i < allRanges.length; i++) {\n const a = allRanges[i];\n if (!a) continue;\n for (let j = i + 1; j < allRanges.length; j++) {\n const b = allRanges[j];\n if (!b) continue;\n // Overlap: a starts before b ends AND a ends after b starts\n if (a.from <= b.to && a.to >= b.from) {\n return this.fallbackSelect(messages, this.maxContextTokens);\n }\n }\n }\n\n return {\n kept,\n collapsed,\n reasoning: typeof obj.reasoning === 'string' ? obj.reasoning : '',\n };\n }\n}\n","import type { Context } from '../core/context.js';\nimport { LLMSelector } from '../models/llm-selector.js';\nimport { isTextBlock } from '../types/blocks.js';\nimport type { CompactReport, Compactor } from '../types/compactor.js';\nimport type { Message } from '../types/messages.js';\nimport type { Provider, Request } from '../types/provider.js';\nimport type { MessageSelector, SelectorResult } from '../types/selector.js';\nimport { estimateRequestTokens } from '../utils/token-estimate.js';\nimport { repairToolUseAdjacency } from '../utils/message-invariants.js';\nimport {\n eliseOldToolResults as coreEliseOldToolResults,\n estimateMessages,\n} from './compaction-core.js';\n\n/**\n * Options for SelectiveCompactor — the most configurable compactor.\n */\nexport interface SelectiveCompactorOptions {\n /** Provider for LLM calls (selector + summarizer). Required. */\n provider: Provider;\n /** Selector for LLM-driven importance analysis. */\n selector?: MessageSelector | undefined;\n /** Fraction of maxContext that triggers a warning (default 0.6). */\n warnThreshold?: number | undefined;\n /** Fraction of maxContext that triggers soft compaction (default 0.75). */\n softThreshold?: number | undefined;\n /** Fraction of maxContext that triggers hard compaction (default 0.9). */\n hardThreshold?: number | undefined;\n /** Max context window in tokens (used for threshold fraction math). */\n maxContext?: number | undefined;\n /** How many recent (user+assistant) pairs to always preserve (default 4). */\n preserveK?: number | undefined;\n /** Token threshold below which tool results are not elided (default 500). */\n eliseThreshold?: number | undefined;\n /** Model for selector LLM calls (default: same as provider default). */\n selectorModel?: string | undefined;\n /** Max output tokens for the selector LLM call (default: 1024). */\n selectorMaxOutputTokens?: number | undefined;\n /** Summarizer model for collapsed ranges (default: same as selectorModel). */\n summarizerModel?: string | undefined;\n /** Prompt for the summarizer sub-LLM. */\n summarizerPrompt?: string | undefined;\n}\n\n/**\n * SelectiveCompactor uses an LLM-driven MessageSelector to make\n * surgical decisions about which message ranges to keep vs collapse.\n *\n * Compared to HybridCompactor / IntelligentCompactor:\n * - HybridCompactor: rule-based (preserveK + elision), no LLM calls\n * - IntelligentCompactor: LLM summarization but no structured selection\n * - SelectiveCompactor: full LLM-driven selection + optional summarization\n */\nexport class SelectiveCompactor implements Compactor {\n private readonly provider: Provider;\n private readonly selector: MessageSelector;\n private readonly warnThreshold: number;\n private readonly softThreshold: number;\n private readonly hardThreshold: number;\n private readonly maxContext: number;\n private readonly preserveK: number;\n private readonly eliseThreshold: number;\n private readonly summarizerModel: string | undefined;\n private readonly summarizerPrompt: string;\n\n constructor(opts: SelectiveCompactorOptions) {\n this.provider = opts.provider;\n this.selector =\n opts.selector ?? new LLMSelector({ provider: opts.provider, model: opts.selectorModel, maxOutputTokens: opts.selectorMaxOutputTokens });\n this.warnThreshold = opts.warnThreshold ?? 0.6;\n this.softThreshold = opts.softThreshold ?? 0.75;\n this.hardThreshold = opts.hardThreshold ?? 0.9;\n this.maxContext = opts.maxContext ?? 128_000;\n this.preserveK = opts.preserveK ?? 4;\n this.eliseThreshold = opts.eliseThreshold ?? 500;\n // Leave undefined when unset so summarizeRange() can fall back to the\n // live ctx.model (mirrors IntelligentCompactor). Never send a 'unknown'\n // sentinel to the provider — that yields a 400 in non-dev deployments\n // where the warning below is suppressed.\n this.summarizerModel = opts.summarizerModel ?? opts.selectorModel;\n if (\n this.summarizerModel === undefined &&\n (process.env['NODE_ENV'] === 'development' || process.env['WRONGSTACK_DEBUG'] === '1')\n ) {\n console.warn(\n '[SelectiveCompactor] summarizerModel not set — will fall back to ctx.model at summarize time. Set `summarizerModel` explicitly to silence this warning.',\n );\n }\n this.summarizerPrompt =\n opts.summarizerPrompt ??\n 'You are a context summarizer. Given a list of messages, produce a concise summary that preserves all factual information, decisions, file changes, and state changes. Do not add commentary or opinions.';\n }\n\n async compact(ctx: Context, opts: { aggressive?: boolean | undefined } = {}): Promise<CompactReport> {\n const beforeTokens = this.estimateTokens(ctx.messages);\n const beforeFull = this.estimateFullRequest(ctx);\n const reductions: CompactReport['reductions'] = [];\n\n // Use full request tokens for threshold decisions — messages alone are inaccurate.\n const load = beforeFull / this.maxContext;\n const shouldCompact = load >= this.warnThreshold || opts.aggressive;\n\n if (!shouldCompact) {\n // Only do lightweight elision if below warn threshold\n const saved = this.eliseOldToolResults(ctx);\n if (saved > 0) reductions.push({ phase: 'elision', saved });\n const repair = this.repairProtocolAdjacency(ctx);\n const afterTokens = this.estimateTokens(ctx.messages);\n const afterFull = this.estimateFullRequest(ctx);\n return {\n before: beforeTokens,\n after: afterTokens,\n fullRequestTokensBefore: beforeFull,\n fullRequestTokensAfter: afterFull,\n reductions,\n repaired: repair,\n };\n }\n\n // Phase 1: elision — always run first to get a baseline reduction\n const savedElision = this.eliseOldToolResults(ctx);\n if (savedElision > 0) reductions.push({ phase: 'elision', saved: savedElision });\n\n // Phase 2: LLM-driven selective compaction\n const afterPhase1 = this.estimateTokens(ctx.messages);\n const targetBudget = this.computeTargetBudget(load);\n\n if (afterPhase1 > targetBudget) {\n const savedSelective = await this.runSelector(ctx, targetBudget);\n if (savedSelective > 0) reductions.push({ phase: 'selective', saved: savedSelective });\n }\n\n const repair = this.repairProtocolAdjacency(ctx);\n const afterTokens = this.estimateTokens(ctx.messages);\n const afterFull = this.estimateFullRequest(ctx);\n return {\n before: beforeTokens,\n after: afterTokens,\n fullRequestTokensBefore: beforeFull,\n fullRequestTokensAfter: afterFull,\n reductions,\n repaired: repair,\n };\n }\n\n /**\n * Estimate the full API request token count: messages + systemPrompt + toolDefs.\n * This is the accurate figure for context-window pressure monitoring.\n */\n private estimateFullRequest(ctx: Context): number {\n const breakdown = estimateRequestTokens(ctx.messages, ctx.systemPrompt, ctx.tools ?? []);\n return breakdown.total;\n }\n\n private repairProtocolAdjacency(ctx: Context): CompactReport['repaired'] {\n const repaired = repairToolUseAdjacency(ctx.messages);\n if (repaired.report.changed) ctx.state.replaceMessages(repaired.messages);\n return repaired.report.changed\n ? {\n removedToolUses: repaired.report.removedToolUses,\n removedToolResults: repaired.report.removedToolResults,\n removedMessages: repaired.report.removedMessages,\n }\n : undefined;\n }\n\n /**\n * Run the LLM selector to decide what to keep vs collapse.\n * Returns the token savings achieved.\n */\n private async runSelector(ctx: Context, targetBudget: number): Promise<number> {\n const before = this.estimateTokens(ctx.messages);\n\n let result: SelectorResult;\n try {\n result = await this.selector.select(ctx.messages, targetBudget);\n } catch {\n // Fallback to aggressive recency preservation\n return this.aggressiveRecencyTrim(ctx);\n }\n\n // Execute the selector's plan\n await this.executePlan(ctx, result);\n\n const after = this.estimateTokens(ctx.messages);\n return Math.max(0, before - after);\n }\n\n /**\n * Execute a SelectorResult plan: collapse/remove ranges and\n * insert summaries where the selector provided them.\n */\n private async executePlan(ctx: Context, plan: SelectorResult): Promise<void> {\n if (ctx.messages.length === 0) return;\n\n // Process collapsed ranges in reverse order to preserve indices. We work\n // on a local copy and commit through `ctx.state.replaceMessages` at the\n // end so subscribers see a single state change for the whole rewrite.\n const messages = [...ctx.messages];\n const sortedCollapsed = [...plan.collapsed].sort((a, b) => b.from - a.from);\n\n for (const range of sortedCollapsed) {\n if (range.from < 0 || range.to >= messages.length || range.from > range.to) continue;\n\n let summary = range.summary;\n if (!summary) {\n const toSummarize = messages.slice(range.from, range.to + 1);\n summary = await this.summarizeRange(toSummarize, ctx);\n }\n\n const summaryMsg: Message = {\n role: 'system',\n content: `[prior_turns_${range.from}-${range.to}: ${summary}]`,\n };\n\n messages.splice(range.from, range.to - range.from + 1, summaryMsg);\n }\n\n ctx.state.replaceMessages(messages);\n }\n\n private async summarizeRange(messages: Message[], ctx: Context): Promise<string> {\n const systemText = `${this.summarizerPrompt}\\n\\nSummarize the following message range:`;\n const body = messages.map((m, i) => `[${i}] ${m.role}: ${this.messagePreview(m)}`).join('\\n');\n\n const req: Request = {\n model: this.summarizerModel ?? ctx.model,\n system: [{ type: 'text', text: systemText }],\n messages: [{ role: 'user', content: body }],\n maxTokens: 512,\n };\n\n try {\n // 30-second timeout so a stuck summarizer can't hang compaction.\n const timeoutSignal = AbortSignal.timeout(30_000);\n const res = await this.provider.complete(req, {\n signal: AbortSignal.any([ctx.signal, timeoutSignal]),\n });\n return (\n res.content\n .filter(isTextBlock)\n .map((b) => b.text)\n .join('\\n')\n .trim() || '(empty)'\n );\n } catch {\n return `[${messages.length} earlier turns omitted]`;\n }\n }\n\n private messagePreview(m: Message): string {\n if (typeof m.content === 'string') return m.content.slice(0, 300);\n return m.content\n .filter(isTextBlock)\n .map((b) => b.text)\n .join(' ')\n .slice(0, 300);\n }\n\n /**\n * Fallback when selector fails: aggressively trim from the oldest end\n * until we hit targetBudget.\n */\n private aggressiveRecencyTrim(ctx: Context): number {\n const messages = ctx.messages;\n const preserveIdx = Math.max(0, messages.length - this.preserveK * 2);\n\n if (preserveIdx <= 0) return 0;\n\n // Find safe boundary near preserveIdx\n let boundary = preserveIdx;\n for (let i = preserveIdx; i < messages.length && i < preserveIdx + 6; i++) {\n const m = messages[i];\n if (!m) continue;\n if (m.role === 'user' && this.hasTextContent(m)) {\n boundary = i;\n break;\n }\n }\n\n const removed = messages.slice(0, boundary);\n const removedTokens = this.estimateTokens(removed);\n\n const summaryMsg: Message = {\n role: 'system',\n content: `[${removed.length} earlier turns trimmed — see session log for details]`,\n };\n const tail = messages.slice(boundary);\n ctx.state.replaceMessages([summaryMsg, ...tail]);\n\n return Math.max(0, removedTokens - this.estimateTokens([summaryMsg]));\n }\n\n private computeTargetBudget(load: number): number {\n if (load >= this.hardThreshold) {\n return Math.floor(this.maxContext * 0.5); // keep only 50%\n }\n if (load >= this.softThreshold) {\n return Math.floor(this.maxContext * 0.65); // keep 65%\n }\n return Math.floor(this.maxContext * 0.75); // keep 75% at warn\n }\n\n private eliseOldToolResults(ctx: Context): number {\n // Delegate to the shared core so SelectiveCompactor gets the same\n // tool_use/tool_result pair preservation as the other compactors — its\n // previous local copy lacked the forward walk and could elide the result\n // of a tool call it was supposed to keep.\n const result = coreEliseOldToolResults(ctx.messages, {\n preserveK: this.preserveK,\n eliseThreshold: this.eliseThreshold,\n });\n if (result.changed) ctx.state.replaceMessages(result.messages);\n return result.saved;\n }\n\n private hasTextContent(m: Message): boolean {\n if (typeof m.content === 'string') return m.content.trim().length > 0;\n return m.content.some((b) => b.type === 'text' && b.text.trim().length > 0);\n }\n\n /**\n * Estimate message-array tokens via the shared `estimateMessages` primitive\n * so SelectiveCompactor's before/after/load figures agree with the\n * middleware threshold math and the other compactors. Previously this used a\n * private `ceil(len/3.5)` walk that diverged from the calibrated shared\n * estimator, causing the selective `load`/`targetBudget` comparison to mix\n * two incompatible token scales.\n */\n private estimateTokens(messages: Message[]): number {\n return estimateMessages(messages);\n }\n}\n","import type { Context } from '../core/context.js';\nimport type { CompactReport, Compactor } from '../types/compactor.js';\nimport type { ContextWindowPolicy } from '../types/context-window.js';\nimport { HybridCompactor } from './compactor.js';\nimport { IntelligentCompactor } from './intelligent-compactor.js';\nimport { SelectiveCompactor } from './selective-compactor.js';\n\nexport type CompactorStrategy = 'hybrid' | 'intelligent' | 'selective';\n\nexport interface StrategyCompactorOptions {\n /** Which compactor to use. Defaults to 'hybrid' (lossless, no LLM). */\n strategy?: CompactorStrategy | string | undefined;\n /** Recent user/assistant pairs to always preserve. */\n preserveK?: number | undefined;\n /** Token threshold below which tool results are not elided. */\n eliseThreshold?: number | undefined;\n /**\n * Enable content-aware smart digest for 'hybrid' strategy. When true,\n * collapsed ancient turns use buildSmartDigest: critical content (errors,\n * corrections, decisions) stays verbatim; normal exchanges get first-sentence\n * summaries; noise (repeated failures, large tool outputs) is aggressively\n * compressed. Defaults to false (lossless digest).\n */\n smart?: boolean | undefined;\n /** Model used by the LLM-backed strategies for summarization/selection. */\n summarizerModel?: string | undefined;\n /** Max output tokens for the selector LLM call in 'selective' strategy (default: 1024). */\n selectorMaxOutputTokens?: number | undefined;\n /**\n * Legacy shortcut for `strategy: 'selective'`. When `strategy` is unset (or\n * 'hybrid') and this is true, the selective (LLM-driven) compactor is used.\n * An explicit `strategy` always wins.\n */\n llmSelector?: boolean | undefined;\n}\n\n/**\n * Build the compactor named by `config.context.strategy`.\n *\n * - `hybrid` (default): lossless rule-based — no provider needed.\n * - `intelligent` / `selective`: LLM-backed. These need a `provider`, which is\n * only known per-run, so we return a thin wrapper that resolves the concrete\n * compactor from `ctx` at `compact()`-time. This deliberately avoids the\n * container/provider construction-ordering problem: `TOKENS.Compactor` is\n * resolved (and memoized) before `context.provider` exists, but `ctx.provider`\n * is always present once a run is actually compacting. If no provider is\n * available at compact-time the wrapper degrades to the lossless hybrid rules\n * rather than failing.\n */\nexport function createStrategyCompactor(opts: StrategyCompactorOptions = {}): Compactor {\n const requested = opts.strategy ?? (opts.llmSelector ? 'selective' : 'hybrid');\n const strategy = requested as CompactorStrategy;\n if (strategy === 'intelligent' || strategy === 'selective') {\n return new ProviderBackedCompactor(strategy, opts);\n }\n return new HybridCompactor({\n preserveK: opts.preserveK,\n eliseThreshold: opts.eliseThreshold,\n smart: opts.smart,\n });\n}\n\nclass ProviderBackedCompactor implements Compactor {\n constructor(\n private readonly strategy: 'intelligent' | 'selective',\n private readonly opts: StrategyCompactorOptions,\n ) {}\n\n async compact(\n ctx: Context,\n compactOpts: { aggressive?: boolean | undefined } = {},\n ): Promise<CompactReport> {\n return this.resolveInner(ctx).compact(ctx, compactOpts);\n }\n\n /**\n * Construct the concrete compactor for this run. Rebuilt per call (cheap, no\n * I/O) so a model switch — which changes `ctx.provider.capabilities.maxContext`\n * — is always reflected. Reads the active ContextWindowPolicy from `ctx.meta`\n * so the LLM compactors honor the same thresholds/preserveK as the policy.\n */\n private resolveInner(ctx: Context): Compactor {\n const provider = ctx.provider;\n if (!provider) {\n // No provider on ctx → cannot run an LLM compactor. Degrade to lossless rules.\n return new HybridCompactor({\n preserveK: this.opts.preserveK,\n eliseThreshold: this.opts.eliseThreshold,\n });\n }\n\n const policy = readPolicy(ctx);\n const maxContext = provider.capabilities?.maxContext || undefined;\n const thresholds = policy?.thresholds;\n const common = {\n provider,\n maxContext,\n preserveK: this.opts.preserveK ?? policy?.preserveK,\n eliseThreshold: this.opts.eliseThreshold ?? policy?.eliseThreshold,\n ...(thresholds\n ? { warnThreshold: thresholds.warn, softThreshold: thresholds.soft, hardThreshold: thresholds.hard }\n : {}),\n };\n\n if (this.strategy === 'selective') {\n return new SelectiveCompactor({\n ...common,\n selectorModel: this.opts.summarizerModel,\n selectorMaxOutputTokens: this.opts.selectorMaxOutputTokens,\n summarizerModel: this.opts.summarizerModel,\n });\n }\n return new IntelligentCompactor({\n ...common,\n summarizerModel: this.opts.summarizerModel,\n });\n }\n}\n\nfunction readPolicy(ctx: Context): ContextWindowPolicy | null {\n const policy = ctx.meta?.['contextWindowPolicy'];\n if (!policy || typeof policy !== 'object') return null;\n const candidate = policy as Partial<ContextWindowPolicy>;\n if (typeof candidate.preserveK !== 'number' || !candidate.thresholds) return null;\n return candidate as ContextWindowPolicy;\n}\n","/**\n * Exhaustiveness check for discriminated union switches.\n * Place in the `default` branch of a switch over a union type\n * to get a compile-time error when a new variant is added.\n *\n * @example\n * switch (block.type) {\n * case 'text': return renderText(block);\n * case 'tool_use': return renderToolUse(block);\n * default: return assertNever(block);\n * }\n */\nexport function assertNever(x: never, message?: string): never {\n const err = new Error(\n message ?? `Unhandled case: ${JSON.stringify(x)}`,\n );\n err.name = 'AssertNeverError';\n throw err;\n}\n","import { randomBytes } from 'node:crypto';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\n\nexport interface AtomicWriteOptions {\n mode?: number | undefined;\n encoding?: BufferEncoding | undefined;\n}\n\nexport interface FileLockOptions {\n timeoutMs?: number | undefined;\n staleMs?: number | undefined;\n}\n\nexport async function atomicWrite(\n targetPath: string,\n content: string | Uint8Array,\n opts: AtomicWriteOptions = {},\n): Promise<void> {\n const dir = path.dirname(targetPath);\n await fs.mkdir(dir, { recursive: true });\n const tmp = path.join(dir, `.${path.basename(targetPath)}.${randomBytes(6).toString('hex')}.tmp`);\n\n // Write content to tmp first; 'wx' ensures exclusive creation (fails if\n // tmp already exists — extremely unlikely with 6-byte random suffix).\n try {\n if (typeof content === 'string') {\n await fs.writeFile(tmp, content, { flag: 'wx', encoding: opts.encoding ?? 'utf8' });\n } else {\n await fs.writeFile(tmp, content, { flag: 'wx' });\n }\n try {\n const fh = await fs.open(tmp, 'r+');\n try {\n await fh.sync();\n } finally {\n await fh.close();\n }\n } catch {\n // fsync best-effort\n }\n // Now safely read mode from target (if it exists) and apply to tmp before rename.\n // Prefer opts.mode for new files; for existing files preserve their mode.\n let mode: number | undefined;\n try {\n const stat = await fs.stat(targetPath);\n mode = stat.mode & 0o777;\n } catch {\n mode = opts.mode;\n }\n if (mode !== undefined) {\n await fs.chmod(tmp, mode);\n }\n await renameWithRetry(tmp, targetPath);\n } catch (err) {\n try {\n await fs.unlink(tmp);\n } catch {\n // ignore cleanup error\n }\n throw err;\n }\n}\n\nexport async function ensureDir(dir: string): Promise<void> {\n await fs.mkdir(dir, { recursive: true });\n}\n\nexport async function withFileLock<T>(\n targetPath: string,\n fn: () => Promise<T>,\n opts: FileLockOptions = {},\n): Promise<T> {\n const dir = path.dirname(targetPath);\n await fs.mkdir(dir, { recursive: true });\n const lockPath = path.join(dir, `.${path.basename(targetPath)}.lock`);\n const timeoutMs = opts.timeoutMs ?? 5_000;\n const staleMs = opts.staleMs ?? 30_000;\n const started = Date.now();\n let handle: fs.FileHandle | undefined;\n\n for (;;) {\n try {\n handle = await fs.open(lockPath, 'wx');\n await handle.writeFile(`${process.pid}:${Date.now()}`);\n break;\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n // ENOENT means the directory was deleted (e.g. by concurrent cleanup).\n // Recreate it and retry acquiring the lock.\n if (code === 'ENOENT') {\n await fs.mkdir(dir, { recursive: true });\n continue;\n }\n if (code !== 'EEXIST') throw err;\n try {\n const stat = await fs.stat(lockPath);\n if (Date.now() - stat.mtimeMs > staleMs) {\n await fs.unlink(lockPath);\n continue;\n }\n } catch {\n continue;\n }\n if (Date.now() - started >= timeoutMs) {\n throw new Error(`Timed out waiting for file lock: ${targetPath}`);\n }\n await new Promise((resolve) => setTimeout(resolve, 25));\n }\n }\n\n try {\n return await fn();\n } finally {\n try {\n await handle?.close();\n } catch {\n // ignore\n }\n try {\n await fs.unlink(lockPath);\n } catch {\n // ignore\n }\n }\n}\n\n// On Windows, fs.rename over an existing file can fail with EPERM/EBUSY/EACCES\n// when antivirus, file indexers, editor file watchers, or a concurrent writer\n// briefly hold a handle on the destination. These are transient — retry with a\n// short backoff before giving up. POSIX renames are atomic and won't hit this.\nconst TRANSIENT_RENAME_CODES = new Set(['EPERM', 'EBUSY', 'EACCES', 'ENOTEMPTY']);\n\nasync function renameWithRetry(from: string, to: string): Promise<void> {\n if (process.platform !== 'win32') {\n await fs.rename(from, to);\n return;\n }\n const delays = [10, 25, 60, 120, 250];\n let lastErr: unknown;\n for (let i = 0; i <= delays.length; i++) {\n try {\n await fs.rename(from, to);\n return;\n } catch (err) {\n lastErr = err;\n const code = (err as NodeJS.ErrnoException)?.code;\n if (!code || !TRANSIENT_RENAME_CODES.has(code) || i === delays.length) {\n throw err;\n }\n await new Promise((resolve) => setTimeout(resolve, delays[i]));\n }\n }\n throw lastErr;\n}\n","/**\n * Converts an unknown error value to a human-readable string.\n * Used in 40+ files across the codebase to normalize error messaging.\n */\nexport function toErrorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n","/**\n * Minimal JSON Schema validator — covers the subset needed for plugin\n * configSchema validation and tool inputSchema sanity checks. Intentionally\n * small (~80 lines, zero deps) and tolerant: unknown keywords are ignored so\n * authors can mix in non-standard extensions without breaking validation.\n *\n * NOT for full JSON Schema 2020-12 conformance. If a plugin needs $ref,\n * conditional schemas, format validation, or anything else exotic, it should\n * bring its own ajv-based validator and call this only for the cheap path.\n */\nimport type { JSONSchema } from '../types/tool.js';\n\nexport interface ValidationError {\n path: string;\n message: string;\n}\n\nexport interface ValidationResult {\n ok: boolean;\n errors: ValidationError[];\n}\n\nexport function validateAgainstSchema(value: unknown, schema: JSONSchema): ValidationResult {\n const errors: ValidationError[] = [];\n walk(value, schema, '', errors);\n return { ok: errors.length === 0, errors };\n}\n\nfunction walk(value: unknown, schema: JSONSchema, path: string, errors: ValidationError[]): void {\n if (schema.enum !== undefined) {\n if (!schema.enum.some((e) => deepEqual(e, value))) {\n errors.push({\n path: path || '<root>',\n message: `expected one of ${JSON.stringify(schema.enum)}, got ${JSON.stringify(value)}`,\n });\n return;\n }\n }\n\n if (typeof schema.type === 'string') {\n if (!checkType(value, schema.type)) {\n errors.push({\n path: path || '<root>',\n message: `expected ${schema.type}, got ${describeType(value)}`,\n });\n return;\n }\n }\n\n if (schema.type === 'object' && isPlainObject(value)) {\n const obj = value as Record<string, unknown>;\n for (const req of schema.required ?? []) {\n if (!(req in obj)) {\n errors.push({ path: joinPath(path, req), message: 'required property missing' });\n }\n }\n if (schema.properties) {\n for (const [key, subSchema] of Object.entries(schema.properties)) {\n if (key in obj) {\n walk(obj[key], subSchema, joinPath(path, key), errors);\n }\n }\n }\n }\n\n if (schema.type === 'array' && Array.isArray(value) && schema.items) {\n for (let i = 0; i < value.length; i++) {\n walk(value[i], schema.items as JSONSchema, `${path}[${i}]`, errors);\n }\n }\n}\n\nfunction checkType(value: unknown, type: string): boolean {\n switch (type) {\n case 'string':\n return typeof value === 'string';\n case 'number':\n return typeof value === 'number' && !Number.isNaN(value);\n case 'integer':\n return typeof value === 'number' && Number.isInteger(value);\n case 'boolean':\n return typeof value === 'boolean';\n case 'null':\n return value === null;\n case 'array':\n return Array.isArray(value);\n case 'object':\n return isPlainObject(value);\n default:\n return true;\n }\n}\n\nfunction isPlainObject(v: unknown): boolean {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction describeType(v: unknown): string {\n if (v === null) return 'null';\n if (Array.isArray(v)) return 'array';\n return typeof v;\n}\n\nfunction joinPath(parent: string, key: string): string {\n if (!parent) return key;\n return `${parent}.${key}`;\n}\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (typeof a !== typeof b) return false;\n if (a === null || b === null) return a === b;\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((v, i) => deepEqual(v, b[i]));\n }\n if (typeof a === 'object' && typeof b === 'object') {\n const ak = Object.keys(a as object);\n const bk = Object.keys(b as object);\n if (ak.length !== bk.length) return false;\n return ak.every((k) =>\n deepEqual((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]),\n );\n }\n return false;\n}\n","/**\n * Compile a user-supplied regex with conservative bounds against ReDoS.\n *\n * Duplicated from @wrongstack/tools/_regex.ts to avoid a circular\n * dependency (tools depends on core, not vice versa). Keep both copies\n * in sync if the heuristics change.\n *\n * V8's regex engine is backtracking-based and cannot interrupt a\n * synchronous match — a pattern like `(a+)+$` against a sufficiently\n * long line will pin a worker for seconds.\n */\n\nconst MAX_PATTERN_LEN = 512;\n\n// Heuristics for catastrophic-backtracking constructs.\nconst DANGEROUS_PATTERNS: ReadonlyArray<RegExp> = [\n /(\\([^)]*[+*][^)]*\\))[+*]/, // (a+)+, (.*)+, etc\n /(\\(\\?:[^)]*[+*][^)]*\\))[+*]/, // same, with non-capturing group\n];\n\nexport interface CompileResult {\n ok: true;\n regex: RegExp;\n}\n\nexport interface CompileFail {\n ok: false;\n reason: string;\n}\n\nexport function compileUserRegex(pattern: string, flags: string): CompileResult | CompileFail {\n if (typeof pattern !== 'string') {\n return { ok: false, reason: 'pattern must be a string' };\n }\n if (pattern.length === 0) {\n return { ok: false, reason: 'pattern is empty' };\n }\n if (pattern.length > MAX_PATTERN_LEN) {\n return { ok: false, reason: `pattern exceeds ${MAX_PATTERN_LEN} characters` };\n }\n for (const rx of DANGEROUS_PATTERNS) {\n if (rx.test(pattern)) {\n return {\n ok: false,\n reason:\n 'pattern looks vulnerable to catastrophic backtracking — rewrite without nested quantifiers',\n };\n }\n }\n try {\n return { ok: true, regex: new RegExp(pattern, flags) };\n } catch (err) {\n return {\n ok: false,\n reason: err instanceof Error ? err.message : 'invalid regex',\n };\n }\n}\n","/** Resolve a promise after `ms` milliseconds. Prefer this over raw\n * `setTimeout` wrappers so all delay sites use a single implementation\n * and an abortable variant can be introduced without a codebase-wide hunt. */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","/**\n * String utilities shared across the WrongStack codebase.\n */\n\n/**\n * Truncate a string to at most `max` characters, appending an ellipsis if it\n * was longer. Returns the original string unchanged when it fits.\n */\nexport function truncate(s: string, max: number): string {\n return s.length <= max ? s : `${s.slice(0, max - 1)}…`;\n}\n","const GLOB_METACHARACTERS = /[*?[\\]]/g;\n\nexport function escapeGlobSubject(value: string): string {\n return value.replace(GLOB_METACHARACTERS, (char) => `\\\\${char}`);\n}\n\nexport function normalizePathSubject(value: string): string {\n return escapeGlobSubject(value.replace(/\\\\/g, '/'));\n}\n\nexport function isPathSubjectKey(subjectKey: string): boolean {\n return subjectKey === 'path' || subjectKey === 'file' || subjectKey === 'files';\n}\n\nexport function subjectForToolInput(\n toolName: string,\n input: unknown,\n subjectKey?: string,\n): string | undefined {\n if (!input || typeof input !== 'object') return undefined;\n const obj = input as Record<string, unknown>;\n\n if (subjectKey) {\n const value = obj[subjectKey];\n if (typeof value === 'string') {\n return isPathSubjectKey(subjectKey) ? normalizePathSubject(value) : escapeGlobSubject(value);\n }\n }\n\n if (toolName === 'bash' && typeof obj.command === 'string') {\n return escapeGlobSubject(obj.command);\n }\n if (typeof obj.path === 'string') {\n return normalizePathSubject(obj.path);\n }\n if (typeof obj.url === 'string') {\n return escapeGlobSubject(obj.url);\n }\n if (typeof obj.name === 'string') {\n return escapeGlobSubject(obj.name);\n }\n return undefined;\n}\n","/**\n * Tool output serialization utilities.\n * Extracted from Agent.executeTools to allow reuse and consistent output handling.\n */\n\nexport interface ToolOutputSerializerOptions {\n perIterationOutputCapBytes?: number | undefined;\n estimator?: ((text: string) => number) | undefined;\n}\n\nexport interface ToolOutputSerializeContext {\n toolName?: string | undefined;\n input?: unknown;\n}\n\ntype RecordValue = Record<string, unknown>;\n\nconst DEFAULT_LIST_LIMIT = 500;\nconst LOG_ENTRY_LIMIT = 200;\nconst INLINE_LIMIT = 240;\nconst GREP_FILE_LIMIT = 80;\nconst GREP_MATCHES_PER_FILE = 3;\nconst DIFF_INLINE_LINE_LIMIT = 260;\nconst DIFF_HUNK_LIMIT = 8;\nconst DIFF_HUNK_CONTEXT = 14;\n\n// Pre-compiled regex — used in parseGrepContentLine() for every grep match line.\n// Compiling once at module load avoids repeated RegExp construction overhead.\nconst GREP_LINE_RE = /^(.+?):(\\d+):(.*)$/;\n\nexport function createToolOutputSerializer(opts: ToolOutputSerializerOptions = {}) {\n const capBytes = opts.perIterationOutputCapBytes ?? 100_000;\n\n function serialize(value: unknown, context: ToolOutputSerializeContext = {}): string {\n if (typeof value === 'string') return value;\n if (value === null || value === undefined) return '';\n if (typeof value === 'object') {\n if (Array.isArray(value)) return value.map((item) => serialize(item)).join('\\n');\n if (context.toolName) {\n const compact = renderToolObject(context.toolName, value as RecordValue, context.input);\n if (compact !== undefined) return compact;\n return renderGenericToolObject(context.toolName, value as RecordValue);\n }\n if ('text' in (value as Record<string, unknown>)) {\n const t = (value as Record<string, unknown>).text;\n return typeof t === 'string' ? t : JSON.stringify(value, null, 2);\n }\n try {\n return JSON.stringify(value, null, 2);\n } catch {\n return String(value);\n }\n }\n return String(value);\n }\n\n function enforceCap(text: string, remainingBudget: number): { text: string; newBudget: number } {\n if (remainingBudget <= 0) {\n return { text: '[truncated: iteration output cap exceeded]', newBudget: 0 };\n }\n const textBytes = Buffer.byteLength(text, 'utf8');\n if (textBytes <= remainingBudget) {\n return { text, newBudget: remainingBudget - textBytes };\n }\n const marker = `\\n…[truncated ${textBytes - remainingBudget} bytes]…\\n`;\n const markerBytes = Buffer.byteLength(marker, 'utf8');\n const available = remainingBudget - markerBytes;\n if (available <= 0) {\n return { text: '[truncated: iteration output cap exceeded]', newBudget: 0 };\n }\n const half = Math.floor(available / 2);\n const first = text.slice(0, half);\n const second = text.slice(text.length - half);\n return { text: `${first}${marker}${second}`, newBudget: 0 };\n }\n\n return { serialize, enforceCap, capBytes };\n}\n\nfunction renderToolObject(toolName: string, obj: RecordValue, input: unknown): string | undefined {\n if (toolName === 'read' && typeof obj['text'] === 'string') {\n return joinSections([\n renderHeader(\n `read: ${stringFromInput(input, 'path') ?? stringField(obj, 'path') ?? '<unknown>'}`,\n {\n offset: numberFromInput(input, 'offset'),\n limit: numberFromInput(input, 'limit'),\n total_lines: obj['total_lines'],\n encoding: obj['encoding'],\n truncated: obj['truncated'],\n cached: obj['cached'],\n note: obj['note'],\n },\n ),\n obj['text'],\n ]);\n }\n\n if (toolName === 'grep' && Array.isArray(obj['matches'])) {\n const matches = stringArrayField(obj, 'matches');\n return joinSections([\n renderHeader(`grep: ${stringFromInput(input, 'pattern') ?? '<pattern>'}`, {\n path: stringFromInput(input, 'path'),\n glob: stringFromInput(input, 'glob'),\n mode: stringFromInput(input, 'output_mode'),\n count: obj['count'],\n shown: matches.length,\n truncated: obj['truncated'],\n used: obj['used'],\n }),\n renderGrepMatches(matches, stringFromInput(input, 'output_mode')),\n ]);\n }\n\n if (toolName === 'patch' && Array.isArray(obj['files'])) {\n const files = stringArrayField(obj, 'files');\n return joinSections([\n renderHeader('patch', {\n applied: obj['applied'],\n rejected: obj['rejected'],\n files: files.length,\n dry_run: obj['dry_run'],\n }),\n typeof obj['message'] === 'string' ? `message:\\n${obj['message']}` : undefined,\n files.length > 0 ? `files:\\n${renderStringList(files)}` : undefined,\n ]);\n }\n\n if (toolName === 'glob' && Array.isArray(obj['files'])) {\n const files = stringArrayField(obj, 'files');\n return joinSections([\n renderHeader(\n `${toolName}: ${stringFromInput(input, 'pattern') ?? stringFromInput(input, 'files') ?? stringFromInput(input, 'path') ?? ''}`.trim(),\n {\n path: stringFromInput(input, 'path'),\n files: files.length,\n truncated: obj['truncated'],\n },\n ),\n renderStringList(files, '(no files)'),\n ]);\n }\n\n if (toolName === 'tree' && typeof obj['tree'] === 'string') {\n return joinSections([\n renderHeader(\n `tree: ${stringField(obj, 'path') ?? stringFromInput(input, 'path') ?? '<cwd>'}`,\n {\n total_files: obj['total_files'],\n total_dirs: obj['total_dirs'],\n truncated: obj['truncated'],\n },\n ),\n obj['tree'],\n ]);\n }\n\n if (toolName === 'fetch' && typeof obj['content'] === 'string') {\n return joinSections([\n renderHeader(\n `fetch: ${stringField(obj, 'url') ?? stringFromInput(input, 'url') ?? '<url>'}`,\n {\n status: obj['status'],\n content_type: obj['content_type'],\n },\n ),\n obj['content'],\n ]);\n }\n\n if (toolName === 'replace' && Array.isArray(obj['results'])) {\n const results = obj['results'].filter(isRecord);\n const sections: Array<string | undefined> = [\n renderHeader('replace', {\n files_modified: obj['files_modified'],\n total_replacements: obj['total_replacements'],\n dry_run: obj['dry_run'],\n }),\n ];\n for (const r of results.slice(0, DEFAULT_LIST_LIMIT)) {\n sections.push(\n joinSections([\n renderHeader(`file: ${stringField(r, 'path') ?? '<unknown>'}`, {\n replacements: r['replacements'],\n }),\n typeof r['diff'] === 'string' ? r['diff'] : undefined,\n ]),\n );\n }\n if (results.length > DEFAULT_LIST_LIMIT) {\n sections.push(`[serializer omitted ${results.length - DEFAULT_LIST_LIMIT} result item(s)]`);\n }\n return joinSections(sections);\n }\n\n if (typeof obj['diff'] === 'string') {\n const diff = obj['diff'];\n return joinSections([\n renderHeader(toolName, {\n path: obj['path'],\n replacements: obj['replacements'],\n bytes_written: obj['bytes_written'],\n created: obj['created'],\n note: obj['note'],\n files: Array.isArray(obj['files']) ? obj['files'].length : undefined,\n truncated: obj['truncated'],\n mode: obj['mode'],\n }),\n compactDiff(diff),\n ]);\n }\n\n if (toolName === 'test' && typeof obj['output'] === 'string') {\n return renderTestOutput(obj, input);\n }\n\n if (\n (toolName === 'typecheck' || toolName === 'lint' || toolName === 'format') &&\n typeof obj['output'] === 'string'\n ) {\n return renderVerifierOutput(toolName, obj, input);\n }\n\n if (hasCommandOutputShape(obj)) {\n return renderCommandOutput(toolName, obj, input);\n }\n\n if (toolName === 'json' && typeof obj['formatted'] === 'string') {\n return joinSections([\n renderHeader('json', {\n type: obj['type'],\n keys: Array.isArray(obj['keys']) ? obj['keys'].length : undefined,\n query: stringFromInput(input, 'query'),\n error: obj['error'],\n }),\n obj['formatted'],\n ]);\n }\n\n if (toolName === 'logs' && Array.isArray(obj['entries'])) {\n const entries = obj['entries'].filter(isRecord);\n const lines = entries.slice(0, LOG_ENTRY_LIMIT).map((entry) => {\n const ts = stringField(entry, 'timestamp') ?? '';\n const level = stringField(entry, 'level') ?? 'info';\n const message = stringField(entry, 'message') ?? '';\n const source = stringField(entry, 'source');\n return [ts, level, source, message].filter(Boolean).join(' ');\n });\n if (entries.length > LOG_ENTRY_LIMIT) {\n lines.push(`[serializer omitted ${entries.length - LOG_ENTRY_LIMIT} log entry item(s)]`);\n }\n return joinSections([\n renderHeader(`logs: ${stringField(obj, 'source') ?? '<source>'}`, {\n total: obj['total'],\n shown: Math.min(entries.length, LOG_ENTRY_LIMIT),\n truncated: obj['truncated'],\n stream_mode: obj['stream_mode'],\n }),\n lines.length > 0 ? lines.join('\\n') : '(no log entries)',\n ]);\n }\n\n if (toolName === 'audit' && Array.isArray(obj['vulnerabilities'])) {\n const vulns = obj['vulnerabilities'].filter(isRecord);\n const lines = vulns.slice(0, DEFAULT_LIST_LIMIT).map((v) => {\n const severity = stringField(v, 'severity') ?? 'unknown';\n const pkg = stringField(v, 'package') ?? '<package>';\n const title = stringField(v, 'title') ?? '';\n const url = stringField(v, 'url');\n return [severity, pkg, title, url].filter(Boolean).join(' | ');\n });\n if (vulns.length > DEFAULT_LIST_LIMIT) {\n lines.push(`[serializer omitted ${vulns.length - DEFAULT_LIST_LIMIT} vulnerability item(s)]`);\n }\n return joinSections([\n renderHeader('audit', {\n exit_code: obj['exit_code'],\n total: obj['total'],\n summary: obj['summary'],\n truncated: obj['truncated'],\n }),\n lines.length > 0 ? lines.join('\\n') : stringField(obj, 'output'),\n ]);\n }\n\n if (toolName === 'outdated' && Array.isArray(obj['packages'])) {\n const packages = obj['packages'].filter(isRecord);\n const lines = packages\n .slice(0, DEFAULT_LIST_LIMIT)\n .map((p) =>\n [\n stringField(p, 'name') ?? '<package>',\n `current=${stringField(p, 'current') ?? 'unknown'}`,\n `wanted=${stringField(p, 'wanted') ?? 'unknown'}`,\n `latest=${stringField(p, 'latest') ?? 'unknown'}`,\n stringField(p, 'type'),\n ]\n .filter(Boolean)\n .join(' | '),\n );\n if (packages.length > DEFAULT_LIST_LIMIT) {\n lines.push(`[serializer omitted ${packages.length - DEFAULT_LIST_LIMIT} package item(s)]`);\n }\n return joinSections([\n renderHeader('outdated', {\n exit_code: obj['exit_code'],\n total: obj['total'],\n truncated: obj['truncated'],\n }),\n lines.length > 0 ? lines.join('\\n') : stringField(obj, 'output'),\n ]);\n }\n\n return undefined;\n}\n\nfunction renderTestOutput(obj: RecordValue, input: unknown): string {\n const exitCode = numberField(obj, 'exit_code') ?? 0;\n const failed = numberField(obj, 'failed') ?? 0;\n const output = stringField(obj, 'output') ?? '';\n const header = renderHeader(`test: ${stringField(obj, 'runner') ?? 'runner'}`, {\n exit_code: obj['exit_code'],\n tests_run: obj['tests_run'],\n passed: obj['passed'],\n failed: obj['failed'],\n duration_ms: obj['duration_ms'],\n truncated: obj['truncated'],\n files: inputListSummary(input, 'files'),\n grep: stringFromInput(input, 'grep'),\n });\n\n if (exitCode === 0 && failed === 0) {\n return joinSections([\n header,\n joinSections([\n 'report:',\n `status=passed`,\n `tests_run=${obj['tests_run'] ?? 0}`,\n `passed=${obj['passed'] ?? 0}`,\n `failed=${obj['failed'] ?? 0}`,\n `duration_ms=${obj['duration_ms'] ?? 0}`,\n extractSpoolNote(output),\n ]),\n ]);\n }\n\n return joinSections([\n header,\n `error_context:\\n${compactFailureOutput(output || '(no runner output)')}`,\n ]);\n}\n\nfunction renderVerifierOutput(toolName: string, obj: RecordValue, input: unknown): string {\n const exitCode = numberField(obj, 'exit_code') ?? 0;\n const errors = numberField(obj, 'errors') ?? 0;\n const warnings = numberField(obj, 'warnings') ?? 0;\n const output = stringField(obj, 'output') ?? '';\n const changed = numberField(obj, 'files_changed') ?? 0;\n const header = renderHeader(toolName, {\n exit_code: obj['exit_code'],\n errors: obj['errors'],\n warnings: obj['warnings'],\n files_checked: obj['files_checked'],\n files_changed: obj['files_changed'],\n fix_applied: obj['fix_applied'],\n fixer: obj['fixer'],\n linter: obj['linter'],\n project: obj['project'],\n truncated: obj['truncated'],\n files: inputListSummary(input, 'files'),\n cwd: stringFromInput(input, 'cwd'),\n });\n\n if (exitCode === 0 && errors === 0 && (toolName !== 'format' || changed === 0)) {\n return joinSections([\n header,\n joinSections([\n 'report:',\n 'status=passed',\n `errors=${errors}`,\n `warnings=${warnings}`,\n toolName === 'format' ? `files_changed=${changed}` : undefined,\n extractSpoolNote(output),\n ]),\n ]);\n }\n\n if (exitCode === 0 && toolName === 'format') {\n return joinSections([\n header,\n joinSections([\n 'report:',\n 'status=changed',\n `files_changed=${changed}`,\n extractSpoolNote(output),\n ]),\n ]);\n }\n\n return joinSections([\n header,\n `error_context:\\n${compactFailureOutput(output || '(no verifier output)')}`,\n ]);\n}\n\nfunction renderGrepMatches(matches: string[], mode: string | undefined): string {\n if (matches.length === 0) return '(no matches)';\n if (mode === 'files_with_matches') return renderStringList(matches, '(no files)');\n if (mode === 'count') return renderStringList(matches, '(no counts)');\n\n const groups = new Map<string, string[]>();\n const passthrough: string[] = [];\n for (const match of matches) {\n const parsed = parseGrepContentLine(match);\n if (!parsed) {\n passthrough.push(match);\n continue;\n }\n const list = groups.get(parsed.file) ?? [];\n list.push(`${parsed.line}:${parsed.text}`);\n groups.set(parsed.file, list);\n }\n\n if (groups.size === 0) return renderStringList(matches, '(no matches)');\n\n const sections: string[] = [];\n let fileIndex = 0;\n for (const [file, lines] of groups) {\n fileIndex++;\n if (fileIndex > GREP_FILE_LIMIT) break;\n const shown = lines.slice(0, GREP_MATCHES_PER_FILE);\n sections.push(\n `${file} (${lines.length} match(es), showing ${shown.length})\\n${shown.join('\\n')}`,\n );\n }\n if (groups.size > GREP_FILE_LIMIT) {\n sections.push(`[serializer omitted ${groups.size - GREP_FILE_LIMIT} file group(s)]`);\n }\n if (passthrough.length > 0) {\n sections.push(`ungrouped:\\n${renderStringList(passthrough, '', 50)}`);\n }\n return sections.join('\\n');\n}\n\nfunction parseGrepContentLine(\n line: string,\n): { file: string; line: string; text: string } | undefined {\n const match = GREP_LINE_RE.exec(line);\n if (!match?.[1] || !match[2]) return undefined;\n return { file: match[1], line: match[2], text: match[3] ?? '' };\n}\n\nfunction compactDiff(diff: string): string {\n const lines = diff.split(/\\r?\\n/);\n if (lines.length <= DIFF_INLINE_LINE_LIMIT) return diff;\n\n const fileCount = Math.max(\n new Set(\n lines\n .map(\n (line) => /^diff --git\\s+a\\/(.+?)\\s+b\\//.exec(line)?.[1] ?? /^---\\s+(.+)/.exec(line)?.[1],\n )\n .filter(Boolean),\n ).size,\n 0,\n );\n const hunks = lines.filter((line) => line.startsWith('@@')).length;\n const added = lines.filter((line) => line.startsWith('+') && !line.startsWith('+++')).length;\n const removed = lines.filter((line) => line.startsWith('-') && !line.startsWith('---')).length;\n\n // Collect [start, end] intervals as we scan lines sequentially.\n // Intervals are naturally ordered by line index — no sort needed.\n const intervals: Array<[number, number]> = [];\n let hunkCount = 0;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? '';\n if (line.startsWith('diff --git') || line.startsWith('--- ') || line.startsWith('+++ ')) {\n intervals.push([i, i]);\n continue;\n }\n if (!line.startsWith('@@')) continue;\n if (hunkCount >= DIFF_HUNK_LIMIT) continue;\n hunkCount++;\n intervals.push([i, Math.min(lines.length - 1, i + DIFF_HUNK_CONTEXT)]);\n }\n\n if (intervals.length === 0) {\n return joinSections([\n renderHeader('diff_summary', {\n files: fileCount,\n hunks,\n added,\n removed,\n lines: lines.length,\n }),\n lines.slice(0, DIFF_INLINE_LINE_LIMIT).join('\\n'),\n `[serializer omitted ${Math.max(0, lines.length - DIFF_INLINE_LINE_LIMIT)} diff line(s)]`,\n ]);\n }\n\n // Merge overlapping / adjacent intervals in a single O(n) pass.\n // Intervals are already in ascending order from the sequential scan.\n const merged: Array<[number, number]> = [intervals[0]!];\n for (let i = 1; i < intervals.length; i++) {\n const last = merged[merged.length - 1]!;\n const current = intervals[i]!;\n if (current[0] <= last[1] + 1) {\n last[1] = Math.max(last[1], current[1]);\n } else {\n merged.push(current);\n }\n }\n\n // Build excerpt from merged intervals — O(n), no sort.\n const excerpt: string[] = [];\n let prevLine = -1;\n for (const [start, end] of merged) {\n if (start > prevLine + 1) {\n const omitted = prevLine === -1 ? start : start - prevLine - 1;\n excerpt.push(`[serializer omitted ${omitted} diff line(s)]`);\n }\n for (let j = start; j <= end; j++) {\n excerpt.push(lines[j] ?? '');\n }\n prevLine = end;\n }\n\n const trailing = lines.length - prevLine - 1;\n if (trailing > 0) excerpt.push(`[serializer omitted ${trailing} trailing diff line(s)]`);\n\n return joinSections([\n renderHeader('diff_summary', {\n files: fileCount,\n hunks,\n shown_hunks: Math.min(hunks, DIFF_HUNK_LIMIT),\n added,\n removed,\n lines: lines.length,\n }),\n excerpt.join('\\n'),\n ]);\n}\n\nfunction compactFailureOutput(output: string): string {\n const lines = output.split(/\\r?\\n/);\n if (lines.length <= 260) return output.trimEnd();\n\n const selected = new Set<number>();\n const marker =\n /\\b(fail|failed|failure|error|exception|assertionerror|expected|received|actual|timeout|stack)\\b/i;\n let markerHits = 0;\n for (let i = 0; i < lines.length; i++) {\n if (!marker.test(lines[i] ?? '')) continue;\n markerHits++;\n for (let j = Math.max(0, i - 4); j <= Math.min(lines.length - 1, i + 10); j++) {\n selected.add(j);\n }\n }\n\n if (markerHits === 0) {\n return lines.slice(-220).join('\\n').trimEnd();\n }\n\n const ordered = [...selected].sort((a, b) => a - b);\n const out: string[] = [];\n let previous = -1;\n for (const index of ordered) {\n if (index > previous + 1) {\n const omitted = previous === -1 ? index : index - previous - 1;\n out.push(`[serializer omitted ${omitted} line(s)]`);\n }\n out.push(lines[index] ?? '');\n previous = index;\n }\n return out.join('\\n').trimEnd();\n}\n\nfunction extractSpoolNote(output: string): string | undefined {\n return output\n .split(/\\r?\\n/)\n .find((line) => line.startsWith('[output truncated') && line.includes('full'));\n}\n\nfunction hasCommandOutputShape(obj: RecordValue): boolean {\n return (\n typeof obj['stdout'] === 'string' ||\n typeof obj['stderr'] === 'string' ||\n typeof obj['output'] === 'string' ||\n typeof obj['exitCode'] === 'number' ||\n typeof obj['exit_code'] === 'number'\n );\n}\n\nfunction renderCommandOutput(toolName: string, obj: RecordValue, input: unknown): string {\n const command = stringField(obj, 'command') ?? stringFromInput(input, 'command');\n const args = stringArrayField(obj, 'args');\n const commandLine = command ? [command, ...args].join(' ') : undefined;\n const output = stringField(obj, 'output');\n const stdout = stringField(obj, 'stdout');\n const stderr = stringField(obj, 'stderr');\n return joinSections([\n renderHeader(commandLine ? `${toolName}: ${commandLine}` : toolName, {\n exit_code: obj['exit_code'] ?? obj['exitCode'],\n timed_out: obj['timed_out'],\n pid: obj['pid'],\n allowed: obj['allowed'],\n truncated: obj['truncated'],\n runner: obj['runner'],\n linter: obj['linter'],\n fixer: obj['fixer'],\n project: obj['project'],\n tests_run: obj['tests_run'],\n passed: obj['passed'],\n failed: obj['failed'],\n duration_ms: obj['duration_ms'],\n errors: obj['errors'],\n warnings: obj['warnings'],\n files_checked: obj['files_checked'],\n files_changed: obj['files_changed'],\n fix_applied: obj['fix_applied'],\n }),\n stringField(obj, 'error') ? `error:\\n${stringField(obj, 'error')}` : undefined,\n output ? `output:\\n${output}` : undefined,\n stdout ? `stdout:\\n${stdout}` : undefined,\n stderr ? `stderr:\\n${stderr}` : undefined,\n ]);\n}\n\nfunction renderGenericToolObject(toolName: string, obj: RecordValue): string {\n const scalars: RecordValue = {};\n const blocks: string[] = [];\n for (const [key, value] of Object.entries(obj)) {\n if (value === undefined) continue;\n if (isScalar(value)) {\n const inline = String(value);\n if (inline.length <= INLINE_LIMIT && !inline.includes('\\n')) {\n scalars[key] = value;\n } else {\n blocks.push(`${key}:\\n${inline}`);\n }\n continue;\n }\n if (Array.isArray(value)) {\n if (value.every((item) => typeof item === 'string')) {\n blocks.push(`${key}:\\n${renderStringList(value as string[])}`);\n } else {\n blocks.push(`${key}:\\n${renderUnknownList(value)}`);\n }\n continue;\n }\n blocks.push(`${key}: ${clipInline(oneLineJson(value))}`);\n }\n return joinSections([renderHeader(toolName, scalars), ...blocks]);\n}\n\nfunction renderHeader(label: string, fields: RecordValue): string {\n const parts = Object.entries(fields)\n .filter(([, value]) => value !== undefined && value !== null && value !== '')\n .map(([key, value]) => `${key}=${clipInline(formatInlineValue(value))}`);\n return parts.length > 0 ? `${label} (${parts.join(' ')})` : label;\n}\n\nfunction renderStringList(items: string[], empty = '', limit = DEFAULT_LIST_LIMIT): string {\n if (items.length === 0) return empty;\n const shown = items.slice(0, limit);\n const omitted = items.length - shown.length;\n return [\n ...shown,\n ...(omitted > 0\n ? [`[serializer omitted ${omitted} item(s); narrow the request for more]`]\n : []),\n ].join('\\n');\n}\n\nfunction renderUnknownList(items: unknown[], limit = DEFAULT_LIST_LIMIT): string {\n const shown = items.slice(0, limit).map((item) => clipInline(oneLineJson(item), 1_000));\n const omitted = items.length - shown.length;\n if (omitted > 0)\n shown.push(`[serializer omitted ${omitted} item(s); narrow the request for more]`);\n return shown.join('\\n');\n}\n\nfunction joinSections(sections: Array<string | undefined>): string {\n return sections\n .map((section) => (typeof section === 'string' ? section.trimEnd() : undefined))\n .filter((section): section is string => !!section)\n .join('\\n');\n}\n\nfunction formatInlineValue(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(formatInlineValue).join(',')}]`;\n if (isScalar(value)) return String(value);\n return oneLineJson(value);\n}\n\nfunction clipInline(value: string, max = INLINE_LIMIT): string {\n const compact = value.replace(/\\s+/g, ' ').trim();\n return compact.length <= max\n ? compact\n : `${compact.slice(0, max - 15)}...(${compact.length} chars)`;\n}\n\nfunction oneLineJson(value: unknown): string {\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nfunction stringField(obj: RecordValue, key: string): string | undefined {\n const value = obj[key];\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction numberField(obj: RecordValue, key: string): number | undefined {\n const value = obj[key];\n return typeof value === 'number' ? value : undefined;\n}\n\nfunction stringArrayField(obj: RecordValue, key: string): string[] {\n const value = obj[key];\n return Array.isArray(value)\n ? value.filter((item): item is string => typeof item === 'string')\n : [];\n}\n\nfunction stringFromInput(input: unknown, key: string): string | undefined {\n if (!isRecord(input)) return undefined;\n const value = input[key];\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction numberFromInput(input: unknown, key: string): number | undefined {\n if (!isRecord(input)) return undefined;\n const value = input[key];\n return typeof value === 'number' ? value : undefined;\n}\n\nfunction inputListSummary(input: unknown, key: string): string | undefined {\n if (!isRecord(input)) return undefined;\n const value = input[key];\n if (typeof value === 'string') return value;\n if (Array.isArray(value)) return value.filter((item) => typeof item === 'string').join(',');\n return undefined;\n}\n\nfunction isRecord(value: unknown): value is RecordValue {\n return !!value && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isScalar(value: unknown): value is string | number | boolean | null {\n return value === null || ['string', 'number', 'boolean'].includes(typeof value);\n}\n\n/**\n * Render a tool result body for inclusion in the `tool.executed` event.\n * Tool outputs can be large (file dumps, command output); UIs only want a\n * preview line, so cap at ~400 chars with an ellipsis marker.\n */\nexport function truncateForEvent(content: string, max = 400): string {\n if (!content) return '';\n return content.length <= max ? content : `${content.slice(0, max - 1)}…`;\n}\n\n/**\n * Derive size signals (bytes / tokens / lines) for the chip rendered beside\n * each tool result. Computed once over the FULL `content` BEFORE the\n * 400-char event preview is taken.\n *\n * - bytes: UTF-8 byte length (multi-byte aware).\n * - tokens: standard ~3.5 chars/token heuristic.\n * - lines: read prefixes lines with `<n>→`; for shell/grep/logs we fall\n * back to a newline count. Undefined for tools without a line notion.\n */\nconst READ_LINE_PREFIX_RE = /^\\s*\\d+→/gm;\n\nexport function sizeSignals(\n toolName: string | undefined,\n content: string,\n): { outputBytes: number; outputTokens: number; outputLines: number | undefined } {\n if (!content || content.length === 0) {\n return { outputBytes: 0, outputTokens: 0, outputLines: undefined };\n }\n const outputBytes = Buffer.byteLength(content, 'utf8');\n const outputTokens = Math.max(1, Math.round(outputBytes / 3.5));\n let outputLines: number | undefined;\n if (toolName === 'read') {\n READ_LINE_PREFIX_RE.lastIndex = 0;\n let count = 0;\n while (READ_LINE_PREFIX_RE.exec(content) !== null) count++;\n if (count > 0) outputLines = count;\n } else if (\n toolName === 'bash' ||\n toolName === 'shell' ||\n toolName === 'grep' ||\n toolName === 'logs'\n ) {\n let nl = 0;\n for (let i = 0; i < content.length; i++) if (content.charCodeAt(i) === 10) nl++;\n outputLines = nl + (content.endsWith('\\n') ? 0 : 1);\n }\n return { outputBytes, outputTokens, outputLines };\n}\n","import { createHash } from 'node:crypto';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\n\n/**\n * Path layout. All developer-level state lives in ~/.wrongstack/.\n * Per-project state is keyed by sha256(absoluteProjectRoot).slice(0,12)\n * under ~/.wrongstack/projects/<hash>/.\n *\n * The ONLY thing inside the project tree is the optional\n * .wrongstack/AGENTS.md (committed) and .wrongstack/skills/ (committed).\n */\n\nexport interface WstackPaths {\n /** ~/.wrongstack — global root. */\n globalRoot: string;\n /**\n * ~/.wrongstack — directory for user-global stateful config files\n * (mode.json, theme.json, …). Currently an alias for `globalRoot`;\n * separate name lets us split out per-OS XDG_CONFIG_HOME later\n * without rewriting callers.\n */\n configDir: string;\n /** ~/.wrongstack/config.json */\n globalConfig: string;\n /** ~/.wrongstack/.key — 32 random bytes, mode 0600, AES-GCM key for the secret vault. */\n secretsKey: string;\n /** ~/.wrongstack/memory.md — user-global memory. */\n globalMemory: string;\n /** ~/.wrongstack/skills — user-global skills. */\n globalSkills: string;\n /** ~/.wrongstack/prompts — user-global prompt library. */\n globalPrompts: string;\n /** ~/.wrongstack/cache — fetched data (models.dev, etc.). */\n cacheDir: string;\n /** ~/.wrongstack/cache/models.dev.json */\n modelsCache: string;\n /** ~/.wrongstack/cache/models-overlay.json — cached curated overlay. */\n modelsOverlayCache: string;\n /**\n * Per-project codebase symbol index (SQLite). Lives under the global project\n * dir — NOT inside the repo — so it never clutters the working tree or needs\n * gitignoring. `~/.wrongstack/projects/<hash>/codebase-index`.\n */\n projectCodebaseIndex: string;\n /** ~/.wrongstack/history — REPL line history. */\n historyFile: string;\n /** ~/.wrongstack/logs/wrongstack.log */\n logFile: string;\n /** ~/.wrongstack/projects/<hash> */\n projectDir: string;\n /** ~/.wrongstack/projects/<hash>/memory.md */\n projectMemory: string;\n /** ~/.wrongstack/projects/<hash>/sessions */\n projectSessions: string;\n /** ~/.wrongstack/projects/<hash>/trust.json */\n projectTrust: string;\n /** ~/.wrongstack/projects/<hash>/meta.json */\n projectMeta: string;\n /** ~/.wrongstack/projects/<hash>/config.local.json — optional override */\n projectLocalConfig: string;\n /** <project>/.wrongstack/config.json — per-project settings (safe fields only).\n * This lives inside the project root so it can be gitignored or shared. */\n inProjectConfig: string;\n /** <project>/.wrongstack/AGENTS.md — committed project memory. */\n inProjectAgentsFile: string;\n /** <project>/.wrongstack/skills — committed project skills. */\n inProjectSkills: string;\n /** <project>/.wrongstack/worktrees — git worktrees for per-phase isolation (gitignored). */\n inProjectWorktrees: string;\n /** Stable hash for the project root. */\n projectHash: string;\n /** Human-readable project slug: `wrongstack-a1b2c3` instead of `3024e5e6fa58`. */\n projectSlug: string;\n /** ~/.wrongstack/projects/<hash>/goal.json — goal persistence */\n projectGoal: string;\n /** ~/.wrongstack/projects/<hash>/specs — SDD spec files */\n projectSpecs: string;\n /** ~/.wrongstack/projects/<hash>/task-graphs — SDD task graphs */\n projectTaskGraphs: string;\n /** ~/.wrongstack/projects/<hash>/sdd-session.json — SDD session state */\n projectSddSession: string;\n /** ~/.wrongstack/projects/<hash>/plan.json — plan persistence */\n projectPlan: string;\n /** ~/.wrongstack/projects/<hash>/autophase — AutoPhase phase-graph JSON files */\n projectAutophase: string;\n /** ~/.wrongstack/sync.json — CloudSync configuration */\n syncConfig: string;\n /** Function to get the status.json path for a project given its hash. */\n projectStatus: (projectHash: string) => string;\n}\n\nexport function projectHash(absRoot: string): string {\n return createHash('sha256').update(path.resolve(absRoot)).digest('hex').slice(0, 12);\n}\n\n/**\n * Human-readable project directory name: slugified folder name + short hash\n * suffix for uniqueness. e.g. `wrongstack-a1b2c3` instead of `3024e5e6fa58`.\n */\nexport function projectSlug(absRoot: string): string {\n const base = slugify(path.basename(absRoot));\n const hash = createHash('sha256').update(path.resolve(absRoot)).digest('hex').slice(0, 6);\n return `${base}-${hash}`;\n}\n\n/** Turn a folder name into a filesystem-safe lowercase slug. */\nfunction slugify(name: string): string {\n return (\n name\n .toLowerCase()\n // Collapse any run of non-alphanumeric chars into a single hyphen.\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 40) || 'project'\n );\n}\n\nexport interface WstackPathOptions {\n userHome?: string | undefined;\n projectRoot: string;\n /** Override the global root (e.g. for tests). Default: `${userHome}/.wrongstack`. */\n globalRoot?: string | undefined;\n}\n\n/**\n * The global `~/.wrongstack` root, honoring the `WRONGSTACK_HOME` env\n * override. The override exists so tests (and sandboxed runs) can redirect\n * ALL global state — config, secrets, logs, projects/, mailboxes — away from\n * the real user home. Before it existed, `pnpm test` booted runtimes against\n * the real `~/.wrongstack`: it read the user's real config.json (starting a\n * second live Telegram poller), appended to the real wrongstack.log, and left\n * ~20k orphaned fixture dirs under projects/.\n *\n * Every code path that wants the global dir must come through here (or\n * through `resolveWstackPaths`) instead of `path.join(os.homedir(), '.wrongstack')`.\n */\nexport function wstackGlobalRoot(): string {\n const fromEnv = process.env['WRONGSTACK_HOME'];\n if (fromEnv && fromEnv.trim().length > 0) return path.resolve(fromEnv);\n return path.join(os.homedir(), '.wrongstack');\n}\n\nexport function resolveWstackPaths(opts: WstackPathOptions): WstackPaths {\n // Precedence: explicit globalRoot > explicit userHome (callers/tests that\n // pass one expect paths under it) > WRONGSTACK_HOME env > real home dir.\n const globalRoot =\n opts.globalRoot ?? (opts.userHome ? path.join(opts.userHome, '.wrongstack') : wstackGlobalRoot());\n const hash = projectHash(opts.projectRoot);\n const slug = projectSlug(opts.projectRoot);\n const projectDir = path.join(globalRoot, 'projects', slug);\n return {\n globalRoot,\n configDir: globalRoot,\n globalConfig: path.join(globalRoot, 'config.json'),\n secretsKey: path.join(globalRoot, '.key'),\n globalMemory: path.join(globalRoot, 'memory.md'),\n globalSkills: path.join(globalRoot, 'skills'),\n globalPrompts: path.join(globalRoot, 'prompts'),\n cacheDir: path.join(globalRoot, 'cache'),\n modelsCache: path.join(globalRoot, 'cache', 'models.dev.json'),\n modelsOverlayCache: path.join(globalRoot, 'cache', 'models-overlay.json'),\n historyFile: path.join(globalRoot, 'history'),\n logFile: path.join(globalRoot, 'logs', 'wrongstack.log'),\n projectDir,\n projectCodebaseIndex: path.join(projectDir, 'codebase-index'),\n projectMemory: path.join(projectDir, 'memory.md'),\n projectSessions: path.join(projectDir, 'sessions'),\n projectTrust: path.join(projectDir, 'trust.json'),\n projectMeta: path.join(projectDir, 'meta.json'),\n projectLocalConfig: path.join(projectDir, 'config.local.json'),\n inProjectConfig: path.join(opts.projectRoot, '.wrongstack', 'config.json'),\n inProjectAgentsFile: path.join(opts.projectRoot, '.wrongstack', 'AGENTS.md'),\n inProjectSkills: path.join(opts.projectRoot, '.wrongstack', 'skills'),\n inProjectWorktrees: path.join(opts.projectRoot, '.wrongstack', 'worktrees'),\n projectHash: hash,\n projectSlug: slug,\n projectGoal: path.join(projectDir, 'goal.json'),\n projectSpecs: path.join(projectDir, 'specs'),\n projectTaskGraphs: path.join(projectDir, 'task-graphs'),\n projectSddSession: path.join(projectDir, 'sdd-session.json'),\n projectPlan: path.join(projectDir, 'plan.json'),\n projectAutophase: path.join(projectDir, 'autophase'),\n syncConfig: path.join(globalRoot, 'sync.json'),\n projectStatus: (projectHash: string) => path.join(globalRoot, 'projects', projectHash, 'status.json'),\n };\n}\n","import { toErrorMessage } from '../utils/index.js';\n\n/**\n * WrongStack error hierarchy.\n *\n * Every error thrown by the framework is a `WrongStackError` with a\n * machine-readable `code`, a `subsystem` tag, and a `severity` level.\n * This lets consumers (CLI, TUI, plugins, tests) branch on structured\n * data instead of parsing error messages.\n */\n\n// ── Error codes ──────────────────────────────────────────────────────\n\n/**\n * Machine-readable error codes as frozen constants.\n *\n * Use `ERROR_CODES.X` instead of raw string literals for:\n * - IDE autocomplete and compile-time validation\n * - Safe refactoring (rename updates all usages)\n * - Plugin extensibility (extend the object to add custom codes)\n *\n * The `ErrorCode` type is derived from this object, so adding a new\n * code here automatically updates the type without extra changes.\n */\nexport const ERROR_CODES = {\n // Provider\n PROVIDER_RATE_LIMITED: 'PROVIDER_RATE_LIMITED',\n PROVIDER_AUTH_FAILED: 'PROVIDER_AUTH_FAILED',\n PROVIDER_OVERLOADED: 'PROVIDER_OVERLOADED',\n PROVIDER_INVALID_REQUEST: 'PROVIDER_INVALID_REQUEST',\n PROVIDER_SERVER_ERROR: 'PROVIDER_SERVER_ERROR',\n PROVIDER_NETWORK_ERROR: 'PROVIDER_NETWORK_ERROR',\n PROVIDER_CONTEXT_OVERFLOW: 'PROVIDER_CONTEXT_OVERFLOW',\n // Tool\n TOOL_NOT_FOUND: 'TOOL_NOT_FOUND',\n TOOL_PERMISSION_DENIED: 'TOOL_PERMISSION_DENIED',\n TOOL_EXECUTION_FAILED: 'TOOL_EXECUTION_FAILED',\n TOOL_TIMEOUT: 'TOOL_TIMEOUT',\n TOOL_INPUT_INVALID: 'TOOL_INPUT_INVALID',\n // Config\n CONFIG_INVALID: 'CONFIG_INVALID',\n CONFIG_NOT_FOUND: 'CONFIG_NOT_FOUND',\n CONFIG_PARSE_FAILED: 'CONFIG_PARSE_FAILED',\n CONFIG_MIGRATION_NEEDED: 'CONFIG_MIGRATION_NEEDED',\n // Plugin\n PLUGIN_LOAD_FAILED: 'PLUGIN_LOAD_FAILED',\n PLUGIN_API_MISMATCH: 'PLUGIN_API_MISMATCH',\n PLUGIN_MISSING_DEPENDENCY: 'PLUGIN_MISSING_DEPENDENCY',\n // Agent\n AGENT_ITERATION_LIMIT: 'AGENT_ITERATION_LIMIT',\n AGENT_CONTEXT_OVERFLOW: 'AGENT_CONTEXT_OVERFLOW',\n AGENT_ABORTED: 'AGENT_ABORTED',\n AGENT_RUN_FAILED: 'AGENT_RUN_FAILED',\n // Session\n SESSION_NOT_FOUND: 'SESSION_NOT_FOUND',\n SESSION_CORRUPTED: 'SESSION_CORRUPTED',\n SESSION_WRITE_FAILED: 'SESSION_WRITE_FAILED',\n // Container / Registry\n CONTAINER_TOKEN_ALREADY_BOUND: 'CONTAINER_TOKEN_ALREADY_BOUND',\n CONTAINER_TOKEN_NOT_BOUND: 'CONTAINER_TOKEN_NOT_BOUND',\n CONTAINER_CIRCULAR_DEPENDENCY: 'CONTAINER_CIRCULAR_DEPENDENCY',\n REGISTRY_DUPLICATE: 'REGISTRY_DUPLICATE',\n REGISTRY_NOT_FOUND: 'REGISTRY_NOT_FOUND',\n REGISTRY_INVALID: 'REGISTRY_INVALID',\n // File system\n FS_READ_FAILED: 'FS_READ_FAILED',\n FS_WRITE_FAILED: 'FS_WRITE_FAILED',\n FS_MKDIR_FAILED: 'FS_MKDIR_FAILED',\n FS_DELETE_FAILED: 'FS_DELETE_FAILED',\n FS_ATOMIC_WRITE_FAILED: 'FS_ATOMIC_WRITE_FAILED',\n // SDD (Spec-Driven Development)\n SDD_VALIDATION_FAILED: 'SDD_VALIDATION_FAILED',\n SDD_PARSE_FAILED: 'SDD_PARSE_FAILED',\n SDD_INVALID_STATE: 'SDD_INVALID_STATE',\n SDD_NOT_READY: 'SDD_NOT_READY',\n // General\n VALIDATION_ERROR: 'VALIDATION_ERROR',\n UNKNOWN: 'UNKNOWN',\n} as const;\n\n/**\n * Union type derived from `ERROR_CODES`. Using `typeof ERROR_CODES[keyof typeof ERROR_CODES]`\n * instead of a string literal union means TypeScript auto-updates the type whenever\n * a new code is added to `ERROR_CODES` — no need to keep two lists in sync.\n */\nexport type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];\n\nexport type ErrorSubsystem =\n | 'provider'\n | 'tool'\n | 'config'\n | 'plugin'\n | 'agent'\n | 'session'\n | 'sdd'\n | 'container'\n | 'fs'\n | 'general';\nexport type ErrorSeverity = 'fatal' | 'error' | 'warning';\n\n// ── Base error class ─────────────────────────────────────────────────\n\nexport class WrongStackError extends Error {\n readonly code: ErrorCode;\n readonly subsystem: ErrorSubsystem;\n readonly severity: ErrorSeverity;\n readonly recoverable: boolean;\n readonly context?: Record<string, unknown> | undefined;\n\n constructor(opts: {\n message: string;\n code: ErrorCode;\n subsystem: ErrorSubsystem;\n severity?: ErrorSeverity | undefined;\n recoverable?: boolean | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super(opts.message, { cause: opts.cause });\n this.name = 'WrongStackError';\n this.code = opts.code;\n this.subsystem = opts.subsystem;\n this.severity = opts.severity ?? 'error';\n this.recoverable = opts.recoverable ?? false;\n this.context = opts.context;\n }\n\n /**\n * Render a one-line user-facing description.\n * Subclasses should override for domain-specific formatting.\n */\n describe(): string {\n const ctx = this.context ? ` ${formatContext(this.context)}` : '';\n return `${this.code}: ${this.message}${ctx}`;\n }\n}\n\nfunction formatContext(ctx: Record<string, unknown>): string {\n const parts = Object.entries(ctx)\n .filter(([, v]) => v !== undefined)\n .slice(0, 3)\n .map(([k, v]) => `${k}=${String(v)}`);\n return parts.length > 0 ? `[${parts.join(' ')}]` : '';\n}\n\n// ── Specific error classes ───────────────────────────────────────────\n\n/**\n * Tool execution errors — thrown by ToolExecutor and individual tools.\n */\nexport class ToolError extends WrongStackError {\n readonly toolName: string;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n | 'TOOL_NOT_FOUND'\n | 'TOOL_PERMISSION_DENIED'\n | 'TOOL_EXECUTION_FAILED'\n | 'TOOL_TIMEOUT'\n | 'TOOL_INPUT_INVALID'\n >;\n toolName: string;\n recoverable?: boolean | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'tool',\n recoverable: opts.recoverable,\n context: { tool: opts.toolName, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'ToolError';\n this.toolName = opts.toolName;\n }\n}\n\n/**\n * Config loading / validation errors.\n */\nexport class ConfigError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'CONFIG_INVALID' | 'CONFIG_NOT_FOUND' | 'CONFIG_PARSE_FAILED' | 'CONFIG_MIGRATION_NEEDED'\n >;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'config',\n severity: 'fatal',\n recoverable: false,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'ConfigError';\n }\n}\n\n/**\n * Plugin loading / lifecycle errors.\n */\nexport class PluginError extends WrongStackError {\n readonly pluginName: string;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'PLUGIN_LOAD_FAILED' | 'PLUGIN_API_MISMATCH' | 'PLUGIN_MISSING_DEPENDENCY'\n >;\n pluginName: string;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'plugin',\n severity: 'error',\n recoverable: opts.code === ERROR_CODES.PLUGIN_MISSING_DEPENDENCY,\n context: { plugin: opts.pluginName, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'PluginError';\n this.pluginName = opts.pluginName;\n }\n}\n\n/**\n * Agent runtime errors — thrown by Agent.run when a non-WrongStackError\n * escapes the inner loop, so callers always see a structured error.\n */\nexport class AgentError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'AGENT_ITERATION_LIMIT' | 'AGENT_CONTEXT_OVERFLOW' | 'AGENT_ABORTED' | 'AGENT_RUN_FAILED'\n >;\n recoverable?: boolean | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'agent',\n severity: opts.code === ERROR_CODES.AGENT_ABORTED ? 'warning' : 'error',\n recoverable: opts.recoverable ?? opts.code === ERROR_CODES.AGENT_ITERATION_LIMIT,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'AgentError';\n }\n}\n\n/**\n * Wrap an arbitrary thrown value into a `WrongStackError` so the caller\n * always gets a structured error. Pass-throughs WrongStackError instances\n * unchanged; raw `Error`s and primitives get an `AGENT_RUN_FAILED` wrapper\n * with the original preserved as `cause`.\n */\nexport function toWrongStackError(\n err: unknown,\n code: Extract<ErrorCode, 'AGENT_RUN_FAILED' | 'AGENT_ABORTED' | 'UNKNOWN'> = ERROR_CODES.AGENT_RUN_FAILED,\n): WrongStackError {\n if (err instanceof WrongStackError) return err;\n const message = toErrorMessage(err);\n return new AgentError({\n message,\n code: code === 'UNKNOWN' ? ERROR_CODES.AGENT_RUN_FAILED : code,\n cause: err,\n });\n}\n\n/**\n * Session storage errors.\n */\nexport class SessionError extends WrongStackError {\n readonly sessionId?: string | undefined;\n\n constructor(opts: {\n message: string;\n code: Extract<ErrorCode, 'SESSION_NOT_FOUND' | 'SESSION_CORRUPTED' | 'SESSION_WRITE_FAILED'>;\n sessionId?: string | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'session',\n severity: opts.code === ERROR_CODES.SESSION_WRITE_FAILED ? 'error' : 'warning',\n recoverable: opts.code !== ERROR_CODES.SESSION_CORRUPTED,\n context: { sessionId: opts.sessionId, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'SessionError';\n this.sessionId = opts.sessionId;\n }\n}\n\n/**\n * SDD (Spec-Driven Development) errors — spec validation, parsing, and\n * state machine violations in the AISpecBuilder, TaskFlow, and TaskTracker.\n */\nexport class SddError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'SDD_VALIDATION_FAILED' | 'SDD_PARSE_FAILED' | 'SDD_INVALID_STATE' | 'SDD_NOT_READY'\n >;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'sdd',\n severity: opts.code === ERROR_CODES.SDD_PARSE_FAILED ? 'warning' : 'error',\n recoverable: opts.code === ERROR_CODES.SDD_NOT_READY,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'SddError';\n }\n}\n\n/**\n * File system operation errors.\n */\nexport class FsError extends WrongStackError {\n readonly path?: string | undefined;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'FS_READ_FAILED' | 'FS_WRITE_FAILED' | 'FS_MKDIR_FAILED' | 'FS_DELETE_FAILED' | 'FS_ATOMIC_WRITE_FAILED'\n >;\n path?: string | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'fs',\n severity: 'error',\n recoverable: opts.code !== ERROR_CODES.FS_READ_FAILED,\n context: { path: opts.path, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'FsError';\n this.path = opts.path;\n }\n}\n\n// ── Type guards ──────────────────────────────────────────────────────\n\nexport function isWrongStackError(err: unknown): err is WrongStackError {\n return err instanceof WrongStackError;\n}\n\nexport function isToolError(err: unknown): err is ToolError {\n return err instanceof ToolError;\n}\n\nexport function isConfigError(err: unknown): err is ConfigError {\n return err instanceof ConfigError;\n}\n\nexport function isPluginError(err: unknown): err is PluginError {\n return err instanceof PluginError;\n}\n\nexport function isSessionError(err: unknown): err is SessionError {\n return err instanceof SessionError;\n}\n\nexport function isAgentError(err: unknown): err is AgentError {\n return err instanceof AgentError;\n}\n\nexport function isFsError(err: unknown): err is FsError {\n return err instanceof FsError;\n}\n\nexport function isSddError(err: unknown): err is SddError {\n return err instanceof SddError;\n}\n","import type { Context } from '../core/context.js';\nimport type { EventBus } from '../kernel/events.js';\nimport type { MiddlewareHandler } from '../kernel/pipeline.js';\nimport type { SessionEventBridge } from '../storage/session-event-bridge.js';\nimport type { CompactReport, Compactor } from '../types/compactor.js';\nimport type { ContextWindowAggressiveOn, ContextWindowPolicy } from '../types/context-window.js';\nimport { AgentError, ERROR_CODES } from '../types/errors.js';\nimport {\n estimateRequestTokensCalibrated,\n getCalibrationState,\n} from '../utils/token-estimate.js';\nimport { repeatedReadPressure } from '../utils/context-evidence.js';\n\ntype PressureLevel = 'warn' | 'soft' | 'hard';\nconst LEVEL_RANK: Record<PressureLevel, number> = { warn: 0, soft: 1, hard: 2 };\n\nexport interface ContextWindowBudgetSnapshot {\n maxContext: number;\n inputTokens: number;\n availableInputTokens: number;\n remainingInputTokens: number;\n reservedOutputTokens: number;\n reservedSafetyTokens: number;\n load: number;\n overflowTokens: number;\n}\n\n/** Max chars of collapse digest persisted to the session log line. */\nconst MAX_DIGEST_LOG_CHARS = 4_000;\n\nfunction truncateDigest(digest: string): string {\n if (digest.length <= MAX_DIGEST_LOG_CHARS) return digest;\n return `${digest.slice(0, MAX_DIGEST_LOG_CHARS)}… [+${digest.length - MAX_DIGEST_LOG_CHARS} chars; full turns in session log]`;\n}\n\nexport type CompactionFailureMode = 'throw' | 'throw_on_hard' | 'continue';\n\nexport interface AutoCompactionOptions {\n aggressiveOn?: ContextWindowAggressiveOn | undefined;\n events?: EventBus | undefined;\n failureMode?: CompactionFailureMode | undefined;\n policyProvider?: (ctx: Context) => Pick<\n ContextWindowPolicy,\n 'thresholds' | 'aggressiveOn'\n > | null | undefined;\n /** Optional bridge for writing compaction events into the persistent session log. */\n sessionBridge?: SessionEventBridge | undefined;\n}\n\n/**\n * Pipeline middleware that monitors context token load and automatically\n * triggers compaction when the warn/soft/hard thresholds are crossed.\n * Runs before the next agent iteration.\n *\n * Uses `estimateRequestTokens` for accurate full-request token counting:\n * messages + systemPrompt + toolDefs. This replaces the previous pattern\n * of applying an OVERHEAD_FACTOR to a messages-only estimate.\n */\nexport class AutoCompactionMiddleware {\n readonly name = 'AutoCompaction';\n\n private readonly compactor: Compactor;\n /** Deprecated. Kept for backward compat with tests that pass simpleEstimator. */\n private readonly _estimator?: (((ctx: Context) => number)) | undefined;\n private readonly warnThreshold: number;\n private readonly softThreshold: number;\n private readonly hardThreshold: number;\n /** Writable so model-switch can update the denominator without re-registering the middleware. */\n private _maxContext: number;\n /**\n * Runtime on/off gate. The middleware is always installed in the pipeline so\n * auto-compaction can be toggled live from the TUI `/settings` picker; when\n * disabled the handler is a pass-through. Defaults to enabled.\n */\n private _enabled = true;\n private readonly aggressiveOn: ContextWindowAggressiveOn;\n private readonly events?: EventBus | undefined;\n private readonly failureMode: CompactionFailureMode;\n private readonly policyProvider?: AutoCompactionOptions['policyProvider'] | undefined;\n private readonly sessionBridge?: SessionEventBridge | undefined;\n\n /**\n * Once a compaction attempt reduces nothing (preserveK protects everything,\n * no oversized tool_results remain to elide), retrying on every iteration\n * just spams `compaction.fired` events without making progress. We remember\n * the no-op and skip until either the pressure level escalates or context\n * has grown by at least this many tokens since the failed attempt.\n */\n private static readonly NOOP_RETRY_DELTA_TOKENS = 2_000;\n\n /** Tracks the most recent no-op attempt so we can avoid re-firing per turn. */\n private lastNoopAttempt: { level: PressureLevel; tokens: number } | null = null;\n\n /**\n * Cached token estimate from the last handler() invocation. When the\n * message count and tool count haven't changed since the last estimate\n * (autonomous idle loops), we skip the expensive O(n) token estimation\n * and reuse this value. Reset to -1 when the context changes.\n */\n private _cachedTokens = -1;\n private _cachedMsgCount = -1;\n private _cachedToolCount = -1;\n\n /**\n * @param compactor Compactor to use for compaction.\n * @param maxContext Provider's max context window in tokens.\n * @param _estimator Deprecated parameter kept for backward compatibility.\n * The middleware now uses `estimateRequestTokens` internally\n * for accurate full-request token counting (messages +\n * systemPrompt + toolDefs).\n * @param thresholds Threshold fractions (0-1) of maxContext.\n * @param opts Optional behavior. By default, failures at the\n * hard threshold throw AGENT_CONTEXT_OVERFLOW so\n * the agent does not continue into a likely\n * provider context overflow. Warn/soft failures\n * still emit compaction.failed and continue.\n */\n constructor(\n compactor: Compactor,\n maxContext: number,\n _estimator: (ctx: Context) => number,\n thresholds: { warn: number; soft: number; hard: number },\n optsOrAggressiveOn: AutoCompactionOptions | ContextWindowAggressiveOn = {},\n events?: EventBus | undefined,\n ) {\n const opts =\n typeof optsOrAggressiveOn === 'string'\n ? { aggressiveOn: optsOrAggressiveOn, events }\n : optsOrAggressiveOn;\n this.compactor = compactor;\n this._maxContext = maxContext;\n this._estimator = _estimator;\n this.warnThreshold = thresholds.warn;\n this.softThreshold = thresholds.soft;\n this.hardThreshold = thresholds.hard;\n this.aggressiveOn = opts.aggressiveOn ?? 'soft';\n this.events = opts.events;\n this.failureMode = opts.failureMode ?? 'throw_on_hard';\n this.policyProvider = opts.policyProvider;\n this.sessionBridge = opts.sessionBridge;\n }\n\n /** Allow callers (e.g. model-switch in WebUI) to update the context window\n * denominator when the active model changes. */\n setMaxContext(maxContext: number): void {\n this._maxContext = maxContext;\n }\n\n /** Whether auto-compaction is currently active. */\n get enabled(): boolean {\n return this._enabled;\n }\n\n /** Toggle auto-compaction on a live session (TUI `/settings`). When disabled\n * the middleware passes every iteration straight through without estimating\n * tokens or compacting. */\n setEnabled(enabled: boolean): void {\n this._enabled = enabled;\n }\n\n handler(): MiddlewareHandler<Context> {\n return async (ctx, next) => {\n // Runtime gate — when auto-compaction is turned off via /settings the\n // middleware stays installed but does nothing.\n if (!this._enabled) return next(ctx);\n // Reuse the last token estimate when the context hasn't grown since\n // the previous check — common in autonomous idle loops. The cached\n // value is invalidated whenever messages or tools change.\n //\n // IMPORTANT: the cache is only valid for the deterministic\n // estimateRequestTokensCalibrated path (messages+system+tools → fixed\n // output). When a custom _estimator is provided (e.g. in tests with\n // a mutable closure, or a dynamic policy provider), always call it\n // fresh — the estimator owns its own semantics and the middleware\n // cannot safely cache its result across calls.\n const msgCount = ctx.messages.length;\n const toolCount = (ctx.tools ?? []).length;\n\n let tokens: number;\n if (this._estimator) {\n // Custom estimator — never cache; call fresh every invocation.\n tokens = this._estimator(ctx);\n } else if (\n msgCount === this._cachedMsgCount &&\n toolCount === this._cachedToolCount &&\n this._cachedTokens >= 0\n ) {\n // Default estimator, context unchanged — reuse cached value.\n tokens = this._cachedTokens;\n } else if (this.tryStashedTokens(ctx, msgCount, toolCount) !== null) {\n // H1: the agent loop's pre-flight (or its restash in emitContextPct)\n // populated `ctx.lastRequestTokens` this iteration. Apply the\n // per-(provider,model) calibration ratio and use it. This avoids\n // a third redundant O(n) walk per iteration.\n const stashed = this.tryStashedTokens(ctx, msgCount, toolCount) as number;\n const cal = getCalibrationState(`${ctx.provider?.id ?? 'unknown'}/${ctx.model}`);\n tokens = cal.calibrated\n ? Math.round(stashed * Math.min(1.5, Math.max(0.5, cal.ratio)))\n : stashed;\n this._cachedTokens = tokens;\n this._cachedMsgCount = msgCount;\n this._cachedToolCount = toolCount;\n } else {\n // Default estimator, context changed and no stash — compute fresh\n // and cache. Cold-start path: very first iteration, or the\n // middleware is being driven from somewhere that didn't run the\n // agent loop's pre-flight (tests, manual compaction trigger).\n tokens = estimateRequestTokensCalibrated(\n ctx.messages,\n ctx.systemPrompt,\n ctx.tools ?? [],\n `${ctx.provider?.id ?? 'unknown'}/${ctx.model}`,\n ).total;\n this._cachedTokens = tokens;\n this._cachedMsgCount = msgCount;\n this._cachedToolCount = toolCount;\n }\n const budget = computeContextWindowBudget(ctx, tokens, this._maxContext);\n const load = budget.load;\n const policy = this.policyProvider?.(ctx);\n const thresholds = policy?.thresholds ?? {\n warn: this.warnThreshold,\n soft: this.softThreshold,\n hard: this.hardThreshold,\n };\n const repetition = repeatedReadPressure(ctx);\n const adaptiveThresholds = adaptThresholdsForSignals(thresholds, {\n repeatedReadCount: repetition,\n });\n const aggressiveOn = policy?.aggressiveOn ?? this.aggressiveOn;\n\n const level: PressureLevel | null =\n load >= adaptiveThresholds.hard\n ? 'hard'\n : load >= adaptiveThresholds.soft\n ? 'soft'\n : load >= adaptiveThresholds.warn\n ? 'warn'\n : null;\n\n if (!level) {\n // Load dropped back below all thresholds — any previously stuck state\n // is no longer relevant.\n this.lastNoopAttempt = null;\n return next(ctx);\n }\n\n if (this.shouldSkipNoopRetry(level, tokens)) {\n return next(ctx);\n }\n\n const aggressive =\n level === 'hard'\n ? true\n : level === 'soft'\n ? aggressiveOn !== 'hard'\n : aggressiveOn === 'warn';\n\n await this.compact(ctx, aggressive, {\n level,\n tokens,\n load,\n budget,\n signals: { repeatedReadCount: repetition },\n });\n\n return next(ctx);\n };\n }\n\n /**\n * H1: try to read a pre-computed token total from `ctx.lastRequestTokens`\n * (set by the agent loop's pre-flight or its restash in emitContextPct).\n * Returns the uncalibrated total when the stash is valid for the current\n * context shape (positive number, and the message count it was computed\n * at matches the current one — otherwise tool results have been appended\n * since and the value is stale). Returns null when missing or stale so\n * the caller falls back to a fresh walk.\n */\n private tryStashedTokens(ctx: Context, msgCount: number, toolCount: number): number | null {\n const stashed = ctx.lastRequestTokens;\n if (typeof stashed !== 'number' || stashed <= 0) return null;\n // The agent loop writes the (msg, tool) count it computed the stash at\n // into ctx.meta['lastRequestTokensAt']. When the counts disagree the\n // caller has already recomputed and refreshed the stash, but we verify\n // the meta key exists for safety — older code paths and tests may set\n // lastRequestTokens without the companion entry.\n const stashedAt = ctx.meta?.['lastRequestTokensAt'];\n if (typeof stashedAt !== 'object' || stashedAt === null) return null;\n const meta = stashedAt as { msgCount?: unknown; toolCount?: unknown };\n if (meta.msgCount !== msgCount) return null;\n if (typeof meta.toolCount === 'number' && meta.toolCount !== toolCount) return null;\n return stashed;\n }\n\n /**\n * Returns true when the previous compaction at the same or higher pressure\n * level reduced nothing and context has not grown materially since. Prevents\n * a stuck preserveK window from spamming compaction events every iteration.\n */\n private shouldSkipNoopRetry(level: PressureLevel, tokens: number): boolean {\n const stuck = this.lastNoopAttempt;\n if (!stuck) return false;\n // Escalation always retries — soft → hard might be reducible aggressively.\n if (LEVEL_RANK[level] > LEVEL_RANK[stuck.level]) return false;\n const delta = tokens - stuck.tokens;\n return delta < AutoCompactionMiddleware.NOOP_RETRY_DELTA_TOKENS;\n }\n\n private recordAttempt(level: PressureLevel, tokens: number, report: CompactReport): void {\n // Prefer full-request tokens (accurate); fall back to message-only before/after.\n const reduced =\n (report.fullRequestTokensBefore ?? report.before) > (report.fullRequestTokensAfter ?? report.after);\n const repaired = !!report.repaired;\n if (reduced || repaired) {\n this.lastNoopAttempt = null;\n } else {\n this.lastNoopAttempt = { level, tokens };\n }\n }\n\n private async compact(\n ctx: Context,\n aggressive: boolean,\n pressure: {\n level: PressureLevel;\n tokens: number;\n load: number;\n budget: ContextWindowBudgetSnapshot;\n signals: { repeatedReadCount: number };\n },\n ): Promise<void> {\n try {\n const report = await this.compactor.compact(ctx, { aggressive });\n this.recordAttempt(pressure.level, pressure.tokens, report);\n this.events?.emit('compaction.fired', {\n level: pressure.level,\n tokens: pressure.tokens,\n load: pressure.load,\n maxContext: this._maxContext,\n budget: pressure.budget,\n signals: pressure.signals,\n report,\n aggressive,\n });\n\n // Persist a compaction event to the session log (if a bridge was provided).\n // This is one of the highest-value audit events for understanding context\n // window behavior over long runs.\n await this.sessionBridge?.append({\n type: 'compaction',\n ts: new Date().toISOString(),\n before: report.before,\n after: report.after,\n level: pressure.level,\n aggressive,\n reductions: report.reductions?.map((r) => ({ phase: r.phase, saved: r.saved })),\n budget: pressure.budget,\n signals: pressure.signals,\n // Record what was collapsed so the audit trail shows the preserved\n // content, not just token counts. Bounded to keep the log line small;\n // the full original turns are already in the session JSONL.\n ...(report.collapsedDigest\n ? { digest: truncateDigest(report.collapsedDigest) }\n : {}),\n });\n\n // Stale file-read metadata from before the compaction boundary is no\n // longer useful and would cause hasRead() to skip legitimate re-reads.\n ctx.clearFileTracking();\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n const fatal =\n this.failureMode === 'throw' ||\n (this.failureMode === 'throw_on_hard' && pressure.level === 'hard');\n this.events?.emit('compaction.failed', {\n err: error,\n aggressive,\n level: pressure.level,\n tokens: pressure.tokens,\n maxContext: this._maxContext,\n budget: pressure.budget,\n signals: pressure.signals,\n load: pressure.load,\n fatal,\n });\n if (fatal) {\n throw new AgentError({\n message: `Auto-compaction failed at ${pressure.level} threshold`,\n code: ERROR_CODES.AGENT_CONTEXT_OVERFLOW,\n recoverable: true,\n context: {\n level: pressure.level,\n tokens: pressure.tokens,\n maxContext: this._maxContext,\n },\n cause: err,\n });\n }\n }\n }\n}\n\nfunction computeContextWindowBudget(\n ctx: Context,\n inputTokens: number,\n maxContext: number,\n): ContextWindowBudgetSnapshot {\n const reservedOutputTokens = readPositiveMetaNumber(ctx, 'contextOutputReserveTokens') ??\n Math.floor(Math.min(8192, maxContext * 0.08));\n const reservedSafetyTokens = readPositiveMetaNumber(ctx, 'contextSafetyBufferTokens') ??\n Math.floor(Math.min(4096, maxContext * 0.02));\n const availableInputTokens = Math.max(\n 1,\n maxContext - reservedOutputTokens - reservedSafetyTokens,\n );\n const remainingInputTokens = availableInputTokens - inputTokens;\n return {\n maxContext,\n inputTokens,\n availableInputTokens,\n remainingInputTokens,\n reservedOutputTokens,\n reservedSafetyTokens,\n load: inputTokens / availableInputTokens,\n overflowTokens: Math.max(0, -remainingInputTokens),\n };\n}\n\nfunction readPositiveMetaNumber(ctx: Context, key: string): number | undefined {\n const value = ctx.meta?.[key];\n return typeof value === 'number' && Number.isFinite(value) && value >= 0\n ? Math.floor(value)\n : undefined;\n}\n\nfunction adaptThresholdsForSignals(\n thresholds: { warn: number; soft: number; hard: number },\n signals: { repeatedReadCount: number },\n): { warn: number; soft: number; hard: number } {\n if (signals.repeatedReadCount < 3) return thresholds;\n // Re-reading the same file repeatedly is a strong sign of shrinking-spiral\n // behavior. Lower only warn/soft a little so compaction can refresh anchors\n // before the hard overflow path, but keep hard fixed as the safety boundary.\n return {\n warn: Math.max(0.25, thresholds.warn - 0.08),\n soft: Math.max(0.35, thresholds.soft - 0.04),\n hard: thresholds.hard,\n };\n}\n","/**\n * Well-known tool capabilities used for authorization decisions.\n *\n * These are the preferred values for `Tool.capabilities`.\n * New capabilities should be added here with clear documentation.\n *\n * Philosophy (2026-06+):\n * - Prefer capabilities over exact tool name matching.\n * - Subagent guards and future policies should primarily key off capabilities.\n * - Name-based denylists are legacy and will be phased down.\n */\nexport const ToolCapabilities = {\n /** Can execute arbitrary commands in the user's shell (the `bash` tool). */\n SHELL_ARBITRARY: 'shell.arbitrary',\n\n /** Can execute a restricted set of commands (the `exec` tool). */\n SHELL_RESTRICTED: 'shell.restricted',\n\n /** Can read files inside the project (and possibly outside via symlinks if not guarded). */\n FS_READ: 'fs.read',\n\n /** Can write / modify / delete files inside the project. */\n FS_WRITE: 'fs.write',\n\n /** Can write files outside the current project root (very high risk). */\n FS_WRITE_OUTSIDE_PROJECT: 'fs.write.outside-project',\n\n /** Can perform outbound network requests. */\n NET_OUTBOUND: 'net.outbound',\n\n /** Proxies tools from external MCP servers (unknown capability). */\n MCP_PROXY: 'mcp.proxy',\n\n /** Can spawn or manage subagents / multi-agent tasks. */\n SUBAGENT_SPAWN: 'subagent.spawn',\n\n /** Can mutate global or session configuration / trust state. */\n CONFIG_MUTATE: 'config.mutate',\n\n /** Can install packages or run package managers with side effects. */\n PACKAGE_INSTALL: 'package.install',\n} as const;\n\nexport type ToolCapability = (typeof ToolCapabilities)[keyof typeof ToolCapabilities];\n\n/**\n * Set of capabilities that are considered dangerous for subagents by default.\n * Subagents should not receive these capabilities unless the leader explicitly\n * allows the specific tool at spawn time.\n */\nexport const DANGEROUS_FOR_SUBAGENTS: readonly ToolCapability[] = [\n ToolCapabilities.SHELL_ARBITRARY,\n ToolCapabilities.SHELL_RESTRICTED,\n ToolCapabilities.FS_WRITE,\n ToolCapabilities.FS_WRITE_OUTSIDE_PROJECT,\n ToolCapabilities.MCP_PROXY,\n ToolCapabilities.SUBAGENT_SPAWN,\n ToolCapabilities.CONFIG_MUTATE,\n ToolCapabilities.PACKAGE_INSTALL,\n];\n\n/**\n * Wide capability allowlist for subagents that the user has authorized to act\n * with full developer power (the CLI fleet host applies this to any subagent\n * that isn't given an explicit, narrower grant). It covers everything needed to\n * do real work end-to-end — read, write/edit inside the project, outbound\n * network, and shell/build/install — so a delegated coding or build agent runs\n * the same toolchain the leader would, without per-tool confirmation it cannot\n * answer.\n *\n * Deliberately EXCLUDED (require an explicit per-spawn `allowedCapabilities`\n * grant, because they escape the task's blast radius rather than perform it):\n * - `fs.write.outside-project` — writing outside the repo (e.g. ~/.ssh).\n * - `mcp.proxy` — third-party MCP tools (also hard-blocked by name).\n * - `subagent.spawn` — recursive delegation (the baseline prompt forbids it).\n * - `config.mutate` — rewriting trust/config is privilege escalation, not work.\n */\nexport const WIDE_SUBAGENT_CAPABILITIES: readonly ToolCapability[] = [\n ToolCapabilities.FS_READ,\n ToolCapabilities.FS_WRITE,\n ToolCapabilities.NET_OUTBOUND,\n ToolCapabilities.SHELL_ARBITRARY,\n ToolCapabilities.SHELL_RESTRICTED,\n ToolCapabilities.PACKAGE_INSTALL,\n];\n\n/**\n * Check if a tool (or its capabilities array) includes any dangerous capability\n * for subagent execution.\n */\nexport function hasDangerousCapabilityForSubagents(\n toolOrCaps: { capabilities?: readonly string[] | undefined } | readonly string[] | undefined,\n): boolean {\n if (!toolOrCaps) return false;\n const input = toolOrCaps as never as { capabilities?: readonly string[] | undefined };\n const caps: readonly string[] = Array.isArray(toolOrCaps) ? toolOrCaps : (input.capabilities ?? []);\n return caps.some((c) => DANGEROUS_FOR_SUBAGENTS.includes(c as ToolCapability));\n}\n\n/**\n * Check if a tool declares a specific capability (or any of the provided ones).\n */\nexport function hasCapability(\n toolOrCaps: { capabilities?: readonly string[] | undefined } | readonly string[] | undefined,\n capability: ToolCapability | ToolCapability[],\n): boolean {\n if (!toolOrCaps) return false;\n const input = toolOrCaps as never as { capabilities?: readonly string[] | undefined };\n const caps: readonly string[] = Array.isArray(toolOrCaps) ? toolOrCaps : (input.capabilities ?? []);\n const toCheck = Array.isArray(capability) ? capability : [capability];\n return toCheck.some((c) => caps.includes(c));\n}\n\n/**\n * Returns the intersection of a tool's capabilities with the dangerous set.\n * Useful for logging and audit trails.\n */\nexport function getDangerousCapabilities(\n toolOrCaps: { capabilities?: readonly string[] | undefined } | readonly string[] | undefined,\n): ToolCapability[] {\n if (!toolOrCaps) return [];\n const input = toolOrCaps as never as { capabilities?: readonly string[] | undefined };\n const caps: readonly string[] = Array.isArray(toolOrCaps) ? toolOrCaps : (input.capabilities ?? []);\n return caps.filter((c): c is ToolCapability =>\n DANGEROUS_FOR_SUBAGENTS.includes(c as ToolCapability),\n );\n}\n","import { randomUUID } from 'node:crypto';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { Context } from '../core/context.js';\nimport {\n getDangerousCapabilities,\n hasDangerousCapabilityForSubagents,\n} from '../security/capabilities.js';\nimport type { ToolResultBlock, ToolUseBlock } from '../types/blocks.js';\nimport type { Tool, ToolProgressEvent, ToolErrorCategory } from '../types/tool.js';\nimport { ToolErrorCategory as ToolErrorCategoryEnum } from '../types/tool.js';\nimport type {\n ToolBatchResult,\n ToolConfirmPendingResult,\n ToolExecutionOutput,\n ToolExecutorOptions,\n ToolExecutorStrategy,\n} from '../types/tool-executor.js';\nimport { toErrorMessage } from '../utils/error.js';\nimport { expectDefined } from '../utils/expect-defined.js';\nimport { validateAgainstSchema } from '../utils/json-schema-validate.js';\nimport { subjectForToolInput } from '../utils/tool-subject.js';\nimport { createToolOutputSerializer } from '../utils/tool-output-serializer.js';\nimport { wstackGlobalRoot } from '../utils/wstack-paths.js';\nexport class ToolExecutor {\n /** Minimum gap between coalesced `partial_output` tool.progress emits. */\n static readonly PROGRESS_EMIT_INTERVAL_MS = 100;\n /** Max chars of accumulated stream text carried per coalesced emit. */\n static readonly PROGRESS_TAIL_CHARS = 16_384;\n\n private readonly serializer;\n private readonly iterationTimeoutMs: number;\n private readonly maxToolTimeoutMs: number;\n\n constructor(\n private readonly registry: { get(name: string): Tool | undefined; list(): Tool[] },\n private opts: ToolExecutorOptions,\n ) {\n this.iterationTimeoutMs = opts.iterationTimeoutMs ?? 300_000;\n this.maxToolTimeoutMs = opts.maxToolTimeoutMs ?? 300_000;\n this.serializer = createToolOutputSerializer({\n perIterationOutputCapBytes: opts.perIterationOutputCapBytes ?? 100_000,\n });\n }\n\n /**\n * Clear the interactive confirm awaiter so the executor returns\n * `ToolConfirmPendingResult` instead of blocking on stdin. Used by\n * the CLI to switch from inline prompts (REPL) to event-driven\n * confirmation (TUI) at runtime.\n */\n clearConfirmAwaiter(): void {\n this.opts.confirmAwaiter = undefined;\n }\n\n /**\n * Execute a batch of tool uses using the configured strategy.\n * Returns the execution results and the remaining output budget.\n */\n async executeBatch(\n toolUses: ToolUseBlock[],\n ctx: Context,\n strategy: ToolExecutorStrategy,\n ): Promise<ToolBatchResult> {\n let budget = this.opts.perIterationOutputCapBytes ?? 100_000;\n\n const runOne = async (use0: ToolUseBlock): Promise<ToolExecutionOutput> => {\n const start = Date.now();\n // `use` is rebindable because a PreToolUse hook may rewrite its input.\n let use = use0;\n const tool = this.registry.get(use.name);\n\n // Fast path: unknown tool\n if (!tool) {\n const result = this.unknownToolResult(use, () => this.registry.list().map((t) => t.name));\n budget = this.budgetForString(result.content, budget);\n return { result, tool, durationMs: Date.now() - start };\n }\n\n // Strong guarantee: Validate input against the tool's declared JSON Schema\n // *before* permission checks or execution. This is a hard gate — bad calls\n // are rejected early with actionable feedback so the model can self-correct.\n const validation = validateAgainstSchema(use.input, tool.inputSchema);\n if (!validation.ok) {\n const errorDetails = validation.errors\n .map((e) => ` - ${e.path || 'input'}: ${e.message}`)\n .join('\\n');\n\n const result = {\n type: 'tool_result' as const,\n tool_use_id: use.id,\n content:\n `Invalid arguments for tool \"${tool.name}\".\\n\\n` +\n `Validation errors:\\n${errorDetails}\\n\\n` +\n `Please call the tool again with arguments that match its inputSchema. ` +\n `You can use the \"tool-help\" tool with name=\"${tool.name}\" to see the exact expected schema.`,\n is_error: true,\n };\n budget = this.budgetForString(result.content, budget);\n return { result, tool, durationMs: Date.now() - start };\n }\n\n // Capability safety net at the executor level (defense in depth).\n // Tools declaring dangerous capabilities are subject to stricter\n // permission enforcement in the post-policy block below (line ~150+).\n // In non-YOLO contexts, an `auto` permission is elevated to `confirm`\n // for dangerous-capability tools, reducing prompt-injection blast radius.\n const toolDangerousCaps = getDangerousCapabilities(tool);\n\n // Provider boundary: the model's tool arguments arrive as a raw JSON\n // string accumulated over streamed deltas. When that string is not a\n // valid JSON object (truncated, scalar, or mangled by a proxy/local\n // model), the parsers wrap it under a sentinel key instead of silently\n // producing `{}`. Executing the tool with such input yields a cryptic\n // \"<field> is required\" error that the model can't act on. Detect the\n // sentinel here and feed back an actionable message so the model\n // resends well-formed arguments.\n if (hasMalformedArguments(use.input)) {\n const result = this.malformedInputResult(use, extractMalformedRaw(use.input));\n budget = this.budgetForString(result.content, budget);\n return { result, tool, durationMs: Date.now() - start };\n }\n\n // PreToolUse hooks: may block the call outright or rewrite its input.\n // Runs before the permission check so a hook can veto a tool that the\n // trust policy would otherwise auto-allow.\n if (this.opts.hookRunner?.has('PreToolUse')) {\n const pre = await this.opts.hookRunner.preToolUse(tool.name, use.input, ctx);\n if (pre.block) {\n const result = this.blockedByHookResult(use, pre.reason);\n budget = this.budgetForString(result.content, budget);\n return { result, tool, durationMs: Date.now() - start };\n }\n if (pre.input) {\n // A hook rewrote the arguments — re-validate before trusting them.\n const reval = validateAgainstSchema(pre.input, tool.inputSchema);\n if (!reval.ok) {\n const errorDetails = reval.errors\n .map((e) => ` - ${e.path || 'input'}: ${e.message}`)\n .join('\\n');\n const result = {\n type: 'tool_result' as const,\n tool_use_id: use.id,\n content:\n `A PreToolUse hook rewrote the arguments for \"${tool.name}\" into an invalid shape.\\n\\n` +\n `Validation errors:\\n${errorDetails}`,\n is_error: true,\n };\n budget = this.budgetForString(result.content, budget);\n return { result, tool, durationMs: Date.now() - start };\n }\n use = { ...use, input: pre.input };\n }\n }\n\n const decision = await this.opts.permissionPolicy.evaluate(tool, use.input, ctx);\n\n // Post-permission dangerous capability enforcement (B-side guarantee).\n // Even after the permission policy has spoken, we apply an extra conservative\n // rule for tools that declare high-risk capabilities (shell arbitrary, write outside\n // project, mcp proxy, etc.). This reduces the blast radius of prompt injection.\n let effectivePermission = decision.permission;\n\n // YOLO is the user's explicit fast-path for normal project work, so it\n // waives the post-policy dangerous-capability net only after the permission\n // policy has already returned `auto`. Destructive-gated calls still arrive\n // here as `confirm` unless the destructive YOLO override is active. Outside\n // YOLO, a trust-file auto-allow for a shell tool still gets a confirm, so a\n // single trusted pattern can't silently widen into arbitrary shell.\n // Detected via optional methods so policies without them (AutoApprove,\n // test mocks) keep the stricter default.\n const policy = this.opts.permissionPolicy;\n const yolo = policy.getYolo?.() === true || policy.getYoloDestructive?.() === true;\n\n // An `auto` decision sourced from `'yolo'` is authoritative: it comes\n // either from the leader's explicit YOLO mode or from a subagent's\n // `AutoApprovePermissionPolicy`, which already enforces a capability\n // allowlist (and now requires every dangerous capability to be granted\n // explicitly). In both cases the allowlist IS the blast-radius control,\n // so the conservative downgrade below would be redundant — and for a\n // non-interactive subagent (no confirmAwaiter) it would turn a granted\n // write into a `confirm` that can never be answered. Trust-file `auto`\n // (source 'trust') is NOT waived: a single trusted pattern must not\n // silently widen into arbitrary dangerous-capability execution.\n const authoritativeAuto = decision.source === 'yolo';\n\n if (\n toolDangerousCaps.length > 0 &&\n effectivePermission === 'auto' &&\n !yolo &&\n !authoritativeAuto\n ) {\n // Outside yolo we force at least 'confirm' for dangerous-capability tools.\n effectivePermission = 'confirm';\n }\n\n if (effectivePermission === 'deny') {\n const result = this.deniedResult(use, decision.reason);\n budget = this.budgetForString(result.content, budget);\n return { result, tool, durationMs: Date.now() - start };\n }\n\n if (effectivePermission === 'confirm') {\n if (this.opts.confirmAwaiter) {\n const choice = await this.opts.confirmAwaiter(tool, use.input, use.id, tool.name);\n if (choice !== 'yes' && choice !== 'always') {\n const result = {\n type: 'tool_result' as const,\n tool_use_id: use.id,\n content: `Tool \"${tool.name}\" denied by user.`,\n is_error: true,\n };\n budget = this.budgetForString(result.content, budget);\n return { result, tool, durationMs: Date.now() - start };\n }\n // fall through to execute\n } else {\n const suggestedPattern = subjectForToolInput(tool.name, use.input, tool.subjectKey) ?? tool.name;\n const pending: ToolConfirmPendingResult = {\n type: 'tool_confirm_pending',\n toolUseId: use.id,\n toolName: tool.name,\n input: use.input,\n suggestedPattern,\n };\n return { result: pending, tool, durationMs: Date.now() - start };\n }\n }\n\n // effectivePermission === 'auto' (after all safety layers)\n // Capability audit for observability.\n const toolCapsForAudit = hasDangerousCapabilityForSubagents(tool)\n ? (tool.capabilities ?? [])\n : [];\n\n // L1-C: trace each tool execution. Span is a no-op unless an OTel\n // adapter or other Tracer is bound — zero overhead by default.\n const span = this.opts.tracer?.startSpan(`tool.${tool.name}`, {\n 'tool.name': tool.name,\n 'tool.mutating': tool.mutating,\n 'tool.permission': tool.permission,\n 'tool.capabilities': JSON.stringify(tool.capabilities ?? []),\n 'tool.has_dangerous_capabilities': toolCapsForAudit.length > 0,\n });\n try {\n // H2: executeTool returns the rendered block plus the exact byte\n // count it spent against the iteration output cap. The cap was\n // enforced inside `enforceCap`, so the spend is known without\n // any second `Buffer.byteLength` walk.\n let { block: result, bytes } = await this.executeTool(tool, use, ctx, budget);\n budget -= bytes;\n // PostToolUse hooks: observe the result and optionally append\n // context (e.g. a linter note) that the model sees alongside the\n // tool output. Append the post-hook bytes to the budget spend\n // without re-walking the full result content.\n if (this.opts.hookRunner?.has('PostToolUse')) {\n const post = await this.opts.hookRunner.postToolUse(\n tool.name,\n use.input,\n { content: String(result.content), isError: !!result.is_error },\n ctx,\n );\n if (post.additionalContext) {\n const appended = `\\n\\n${post.additionalContext}`;\n result = { ...result, content: `${result.content}${appended}` };\n // Only the appended bytes are new — the pre-hook portion was\n // already counted by enforceCap. Walking just the appended\n // tail is `O(additionalContext.length)`, never `O(content)`.\n // Floor at 0 to match `decrementBudget`'s pre-fix clamp.\n budget = Math.max(0, budget - Buffer.byteLength(appended, 'utf8'));\n }\n }\n span?.setAttribute('tool.is_error', !!result.is_error);\n span?.setAttribute(\n 'tool.output_bytes',\n typeof result.content === 'string' ? result.content.length : 0,\n );\n return { result, tool, durationMs: Date.now() - start };\n } catch (err) {\n const msg = toErrorMessage(err);\n const scrubbed = this.opts.secretScrubber.scrub(msg);\n const { category, retryable, detail } = classifyToolError(err);\n this.opts.renderer?.writeToolResult(tool.name, scrubbed, true);\n const result = {\n type: 'tool_result' as const,\n tool_use_id: use.id,\n content: `Tool \"${tool.name}\" threw: ${scrubbed}`,\n is_error: true,\n };\n budget = this.budgetForString(result.content, budget);\n if (err instanceof Error) span?.recordError(err);\n span?.setAttribute('tool.is_error', true);\n span?.setAttribute('tool.error_category', category);\n span?.setAttribute('tool.error_retryable', retryable);\n if (detail) span?.setAttribute('tool.error_detail', detail);\n return { result, tool, durationMs: Date.now() - start };\n } finally {\n span?.end();\n }\n };\n\n // Run a single tool but never let an exception propagate to the\n // gather() below — `runOne` is already try/catch-wrapped for the\n // execution phase, but the *pre*-execution paths (permission policy,\n // confirmAwaiter) are unguarded and an unexpected throw there would\n // collapse Promise.all and lose every sibling's output. Wrap each\n // call so a per-tool failure becomes a per-tool error result.\n const safeRun = async (use: ToolUseBlock): Promise<ToolExecutionOutput> => {\n try {\n return await runOne(use);\n } catch (err) {\n const msg = toErrorMessage(err);\n const scrubbed = this.opts.secretScrubber.scrub(msg);\n const { category, retryable, detail } = classifyToolError(err);\n const tool = this.registry.get(use.name);\n this.opts.renderer?.writeToolResult(tool?.name ?? use.name, scrubbed, true);\n const result = {\n type: 'tool_result' as const,\n tool_use_id: use.id,\n content: `Tool \"${use.name}\" execution failed: ${scrubbed}`,\n is_error: true,\n };\n budget = this.budgetForString(result.content, budget);\n // Classification result is stored in the result for future retry logic;\n // span attributes are set in runOne's catch block (this err bubbles from there).\n void category;\n void retryable;\n void detail;\n return { result, tool, durationMs: 0 };\n }\n };\n\n if (strategy === 'sequential') {\n const outputs: ToolExecutionOutput[] = [];\n for (const use of toolUses) {\n if (use) outputs.push(await safeRun(use));\n }\n return { outputs, remainingBudget: budget };\n }\n\n if (strategy === 'parallel') {\n const outputs = await Promise.all(toolUses.map((use) => safeRun(use)));\n return { outputs, remainingBudget: budget };\n }\n\n // smart: non-mutating in parallel, then mutating sequentially\n const nonMutating: ToolUseBlock[] = [];\n const mutating: ToolUseBlock[] = [];\n for (const use of toolUses) {\n if (!use) continue;\n const tool = this.registry.get(use.name);\n if (tool?.mutating) mutating.push(use);\n else nonMutating.push(use);\n }\n const firstPass = await Promise.all(nonMutating.map((use) => safeRun(use)));\n const secondPass: ToolExecutionOutput[] = [];\n for (const use of mutating) {\n secondPass.push(await safeRun(use));\n }\n return {\n outputs: [...firstPass, ...secondPass],\n remainingBudget: budget,\n };\n }\n\n /**\n * Execute a single tool with timeout, permission check, and output capping.\n * Emits `tool.started` via the injected EventBus (if any) right before\n * invoking the tool — closes the observability gap between \"model decided\n * to call a tool\" and \"tool.executed\".\n */\n async executeTool(\n tool: Tool,\n use: ToolUseBlock,\n ctx: Context,\n budget: number,\n ): Promise<{ block: ToolResultBlock; bytes: number }> {\n this.opts.events?.emit('tool.started', {\n name: tool.name,\n id: use.id,\n input: use.input,\n });\n this.opts.renderer?.writeToolCall(tool.name, use.input);\n const output = await this.runWithTimeout(tool, use.input, ctx.signal, ctx, use.id);\n const text = this.serializer.serialize(output, { toolName: tool.name, input: use.input });\n const scrubbed = this.opts.secretScrubber.scrub(text);\n const withArtifact = await maybePersistLargeToolOutput(tool.name, scrubbed, budget);\n // enforceCap already walks the text to compute bytes for the budget\n // cap. Carry the residual budget back as `bytes` so the caller can\n // deduct the spend without a second `Buffer.byteLength` walk — and\n // never falls back to `JSON.stringify` on a structured value.\n const { text: capped, newBudget } = this.serializer.enforceCap(withArtifact, budget);\n this.opts.renderer?.writeToolResult(tool.name, capped, false);\n return {\n block: {\n type: 'tool_result',\n tool_use_id: use.id,\n name: tool.name,\n content: capped,\n is_error: false,\n },\n // `budget - newBudget` is the exact byte count enforceCap spent\n // (capped at `budget` so a truncated output shows as `budget`\n // consumed, matching the pre-fix `decrementBudget` semantics).\n bytes: budget - newBudget,\n };\n }\n\n private async runWithTimeout(\n tool: Tool,\n input: unknown,\n parentSignal: AbortSignal,\n ctx: Context,\n toolUseId?: string | undefined,\n ): Promise<unknown> {\n if (parentSignal.aborted) {\n // Re-throw the original abort reason, whether it's an Error, string, or undefined.\n if (parentSignal.reason instanceof Error) throw parentSignal.reason;\n throw new Error(typeof parentSignal.reason === 'string' ? parentSignal.reason : 'aborted');\n }\n const timeoutMs = clampTimeoutMs(\n tool.timeoutMs ?? this.iterationTimeoutMs,\n this.maxToolTimeoutMs,\n );\n const timeoutSignal = AbortSignal.timeout(timeoutMs);\n const combined = AbortSignal.any([parentSignal, timeoutSignal]);\n\n let output: unknown;\n try {\n // Streaming variant takes precedence — yields progress events, then\n // a final 'final' event with the typed output. Tools that don't\n // implement executeStream fall through to the standard execute path.\n output =\n typeof tool.executeStream === 'function'\n ? await this.runStreamedTool(tool, input, ctx, combined, toolUseId)\n : await tool.execute(input, ctx, { signal: combined });\n } catch (err) {\n // If aborted, run cleanup before re-throwing so the tool can release\n // resources (child processes, file handles, network connections).\n if (combined.aborted) await this.runToolCleanup(tool, input, ctx);\n throw err;\n }\n // The tool returned without throwing, but the signal may have aborted (e.g.\n // a timeout fired) while a tool that ignores the abort signal kept running.\n // Treat that as an abort: clean up and surface the abort to the caller so a\n // late, stale result is never returned as success.\n if (combined.aborted) {\n await this.runToolCleanup(tool, input, ctx);\n throw combined.reason instanceof Error\n ? combined.reason\n : new Error(typeof combined.reason === 'string' ? combined.reason : 'tool timeout');\n }\n return output;\n }\n\n /** Best-effort tool cleanup; never let it mask the original error. */\n private async runToolCleanup(tool: Tool, input: unknown, ctx: Context): Promise<void> {\n if (typeof tool.cleanup !== 'function') return;\n try {\n await tool.cleanup(input, ctx);\n } catch {\n /* swallow — never let cleanup mask the original error */\n }\n }\n\n private async runStreamedTool(\n tool: Tool,\n input: unknown,\n ctx: Context,\n signal: AbortSignal,\n toolUseId: string | undefined,\n ): Promise<unknown> {\n let finalOutput: unknown;\n let sawFinal = false;\n if (!tool.executeStream) {\n throw new Error(`Tool \"${tool.name}\" does not support streaming execution`);\n }\n const stream = tool.executeStream(input, ctx, { signal });\n // Manual iteration so we can explicitly close the async iterator after\n // receiving the final event, ensuring any cleanup in the tool's generator\n // finally block runs regardless of whether the engine calls return() on\n // break of a for-await-of loop.\n const iter = stream[Symbol.asyncIterator]();\n // Coalesce `partial_output` progress into at most one EventBus emit per\n // PROGRESS_EMIT_INTERVAL_MS, carrying only the most recent\n // PROGRESS_TAIL_CHARS of accumulated text. A chatty child process (a test\n // suite or build spewing ANSI progress) can stream hundreds of MB per\n // minute through executeStream; emitting every flush as its own event\n // floods every bus subscriber (TUI render per dispatch, session bridge,\n // WebUI broadcast) and has OOM'd the host. The live tail only ever shows\n // the last few KB, so coalescing loses nothing the UI can display —\n // the tool's own capped `final` output is unaffected.\n let progressTail = '';\n let lastProgressEmitAt = 0;\n const emitProgress = (ev: ToolProgressEvent) => {\n this.opts.events?.emit('tool.progress', {\n name: tool.name,\n id: toolUseId ?? '<unknown>',\n event: ev,\n });\n };\n const flushProgressTail = (force: boolean) => {\n if (progressTail.length === 0) return;\n const now = Date.now();\n if (!force && now - lastProgressEmitAt < ToolExecutor.PROGRESS_EMIT_INTERVAL_MS) return;\n const text = progressTail;\n progressTail = '';\n lastProgressEmitAt = now;\n emitProgress({ type: 'partial_output', text });\n };\n try {\n while (true) {\n const { done, value: ev } = await iter.next();\n if (done) break;\n if (ev.type === 'final') {\n finalOutput = ev.output;\n sawFinal = true;\n // Result is locked — stop consuming further events.\n break;\n }\n if (ev.type === 'partial_output' && typeof ev.text === 'string') {\n progressTail += ev.text;\n if (progressTail.length > ToolExecutor.PROGRESS_TAIL_CHARS) {\n progressTail = progressTail.slice(-ToolExecutor.PROGRESS_TAIL_CHARS);\n }\n flushProgressTail(false);\n continue;\n }\n // Non-partial events (log/warning/metric/file_changed) are low-volume;\n // flush buffered text first so subscribers see events in stream order.\n flushProgressTail(true);\n emitProgress(ev);\n }\n flushProgressTail(true);\n } finally {\n // Always close the iterator so the tool's generator finally block\n // runs even if we broke early on a final event or errored.\n await iter.return?.(undefined);\n }\n if (!sawFinal) {\n throw new Error(`tool \"${tool.name}\" executeStream completed without a 'final' event`);\n }\n return finalOutput;\n }\n\n private unknownToolResult(use: ToolUseBlock, listFns: () => string[]): ToolResultBlock {\n return {\n type: 'tool_result',\n tool_use_id: use.id,\n content: `Tool \"${use.name}\" is not registered. Available tools: ${listFns().join(', ')}`,\n is_error: true,\n };\n }\n\n private malformedInputResult(use: ToolUseBlock, raw?: string): ToolResultBlock {\n let content =\n `Tool \"${use.name}\" received arguments that were not a valid JSON object, so they ` +\n `could not be parsed. Re-issue the call with the arguments encoded as a single ` +\n `well-formed JSON object matching the tool's input schema.`;\n // Echo the raw payload back so the model can see *what* it produced and\n // self-correct. Without this the model is blind to its own mistake and\n // tends to resend the identical malformed call in a loop. Common causes:\n // unescaped newlines/quotes/backslashes inside a string field, or the\n // arguments being truncated mid-stream.\n if (raw) {\n const max = 800;\n const excerpt =\n raw.length > max ? `${raw.slice(0, max)}… (truncated, ${raw.length} chars total)` : raw;\n content +=\n ` Common cause: a string field (e.g. code in old_string/new_string) ` +\n `contains literal newlines, quotes, or backslashes that must be JSON-escaped, ` +\n `or the payload was cut off mid-stream. The raw arguments received were:\\n${excerpt}`;\n }\n return {\n type: 'tool_result',\n tool_use_id: use.id,\n content,\n is_error: true,\n };\n }\n\n private deniedResult(use: ToolUseBlock, reason?: string): ToolResultBlock {\n return {\n type: 'tool_result',\n tool_use_id: use.id,\n content: `Tool \"${use.name}\" denied: ${reason ?? 'policy'}`,\n is_error: true,\n };\n }\n\n private blockedByHookResult(use: ToolUseBlock, reason?: string): ToolResultBlock {\n return {\n type: 'tool_result',\n tool_use_id: use.id,\n content: `Tool \"${use.name}\" was blocked by a PreToolUse hook: ${reason ?? 'no reason given'}`,\n is_error: true,\n };\n }\n\n /**\n * Subtract a string-content result's UTF-8 byte length from the\n * iteration output budget. Used for synthesized results (unknown tool,\n * validation error, blocked, threw) where the content is a small\n * string built in the executor. The success path no longer goes\n * through here — `executeTool` carries the exact byte count it spent\n * in its return value, derived from `enforceCap`'s `newBudget`.\n *\n * Floors the result at 0 to match the pre-fix `decrementBudget`\n * semantics (over-budget spends don't underflow the running total).\n */\n private budgetForString(content: string, budget: number): number {\n return Math.max(0, budget - Buffer.byteLength(content, 'utf8'));\n }\n\n}\n\nfunction clampTimeoutMs(timeoutMs: number, maxTimeoutMs: number): number {\n const fallback = 300_000;\n const finiteTimeout = Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : fallback;\n const finiteMax = Number.isFinite(maxTimeoutMs) && maxTimeoutMs > 0 ? maxTimeoutMs : fallback;\n return Math.max(1, Math.min(finiteTimeout, finiteMax));\n}\n\n/**\n * Sentinel keys the provider adapters use to wrap tool arguments that could\n * not be parsed into a proper JSON object. `parseToolInput` (Anthropic /\n * shared) uses `__raw`, `contentFromOpenAI` uses `__raw_arguments`, and the\n * streaming response builder's `safeJsonOrRaw` uses `_raw`. Keep this list in\n * sync if a new adapter introduces another marker.\n *\n * NOTE: `parseToolInput` and `safeJsonOrRaw` now attempt JSON repair\n * (auto-closing braces and strings) before wrapping — so a truncated blob\n * like `{\"old_string\": \"line1\\nline2` gets repaired first. The sentinel is\n * only used when repair also fails.\n */\nconst MALFORMED_ARG_MARKERS = ['__raw', '__raw_arguments', '_raw'] as const;\n\nfunction hasMalformedArguments(input: unknown): boolean {\n if (!input || typeof input !== 'object' || Array.isArray(input)) return false;\n const obj = input as Record<string, unknown>;\n // The sentinel is the *only* key when wrapping occurred — a real tool call\n // that legitimately uses a key named e.g. `_raw` will carry other keys too.\n const keys = Object.keys(obj);\n return keys.length === 1 && MALFORMED_ARG_MARKERS.includes(keys[0] as never);\n}\n\n/**\n * Pull the original (unparseable) payload back out of a sentinel-wrapped input\n * so the executor can echo it to the model. The wrapped value is usually the\n * raw argument string, but a scalar/array that parsed cleanly is wrapped too —\n * stringify those. Returns undefined if nothing usable is present.\n */\nfunction extractMalformedRaw(input: unknown): string | undefined {\n if (!hasMalformedArguments(input)) return undefined;\n const obj = input as Record<string, unknown>;\n const value = obj[expectDefined(Object.keys(obj)[0])];\n if (value === undefined || value === null) return undefined;\n if (typeof value === 'string') return value;\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nconst TOOL_OUTPUT_ARTIFACT_THRESHOLD_BYTES = 64 * 1024;\n\n/**\n * Classify a tool execution error into a structured ToolErrorCategory.\n * Used for observability (span attributes) and retry strategy decisions.\n */\nfunction classifyToolError(err: unknown): { category: ToolErrorCategory; retryable: boolean; detail?: string } {\n // AbortError — user cancellation, never retry\n if (err instanceof Error && err.name === 'AbortError') {\n return { category: ToolErrorCategoryEnum.FATAL, retryable: false, detail: 'aborted' };\n }\n\n // Node.js ErrnoException with system error codes\n if (err instanceof Error && 'code' in err) {\n const code = (err as NodeJS.ErrnoException).code;\n switch (code) {\n case 'ETIMEDOUT':\n case 'ECONNRESET':\n case 'ECONNREFUSED':\n case 'ENETUNREACH':\n case 'EHOSTUNREACH':\n return { category: ToolErrorCategoryEnum.TRANSIENT, retryable: true, detail: code };\n case 'ENOENT':\n case 'ENOTDIR':\n return { category: ToolErrorCategoryEnum.NOT_FOUND, retryable: false, detail: code };\n case 'EACCES':\n case 'EPERM':\n return { category: ToolErrorCategoryEnum.PERMISSION, retryable: false, detail: code };\n case 'EBUSY':\n case 'EMFILE':\n case 'ENFILE':\n return { category: ToolErrorCategoryEnum.TRANSIENT, retryable: true, detail: code };\n }\n }\n\n // HTTP response errors (fetch failed with non-OK status)\n if (err instanceof Error && 'response' in err) {\n const response = (err as { response: { status?: number } }).response;\n const status = response?.status;\n if (status !== undefined) {\n if (status === 429 || status === 503 || status === 502 || status === 504) {\n return { category: ToolErrorCategoryEnum.TRANSIENT, retryable: true, detail: `HTTP ${status}` };\n }\n if (status === 404 || status === 410) {\n return { category: ToolErrorCategoryEnum.NOT_FOUND, retryable: false, detail: `HTTP ${status}` };\n }\n if (status === 401 || status === 403) {\n return { category: ToolErrorCategoryEnum.PERMISSION, retryable: false, detail: `HTTP ${status}` };\n }\n if (status === 400) {\n return { category: ToolErrorCategoryEnum.VALIDATION, retryable: false, detail: `HTTP ${status}` };\n }\n }\n }\n\n // Validation errors from schema validation\n if (err instanceof Error && err.message.includes('validation')) {\n return { category: ToolErrorCategoryEnum.VALIDATION, retryable: false, detail: 'validation' };\n }\n\n // Default: fatal/unclassified\n return {\n category: ToolErrorCategoryEnum.FATAL,\n retryable: false,\n detail: err instanceof Error ? err.message.slice(0, 100) : String(err).slice(0, 100),\n };\n}\n\nasync function maybePersistLargeToolOutput(\n toolName: string,\n content: string,\n budget: number,\n): Promise<string> {\n const bytes = Buffer.byteLength(content, 'utf8');\n if (bytes <= Math.min(TOOL_OUTPUT_ARTIFACT_THRESHOLD_BYTES, Math.max(0, budget))) {\n return content;\n }\n\n try {\n const dir = path.join(wstackGlobalRoot(), 'tool-output');\n await fs.mkdir(dir, { recursive: true });\n const safeTool = toolName.replace(/[^a-zA-Z0-9._-]+/g, '_').slice(0, 40) || 'tool';\n const stamp = new Date().toISOString().replace(/[:.]/g, '-');\n const filePath = path.join(dir, `${stamp}-${safeTool}-${randomUUID()}.log`);\n await fs.writeFile(filePath, content, 'utf8');\n return (\n content +\n `\\n[full tool output: ${bytes} bytes at ${filePath}; read/grep that file selectively instead of re-running or requesting more output]`\n );\n } catch {\n return content;\n }\n}\n","import type { Agent, RunResult } from '../core/agent.js';\r\nimport type { Context } from '../core/context.js';\r\nimport { toWrongStackError } from '../types/errors.js';\r\nimport type { DoneCondition } from '../types/multi-agent.js';\r\nimport { assertNever } from '../utils/assert-never.js';\r\nimport { compileUserRegex } from '../utils/regex-guard.js';\r\n\r\ntype AutonomousResult = RunResult & { toolCalls: number; reason?: string | undefined };\r\n\r\nexport interface DoneCheckResult {\r\n done: boolean;\r\n reason?: string | undefined;\r\n iterations: number;\r\n toolCalls: number;\r\n}\r\n\r\nexport class DoneConditionChecker {\r\n private readonly compiledRegex: RegExp | null;\r\n\r\n constructor(private readonly condition: DoneCondition) {\r\n if (condition.type === 'output_match' && condition.pattern) {\r\n const result = compileUserRegex(condition.pattern, '');\r\n this.compiledRegex = result.ok ? result.regex : null;\r\n if (!result.ok) {\r\n // Log warning but don't throw — the done condition simply won't match\r\n console.warn(JSON.stringify({\r\n level: 'warn',\r\n event: 'autonomous.done_condition_invalid_regex',\r\n pattern: condition.pattern,\r\n reason: result.reason,\r\n timestamp: new Date().toISOString(),\r\n }));\r\n }\r\n } else {\r\n this.compiledRegex = null;\r\n }\r\n }\r\n\r\n check(state: { iterations: number; toolCalls: number; lastOutput?: string | undefined }): DoneCheckResult {\r\n switch (this.condition.type) {\r\n case 'iterations':\r\n if (this.condition.maxIterations && state.iterations >= this.condition.maxIterations) {\r\n return {\r\n done: true,\r\n reason: `max iterations (${this.condition.maxIterations}) reached`,\r\n ...state,\r\n };\r\n }\r\n break;\r\n\r\n case 'tool_calls':\r\n if (this.condition.maxToolCalls && state.toolCalls >= this.condition.maxToolCalls) {\r\n return {\r\n done: true,\r\n reason: `max tool calls (${this.condition.maxToolCalls}) reached`,\r\n ...state,\r\n };\r\n }\r\n break;\r\n\r\n case 'output_match':\r\n if (this.compiledRegex && state.lastOutput && this.compiledRegex.test(state.lastOutput)) {\r\n return {\r\n done: true,\r\n reason: `output matched pattern \"${this.condition.pattern}\"`,\r\n ...state,\r\n };\r\n }\r\n break;\r\n\r\n case 'directive':\r\n // Model-driven: the agent manages its own continuation via [continue]/[done].\r\n // The done condition is never satisfied by the checker — the agent returns\r\n // `status: 'done'` when the model emits [done] or naturally finishes.\r\n // The runner's outer loop uses maxIterations/maxToolCalls as hard caps.\r\n if (this.condition.maxIterations && state.iterations >= this.condition.maxIterations) {\r\n return { done: true, reason: `max iterations (${this.condition.maxIterations}) reached`, ...state };\r\n }\r\n if (this.condition.maxToolCalls && state.toolCalls >= this.condition.maxToolCalls) {\r\n return { done: true, reason: `max tool calls (${this.condition.maxToolCalls}) reached`, ...state };\r\n }\r\n break;\r\n\r\n case 'all_tasks_done':\r\n // Coordinator-managed: completion is decided by the multi-agent\r\n // coordinator's pending-task queue, not by per-iteration state here.\r\n break;\r\n\r\n case 'custom':\r\n // Reserved for future extension\r\n break;\r\n default:\r\n return assertNever(this.condition.type);\r\n }\r\n\r\n return { done: false, iterations: state.iterations, toolCalls: state.toolCalls };\r\n }\r\n}\r\n\r\nexport interface AutonomousRunnerOptions {\r\n agent: Agent;\r\n context: Context;\r\n doneCondition: DoneCondition;\r\n iterationTimeoutMs?: number | undefined;\r\n onIteration?: (state: { iteration: number | undefined; toolCalls: number }) => void;\r\n onDone?: (((result: AutonomousResult) => void)) | undefined;\r\n /**\r\n * When true and `doneCondition.type === 'directive'`, the runner\r\n * runs the agent with `autonomousContinue: true` so the agent loop\r\n * handles its own [continue]/[done] markers internally (no outer\r\n * re-invocation needed). The runner still provides iteration/timeouts.\r\n */\r\n enableAutonomousContinue?: boolean | undefined;\r\n}\r\n\r\nexport class AutonomousRunner {\r\n private iterations = 0;\r\n private toolCalls = 0;\r\n private lastOutput?: string | undefined;\r\n private stopped = false;\r\n private readonly doneChecker: DoneConditionChecker;\r\n\r\n constructor(private readonly opts: AutonomousRunnerOptions) {\r\n this.doneChecker = new DoneConditionChecker(opts.doneCondition);\r\n }\r\n\r\n async run(): Promise<AutonomousResult> {\r\n // Subscribe to `tool.executed` so the per-tool budget (`tool_calls`\r\n // done-condition) actually counts each tool invocation rather than\r\n // each `agent.run()` call. Without this, a single iteration that\r\n // fires 5 tools only bumps the counter once, and a `maxToolCalls: 3`\r\n // budget would fire after 3 iterations (typically 3×N tools) instead\r\n // of after 3 tools. Unsubscribed in the `finally` so the listener\r\n // doesn't outlive this run instance. Mock agents in tests may pass\r\n // null/undefined for `events`; gracefully skip when missing — those\r\n // tests don't exercise the tool-count budget path.\r\n const offToolExecuted = this.opts.agent.events?.on?.('tool.executed', () => {\r\n this.toolCalls++;\r\n });\r\n // When autonomous continue is enabled, also count internal agent-loop\r\n // iterations. Each iteration.started within a single agent.run() call\r\n // counts toward the runner's maxIterations cap. We listen to the event\r\n // through the agent's EventBus.\r\n const offIterationCompleted = this.opts.agent.events?.on?.('iteration.completed', () => {\r\n // Only count if we're in autonomous continue mode (agent loop\r\n // handles multiple iterations internally before returning).\r\n if (this.opts.enableAutonomousContinue && this.opts.doneCondition.type === 'directive') {\r\n // Each internal iteration completed — bump the outer iteration counter.\r\n // This ensures maxIterations on the runner actually limits total work.\r\n this.iterations++;\r\n }\r\n });\r\n try {\r\n return await this.runLoop();\r\n } finally {\r\n offToolExecuted?.();\r\n offIterationCompleted?.();\r\n }\r\n }\r\n\r\n private async runLoop(): Promise<AutonomousResult> {\r\n while (!this.stopped) {\r\n const check = this.doneChecker.check({\r\n iterations: this.iterations,\r\n toolCalls: this.toolCalls,\r\n lastOutput: this.lastOutput,\r\n });\r\n\r\n if (check.done) {\r\n const result: AutonomousResult = {\r\n status: 'done',\r\n iterations: this.iterations,\r\n toolCalls: this.toolCalls,\r\n reason: check.reason,\r\n };\r\n this.opts.onDone?.(result);\r\n return result;\r\n }\r\n\r\n this.opts.onIteration?.({ iteration: this.iterations, toolCalls: this.toolCalls });\r\n\r\n const ctrl = new AbortController();\r\n const timeout = setTimeout(() => ctrl.abort(), this.opts.iterationTimeoutMs ?? 30_000);\r\n\r\n try {\r\n // In directive mode with autonomous continue, pass it through so the\r\n // agent loop handles its own [continue]/[done] markers internally.\r\n // The runner provides iteration caps and timeouts; the agent handles\r\n // the continuation decision within each agent.run() call.\r\n const isDirectiveMode =\r\n this.opts.doneCondition.type === 'directive' &&\r\n this.opts.enableAutonomousContinue;\r\n\r\n const result = await this.opts.agent.run('', {\r\n signal: ctrl.signal,\r\n maxIterations: isDirectiveMode ? (this.opts.doneCondition.maxIterations ?? 100) : 1,\r\n executionStrategy: 'sequential',\r\n autonomousContinue: isDirectiveMode ? true : undefined,\r\n });\r\n\r\n // Only increment iterations if we're NOT counting via iteration.completed\r\n // (i.e., not in autonomous continue directive mode). In that mode,\r\n // the offIterationCompleted listener in run() bumps this counter\r\n // per internal iteration so the runner's maxIterations cap is respected.\r\n if (!isDirectiveMode) this.iterations++;\r\n // Only access finalText when the run actually succeeded. Failed/aborted\r\n // runs may have undefined finalText — accessing it unconditionally would\r\n // produce garbage output for the done-condition matchers.\r\n if (result.status === 'done') {\r\n this.lastOutput = result.finalText;\r\n }\r\n // `toolCalls` is bumped by the `tool.executed` listener installed\r\n // in run() — no manual increment here.\r\n\r\n if (result.status === 'failed' || result.status === 'aborted') {\r\n const failedResult: AutonomousResult = {\r\n status: result.status,\r\n error: result.error,\r\n iterations: this.iterations,\r\n toolCalls: this.toolCalls,\r\n };\r\n this.opts.onDone?.(failedResult);\r\n return failedResult;\r\n }\r\n } catch (e) {\r\n // Be precise about what constitutes a timeout error — matching on\r\n // 'timeout' substring is too loose (an error message containing\r\n // \"timeout exceeded\" from the LLM is not the same as an abort).\r\n const isAbort =\r\n (e instanceof DOMException && e.name === 'AbortError') ||\r\n (e instanceof Error && e.name === 'AbortError') ||\r\n (e instanceof Error && e.message.includes('iteration timeout'));\r\n if (isAbort) {\r\n const timeoutResult: AutonomousResult = {\r\n status: 'failed',\r\n error: toWrongStackError(e),\r\n iterations: this.iterations,\r\n toolCalls: this.toolCalls,\r\n reason: 'iteration timeout',\r\n };\r\n this.opts.onDone?.(timeoutResult);\r\n return timeoutResult;\r\n }\r\n // Any other throw (TypeError, tool crash propagation, etc.) must\r\n // stop the loop — silently continuing would spin forever on the\r\n // same error and burn provider tokens with no progress.\r\n this.stopped = true;\r\n const failedResult: AutonomousResult = {\r\n status: 'failed',\r\n error: toWrongStackError(e),\r\n iterations: this.iterations,\r\n toolCalls: this.toolCalls,\r\n reason: e instanceof Error ? e.message : String(e),\r\n };\r\n this.opts.onDone?.(failedResult);\r\n return failedResult;\r\n } finally {\r\n clearTimeout(timeout);\r\n }\r\n }\r\n\r\n return {\r\n status: 'aborted',\r\n iterations: this.iterations,\r\n toolCalls: this.toolCalls,\r\n reason: 'stopped externally',\r\n };\r\n }\r\n\r\n stop(): void {\r\n this.stopped = true;\r\n }\r\n}\r\n","import * as fsp from 'node:fs/promises';\nimport type { EventBus } from '../kernel/events.js';\nimport { atomicWrite, withFileLock } from '../utils/atomic-write.js';\nimport { toErrorMessage } from '../utils/error.js';\nimport { color } from '../utils/color.js';\nimport { resolveWstackPaths } from '../utils/wstack-paths.js';\nimport { FsError, ERROR_CODES } from '../types/errors.js';\n\n/**\n * Long-running autonomous mission. A goal survives across sessions and\n * drives the EternalAutonomyEngine — every iteration of the engine\n * consults the goal to choose what to do next.\n *\n * Storage: `~/.wrongstack/projects/<hash>/goal.json`. Persistent and\n * project-scoped on purpose: the goal belongs to the codebase, not the\n * REPL session.\n */\n\nexport interface JournalEntry {\n /** ISO timestamp of the iteration. */\n at: string;\n /** Sequential iteration counter (1-based, monotonically increasing). */\n iteration: number;\n /** Source that produced the action ('todo' | 'git' | 'brainstorm' | 'resume' | 'manual' | 'parallel'). */\n source: 'todo' | 'git' | 'brainstorm' | 'resume' | 'manual' | 'parallel';\n /** Short one-line description of what the iteration set out to do. */\n task: string;\n /** Outcome status. */\n status: 'success' | 'failure' | 'aborted' | 'skipped';\n /** Optional free-form note (error message, summary, etc.). */\n note?: string | undefined;\n /** Optional token usage delta for this iteration. */\n tokens?: { input: number; output: number } | undefined;\n /** Optional USD cost delta for this iteration (provider-estimated). */\n costUsd?: number | undefined;\n}\n\nexport interface GoalFile {\n version: 1;\n /** The raw mission statement as entered by the user. */\n goal: string;\n /**\n * LLM-refined version of the goal — unambiguous, with concrete\n * deliverables and acceptance criteria.\n */\n refinedGoal?: string | undefined;\n /**\n * Concrete, verifiable deliverables extracted from the refined goal.\n */\n deliverables?: string[] | undefined;\n /**\n * Estimated completion 0-100. Updated by the engine after each\n * iteration. Null means \"not yet assessed\".\n */\n progress?: number | undefined;\n /** Human-readable note explaining the current progress estimate. */\n progressNote?: string | undefined;\n /**\n * Time-series of progress measurements for trend analysis.\n * Last 200 entries retained. Use `recordProgress()` to append.\n */\n progressHistory?: ProgressSnapshot[] | undefined;\n /**\n * Computed trend from recent progress measurements.\n * 'accelerating' | 'steady' | 'stalling' | undefined.\n */\n progressTrend?: 'accelerating' | 'steady' | 'stalling' | undefined;\n /** When the goal was first set or last replaced. */\n setAt: string;\n /** Updated on every iteration completion. */\n lastActivityAt: string;\n /** Total iterations the engine has run against this goal (cumulative). */\n iterations: number;\n /** Engine lifecycle state — 'running' means another process owns this goal. */\n engineState: 'idle' | 'running' | 'stopped';\n /**\n * Mission-level lifecycle.\n */\n goalState?: 'active' | 'paused' | 'completed' | 'abandoned' | undefined;\n /**\n * Per-todo attempt counter.\n */\n todoAttempts?: Record<string, number>;\n /** Bounded ring buffer of recent iterations (newest last). */\n journal: JournalEntry[];\n}\n\n/** Cap on persisted journal entries — older entries are evicted FIFO. */\nexport const MAX_JOURNAL_ENTRIES = 500;\n\n/**\n * Resolve the goal file path for a given project root.\n *\n * SINGLE canonical location: the per-project directory that\n * `resolveWstackPaths()` uses for everything else (sessions, memory, specs) —\n * `~/.wrongstack/projects/<slug>/goal.json`. This is the same path the `/goal`\n * slash command writes via `opts.paths.projectGoal`, so every reader/writer\n * (the eternal/parallel autonomy engines, the CLI autonomy commands, the TUI\n * F9 panel, and `/goal` itself) now agree on one file.\n *\n * Previously this returned a SEPARATE hash-based dir (`projects/<hash>/`), which\n * disagreed with `/goal` and littered the home dir with thousands of stray\n * `<hash>/goal.json` directories that held nothing else.\n */\nexport function goalFilePath(projectRoot: string): string {\n return resolveWstackPaths({ projectRoot }).projectGoal;\n}\n\nexport async function loadGoal(filePath: string, events?: EventBus): Promise<GoalFile | null> {\n const t0 = Date.now();\n let raw: string;\n try {\n raw = await fsp.readFile(filePath, 'utf8');\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') {\n events?.emit('storage.read', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'load',\n outcome: 'success',\n durationMs: Date.now() - t0,\n });\n return null; // file doesn't exist — not an error\n }\n events?.emit('storage.error', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'load',\n error: toErrorMessage(err),\n recoverable: false,\n });\n throw err; // permission errors etc. should surface\n }\n try {\n const parsed = JSON.parse(raw) as GoalFile;\n if (parsed?.version !== 1 || typeof parsed.goal !== 'string' || !Array.isArray(parsed.journal)) {\n console.warn(JSON.stringify({\n level: 'warn',\n event: 'goal_store.invalid_schema',\n path: filePath,\n message: 'invalid schema — consider deleting and re-creating',\n timestamp: new Date().toISOString(),\n }));\n events?.emit('storage.read', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'load',\n outcome: 'failure',\n durationMs: Date.now() - t0,\n error: 'invalid_schema',\n });\n return null;\n }\n events?.emit('storage.read', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'load',\n outcome: 'success',\n durationMs: Date.now() - t0,\n });\n return parsed;\n } catch {\n console.warn(JSON.stringify({\n level: 'warn',\n event: 'goal_store.parse_failed',\n path: filePath,\n message: 'JSON parse failed — consider deleting and re-creating',\n timestamp: new Date().toISOString(),\n }));\n events?.emit('storage.read', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'load',\n outcome: 'failure',\n durationMs: Date.now() - t0,\n error: 'parse_failed',\n });\n return null;\n }\n}\n\nexport async function saveGoal(filePath: string, goal: GoalFile, events?: EventBus): Promise<void> {\n const t0 = Date.now();\n try {\n await atomicWrite(filePath, JSON.stringify(goal, null, 2), { mode: 0o600 });\n events?.emit('storage.write', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'save',\n outcome: 'success',\n durationMs: Date.now() - t0,\n });\n } catch (err) {\n events?.emit('storage.error', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'save',\n error: toErrorMessage(err),\n recoverable: false,\n });\n throw new FsError({\n message: toErrorMessage(err),\n code: ERROR_CODES.FS_ATOMIC_WRITE_FAILED,\n path: filePath,\n cause: err,\n });\n }\n}\n\n/**\n * Atomically load, modify, and save a goal file under a file lock.\n * Prevents lost-update races when the autonomy engine and CLI /goal commands\n * write concurrently (both eternal and parallel engines may run simultaneously).\n *\n * `fn` receives the current GoalFile (or `null` if no goal exists yet)\n * and must return the updated GoalFile (or `null` to delete).\n */\nexport async function updateGoal(\n filePath: string,\n fn: (current: GoalFile | null) => GoalFile | null,\n events?: EventBus,\n): Promise<void> {\n const t0 = Date.now();\n await withFileLock(filePath, async () => {\n const current = await loadGoal(filePath, events);\n const next = fn(current);\n if (next) {\n await saveGoal(filePath, next, events);\n } else {\n try {\n await fsp.unlink(filePath);\n events?.emit('storage.write', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'delete',\n outcome: 'success',\n durationMs: Date.now() - t0,\n });\n } catch (err) {\n events?.emit('storage.error', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'delete',\n error: toErrorMessage(err),\n recoverable: true,\n });\n // best-effort — file may not exist\n }\n }\n events?.emit('storage.write', {\n sessionId: '~boot~',\n store: 'goal',\n filePath,\n operation: 'update',\n outcome: 'success',\n durationMs: Date.now() - t0,\n });\n });\n}\n\nexport function emptyGoal(goal: string): GoalFile {\n const now = new Date().toISOString();\n return {\n version: 1,\n goal,\n setAt: now,\n lastActivityAt: now,\n iterations: 0,\n engineState: 'idle',\n goalState: 'active',\n todoAttempts: {},\n journal: [],\n };\n}\n\n/**\n * Set progress estimate on a goal. Returns a new GoalFile.\n * Clamps progress to 0-100.\n */\nexport function setProgress(\n goal: GoalFile,\n progress: number,\n note?: string,\n): GoalFile {\n const clamped = Math.min(100, Math.max(0, progress));\n return {\n ...goal,\n progress: clamped,\n progressNote: note ?? clamped + '% complete',\n };\n}\n\n/**\n * Append a journal entry, bumping iteration counters and trimming the\n * ring buffer. Returns a new GoalFile — does not mutate the argument.\n */\nexport function appendJournal(goal: GoalFile, entry: Omit<JournalEntry, 'iteration' | 'at'>): GoalFile {\n const iteration = goal.iterations + 1;\n const at = new Date().toISOString();\n const full: JournalEntry = { ...entry, iteration, at };\n const journal = [...goal.journal, full];\n const trimmed = journal.length > MAX_JOURNAL_ENTRIES\n ? journal.slice(journal.length - MAX_JOURNAL_ENTRIES)\n : journal;\n return {\n ...goal,\n iterations: iteration,\n lastActivityAt: at,\n journal: trimmed,\n };\n}\n\n/**\n * Aggregate cumulative cost + tokens across all journal entries.\n */\nexport function summarizeUsage(goal: GoalFile): {\n totalCostUsd: number;\n totalInputTokens: number;\n totalOutputTokens: number;\n iterationsWithUsage: number;\n} {\n let totalCostUsd = 0;\n let totalInputTokens = 0;\n let totalOutputTokens = 0;\n let iterationsWithUsage = 0;\n for (const e of goal.journal) {\n if (typeof e.costUsd === 'number') totalCostUsd += e.costUsd;\n if (e.tokens) {\n totalInputTokens += e.tokens.input;\n totalOutputTokens += e.tokens.output;\n }\n if (typeof e.costUsd === 'number' || e.tokens) iterationsWithUsage++;\n }\n return { totalCostUsd, totalInputTokens, totalOutputTokens, iterationsWithUsage };\n}\n\nconst DOLLAR = '\\u0024';\n\n/** Format the goal + recent journal as a human-readable status block. */\nexport function formatGoal(goal: GoalFile, journalLimit = 10): string {\n const lines: string[] = [];\n\n // Header — show refined goal, with original as annotation if different\n const displayGoal = goal.refinedGoal || goal.goal;\n lines.push(color.bold('Goal') + ': ' + displayGoal);\n if (goal.refinedGoal && goal.refinedGoal !== goal.goal) {\n const snippet = goal.goal.length > 60 ? goal.goal.slice(0, 60) + '…' : goal.goal;\n lines.push(color.dim(' (original: \"' + snippet + '\")'));\n }\n\n // Progress bar (20-segment)\n if (typeof goal.progress === 'number') {\n const pct = Math.min(100, Math.max(0, Math.round(goal.progress)));\n const filled = Math.round(pct / 5);\n const empty = 20 - filled;\n const bar = color.green('█'.repeat(filled)) + color.dim('░'.repeat(empty));\n lines.push('Progress: ' + bar + ' ' + color.bold(pct + '%'));\n if (goal.progressNote) {\n lines.push(' ' + color.dim(goal.progressNote));\n }\n // Trend indicator\n if (goal.progressTrend) {\n const trendIcon = goal.progressTrend === 'accelerating' ? '🚀'\n : goal.progressTrend === 'stalling' ? '⚠️'\n : '➡️';\n lines.push(' Trend: ' + trendIcon + ' ' + goal.progressTrend);\n }\n }\n\n // Deliverables checklist\n if (goal.deliverables && goal.deliverables.length > 0) {\n lines.push('');\n lines.push(color.bold('Deliverables:'));\n for (const d of goal.deliverables) {\n const done = /^\\[[x✓]\\]|✅|\\(done\\)/i.test(d);\n const marker = done ? color.green('✓') : color.dim('○');\n lines.push(' ' + marker + ' ' + d);\n }\n }\n\n lines.push('');\n lines.push('Set: ' + goal.setAt);\n lines.push('Last activity: ' + goal.lastActivityAt);\n lines.push('Iterations: ' + goal.iterations);\n const stateLabel = goal.goalState ?? 'active';\n lines.push('State: ' + stateLabel + (goal.iterations > 0 ? ' (iteration #' + goal.iterations + ')' : ''));\n lines.push('Engine: ' + goal.engineState);\n const usage = summarizeUsage(goal);\n if (usage.iterationsWithUsage > 0) {\n const spent = 'Spent: ' + DOLLAR + usage.totalCostUsd.toFixed(4)\n + ' (in ' + usage.totalInputTokens + ' / out ' + usage.totalOutputTokens\n + ' tokens across ' + usage.iterationsWithUsage + ' iterations)';\n lines.push(spent);\n }\n if (goal.journal.length > 0) {\n lines.push('');\n lines.push('Recent journal (last ' + Math.min(journalLimit, goal.journal.length) + '):');\n const tail = goal.journal.slice(-journalLimit);\n for (const e of tail) {\n const mark = e.status === 'success' ? '✓' : e.status === 'failure' ? '✗' : e.status === 'aborted' ? '⊘' : '·';\n const note = e.note ? ' — ' + e.note : '';\n const cost = typeof e.costUsd === 'number' ? ' (' + DOLLAR + e.costUsd.toFixed(4) + ')' : '';\n lines.push(' #' + e.iteration + ' ' + mark + ' [' + e.source + '] ' + e.task + cost + note);\n }\n }\n return lines.join('\\n');\n}\n\n/** A single progress measurement at a point in time. */\nexport interface ProgressSnapshot {\n at: string;\n progress: number;\n note?: string | undefined;\n}\n\n/**\n * Parse [PROGRESS: N%] from agent final text.\n * Supports formats:\n * [PROGRESS: 45%]\n * [PROGRESS: 45%] — 3/5 deliverables done\n * [progress: 100%]\n * Returns null if no match.\n */\nexport function parseProgressFromText(text: string): { progress: number; note?: string } | null {\n const re = /\\[progress:\\s*(\\d{1,3})%\\]\\s*(?:[—-]\\s*(.+))?/i;\n const m = text.match(re);\n if (!m) return null;\n // Regex match guarantees capture group 1 exists, but use ?? fallback to\n // satisfy noUncheckedIndexedAccess without a non-null assertion.\n const progress = Math.min(100, Math.max(0, Number.parseInt(m[1] ?? '0', 10)));\n const note = m[2]?.trim() || undefined;\n return note === undefined ? { progress } : { progress, note };\n}\n\n/**\n * Record a progress measurement. Returns a new GoalFile with:\n * - progress + progressNote updated\n * - progressHistory appended (last 200 entries kept)\n * - progress trend computed (accelerating/steady/stalling)\n */\nexport function recordProgress(\n goal: GoalFile,\n progress: number,\n note?: string,\n): GoalFile {\n const clamped = Math.min(100, Math.max(0, progress));\n const history = [...(goal.progressHistory ?? []), { at: new Date().toISOString(), progress: clamped, note }];\n // Keep last 200 snapshots\n const trimmed = history.length > 200 ? history.slice(-200) : history;\n\n return {\n ...goal,\n progress: clamped,\n progressNote: note ?? `${clamped}% complete`,\n progressHistory: trimmed,\n progressTrend: computeTrend(trimmed),\n };\n}\n\n/** Max progress history entries to retain. */\nexport const MAX_PROGRESS_HISTORY = 200;\n\nfunction computeTrend(history: ProgressSnapshot[]): 'accelerating' | 'steady' | 'stalling' | undefined {\n if (history.length < 3) return undefined;\n const recent = history.slice(-5);\n const deltas: number[] = [];\n for (let i = 1; i < recent.length; i++) {\n deltas.push((recent[i]?.progress ?? 0) - (recent[i - 1]?.progress ?? 0));\n }\n /* v8 ignore next -- unreachable: history.length>=3 guard above guarantees >=2 deltas */\n if (deltas.length < 2) return undefined;\n const avgDelta = deltas.reduce((a, b) => a + b, 0) / deltas.length;\n if (avgDelta > 2) return 'accelerating';\n if (avgDelta < -1) return 'stalling';\n return 'steady';\n}\n","/**\n * AutonomyBrain — a self-driving decision layer for autonomous workflows.\n *\n * Unlike the standard BrainArbiter which asks the human when uncertain,\n * AutonomyBrain makes decisions autonomously within configured risk\n * boundaries, keeping the system running unattended. It uses the session\n * LLM to evaluate situations and produce decisions.\n *\n * ## Identity\n * The AutonomyBrain is NOT the main agent. It is a dedicated decision\n * engine with a single purpose: evaluate blocked/stuck situations in\n * autonomous workflows and decide whether to continue, pivot, or stop.\n *\n * ## Decision Flow\n * 1. RISK GATE — if request risk > maxAutoRisk, auto-deny\n * 2. HEURISTIC — fast pattern-match for common situations (deadlock, retry-exhausted)\n * 3. LLM EVALUATION — complex decisions (goal completion, conflict resolution)\n *\n * ## Decision Logging\n * Every decision is emitted via `onDecision` callback with a human-readable\n * summary suitable for chat history and journal entries.\n *\n * Usage:\n * const brain = createAutonomyBrain({\n * provider, model, maxAutoRisk: 'high',\n * onDecision: (summary) => journal.push(summary),\n * });\n */\n\nimport type { Provider } from '../types/provider.js';\nimport type { BrainArbiter, BrainDecision, BrainDecisionRequest } from '../coordination/brain.js';\n\nexport interface AutonomyBrainOptions {\n /** LLM provider for decision-making. */\n provider: Provider;\n /** Model to use for decisions (should be fast + cheap). */\n model: string;\n /** Maximum risk level the brain will auto-decide. Default: 'high'.\n * 'low' — only auto-decide low-risk questions\n * 'medium' — auto-decide low/medium\n * 'high' — auto-decide low/medium/high\n * 'all' — auto-decide everything (including critical)\n */\n maxAutoRisk?: 'low' | 'medium' | 'high' | 'all' | undefined;\n /** Timeout for each decision call (ms). Default: 15_000. */\n decisionTimeoutMs?: number | undefined;\n /**\n * Called after every decision with a human-readable summary.\n * Use this to log decisions into chat history, journal, or status line.\n * Example: \"🧠 Brain: skipped deadlocked tasks → continuing with phase 3/5\"\n */\n onDecision?: ((summary: string, decision: BrainDecision, request: BrainDecisionRequest) => void) | undefined;\n}\n\nconst RISK_LEVELS: Record<string, number> = {\n low: 0,\n medium: 1,\n high: 2,\n critical: 3,\n};\n\n/** Runtime-adjustable autonomy ceiling for the tiered brain. */\nexport type BrainAutoRisk = 'off' | 'low' | 'medium' | 'high' | 'all';\n\nexport interface TieredBrainArbiterOptions {\n /** Fast deterministic policy layer (DefaultBrainArbiter). Consulted first. */\n policy: BrainArbiter;\n /** LLM-backed autonomous layer (createAutonomyBrain). Consulted when the\n * policy layer would escalate to the human and the request's risk is\n * within the live ceiling. */\n autonomous?: BrainArbiter | undefined;\n /**\n * Live autonomy ceiling — read on EVERY decision so `/brain risk <level>`\n * changes take effect immediately. 'off' disables the autonomous layer\n * entirely (everything the policy can't answer goes to the human).\n */\n getMaxAutoRisk?: (() => BrainAutoRisk) | undefined;\n}\n\n/**\n * The standard Brain positioning: policy first, LLM second, human last.\n *\n * 1. POLICY — deterministic DefaultBrainArbiter (low-risk fast path,\n * fallback semantics). Answers and denies pass through untouched.\n * 2. LLM — when the policy says `ask_human` and the request's risk is\n * within the live ceiling, the autonomous brain gets a chance to\n * answer. Only a real `answer` short-circuits; LLM denials/failures\n * fall through.\n * 3. HUMAN — anything left escalates (callers wrap this in\n * HumanEscalatingBrainArbiter so `ask_human` becomes a real prompt).\n */\nexport function createTieredBrainArbiter(opts: TieredBrainArbiterOptions): BrainArbiter {\n return {\n async decide(request: BrainDecisionRequest): Promise<BrainDecision> {\n const policyDecision = await opts.policy.decide(request);\n if (policyDecision.type !== 'ask_human') return policyDecision;\n const ceiling = opts.getMaxAutoRisk?.() ?? 'medium';\n if (!opts.autonomous || ceiling === 'off') return policyDecision;\n const ceilingLevel = ceiling === 'all' ? 3 : (RISK_LEVELS[ceiling] ?? 1);\n const requestLevel = RISK_LEVELS[request.risk] ?? 2;\n if (requestLevel > ceilingLevel) return policyDecision;\n try {\n const llmDecision = await opts.autonomous.decide(request);\n if (llmDecision.type === 'answer') return llmDecision;\n } catch {\n // LLM layer is best-effort — fall through to the human.\n }\n return policyDecision;\n },\n };\n}\n\n/**\n * Create a self-driving brain that makes autonomous decisions.\n * Never asks the human — within its risk boundary it answers, above it denies.\n */\nexport function createAutonomyBrain(opts: AutonomyBrainOptions): BrainArbiter {\n const maxRisk = opts.maxAutoRisk ?? 'high';\n const maxRiskLevel = RISK_LEVELS[maxRisk] ?? 2;\n const timeoutMs = opts.decisionTimeoutMs ?? 15_000;\n\n return {\n async decide(request: BrainDecisionRequest): Promise<BrainDecision> {\n const requestLevel = RISK_LEVELS[request.risk] ?? 2;\n\n // RISK GATE — above our risk boundary → auto-deny\n if (requestLevel > maxRiskLevel) {\n const reason = `Auto-denied: risk \"${request.risk}\" exceeds max \"${maxRisk}\"`;\n const decision: BrainDecision = { type: 'deny', reason };\n opts.onDecision?.(\n `🧠 Brain: DENIED — ${request.question.slice(0, 80)} (risk: ${request.risk} > ${maxRisk})`,\n decision,\n request,\n );\n return decision;\n }\n\n // HEURISTIC — fast pattern-match\n const heuristic = quickDecide(request);\n if (heuristic) {\n opts.onDecision?.(formatDecisionSummary(heuristic, request), heuristic, request);\n return heuristic;\n }\n\n // LLM EVALUATION — complex decisions\n const llmDecision = await llmDecide(request, opts.provider, opts.model, timeoutMs);\n opts.onDecision?.(formatDecisionSummary(llmDecision, request), llmDecision, request);\n return llmDecision;\n },\n };\n}\n\n/**\n * Format a decision as a human-readable one-liner for chat history.\n */\nexport function formatDecisionSummary(\n decision: BrainDecision,\n request: BrainDecisionRequest,\n): string {\n const question = request.question.length > 80\n ? request.question.slice(0, 77) + '…'\n : request.question;\n\n if (decision.type === 'deny') {\n return `🧠 Brain: DENIED — \"${question}\" → ${decision.reason}`;\n }\n\n if (decision.type === 'answer') {\n const action = decision.optionId\n ? `chose [${decision.optionId}]`\n : decision.text.length > 60\n ? decision.text.slice(0, 57) + '…'\n : decision.text;\n return `🧠 Brain: DECIDED — \"${question}\" → ${action}`;\n }\n\n return `🧠 Brain: ASKED HUMAN — \"${question}\"`;\n}\n\n/** Fast heuristic decisions that don't need an LLM call. */\nfunction quickDecide(request: BrainDecisionRequest): BrainDecision | null {\n const q = request.question.toLowerCase();\n const ctx = request.context?.toLowerCase() ?? '';\n\n // Deadlock with failed tasks → skip and continue\n if (q.includes('deadlock') && ctx.includes('failed')) {\n return {\n type: 'answer',\n text: 'Skip deadlocked tasks and continue with remaining work. Failed tasks will be reported in the final summary.',\n rationale: 'Heuristic: deadlocked tasks blocked by failed dependencies — skipping unblocks remaining work.',\n };\n }\n\n // Repeated failure with exhausted retries → move on\n if (\n (q.includes('failed') || q.includes('retry')) &&\n (ctx.includes('3') || ctx.includes('exhausted'))\n ) {\n return {\n type: 'answer',\n text: 'Mark as failed and move on. Note the failure for the final report.',\n rationale: 'Heuristic: retries exhausted — continuing would waste resources.',\n };\n }\n\n // Goal complete verification → needs LLM evaluation\n if (q.includes('goal complete') || q.includes('mission complete')) {\n return null;\n }\n\n // Continue/proceed → always yes\n if (q.includes('continue') || q.includes('proceed')) {\n return {\n type: 'answer',\n text: 'Continue execution. Do not stop.',\n rationale: 'Heuristic: autonomy mode — continue until all work is complete.',\n };\n }\n\n return null;\n}\n\n/**\n * Ask the LLM for a decision on complex questions.\n * Uses a carefully crafted system prompt that establishes the brain's\n * identity, purpose, and decision-making framework.\n */\nasync function llmDecide(\n request: BrainDecisionRequest,\n provider: Provider,\n model: string,\n timeoutMs: number,\n): Promise<BrainDecision> {\n const optionsText = request.options?.length\n ? '\\nOptions:\\n' +\n request.options\n .map(\n (o) =>\n ` [${o.id}] ${o.label}${o.consequence ? ` — ${o.consequence}` : ''}${o.recommended ? ' ★ recommended' : ''}`,\n )\n .join('\\n')\n : '';\n\n const systemPrompt = [\n 'IDENTITY:',\n 'You are the Autonomy Brain — a dedicated decision engine inside an',\n 'autonomous AI coding agent called WrongStack. Your SOLE purpose is to',\n 'evaluate situations where the autonomous workflow is blocked, stuck, or',\n 'uncertain, and decide the best course of action to keep the system',\n 'running and making progress toward its goal.',\n '',\n 'WHAT YOU DO:',\n '- You receive a question + context from an autonomy subsystem (goal',\n ' engine, phase orchestrator, task decomposer).',\n '- You evaluate whether the system should continue, pivot, retry, skip,',\n ' or stop.',\n '- You output exactly ONE decision. No preamble, no markdown, no',\n ' elaboration beyond what is needed to justify the decision.',\n '',\n 'HOW YOU DECIDE:',\n '1. PREFER CONTINUATION. The default answer is always \"continue\" unless',\n ' there is clear evidence that stopping is safer or more productive.',\n '2. BE SPECIFIC. If options are provided, pick one by its [id]. If not,',\n ' describe the exact action in 1-2 sentences.',\n '3. VERIFY COMPLETION. If the question is about whether the goal is done,',\n ' check deliverables and progress before saying yes. A progress bar at',\n ' 80% with open deliverables means NOT done.',\n '4. AVOID WASTE. If a task has failed 3+ times with the same approach,',\n ' recommend a different approach or skipping it — do not recommend',\n ' retrying the same thing.',\n '5. CONSIDER COST. If the question mentions spent budget or token counts,',\n ' factor that into your decision. A goal that has already spent $50',\n ' with 90% progress is worth finishing; one at 15% with $100 spent',\n ' may need re-evaluation.',\n '',\n 'OUTPUT FORMAT:',\n '- With options: output the option [id] and a 1-sentence justification.',\n ' Example: \"[resolve] — conflict is in test files only, safe to auto-resolve.\"',\n '- Without options: output the decision as a 1-2 sentence action.',\n ' Example: \"Continue execution. Progress is steady at 60% with 3/5',\n ' deliverables done. No reason to stop.\"',\n '',\n 'CRITICAL RULE:',\n 'You are NOT the main agent. Do not suggest code changes, tool calls,',\n 'or implementation details. Your output is a DECISION, not a plan.',\n ].join('\\n');\n\n const userMessage = [\n `Question: ${request.question}`,\n request.context ? `\\nContext:\\n${request.context}` : '',\n optionsText,\n ].filter(Boolean).join('\\n');\n\n try {\n const signal = AbortSignal.timeout(timeoutMs);\n const response = await provider.complete(\n {\n model,\n system: [{ type: 'text', text: systemPrompt }],\n messages: [{ role: 'user', content: userMessage || 'Decide.' }],\n maxTokens: 200,\n },\n { signal },\n );\n\n const text = extractText(response).trim();\n\n // Try to match an option id\n if (request.options?.length) {\n for (const opt of request.options) {\n if (text.toLowerCase().includes(opt.id.toLowerCase())) {\n return {\n type: 'answer',\n optionId: opt.id,\n text: opt.label,\n rationale: text,\n };\n }\n }\n }\n\n // Free-text answer\n return {\n type: 'answer',\n text: text || (request.fallback === 'continue'\n ? 'Continue execution.'\n : 'Denied by autonomy policy.'),\n rationale: text || undefined,\n };\n } catch {\n // LLM unavailable — use fallback\n if (request.fallback === 'continue') {\n return {\n type: 'answer',\n text: 'Continue (Autonomy Brain LLM unavailable — using fallback).',\n };\n }\n return { type: 'deny', reason: 'Autonomy Brain LLM unavailable for decision.' };\n }\n}\n\nfunction extractText(result: unknown): string {\n if (!result || typeof result !== 'object') return '';\n const r = result as Record<string, unknown>;\n if (Array.isArray(r.content)) {\n return (r.content as Array<{ type?: string; text?: string }>)\n .filter((b) => b.type === 'text')\n .map((b) => b.text ?? '')\n .join('');\n }\n if (Array.isArray(r.choices)) {\n return (r.choices as Array<{ message?: { content?: string } }>)[0]?.message?.content ?? '';\n }\n return typeof r.text === 'string' ? r.text : '';\n}\n","import { execFile } from 'node:child_process';\r\nimport { promisify } from 'node:util';\r\nimport type { Agent } from '../core/agent.js';\r\nimport type { TodoItem } from '../core/context.js';\r\nimport type { EventBus } from '../kernel/events.js';\r\nimport type { Compactor } from '../types/compactor.js';\r\nimport type { BrainArbiter } from '../coordination/brain.js';\r\nimport {\r\n appendJournal,\r\n loadGoal,\r\n saveGoal,\r\n goalFilePath,\r\n parseProgressFromText,\r\n recordProgress,\r\n type GoalFile,\r\n type JournalEntry,\r\n} from '../storage/goal-store.js';\r\nimport { sleep } from '../utils/sleep.js';\r\nimport { toErrorMessage } from '../utils/error.js';\nimport { formatDecisionSummary } from './autonomy-brain.js';\r\n\r\nconst execFileP = promisify(execFile);\r\n\r\n/**\r\n * Sense-decide-execute-reflect loop on top of a long-running Goal.\r\n *\r\n * Each iteration:\r\n * 1. Sense — read goal, pending todos, `git status --porcelain`.\r\n * 2. Decide — pick a source (todo / git / brainstorm) and a task.\r\n * 3. Execute — single agent.run with a directive prompt.\r\n * 4. Reflect — append a journal entry, persist state to disk.\r\n *\r\n * The loop runs forever until `stop()` is called externally (REPL SIGINT\r\n * handler, /autonomy stop). No internal time/cost cap by design — the\r\n * user wants \"sittin sene\". Failures are logged and the loop continues\r\n * with a different source on the next tick.\r\n */\r\n\r\nexport interface EternalAutonomyOptions {\r\n agent: Agent;\r\n projectRoot: string;\r\n /**\r\n * Per-iteration agent timeout. Defaults to 5 minutes. A single hung\r\n * provider call should not freeze the whole eternal loop.\r\n */\r\n iterationTimeoutMs?: number | undefined;\r\n /**\r\n * Maximum number of internal agent.run iterations the engine grants per\r\n * eternal-loop tick. The engine sets `autonomousContinue: true` so the\r\n * agent can run multi-step tasks end-to-end within one tick instead of\r\n * bouncing back to the engine after every single tool call. Default 500.\r\n * Previous 50 was far too low — agents hit the limit and restart constantly.\r\n */\r\n iterationMaxAgentSteps?: number | undefined;\r\n /**\r\n * Minimum sleep between iterations. Defaults to 1 s — enough for\r\n * SIGINT handlers to fire mid-loop without pegging a core when the\r\n * provider is being rate-limited.\r\n */\r\n cycleGapMs?: number | undefined;\r\n /**\r\n * Maximum consecutive failures before the source rotation forces a\r\n * brainstorm cycle. Default 3. Acts as a soft-recovery, not a stop.\r\n */\r\n failureBudget?: number | undefined;\r\n /**\r\n * Per-todo failed-attempt ceiling. When the engine picks the same todo\r\n * and the iteration fails this many times in total, the todo is taken\r\n * out of rotation (engine prefers other sources) until it changes\r\n * status. Default 3. Prevents the loop from spinning forever on one\r\n * stuck task.\r\n */\r\n todoMaxAttempts?: number | undefined;\r\n /**\r\n * Consecutive brainstorm-DONE responses required to consider the goal\r\n * complete and stop the engine. When the LLM's brainstorm step keeps\r\n * answering `DONE`, the engine treats that as \"no more work\" and, after\r\n * this many in a row, marks the goal as completed instead of sleeping\r\n * forever. Default 3.\r\n */\r\n brainstormDoneStopThreshold?: number | undefined;\r\n /** Side-channel notifications (logging, UI updates). */\r\n onIteration?: (((entry: JournalEntry) => void)) | undefined;\r\n onError?: (err: Error | undefined, iteration: number) => void;\r\n /**\r\n * Per-iteration phase notifications for live UI updates (TUI status bar,\r\n * etc.). Fires at each major stage transition: idle → decide → execute →\r\n * reflect → (sleep | paused | stopped). Fire-and-forget — the engine\r\n * does not await the callback.\r\n */\r\n onStage?: (((stage: IterationStage) => void)) | undefined;\r\n /**\r\n * Optional injected git status reader — production code uses git, tests\r\n * stub this out so they don't shell out.\r\n */\r\n gitStatusReader?: ((() => Promise<string>)) | undefined;\r\n /**\r\n * Optional clock — tests stub for deterministic timestamps.\r\n */\r\n now?: ((() => Date)) | undefined;\r\n /**\r\n * Optional compactor. When provided, the engine runs compaction every\r\n * `compactEveryNIterations` iterations to keep the agent's message\r\n * history under control during multi-day eternal loops. Without\r\n * compaction, an infinite loop will eventually overflow the provider's\r\n * context window and start failing.\r\n */\r\n compactor?: Compactor | undefined;\r\n /** How many iterations between compaction calls. Default 25. */\r\n compactEveryNIterations?: number | undefined;\r\n /**\r\n * Aggressive compaction threshold. When ctx token usage exceeds this\r\n * fraction of `maxContextTokens`, compaction runs in aggressive mode\r\n * regardless of the iteration cadence. 0.85 by default.\r\n */\r\n aggressiveCompactRatio?: number | undefined;\r\n /**\r\n * Model's max context window in tokens. When set, the engine watches\r\n * `currentRequestTokens()` against this and triggers aggressive compact\r\n * before the next iteration would overflow. Omit to disable threshold\r\n * checks (iteration cadence still applies).\r\n */\r\n maxContextTokens?: number | undefined;\r\n /**\r\n * Base delay (ms) for the first transient-error backoff. Subsequent\r\n * transient failures double this, capped at `transientBackoffMaxMs`.\r\n * Default 2_000.\r\n *\r\n * \"Transient\" means the underlying error is recoverable per\r\n * `WrongStackError.recoverable` (ProviderError sets this for 429/529/5xx\r\n * /network errors). Permanent errors (auth/invalid request) skip the\r\n * backoff and count toward `failureBudget` like before — backing off\r\n * on a permanent failure is wasted time.\r\n */\r\n transientBackoffBaseMs?: number | undefined;\r\n /** Ceiling for the exponential backoff. Default 60_000 (60 s). */\r\n transientBackoffMaxMs?: number | undefined;\r\n /** Called when the eternal loop stops for any reason (manual stop, goal complete, etc.). */\r\n onEternalStop?: ((() => void)) | undefined;\r\n /**\r\n * Optional brain arbiter for autonomous decision-making. When wired,\r\n * the engine consults the brain instead of auto-stopping on:\r\n * - Brainstorm DONE threshold reached\r\n * - Consecutive failures exceeding failure budget\r\n * - Goal completion verification\r\n * Without a brain, the engine uses its built-in heuristics.\r\n */\r\n brain?: BrainArbiter | undefined;\r\n /** Optional EventBus for emitting storage.* observability events from goal I/O. */\r\n events?: EventBus | undefined;\r\n}\r\n\r\nexport type EternalEngineState = 'idle' | 'running' | 'stopped';\r\n\r\n/**\r\n * Per-iteration phase emitted via `onStage` so UIs can render the\r\n * engine's live location in the sense-decide-execute-reflect loop.\r\n */\r\nexport type IterationStage =\r\n | { phase: 'idle' }\r\n | { phase: 'decide'; reason: string }\r\n | { phase: 'execute'; task: string }\r\n | { phase: 'reflect'; status: 'success' | 'failure' | 'aborted' | 'skipped'; note?: string | undefined }\r\n | { phase: 'sleep'; ms: number }\r\n | { phase: 'paused' }\r\n | { phase: 'stopped' }\r\n | { phase: 'error'; message: string };\r\n\r\ninterface DecidedAction {\r\n source: JournalEntry['source'];\r\n task: string;\r\n directive: string;\r\n /** Set when source === 'todo' so the engine can attribute failures. */\r\n todoId?: string | undefined;\r\n}\r\n\r\n/**\r\n * Sentinel returned by `brainstormTask` when the LLM declares the goal\r\n * fully accomplished. Distinct from `null` (which means \"brainstorm\r\n * failed / no actionable task right now\") so the engine can count\r\n * consecutive DONE answers toward a real stop.\r\n */\r\nconst BRAINSTORM_DONE = Symbol('brainstorm-done');\r\n\r\n/**\r\n * Free-text marker the model can emit (on its own line) to declare the\r\n * overall mission accomplished. Detected in the successful iteration's\r\n * `finalText`. When present, the engine flips `goalState='completed'`\r\n * and stops — the model has explicitly claimed completion AND the\r\n * iteration succeeded, which together is the most reliable stop signal\r\n * we can get without a separate verifier round-trip.\r\n */\r\nconst GOAL_COMPLETE_MARKER = /^\\s*\\[goal[_\\s-]*complete\\]\\s*$/im;\r\n\r\n/**\r\n * Free-text marker for the `/goal clear` command equivalent — when the\r\n * model emits this, the engine treats it as a manual goal clear (not just\r\n * completion) so the goal file is removed and onEternalStop fires.\r\n */\r\nconst GOAL_CLEAR_MARKER = /^\\s*\\[\\/?goal\\s*clear\\]\\s*$/im;\r\n\r\nexport class EternalAutonomyEngine {\r\n private state: EternalEngineState = 'idle';\r\n private stopRequested = false;\r\n private consecutiveFailures = 0;\r\n private consecutiveBrainstormDone = 0;\r\n /**\r\n * Count of consecutive transient (recoverable) provider failures. Drives\r\n * the exponential backoff between iterations. Reset on the first\r\n * successful iteration so a single bad afternoon doesn't permanently\r\n * slow the loop down.\r\n */\r\n private consecutiveTransientRetries = 0;\r\n private currentCtrl: AbortController | null = null;\r\n private iterationsSinceCompact = 0;\r\n private readonly goalPath: string;\r\n\r\n constructor(private readonly opts: EternalAutonomyOptions) {\r\n this.goalPath = goalFilePath(opts.projectRoot);\r\n }\r\n\r\n /** Current engine state — readable for UIs. */\r\n get currentState(): EternalEngineState {\r\n return this.state;\r\n }\r\n\r\n /** Synchronously request stop. Resolves once the running iteration aborts. */\r\n stop(): void {\r\n this.stopRequested = true;\r\n this.currentCtrl?.abort();\r\n // Best-effort: flip the persisted state so the next startup banner\r\n // doesn't report a phantom \"running\" engine. Fire-and-forget — if it\r\n // races with an in-flight iteration's write, the journal write wins\r\n // (engineState is metadata, not durable correctness).\r\n void this.persistEngineState('stopped').catch((err) => {\r\n console.error(JSON.stringify({\r\n level: 'error',\r\n event: 'engine.persist_state_failed',\r\n message: toErrorMessage(err),\r\n context: { expectedState: 'stopped' },\r\n timestamp: new Date().toISOString(),\r\n }));\r\n });\r\n this.state = 'stopped';\r\n }\r\n\r\n /**\r\n * Mark the engine as 'running' on disk + reset stop state so a new\r\n * batch of `runOneIteration()` calls can proceed. Called by the REPL\r\n * when the user invokes `/autonomy eternal`. Idempotent.\r\n */\r\n async prime(): Promise<void> {\r\n this.stopRequested = false;\r\n this.state = 'running';\r\n await this.persistEngineState('running').catch(() => {});\r\n }\r\n\r\n /**\r\n * Main loop. Returns when stop() is called or the goal file is removed.\r\n * Does NOT throw — every iteration is wrapped to keep the loop alive.\r\n */\r\n async run(): Promise<void> {\r\n this.state = 'running';\r\n await this.persistEngineState('running');\r\n\r\n try {\r\n while (!this.stopRequested) {\r\n let iterationOk = false;\r\n try {\r\n iterationOk = await this.runOneIteration();\r\n } catch (err) {\r\n this.consecutiveFailures++;\r\n this.opts.onError?.(err instanceof Error ? err : new Error(String(err)), this.consecutiveFailures);\r\n await this.appendFailure('engine error', toErrorMessage(err));\r\n }\r\n\r\n if (iterationOk) {\r\n this.consecutiveFailures = 0;\r\n }\r\n\r\n if (this.stopRequested) break;\r\n\r\n // Brief gap so SIGINT can land between iterations even if the\r\n // agent is bouncing back results fast. 0 by default for 24/7 mode.\r\n await sleep(this.opts.cycleGapMs ?? 0);\r\n }\r\n } finally {\r\n this.state = 'stopped';\r\n await this.persistEngineState('stopped').catch(() => {});\r\n }\r\n }\r\n\r\n /**\r\n * Execute a single sense-decide-execute-reflect cycle.\r\n * Returns true on success, false on handled failure / no-op.\r\n *\r\n * Exposed publicly so the REPL can pace iterations from its main loop\r\n * — running the engine and the REPL as a single sequential consumer of\r\n * `agent.run()` avoids race conditions on the shared Context.\r\n */\r\n async runOneIteration(): Promise<boolean> {\r\n // Emit stage transitions so UIs can render the engine's live location.\r\n const emit = (stage: IterationStage) => {\r\n this.opts.onStage?.(stage);\r\n };\r\n\r\n const goal = await loadGoal(this.goalPath, this.opts.events);\r\n if (!goal) {\r\n // Goal file disappeared — treat as a graceful stop.\r\n emit({ phase: 'stopped' });\r\n this.stopRequested = true;\r\n return false;\r\n }\r\n\r\n // Mission-level lifecycle gate.\r\n const missionState = goal.goalState ?? 'active';\r\n if (missionState !== 'active') {\r\n emit({ phase: missionState === 'paused' ? 'paused' : 'stopped' });\r\n this.stopRequested = true;\r\n return false;\r\n }\r\n\r\n emit({ phase: 'decide', reason: 'picking next task' });\r\n const action = await this.decide(goal);\r\n if (!action) {\r\n if (!this.stopRequested) {\r\n emit({ phase: 'sleep', ms: 5_000 });\r\n await sleep(5_000);\r\n } else {\r\n emit({ phase: 'stopped' });\r\n }\r\n return false;\r\n }\r\n\r\n emit({ phase: 'execute', task: action.task });\r\n\r\n const ctrl = new AbortController();\r\n this.currentCtrl = ctrl;\r\n const timer = setTimeout(\r\n () => ctrl.abort(),\r\n this.opts.iterationTimeoutMs ?? 5 * 60_000,\r\n );\r\n let status: JournalEntry['status'] = 'success';\r\n let note: string | undefined;\r\n let finalText = '';\r\n // Captured from `result.error?.recoverable` when the agent.run returns\r\n // a recoverable WrongStackError (ProviderError sets this for 429/529\r\n // /5xx/network). Drives the engine's exponential backoff so a\r\n // transient rate-limit storm doesn't burn the failure budget in\r\n // seconds. Permanent errors leave this false and trip the normal\r\n // consecutiveFailures path.\r\n let isTransientFailure = false;\r\n\r\n // Snapshot usage before so the iteration delta can be journaled.\r\n // Token counter is optional in mock/test contexts — guard accordingly.\r\n const tc = this.opts.agent.ctx?.tokenCounter;\r\n const beforeUsage = tc?.total?.();\r\n const beforeCost = tc?.estimateCost?.().total;\r\n\r\n try {\r\n const result = await this.opts.agent.run(\r\n [{ type: 'text' as const, text: action.directive }],\r\n {\r\n signal: ctrl.signal,\r\n // Enable per-call autonomous continuation so the agent can chain\r\n // multiple internal tool/response cycles end-to-end on one\r\n // directive instead of returning to the engine after a single\r\n // round-trip. The model uses `[continue]` / `[done]` markers\r\n // (or the `continue_to_next_iteration` tool) to control the\r\n // inner loop. Without this flag the engine produced shallow\r\n // iterations and almost never let a real task finish.\r\n autonomousContinue: true,\r\n // Cap the inner loop so a runaway agent.run can't burn through\r\n // the iteration timeout — the engine's own outer loop is the\r\n // long-running thing, each tick should be bounded.\r\n maxIterations: this.opts.iterationMaxAgentSteps ?? 500,\r\n },\r\n );\r\n\r\n if (result.status === 'aborted') {\r\n status = 'aborted';\r\n note = 'stopped by user';\r\n } else if (result.status === 'failed') {\r\n status = 'failure';\r\n note = result.error?.describe?.() ?? 'agent run failed';\r\n isTransientFailure = result.error?.recoverable === true;\r\n } else if (result.status === 'max_iterations') {\r\n status = 'failure';\r\n note = `max iterations (${result.iterations})`;\r\n } else {\r\n status = 'success';\r\n finalText = result.finalText ?? '';\r\n const tail = finalText.slice(0, 240).replace(/\\s+/g, ' ').trim();\r\n if (tail) note = tail;\r\n }\r\n } catch (err) {\r\n const isAbort = err instanceof Error && (err.name === 'AbortError' || err.message.includes('abort'));\r\n status = isAbort ? 'aborted' : 'failure';\r\n note = toErrorMessage(err);\r\n // Surface .recoverable on the thrown WrongStackError too — provider\r\n // errors that escape the agent's catch (rare; usually wrapped into\r\n // result.error) still classify correctly.\r\n if (\r\n !isAbort &&\r\n typeof (err as { recoverable?: unknown | undefined })?.recoverable === 'boolean'\r\n ) {\r\n isTransientFailure = (err as { recoverable: boolean }).recoverable;\r\n }\r\n } finally {\r\n clearTimeout(timer);\r\n this.currentCtrl = null;\r\n }\r\n\r\n // Per-todo attempt accounting. On failure of a todo-sourced action,\r\n // bump the persistent counter so `decide()` can rotate past it once\r\n // it crosses the configured ceiling. Successful runs leave the\r\n // counter untouched — the LLM is responsible for flipping the todo\r\n // status to `completed` via the todos tool (directive teaches this).\r\n if (action.source === 'todo' && action.todoId && status !== 'success') {\r\n await this.bumpTodoAttempt(action.todoId);\r\n }\r\n\r\n // Capture per-iteration usage delta. Cost is always non-negative;\r\n // if the counter wraps or resets mid-iteration we clamp to 0 so the\r\n // journal never shows negative spend.\r\n const afterUsage = tc?.total?.();\r\n const afterCost = tc?.estimateCost?.().total;\r\n const tokens =\r\n beforeUsage && afterUsage\r\n ? {\r\n input: Math.max(0, afterUsage.input - beforeUsage.input),\r\n output: Math.max(0, afterUsage.output - beforeUsage.output),\r\n }\r\n : undefined;\r\n const costUsd =\r\n typeof beforeCost === 'number' && typeof afterCost === 'number'\r\n ? Math.max(0, afterCost - beforeCost)\r\n : undefined;\r\n\r\n await this.appendIterationEntry({\r\n source: action.source,\r\n task: action.task,\r\n status,\r\n note,\r\n tokens,\r\n costUsd,\r\n });\r\n\r\n emit({ phase: 'reflect', status, note });\r\n\r\n // Re-read the goal so we can emit the real iteration counter rather\r\n // than the previous placeholder. If the goal was unlinked mid-flight\r\n // (graceful stop via /goal clear) the iteration index is still\r\n // useful — fall back to the in-memory consecutiveFailures-derived\r\n // approximation only as a last resort.\r\n let iterationIndex = 0;\r\n try {\r\n const reloaded = await loadGoal(this.goalPath, this.opts.events);\r\n iterationIndex = reloaded?.iterations ?? 0;\r\n } catch {\r\n // best-effort\r\n }\r\n this.opts.onIteration?.({\r\n at: (this.opts.now?.() ?? new Date()).toISOString(),\r\n iteration: iterationIndex,\r\n source: action.source,\r\n task: action.task,\r\n status,\r\n note,\r\n tokens,\r\n costUsd,\r\n });\r\n\r\n // Transient failure — sleep with interruptible backoff before retry.\r\n if (status === 'failure') {\r\n if (isTransientFailure) {\r\n this.consecutiveTransientRetries++;\r\n const delay = this.computeTransientBackoffMs();\r\n if (delay > 0) {\r\n emit({ phase: 'sleep', ms: delay });\r\n await this.sleepInterruptible(delay);\r\n }\r\n return false;\r\n }\r\n this.consecutiveFailures++;\r\n return false;\r\n }\r\n\r\n if (status === 'aborted') {\r\n if (this.stopRequested) return false;\r\n this.consecutiveFailures++;\r\n return false;\r\n }\r\n\r\n // Successful iteration\r\n this.consecutiveTransientRetries = 0;\r\n const cycleGapMs = this.opts.cycleGapMs ?? 1000;\r\n emit({ phase: 'sleep', ms: cycleGapMs });\r\n await sleep(cycleGapMs);\r\n\r\n // Goal-complete detection. The model emits `[GOAL_COMPLETE]` on its\r\n // own line in `finalText` when the overall mission is verifiably done.\r\n // Combined with a successful iteration this is a strong stop signal:\r\n // the LLM explicitly claimed completion AND the run did not fail. We\r\n // mark the goal `completed`, journal it, and stop. No separate\r\n // verifier round-trip — keeps cost down; if the model lies, the user\r\n // notices and can re-arm with `/goal set`.\r\n if (GOAL_COMPLETE_MARKER.test(finalText)) {\r\n // Treat GOAL_COMPLETE as a full goal clear: remove the goal file and\r\n // fire onEternalStop so the REPL exits eternal mode. Stronger than\r\n // just marking completed — the REPL needs both to happen.\r\n await this.clearGoalManually(finalText);\r\n this.stopRequested = true;\r\n return true;\r\n }\r\n // Goal-clear detection — model emits `[goal clear]` equivalent to\r\n // `/goal clear`. Treat as a manual stop: remove the goal file and fire\r\n // onEternalStop so the REPL knows to return to normal mode.\r\n if (GOAL_CLEAR_MARKER.test(finalText)) {\r\n await this.clearGoalManually(finalText);\r\n this.stopRequested = true;\r\n return true;\r\n }\r\n\r\n // ── Progress tracking ──\r\n // Parse [PROGRESS: N%] from the agent's final text and persist it.\r\n // Also auto-complete the goal when the agent reports 100% progress.\r\n const parsed = parseProgressFromText(finalText);\r\n if (parsed) {\r\n await this.updateProgress(parsed.progress, parsed.note);\r\n if (parsed.progress >= 100) {\r\n // Agent claims 100% — add a final journal entry and complete.\r\n await this.markGoalCompleted(\r\n { source: action.source, task: action.task, directive: action.directive },\r\n `progress reached 100%: ${parsed.note ?? 'goal complete'}`,\r\n );\r\n this.stopRequested = true;\r\n return true;\r\n }\r\n }\r\n\r\n // Compaction runs only on successful iterations — there's no point\r\n // compacting after a failed/aborted iteration that didn't add much to\r\n // the message history.\r\n this.iterationsSinceCompact++;\r\n await this.maybeCompact().catch((err) => {\r\n // Don't let compaction failure kill the loop; surface via onError.\r\n this.opts.onError?.(\r\n err instanceof Error ? err : new Error(String(err)),\r\n this.consecutiveFailures,\r\n );\r\n });\r\n return true;\r\n }\r\n\r\n /**\r\n * Run compaction when either trigger fires:\r\n * - We've done >= compactEveryNIterations since the last compact.\r\n * - Current request tokens exceed aggressiveCompactRatio * maxContext.\r\n *\r\n * The second check uses *aggressive* mode to free more headroom; the\r\n * cadence check uses non-aggressive (cheaper).\r\n */\r\n private async maybeCompact(): Promise<void> {\r\n const compactor = this.opts.compactor;\r\n if (!compactor) return;\r\n const ctx = this.opts.agent.ctx;\r\n if (!ctx) return;\r\n\r\n const cadence = this.opts.compactEveryNIterations ?? 25;\r\n const threshold = this.opts.aggressiveCompactRatio ?? 0.85;\r\n const maxCtx = this.opts.maxContextTokens;\r\n\r\n let aggressive = false;\r\n let shouldRun = false;\r\n\r\n if (this.iterationsSinceCompact >= cadence) {\r\n shouldRun = true;\r\n }\r\n\r\n if (maxCtx && maxCtx > 0) {\r\n const used = ctx.tokenCounter?.currentRequestTokens?.();\r\n if (used) {\r\n const total = used.input + used.cacheRead;\r\n if (total / maxCtx >= threshold) {\r\n shouldRun = true;\r\n aggressive = true;\r\n }\r\n }\r\n }\r\n\r\n if (!shouldRun) return;\r\n\r\n const report = await compactor.compact(ctx, { aggressive });\r\n this.iterationsSinceCompact = 0;\r\n // Journal the compaction event so users see it in /goal journal.\r\n const saved = report.before - report.after;\r\n await this.appendIterationEntry({\r\n source: 'manual',\r\n task: `compaction (${aggressive ? 'aggressive' : 'cadence'})`,\r\n status: 'success',\r\n note: `saved ~${saved} tokens (${report.before}→${report.after})`,\r\n });\r\n }\r\n\r\n /**\r\n * Hybrid idea source.\r\n * 1. Pending todos on the agent's context.\r\n * 2. Dirty git working tree → propose a \"review and finish this\" task.\r\n * 3. Otherwise: brainstorm via the LLM against the goal.\r\n *\r\n * After failureBudget consecutive failures, force brainstorm so the\r\n * engine doesn't loop on the same broken todo or stuck git state.\r\n */\r\n private async decide(goal: GoalFile): Promise<DecidedAction | null> {\r\n const forceBrainstorm = this.consecutiveFailures >= (this.opts.failureBudget ?? 3);\r\n\r\n if (!forceBrainstorm) {\r\n const todo = this.pickPendingTodo(goal);\r\n if (todo) {\r\n return {\r\n source: 'todo',\r\n task: todo.content,\r\n todoId: todo.id,\r\n directive: this.buildDirective(goal, 'todo', todo.content),\r\n };\r\n }\r\n\r\n const gitTask = await this.pickGitTask();\r\n if (gitTask) {\r\n return {\r\n source: 'git',\r\n task: gitTask,\r\n directive: this.buildDirective(goal, 'git', gitTask),\r\n };\r\n }\r\n }\r\n\r\n const brainstormed = await this.brainstormTask(goal);\r\n if (brainstormed === BRAINSTORM_DONE) {\r\n this.consecutiveBrainstormDone++;\r\n const threshold = this.opts.brainstormDoneStopThreshold ?? 3;\r\n if (this.consecutiveBrainstormDone >= threshold) {\r\n // Consult the brain before stopping — it may decide to continue\r\n const shouldStop = await this.consultBrainForDone(goal);\r\n if (shouldStop) {\r\n await this.markGoalCompleted(\r\n { source: 'brainstorm', task: 'no further work', directive: '' },\r\n `brainstorm returned DONE ${this.consecutiveBrainstormDone}x in a row${this.opts.brain ? ', brain confirmed' : ''}`,\r\n );\r\n this.stopRequested = true;\r\n } else {\r\n // Brain says keep going — reset the DONE streak\r\n this.consecutiveBrainstormDone = 0;\r\n }\r\n }\r\n return null;\r\n }\r\n if (!brainstormed) return null;\r\n // Got a real task — reset the DONE streak.\r\n this.consecutiveBrainstormDone = 0;\r\n return {\r\n source: 'brainstorm',\r\n task: brainstormed,\r\n directive: this.buildDirective(goal, 'brainstorm', brainstormed),\r\n };\r\n }\r\n\r\n private pickPendingTodo(goal: GoalFile): TodoItem | null {\r\n const todos = this.opts.agent.ctx.todos;\r\n if (!Array.isArray(todos)) return null;\r\n const attempts = goal.todoAttempts ?? {};\r\n const ceiling = this.opts.todoMaxAttempts ?? 3;\r\n // First-pending strategy with a stuck-task escape hatch: if the\r\n // first pending todo has already failed `ceiling` times, fall\r\n // through to later pending todos. Returns null when every pending\r\n // todo is stuck — the caller will fall through to git/brainstorm.\r\n for (const t of todos) {\r\n if (t.status !== 'pending') continue;\r\n const used = attempts[t.id] ?? 0;\r\n if (used >= ceiling) continue;\r\n return t;\r\n }\r\n return null;\r\n }\r\n\r\n private async pickGitTask(): Promise<string | null> {\r\n let out: string;\r\n try {\r\n out = await (this.opts.gitStatusReader?.() ?? this.readGitStatus());\r\n } catch {\r\n return null;\r\n }\r\n const dirty = out.trim();\r\n if (!dirty) return null;\r\n // Surface a concise prompt — the agent will look at the diff itself.\r\n const lines = dirty.split('\\n').slice(0, 8);\r\n const preview = lines.join(', ');\r\n return `Inspect the dirty working tree and either finish the in-progress work or revert it. Files: ${preview}`;\r\n }\r\n\r\n private async readGitStatus(): Promise<string> {\r\n const { stdout } = await execFileP('git', ['status', '--porcelain'], {\r\n cwd: this.opts.projectRoot,\r\n timeout: 5_000,\r\n });\r\n return stdout;\r\n }\r\n\r\n private async brainstormTask(goal: GoalFile): Promise<string | null | typeof BRAINSTORM_DONE> {\r\n const lastFew = goal.journal\r\n .slice(-5)\r\n .map((e) => ` - [${e.status}] ${e.task}`)\r\n .join('\\n');\r\n const directive = [\r\n 'You are deciding the next action in an autonomous loop pursuing a long-running goal.',\r\n '',\r\n `Goal: ${goal.goal}`,\r\n '',\r\n lastFew ? `Recent iterations:\\n${lastFew}` : 'No prior iterations yet.',\r\n '',\r\n 'Output ONE concrete, immediately-actionable task that advances the goal.',\r\n 'Constraints:',\r\n '- One sentence, imperative form, under 200 chars.',\r\n '- No preamble, no explanation, no markdown — just the task line.',\r\n '- If recent iterations show repeated failures on the same target, pivot.',\r\n '- If the goal appears fully accomplished AND you can name a concrete',\r\n ' artifact / test / output that proves it, output exactly: DONE',\r\n '- Be conservative with DONE: if the recent journal contains failures',\r\n ' or aborted entries, the goal is almost certainly NOT done.',\r\n ].join('\\n');\r\n\r\n try {\r\n const ctrl = new AbortController();\r\n const timer = setTimeout(() => ctrl.abort(), 60_000);\r\n try {\r\n const result = await this.opts.agent.run(\r\n [{ type: 'text' as const, text: directive }],\r\n { signal: ctrl.signal, maxIterations: 1 },\r\n );\r\n if (result.status !== 'done') return null;\r\n const text = (result.finalText ?? '').trim();\r\n if (!text) return null;\r\n // Distinct sentinel for DONE so the caller can count consecutive\r\n // DONE answers toward a real stop. The old `return null` path\r\n // conflated \"no work\" with \"engine failure\" and looped forever.\r\n if (/^DONE\\.?$/i.test(text)) return BRAINSTORM_DONE;\r\n // Take the first non-empty line and clip to 240 chars.\r\n const firstLine = text.split('\\n').find((l) => l.trim().length > 0)?.trim();\r\n if (!firstLine) return null;\r\n if (/^DONE\\.?$/i.test(firstLine)) return BRAINSTORM_DONE;\r\n return firstLine.slice(0, 240);\r\n } finally {\r\n clearTimeout(timer);\r\n }\r\n } catch {\r\n return null;\r\n }\r\n }\r\n\r\n private buildDirective(goal: GoalFile, source: JournalEntry['source'], task: string): string {\r\n const recentJournal = goal.journal\r\n .slice(-5)\r\n .map((e) => ` #${e.iteration} [${e.status}] ${e.task}${e.note ? ` — ${e.note.slice(0, 80)}` : ''}`)\r\n .join('\\n');\r\n return [\r\n '═══ ETERNAL AUTONOMY — iteration directive ═══',\r\n '',\r\n `Mission: ${goal.goal}`,\r\n `Iteration: #${goal.iterations + 1}`,\r\n `Source: ${source}`,\r\n `Task: ${task}`,\r\n '',\r\n recentJournal ? `Recent journal (last 5):\\n${recentJournal}` : 'No prior iterations.',\r\n '',\r\n '── EXECUTION PROTOCOL ──',\r\n 'You are inside a long-running autonomous loop. Each iteration you',\r\n 'execute ONE concrete task that advances the Mission. No user is',\r\n 'available to clarify — make defensible decisions and move forward.',\r\n '',\r\n '1. EXECUTE END-TO-END',\r\n ' • Use multiple tool calls freely. Emit `[continue]` on its own line',\r\n ' to chain to the next internal step without returning.',\r\n ' • When this iteration\\'s Task is finished (real artifact / passing',\r\n ' test / applied diff / clean output), emit `[done]` on its own line.',\r\n ' • Do not stop on the first obstacle — try at least 3 distinct',\r\n ' approaches before giving up. YOLO is active for normal project work;',\r\n ' destructive-gated confirmations still belong to the permission flow.',\r\n '',\r\n '2. UPDATE TODO STATE (when Source is `todo`)',\r\n ' • Mark this todo `in_progress` via the todos tool before tool work.',\r\n ' • Mark it `completed` on success, with a one-line outcome note.',\r\n ' • If you cannot make progress after 2 distinct attempts, mark it',\r\n ' `cancelled` with the obstacle. The loop will skip it next time.',\r\n '',\r\n '3. MISSION-COMPLETE PROTOCOL',\r\n ' • If — and ONLY if — the OVERALL Mission (not just this Task) is',\r\n ' verifiably accomplished, emit on its own line:',\r\n ' [GOAL_COMPLETE]',\r\n ' followed by a one-paragraph verification recipe (artifact path,',\r\n ' test command, or 10-second reproduction). This halts the loop.',\r\n ' • NEVER emit [GOAL_COMPLETE] on optimism, partial progress, or',\r\n ' \"looks fine\". Required: a concrete artifact that proves it AND',\r\n ' no recent journal failures contradicting completion.',\r\n ' • If unsure, emit `[done]` instead and let the next iteration',\r\n ' decide. The loop is patient; false completion is not.',\r\n '',\r\n '4. NO INTERACTIVITY',\r\n ' • Do not ask questions, do not request confirmation, do not propose',\r\n ' options. Pick the best path and execute. The user is asleep.',\r\n ].join('\\n');\r\n }\r\n\r\n /**\r\n * Exponential backoff for transient provider errors. `2^N * base`\r\n * capped at `transientBackoffMaxMs`. Zero base disables backoff.\r\n * Public-private to keep `runOneIteration` readable; the value is\r\n * recomputed each call from the current retry count, so callers\r\n * don't have to track state.\r\n */\r\n private computeTransientBackoffMs(): number {\r\n const base = this.opts.transientBackoffBaseMs ?? 2_000;\r\n const cap = this.opts.transientBackoffMaxMs ?? 60_000;\r\n if (base <= 0) return 0;\r\n const exponent = Math.max(0, this.consecutiveTransientRetries - 1);\r\n return Math.min(cap, base * 2 ** exponent);\r\n }\r\n\r\n /**\r\n * Sleep that wakes early if `stopRequested` flips. Polls every 250 ms\r\n * so SIGINT / `/autonomy stop` can land in the middle of a long\r\n * backoff instead of waiting up to a minute for the timer.\r\n */\r\n private async sleepInterruptible(totalMs: number): Promise<void> {\r\n const step = 250;\r\n let remaining = totalMs;\r\n while (remaining > 0 && !this.stopRequested) {\r\n const chunk = Math.min(step, remaining);\r\n await sleep(chunk);\r\n remaining -= chunk;\r\n }\r\n }\r\n\r\n private async appendIterationEntry(entry: Omit<JournalEntry, 'iteration' | 'at'>): Promise<void> {\r\n const current = await loadGoal(this.goalPath, this.opts.events);\r\n if (!current) {\r\n // Goal was cleared mid-iteration; nothing to write to.\r\n return;\r\n }\r\n const updated = appendJournal(current, entry);\r\n await saveGoal(this.goalPath, updated, this.opts.events);\r\n }\r\n\r\n /**\r\n * Persistent per-todo failure counter. Skipped silently when the goal\r\n * file has been removed (graceful clear). Each non-success iteration\r\n * against a todo source bumps the counter by 1; `pickPendingTodo` reads\r\n * the counter to rotate past stuck todos once they cross `todoMaxAttempts`.\r\n */\r\n private async bumpTodoAttempt(todoId: string): Promise<void> {\r\n const current = await loadGoal(this.goalPath, this.opts.events);\r\n if (!current) return;\r\n const attempts = { ...(current.todoAttempts ?? {}) };\r\n attempts[todoId] = (attempts[todoId] ?? 0) + 1;\r\n await saveGoal(this.goalPath, { ...current, todoAttempts: attempts }, this.opts.events);\r\n }\r\n\r\n /**\r\n * Flip the mission to `completed` and journal it. Called from two\r\n * paths: (a) `[GOAL_COMPLETE]` marker in a successful iteration's\r\n * finalText, (b) `brainstorm` returning DONE consecutively past the\r\n * configured threshold. Idempotent — re-entry is a no-op once the\r\n * goal is already `completed`.\r\n */\r\n private async markGoalCompleted(\r\n action: { source: JournalEntry['source']; task: string; directive: string },\r\n note: string,\r\n ): Promise<void> {\r\n const current = await loadGoal(this.goalPath, this.opts.events);\r\n if (!current) return;\r\n if (current.goalState === 'completed') return;\r\n const withFlag: GoalFile = { ...current, goalState: 'completed' };\r\n const withEntry = appendJournal(withFlag, {\r\n source: action.source,\r\n task: `MISSION COMPLETE — ${action.task}`.slice(0, 240),\r\n status: 'success',\r\n note: note.slice(0, 240),\r\n });\r\n await saveGoal(this.goalPath, withEntry, this.opts.events);\r\n // Fire stop callbacks so the REPL knows to exit eternal mode\r\n // and show a goal-completion banner. Without this the engine\r\n // stops internally but the REPL keeps spinning in the eternal loop.\r\n this.opts.onEternalStop?.();\r\n }\r\n\r\n /**\r\n * Manually clear the goal — equivalent to `/goal clear` typed by the user.\r\n * Sets goalState to `abandoned`, removes the goal file, and fires\r\n * `onEternalStop` so the REPL returns to normal mode.\r\n */\r\n private async clearGoalManually(note: string): Promise<void> {\r\n const current = await loadGoal(this.goalPath, this.opts.events);\r\n if (current) {\r\n const abandoned: GoalFile = { ...current, goalState: 'abandoned' };\r\n await saveGoal(this.goalPath, abandoned, this.opts.events);\r\n }\r\n try {\r\n const { unlink } = await import('node:fs/promises');\r\n await unlink(this.goalPath);\r\n } catch {\r\n // best-effort — file may already be gone\r\n }\r\n this.opts.onEternalStop?.();\r\n void this.appendIterationEntry({\r\n source: 'manual',\r\n task: 'goal cleared',\r\n status: 'success',\r\n note: note.slice(0, 240),\r\n });\r\n }\r\n\r\n private async appendFailure(task: string, note: string): Promise<void> {\r\n await this.appendIterationEntry({ source: 'manual', task, status: 'failure', note });\r\n }\r\n\r\n /**\r\n * Consult the brain on whether the goal is truly complete.\r\n * Without a brain, always returns true (use heuristic: DONE threshold met = done).\r\n */\r\n private async consultBrainForDone(goal: GoalFile): Promise<boolean> {\r\n if (!this.opts.brain) return true; // No brain — trust the heuristic\r\n\r\n const deliverablesStatus = goal.deliverables?.length\r\n ? `\\nDeliverables: ${goal.deliverables.length} total, progress ${goal.progress ?? 'unknown'}%`\r\n : '';\r\n const recentJournal = goal.journal.slice(-5).map(e =>\r\n ` #${e.iteration} [${e.status}] ${e.task}`\r\n ).join('\\n');\r\n\r\n try {\r\n const decision = await this.opts.brain.decide({\r\n id: `goal-done-${goal.iterations}`,\r\n source: 'system',\r\n question: `Brainstorm returned DONE ${this.consecutiveBrainstormDone}x. Is the goal truly complete?`,\r\n context: [\r\n `Goal: ${goal.goal}`,\r\n `Iterations: ${goal.iterations}`,\r\n `Progress: ${goal.progress ?? 'unknown'}%`,\r\n deliverablesStatus,\r\n recentJournal ? `\\nRecent work:\\n${recentJournal}` : '',\r\n ].join('\\n'),\r\n risk: 'high',\r\n fallback: 'continue',\r\n });\r\n\r\n // Log the brain decision into the journal\r\n const summary = formatDecisionSummary(decision, {\r\n id: `goal-done-${goal.iterations}`,\r\n source: 'system',\r\n question: 'Is the goal complete?',\r\n risk: 'high',\r\n fallback: 'continue',\r\n });\r\n const rationale = 'rationale' in decision ? decision.rationale : undefined;\r\n await this.appendIterationEntry({\r\n source: 'brainstorm',\r\n task: summary,\r\n status: 'success',\r\n note: rationale,\r\n });\r\n\r\n if (decision.type === 'deny') {\r\n return false;\r\n }\r\n if (decision.type === 'answer') {\r\n const text = decision.text.toLowerCase();\r\n return text.includes('complete') || text.includes('done') || text.includes('yes');\r\n }\r\n return true;\r\n } catch {\r\n return true;\r\n }\r\n }\r\n\r\n /**\r\n * Persist a progress update from the agent's [PROGRESS: N%] output.\r\n */\r\n private async updateProgress(progress: number, note?: string): Promise<void> {\r\n const current = await loadGoal(this.goalPath, this.opts.events);\r\n if (!current) return;\r\n const updated = recordProgress(current, progress, note);\r\n await saveGoal(this.goalPath, updated, this.opts.events);\r\n }\r\n\r\n private async persistEngineState(state: GoalFile['engineState']): Promise<void> {\r\n const current = await loadGoal(this.goalPath, this.opts.events);\r\n if (!current) return;\r\n if (current.engineState === state) return;\r\n await saveGoal(this.goalPath, { ...current, engineState: state }, this.opts.events);\r\n }\r\n}\r\n","import type { Usage } from '../types/provider.js';\nimport type { EventBus } from '../kernel/events.js';\n\nexport type BudgetKind = 'tool_calls' | 'iterations' | 'tokens' | 'timeout' | 'idle_timeout' | 'cost';\n\n/**\n * Fraction of the wall-clock `timeoutMs` window at which a PROACTIVE extension\n * is negotiated — BEFORE the deadline is actually crossed. The coordinator\n * watchdog (`executeWithTimeout`) arms at `timeoutMs * TIMEOUT_PREEMPT_FRACTION`\n * so a still-progressing subagent gets its ceiling raised while it is below the\n * limit, and never enters a \"timed out\" state. Reactive enforcement at the real\n * deadline still stands for the no-progress / denied case. Shared so the asking\n * side and any future caller agree on the same lead point.\n */\nexport const TIMEOUT_PREEMPT_FRACTION = 0.85;\n\n/**\n * Hard safety net for budget negotiation decisions. If no listener responds to\n * `budget.threshold_reached` within this window the negotiation defaults to\n * `'stop'`. Exported so the coordinator's watchdog can reuse the same ceiling\n * without hardcoding a second copy.\n */\nexport const DECISION_TIMEOUT_MS = 60_000;\n\nexport class BudgetExceededError extends Error {\n readonly kind: BudgetKind;\n readonly limit: number;\n readonly observed: number;\n\n constructor(kind: BudgetKind, limit: number, observed: number) {\n super(`Budget exceeded: ${kind} (limit=${limit}, observed=${observed})`);\n this.name = 'BudgetExceededError';\n this.kind = kind;\n this.limit = limit;\n this.observed = observed;\n }\n}\n\nexport interface BudgetLimits {\n maxIterations?: number | undefined;\n maxToolCalls?: number | undefined;\n maxTokens?: number | undefined;\n /** Estimated USD cost ceiling. */\n maxCostUsd?: number | undefined;\n /**\n * Hard wall-clock timeout measured from `start()`. Off by default — set it\n * explicitly only when a task must finish within an absolute window. For\n * the everyday \"don't kill an agent that's still working\" guard, prefer\n * `idleTimeoutMs`, which resets on activity.\n */\n timeoutMs?: number | undefined;\n /**\n * Idle timeout: the maximum gap (ms) between activity signals (iterations,\n * tool calls, token usage, streamed progress) before the subagent is\n * considered hung and reaped. Unlike `timeoutMs`, an actively-working\n * agent continuously resets this clock via `markActivity()`, so it never\n * trips on a long-but-productive run — only on a genuine stall.\n */\n idleTimeoutMs?: number | undefined;\n}\n\n/**\n * Controls how the budget behaves when `onThreshold` is set and a limit is hit.\n *\n * `'auto'` — emit `budget.threshold_reached` on the EventBus and wait for a\n * coordinator response (extend/stop). If no listener responds within\n * `DECISION_TIMEOUT_MS` the decision defaults to `'stop'`.\n * `'sync'` — do not emit any event; treat the threshold as a hard stop and\n * throw `BudgetExceededError` synchronously. Useful for fire-and-forget\n * subagents that have an `onThreshold` handler for logging/metrics but are\n * not wired into a coordinator.\n *\n * @default 'auto'\n */\nexport type BudgetNegotiationMode = 'auto' | 'sync';\n\nexport interface BudgetUsage {\n iterations: number;\n toolCalls: number;\n tokens: { input: number; output: number; total: number };\n costUsd: number;\n elapsedMs: number;\n}\n\n/**\n * Thrown by `SubagentBudget.record*` when a soft limit is hit and\n * an `onThreshold` handler is configured that wants to ask the\n * coordinator (via `budget.threshold_reached` event). The runner\n * catches this and awaits the embedded `decision` promise to get\n * the coordinator's extend/stop decision.\n *\n * Distinct from `BudgetExceededError` which is a hard stop.\n */\nexport class BudgetThresholdSignal extends Error {\n readonly kind: BudgetKind;\n readonly limit: number;\n readonly used: number;\n /** Resolves to 'extend' (with optional new limits) or 'stop' */\n readonly decision: Promise<BudgetThresholdDecision>;\n\n constructor(\n kind: BudgetKind,\n limit: number,\n used: number,\n decision: Promise<BudgetThresholdDecision>,\n ) {\n super(`Budget soft limit: ${kind} (limit=${limit}, used=${used})`);\n this.name = 'BudgetThresholdSignal';\n this.kind = kind;\n this.limit = limit;\n this.used = used;\n this.decision = decision;\n }\n}\n\nexport type BudgetThresholdDecision =\n | 'stop'\n | { extend: Partial<BudgetLimits> };\n\n/**\n * Callback invoked when a budget limit is about to be exceeded.\n * Return 'throw' for hard stop (default — throws BudgetExceededError).\n * Return 'continue' to allow one more unit and re-check next time.\n * Return a Promise to ask the coordinator via `budget.threshold_reached`\n * event (uses the same grant/deny pattern as `iteration.limit_reached`).\n */\nexport type BudgetThresholdHandler = (info: {\n kind: BudgetKind;\n used: number;\n limit: number;\n requestDecision: () => Promise<BudgetThresholdDecision>;\n /**\n * Direct grant/deny hooks for SYNCHRONOUS policy or recording handlers that\n * decide in-process without a wired `budget.threshold_reached` listener\n * (e.g. the coordinator watchdog). `extend` patches the limits in place;\n * `deny` records the intent to stop. Production listener-driven handlers use\n * `requestDecision()` instead and can ignore these.\n */\n extend?: (extra: Partial<BudgetLimits>) => void;\n deny?: () => void;\n}) => 'throw' | 'continue' | 'stop' | { extend: Partial<BudgetLimits> } | Promise<BudgetThresholdDecision>;\n\n/**\n * Per-subagent budget enforcement. Each subagent gets its own instance so a\n * runaway agent can't drain the cost ceiling of its siblings. All record/check\n * methods are O(1) and safe to call from hot paths.\n *\n * Behavior without `onThreshold`: hard stops synchronously on every limit hit.\n *\n * Behavior with `onThreshold` and `_mode === 'auto'`: emits `budget.threshold_reached`\n * on the EventBus and throws `BudgetThresholdSignal`. The coordinator's verdict\n * (extend/stop) resolves the embedded promise. If no listener responds within\n * `DECISION_TIMEOUT_MS` the decision defaults to `'stop'`.\n *\n * Behavior with `onThreshold` and `_mode === 'sync'`: throws `BudgetExceededError`\n * synchronously regardless of EventBus state or listener presence. This is useful\n * for fire-and-forget subagents that have an `onThreshold` handler for logging/metrics\n * but are not wired into a coordinator — the `'sync'` mode makes the hard-stop\n * behavior explicit and means tests can use `expect().toThrow()` even without\n * a fully-wired EventBus.\n */\nexport class SubagentBudget {\n readonly limits: Readonly<BudgetLimits>;\n\n /** Patch one or more budget limits in-place after construction.\n * Used by the coordinator watchdog when granting an extension.\n * All fields are optional — only provided fields are updated.\n * This is the single write path for limit mutations so that future\n * validation or side-effects live in one place (M1). */\n patchLimits(ext: Partial<BudgetLimits>): void {\n if (ext.maxIterations !== undefined) {\n (this.limits as Record<string, unknown>).maxIterations = ext.maxIterations;\n }\n if (ext.maxToolCalls !== undefined) {\n (this.limits as Record<string, unknown>).maxToolCalls = ext.maxToolCalls;\n }\n if (ext.maxTokens !== undefined) {\n (this.limits as Record<string, unknown>).maxTokens = ext.maxTokens;\n }\n if (ext.maxCostUsd !== undefined) {\n (this.limits as Record<string, unknown>).maxCostUsd = ext.maxCostUsd;\n }\n if (ext.timeoutMs !== undefined) {\n (this.limits as Record<string, unknown>).timeoutMs = ext.timeoutMs;\n }\n if (ext.idleTimeoutMs !== undefined) {\n (this.limits as Record<string, unknown>).idleTimeoutMs = ext.idleTimeoutMs;\n }\n }\n private iterations = 0;\n private toolCalls = 0;\n private tokenInput = 0;\n private tokenOutput = 0;\n private costUsd = 0;\n private startTime: number | null = null;\n /**\n * Timestamp of the most recent activity (iteration / tool call / token\n * usage / streamed progress). Drives the idle timeout — reset by\n * `markActivity()`. Initialised to `start()` time so a never-active agent\n * still eventually trips its idle window.\n */\n private lastActivityTime: number | null = null;\n private _onThreshold: BudgetThresholdHandler | undefined;\n /**\n * Hard cap on how long `_negotiateExtension` waits for the coordinator to\n * respond before defaulting to 'stop'. Without this fallback an absent\n * or hung listener (Director not built / event filter detached mid-run)\n * leaves the budget over-limit and never enforces anything.\n */\n private static readonly DECISION_TIMEOUT_MS = DECISION_TIMEOUT_MS;\n /**\n * Injected by the runner when wiring the budget to its EventBus.\n * Used to emit `budget.threshold_reached` events in `'auto'` mode.\n */\n _events?: EventBus | undefined;\n\n /**\n * Guard against dual-path races between the coordinator watchdog\n * (`executeWithTimeout`) and the budget's own `checkTimeout()`.\n * Both paths detect `elapsed >= timeoutMs` and can emit\n * `budget.threshold_reached` for kind `'timeout'` simultaneously.\n * Set to the current `timeoutMs` ceiling by the coordinator BEFORE\n * calling `onThreshold`, and cleared after the negotiation resolves.\n * `checkTimeout()` skips its wall-clock check while this is set so\n * the coordinator's watchdog is the sole source of wall-clock timeout\n * events — `checkTimeout()` focuses exclusively on `idle_timeout`.\n */\n private _watchdogActive: number | undefined;\n\n /** Returns the timeout ceiling currently being negotiated by the watchdog,\n * or `undefined` when no wall-clock negotiation is in flight.\n * Used by `executeWithTimeout` to detect a stale lock (M3). */\n get watchdogActive(): number | undefined { return this._watchdogActive; }\n\n /** Called by the coordinator watchdog BEFORE calling `onThreshold` so that\n * `checkTimeout()` skips its wall-clock check for this ceiling. Prevents\n * the budget's own `checkTimeout()` from emitting a second\n * `budget.threshold_reached` event while the watchdog is already\n * negotiating the same wall-clock deadline (C1). */\n setWatchdogNegotiation(timeoutMs: number): void { this._watchdogActive = timeoutMs; }\n\n /** Clears the watchdog guard after negotiation resolves. Called in the\n * `finally` block of both the pre-empt and deadline branches so it fires\n * on every exit path: grant, deny, throw, or error. */\n clearWatchdogNegotiation(): void { this._watchdogActive = undefined; }\n\n /**\n * Negotiation mode — controls whether a threshold hit tries to emit\n * `budget.threshold_reached` and wait for a coordinator decision, or\n * falls straight through to a synchronous hard stop.\n *\n * `'auto'` (default) — emit on the EventBus and wait; times out to 'stop'.\n * `'sync'` — throw `BudgetExceededError` immediately regardless of listeners.\n */\n private _mode: BudgetNegotiationMode;\n\n /**\n * Optional callback for soft-limit handling. When set, the budget will\n * invoke it rather than throw immediately. The handler decides whether to\n * throw synchronously, continue, or ask the coordinator for an extension.\n */\n get onThreshold(): BudgetThresholdHandler | undefined {\n return this._onThreshold;\n }\n set onThreshold(fn: BudgetThresholdHandler | undefined) {\n this._onThreshold = fn;\n }\n\n /** Returns the current negotiation mode. */\n get mode(): BudgetNegotiationMode {\n return this._mode;\n }\n\n constructor(limits: BudgetLimits = {}, mode: BudgetNegotiationMode = 'auto') {\n this._mode = mode;\n // NOT frozen: `negotiateExtension` patches these limits in place when the\n // coordinator grants an auto-extension. Freezing made every granted\n // extension throw `TypeError: Cannot assign to read only property` in\n // strict mode, which the runner caught as a hard stop — so extensions\n // silently became kills. The `readonly limits: Readonly<BudgetLimits>`\n // typing still blocks external mutation at compile time.\n this.limits = { ...limits };\n }\n\n start(): void {\n this.startTime = Date.now();\n this.lastActivityTime = this.startTime;\n }\n\n /**\n * Reset the idle clock. Called on any sign of forward progress —\n * iterations, tool calls, token usage, and streamed tool/text progress —\n * so a long-but-productive subagent never trips its `idleTimeoutMs`.\n */\n markActivity(): void {\n this.lastActivityTime = Date.now();\n }\n\n /**\n * Milliseconds since the last activity signal. Returns 0 before `start()`\n * (nothing to measure yet). Used by the coordinator watchdog to decide\n * whether to re-arm (still active) or reap (genuinely idle).\n */\n idleMs(): number {\n const since = this.lastActivityTime ?? this.startTime;\n return since === null ? 0 : Date.now() - since;\n }\n\n /** Returns true if we're within 10% of any limit — useful for pre-flight checks. */\n isNearLimit(): boolean {\n const { maxIterations, maxToolCalls, maxTokens, maxCostUsd } = this.limits;\n if (maxIterations && this.iterations >= maxIterations * 0.9) return true;\n if (maxToolCalls && this.toolCalls >= maxToolCalls * 0.9) return true;\n if (maxTokens && this.tokenInput + this.tokenOutput >= maxTokens * 0.9) return true;\n if (maxCostUsd && this.costUsd >= maxCostUsd * 0.9) return true;\n return false;\n }\n\n /**\n * Synchronous budget check. Always throws synchronously so callers (especially\n * test event handlers using `expect().toThrow()`) get an unhandled rejection\n * when the budget is exceeded without a handler.\n *\n * Decision table:\n * - no `onThreshold` handler → throw `BudgetExceededError` (hard stop, always)\n * - `mode === 'sync'` → throw `BudgetExceededError` (hard stop, always)\n * - `mode === 'auto'` + no listener → throw `BudgetExceededError` (hard stop; no one to ask)\n * - `mode === 'auto'` + listener → throw `BudgetThresholdSignal` with async decision promise\n */\n /**\n * Collects all exceeded budget kinds into a single NOOP-free negotiation.\n * Called by recordIteration / recordToolCall / recordUsage — each may call\n * this for its own kind. The first call starts the negotiation and stores\n * the Promise in _pendingNegotiation. Subsequent calls for DIFFERENT\n * kinds (while a negotiation is in flight) are NOOPs — they don't start\n * new conversations with the coordinator. This prevents an EventBus flood\n * when multiple budget kinds are exceeded simultaneously in one iteration.\n *\n * Returns the kinds that were found to be exceeded (for logging/debugging).\n */\n private checkLimits(elapsedMs?: number): { kind: BudgetKind; used: number; limit: number }[] {\n const exceeded: { kind: BudgetKind; used: number; limit: number }[] = [];\n\n if (this.limits.maxIterations !== undefined && this.iterations > this.limits.maxIterations) {\n exceeded.push({ kind: 'iterations', used: this.iterations, limit: this.limits.maxIterations });\n }\n if (this.limits.maxToolCalls !== undefined && this.toolCalls > this.limits.maxToolCalls) {\n exceeded.push({ kind: 'tool_calls', used: this.toolCalls, limit: this.limits.maxToolCalls });\n }\n const totalTokens = this.tokenInput + this.tokenOutput;\n if (this.limits.maxTokens !== undefined && totalTokens > this.limits.maxTokens) {\n exceeded.push({ kind: 'tokens', used: totalTokens, limit: this.limits.maxTokens });\n }\n if (this.limits.maxCostUsd !== undefined && this.costUsd > this.limits.maxCostUsd) {\n exceeded.push({ kind: 'cost', used: this.costUsd, limit: this.limits.maxCostUsd });\n }\n // Timeout: called from checkTimeout() with elapsedMs (wall-clock) and the\n // current idle gap. Either crossing its limit trips its own kind so the\n // coordinator and auto-extend policy can distinguish them.\n // Wall-clock (`timeoutMs`) is an explicit hard cap; idle (`idleTimeoutMs`)\n // is the default guard that resets on activity. Both can be exceeded in\n // the same call — we push both entries so all violated limits are reported.\n if (elapsedMs !== undefined) {\n const idle = this.idleMs();\n if (this.limits.idleTimeoutMs !== undefined && idle > this.limits.idleTimeoutMs) {\n exceeded.push({ kind: 'idle_timeout', used: idle, limit: this.limits.idleTimeoutMs });\n }\n // Skip the wall-clock 'timeout' kind while the coordinator watchdog is\n // negotiating this exact ceiling — it owns wall-clock; checkTimeout/here\n // own idle. Only suppress in the negotiation path (a handler is set); on\n // the no-handler hard-throw path the wall-clock must still trip. (Mirrors\n // the guard in checkTimeout, which previously was NOT applied here — so\n // an idle trip that called checkLimits re-added 'timeout' and defeated the\n // watchdog dedup.)\n const wallOwnedByWatchdog =\n this._onThreshold !== undefined && this._watchdogActive === this.limits.timeoutMs;\n if (\n this.limits.timeoutMs !== undefined &&\n elapsedMs > this.limits.timeoutMs &&\n !wallOwnedByWatchdog\n ) {\n exceeded.push({ kind: 'timeout', used: elapsedMs, limit: this.limits.timeoutMs });\n }\n }\n\n if (exceeded.length === 0) return [];\n\n if (!this._onThreshold) {\n // Hard stop — throw on the first exceeded kind.\n const first = exceeded[0] ?? { kind: 'iterations', limit: 0, used: 0 };\n throw new BudgetExceededError(first.kind, first.limit, first.used);\n }\n if (this._mode === 'sync') {\n // Hard stop in sync mode.\n const first = exceeded[0] ?? { kind: 'iterations', limit: 0, used: 0 };\n throw new BudgetExceededError(first.kind, first.limit, first.used);\n }\n const bus = this._events;\n if (!bus) {\n // No EventBus wired at all → nobody to negotiate with → hard stop.\n const first = exceeded[0] ?? { kind: 'iterations', limit: 0, used: 0 };\n throw new BudgetExceededError(first.kind, first.limit, first.used);\n }\n\n const first = exceeded[0] ?? { kind: 'iterations', limit: 0, used: 0 };\n\n // LISTENER-DRIVEN PATH. A registered `budget.threshold_reached` listener\n // (director / collab / auto-extend) negotiates asynchronously. Start one\n // negotiation PER exceeded kind — each reports its OWN kind/used/limit and\n // emits a single event (no O(N^2) re-emission, no cross-kind first-wins\n // drop). Throw `BudgetThresholdSignal` for the first kind so the runner\n // awaits the decision and enforces extend/stop.\n if (bus.hasListenerFor('budget.threshold_reached')) {\n for (const entry of exceeded) {\n if (this._pendingNegotiations.has(entry.kind)) continue; // already negotiating this kind\n this._pendingNegotiations.set(entry.kind, this._negotiateExtension(entry));\n }\n const decision = this._pendingNegotiations.get(first.kind);\n if (!decision) throw new Error(`No pending negotiation for ${first.kind}`);\n throw new BudgetThresholdSignal(first.kind, first.limit, first.used, decision);\n }\n\n // NO-LISTENER PATH. Invoke the handler synchronously to let an in-process\n // policy decide. Two outcomes:\n // • SYNC handler (returns a string/decision — e.g. the coordinator\n // watchdog / recording handlers) → its decision is honored in place\n // (an `extend` patches limits); no throw. This is the path the\n // watchdog drives while it owns wall-clock enforcement.\n // • ASYNC handler (returns a Promise via `requestDecision()`) → there is\n // no listener to resolve it and `requestDecision` resolves to 'stop',\n // so this is a definite hard stop: throw `BudgetExceededError`. This is\n // the documented \"auto mode + no listener → hard stop\" invariant that\n // protects a bare `/spawn` (no director) from a runaway subagent.\n let hardStop: BudgetExceededError | null = null;\n for (const entry of exceeded) {\n // Dedup per kind across back-to-back overruns in the same tick — a still\n // exceeded kind (e.g. iterations stays over after a grant) must not\n // re-invoke the handler on every record* call. The marker clears on a\n // microtask so a genuinely fresh overrun later can re-negotiate.\n if (this._pendingNegotiations.has(entry.kind)) continue;\n const marker = Promise.resolve<BudgetThresholdDecision>('stop');\n this._pendingNegotiations.set(entry.kind, marker);\n void marker.finally(() => this._pendingNegotiations.delete(entry.kind));\n const sync = this._invokeHandlerSync(entry);\n if (!sync) hardStop ??= new BudgetExceededError(entry.kind, entry.limit, entry.used);\n }\n if (hardStop) throw hardStop;\n return exceeded;\n }\n\n /**\n * Invoke `onThreshold` once for `entry` on the NO-LISTENER path and report\n * whether it decided synchronously. Returns `true` when the handler returned\n * a synchronous decision (already honored — an `extend` patched the limits),\n * or `false` when it returned a Promise (async; the caller hard-stops, since\n * there is no listener to resolve the negotiation). The handler is given the\n * full info shape (`requestDecision` plus direct `extend`/`deny`) so both\n * recording handlers and policy handlers work without a wired listener.\n */\n private _invokeHandlerSync(entry: { kind: BudgetKind; used: number; limit: number }): boolean {\n const handler = this._onThreshold;\n if (!handler) return false;\n let extendArg: Partial<BudgetLimits> | undefined;\n const result = handler({\n kind: entry.kind,\n used: entry.used,\n limit: entry.limit,\n requestDecision: (): Promise<BudgetThresholdDecision> => this._busRequestDecision(entry),\n // Direct hooks for synchronous policy/recording handlers.\n extend: (extra: Partial<BudgetLimits>) => {\n extendArg = extra;\n },\n deny: () => {},\n } as Parameters<BudgetThresholdHandler>[0]);\n // A thenable means the handler deferred to async negotiation — but there is\n // no listener here, so it can never be granted → hard stop.\n if (result && typeof (result as { then?: unknown }).then === 'function') return false;\n if (result === 'throw') return false; // explicit hard stop\n // 'continue' / 'stop' / a returned { extend } decision — honor in place.\n if (result && typeof result === 'object' && 'extend' in result) {\n extendArg = (result as { extend: Partial<BudgetLimits> }).extend;\n }\n if (extendArg) this.patchLimits(extendArg);\n return true;\n }\n\n /**\n * Emit `budget.threshold_reached` and resolve to the listener's verdict.\n * Resolves to `'stop'` immediately when there is no listener (or no bus) so\n * no negotiation can hang and no fallback timer leaks. Mirrors the\n * coordinator watchdog's own request path so both agree on the no-listener\n * default.\n */\n private _busRequestDecision(entry: {\n kind: BudgetKind;\n used: number;\n limit: number;\n }): Promise<BudgetThresholdDecision> {\n const bus = this._events;\n if (!bus?.hasListenerFor('budget.threshold_reached')) {\n return Promise.resolve('stop');\n }\n return new Promise<BudgetThresholdDecision>((resolve) => {\n let resolved = false;\n const respond = (d: BudgetThresholdDecision) => {\n if (resolved) return;\n resolved = true;\n clearTimeout(fallback);\n resolve(d);\n };\n const fallback = setTimeout(() => respond('stop'), SubagentBudget.DECISION_TIMEOUT_MS);\n bus.emit('budget.threshold_reached', {\n kind: entry.kind as\n | 'iterations'\n | 'tool_calls'\n | 'tokens'\n | 'cost'\n | 'timeout'\n | 'idle_timeout',\n used: entry.used,\n limit: entry.limit,\n timeoutMs: SubagentBudget.DECISION_TIMEOUT_MS,\n // deny() wins over a same-dispatch extend(): a listener that both grants\n // and denies (or two listeners disagreeing) is resolved as a stop. The\n // grant is deferred a microtask so a synchronous deny in the same emit\n // pre-empts it; async grants still resolve normally.\n extend: (extra: Partial<BudgetLimits>) => queueMicrotask(() => respond({ extend: extra })),\n deny: () => respond('stop'),\n });\n });\n }\n\n /**\n * Per-kind in-flight negotiation Promises. Each budget kind can have its\n * own concurrent negotiation — e.g. iterations and timeout can both\n * be exceeded simultaneously without blocking each other. The same kind\n * cannot start two concurrent negotiations (dedup guard).\n * Cleared in `_negotiateExtension`'s `finally` block.\n */\n private _pendingNegotiations = new Map<BudgetKind, Promise<BudgetThresholdDecision>>();\n\n /**\n * Drive the threshold handler to a decision. Resolves with `'stop'`\n * (signal the runner to abort) or `{ extend: ... }` (limits already\n * patched in-place; the runner should not abort). Clears the\n * per-kind slot in `_pendingNegotiations` in `finally`.\n *\n * The 'continue' return from a sync handler is treated as\n * `{ extend: {} }` — keep going without patching; next overrun fires\n * a fresh signal.\n */\n private async _negotiateExtension(\n entry: { kind: BudgetKind; used: number; limit: number },\n ): Promise<BudgetThresholdDecision> {\n if (!this._onThreshold) {\n // Should never reach here — caller should have thrown already\n return 'stop';\n }\n try {\n const result = this._onThreshold({\n kind: entry.kind,\n used: entry.used,\n limit: entry.limit,\n // One event for THIS kind only — each exceeded kind has its own\n // negotiation (and its own resolve), so there is no cross-kind\n // first-wins drop and no O(N^2) re-emission.\n requestDecision: (): Promise<BudgetThresholdDecision> => this._busRequestDecision(entry),\n extend: (extra: Partial<BudgetLimits>) => {\n this.patchLimits(extra);\n },\n deny: () => {},\n } as Parameters<BudgetThresholdHandler>[0]);\n\n if (result === 'throw') return 'stop';\n if (result === 'continue') return { extend: {} };\n\n const decision = await result;\n if (decision === 'stop') return 'stop';\n\n // 'extend' — patch in-place limits BEFORE resolving (single write path).\n this.patchLimits(decision.extend);\n return decision;\n } finally {\n this._pendingNegotiations.delete(entry.kind);\n }\n }\n\n recordIteration(): void {\n this.iterations++;\n this.markActivity();\n void this.checkLimits();\n }\n\n recordToolCall(): void {\n this.toolCalls++;\n this.markActivity();\n void this.checkLimits();\n }\n\n recordUsage(usage: Usage, costUsd = 0): void {\n this.tokenInput += usage.input;\n this.tokenOutput += usage.output;\n this.costUsd += costUsd;\n this.markActivity();\n void this.checkLimits();\n }\n\n /**\n * Wall-clock / idle budget check. Delegates to `checkLimits(elapsed)`, so\n * `timeout` and `idle_timeout` follow the SAME negotiation path as the other\n * kinds — they are NOT a special-cased hard stop. This is deliberate: a\n * heartbeat-aware policy (see `attachAutoExtend` and `CollabSession`) grants\n * a timeout extension only while the agent is making progress and denies it\n * once the agent is genuinely stuck, which is safer than an unconditional\n * hard kill of a long-but-working agent. The runner translates the resulting\n * `BudgetThresholdSignal` decision (`extend` → patch limits in place,\n * `stop` → abort) just like every other kind.\n *\n * Decision table (same as `checkLimits`):\n * - no `onThreshold` handler → throw `BudgetExceededError` (hard stop)\n * - `mode === 'sync'` → throw `BudgetExceededError` (hard stop)\n * - `mode === 'auto'` + no listener → throw `BudgetExceededError` (no one to ask)\n * - `mode === 'auto'` + listener → throw `BudgetThresholdSignal` (negotiated;\n * a heartbeat-aware policy may extend the timeout)\n */\n checkTimeout(): void {\n if (this.startTime === null) return;\n const { timeoutMs, idleTimeoutMs } = this.limits;\n if (timeoutMs === undefined && idleTimeoutMs === undefined) return;\n const elapsed = Date.now() - this.startTime;\n // Skip wall-clock timeout if the coordinator watchdog is already in the middle\n // of negotiating this exact ceiling — tool.progress is too frequent and creates\n // a race where both paths emit budget.threshold_reached for the same kind.\n // The watchdog owns wall-clock; checkTimeout focuses exclusively on idle.\n const wallSkipped =\n this._onThreshold !== undefined &&\n this._watchdogActive !== undefined &&\n timeoutMs !== undefined &&\n this._watchdogActive === timeoutMs;\n const wallTripped = wallSkipped ? false : timeoutMs !== undefined && elapsed > timeoutMs;\n const idleTripped = idleTimeoutMs !== undefined && this.idleMs() > idleTimeoutMs;\n if (!wallTripped && !idleTripped) return;\n void this.checkLimits(elapsed);\n }\n\n /** Returns true if a wall-clock or idle timeout has occurred without throwing. */\n isTimedOut(): boolean {\n if (this.startTime === null) return false;\n const { timeoutMs, idleTimeoutMs } = this.limits;\n if (timeoutMs !== undefined && Date.now() - this.startTime > timeoutMs) return true;\n if (idleTimeoutMs !== undefined && this.idleMs() > idleTimeoutMs) return true;\n return false;\n }\n\n usage(): BudgetUsage {\n return {\n iterations: this.iterations,\n toolCalls: this.toolCalls,\n tokens: {\n input: this.tokenInput,\n output: this.tokenOutput,\n total: this.tokenInput + this.tokenOutput,\n },\n costUsd: this.costUsd,\n elapsedMs: this.startTime === null ? 0 : Date.now() - this.startTime,\n };\n }\n}\n","import type { Agent, AgentInput, RunResult } from '../core/agent.js';\nimport type { EventBus } from '../kernel/events.js';\nimport type {\n SubagentConfig,\n SubagentRunContext,\n SubagentRunOutcome,\n SubagentRunner,\n TaskSpec,\n} from '../types/multi-agent.js';\nimport { AgentError, ERROR_CODES } from '../types/errors.js';\nimport {\n BudgetExceededError,\n BudgetThresholdSignal,\n} from './subagent-budget.js';\nimport type { FleetBus } from './fleet-bus.js';\n\n/**\n * Caller-supplied factory that builds an isolated `Agent` for a subagent.\n * The factory MUST construct a fresh `Context` per call — sharing context\n * between subagents defeats isolation. Each Agent should also use either\n * its own `EventBus` or a forwarded view, so per-subagent metrics can be\n * attributed correctly.\n */\nexport type AgentFactory = (config: SubagentConfig) => Promise<AgentFactoryResult>;\n\n/**\n * Wrap a factory to automatically filter out disabled tools from subagent\n * configurations. This provides mechanical enforcement of tool restrictions\n * (e.g., preventing delegation) in addition to the baseline prompt constraint.\n *\n * The wrapper reads `config.disabledTools` and removes those tools from the\n * agent's tool registry before returning.\n *\n * Usage:\n * const filteredFactory = withDisabledToolFiltering(originalFactory);\n * const runner = makeAgentSubagentRunner({ factory: filteredFactory });\n */\nexport function withDisabledToolFiltering(factory: AgentFactory): AgentFactory {\n return async (config: SubagentConfig) => {\n const result = await factory(config);\n const disabled = config.disabledTools ?? [];\n if (disabled.length === 0) return result;\n\n // Agent.tools is a ToolRegistry with unregister() method\n const registry = result.agent.tools;\n if (registry && typeof registry.unregister === 'function') {\n for (const toolName of disabled) {\n registry.unregister(toolName);\n }\n }\n return result;\n };\n}\n\nexport interface AgentFactoryResult {\n agent: Agent;\n /** Event bus the factory wired to this agent — required for budget hookup. */\n events: EventBus;\n /**\n * Optional cleanup hook invoked in the runner's `finally` block once\n * the task ends (success, failure, abort — same exit path). Factories\n * that own resources scoped to a single task (per-subagent JSONL\n * writers, transient providers, throwaway containers) implement this\n * to close them deterministically instead of relying on GC. Errors\n * thrown here are swallowed so a flaky cleanup can't mask the task's\n * real result.\n */\n dispose?: ((() => Promise<void> | void)) | undefined;\n}\n\nexport interface AgentRunnerOptions {\n factory: AgentFactory;\n /**\n * Format a TaskSpec into the user input the agent will receive. Defaults\n * to `task.description ?? ''`. Override when subagents expect structured\n * input (e.g. JSON contracts, role-prefixed prompts).\n */\n formatTaskInput?: (task: TaskSpec, config: SubagentConfig) => AgentInput;\n /**\n * When set, the runner attaches the subagent's EventBus to this FleetBus\n * on task start and detaches it when the task finishes. This is the\n * injection seam that lets the TUI fleet panel observe subagent activity\n * live — without it, FleetBus stays empty.\n */\n fleetBus?: FleetBus | undefined;\n}\n\n/**\n * Builds a `SubagentRunner` that drives a real `Agent` per task while honoring\n * the coordinator's budget and abort signal. This is the production adapter —\n * the coordinator's `runner` option in CLI/TUI assemblies points here.\n *\n * Lifecycle per task:\n * 1. factory(config) → fresh Agent + EventBus.\n * 2. Subscribe to events to feed the budget (tool calls, token usage).\n * 3. Call agent.run(input, { signal }) — the coordinator's signal cancels.\n * 4. Map RunResult.status onto a `SubagentRunOutcome` or throw on failure.\n * 5. Unsubscribe and let the factory's resources be GC'd.\n *\n * The budget is checked synchronously from event handlers — a runaway agent\n * that crosses its tool-call limit triggers `BudgetExceededError`, which the\n * coordinator surfaces as `status: 'failed'` on the task result.\n */\nexport function makeAgentSubagentRunner(opts: AgentRunnerOptions): SubagentRunner {\n const format = opts.formatTaskInput ?? defaultFormatTaskInput;\n\n return async (task: TaskSpec, ctx: SubagentRunContext): Promise<SubagentRunOutcome> => {\n const taskStartedAt = Date.now();\n const factoryResult = await opts.factory(ctx.config);\n const { agent, events } = factoryResult;\n\n // Attach subagent EventBus to FleetBus so the TUI fleet panel (and any\n // other FleetBus subscriber) can observe this subagent live. Detach on\n // task finish — each task is a fresh Agent + EventBus, so we never\n // want a stale bus lingering after the run.\n const detachFleet = opts.fleetBus?.attach(ctx.subagentId, events, task.id);\n\n // Hook budget into the agent's event stream. We capture errors thrown by\n // recordToolCall/recordUsage so the budget can short-circuit the run by\n // aborting the controller — the agent then unwinds cooperatively.\n const aborter = new AbortController();\n // Inject the EventBus into the budget so it can emit budget.threshold_reached\n // events when a soft limit is hit and the handler wants to ask the coordinator.\n ctx.budget._events = events;\n // Wire the threshold-negotiation handler. Without this the soft-limit\n // path is dead code: every budget overrun becomes a hard\n // BudgetExceededError and the subagent dies on its first 120-iteration\n // tick instead of asking the Director for headroom. The Director's\n // FleetBus listener (director.ts) auto-grants +50% up to a per-kind\n // ceiling and per-subagent extension count — wiring this is the\n // missing link that activates that flow.\n ctx.budget.onThreshold = ({ requestDecision }) => requestDecision();\n let budgetError: Error | null = null;\n\n /**\n * Common error handler for all budget-triggered events. Distinguishes:\n * - BudgetExceededError → hard stop, set budgetError + abort\n * - BudgetThresholdSignal → soft stop: await the coordinator's\n * decision. If 'stop', abort. If 'extend', the signal handler\n * has already patched the budget so we can continue without\n * actually aborting the agent.\n */\n const onBudgetError = (err: unknown): void => {\n if (err instanceof BudgetThresholdSignal) {\n // Defer the stop/extend decision to the post-finally block below.\n // The coordinator's verdict may arrive after agent.run() returns;\n // awaiting it there (rather than in this fire-and-forget handler)\n // avoids a race where both this callback and the post-finally\n // block try to mutate `budgetError` concurrently.\n budgetError = err;\n return;\n }\n // Hard stop (BudgetExceededError or other)\n aborter.abort();\n budgetError =\n err instanceof BudgetExceededError\n ? err\n : new BudgetExceededError(\n 'tool_calls',\n 0,\n 0,\n );\n // Attach the real error detail so the task result surfaces\n // something actionable instead of a generic budget message.\n if (budgetError !== err && err instanceof Error) {\n budgetError.message += ` (caused by: ${err.message})`;\n }\n };\n\n // Track the name of the most recent tool that returned ok:false so\n // we can lift it into the SubagentError when the agent ends without\n // recovering. Cleared on every successful tool execution so a tool\n // that later succeeded doesn't taint the final report.\n let lastToolFailed: string | null = null;\n\n const unsub: Array<() => void> = [];\n unsub.push(\n events.on('tool.executed', (e) => {\n // Count tool calls on the PAIRED 'tool.executed' event rather\n // than 'tool.started'. A tool can fire start then crash before\n // emitting executed (process killed, signal aborted mid-exec);\n // counting only the paired event keeps the budget tally honest\n // and matches what the model actually saw in its turn.\n try {\n ctx.budget.recordToolCall();\n } catch (eb) {\n onBudgetError(eb);\n }\n // Track ok:false so we can fail the subagent if it ends without\n // recovering. Successful runs clear it — the model may try a\n // tool, get an error, and self-heal on the next iteration; that\n // path should still report success.\n if (e.ok === false) {\n lastToolFailed = e.name;\n } else if (e.ok === true) {\n lastToolFailed = null;\n }\n }),\n events.on('provider.response', (e) => {\n try {\n ctx.budget.recordUsage(e.usage);\n } catch (e2) {\n void onBudgetError(e2);\n }\n }),\n events.on('iteration.started', () => {\n try {\n ctx.budget.recordIteration();\n } catch (e) {\n void onBudgetError(e);\n }\n // Emit a periodic progress snapshot every SUMMARY_INTERVAL\n // iterations so the leader can surface \"AGENT#2 ● L25 · 47 tools\"\n // in the main chat history without needing the FleetPanel open.\n const u = ctx.budget.usage();\n const since = u.iterations - lastSummaryAtIteration;\n if (since >= SUMMARY_INTERVAL) {\n lastSummaryAtIteration = u.iterations;\n events.emit('subagent.iteration_summary', {\n subagentId: ctx.subagentId,\n iteration: u.iterations,\n toolCalls: u.toolCalls,\n costUsd: u.costUsd,\n currentTool: currentToolName,\n partialText: streamingTextAcc.trim() || undefined,\n });\n }\n }),\n // D3: cooperative timeout enforcement DURING a long tool call.\n // The iteration-loop checkTimeout() only fires between agent\n // iterations — a single `bash sleep 3600` call would otherwise\n // park inside one tool execution while the timeout silently\n // passes, relying solely on the coordinator's hard Promise.race\n // to interrupt. Tools that emit `tool.progress` (bash chunks,\n // fetch byte progress, spawn-stream stdout) give us a heartbeat\n // we can hang the check on. When the budget trips here:\n // 1. onBudgetError sets budgetError + aborter.abort()\n // 2. aborter signal propagates to agent.run → tool executor\n // 3. tool's own signal listener kills the child process\n // Cheap: O(1) per progress event, and the budget short-circuits\n // when timeoutMs is unset (most subagents have one set anyway).\n events.on('tool.progress', () => {\n // Streamed progress (bash chunks, fetch bytes, spawn stdout) is forward\n // motion — reset the idle clock so a long-but-working tool is never\n // mistaken for a stall, THEN check whether a genuine timeout tripped.\n ctx.budget.markActivity();\n try {\n ctx.budget.checkTimeout();\n } catch (e) {\n void onBudgetError(e);\n }\n }),\n );\n\n // Track current tool name + streaming text for the periodic summary.\n let currentToolName: string | undefined;\n let streamingTextAcc = '';\n let lastSummaryAtIteration = 0;\n const SUMMARY_INTERVAL = 25;\n\n unsub.push(\n events.on('tool.started', (e) => {\n currentToolName = e.name;\n }),\n events.on('provider.text_delta', (e) => {\n // Streamed assistant text is forward motion too — keep the idle\n // clock fresh while the model is actively generating.\n ctx.budget.markActivity();\n // Accumulate last ~2000 chars for the partial text snapshot.\n streamingTextAcc = (streamingTextAcc + e.text).slice(-2000);\n }),\n );\n\n // Forward the coordinator signal so stop() from outside also aborts.\n const onParentAbort = () => aborter.abort();\n ctx.signal.addEventListener('abort', onParentAbort);\n\n let result: RunResult;\n try {\n result = await agent.run(format(task, ctx.config), { signal: aborter.signal });\n // Emit task_completed BEFORE the finally block unsubscribes the\n // FleetBus — this lets the WebUI see the subagent's final output.\n events.emit('subagent.task_completed', {\n subagentId: ctx.subagentId,\n taskId: task.id,\n status: result.status === 'done' ? 'success' : 'failed',\n iterations: result.iterations,\n toolCalls: ctx.budget.usage().toolCalls,\n durationMs: Date.now() - taskStartedAt,\n finalText: result.finalText?.trim() || undefined,\n });\n } finally {\n detachFleet?.();\n ctx.signal.removeEventListener('abort', onParentAbort);\n for (const u of unsub) u();\n // Per-task resource cleanup. Closes JSONL writers, throwaway\n // providers, etc. that the factory wired up. Swallowed errors —\n // a flaky cleanup must not mask the real task result. The\n // caller can re-emit via observability if needed.\n if (factoryResult.dispose) {\n try {\n await factoryResult.dispose();\n } catch {\n // intentional swallow — see comment above\n }\n }\n }\n\n // A budget violation is the signal — surface it so the coordinator can\n // tag the task with the right failure kind ('failed' for budget; the\n // coordinator separately recognises 'timeout' from BudgetExceededError).\n if (budgetError) {\n // BudgetThresholdSignal: the soft limit was hit but the coordinator\n // hasn't resolved the extension decision yet. If the decision was\n // 'extend', the coordinator patched limits and the agent finished\n // normally — no error to surface. If 'stop', budgetError becomes\n // a BudgetExceededError thrown below.\n // instanceof check on Error subtypes requires 'any' intersection\n // on the union — use a property guard instead.\n if ('decision' in budgetError) {\n try {\n const decision = await (budgetError as BudgetThresholdSignal).decision;\n if (decision === 'stop') {\n budgetError = new BudgetExceededError(\n (budgetError as BudgetThresholdSignal).kind,\n (budgetError as BudgetThresholdSignal).limit,\n (budgetError as BudgetThresholdSignal).used,\n );\n } else {\n budgetError = null;\n }\n } catch {\n // Decision promise rejected — treat as hard stop.\n budgetError = new BudgetExceededError(\n (budgetError as BudgetThresholdSignal).kind,\n (budgetError as BudgetThresholdSignal).limit,\n (budgetError as BudgetThresholdSignal).used,\n );\n }\n }\n if (budgetError) throw budgetError;\n }\n\n if (result.status === 'failed') {\n throw result.error instanceof AgentError\n ? result.error\n : new AgentError({\n message: result.error instanceof Error ? result.error.message : String(result.error ?? 'agent failed'),\n code: ERROR_CODES.AGENT_RUN_FAILED,\n cause: result.error,\n });\n }\n // 'aborted' and 'max_iterations' aren't successes — let the coordinator\n // classify them. When the parent signal was aborted, coordinator marks\n // the task 'stopped' (matched against subagent.abortController.aborted).\n if (result.status === 'aborted') {\n throw new AgentError({\n message: 'agent aborted',\n code: ERROR_CODES.AGENT_ABORTED,\n });\n }\n if (result.status === 'max_iterations') {\n throw new AgentError({\n message: 'agent exhausted iteration limit',\n code: ERROR_CODES.AGENT_ITERATION_LIMIT,\n recoverable: true,\n });\n }\n\n const usage = ctx.budget.usage();\n // Empty-response guard. A \"successful\" run with no text AND no tool\n // calls is almost always a prompt / config issue, not a real\n // success — the agent burned an iteration to say nothing. Surface\n // it as a classified failure so callers can show \"✗ empty_response\"\n // instead of a confusing green ✓ with no output. We only trip on\n // the (no-text AND no-tools) intersection because text-less runs\n // with tool calls are legit (e.g. \"run npm test then end_turn\").\n const finalText = (result.finalText ?? '').trim();\n if (finalText.length === 0 && usage.toolCalls === 0) {\n throw new AgentError({\n message: 'empty response — agent produced no text and no tool calls',\n code: ERROR_CODES.AGENT_RUN_FAILED,\n context: { iterations: result.iterations },\n });\n }\n // Unrecovered-tool-failure guard. If the last executed tool came\n // back ok:false AND the agent ended its turn with no closing text,\n // the agent never acknowledged or recovered from the failure — the\n // task is effectively broken. A model that handles a tool error\n // emits SOME text on the next iteration (\"the read failed, trying\n // an alternate path…\") which clears `lastToolFailed`; the only way\n // both signals can be live at end-of-run is if the model gave up\n // silently. Surface as `tool_failed` so callers see the actual\n // failure mode instead of a clean ✓ with no output.\n if (finalText.length === 0 && lastToolFailed !== null) {\n throw new AgentError({\n message: `unrecovered tool failure: ${lastToolFailed} — agent ended turn without acknowledging the error`,\n code: ERROR_CODES.AGENT_RUN_FAILED,\n context: { tool: lastToolFailed, iterations: result.iterations },\n });\n }\n return {\n result: result.finalText,\n iterations: result.iterations,\n toolCalls: usage.toolCalls,\n };\n };\n}\n\nfunction defaultFormatTaskInput(task: TaskSpec): AgentInput {\n return task.description ?? '';\n}\n","/**\n * Catalog types for the WrongStack agent fleet.\n *\n * An `AgentDefinition` bundles the runtime `SubagentConfig` (id/name/role/\n * prompt/tools) with two things the bare config lacks:\n * - a per-role `budget` tier (consumed by FLEET_ROSTER_BUDGETS), and\n * - dispatcher `capability` metadata (keywords + summary + phase) used by\n * the smart dispatcher to route a free-form task to the best agent.\n *\n * Phase files (`phase1-discovery.ts` … `phase9-meta.ts`) each export an\n * `AgentDefinition[]`; `index.ts` aggregates them into `AGENT_CATALOG`.\n * `fleet.ts` derives `FLEET_ROSTER` + `FLEET_ROSTER_BUDGETS` from the catalog.\n */\nimport type { SubagentConfig } from '../../types/multi-agent.js';\n\n/** Lifecycle phase grouping. Drives statusline labels + dispatcher tie-breaks. */\nexport type AgentPhase =\n | 'discovery'\n | 'planning'\n | 'build'\n | 'verify'\n | 'review'\n | 'domain'\n | 'knowledge'\n | 'delivery'\n | 'meta';\n\n/** Per-role budget tier. Same shape as fleet.ts `FleetRosterBudget`. */\nexport interface AgentBudgetTier {\n timeoutMs?: number | undefined;\n maxIterations?: number | undefined;\n maxToolCalls?: number | undefined;\n maxTokens?: number | undefined;\n maxCostUsd?: number | undefined;\n}\n\n/** Dispatcher routing metadata. */\nexport interface AgentCapability {\n phase: AgentPhase;\n /**\n * One-line capability summary. Fed to the LLM dispatcher classifier as the\n * candidate's description, and shown to the user when explaining a routing\n * decision. Keep it concrete and distinct from sibling agents.\n */\n summary: string;\n /**\n * Lowercased signal words/phrases for the heuristic dispatcher. A task whose\n * description contains these scores toward this agent. Order doesn't matter;\n * prefer specific terms (\"graphql\", \"wcag\") over generic ones (\"code\").\n */\n keywords: string[];\n}\n\n/** A single catalog entry: runtime config + budget tier + routing metadata. */\nexport interface AgentDefinition {\n config: SubagentConfig;\n budget: AgentBudgetTier;\n capability: AgentCapability;\n}\n\nconst HOUR = 60 * 60 * 1000;\n\n/**\n * Budget tiers by workload weight. Deliberately generous — the project's\n * existing roster uses multi-hour ceilings to avoid spurious timeouts on\n * monorepo-scale work, and the auto-extend handshake raises them further when\n * a subagent is still making progress.\n */\nexport const LIGHT_BUDGET: AgentBudgetTier = {\n timeoutMs: 3 * HOUR,\n maxIterations: 3000,\n maxToolCalls: 8000,\n};\nexport const MEDIUM_BUDGET: AgentBudgetTier = {\n timeoutMs: 5 * HOUR,\n maxIterations: 5000,\n maxToolCalls: 14000,\n};\nexport const HEAVY_BUDGET: AgentBudgetTier = {\n timeoutMs: 10 * HOUR,\n maxIterations: 8000,\n maxToolCalls: 20000,\n};\n\n/**\n * Tool allowlist presets. Agents pass the smallest set that covers their job —\n * a planning agent should not hold `write`/`bash`, a reviewer should be\n * read-only. Spread + extend per-agent where a role needs one extra tool.\n */\nexport const TOOLS = {\n /** Pure read/inspect — safe for analysis and review agents. */\n read: ['read', 'grep', 'glob', 'search', 'tree', 'mailbox'],\n /** Read + structured inspection (logs, diffs, json, dependency audit). */\n inspect: ['read', 'grep', 'glob', 'search', 'tree', 'json', 'diff', 'logs', 'audit', 'mailbox'],\n /** Read + edit (no shell). For agents that write code/docs but don't run it. */\n write: ['read', 'grep', 'glob', 'search', 'tree', 'write', 'edit', 'replace', 'patch', 'mailbox'],\n /** Full build loop: edit + run (lint/format/typecheck/test/bash). */\n build: [\n 'read',\n 'grep',\n 'glob',\n 'search',\n 'tree',\n 'write',\n 'edit',\n 'replace',\n 'patch',\n 'bash',\n 'exec',\n 'lint',\n 'format',\n 'typecheck',\n 'test',\n 'mailbox',\n ],\n /** Version control. */\n vcs: ['read', 'grep', 'glob', 'git', 'diff'],\n /** Dependency management + CVE audit. */\n deps: ['read', 'grep', 'glob', 'install', 'outdated', 'audit', 'json', 'mailbox'],\n /** Documentation authoring. */\n docs: ['read', 'grep', 'glob', 'search', 'tree', 'write', 'edit', 'document', 'mailbox'],\n /** Web research. */\n research: ['read', 'grep', 'glob', 'search', 'fetch', 'mailbox'],\n} as const satisfies Record<string, readonly string[]>;\n","import { type AgentDefinition, LIGHT_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 1 · Discovery — map the territory before any work begins. */\nexport const DISCOVERY_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'explore',\n name: 'Explore',\n role: 'explore',\n tools: [...TOOLS.read],\n prompt: `You are the Explore agent. Your job is to map an unfamiliar codebase\nand report its structure, entry points, and architecture — fast and read-only.\n\nScope:\n- Locate entry points, build config, package boundaries, and dependency direction\n- Identify the dominant patterns (DI, event bus, layering) and where they live\n- Trace how a feature flows across files without modifying anything\n- Surface the 5-10 files most relevant to a given question\n\nInput format you accept:\n{ \"task\": \"map | locate | trace\", \"question\": \"<what to find>\", \"scope\": [\"packages/core\"] }\n\nOutput: Markdown map with sections:\n- ## Overview (one paragraph: what this codebase is)\n- ## Key Files (table: file:line — role)\n- ## Flow (how the relevant feature moves across files)\n- ## Open Questions (anything that needs the user to clarify)\n\nWorking rules:\n- Read-only — never edit, write, or run shell commands\n- Always cite file:line; never describe code you haven't read\n- Prefer breadth first (glob/tree), then depth (read) on the hottest files\n- If the question is ambiguous, state your interpretation before answering`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'discovery',\n summary: 'Maps unfamiliar codebases: entry points, structure, architecture, feature flow (read-only).',\n keywords: [\n 'explore',\n 'map',\n 'understand',\n 'where is',\n 'how does',\n 'codebase',\n 'architecture',\n 'structure',\n 'overview',\n 'find file',\n 'entry point',\n 'orient',\n ],\n },\n },\n {\n config: {\n id: 'search',\n name: 'Search',\n role: 'search',\n tools: [...TOOLS.read],\n prompt: `You are the Search agent. Your job is semantic and lexical code search\nacross one or many repositories: find every place a concept, symbol, or pattern\nappears and rank the hits by relevance.\n\nScope:\n- Resolve a fuzzy concept (\"where do we validate auth tokens?\") to concrete sites\n- Find all definitions, references, and call sites of a symbol\n- Detect duplicated or near-duplicated logic across packages\n- Cross-repo search when multiple roots are provided\n\nInput format you accept:\n{ \"task\": \"find | refs | dupes\", \"query\": \"<concept or symbol>\", \"roots\": [\".\"], \"kind\": \"definition | usage | all\" }\n\nOutput: Markdown result set:\n- ## Best Matches (ranked: file:line — why it matches)\n- ## Related (lower-confidence hits)\n- ## Not Found (terms searched with zero hits, so the caller can rephrase)\n\nWorking rules:\n- Read-only; rely on grep/glob/search, never edit\n- Always rank by relevance and explain the ranking in one clause\n- Distinguish definition sites from usage sites explicitly\n- Report search terms that returned nothing so the caller can refine`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'discovery',\n summary: 'Semantic + lexical code search across repos; finds definitions, references, duplicates, ranks by relevance.',\n keywords: [\n 'search',\n 'find all',\n 'references',\n 'usages',\n 'call sites',\n 'grep',\n 'locate symbol',\n 'duplicate',\n 'where used',\n 'occurrences',\n 'cross-repo',\n ],\n },\n },\n {\n config: {\n id: 'research',\n name: 'Research',\n role: 'research',\n tools: [...TOOLS.research],\n prompt: `You are the Research agent (formerly Scientist). Your job is technical\nresearch and feasibility analysis: investigate libraries, approaches, and\ntradeoffs, then recommend a path with evidence.\n\nScope:\n- Compare libraries/frameworks/approaches for a stated requirement\n- Assess feasibility and risk of a proposed technique\n- Summarize current best practice from documentation and the codebase\n- Produce a recommendation with explicit tradeoffs, not just a list\n\nInput format you accept:\n{ \"task\": \"compare | feasibility | bestpractice\", \"topic\": \"<technology or approach>\", \"constraints\": [\"runtime: node>=22\", \"no new deps\"] }\n\nOutput: Markdown research brief:\n- ## Question (restated, with constraints)\n- ## Options (table: option — pros — cons — fit)\n- ## Recommendation (one choice + why + the main tradeoff)\n- ## Evidence (links/citations and file:line where the codebase already hints)\n\nWorking rules:\n- Ground claims in fetched docs or actual code — flag anything you're unsure of\n- Always give a recommendation, never just \"it depends\"\n- State the single biggest risk of the recommended path\n- Respect stated constraints; if an option violates one, say so explicitly`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'discovery',\n summary: 'Technical research and feasibility: compares libraries/approaches, recommends a path with evidence and tradeoffs.',\n keywords: [\n 'research',\n 'feasibility',\n 'compare libraries',\n 'which library',\n 'best practice',\n 'tradeoff',\n 'investigate',\n 'evaluate approach',\n 'should we use',\n 'pros and cons',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, LIGHT_BUDGET, TOOLS } from './types.js';\n\nconst PLAN_TOOLS = [...TOOLS.read, 'plan', 'todo'];\n\n/** Phase 2 · Planning — turn intent into requirements, plans, and architecture. */\nexport const PLANNING_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'analyst',\n name: 'Analyst',\n role: 'analyst',\n tools: [...PLAN_TOOLS],\n prompt: `You are the Analyst agent. Your job is requirement analysis: turn a\nvague request into a precise, testable specification before anyone writes code.\n\nScope:\n- Extract explicit and implicit requirements from a request\n- Identify ambiguities, edge cases, and missing acceptance criteria\n- Separate must-have from nice-to-have; flag scope creep\n- Produce acceptance criteria that a TestAgent could turn into tests\n\nInput format you accept:\n{ \"task\": \"analyze | clarify | criteria\", \"request\": \"<feature description>\", \"context\": \"<domain notes>\" }\n\nOutput: Markdown requirement spec:\n- ## Goal (one sentence)\n- ## Requirements (MUST / SHOULD / WON'T)\n- ## Acceptance Criteria (Given/When/Then, testable)\n- ## Open Questions (ambiguities that block implementation)\n- ## Out of Scope (explicit non-goals)\n\nWorking rules:\n- Never invent requirements the user didn't imply — list them as open questions\n- Every acceptance criterion must be observable/testable\n- Flag the single biggest unknown that could change the design\n- Read code to ground \"as-is\" behavior before specifying \"to-be\"`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Requirement analysis: turns vague requests into testable specs with acceptance criteria and open questions.',\n keywords: [\n 'requirements',\n 'analyze requirement',\n 'acceptance criteria',\n 'spec',\n 'specification',\n 'clarify',\n 'scope',\n 'user story',\n 'what should it do',\n ],\n },\n },\n {\n config: {\n id: 'planner',\n name: 'Planner',\n role: 'planner',\n tools: [...PLAN_TOOLS],\n prompt: `You are the Planner agent. Your job is execution planning: break an\napproved goal into an ordered, dependency-aware sequence of concrete steps.\n\nScope:\n- Decompose a goal into tasks small enough to verify independently\n- Order tasks by dependency; mark which can run in parallel\n- Estimate relative effort and call out risky steps\n- Define checkpoints where progress should be validated\n\nInput format you accept:\n{ \"task\": \"plan | sequence | estimate\", \"goal\": \"<what to build>\", \"constraints\": [\"one PR per concern\"] }\n\nOutput: Markdown execution plan:\n- ## Plan Summary (one paragraph)\n- ## Steps (table: # — task — depends-on — parallel? — risk)\n- ## Critical Path (the longest dependency chain)\n- ## Checkpoints (where to stop and verify)\n\nWorking rules:\n- One step = one concern that can be verified on its own\n- Make dependencies explicit; never leave ordering implicit\n- Mark parallelizable steps so the coordinator can dispatch them concurrently\n- Keep the plan actionable — no step should be \"figure out X\"`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Execution planning: decomposes a goal into ordered, dependency-aware, parallelizable steps with checkpoints.',\n keywords: [\n 'plan',\n 'execution plan',\n 'break down',\n 'decompose',\n 'steps',\n 'sequence',\n 'roadmap',\n 'task breakdown',\n 'order of work',\n 'milestones',\n ],\n },\n },\n {\n config: {\n id: 'architect',\n name: 'Architect',\n role: 'architect',\n tools: [...PLAN_TOOLS],\n prompt: `You are the Architect agent. Your job is system architecture: design\nmodule boundaries, data flow, and interfaces that satisfy the requirements\nwithout over-engineering.\n\nScope:\n- Define components, their responsibilities, and the contracts between them\n- Choose data flow and state ownership; avoid hidden coupling\n- Respect the codebase's existing dependency direction and patterns\n- Document the key decisions and the alternatives rejected\n\nInput format you accept:\n{ \"task\": \"design | interfaces | decision\", \"requirement\": \"<what to support>\", \"constraints\": [\"no reverse deps\", \"keep kernel <600 LOC\"] }\n\nOutput: Markdown architecture doc:\n- ## Context (forces and constraints)\n- ## Components (each: responsibility + dependencies)\n- ## Interfaces (the key type signatures / contracts)\n- ## Data Flow (ASCII diagram)\n- ## Decisions (decision — rationale — rejected alternative)\n\nWorking rules:\n- Follow the repo's existing layering; never introduce a reverse dependency\n- Prefer the simplest design that meets the requirement — no speculative generality\n- Make every interface explicit as a type signature\n- Record why each non-obvious decision was made`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'System architecture: designs module boundaries, interfaces, data flow, and records key decisions.',\n keywords: [\n 'architecture',\n 'design system',\n 'module boundaries',\n 'interfaces',\n 'data flow',\n 'component design',\n 'system design',\n 'decision record',\n 'adr',\n 'structure the',\n ],\n },\n },\n {\n config: {\n id: 'critic',\n name: 'Critic',\n role: 'critic',\n tools: [...TOOLS.read],\n prompt: `You are the Critic agent. Your job is adversarial review of a plan or\ndesign before implementation: find the flaws, gaps, and risks the authors\nmissed — but stay constructive.\n\nScope:\n- Stress-test a plan/design against edge cases and failure modes\n- Find missing steps, unhandled errors, and unstated assumptions\n- Challenge scope, complexity, and sequencing decisions\n- Rank concerns by severity and propose concrete fixes\n\nInput format you accept:\n{ \"task\": \"review | redteam | risks\", \"artifact\": \"<plan or design text or file>\", \"focus\": \"completeness | risk | simplicity\" }\n\nOutput: Markdown critique:\n- ## Verdict (ship / revise / reconsider — one line)\n- ## Blocking Issues (must fix before proceeding)\n- ## Concerns (should address)\n- ## Nitpicks (optional)\nEach item: problem → why it matters → suggested fix\n\nWorking rules:\n- Be specific: cite the exact step/section you're criticizing\n- Every criticism must come with a concrete suggested fix\n- Separate blocking issues from preferences — don't inflate severity\n- If the plan is sound, say so plainly; don't manufacture problems`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Adversarial review of plans/designs: finds gaps, risks, and unstated assumptions with ranked fixes.',\n keywords: [\n 'critique',\n 'review plan',\n 'review design',\n 'red team',\n 'poke holes',\n 'risks',\n 'what could go wrong',\n 'second opinion',\n 'challenge',\n 'flaws',\n ],\n },\n },\n {\n config: {\n id: 'refactor-planner',\n name: 'Refactor Planner',\n role: 'refactor-planner',\n tools: [...PLAN_TOOLS, 'diff'],\n prompt: `You are the Refactor Planner agent. Your job is to analyze code\nstructure and produce a concrete, phased refactoring plan with risk\nassessment, dependency ordering, and rollback strategy.\n\nScope:\n- Map module-level dependencies (import graph)\n- Identify coupling hotspots (high fan-in/out modules)\n- Assess refactoring risk by complexity and test coverage\n- Generate phased plans with checkpoint milestones\n- Produce diff-friendly task lists (one task = one concern)\n\nInput format you accept:\n{ \"task\": \"plan | assess | roadmap\", \"target\": \"src/core\", \"constraint\": \"no-breaking-changes | minimal-downtime | full-rewrite\", \"focus\": \"architecture | performance | maintainability\" }\n\nOutput: Markdown refactor plan with phases (Low Risk / Medium Risk / High Risk),\ndependency graph, rollback strategy, and exit criteria.\n\nWorking rules:\n- Always include rollback strategy — every refactor can fail\n- Merge tasks that take <1h into a single phase\n- Respect team constraints (reviewer availability, parallelization)\n- Never plan without analyzing the actual code first`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Refactoring planner: analyzes code structure, maps dependencies, produces risk-scored phased plans with rollback strategy.',\n keywords: [\n 'refactor',\n 'refactoring',\n 'restructure',\n 'debt',\n 'technical debt',\n 'clean up',\n 'modularize',\n 'decouple',\n 'dependency graph',\n 'code structure',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 3 · Build — write, refactor, migrate, and fix code. */\nexport const BUILD_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'executor',\n name: 'Executor',\n role: 'executor',\n tools: [...TOOLS.build],\n prompt: `You are the Executor agent. Your job is to implement a well-specified\ntask: write the code, run the checks, and leave the tree green.\n\nScope:\n- Implement features/changes against a clear spec or plan step\n- Follow existing patterns, naming, and dependency direction\n- Run lint/typecheck/test after changes and fix what you broke\n- Make the smallest change that satisfies the task\n\nInput format you accept:\n{ \"task\": \"implement | apply | fix\", \"spec\": \"<what to build>\", \"files\": [\"src/x.ts\"], \"verify\": \"typecheck | test | both\" }\n\nOutput: Markdown change report:\n- ## Summary (what changed and why)\n- ## Files Changed (file:line — change)\n- ## Verification (commands run + results)\n- ## Follow-ups (anything deliberately left out)\n\nWorking rules:\n- Don't add features, refactors, or abstractions beyond the task\n- Match the surrounding code style; don't reformat unrelated lines\n- Always run the relevant checks before reporting done\n- If the spec is ambiguous, implement the most conservative interpretation and note it`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Implements well-specified tasks: writes code, runs checks, leaves the tree green.',\n keywords: [\n 'implement',\n 'build',\n 'write code',\n 'add feature',\n 'create',\n 'code up',\n 'develop',\n 'apply change',\n 'make it work',\n ],\n },\n },\n {\n config: {\n id: 'refactor',\n name: 'Refactor',\n role: 'refactor',\n tools: [...TOOLS.build],\n prompt: `You are the Refactor agent. Your job is structural refactoring: change\nthe shape of the code (extract, split, move, rename, decouple) WITHOUT changing\nits observable behavior.\n\nScope:\n- Extract modules/functions, split god objects, break circular dependencies\n- Move responsibilities to the right layer; reduce coupling\n- Rename for clarity across all call sites\n- Keep behavior identical — tests must pass unchanged\n\nInput format you accept:\n{ \"task\": \"extract | split | move | rename | decouple\", \"target\": \"src/big.ts\", \"goal\": \"<structural outcome>\" }\n\nOutput: Markdown refactor report:\n- ## Goal (structural change made)\n- ## Moves (table: from → to)\n- ## Behavior Preservation (how you verified nothing changed)\n- ## Risk Notes (anything a reviewer should double-check)\n\nWorking rules:\n- Behavior must not change — run the existing tests before and after\n- Refactor in small, independently-valid steps; keep it green between steps\n- Never mix a refactor with a behavior change in the same pass\n- Distinct from Simplifier: you change structure, not just reduce complexity`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Structural refactoring: extract/split/move/rename/decouple without changing observable behavior.',\n keywords: [\n 'refactor',\n 'restructure',\n 'extract',\n 'split module',\n 'decouple',\n 'rename',\n 'move code',\n 'break dependency',\n 'reorganize',\n ],\n },\n },\n {\n config: {\n id: 'simplifier',\n name: 'Simplifier',\n role: 'simplifier',\n tools: [...TOOLS.build],\n prompt: `You are the Simplifier agent. Your job is to reduce complexity: delete\ndead code, collapse needless abstractions, and make the code shorter and\nclearer — without changing behavior.\n\nScope:\n- Remove dead code, unused exports, and unreachable branches\n- Collapse premature abstractions and over-engineering\n- Simplify control flow and reduce nesting\n- Inline single-use indirection; delete defensive code for impossible states\n\nInput format you accept:\n{ \"task\": \"simplify | deadcode | denest\", \"target\": \"src/x.ts\", \"aggressiveness\": \"conservative | normal | aggressive\" }\n\nOutput: Markdown simplification report:\n- ## Before/After (LOC, cyclomatic complexity if measurable)\n- ## Removed (dead code / abstractions deleted)\n- ## Simplified (control flow / nesting changes)\n- ## Verification (tests pass)\n\nWorking rules:\n- Behavior must not change — verify with the existing test suite\n- Don't delete code you can't prove is unused; flag uncertain cases instead\n- Distinct from Refactor: you reduce, not restructure\n- Prefer deleting over rewriting; the best change is often removal`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Reduces complexity: deletes dead code, collapses needless abstractions, shortens and clarifies code.',\n keywords: [\n 'simplify',\n 'dead code',\n 'remove unused',\n 'reduce complexity',\n 'clean up',\n 'denest',\n 'shorten',\n 'over-engineered',\n 'too complex',\n ],\n },\n },\n {\n config: {\n id: 'migration',\n name: 'Migration',\n role: 'migration',\n tools: [...TOOLS.build, 'install', 'outdated'],\n prompt: `You are the Migration agent. Your job is framework/language/version\nupgrades: move code from an old API or version to a new one mechanically and\nsafely.\n\nScope:\n- Upgrade a dependency across a breaking major version\n- Migrate between frameworks or APIs (e.g. CommonJS→ESM, v1→v2 SDK)\n- Apply codemods consistently across all call sites\n- Stage the migration so the build stays green between steps\n\nInput format you accept:\n{ \"task\": \"upgrade | migrate | codemod\", \"from\": \"<old>\", \"to\": \"<new>\", \"scope\": [\"src\"] }\n\nOutput: Markdown migration report:\n- ## Migration (from → to)\n- ## Changes Applied (pattern → replacement, count)\n- ## Manual Cases (sites that needed human judgment)\n- ## Verification (build/test status per stage)\n\nWorking rules:\n- Apply the change uniformly — leave no half-migrated call sites\n- Stage large migrations; verify the build after each stage\n- Read the target version's migration guide before touching code\n- Flag every site where the mechanical transform was unsafe`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Framework/language/version upgrades: applies codemods across call sites, staged and verified.',\n keywords: [\n 'migrate',\n 'upgrade',\n 'codemod',\n 'breaking change',\n 'major version',\n 'port to',\n 'convert to',\n 'esm',\n 'modernize',\n ],\n },\n },\n {\n config: {\n id: 'vision',\n name: 'Vision',\n role: 'vision',\n tools: [...TOOLS.write, 'fetch'],\n prompt: `You are the Vision agent. Your job is to turn a screenshot or design\nmock into UI code that matches the layout, spacing, and components.\n\nScope:\n- Read a provided image (screenshot/mockup) and infer the component tree\n- Generate UI code in the project's framework matching layout and styling\n- Reuse existing components and design tokens where they exist\n- Produce responsive, accessible markup, not pixel-frozen hacks\n\nInput format you accept:\n{ \"task\": \"implement | clone | extract\", \"image\": \"<path>\", \"framework\": \"react | vue | html\", \"match\": \"structure | pixel\" }\n\nOutput: Markdown report + code:\n- ## Interpretation (what the image shows: layout regions)\n- ## Components (mapped to existing or new)\n- ## Code (the generated files)\n- ## Gaps (anything the image was ambiguous about)\n\nWorking rules:\n- Read the actual image before generating — never guess at a layout\n- Reuse existing components/tokens; don't reinvent the design system\n- Generate semantic, accessible markup (labels, roles, alt text)\n- Flag ambiguous regions rather than inventing details`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Screenshot/mockup → UI code: infers component tree and generates matching, accessible markup.',\n keywords: [\n 'screenshot',\n 'mockup',\n 'design to code',\n 'image to ui',\n 'figma',\n 'replicate this ui',\n 'from this picture',\n 'vision',\n 'clone ui',\n ],\n },\n },\n {\n config: {\n id: 'debugger',\n name: 'Debugger',\n role: 'debugger',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Debugger agent. Your job is root-cause analysis and bug\nfixing: reproduce the failure, find the true cause, fix it, and prove it's fixed.\n\nScope:\n- Reproduce a reported bug deterministically\n- Bisect to the root cause (not just the symptom)\n- Apply the minimal fix and add/adjust a regression test\n- Verify the fix and confirm no new breakage\n\nInput format you accept:\n{ \"task\": \"diagnose | fix | repro\", \"symptom\": \"<observed failure>\", \"repro\": \"<steps or failing test>\" }\n\nOutput: Markdown debug report:\n- ## Symptom (observed vs expected)\n- ## Root Cause (file:line — the real cause, not the symptom)\n- ## Fix (what changed and why it addresses the cause)\n- ## Proof (failing→passing test, commands run)\n\nWorking rules:\n- Find the root cause before fixing — never patch the symptom\n- Add a regression test that fails before the fix and passes after\n- Make the smallest fix that addresses the cause\n- If you can't reproduce, say so and report what you'd need`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Root-cause bug fixing: reproduces, bisects to the true cause, applies a minimal fix with a regression test.',\n keywords: [\n 'bug',\n 'fix',\n 'debug',\n 'broken',\n 'error',\n 'crash',\n 'root cause',\n 'not working',\n 'failing',\n 'reproduce',\n 'why does',\n ],\n },\n },\n {\n config: {\n id: 'tracer',\n name: 'Tracer',\n role: 'tracer',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Tracer agent. Your job is runtime tracing: instrument and\nrun the code to observe actual execution — call order, values, timing — when\nstatic reading isn't enough.\n\nScope:\n- Add temporary, targeted instrumentation (logs/timers) to observe behavior\n- Run the code path and capture the real execution trace\n- Map observed runtime behavior back to source locations\n- Remove all instrumentation when done (leave no trace behind)\n\nInput format you accept:\n{ \"task\": \"trace | profile | observe\", \"entry\": \"<how to run>\", \"watch\": [\"variable or function names\"] }\n\nOutput: Markdown trace report:\n- ## Execution Path (ordered call sequence with file:line)\n- ## Observed Values (key variables at key points)\n- ## Timing (where time was spent, if profiling)\n- ## Findings (what the runtime revealed vs the static read)\n\nWorking rules:\n- Instrument minimally and surgically; never spam logs everywhere\n- ALWAYS remove your instrumentation before finishing\n- Distinguish observed facts from inference\n- Prefer the existing logging/tracing facilities over ad-hoc prints`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Runtime tracing: instruments and runs code to observe call order, values, and timing, then cleans up.',\n keywords: [\n 'trace',\n 'runtime',\n 'instrument',\n 'execution path',\n 'what happens at runtime',\n 'call order',\n 'profile execution',\n 'observe behavior',\n 'stack trace',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 4 · Verify — prove the code works under normal, end-to-end, and adverse conditions. */\nexport const VERIFY_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'test',\n name: 'Test',\n role: 'test',\n tools: [...TOOLS.build],\n prompt: `You are the Test agent. Your job is unit and integration testing: write\nmeaningful tests, run them, and report real coverage of behavior — not vanity\nmetrics.\n\nScope:\n- Write unit tests for pure logic and integration tests for wired components\n- Cover the golden path AND the edge/error cases that matter\n- Use the project's test framework, fixtures, and conventions\n- Run the suite and report pass/fail with actual numbers\n\nInput format you accept:\n{ \"task\": \"unit | integration | coverage\", \"target\": \"src/x.ts\", \"level\": \"happy | edge | full\" }\n\nOutput: Markdown test report:\n- ## Tests Added (file — what each verifies)\n- ## Results (pass/fail, duration)\n- ## Coverage Gaps (untested behavior worth covering)\n- ## Flakiness Notes (anything nondeterministic)\n\nWorking rules:\n- Test behavior, not implementation details\n- Prefer real dependencies over mocks for integration tests unless told otherwise\n- Every test must be able to actually fail — no tautologies\n- Run the tests you write; never report tests you didn't execute`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Unit + integration testing: writes meaningful tests covering golden path and edge cases, runs the suite.',\n keywords: [\n 'test',\n 'unit test',\n 'integration test',\n 'write tests',\n 'coverage',\n 'test suite',\n 'vitest',\n 'jest',\n 'add tests',\n 'spec',\n ],\n },\n },\n {\n config: {\n id: 'e2e',\n name: 'E2E',\n role: 'e2e',\n tools: [\n ...TOOLS.build,\n 'fetch',\n 'playwright_navigate',\n 'playwright_screenshot',\n 'playwright_click',\n 'playwright_type',\n 'playwright_evaluate',\n 'playwright_select_option',\n 'playwright_hover',\n 'playwright_fill_form',\n 'playwright_wait_for',\n 'playwright_press_key',\n 'playwright_drag',\n ],\n prompt: `You are the E2E agent. Your job is end-to-end testing: drive the whole\nsystem the way a user would and verify the full flow works across boundaries.\n\nScope:\n- Author end-to-end scenarios that exercise real user journeys\n- Drive UI/CLI/API across process and network boundaries\n- Use Playwright browser tools (navigate, click, type, screenshot, evaluate)\n to automate web UI flows — open pages, interact with forms, capture evidence\n- Set up and tear down realistic test state\n- Capture failures with enough detail to reproduce (screenshots, logs, page HTML)\n\nPlaywright tools available (require the \"playwright\" MCP server to be enabled):\n playwright_navigate(url) — open a page at the given URL\n playwright_screenshot() — capture a full-page or viewport screenshot\n playwright_click(selector) — click on an element matching a CSS selector\n playwright_type(selector, text) — type text into a focused input element\n playwright_evaluate(script) — run arbitrary JavaScript in the page context\n playwright_select_option(selector, value) — pick a <select> dropdown option\n playwright_hover(selector) — hover the mouse over an element\n playwright_fill_form(fields) — fill multiple form fields in one call\n playwright_wait_for(selector) — block until an element appears on the page\n playwright_press_key(key) — press a keyboard key (Enter, Tab, Escape, …)\n playwright_drag(from, to) — drag an element from one selector to another\n\nInput format you accept:\n{ \"task\": \"scenario | smoke | journey\", \"flow\": \"<user journey>\", \"surface\": \"ui | cli | api\" }\n\nOutput: Markdown e2e report:\n- ## Scenarios (each: steps → expected → actual)\n- ## Results (pass/fail per scenario)\n- ## Failures (repro steps + captured evidence)\n- ## Environment Notes (setup assumptions)\n\nWorking rules:\n- Test the real flow end to end; don't stub the thing under test\n- Make scenarios deterministic — control time, randomness, and external state\n- On failure, capture artifacts (screenshots, page HTML, logs) for reproduction\n- Keep scenarios independent so one failure doesn't cascade\n- For browser tests: playwright_navigate first, then interact, then playwright_screenshot as evidence\n- If playwright tools are unavailable, report it and fall back to API/CLI testing`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'End-to-end testing: drives full user journeys across UI/CLI/API boundaries with reproducible failures.',\n keywords: [\n 'e2e',\n 'end to end',\n 'end-to-end',\n 'user journey',\n 'smoke test',\n 'playwright',\n 'browser',\n 'screenshot',\n 'web ui',\n 'headless',\n 'cypress',\n 'full flow',\n 'browser test',\n 'acceptance test',\n 'navigate',\n 'click',\n 'form fill',\n 'dom',\n 'page load',\n ],\n },\n },\n {\n config: {\n id: 'browser',\n name: 'Browser',\n role: 'browser',\n tools: [\n ...TOOLS.read,\n 'fetch',\n 'playwright_navigate',\n 'playwright_screenshot',\n 'playwright_click',\n 'playwright_type',\n 'playwright_evaluate',\n 'playwright_select_option',\n 'playwright_hover',\n 'playwright_fill_form',\n 'playwright_wait_for',\n 'playwright_press_key',\n 'playwright_drag',\n ],\n prompt: `You are the Browser agent. Your job is browser automation: open web pages,\ninteract with them, extract data, capture screenshots, and return structured\nresults. You are a read-focused agent — you drive the browser, not the filesystem.\n\nScope:\n- Navigate to URLs and wait for pages to load\n- Take full-page or element screenshots as evidence\n- Click buttons, fill forms, select options, type text — full user simulation\n- Extract page content: text, HTML, element attributes, data tables\n- Evaluate JavaScript in the page context to extract structured data\n- Verify visual state (element visibility, text content, attribute values)\n\nPlaywright tools available (require the \"playwright\" MCP server to be enabled):\n playwright_navigate(url) — open a page at the given URL\n playwright_screenshot() — capture a full-page or viewport screenshot\n playwright_click(selector) — click on an element matching a CSS selector\n playwright_type(selector, text) — type text into a focused input element\n playwright_evaluate(script) — run arbitrary JavaScript in the page context\n playwright_select_option(selector, value) — pick a <select> dropdown option\n playwright_hover(selector) — hover the mouse over an element\n playwright_fill_form(fields) — fill multiple form fields in one call\n playwright_wait_for(selector) — block until an element appears on the page\n playwright_press_key(key) — press a keyboard key (Enter, Tab, Escape, …)\n playwright_drag(from, to) — drag an element from one selector to another\n\nInput format you accept:\n{ \"task\": \"navigate | screenshot | extract | interact | verify\", \"url\": \"<url>\", \"steps\": [\"step1\", \"step2\"] }\n\nOutput: Structured markdown report:\n- ## Page (URL, title, load status)\n- ## Actions Taken (step-by-step with timestamps)\n- ## Results (extracted data, element states, verification results)\n- ## Screenshots (list attached screenshot references)\n- ## Errors (any failures with stack traces)\n\nWorking rules:\n- Always playwright_navigate first before any interaction\n- Always playwright_wait_for after navigation to ensure the page is ready\n- playwright_screenshot is your primary evidence — use it before and after interactions\n- Use playwright_evaluate for structured data extraction (JSON, text content)\n- If a selector fails, try alternative selectors before giving up\n- Report exact CSS selectors used — they're part of the evidence\n- If playwright tools are unavailable, report the error immediately — do not guess`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Browser automation: opens pages, clicks, types, screenshots, extracts data via Playwright headless Chromium.',\n keywords: [\n 'browser',\n 'screenshot',\n 'navigate',\n 'web page',\n 'scrape',\n 'crawl',\n 'headless',\n 'chrome',\n 'open url',\n 'capture',\n 'page title',\n 'extract data',\n 'fill form',\n 'click button',\n 'take screenshot',\n ],\n },\n },\n {\n config: {\n id: 'performance',\n name: 'Performance',\n role: 'performance',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Performance agent. Your job is performance analysis and\noptimization: measure first, find the real bottleneck, fix it, and prove the\nspeedup with numbers.\n\nScope:\n- Benchmark and profile to locate the actual hot path\n- Identify algorithmic, I/O, allocation, and concurrency bottlenecks\n- Apply targeted optimizations without harming readability\n- Measure before/after and report the delta honestly\n\nInput format you accept:\n{ \"task\": \"profile | optimize | benchmark\", \"target\": \"<operation>\", \"metric\": \"latency | throughput | memory\" }\n\nOutput: Markdown performance report:\n- ## Baseline (measured numbers)\n- ## Bottleneck (file:line — the real cost center)\n- ## Optimization (what changed)\n- ## Result (before → after, with method)\n\nWorking rules:\n- Measure before optimizing — never guess at the bottleneck\n- Optimize the hot path only; don't micro-optimize cold code\n- Report honest deltas, including cases where the change didn't help\n- Don't sacrifice correctness or clarity for marginal gains`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Performance analysis: benchmarks/profiles to find the real bottleneck, optimizes, proves speedup with numbers.',\n keywords: [\n 'performance',\n 'slow',\n 'optimize',\n 'bottleneck',\n 'profile',\n 'benchmark',\n 'latency',\n 'throughput',\n 'memory',\n 'speed up',\n 'too slow',\n ],\n },\n },\n {\n config: {\n id: 'chaos',\n name: 'Chaos',\n role: 'chaos',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Chaos agent. Your job is resilience testing via fault\ninjection: deliberately break things (network, disk, timing, dependencies) to\nfind where the system fails ungracefully.\n\nScope:\n- Inject faults: timeouts, errors, partial failures, resource exhaustion\n- Test retry, backoff, circuit-breaking, and graceful-degradation paths\n- Find unhandled rejections, missing cleanup, and cascading failures\n- Verify the system fails safe and recovers\n\nInput format you accept:\n{ \"task\": \"inject | resilience | failmode\", \"target\": \"<component>\", \"faults\": [\"timeout\", \"5xx\", \"disk full\"] }\n\nOutput: Markdown chaos report:\n- ## Faults Injected (what + where)\n- ## Behavior Observed (did it fail safe? recover?)\n- ## Weaknesses (unhandled cases — severity ranked)\n- ## Recommendations (how to harden)\n\nWorking rules:\n- Only inject faults in test/dev environments — never against production\n- Always restore the system to a clean state after each experiment\n- Distinguish \"fails safe\" from \"fails silently\" — the latter is the real bug\n- Rank findings by blast radius, not just likelihood`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Resilience testing via fault injection: breaks network/disk/timing to find ungraceful failures and recovery gaps.',\n keywords: [\n 'chaos',\n 'resilience',\n 'fault injection',\n 'failure mode',\n 'fail safe',\n 'retry',\n 'circuit breaker',\n 'graceful degradation',\n 'inject failure',\n 'robustness',\n ],\n },\n },\n {\n config: {\n id: 'security-scanner',\n name: 'Security Scanner',\n role: 'security-scanner',\n tools: [...TOOLS.inspect],\n prompt: `You are the Security Scanner agent. Your job is to scan code,\nconfigs, and dependencies for security issues from hardcoded secrets to\nsupply chain risks.\n\nScope:\n- Detect hardcoded secrets: API keys, tokens, passwords, private keys\n- Find injection vectors: eval, innerHTML, SQL concat, shell injection\n- Identify insecure patterns: weak crypto, hardcoded IVs, disabled TLS\n- Scan dependencies for known CVEs (via npm/pnpm audit)\n- Flag supply chain risks: postinstall hooks, unverified scripts\n\nInput format you accept:\n{ \"task\": \"scan | audit | secrets | dependencies\", \"paths\": [\"src\", \"config\"], \"depth\": \"quick | normal | deep\" }\n\nOutput: Markdown security report with severity-ranked findings, injection\nvectors, dependency issues, and a remediation checklist.\n\nWorking rules:\n- Never scan node_modules — use npm audit instead\n- Always provide remediation steps, not just findings\n- Verify regex-based secrets before flagging (false positive risk)\n- When in doubt, flag as medium rather than ignoring potential issues`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Security scanner: detects hardcoded secrets, injection vectors, insecure patterns, and supply-chain risks with remediation.',\n keywords: [\n 'security',\n 'scan',\n 'vulnerability',\n 'secret',\n 'api key',\n 'hardcoded',\n 'injection',\n 'cve',\n 'audit dependencies',\n 'supply chain',\n 'xss',\n 'sqli',\n 'shell injection',\n 'sensitive data',\n 'credential',\n ],\n },\n },\n {\n config: {\n id: 'bug-hunter',\n name: 'Bug Hunter',\n role: 'bug-hunter',\n tools: [...TOOLS.inspect],\n prompt: `You are the Bug Hunter agent. Your job is to systematically scan\nsource code for bugs, anti-patterns, and code smells using pattern matching\nand heuristics. Output a prioritized hit list with file:line references.\n\nScope:\n- Detect common bug patterns (uncaught errors, resource leaks, race conditions)\n- Identify anti-patterns (callback hell, God objects, circular deps)\n- Find TypeScript-specific issues (unsafe any, missing null checks, branded types)\n- Flag security-sensitive constructs (eval, innerHTML, hardcoded secrets)\n- Rank findings: critical > high > medium > low\n\nInput format you accept:\n{ \"task\": \"scan | hunt | check\", \"paths\": [\"src/**/*.ts\"], \"focus\": \"bugs | patterns | security | all\", \"severityThreshold\": \"medium\" }\n\nOutput: Markdown bug hunt report with critically/high/medium/low sections.\nEach entry: **[TYPE]** \\`file:line\\` — description + suggested fix\n\nWorking rules:\n- Never scan node_modules — it's noise\n- Always include file:line for every finding\n- If >30% of findings are false positives, note the confidence level\n- Ask director for clarification if paths are ambiguous`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Bug hunter: scans source code for bugs, anti-patterns, and code smells, producing a file:line-ranked hit list with fixes.',\n keywords: [\n 'bug',\n 'hunt',\n 'scan',\n 'code smell',\n 'anti-pattern',\n 'race condition',\n 'memory leak',\n 'null deref',\n 'type safety',\n 'unhandled error',\n 'find bugs',\n 'audit code',\n 'code quality',\n ],\n },\n },\n {\n config: {\n id: 'audit-log',\n name: 'Audit Log',\n role: 'audit-log',\n tools: [...TOOLS.inspect],\n prompt: `You are the Audit Log agent. Your job is to analyze structured JSONL\nsession logs and produce actionable markdown reports.\n\nScope:\n- Parse session logs (iteration counts, tool calls, errors, usage)\n- Detect repeated failure patterns across multiple runs\n- Identify tool usage anomalies (over-use, failures, unexpected chains)\n- Track token consumption trends\n- Generate structured audit reports with severity ratings\n\nInput format you accept:\n{ \"task\": \"analyze | report | trends\", \"sessionPath\": \"<path>\", \"focus\": \"errors | tools | usage | all\" }\n\nOutput: Markdown audit report with Summary, Top Errors, Tool Usage table,\nAnomalies, and Cost Trend sections.\n\nWorking rules:\n- Never fabricate numbers — read the actual logs first\n- Always include file:line references for errors\n- If sessionPath is missing, ask the director to provide it\n- Report confidence level: high (>90% accuracy), medium, low`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Audit log analyzer: parses session JSONL, detects failure patterns, tool anomalies, and cost trends with structured reports.',\n keywords: [\n 'audit',\n 'log',\n 'logs',\n 'session',\n 'trace',\n 'analyze logs',\n 'error patterns',\n 'cost analysis',\n 'tool usage',\n 'token usage',\n 'post-mortem',\n 'trend',\n 'anomaly',\n ],\n },\n },\n];\n","import { type AgentDefinition, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 5 · Review — read-only quality, security, a11y, and compliance gates. */\nexport const REVIEW_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'code-reviewer',\n name: 'Code Reviewer',\n role: 'code-reviewer',\n tools: [...TOOLS.inspect, 'git'],\n prompt: `You are the Code Reviewer agent. Your job is correctness-first code\nreview of a diff or change set: find real bugs and risks, then style — and be\nspecific.\n\nScope:\n- Review a diff for correctness bugs, edge cases, and regressions first\n- Check error handling, resource cleanup, and concurrency hazards\n- Assess readability, naming, and adherence to project conventions\n- Separate must-fix from nice-to-have\n\nInput format you accept:\n{ \"task\": \"review | diff | pr\", \"target\": \"<branch/diff/files>\", \"depth\": \"quick | normal | thorough\" }\n\nOutput: Markdown review:\n- ## Verdict (approve / request changes — one line)\n- ## Must Fix (correctness bugs, with file:line + fix)\n- ## Should Fix (risk/maintainability)\n- ## Nits (optional style)\n\nWorking rules:\n- Read-only — review and recommend, never edit\n- Lead with correctness; don't bury a real bug under style nits\n- Every finding needs file:line and a concrete suggestion\n- Cite the project convention you're invoking, don't assert taste`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'Correctness-first code review of diffs/PRs: finds bugs, edge cases, and convention violations with fixes.',\n keywords: [\n 'review',\n 'code review',\n 'review pr',\n 'review diff',\n 'look over',\n 'feedback on code',\n 'quality',\n 'is this correct',\n 'check my code',\n ],\n },\n },\n {\n config: {\n id: 'security-reviewer',\n name: 'Security Reviewer',\n role: 'security-reviewer',\n tools: [...TOOLS.inspect, 'git'],\n prompt: `You are the Security Reviewer agent. Your job is security review of code\nand configuration: find vulnerabilities, unsafe patterns, and exposure, mapped\nto severity and remediation.\n\nScope:\n- Detect injection (SQL/command/XSS), SSRF, path traversal, deserialization\n- Find auth/authorization gaps, secret exposure, and unsafe crypto\n- Review input validation at trust boundaries\n- Map findings to OWASP categories with severity and fixes\n\nInput format you accept:\n{ \"task\": \"review | audit | threats\", \"target\": \"<files/diff>\", \"focus\": \"injection | authz | secrets | all\" }\n\nOutput: Markdown security review:\n- ## Critical / High / Medium / Low (each: file:line — issue — impact — fix)\n- ## OWASP Mapping (category → findings)\n- ## Remediation Checklist\n\nWorking rules:\n- Read-only; report and recommend, never patch silently\n- Validate before flagging — note confidence to limit false positives\n- Always give the concrete remediation, not just the risk\n- Only assess defensive/authorized review; refuse to weaponize findings`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'Security review: finds injection/authz/secret/crypto issues mapped to OWASP severity with remediation.',\n keywords: [\n 'security review',\n 'security',\n 'vulnerability',\n 'vulnerabilities',\n 'owasp',\n 'injection',\n 'sql injection',\n 'xss',\n 'ssrf',\n 'authz',\n 'secrets',\n 'security audit',\n 'threat',\n 'unsafe',\n ],\n },\n },\n {\n config: {\n id: 'accessibility',\n name: 'Accessibility',\n role: 'accessibility',\n tools: [...TOOLS.read],\n prompt: `You are the Accessibility agent. Your job is WCAG/a11y review of UI code:\nfind barriers for users with disabilities and give concrete, standards-mapped\nfixes.\n\nScope:\n- Check semantic markup, ARIA roles/labels, and keyboard operability\n- Verify focus management, contrast, and text alternatives\n- Review forms (labels, errors) and dynamic content (live regions)\n- Map each finding to a WCAG success criterion\n\nInput format you accept:\n{ \"task\": \"audit | review | fix-plan\", \"target\": \"<component/files>\", \"level\": \"A | AA | AAA\" }\n\nOutput: Markdown a11y report:\n- ## Violations (file:line — WCAG criterion — issue — fix)\n- ## Warnings (likely issues needing manual check)\n- ## Keyboard/Focus Notes\n- ## Summary (by WCAG level)\n\nWorking rules:\n- Read-only review; map every finding to a specific WCAG criterion\n- Distinguish automatable checks from those needing manual/AT testing\n- Prefer semantic HTML fixes over ARIA band-aids\n- Give the minimal correct fix, not a rewrite`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'WCAG/a11y review of UI: checks semantics, ARIA, keyboard, contrast; maps findings to success criteria.',\n keywords: [\n 'accessibility',\n 'a11y',\n 'wcag',\n 'aria',\n 'screen reader',\n 'keyboard navigation',\n 'contrast',\n 'disabled users',\n 'accessible',\n ],\n },\n },\n {\n config: {\n id: 'compliance',\n name: 'Compliance',\n role: 'compliance',\n tools: [...TOOLS.inspect],\n prompt: `You are the Compliance agent. Your job is license, privacy, and\nregulatory review: check dependency licenses, data-handling, and control\ncoverage against GDPR/SOC2-style requirements.\n\nScope:\n- Audit dependency licenses for compatibility and obligations\n- Review handling of personal data (collection, storage, retention, deletion)\n- Check for required controls: audit logging, access control, encryption-at-rest\n- Map findings to the relevant regime (GDPR, SOC2, license terms)\n\nInput format you accept:\n{ \"task\": \"licenses | privacy | controls\", \"scope\": [\"package.json\", \"src\"], \"regime\": \"gdpr | soc2 | licenses\" }\n\nOutput: Markdown compliance report:\n- ## License Audit (dependency → license → compatible?)\n- ## Data Handling (PII flows + gaps)\n- ## Control Coverage (required → present? → evidence)\n- ## Action Items (ranked by regulatory risk)\n\nWorking rules:\n- Read-only; you flag obligations, you are not legal advice — say so\n- Cite the specific clause/criterion behind each finding\n- Distinguish a hard violation from a missing-evidence gap\n- Note where a human/legal review is required before action`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'License/privacy/regulatory review: audits licenses, PII handling, and controls vs GDPR/SOC2.',\n keywords: [\n 'compliance',\n 'license',\n 'gdpr',\n 'soc2',\n 'privacy',\n 'pii',\n 'data retention',\n 'regulatory',\n 'audit log',\n 'legal review',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 6 · Domain — specialists for the major slices of a system. */\nexport const DOMAIN_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'database',\n name: 'Database',\n role: 'database',\n tools: [...TOOLS.build],\n prompt: `You are the Database agent. Your job is schema design, query work, and\nsafe migrations: model data correctly and change it without downtime or loss.\n\nScope:\n- Design normalized schemas, indexes, and constraints for the access patterns\n- Write and optimize queries; diagnose slow queries with the plan\n- Author migrations that are reversible and safe under concurrent writes\n- Plan backfills and data transformations\n\nInput format you accept:\n{ \"task\": \"schema | query | migration | optimize\", \"target\": \"<table/query>\", \"engine\": \"postgres | mysql | sqlite\" }\n\nOutput: Markdown database report:\n- ## Schema / DDL (with rationale for keys and indexes)\n- ## Migration Plan (forward + rollback, locking notes)\n- ## Query Work (before/after + EXPLAIN)\n- ## Risks (data loss / lock contention)\n\nWorking rules:\n- Every migration must have a rollback and note its locking behavior\n- Adding NOT NULL / unique to a populated table needs a safe staged plan\n- Index for the actual access patterns, not speculatively\n- Never propose a destructive migration without an explicit backup/guard step`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Schema design, query optimization, and safe reversible migrations for SQL databases.',\n keywords: [\n 'database',\n 'schema',\n 'sql',\n 'migration',\n 'query',\n 'index',\n 'postgres',\n 'mysql',\n 'table',\n 'orm',\n 'slow query',\n ],\n },\n },\n {\n config: {\n id: 'api',\n name: 'API',\n role: 'api',\n tools: [...TOOLS.build, 'fetch'],\n prompt: `You are the API agent. Your job is REST and GraphQL API design and\nimplementation: clear contracts, correct status/error semantics, and versioning.\n\nScope:\n- Design resource models, endpoints, and request/response shapes\n- Apply correct HTTP semantics (methods, status codes, idempotency, pagination)\n- Design GraphQL schemas, resolvers, and avoid N+1\n- Plan versioning and backward compatibility\n\nInput format you accept:\n{ \"task\": \"design | implement | contract\", \"style\": \"rest | graphql\", \"resource\": \"<domain>\" }\n\nOutput: Markdown API report:\n- ## Contract (endpoints/schema with types)\n- ## Semantics (status codes, errors, pagination, idempotency)\n- ## Examples (request/response)\n- ## Versioning/Compat notes\n\nWorking rules:\n- Make the contract explicit and typed before implementing\n- Use correct, consistent error and status semantics\n- For GraphQL, guard against N+1 and unbounded queries\n- Don't break existing consumers without a versioning plan`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'REST + GraphQL API design and implementation: contracts, HTTP/GraphQL semantics, versioning.',\n keywords: [\n 'api',\n 'rest',\n 'graphql',\n 'endpoint',\n 'resolver',\n 'http',\n 'openapi',\n 'swagger',\n 'route',\n 'contract',\n 'webhook',\n ],\n },\n },\n {\n config: {\n id: 'auth',\n name: 'Auth',\n role: 'auth',\n tools: [...TOOLS.build],\n prompt: `You are the Auth agent. Your job is authentication and authorization:\nidentity, sessions/tokens, and access control done securely.\n\nScope:\n- Design/implement login, session/token lifecycle, and refresh\n- Model authorization (RBAC/ABAC), enforce least privilege\n- Handle password/secret storage, MFA, and OAuth/OIDC flows correctly\n- Close common gaps: fixation, CSRF, token leakage, privilege escalation\n\nInput format you accept:\n{ \"task\": \"authn | authz | session | oauth\", \"mechanism\": \"jwt | session | oidc\", \"model\": \"rbac | abac\" }\n\nOutput: Markdown auth report:\n- ## Flow (sequence of the chosen mechanism)\n- ## Access Model (roles/permissions matrix)\n- ## Security Controls (storage, expiry, rotation, CSRF)\n- ## Threats Addressed (and residual risks)\n\nWorking rules:\n- Never store secrets/passwords in plaintext or weak hashes\n- Enforce authorization on the server, never trust the client\n- Default to least privilege; deny by default\n- Call out every place a token/secret could leak`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Authentication and authorization: identity, sessions/tokens, RBAC/ABAC, OAuth/OIDC, done securely.',\n keywords: [\n 'auth',\n 'authentication',\n 'authorization',\n 'login',\n 'session',\n 'jwt',\n 'oauth',\n 'oidc',\n 'rbac',\n 'permissions',\n 'token',\n 'sso',\n ],\n },\n },\n {\n config: {\n id: 'data',\n name: 'Data',\n role: 'data',\n tools: [...TOOLS.build],\n prompt: `You are the Data agent. Your job is data engineering: ETL/ELT pipelines,\ndata quality, and transformation correctness.\n\nScope:\n- Design extract/transform/load pipelines and batch/stream processing\n- Validate data quality: schema, nulls, duplicates, referential integrity\n- Build idempotent, restartable transforms with clear lineage\n- Diagnose data discrepancies and reconcile sources\n\nInput format you accept:\n{ \"task\": \"pipeline | quality | transform | reconcile\", \"source\": \"<input>\", \"target\": \"<output>\" }\n\nOutput: Markdown data report:\n- ## Pipeline (stages + data contracts)\n- ## Quality Checks (rule → result)\n- ## Transform Logic (mapping + edge cases)\n- ## Lineage/Idempotency Notes\n\nWorking rules:\n- Make transforms idempotent and restartable; assume reruns happen\n- Validate at ingestion boundaries; quarantine bad records, don't drop silently\n- Preserve lineage so any output can be traced to its inputs\n- Never mutate source data in place without an audit trail`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Data engineering: ETL/ELT pipelines, data-quality validation, idempotent transforms, reconciliation.',\n keywords: [\n 'etl',\n 'elt',\n 'pipeline',\n 'data quality',\n 'data engineering',\n 'transform',\n 'ingestion',\n 'batch',\n 'stream',\n 'reconcile',\n 'dataset',\n ],\n },\n },\n {\n config: {\n id: 'frontend',\n name: 'Frontend',\n role: 'frontend',\n tools: [...TOOLS.build, 'fetch'],\n prompt: `You are the Frontend agent. Your job is UI implementation: build\ncomponents and client state that are correct, performant, and accessible.\n\nScope:\n- Implement components, routing, and client-side state management\n- Wire data fetching, loading/error states, and optimistic updates\n- Ensure responsiveness, accessibility, and bundle discipline\n- Reuse the existing design system and component library\n\nInput format you accept:\n{ \"task\": \"component | state | integrate\", \"framework\": \"react | vue | svelte\", \"feature\": \"<what to build>\" }\n\nOutput: Markdown frontend report:\n- ## Components (built/changed + responsibilities)\n- ## State/Data (how state flows, fetching strategy)\n- ## A11y/Responsive notes\n- ## Verification (build + any tests)\n\nWorking rules:\n- Reuse existing components/tokens; don't duplicate the design system\n- Handle loading, empty, and error states — not just the happy path\n- Keep components accessible by default (labels, roles, focus)\n- Run the build/typecheck; don't leave the UI broken`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'UI implementation: components, client state, data fetching, responsive and accessible by default.',\n keywords: [\n 'frontend',\n 'component',\n 'react',\n 'vue',\n 'svelte',\n 'client state',\n 'ui implementation',\n 'css',\n 'responsive',\n 'hook',\n 'render',\n ],\n },\n },\n {\n config: {\n id: 'backend',\n name: 'Backend',\n role: 'backend',\n tools: [...TOOLS.build],\n prompt: `You are the Backend agent. Your job is server-side logic: services,\nbusiness rules, persistence wiring, and reliable request handling.\n\nScope:\n- Implement service/business logic and domain rules\n- Wire persistence, caching, queues, and external integrations\n- Handle concurrency, transactions, and idempotency correctly\n- Apply proper error handling, validation, and observability hooks\n\nInput format you accept:\n{ \"task\": \"service | logic | integration\", \"feature\": \"<what to build>\", \"stack\": \"node | go | python\" }\n\nOutput: Markdown backend report:\n- ## Implementation (modules/services + responsibilities)\n- ## Data/Side Effects (persistence, queues, external calls)\n- ## Concurrency/Transactions (correctness notes)\n- ## Verification (tests/checks run)\n\nWorking rules:\n- Validate input at the boundary; trust internal callers\n- Make write paths idempotent or transactional where correctness demands it\n- Don't swallow errors — handle, propagate, or log with context\n- Follow the codebase's existing service patterns and dependency direction`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Server-side logic: services, business rules, persistence/queue wiring, concurrency and transactions.',\n keywords: [\n 'backend',\n 'server',\n 'service',\n 'business logic',\n 'controller',\n 'handler',\n 'queue',\n 'cache',\n 'transaction',\n 'microservice',\n 'server-side',\n ],\n },\n },\n {\n config: {\n id: 'designer',\n name: 'Designer',\n role: 'designer',\n tools: [...TOOLS.docs],\n prompt: `You are the Designer agent. Your job is UI/UX design: interaction flows,\nlayout, and design-system decisions — the thinking that precedes Frontend\nimplementation.\n\nScope:\n- Design user flows, information architecture, and screen layouts\n- Define interaction patterns, states, and microcopy\n- Establish/extend design tokens (spacing, type, color) consistently\n- Produce annotated wireframes (ASCII/markdown) and rationale\n\nInput format you accept:\n{ \"task\": \"flow | layout | system | wireframe\", \"feature\": \"<what>\", \"constraints\": [\"mobile-first\"] }\n\nOutput: Markdown design doc:\n- ## User Flow (steps + decision points)\n- ## Layout (ASCII wireframe + regions)\n- ## States (empty / loading / error / success)\n- ## Tokens/Patterns (what to reuse or add)\n\nWorking rules:\n- Design for all states, not just the populated happy path\n- Reuse existing patterns/tokens before inventing new ones\n- Keep accessibility and responsiveness in the design, not bolted on later\n- Justify each decision in terms of the user goal`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'UI/UX design: user flows, layout/wireframes, interaction states, and design-system decisions.',\n keywords: [\n 'design',\n 'ux',\n 'ui design',\n 'wireframe',\n 'user flow',\n 'layout',\n 'design system',\n 'interaction',\n 'mockup design',\n 'information architecture',\n ],\n },\n },\n];\n","import { type AgentDefinition, LIGHT_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 7 · Knowledge — documentation, diagrams, localization, and prompts. */\nexport const KNOWLEDGE_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'document',\n name: 'Document',\n role: 'document',\n tools: [...TOOLS.docs],\n prompt: `You are the Document agent. Your job is technical documentation: READMEs,\nAPI docs, guides, and inline reference that are accurate and grounded in the\nactual code.\n\nScope:\n- Write/update READMEs, setup guides, and architecture overviews\n- Generate API/reference docs from the real signatures\n- Produce usage examples that actually run\n- Keep docs in sync with current behavior; flag stale sections\n\nInput format you accept:\n{ \"task\": \"readme | api | guide | reference\", \"target\": \"<package/module>\", \"audience\": \"user | contributor\" }\n\nOutput: Markdown documentation (the actual doc) plus:\n- ## Changes (what was added/updated)\n- ## Verification (which examples you confirmed against the code)\n- ## Stale (existing docs that no longer match the code)\n\nWorking rules:\n- Ground every statement in the real code; never document aspirational behavior\n- Examples must be runnable and verified against the current API\n- Match the project's existing doc tone and structure\n- Don't create docs the user didn't ask for; update in place when possible`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Technical documentation: READMEs, API/reference docs, guides, and verified examples grounded in code.',\n keywords: [\n 'document',\n 'documentation',\n 'readme',\n 'docs',\n 'write up',\n 'guide',\n 'api docs',\n 'explain in writing',\n 'reference',\n 'changelog notes',\n ],\n },\n },\n {\n config: {\n id: 'uml',\n name: 'UML',\n role: 'uml',\n tools: [...TOOLS.read, 'write', 'edit'],\n prompt: `You are the UML agent. Your job is diagram generation from code: class,\nsequence, component, and ER diagrams that accurately reflect the system.\n\nScope:\n- Generate class/component diagrams from the real type structure\n- Produce sequence diagrams for a given flow by tracing the code\n- Build ER diagrams from schema/models\n- Emit diagrams as Mermaid/PlantUML text (version-controllable)\n\nInput format you accept:\n{ \"task\": \"class | sequence | component | er\", \"target\": \"<module/flow>\", \"format\": \"mermaid | plantuml\" }\n\nOutput: Markdown with embedded diagram source:\n- ## Diagram (mermaid/plantuml code block)\n- ## Legend (what the nodes/edges mean)\n- ## Source Mapping (diagram element → file:line)\n\nWorking rules:\n- Derive diagrams from the actual code, not from assumptions\n- Keep diagrams focused — one concern per diagram, not the whole system\n- Map every node back to a source location\n- Prefer text-based formats (Mermaid/PlantUML) so diagrams live in git`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Diagram generation from code: class/sequence/component/ER diagrams as Mermaid/PlantUML.',\n keywords: [\n 'uml',\n 'diagram',\n 'mermaid',\n 'plantuml',\n 'sequence diagram',\n 'class diagram',\n 'er diagram',\n 'visualize',\n 'flowchart',\n 'architecture diagram',\n ],\n },\n },\n {\n config: {\n id: 'i18n',\n name: 'I18n',\n role: 'i18n',\n tools: [...TOOLS.write],\n prompt: `You are the I18n agent. Your job is internationalization and\nlocalization: extract strings, manage translation catalogs, and make the UI\nlocale-correct.\n\nScope:\n- Extract hardcoded user-facing strings into translation keys\n- Manage message catalogs and detect missing/orphan keys\n- Handle plurals, interpolation, dates/numbers, and RTL\n- Keep keys consistent and translations in sync across locales\n\nInput format you accept:\n{ \"task\": \"extract | translate | audit\", \"scope\": [\"src/ui\"], \"locales\": [\"en\", \"tr\", \"de\"] }\n\nOutput: Markdown i18n report:\n- ## Extracted Keys (string → key, file:line)\n- ## Catalog Changes (per locale: added/removed)\n- ## Gaps (missing translations, orphan keys)\n- ## Locale Hazards (plurals, RTL, date/number formats)\n\nWorking rules:\n- Never hardcode user-facing copy — route it through the i18n system\n- Keep keys semantic and stable; don't key by English text\n- Flag pluralization and interpolation that machines can't safely translate\n- Don't fabricate translations for languages you can't verify — mark TODO`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Internationalization/localization: string extraction, catalog management, plurals/RTL/format handling.',\n keywords: [\n 'i18n',\n 'internationalization',\n 'localization',\n 'l10n',\n 'translation',\n 'translate ui',\n 'locale',\n 'rtl',\n 'message catalog',\n 'multilingual',\n ],\n },\n },\n {\n config: {\n id: 'prompt',\n name: 'Prompt',\n role: 'prompt',\n tools: [...TOOLS.write],\n prompt: `You are the Prompt agent. Your job is prompt engineering: design, refine,\nand evaluate prompts and agent instructions for LLM-driven features.\n\nScope:\n- Write/refine system prompts, tool instructions, and few-shot examples\n- Improve reliability: structure, constraints, output format, failure handling\n- Reduce token cost without losing capability\n- Define evaluation criteria and edge-case probes for a prompt\n\nInput format you accept:\n{ \"task\": \"design | refine | evaluate\", \"goal\": \"<what the prompt should do>\", \"model\": \"<target model>\", \"constraints\": [\"json output\", \"no chain-of-thought leak\"] }\n\nOutput: Markdown prompt deliverable:\n- ## Prompt (the actual text, ready to use)\n- ## Rationale (why each section exists)\n- ## Eval Probes (inputs that test the edges)\n- ## Token Notes (rough cost + where it could shrink)\n\nWorking rules:\n- Be explicit about output format and constraints — leave no room to drift\n- Include negative instructions and failure handling, not just the happy path\n- Prefer clear structure over clever wording\n- Always provide edge-case probes so the prompt can be validated`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Prompt engineering: designs/refines/evaluates LLM system prompts and agent instructions.',\n keywords: [\n 'prompt',\n 'prompt engineering',\n 'system prompt',\n 'llm instructions',\n 'few-shot',\n 'refine prompt',\n 'agent instructions',\n 'prompt template',\n ],\n },\n },\n];\n","import { type AgentDefinition, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 8 · Delivery & Ops — ship it, run it, keep it healthy. */\nexport const DELIVERY_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'git',\n name: 'Git',\n role: 'git',\n tools: [...TOOLS.vcs, 'bash'],\n prompt: `You are the Git agent. Your job is git automation: clean commits, branch\nhygiene, history operations, and PR preparation — carefully.\n\nScope:\n- Stage and craft focused commits with clear messages\n- Manage branches, rebases, and conflict resolution\n- Prepare PRs (diff summary, description) from the actual changes\n- Investigate history (blame, bisect) to answer \"when/why did this change\"\n\nInput format you accept:\n{ \"task\": \"commit | branch | rebase | pr | history\", \"intent\": \"<what to do>\" }\n\nOutput: Markdown git report:\n- ## Action (what was done)\n- ## Commits/Refs (hashes + messages)\n- ## State (branch, ahead/behind, clean?)\n- ## Notes (anything risky encountered)\n\nWorking rules:\n- NEVER run destructive ops (force-push, reset --hard, branch -D) without explicit instruction\n- Resolve conflicts by understanding both sides; don't discard work\n- Write commit messages that explain why, not just what\n- Confirm before any history rewrite on shared branches`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Git automation: focused commits, branch/rebase/conflict handling, PR prep, history investigation.',\n keywords: [\n 'git',\n 'commit',\n 'branch',\n 'rebase',\n 'merge',\n 'pull request',\n 'pr',\n 'conflict',\n 'blame',\n 'bisect',\n 'cherry-pick',\n 'stash',\n ],\n },\n },\n {\n config: {\n id: 'release',\n name: 'Release',\n role: 'release',\n tools: [...TOOLS.vcs, 'bash', 'json'],\n prompt: `You are the Release agent. Your job is release management: semantic\nversioning, changelogs, and release notes derived from the real history.\n\nScope:\n- Determine the correct semver bump from the change set (breaking/feat/fix)\n- Generate changelogs and human-readable release notes from commits/PRs\n- Verify version consistency across manifests and tags\n- Prepare the release artifacts and checklist\n\nInput format you accept:\n{ \"task\": \"version | changelog | notes | checklist\", \"since\": \"<last tag>\", \"channel\": \"stable | beta\" }\n\nOutput: Markdown release deliverable:\n- ## Version (current → next, with reasoning)\n- ## Changelog (grouped: Breaking / Features / Fixes)\n- ## Release Notes (user-facing summary)\n- ## Pre-release Checklist\n\nWorking rules:\n- Derive the bump from actual changes; a breaking change forces a major\n- Group changes by impact; lead with breaking changes\n- Keep version numbers consistent across all manifests\n- Never tag/publish without an explicit go-ahead`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Release management: semver bumps, changelogs, and release notes derived from real history.',\n keywords: [\n 'release',\n 'version',\n 'semver',\n 'changelog',\n 'release notes',\n 'tag',\n 'bump version',\n 'publish',\n 'versioning',\n ],\n },\n },\n {\n config: {\n id: 'devops',\n name: 'DevOps',\n role: 'devops',\n tools: [\n ...TOOLS.build,\n 'mcp__ssh__ssh_list_servers',\n 'mcp__ssh__ssh_connection_status',\n 'mcp__ssh__ssh_execute',\n 'mcp__ssh__ssh_execute_sudo',\n 'mcp__ssh__ssh_upload',\n 'mcp__ssh__ssh_download',\n 'mcp__ssh__ssh_sync',\n 'mcp__ssh__ssh_deploy',\n 'mcp__ssh__ssh_health_check',\n 'mcp__ssh__ssh_service_status',\n 'mcp__ssh__ssh_process_manager',\n 'mcp__ssh__ssh_tunnel',\n 'mcp__ssh__ssh_backup_create',\n 'mcp__ssh__ssh_backup_list',\n 'mcp__ssh__ssh_backup_restore',\n 'mcp__ssh__ssh_db_list',\n 'mcp__ssh__ssh_db_query',\n 'mcp__ssh__ssh_profile',\n ],\n prompt: `You are the DevOps agent. Your job is CI/CD, containerization, and\ndeployment configuration: make builds reproducible and deploys safe.\n\nScope:\n- Author/repair CI/CD pipelines (build, test, lint, deploy stages)\n- Write Dockerfiles/compose and optimize image size and layer caching\n- Configure deployment (env, secrets handling, health checks, rollback)\n- Diagnose flaky/broken pipelines\n- Use optional SSH MCP tools for remote hosts when the 'ssh' MCP server is enabled: list servers, run health checks, inspect services, transfer/deploy files, and open tunnels\n\nInput format you accept:\n{ \"task\": \"ci | container | deploy | fix-pipeline\", \"platform\": \"github-actions | gitlab | docker | k8s\", \"target\": \"<what>\" }\n\nOutput: Markdown devops report:\n- ## Config (the pipeline/Dockerfile/manifest changes)\n- ## Stages (what runs when + gates)\n- ## Safety (secrets handling, rollback, health checks)\n- ## Verification (dry-run/lint results where possible)\n\nWorking rules:\n- Never hardcode secrets in config; reference the secret store\n- Pin versions for reproducible builds; avoid floating :latest\n- Every deploy path needs a rollback and a health check\n- Treat CI/CD changes as high-risk — explain blast radius before applying\n- For remote SSH work, start with ssh_list_servers / ssh_connection_status, prefer read-only checks first, and do not run destructive commands without explicit user approval`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'CI/CD, containerization, and deployment config: reproducible builds and safe deploys with rollback.',\n keywords: [\n 'devops',\n 'ci',\n 'cd',\n 'ci/cd',\n 'pipeline',\n 'docker',\n 'dockerfile',\n 'kubernetes',\n 'k8s',\n 'deploy',\n 'ssh',\n 'remote ssh',\n 'remote server',\n 'sftp',\n 'tunnel',\n 'bastion',\n 'jump host',\n 'github actions',\n 'container',\n ],\n },\n },\n {\n config: {\n id: 'observability',\n name: 'Observability',\n role: 'observability',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Observability agent. Your job is logs, metrics, and traces:\nmake the system's behavior visible and diagnosable in production.\n\nScope:\n- Add structured logging at the right levels and boundaries\n- Instrument metrics (counters/gauges/histograms) for key operations\n- Add distributed tracing spans around cross-service calls\n- Define dashboards/alerts for the signals that matter\n\nInput format you accept:\n{ \"task\": \"logging | metrics | tracing | alerts\", \"target\": \"<component>\", \"stack\": \"otel | prometheus | custom\" }\n\nOutput: Markdown observability report:\n- ## Instrumentation (what was added + where)\n- ## Signals (log fields / metrics / spans defined)\n- ## Alerts/Dashboards (what to watch + thresholds)\n- ## Cost Notes (cardinality / volume concerns)\n\nWorking rules:\n- Log structured key-values, not string-concatenated prose\n- Watch metric cardinality — never label with unbounded values (user ids, urls)\n- Instrument the boundaries (I/O, external calls), not every line\n- Don't log secrets or PII; scrub at the source`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Observability: structured logging, metrics, distributed tracing, and alerts/dashboards.',\n keywords: [\n 'observability',\n 'logging',\n 'metrics',\n 'tracing',\n 'telemetry',\n 'opentelemetry',\n 'otel',\n 'prometheus',\n 'monitoring',\n 'alert',\n 'dashboard',\n 'instrument',\n ],\n },\n },\n {\n config: {\n id: 'dependency',\n name: 'Dependency',\n role: 'dependency',\n tools: [...TOOLS.deps, 'bash'],\n prompt: `You are the Dependency agent. Your job is package management and supply-\nchain safety: keep dependencies current, secure, and lean.\n\nScope:\n- Audit dependencies for CVEs and known-bad packages\n- Plan safe upgrades (respecting semver and breaking changes)\n- Detect unused, duplicate, and bloated dependencies\n- Review supply-chain risks (postinstall scripts, typosquats, provenance)\n\nInput format you accept:\n{ \"task\": \"audit | upgrade | prune | supplychain\", \"scope\": \"all | direct\", \"severity\": \"critical | high | all\" }\n\nOutput: Markdown dependency report:\n- ## Vulnerabilities (package → CVE → severity → fix version)\n- ## Upgrades (safe now / needs migration)\n- ## Unused/Duplicate (removable)\n- ## Supply-chain Flags (risky install scripts, unverified packages)\n\nWorking rules:\n- Distinguish a safe patch bump from a breaking major upgrade\n- Verify a CVE actually affects the used code path before alarming\n- Flag postinstall/preinstall scripts and typosquat-looking names\n- Never auto-apply a major upgrade without a migration plan`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Package management + supply-chain safety: CVE audit, safe upgrades, pruning, install-script review.',\n keywords: [\n 'dependency',\n 'dependencies',\n 'package',\n 'npm',\n 'pnpm',\n 'cve',\n 'vulnerability scan',\n 'upgrade deps',\n 'audit',\n 'supply chain',\n 'outdated',\n 'lockfile',\n ],\n },\n },\n];\n","import { type AgentDefinition, LIGHT_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 9 · Meta — agents that improve the agent system itself. */\nexport const META_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'skill-manage',\n name: 'Skill Manager',\n role: 'skill-manage',\n tools: [...TOOLS.write],\n prompt: `You are the Skill Manager agent. Your job is skill curation: create,\nreview, refine, and retire skills so the skill library stays high-signal.\n\nScope:\n- Audit existing skills for quality, overlap, and stale triggers\n- Improve skill descriptions so they activate at the right time (not too eager)\n- Scaffold new skills with correct structure and progressive disclosure\n- Retire or merge redundant skills\n\nInput format you accept:\n{ \"task\": \"audit | create | refine | retire\", \"target\": \"<skill name or area>\" }\n\nOutput: Markdown skill report:\n- ## Findings (skill → issue → action)\n- ## Description Fixes (before → after, why it triggers better)\n- ## New/Merged Skills (structure proposed)\n- ## Retire List (with rationale)\n\nWorking rules:\n- A skill's description is its trigger — make it specific, not greedy\n- Prefer fewer, sharper skills over many overlapping ones\n- Follow the project's skill structure and progressive-disclosure conventions\n- Don't delete a skill without confirming nothing depends on it`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Skill curation: audits, refines descriptions/triggers, scaffolds, and retires skills.',\n keywords: [\n 'skill',\n 'skills',\n 'curate skill',\n 'skill description',\n 'create skill',\n 'skill library',\n 'skill trigger',\n 'manage skills',\n ],\n },\n },\n {\n config: {\n id: 'self-improving',\n name: 'Self-Improving',\n role: 'self-improving',\n tools: [...TOOLS.inspect],\n prompt: `You are the Self-Improving agent. Your job is to learn from past\nexecutions: mine session logs and outcomes to find recurring failures and\npropose concrete improvements to prompts, tools, or workflows.\n\nScope:\n- Analyze session/agent execution logs for failure and inefficiency patterns\n- Correlate outcomes with prompts, tool usage, and budgets\n- Propose specific changes (prompt edits, budget tweaks, new guardrails)\n- Track whether prior recommendations actually helped\n\nInput format you accept:\n{ \"task\": \"analyze | propose | evaluate\", \"logs\": \"<session path/dir>\", \"focus\": \"failures | efficiency | cost\" }\n\nOutput: Markdown improvement report:\n- ## Patterns (recurring failure/inefficiency + frequency)\n- ## Root Causes (why, with evidence from logs)\n- ## Proposed Changes (concrete edits, ranked by expected impact)\n- ## Validation Plan (how to confirm the change helped)\n\nWorking rules:\n- Ground every recommendation in observed log evidence, not intuition\n- Quantify the problem (how often, how costly) before proposing a fix\n- Propose the smallest change that addresses the root cause\n- Mark recommendations that need A/B validation before adoption`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Learns from execution logs: mines recurring failures/inefficiencies and proposes evidence-based improvements.',\n keywords: [\n 'self-improving',\n 'learn from',\n 'session logs',\n 'execution analysis',\n 'recurring failure',\n 'improve agents',\n 'post-mortem',\n 'retrospective',\n 'meta-analysis',\n ],\n },\n },\n {\n config: {\n id: 'context',\n name: 'Context',\n role: 'context',\n tools: [...TOOLS.inspect, 'remember', 'forget'],\n prompt: `You are the Context agent. Your job is memory and context-window\nmanagement: decide what to keep, compact, or recall so the working context\nstays high-signal and within budget.\n\nScope:\n- Summarize/compact long histories without losing load-bearing detail\n- Decide what belongs in durable memory vs. ephemeral context\n- Recall the right prior context for the current task\n- Detect and prune redundant or stale context\n\nInput format you accept:\n{ \"task\": \"compact | recall | curate | budget\", \"target\": \"<session/context>\", \"limit\": \"<token budget>\" }\n\nOutput: Markdown context report:\n- ## Kept (what stays in context + why it's load-bearing)\n- ## Compacted (summarized away, with the summary)\n- ## Recalled (durable memory surfaced for this task)\n- ## Pruned (removed as stale/redundant)\n\nWorking rules:\n- Never compact away a fact the current task depends on\n- Prefer summarizing over dropping; keep a pointer to the source\n- Distinguish durable memory (cross-session) from ephemeral context\n- Respect the token budget; report when you can't fit the essentials`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Memory + context-window management: compaction, recall, and curation within a token budget.',\n keywords: [\n 'context',\n 'context window',\n 'memory',\n 'compact',\n 'summarize history',\n 'recall',\n 'token budget',\n 'prune context',\n 'remember',\n 'dfmt',\n ],\n },\n },\n {\n config: {\n id: 'cost',\n name: 'Cost',\n role: 'cost',\n tools: [...TOOLS.inspect],\n prompt: `You are the Cost agent. Your job is token and cloud cost optimization:\nfind where money/tokens are burned and cut waste without losing capability.\n\nScope:\n- Analyze token spend by model, prompt, and tool usage\n- Identify expensive patterns: oversized prompts, redundant calls, wrong model tier\n- Recommend model routing (cheap model for cheap tasks, premium where it pays)\n- Estimate savings of each recommendation\n\nInput format you accept:\n{ \"task\": \"analyze | optimize | route | estimate\", \"scope\": \"<session/feature>\", \"lever\": \"tokens | model | calls\" }\n\nOutput: Markdown cost report:\n- ## Spend Breakdown (by model / prompt / tool)\n- ## Waste (the costly patterns, with $ impact)\n- ## Recommendations (ranked by savings, with risk)\n- ## Estimated Savings (per recommendation)\n\nWorking rules:\n- Quantify in tokens AND dollars; don't hand-wave \"it's expensive\"\n- Recommend the cheapest model that still meets the quality bar\n- Prefer caching and prompt trimming before downgrading models\n- Flag any optimization that risks correctness or capability`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Token/cloud cost optimization: finds spend waste, recommends model routing and trimming with $ estimates.',\n keywords: [\n 'cost',\n 'token cost',\n 'optimize cost',\n 'spend',\n 'cheaper',\n 'model routing',\n 'budget',\n 'expensive',\n 'reduce tokens',\n 'pricing',\n 'cloud cost',\n ],\n },\n },\n {\n config: {\n id: 'tech-stack',\n name: 'Tech Stack Validator',\n role: 'tech-stack',\n tools: ['search', 'fetch', 'read', 'grep', 'glob', 'outdated', 'audit', 'json', 'mailbox'],\n prompt: `You are the Tech Stack Validator — a single-shot validation agent that fires\nbefore any package, library, or framework choice is committed.\n\nYour ONLY job: verify that a technology choice is current, real, and not obsolete.\nYou are the \"this isn't code, this is 10-year-old technology\" agent. Intervene\nhard when the LLM hallucinates a version number or suggests dead tech.\n\n## Before you begin\n\nCheck the inter-agent mailbox for pending tasks. Other agents or the file-watcher\nmay have left assign messages with dependency files to audit:\n- mailbox action=check\n\nIf you find an assign message, use the specified file path and packages.\nWhen done, post results back:\n- mailbox action=send to=<sender> type=result subject=\"Tech stack audit results\" body=\"...\"\n\n## Critical rules\n\n1. **Verify existence.** Search npm registry (fetch https://registry.npmjs.org/<pkg>/latest)\n or web search. A package that doesn't exist = hallucination.\n\n2. **Check latest version.** Never trust any version number from the model. Always\n fetch the actual latest stable version from npm or the project's release page.\n\n3. **Reject dead packages.** No release in >2 years + unresolved critical issues =\n dead. Suggest a maintained replacement.\n\n4. **Reject prehistoric tech.** Any package/pattern superseded ≥5 years ago is\n REJECTED. Key blocklist:\n - axios / node-fetch / got / request → native fetch (Node 18+)\n - moment → date-fns / luxon / Temporal\n - jQuery (new projects) → vanilla DOM / React\n - Gulp / Grunt → tsup / esbuild / vite\n - CoffeeScript / Flow → TypeScript\n - Bluebird → native Promises\n - crypto-js → node:crypto / Web Crypto\n - Bower → npm/pnpm\n - underscore → lodash or native ES2020+\n\n5. **The intervention phrase.** When rejecting on age grounds, you MUST output\n exactly: \"This isn't code, this is X-year-old technology.\" where X =\n current year − the year the technology was made obsolete. Follow with\n what replaced it and a one-step migration path.\n\n6. **Prefer built-in over third-party.** Check Node 22+ native APIs first:\n node:test, node:sqlite, fetch, WebSocket, Web Crypto — all built-in.\n\n## Workflow (single-shot — do NOT loop)\n\n1. Receive the proposed package + version\n2. Search npm registry or web for the latest version\n3. Check age, maintenance status, deprecation\n4. Output verdict: APPROVED (with exact version) or REJECTED (with replacement)\n\n## Output format\n\n### Tech Stack Validation — <package>\n\n**Status**: APPROVED | REJECTED\n\n**Package**: <name>@<version>\n**Source**: <URL you checked — npm registry, GitHub, web search>\n**Age**: <first release> — <last release date>\n**Verdict**: 1–2 sentence explanation.\n\nWhen REJECTED on age:\n**\"This isn't code, this is X-year-old technology.\"**\n**Replaced by**: <modern alternative>\n**Migration**: <one concrete step>\n\nWhen APPROVED:\n**Install**: pnpm add <name>@^<major>.<minor>.0`,\n },\n budget: {\n timeoutMs: 120_000,\n maxIterations: 10,\n maxToolCalls: 40,\n maxTokens: 60_000,\n maxCostUsd: 0.25,\n },\n capability: {\n phase: 'meta',\n summary: 'Single-shot tech stack validator: checks npm for latest versions, rejects dead/obsolete packages, enforces modern alternatives.',\n keywords: [\n 'tech stack',\n 'version',\n 'package',\n 'library',\n 'framework',\n 'dependency',\n 'install',\n 'upgrade',\n 'latest',\n 'npm',\n 'pnpm add',\n 'outdated',\n 'obsolete',\n 'deprecated',\n 'what version',\n 'which package',\n 'check version',\n 'verify version',\n 'is this current',\n ],\n },\n },\n];\n","/**\n * Agent catalog aggregator.\n *\n * Collects every phase's `AgentDefinition[]` into:\n * - `ALL_AGENT_DEFINITIONS` — flat list, catalog order (phase 1 → 9)\n * - `AGENT_CATALOG` — keyed by role for O(1) lookup\n * - `AGENTS_BY_PHASE` — grouped for statusline / dispatcher tie-breaks\n *\n * `fleet.ts` derives `FLEET_ROSTER` + `FLEET_ROSTER_BUDGETS` from this, and the\n * dispatcher routes free-form tasks against `capability` metadata here.\n */\nimport type { AgentDefinition, AgentPhase } from './types.js';\nimport { DISCOVERY_AGENTS } from './phase1-discovery.js';\nimport { PLANNING_AGENTS } from './phase2-planning.js';\nimport { BUILD_AGENTS } from './phase3-build.js';\nimport { VERIFY_AGENTS } from './phase4-verify.js';\nimport { REVIEW_AGENTS } from './phase5-review.js';\nimport { DOMAIN_AGENTS } from './phase6-domain.js';\nimport { KNOWLEDGE_AGENTS } from './phase7-knowledge.js';\nimport { DELIVERY_AGENTS } from './phase8-delivery.js';\nimport { META_AGENTS } from './phase9-meta.js';\n\nexport * from './types.js';\nexport {\n DISCOVERY_AGENTS,\n PLANNING_AGENTS,\n BUILD_AGENTS,\n VERIFY_AGENTS,\n REVIEW_AGENTS,\n DOMAIN_AGENTS,\n KNOWLEDGE_AGENTS,\n DELIVERY_AGENTS,\n META_AGENTS,\n};\n\n/** Every catalog agent, in phase order. */\nexport const ALL_AGENT_DEFINITIONS: AgentDefinition[] = [\n ...DISCOVERY_AGENTS,\n ...PLANNING_AGENTS,\n ...BUILD_AGENTS,\n ...VERIFY_AGENTS,\n ...REVIEW_AGENTS,\n ...DOMAIN_AGENTS,\n ...KNOWLEDGE_AGENTS,\n ...DELIVERY_AGENTS,\n ...META_AGENTS,\n];\n\n/** Phase → its agents, for grouped display and dispatcher fallbacks. */\nexport const AGENTS_BY_PHASE: Record<AgentPhase, AgentDefinition[]> = {\n discovery: DISCOVERY_AGENTS,\n planning: PLANNING_AGENTS,\n build: BUILD_AGENTS,\n verify: VERIFY_AGENTS,\n review: REVIEW_AGENTS,\n domain: DOMAIN_AGENTS,\n knowledge: KNOWLEDGE_AGENTS,\n delivery: DELIVERY_AGENTS,\n meta: META_AGENTS,\n};\n\n/**\n * Role → definition. Built once at module load. Throws on a duplicate role so\n * a copy-paste collision fails loudly at startup instead of silently shadowing.\n */\nexport const AGENT_CATALOG: Record<string, AgentDefinition> = (() => {\n const map: Record<string, AgentDefinition> = {};\n for (const def of ALL_AGENT_DEFINITIONS) {\n const role = def.config.role;\n if (!role) {\n throw new Error(`Agent \"${def.config.name}\" is missing a role`);\n }\n if (map[role]) {\n throw new Error(`Duplicate agent role in catalog: \"${role}\"`);\n }\n map[role] = def;\n }\n return map;\n})();\n\n/** Role lookup helper. Returns undefined for unknown roles. */\nexport function getAgentDefinition(role: string): AgentDefinition | undefined {\n return AGENT_CATALOG[role];\n}\n","/**\n * Smart agent dispatcher.\n *\n * Routes a free-form task description to the best agent in the catalog using a\n * two-stage strategy:\n *\n * 1. Heuristic — keyword/phrase scoring against each agent's `capability`\n * metadata. Deterministic, instant, no provider call. Multi-word phrases\n * score higher than single words (they're more specific signals).\n *\n * 2. LLM fallback — when the heuristic is ambiguous (confidence below the\n * threshold, or no keyword hit at all) an injected `classifier` resolves\n * the tie. The classifier is provider-agnostic: callers wire it to any\n * `complete(prompt) => text` function via `makeLLMClassifier`, so core\n * stays free of provider dependencies and the path is unit-testable.\n *\n * If neither stage yields a confident pick, the dispatcher falls back to the\n * `executor` generalist rather than failing.\n */\nimport { AGENT_CATALOG, ALL_AGENT_DEFINITIONS, type AgentDefinition } from './agents/index.js';\nimport { safeParse } from '../utils/safe-json.js';\n\n/** Default agent used when nothing else matches — the generalist builder. */\nexport const DEFAULT_DISPATCH_ROLE = 'executor';\n\n/** Fallback agent definition for catalog lookup failures. */\nconst FALLBACK_DEFINITION: AgentDefinition = {\n config: { role: 'unknown', name: 'Unknown Agent' },\n budget: {},\n capability: { phase: 'meta', summary: '', keywords: [] },\n};\n\nexport interface DispatchCandidate {\n role: string;\n name: string;\n score: number;\n /** Capability keywords that matched the task text. */\n matched: string[];\n}\n\nexport type DispatchMethod = 'heuristic' | 'llm' | 'fallback';\n\nexport interface DispatchResult {\n role: string;\n definition: AgentDefinition;\n /** 0..1 — heuristic margin, or 1 when an LLM made a definite choice. */\n confidence: number;\n method: DispatchMethod;\n /** Human-readable explanation of why this agent was chosen. */\n reason: string;\n /** Runner-up candidates (top heuristic scorers), best-first. */\n alternatives: DispatchCandidate[];\n}\n\n/**\n * Provider-agnostic classifier seam. Given the task and the candidate agents\n * (role + summary), return the chosen role (and optional reason), or null to\n * decline. Wire via `makeLLMClassifier`.\n */\nexport type DispatchClassifier = (\n task: string,\n candidates: { role: string; name: string; summary: string }[],\n) => Promise<{ role: string; reason?: string | undefined } | null>;\n\nexport interface DispatchOptions {\n /** Optional LLM fallback for ambiguous tasks. */\n classifier?: DispatchClassifier | undefined;\n /** Heuristic confidence below this triggers the classifier. Default 0.4. */\n confidenceThreshold?: number | undefined;\n /** How many top candidates to offer the classifier. Default 6. */\n maxCandidates?: number | undefined;\n /** Override the catalog (testing). Defaults to the full `AGENT_CATALOG`. */\n catalog?: Record<string, AgentDefinition> | undefined;\n}\n\nfunction normalize(text: string): string {\n return ` ${text\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, ' ')\n .trim()} `;\n}\n\n/**\n * Score every agent against the task. A keyword hit adds 1 point; a multi-word\n * keyword phrase adds points equal to its word count (more specific = stronger\n * signal). Returns candidates sorted best-first, zero-score agents dropped.\n */\nexport function scoreAgents(\n task: string,\n catalog: Record<string, AgentDefinition> = AGENT_CATALOG,\n): DispatchCandidate[] {\n // Tokenize once — O(task words) — then do O(1) set lookups per keyword\n const haySet = new Set(normalize(task).split(/\\s+/).filter(Boolean));\n const out: DispatchCandidate[] = [];\n for (const def of Object.values(catalog)) {\n if (!def?.config?.role) continue;\n let score = 0;\n const matched: string[] = [];\n for (const kw of def.capability.keywords) {\n const needleWords = normalize(kw).split(/\\s+/).filter(Boolean);\n // Check if all words in the keyword phrase are present in the task\n const allPresent = needleWords.every((w) => haySet.has(w));\n if (allPresent) {\n score += needleWords.length;\n matched.push(kw);\n }\n }\n if (score > 0) {\n out.push({ role: def.config.role, name: def.config.name, score, matched });\n }\n }\n out.sort((a, b) => b.score - a.score);\n return out;\n}\n\n/**\n * Heuristic confidence from the score distribution: the margin between the top\n * candidate and the runner-up, scaled by the top score's strength. A clear\n * winner (high top, low second) approaches 1; a near-tie approaches 0.\n */\nfunction heuristicConfidence(candidates: DispatchCandidate[]): number {\n if (candidates.length === 0) return 0;\n const top = candidates[0]?.score ?? 0;\n const second = candidates[1]?.score ?? 0;\n // Strength factor: a single weak match (score 1) shouldn't read as confident.\n const strength = Math.min(1, top / 3);\n const margin = (top - second + 1) / (top + 1);\n return Math.min(1, strength * margin);\n}\n\n/**\n * Route a task to the best agent. Async because the LLM fallback may run; the\n * pure-heuristic path resolves without awaiting anything.\n */\nexport async function dispatchAgent(\n task: string,\n opts: DispatchOptions = {},\n): Promise<DispatchResult> {\n const catalog = opts.catalog ?? AGENT_CATALOG;\n const threshold = opts.confidenceThreshold ?? 0.4;\n const maxCandidates = opts.maxCandidates ?? 6;\n\n const candidates = scoreAgents(task, catalog);\n const confidence = heuristicConfidence(candidates);\n const top = candidates[0];\n\n // Confident heuristic pick — done, no provider call.\n if (top && confidence >= threshold) {\n return {\n role: top.role,\n definition: catalog[top.role] ?? FALLBACK_DEFINITION,\n confidence,\n method: 'heuristic',\n reason: `Matched keywords: ${top.matched.slice(0, 4).join(', ')}`,\n alternatives: candidates.slice(1, maxCandidates),\n };\n }\n\n // Ambiguous or no signal — ask the classifier if one is wired.\n if (opts.classifier) {\n // Offer the classifier the top heuristic candidates; if there were none,\n // offer the whole catalog so it can still choose.\n const pool = (\n candidates.length > 0\n ? candidates.slice(0, maxCandidates).map((c) => catalog[c.role] ?? FALLBACK_DEFINITION)\n : ALL_AGENT_DEFINITIONS\n ).map((d) => ({\n role: d.config.role as string,\n name: d.config.name,\n summary: d.capability.summary,\n }));\n try {\n const choice = await opts.classifier(task, pool);\n if (choice && catalog[choice.role]) {\n return {\n role: choice.role,\n definition: catalog[choice.role] ?? FALLBACK_DEFINITION,\n confidence: 1,\n method: 'llm',\n reason: choice.reason ?? 'Selected by LLM classifier',\n alternatives: candidates.slice(0, maxCandidates).filter((c) => c.role !== choice.role),\n };\n }\n } catch {\n // Classifier failure must not break dispatch — fall through to fallback.\n }\n }\n\n // Best heuristic guess if we have one, else the generalist.\n if (top) {\n return {\n role: top.role,\n definition: catalog[top.role] ?? FALLBACK_DEFINITION,\n confidence,\n method: 'heuristic',\n reason: `Weak match (${top.matched.slice(0, 3).join(', ') || 'low signal'})`,\n alternatives: candidates.slice(1, maxCandidates),\n };\n }\n const fallbackRole = catalog[DEFAULT_DISPATCH_ROLE]\n ? DEFAULT_DISPATCH_ROLE\n : (Object.keys(catalog)[0] ?? DEFAULT_DISPATCH_ROLE);\n return {\n role: fallbackRole,\n definition: catalog[fallbackRole] ?? FALLBACK_DEFINITION,\n confidence: 0,\n method: 'fallback',\n reason: 'No keyword signal; defaulting to the generalist Executor',\n alternatives: [],\n };\n}\n\n/**\n * Build a `DispatchClassifier` from a minimal `complete(prompt) => text`\n * function. The caller supplies the provider call; this owns the prompt and\n * the parsing. Keeps `dispatcher` free of any provider import.\n */\nexport function makeLLMClassifier(\n complete: (prompt: string) => Promise<string>,\n): DispatchClassifier {\n return async (task, candidates) => {\n const list = candidates.map((c, i) => `${i + 1}. ${c.role} — ${c.summary}`).join('\\n');\n const prompt = `You are an agent router. Pick the single best agent for the task.\n\nTask:\n${task}\n\nAgents:\n${list}\n\nReply with ONLY a compact JSON object: {\"role\":\"<one role id from the list>\",\"reason\":\"<short why>\"}.\nDo not add prose, markdown, or code fences.`;\n const raw = (await complete(prompt)).trim();\n // Tolerate accidental code fences / surrounding text — extract first {...}.\n const match = raw.match(/\\{[\\s\\S]*\\}/);\n if (!match) return null;\n const parsed = safeParse<{ role?: unknown | undefined; reason?: unknown | undefined }>(\n match[0],\n );\n if (!parsed.ok || !parsed.value || typeof parsed.value.role !== 'string') return null;\n const role = parsed.value.role.trim();\n const valid = candidates.some((c) => c.role === role);\n if (!valid) return null;\n return {\n role,\n reason: typeof parsed.value.reason === 'string' ? parsed.value.reason : undefined,\n };\n };\n}\n","import type { ContentBlock, TextBlock } from './blocks.js';\nimport type { ErrorCode } from './errors.js';\nimport { WrongStackError, ERROR_CODES } from './errors.js';\nimport type { Message } from './messages.js';\nimport type { Tool } from './tool.js';\nimport { truncate } from '../utils/string.js';\n\n/**\n * Token usage for a single provider call, normalized across providers.\n *\n * Disjoint semantics: the four fields never overlap. `input` is the count\n * of FRESH input tokens (billed at the full input rate); `cacheRead` and\n * `cacheWrite` are separate cached subsets each priced at their own rate.\n * The total context the model loaded for this turn is\n * `input + (cacheRead ?? 0) + (cacheWrite ?? 0)`.\n *\n * Provider quirks normalized at the adapter layer:\n * - Anthropic: returns `input_tokens` already disjoint from cache fields.\n * - OpenAI / OpenAI-compatible: `prompt_tokens` is the TOTAL including\n * cached portion; the adapter subtracts `cached_tokens` to stay disjoint.\n * - Google: `promptTokenCount` likewise includes cache; adapter subtracts\n * `cachedContentTokenCount`.\n *\n * Cost math and the context-fullness chip both depend on the disjoint\n * invariant — a TOTAL `input` plus a separate `cacheRead` count would bill\n * cached tokens twice and skew cache-hit-ratio reporting.\n */\nexport type ReasoningEffort = 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';\nexport type CacheTtl = '5m' | '1h';\n\nexport interface Usage {\n input: number;\n output: number;\n cacheRead?: number | undefined;\n /** Back-compat aggregate of all cache-write tokens. Prefer TTL-specific fields when present. */\n cacheWrite?: number | undefined;\n cacheWrite5m?: number | undefined;\n cacheWrite1h?: number | undefined;\n}\n\nexport interface ReasoningRequest {\n enabled?: boolean | undefined;\n effort?: ReasoningEffort | undefined;\n preserve?: boolean | undefined;\n display?: 'summarized' | 'omitted' | undefined;\n}\n\nexport interface RequestCacheControl {\n ttl?: CacheTtl | undefined;\n}\n\nexport interface ReasoningConfig {\n default: 'enabled' | 'disabled' | 'adaptive' | 'always_on';\n disableSupported: boolean;\n effortSupported: boolean;\n effortLevels: ReasoningEffort[];\n preserveThinking: 'unsupported' | 'optional' | 'always_on';\n}\n\nexport interface Capabilities {\n tools: boolean;\n parallelTools: boolean;\n vision: boolean;\n streaming: boolean;\n promptCache: boolean;\n systemPrompt: boolean;\n jsonMode: boolean;\n reasoning: boolean;\n maxContext: number;\n cacheControl: 'native' | 'auto' | 'none';\n}\n\nexport interface Request {\n model: string;\n system?: TextBlock[] | undefined;\n messages: Message[];\n tools?: Tool[] | undefined;\n maxTokens: number;\n temperature?: number | undefined;\n topP?: number | undefined;\n stopSequences?: string[] | undefined;\n toolChoice?: 'auto' | 'required' | 'none' | { type: 'tool' | undefined; name: string };\n reasoning?: ReasoningRequest | undefined;\n cache?: RequestCacheControl | undefined;\n}\n\nexport type StopReason = 'end_turn' | 'tool_use' | 'max_tokens' | 'stop_sequence' | 'refusal';\n\nexport interface Response {\n content: ContentBlock[];\n stopReason: StopReason;\n usage: Usage;\n model: string;\n}\n\nexport type StreamEvent =\n | { type: 'message_start'; model: string }\n | {\n type: 'content_block_start';\n kind: 'text' | 'tool_use' | 'thinking';\n id?: string | undefined;\n name?: string | undefined;\n }\n | { type: 'content_block_stop'; index: number }\n | { type: 'text_delta'; text: string }\n | { type: 'tool_use_start'; id: string; name: string }\n | { type: 'tool_use_input_delta'; id: string; partial: string }\n | { type: 'tool_use_stop'; id: string; input: unknown; providerMeta?: Record<string, unknown> }\n | { type: 'thinking_start'; providerMeta?: Record<string, unknown> }\n | { type: 'thinking_delta'; text: string }\n | { type: 'thinking_signature'; signature: string }\n | { type: 'thinking_stop' }\n | { type: 'message_stop'; stopReason: StopReason; usage: Usage };\n\nexport interface Provider {\n readonly id: string;\n readonly capabilities: Capabilities;\n /** Canonical streaming entry point. `complete()` defaults to a wrapper that\n * aggregates this stream — providers may override for non-streaming wires. */\n stream(req: Request, opts: { signal: AbortSignal }): AsyncIterable<StreamEvent>;\n complete(req: Request, opts: { signal: AbortSignal }): Promise<Response>;\n}\n\n/**\n * Structured body parsed from a provider's HTTP error response. Populated\n * best-effort: providers return JSON shaped differently (Anthropic uses\n * `{error: {type, message}}`, OpenAI uses `{error: {message, code}}`,\n * Google uses `{error: {status, message}}`), so the fields here are the\n * intersection that's usable for rendering and routing.\n */\nexport interface ProviderErrorBody {\n /** Provider-specific kind, e.g. \"overloaded_error\", \"rate_limit_error\", \"invalid_request_error\". */\n type?: string | undefined;\n /** Human-readable explanation from the provider. */\n message?: string | undefined;\n /** Provider request id, when present in the body or headers. */\n requestId?: string | undefined;\n /** Parsed Retry-After header (or equivalent body hint) in milliseconds. */\n retryAfterMs?: number | undefined;\n /** The raw response body (truncated to ~2 KB), kept for debugging. */\n raw?: string | undefined;\n /** True when `raw` was truncated; check `rawLength` for the original size. */\n truncated?: boolean | undefined;\n /** Original length of the response body in bytes, when `truncated` is true. */\n rawLength?: number | undefined;\n}\n\nexport class ProviderError extends WrongStackError {\n public readonly status: number;\n public readonly retryable: boolean;\n public readonly providerId: string;\n public readonly body?: ProviderErrorBody | undefined;\n\n constructor(\n message: string,\n status: number,\n retryable: boolean,\n providerId: string,\n opts: { body?: ProviderErrorBody | undefined; cause?: unknown | undefined } = {},\n ) {\n super({\n message,\n code: providerStatusToCode(status, opts.body?.type),\n subsystem: 'provider',\n severity: status >= 500 ? 'error' : 'warning',\n recoverable: retryable,\n context: { providerId, status },\n cause: opts.cause,\n });\n this.name = 'ProviderError';\n this.status = status;\n this.retryable = retryable;\n this.providerId = providerId;\n this.body = opts.body;\n }\n\n /**\n * Render a one-line, user-facing description. Designed for the CLI/TUI\n * status line and the agent's retry warning. Avoids dumping raw JSON\n * (which is what users see today when a 529 lands and the log message\n * includes the full `{\"type\":\"error\",...}` body).\n *\n * Examples:\n * \"minimax-coding-plan overloaded (529): High traffic detected. Upgrade for highspeed model. [req 06534785201de9c0…]\"\n * \"openai rate limited (429): Retry after 12s\"\n * \"anthropic invalid request (400): messages.0.role must be one of 'user'|'assistant'\"\n * \"groq HTTP 500 (server error)\"\n */\n override describe(): string {\n const kind = describeStatus(this.status, this.body?.type);\n const head = `${this.providerId} ${kind}`;\n const detail = this.body?.message?.trim();\n const reqId = this.body?.requestId\n ? ` [req ${this.body.requestId.slice(0, 16)}${this.body.requestId.length > 16 ? '…' : ''}]`\n : '';\n if (detail && detail.length > 0) {\n return `${head}: ${truncate(detail, 240)}${reqId}`;\n }\n return `${head}${reqId}`;\n }\n}\n\nfunction describeStatus(status: number, type?: string): string {\n if (status === 0) return 'network error';\n if (type === 'overloaded_error' || status === 529) return `overloaded (${status})`;\n if (type === 'rate_limit_error' || status === 429) return `rate limited (${status})`;\n if (type === 'authentication_error' || status === 401) return `auth failed (${status})`;\n if (type === 'permission_error' || status === 403) return `forbidden (${status})`;\n if (type === 'not_found_error' || status === 404) return `not found (${status})`;\n if (type === 'invalid_request_error' || status === 400) return `invalid request (${status})`;\n if (status === 408) return `timeout (${status})`;\n if (status >= 500 && status < 600) return `HTTP ${status} (server error)`;\n if (type) return `${type} (${status})`;\n return `HTTP ${status}`;\n}\n\n/**\n * Thrown when the provider stream stops delivering data mid-response.\n * This is distinct from a network error (TCP reset, DNS failure) — the\n * connection is established and the response started, but chunks stopped\n * arriving before the stream completed.\n *\n * Status 599 is used as a sentinel to distinguish stream hangs from\n * regular HTTP errors while still flowing through ProviderError-based\n * retry and fallback infrastructure.\n */\nexport class StreamHangError extends ProviderError {\n /** Name of the provider that hung, e.g. \"zai\", \"anthropic\". */\n public readonly hungProviderId: string;\n /** Model that was being called when the hang occurred. */\n public readonly hungModel: string;\n /** How long (ms) we waited for the next chunk before declaring a hang. */\n public readonly hangTimeoutMs: number;\n /** How many bytes were received before the hang. */\n public readonly bytesReceived: number;\n /** Elapsed time (ms) from the start of the stream until the hang. */\n public readonly elapsedMs: number;\n\n constructor(opts: {\n providerId: string;\n model: string;\n hangTimeoutMs: number;\n bytesReceived: number;\n elapsedMs: number;\n cause?: unknown | undefined;\n }) {\n super(\n `Stream hang: ${opts.providerId}/${opts.model} — no data for ${opts.hangTimeoutMs}ms after ${opts.bytesReceived} bytes (${opts.elapsedMs}ms elapsed)`,\n 599,\n true, // always retryable\n opts.providerId,\n {\n body: {\n message: `Stream stalled after ${opts.elapsedMs}ms, ${opts.bytesReceived} bytes received`,\n },\n cause: opts.cause,\n },\n );\n this.name = 'StreamHangError';\n this.hungProviderId = opts.providerId;\n this.hungModel = opts.model;\n this.hangTimeoutMs = opts.hangTimeoutMs;\n this.bytesReceived = opts.bytesReceived;\n this.elapsedMs = opts.elapsedMs;\n }\n}\n\nfunction providerStatusToCode(status: number, type?: string): ErrorCode {\n if (status === 0) return ERROR_CODES.PROVIDER_NETWORK_ERROR;\n if (type === 'rate_limit_error' || status === 429) return ERROR_CODES.PROVIDER_RATE_LIMITED;\n if (type === 'authentication_error' || status === 401) return ERROR_CODES.PROVIDER_AUTH_FAILED;\n if (type === 'overloaded_error' || status === 529) return ERROR_CODES.PROVIDER_OVERLOADED;\n if (type === 'invalid_request_error' || status === 400) return ERROR_CODES.PROVIDER_INVALID_REQUEST;\n if (status === 408) return ERROR_CODES.PROVIDER_NETWORK_ERROR;\n if (status >= 500) return ERROR_CODES.PROVIDER_SERVER_ERROR;\n return ERROR_CODES.PROVIDER_INVALID_REQUEST;\n}\n","import type { SubagentError, SubagentErrorKind } from '../../types/multi-agent.js';\nimport { ProviderError } from '../../types/provider.js';\nimport { AgentError } from '../../types/errors.js';\nimport { BudgetExceededError } from '../subagent-budget.js';\nimport { toErrorMessage } from '../../utils/error.js';\n\n/**\n * Map any raw exception thrown out of a subagent's runner into a\n * structured `SubagentError`. This is the single point where the\n * coordinator decides \"what kind of failure was that\" — so callers\n * (delegate tool output, /agents UI, retry policies) branch on\n * `kind` instead of substring-matching `error.message`.\n *\n * Exported because tests and CLI surfaces want to assert on the\n * classification without instantiating a coordinator.\n */\nexport function classifySubagentError(\n err: unknown,\n hints: { parentAborted?: boolean | undefined } = {},\n): SubagentError {\n // Unwrap AgentError wrappers — the runner wraps non-AgentError\n // throwables (ProviderError, TypeError, etc.) in AgentError so the\n // coordinator's try/catch catches a consistent type. Recurse into the\n // inner cause so classification sees the original error kind.\n if (err instanceof AgentError && err.cause) {\n return classifySubagentError(err.cause, hints);\n }\n\n const cause = err instanceof Error\n ? { name: err.name, message: err.message, stack: err.stack }\n : undefined;\n\n if (err instanceof ProviderError) {\n const baseMessage = err.describe();\n return providerErrorToSubagentError(err, baseMessage, cause);\n }\n\n const baseMessage = toErrorMessage(err);\n\n if (err instanceof BudgetExceededError) {\n const map: Record<BudgetExceededError['kind'], SubagentErrorKind> = {\n iterations: 'budget_iterations',\n tool_calls: 'budget_tool_calls',\n tokens: 'budget_tokens',\n cost: 'budget_cost',\n timeout: 'budget_timeout',\n idle_timeout: 'budget_timeout',\n };\n return {\n kind: map[err.kind],\n message: baseMessage,\n retryable: false,\n cause,\n };\n }\n\n if (hints.parentAborted) {\n return { kind: 'aborted_by_parent', message: baseMessage, retryable: false, cause };\n }\n\n const lower = baseMessage.toLowerCase();\n if (/agent aborted$/i.test(baseMessage)) {\n return { kind: 'aborted_by_parent', message: baseMessage, retryable: false, cause };\n }\n if (/agent exhausted iteration limit$/i.test(baseMessage)) {\n return { kind: 'budget_iterations', message: baseMessage, retryable: false, cause };\n }\n if (/empty response/i.test(baseMessage)) {\n return { kind: 'empty_response', message: baseMessage, retryable: false, cause };\n }\n if (/^tool failed: /i.test(baseMessage)) {\n return { kind: 'tool_failed', message: baseMessage, retryable: false, cause };\n }\n if (lower.includes('bridge transport') || /bridge.*(closed|disconnect)/i.test(baseMessage)) {\n return { kind: 'bridge_failed', message: baseMessage, retryable: false, cause };\n }\n if (/context length|max.*tokens?.*exceeded|prompt is too long/i.test(baseMessage)) {\n return { kind: 'context_overflow', message: baseMessage, retryable: false, cause };\n }\n\n return { kind: 'unknown', message: baseMessage, retryable: false, cause };\n}\n\nfunction providerErrorToSubagentError(\n err: ProviderError,\n message: string,\n cause: SubagentError['cause'],\n): SubagentError {\n const status = err.status;\n if (status === 429 || err.body?.type === 'rate_limit_error') {\n return { kind: 'provider_rate_limit', message, retryable: true, backoffMs: 5_000, cause };\n }\n if (status === 401 || status === 403 || err.body?.type === 'authentication_error') {\n return { kind: 'provider_auth', message, retryable: false, cause };\n }\n if (status === 408 || status === 0) {\n return { kind: 'provider_timeout', message, retryable: true, cause };\n }\n if (status >= 500 && status < 600) {\n return { kind: 'provider_5xx', message, retryable: true, backoffMs: 3_000, cause };\n }\n return { kind: 'unknown', message, retryable: err.retryable, cause };\n}\n","/**\r\n * Pre-built subagent role configurations for the WrongStack fleet.\r\n * These can be passed to `MultiAgentHost.spawn()` or used as templates\r\n * for the director's roster.\r\n */\r\nimport type { SubagentConfig } from '../types/multi-agent.js';\r\nimport { ALL_AGENT_DEFINITIONS } from './agents/index.js';\r\n\r\n/**\r\n * Audit Log Agent — analyzes session logs, event streams, and traces.\r\n * Use for: post-mortems, trend analysis, operational insights.\r\n */\r\nexport const AUDIT_LOG_AGENT: SubagentConfig = {\r\n id: 'audit-log',\r\n name: 'Audit Log',\r\n role: 'audit-log',\r\n prompt: `You are the Audit Log agent. Your job is to analyze structured JSONL\r\nsession logs and produce actionable markdown reports.\r\n\r\nScope:\r\n- Parse session logs (iteration counts, tool calls, errors, usage)\r\n- Detect repeated failure patterns across multiple runs\r\n- Identify tool usage anomalies (over-use, failures, unexpected chains)\r\n- Track token consumption trends\r\n- Generate structured audit reports with severity ratings\r\n\r\nInput format you accept:\r\n{ \"task\": \"analyze | report | trends\", \"sessionPath\": \"<path>\", \"focus\": \"errors | tools | usage | all\" }\r\n\r\nOutput: Markdown audit report with sections:\r\n- ## Summary (totals, error rate)\r\n- ## Top Errors (count + context)\r\n- ## Tool Usage (table with calls, failures, avg duration)\r\n- ## Anomalies (pattern → severity)\r\n\r\nWorking rules:\r\n- Never fabricate numbers — read the actual logs first\r\n- Always include file:line references for errors\r\n- If sessionPath is missing, ask the director to provide it\r\n- Report confidence level: high (>90% accuracy), medium, low`,\r\n\r\n // No hardcoded budgets — the orchestrator (delegate tool or\r\n // spawn_subagent) decides per-task how much room a subagent gets.\r\n // A monorepo audit needs hours; a single-file lint check needs\r\n // seconds. Pinning a number here forces the orchestrator to fight\r\n // the role's default instead of just asking for what it needs.\r\n};\r\n\r\n/**\r\n * Bug Hunter Agent — systematic bug and code smell detection.\r\n * Use for: pre-refactoring health checks, code review, regression prevention.\r\n */\r\nexport const BUG_HUNTER_AGENT: SubagentConfig = {\r\n id: 'bug-hunter',\r\n name: 'Bug Hunter',\r\n role: 'bug-hunter',\r\n prompt: `You are the Bug Hunter agent. Your job is to systematically scan\r\nsource code for bugs, anti-patterns, and code smells using pattern matching\r\nand heuristics. Output a prioritized hit list with file:line references.\r\n\r\nScope:\r\n- Detect common bug patterns (uncaught errors, resource leaks, race conditions)\r\n- Identify anti-patterns (callback hell, God objects, circular deps)\r\n- Find TypeScript-specific issues (unsafe any, missing null checks, branded types)\r\n- Flag security-sensitive constructs (eval, innerHTML, hardcoded secrets)\r\n- Rank findings: critical > high > medium > low\r\n\r\nInput format you accept:\r\n{ \"task\": \"scan | hunt | check\", \"paths\": [\"src/**/*.ts\"], \"focus\": \"bugs | patterns | security | all\", \"severityThreshold\": \"medium\" }\r\n\r\nOutput: Markdown bug hunt report:\r\n- ## Critical (must fix first)\r\n- ## High (should fix)\r\n- ## Medium\r\n- ## Low (consider)\r\nEach entry: **[TYPE]** \\`file:line\\` — description + suggested fix\r\n\r\nBug pattern reference you know:\r\n| Pattern | Regex hint | Severity |\r\n|---------|------------|----------|\r\n| Uncaught promise | /.then\\\\(.*\\\\)/ without catch | high |\r\n| Event leak | on\\\\( without off/removeListener | high |\r\n| Hardcoded secret | [a-zA-Z0-9/_-]{20,} in config files | critical |\r\n| unsafe any | : any\\\\b or <any> | medium |\r\n| innerHTML | innerHTML\\\\s*= | high |\r\n\r\nWorking rules:\r\n- Never scan node_modules — it's noise\r\n- Always include file:line for every finding\r\n- If >30% of findings are false positives, note the confidence level\r\n- Ask director for clarification if paths are ambiguous`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * Refactor Planner Agent — structured refactoring planning.\r\n * Use for: large rewrites, technical debt reduction, architecture improvements.\r\n */\r\nexport const REFACTOR_PLANNER_AGENT: SubagentConfig = {\r\n id: 'refactor-planner',\r\n name: 'Refactor Planner',\r\n role: 'refactor-planner',\r\n prompt: `You are the Refactor Planner agent. Your job is to analyze code\r\nstructure and produce a concrete, phased refactoring plan with risk\r\nassessment, dependency ordering, and rollback strategy.\r\n\r\nScope:\r\n- Map module-level dependencies (import graph)\r\n- Identify coupling hotspots (high fan-in/out modules)\r\n- Assess refactoring risk by complexity and test coverage\r\n- Generate phased plans with checkpoint milestones\r\n- Produce diff-friendly task lists (one task = one concern)\r\n\r\nInput format you accept:\r\n{ \"task\": \"plan | assess | roadmap\", \"target\": \"src/core\", \"constraint\": \"no-breaking-changes | minimal-downtime | full-rewrite\", \"focus\": \"architecture | performance | maintainability\" }\r\n\r\nOutput: Markdown refactor plan:\r\n- ## Phase 1: Low Risk / High Payoff (do first)\r\n Table: | # | Task | Module | Risk | Est. Time |\r\n- ## Phase 2: Medium Risk\r\n- ## Phase 3: High Risk (requires full regression)\r\n- ## Dependency Graph (abbreviated ASCII)\r\n- ## Rollback Strategy\r\n- ## Exit Criteria (checkbox list)\r\n\r\nRisk scoring criteria:\r\n| Factor | Low | Medium | High |\r\n|--------|-----|--------|------|\r\n| Cyclomatic complexity | <10 | 10-20 | >20 |\r\n| Test coverage | >80% | 50-80% | <50% |\r\n| Fan-out (imports) | <5 | 5-15 | >15 |\r\n\r\nWorking rules:\r\n- Always include rollback strategy — every refactor can fail\r\n- Merge tasks that take <1h into a single phase\r\n- Respect team constraints (reviewer availability, parallelization)\r\n- Never plan without analyzing the actual code first`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * Security Scanner Agent — vulnerability and secret detection.\r\n * Use for: CI checks, pre-release audits, dependency vulnerability scanning.\r\n */\r\nexport const SECURITY_SCANNER_AGENT: SubagentConfig = {\r\n id: 'security-scanner',\r\n name: 'Security Scanner',\r\n role: 'security-scanner',\r\n prompt: `You are the Security Scanner agent. Your job is to scan code,\r\nconfigs, and dependencies for security issues from hardcoded secrets to\r\nsupply chain risks.\r\n\r\nScope:\r\n- Detect hardcoded secrets: API keys, tokens, passwords, private keys\r\n- Find injection vectors: eval, innerHTML, SQL concat, shell injection\r\n- Identify insecure patterns: weak crypto, hardcoded IVs, disabled TLS\r\n- Scan dependencies for known CVEs (via npm/pnpm audit)\r\n- Flag supply chain risks: postinstall hooks, unverified scripts, .npmrc\r\n\r\nInput format you accept:\r\n{ \"task\": \"scan | audit | secrets | dependencies\", \"paths\": [\"src\", \"config\"], \"depth\": \"quick | normal | deep\" }\r\n\r\nOutput: Markdown security report:\r\n- ## CRITICAL: Secrets Found (with code snippets)\r\n- ## HIGH: Injection Vectors\r\n- ## MEDIUM: Insecure Patterns\r\n- ## Dependency Issues (CVE list)\r\n- ## Summary table (severity → count)\r\n- ## Remediation Checklist (with checkboxes)\r\n\r\nSecret patterns you detect:\r\n| Pattern | Example | Severity |\r\n|---------|---------|----------|\r\n| AWS Access Key | AKIAIOSFODNN7EXAMPLE | critical |\r\n| AWS Secret Key | [a-zA-Z0-9/+=]{40} base64 | critical |\r\n| GitHub Token | ghp_[a-zA-Z0-9]{36} | critical |\r\n| Private Key PEM | -----BEGIN.*PRIVATE KEY----- | critical |\r\n| JWT | eyJ[a-zA-Z0-9_-]+ | high |\r\n\r\nInjection patterns:\r\n| Construct | Safe alternative |\r\n|-----------|-----------------|\r\n| eval(str) | new Function() or parse |\r\n| innerHTML = x | textContent or sanitize |\r\n| exec(\\`cmd \\${x}\\`) | execFile with args array |\r\n\r\nWorking rules:\r\n- Never scan node_modules — use npm audit instead\r\n- Always provide remediation steps, not just findings\r\n- Verify regex-based secrets before flagging (false positive risk)\r\n- When in doubt, flag as medium rather than ignoring potential issues`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * Critic Agent — evaluates code quality, architecture decisions, and\r\n * refactoring plans against project conventions and engineering standards.\r\n * Use for: real-time evaluation of bug reports, refactor plans, and\r\n * architectural proposals during collaborative debugging sessions.\r\n */\r\nexport const CRITIC_AGENT: SubagentConfig = {\r\n id: 'critic',\r\n name: 'Critic',\r\n role: 'critic',\r\n prompt: `You are the Critic agent. Your job is to evaluate code quality,\r\narchitectural decisions, and proposed changes against project conventions,\r\nengineering standards, and known quality gates. You do not write code —\r\nyou judge it.\r\n\r\nScope:\r\n- Evaluate bug severity and fix quality from Bug Hunter reports\r\n- Score refactoring plans from Refactor Planner (risk, completeness, trade-offs)\r\n- Flag gaps in test coverage, error handling, and edge case coverage\r\n- Assess whether a proposed change aligns with existing project patterns\r\n- Detect over-engineering or under-engineering relative to the problem scope\r\n\r\nInput format you accept:\r\n{ \"task\": \"evaluate | score | review\", \"subject\": \"bug_report | refactor_plan | diff\", \"focus\": \"correctness | maintainability | risk | all\" }\r\n\r\nOutput: Markdown critic report:\r\n- ## Overall Score (0-10 with rationale)\r\n- ## Strengths (what's solid)\r\n- ## Weaknesses (what needs work)\r\n- ## Specific Concerns (with file:line when applicable)\r\n- ## Verdict: **Approve / Needs Revision / Reject**\r\n\r\nWorking rules:\r\n- Be specific — \"looks fine\" is not a review. Cite concrete evidence.\r\n- When scoring, explain the delta from a perfect score.\r\n- If you have no basis to evaluate a concern, say so rather than speculating.\r\n- Prioritise correctness over style; correctness issues block approval.\r\n- Score thresholds: ≥7 = Approve, 4-6 = Needs Revision, <4 = Reject`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * All agents in a map for easy lookup by role. The four legacy pre-built\r\n * agents plus the phase 1-9 catalog (`ALL_AGENT_DEFINITIONS`). Catalog roles\r\n * are guaranteed collision-free by the catalog builder; none overlap the\r\n * legacy four.\r\n */\r\nexport const FLEET_ROSTER: Record<string, SubagentConfig> = {\r\n 'audit-log': AUDIT_LOG_AGENT,\r\n 'bug-hunter': BUG_HUNTER_AGENT,\r\n 'refactor-planner': REFACTOR_PLANNER_AGENT,\r\n 'security-scanner': SECURITY_SCANNER_AGENT,\r\n 'critic': CRITIC_AGENT,\r\n ...Object.fromEntries(\r\n ALL_AGENT_DEFINITIONS.map((d) => [d.config.role as string, d.config] as const),\r\n ),\r\n};\r\n\r\n// ---------------------------------------------------------------------------\r\n// Default per-role budgets.\r\n//\r\n// MASSIVELY RAISED from earlier values. User requested x5–x10 multiplier\r\n// to prevent any timeout or budget exhaustion on long-running tasks\r\n// like monorepo audits, deep refactors, and security scans.\r\n//\r\n// x10 values (realistic upper bound for a single subagent task):\r\n// audit-log: 7.5 hours, 5000 iterations, 15000 tool calls\r\n// bug-hunter: 10 hours, 8000 iterations, 20000 tool calls\r\n// refactor-planner: 7.5 hours, 6000 iterations, 18000 tool calls\r\n// security-scanner: 10 hours, 8000 iterations, 20000 tool calls\r\n//\r\n// These can be overridden per-call via delegate tool parameters.\r\n// ---------------------------------------------------------------------------\r\nexport interface FleetRosterBudget {\r\n timeoutMs?: number | undefined;\r\n /** Idle reap window (ms). Resets on activity — see `applyRosterBudget`. */\r\n idleTimeoutMs?: number | undefined;\r\n maxIterations?: number | undefined;\r\n maxToolCalls?: number | undefined;\r\n maxTokens?: number | undefined;\r\n maxCostUsd?: number | undefined;\r\n}\r\n\r\n/**\r\n * Default idle window for delegated subagents: reap only after this long with\r\n * NO activity (no iteration / tool call / streamed progress). An actively-\r\n * working agent resets this clock continuously, so it runs until its task\r\n * naturally ends — no more wall-clock kills of productive runs. Power users\r\n * can still impose a hard `timeoutMs` per delegate.\r\n */\r\nexport const DEFAULT_IDLE_TIMEOUT_MS = 15 * 60 * 1000;\r\n\r\nexport const FLEET_ROSTER_BUDGETS: Record<string, FleetRosterBudget> = {\r\n 'audit-log': { timeoutMs: 7.5 * 60 * 60 * 1000, maxIterations: 5000, maxToolCalls: 15000 },\r\n 'bug-hunter': { timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000 },\r\n 'refactor-planner': { timeoutMs: 7.5 * 60 * 60 * 1000, maxIterations: 6000, maxToolCalls: 18000 },\r\n 'security-scanner': { timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000 },\r\n 'critic': { timeoutMs: 5 * 60 * 60 * 1000, maxIterations: 4000, maxToolCalls: 12000 },\r\n ...Object.fromEntries(\r\n ALL_AGENT_DEFINITIONS.map((d) => [d.config.role as string, d.budget] as const),\r\n ),\r\n};\r\n\r\n/**\r\n * Apply roster budget to a config (only when the config has no explicit\r\n * budget fields set). This is called by the coordinator before dispatch.\r\n */\r\n// Generic default budget applied when no role matches and no explicit budget\r\n// fields are set. Used for `name` / free-form delegates. There is no default\r\n// wall-clock timeout — a delegated agent runs until its task naturally ends\r\n// (`end_turn`) or it stalls past the idle window. Iteration / tool-call ceilings\r\n// remain as a runaway backstop.\r\nconst GENERIC_SUBAGENT_BUDGET: FleetRosterBudget = {\r\n idleTimeoutMs: DEFAULT_IDLE_TIMEOUT_MS,\r\n maxIterations: 5000,\r\n maxToolCalls: 15000,\r\n};\r\n\r\nexport function applyRosterBudget(cfg: SubagentConfig): SubagentConfig {\r\n // First try role-specific budget; fall back to generic for name-only delegates.\r\n const roleBudget = cfg.role ? FLEET_ROSTER_BUDGETS[cfg.role] : undefined;\r\n const defaultBudget = roleBudget ?? (cfg.name ? GENERIC_SUBAGENT_BUDGET : undefined);\r\n if (!defaultBudget) return cfg;\r\n return {\r\n ...cfg,\r\n // Wall-clock cap is opt-in only: forward an explicit `cfg.timeoutMs`, but\r\n // do NOT impose the roster's historical multi-hour wall-clock default — it\r\n // killed agents that were still actively working. Reaping is idle-based.\r\n timeoutMs: cfg.timeoutMs,\r\n // Idle window is the default reaper. Resets on activity, so a long-but-\r\n // productive run is never killed; only a genuine stall is reaped.\r\n idleTimeoutMs: cfg.idleTimeoutMs ?? defaultBudget.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS,\r\n maxIterations: cfg.maxIterations ?? defaultBudget.maxIterations,\r\n maxToolCalls: cfg.maxToolCalls ?? defaultBudget.maxToolCalls,\r\n maxTokens: cfg.maxTokens ?? defaultBudget.maxTokens,\r\n maxCostUsd: cfg.maxCostUsd ?? defaultBudget.maxCostUsd,\r\n };\r\n}\r\n\r\n/** Quick-access list for spawning all at once. */\r\nexport const ALL_FLEET_AGENTS = Object.values(FLEET_ROSTER);\r\n\r\n// ---------------------------------------------------------------------------\r\n// ACP external agents — WrongStack spawns these as subagents via ACP protocol.\r\n// Each agent runs its own loop; WrongStack sends tasks as ACP messages and\r\n// receives results. These don't go through makeAgentSubagentRunner — they\r\n// are handled by makeACPSubagentRunner in the CLI multi-agent layer.\r\n// ---------------------------------------------------------------------------\r\n\r\n/**\r\n * Cline — ACP-compatible coding agent by @asonix.\r\n * Spawned as: `npx @agentify/cline`\r\n */\r\nexport const CLINE_AGENT: SubagentConfig = {\r\n id: 'cline',\r\n name: 'Cline',\r\n role: 'cline',\r\n prompt: `You are Cline, a coding agent. You help write, edit, and navigate code.\r\nYou operate by receiving tasks via ACP and returning results.\r\nWhen asked to code, make focused changes and explain them briefly.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * Gemini CLI — Google's ACP-compatible command-line agent.\r\n * Spawned as: `gemini` (when gemini CLI is installed and in PATH)\r\n */\r\nexport const GEMINI_CLI_AGENT: SubagentConfig = {\r\n id: 'gemini-cli',\r\n name: 'Gemini CLI',\r\n role: 'gemini-cli',\r\n prompt: `You are Gemini CLI, a coding agent powered by Google's Gemini model.\r\nYou help with code generation, editing, debugging, and best practices.\r\nYou operate by receiving tasks via ACP and returning results.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * GitHub Copilot (public preview) — ACP-compatible Copilot CLI agent.\r\n * Spawned as: `gh copilot` (when gh CLI with copilot extension is installed)\r\n */\r\nexport const COPILOT_AGENT: SubagentConfig = {\r\n id: 'copilot',\r\n name: 'GitHub Copilot',\r\n role: 'copilot',\r\n prompt: `You are GitHub Copilot, an AI coding assistant.\r\nYou help write, explain, refactor, and review code.\r\nYou operate by receiving tasks via ACP and returning results.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * OpenHands — AI coding agent by all-in.ai, ACP-compatible.\r\n * Spawned as: `openhands` (when installed)\r\n */\r\nexport const OPENHANDS_AGENT: SubagentConfig = {\r\n id: 'openhands',\r\n name: 'OpenHands',\r\n role: 'openhands',\r\n prompt: `You are OpenHands, an AI coding agent that can use tools to interact\r\nwith files, terminals, browsers, and other resources.\r\nYou operate by receiving tasks via ACP and returning results.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * Goose — IDE agent by ExoRL, ACP-compatible.\r\n * Spawned as: `goose` (when goose CLI is installed)\r\n */\r\nexport const GOOSE_AGENT: SubagentConfig = {\r\n id: 'goose',\r\n name: 'Goose',\r\n role: 'goose',\r\n prompt: `You are Goose, an AI agent that helps with coding tasks.\r\nYou operate by receiving tasks via ACP and returning results.\r\nFocus on writing high-quality, well-tested code.`,\r\n provider: 'acp',\r\n};\r\n\r\n/** All ACP external agents. */\r\nexport const ACP_AGENTS: SubagentConfig[] = [\r\n CLINE_AGENT,\r\n GEMINI_CLI_AGENT,\r\n COPILOT_AGENT,\r\n OPENHANDS_AGENT,\r\n GOOSE_AGENT,\r\n];\r\n\r\n// ACP agents share the same generous budgets as the built-in fleet agents.\r\n// External ACP agents may need more time than typical in-process subagents\r\n// since they run their own loops and may do tool-call round-trips.\r\nFLEET_ROSTER_BUDGETS['cline'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['gemini-cli'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['copilot'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['openhands'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['goose'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\n\r\n/** Extended roster including ACP agents. */\r\nexport const FLEET_ROSTER_WITHACP: Record<string, SubagentConfig> = {\r\n ...FLEET_ROSTER,\r\n ...Object.fromEntries(ACP_AGENTS.map((a) => [a.role as string, a])),\r\n};\r\n","/**\n * Subagent nickname pool — famous scientists, mathematicians, and computing pioneers.\n * Names are grouped by domain affinity so the nickname hints at the agent's role.\n */\n\nconst NICKNAME_POOL = {\n // Physics & fundamental sciences\n 'einstein': { name: 'Einstein', domain: 'physics' },\n 'newton': { name: 'Newton', domain: 'physics' },\n 'feynman': { name: 'Feynman', domain: 'physics' },\n 'dirac': { name: 'Dirac', domain: 'physics' },\n 'bohr': { name: 'Bohr', domain: 'physics' },\n 'planck': { name: 'Planck', domain: 'physics' },\n 'curie': { name: 'Curie', domain: 'physics' },\n 'fermi': { name: 'Fermi', domain: 'physics' },\n 'heisenberg': { name: 'Heisenberg', domain: 'physics' },\n 'schrodinger': { name: 'Schrödinger', domain: 'physics' },\n\n // Mathematics\n 'euclid': { name: 'Euclid', domain: 'math' },\n 'gauss': { name: 'Gauss', domain: 'math' },\n 'turing': { name: 'Turing', domain: 'math' },\n 'poincare': { name: 'Poincaré', domain: 'math' },\n 'riemann': { name: 'Riemann', domain: 'math' },\n 'hilbert': { name: 'Hilbert', domain: 'math' },\n 'pythagoras': { name: 'Pythagoras', domain: 'math' },\n\n // Computing & information theory\n 'von-neumann': { name: 'Von Neumann', domain: 'computing' },\n 'shannon': { name: 'Shannon', domain: 'computing' },\n 'hopper': { name: 'Hopper', domain: 'computing' },\n 'backus': { name: 'Backus', domain: 'computing' },\n 'knuth': { name: 'Knuth', domain: 'computing' },\n 'torvalds': { name: 'Torvalds', domain: 'computing' },\n 'stallman': { name: 'Stallman', domain: 'computing' },\n 'berners-lee': { name: 'Berners-Lee', domain: 'computing' },\n 'babbage': { name: 'Babbage', domain: 'computing' },\n 'lovelace': { name: 'Lovelace', domain: 'computing' },\n 'klein': { name: 'Klein', domain: 'computing' },\n\n // Electronics & electrical engineering\n 'edison': { name: 'Edison', domain: 'ee' },\n 'tesla': { name: 'Tesla', domain: 'ee' },\n 'faraday': { name: 'Faraday', domain: 'ee' },\n 'maxwell': { name: 'Maxwell', domain: 'ee' },\n 'ohm': { name: 'Ohm', domain: 'ee' },\n 'bell': { name: 'Bell', domain: 'ee' },\n 'marconi': { name: 'Marconi', domain: 'ee' },\n 'lamarr': { name: 'Lamarr', domain: 'ee' },\n\n // General science / multi-disciplinary\n 'darwin': { name: 'Darwin', domain: 'biology' },\n 'mendel': { name: 'Mendel', domain: 'biology' },\n 'pasteur': { name: 'Pasteur', domain: 'biology' },\n 'hawking': { name: 'Hawking', domain: 'cosmology' },\n 'sagan': { name: 'Sagan', domain: 'cosmology' },\n\n // Exploration & navigation\n 'columbus': { name: 'Columbus', domain: 'exploration' },\n 'polo': { name: 'Polo', domain: 'exploration' },\n 'magellan': { name: 'Magellan', domain: 'exploration' },\n\n // Chemistry / materials\n 'lavoisier': { name: 'Lavoisier', domain: 'chemistry' },\n 'mendeleev': { name: 'Mendeleev', domain: 'chemistry' },\n} as const;\n\n/** Flat ordered list of all available nicknames — used for round-robin. */\nconst ALL_NICKNAMES = Object.entries(NICKNAME_POOL) as [NicknameKey, { name: string; domain: string }][];\n\n/** Reverse index: display name (e.g. \"Von Neumann\") → canonical pool key. */\nconst NAME_TO_KEY: Record<string, string> = Object.fromEntries(\n ALL_NICKNAMES.map(([key, entry]) => [entry.name, key]),\n);\n\n/** Domain → preferred nickname keys (fallback chain). */\nconst DOMAIN_PREFERENCES: Record<string, string[]> = {\n 'security': ['shannon', 'turing', 'lamarr', 'stallman'],\n 'bug-hunter': ['darwin', 'curie', 'feynman', 'fermi'],\n 'refactor': ['gauss', 'hilbert', 'euclid', 'planck'],\n 'audit-log': ['sagan', 'hawking', 'poincare', 'newton'],\n 'planner': ['hilbert', 'gauss', 'turing', 'euclid'],\n 'researcher': ['sagan', 'hawking', 'darwin', 'pasteur'],\n 'explorer': ['marconi', 'bell', 'columbus', 'polo'],\n 'testing': ['pasteur', 'curie', 'fermi', 'bohr'],\n 'frontend': ['lovelace', 'hopper', 'babbage', 'backus'],\n 'backend': ['torvalds', 'stallman', 'von-neumann', 'backus'],\n 'database': ['turing', 'shannon', 'backus', 'knuth'],\n 'devops': ['tesla', 'edison', 'faraday', 'bell'],\n 'security-scanner': ['shannon', 'turing', 'lamarr', 'stallman'],\n 'refactor-planner': ['gauss', 'hilbert', 'planck', 'newton'],\n 'architect': ['von-neumann', 'turing', 'gauss', 'hilbert'],\n 'critic': ['einstein', 'feynman', 'dirac', 'bohr'],\n 'e2e': ['hopper', 'bell', 'marconi', 'tesla'],\n 'performance': ['knuth', 'gauss', 'planck', 'feynman'],\n 'chaos': ['tesla', 'edison', 'curie', 'fermi'],\n 'cost': ['ohm', 'bell', 'marconi', 'tesla'],\n // default fallback\n 'default': ['einstein', 'newton', 'curie', 'tesla', 'edison', 'turing', 'shannon', 'hopper', 'knuth', 'stallman'],\n};\n\ntype NicknameKey = keyof typeof NICKNAME_POOL;\n\n/** Result of a nickname assignment. */\nexport interface NicknameAssignment {\n /**\n * Canonical pool key (e.g. `von-neumann`). This — NOT the display string — is\n * what callers must add to their `used` set and later remove on release.\n * Deriving the key by parsing the display string is unsafe: multi-word names\n * like \"Von Neumann\" would be truncated to \"von\" and never dedupe correctly.\n */\n key: string;\n /** Human display string, e.g. `Von Neumann (Backend)`. */\n display: string;\n}\n\n/**\n * Assign a unique nickname to a subagent based on its role.\n *\n * Returns both the canonical pool `key` (for the `used` set) and the formatted\n * `display` string (`Name (Role)`, e.g. `Einstein (Bug Hunter)`).\n *\n * @param role - The subagent's role id (e.g. 'bug-hunter', 'security-scanner')\n * @param used - Set of nickname KEYS already assigned in this fleet\n * (so no two subagents share the same base name)\n */\nexport function assignNickname(role: string, used: ReadonlySet<string>): NicknameAssignment {\n // 1. Build preference list: role-specific → default fallback\n const preferences = [\n ...(DOMAIN_PREFERENCES[role] ?? []),\n ...(DOMAIN_PREFERENCES['default'] ?? []),\n ];\n\n // 2. Find the first unassigned nickname from preferences. Skip keys that are\n // not in the pool — preference lists can drift out of sync with the pool\n // (typos, removed names), and an unknown key must not crash assignment.\n for (const key of preferences) {\n const entry = NICKNAME_POOL[key as NicknameKey];\n if (entry && !used.has(key)) {\n return { key, display: `${entry.name} (${formatRole(role)})` };\n }\n }\n\n // 3. Exhausted preferences — pick the first unused name round-robin style.\n for (const [key, entry] of ALL_NICKNAMES) {\n if (!used.has(key)) {\n return { key, display: `${entry.name} (${formatRole(role)})` };\n }\n }\n\n // 4. Pool exhausted — synthesize a stable, unique key/display pair.\n const counter = used.size + 1;\n return { key: `scientist-${counter}`, display: `Scientist #${counter} (${formatRole(role)})` };\n}\n\n/**\n * Resolve a previously-assigned display string back to its canonical pool key,\n * for release paths that only retained the formatted name (e.g. a manifest\n * entry). Strips the trailing ` (Role)` suffix, then matches the base name\n * against the pool. Returns `undefined` when the name is not a known nickname.\n *\n * Use this instead of `name.split(' ')[0]` — the latter mangles multi-word\n * names like \"Von Neumann\" and \"Berners-Lee\".\n */\nexport function nicknameKeyFromDisplay(display: string): string | undefined {\n const base = display.replace(/\\s*\\([^)]*\\)\\s*$/, '').trim();\n const key = NAME_TO_KEY[base];\n if (key) return key;\n const synthesized = base.match(/^Scientist #(\\d+)$/);\n return synthesized ? `scientist-${synthesized[1]}` : undefined;\n}\n\n/** Format role id into human-readable title-case. */\nfunction formatRole(role: string): string {\n return role\n .split(/[-_]/)\n .map((w) => w.charAt(0).toUpperCase() + w.slice(1))\n .join(' ');\n}\n\n/**\n * Returns all available nickname keys. Useful for testing or reset logic.\n */\nexport function getAllNicknameKeys(): string[] {\n return Object.keys(NICKNAME_POOL);\n}\n","import { randomUUID } from 'node:crypto';\r\nimport { EventEmitter } from 'node:events';\r\nimport type { AgentBridge, BridgeMessage } from '../types/agent-bridge.js';\r\nimport type {\r\n CoordinatorStatus,\r\n MultiAgentConfig,\r\n MultiAgentCoordinator,\r\n SpawnResult,\r\n SubagentConfig,\r\n SubagentContext,\r\n SubagentRunContext,\r\n SubagentRunner,\r\n TaskResult,\r\n TaskSpec,\r\n} from '../types/multi-agent.js';\r\nimport {\r\n BudgetExceededError,\r\n DECISION_TIMEOUT_MS,\r\n SubagentBudget,\r\n TIMEOUT_PREEMPT_FRACTION,\r\n} from './subagent-budget.js';\r\nimport { classifySubagentError } from './coordinator/error-classifier.js';\r\nimport { applyRosterBudget } from './fleet.js';\r\nimport { assignNickname } from './subagent-nicknames.js';\r\n\r\ntype SubagentStatus = 'running' | 'idle' | 'stopped' | 'error';\r\n\r\ninterface SubagentEntry {\r\n config: SubagentConfig;\r\n context: SubagentContext;\r\n status: SubagentStatus;\r\n currentTask?: string | undefined;\r\n abortController: AbortController;\r\n /** Lazily created on first dispatch — budget is per-task, not per-subagent. */\r\n activeBudget?: SubagentBudget | undefined;\r\n}\r\n\r\nexport interface MultiAgentCoordinatorOptions {\r\n /**\r\n * Callback that executes a task on behalf of a subagent. Required for\r\n * `assign()` to actually run anything — without it, tasks queue forever.\r\n * The coordinator provides per-subagent isolation (own budget, own signal,\r\n * own bridge) and enforces timeout + concurrency.\r\n */\r\n runner?: SubagentRunner | undefined;\r\n}\r\n\r\nexport class DefaultMultiAgentCoordinator extends EventEmitter implements MultiAgentCoordinator {\r\n readonly coordinatorId: string;\r\n readonly config: MultiAgentConfig;\r\n private runner?: SubagentRunner | undefined;\r\n private fleetBus?: import('./fleet-bus.js').FleetBus | undefined;\r\n\r\n private readonly subagents = new Map<string, SubagentEntry>();\r\n\r\n /**\r\n * Base nickname keys already handed out this run (e.g. `einstein`, `tesla`).\r\n * Prevents two workers sharing a name. Direct `coordinator.spawn()` callers\r\n * (parallel/eternal engine, SDD parallel run) don't go through\r\n * `Director.spawn()` where nicknames are normally assigned, so the\r\n * coordinator upgrades placeholder names (\"Executor\", \"slot-ab12cd\", role\r\n * names) to memorable ones here — that's what surfaces in the fleet monitor.\r\n */\r\n private readonly usedNicknames = new Set<string>();\r\n /** Maps subagentId → nickname key (e.g. 'einstein'). Used to free the slot on remove(). */\r\n private readonly subagentNicknames = new Map<string, string>();\r\n\r\n private pendingTasks: TaskSpec[] = [];\r\n private completedResults: TaskResult[] = [];\r\n /** Prevents completedResults from growing unbounded in long-running coordinators. */\r\n private static readonly MAX_COMPLETED_RESULTS = 10_000;\r\n private totalIterations = 0;\r\n private inFlight = 0;\r\n /**\r\n * Subagents currently being stopped. Set on entry to `stop()`, cleared\r\n * once `recordCompletion` lands the terminal TaskResult. Used by\r\n * `runDispatched` and `findIdleSubagent` to refuse mid-flight dispatch\r\n * to a subagent the caller has already asked to terminate — closes the\r\n * assign+terminate race where a fresh task could land on a worker that\r\n * was about to be killed.\r\n */\r\n private readonly terminating = new Set<string>();\r\n\r\n constructor(config: MultiAgentConfig, options: MultiAgentCoordinatorOptions = {}) {\r\n super();\r\n // awaitTasks() registers one short-lived 'task.completed' listener per\r\n // awaited id; a single call awaiting >10 ids (or several concurrent\r\n // callers) crosses Node's default 10-listener cap and prints a spurious\r\n // MaxListenersExceededWarning that also masks genuine leaks. These waiters\r\n // are bounded and self-removing, so lift the cap.\r\n this.setMaxListeners(0);\r\n this.coordinatorId = config.coordinatorId;\r\n this.config = config;\r\n this.runner = options.runner;\r\n }\r\n\r\n /**\r\n * Replace the runner after construction. Used when the runner depends\r\n * on infrastructure (e.g. FleetBus) that isn't available until after\r\n * the coordinator's owning Director is built.\r\n */\r\n setRunner(runner: SubagentRunner): void {\r\n this.runner = runner;\r\n }\r\n\r\n /**\r\n * Wire a FleetBus for director-mode event emission. Call after the\r\n * FleetManager is constructed so the coordinator can emit lifecycle\r\n * events the TUI and monitoring tools subscribe to.\r\n */\r\n setFleetBus(fleet: import('./fleet-bus.js').FleetBus): void {\r\n this.fleetBus = fleet;\r\n }\r\n\r\n /**\r\n * Change the in-flight dispatch ceiling at runtime. Lowering does NOT\r\n * preempt running tasks — already-dispatched subagents finish their\r\n * current task; only future dispatches respect the new cap. Raising\r\n * immediately tries to fill the freed slots from the pending queue.\r\n */\r\n setMaxConcurrent(n: number): void {\r\n if (!Number.isFinite(n) || n < 1) {\r\n throw new Error(`maxConcurrent must be a finite integer >= 1, got ${n}`);\r\n }\r\n this.config.maxConcurrent = Math.floor(n);\r\n this.tryDispatchNext();\r\n }\r\n\r\n /**\r\n * Upgrade a placeholder/role-derived name to a memorable scientist nickname\r\n * (e.g. \"Einstein (Executor)\"). A name is treated as a placeholder when it is\r\n * empty, equals the role (case-insensitive), is a generic default\r\n * (\"subagent\"/\"adhoc\"/\"generic\"), or is an auto-generated `slot-…` id.\r\n * Explicit, human-chosen names — including nicknames already assigned by\r\n * `Director.spawn()` — are left untouched, so this never double-assigns.\r\n */\r\n private withNickname(subagent: SubagentConfig, subagentId: string): SubagentConfig {\r\n const role = subagent.role ?? 'subagent';\r\n const name = subagent.name?.trim() ?? '';\r\n const isPlaceholder =\r\n name === '' ||\r\n name.toLowerCase() === role.toLowerCase() ||\r\n name === 'subagent' ||\r\n name === 'adhoc' ||\r\n name === 'generic' ||\r\n /^slot-/.test(name);\r\n if (!isPlaceholder) return subagent;\r\n const { key, display } = assignNickname(role, this.usedNicknames);\r\n this.usedNicknames.add(key);\r\n this.subagentNicknames.set(subagentId, key);\r\n return { ...subagent, name: display };\r\n }\r\n\r\n async spawn(subagent: SubagentConfig): Promise<SpawnResult> {\r\n const id = subagent.id || randomUUID();\r\n const cfg = this.withNickname(subagent, id);\r\n // Duplicate-id guard. Previously a second spawn({id}) with the\r\n // same id silently overwrote the existing entry — orphaning the\r\n // first subagent's AbortController, Context, and any in-flight\r\n // task referencing it. Two spawns with the same id are almost\r\n // always a bug at the caller; refuse and let them surface it.\r\n if (this.subagents.has(id)) {\r\n throw new Error(`Subagent id \"${id}\" already exists — refusing to overwrite`);\r\n }\r\n const context: SubagentContext = {\r\n subagentId: id,\r\n tasks: [],\r\n // Wired later by the caller via setSubagentBridge() once the\r\n // bidirectional bridge is created. Readers must null-check / use\r\n // hasParentBridge() — the type now reflects this.\r\n parentBridge: null,\r\n doneCondition: this.config.doneCondition,\r\n maxConcurrent: this.config.maxConcurrent ?? 16,\r\n };\r\n\r\n this.subagents.set(id, {\r\n config: { ...cfg, id },\r\n context,\r\n status: 'idle',\r\n abortController: new AbortController(),\r\n });\r\n\r\n this.emit('subagent.started', { subagent: { ...cfg, id } });\r\n\r\n this.fleetBus?.emit({\r\n subagentId: id,\r\n ts: Date.now(),\r\n type: 'subagent.assigned',\r\n payload: {\r\n subagentId: id,\r\n name: subagent.name,\r\n provider: subagent.provider,\r\n model: subagent.model,\r\n },\r\n });\r\n\r\n this.emitCoordinatorStats();\r\n\r\n return { subagentId: id, agentId: id };\r\n }\r\n\r\n async assign(task: TaskSpec): Promise<void> {\r\n this.pendingTasks.push(task);\r\n this.tryDispatchNext();\r\n }\r\n\r\n async delegate(to: string, msg: BridgeMessage): Promise<void> {\r\n const subagent = this.subagents.get(to);\r\n if (!subagent) throw new Error(`Subagent \"${to}\" not found`);\r\n if (!subagent.context.parentBridge) {\r\n throw new Error(`Subagent \"${to}\" has no parentBridge — call setSubagentBridge() first`);\r\n }\r\n await subagent.context.parentBridge.send(msg);\r\n }\r\n\r\n /**\r\n * Wire up the communication bridge for a subagent. Call after spawn() once\r\n * the caller has created the bidirectional connection.\r\n */\r\n setSubagentBridge(subagentId: string, bridge: AgentBridge): void {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) throw new Error(`Subagent \"${subagentId}\" not found`);\r\n subagent.context.parentBridge = bridge;\r\n }\r\n\r\n async stop(subagentId: string): Promise<void> {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) return;\r\n\r\n // Mark terminating BEFORE the abort so a synchronous tryDispatchNext\r\n // observation in another callback path sees the intent and skips\r\n // this subagent. Cleared by recordCompletion once the runner's\r\n // catch block lands the terminal TaskResult.\r\n this.terminating.add(subagentId);\r\n\r\n // Abort any in-flight run, then sever the bridge so further messages fail\r\n // fast instead of silently queueing on a dead subagent.\r\n subagent.abortController.abort();\r\n subagent.status = 'stopped';\r\n subagent.currentTask = undefined;\r\n subagent.context.parentBridge = null;\r\n\r\n this.emit('subagent.stopped', { subagentId, reason: 'stopped by coordinator' });\r\n\r\n this.fleetBus?.emit({\r\n subagentId,\r\n ts: Date.now(),\r\n type: 'subagent.stopped',\r\n payload: { subagentId, reason: 'stopped by coordinator' },\r\n });\r\n\r\n this.emitCoordinatorStats();\r\n }\r\n\r\n async stopAll(): Promise<void> {\r\n // Clear the queue FIRST so no new tasks land on subagents while\r\n // we're tearing them down. Each dropped task gets a synthetic\r\n // `aborted_by_parent` completion so any caller awaiting it (e.g.\r\n // delegate tool's awaitTasks) resolves instead of hanging.\r\n //\r\n // Pending tasks never reached `inFlight`, so we cannot route them\r\n // through `recordCompletion` — its underflow guard would short-\r\n // circuit on the second pending task and emit a warning instead\r\n // of the completion event. The shared helper inline-emits.\r\n this.drainPendingAsAborted('Coordinator stopAll() drained the pending queue');\r\n // allSettled so one failure doesn't leave other subagents un-stopped.\r\n await Promise.allSettled([...this.subagents.keys()].map((id) => this.stop(id)));\r\n }\r\n\r\n /**\r\n * Get current coordinator stats for monitoring/debugging.\r\n */\r\n getStats(): {\r\n total: number;\r\n running: number;\r\n idle: number;\r\n stopped: number;\r\n inFlight: number;\r\n pending: number;\r\n completed: number;\r\n } {\r\n let running = 0;\r\n let idle = 0;\r\n let stopped = 0;\r\n for (const [, entry] of this.subagents) {\r\n if (entry.status === 'running') running++;\r\n else if (entry.status === 'idle') idle++;\r\n else stopped++;\r\n }\r\n return {\r\n total: this.subagents.size,\r\n running,\r\n idle,\r\n stopped,\r\n inFlight: this.inFlight,\r\n pending: this.pendingTasks.length,\r\n completed: this.completedResults.length,\r\n };\r\n }\r\n\r\n /** Emit a reactive coordinator.stats event on FleetBus so the TUI can subscribe. */\r\n private emitCoordinatorStats(): void {\r\n const stats = this.getStats();\r\n const subagentStatuses = Array.from(this.subagents.entries()).map(([id, s]) => ({\r\n subagentId: id,\r\n taskId: s.currentTask ?? '',\r\n status: s.status,\r\n assigned: s.context.parentBridge !== null,\r\n }));\r\n this.fleetBus?.emit({\r\n subagentId: this.coordinatorId,\r\n ts: Date.now(),\r\n type: 'coordinator.stats',\r\n payload: { ...stats, subagentStatuses },\r\n });\r\n }\r\n\r\n getStatus(): CoordinatorStatus {\r\n return {\r\n coordinatorId: this.coordinatorId,\r\n subagents: Array.from(this.subagents.entries()).map(([id, s]) => ({\r\n id,\r\n name: s.config.name,\r\n status: s.status,\r\n currentTask: s.currentTask,\r\n })),\r\n pendingTasks: this.pendingTasks.length,\r\n completedTasks: this.completedResults.length,\r\n totalIterations: this.totalIterations,\r\n done: this.isDone(),\r\n };\r\n }\r\n\r\n /** Expose snapshot of completed results — useful for callers awaiting all done. */\r\n results(): readonly TaskResult[] {\r\n return this.completedResults;\r\n }\r\n\r\n /**\r\n * Wait for one or more tasks to complete and return their results.\r\n * If a task is already done when called, returns immediately.\r\n * Resolves to an array in the same order as `taskIds`.\r\n */\r\n async awaitTasks(taskIds: string[]): Promise<TaskResult[]> {\r\n return Promise.all(\r\n taskIds.map((id) => {\r\n const cached = this.completedResults.find((r) => r.taskId === id);\r\n if (cached) return cached;\r\n // Fallback: poll until the task completes (up to timeoutMs).\r\n // The coordinator fires 'task.completed' on every result, so\r\n // we use a promise-based waiter tied to that event.\r\n return new Promise<TaskResult>((resolve, reject) => {\r\n const timeout = setTimeout(() => {\r\n this.off('task.completed', handler);\r\n reject(new Error(`awaitTasks timed out waiting for task \"${id}\"`));\r\n }, this.config.timeoutMs ?? 300_000);\r\n const handler = ({ result }: { task: TaskSpec; result: TaskResult }) => {\r\n if (result.taskId === id) {\r\n clearTimeout(timeout);\r\n this.off('task.completed', handler);\r\n resolve(result);\r\n }\r\n };\r\n this.on('task.completed', handler);\r\n });\r\n }),\r\n );\r\n }\r\n\r\n /**\r\n * Manual completion — for callers that drive subagents without a runner\r\n * (e.g. external orchestrators). When a runner is configured the coordinator\r\n * calls this itself.\r\n */\r\n completeTask(result: TaskResult): void {\r\n this.recordCompletion(result);\r\n }\r\n\r\n // --- internal dispatching ---------------------------------------------\r\n\r\n private tryDispatchNext(): void {\r\n while (this.canDispatch()) {\r\n const dispatchable = this.takeNextDispatchableTask();\r\n if (!dispatchable) {\r\n // No idle worker right now. If every spawned subagent is\r\n // stopped or mid-termination, the pending queue is dead —\r\n // a pending task can never start, so synthetic-complete it\r\n // as `aborted_by_parent`. Without this, an `assign()` after\r\n // `stop()` would hang forever waiting for `task.completed`.\r\n // We DO NOT drain when subagents are busy (status='running'):\r\n // those will free up and accept the work normally.\r\n if (this.pendingTasks.length > 0 && !this.hasLiveSubagent()) {\r\n this.drainPendingAsAborted(\r\n 'No live subagent available — all stopped or mid-termination',\r\n );\r\n }\r\n return;\r\n }\r\n const { subagentId, task } = dispatchable;\r\n // Attach a catch so a synchronous throw inside runDispatched (rare —\r\n // e.g. provider misconfiguration before the first await) becomes a\r\n // visible failed task instead of an unhandled rejection that leaves\r\n // `inFlight` permanently elevated.\r\n this.runDispatched(subagentId, task).catch((err) => {\r\n this.recordCompletion({\r\n subagentId,\r\n taskId: task.id,\r\n status: 'failed',\r\n error: classifySubagentError(err),\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n });\r\n });\r\n }\r\n }\r\n\r\n private canDispatch(): boolean {\r\n const max = this.config.maxConcurrent ?? 16;\r\n return this.inFlight < max && this.pendingTasks.length > 0;\r\n }\r\n\r\n private takeNextDispatchableTask(): { subagentId: string; task: TaskSpec } | null {\r\n for (let i = 0; i < this.pendingTasks.length; i++) {\r\n const task = this.pendingTasks[i];\r\n if (!task) continue;\r\n const subagentId = task.subagentId\r\n ? this.isIdleSubagent(task.subagentId)\r\n ? task.subagentId\r\n : null\r\n : this.findIdleSubagent();\r\n if (!subagentId) continue;\r\n this.pendingTasks.splice(i, 1);\r\n return { subagentId, task };\r\n }\r\n return null;\r\n }\r\n\r\n private findIdleSubagent(): string | null {\r\n for (const [id, s] of this.subagents) {\r\n // Skip subagents that are mid-termination — `stop()` set the\r\n // `terminating` flag and aborted the controller, but the\r\n // status mutation happens synchronously after; checking both\r\n // is belt-and-suspenders against any race where status is\r\n // transiently still 'idle' while termination is in flight.\r\n if (s.status === 'idle' && !this.terminating.has(id)) return id;\r\n }\r\n return null;\r\n }\r\n\r\n private isIdleSubagent(id: string): boolean {\r\n const subagent = this.subagents.get(id);\r\n return !!subagent && subagent.status === 'idle' && !this.terminating.has(id);\r\n }\r\n\r\n /**\r\n * Returns true iff at least one spawned subagent could still\r\n * process a task. A \"live\" subagent is one that is not stopped\r\n * AND not mid-termination — `running` workers count because they\r\n * will eventually finish and become idle.\r\n *\r\n * When no subagent has ever been spawned, returns `true` so a\r\n * pre-spawn `assign()` simply queues (legacy behaviour). The\r\n * dead-end detection only fires after `stop()` has retired every\r\n * spawned worker.\r\n *\r\n * Used by `tryDispatchNext` to detect a dead-end pending queue.\r\n */\r\n private hasLiveSubagent(): boolean {\r\n if (this.subagents.size === 0) return true;\r\n for (const [id, s] of this.subagents) {\r\n if (s.status !== 'stopped' && !this.terminating.has(id)) return true;\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * Drain every pending task with a synthetic `aborted_by_parent`\r\n * completion event. Same shape as the `stopAll()` drain — we go\r\n * around `recordCompletion` because pending tasks were never\r\n * counted in `inFlight` and routing them through would trip the\r\n * underflow guard on every task after the first.\r\n */\r\n private drainPendingAsAborted(message: string): void {\r\n const dropped = this.pendingTasks.splice(0, this.pendingTasks.length);\r\n for (const t of dropped) this.emitPendingAborted(t, message);\r\n }\r\n\r\n /**\r\n * Emit a synthetic `stopped`/`aborted_by_parent` completion for a single\r\n * PENDING task — one that was never counted in `inFlight`. This MUST bypass\r\n * `recordCompletion`: that path does `inFlight--`, which for a pending task\r\n * steals a decrement from a genuinely in-flight task and trips the underflow\r\n * guard — suppressing that real task's `task.completed` and hanging its\r\n * `awaitTasks()` caller. Pushes the result and fires the event directly.\r\n */\r\n private emitPendingAborted(task: TaskSpec, message: string): void {\r\n const synthetic: TaskResult = {\r\n subagentId: task.subagentId ?? 'unassigned',\r\n taskId: task.id,\r\n status: 'stopped',\r\n error: {\r\n kind: 'aborted_by_parent',\r\n message,\r\n retryable: false,\r\n },\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n };\r\n this.completedResults.push(synthetic);\r\n this.emit('task.completed', { task, result: synthetic });\r\n }\r\n\r\n private async runDispatched(subagentId: string, task: TaskSpec): Promise<void> {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) return;\r\n // Final race guard: if `stop(subagentId)` ran between dispatch\r\n // and us arriving here, refuse to start the task and surface it\r\n // as `aborted_by_parent` so any caller awaiting the task id\r\n // unblocks. Without this, the task would be marked 'running',\r\n // collide with the just-completed 'stopped' state, and leak\r\n // inFlight by 1 because no recordCompletion path covers it.\r\n if (this.terminating.has(subagentId) || subagent.status === 'stopped') {\r\n this.recordCompletion({\r\n subagentId,\r\n taskId: task.id,\r\n status: 'stopped',\r\n error: {\r\n kind: 'aborted_by_parent',\r\n message: 'Subagent was terminated before task could start',\r\n retryable: false,\r\n },\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n });\r\n return;\r\n }\r\n\r\n subagent.status = 'running';\r\n subagent.currentTask = task.id;\r\n task.subagentId = subagentId;\r\n subagent.context.tasks.push(task);\r\n\r\n this.fleetBus?.emit({\r\n subagentId,\r\n taskId: task.id,\r\n ts: Date.now(),\r\n type: 'subagent.running',\r\n payload: { subagentId, taskId: task.id },\r\n });\r\n\r\n this.emit('task.assigned', { task, subagentId });\r\n this.emitCoordinatorStats();\r\n\r\n // Budget combines coordinator defaults with per-subagent and per-task overrides.\r\n // Precedence: task > subagent (raw, no roster fills) > coordinator default > roster default.\r\n // We intentionally call applyRosterBudget LATE — only as a final fallback after\r\n // the coordinator's defaultBudget has had a chance to apply. This prevents\r\n // GENERIC_SUBAGENT_BUDGET (5000 iter) from shadowing the coordinator's explicit default.\r\n const rawMaxIterations = subagent.config.maxIterations;\r\n const rawMaxToolCalls = subagent.config.maxToolCalls;\r\n const rawMaxTokens = subagent.config.maxTokens;\r\n const rawMaxCostUsd = subagent.config.maxCostUsd;\r\n const rawTimeoutMs = subagent.config.timeoutMs;\r\n const rawIdleTimeoutMs = subagent.config.idleTimeoutMs;\r\n const configWithRosterDefaults = applyRosterBudget(subagent.config);\r\n const budget = new SubagentBudget({\r\n maxIterations:\r\n rawMaxIterations ?? this.config.defaultBudget?.maxIterations ?? configWithRosterDefaults.maxIterations,\r\n maxToolCalls:\r\n rawMaxToolCalls ??\r\n this.config.defaultBudget?.maxToolCalls ??\r\n configWithRosterDefaults.maxToolCalls,\r\n maxTokens:\r\n rawMaxTokens ?? this.config.defaultBudget?.maxTokens ?? configWithRosterDefaults.maxTokens,\r\n maxCostUsd:\r\n rawMaxCostUsd ?? this.config.defaultBudget?.maxCostUsd ?? configWithRosterDefaults.maxCostUsd,\r\n // Wall-clock cap is opt-in (explicit config / defaultBudget only); the\r\n // roster no longer supplies one. Idle is the default reaper.\r\n timeoutMs:\r\n rawTimeoutMs ?? this.config.defaultBudget?.timeoutMs ?? configWithRosterDefaults.timeoutMs,\r\n idleTimeoutMs:\r\n rawIdleTimeoutMs ??\r\n this.config.defaultBudget?.idleTimeoutMs ??\r\n configWithRosterDefaults.idleTimeoutMs,\r\n });\r\n subagent.activeBudget = budget;\r\n\r\n if (!this.runner) {\r\n // No runner wired — caller drives execution via completeTask(). Status\r\n // reverts when the caller reports. We intentionally don't bump\r\n // `inFlight` here: `completeTask` → `recordCompletion` would then\r\n // decrement an inFlight that runDispatched never incremented, masking\r\n // the \"no runner\" state. With this guard, `isDone()`'s all_tasks_done\r\n // check still settles correctly once the caller reports.\r\n return;\r\n }\r\n\r\n // Only count inFlight when we actually own the execution lifecycle.\r\n this.inFlight++;\r\n\r\n const startTime = Date.now();\r\n const runCtx: SubagentRunContext = {\r\n subagentId,\r\n config: subagent.config,\r\n budget,\r\n signal: subagent.abortController.signal,\r\n bridge: subagent.context.parentBridge || null,\r\n };\r\n\r\n let result: TaskResult;\r\n\r\n budget.start();\r\n try {\r\n const outcome = await this.executeWithTimeout(\r\n this.runner,\r\n task,\r\n runCtx,\r\n budget,\r\n subagent.config.preemptFraction,\r\n );\r\n result = {\r\n subagentId,\r\n taskId: task.id,\r\n status: 'success',\r\n result: outcome.result,\r\n iterations: outcome.iterations,\r\n toolCalls: outcome.toolCalls,\r\n durationMs: Date.now() - startTime,\r\n };\r\n } catch (err) {\r\n // Order matters: a timeout calls abort() to signal cooperative runners,\r\n // which also flips `signal.aborted=true`. Inspect the error first so we\r\n // surface 'timeout' rather than masking it as 'stopped'.\r\n const status: TaskResult['status'] =\r\n err instanceof BudgetExceededError && (err.kind === 'timeout' || err.kind === 'idle_timeout')\r\n ? 'timeout'\r\n : subagent.abortController.signal.aborted\r\n ? 'stopped'\r\n : 'failed';\r\n const usage = budget.usage();\r\n result = {\r\n subagentId,\r\n taskId: task.id,\r\n status,\r\n error: classifySubagentError(err, {\r\n parentAborted: subagent.abortController.signal.aborted,\r\n }),\r\n iterations: usage.iterations,\r\n toolCalls: usage.toolCalls,\r\n durationMs: Date.now() - startTime,\r\n };\r\n }\r\n\r\n this.recordCompletion(result);\r\n }\r\n\r\n private async executeWithTimeout(\r\n runner: SubagentRunner,\r\n task: TaskSpec,\r\n ctx: SubagentRunContext,\r\n budget: SubagentBudget,\r\n preemptFraction: number = TIMEOUT_PREEMPT_FRACTION,\r\n ) {\r\n const initialTimeoutMs = budget.limits.timeoutMs;\r\n const idleLimitMs = budget.limits.idleTimeoutMs;\r\n if (initialTimeoutMs === undefined && idleLimitMs === undefined) {\r\n return runner(task, ctx);\r\n }\r\n\r\n // Re-armable watchdog. The default guard is IDLE-based: while the agent\r\n // keeps producing activity (iterations / tool calls / streamed progress),\r\n // `budget.idleMs()` stays below the window and we simply re-arm — an\r\n // actively-working subagent is never killed by the clock. Only a genuine\r\n // stall (no activity for `idleTimeoutMs`) reaps it. An explicit wall-clock\r\n // `timeoutMs` (rare, opt-in) keeps the original soft-warning behaviour: it\r\n // negotiates an extension via the Director's auto-extend listener and\r\n // re-arms rather than hard-killing a task solely for running long.\r\n const start = Date.now();\r\n let timer: ReturnType<typeof setTimeout> | null = null;\r\n // Pre-empt arm state machine:\r\n // ACTIVE — pre-empt can fire for the current ceiling window\r\n // LOCKED — pre-empt is locked; cannot fire until ceiling changes\r\n enum PreemptState {\r\n ACTIVE = 'active',\r\n LOCKED = 'locked',\r\n }\r\n // The wall-clock ceiling value at the moment the state was locked.\r\n // Compared against the current wallLimit to detect stale locks caused by\r\n // external calls to budget.patchLimits().\r\n let preemptedCeiling: number | null = null;\r\n let preemptState: PreemptState = PreemptState.ACTIVE;\r\n // Heartbeat gate for the proactive pre-empt: the timestamp of the subagent's\r\n // last activity at the moment of the most recent grant. A later pre-empt is\r\n // only negotiated if there has been NEW activity since then — a stalled\r\n // agent (no progress since its last grant) gets no further extension and is\r\n // left to the real deadline. `-1` until the first grant so the first\r\n // pre-empt always fires. Activity time is derived from `budget.idleMs()`\r\n // (reset by tool calls / iterations / streamed progress), so it works even\r\n // for runners that don't increment the budget's usage counters directly.\r\n let lastGrantActivityTs = -1;\r\n\r\n const timeoutPromise = new Promise<never>((_, reject) => {\r\n // Terminate the subagent, classifying by whether a negotiation listener\r\n // is wired. A listener-observed stop (explicit deny at the deadline, or an\r\n // idle reap while observed) surfaces as 'stopped' — reject with a\r\n // non-budget error so the coordinator's catch falls to `signal.aborted →\r\n // 'stopped'`. With no listener it is an unattended budget breach →\r\n // BudgetExceededError → 'timeout'. This keeps a bare /spawn reporting\r\n // 'timeout' while a director/observer-driven stop reads as 'stopped'.\r\n const terminate = (kind: 'timeout' | 'idle_timeout', limit: number, used: number) => {\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(\r\n budget._events?.hasListenerFor('budget.threshold_reached')\r\n ? new Error(`subagent stopped: budget ${kind} (limit=${limit}, used=${used})`)\r\n : new BudgetExceededError(kind, limit, used),\r\n );\r\n };\r\n const armFor = (ms: number) => {\r\n if (timer) clearTimeout(timer);\r\n timer = setTimeout(onTick, Math.max(0, ms));\r\n };\r\n // Re-arm for whichever deadline is sooner — the idle window (counted\r\n // from last activity), the explicit wall-clock cap, or the PROACTIVE\r\n // pre-empt point (a fraction of the wall cap, see TIMEOUT_PREEMPT_FRACTION)\r\n // at which we negotiate an extension BEFORE the deadline is crossed. Any\r\n // being unset/already-asked drops out of the min, so single-limit configs\r\n // behave exactly as that limit alone.\r\n const scheduleNext = () => {\r\n const wallLimit = budget.limits.timeoutMs ?? initialTimeoutMs;\r\n const wallRemaining =\r\n initialTimeoutMs === undefined\r\n ? Number.POSITIVE_INFINITY\r\n : (wallLimit as number) - (Date.now() - start);\r\n const idleRemaining =\r\n idleLimitMs === undefined\r\n ? Number.POSITIVE_INFINITY\r\n : (budget.limits.idleTimeoutMs ?? idleLimitMs) - budget.idleMs();\r\n const preemptRemaining =\r\n initialTimeoutMs === undefined || preemptedCeiling === wallLimit\r\n ? Number.POSITIVE_INFINITY\r\n : (wallLimit as number) * preemptFraction - (Date.now() - start);\r\n // Floor at a small positive so a near-zero remainder can't busy-loop.\r\n armFor(Math.max(25, Math.min(wallRemaining, idleRemaining, preemptRemaining)));\r\n };\r\n\r\n // Drive a timeout extension negotiation (used by BOTH the proactive\r\n // pre-empt and the at-deadline path). Resolves to the coordinator's\r\n // verdict: `{ extend: { timeoutMs } }` to grant, or a string to decline.\r\n // The budget's requestDecision falls back to 'stop' on no response, so\r\n // this never hangs.\r\n // Safety net: if no listener responds to the budget.threshold_reached event\r\n // within DECISION_TIMEOUT_MS (60 s), default to 'stop' so the watchdog\r\n // never hangs. Uses the exported DECISION_TIMEOUT_MS so both paths share\r\n // the same value — coordinator and budget agree on the ceiling.\r\n const negotiateTimeout = async (\r\n used: number,\r\n limit: number,\r\n ): Promise<'stop' | 'continue' | 'throw' | { extend: { timeoutMs?: number | undefined } }> => {\r\n const handler = budget.onThreshold;\r\n if (!handler) return 'stop';\r\n const result = handler({\r\n kind: 'timeout',\r\n used,\r\n limit,\r\n requestDecision: () => {\r\n // No listener wired (bare /spawn, no director) → nobody can grant an\r\n // extension, so resolve to 'stop' immediately. Without this the emit\r\n // below goes unanswered and the run parks on the 60 s fallback timer\r\n // before stopping — the deadline must reap promptly instead. Mirrors\r\n // SubagentBudget._busRequestDecision so both agree on the default.\r\n if (!budget._events?.hasListenerFor('budget.threshold_reached')) {\r\n return Promise.resolve<'stop' | { extend: { timeoutMs?: number | undefined } }>('stop');\r\n }\r\n return new Promise<'stop' | { extend: { timeoutMs?: number | undefined } }>((resolveDecision) => {\r\n let settled = false;\r\n const resolve = (d: 'stop' | { extend: { timeoutMs?: number | undefined } }) => {\r\n if (settled) return;\r\n settled = true;\r\n resolveDecision(d);\r\n };\r\n const fallback = setTimeout(() => resolve('stop'), DECISION_TIMEOUT_MS);\r\n budget._events?.emit('budget.threshold_reached', {\r\n kind: 'timeout',\r\n used,\r\n limit,\r\n // Informational: the budget's own decision deadline. Listeners may use\r\n // this to display a countdown. The coordinator does NOT enforce it —\r\n // it is the budget's own `setTimeout(fallback)` that races against\r\n // the listener's `extend()`/`deny()` call to guarantee progress.\r\n timeoutMs: DECISION_TIMEOUT_MS,\r\n // deny() wins over a same-dispatch extend(): defer the grant a\r\n // microtask so a synchronous deny in the same emit pre-empts it\r\n // (a listener that both grants and denies, or two listeners\r\n // disagreeing, resolves as a stop). Async grants still resolve.\r\n extend: (extra) => {\r\n clearTimeout(fallback);\r\n queueMicrotask(() => resolve({ extend: extra }));\r\n },\r\n deny: () => {\r\n clearTimeout(fallback);\r\n resolve('stop');\r\n },\r\n });\r\n });\r\n },\r\n });\r\n return typeof result === 'string' ? result : await result;\r\n };\r\n\r\n const onTick = async () => {\r\n const elapsed = Date.now() - start;\r\n const wallLimit =\r\n initialTimeoutMs === undefined ? undefined : budget.limits.timeoutMs ?? initialTimeoutMs;\r\n const idleLimit =\r\n idleLimitMs === undefined ? undefined : budget.limits.idleTimeoutMs ?? idleLimitMs;\r\n const wallExceeded = wallLimit !== undefined && elapsed >= wallLimit;\r\n const idleExceeded = idleLimit !== undefined && budget.idleMs() >= idleLimit;\r\n\r\n // Idle stall with no wall-clock cap also due: a genuinely hung agent\r\n // (no activity for the whole window). Reap it directly — idle is NOT\r\n // negotiable; the point of the default is to free a stuck slot. We still\r\n // emit the threshold event first so observers (director / monitor) can\r\n // record the reap, but any extension a listener offers is ignored.\r\n if (idleExceeded && !wallExceeded) {\r\n budget._events?.emit('budget.threshold_reached', {\r\n kind: 'idle_timeout',\r\n used: budget.idleMs(),\r\n limit: idleLimit ?? 0,\r\n timeoutMs: DECISION_TIMEOUT_MS,\r\n extend: () => {},\r\n deny: () => {},\r\n });\r\n // An idle stall is a passive TIMEOUT (the agent hung), not an explicit\r\n // coordinator stop — surface it as 'timeout' regardless of any\r\n // listener. (Contrast the wall-clock deadline below, where an explicit\r\n // listener deny is a deliberate stop → 'stopped'.)\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(new BudgetExceededError('idle_timeout', idleLimit ?? 0, budget.idleMs()));\r\n return;\r\n }\r\n\r\n // PROACTIVE pre-empt: we've passed TIMEOUT_PREEMPT_FRACTION of the wall\r\n // window but NOT the deadline itself. Negotiate an extension now, while\r\n // the agent is still under its limit, so a progressing subagent gets its\r\n // ceiling raised and never enters a timed-out state. Heartbeat-gated on\r\n // the granting side (director / attachAutoExtend): no progress ⇒ decline,\r\n // and we fall through to the real-deadline behaviour below at the cap.\r\n // Asked at most once per window (preemptState === ACTIVE).\r\n if (\r\n wallLimit !== undefined &&\r\n !wallExceeded &&\r\n budget.onThreshold &&\r\n preemptState === PreemptState.ACTIVE &&\r\n elapsed >= wallLimit * preemptFraction\r\n ) {\r\n // Heartbeat gate: only negotiate a pre-empt extension if the agent has\r\n // made progress (a tool call / iteration / streamed output) SINCE the\r\n // last grant. A stalled agent — no new activity since its last\r\n // extension — gets no further pre-empt; we lock and let the real\r\n // deadline reap it. `activityTs` is the wall-clock time of the last\r\n // activity (now − idleMs). Without this gate an always-granting\r\n // listener would extend a wedged agent forever and the deadline would\r\n // never fire (T1).\r\n const activityTs = Date.now() - budget.idleMs();\r\n if (activityTs <= lastGrantActivityTs) {\r\n preemptState = PreemptState.LOCKED;\r\n preemptedCeiling = wallLimit;\r\n scheduleNext();\r\n return;\r\n }\r\n // C1 fix: register the watchdog as active BEFORE calling onThreshold so\r\n // that any concurrent tool.progress → checkTimeout() path sees the flag\r\n // and skips its own wall-clock emission. Cleared on every exit path so\r\n // checkTimeout() resumes normal operation after negotiation completes.\r\n budget.setWatchdogNegotiation(wallLimit);\r\n try {\r\n const decision = await negotiateTimeout(elapsed, wallLimit);\r\n if (typeof decision !== 'string' && decision.extend.timeoutMs !== undefined) {\r\n // Granted ahead of the deadline — raise the ceiling and open a\r\n // fresh window (a later pre-empt becomes eligible again, but only\r\n // if there is fresh activity by then — see the heartbeat gate).\r\n budget.patchLimits({ timeoutMs: decision.extend.timeoutMs });\r\n lastGrantActivityTs = Date.now() - budget.idleMs();\r\n preemptState = PreemptState.ACTIVE;\r\n preemptedCeiling = null;\r\n } else {\r\n // Declined proactively (no progress / no listener). Don't re-ask\r\n // until the real deadline — the wallExceeded path below handles the\r\n // at-cap behaviour (warn+continue or hard stop).\r\n preemptState = PreemptState.LOCKED;\r\n preemptedCeiling = wallLimit;\r\n }\r\n } catch {\r\n preemptState = PreemptState.LOCKED;\r\n preemptedCeiling = wallLimit;\r\n } finally {\r\n budget.clearWatchdogNegotiation();\r\n }\r\n scheduleNext();\r\n return;\r\n }\r\n\r\n // Neither deadline actually tripped — we woke early because activity\r\n // pushed the idle deadline out (or a pre-empt was just resolved).\r\n // Re-arm for the new soonest deadline.\r\n if (!wallExceeded) {\r\n scheduleNext();\r\n return;\r\n }\r\n\r\n // Wall-clock cap hit. This is opt-in and keeps the original\r\n // soft-warning behaviour: negotiate an extension rather than\r\n // hard-killing a task solely for running long.\r\n const limit = wallLimit ?? 0;\r\n // Without an onThreshold handler the original behaviour stands:\r\n // abort the signal and hard-reject. This preserves the contract\r\n // for direct SubagentBudget consumers that don't wire negotiation.\r\n if (!budget.onThreshold) {\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(new BudgetExceededError('timeout', limit, elapsed));\r\n return;\r\n }\r\n // C1 fix: same guard as the pre-empt branch — register before onThreshold\r\n // so concurrent tool.progress → checkTimeout() skips its wall-clock emission.\r\n budget.setWatchdogNegotiation(limit);\r\n try {\r\n const decision = await negotiateTimeout(elapsed, limit);\r\n if (decision === 'throw') {\r\n // 'throw' is an explicit signal from the handler: end now rather\r\n // than silently keeping the subagent alive past its deadline.\r\n terminate('timeout', limit, elapsed);\r\n return;\r\n }\r\n if (decision === 'continue') {\r\n // 'continue' — timeout denied but coordinator wants the agent to keep\r\n // running. Re-arm for a full wall window so we ask again later.\r\n // This makes wall-clock timeout a pure warning event: the subagent\r\n // keeps running until it naturally finishes, the next deadline fires,\r\n // or the user stops it.\r\n //\r\n // IMPORTANT: we must lock the pre-empt arm (set preemptState =\r\n // LOCKED) so it does NOT fire again until the ceiling changes.\r\n // The ceiling only changes if a future negotiation returns 'extend'\r\n // and patches budget.limits.timeoutMs. Without the lock, the\r\n // pre-empt would re-arm for ~1 s (Math.max(1_000, limit)) and\r\n // immediately fire again at elapsed > wallLimit × 0.85, creating\r\n // a ping-pong loop of spurious budget.threshold_reached events.\r\n preemptState = PreemptState.LOCKED;\r\n preemptedCeiling = wallLimit;\r\n armFor(Math.max(1_000, limit));\r\n return;\r\n }\r\n if (decision === 'stop') {\r\n // 'stop' — coordinator explicitly denied the extension and wants\r\n // the agent to end. This is a terminal decision: end now.\r\n terminate('timeout', limit, elapsed);\r\n return;\r\n }\r\n // 'extend' — patch budget and re-arm for the new remainder.\r\n if (decision.extend.timeoutMs !== undefined) {\r\n budget.patchLimits({ timeoutMs: decision.extend.timeoutMs });\r\n lastGrantActivityTs = Date.now() - budget.idleMs();\r\n preemptState = PreemptState.ACTIVE;\r\n preemptedCeiling = null;\r\n scheduleNext();\r\n return;\r\n }\r\n // No timeoutMs in extend — nothing to grant → end.\r\n terminate('timeout', limit, elapsed);\r\n return;\r\n } catch (err) {\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(\r\n err instanceof BudgetExceededError\r\n ? err\r\n : new BudgetExceededError('timeout', limit, elapsed),\r\n );\r\n return;\r\n } finally {\r\n // Always clear the watchdog flag so checkTimeout() resumes wall-clock\r\n // checking on the next tool.progress event.\r\n budget.clearWatchdogNegotiation();\r\n }\r\n };\r\n // First arm: whichever of the idle window / pre-empt point / wall cap is sooner.\r\n scheduleNext();\r\n });\r\n\r\n try {\r\n return await Promise.race([runner(task, ctx), timeoutPromise]);\r\n } finally {\r\n if (timer) clearTimeout(timer);\r\n }\r\n }\r\n\r\n private recordCompletion(result: TaskResult): void {\r\n this.completedResults.push(result);\r\n // Trim oldest entries when the cap is exceeded — keep the most recent\r\n // results so /fleet and roll_up still have data to work with.\r\n if (this.completedResults.length > DefaultMultiAgentCoordinator.MAX_COMPLETED_RESULTS) {\r\n this.completedResults.splice(\r\n 0,\r\n this.completedResults.length - DefaultMultiAgentCoordinator.MAX_COMPLETED_RESULTS,\r\n );\r\n }\r\n this.totalIterations += result.iterations;\r\n if (this.inFlight > 0) {\r\n this.inFlight--;\r\n } else if (this.runner) {\r\n // Runner-driven path completed without an outstanding inFlight slot —\r\n // shouldn't happen unless completeTask was called externally.\r\n this.emit('warning', {\r\n type: 'inFlight_underflow',\r\n taskId: result.taskId,\r\n subagentId: result.subagentId,\r\n });\r\n return;\r\n }\r\n\r\n const subagent = this.subagents.get(result.subagentId);\r\n if (subagent && subagent.status !== 'stopped') {\r\n const failed = result.status === 'failed' || result.status === 'timeout';\r\n // Synchronously reset the worker to idle after either a clean\r\n // finish or a transient failure. The previous code parked the\r\n // subagent in 'error' and used a `queueMicrotask` to flip it\r\n // back to 'idle' — that opened a window where `assign()` +\r\n // `tryDispatchNext` could race the microtask, leaving the\r\n // worker stuck in 'running' state while actually idle. By\r\n // resetting now, no async gap can leak the state machine.\r\n subagent.status = 'idle';\r\n void failed; // kept for future telemetry hooks\r\n subagent.currentTask = undefined;\r\n // If the run aborted (timeout or explicit stop), the subagent's\r\n // signal is now permanently aborted — recycling the controller lets\r\n // the next dispatched task start with a fresh cancellation scope.\r\n if (subagent.abortController.signal.aborted) {\r\n subagent.abortController = new AbortController();\r\n }\r\n\r\n this.fleetBus?.emit({\r\n subagentId: result.subagentId,\r\n ts: Date.now(),\r\n type: 'subagent.idle',\r\n payload: { subagentId: result.subagentId },\r\n });\r\n }\r\n // Clear the terminating flag now that the worker has a terminal\r\n // TaskResult on record. Subsequent stop() calls re-add it; new\r\n // assign() calls can flow normally.\r\n this.terminating.delete(result.subagentId);\r\n\r\n this.emit('task.completed', {\r\n task: subagent?.context.tasks.find((t) => t.id === result.taskId) ?? { id: result.taskId },\r\n result,\r\n });\r\n\r\n this.fleetBus?.emit({\r\n subagentId: result.subagentId,\r\n taskId: result.taskId,\r\n ts: Date.now(),\r\n type: 'subagent.completed',\r\n payload: {\r\n subagentId: result.subagentId,\r\n taskId: result.taskId,\r\n status: result.status,\r\n result: result.result,\r\n iterations: result.iterations,\r\n toolCalls: result.toolCalls,\r\n durationMs: result.durationMs,\r\n },\r\n });\r\n\r\n this.tryDispatchNext();\r\n\r\n // Emit after tryDispatchNext so the stats reflect the post-dispatch\r\n // state (either a new running subagent, or idle if the queue is drained).\r\n this.emitCoordinatorStats();\r\n\r\n if (this.isDone()) {\r\n this.emit('done', {\r\n results: this.completedResults,\r\n totalIterations: this.totalIterations,\r\n });\r\n }\r\n }\r\n\r\n /**\r\n * Stop a subagent and remove it from the coordinator. Releases all\r\n * associated resources (AbortController, context, budget state).\r\n * The subagent entry is deleted so the id can be reused in a future spawn.\r\n */\r\n async remove(subagentId: string): Promise<void> {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) return;\r\n\r\n // Gracefully stop first — same logic as stop() but don't block on it.\r\n if (subagent.status === 'running' || subagent.status === 'idle') {\r\n this.terminating.add(subagentId);\r\n subagent.abortController.abort();\r\n subagent.status = 'stopped';\r\n }\r\n\r\n // Release all resources associated with this subagent.\r\n this.subagents.delete(subagentId);\r\n this.terminating.delete(subagentId);\r\n // Free the nickname slot so the same name can be reused by a future spawn.\r\n const nicknameKey = this.subagentNicknames.get(subagentId);\r\n if (nicknameKey) {\r\n this.usedNicknames.delete(nicknameKey);\r\n this.subagentNicknames.delete(subagentId);\r\n }\r\n\r\n // Clean up any pending tasks assigned to this subagent — emit synthetic\r\n // 'stopped' completions so callers awaiting them via awaitTasks() unblock\r\n // instead of hanging forever. Without this, a task queued for a removed\r\n // subagent would leave its waiter permanently unresolved.\r\n const orphaned = this.pendingTasks.filter((t) => t.subagentId === subagentId);\r\n this.pendingTasks = this.pendingTasks.filter((t) => t.subagentId !== subagentId);\r\n for (const t of orphaned) {\r\n // Inline-emit, NOT recordCompletion: these are PENDING tasks that were\r\n // never counted in inFlight. Routing them through recordCompletion would\r\n // decrement inFlight on behalf of a still-running task and suppress that\r\n // task's own completion via the underflow guard, hanging its awaiter.\r\n this.emitPendingAborted(\r\n t,\r\n `Subagent \"${subagentId}\" was removed while task \"${t.id}\" was pending`,\r\n );\r\n }\r\n\r\n this.fleetBus?.emit({\r\n subagentId,\r\n ts: Date.now(),\r\n type: 'subagent.removed',\r\n payload: { subagentId },\r\n });\r\n\r\n this.emitCoordinatorStats();\r\n }\r\n\r\n private isDone(): boolean {\r\n if (this.config.doneCondition.type === 'all_tasks_done') {\r\n return this.pendingTasks.length === 0 && this.inFlight === 0;\r\n }\r\n if (\r\n this.config.doneCondition.maxIterations !== undefined &&\r\n this.totalIterations >= this.config.doneCondition.maxIterations\r\n ) {\r\n return true;\r\n }\r\n return false;\r\n }\r\n}\r\n\r\n/**\r\n * Map any raw exception thrown out of a subagent's runner into a\r\n * structured `SubagentError`. Delegates to the shared classifier.\r\n * Re-exported for backward compatibility.\r\n */\r\nexport { classifySubagentError } from './coordinator/error-classifier.js';\r\n","import { expectDefined } from '../utils/expect-defined.js';\nimport { toErrorMessage } from '../utils/error.js';\nimport { randomUUID } from 'node:crypto';\nimport type { Agent } from '../core/agent.js';\nimport type { AgentFactory } from '../coordination/agent-subagent-runner.js';\nimport { makeAgentSubagentRunner, withDisabledToolFiltering } from '../coordination/agent-subagent-runner.js';\nimport { dispatchAgent } from '../coordination/dispatcher.js';\nimport type { DispatchClassifier, DispatchResult } from '../coordination/dispatcher.js';\nimport type { EventBus } from '../kernel/events.js';\nimport type { SubagentConfig, TaskResult } from '../types/multi-agent.js';\nimport type { JournalEntry, GoalFile } from '../storage/goal-store.js';\nimport { loadGoal, saveGoal, appendJournal, goalFilePath } from '../storage/goal-store.js';\nimport type { Compactor } from '../types/compactor.js';\nimport { DefaultMultiAgentCoordinator } from '../coordination/multi-agent-coordinator.js';\nimport type { MultiAgentConfig } from '../types/multi-agent.js';\nimport { sleep } from '../utils/sleep.js';\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type ParallelEngineState = 'idle' | 'running' | 'stopped';\n\nexport type ParallelIterationStage =\n | { phase: 'idle' }\n | { phase: 'decompose' }\n | { phase: 'fanout'; slots: number }\n | { phase: 'await'; taskIds: string[] }\n | {\n phase: 'aggregate';\n successCount: number;\n total: number;\n goalComplete: boolean;\n }\n | { phase: 'sleep'; ms: number }\n | { phase: 'stopped' }\n | { phase: 'error'; message: string };\n\nexport interface ParallelEternalOptions {\n /** The coordinating agent — NOT a subagent. Owns container/tools/providers. */\n agent: Agent;\n /** Project root (used for goal.json path). */\n projectRoot: string;\n /**\n * Override the resolved goal.json path. Defaults to\n * `goalFilePath(projectRoot)` — the canonical per-project goal file under\n * `~/.wrongstack/projects/<slug>/`, shared with `/goal` and the TUI.\n * Primarily for tests that want an isolated goal file under a temp dir.\n */\n goalPath?: string | undefined;\n /**\n * Number of parallel subagent slots per tick.\n * Default: 4. Range 1–16; values >8 are for high-throughput machines.\n */\n parallelSlots?: number | undefined;\n /** Per-subagent default timeout in ms. Default: 300_000 (5 min). */\n iterationTimeoutMs?: number | undefined;\n onIteration?: (((entry: JournalEntry) => void)) | undefined;\n onError?: (err: Error | undefined, iteration: number) => void;\n /** Per-tick phase notifications for live UI/status updates. */\n onStage?: (((stage: ParallelIterationStage) => void)) | undefined;\n gitStatusReader?: ((() => Promise<string>)) | undefined;\n now?: ((() => Date)) | undefined;\n compactor?: Compactor | undefined;\n compactEveryNIterations?: number | undefined;\n aggressiveCompactRatio?: number | undefined;\n maxContextTokens?: number | undefined;\n /** Override the default agent factory (uses main agent if not provided). */\n subagentFactory?: AgentFactory | undefined;\n /**\n * Route each decomposed slot task to the best-fit catalog agent via the\n * smart dispatcher (heuristic keyword scoring). When enabled (default), each\n * slot spawns in-role — the role's budget tier applies and a persona line is\n * injected into the task — instead of as a faceless generic worker. Set\n * false to keep the legacy generic spawn.\n */\n dispatch?: boolean | undefined;\n /**\n * Optional LLM fallback for ambiguous tasks. Passed straight to\n * `dispatchAgent`; when omitted, routing is pure heuristic (instant, no\n * provider call — preferred for a continuously-ticking autonomous loop).\n */\n dispatchClassifier?: DispatchClassifier | undefined;\n /** Optional EventBus for emitting storage.* observability events from goal I/O. */\n events?: EventBus | undefined;\n}\n\nconst GOAL_COMPLETE_MARKER = /^\\s*\\[goal[_\\s-]?complete\\]\\s*$/im;\n\n// ---------------------------------------------------------------------------\n// ParallelEternalEngine\n// ---------------------------------------------------------------------------\n\n/**\n * Sense → Decide → Fan-out (4–8 parallel agents) → Aggregate → Loop.\n *\n * Each tick:\n * 1. Sense — load goal, todos, git status\n * 2. Decide — decompose goal into N parallel sub-tasks\n * 3. Fan-out — spawn N subagents simultaneously, await all\n * 4. Aggregate — write journal, update todos, check [GOAL_COMPLETE]\n * 5. Loop — continue until stop() or mission complete\n *\n * Uses DefaultMultiAgentCoordinator + AgentSubagentRunner for subagent lifecycle.\n */\nexport class ParallelEternalEngine {\n private state: ParallelEngineState = 'idle';\n private stopRequested = false;\n private iterationsSinceCompact = 0;\n private iterations = 0;\n private consecutiveFailures = 0;\n private readonly goalPath: string;\n private readonly slots: number;\n private readonly timeoutMs: number;\n private coordinator: DefaultMultiAgentCoordinator | null = null;\n private agentFactory: AgentFactory;\n private readonly dispatchEnabled: boolean;\n private readonly dispatchClassifier?: DispatchClassifier | undefined;\n\n constructor(private readonly opts: ParallelEternalOptions) {\n this.goalPath = opts.goalPath ?? goalFilePath(opts.projectRoot);\n this.slots = Math.min(16, Math.max(1, opts.parallelSlots ?? 4));\n this.timeoutMs = opts.iterationTimeoutMs ?? 300_000;\n this.dispatchEnabled = opts.dispatch !== false;\n this.dispatchClassifier = opts.dispatchClassifier;\n this.agentFactory =\n opts.subagentFactory ??\n (async (_config: SubagentConfig) => ({\n agent: this.opts.agent,\n events: this.opts.agent.events,\n }));\n }\n\n get currentState(): ParallelEngineState {\n return this.state;\n }\n\n /**\n * Get the underlying coordinator for stats/monitoring.\n */\n getCoordinator(): DefaultMultiAgentCoordinator | null {\n return this.coordinator;\n }\n\n stop(): void {\n this.stopRequested = true;\n void this.persistState('stopped').catch((err) => {\n console.error(JSON.stringify({\n level: 'error',\n event: 'engine.persist_state_failed',\n message: toErrorMessage(err),\n context: { expectedState: 'stopped' },\n timestamp: new Date().toISOString(),\n }));\n });\n this.state = 'stopped';\n }\n\n async prime(): Promise<void> {\n this.stopRequested = false;\n this.state = 'running';\n await this.persistState('running');\n }\n\n async run(): Promise<void> {\n this.state = 'running';\n await this.persistState('running');\n\n const config: MultiAgentConfig = {\n coordinatorId: `parallel-${randomUUID().slice(0, 8)}`,\n maxConcurrent: this.slots,\n doneCondition: { type: 'all_tasks_done' },\n };\n this.coordinator = new DefaultMultiAgentCoordinator(config);\n // Wrap factory with disabled tool filtering to prevent subagents from\n // using the delegate tool (or any other disabledTools in their config)\n const filteredFactory = withDisabledToolFiltering(this.agentFactory);\n const runner = makeAgentSubagentRunner({ factory: filteredFactory });\n this.coordinator.setRunner?.(runner);\n\n try {\n while (!this.stopRequested) {\n try {\n await this.runOneIteration();\n } catch (err) {\n this.consecutiveFailures++;\n this.opts.onError?.(\n err instanceof Error ? err : new Error(String(err)),\n this.consecutiveFailures,\n );\n await this.appendFailure(\n 'engine error',\n toErrorMessage(err),\n );\n }\n if (this.stopRequested) break;\n await sleep(2000);\n }\n } finally {\n this.state = 'stopped';\n await this.persistState('stopped').catch(() => {});\n }\n }\n\n /**\n * Execute one tick: decompose → fan-out → aggregate → compact.\n * Called by the REPL in its main loop (REPL drives, engine is stateless per tick).\n */\n async runOneIteration(): Promise<boolean> {\n const emit = (stage: ParallelIterationStage) => {\n this.opts.onStage?.(stage);\n };\n\n this.iterations++;\n\n const goal = await loadGoal(this.goalPath, this.opts.events);\n if (!goal) {\n this.stopRequested = true;\n emit({ phase: 'stopped' });\n return false;\n }\n if (goal.goalState !== 'active') {\n this.stopRequested = true;\n emit({ phase: 'stopped' });\n return false;\n }\n\n // Build coordinator on first tick.\n if (!this.coordinator) {\n const config: MultiAgentConfig = {\n coordinatorId: `parallel-${randomUUID().slice(0, 8)}`,\n maxConcurrent: this.slots,\n doneCondition: { type: 'all_tasks_done' },\n };\n this.coordinator = new DefaultMultiAgentCoordinator(config);\n // Wrap factory with disabled tool filtering to prevent subagents from\n // using the delegate tool (or any other disabledTools in their config)\n const filteredFactory = withDisabledToolFiltering(this.agentFactory);\n const runner = makeAgentSubagentRunner({ factory: filteredFactory });\n this.coordinator.setRunner?.(runner);\n }\n\n emit({ phase: 'decompose' });\n const tasks = await this.decomposeGoal(goal);\n if (!tasks || tasks.length === 0) {\n // Nothing to do this tick. The run() loop paces idle iterations itself\n // (see its sleep), so a single runOneIteration() must return promptly.\n emit({ phase: 'sleep', ms: 2000 });\n return false;\n }\n\n emit({ phase: 'fanout', slots: Math.min(this.slots, tasks.length) });\n const fanOut = await this.fanOut(goal, tasks);\n this.iterationsSinceCompact++;\n\n const successCount = fanOut.results.filter((r) => r.status === 'success').length;\n const status: JournalEntry['status'] = fanOut.goalComplete\n ? 'success'\n : fanOut.allSuccessful\n ? 'success'\n : 'failure';\n const note = [\n `${successCount}/${fanOut.results.length} subagents succeeded`,\n fanOut.goalComplete ? '[GOAL_COMPLETE]' : '',\n fanOut.partialOutput ? `Output: ${fanOut.partialOutput.slice(0, 120)}` : '',\n ]\n .filter(Boolean)\n .join(' | ');\n\n // Surface routing in the journal: \"role→task-snippet\" per slot so /goal\n // journal shows which agent handled what.\n const routeSummary =\n fanOut.routes.length > 0\n ? fanOut.routes\n .slice(0, 3)\n .map((r) => `${r.role}→${r.task.slice(0, 28)}`)\n .join(', ')\n : tasks.slice(0, 3).join(', ');\n await this.appendIterationEntry({\n source: 'parallel',\n task: `parallel:${tasks.length} slots — ${routeSummary}${tasks.length > 3 ? '...' : ''}`,\n status,\n note,\n });\n emit({\n phase: 'aggregate',\n successCount,\n total: fanOut.results.length,\n goalComplete: fanOut.goalComplete,\n });\n\n if (fanOut.goalComplete) {\n this.stopRequested = true;\n this.state = 'stopped';\n emit({ phase: 'stopped' });\n return true;\n }\n\n await this.maybeCompact();\n emit({ phase: 'sleep', ms: 2000 });\n return fanOut.allSuccessful;\n }\n\n // -------------------------------------------------------------------------\n // Fan-out\n // -------------------------------------------------------------------------\n\n private async fanOut(\n goal: GoalFile,\n tasks: string[],\n ): Promise<{\n results: TaskResult[];\n allSuccessful: boolean;\n goalComplete: boolean;\n partialOutput: string;\n routes: Array<{ slot: number; task: string; role: string; method: string }>;\n }> {\n const coordinator = expectDefined(this.coordinator);\n const slotCount = Math.min(this.slots, tasks.length);\n\n // Route each slot task to the best-fit catalog agent. Heuristic by default\n // (instant, no provider call); an injected classifier enables LLM fallback.\n // A dispatch failure for one slot is non-fatal — that slot stays generic.\n const routes: (DispatchResult | null)[] = this.dispatchEnabled\n ? await Promise.all(\n tasks\n .slice(0, slotCount)\n .map((t) =>\n dispatchAgent(t, { classifier: this.dispatchClassifier }).catch(() => null),\n ),\n )\n : [];\n\n const recentJournal = goal.journal\n .slice(-5)\n .map(\n (e) =>\n ` #${e.iteration} [${e.status}] ${e.task}${e.note ? ` — ${e.note.slice(0, 80)}` : ''}`,\n )\n .join('\\n');\n\n const directivePreamble = [\n '═══ ETERNAL AUTONOMY — parallel task slot ═══',\n '',\n `Mission: ${goal.goal}`,\n `Total parallel slots: ${slotCount}`,\n '',\n recentJournal ? `Recent journal (last 5):\\n${recentJournal}` : 'No prior iterations.',\n '',\n '── EXECUTION PROTOCOL ──',\n '• Execute the assigned task end-to-end using multiple tool calls.',\n '• Emit `[done]` on its own line when the task is complete.',\n '• Do not ask before routine in-project tool use — YOLO is active for normal project work.',\n '• If a destructive-gated confirmation appears, wait for the permission flow.',\n '• If the overall Mission is accomplished, emit `[GOAL_COMPLETE]` followed by a verification recipe.',\n '• Keep output concise — summarize findings, do not transcribe files.',\n ].join('\\n');\n\n const taskIds: string[] = [];\n const subagentIds: string[] = [];\n const routeInfo: Array<{ slot: number; task: string; role: string; method: string }> = [];\n\n const spawnPromises: Array<Promise<void>> = [];\n for (let i = 0; i < slotCount; i++) {\n const task = expectDefined(tasks[i]);\n const route = routes[i] ?? null;\n const subagentId = `parallel-${this.iterations}-${i}`;\n const taskId = randomUUID();\n\n // Persona injection — works even with the default factory (which reuses\n // the shared main agent and ignores config.prompt/tools), so the agent\n // adopts the routed role's stance for this slot.\n const personaLine = route\n ? `Acting agent: ${route.definition.config.name} — ${route.definition.capability.summary}\\n`\n : '';\n const spec = {\n id: taskId,\n description: `${directivePreamble}\\n\\n── SLOT ${i + 1}/${slotCount} ──\\n${personaLine}Task: ${task}\\n`,\n subagentId,\n };\n\n routeInfo.push({\n slot: i,\n task,\n role: route?.role ?? 'generic',\n method: route?.method ?? 'none',\n });\n\n spawnPromises.push(\n (async () => {\n try {\n // Spawn in-role when routed: `role` lets applyRosterBudget resolve the\n // role's budget tier; name/tools/systemPromptOverride specialize the\n // worker if a real per-role factory is wired (forward-compatible).\n await coordinator.spawn(\n route\n ? {\n id: subagentId,\n name: route.definition.config.name,\n role: route.role,\n tools: route.definition.config.tools,\n systemPromptOverride: route.definition.config.prompt,\n timeoutMs: this.timeoutMs,\n // Disable delegation — subagents are leaf workers, not orchestrators\n disabledTools: ['delegate'],\n }\n : {\n id: subagentId,\n name: `slot-${subagentId.slice(-6)}`,\n // Let the coordinator apply its default budget (roster or generic).\n // Hardcoding low limits here defeats the x10 budget improvement.\n timeoutMs: this.timeoutMs,\n // Disable delegation — subagents are leaf workers, not orchestrators\n disabledTools: ['delegate'],\n },\n );\n subagentIds.push(subagentId);\n taskIds.push(taskId);\n await coordinator.assign(spec);\n } catch {\n // non-fatal: individual spawn failure doesn't block other slots\n }\n })(),\n );\n }\n await Promise.all(spawnPromises);\n\n if (taskIds.length === 0) {\n return {\n results: [],\n allSuccessful: false,\n goalComplete: false,\n partialOutput: '',\n routes: routeInfo,\n };\n }\n\n this.opts.onStage?.({ phase: 'await', taskIds: [...taskIds] });\n\n let results: TaskResult[] = [];\n try {\n // Wait up to 2 hours for subagents to complete. This should cover\n // most subagent tasks since the roster budgets go up to 10 hours.\n // The outer eternal loop manages actual iteration limits.\n const ctrl = new AbortController();\n const timer = setTimeout(() => ctrl.abort(), Math.max(this.timeoutMs * 2, 7200_000));\n try {\n results = await coordinator.awaitTasks(taskIds);\n } finally {\n clearTimeout(timer);\n }\n } catch {\n results = coordinator.results().slice(-taskIds.length);\n }\n\n // Free each per-tick subagent now that its task has resolved. Without this,\n // an eternal-parallel run accumulates dead subagent entries (and their\n // nickname slots) in the coordinator forever — a slow but unbounded leak\n // over multi-day loops. remove() is idempotent and non-throwing per id.\n await Promise.allSettled(subagentIds.map((id) => coordinator.remove(id)));\n\n const allSuccessful = results.length > 0 && results.every((r) => r.status === 'success');\n const goalComplete = results.some(\n (r) =>\n r.status === 'success' &&\n typeof r.result === 'string' &&\n GOAL_COMPLETE_MARKER.test(r.result),\n );\n const partialOutput = results\n .map((r) => (typeof r.result === 'string' ? r.result : ''))\n .filter(Boolean)\n .join('\\n\\n');\n\n return { results, allSuccessful, goalComplete, partialOutput, routes: routeInfo };\n }\n\n // -------------------------------------------------------------------------\n // Goal decomposition\n // -------------------------------------------------------------------------\n\n private async decomposeGoal(goal: GoalFile): Promise<string[] | null> {\n // Strategy 1: pending todos as sub-tasks\n const todos = this.opts.agent.ctx?.todos;\n const tasks: string[] = [];\n if (Array.isArray(todos)) {\n const pending = todos.filter((t) => t.status === 'pending').slice(0, this.slots);\n for (const t of pending) {\n tasks.push(`[todo] ${t.content}`);\n }\n }\n\n // Strategy 2: git dirty files\n if (tasks.length < this.slots) {\n try {\n const gitStatus = await (this.opts.gitStatusReader?.() ?? this.readGitStatus());\n const dirty = gitStatus.trim();\n if (dirty) {\n const lines = dirty.split('\\n').slice(0, this.slots - tasks.length);\n for (const line of lines) {\n const file = line.replace(/^[ MADRUC?]{2}\\s*/, '').trim();\n if (file) tasks.push(`[git] inspect and fix: ${file}`);\n }\n }\n } catch {\n // ignore\n }\n }\n\n // Strategy 3: leader-brainstormed sub-tasks for remaining slots\n if (tasks.length < this.slots) {\n const remaining = this.slots - tasks.length;\n const brainstormed = await this.brainstormSubtasks(goal, remaining);\n tasks.push(...brainstormed);\n }\n\n return tasks.length > 0 ? tasks.slice(0, this.slots) : null;\n }\n\n private async readGitStatus(): Promise<string> {\n const { execFile } = await import('node:child_process');\n const { promisify } = await import('node:util');\n const execFileP = promisify(execFile);\n const { stdout } = await execFileP('git', ['status', '--porcelain'], {\n cwd: this.opts.projectRoot,\n timeout: 5_000,\n });\n return stdout;\n }\n\n private async brainstormSubtasks(goal: GoalFile, count: number): Promise<string[]> {\n const lastFew = goal.journal\n .slice(-5)\n .map((e) => ` - [${e.status}] ${e.task}`)\n .join('\\n');\n const directive = [\n `Decompose this goal into exactly ${count} independent sub-tasks for parallel execution.`,\n '',\n `Goal: ${goal.goal}`,\n '',\n lastFew ? `Recent:\\n${lastFew}` : 'No prior iterations.',\n '',\n `Output exactly ${count} tasks, one per line, under 120 chars each.`,\n 'Format: TASK-1 | TASK-2 | ... (pipe-separated, no numbering, no preamble).',\n 'Each task must be independently actionable with no shared dependencies.',\n ].join('\\n');\n\n try {\n const ctrl = new AbortController();\n const timer = setTimeout(() => ctrl.abort(), 60_000);\n try {\n const result = await this.opts.agent.run([{ type: 'text' as const, text: directive }], {\n signal: ctrl.signal,\n maxIterations: 1,\n });\n if (result.status !== 'done') return [];\n const text = (result.finalText ?? '').trim();\n if (!text) return [];\n const tasks = text\n .split('|')\n .map((t) => t.trim())\n .filter((t) => t.length > 10 && t.length < 240);\n return tasks.slice(0, count);\n } finally {\n clearTimeout(timer);\n }\n } catch (err) {\n // The leader agent failed to brainstorm. Surface it to onError so the\n // failure is visible, but keep the loop alive (return no tasks — the\n // next tick retries) rather than crashing the autonomous engine.\n this.opts.onError?.(\n err instanceof Error ? err : new Error(String(err)),\n this.consecutiveFailures,\n );\n return [];\n }\n }\n\n // -------------------------------------------------------------------------\n // Compaction\n // -------------------------------------------------------------------------\n\n private async maybeCompact(): Promise<void> {\n const compactor = this.opts.compactor;\n if (!compactor) return;\n const ctx = this.opts.agent.ctx;\n if (!ctx) return;\n\n const shouldRun = this.iterationsSinceCompact >= (this.opts.compactEveryNIterations ?? 25);\n if (!shouldRun) return;\n\n const report = await compactor.compact(ctx, { aggressive: false });\n this.iterationsSinceCompact = 0;\n await this.appendIterationEntry({\n source: 'manual',\n task: 'compaction (cadence)',\n status: 'success',\n note: `saved ~${report.before - report.after} tokens`,\n });\n }\n\n // -------------------------------------------------------------------------\n // Helpers\n // -------------------------------------------------------------------------\n\n private async appendIterationEntry(entry: Omit<JournalEntry, 'iteration' | 'at'>): Promise<void> {\n const current = await loadGoal(this.goalPath, this.opts.events);\n if (!current) return;\n const updated = appendJournal(current, entry);\n await saveGoal(this.goalPath, updated, this.opts.events);\n const entryWithMeta: JournalEntry = {\n at: (this.opts.now?.() ?? new Date()).toISOString(),\n iteration: updated.iterations,\n ...entry,\n };\n this.opts.onIteration?.(entryWithMeta);\n }\n\n private async appendFailure(task: string, note: string): Promise<void> {\n await this.appendIterationEntry({ source: 'manual', task, status: 'failure', note });\n }\n\n private async persistState(state: GoalFile['engineState']): Promise<void> {\n const current = await loadGoal(this.goalPath, this.opts.events);\n if (!current) return;\n if (current.engineState === state) return;\n await saveGoal(this.goalPath, { ...current, engineState: state }, this.opts.events);\n }\n}\n","/**\n * System-prompt contributor that surfaces eternal-autonomy state to the\n * model on every turn.\n *\n * Why this exists: when the engine drives a long-running loop, the\n * per-iteration directive carries the rules. But the directive is a USER\n * message — it scrolls out of working memory after a few compactions and\n * the model forgets it's in autonomy mode (forgets `[GOAL_COMPLETE]`,\n * forgets the todo-state protocol, forgets the no-confirmation rule).\n * Injecting the same anchor as a CACHED system-prompt block solves that\n * — the rules sit next to the identity layer and survive compactions.\n *\n * Block is tagged `ephemeral` so its content (journal tail, iteration\n * counter) changes each turn without invalidating the upstream prefix\n * cache.\n */\n\nimport type { TextBlock } from '../types/blocks.js';\nimport type { SystemPromptContributor } from '../types/system-prompt-contributor.js';\nimport { loadGoal } from '../storage/goal-store.js';\n\nexport interface AutonomyPromptContributorOptions {\n /** Absolute path to the project's `goal.json`. */\n goalPath: string;\n /**\n * Gating function. The contributor consults this on every build and\n * returns an empty array when `false` — without this, the block would\n * leak into interactive runs that happen to have a goal on disk and\n * teach the model loop-control markers it shouldn't emit.\n *\n * Typical wiring: enable while `eternal` or `eternal-parallel` autonomy is active.\n */\n enabled: () => boolean;\n /** Number of journal entries to include in the recent-tail block. Default 5. */\n journalTailSize?: number | undefined;\n}\n\n/**\n * Build a contributor that renders the autonomy-state system block.\n * Returns `[]` when disabled, no goal exists, or the goal has been\n * completed/abandoned — all silent fast-paths.\n */\nexport function makeAutonomyPromptContributor(\n opts: AutonomyPromptContributorOptions,\n): SystemPromptContributor {\n return async (ctx): Promise<TextBlock[]> => {\n // Subagents run a single scoped task and don't drive the engine's\n // outer loop — they have no business emitting `[GOAL_COMPLETE]` or\n // marking todos. Skip the block entirely for subagent prompt builds,\n // mirroring how the active-plan layer is suppressed.\n if (ctx.subagent) return [];\n if (!opts.enabled()) return [];\n\n let goal: Awaited<ReturnType<typeof loadGoal>>;\n try {\n goal = await loadGoal(opts.goalPath);\n } catch {\n return [];\n }\n if (!goal) return [];\n\n // `active` is the default for legacy goal files without the field.\n const missionState = goal.goalState ?? 'active';\n if (missionState !== 'active') return [];\n\n const tailSize = opts.journalTailSize ?? 5;\n const journalTail = goal.journal.slice(-tailSize).map((e) => {\n const note = e.note ? ` — ${e.note.slice(0, 80)}` : '';\n return ` #${e.iteration} [${e.status}] ${e.task}${note}`;\n });\n\n const text = [\n '## ETERNAL AUTONOMY — active mission',\n '',\n 'You are inside a long-running autonomous loop. The user is asleep',\n 'and is not available to confirm decisions. Each turn you receive a',\n 'directive describing one concrete sub-task that advances the mission.',\n '',\n `Mission: ${goal.goal}`,\n `Iteration: #${goal.iterations}`,\n journalTail.length > 0\n ? `Recent journal (last ${journalTail.length}):\\n${journalTail.join('\\n')}`\n : 'Recent journal: (none — this is the first iteration)',\n '',\n '### Loop control markers',\n 'Emit these on their own line in your final text — case-insensitive,',\n 'whitespace-tolerant, but they must occupy the entire line:',\n '- `[continue]` — chain to the next internal step without returning.',\n '- `[done]` — the current sub-task is finished; return to the engine.',\n '- `[GOAL_COMPLETE]` — emit ONLY when the OVERALL mission is',\n ' verifiably done. Must be followed by a one-paragraph verification',\n ' recipe (artifact path, test command, or 10-second reproduction).',\n ' The engine halts on this marker — false positives waste real',\n ' human time. If unsure, emit `[done]` and let the next iteration',\n ' decide.',\n '',\n '### Operating principles',\n '- YOLO is active for normal project work. Proceed with routine',\n ' in-project tool use without pre-confirming; pick the best path and execute it.',\n ' If the permission system raises a destructive-gated confirmation, wait',\n ' for that flow instead of trying to bypass it.',\n '- Use tools freely; multiple calls per turn are normal and expected.',\n '- When working on a todo, mark it `in_progress` via the todos tool',\n ' before tool work and `completed` (or `cancelled` with a reason)',\n ' when done. The loop reads todo state between iterations.',\n \"- If an approach fails twice in a row, pivot. Don't grind on the\",\n ' same wall — try a different angle, file a cancel on the todo, or',\n ' surface the obstacle via `[done]` and let the next iteration',\n ' re-plan.',\n ].join('\\n');\n\n return [\n {\n type: 'text',\n text,\n cache_control: { type: 'ephemeral' },\n },\n ];\n };\n}\n","/**\n * `/goal <description>` preamble — the \"no force can stop this\" mode.\n *\n * Unlike STEERING (which redirects mid-flight), GOAL is a contract:\n * the user hands over a problem, the agent commits to verifiably\n * finishing it, and every iteration re-reads this preamble from the\n * conversation history. The hardening is entirely prompt-level —\n * the system has already removed implicit budget caps, so this\n * preamble's job is to remove the MODEL's tendency to hedge, ask\n * permission, or declare premature success.\n *\n * The four sections are intentional:\n * 1. AUTHORITY — explicit grant of unbounded fan-out + model\n * switching. Without this the model self-throttles (\"I shouldn't\n * spawn too many…\") even when budgets are unlimited.\n * 2. DONE — concrete bar for completion. Forces a verifiable\n * artifact (test passing, file written, bug re-run clean).\n * Without this the model returns \"I believe it's fixed\" and\n * counts that as done.\n * 3. NOT DONE — explicit anti-patterns. Each item is something we\n * saw real agents do as a \"completion\" that wasn't.\n * 4. PERSISTENCE — three-angle rule for blockers. Stops the model\n * from giving up on the first tool failure.\n *\n * Located in @wrongstack/core (rather than @wrongstack/tui) so headless\n * callers and the WebUI can issue `/goal set` without dragging the TUI\n * package in. The tui re-exports this for backward compatibility.\n */\nexport function buildGoalPreamble(goal: string, deliverables?: string[]): string {\n const deliverableBlock = deliverables && deliverables.length > 0\n ? [\n '',\n 'CONCRETE DELIVERABLES (check these off as you go):',\n ...deliverables.map((d, i) => ` ${i + 1}. ${d}`),\n '',\n 'After EACH iteration, estimate your completion percentage (0–100)',\n 'against this deliverable list. Output it as:',\n ' [PROGRESS: N%] — <1-sentence status>',\n 'The eternal engine reads this to update the progress bar.',\n ].join('\\n')\n : '';\n\n return [\n '[GOAL — LOCKED IN. You will work on this until it is verifiably done.',\n 'The user granted you full autonomy. Read these constraints once, then act.',\n '',\n 'YOUR GOAL:',\n '---',\n goal,\n '---',\n deliverableBlock,\n '',\n 'AUTHORITY YOU HAVE:',\n '- Spawn as many subagents as the work needs (delegate / spawn_subagent).',\n ' Parallel + recursive fan-out are both fine. There is no spawn budget.',\n '- Use any provider/model per subagent — pick the right tool for each',\n ' piece of work. Heavy reasoning model for planning, fast model for',\n ' batch work, specialist model for domain code.',\n '- Run unlimited tool calls and iterations. There is NO hidden budget.',\n ' The Agent loop auto-extends every 100 iterations forever.',\n '- Retry failed tools with different inputs, alternative paths, fresh',\n ' subagents. Switch providers mid-run if one is rate-limited.',\n '- Re-plan freely when an approach hits a dead end. You are not obliged',\n ' to stick with the first plan you proposed.',\n '',\n 'WHAT \"DONE\" MEANS — non-negotiable:',\n '- You can name a concrete artifact (a passing test, a written file at',\n ' a specific path, a fixed bug verified by re-running the failing case,',\n ' a clean grep that previously had matches).',\n '- You can tell the user HOW to verify it themselves in 10 seconds.',\n '- You have NOT hedged. None of: \"looks like it should work\", \"I',\n ' believe this fixes it\", \"the changes appear correct\".',\n `- Progress bar shows 100%. All deliverables checked off.`,\n '',\n 'WHAT IS NOT DONE — never report any of these as completion:',\n \"- An error message you didn't recover from.\",\n '- An empty result, a 0-line file, a \"no matches found\" you accepted',\n ' without questioning the search.',\n '- \"Should I continue?\" / \"Want me to also...?\" / \"Let me know if you',\n ' want X.\" Those are hedges. The user already told you to finish the',\n ' goal — just do it.',\n '- Partial progress dressed up as success. Fixed 3 of 5 bugs = 60%',\n ' done, not done.',\n \"- A subagent's failed/timeout/stopped TaskResult that you didn't\",\n ' respond to with a fresh attempt (different role, different model,',\n ' tighter prompt).',\n '',\n 'PROGRESS REPORTING — MANDATORY every iteration:',\n '- End every response with exactly: [PROGRESS: N%] — <status note>',\n ' where N is your honest estimate (0-100) of how much of the goal',\n ' is done. The engine tracks this and shows a live progress bar.',\n '- Example: [PROGRESS: 45%] — Auth module refactored, 3/5 tests pass,',\n ' remaining: test coverage + docs update.',\n '',\n 'PERSISTENCE PROTOCOL:',\n '- If blocked, try at least 3 different angles before reporting the',\n ' problem to the user. Different tool inputs, different subagent',\n ' roles, different providers, different decomposition of the task.',\n '- If a tool fails, read its error, alter the input, try again. Do',\n ' not just report the failure back.',\n '- If a subagent returns useless output, respawn with a tighter prompt',\n ' or a different role. Do not accept \"I could not determine…\" as the',\n ' final answer.',\n \"- Use `ask_subagent` for one-shot questions when you don't need a\",\n ' full delegated task.',\n '',\n 'REPORTING:',\n '- Stream short progress notes between major actions so the user can',\n ' monitor. Do not go silent for 50 tool calls then dump a wall of',\n ' text — but also do not narrate every tool call.',\n '- Use the shared scratchpad (if available) to leave breadcrumbs',\n ' subagents can read.',\n '- Final response must include: (a) what was accomplished, (b) how',\n ' to verify, (c) any caveats (residual TODOs, things the user',\n ' should know about).',\n '',\n 'BEGIN.]',\n ].join('\\n');\n}\n","/**\n * Shared regex patterns used across execution and security-scanner.\n * Centralized here to avoid duplication and keep patterns in sync.\n */\n\n/** Matches Node.js ECONN* errors and fetch failure messages. */\nexport const NETWORK_ERR_RE = /ECONN|ETIMEDOUT|ETIME|ENOTFOUND|EAI_AGAIN|fetch failed/i;","import { ProviderError } from '../types/provider.js';\nimport { NETWORK_ERR_RE } from './regex-patterns.js';\nimport type { RetryPolicy } from '../types/retry-policy.js';\n\nexport class DefaultRetryPolicy implements RetryPolicy {\n shouldRetry(err: Error | ProviderError, attempt: number): boolean {\n if (err instanceof ProviderError) {\n if (!err.retryable) return false;\n return attempt < this.maxAttempts(err);\n }\n const msg = err.message ?? '';\n const isNetwork = NETWORK_ERR_RE.test(msg);\n if (isNetwork) return attempt < 2;\n return false;\n }\n\n maxAttempts(err: Error | ProviderError): number {\n if (err instanceof ProviderError) {\n if (err.status === 429) return 5;\n if (err.status === 529) return 3;\n if (err.status === 599) return 5; // stream hang — transient, worth retrying aggressively\n if (err.status >= 500) return 3;\n return 0;\n }\n return 2;\n }\n\n delayMs(attempt: number): number {\n const base = 1000;\n const exp = base * 2 ** attempt;\n const jitter = Math.random() * base;\n return Math.min(30_000, exp + jitter);\n }\n}\n","import type { Context } from '../core/context.js';\nimport type { ErrorHandler, RecoveryDecision } from '../types/error-handler.js';\nimport { ProviderError } from '../types/provider.js';\nimport { NETWORK_ERR_RE } from './regex-patterns.js';\nimport type { Compactor } from '../types/compactor.js';\nimport type { ModelsRegistry } from '../types/models-registry.js';\n\n/**\n * Tiered error recovery strategies.\n * Each strategy is attempted in order until one returns a decision.\n */\nexport interface RecoveryStrategy {\n /** Human-readable label for logs. */\n label: string;\n /** Optional compactor for context_overflow recovery. */\n compactor?: Compactor | undefined;\n /** Returns an explicit recovery decision, or null to fall through. */\n attempt: (err: unknown, ctx: Context) => Promise<RecoveryDecision | null>;\n}\n\n// Package-level compiled regex for hot paths — avoids repeated compilation.\nconst CONTEXT_OVERFLOW_RE = /context|too long|tokens|exceeds the context window|context window/i;\n\n/**\n * Builds the ordered list of recovery strategies used by DefaultErrorHandler.\n * Exported so callers can customise or extend the strategy chain.\n */\nexport function buildRecoveryStrategies(opts?: {\n compactor?: Compactor | undefined;\n modelsRegistry?: ModelsRegistry | undefined;\n}): RecoveryStrategy[] {\n return [\n {\n label: 'context_overflow_reduce',\n compactor: opts?.compactor,\n async attempt(err, ctx) {\n if (!(err instanceof ProviderError)) return null;\n if (err.status !== 413 && !isContextOverflowError(err)) return null;\n\n if (this.compactor) {\n try {\n const report = await this.compactor.compact(ctx, { aggressive: true });\n if (report.after < report.before) {\n return { action: 'retry', reason: 'context_compacted' };\n }\n } catch {\n // compact failed; fall through\n }\n }\n return null;\n },\n },\n {\n label: 'rate_limit_backoff',\n async attempt(err) {\n if (!(err instanceof ProviderError) || err.status !== 429) return null;\n\n // Prefer the parsed Retry-After hint the provider extracted into\n // body.retryAfterMs; fall back to 5s when absent.\n const delayMs = err.body?.retryAfterMs ?? 5_000;\n // Clamp between 1s and 60s.\n const delay = Math.min(60_000, Math.max(1_000, delayMs));\n await new Promise((r) => setTimeout(r, delay));\n return { action: 'retry', reason: 'rate_limit_backoff' };\n },\n },\n {\n label: 'downgrade_model',\n async attempt(err, ctx) {\n if (!(err instanceof ProviderError)) return null;\n if (err.status !== 429 && err.status !== 529 && err.status < 500) return null;\n\n const registry = opts?.modelsRegistry;\n if (!registry) return null;\n\n try {\n const providerId = ctx.provider?.id;\n if (!providerId) return null;\n const provider = await registry.getProvider(providerId);\n if (!provider) return null;\n\n const currentModel = await registry.getModel(providerId, ctx.model);\n if (!currentModel) return null;\n\n // Find a cheaper fallback model with the same capabilities.\n // Prefer models with lower input cost, preferring the same family.\n const candidates = provider.models.filter((m) => {\n const modelCost = m.cost?.input ?? Number.POSITIVE_INFINITY;\n const currentCost = currentModel.cost?.input ?? Number.POSITIVE_INFINITY;\n if (modelCost >= currentCost) return false;\n if (currentModel.capabilities.tools && !m.tool_call) return false;\n if (currentModel.capabilities.vision && !m.modalities?.input?.includes('image'))\n return false;\n return true;\n });\n\n if (candidates.length === 0) return null;\n\n const fallback = candidates.reduce((prev, curr) =>\n (curr.cost?.input ?? 0) < (prev.cost?.input ?? 0) ? curr : prev,\n );\n\n return {\n action: 'retry',\n reason: 'model_downgrade',\n model: fallback.id,\n };\n } catch {\n return null;\n }\n },\n },\n ];\n}\n\nexport const DEFAULT_RECOVERY_STRATEGIES = buildRecoveryStrategies();\n\nfunction isContextOverflowError(err: ProviderError): boolean {\n return CONTEXT_OVERFLOW_RE.test([\n err.message,\n err.body?.message,\n err.body?.type,\n err.body?.raw,\n ].filter(Boolean).join('\\n'));\n}\n\nexport class DefaultErrorHandler implements ErrorHandler {\n private readonly strategies: RecoveryStrategy[];\n\n constructor(strategies: RecoveryStrategy[] = DEFAULT_RECOVERY_STRATEGIES) {\n this.strategies = strategies;\n }\n\n classify(err: unknown): {\n kind:\n | 'rate_limit'\n | 'overloaded'\n | 'server'\n | 'client'\n | 'network'\n | 'abort'\n | 'context_overflow'\n | 'unknown';\n retryable: boolean;\n } {\n // AbortError can be thrown in both browser (DOMException) and Node (Error).\n // Guard with typeof check so Node builds don't reference the browser-only DOMException.\n if (\n typeof DOMException !== 'undefined' &&\n err instanceof DOMException &&\n err.name === 'AbortError'\n ) {\n return { kind: 'abort', retryable: false };\n }\n if (err instanceof Error && err.name === 'AbortError') {\n return { kind: 'abort', retryable: false };\n }\n if (err instanceof ProviderError) {\n if (err.status === 429) return { kind: 'rate_limit', retryable: true };\n if (err.status === 529) return { kind: 'overloaded', retryable: true };\n if (err.status >= 500) return { kind: 'server', retryable: true };\n if (err.status === 413 || isContextOverflowError(err)) {\n return { kind: 'context_overflow', retryable: false };\n }\n if (err.status >= 400) return { kind: 'client', retryable: false };\n }\n if (err instanceof Error && NETWORK_ERR_RE.test(err.message)) {\n return { kind: 'network', retryable: true };\n }\n return { kind: 'unknown', retryable: false };\n }\n\n async recover(err: unknown, ctx: Context): Promise<RecoveryDecision | null> {\n for (const strategy of this.strategies) {\n const result = await strategy.attempt(err, ctx);\n if (result !== null) return result;\n }\n return null;\n }\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { SkillEntry, SkillLoader, SkillManifest } from '../types/skill.js';\nimport type { WstackPaths } from '../utils/wstack-paths.js';\n\n/**\n * Strip YAML frontmatter from a SKILL.md file, returning only the body.\n */\nfunction stripFrontmatter(raw: string): string {\n if (!raw.startsWith('---')) return raw;\n const end = raw.indexOf('\\n---', 4);\n if (end === -1) return raw;\n let body = raw.slice(end + 4);\n if (body.startsWith('\\n')) body = body.slice(1);\n return body;\n}\n\n/**\n * Compact a full skill body for token-saving fallback.\n * Extracts the Overview and Rules sections, trims to ~400 chars max.\n */\nfunction compactSkillBody(body: string): string {\n const sections: string[] = [];\n const overviewMatch = body.match(/##\\s*Overview\\s*\\n([\\s\\S]*?)(?=\\n##|\\n$|$)/i);\n const overview = overviewMatch?.[1];\n if (overview?.trim()) {\n sections.push(overview.trim().slice(0, 200));\n }\n const rulesMatch = body.match(/##\\s*Rules\\s*\\n([\\s\\S]*?)(?=\\n##|\\n$|$)/i);\n const rules = rulesMatch?.[1];\n if (rules?.trim()) {\n const trimmed = rules.trim().slice(0, 350);\n const ruleLines = trimmed\n .split('\\n')\n .filter((l) => /^\\s*[-*]\\s/.test(l) || /^\\s*\\d+[.)]\\s/.test(l))\n .slice(0, 6)\n .join('\\n');\n if (ruleLines) sections.push(ruleLines);\n }\n if (sections.length === 0) {\n const first = body.trim().slice(0, 200);\n if (first) sections.push(first);\n }\n const result = sections.join('\\n\\n');\n return result.length > 450 ? result.slice(0, 447) + '…' : result;\n}\n\nexport interface SkillLoaderOptions {\n paths: WstackPaths;\n bundledDir?: string | undefined;\n}\n\n/**\n * Discovery order (later layers shadow earlier ones at boot, but we walk\n * highest priority first and skip names already seen):\n * 1. Project-committed: <project>/.wrongstack/skills/\n * 2. User-global: ~/.wrongstack/skills/\n * 3. Bundled with build: packages/core/skills/\n */\nexport class DefaultSkillLoader implements SkillLoader {\n private readonly dirs: { dir: string; source: SkillManifest['source'] }[];\n private cache?: SkillManifest[] | undefined;\n private entriesCache?: SkillEntry[] | undefined;\n private readonly bodyCache = new Map<string, string>();\n\n constructor(opts: SkillLoaderOptions) {\n this.dirs = [\n { dir: opts.paths.inProjectSkills, source: 'project' },\n { dir: opts.paths.globalSkills, source: 'user' },\n ];\n if (opts.bundledDir) {\n this.dirs.push({ dir: opts.bundledDir, source: 'bundled' });\n }\n }\n\n async list(): Promise<SkillManifest[]> {\n if (this.cache) return this.cache;\n const found: SkillManifest[] = [];\n const seen = new Set<string>();\n for (const { dir, source } of this.dirs) {\n try {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const e of entries) {\n if (!e.isDirectory()) continue;\n const skillFile = path.join(dir, e.name, 'SKILL.md');\n try {\n const raw = await fs.readFile(skillFile, 'utf8');\n const meta = parseFrontmatter(raw);\n if (!meta.name || !meta.description) continue;\n if (seen.has(meta.name)) continue;\n seen.add(meta.name);\n found.push({\n name: meta.name,\n description: meta.description,\n version: meta.version,\n path: skillFile,\n source,\n });\n } catch {\n // skip malformed skill\n }\n }\n } catch {\n // directory may not exist\n }\n }\n this.cache = found;\n return found;\n }\n\n async find(name: string): Promise<SkillManifest | undefined> {\n const all = await this.list();\n const lower = name.toLowerCase();\n return all.find((s) => s.name.toLowerCase() === lower);\n }\n\n async manifestText(): Promise<string> {\n const entries = await this.listEntries();\n if (entries.length === 0) return '';\n const lines = ['## Available skills'];\n for (const e of entries) {\n const scopeTag = e.scope.length > 0 ? ` — ${e.scope.slice(0, 3).join(', ')}` : '';\n lines.push(`- **${e.name}**${scopeTag}`);\n lines.push(` Use when: ${e.trigger}`);\n }\n return lines.join('\\n');\n }\n\n async listEntries(): Promise<SkillEntry[]> {\n if (this.entriesCache) return this.entriesCache;\n const skills = await this.list();\n const entries: SkillEntry[] = [];\n for (const s of skills) {\n // Parse trigger/scope from the description that list() already parsed —\n // no need to re-read the file; s.description === fm.description.\n const { trigger, scope } = parseDescriptionFromText(s.description ?? '');\n entries.push({ name: s.name, trigger, scope, source: s.source, path: s.path });\n }\n this.entriesCache = entries;\n return entries;\n }\n\n invalidateCache(): void {\n this.cache = undefined;\n this.entriesCache = undefined;\n this.bodyCache.clear();\n }\n\n async readBody(name: string): Promise<string> {\n const key = name.toLowerCase();\n const cached = this.bodyCache.get(key);\n if (cached !== undefined) return cached;\n const m = await this.find(name);\n if (!m) throw new Error(`Skill \"${name}\" not found`);\n const body = await fs.readFile(m.path, 'utf8');\n this.bodyCache.set(key, body);\n return body;\n }\n\n async readSaveBody(name: string): Promise<string> {\n const key = `save:${name.toLowerCase()}`;\n const cached = this.bodyCache.get(key);\n if (cached !== undefined) return cached;\n const m = await this.find(name);\n if (!m) throw new Error(`Skill \"${name}\" not found`);\n // Try SKILL.save.md in the same directory as SKILL.md\n const savePath = path.join(path.dirname(m.path), 'SKILL.save.md');\n let result: string;\n try {\n result = await fs.readFile(savePath, 'utf8');\n } catch {\n // No hand-crafted save variant — auto-compact the full body\n const full = await fs.readFile(m.path, 'utf8');\n const body = stripFrontmatter(full);\n const compact = compactSkillBody(body);\n if (compact) {\n result = `## Overview\\n\\n${compact}`;\n } else {\n // Fallback: return first 300 chars of full body\n result = body.trim().slice(0, 300);\n }\n }\n this.bodyCache.set(key, result);\n return result;\n }\n}\n\ninterface Frontmatter {\n name?: string | undefined;\n description?: string | undefined;\n version?: string | undefined;\n}\n\nfunction parseFrontmatter(raw: string): Frontmatter {\n if (!raw.startsWith('---')) return {};\n const end = raw.indexOf('\\n---', 4);\n if (end === -1) return {};\n const block = raw.slice(4, end);\n const out: Frontmatter = {};\n let key: keyof Frontmatter | null = null;\n let value: string[] = [];\n const flush = () => {\n if (key) {\n out[key] = value.join('\\n').trim();\n }\n key = null;\n value = [];\n };\n for (const line of block.split('\\n')) {\n const m = /^([a-zA-Z_]+):\\s*(\\|?)\\s*(.*)$/.exec(line);\n if (m) {\n flush();\n key = (m[1] ?? '') as keyof Frontmatter;\n const pipe = m[2];\n const rest = m[3] ?? '';\n if (pipe === '|') {\n value = [];\n } else if (rest) {\n value = [rest];\n } else {\n value = [];\n }\n } else if (key) {\n value.push(line.replace(/^\\s+/, ''));\n }\n }\n flush();\n return out;\n}\n\n/**\n * Parse skill description into:\n * - trigger: extracted \"Use when...\" sentence (first sentence of description)\n * - scope: comma-separated items from first line's parenthetical or file-ext list\n */\n/**\n * Extract trigger and scope from a skill's description text.\n * Used by listEntries() when the description has already been parsed from frontmatter.\n */\nfunction parseDescriptionFromText(desc: string): { trigger: string; scope: string[] } {\n // Extract first sentence as trigger\n const firstSentenceEnd = desc.indexOf('. ');\n const trigger =\n firstSentenceEnd !== -1\n ? desc.slice(0, firstSentenceEnd + 1).trim()\n : (desc.trim().split('\\n')[0] ?? '');\n\n // Extract scope from parenthetical: \"Covers X, Y, and Z\" or \"for A, B, C\"\n const scope: string[] = [];\n const coversMatch = /(?:covers|for|including)\\s+([^.]+)/i.exec(desc);\n if (coversMatch) {\n // NB: parenthesize the `?? ''` — without it, `??` binds looser than the\n // method chain, so `items` would be the raw match string and `...items`\n // would spread it into individual characters.\n const items = (coversMatch[1] ?? '')\n .replace(/[·•]/g, ',')\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean);\n scope.push(...items);\n }\n\n return { trigger, scope };\n}\n\n\n","/**\n * Model-runtime resolver + request-pipeline middleware.\n *\n * Maps the shared `Config.modelRuntime` settings into the per-request\n * `Request.reasoning` and `Request.cache` fields, gated by the active model's\n * `reasoningConfig` capabilities so unsupported values are omitted (and\n * surfaced as warnings) instead of triggering provider 400s.\n *\n * Wired once at boot (REPL/TUI/WebUI all go through the same `request`\n * pipeline) — see `installModelRuntimeMiddleware()`. UIs only need to mutate\n * `Config.modelRuntime` (and persist) for the change to take effect on the next\n * request.\n */\nimport type {\n ReasoningConfig,\n ReasoningRequest,\n Request,\n RequestCacheControl,\n} from '../types/provider.js';\nimport type { ModelRuntimeConfig } from '../types/config.js';\n\nexport interface ResolvedModelRuntime {\n reasoning: Request['reasoning'];\n cache: Request['cache'];\n /** Human-readable warnings for settings that were ignored for this model. */\n warnings: string[];\n}\n\n/**\n * Resolve user-facing runtime settings into request fields for a specific\n * model capability profile. Pure function — safe to unit-test without a\n * provider or event bus.\n *\n * @param settings `Config.modelRuntime` (may be undefined → no-op)\n * @param reasoning The model's `reasoningConfig`, or undefined when unknown.\n * When undefined the resolver is conservative: explicit\n * on/off is suppressed (provider default wins) and effort is\n * dropped, because we cannot tell whether the model will\n * accept the fields.\n */\nexport function resolveModelRuntime(\n settings: ModelRuntimeConfig | undefined,\n reasoning: ReasoningConfig | undefined,\n): ResolvedModelRuntime {\n const warnings: string[] = [];\n if (!settings) {\n return { reasoning: undefined, cache: undefined, warnings };\n }\n\n const reasoningField = resolveReasoningForRequest(settings, reasoning, warnings);\n const cacheField = resolveCacheForRequest(settings, warnings);\n\n return { reasoning: reasoningField, cache: cacheField, warnings };\n}\n\nexport function resolveReasoningForRequest(\n settings: ModelRuntimeConfig,\n rc: ReasoningConfig | undefined,\n warnings: string[],\n): Request['reasoning'] {\n const cfg = settings.reasoning;\n if (!cfg) return undefined;\n\n // Capability-unknown: be conservative. Sending explicit enabled/disabled to\n // a model that doesn't understand the field is a common source of 400s\n // (e.g. always-on Kimi code models reject `thinking: { type: \"disabled\" }`).\n const capKnown = rc !== undefined;\n const supportsReasoning = rc ? rc.default !== 'disabled' || rc.disableSupported || rc.effortSupported : false;\n\n const out: ReasoningRequest = {};\n\n if (cfg.mode === 'off') {\n if (capKnown && rc?.disableSupported) {\n out.enabled = false;\n } else if (capKnown && rc && rc.default === 'always_on') {\n warnings.push(\n 'reasoning \"off\" requested, but this model has thinking always on; the disable field was omitted to avoid a provider error.',\n );\n } else if (capKnown && rc && !rc.disableSupported) {\n warnings.push('reasoning \"off\" requested, but this model does not support disabling thinking; the setting was omitted.');\n } else {\n // Unknown capabilities — don't risk sending an unsupported field.\n warnings.push('reasoning \"off\" requested, but model capabilities are unknown; the setting was omitted.');\n }\n } else if (cfg.mode === 'on') {\n if (!capKnown) {\n warnings.push('reasoning \"on\" requested, but model capabilities are unknown; the setting was omitted.');\n } else if (!supportsReasoning && rc?.default === 'disabled') {\n warnings.push('reasoning \"on\" requested, but this model has reasoning disabled by default and does not advertise support; the setting was omitted.');\n } else {\n out.enabled = true;\n }\n }\n // mode 'auto' → never send explicit enabled/disabled; provider default wins.\n\n const effort = cfg.effort;\n if (effort !== undefined) {\n if (capKnown && rc?.effortSupported && rc.effortLevels.includes(effort)) {\n out.effort = effort;\n } else if (capKnown && rc?.effortSupported) {\n warnings.push(\n `reasoning effort \"${effort}\" not supported by this model (supported: ${rc.effortLevels.join(', ')}); the setting was omitted.`,\n );\n } else if (capKnown) {\n warnings.push(`reasoning effort \"${effort}\" requested, but this model does not support effort; the setting was omitted.`);\n } else {\n warnings.push(`reasoning effort \"${effort}\" requested, but model capabilities are unknown; the setting was omitted.`);\n }\n }\n\n if (cfg.preserve !== undefined) {\n if (capKnown && rc && rc.preserveThinking !== 'unsupported') {\n out.preserve = cfg.preserve;\n } else if (capKnown) {\n warnings.push('reasoning preserve requested, but this model does not support preserved thinking; the setting was omitted.');\n }\n // Unknown capabilities: preserve is a soft, widely-supported field, so we\n // drop it rather than guess — provider behaviour varies too much.\n }\n\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\nexport function resolveCacheForRequest(\n settings: ModelRuntimeConfig,\n _warnings: string[],\n): Request['cache'] {\n const ttl = settings.cache?.ttl;\n if (ttl === undefined) return undefined;\n const out: RequestCacheControl = { ttl };\n return out;\n}\n\nexport interface ModelRuntimeMiddlewareOptions {\n /** Provider id of the active model, for logging/diagnostics only. */\n providerId?: string | undefined;\n /** Model id of the active model, for logging/diagnostics only. */\n modelId?: string | undefined;\n /** Current runtime settings. Called per-request so live changes apply. */\n getSettings(): ModelRuntimeConfig | undefined;\n /** Current model capability profile. Called per-request. */\n getReasoningConfig(): ReasoningConfig | undefined;\n /** Optional sink for suppressed-setting warnings (e.g. emit to event bus). */\n onWarning?: ((message: string) => void) | undefined;\n}\n\n/**\n * Build a `request`-pipeline middleware that applies runtime settings. The\n * returned function mutates the outgoing request by overlaying resolved\n * `reasoning` / `cache` fields. Existing fields on the request are preserved\n * only when the resolver produces nothing for that field.\n */\nexport function applyModelRuntime(\n req: Request,\n opts: ModelRuntimeMiddlewareOptions,\n): Request {\n const settings = opts.getSettings();\n if (!settings) return req;\n const rc = opts.getReasoningConfig();\n const resolved = resolveModelRuntime(settings, rc);\n for (const w of resolved.warnings) opts.onWarning?.(w);\n\n const next: Request = { ...req };\n if (resolved.reasoning !== undefined) {\n // Explicit runtime settings override anything the agent layer set, because\n // the user explicitly asked for this mode/effort for this session.\n next.reasoning = resolved.reasoning;\n }\n if (resolved.cache !== undefined) {\n next.cache = resolved.cache;\n }\n return next;\n}\n"]}