#!/usr/bin/env node
// Reads stdin line-by-line and writes each line to stdout, injecting a
// wall-clock `timestamp` field into any JSON object that doesn't already
// have one. Non-JSON lines (raw stderr noise, auth-failure text) and JSON
// values that aren't plain objects pass through unchanged.
//
// agent-wrapper.sh pipes the agent CLI's stdout+stderr through this filter
// before appending to /task-output/debug-stream.jsonl, so downstream
// consumers (the snapshot scanner and the SSE forwarder) see real
// timestamps on Claude/Codex events instead of synthesised sequences.

import { createInterface } from 'node:readline';

const rl = createInterface({ input: process.stdin });

rl.on('line', (line) => {
  let out = line;
  try {
    const obj = JSON.parse(line);
    if (obj && typeof obj === 'object' && !Array.isArray(obj) && obj.timestamp === undefined) {
      obj.timestamp = new Date().toISOString();
      out = JSON.stringify(obj);
    }
  } catch {
    // Not JSON — preserve as-is.
  }
  process.stdout.write(out + '\n');
});

rl.on('close', () => {
  process.exit(0);
});
