buildContext method

String buildContext({
  1. bool includeLocal = true,
  2. bool includeTeam = true,
  3. bool includeRules = true,
  4. int? maxTokens,
})

Build the combined memory context for the system prompt.

Implementation

String buildContext({
  bool includeLocal = true,
  bool includeTeam = true,
  bool includeRules = true,
  int? maxTokens,
}) {
  final buffer = StringBuffer();
  final sorted = _files.values.toList()
    ..sort((a, b) {
      // Order: project NEOMAGE.md first, then parent dirs, then rules, then team, then local.
      final typeOrder = {
        MemoryFileType.neomageMd: 0,
        MemoryFileType.ruleset: 1,
        MemoryFileType.teamMd: 2,
        MemoryFileType.neomageLocalMd: 3,
      };
      return (typeOrder[a.type] ?? 99).compareTo(typeOrder[b.type] ?? 99);
    });

  for (final file in sorted) {
    if (!includeLocal && file.type == MemoryFileType.neomageLocalMd) {
      continue;
    }
    if (!includeTeam && file.type == MemoryFileType.teamMd) continue;
    if (!includeRules && file.type == MemoryFileType.ruleset) continue;

    buffer.writeln('<!-- ${file.path} -->');
    buffer.writeln(file.content);
    buffer.writeln();

    // Check token budget (rough estimate: ~4 chars per token).
    if (maxTokens != null && buffer.length ~/ 4 > maxTokens) {
      buffer.writeln('<!-- truncated: token budget exceeded -->');
      break;
    }
  }

  return buffer.toString().trim();
}