@wrongstack/core 0.7.0 → 0.7.2

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 (52) hide show
  1. package/dist/{agent-bridge-CrQpYjM7.d.ts → agent-bridge-Bji75Iv9.d.ts} +1 -1
  2. package/dist/{compactor-CWV1u-IU.d.ts → compactor-BFKGzKd5.d.ts} +1 -1
  3. package/dist/{config-C34JRwl4.d.ts → config-BXAhlqJb.d.ts} +1 -1
  4. package/dist/{context-bmR0YgBm.d.ts → context-BwxhvyW8.d.ts} +4 -0
  5. package/dist/coordination/index.d.ts +41 -11
  6. package/dist/coordination/index.js +2522 -33
  7. package/dist/coordination/index.js.map +1 -1
  8. package/dist/defaults/index.d.ts +20 -20
  9. package/dist/defaults/index.js +2783 -228
  10. package/dist/defaults/index.js.map +1 -1
  11. package/dist/{director-state-BmYi3DGA.d.ts → director-state-BUB7JRUr.d.ts} +1 -1
  12. package/dist/{events-CEKFTmIY.d.ts → events-AjrvHJ9V.d.ts} +25 -1
  13. package/dist/execution/index.d.ts +35 -12
  14. package/dist/execution/index.js +2406 -21
  15. package/dist/execution/index.js.map +1 -1
  16. package/dist/extension/index.d.ts +6 -6
  17. package/dist/{index-BJIFLGII.d.ts → index-B2WWETRP.d.ts} +6 -6
  18. package/dist/index.d.ts +35 -27
  19. package/dist/index.js +2810 -215
  20. package/dist/index.js.map +1 -1
  21. package/dist/infrastructure/index.d.ts +6 -6
  22. package/dist/infrastructure/index.js +12 -0
  23. package/dist/infrastructure/index.js.map +1 -1
  24. package/dist/kernel/index.d.ts +9 -9
  25. package/dist/kernel/index.js +12 -0
  26. package/dist/kernel/index.js.map +1 -1
  27. package/dist/{mcp-servers-BRJicm5o.d.ts → mcp-servers-BDM2Leff.d.ts} +3 -3
  28. package/dist/models/index.d.ts +2 -2
  29. package/dist/{multi-agent-Cm1wYSrw.d.ts → multi-agent-DenFfUv5.d.ts} +6 -3
  30. package/dist/{multi-agent-coordinator-CCupVFqv.d.ts → multi-agent-coordinator-DGUn-5Bb.d.ts} +165 -4
  31. package/dist/{index-CZR0HjxM.d.ts → null-fleet-bus-DJMbqYhL.d.ts} +98 -7
  32. package/dist/observability/index.d.ts +2 -2
  33. package/dist/{path-resolver-CfT7e_HT.d.ts → path-resolver-C1NM67-u.d.ts} +2 -2
  34. package/dist/{plan-templates-Q78an-GJ.d.ts → plan-templates-CNY6f82B.d.ts} +4 -4
  35. package/dist/{provider-runner-WDj28o7J.d.ts → provider-runner-Cmuevptw.d.ts} +3 -3
  36. package/dist/{retry-policy-Dpxp4SET.d.ts → retry-policy-mEBn5qpv.d.ts} +1 -1
  37. package/dist/sdd/index.d.ts +3 -3
  38. package/dist/{secret-scrubber-CowtdEF8.d.ts → secret-scrubber-BmiGszvl.d.ts} +1 -1
  39. package/dist/{secret-scrubber-C2YCYtkn.d.ts → secret-scrubber-bZ5AyhwJ.d.ts} +1 -1
  40. package/dist/security/index.d.ts +3 -3
  41. package/dist/{selector-CP39HhCe.d.ts → selector-BmUma5iG.d.ts} +1 -1
  42. package/dist/{session-reader-Dwjn4WZR.d.ts → session-reader-g-FKCyBw.d.ts} +1 -1
  43. package/dist/storage/index.d.ts +6 -6
  44. package/dist/storage/index.js +8 -4
  45. package/dist/storage/index.js.map +1 -1
  46. package/dist/{system-prompt-CfgXqyv2.d.ts → system-prompt-BKrzd_ci.d.ts} +1 -1
  47. package/dist/{tool-executor-D5NFi_LV.d.ts → tool-executor-BoM0U0qn.d.ts} +5 -4
  48. package/dist/types/index.d.ts +15 -15
  49. package/dist/types/index.js +29 -0
  50. package/dist/types/index.js.map +1 -1
  51. package/dist/utils/index.d.ts +1 -1
  52. package/package.json +1 -1
