#!/usr/bin/env bash
# Issue #24711: a t3_thread_send from another thread's agent reaches the receiving model as a bare user turn.
# Claim: already fixed by #39306 (b0b2c4f952). The provider-bound text of an agent-sent message now starts
# with a line naming the sending thread, on new turns (ProviderTurnStartService), steers
# (ProviderTurnControlService) and history handoffs (handoffBudget).
# Shows: before #39306 a steer that another thread's agent sent reaches the provider as the bare body;
# on main the same steer reaches it with the sender line, and the body follows unchanged.
# Needs deps installed (`vp i`). Run from the root of a clean t3code checkout.
set -euo pipefail

ok=1
pass() { echo "PASS  $*"; }
fail() { echo "FAIL  $*"; ok=0; }

if [ -n "$(git status --porcelain)" ]; then
  echo "refusing to run on a dirty tree"
  exit 2
fi
ORIG=$(git symbolic-ref -q --short HEAD || git rev-parse HEAD)
TEST=apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts
LOG=$(mktemp)
cleanup() {
  git checkout -q -- "$TEST" 2>/dev/null || true
  rm -f "$LOG"
  git checkout -q -f "$ORIG"
}
trap 'rc=$?; cleanup; [ "${PROOF_DONE:-0}" = 1 ] && exit 0; [ "$rc" -ne 0 ] && exit "$rc"; exit 1' EXIT

git fetch -q origin main
MAIN=$(git rev-parse FETCH_HEAD)
FIX=b0b2c4f952d3a12a886e915ad8ffe7e82ebc1fb4
BEFORE=$(git rev-parse "$FIX^")
echo "main=$MAIN fix=$FIX before=$BEFORE"

subject=$(git log -1 --format=%s "$FIX")
if git merge-base --is-ancestor "$FIX" "$MAIN" \
  && [ "$subject" = "fix(server): agents can tell another agent's message from the user's (#39306)" ]; then
  pass "#39306 ($(git rev-parse --short "$FIX")) is on main: $subject"
else
  fail "#39306 is not on main, or $FIX is a different commit ($subject)"
fi

# The three places that build provider-bound user text all apply the sender line on main.
start=$(git show "${MAIN}:apps/server/src/orchestration-v2/ProviderTurnStartService.ts" | grep -c 'withMessageSenderNote(' || true)
steer=$(git show "${MAIN}:apps/server/src/orchestration-v2/ProviderTurnControlService.ts" | grep -c 'withMessageSenderNote(' || true)
handoff=$(git show "${MAIN}:packages/provider-core/src/server/handoffBudget.ts" | grep -c 'withMessageSenderNote(' || true)
if [ "$start" -gt 0 ] && [ "$steer" -gt 0 ] && [ "$handoff" -gt 0 ]; then
  pass "main: new turns (ProviderTurnStartService), steers (ProviderTurnControlService) and history handoffs (handoffBudget) pass user text through withMessageSenderNote"
else
  fail "main: a provider-text path no longer applies withMessageSenderNote (start=$start steer=$steer handoff=$handoff)"
fi

