# Code coverage report for src/agent/file-io.ts

# All files / src/agent file-io.ts

76.61% Statements 95/124
69.76% Branches 60/86
100% Functions 14/14
76.27% Lines 90/118

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377

    101x

    5x
    5x
    20x
    19x

    19x

    19x

    19x

    5x
    5x
    1x
    1x

    5x

    5x
    5x

    5x

    5x

    5x
    1x
    1x

    1x
    1x

    5x
    1x
    1x

    1x
    2x
    2x

    2x

    2x
    2x
    2x

    5x
    1x
    1x
    1x
    1x
    1x

    1x

    1x
    1x

    5x
    1x
    1x

    1x
    1x

    5x

    5x

    5x

    5x

    14x
    14x
    14x
    14x

    4x

    14x

    7x
    7x
    7x
    7x
    8x
    7x
    7x
    7x
    7x
    7x

    7x

    7x
    7x
    7x

    3x
    3x

    3x
    3x
    2x
    2x
    2x

    3x
    3x
    2x
    2x
    2x

    2x
    2x
    1x
    1x

    6x
    6x
    2x
    2x

     /**
     * File-Based Agent I/O
     *
     * Writes context as input files before agent spawn and reads output files after completion.
     * Uses YAML frontmatter (gray-matter) for structured metadata and markdown bodies.
     *
     * Input: .cw/input/ — written by system before spawn
     * Output: .cw/output/ — written by agent during execution
     */

    import { mkdirSync, writeFileSync, readdirSync, existsSync } from 'node:fs';
    import { readFileSync } from 'node:fs';
    import { join } from 'node:path';
    import matter from 'gray-matter';
    import { nanoid } from 'nanoid';
    import { tiptapJsonToMarkdown } from './content-serializer.js';
    import type { AgentInputContext } from './types.js';

    // Re-export for convenience
    export type { AgentInputContext } from './types.js';

    // =============================================================================
    // TYPES
    // =============================================================================

    export interface WriteInputFilesOptions extends AgentInputContext {
      agentWorkdir: string;
    }

    export interface ParsedSummary {
      body: string;
      filesModified?: string[];
    }

    export interface ParsedPhaseFile {
      id: string;
      title: string;
      dependencies: string[];
      body: string;
    }

    export interface ParsedTaskFile {
      id: string;
      title: string;
      category: string;
      type: string;
      dependencies: string[];
      body: string;
    }

    export interface ParsedDecisionFile {
      id: string;
      topic: string;
      decision: string;
      reason: string;
      body: string;
    }

    export interface ParsedPageFile {
      pageId: string;
      title: string;
      summary: string;
      body: string;
    }

    // =============================================================================
    // ID GENERATION
    // =============================================================================

    export function generateId(): string {
      return nanoid();
    }

    // =============================================================================
    // INPUT FILE WRITING
    // =============================================================================

    function formatFrontmatter(data: Record<string, unknown>, body: string = ''): string {
      const lines: string[] = ['---'];
      for (const [key, value] of Object.entries(data)) {
        if (value === undefined || value === null) continue;
        Iif (Array.isArray(value)) {
          if (value.length === 0) {
            lines.push(`${key}: []`);
          } else {
            lines.push(`${key}:`);
            for (const item of value) {
              lines.push(`  - ${String(item)}`);
            }
          }
        I} else if (value instanceof Date) {
          lines.push(`${key}: "${value.toISOString()}"`);
        I} else if (typeof value === 'string' && (value.includes('\n') || value.includes(':'))) {
          lines.push(`${key}: ${JSON.stringify(value)}`);
        } else {
          lines.push(`${key}: ${String(value)}`);
        }
      }
      lines.push('---');
      if (body) {
        lines.push('');
        lines.push(body);
      }
      return lines.join('\n') + '\n';
    }

    export function writeInputFiles(options: WriteInputFilesOptions): void {
      const inputDir = join(options.agentWorkdir, '.cw', 'input');
      mkdirSync(inputDir, { recursive: true });

      // Write expected working directory marker for verification
      writeFileSync(
        join(inputDir, '../expected-pwd.txt'),
        options.agentWorkdir,
        'utf-8'
      );

      const manifestFiles: string[] = [];

      if (options.initiative) {
        const ini = options.initiative;
        const content = formatFrontmatter(
          {
            id: ini.id,
            name: ini.name,
            status: ini.status,
            mergeRequiresApproval: ini.mergeRequiresApproval,
            branch: ini.branch,
          },
          '',
        );
        writeFileSync(join(inputDir, 'initiative.md'), content, 'utf-8');
        manifestFiles.push('initiative.md');
      }

      if (options.pages && options.pages.length > 0) {
        const pagesDir = join(inputDir, 'pages');
        mkdirSync(pagesDir, { recursive: true });

        for (const page of options.pages) {
          let bodyMarkdown = '';
          Iif (page.content) {
            try {
              const parsed = JSON.parse(page.content);
              bodyMarkdown = tiptapJsonToMarkdown(parsed);
            } catch {
              // Invalid JSON content — skip
            }
          }

          const content = formatFrontmatter(
            {
              title: page.title,
              parentPageId: page.parentPageId,
              sortOrder: page.sortOrder,
            },
            bodyMarkdown,
          );
          const filename = `pages/${page.id}.md`;
          writeFileSync(join(pagesDir, `${page.id}.md`), content, 'utf-8');
          manifestFiles.push(filename);
        }
      }

      if (options.phase) {
        const ph = options.phase;
        let bodyMarkdown = '';
        Eif (ph.content) {
          try {
            bodyMarkdown = tiptapJsonToMarkdown(JSON.parse(ph.content));
          } catch {
            // Invalid JSON content — skip
          }
        }
        const content = formatFrontmatter(
          {
            id: ph.id,
            name: ph.name,
            status: ph.status,
          },
          bodyMarkdown,
        );
        writeFileSync(join(inputDir, 'phase.md'), content, 'utf-8');
        manifestFiles.push('phase.md');
      }

      if (options.task) {
        const t = options.task;
        const content = formatFrontmatter(
          {
            id: t.id,
            name: t.name,
            category: t.category,
            type: t.type,
            priority: t.priority,
            status: t.status,
          },
          t.description ?? '',
        );
        writeFileSync(join(inputDir, 'task.md'), content, 'utf-8');
        manifestFiles.push('task.md');
      }

      // Write read-only context directories
      const contextFiles: string[] = [];

      Iif (options.phases && options.phases.length > 0) {
        const phasesDir = join(inputDir, 'context', 'phases');
        mkdirSync(phasesDir, { recursive: true });

        for (const ph of options.phases) {
          let bodyMarkdown = '';
          if (ph.content) {
            try {
              bodyMarkdown = tiptapJsonToMarkdown(JSON.parse(ph.content));
            } catch {
              // Invalid JSON content — skip
            }
          }
          const content = formatFrontmatter(
            {
              id: ph.id,
              name: ph.name,
              status: ph.status,
              dependsOn: ph.dependsOn ?? [],
            },
            bodyMarkdown,
          );
          const filename = `context/phases/${ph.id}.md`;
          writeFileSync(join(phasesDir, `${ph.id}.md`), content, 'utf-8');
          contextFiles.push(filename);
        }
      }

      Iif (options.tasks && options.tasks.length > 0) {
        const tasksDir = join(inputDir, 'context', 'tasks');
        mkdirSync(tasksDir, { recursive: true });

        for (const t of options.tasks) {
          const content = formatFrontmatter(
            {
              id: t.id,
              name: t.name,
              phaseId: t.phaseId,
              parentTaskId: t.parentTaskId,
              category: t.category,
              type: t.type,
              priority: t.priority,
              status: t.status,
            },
            t.description ?? '',
          );
          const filename = `context/tasks/${t.id}.md`;
          writeFileSync(join(tasksDir, `${t.id}.md`), content, 'utf-8');
          contextFiles.push(filename);
        }
      }

      // Write manifest listing exactly which files were created
      writeFileSync(
        join(inputDir, 'manifest.json'),
        JSON.stringify({
          files: manifestFiles,
          contextFiles,
          agentId: options.agentId ?? null,
          agentName: options.agentName ?? null,
        }) + '\n',
        'utf-8',
      );
    }

    // =============================================================================
    // OUTPUT FILE READING
    // =============================================================================

    export function readFrontmatterFile(filePath: string): { data: Record<string, unknown>; body: string } | null {
      try {
        const raw = readFileSync(filePath, 'utf-8');
        const parsed = matter(raw);
        return { data: parsed.data as Record<string, unknown>, body: parsed.content.trim() };
      } catch {
        return null;
      }
    }

    function readFrontmatterDir<T>(
      dirPath: string,
      mapper: (data: Record<string, unknown>, body: string, filename: string) => T | null,
    ): T[] {
      if (!existsSync(dirPath)) return [];

      const results: T[] = [];
      try {
        const entries = readdirSync(dirPath);
        for (const entry of entries) {
          if (!entry.endsWith('.md')) continue;
          const filePath = join(dirPath, entry);
          const parsed = readFrontmatterFile(filePath);
          Iif (!parsed) continue;
          const mapped = mapper(parsed.data, parsed.body, entry);
          Eif (mapped) results.push(mapped);
        }
      } catch {
        // Directory read error — return empty
      }
      return results;
    }

    export function readSummary(agentWorkdir: string): ParsedSummary | null {
      const filePath = join(agentWorkdir, '.cw', 'output', 'SUMMARY.md');
      const parsed = readFrontmatterFile(filePath);
      if (!parsed) return null;

      const filesModified = parsed.data.files_modified;
      return {
        body: parsed.body,
        filesModified: Array.isArray(filesModified) ? filesModified.map(String) : undefined,
      };
    }

    export function readPhaseFiles(agentWorkdir: string): ParsedPhaseFile[] {
      const dirPath = join(agentWorkdir, '.cw', 'output', 'phases');
      return readFrontmatterDir(dirPath, (data, body, filename) => {
        const id = filename.replace(/\.md$/, '');
        const deps = Array.isArray(data.dependencies) ? data.dependencies.map(String) : [];
        return {
          id,
          title: String(data.title ?? ''),
          dependencies: deps,
          body,
        };
      });
    }

    export function readTaskFiles(agentWorkdir: string): ParsedTaskFile[] {
      const dirPath = join(agentWorkdir, '.cw', 'output', 'tasks');
      return readFrontmatterDir(dirPath, (data, body, filename) => {
        const id = filename.replace(/\.md$/, '');
        const deps = Array.isArray(data.dependencies) ? data.dependencies.map(String) : [];
        return {
          id,
          title: String(data.title ?? ''),
          category: String(data.category ?? 'execute'),
          type: String(data.type ?? 'auto'),
          dependencies: deps,
          body,
        };
      });
    }

    export function readDecisionFiles(agentWorkdir: string): ParsedDecisionFile[] {
      const dirPath = join(agentWorkdir, '.cw', 'output', 'decisions');
      return readFrontmatterDir(dirPath, (data, body, filename) => {
        const id = filename.replace(/\.md$/, '');
        return {
          id,
          topic: String(data.topic ?? ''),
          decision: String(data.decision ?? ''),
          reason: String(data.reason ?? ''),
          body,
        };
      });
    }

    export function readPageFiles(agentWorkdir: string): ParsedPageFile[] {
      const dirPath = join(agentWorkdir, '.cw', 'output', 'pages');
      return readFrontmatterDir(dirPath, (data, body, filename) => {
        const pageId = filename.replace(/\.md$/, '');
        return {
          pageId,
          title: String(data.title ?? ''),
          summary: String(data.summary ?? ''),
          body,
        };
      });
    }