"""Run with owned server stopped. Instrument a fresh synthetic DB and optionally seed one stop."""
import sys, pathlib, sqlite3, datetime, json
db, row, thread = sys.argv[1:4]
assert str(pathlib.Path(db).resolve()).startswith(('/home/ubuntu/wt/pr-25675-before/.t3/', '/home/ubuntu/wt/pr-25675-after/.t3/'))
conn = sqlite3.connect(db)
cols = [r[1] for r in conn.execute('PRAGMA table_info(orchestration_v2_effect_outbox)')]
conn.execute('CREATE TABLE evidence_outbox_audit (seq INTEGER PRIMARY KEY AUTOINCREMENT, recorded_at TEXT, operation TEXT, row_json TEXT)')
for op in ('INSERT', 'UPDATE'):
    args = ', '.join("'%s', NEW.%s" % (c, c) for c in cols)
    conn.execute(f"""CREATE TRIGGER evidence_outbox_{op.lower()} AFTER {op} ON orchestration_v2_effect_outbox BEGIN
      INSERT INTO evidence_outbox_audit(recorded_at,operation,row_json) VALUES(strftime('%Y-%m-%dT%H:%M:%fZ','now'),'{op}',json_object({args})); END""")
args = ', '.join("'%s', %s" % (c, c) for c in cols)
conn.execute(f"INSERT INTO evidence_outbox_audit(recorded_at,operation,row_json) SELECT strftime('%Y-%m-%dT%H:%M:%fZ','now'),'INITIAL',json_object({args}) FROM orchestration_v2_effect_outbox")
if row in ('R1', 'R2', 'R4', 'R5'):
    now = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='milliseconds').replace('+00:00','Z')
    conn.execute('''INSERT INTO orchestration_v2_effect_outbox
      (effect_id,command_id,thread_id,effect_type,payload_json,status,attempt_count,available_at,created_at,updated_at)
      VALUES(?,?,?,'delegated-tasks.stop',?,'pending',0,?,?,?)''',
      (f'effect:evidence:{row}:stop',f'command:evidence:{row}:stop',thread,json.dumps({'type':'delegated-tasks.stop','reason':f'EVIDENCE:{row}'}),now,now,now))
conn.commit()
print(json.dumps({'at':datetime.datetime.now(datetime.timezone.utc).isoformat(), 'row':row,'threadId':thread,'database':db,'seed':'one pending stop' if row in ('R1', 'R2', 'R4', 'R5') else 'audit triggers only; no outbox row inserted','instrumentation':'append-only audit triggers; no worker/outbox-row policy changes'}))
