import pathlib,sys
root=pathlib.Path(sys.argv[1]); control=pathlib.Path(sys.argv[2])
p=root/'packages/effect-codex-app-server/src/protocol.ts'
s=p.read_text()
s='import { readFileSync, appendFileSync } from "node:fs";\n'+s
s=s.replace('const EXIT_STATUS_GRACE = "250 millis";', '''const EXIT_STATUS_GRACE = "250 millis";
const faultMode = () => { try { return readFileSync(process.env.T3_FAULT_DIR + "/mode", "utf8").trim(); } catch { return "none"; } };
const fault = (kind: string) => { appendFileSync(process.env.T3_FAULT_DIR + "/faults.jsonl", JSON.stringify({at:new Date().toISOString(),kind})+"\\n"); return Effect.die(new Error("private-fault-sentinel")); };
''')
s=s.replace('const protocolScope = yield* Scope.Scope;', 'let fired = false;\n    const protocolScope = yield* Scope.Scope;')
s=s.replace('const handler = options.onRequest;', '''const handler = faultMode() === "approval" && request.method === "item/commandExecution/requestApproval" && !fired
            ? (_request: unknown) => { fired = true; return fault("approval"); }
            : options.onRequest;''')
s=s.replace('Effect.andThen(options.onNotification ? options.onNotification(notification) : Effect.void)', '''Effect.andThen(() => {
          if (faultMode() === "notify" && notification.method === "item/started" && !fired) { fired = true; return fault("notify"); }
          return options.onNotification ? options.onNotification(notification) : Effect.void;
        })''')
s=s.replace('yield* options.stdio.stdin.pipe(', '''yield* options.stdio.stdin.pipe(
      Stream.takeUntil((chunk) => {
        if (faultMode() === "exit" && !fired && Buffer.from(chunk).toString().includes('"method":"item/started"')) { fired = true; return true; }
        return false;
      }),''')
s=s.replace('options.terminationError.pipe(', '(faultMode() === "exit" ? fault("exit") : options.terminationError).pipe(')
s=s.replace('yield* Stream.fromQueue(outgoing).pipe(', '''yield* Stream.fromQueue(outgoing).pipe(
      Stream.mapEffect((line) => {
        if (faultMode() === "writer" && line.includes('"method":"turn/start"') && !fired) { fired = true; return fault("writer"); }
        return Effect.succeed(line);
      }),''')
# Record raw wire events independently of optional protocol logging.
s=s.replace('const logProtocol = (event: CodexAppServerProtocolLogEvent) => {', '''const logProtocol = (event: CodexAppServerProtocolLogEvent) => {
      if (event.stage === "decoded") appendFileSync(process.env.T3_FAULT_DIR + "/wire.jsonl", JSON.stringify({at:new Date().toISOString(), ...event})+"\\n");''')
p.write_text(s)
print('Injected identical fault hooks')