# Same harness as the file's own "steers a running turn with ... MCP app model context" case.
append_test() {
  cat >> "$TEST" <<'EOF'

it.effect("prove-issue-24711", () =>
  Effect.gen(function* () {
    const now = yield* DateTime.now;
    const threadId = ThreadId.make("thread:parent");
    const sessionId = ProviderSessionId.make("provider-session:prove-24711");
    const providerTurnId = ProviderTurnId.make("provider-turn:prove-24711");
    const attemptId = RunAttemptId.make("run-attempt:prove-24711");
    const providerThread = {
      id: ProviderThreadId.make("provider-thread:prove-24711"),
      driver,
      providerInstanceId,
      providerSessionId: sessionId,
    } as OrchestrationV2ProviderThread;
    const projection = makeProjection({ now, threadId, providerThread, providerTurnId, attemptId });
    const steered: Array<ProviderAdapter.ProviderAdapterV2SteerInput> = [];
    const runtime = {
      instanceId: providerInstanceId,
      driver,
      providerSessionId: sessionId,
      steerTurn: (input: ProviderAdapter.ProviderAdapterV2SteerInput) =>
        Effect.sync(() => void steered.push(input)),
    } as unknown as ProviderAdapter.ProviderAdapterV2SessionRuntime;
    // What t3_thread_send stores when the child thread's agent steers the parent.
    const message = {
      id: MessageId.make("message:prove-24711"),
      text: "Please merge the PR now.",
      attachments: [],
      createdBy: "agent",
      creationSource: "mcp",
      senderThreadId: ThreadId.make("thread:child"),
    } as unknown as NonNullable<ProjectionStore.ProjectionProviderControlContext["message"]>;
    const layerControl = ProviderTurnControlService.layer.pipe(
      Layer.provide(
        Layer.mergeAll(
          layerProjectionStore(() =>
            Effect.succeed({
              providerThread,
              providerTurn: projection.providerTurns[0],
              attempt: projection.attempts[0],
              message,
              run: {
                id: RunId.make("run:prove-24711"),
                status: "running",
                activeAttemptId: attemptId,
              } as OrchestrationV2Run,
            }),
          ),
          layerSessions(sessionId, runtime),
          Layer.mock(EventSink.EventSinkV2)({}),
          Layer.mock(McpAppModelContext.McpAppModelContext)({ forThread: () => Effect.succeed([]) }),
        ),
      ),
    );

    yield* Effect.gen(function* () {
      const control = yield* ProviderTurnControlService.ProviderTurnControlServiceV2;
      yield* control.steer({
        threadId,
        providerSessionId: sessionId,
        providerThreadId: providerThread.id,
        providerTurnId,
        messageId: message.id,
      });
    }).pipe(Effect.provide(layerControl));

    assert.equal(steered.length, 1);
    const sent = steered[0]!.message;
    // The stored provenance reaches the adapter on both commits; only the model-visible text differs.
    assert.equal(sent.createdBy, "agent");
    assert.equal(sent.creationSource, "mcp");
    if (process.env.PROOF_EXPECT === "bug") {
      assert.equal(sent.text, "Please merge the PR now.");
    } else {
      assert.equal(
        sent.text,
        '[T3 Code: the agent in T3 thread "thread:child" sent this message, not the user.]\n\nPlease merge the PR now.',
      );
    }
  }),
);
EOF
}

run_at() {
  git checkout -q --detach "$1"
  append_test
  local rc=0
  PROOF_EXPECT="$2" vp test run "$TEST" -t "prove-issue-24711" > "$LOG" 2>&1 || rc=$?
  git checkout -q -- "$TEST"
  if [ "$rc" -eq 0 ] && ! grep -Eq 'Tests +1 passed' "$LOG"; then rc=3; fi
  if [ "$rc" -ne 0 ]; then sed 's#'"$HOME"'#~#g' "$LOG" | tail -25; fi
  return "$rc"
}

if run_at "$BEFORE" bug; then
  pass "before #39306 ($(git rev-parse --short "$BEFORE")): a steer sent by thread:child's agent reaches the provider as the bare text \"Please merge the PR now.\""
else
  fail "before #39306: the agent-sent steer did not reach the provider as the bare text"
fi
if run_at "$MAIN" fixed; then
  pass "main ($(git rev-parse --short "$MAIN")): the same steer reaches the provider as '[T3 Code: the agent in T3 thread \"thread:child\" sent this message, not the user.]' followed by the unchanged text"
else
  fail "main: the agent-sent steer still reaches the provider without the sender line"
fi

if [ "$ok" = 1 ]; then
  echo "VERDICT: #24711 is fixed on main by #39306"
  PROOF_DONE=1; exit 0
fi
echo "VERDICT: not shown"
exit 1