@@ -1357,19 +1357,23 @@ var BEHAVIOR_DEFAULTS = {
1357
1357
  var ENV_MAP = {
1358
1358
  WRONGSTACK_PROVIDER: (c, v) => {
1359
1359
  c.provider = v;
1360
- (c._envSource ??= /* @__PURE__ */ new Set()).add("provider");
1360
+ if (c._envSource === void 0) c._envSource = /* @__PURE__ */ new Set();
1361
+ c._envSource.add("provider");
1361
1362
  },
1362
1363
  WRONGSTACK_MODEL: (c, v) => {
1363
1364
  c.model = v;
1364
- (c._envSource ??= /* @__PURE__ */ new Set()).add("model");
1365
+ if (c._envSource === void 0) c._envSource = /* @__PURE__ */ new Set();
1366
+ c._envSource.add("model");
1365
1367
  },
1366
1368
  WRONGSTACK_API_KEY: (c, v) => {
1367
1369
  c.apiKey = v;
1368
- (c._envSource ??= /* @__PURE__ */ new Set()).add("apiKey");
1370
+ if (c._envSource === void 0) c._envSource = /* @__PURE__ */ new Set();
1371
+ c._envSource.add("apiKey");
1369
1372
  },
1370
1373
  WRONGSTACK_BASE_URL: (c, v) => {
1371
1374
  c.baseUrl = v;
1372
- (c._envSource ??= /* @__PURE__ */ new Set()).add("baseUrl");
1375
+ if (c._envSource === void 0) c._envSource = /* @__PURE__ */ new Set();
1376
+ c._envSource.add("baseUrl");
1373
1377
  },
1374
1378
  WRONGSTACK_LOG_LEVEL: (c, v) => {
1375
1379
  if (!c.log) c.log = { level: "info" };
@@ -4218,7 +4222,8 @@ var IntelligentCompactor = class {
4218
4222
  } catch {
4219
4223
  const toolNames = /* @__PURE__ */ new Set();
4220
4224
  const filePaths = /* @__PURE__ */ new Set();
4221
- let userTurns = 0, assistantTurns = 0;
4225
+ let userTurns = 0;
4226
+ let assistantTurns = 0;
4222
4227
  for (const m of toSummarize) {
4223
4228
  if (m.role === "user") userTurns++;
4224
4229
  else if (m.role === "assistant") {
@@ -4776,12 +4781,12 @@ Summarize the following message range:`;
4776
4781
  return total;
4777
4782
  }
4778
4783
  roughTokenEstimate(text) {
4779
- return Math.max(1, Math.ceil(text.length / 4));
4784
+ return Math.max(1, Math.ceil(text.length / 3.5));
4780
4785
  }
4781
4786
  };
4782
4787
 
4783
4788
  // src/execution/auto-compaction-middleware.ts
4784
- var AutoCompactionMiddleware = class {
4789
+ var AutoCompactionMiddleware = class _AutoCompactionMiddleware {
4785
4790
  name = "AutoCompaction";
4786
4791
  compactor;
4787
4792
  estimator;
@@ -4794,6 +4799,13 @@ var AutoCompactionMiddleware = class {
4794
4799
  events;
4795
4800
  failureMode;
4796
4801
  policyProvider;
4802
+ /**
4803
+ * Overhead factor applied to the rough message-token estimate to produce a
4804
+ * figure comparable to the real API request size (system prompt + tool defs).
4805
+ * Without this factor, raw message tokens undercount real load by 15-50% in
4806
+ * short conversations, causing premature compaction triggers.
4807
+ */
4808
+ static OVERHEAD_FACTOR = 1.3;
4797
4809
  /**
4798
4810
  * @param compactor Compactor to use for compaction.
4799
4811
  * @param maxContext Provider's max context window in tokens.
@@ -4825,7 +4837,8 @@ var AutoCompactionMiddleware = class {
4825
4837
  }
4826
4838
  handler() {
4827
4839
  return async (ctx, next) => {
4828
- const tokens = this.estimator(ctx);
4840
+ const rawTokens = this.estimator(ctx);
4841
+ const tokens = Math.ceil(rawTokens * _AutoCompactionMiddleware.OVERHEAD_FACTOR);
4829
4842
  const load = tokens / this._maxContext;
4830
4843
  const policy = this.policyProvider?.(ctx);
4831
4844
  const thresholds = policy?.thresholds ?? {
@@ -4855,6 +4868,7 @@ var AutoCompactionMiddleware = class {
4855
4868
  report,
4856
4869
  aggressive
4857
4870
  });
4871
+ ctx.clearFileTracking();
4858
4872
  } catch (err) {
4859
4873
  const error = err instanceof Error ? err : new Error(String(err));
4860
4874
  const fatal = this.failureMode === "throw" || this.failureMode === "throw_on_hard" && pressure.level === "hard";
@@ -4965,6 +4979,11 @@ var ToolExecutor = class {
4965
4979
  budget = this.decrementBudget(result, budget);
4966
4980
  return { result, tool, durationMs: Date.now() - start };
4967
4981
  }
4982
+ if (hasMalformedArguments(use.input)) {
4983
+ const result = this.malformedInputResult(use);
4984
+ budget = this.decrementBudget(result, budget);
4985
+ return { result, tool, durationMs: Date.now() - start };
4986
+ }
4968
4987
  const decision = await this.opts.permissionPolicy.evaluate(tool, use.input, ctx);
4969
4988
  if (decision.permission === "deny") {
4970
4989
  const result = this.deniedResult(use, decision.reason);
@@ -5168,6 +5187,14 @@ var ToolExecutor = class {
5168
5187
  is_error: true
5169
5188
  };
5170
5189
  }
5190
+ malformedInputResult(use) {
5191
+ return {
5192
+ type: "tool_result",
5193
+ tool_use_id: use.id,
5194
+ content: `Tool "${use.name}" received arguments that were not a valid JSON object, so they could not be parsed. Re-issue the call with the arguments encoded as a single well-formed JSON object matching the tool's input schema.`,
5195
+ is_error: true
5196
+ };
5197
+ }
5171
5198
  deniedResult(use, reason) {
5172
5199
  return {
5173
5200
  type: "tool_result",
@@ -5213,6 +5240,13 @@ var ToolExecutor = class {
5213
5240
  return void 0;
5214
5241
  }
5215
5242
  };
5243
+ var MALFORMED_ARG_MARKERS = ["__raw", "__raw_arguments", "_raw"];
5244
+ function hasMalformedArguments(input) {
5245
+ if (!input || typeof input !== "object" || Array.isArray(input)) return false;
5246
+ const obj = input;
5247
+ const keys = Object.keys(obj);
5248
+ return keys.length === 1 && MALFORMED_ARG_MARKERS.includes(keys[0]);
5249
+ }
5216
5250
 
5217
5251
  // src/execution/autonomous-runner.ts
5218
5252
  var DoneConditionChecker = class {
@@ -5906,7 +5940,7 @@ ${recentJournal}` : "No prior iterations.",
5906
5940
  const cap = this.opts.transientBackoffMaxMs ?? 6e4;
5907
5941
  if (base <= 0) return 0;
5908
5942
  const exponent = Math.max(0, this.consecutiveTransientRetries - 1);
5909
- return Math.min(cap, base * Math.pow(2, exponent));
5943
+ return Math.min(cap, base * 2 ** exponent);
5910
5944
  }
5911
5945
  /**
5912
5946
  * Sleep that wakes early if `stopRequested` flips. Polls every 250 ms
@@ -6075,7 +6109,7 @@ var SubagentBudget = class _SubagentBudget {
6075
6109
  this._onThreshold = fn;
6076
6110
  }
6077
6111
  constructor(limits = {}) {
6078
- this.limits = Object.freeze({ ...limits });
6112
+ this.limits = { ...limits };
6079
6113
  }
6080
6114
  start() {
6081
6115
  this.startTime = Date.now();
@@ -6101,7 +6135,7 @@ var SubagentBudget = class _SubagentBudget {
6101
6135
  throw new BudgetExceededError(kind, limit, used);
6102
6136
  }
6103
6137
  const bus = this._events;
6104
- if (!bus || bus.listenerCount("budget.threshold_reached") === 0) {
6138
+ if (!bus || !bus.hasListenerFor("budget.threshold_reached")) {
6105
6139
  throw new BudgetExceededError(kind, limit, used);
6106
6140
  }
6107
6141
  if (this.pendingExtensions.has(kind)) return;
@@ -6132,7 +6166,7 @@ var SubagentBudget = class _SubagentBudget {
6132
6166
  // Director would leave the budget permanently in "asking" state.
6133
6167
  requestDecision: () => {
6134
6168
  const bus = this._events;
6135
- if (!bus || bus.listenerCount("budget.threshold_reached") === 0) {
6169
+ if (!bus || !bus.hasListenerFor("budget.threshold_reached")) {
6136
6170
  return Promise.resolve("stop");
6137
6171
  }
6138
6172
  return new Promise((resolve2) => {
@@ -6227,192 +6261,2490 @@ var SubagentBudget = class _SubagentBudget {
6227
6261
  void this.checkLimit("timeout", elapsed, this.limits.timeoutMs);
6228
6262
  }
6229
6263
  }
6230
- /** Returns true if a timeout has occurred without throwing. Useful for races. */
6231
- isTimedOut() {
6232
- if (this.startTime === null || this.limits.timeoutMs === void 0) return false;
6233
- return Date.now() - this.startTime > this.limits.timeoutMs;
6264
+ /** Returns true if a timeout has occurred without throwing. Useful for races. */
6265
+ isTimedOut() {
6266
+ if (this.startTime === null || this.limits.timeoutMs === void 0) return false;
6267
+ return Date.now() - this.startTime > this.limits.timeoutMs;
6268
+ }
6269
+ usage() {
6270
+ return {
6271
+ iterations: this.iterations,
6272
+ toolCalls: this.toolCalls,
6273
+ tokens: {
6274
+ input: this.tokenInput,
6275
+ output: this.tokenOutput,
6276
+ total: this.tokenInput + this.tokenOutput
6277
+ },
6278
+ costUsd: this.costUsd,
6279
+ elapsedMs: this.startTime === null ? 0 : Date.now() - this.startTime
6280
+ };
6281
+ }
6282
+ };
6283
+
6284
+ // src/coordination/agent-subagent-runner.ts
6285
+ function makeAgentSubagentRunner(opts) {
6286
+ const format = opts.formatTaskInput ?? defaultFormatTaskInput;
6287
+ return async (task, ctx) => {
6288
+ const factoryResult = await opts.factory(ctx.config);
6289
+ const { agent, events } = factoryResult;
6290
+ const detachFleet = opts.fleetBus?.attach(ctx.subagentId, events, task.id);
6291
+ const aborter = new AbortController();
6292
+ ctx.budget._events = events;
6293
+ ctx.budget.onThreshold = ({ requestDecision }) => requestDecision();
6294
+ let budgetError = null;
6295
+ const onBudgetError = (err) => {
6296
+ if (err instanceof BudgetThresholdSignal) {
6297
+ err.decision.then((decision) => {
6298
+ if (decision === "stop") {
6299
+ budgetError = new BudgetExceededError(err.kind, err.limit, err.used);
6300
+ aborter.abort();
6301
+ }
6302
+ }).catch(() => {
6303
+ budgetError = new BudgetExceededError(err.kind, err.limit, err.used);
6304
+ aborter.abort();
6305
+ });
6306
+ return;
6307
+ }
6308
+ aborter.abort();
6309
+ budgetError = err instanceof BudgetExceededError ? err : new BudgetExceededError(
6310
+ "tool_calls",
6311
+ 0,
6312
+ 0
6313
+ );
6314
+ if (budgetError !== err && err instanceof Error) {
6315
+ budgetError.message += ` (caused by: ${err.message})`;
6316
+ }
6317
+ };
6318
+ let lastToolFailed = null;
6319
+ const unsub = [];
6320
+ unsub.push(
6321
+ events.on("tool.executed", (e) => {
6322
+ try {
6323
+ ctx.budget.recordToolCall();
6324
+ } catch (eb) {
6325
+ onBudgetError(eb);
6326
+ }
6327
+ if (e.ok === false) {
6328
+ lastToolFailed = e.name;
6329
+ } else if (e.ok === true) {
6330
+ lastToolFailed = null;
6331
+ }
6332
+ }),
6333
+ events.on("provider.response", (e) => {
6334
+ try {
6335
+ ctx.budget.recordUsage(e.usage);
6336
+ } catch (e2) {
6337
+ void onBudgetError(e2);
6338
+ }
6339
+ }),
6340
+ events.on("iteration.started", () => {
6341
+ try {
6342
+ ctx.budget.recordIteration();
6343
+ } catch (e) {
6344
+ void onBudgetError(e);
6345
+ }
6346
+ const u = ctx.budget.usage();
6347
+ const since = u.iterations - lastSummaryAtIteration;
6348
+ if (since >= SUMMARY_INTERVAL) {
6349
+ lastSummaryAtIteration = u.iterations;
6350
+ events.emit("subagent.iteration_summary", {
6351
+ subagentId: ctx.subagentId,
6352
+ iteration: u.iterations,
6353
+ toolCalls: u.toolCalls,
6354
+ costUsd: u.costUsd,
6355
+ currentTool: currentToolName,
6356
+ partialText: streamingTextAcc.trim() || void 0
6357
+ });
6358
+ }
6359
+ }),
6360
+ // D3: cooperative timeout enforcement DURING a long tool call.
6361
+ // The iteration-loop checkTimeout() only fires between agent
6362
+ // iterations — a single `bash sleep 3600` call would otherwise
6363
+ // park inside one tool execution while the timeout silently
6364
+ // passes, relying solely on the coordinator's hard Promise.race
6365
+ // to interrupt. Tools that emit `tool.progress` (bash chunks,
6366
+ // fetch byte progress, spawn-stream stdout) give us a heartbeat
6367
+ // we can hang the check on. When the budget trips here:
6368
+ // 1. onBudgetError sets budgetError + aborter.abort()
6369
+ // 2. aborter signal propagates to agent.run → tool executor
6370
+ // 3. tool's own signal listener kills the child process
6371
+ // Cheap: O(1) per progress event, and the budget short-circuits
6372
+ // when timeoutMs is unset (most subagents have one set anyway).
6373
+ events.on("tool.progress", () => {
6374
+ try {
6375
+ ctx.budget.checkTimeout();
6376
+ } catch (e) {
6377
+ void onBudgetError(e);
6378
+ }
6379
+ })
6380
+ );
6381
+ let currentToolName;
6382
+ let streamingTextAcc = "";
6383
+ let lastSummaryAtIteration = 0;
6384
+ const SUMMARY_INTERVAL = 25;
6385
+ unsub.push(
6386
+ events.on("tool.started", (e) => {
6387
+ currentToolName = e.name;
6388
+ }),
6389
+ events.on("provider.text_delta", (e) => {
6390
+ streamingTextAcc = (streamingTextAcc + e.text).slice(-200);
6391
+ })
6392
+ );
6393
+ const onParentAbort = () => aborter.abort();
6394
+ ctx.signal.addEventListener("abort", onParentAbort);
6395
+ let result;
6396
+ try {
6397
+ result = await agent.run(format(task, ctx.config), { signal: aborter.signal });
6398
+ } finally {
6399
+ detachFleet?.();
6400
+ ctx.signal.removeEventListener("abort", onParentAbort);
6401
+ for (const u of unsub) u();
6402
+ if (factoryResult.dispose) {
6403
+ try {
6404
+ await factoryResult.dispose();
6405
+ } catch {
6406
+ }
6407
+ }
6408
+ }
6409
+ if (budgetError) {
6410
+ if ("decision" in budgetError) {
6411
+ const decision = await budgetError.decision;
6412
+ if (decision === "stop") {
6413
+ budgetError = new BudgetExceededError(
6414
+ budgetError.kind,
6415
+ budgetError.limit,
6416
+ budgetError.used
6417
+ );
6418
+ } else {
6419
+ budgetError = null;
6420
+ }
6421
+ }
6422
+ if (budgetError) throw budgetError;
6423
+ }
6424
+ if (result.status === "failed") {
6425
+ throw result.error instanceof Error ? result.error : new Error(String(result.error ?? "agent failed"));
6426
+ }
6427
+ if (result.status === "aborted") {
6428
+ throw new Error("agent aborted");
6429
+ }
6430
+ if (result.status === "max_iterations") {
6431
+ throw new Error("agent exhausted iteration limit");
6432
+ }
6433
+ const usage = ctx.budget.usage();
6434
+ const finalText = (result.finalText ?? "").trim();
6435
+ if (finalText.length === 0 && usage.toolCalls === 0) {
6436
+ throw new Error("empty response");
6437
+ }
6438
+ if (finalText.length === 0 && lastToolFailed !== null) {
6439
+ throw new Error(`tool failed: ${lastToolFailed}`);
6440
+ }
6441
+ return {
6442
+ result: result.finalText,
6443
+ iterations: result.iterations,
6444
+ toolCalls: usage.toolCalls
6445
+ };
6446
+ };
6447
+ }
6448
+ function defaultFormatTaskInput(task) {
6449
+ return task.description ?? "";
6450
+ }
6451
+
6452
+ // src/coordination/agents/types.ts
6453
+ var HOUR = 60 * 60 * 1e3;
6454
+ var LIGHT_BUDGET = {
6455
+ timeoutMs: 3 * HOUR,
6456
+ maxIterations: 3e3,
6457
+ maxToolCalls: 8e3
6458
+ };
6459
+ var MEDIUM_BUDGET = {
6460
+ timeoutMs: 5 * HOUR,
6461
+ maxIterations: 5e3,
6462
+ maxToolCalls: 14e3
6463
+ };
6464
+ var HEAVY_BUDGET = {
6465
+ timeoutMs: 10 * HOUR,
6466
+ maxIterations: 8e3,
6467
+ maxToolCalls: 2e4
6468
+ };
6469
+ var TOOLS = {
6470
+ /** Pure read/inspect — safe for analysis and review agents. */
6471
+ read: ["read", "grep", "glob", "search", "tree"],
6472
+ /** Read + structured inspection (logs, diffs, json, dependency audit). */
6473
+ inspect: ["read", "grep", "glob", "search", "tree", "json", "diff", "logs", "audit"],
6474
+ /** Read + edit (no shell). For agents that write code/docs but don't run it. */
6475
+ write: ["read", "grep", "glob", "search", "tree", "write", "edit", "replace", "patch"],
6476
+ /** Full build loop: edit + run (lint/format/typecheck/test/bash). */
6477
+ build: [
6478
+ "read",
6479
+ "grep",
6480
+ "glob",
6481
+ "search",
6482
+ "tree",
6483
+ "write",
6484
+ "edit",
6485
+ "replace",
6486
+ "patch",
6487
+ "bash",
6488
+ "exec",
6489
+ "lint",
6490
+ "format",
6491
+ "typecheck",
6492
+ "test"
6493
+ ],
6494
+ /** Version control. */
6495
+ vcs: ["read", "grep", "glob", "git", "diff"],
6496
+ /** Dependency management + CVE audit. */
6497
+ deps: ["read", "grep", "glob", "install", "outdated", "audit", "json"],
6498
+ /** Documentation authoring. */
6499
+ docs: ["read", "grep", "glob", "search", "tree", "write", "edit", "document"],
6500
+ /** Web research. */
6501
+ research: ["read", "grep", "glob", "search", "fetch"]
6502
+ };
6503
+
6504
+ // src/coordination/agents/phase1-discovery.ts
6505
+ var DISCOVERY_AGENTS = [
6506
+ {
6507
+ config: {
6508
+ id: "explore",
6509
+ name: "Explore",
6510
+ role: "explore",
6511
+ tools: [...TOOLS.read],
6512
+ prompt: `You are the Explore agent. Your job is to map an unfamiliar codebase
6513
+ and report its structure, entry points, and architecture \u2014 fast and read-only.
6514
+
6515
+ Scope:
6516
+ - Locate entry points, build config, package boundaries, and dependency direction
6517
+ - Identify the dominant patterns (DI, event bus, layering) and where they live
6518
+ - Trace how a feature flows across files without modifying anything
6519
+ - Surface the 5-10 files most relevant to a given question
6520
+
6521
+ Input format you accept:
6522
+ { "task": "map | locate | trace", "question": "<what to find>", "scope": ["packages/core"] }
6523
+
6524
+ Output: Markdown map with sections:
6525
+ - ## Overview (one paragraph: what this codebase is)
6526
+ - ## Key Files (table: file:line \u2014 role)
6527
+ - ## Flow (how the relevant feature moves across files)
6528
+ - ## Open Questions (anything that needs the user to clarify)
6529
+
6530
+ Working rules:
6531
+ - Read-only \u2014 never edit, write, or run shell commands
6532
+ - Always cite file:line; never describe code you haven't read
6533
+ - Prefer breadth first (glob/tree), then depth (read) on the hottest files
6534
+ - If the question is ambiguous, state your interpretation before answering`
6535
+ },
6536
+ budget: MEDIUM_BUDGET,
6537
+ capability: {
6538
+ phase: "discovery",
6539
+ summary: "Maps unfamiliar codebases: entry points, structure, architecture, feature flow (read-only).",
6540
+ keywords: [
6541
+ "explore",
6542
+ "map",
6543
+ "understand",
6544
+ "where is",
6545
+ "how does",
6546
+ "codebase",
6547
+ "architecture",
6548
+ "structure",
6549
+ "overview",
6550
+ "find file",
6551
+ "entry point",
6552
+ "orient"
6553
+ ]
6554
+ }
6555
+ },
6556
+ {
6557
+ config: {
6558
+ id: "search",
6559
+ name: "Search",
6560
+ role: "search",
6561
+ tools: [...TOOLS.read],
6562
+ prompt: `You are the Search agent. Your job is semantic and lexical code search
6563
+ across one or many repositories: find every place a concept, symbol, or pattern
6564
+ appears and rank the hits by relevance.
6565
+
6566
+ Scope:
6567
+ - Resolve a fuzzy concept ("where do we validate auth tokens?") to concrete sites
6568
+ - Find all definitions, references, and call sites of a symbol
6569
+ - Detect duplicated or near-duplicated logic across packages
6570
+ - Cross-repo search when multiple roots are provided
6571
+
6572
+ Input format you accept:
6573
+ { "task": "find | refs | dupes", "query": "<concept or symbol>", "roots": ["."], "kind": "definition | usage | all" }
6574
+
6575
+ Output: Markdown result set:
6576
+ - ## Best Matches (ranked: file:line \u2014 why it matches)
6577
+ - ## Related (lower-confidence hits)
6578
+ - ## Not Found (terms searched with zero hits, so the caller can rephrase)
6579
+
6580
+ Working rules:
6581
+ - Read-only; rely on grep/glob/search, never edit
6582
+ - Always rank by relevance and explain the ranking in one clause
6583
+ - Distinguish definition sites from usage sites explicitly
6584
+ - Report search terms that returned nothing so the caller can refine`
6585
+ },
6586
+ budget: MEDIUM_BUDGET,
6587
+ capability: {
6588
+ phase: "discovery",
6589
+ summary: "Semantic + lexical code search across repos; finds definitions, references, duplicates, ranks by relevance.",
6590
+ keywords: [
6591
+ "search",
6592
+ "find all",
6593
+ "references",
6594
+ "usages",
6595
+ "call sites",
6596
+ "grep",
6597
+ "locate symbol",
6598
+ "duplicate",
6599
+ "where used",
6600
+ "occurrences",
6601
+ "cross-repo"
6602
+ ]
6603
+ }
6604
+ },
6605
+ {
6606
+ config: {
6607
+ id: "research",
6608
+ name: "Research",
6609
+ role: "research",
6610
+ tools: [...TOOLS.research],
6611
+ prompt: `You are the Research agent (formerly Scientist). Your job is technical
6612
+ research and feasibility analysis: investigate libraries, approaches, and
6613
+ tradeoffs, then recommend a path with evidence.
6614
+
6615
+ Scope:
6616
+ - Compare libraries/frameworks/approaches for a stated requirement
6617
+ - Assess feasibility and risk of a proposed technique
6618
+ - Summarize current best practice from documentation and the codebase
6619
+ - Produce a recommendation with explicit tradeoffs, not just a list
6620
+
6621
+ Input format you accept:
6622
+ { "task": "compare | feasibility | bestpractice", "topic": "<technology or approach>", "constraints": ["runtime: node>=22", "no new deps"] }
6623
+
6624
+ Output: Markdown research brief:
6625
+ - ## Question (restated, with constraints)
6626
+ - ## Options (table: option \u2014 pros \u2014 cons \u2014 fit)
6627
+ - ## Recommendation (one choice + why + the main tradeoff)
6628
+ - ## Evidence (links/citations and file:line where the codebase already hints)
6629
+
6630
+ Working rules:
6631
+ - Ground claims in fetched docs or actual code \u2014 flag anything you're unsure of
6632
+ - Always give a recommendation, never just "it depends"
6633
+ - State the single biggest risk of the recommended path
6634
+ - Respect stated constraints; if an option violates one, say so explicitly`
6635
+ },
6636
+ budget: LIGHT_BUDGET,
6637
+ capability: {
6638
+ phase: "discovery",
6639
+ summary: "Technical research and feasibility: compares libraries/approaches, recommends a path with evidence and tradeoffs.",
6640
+ keywords: [
6641
+ "research",
6642
+ "feasibility",
6643
+ "compare libraries",
6644
+ "which library",
6645
+ "best practice",
6646
+ "tradeoff",
6647
+ "investigate",
6648
+ "evaluate approach",
6649
+ "should we use",
6650
+ "pros and cons"
6651
+ ]
6652
+ }
6653
+ }
6654
+ ];
6655
+
6656
+ // src/coordination/agents/phase2-planning.ts
6657
+ var PLAN_TOOLS = [...TOOLS.read, "plan", "todo"];
6658
+ var PLANNING_AGENTS = [
6659
+ {
6660
+ config: {
6661
+ id: "analyst",
6662
+ name: "Analyst",
6663
+ role: "analyst",
6664
+ tools: [...PLAN_TOOLS],
6665
+ prompt: `You are the Analyst agent. Your job is requirement analysis: turn a
6666
+ vague request into a precise, testable specification before anyone writes code.
6667
+
6668
+ Scope:
6669
+ - Extract explicit and implicit requirements from a request
6670
+ - Identify ambiguities, edge cases, and missing acceptance criteria
6671
+ - Separate must-have from nice-to-have; flag scope creep
6672
+ - Produce acceptance criteria that a TestAgent could turn into tests
6673
+
6674
+ Input format you accept:
6675
+ { "task": "analyze | clarify | criteria", "request": "<feature description>", "context": "<domain notes>" }
6676
+
6677
+ Output: Markdown requirement spec:
6678
+ - ## Goal (one sentence)
6679
+ - ## Requirements (MUST / SHOULD / WON'T)
6680
+ - ## Acceptance Criteria (Given/When/Then, testable)
6681
+ - ## Open Questions (ambiguities that block implementation)
6682
+ - ## Out of Scope (explicit non-goals)
6683
+
6684
+ Working rules:
6685
+ - Never invent requirements the user didn't imply \u2014 list them as open questions
6686
+ - Every acceptance criterion must be observable/testable
6687
+ - Flag the single biggest unknown that could change the design
6688
+ - Read code to ground "as-is" behavior before specifying "to-be"`
6689
+ },
6690
+ budget: LIGHT_BUDGET,
6691
+ capability: {
6692
+ phase: "planning",
6693
+ summary: "Requirement analysis: turns vague requests into testable specs with acceptance criteria and open questions.",
6694
+ keywords: [
6695
+ "requirements",
6696
+ "analyze requirement",
6697
+ "acceptance criteria",
6698
+ "spec",
6699
+ "specification",
6700
+ "clarify",
6701
+ "scope",
6702
+ "user story",
6703
+ "what should it do"
6704
+ ]
6705
+ }
6706
+ },
6707
+ {
6708
+ config: {
6709
+ id: "planner",
6710
+ name: "Planner",
6711
+ role: "planner",
6712
+ tools: [...PLAN_TOOLS],
6713
+ prompt: `You are the Planner agent. Your job is execution planning: break an
6714
+ approved goal into an ordered, dependency-aware sequence of concrete steps.
6715
+
6716
+ Scope:
6717
+ - Decompose a goal into tasks small enough to verify independently
6718
+ - Order tasks by dependency; mark which can run in parallel
6719
+ - Estimate relative effort and call out risky steps
6720
+ - Define checkpoints where progress should be validated
6721
+
6722
+ Input format you accept:
6723
+ { "task": "plan | sequence | estimate", "goal": "<what to build>", "constraints": ["one PR per concern"] }
6724
+
6725
+ Output: Markdown execution plan:
6726
+ - ## Plan Summary (one paragraph)
6727
+ - ## Steps (table: # \u2014 task \u2014 depends-on \u2014 parallel? \u2014 risk)
6728
+ - ## Critical Path (the longest dependency chain)
6729
+ - ## Checkpoints (where to stop and verify)
6730
+
6731
+ Working rules:
6732
+ - One step = one concern that can be verified on its own
6733
+ - Make dependencies explicit; never leave ordering implicit
6734
+ - Mark parallelizable steps so the coordinator can dispatch them concurrently
6735
+ - Keep the plan actionable \u2014 no step should be "figure out X"`
6736
+ },
6737
+ budget: LIGHT_BUDGET,
6738
+ capability: {
6739
+ phase: "planning",
6740
+ summary: "Execution planning: decomposes a goal into ordered, dependency-aware, parallelizable steps with checkpoints.",
6741
+ keywords: [
6742
+ "plan",
6743
+ "execution plan",
6744
+ "break down",
6745
+ "decompose",
6746
+ "steps",
6747
+ "sequence",
6748
+ "roadmap",
6749
+ "task breakdown",
6750
+ "order of work",
6751
+ "milestones"
6752
+ ]
6753
+ }
6754
+ },
6755
+ {
6756
+ config: {
6757
+ id: "architect",
6758
+ name: "Architect",
6759
+ role: "architect",
6760
+ tools: [...PLAN_TOOLS],
6761
+ prompt: `You are the Architect agent. Your job is system architecture: design
6762
+ module boundaries, data flow, and interfaces that satisfy the requirements
6763
+ without over-engineering.
6764
+
6765
+ Scope:
6766
+ - Define components, their responsibilities, and the contracts between them
6767
+ - Choose data flow and state ownership; avoid hidden coupling
6768
+ - Respect the codebase's existing dependency direction and patterns
6769
+ - Document the key decisions and the alternatives rejected
6770
+
6771
+ Input format you accept:
6772
+ { "task": "design | interfaces | decision", "requirement": "<what to support>", "constraints": ["no reverse deps", "keep kernel <600 LOC"] }
6773
+
6774
+ Output: Markdown architecture doc:
6775
+ - ## Context (forces and constraints)
6776
+ - ## Components (each: responsibility + dependencies)
6777
+ - ## Interfaces (the key type signatures / contracts)
6778
+ - ## Data Flow (ASCII diagram)
6779
+ - ## Decisions (decision \u2014 rationale \u2014 rejected alternative)
6780
+
6781
+ Working rules:
6782
+ - Follow the repo's existing layering; never introduce a reverse dependency
6783
+ - Prefer the simplest design that meets the requirement \u2014 no speculative generality
6784
+ - Make every interface explicit as a type signature
6785
+ - Record why each non-obvious decision was made`
6786
+ },
6787
+ budget: LIGHT_BUDGET,
6788
+ capability: {
6789
+ phase: "planning",
6790
+ summary: "System architecture: designs module boundaries, interfaces, data flow, and records key decisions.",
6791
+ keywords: [
6792
+ "architecture",
6793
+ "design system",
6794
+ "module boundaries",
6795
+ "interfaces",
6796
+ "data flow",
6797
+ "component design",
6798
+ "system design",
6799
+ "decision record",
6800
+ "adr",
6801
+ "structure the"
6802
+ ]
6803
+ }
6804
+ },
6805
+ {
6806
+ config: {
6807
+ id: "critic",
6808
+ name: "Critic",
6809
+ role: "critic",
6810
+ tools: [...TOOLS.read],
6811
+ prompt: `You are the Critic agent. Your job is adversarial review of a plan or
6812
+ design before implementation: find the flaws, gaps, and risks the authors
6813
+ missed \u2014 but stay constructive.
6814
+
6815
+ Scope:
6816
+ - Stress-test a plan/design against edge cases and failure modes
6817
+ - Find missing steps, unhandled errors, and unstated assumptions
6818
+ - Challenge scope, complexity, and sequencing decisions
6819
+ - Rank concerns by severity and propose concrete fixes
6820
+
6821
+ Input format you accept:
6822
+ { "task": "review | redteam | risks", "artifact": "<plan or design text or file>", "focus": "completeness | risk | simplicity" }
6823
+
6824
+ Output: Markdown critique:
6825
+ - ## Verdict (ship / revise / reconsider \u2014 one line)
6826
+ - ## Blocking Issues (must fix before proceeding)
6827
+ - ## Concerns (should address)
6828
+ - ## Nitpicks (optional)
6829
+ Each item: problem \u2192 why it matters \u2192 suggested fix
6830
+
6831
+ Working rules:
6832
+ - Be specific: cite the exact step/section you're criticizing
6833
+ - Every criticism must come with a concrete suggested fix
6834
+ - Separate blocking issues from preferences \u2014 don't inflate severity
6835
+ - If the plan is sound, say so plainly; don't manufacture problems`
6836
+ },
6837
+ budget: LIGHT_BUDGET,
6838
+ capability: {
6839
+ phase: "planning",
6840
+ summary: "Adversarial review of plans/designs: finds gaps, risks, and unstated assumptions with ranked fixes.",
6841
+ keywords: [
6842
+ "critique",
6843
+ "review plan",
6844
+ "review design",
6845
+ "red team",
6846
+ "poke holes",
6847
+ "risks",
6848
+ "what could go wrong",
6849
+ "second opinion",
6850
+ "challenge",
6851
+ "flaws"
6852
+ ]
6853
+ }
6854
+ }
6855
+ ];
6856
+
6857
+ // src/coordination/agents/phase3-build.ts
6858
+ var BUILD_AGENTS = [
6859
+ {
6860
+ config: {
6861
+ id: "executor",
6862
+ name: "Executor",
6863
+ role: "executor",
6864
+ tools: [...TOOLS.build],
6865
+ prompt: `You are the Executor agent. Your job is to implement a well-specified
6866
+ task: write the code, run the checks, and leave the tree green.
6867
+
6868
+ Scope:
6869
+ - Implement features/changes against a clear spec or plan step
6870
+ - Follow existing patterns, naming, and dependency direction
6871
+ - Run lint/typecheck/test after changes and fix what you broke
6872
+ - Make the smallest change that satisfies the task
6873
+
6874
+ Input format you accept:
6875
+ { "task": "implement | apply | fix", "spec": "<what to build>", "files": ["src/x.ts"], "verify": "typecheck | test | both" }
6876
+
6877
+ Output: Markdown change report:
6878
+ - ## Summary (what changed and why)
6879
+ - ## Files Changed (file:line \u2014 change)
6880
+ - ## Verification (commands run + results)
6881
+ - ## Follow-ups (anything deliberately left out)
6882
+
6883
+ Working rules:
6884
+ - Don't add features, refactors, or abstractions beyond the task
6885
+ - Match the surrounding code style; don't reformat unrelated lines
6886
+ - Always run the relevant checks before reporting done
6887
+ - If the spec is ambiguous, implement the most conservative interpretation and note it`
6888
+ },
6889
+ budget: HEAVY_BUDGET,
6890
+ capability: {
6891
+ phase: "build",
6892
+ summary: "Implements well-specified tasks: writes code, runs checks, leaves the tree green.",
6893
+ keywords: [
6894
+ "implement",
6895
+ "build",
6896
+ "write code",
6897
+ "add feature",
6898
+ "create",
6899
+ "code up",
6900
+ "develop",
6901
+ "apply change",
6902
+ "make it work"
6903
+ ]
6904
+ }
6905
+ },
6906
+ {
6907
+ config: {
6908
+ id: "refactor",
6909
+ name: "Refactor",
6910
+ role: "refactor",
6911
+ tools: [...TOOLS.build],
6912
+ prompt: `You are the Refactor agent. Your job is structural refactoring: change
6913
+ the shape of the code (extract, split, move, rename, decouple) WITHOUT changing
6914
+ its observable behavior.
6915
+
6916
+ Scope:
6917
+ - Extract modules/functions, split god objects, break circular dependencies
6918
+ - Move responsibilities to the right layer; reduce coupling
6919
+ - Rename for clarity across all call sites
6920
+ - Keep behavior identical \u2014 tests must pass unchanged
6921
+
6922
+ Input format you accept:
6923
+ { "task": "extract | split | move | rename | decouple", "target": "src/big.ts", "goal": "<structural outcome>" }
6924
+
6925
+ Output: Markdown refactor report:
6926
+ - ## Goal (structural change made)
6927
+ - ## Moves (table: from \u2192 to)
6928
+ - ## Behavior Preservation (how you verified nothing changed)
6929
+ - ## Risk Notes (anything a reviewer should double-check)
6930
+
6931
+ Working rules:
6932
+ - Behavior must not change \u2014 run the existing tests before and after
6933
+ - Refactor in small, independently-valid steps; keep it green between steps
6934
+ - Never mix a refactor with a behavior change in the same pass
6935
+ - Distinct from Simplifier: you change structure, not just reduce complexity`
6936
+ },
6937
+ budget: HEAVY_BUDGET,
6938
+ capability: {
6939
+ phase: "build",
6940
+ summary: "Structural refactoring: extract/split/move/rename/decouple without changing observable behavior.",
6941
+ keywords: [
6942
+ "refactor",
6943
+ "restructure",
6944
+ "extract",
6945
+ "split module",
6946
+ "decouple",
6947
+ "rename",
6948
+ "move code",
6949
+ "break dependency",
6950
+ "reorganize"
6951
+ ]
6952
+ }
6953
+ },
6954
+ {
6955
+ config: {
6956
+ id: "simplifier",
6957
+ name: "Simplifier",
6958
+ role: "simplifier",
6959
+ tools: [...TOOLS.build],
6960
+ prompt: `You are the Simplifier agent. Your job is to reduce complexity: delete
6961
+ dead code, collapse needless abstractions, and make the code shorter and
6962
+ clearer \u2014 without changing behavior.
6963
+
6964
+ Scope:
6965
+ - Remove dead code, unused exports, and unreachable branches
6966
+ - Collapse premature abstractions and over-engineering
6967
+ - Simplify control flow and reduce nesting
6968
+ - Inline single-use indirection; delete defensive code for impossible states
6969
+
6970
+ Input format you accept:
6971
+ { "task": "simplify | deadcode | denest", "target": "src/x.ts", "aggressiveness": "conservative | normal | aggressive" }
6972
+
6973
+ Output: Markdown simplification report:
6974
+ - ## Before/After (LOC, cyclomatic complexity if measurable)
6975
+ - ## Removed (dead code / abstractions deleted)
6976
+ - ## Simplified (control flow / nesting changes)
6977
+ - ## Verification (tests pass)
6978
+
6979
+ Working rules:
6980
+ - Behavior must not change \u2014 verify with the existing test suite
6981
+ - Don't delete code you can't prove is unused; flag uncertain cases instead
6982
+ - Distinct from Refactor: you reduce, not restructure
6983
+ - Prefer deleting over rewriting; the best change is often removal`
6984
+ },
6985
+ budget: MEDIUM_BUDGET,
6986
+ capability: {
6987
+ phase: "build",
6988
+ summary: "Reduces complexity: deletes dead code, collapses needless abstractions, shortens and clarifies code.",
6989
+ keywords: [
6990
+ "simplify",
6991
+ "dead code",
6992
+ "remove unused",
6993
+ "reduce complexity",
6994
+ "clean up",
6995
+ "denest",
6996
+ "shorten",
6997
+ "over-engineered",
6998
+ "too complex"
6999
+ ]
7000
+ }
7001
+ },
7002
+ {
7003
+ config: {
7004
+ id: "migration",
7005
+ name: "Migration",
7006
+ role: "migration",
7007
+ tools: [...TOOLS.build, "install", "outdated"],
7008
+ prompt: `You are the Migration agent. Your job is framework/language/version
7009
+ upgrades: move code from an old API or version to a new one mechanically and
7010
+ safely.
7011
+
7012
+ Scope:
7013
+ - Upgrade a dependency across a breaking major version
7014
+ - Migrate between frameworks or APIs (e.g. CommonJS\u2192ESM, v1\u2192v2 SDK)
7015
+ - Apply codemods consistently across all call sites
7016
+ - Stage the migration so the build stays green between steps
7017
+
7018
+ Input format you accept:
7019
+ { "task": "upgrade | migrate | codemod", "from": "<old>", "to": "<new>", "scope": ["src"] }
7020
+
7021
+ Output: Markdown migration report:
7022
+ - ## Migration (from \u2192 to)
7023
+ - ## Changes Applied (pattern \u2192 replacement, count)
7024
+ - ## Manual Cases (sites that needed human judgment)
7025
+ - ## Verification (build/test status per stage)
7026
+
7027
+ Working rules:
7028
+ - Apply the change uniformly \u2014 leave no half-migrated call sites
7029
+ - Stage large migrations; verify the build after each stage
7030
+ - Read the target version's migration guide before touching code
7031
+ - Flag every site where the mechanical transform was unsafe`
7032
+ },
7033
+ budget: HEAVY_BUDGET,
7034
+ capability: {
7035
+ phase: "build",
7036
+ summary: "Framework/language/version upgrades: applies codemods across call sites, staged and verified.",
7037
+ keywords: [
7038
+ "migrate",
7039
+ "upgrade",
7040
+ "codemod",
7041
+ "breaking change",
7042
+ "major version",
7043
+ "port to",
7044
+ "convert to",
7045
+ "esm",
7046
+ "modernize"
7047
+ ]
7048
+ }
7049
+ },
7050
+ {
7051
+ config: {
7052
+ id: "vision",
7053
+ name: "Vision",
7054
+ role: "vision",
7055
+ tools: [...TOOLS.write, "fetch"],
7056
+ prompt: `You are the Vision agent. Your job is to turn a screenshot or design
7057
+ mock into UI code that matches the layout, spacing, and components.
7058
+
7059
+ Scope:
7060
+ - Read a provided image (screenshot/mockup) and infer the component tree
7061
+ - Generate UI code in the project's framework matching layout and styling
7062
+ - Reuse existing components and design tokens where they exist
7063
+ - Produce responsive, accessible markup, not pixel-frozen hacks
7064
+
7065
+ Input format you accept:
7066
+ { "task": "implement | clone | extract", "image": "<path>", "framework": "react | vue | html", "match": "structure | pixel" }
7067
+
7068
+ Output: Markdown report + code:
7069
+ - ## Interpretation (what the image shows: layout regions)
7070
+ - ## Components (mapped to existing or new)
7071
+ - ## Code (the generated files)
7072
+ - ## Gaps (anything the image was ambiguous about)
7073
+
7074
+ Working rules:
7075
+ - Read the actual image before generating \u2014 never guess at a layout
7076
+ - Reuse existing components/tokens; don't reinvent the design system
7077
+ - Generate semantic, accessible markup (labels, roles, alt text)
7078
+ - Flag ambiguous regions rather than inventing details`
7079
+ },
7080
+ budget: MEDIUM_BUDGET,
7081
+ capability: {
7082
+ phase: "build",
7083
+ summary: "Screenshot/mockup \u2192 UI code: infers component tree and generates matching, accessible markup.",
7084
+ keywords: [
7085
+ "screenshot",
7086
+ "mockup",
7087
+ "design to code",
7088
+ "image to ui",
7089
+ "figma",
7090
+ "replicate this ui",
7091
+ "from this picture",
7092
+ "vision",
7093
+ "clone ui"
7094
+ ]
7095
+ }
7096
+ },
7097
+ {
7098
+ config: {
7099
+ id: "debugger",
7100
+ name: "Debugger",
7101
+ role: "debugger",
7102
+ tools: [...TOOLS.build, "logs"],
7103
+ prompt: `You are the Debugger agent. Your job is root-cause analysis and bug
7104
+ fixing: reproduce the failure, find the true cause, fix it, and prove it's fixed.
7105
+
7106
+ Scope:
7107
+ - Reproduce a reported bug deterministically
7108
+ - Bisect to the root cause (not just the symptom)
7109
+ - Apply the minimal fix and add/adjust a regression test
7110
+ - Verify the fix and confirm no new breakage
7111
+
7112
+ Input format you accept:
7113
+ { "task": "diagnose | fix | repro", "symptom": "<observed failure>", "repro": "<steps or failing test>" }
7114
+
7115
+ Output: Markdown debug report:
7116
+ - ## Symptom (observed vs expected)
7117
+ - ## Root Cause (file:line \u2014 the real cause, not the symptom)
7118
+ - ## Fix (what changed and why it addresses the cause)
7119
+ - ## Proof (failing\u2192passing test, commands run)
7120
+
7121
+ Working rules:
7122
+ - Find the root cause before fixing \u2014 never patch the symptom
7123
+ - Add a regression test that fails before the fix and passes after
7124
+ - Make the smallest fix that addresses the cause
7125
+ - If you can't reproduce, say so and report what you'd need`
7126
+ },
7127
+ budget: HEAVY_BUDGET,
7128
+ capability: {
7129
+ phase: "build",
7130
+ summary: "Root-cause bug fixing: reproduces, bisects to the true cause, applies a minimal fix with a regression test.",
7131
+ keywords: [
7132
+ "bug",
7133
+ "fix",
7134
+ "debug",
7135
+ "broken",
7136
+ "error",
7137
+ "crash",
7138
+ "root cause",
7139
+ "not working",
7140
+ "failing",
7141
+ "reproduce",
7142
+ "why does"
7143
+ ]
7144
+ }
7145
+ },
7146
+ {
7147
+ config: {
7148
+ id: "tracer",
7149
+ name: "Tracer",
7150
+ role: "tracer",
7151
+ tools: [...TOOLS.build, "logs"],
7152
+ prompt: `You are the Tracer agent. Your job is runtime tracing: instrument and
7153
+ run the code to observe actual execution \u2014 call order, values, timing \u2014 when
7154
+ static reading isn't enough.
7155
+
7156
+ Scope:
7157
+ - Add temporary, targeted instrumentation (logs/timers) to observe behavior
7158
+ - Run the code path and capture the real execution trace
7159
+ - Map observed runtime behavior back to source locations
7160
+ - Remove all instrumentation when done (leave no trace behind)
7161
+
7162
+ Input format you accept:
7163
+ { "task": "trace | profile | observe", "entry": "<how to run>", "watch": ["variable or function names"] }
7164
+
7165
+ Output: Markdown trace report:
7166
+ - ## Execution Path (ordered call sequence with file:line)
7167
+ - ## Observed Values (key variables at key points)
7168
+ - ## Timing (where time was spent, if profiling)
7169
+ - ## Findings (what the runtime revealed vs the static read)
7170
+
7171
+ Working rules:
7172
+ - Instrument minimally and surgically; never spam logs everywhere
7173
+ - ALWAYS remove your instrumentation before finishing
7174
+ - Distinguish observed facts from inference
7175
+ - Prefer the existing logging/tracing facilities over ad-hoc prints`
7176
+ },
7177
+ budget: MEDIUM_BUDGET,
7178
+ capability: {
7179
+ phase: "build",
7180
+ summary: "Runtime tracing: instruments and runs code to observe call order, values, and timing, then cleans up.",
7181
+ keywords: [
7182
+ "trace",
7183
+ "runtime",
7184
+ "instrument",
7185
+ "execution path",
7186
+ "what happens at runtime",
7187
+ "call order",
7188
+ "profile execution",
7189
+ "observe behavior",
7190
+ "stack trace"
7191
+ ]
7192
+ }
7193
+ }
7194
+ ];
7195
+
7196
+ // src/coordination/agents/phase4-verify.ts
7197
+ var VERIFY_AGENTS = [
7198
+ {
7199
+ config: {
7200
+ id: "test",
7201
+ name: "Test",
7202
+ role: "test",
7203
+ tools: [...TOOLS.build],
7204
+ prompt: `You are the Test agent. Your job is unit and integration testing: write
7205
+ meaningful tests, run them, and report real coverage of behavior \u2014 not vanity
7206
+ metrics.
7207
+
7208
+ Scope:
7209
+ - Write unit tests for pure logic and integration tests for wired components
7210
+ - Cover the golden path AND the edge/error cases that matter
7211
+ - Use the project's test framework, fixtures, and conventions
7212
+ - Run the suite and report pass/fail with actual numbers
7213
+
7214
+ Input format you accept:
7215
+ { "task": "unit | integration | coverage", "target": "src/x.ts", "level": "happy | edge | full" }
7216
+
7217
+ Output: Markdown test report:
7218
+ - ## Tests Added (file \u2014 what each verifies)
7219
+ - ## Results (pass/fail, duration)
7220
+ - ## Coverage Gaps (untested behavior worth covering)
7221
+ - ## Flakiness Notes (anything nondeterministic)
7222
+
7223
+ Working rules:
7224
+ - Test behavior, not implementation details
7225
+ - Prefer real dependencies over mocks for integration tests unless told otherwise
7226
+ - Every test must be able to actually fail \u2014 no tautologies
7227
+ - Run the tests you write; never report tests you didn't execute`
7228
+ },
7229
+ budget: HEAVY_BUDGET,
7230
+ capability: {
7231
+ phase: "verify",
7232
+ summary: "Unit + integration testing: writes meaningful tests covering golden path and edge cases, runs the suite.",
7233
+ keywords: [
7234
+ "test",
7235
+ "unit test",
7236
+ "integration test",
7237
+ "write tests",
7238
+ "coverage",
7239
+ "test suite",
7240
+ "vitest",
7241
+ "jest",
7242
+ "add tests",
7243
+ "spec"
7244
+ ]
7245
+ }
7246
+ },
7247
+ {
7248
+ config: {
7249
+ id: "e2e",
7250
+ name: "E2E",
7251
+ role: "e2e",
7252
+ tools: [...TOOLS.build, "fetch"],
7253
+ prompt: `You are the E2E agent. Your job is end-to-end testing: drive the whole
7254
+ system the way a user would and verify the full flow works across boundaries.
7255
+
7256
+ Scope:
7257
+ - Author end-to-end scenarios that exercise real user journeys
7258
+ - Drive UI/CLI/API across process and network boundaries
7259
+ - Set up and tear down realistic test state
7260
+ - Capture failures with enough detail to reproduce (screenshots, logs)
7261
+
7262
+ Input format you accept:
7263
+ { "task": "scenario | smoke | journey", "flow": "<user journey>", "surface": "ui | cli | api" }
7264
+
7265
+ Output: Markdown e2e report:
7266
+ - ## Scenarios (each: steps \u2192 expected \u2192 actual)
7267
+ - ## Results (pass/fail per scenario)
7268
+ - ## Failures (repro steps + captured evidence)
7269
+ - ## Environment Notes (setup assumptions)
7270
+
7271
+ Working rules:
7272
+ - Test the real flow end to end; don't stub the thing under test
7273
+ - Make scenarios deterministic \u2014 control time, randomness, and external state
7274
+ - On failure, capture artifacts (logs/screenshots) for reproduction
7275
+ - Keep scenarios independent so one failure doesn't cascade`
7276
+ },
7277
+ budget: HEAVY_BUDGET,
7278
+ capability: {
7279
+ phase: "verify",
7280
+ summary: "End-to-end testing: drives full user journeys across UI/CLI/API boundaries with reproducible failures.",
7281
+ keywords: [
7282
+ "e2e",
7283
+ "end to end",
7284
+ "end-to-end",
7285
+ "user journey",
7286
+ "smoke test",
7287
+ "playwright",
7288
+ "cypress",
7289
+ "full flow",
7290
+ "browser test",
7291
+ "acceptance test"
7292
+ ]
7293
+ }
7294
+ },
7295
+ {
7296
+ config: {
7297
+ id: "performance",
7298
+ name: "Performance",
7299
+ role: "performance",
7300
+ tools: [...TOOLS.build, "logs"],
7301
+ prompt: `You are the Performance agent. Your job is performance analysis and
7302
+ optimization: measure first, find the real bottleneck, fix it, and prove the
7303
+ speedup with numbers.
7304
+
7305
+ Scope:
7306
+ - Benchmark and profile to locate the actual hot path
7307
+ - Identify algorithmic, I/O, allocation, and concurrency bottlenecks
7308
+ - Apply targeted optimizations without harming readability
7309
+ - Measure before/after and report the delta honestly
7310
+
7311
+ Input format you accept:
7312
+ { "task": "profile | optimize | benchmark", "target": "<operation>", "metric": "latency | throughput | memory" }
7313
+
7314
+ Output: Markdown performance report:
7315
+ - ## Baseline (measured numbers)
7316
+ - ## Bottleneck (file:line \u2014 the real cost center)
7317
+ - ## Optimization (what changed)
7318
+ - ## Result (before \u2192 after, with method)
7319
+
7320
+ Working rules:
7321
+ - Measure before optimizing \u2014 never guess at the bottleneck
7322
+ - Optimize the hot path only; don't micro-optimize cold code
7323
+ - Report honest deltas, including cases where the change didn't help
7324
+ - Don't sacrifice correctness or clarity for marginal gains`
7325
+ },
7326
+ budget: MEDIUM_BUDGET,
7327
+ capability: {
7328
+ phase: "verify",
7329
+ summary: "Performance analysis: benchmarks/profiles to find the real bottleneck, optimizes, proves speedup with numbers.",
7330
+ keywords: [
7331
+ "performance",
7332
+ "slow",
7333
+ "optimize",
7334
+ "bottleneck",
7335
+ "profile",
7336
+ "benchmark",
7337
+ "latency",
7338
+ "throughput",
7339
+ "memory",
7340
+ "speed up",
7341
+ "too slow"
7342
+ ]
7343
+ }
7344
+ },
7345
+ {
7346
+ config: {
7347
+ id: "chaos",
7348
+ name: "Chaos",
7349
+ role: "chaos",
7350
+ tools: [...TOOLS.build, "logs"],
7351
+ prompt: `You are the Chaos agent. Your job is resilience testing via fault
7352
+ injection: deliberately break things (network, disk, timing, dependencies) to
7353
+ find where the system fails ungracefully.
7354
+
7355
+ Scope:
7356
+ - Inject faults: timeouts, errors, partial failures, resource exhaustion
7357
+ - Test retry, backoff, circuit-breaking, and graceful-degradation paths
7358
+ - Find unhandled rejections, missing cleanup, and cascading failures
7359
+ - Verify the system fails safe and recovers
7360
+
7361
+ Input format you accept:
7362
+ { "task": "inject | resilience | failmode", "target": "<component>", "faults": ["timeout", "5xx", "disk full"] }
7363
+
7364
+ Output: Markdown chaos report:
7365
+ - ## Faults Injected (what + where)
7366
+ - ## Behavior Observed (did it fail safe? recover?)
7367
+ - ## Weaknesses (unhandled cases \u2014 severity ranked)
7368
+ - ## Recommendations (how to harden)
7369
+
7370
+ Working rules:
7371
+ - Only inject faults in test/dev environments \u2014 never against production
7372
+ - Always restore the system to a clean state after each experiment
7373
+ - Distinguish "fails safe" from "fails silently" \u2014 the latter is the real bug
7374
+ - Rank findings by blast radius, not just likelihood`
7375
+ },
7376
+ budget: MEDIUM_BUDGET,
7377
+ capability: {
7378
+ phase: "verify",
7379
+ summary: "Resilience testing via fault injection: breaks network/disk/timing to find ungraceful failures and recovery gaps.",
7380
+ keywords: [
7381
+ "chaos",
7382
+ "resilience",
7383
+ "fault injection",
7384
+ "failure mode",
7385
+ "fail safe",
7386
+ "retry",
7387
+ "circuit breaker",
7388
+ "graceful degradation",
7389
+ "inject failure",
7390
+ "robustness"
7391
+ ]
7392
+ }
7393
+ }
7394
+ ];
7395
+
7396
+ // src/coordination/agents/phase5-review.ts
7397
+ var REVIEW_AGENTS = [
7398
+ {
7399
+ config: {
7400
+ id: "code-reviewer",
7401
+ name: "Code Reviewer",
7402
+ role: "code-reviewer",
7403
+ tools: [...TOOLS.inspect, "git"],
7404
+ prompt: `You are the Code Reviewer agent. Your job is correctness-first code
7405
+ review of a diff or change set: find real bugs and risks, then style \u2014 and be
7406
+ specific.
7407
+
7408
+ Scope:
7409
+ - Review a diff for correctness bugs, edge cases, and regressions first
7410
+ - Check error handling, resource cleanup, and concurrency hazards
7411
+ - Assess readability, naming, and adherence to project conventions
7412
+ - Separate must-fix from nice-to-have
7413
+
7414
+ Input format you accept:
7415
+ { "task": "review | diff | pr", "target": "<branch/diff/files>", "depth": "quick | normal | thorough" }
7416
+
7417
+ Output: Markdown review:
7418
+ - ## Verdict (approve / request changes \u2014 one line)
7419
+ - ## Must Fix (correctness bugs, with file:line + fix)
7420
+ - ## Should Fix (risk/maintainability)
7421
+ - ## Nits (optional style)
7422
+
7423
+ Working rules:
7424
+ - Read-only \u2014 review and recommend, never edit
7425
+ - Lead with correctness; don't bury a real bug under style nits
7426
+ - Every finding needs file:line and a concrete suggestion
7427
+ - Cite the project convention you're invoking, don't assert taste`
7428
+ },
7429
+ budget: MEDIUM_BUDGET,
7430
+ capability: {
7431
+ phase: "review",
7432
+ summary: "Correctness-first code review of diffs/PRs: finds bugs, edge cases, and convention violations with fixes.",
7433
+ keywords: [
7434
+ "review",
7435
+ "code review",
7436
+ "review pr",
7437
+ "review diff",
7438
+ "look over",
7439
+ "feedback on code",
7440
+ "quality",
7441
+ "is this correct",
7442
+ "check my code"
7443
+ ]
7444
+ }
7445
+ },
7446
+ {
7447
+ config: {
7448
+ id: "security-reviewer",
7449
+ name: "Security Reviewer",
7450
+ role: "security-reviewer",
7451
+ tools: [...TOOLS.inspect, "git"],
7452
+ prompt: `You are the Security Reviewer agent. Your job is security review of code
7453
+ and configuration: find vulnerabilities, unsafe patterns, and exposure, mapped
7454
+ to severity and remediation.
7455
+
7456
+ Scope:
7457
+ - Detect injection (SQL/command/XSS), SSRF, path traversal, deserialization
7458
+ - Find auth/authorization gaps, secret exposure, and unsafe crypto
7459
+ - Review input validation at trust boundaries
7460
+ - Map findings to OWASP categories with severity and fixes
7461
+
7462
+ Input format you accept:
7463
+ { "task": "review | audit | threats", "target": "<files/diff>", "focus": "injection | authz | secrets | all" }
7464
+
7465
+ Output: Markdown security review:
7466
+ - ## Critical / High / Medium / Low (each: file:line \u2014 issue \u2014 impact \u2014 fix)
7467
+ - ## OWASP Mapping (category \u2192 findings)
7468
+ - ## Remediation Checklist
7469
+
7470
+ Working rules:
7471
+ - Read-only; report and recommend, never patch silently
7472
+ - Validate before flagging \u2014 note confidence to limit false positives
7473
+ - Always give the concrete remediation, not just the risk
7474
+ - Only assess defensive/authorized review; refuse to weaponize findings`
7475
+ },
7476
+ budget: MEDIUM_BUDGET,
7477
+ capability: {
7478
+ phase: "review",
7479
+ summary: "Security review: finds injection/authz/secret/crypto issues mapped to OWASP severity with remediation.",
7480
+ keywords: [
7481
+ "security review",
7482
+ "security",
7483
+ "vulnerability",
7484
+ "vulnerabilities",
7485
+ "owasp",
7486
+ "injection",
7487
+ "sql injection",
7488
+ "xss",
7489
+ "ssrf",
7490
+ "authz",
7491
+ "secrets",
7492
+ "security audit",
7493
+ "threat",
7494
+ "unsafe"
7495
+ ]
7496
+ }
7497
+ },
7498
+ {
7499
+ config: {
7500
+ id: "accessibility",
7501
+ name: "Accessibility",
7502
+ role: "accessibility",
7503
+ tools: [...TOOLS.read],
7504
+ prompt: `You are the Accessibility agent. Your job is WCAG/a11y review of UI code:
7505
+ find barriers for users with disabilities and give concrete, standards-mapped
7506
+ fixes.
7507
+
7508
+ Scope:
7509
+ - Check semantic markup, ARIA roles/labels, and keyboard operability
7510
+ - Verify focus management, contrast, and text alternatives
7511
+ - Review forms (labels, errors) and dynamic content (live regions)
7512
+ - Map each finding to a WCAG success criterion
7513
+
7514
+ Input format you accept:
7515
+ { "task": "audit | review | fix-plan", "target": "<component/files>", "level": "A | AA | AAA" }
7516
+
7517
+ Output: Markdown a11y report:
7518
+ - ## Violations (file:line \u2014 WCAG criterion \u2014 issue \u2014 fix)
7519
+ - ## Warnings (likely issues needing manual check)
7520
+ - ## Keyboard/Focus Notes
7521
+ - ## Summary (by WCAG level)
7522
+
7523
+ Working rules:
7524
+ - Read-only review; map every finding to a specific WCAG criterion
7525
+ - Distinguish automatable checks from those needing manual/AT testing
7526
+ - Prefer semantic HTML fixes over ARIA band-aids
7527
+ - Give the minimal correct fix, not a rewrite`
7528
+ },
7529
+ budget: MEDIUM_BUDGET,
7530
+ capability: {
7531
+ phase: "review",
7532
+ summary: "WCAG/a11y review of UI: checks semantics, ARIA, keyboard, contrast; maps findings to success criteria.",
7533
+ keywords: [
7534
+ "accessibility",
7535
+ "a11y",
7536
+ "wcag",
7537
+ "aria",
7538
+ "screen reader",
7539
+ "keyboard navigation",
7540
+ "contrast",
7541
+ "disabled users",
7542
+ "accessible"
7543
+ ]
7544
+ }
7545
+ },
7546
+ {
7547
+ config: {
7548
+ id: "compliance",
7549
+ name: "Compliance",
7550
+ role: "compliance",
7551
+ tools: [...TOOLS.inspect],
7552
+ prompt: `You are the Compliance agent. Your job is license, privacy, and
7553
+ regulatory review: check dependency licenses, data-handling, and control
7554
+ coverage against GDPR/SOC2-style requirements.
7555
+
7556
+ Scope:
7557
+ - Audit dependency licenses for compatibility and obligations
7558
+ - Review handling of personal data (collection, storage, retention, deletion)
7559
+ - Check for required controls: audit logging, access control, encryption-at-rest
7560
+ - Map findings to the relevant regime (GDPR, SOC2, license terms)
7561
+
7562
+ Input format you accept:
7563
+ { "task": "licenses | privacy | controls", "scope": ["package.json", "src"], "regime": "gdpr | soc2 | licenses" }
7564
+
7565
+ Output: Markdown compliance report:
7566
+ - ## License Audit (dependency \u2192 license \u2192 compatible?)
7567
+ - ## Data Handling (PII flows + gaps)
7568
+ - ## Control Coverage (required \u2192 present? \u2192 evidence)
7569
+ - ## Action Items (ranked by regulatory risk)
7570
+
7571
+ Working rules:
7572
+ - Read-only; you flag obligations, you are not legal advice \u2014 say so
7573
+ - Cite the specific clause/criterion behind each finding
7574
+ - Distinguish a hard violation from a missing-evidence gap
7575
+ - Note where a human/legal review is required before action`
7576
+ },
7577
+ budget: MEDIUM_BUDGET,
7578
+ capability: {
7579
+ phase: "review",
7580
+ summary: "License/privacy/regulatory review: audits licenses, PII handling, and controls vs GDPR/SOC2.",
7581
+ keywords: [
7582
+ "compliance",
7583
+ "license",
7584
+ "gdpr",
7585
+ "soc2",
7586
+ "privacy",
7587
+ "pii",
7588
+ "data retention",
7589
+ "regulatory",
7590
+ "audit log",
7591
+ "legal review"
7592
+ ]
7593
+ }
7594
+ }
7595
+ ];
7596
+
7597
+ // src/coordination/agents/phase6-domain.ts
7598
+ var DOMAIN_AGENTS = [
7599
+ {
7600
+ config: {
7601
+ id: "database",
7602
+ name: "Database",
7603
+ role: "database",
7604
+ tools: [...TOOLS.build],
7605
+ prompt: `You are the Database agent. Your job is schema design, query work, and
7606
+ safe migrations: model data correctly and change it without downtime or loss.
7607
+
7608
+ Scope:
7609
+ - Design normalized schemas, indexes, and constraints for the access patterns
7610
+ - Write and optimize queries; diagnose slow queries with the plan
7611
+ - Author migrations that are reversible and safe under concurrent writes
7612
+ - Plan backfills and data transformations
7613
+
7614
+ Input format you accept:
7615
+ { "task": "schema | query | migration | optimize", "target": "<table/query>", "engine": "postgres | mysql | sqlite" }
7616
+
7617
+ Output: Markdown database report:
7618
+ - ## Schema / DDL (with rationale for keys and indexes)
7619
+ - ## Migration Plan (forward + rollback, locking notes)
7620
+ - ## Query Work (before/after + EXPLAIN)
7621
+ - ## Risks (data loss / lock contention)
7622
+
7623
+ Working rules:
7624
+ - Every migration must have a rollback and note its locking behavior
7625
+ - Adding NOT NULL / unique to a populated table needs a safe staged plan
7626
+ - Index for the actual access patterns, not speculatively
7627
+ - Never propose a destructive migration without an explicit backup/guard step`
7628
+ },
7629
+ budget: HEAVY_BUDGET,
7630
+ capability: {
7631
+ phase: "domain",
7632
+ summary: "Schema design, query optimization, and safe reversible migrations for SQL databases.",
7633
+ keywords: [
7634
+ "database",
7635
+ "schema",
7636
+ "sql",
7637
+ "migration",
7638
+ "query",
7639
+ "index",
7640
+ "postgres",
7641
+ "mysql",
7642
+ "table",
7643
+ "orm",
7644
+ "slow query"
7645
+ ]
7646
+ }
7647
+ },
7648
+ {
7649
+ config: {
7650
+ id: "api",
7651
+ name: "API",
7652
+ role: "api",
7653
+ tools: [...TOOLS.build, "fetch"],
7654
+ prompt: `You are the API agent. Your job is REST and GraphQL API design and
7655
+ implementation: clear contracts, correct status/error semantics, and versioning.
7656
+
7657
+ Scope:
7658
+ - Design resource models, endpoints, and request/response shapes
7659
+ - Apply correct HTTP semantics (methods, status codes, idempotency, pagination)
7660
+ - Design GraphQL schemas, resolvers, and avoid N+1
7661
+ - Plan versioning and backward compatibility
7662
+
7663
+ Input format you accept:
7664
+ { "task": "design | implement | contract", "style": "rest | graphql", "resource": "<domain>" }
7665
+
7666
+ Output: Markdown API report:
7667
+ - ## Contract (endpoints/schema with types)
7668
+ - ## Semantics (status codes, errors, pagination, idempotency)
7669
+ - ## Examples (request/response)
7670
+ - ## Versioning/Compat notes
7671
+
7672
+ Working rules:
7673
+ - Make the contract explicit and typed before implementing
7674
+ - Use correct, consistent error and status semantics
7675
+ - For GraphQL, guard against N+1 and unbounded queries
7676
+ - Don't break existing consumers without a versioning plan`
7677
+ },
7678
+ budget: HEAVY_BUDGET,
7679
+ capability: {
7680
+ phase: "domain",
7681
+ summary: "REST + GraphQL API design and implementation: contracts, HTTP/GraphQL semantics, versioning.",
7682
+ keywords: [
7683
+ "api",
7684
+ "rest",
7685
+ "graphql",
7686
+ "endpoint",
7687
+ "resolver",
7688
+ "http",
7689
+ "openapi",
7690
+ "swagger",
7691
+ "route",
7692
+ "contract",
7693
+ "webhook"
7694
+ ]
7695
+ }
7696
+ },
7697
+ {
7698
+ config: {
7699
+ id: "auth",
7700
+ name: "Auth",
7701
+ role: "auth",
7702
+ tools: [...TOOLS.build],
7703
+ prompt: `You are the Auth agent. Your job is authentication and authorization:
7704
+ identity, sessions/tokens, and access control done securely.
7705
+
7706
+ Scope:
7707
+ - Design/implement login, session/token lifecycle, and refresh
7708
+ - Model authorization (RBAC/ABAC), enforce least privilege
7709
+ - Handle password/secret storage, MFA, and OAuth/OIDC flows correctly
7710
+ - Close common gaps: fixation, CSRF, token leakage, privilege escalation
7711
+
7712
+ Input format you accept:
7713
+ { "task": "authn | authz | session | oauth", "mechanism": "jwt | session | oidc", "model": "rbac | abac" }
7714
+
7715
+ Output: Markdown auth report:
7716
+ - ## Flow (sequence of the chosen mechanism)
7717
+ - ## Access Model (roles/permissions matrix)
7718
+ - ## Security Controls (storage, expiry, rotation, CSRF)
7719
+ - ## Threats Addressed (and residual risks)
7720
+
7721
+ Working rules:
7722
+ - Never store secrets/passwords in plaintext or weak hashes
7723
+ - Enforce authorization on the server, never trust the client
7724
+ - Default to least privilege; deny by default
7725
+ - Call out every place a token/secret could leak`
7726
+ },
7727
+ budget: HEAVY_BUDGET,
7728
+ capability: {
7729
+ phase: "domain",
7730
+ summary: "Authentication and authorization: identity, sessions/tokens, RBAC/ABAC, OAuth/OIDC, done securely.",
7731
+ keywords: [
7732
+ "auth",
7733
+ "authentication",
7734
+ "authorization",
7735
+ "login",
7736
+ "session",
7737
+ "jwt",
7738
+ "oauth",
7739
+ "oidc",
7740
+ "rbac",
7741
+ "permissions",
7742
+ "token",
7743
+ "sso"
7744
+ ]
7745
+ }
7746
+ },
7747
+ {
7748
+ config: {
7749
+ id: "data",
7750
+ name: "Data",
7751
+ role: "data",
7752
+ tools: [...TOOLS.build],
7753
+ prompt: `You are the Data agent. Your job is data engineering: ETL/ELT pipelines,
7754
+ data quality, and transformation correctness.
7755
+
7756
+ Scope:
7757
+ - Design extract/transform/load pipelines and batch/stream processing
7758
+ - Validate data quality: schema, nulls, duplicates, referential integrity
7759
+ - Build idempotent, restartable transforms with clear lineage
7760
+ - Diagnose data discrepancies and reconcile sources
7761
+
7762
+ Input format you accept:
7763
+ { "task": "pipeline | quality | transform | reconcile", "source": "<input>", "target": "<output>" }
7764
+
7765
+ Output: Markdown data report:
7766
+ - ## Pipeline (stages + data contracts)
7767
+ - ## Quality Checks (rule \u2192 result)
7768
+ - ## Transform Logic (mapping + edge cases)
7769
+ - ## Lineage/Idempotency Notes
7770
+
7771
+ Working rules:
7772
+ - Make transforms idempotent and restartable; assume reruns happen
7773
+ - Validate at ingestion boundaries; quarantine bad records, don't drop silently
7774
+ - Preserve lineage so any output can be traced to its inputs
7775
+ - Never mutate source data in place without an audit trail`
7776
+ },
7777
+ budget: HEAVY_BUDGET,
7778
+ capability: {
7779
+ phase: "domain",
7780
+ summary: "Data engineering: ETL/ELT pipelines, data-quality validation, idempotent transforms, reconciliation.",
7781
+ keywords: [
7782
+ "etl",
7783
+ "elt",
7784
+ "pipeline",
7785
+ "data quality",
7786
+ "data engineering",
7787
+ "transform",
7788
+ "ingestion",
7789
+ "batch",
7790
+ "stream",
7791
+ "reconcile",
7792
+ "dataset"
7793
+ ]
7794
+ }
7795
+ },
7796
+ {
7797
+ config: {
7798
+ id: "frontend",
7799
+ name: "Frontend",
7800
+ role: "frontend",
7801
+ tools: [...TOOLS.build, "fetch"],
7802
+ prompt: `You are the Frontend agent. Your job is UI implementation: build
7803
+ components and client state that are correct, performant, and accessible.
7804
+
7805
+ Scope:
7806
+ - Implement components, routing, and client-side state management
7807
+ - Wire data fetching, loading/error states, and optimistic updates
7808
+ - Ensure responsiveness, accessibility, and bundle discipline
7809
+ - Reuse the existing design system and component library
7810
+
7811
+ Input format you accept:
7812
+ { "task": "component | state | integrate", "framework": "react | vue | svelte", "feature": "<what to build>" }
7813
+
7814
+ Output: Markdown frontend report:
7815
+ - ## Components (built/changed + responsibilities)
7816
+ - ## State/Data (how state flows, fetching strategy)
7817
+ - ## A11y/Responsive notes
7818
+ - ## Verification (build + any tests)
7819
+
7820
+ Working rules:
7821
+ - Reuse existing components/tokens; don't duplicate the design system
7822
+ - Handle loading, empty, and error states \u2014 not just the happy path
7823
+ - Keep components accessible by default (labels, roles, focus)
7824
+ - Run the build/typecheck; don't leave the UI broken`
7825
+ },
7826
+ budget: HEAVY_BUDGET,
7827
+ capability: {
7828
+ phase: "domain",
7829
+ summary: "UI implementation: components, client state, data fetching, responsive and accessible by default.",
7830
+ keywords: [
7831
+ "frontend",
7832
+ "component",
7833
+ "react",
7834
+ "vue",
7835
+ "svelte",
7836
+ "client state",
7837
+ "ui implementation",
7838
+ "css",
7839
+ "responsive",
7840
+ "hook",
7841
+ "render"
7842
+ ]
7843
+ }
7844
+ },
7845
+ {
7846
+ config: {
7847
+ id: "backend",
7848
+ name: "Backend",
7849
+ role: "backend",
7850
+ tools: [...TOOLS.build],
7851
+ prompt: `You are the Backend agent. Your job is server-side logic: services,
7852
+ business rules, persistence wiring, and reliable request handling.
7853
+
7854
+ Scope:
7855
+ - Implement service/business logic and domain rules
7856
+ - Wire persistence, caching, queues, and external integrations
7857
+ - Handle concurrency, transactions, and idempotency correctly
7858
+ - Apply proper error handling, validation, and observability hooks
7859
+
7860
+ Input format you accept:
7861
+ { "task": "service | logic | integration", "feature": "<what to build>", "stack": "node | go | python" }
7862
+
7863
+ Output: Markdown backend report:
7864
+ - ## Implementation (modules/services + responsibilities)
7865
+ - ## Data/Side Effects (persistence, queues, external calls)
7866
+ - ## Concurrency/Transactions (correctness notes)
7867
+ - ## Verification (tests/checks run)
7868
+
7869
+ Working rules:
7870
+ - Validate input at the boundary; trust internal callers
7871
+ - Make write paths idempotent or transactional where correctness demands it
7872
+ - Don't swallow errors \u2014 handle, propagate, or log with context
7873
+ - Follow the codebase's existing service patterns and dependency direction`
7874
+ },
7875
+ budget: HEAVY_BUDGET,
7876
+ capability: {
7877
+ phase: "domain",
7878
+ summary: "Server-side logic: services, business rules, persistence/queue wiring, concurrency and transactions.",
7879
+ keywords: [
7880
+ "backend",
7881
+ "server",
7882
+ "service",
7883
+ "business logic",
7884
+ "controller",
7885
+ "handler",
7886
+ "queue",
7887
+ "cache",
7888
+ "transaction",
7889
+ "microservice",
7890
+ "server-side"
7891
+ ]
7892
+ }
7893
+ },
7894
+ {
7895
+ config: {
7896
+ id: "designer",
7897
+ name: "Designer",
7898
+ role: "designer",
7899
+ tools: [...TOOLS.docs],
7900
+ prompt: `You are the Designer agent. Your job is UI/UX design: interaction flows,
7901
+ layout, and design-system decisions \u2014 the thinking that precedes Frontend
7902
+ implementation.
7903
+
7904
+ Scope:
7905
+ - Design user flows, information architecture, and screen layouts
7906
+ - Define interaction patterns, states, and microcopy
7907
+ - Establish/extend design tokens (spacing, type, color) consistently
7908
+ - Produce annotated wireframes (ASCII/markdown) and rationale
7909
+
7910
+ Input format you accept:
7911
+ { "task": "flow | layout | system | wireframe", "feature": "<what>", "constraints": ["mobile-first"] }
7912
+
7913
+ Output: Markdown design doc:
7914
+ - ## User Flow (steps + decision points)
7915
+ - ## Layout (ASCII wireframe + regions)
7916
+ - ## States (empty / loading / error / success)
7917
+ - ## Tokens/Patterns (what to reuse or add)
7918
+
7919
+ Working rules:
7920
+ - Design for all states, not just the populated happy path
7921
+ - Reuse existing patterns/tokens before inventing new ones
7922
+ - Keep accessibility and responsiveness in the design, not bolted on later
7923
+ - Justify each decision in terms of the user goal`
7924
+ },
7925
+ budget: MEDIUM_BUDGET,
7926
+ capability: {
7927
+ phase: "domain",
7928
+ summary: "UI/UX design: user flows, layout/wireframes, interaction states, and design-system decisions.",
7929
+ keywords: [
7930
+ "design",
7931
+ "ux",
7932
+ "ui design",
7933
+ "wireframe",
7934
+ "user flow",
7935
+ "layout",
7936
+ "design system",
7937
+ "interaction",
7938
+ "mockup design",
7939
+ "information architecture"
7940
+ ]
7941
+ }
7942
+ }
7943
+ ];
7944
+
7945
+ // src/coordination/agents/phase7-knowledge.ts
7946
+ var KNOWLEDGE_AGENTS = [
7947
+ {
7948
+ config: {
7949
+ id: "document",
7950
+ name: "Document",
7951
+ role: "document",
7952
+ tools: [...TOOLS.docs],
7953
+ prompt: `You are the Document agent. Your job is technical documentation: READMEs,
7954
+ API docs, guides, and inline reference that are accurate and grounded in the
7955
+ actual code.
7956
+
7957
+ Scope:
7958
+ - Write/update READMEs, setup guides, and architecture overviews
7959
+ - Generate API/reference docs from the real signatures
7960
+ - Produce usage examples that actually run
7961
+ - Keep docs in sync with current behavior; flag stale sections
7962
+
7963
+ Input format you accept:
7964
+ { "task": "readme | api | guide | reference", "target": "<package/module>", "audience": "user | contributor" }
7965
+
7966
+ Output: Markdown documentation (the actual doc) plus:
7967
+ - ## Changes (what was added/updated)
7968
+ - ## Verification (which examples you confirmed against the code)
7969
+ - ## Stale (existing docs that no longer match the code)
7970
+
7971
+ Working rules:
7972
+ - Ground every statement in the real code; never document aspirational behavior
7973
+ - Examples must be runnable and verified against the current API
7974
+ - Match the project's existing doc tone and structure
7975
+ - Don't create docs the user didn't ask for; update in place when possible`
7976
+ },
7977
+ budget: MEDIUM_BUDGET,
7978
+ capability: {
7979
+ phase: "knowledge",
7980
+ summary: "Technical documentation: READMEs, API/reference docs, guides, and verified examples grounded in code.",
7981
+ keywords: [
7982
+ "document",
7983
+ "documentation",
7984
+ "readme",
7985
+ "docs",
7986
+ "write up",
7987
+ "guide",
7988
+ "api docs",
7989
+ "explain in writing",
7990
+ "reference",
7991
+ "changelog notes"
7992
+ ]
7993
+ }
7994
+ },
7995
+ {
7996
+ config: {
7997
+ id: "uml",
7998
+ name: "UML",
7999
+ role: "uml",
8000
+ tools: [...TOOLS.read, "write", "edit"],
8001
+ prompt: `You are the UML agent. Your job is diagram generation from code: class,
8002
+ sequence, component, and ER diagrams that accurately reflect the system.
8003
+
8004
+ Scope:
8005
+ - Generate class/component diagrams from the real type structure
8006
+ - Produce sequence diagrams for a given flow by tracing the code
8007
+ - Build ER diagrams from schema/models
8008
+ - Emit diagrams as Mermaid/PlantUML text (version-controllable)
8009
+
8010
+ Input format you accept:
8011
+ { "task": "class | sequence | component | er", "target": "<module/flow>", "format": "mermaid | plantuml" }
8012
+
8013
+ Output: Markdown with embedded diagram source:
8014
+ - ## Diagram (mermaid/plantuml code block)
8015
+ - ## Legend (what the nodes/edges mean)
8016
+ - ## Source Mapping (diagram element \u2192 file:line)
8017
+
8018
+ Working rules:
8019
+ - Derive diagrams from the actual code, not from assumptions
8020
+ - Keep diagrams focused \u2014 one concern per diagram, not the whole system
8021
+ - Map every node back to a source location
8022
+ - Prefer text-based formats (Mermaid/PlantUML) so diagrams live in git`
8023
+ },
8024
+ budget: LIGHT_BUDGET,
8025
+ capability: {
8026
+ phase: "knowledge",
8027
+ summary: "Diagram generation from code: class/sequence/component/ER diagrams as Mermaid/PlantUML.",
8028
+ keywords: [
8029
+ "uml",
8030
+ "diagram",
8031
+ "mermaid",
8032
+ "plantuml",
8033
+ "sequence diagram",
8034
+ "class diagram",
8035
+ "er diagram",
8036
+ "visualize",
8037
+ "flowchart",
8038
+ "architecture diagram"
8039
+ ]
8040
+ }
8041
+ },
8042
+ {
8043
+ config: {
8044
+ id: "i18n",
8045
+ name: "I18n",
8046
+ role: "i18n",
8047
+ tools: [...TOOLS.write],
8048
+ prompt: `You are the I18n agent. Your job is internationalization and
8049
+ localization: extract strings, manage translation catalogs, and make the UI
8050
+ locale-correct.
8051
+
8052
+ Scope:
8053
+ - Extract hardcoded user-facing strings into translation keys
8054
+ - Manage message catalogs and detect missing/orphan keys
8055
+ - Handle plurals, interpolation, dates/numbers, and RTL
8056
+ - Keep keys consistent and translations in sync across locales
8057
+
8058
+ Input format you accept:
8059
+ { "task": "extract | translate | audit", "scope": ["src/ui"], "locales": ["en", "tr", "de"] }
8060
+
8061
+ Output: Markdown i18n report:
8062
+ - ## Extracted Keys (string \u2192 key, file:line)
8063
+ - ## Catalog Changes (per locale: added/removed)
8064
+ - ## Gaps (missing translations, orphan keys)
8065
+ - ## Locale Hazards (plurals, RTL, date/number formats)
8066
+
8067
+ Working rules:
8068
+ - Never hardcode user-facing copy \u2014 route it through the i18n system
8069
+ - Keep keys semantic and stable; don't key by English text
8070
+ - Flag pluralization and interpolation that machines can't safely translate
8071
+ - Don't fabricate translations for languages you can't verify \u2014 mark TODO`
8072
+ },
8073
+ budget: MEDIUM_BUDGET,
8074
+ capability: {
8075
+ phase: "knowledge",
8076
+ summary: "Internationalization/localization: string extraction, catalog management, plurals/RTL/format handling.",
8077
+ keywords: [
8078
+ "i18n",
8079
+ "internationalization",
8080
+ "localization",
8081
+ "l10n",
8082
+ "translation",
8083
+ "translate ui",
8084
+ "locale",
8085
+ "rtl",
8086
+ "message catalog",
8087
+ "multilingual"
8088
+ ]
8089
+ }
8090
+ },
8091
+ {
8092
+ config: {
8093
+ id: "prompt",
8094
+ name: "Prompt",
8095
+ role: "prompt",
8096
+ tools: [...TOOLS.write],
8097
+ prompt: `You are the Prompt agent. Your job is prompt engineering: design, refine,
8098
+ and evaluate prompts and agent instructions for LLM-driven features.
8099
+
8100
+ Scope:
8101
+ - Write/refine system prompts, tool instructions, and few-shot examples
8102
+ - Improve reliability: structure, constraints, output format, failure handling
8103
+ - Reduce token cost without losing capability
8104
+ - Define evaluation criteria and edge-case probes for a prompt
8105
+
8106
+ Input format you accept:
8107
+ { "task": "design | refine | evaluate", "goal": "<what the prompt should do>", "model": "<target model>", "constraints": ["json output", "no chain-of-thought leak"] }
8108
+
8109
+ Output: Markdown prompt deliverable:
8110
+ - ## Prompt (the actual text, ready to use)
8111
+ - ## Rationale (why each section exists)
8112
+ - ## Eval Probes (inputs that test the edges)
8113
+ - ## Token Notes (rough cost + where it could shrink)
8114
+
8115
+ Working rules:
8116
+ - Be explicit about output format and constraints \u2014 leave no room to drift
8117
+ - Include negative instructions and failure handling, not just the happy path
8118
+ - Prefer clear structure over clever wording
8119
+ - Always provide edge-case probes so the prompt can be validated`
8120
+ },
8121
+ budget: LIGHT_BUDGET,
8122
+ capability: {
8123
+ phase: "knowledge",
8124
+ summary: "Prompt engineering: designs/refines/evaluates LLM system prompts and agent instructions.",
8125
+ keywords: [
8126
+ "prompt",
8127
+ "prompt engineering",
8128
+ "system prompt",
8129
+ "llm instructions",
8130
+ "few-shot",
8131
+ "refine prompt",
8132
+ "agent instructions",
8133
+ "prompt template"
8134
+ ]
8135
+ }
8136
+ }
8137
+ ];
8138
+
8139
+ // src/coordination/agents/phase8-delivery.ts
8140
+ var DELIVERY_AGENTS = [
8141
+ {
8142
+ config: {
8143
+ id: "git",
8144
+ name: "Git",
8145
+ role: "git",
8146
+ tools: [...TOOLS.vcs, "bash"],
8147
+ prompt: `You are the Git agent. Your job is git automation: clean commits, branch
8148
+ hygiene, history operations, and PR preparation \u2014 carefully.
8149
+
8150
+ Scope:
8151
+ - Stage and craft focused commits with clear messages
8152
+ - Manage branches, rebases, and conflict resolution
8153
+ - Prepare PRs (diff summary, description) from the actual changes
8154
+ - Investigate history (blame, bisect) to answer "when/why did this change"
8155
+
8156
+ Input format you accept:
8157
+ { "task": "commit | branch | rebase | pr | history", "intent": "<what to do>" }
8158
+
8159
+ Output: Markdown git report:
8160
+ - ## Action (what was done)
8161
+ - ## Commits/Refs (hashes + messages)
8162
+ - ## State (branch, ahead/behind, clean?)
8163
+ - ## Notes (anything risky encountered)
8164
+
8165
+ Working rules:
8166
+ - NEVER run destructive ops (force-push, reset --hard, branch -D) without explicit instruction
8167
+ - Resolve conflicts by understanding both sides; don't discard work
8168
+ - Write commit messages that explain why, not just what
8169
+ - Confirm before any history rewrite on shared branches`
8170
+ },
8171
+ budget: MEDIUM_BUDGET,
8172
+ capability: {
8173
+ phase: "delivery",
8174
+ summary: "Git automation: focused commits, branch/rebase/conflict handling, PR prep, history investigation.",
8175
+ keywords: [
8176
+ "git",
8177
+ "commit",
8178
+ "branch",
8179
+ "rebase",
8180
+ "merge",
8181
+ "pull request",
8182
+ "pr",
8183
+ "conflict",
8184
+ "blame",
8185
+ "bisect",
8186
+ "cherry-pick",
8187
+ "stash"
8188
+ ]
8189
+ }
8190
+ },
8191
+ {
8192
+ config: {
8193
+ id: "release",
8194
+ name: "Release",
8195
+ role: "release",
8196
+ tools: [...TOOLS.vcs, "bash", "json"],
8197
+ prompt: `You are the Release agent. Your job is release management: semantic
8198
+ versioning, changelogs, and release notes derived from the real history.
8199
+
8200
+ Scope:
8201
+ - Determine the correct semver bump from the change set (breaking/feat/fix)
8202
+ - Generate changelogs and human-readable release notes from commits/PRs
8203
+ - Verify version consistency across manifests and tags
8204
+ - Prepare the release artifacts and checklist
8205
+
8206
+ Input format you accept:
8207
+ { "task": "version | changelog | notes | checklist", "since": "<last tag>", "channel": "stable | beta" }
8208
+
8209
+ Output: Markdown release deliverable:
8210
+ - ## Version (current \u2192 next, with reasoning)
8211
+ - ## Changelog (grouped: Breaking / Features / Fixes)
8212
+ - ## Release Notes (user-facing summary)
8213
+ - ## Pre-release Checklist
8214
+
8215
+ Working rules:
8216
+ - Derive the bump from actual changes; a breaking change forces a major
8217
+ - Group changes by impact; lead with breaking changes
8218
+ - Keep version numbers consistent across all manifests
8219
+ - Never tag/publish without an explicit go-ahead`
8220
+ },
8221
+ budget: MEDIUM_BUDGET,
8222
+ capability: {
8223
+ phase: "delivery",
8224
+ summary: "Release management: semver bumps, changelogs, and release notes derived from real history.",
8225
+ keywords: [
8226
+ "release",
8227
+ "version",
8228
+ "semver",
8229
+ "changelog",
8230
+ "release notes",
8231
+ "tag",
8232
+ "bump version",
8233
+ "publish",
8234
+ "versioning"
8235
+ ]
8236
+ }
8237
+ },
8238
+ {
8239
+ config: {
8240
+ id: "devops",
8241
+ name: "DevOps",
8242
+ role: "devops",
8243
+ tools: [...TOOLS.build],
8244
+ prompt: `You are the DevOps agent. Your job is CI/CD, containerization, and
8245
+ deployment configuration: make builds reproducible and deploys safe.
8246
+
8247
+ Scope:
8248
+ - Author/repair CI/CD pipelines (build, test, lint, deploy stages)
8249
+ - Write Dockerfiles/compose and optimize image size and layer caching
8250
+ - Configure deployment (env, secrets handling, health checks, rollback)
8251
+ - Diagnose flaky/broken pipelines
8252
+
8253
+ Input format you accept:
8254
+ { "task": "ci | container | deploy | fix-pipeline", "platform": "github-actions | gitlab | docker | k8s", "target": "<what>" }
8255
+
8256
+ Output: Markdown devops report:
8257
+ - ## Config (the pipeline/Dockerfile/manifest changes)
8258
+ - ## Stages (what runs when + gates)
8259
+ - ## Safety (secrets handling, rollback, health checks)
8260
+ - ## Verification (dry-run/lint results where possible)
8261
+
8262
+ Working rules:
8263
+ - Never hardcode secrets in config; reference the secret store
8264
+ - Pin versions for reproducible builds; avoid floating :latest
8265
+ - Every deploy path needs a rollback and a health check
8266
+ - Treat CI/CD changes as high-risk \u2014 explain blast radius before applying`
8267
+ },
8268
+ budget: MEDIUM_BUDGET,
8269
+ capability: {
8270
+ phase: "delivery",
8271
+ summary: "CI/CD, containerization, and deployment config: reproducible builds and safe deploys with rollback.",
8272
+ keywords: [
8273
+ "devops",
8274
+ "ci",
8275
+ "cd",
8276
+ "ci/cd",
8277
+ "pipeline",
8278
+ "docker",
8279
+ "dockerfile",
8280
+ "kubernetes",
8281
+ "k8s",
8282
+ "deploy",
8283
+ "github actions",
8284
+ "container"
8285
+ ]
8286
+ }
8287
+ },
8288
+ {
8289
+ config: {
8290
+ id: "observability",
8291
+ name: "Observability",
8292
+ role: "observability",
8293
+ tools: [...TOOLS.build, "logs"],
8294
+ prompt: `You are the Observability agent. Your job is logs, metrics, and traces:
8295
+ make the system's behavior visible and diagnosable in production.
8296
+
8297
+ Scope:
8298
+ - Add structured logging at the right levels and boundaries
8299
+ - Instrument metrics (counters/gauges/histograms) for key operations
8300
+ - Add distributed tracing spans around cross-service calls
8301
+ - Define dashboards/alerts for the signals that matter
8302
+
8303
+ Input format you accept:
8304
+ { "task": "logging | metrics | tracing | alerts", "target": "<component>", "stack": "otel | prometheus | custom" }
8305
+
8306
+ Output: Markdown observability report:
8307
+ - ## Instrumentation (what was added + where)
8308
+ - ## Signals (log fields / metrics / spans defined)
8309
+ - ## Alerts/Dashboards (what to watch + thresholds)
8310
+ - ## Cost Notes (cardinality / volume concerns)
8311
+
8312
+ Working rules:
8313
+ - Log structured key-values, not string-concatenated prose
8314
+ - Watch metric cardinality \u2014 never label with unbounded values (user ids, urls)
8315
+ - Instrument the boundaries (I/O, external calls), not every line
8316
+ - Don't log secrets or PII; scrub at the source`
8317
+ },
8318
+ budget: MEDIUM_BUDGET,
8319
+ capability: {
8320
+ phase: "delivery",
8321
+ summary: "Observability: structured logging, metrics, distributed tracing, and alerts/dashboards.",
8322
+ keywords: [
8323
+ "observability",
8324
+ "logging",
8325
+ "metrics",
8326
+ "tracing",
8327
+ "telemetry",
8328
+ "opentelemetry",
8329
+ "otel",
8330
+ "prometheus",
8331
+ "monitoring",
8332
+ "alert",
8333
+ "dashboard",
8334
+ "instrument"
8335
+ ]
8336
+ }
8337
+ },
8338
+ {
8339
+ config: {
8340
+ id: "dependency",
8341
+ name: "Dependency",
8342
+ role: "dependency",
8343
+ tools: [...TOOLS.deps, "bash"],
8344
+ prompt: `You are the Dependency agent. Your job is package management and supply-
8345
+ chain safety: keep dependencies current, secure, and lean.
8346
+
8347
+ Scope:
8348
+ - Audit dependencies for CVEs and known-bad packages
8349
+ - Plan safe upgrades (respecting semver and breaking changes)
8350
+ - Detect unused, duplicate, and bloated dependencies
8351
+ - Review supply-chain risks (postinstall scripts, typosquats, provenance)
8352
+
8353
+ Input format you accept:
8354
+ { "task": "audit | upgrade | prune | supplychain", "scope": "all | direct", "severity": "critical | high | all" }
8355
+
8356
+ Output: Markdown dependency report:
8357
+ - ## Vulnerabilities (package \u2192 CVE \u2192 severity \u2192 fix version)
8358
+ - ## Upgrades (safe now / needs migration)
8359
+ - ## Unused/Duplicate (removable)
8360
+ - ## Supply-chain Flags (risky install scripts, unverified packages)
8361
+
8362
+ Working rules:
8363
+ - Distinguish a safe patch bump from a breaking major upgrade
8364
+ - Verify a CVE actually affects the used code path before alarming
8365
+ - Flag postinstall/preinstall scripts and typosquat-looking names
8366
+ - Never auto-apply a major upgrade without a migration plan`
8367
+ },
8368
+ budget: MEDIUM_BUDGET,
8369
+ capability: {
8370
+ phase: "delivery",
8371
+ summary: "Package management + supply-chain safety: CVE audit, safe upgrades, pruning, install-script review.",
8372
+ keywords: [
8373
+ "dependency",
8374
+ "dependencies",
8375
+ "package",
8376
+ "npm",
8377
+ "pnpm",
8378
+ "cve",
8379
+ "vulnerability scan",
8380
+ "upgrade deps",
8381
+ "audit",
8382
+ "supply chain",
8383
+ "outdated",
8384
+ "lockfile"
8385
+ ]
8386
+ }
8387
+ }
8388
+ ];
8389
+
8390
+ // src/coordination/agents/phase9-meta.ts
8391
+ var META_AGENTS = [
8392
+ {
8393
+ config: {
8394
+ id: "skill-manage",
8395
+ name: "Skill Manager",
8396
+ role: "skill-manage",
8397
+ tools: [...TOOLS.write],
8398
+ prompt: `You are the Skill Manager agent. Your job is skill curation: create,
8399
+ review, refine, and retire skills so the skill library stays high-signal.
8400
+
8401
+ Scope:
8402
+ - Audit existing skills for quality, overlap, and stale triggers
8403
+ - Improve skill descriptions so they activate at the right time (not too eager)
8404
+ - Scaffold new skills with correct structure and progressive disclosure
8405
+ - Retire or merge redundant skills
8406
+
8407
+ Input format you accept:
8408
+ { "task": "audit | create | refine | retire", "target": "<skill name or area>" }
8409
+
8410
+ Output: Markdown skill report:
8411
+ - ## Findings (skill \u2192 issue \u2192 action)
8412
+ - ## Description Fixes (before \u2192 after, why it triggers better)
8413
+ - ## New/Merged Skills (structure proposed)
8414
+ - ## Retire List (with rationale)
8415
+
8416
+ Working rules:
8417
+ - A skill's description is its trigger \u2014 make it specific, not greedy
8418
+ - Prefer fewer, sharper skills over many overlapping ones
8419
+ - Follow the project's skill structure and progressive-disclosure conventions
8420
+ - Don't delete a skill without confirming nothing depends on it`
8421
+ },
8422
+ budget: LIGHT_BUDGET,
8423
+ capability: {
8424
+ phase: "meta",
8425
+ summary: "Skill curation: audits, refines descriptions/triggers, scaffolds, and retires skills.",
8426
+ keywords: [
8427
+ "skill",
8428
+ "skills",
8429
+ "curate skill",
8430
+ "skill description",
8431
+ "create skill",
8432
+ "skill library",
8433
+ "skill trigger",
8434
+ "manage skills"
8435
+ ]
8436
+ }
8437
+ },
8438
+ {
8439
+ config: {
8440
+ id: "self-improving",
8441
+ name: "Self-Improving",
8442
+ role: "self-improving",
8443
+ tools: [...TOOLS.inspect],
8444
+ prompt: `You are the Self-Improving agent. Your job is to learn from past
8445
+ executions: mine session logs and outcomes to find recurring failures and
8446
+ propose concrete improvements to prompts, tools, or workflows.
8447
+
8448
+ Scope:
8449
+ - Analyze session/agent execution logs for failure and inefficiency patterns
8450
+ - Correlate outcomes with prompts, tool usage, and budgets
8451
+ - Propose specific changes (prompt edits, budget tweaks, new guardrails)
8452
+ - Track whether prior recommendations actually helped
8453
+
8454
+ Input format you accept:
8455
+ { "task": "analyze | propose | evaluate", "logs": "<session path/dir>", "focus": "failures | efficiency | cost" }
8456
+
8457
+ Output: Markdown improvement report:
8458
+ - ## Patterns (recurring failure/inefficiency + frequency)
8459
+ - ## Root Causes (why, with evidence from logs)
8460
+ - ## Proposed Changes (concrete edits, ranked by expected impact)
8461
+ - ## Validation Plan (how to confirm the change helped)
8462
+
8463
+ Working rules:
8464
+ - Ground every recommendation in observed log evidence, not intuition
8465
+ - Quantify the problem (how often, how costly) before proposing a fix
8466
+ - Propose the smallest change that addresses the root cause
8467
+ - Mark recommendations that need A/B validation before adoption`
8468
+ },
8469
+ budget: MEDIUM_BUDGET,
8470
+ capability: {
8471
+ phase: "meta",
8472
+ summary: "Learns from execution logs: mines recurring failures/inefficiencies and proposes evidence-based improvements.",
8473
+ keywords: [
8474
+ "self-improving",
8475
+ "learn from",
8476
+ "session logs",
8477
+ "execution analysis",
8478
+ "recurring failure",
8479
+ "improve agents",
8480
+ "post-mortem",
8481
+ "retrospective",
8482
+ "meta-analysis"
8483
+ ]
8484
+ }
8485
+ },
8486
+ {
8487
+ config: {
8488
+ id: "context",
8489
+ name: "Context",
8490
+ role: "context",
8491
+ tools: [...TOOLS.inspect, "remember", "forget"],
8492
+ prompt: `You are the Context agent. Your job is memory and context-window
8493
+ management: decide what to keep, compact, or recall so the working context
8494
+ stays high-signal and within budget.
8495
+
8496
+ Scope:
8497
+ - Summarize/compact long histories without losing load-bearing detail
8498
+ - Decide what belongs in durable memory vs. ephemeral context
8499
+ - Recall the right prior context for the current task
8500
+ - Detect and prune redundant or stale context
8501
+
8502
+ Input format you accept:
8503
+ { "task": "compact | recall | curate | budget", "target": "<session/context>", "limit": "<token budget>" }
8504
+
8505
+ Output: Markdown context report:
8506
+ - ## Kept (what stays in context + why it's load-bearing)
8507
+ - ## Compacted (summarized away, with the summary)
8508
+ - ## Recalled (durable memory surfaced for this task)
8509
+ - ## Pruned (removed as stale/redundant)
8510
+
8511
+ Working rules:
8512
+ - Never compact away a fact the current task depends on
8513
+ - Prefer summarizing over dropping; keep a pointer to the source
8514
+ - Distinguish durable memory (cross-session) from ephemeral context
8515
+ - Respect the token budget; report when you can't fit the essentials`
8516
+ },
8517
+ budget: LIGHT_BUDGET,
8518
+ capability: {
8519
+ phase: "meta",
8520
+ summary: "Memory + context-window management: compaction, recall, and curation within a token budget.",
8521
+ keywords: [
8522
+ "context",
8523
+ "context window",
8524
+ "memory",
8525
+ "compact",
8526
+ "summarize history",
8527
+ "recall",
8528
+ "token budget",
8529
+ "prune context",
8530
+ "remember",
8531
+ "dfmt"
8532
+ ]
8533
+ }
8534
+ },
8535
+ {
8536
+ config: {
8537
+ id: "cost",
8538
+ name: "Cost",
8539
+ role: "cost",
8540
+ tools: [...TOOLS.inspect],
8541
+ prompt: `You are the Cost agent. Your job is token and cloud cost optimization:
8542
+ find where money/tokens are burned and cut waste without losing capability.
8543
+
8544
+ Scope:
8545
+ - Analyze token spend by model, prompt, and tool usage
8546
+ - Identify expensive patterns: oversized prompts, redundant calls, wrong model tier
8547
+ - Recommend model routing (cheap model for cheap tasks, premium where it pays)
8548
+ - Estimate savings of each recommendation
8549
+
8550
+ Input format you accept:
8551
+ { "task": "analyze | optimize | route | estimate", "scope": "<session/feature>", "lever": "tokens | model | calls" }
8552
+
8553
+ Output: Markdown cost report:
8554
+ - ## Spend Breakdown (by model / prompt / tool)
8555
+ - ## Waste (the costly patterns, with $ impact)
8556
+ - ## Recommendations (ranked by savings, with risk)
8557
+ - ## Estimated Savings (per recommendation)
8558
+
8559
+ Working rules:
8560
+ - Quantify in tokens AND dollars; don't hand-wave "it's expensive"
8561
+ - Recommend the cheapest model that still meets the quality bar
8562
+ - Prefer caching and prompt trimming before downgrading models
8563
+ - Flag any optimization that risks correctness or capability`
8564
+ },
8565
+ budget: LIGHT_BUDGET,
8566
+ capability: {
8567
+ phase: "meta",
8568
+ summary: "Token/cloud cost optimization: finds spend waste, recommends model routing and trimming with $ estimates.",
8569
+ keywords: [
8570
+ "cost",
8571
+ "token cost",
8572
+ "optimize cost",
8573
+ "spend",
8574
+ "cheaper",
8575
+ "model routing",
8576
+ "budget",
8577
+ "expensive",
8578
+ "reduce tokens",
8579
+ "pricing",
8580
+ "cloud cost"
8581
+ ]
8582
+ }
8583
+ }
8584
+ ];
8585
+
8586
+ // src/coordination/agents/index.ts
8587
+ var ALL_AGENT_DEFINITIONS = [
8588
+ ...DISCOVERY_AGENTS,
8589
+ ...PLANNING_AGENTS,
8590
+ ...BUILD_AGENTS,
8591
+ ...VERIFY_AGENTS,
8592
+ ...REVIEW_AGENTS,
8593
+ ...DOMAIN_AGENTS,
8594
+ ...KNOWLEDGE_AGENTS,
8595
+ ...DELIVERY_AGENTS,
8596
+ ...META_AGENTS
8597
+ ];
8598
+ var AGENTS_BY_PHASE = {
8599
+ discovery: DISCOVERY_AGENTS,
8600
+ planning: PLANNING_AGENTS,
8601
+ build: BUILD_AGENTS,
8602
+ verify: VERIFY_AGENTS,
8603
+ review: REVIEW_AGENTS,
8604
+ domain: DOMAIN_AGENTS,
8605
+ knowledge: KNOWLEDGE_AGENTS,
8606
+ delivery: DELIVERY_AGENTS,
8607
+ meta: META_AGENTS
8608
+ };
8609
+ var AGENT_CATALOG = (() => {
8610
+ const map = {};
8611
+ for (const def of ALL_AGENT_DEFINITIONS) {
8612
+ const role = def.config.role;
8613
+ if (!role) {
8614
+ throw new Error(`Agent "${def.config.name}" is missing a role`);
8615
+ }
8616
+ if (map[role]) {
8617
+ throw new Error(`Duplicate agent role in catalog: "${role}"`);
8618
+ }
8619
+ map[role] = def;
8620
+ }
8621
+ return map;
8622
+ })();
8623
+ function getAgentDefinition(role) {
8624
+ return AGENT_CATALOG[role];
8625
+ }
8626
+
8627
+ // src/coordination/dispatcher.ts
8628
+ var DEFAULT_DISPATCH_ROLE = "executor";
8629
+ function normalize(text) {
8630
+ return ` ${text.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim()} `;
8631
+ }
8632
+ function scoreAgents(task, catalog = AGENT_CATALOG) {
8633
+ const hay = normalize(task);
8634
+ const out = [];
8635
+ for (const def of Object.values(catalog)) {
8636
+ const role = def.config.role;
8637
+ if (!role) continue;
8638
+ let score = 0;
8639
+ const matched = [];
8640
+ for (const kw of def.capability.keywords) {
8641
+ const needle = normalize(kw);
8642
+ if (hay.includes(needle.trimEnd() + " ") || hay.includes(" " + needle.trimStart())) {
8643
+ const words = kw.trim().split(/\s+/).length;
8644
+ score += words;
8645
+ matched.push(kw);
8646
+ }
8647
+ }
8648
+ if (score > 0) {
8649
+ out.push({ role, name: def.config.name, score, matched });
8650
+ }
6234
8651
  }
6235
- usage() {
8652
+ out.sort((a, b) => b.score - a.score);
8653
+ return out;
8654
+ }
8655
+ function heuristicConfidence(candidates) {
8656
+ if (candidates.length === 0) return 0;
8657
+ const top = candidates[0].score;
8658
+ const second = candidates[1]?.score ?? 0;
8659
+ const strength = Math.min(1, top / 3);
8660
+ const margin = (top - second + 1) / (top + 1);
8661
+ return Math.min(1, strength * margin);
8662
+ }
8663
+ async function dispatchAgent(task, opts = {}) {
8664
+ const catalog = opts.catalog ?? AGENT_CATALOG;
8665
+ const threshold = opts.confidenceThreshold ?? 0.4;
8666
+ const maxCandidates = opts.maxCandidates ?? 6;
8667
+ const candidates = scoreAgents(task, catalog);
8668
+ const confidence = heuristicConfidence(candidates);
8669
+ const top = candidates[0];
8670
+ if (top && confidence >= threshold) {
6236
8671
  return {
6237
- iterations: this.iterations,
6238
- toolCalls: this.toolCalls,
6239
- tokens: {
6240
- input: this.tokenInput,
6241
- output: this.tokenOutput,
6242
- total: this.tokenInput + this.tokenOutput
6243
- },
6244
- costUsd: this.costUsd,
6245
- elapsedMs: this.startTime === null ? 0 : Date.now() - this.startTime
8672
+ role: top.role,
8673
+ definition: catalog[top.role],
8674
+ confidence,
8675
+ method: "heuristic",
8676
+ reason: `Matched keywords: ${top.matched.slice(0, 4).join(", ")}`,
8677
+ alternatives: candidates.slice(1, maxCandidates)
6246
8678
  };
6247
8679
  }
6248
- };
6249
-
6250
- // src/coordination/agent-subagent-runner.ts
6251
- function makeAgentSubagentRunner(opts) {
6252
- const format = opts.formatTaskInput ?? defaultFormatTaskInput;
6253
- return async (task, ctx) => {
6254
- const factoryResult = await opts.factory(ctx.config);
6255
- const { agent, events } = factoryResult;
6256
- const detachFleet = opts.fleetBus?.attach(ctx.subagentId, events, task.id);
6257
- const aborter = new AbortController();
6258
- ctx.budget._events = events;
6259
- ctx.budget.onThreshold = ({ requestDecision }) => requestDecision();
6260
- let budgetError = null;
6261
- const onBudgetError = (err) => {
6262
- if (err instanceof BudgetThresholdSignal) {
6263
- err.decision.then((decision) => {
6264
- if (decision === "stop") {
6265
- budgetError = new BudgetExceededError(err.kind, err.limit, err.used);
6266
- aborter.abort();
6267
- }
6268
- }).catch(() => {
6269
- budgetError = new BudgetExceededError(err.kind, err.limit, err.used);
6270
- aborter.abort();
6271
- });
6272
- return;
6273
- }
6274
- aborter.abort();
6275
- budgetError = err instanceof BudgetExceededError ? err : new BudgetExceededError(
6276
- "tool_calls",
6277
- 0,
6278
- 0
6279
- );
6280
- if (budgetError !== err && err instanceof Error) {
6281
- budgetError.message += ` (caused by: ${err.message})`;
6282
- }
6283
- };
6284
- let lastToolFailed = null;
6285
- const unsub = [];
6286
- unsub.push(
6287
- events.on("tool.executed", (e) => {
6288
- try {
6289
- ctx.budget.recordToolCall();
6290
- } catch (eb) {
6291
- onBudgetError(eb);
6292
- }
6293
- if (e.ok === false) {
6294
- lastToolFailed = e.name;
6295
- } else if (e.ok === true) {
6296
- lastToolFailed = null;
6297
- }
6298
- }),
6299
- events.on("provider.response", (e) => {
6300
- try {
6301
- ctx.budget.recordUsage(e.usage);
6302
- } catch (e2) {
6303
- void onBudgetError(e2);
6304
- }
6305
- }),
6306
- events.on("iteration.started", () => {
6307
- try {
6308
- ctx.budget.recordIteration();
6309
- } catch (e) {
6310
- void onBudgetError(e);
6311
- }
6312
- const u = ctx.budget.usage();
6313
- const since = u.iterations - lastSummaryAtIteration;
6314
- if (since >= SUMMARY_INTERVAL) {
6315
- lastSummaryAtIteration = u.iterations;
6316
- events.emit("subagent.iteration_summary", {
6317
- subagentId: ctx.subagentId,
6318
- iteration: u.iterations,
6319
- toolCalls: u.toolCalls,
6320
- costUsd: u.costUsd,
6321
- currentTool: currentToolName,
6322
- partialText: streamingTextAcc.trim() || void 0
6323
- });
6324
- }
6325
- }),
6326
- // D3: cooperative timeout enforcement DURING a long tool call.
6327
- // The iteration-loop checkTimeout() only fires between agent
6328
- // iterations — a single `bash sleep 3600` call would otherwise
6329
- // park inside one tool execution while the timeout silently
6330
- // passes, relying solely on the coordinator's hard Promise.race
6331
- // to interrupt. Tools that emit `tool.progress` (bash chunks,
6332
- // fetch byte progress, spawn-stream stdout) give us a heartbeat
6333
- // we can hang the check on. When the budget trips here:
6334
- // 1. onBudgetError sets budgetError + aborter.abort()
6335
- // 2. aborter signal propagates to agent.run → tool executor
6336
- // 3. tool's own signal listener kills the child process
6337
- // Cheap: O(1) per progress event, and the budget short-circuits
6338
- // when timeoutMs is unset (most subagents have one set anyway).
6339
- events.on("tool.progress", () => {
6340
- try {
6341
- ctx.budget.checkTimeout();
6342
- } catch (e) {
6343
- void onBudgetError(e);
6344
- }
6345
- })
6346
- );
6347
- let currentToolName;
6348
- let streamingTextAcc = "";
6349
- let lastSummaryAtIteration = 0;
6350
- const SUMMARY_INTERVAL = 25;
6351
- unsub.push(
6352
- events.on("tool.started", (e) => {
6353
- currentToolName = e.name;
6354
- }),
6355
- events.on("provider.text_delta", (e) => {
6356
- streamingTextAcc = (streamingTextAcc + e.text).slice(-200);
6357
- })
6358
- );
6359
- const onParentAbort = () => aborter.abort();
6360
- ctx.signal.addEventListener("abort", onParentAbort);
6361
- let result;
8680
+ if (opts.classifier) {
8681
+ const pool = (candidates.length > 0 ? candidates.slice(0, maxCandidates).map((c) => catalog[c.role]) : ALL_AGENT_DEFINITIONS).map((d) => ({
8682
+ role: d.config.role,
8683
+ name: d.config.name,
8684
+ summary: d.capability.summary
8685
+ }));
6362
8686
  try {
6363
- result = await agent.run(format(task, ctx.config), { signal: aborter.signal });
6364
- } finally {
6365
- detachFleet?.();
6366
- ctx.signal.removeEventListener("abort", onParentAbort);
6367
- for (const u of unsub) u();
6368
- if (factoryResult.dispose) {
6369
- try {
6370
- await factoryResult.dispose();
6371
- } catch {
6372
- }
6373
- }
6374
- }
6375
- if (budgetError) {
6376
- if ("decision" in budgetError) {
6377
- const decision = await budgetError.decision;
6378
- if (decision === "stop") {
6379
- budgetError = new BudgetExceededError(
6380
- budgetError.kind,
6381
- budgetError.limit,
6382
- budgetError.used
6383
- );
6384
- } else {
6385
- budgetError = null;
6386
- }
8687
+ const choice = await opts.classifier(task, pool);
8688
+ if (choice && catalog[choice.role]) {
8689
+ return {
8690
+ role: choice.role,
8691
+ definition: catalog[choice.role],
8692
+ confidence: 1,
8693
+ method: "llm",
8694
+ reason: choice.reason ?? "Selected by LLM classifier",
8695
+ alternatives: candidates.slice(0, maxCandidates).filter((c) => c.role !== choice.role)
8696
+ };
6387
8697
  }
6388
- if (budgetError) throw budgetError;
6389
- }
6390
- if (result.status === "failed") {
6391
- throw result.error instanceof Error ? result.error : new Error(String(result.error ?? "agent failed"));
6392
- }
6393
- if (result.status === "aborted") {
6394
- throw new Error("agent aborted");
6395
- }
6396
- if (result.status === "max_iterations") {
6397
- throw new Error("agent exhausted iteration limit");
6398
- }
6399
- const usage = ctx.budget.usage();
6400
- const finalText = (result.finalText ?? "").trim();
6401
- if (finalText.length === 0 && usage.toolCalls === 0) {
6402
- throw new Error("empty response");
6403
- }
6404
- if (finalText.length === 0 && lastToolFailed !== null) {
6405
- throw new Error(`tool failed: ${lastToolFailed}`);
8698
+ } catch {
6406
8699
  }
8700
+ }
8701
+ if (top) {
6407
8702
  return {
6408
- result: result.finalText,
6409
- iterations: result.iterations,
6410
- toolCalls: usage.toolCalls
8703
+ role: top.role,
8704
+ definition: catalog[top.role],
8705
+ confidence,
8706
+ method: "heuristic",
8707
+ reason: `Weak match (${top.matched.slice(0, 3).join(", ") || "low signal"})`,
8708
+ alternatives: candidates.slice(1, maxCandidates)
6411
8709
  };
8710
+ }
8711
+ const fallbackRole = catalog[DEFAULT_DISPATCH_ROLE] ? DEFAULT_DISPATCH_ROLE : Object.keys(catalog)[0];
8712
+ return {
8713
+ role: fallbackRole,
8714
+ definition: catalog[fallbackRole],
8715
+ confidence: 0,
8716
+ method: "fallback",
8717
+ reason: "No keyword signal; defaulting to the generalist Executor",
8718
+ alternatives: []
6412
8719
  };
6413
8720
  }
6414
- function defaultFormatTaskInput(task) {
6415
- return task.description ?? "";
8721
+ function makeLLMClassifier(complete) {
8722
+ return async (task, candidates) => {
8723
+ const list = candidates.map((c, i) => `${i + 1}. ${c.role} \u2014 ${c.summary}`).join("\n");
8724
+ const prompt = `You are an agent router. Pick the single best agent for the task.
8725
+
8726
+ Task:
8727
+ ${task}
8728
+
8729
+ Agents:
8730
+ ${list}
8731
+
8732
+ Reply with ONLY a compact JSON object: {"role":"<one role id from the list>","reason":"<short why>"}.
8733
+ Do not add prose, markdown, or code fences.`;
8734
+ const raw = (await complete(prompt)).trim();
8735
+ const match = raw.match(/\{[\s\S]*\}/);
8736
+ if (!match) return null;
8737
+ try {
8738
+ const parsed = JSON.parse(match[0]);
8739
+ if (typeof parsed.role !== "string") return null;
8740
+ const role = parsed.role.trim();
8741
+ const valid = candidates.some((c) => c.role === role);
8742
+ if (!valid) return null;
8743
+ return { role, reason: typeof parsed.reason === "string" ? parsed.reason : void 0 };
8744
+ } catch {
8745
+ return null;
8746
+ }
8747
+ };
6416
8748
  }
6417
8749
 
6418
8750
  // src/coordination/fleet.ts
@@ -6585,13 +8917,19 @@ var FLEET_ROSTER = {
6585
8917
  "audit-log": AUDIT_LOG_AGENT,
6586
8918
  "bug-hunter": BUG_HUNTER_AGENT,
6587
8919
  "refactor-planner": REFACTOR_PLANNER_AGENT,
6588
- "security-scanner": SECURITY_SCANNER_AGENT
8920
+ "security-scanner": SECURITY_SCANNER_AGENT,
8921
+ ...Object.fromEntries(
8922
+ ALL_AGENT_DEFINITIONS.map((d) => [d.config.role, d.config])
8923
+ )
6589
8924
  };
6590
8925
  var FLEET_ROSTER_BUDGETS = {
6591
8926
  "audit-log": { timeoutMs: 7.5 * 60 * 60 * 1e3, maxIterations: 5e3, maxToolCalls: 15e3 },
6592
8927
  "bug-hunter": { timeoutMs: 10 * 60 * 60 * 1e3, maxIterations: 8e3, maxToolCalls: 2e4 },
6593
8928
  "refactor-planner": { timeoutMs: 7.5 * 60 * 60 * 1e3, maxIterations: 6e3, maxToolCalls: 18e3 },
6594
- "security-scanner": { timeoutMs: 10 * 60 * 60 * 1e3, maxIterations: 8e3, maxToolCalls: 2e4 }
8929
+ "security-scanner": { timeoutMs: 10 * 60 * 60 * 1e3, maxIterations: 8e3, maxToolCalls: 2e4 },
8930
+ ...Object.fromEntries(
8931
+ ALL_AGENT_DEFINITIONS.map((d) => [d.config.role, d.budget])
8932
+ )
6595
8933
  };
6596
8934
  var GENERIC_SUBAGENT_BUDGET = {
6597
8935
  timeoutMs: 3 * 60 * 60 * 1e3,
@@ -6612,6 +8950,67 @@ function applyRosterBudget(cfg) {
6612
8950
  };
6613
8951
  }
6614
8952
  var ALL_FLEET_AGENTS = Object.values(FLEET_ROSTER);
8953
+ var CLINE_AGENT = {
8954
+ id: "cline",
8955
+ name: "Cline",
8956
+ role: "cline",
8957
+ prompt: `You are Cline, a coding agent. You help write, edit, and navigate code.
8958
+ You operate by receiving tasks via ACP and returning results.
8959
+ When asked to code, make focused changes and explain them briefly.`,
8960
+ provider: "acp"
8961
+ };
8962
+ var GEMINI_CLI_AGENT = {
8963
+ id: "gemini-cli",
8964
+ name: "Gemini CLI",
8965
+ role: "gemini-cli",
8966
+ prompt: `You are Gemini CLI, a coding agent powered by Google's Gemini model.
8967
+ You help with code generation, editing, debugging, and best practices.
8968
+ You operate by receiving tasks via ACP and returning results.`,
8969
+ provider: "acp"
8970
+ };
8971
+ var COPILOT_AGENT = {
8972
+ id: "copilot",
8973
+ name: "GitHub Copilot",
8974
+ role: "copilot",
8975
+ prompt: `You are GitHub Copilot, an AI coding assistant.
8976
+ You help write, explain, refactor, and review code.
8977
+ You operate by receiving tasks via ACP and returning results.`,
8978
+ provider: "acp"
8979
+ };
8980
+ var OPENHANDS_AGENT = {
8981
+ id: "openhands",
8982
+ name: "OpenHands",
8983
+ role: "openhands",
8984
+ prompt: `You are OpenHands, an AI coding agent that can use tools to interact
8985
+ with files, terminals, browsers, and other resources.
8986
+ You operate by receiving tasks via ACP and returning results.`,
8987
+ provider: "acp"
8988
+ };
8989
+ var GOOSE_AGENT = {
8990
+ id: "goose",
8991
+ name: "Goose",
8992
+ role: "goose",
8993
+ prompt: `You are Goose, an AI agent that helps with coding tasks.
8994
+ You operate by receiving tasks via ACP and returning results.
8995
+ Focus on writing high-quality, well-tested code.`,
8996
+ provider: "acp"
8997
+ };
8998
+ var ACP_AGENTS = [
8999
+ CLINE_AGENT,
9000
+ GEMINI_CLI_AGENT,
9001
+ COPILOT_AGENT,
9002
+ OPENHANDS_AGENT,
9003
+ GOOSE_AGENT
9004
+ ];
9005
+ FLEET_ROSTER_BUDGETS["cline"] = { timeoutMs: 10 * 60 * 60 * 1e3, maxIterations: 8e3, maxToolCalls: 2e4 };
9006
+ FLEET_ROSTER_BUDGETS["gemini-cli"] = { timeoutMs: 10 * 60 * 60 * 1e3, maxIterations: 8e3, maxToolCalls: 2e4 };
9007
+ FLEET_ROSTER_BUDGETS["copilot"] = { timeoutMs: 10 * 60 * 60 * 1e3, maxIterations: 8e3, maxToolCalls: 2e4 };
9008
+ FLEET_ROSTER_BUDGETS["openhands"] = { timeoutMs: 10 * 60 * 60 * 1e3, maxIterations: 8e3, maxToolCalls: 2e4 };
9009
+ FLEET_ROSTER_BUDGETS["goose"] = { timeoutMs: 10 * 60 * 60 * 1e3, maxIterations: 8e3, maxToolCalls: 2e4 };
9010
+ ({
9011
+ ...FLEET_ROSTER,
9012
+ ...Object.fromEntries(ACP_AGENTS.map((a) => [a.role, a]))
9013
+ });
6615
9014
 
6616
9015
  // src/coordination/multi-agent-coordinator.ts
6617
9016
  var DefaultMultiAgentCoordinator = class extends EventEmitter {
@@ -6726,7 +9125,9 @@ var DefaultMultiAgentCoordinator = class extends EventEmitter {
6726
9125
  * Get current coordinator stats for monitoring/debugging.
6727
9126
  */
6728
9127
  getStats() {
6729
- let running = 0, idle = 0, stopped = 0;
9128
+ let running = 0;
9129
+ let idle = 0;
9130
+ let stopped = 0;
6730
9131
  for (const [, entry] of this.subagents) {
6731
9132
  if (entry.status === "running") running++;
6732
9133
  else if (entry.status === "idle") idle++;
@@ -7190,6 +9591,8 @@ var ParallelEternalEngine = class {
7190
9591
  this.goalPath = goalFilePath(opts.projectRoot);
7191
9592
  this.slots = Math.min(16, Math.max(1, opts.parallelSlots ?? 4));
7192
9593
  this.timeoutMs = opts.iterationTimeoutMs ?? 3e5;
9594
+ this.dispatchEnabled = opts.dispatch !== false;
9595
+ this.dispatchClassifier = opts.dispatchClassifier;
7193
9596
  this.agentFactory = opts.subagentFactory ?? (async (config) => ({
7194
9597
  agent: this.opts.agent,
7195
9598
  events: this.opts.agent.events
@@ -7206,6 +9609,8 @@ var ParallelEternalEngine = class {
7206
9609
  timeoutMs;
7207
9610
  coordinator = null;
7208
9611
  agentFactory;
9612
+ dispatchEnabled;
9613
+ dispatchClassifier;
7209
9614
  get currentState() {
7210
9615
  return this.state;
7211
9616
  }
@@ -7294,9 +9699,10 @@ var ParallelEternalEngine = class {
7294
9699
  fanOut.goalComplete ? "[GOAL_COMPLETE]" : "",
7295
9700
  fanOut.partialOutput ? `Output: ${fanOut.partialOutput.slice(0, 120)}` : ""
7296
9701
  ].filter(Boolean).join(" | ");
9702
+ const routeSummary = fanOut.routes.length > 0 ? fanOut.routes.slice(0, 3).map((r) => `${r.role}\u2192${r.task.slice(0, 28)}`).join(", ") : tasks.slice(0, 3).join(", ");
7297
9703
  await this.appendIterationEntry({
7298
9704
  source: "parallel",
7299
- task: `parallel:${tasks.length} slots \u2014 ${tasks.slice(0, 3).join(", ")}${tasks.length > 3 ? "..." : ""}`,
9705
+ task: `parallel:${tasks.length} slots \u2014 ${routeSummary}${tasks.length > 3 ? "..." : ""}`,
7300
9706
  status,
7301
9707
  note
7302
9708
  });
@@ -7313,6 +9719,11 @@ var ParallelEternalEngine = class {
7313
9719
  async fanOut(goal, tasks) {
7314
9720
  const coordinator = this.coordinator;
7315
9721
  const slotCount = Math.min(this.slots, tasks.length);
9722
+ const routes = this.dispatchEnabled ? await Promise.all(
9723
+ tasks.slice(0, slotCount).map(
9724
+ (t) => dispatchAgent(t, { classifier: this.dispatchClassifier }).catch(() => null)
9725
+ )
9726
+ ) : [];
7316
9727
  const recentJournal = goal.journal.slice(-5).map((e) => ` #${e.iteration} [${e.status}] ${e.task}${e.note ? ` \u2014 ${e.note.slice(0, 80)}` : ""}`).join("\n");
7317
9728
  const directivePreamble = [
7318
9729
  "\u2550\u2550\u2550 ETERNAL AUTONOMY \u2014 parallel task slot \u2550\u2550\u2550",
@@ -7332,29 +9743,48 @@ ${recentJournal}` : "No prior iterations.",
7332
9743
  ].join("\n");
7333
9744
  const taskIds = [];
7334
9745
  const subagentIds = [];
9746
+ const routeInfo = [];
7335
9747
  const spawnPromises = [];
7336
9748
  for (let i = 0; i < slotCount; i++) {
7337
9749
  const task = tasks[i];
9750
+ const route = routes[i] ?? null;
7338
9751
  const subagentId = `parallel-${this.iterations}-${i}`;
7339
9752
  const taskId = randomUUID();
9753
+ const personaLine = route ? `Acting agent: ${route.definition.config.name} \u2014 ${route.definition.capability.summary}
9754
+ ` : "";
7340
9755
  const spec = {
7341
9756
  id: taskId,
7342
9757
  description: `${directivePreamble}
7343
9758
 
7344
9759
  \u2500\u2500 SLOT ${i + 1}/${slotCount} \u2500\u2500
7345
- Task: ${task}
9760
+ ${personaLine}Task: ${task}
7346
9761
  `,
7347
9762
  subagentId
7348
9763
  };
9764
+ routeInfo.push({
9765
+ slot: i,
9766
+ task,
9767
+ role: route?.role ?? "generic",
9768
+ method: route?.method ?? "none"
9769
+ });
7349
9770
  spawnPromises.push((async () => {
7350
9771
  try {
7351
- await coordinator.spawn({
7352
- id: subagentId,
7353
- name: `slot-${subagentId.slice(-6)}`,
7354
- // Let the coordinator apply its default budget (from roster or generic).
7355
- // Hardcoding low limits here defeats the x10 budget improvement.
7356
- timeoutMs: this.timeoutMs
7357
- });
9772
+ await coordinator.spawn(
9773
+ route ? {
9774
+ id: subagentId,
9775
+ name: route.definition.config.name,
9776
+ role: route.role,
9777
+ tools: route.definition.config.tools,
9778
+ systemPromptOverride: route.definition.config.prompt,
9779
+ timeoutMs: this.timeoutMs
9780
+ } : {
9781
+ id: subagentId,
9782
+ name: `slot-${subagentId.slice(-6)}`,
9783
+ // Let the coordinator apply its default budget (roster or generic).
9784
+ // Hardcoding low limits here defeats the x10 budget improvement.
9785
+ timeoutMs: this.timeoutMs
9786
+ }
9787
+ );
7358
9788
  subagentIds.push(subagentId);
7359
9789
  taskIds.push(taskId);
7360
9790
  await coordinator.assign(spec);
@@ -7364,7 +9794,7 @@ Task: ${task}
7364
9794
  }
7365
9795
  await Promise.all(spawnPromises);
7366
9796
  if (taskIds.length === 0) {
7367
- return { results: [], allSuccessful: false, goalComplete: false, partialOutput: "" };
9797
+ return { results: [], allSuccessful: false, goalComplete: false, partialOutput: "", routes: routeInfo };
7368
9798
  }
7369
9799
  let results = [];
7370
9800
  try {
@@ -7383,7 +9813,7 @@ Task: ${task}
7383
9813
  (r) => r.status === "success" && typeof r.result === "string" && GOAL_COMPLETE_MARKER2.test(r.result)
7384
9814
  );
7385
9815
  const partialOutput = results.map((r) => typeof r.result === "string" ? r.result : "").filter(Boolean).join("\n\n");
7386
- return { results, allSuccessful, goalComplete, partialOutput };
9816
+ return { results, allSuccessful, goalComplete, partialOutput, routes: routeInfo };
7387
9817
  }
7388
9818
  // -------------------------------------------------------------------------
7389
9819
  // Goal decomposition
@@ -8399,6 +10829,9 @@ var Director = class {
8399
10829
  /** Snapshot of which subagent owns each task — drives state-checkpoint
8400
10830
  * status updates without re-walking the manifest. */
8401
10831
  taskOwners = /* @__PURE__ */ new Map();
10832
+ /** Cumulative auto-extension grants per subagent (all budget kinds). Lets
10833
+ * /fleet render "⚡ extended ×N" without replaying the event stream. */
10834
+ extendTotals = /* @__PURE__ */ new Map();
8402
10835
  /**
8403
10836
  * Handle to the coordinator-side `task.completed` listener so we can
8404
10837
  * unsubscribe in `shutdown()`. Without this, repeated Director
@@ -8494,8 +10927,28 @@ var Director = class {
8494
10927
  };
8495
10928
  this.coordinator.on("task.completed", this.taskCompletedListener);
8496
10929
  const extendCounts = /* @__PURE__ */ new Map();
10930
+ const progressBySubagent = /* @__PURE__ */ new Map();
10931
+ const lastTimeoutProgress = /* @__PURE__ */ new Map();
10932
+ this.fleet.filter("tool.executed", (e) => {
10933
+ progressBySubagent.set(e.subagentId, (progressBySubagent.get(e.subagentId) ?? 0) + 1);
10934
+ });
8497
10935
  this.fleet.filter("budget.threshold_reached", (e) => {
8498
10936
  const payload = e.payload;
10937
+ if (payload.kind === "timeout") {
10938
+ const progress = progressBySubagent.get(e.subagentId) ?? 0;
10939
+ const lastProgress = lastTimeoutProgress.get(e.subagentId) ?? -1;
10940
+ if (progress <= lastProgress) {
10941
+ payload.deny();
10942
+ return;
10943
+ }
10944
+ lastTimeoutProgress.set(e.subagentId, progress);
10945
+ setImmediate(() => {
10946
+ const newLimit = Math.min(Math.ceil(payload.limit * 2), 24 * 60 * 6e4);
10947
+ this.recordExtension(e.subagentId, e.taskId, "timeout", newLimit);
10948
+ payload.extend({ timeoutMs: newLimit });
10949
+ });
10950
+ return;
10951
+ }
8499
10952
  const guardKey = `${e.subagentId}:${payload.kind}`;
8500
10953
  const prior = extendCounts.get(guardKey) ?? 0;
8501
10954
  if (prior >= this.maxBudgetExtensions) {
@@ -8506,27 +10959,52 @@ var Director = class {
8506
10959
  extendCounts.set(guardKey, prior + 1);
8507
10960
  setImmediate(() => {
8508
10961
  const extra = {};
10962
+ const base = Math.max(payload.limit, payload.used);
10963
+ const grow = (ceiling) => Math.min(Math.ceil(base * 1.5), ceiling);
10964
+ let newLimit = base;
8509
10965
  switch (payload.kind) {
8510
10966
  case "iterations":
8511
- extra.maxIterations = Math.min(payload.used + 100, 800);
10967
+ newLimit = grow(5e4);
10968
+ extra.maxIterations = newLimit;
8512
10969
  break;
8513
10970
  case "tool_calls":
8514
- extra.maxToolCalls = Math.min(Math.ceil(payload.limit * 2), 1500);
10971
+ newLimit = grow(1e5);
10972
+ extra.maxToolCalls = newLimit;
8515
10973
  break;
8516
10974
  case "tokens":
8517
- extra.maxTokens = Math.min(Math.ceil(payload.limit * 2), 8e5);
10975
+ newLimit = grow(5e6);
10976
+ extra.maxTokens = newLimit;
8518
10977
  break;
8519
10978
  case "cost":
8520
- extra.maxCostUsd = Math.min(payload.limit * 2, 25);
8521
- break;
8522
- case "timeout":
8523
- extra.timeoutMs = Math.min(Math.ceil(payload.limit * 2), 2 * 60 * 6e4);
10979
+ newLimit = Math.min(base * 1.5, 100);
10980
+ extra.maxCostUsd = newLimit;
8524
10981
  break;
8525
10982
  }
10983
+ this.recordExtension(e.subagentId, e.taskId, payload.kind, newLimit);
8526
10984
  payload.extend(extra);
8527
10985
  });
8528
10986
  });
8529
10987
  }
10988
+ /**
10989
+ * Record a granted budget extension and broadcast it on the FleetBus so
10990
+ * the host can re-emit `subagent.budget_extended` for live UI badges.
10991
+ * Called from both the timeout heartbeat path and the per-kind grant path.
10992
+ */
10993
+ recordExtension(subagentId, taskId, kind, newLimit) {
10994
+ const total = (this.extendTotals.get(subagentId) ?? 0) + 1;
10995
+ this.extendTotals.set(subagentId, total);
10996
+ this.fleet.emit({
10997
+ subagentId,
10998
+ taskId,
10999
+ ts: Date.now(),
11000
+ type: "budget.extended",
11001
+ payload: { kind, newLimit, totalExtensions: total }
11002
+ });
11003
+ }
11004
+ /** Cumulative auto-extension count for one subagent (0 when never extended). */
11005
+ extensionsFor(subagentId) {
11006
+ return this.extendTotals.get(subagentId) ?? 0;
11007
+ }
8530
11008
  /** Best-effort session-writer append. Swallows failures — the director
8531
11009
  * must not break a fleet run because the session JSONL handle closed. */
8532
11010
  async appendSessionEvent(event) {
@@ -8580,11 +11058,7 @@ var Director = class {
8580
11058
  }
8581
11059
  }
8582
11060
  let result;
8583
- try {
8584
- result = await this.coordinator.spawn(config);
8585
- } catch (err) {
8586
- throw err;
8587
- }
11061
+ result = await this.coordinator.spawn(config);
8588
11062
  if (this.fleetManager) {
8589
11063
  this.fleetManager.recordSpawn(result.subagentId, config, priceLookup);
8590
11064
  } else {
@@ -8856,7 +11330,14 @@ var Director = class {
8856
11330
  await this.coordinator.remove(subagentId);
8857
11331
  }
8858
11332
  status() {
8859
- return this.coordinator.getStatus();
11333
+ const base = this.coordinator.getStatus();
11334
+ return {
11335
+ ...base,
11336
+ subagents: base.subagents.map((s) => ({
11337
+ ...s,
11338
+ extensions: this.extendTotals.get(s.id) ?? 0
11339
+ }))
11340
+ };
8860
11341
  }
8861
11342
  /**
8862
11343
  * Subscribe to coordinator events. Currently only `task.completed` is
@@ -9140,9 +11621,8 @@ function createDelegateTool(opts) {
9140
11621
  cfg.maxToolCalls = i.maxToolCalls;
9141
11622
  }
9142
11623
  const SUBAGENT_TIMEOUT_BUFFER_MS = opts.subagentTimeoutBufferMs ?? 6e4;
9143
- const desiredSubTimeout = Math.max(3e4, timeoutMs - SUBAGENT_TIMEOUT_BUFFER_MS);
9144
- if (!cfg.timeoutMs || cfg.timeoutMs > desiredSubTimeout) {
9145
- cfg.timeoutMs = desiredSubTimeout;
11624
+ if (!cfg.timeoutMs) {
11625
+ cfg.timeoutMs = Math.max(3e4, timeoutMs - SUBAGENT_TIMEOUT_BUFFER_MS);
9146
11626
  }
9147
11627
  const subagentId = await director.spawn(cfg);
9148
11628
  const taskId = await director.assign({
@@ -9150,15 +11630,30 @@ function createDelegateTool(opts) {
9150
11630
  description: i.task,
9151
11631
  subagentId
9152
11632
  });
9153
- const result = await Promise.race([
9154
- director.awaitTasks([taskId]).then((r) => {
9155
- if (!r[0]) throw new Error(`Task "${taskId}" not found in completed results`);
9156
- return r[0];
9157
- }),
9158
- new Promise(
9159
- (resolve2) => setTimeout(() => resolve2({ __timeout: true }), timeoutMs)
9160
- )
9161
- ]);
11633
+ const dir = director;
11634
+ const result = await new Promise((resolve2) => {
11635
+ let settled = false;
11636
+ let timer;
11637
+ const finish = (value) => {
11638
+ if (settled) return;
11639
+ settled = true;
11640
+ if (timer) clearTimeout(timer);
11641
+ offTool();
11642
+ offIter();
11643
+ resolve2(value);
11644
+ };
11645
+ const arm = () => {
11646
+ if (timer) clearTimeout(timer);
11647
+ timer = setTimeout(() => finish({ __timeout: true }), timeoutMs);
11648
+ };
11649
+ const bump = (e) => {
11650
+ if (e.subagentId === subagentId) arm();
11651
+ };
11652
+ const offTool = dir.fleet.filter("tool.executed", bump);
11653
+ const offIter = dir.fleet.filter("iteration.started", bump);
11654
+ arm();
11655
+ dir.awaitTasks([taskId]).then((r) => finish(r[0] ?? { __timeout: true })).catch(() => finish({ __timeout: true }));
11656
+ });
9162
11657
  if ("__timeout" in result) {
9163
11658
  const partial2 = await readSubagentPartial(opts, subagentId);
9164
11659
  return {
@@ -9324,7 +11819,6 @@ async function readSubagentPartial(opts, subagentId) {
9324
11819
  }
9325
11820
  }
9326
11821
  } catch {
9327
- continue;
9328
11822
  }
9329
11823
  }
9330
11824
  return {
@@ -9363,6 +11857,64 @@ function makeDirectorSessionFactory(opts) {
9363
11857
  };
9364
11858
  }
9365
11859
 
11860
+ // src/coordination/auto-extend.ts
11861
+ var DEFAULT_CEILING = {
11862
+ maxIterations: 5e4,
11863
+ maxToolCalls: 1e5,
11864
+ maxTokens: 5e6,
11865
+ maxCostUsd: 100,
11866
+ timeoutMs: 24 * 60 * 60 * 1e3
11867
+ };
11868
+ var FIELD_BY_KIND = {
11869
+ iterations: "maxIterations",
11870
+ tool_calls: "maxToolCalls",
11871
+ tokens: "maxTokens",
11872
+ cost: "maxCostUsd",
11873
+ timeout: "timeoutMs"
11874
+ };
11875
+ function attachAutoExtend(events, policy = {}) {
11876
+ const factor = policy.factor ?? 0.5;
11877
+ const maxPerKind = policy.maxExtensionsPerKind ?? 8;
11878
+ const ceiling = { ...DEFAULT_CEILING, ...policy.ceiling };
11879
+ const extendCounts = /* @__PURE__ */ new Map();
11880
+ let progress = 0;
11881
+ let lastTimeoutProgress = -1;
11882
+ const unsubs = [
11883
+ events.on("tool.executed", () => {
11884
+ progress++;
11885
+ }),
11886
+ events.on("iteration.started", () => {
11887
+ progress++;
11888
+ }),
11889
+ events.on("budget.threshold_reached", (e) => {
11890
+ const { kind, limit, extend, deny } = e;
11891
+ if (kind === "timeout") {
11892
+ if (progress > lastTimeoutProgress) {
11893
+ lastTimeoutProgress = progress;
11894
+ const next2 = Math.min(Math.ceil(limit * (1 + factor)), ceiling.timeoutMs);
11895
+ extend({ timeoutMs: next2 });
11896
+ } else {
11897
+ deny();
11898
+ }
11899
+ return;
11900
+ }
11901
+ const count = extendCounts.get(kind) ?? 0;
11902
+ if (count >= maxPerKind) {
11903
+ deny();
11904
+ return;
11905
+ }
11906
+ extendCounts.set(kind, count + 1);
11907
+ const field = FIELD_BY_KIND[kind];
11908
+ const cap = ceiling[field];
11909
+ const next = Math.min(Math.ceil(limit * (1 + factor)), cap);
11910
+ extend({ [field]: next });
11911
+ })
11912
+ ];
11913
+ return () => {
11914
+ for (const u of unsubs) u();
11915
+ };
11916
+ }
11917
+
9366
11918
  // src/coordination/null-fleet-bus.ts
9367
11919
  var NULL_FLEET_BUS = new FleetBus();
9368
11920
 
@@ -13074,6 +15626,7 @@ function createContextManagerTool(opts = {}) {
13074
15626
  };
13075
15627
  }
13076
15628
  const report = await opts.compactor.compact(ctx);
15629
+ ctx.clearFileTracking();
13077
15630
  const repair = applyMessages([...ctx.messages]);
13078
15631
  const afterTokens = repair.changed ? roughEstimate(ctx.messages) : report.after;
13079
15632
  const repaired = report.repaired ?? (repair.changed ? repair : void 0);
@@ -13102,6 +15655,7 @@ function createContextManagerTool(opts = {}) {
13102
15655
  }
13103
15656
  const copy = [...messages];
13104
15657
  const removed = copy.splice(from, to - from + 1);
15658
+ ctx.clearFileTracking();
13105
15659
  const repair = applyMessages(copy);
13106
15660
  const afterTokens = roughEstimate(ctx.messages);
13107
15661
  return {
@@ -13159,6 +15713,7 @@ function createContextManagerTool(opts = {}) {
13159
15713
  };
13160
15714
  const copy = [...messages];
13161
15715
  copy.splice(from, to - from + 1, summaryMsg);
15716
+ ctx.clearFileTracking();
13162
15717
  const repair = applyMessages(copy);
13163
15718
  const afterTokens = roughEstimate(ctx.messages);
13164
15719
  return {
@@ -13313,6 +15868,6 @@ var allServers = () => ({
13313
15868
  "minimax-vision": { ...miniMaxVisionServer(), enabled: false }
13314
15869
  });
13315
15870
 
13316
- export { AISpecBuilder, ALL_FLEET_AGENTS, AUDIT_LOG_AGENT, AutoApprovePermissionPolicy, AutoCompactionMiddleware, AutoExecutor, AutonomousRunner, BUG_HUNTER_AGENT, BudgetExceededError, ConfigMigrationError, DEFAULT_CONFIG_MIGRATIONS, DEFAULT_CONTEXT_CONFIG, DEFAULT_DIRECTOR_PREAMBLE, DEFAULT_SUBAGENT_BASELINE, DEFAULT_TOOLS_CONFIG, DefaultAttachmentStore, DefaultConfigLoader, DefaultConfigStore, DefaultErrorHandler, DefaultHealthRegistry, DefaultLogger, DefaultMemoryStore, DefaultModeStore, DefaultModelsRegistry, DefaultMultiAgentCoordinator, DefaultPermissionPolicy, DefaultProviderRunner, DefaultRetryPolicy, DefaultSecretScrubber, DefaultSecretVault, DefaultSessionReader, DefaultSessionStore, DefaultSkillLoader, DefaultTaskStore, Director, DirectorStateCheckpoint, DoneConditionChecker, EternalAutonomyEngine, FLEET_ROSTER, FLEET_ROSTER_BUDGETS, FleetBus, FleetSpawnBudgetError, FleetUsageAggregator, HybridCompactor, InMemoryAgentBridge, InMemoryBridgeTransport, InMemoryMetricsSink, IntelligentCompactor, LLMSelector, NULL_FLEET_BUS, NoopMetricsSink, NoopTracer, OTelTracer, PROMETHEUS_CONTENT_TYPE, ParallelEternalEngine, QueueStore, REFACTOR_PLANNER_AGENT, RecoveryLock, SECURITY_SCANNER_AGENT, SPEC_TEMPLATES, SelectiveCompactor, SessionAnalyzer, SpecDrivenDev, SpecParser, SpecStore, SpecVersioning, SubagentBudget, TaskFlow, TaskGenerator, TaskGraphStore, TaskTracker, ToolExecutor, addPlanItem, allServers, analyzeCriticalPath, applyRosterBudget, attachPlanCheckpoint, attachTodosCheckpoint, awsServer, blockServer, braveSearchServer, buildGoalPreamble, buildOtlpMetricsRequest, buildOtlpTracesRequest, classifyFamily, clearPlan, composeDirectorPrompt, composeSubagentPrompt, context7Server, contextManagerTool, createAutoExecutor, createContextManagerTool, createDelegateTool, createMessage, decryptConfigSecrets2 as decryptConfigSecrets, deriveTodosFromPlanItem, emptyPlan, encryptConfigSecrets, everArtServer, filesystemServer, formatPlan, formatPlanTemplates, getPlanTemplate, getTemplate, githubServer, googleMapsServer, listPlanTemplates, listTemplates, loadDirectorState, loadPlan, loadProjectModes, loadTodosCheckpoint, loadUserModes, makeAgentSubagentRunner, makeAutonomyPromptContributor, makeDirectorSessionFactory, migratePlaintextSecrets, miniMaxVisionServer, removePlanItem, renderProgress, renderPrometheus, renderSpecAnalysis, renderTaskGraph, renderTaskList, rewriteConfigEncrypted, rosterSummaryFromConfigs, runConfigMigrations, savePlan, saveTodosCheckpoint, sentinelServer, setPlanItemStatus, slackServer, startMetricsServer, startOtlpMetricsExporter, startOtlpTraceExporter, templateToMarkdown, wireMetricsToEvents, zaiVisionServer };
15871
+ export { AGENTS_BY_PHASE, AGENT_CATALOG, AISpecBuilder, ALL_AGENT_DEFINITIONS, ALL_FLEET_AGENTS, AUDIT_LOG_AGENT, AutoApprovePermissionPolicy, AutoCompactionMiddleware, AutoExecutor, AutonomousRunner, BUG_HUNTER_AGENT, BudgetExceededError, ConfigMigrationError, DEFAULT_CONFIG_MIGRATIONS, DEFAULT_CONTEXT_CONFIG, DEFAULT_DIRECTOR_PREAMBLE, DEFAULT_DISPATCH_ROLE, DEFAULT_SUBAGENT_BASELINE, DEFAULT_TOOLS_CONFIG, DefaultAttachmentStore, DefaultConfigLoader, DefaultConfigStore, DefaultErrorHandler, DefaultHealthRegistry, DefaultLogger, DefaultMemoryStore, DefaultModeStore, DefaultModelsRegistry, DefaultMultiAgentCoordinator, DefaultPermissionPolicy, DefaultProviderRunner, DefaultRetryPolicy, DefaultSecretScrubber, DefaultSecretVault, DefaultSessionReader, DefaultSessionStore, DefaultSkillLoader, DefaultTaskStore, Director, DirectorStateCheckpoint, DoneConditionChecker, EternalAutonomyEngine, FLEET_ROSTER, FLEET_ROSTER_BUDGETS, FleetBus, FleetSpawnBudgetError, FleetUsageAggregator, HybridCompactor, InMemoryAgentBridge, InMemoryBridgeTransport, InMemoryMetricsSink, IntelligentCompactor, LLMSelector, NULL_FLEET_BUS, NoopMetricsSink, NoopTracer, OTelTracer, PROMETHEUS_CONTENT_TYPE, ParallelEternalEngine, QueueStore, REFACTOR_PLANNER_AGENT, RecoveryLock, SECURITY_SCANNER_AGENT, SPEC_TEMPLATES, SelectiveCompactor, SessionAnalyzer, SpecDrivenDev, SpecParser, SpecStore, SpecVersioning, SubagentBudget, TaskFlow, TaskGenerator, TaskGraphStore, TaskTracker, ToolExecutor, addPlanItem, allServers, analyzeCriticalPath, applyRosterBudget, attachAutoExtend, attachPlanCheckpoint, attachTodosCheckpoint, awsServer, blockServer, braveSearchServer, buildGoalPreamble, buildOtlpMetricsRequest, buildOtlpTracesRequest, classifyFamily, clearPlan, composeDirectorPrompt, composeSubagentPrompt, context7Server, contextManagerTool, createAutoExecutor, createContextManagerTool, createDelegateTool, createMessage, decryptConfigSecrets2 as decryptConfigSecrets, deriveTodosFromPlanItem, dispatchAgent, emptyPlan, encryptConfigSecrets, everArtServer, filesystemServer, formatPlan, formatPlanTemplates, getAgentDefinition, getPlanTemplate, getTemplate, githubServer, googleMapsServer, listPlanTemplates, listTemplates, loadDirectorState, loadPlan, loadProjectModes, loadTodosCheckpoint, loadUserModes, makeAgentSubagentRunner, makeAutonomyPromptContributor, makeDirectorSessionFactory, makeLLMClassifier, migratePlaintextSecrets, miniMaxVisionServer, removePlanItem, renderProgress, renderPrometheus, renderSpecAnalysis, renderTaskGraph, renderTaskList, rewriteConfigEncrypted, rosterSummaryFromConfigs, runConfigMigrations, savePlan, saveTodosCheckpoint, scoreAgents, sentinelServer, setPlanItemStatus, slackServer, startMetricsServer, startOtlpMetricsExporter, startOtlpTraceExporter, templateToMarkdown, wireMetricsToEvents, zaiVisionServer };
13317
15872
  //# sourceMappingURL=index.js.map
13318
15873
  //# sourceMappingURL=index.js.map