Răsfoiți Sursa

✅ (api-v13): 新增 AI 对话、积分与管理统计的 Pest 测试

- AgentTraceV3Test:研究过程入库、会话归属、threadId 全局唯一(别人的 403)、重新生成记替换关系、软删后补发不复活
- AgentThreadV3Test:会话历史列表 / 详情 / 改名 / 存档 / 删除(会话、提问、步骤一起软删)
- AgentCreditV3Test:扣费、额度、同 IP 上限、读经 / 编辑换积分、公开积分策略、漏结算补发
- AgentFeedbackV3Test:评价、隐式信号、评价即同意用于改进、管理员审阅、digest(含 full)、软删提问读不到
- AdminStatsV3Test:管理后台阅读 / AI 统计与权限

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
visuddhinanda 4 zile în urmă
părinte
comite
24a2cc2f1d

+ 204 - 0
api-v13/tests/Feature/AdminStatsV3Test.php

@@ -0,0 +1,204 @@
+<?php
+
+use App\Models\AgentRun;
+use App\Models\AgentThread;
+use App\Models\UserInfo;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Str;
+
+uses(RefreshDatabase::class);
+
+/**
+ * v3 管理后台统计(仅 root / administrator):
+ *
+ *   GET /api/v3/admin/reading-stats   阅读统计
+ *   GET /api/v3/admin/agent-stats     AI 对话统计
+ *   GET /api/v3/admin/agent-runs      提问列表
+ *   GET /api/v3/admin/agent-runs/{run}  研究过程
+ *
+ * 这里断言的是形状而非契约(spectator 尚未安装,见 v3-resource skill 第 3 步)。
+ */
+function makeAdmin(string $role = 'administrator'): string
+{
+    $uid = makeStudio('admin-'.Str::random(6));
+    UserInfo::where('userid', $uid)->update(['role' => json_encode([$role, 'member'])]);
+
+    return $uid;
+}
+
+function addRecent(string $user, string $article, string $mode, string $at): void
+{
+    DB::table('recents')->insert([
+        'id' => (string) Str::uuid(), 'type' => 'chapter', 'article_id' => $article,
+        'param' => json_encode(['mode' => $mode]), 'user_uid' => $user, 'created_at' => $at, 'updated_at' => $at,
+    ]);
+}
+
+/* ------------------------------------------------------------------ 权限 */
+
+it('requires login for admin stats', function (string $path) {
+    $this->getJson("/api/v3/admin/{$path}")->assertUnauthorized();
+})->with(['reading-stats', 'agent-stats', 'agent-runs']);
+
+it('forbids non-admin users', function (string $path) {
+    $this->getJson("/api/v3/admin/{$path}", authHeader(makeStudio('plain-'.Str::random(5))))->assertForbidden();
+})->with(['reading-stats', 'agent-stats', 'agent-runs']);
+
+it('lets the root account in', function () {
+    $this->getJson('/api/v3/admin/agent-stats', authHeader(config('mint.admin.root_uuid')))->assertOk();
+});
+
+it('lets administrators in', function () {
+    $this->getJson('/api/v3/admin/reading-stats', authHeader(makeAdmin()))->assertOk();
+});
+
+/* ------------------------------------------------------------------ 区间 */
+
+it('defaults to the last 30 days', function () {
+    $this->getJson('/api/v3/admin/agent-stats', authHeader(makeAdmin()))
+        ->assertOk()
+        ->assertJsonPath('data.range.to', now('UTC')->toDateString())
+        ->assertJsonPath('data.range.from', now('UTC')->subDays(29)->toDateString())
+        ->assertJsonCount(30, 'data.daily');
+});
+
+it('rejects a range longer than 366 days', function () {
+    $this->getJson('/api/v3/admin/reading-stats?from=2024-01-01&to=2026-01-01', authHeader(makeAdmin()))
+        ->assertUnprocessable()
+        ->assertJsonValidationErrors('from');
+});
+
+it('rejects a range that ends before it starts', function () {
+    $this->getJson('/api/v3/admin/reading-stats?from=2026-10-10&to=2026-10-01', authHeader(makeAdmin()))
+        ->assertUnprocessable();
+});
+
+/* ------------------------------------------------------------------ 阅读统计 */
+
+it('counts readers by client and compares with the previous period', function () {
+    $a = makeStudio('r1-'.Str::random(4));
+    $b = makeStudio('r2-'.Str::random(4));
+    addRecent($a, '93-6', 'reading', '2026-10-20 08:00:00');   // App
+    addRecent($a, '93-9', 'reading', '2026-10-21 08:00:00');
+    addRecent($b, '93-6', 'read', '2026-10-21 09:00:00');      // Web
+    addRecent($b, '169-3', 'read', '2026-10-10 09:00:00');     // 上一区间(10-08~10-14)
+    DB::table('reading_dailies')->insert([
+        'user_uid' => $a, 'day' => '2026-10-20', 'seconds' => 1200, 'seconds_reported' => 1500,
+        'created_at' => now(), 'updated_at' => now(),
+    ]);
+
+    $data = $this->getJson('/api/v3/admin/reading-stats?from=2026-10-15&to=2026-10-21', authHeader(makeAdmin()))
+        ->assertOk()->json('data');
+
+    expect($data['summary']['active_readers'])->toBe(2)
+        ->and($data['summary']['chapters_opened'])->toBe(3)
+        ->and($data['summary']['reading_seconds'])->toBe(1200)
+        ->and($data['previous']['active_readers'])->toBe(1)
+        ->and($data['daily'])->toHaveCount(7)
+        ->and(collect($data['daily'])->firstWhere('date', '2026-10-21'))->toMatchArray(['readers_web' => 1, 'readers_mobile' => 1])
+        ->and(collect($data['daily'])->firstWhere('date', '2026-10-20')['reading_minutes'])->toBe(20)
+        ->and($data['top_chapters'][0])->toMatchArray(['article_id' => '93-6', 'readers' => 2])
+        ->and(collect($data['duration_buckets'])->firstWhere('bucket', '15-30')['user_days'])->toBe(1);
+});
+
+it('filters reading stats by client', function () {
+    $a = makeStudio('c1-'.Str::random(4));
+    addRecent($a, '93-6', 'reading', '2026-10-20 08:00:00');
+    addRecent(makeStudio('c2-'.Str::random(4)), '93-6', 'read', '2026-10-20 08:00:00');
+
+    $web = $this->getJson('/api/v3/admin/reading-stats?from=2026-10-20&to=2026-10-20&client=web', authHeader(makeAdmin()))
+        ->assertOk()->json('data');
+
+    expect($web['summary']['active_readers'])->toBe(1)
+        ->and($web['summary']['reading_seconds'])->toBeNull()
+        ->and($web['reading_credits'])->toBeNull();
+});
+
+it('rejects an unknown client', function () {
+    $this->getJson('/api/v3/admin/reading-stats?client=tv', authHeader(makeAdmin()))->assertUnprocessable();
+});
+
+/* ------------------------------------------------------------------ AI 对话统计 */
+
+it('summarises agent runs', function () {
+    $user = (string) Str::uuid();
+    $userThread = AgentThread::factory()->forUser($user)->create();
+    $guestThread = AgentThread::factory()->create();
+    $at = '2026-10-20 10:00:00';
+    AgentRun::factory()->for($userThread, 'thread')->create(['route' => 'term', 'deep' => true, 'latency_ms' => 1000, 'started_at' => $at, 'user_uid' => $user, 'tokens_in' => 100]);
+    AgentRun::factory()->for($userThread, 'thread')->create(['route' => 'passage', 'latency_ms' => 3000, 'started_at' => $at, 'user_uid' => $user]);
+    AgentRun::factory()->for($guestThread, 'thread')->create(['route' => null, 'status' => 'denied', 'latency_ms' => 50, 'started_at' => $at, 'improve' => false]);
+    AgentRun::factory()->for($guestThread, 'thread')->create(['route' => 'question', 'status' => 'ok', 'latency_ms' => 99999, 'started_at' => '2026-09-01 00:00:00']);
+
+    $data = $this->getJson('/api/v3/admin/agent-stats?from=2026-10-20&to=2026-10-20', authHeader(makeAdmin()))
+        ->assertOk()->json('data');
+
+    expect($data['summary'])->toMatchArray([
+        'runs' => 3, 'deep' => 1, 'passage' => 1, 'denied' => 1, 'improve' => 2,
+        'askers' => 2, 'askers_user' => 1, 'askers_guest' => 1, 'latency_p50_ms' => 2000, 'tokens_in' => 100,
+    ])->and($data['daily'][0])->toMatchArray(['term' => 1, 'passage' => 1, 'none' => 1, 'denied' => 1]);
+
+    $users = $this->getJson('/api/v3/admin/agent-stats?from=2026-10-20&to=2026-10-20&account_type=user', authHeader(makeAdmin()))
+        ->json('data.summary.runs');
+    expect($users)->toBe(2);
+});
+
+it('lists tool calls and credit flows', function () {
+    $thread = AgentThread::factory()->create();
+    $run = AgentRun::factory()->for($thread, 'thread')->create(['started_at' => '2026-10-20 10:00:00']);
+    $run->steps()->createMany([
+        ['seq' => 0, 'kind' => 'tool', 'name' => 'wikipali_search', 'ms' => 100],
+        ['seq' => 1, 'kind' => 'tool', 'name' => 'wikipali_search', 'ms' => 300, 'error' => 'boom'],
+        ['seq' => 2, 'kind' => 'event', 'name' => 'quota', 'args' => ['result' => 'unchecked']],
+    ]);
+    DB::table('credit_ledger')->insert([
+        'account' => $thread->account, 'delta' => -10, 'kind' => 'spend', 'bucket' => 'free', 'source' => 'agent_run',
+        'ref' => $run->run_id, 'day' => '2026-10-20', 'policy_version' => 1, 'created_at' => now(), 'updated_at' => now(),
+    ]);
+
+    $data = $this->getJson('/api/v3/admin/agent-stats?from=2026-10-20&to=2026-10-20', authHeader(makeAdmin()))->json('data');
+
+    expect($data['tools'][0])->toMatchArray(['name' => 'wikipali_search', 'calls' => 2, 'errors' => 1, 'avg_ms' => 200])
+        ->and($data['summary']['unchecked'])->toBe(1)
+        ->and($data['credits']['spent_free'])->toBe(10);
+});
+
+/* ------------------------------------------------------------------ 提问列表与研究过程 */
+
+it('lists runs newest first with filters', function () {
+    $thread = AgentThread::factory()->create();
+    AgentRun::factory()->for($thread, 'thread')->create(['question' => '什么是四圣谛?', 'status' => 'ok']);
+    AgentRun::factory()->for($thread, 'thread')->create(['question' => 'What is anatta?', 'status' => 'denied']);
+
+    $admin = authHeader(makeAdmin());
+    $this->getJson('/api/v3/admin/agent-runs', $admin)
+        ->assertOk()
+        ->assertJsonPath('data.0.question', 'What is anatta?')
+        ->assertJsonPath('data.0.account_type', 'guest')
+        ->assertJsonMissingPath('data.0.steps')
+        ->assertJsonPath('meta.total', 2);
+    $this->getJson('/api/v3/admin/agent-runs?filter[status]=ok', $admin)->assertJsonCount(1, 'data');
+    $this->getJson('/api/v3/admin/agent-runs?filter[q]=四圣谛', $admin)->assertJsonCount(1, 'data');
+});
+
+it('shows the full research process of a run', function () {
+    $user = makeStudio('asker-'.Str::random(4));
+    $thread = AgentThread::factory()->forUser($user)->create();
+    $run = AgentRun::factory()->for($thread, 'thread')->create(['user_uid' => $user, 'evidence' => '证据全文']);
+    $run->steps()->create(['seq' => 0, 'kind' => 'route', 'args' => ['route' => 'term']]);
+
+    $this->getJson("/api/v3/admin/agent-runs/{$run->run_id}", authHeader(makeAdmin()))
+        ->assertOk()
+        ->assertJsonPath('data.evidence', '证据全文')
+        ->assertJsonPath('data.steps.0.kind', 'route')
+        ->assertJsonPath('data.user.id', $user);
+});
+
+it('returns 404 for an unknown run', function () {
+    $this->getJson('/api/v3/admin/agent-runs/'.Str::uuid(), authHeader(makeAdmin()))->assertNotFound();
+});
+
+it('rejects an unknown status filter', function () {
+    $this->getJson('/api/v3/admin/agent-runs?filter[status]=weird', authHeader(makeAdmin()))->assertUnprocessable();
+});

+ 418 - 0
api-v13/tests/Feature/AgentCreditV3Test.php

@@ -0,0 +1,418 @@
+<?php
+
+use App\Models\AgentThread;
+use App\Models\AiModel;
+use App\Models\CreditLedgerEntry;
+use App\Models\ReadingDaily;
+use App\Models\UserInfo;
+use App\Models\UserOperationDaily;
+use App\Services\AuthService;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Str;
+
+uses(RefreshDatabase::class);
+
+/**
+ * v3 AI 对话额度与积分(策略在 config mint.credits.policy):
+ *
+ *   POST /api/v3/agent-charges       提问扣费(服务间,X-Agent-Service-Key)
+ *   GET  /api/v3/agent-quota         额度概况(可选登录,游客带 device_id)
+ *   POST /api/v3/me/reading-time     读经时长上报(登录)
+ *   GET  /api/v3/credit-policy    当前积分策略(公开)
+ *   artisan credits:settle-activity / credits:adjust
+ *
+ * v1:游客每日 100、登录 500;普通 10、深度 30;读经 1/分钟每日上限 100;编辑 5/分钟不设上限;
+ * 游客同 IP 每日 500。
+ *
+ * 这里断言的是形状而非契约(spectator 尚未安装,见 v3-resource skill 第 3 步)。
+ */
+beforeEach(function () {
+    config(['mint.app.agent_service_key' => 'test-agent-key']);
+});
+
+function chargeHeaders(?string $userUid = null): array
+{
+    $headers = ['X-Agent-Service-Key' => 'test-agent-key'];
+
+    return $userUid ? $headers + authHeader($userUid) : $headers;
+}
+
+function charge(array $body, ?string $userUid = null, array $headers = [])
+{
+    return test()->postJson('/api/v3/agent-charges', $body + ['run_id' => (string) Str::uuid()], chargeHeaders($userUid) + $headers);
+}
+
+function spendFree(string $account, int $amount, ?string $ip = null): void
+{
+    CreditLedgerEntry::create([
+        'account' => $account, 'delta' => -$amount, 'kind' => 'spend', 'bucket' => 'free',
+        'source' => 'agent_run', 'ref' => (string) Str::uuid(), 'day' => now('UTC')->toDateString(),
+        'policy_version' => 1, 'client_ip' => $ip,
+    ]);
+}
+
+/* ------------------------------------------------------------------ 扣费 */
+
+it('refuses to charge for a thread that belongs to another account', function () {
+    $thread = AgentThread::factory()->create(['account' => 'user:'.Str::uuid()]);
+
+    charge(['device_id' => (string) Str::uuid(), 'thread_id' => $thread->thread_id])->assertForbidden();
+    expect(CreditLedgerEntry::count())->toBe(0);
+});
+
+it('charges for my own thread, deleted or not, and for a new one', function () {
+    $device = (string) Str::uuid();
+    $thread = AgentThread::factory()->create(['account' => 'guest:'.$device, 'user_uid' => null, 'device_id' => $device]);
+    $thread->delete();
+
+    charge(['device_id' => $device, 'thread_id' => $thread->thread_id])->assertCreated();
+    charge(['device_id' => $device, 'thread_id' => (string) Str::uuid()])->assertCreated();
+});
+
+it('requires the service key to charge', function () {
+    $this->postJson('/api/v3/agent-charges', ['run_id' => (string) Str::uuid(), 'device_id' => (string) Str::uuid()])
+        ->assertUnauthorized();
+});
+
+it('gives a guest ten normal questions a day', function () {
+    $device = (string) Str::uuid();
+
+    foreach (range(1, 10) as $i) {
+        charge(['device_id' => $device])->assertCreated()->assertJsonPath('data.free_remaining', 100 - 10 * $i);
+    }
+
+    charge(['device_id' => $device])
+        ->assertStatus(402)
+        ->assertJsonPath('type', fn ($type) => str_ends_with($type, 'quota-exceeded'))
+        ->assertJsonPath('reason', 'insufficient')
+        ->assertJsonPath('cost', 10)
+        ->assertJsonPath('free_remaining', 0);
+});
+
+it('charges a deep question thirty credits', function () {
+    $user = makeStudio('deep-'.Str::random(5));
+
+    charge(['deep' => true], $user)
+        ->assertCreated()
+        ->assertJsonPath('data.cost', 30)
+        ->assertJsonPath('data.charged_free', 30)
+        ->assertJsonPath('data.free_remaining', 470);
+});
+
+it('is idempotent on run_id', function () {
+    $device = (string) Str::uuid();
+    $run = (string) Str::uuid();
+
+    charge(['device_id' => $device, 'run_id' => $run])->assertCreated();
+    charge(['device_id' => $device, 'run_id' => $run])->assertOk()->assertJsonPath('data.cost', 10);
+
+    expect(CreditLedgerEntry::where('ref', $run)->count())->toBe(1);
+});
+
+it('spends daily free first, then earned credits', function () {
+    $user = makeStudio('mix-'.Str::random(5));
+    spendFree('user:'.$user, 490);
+    $this->artisan('credits:adjust', ['user' => $user, 'delta' => 50, '--reason' => 'test'])->assertSuccessful();
+
+    charge(['deep' => true], $user)
+        ->assertCreated()
+        ->assertJsonPath('data.charged_free', 10)
+        ->assertJsonPath('data.charged_earned', 20)
+        ->assertJsonPath('data.free_remaining', 0)
+        ->assertJsonPath('data.earned_balance', 30);
+});
+
+it('caps all guests behind one ip', function () {
+    spendFree('guest:'.Str::uuid(), 490, '198.51.100.9');
+
+    charge(['device_id' => (string) Str::uuid(), 'client_ip' => '198.51.100.9'])->assertCreated();
+    charge(['device_id' => (string) Str::uuid(), 'client_ip' => '198.51.100.9'])
+        ->assertStatus(402)
+        ->assertJsonPath('reason', 'ip_cap');
+    charge(['device_id' => (string) Str::uuid(), 'client_ip' => '198.51.100.10'])->assertCreated();
+});
+
+it('does not apply the ip cap to signed-in users', function () {
+    spendFree('guest:'.Str::uuid(), 500, '198.51.100.9');
+
+    charge(['client_ip' => '198.51.100.9'], makeStudio('ipuser-'.Str::random(5)))->assertCreated();
+});
+
+it('treats a model token as a guest when charging', function () {
+    $human = makeStudio('owner-'.Str::random(5));
+    $model = AiModel::factory()->ownedBy($human)->create();
+
+    $this->postJson('/api/v3/agent-charges', ['run_id' => (string) Str::uuid()], [
+        'X-Agent-Service-Key' => 'test-agent-key',
+        'Authorization' => 'Bearer '.AuthService::getUserToken($model->uid),
+    ])->assertUnprocessable()->assertJsonValidationErrors('device_id');
+});
+
+/* ------------------------------------------------------------------ 退款 */
+
+it('refunds the charge when the run failed without an answer', function () {
+    $device = (string) Str::uuid();
+    $run = (string) Str::uuid();
+    charge(['device_id' => $device, 'run_id' => $run])->assertCreated();
+
+    $this->postJson('/api/v3/agent-traces', [
+        'run_id' => $run, 'thread_id' => (string) Str::uuid(), 'device_id' => $device,
+        'question' => 'q', 'status' => 'error', 'error' => 'boom',
+    ], chargeHeaders())->assertCreated();
+
+    $this->getJson("/api/v3/agent-quota?device_id={$device}")->assertOk()->assertJsonPath('data.free_remaining', 100);
+
+    // 补发同一条研究过程不会退两次
+    $this->postJson('/api/v3/agent-traces', [
+        'run_id' => $run, 'thread_id' => (string) Str::uuid(), 'device_id' => $device,
+        'question' => 'q', 'status' => 'error',
+    ], chargeHeaders())->assertOk();
+    expect(CreditLedgerEntry::where('ref', $run)->where('kind', 'refund')->count())->toBe(1);
+});
+
+it('keeps the charge when the user cancelled', function () {
+    $device = (string) Str::uuid();
+    $run = (string) Str::uuid();
+    charge(['device_id' => $device, 'run_id' => $run])->assertCreated();
+
+    $this->postJson('/api/v3/agent-traces', [
+        'run_id' => $run, 'thread_id' => (string) Str::uuid(), 'device_id' => $device,
+        'question' => 'q', 'status' => 'cancelled',
+    ], chargeHeaders())->assertCreated();
+
+    $this->getJson("/api/v3/agent-quota?device_id={$device}")->assertJsonPath('data.free_remaining', 90);
+});
+
+/* ------------------------------------------------------------------ 额度概况 */
+
+it('shows guest quota without earn rules', function () {
+    $this->getJson('/api/v3/agent-quota?device_id='.Str::uuid())
+        ->assertOk()
+        ->assertJsonPath('data.account_type', 'guest')
+        ->assertJsonPath('data.daily_free', 100)
+        ->assertJsonPath('data.cost.deep', 30)
+        ->assertJsonPath('data.earn', [])
+        ->assertJsonStructure(['data' => ['resets_at', 'policy_version', 'earned_balance', 'earned_today']]);
+});
+
+it('requires a device id for guest quota', function () {
+    $this->getJson('/api/v3/agent-quota')->assertUnprocessable()->assertJsonValidationErrors('device_id');
+});
+
+it('shows user quota with earn rules', function () {
+    $this->getJson('/api/v3/agent-quota', authHeader(makeStudio('q-'.Str::random(5))))
+        ->assertOk()
+        ->assertJsonPath('data.account_type', 'user')
+        ->assertJsonPath('data.daily_free', 500)
+        ->assertJsonPath('data.earn.reading.daily_cap', 100)
+        ->assertJsonPath('data.earn.editing.credits_per_minute', 5);
+});
+
+/* ------------------------------------------------------------------ 读经时长 */
+
+it('turns reading time into credits', function () {
+    $user = makeStudio('reader-'.Str::random(5));
+
+    $this->postJson('/api/v3/me/reading-time', ['seconds' => 300], authHeader($user))
+        ->assertOk()
+        ->assertJsonPath('data.seconds', 300);
+
+    $this->getJson('/api/v3/agent-quota', authHeader($user))
+        ->assertJsonPath('data.earned_today.reading', 5)
+        ->assertJsonPath('data.earned_balance', 5);
+});
+
+it('clamps reading reports to wall-clock time', function () {
+    $user = makeStudio('clamp-'.Str::random(5));
+
+    $this->postJson('/api/v3/me/reading-time', ['seconds' => 600], authHeader($user))->assertOk();
+    $this->travel(60)->seconds();
+    $this->postJson('/api/v3/me/reading-time', ['seconds' => 600], authHeader($user))
+        ->assertOk()
+        ->assertJsonPath('data.seconds', 690);
+});
+
+it('caps reading credits at one hundred a day', function () {
+    $user = makeStudio('cap-'.Str::random(5));
+    ReadingDaily::create(['user_uid' => $user, 'day' => now('UTC')->toDateString(), 'seconds' => 20000, 'seconds_reported' => 20000]);
+
+    $this->getJson('/api/v3/agent-quota', authHeader($user))->assertJsonPath('data.earned_today.reading', 100);
+});
+
+it('rejects reading reports too far in the past', function () {
+    $this->postJson('/api/v3/me/reading-time', [
+        'seconds' => 60, 'day' => now('UTC')->subDays(3)->toDateString(),
+    ], authHeader(makeStudio('old-'.Str::random(5))))->assertUnprocessable()->assertJsonValidationErrors('day');
+});
+
+it('requires login to report reading time', function () {
+    $this->postJson('/api/v3/me/reading-time', ['seconds' => 60])->assertUnauthorized();
+});
+
+it('rejects an oversized reading report', function () {
+    $this->postJson('/api/v3/me/reading-time', ['seconds' => 5000], authHeader(makeStudio('big-'.Str::random(5))))
+        ->assertUnprocessable();
+});
+
+/* ------------------------------------------------------------------ 编辑时长 */
+
+it('turns editing time into credits without a cap', function () {
+    $user = makeStudio('editor-'.Str::random(5));
+    $sn = UserInfo::where('userid', $user)->value('id');
+    // UTC+8 的客户端:本地今天零点 = UTC 今天零点 − 8 小时
+    $localMidnight = now('UTC')->startOfDay()->getTimestampMs() - 8 * 3600 * 1000;
+    UserOperationDaily::forceCreate([
+        'id' => app('snowflake')->id(), 'user_id' => $sn, 'date_int' => $localMidnight,
+        'duration' => 600 * 60 * 1000, 'hit' => 10,
+    ]);
+
+    $this->getJson('/api/v3/agent-quota', authHeader($user))->assertJsonPath('data.earned_today.editing', 3000);
+});
+
+it('settles yesterday for everyone with the daily command', function () {
+    $user = makeStudio('nightly-'.Str::random(5));
+    ReadingDaily::create(['user_uid' => $user, 'day' => now('UTC')->subDay()->toDateString(), 'seconds' => 1200, 'seconds_reported' => 1200]);
+
+    $this->artisan('credits:settle-activity')->assertSuccessful();
+
+    expect(CreditLedgerEntry::where('account', 'user:'.$user)->where('source', 'reading')->value('delta'))->toBe(20);
+
+    // 重复执行不重复入账
+    $this->artisan('credits:settle-activity')->assertSuccessful();
+    expect(CreditLedgerEntry::where('account', 'user:'.$user)->where('source', 'reading')->count())->toBe(1);
+});
+
+it('backfills every missed day since credits started, however many', function () {
+    config(['mint.credits.earn_since' => now('UTC')->subDays(60)->toDateString()]);
+    $user = makeStudio('missed-'.Str::random(5));
+    $sn = UserInfo::where('userid', $user)->value('id');
+    foreach ([10, 40] as $ago) {
+        ReadingDaily::create(['user_uid' => $user, 'day' => now('UTC')->subDays($ago)->toDateString(), 'seconds' => 300, 'seconds_reported' => 300]);
+    }
+    // UTC+8 客户端 25 天前的本地日:编辑 3 分钟
+    UserOperationDaily::forceCreate([
+        'id' => app('snowflake')->id(), 'user_id' => $sn,
+        'date_int' => now('UTC')->subDays(25)->startOfDay()->getTimestampMs() - 8 * 3600 * 1000,
+        'duration' => 3 * 60 * 1000, 'hit' => 3,
+    ]);
+    // 上线日之前的不补
+    ReadingDaily::create(['user_uid' => $user, 'day' => now('UTC')->subDays(70)->toDateString(), 'seconds' => 600, 'seconds_reported' => 600]);
+    // 不足 1 分钟的不给积分,也不算漏
+    ReadingDaily::create(['user_uid' => $user, 'day' => now('UTC')->subDays(5)->toDateString(), 'seconds' => 30, 'seconds_reported' => 30]);
+
+    $this->artisan('credits:settle-activity')->assertSuccessful();
+
+    $earned = CreditLedgerEntry::where('account', 'user:'.$user)->orderBy('day')->get(['source', 'day', 'delta'])
+        ->map(fn ($e) => [$e->source, $e->day->toDateString(), $e->delta])->all();
+    expect($earned)->toBe([
+        ['reading', now('UTC')->subDays(40)->toDateString(), 5],
+        ['editing', now('UTC')->subDays(25)->toDateString(), 15],
+        ['reading', now('UTC')->subDays(10)->toDateString(), 5],
+    ]);
+
+    // 再跑一次:都已结清,什么都不动
+    $this->artisan('credits:settle-activity')->expectsOutputToContain('补结算了 0 位用户')->assertSuccessful();
+});
+
+it('re-settles a day that was settled before it ended and leaves closed days alone', function () {
+    config(['mint.credits.earn_since' => now('UTC')->subDays(30)->toDateString()]);
+    $user = makeStudio('early-'.Str::random(5));
+    $early = now('UTC')->subDays(3)->startOfDay();
+    $closed = now('UTC')->subDays(4)->startOfDay();
+    foreach ([$early, $closed] as $day) {
+        ReadingDaily::create(['user_uid' => $user, 'day' => $day->toDateString(), 'seconds' => 1200, 'seconds_reported' => 1200]);
+    }
+    // 那天中午就结算过(之后又读了),以及那天结束后才结算过(数额以当时为准,不再动)
+    $entry = fn ($day, int $delta, $at) => CreditLedgerEntry::create([
+        'account' => 'user:'.$user, 'delta' => $delta, 'kind' => 'earn', 'bucket' => 'earned', 'source' => 'reading',
+        'ref' => $day->toDateString(), 'day' => $day->toDateString(), 'policy_version' => 1,
+    ])->forceFill(['updated_at' => $at])->saveQuietly();
+    $entry($early, 2, $early->copy()->addHours(12));
+    $entry($closed, 7, $closed->copy()->addDay()->addHour());
+
+    $this->artisan('credits:settle-activity')->assertSuccessful();
+
+    $deltas = CreditLedgerEntry::where('account', 'user:'.$user)->pluck('delta', 'ref');
+    expect($deltas[$early->toDateString()])->toBe(20)
+        ->and($deltas[$closed->toDateString()])->toBe(7);
+});
+
+it('does not keep re-settling an early-settled day whose amount was already right', function () {
+    config(['mint.credits.earn_since' => now('UTC')->subDays(30)->toDateString()]);
+    $user = makeStudio('same-'.Str::random(5));
+    $day = now('UTC')->subDays(3)->startOfDay();
+    ReadingDaily::create(['user_uid' => $user, 'day' => $day->toDateString(), 'seconds' => 120, 'seconds_reported' => 120]);
+    // 当天中途结算过,数额恰好已经对了(2 分)
+    CreditLedgerEntry::create([
+        'account' => 'user:'.$user, 'delta' => 2, 'kind' => 'earn', 'bucket' => 'earned', 'source' => 'reading',
+        'ref' => $day->toDateString(), 'day' => $day->toDateString(), 'policy_version' => 1,
+    ])->forceFill(['updated_at' => $day->copy()->addHours(12)])->saveQuietly();
+
+    $this->artisan('credits:settle-activity')->expectsOutputToContain('补结算了 1 位用户')->assertSuccessful();
+    $this->artisan('credits:settle-activity')->expectsOutputToContain('补结算了 0 位用户')->assertSuccessful();
+});
+
+it('re-settles editing on a western client day settled before that local day ended', function () {
+    config(['mint.credits.earn_since' => now('UTC')->subDays(30)->toDateString()]);
+    $user = makeStudio('west-'.Str::random(5));
+    $sn = UserInfo::where('userid', $user)->value('id');
+    $day = now('UTC')->subDays(3)->startOfDay();
+    // UTC−8 客户端:本地那天零点 = UTC 当天 08:00,一直到 UTC 次日 08:00
+    UserOperationDaily::forceCreate([
+        'id' => app('snowflake')->id(), 'user_id' => $sn, 'date_int' => $day->getTimestampMs() + 8 * 3600 * 1000,
+        'duration' => 10 * 60 * 1000, 'hit' => 10,
+    ]);
+    // 次日 01:00 UTC(本地那天还没结束)只结算到 2 分钟
+    CreditLedgerEntry::create([
+        'account' => 'user:'.$user, 'delta' => 10, 'kind' => 'earn', 'bucket' => 'earned', 'source' => 'editing',
+        'ref' => $day->toDateString(), 'day' => $day->toDateString(), 'policy_version' => 1,
+    ])->forceFill(['updated_at' => $day->copy()->addDay()->addHour()])->saveQuietly();
+
+    $this->artisan('credits:settle-activity')->assertSuccessful();
+
+    expect(CreditLedgerEntry::where('account', 'user:'.$user)->where('source', 'editing')->value('delta'))->toBe(50);
+});
+
+/* ------------------------------------------------------------------ 策略与调整 */
+
+it('shows the current credit policy to anyone', function () {
+    $this->getJson('/api/v3/credit-policy')
+        ->assertOk()
+        ->assertJsonPath('data.version', config('mint.credits.policy.version'))
+        ->assertJsonPath('data.day_timezone', 'UTC')
+        ->assertJsonPath('data.daily_free.guest', 100)
+        ->assertJsonPath('data.cost.deep', 30)
+        ->assertJsonPath('data.earn.editing.daily_cap', null);
+});
+
+it('charges by the policy in config and records its version', function () {
+    config(['mint.credits.policy.version' => 20261201, 'mint.credits.policy.cost.normal' => 5]);
+
+    charge(['device_id' => (string) Str::uuid()])->assertCreated()
+        ->assertJsonPath('data.cost', 5)
+        ->assertJsonPath('data.policy_version', 20261201);
+    expect(CreditLedgerEntry::value('policy_version'))->toBe(20261201);
+});
+
+it('applies a manual adjustment only once per ref', function () {
+    $user = makeStudio('adj-'.Str::random(5));
+
+    $this->artisan('credits:adjust', ['user' => $user, 'delta' => 100, '--ref' => 'gift-1'])->assertSuccessful();
+    $this->artisan('credits:adjust', ['user' => $user, 'delta' => 100, '--ref' => 'gift-1'])->assertSuccessful();
+
+    $this->getJson('/api/v3/agent-quota', authHeader($user))->assertJsonPath('data.earned_balance', 100);
+});
+
+it('tells guests to sign in and users to read when out of credits', function () {
+    $device = (string) Str::uuid();
+    spendFree('guest:'.$device, 100);
+    $user = makeStudio('out-'.Str::random(5));
+    spendFree('user:'.$user, 500);
+
+    $guestDetail = charge(['device_id' => $device], null, ['Accept-Language' => 'zh-Hans'])->assertStatus(402)->json('detail');
+    $userDetail = charge([], $user, ['Accept-Language' => 'zh-Hans'])->assertStatus(402)->json('detail');
+
+    expect($guestDetail)->toContain('登录')
+        ->and($userDetail)->toContain('读经')
+        ->and($guestDetail)->not->toBe('messages.agent_quota_insufficient_guest');
+});

+ 245 - 0
api-v13/tests/Feature/AgentFeedbackV3Test.php

@@ -0,0 +1,245 @@
+<?php
+
+use App\Models\AgentEvent;
+use App\Models\AgentFeedback;
+use App\Models\AgentRun;
+use App\Models\AgentThread;
+use App\Models\UserInfo;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Str;
+
+uses(RefreshDatabase::class);
+
+/**
+ * v3 AI 回答评价、隐式信号、自动质量指标与分析导出:
+ *
+ *   POST   /api/v3/agent-feedback               评价(可选登录,游客带 device_id)
+ *   DELETE /api/v3/agent-feedback/{message}     撤回
+ *   POST   /api/v3/agent-events                 隐式信号
+ *   GET    /api/v3/admin/agent-feedback         管理员审阅
+ *   GET    /api/v3/admin/agent-runs/digest      分析用精简导出
+ *
+ * 这里断言的是形状而非契约(spectator 尚未安装,见 v3-resource skill 第 3 步)。
+ */
+function feedbackAdmin(): array
+{
+    $uid = makeStudio('fa-'.Str::random(5));
+    UserInfo::where('userid', $uid)->update(['role' => json_encode(['administrator'])]);
+
+    return authHeader($uid);
+}
+
+/* ------------------------------------------------------------------ 评价 */
+
+it('lets a guest rate an answer and change the rating', function () {
+    $device = (string) Str::uuid();
+
+    $this->postJson('/api/v3/agent-feedback', ['message_id' => 'lc_run--abc', 'rating' => 1, 'tags' => ['clear'], 'device_id' => $device])
+        ->assertCreated()
+        ->assertJsonPath('data.rating', 1)
+        ->assertJsonPath('data.tags', ['clear']);
+    $this->postJson('/api/v3/agent-feedback', [
+        'message_id' => 'lc_run--abc', 'rating' => -1, 'tags' => ['missed', 'other'], 'comment' => '中部有这段', 'device_id' => $device,
+    ])->assertOk()->assertJsonPath('data.comment', '中部有这段');
+
+    expect(AgentFeedback::count())->toBe(1)
+        ->and(AgentFeedback::first()->account)->toBe('guest:'.$device);
+});
+
+it('keeps one rating per user and per guest device', function () {
+    $user = (string) Str::uuid();
+    $this->postJson('/api/v3/agent-feedback', ['message_id' => 'm1', 'rating' => 1], authHeader($user))->assertCreated();
+    $this->postJson('/api/v3/agent-feedback', ['message_id' => 'm1', 'rating' => -1, 'device_id' => (string) Str::uuid()])->assertCreated();
+
+    expect(AgentFeedback::where('message_id', 'm1')->count())->toBe(2);
+});
+
+it('drops the comment unless other is chosen', function () {
+    $this->postJson('/api/v3/agent-feedback', [
+        'message_id' => 'm2', 'rating' => -1, 'tags' => ['slow'], 'comment' => 'x', 'device_id' => (string) Str::uuid(),
+    ])->assertCreated()->assertJsonPath('data.comment', null);
+});
+
+it('rejects tags that do not match the rating', function () {
+    $this->postJson('/api/v3/agent-feedback', ['message_id' => 'm3', 'rating' => 1, 'tags' => ['slow'], 'device_id' => (string) Str::uuid()])
+        ->assertUnprocessable()->assertJsonValidationErrors('tags');
+});
+
+it('rejects an unknown tag and a bad message id', function () {
+    $device = (string) Str::uuid();
+    $this->postJson('/api/v3/agent-feedback', ['message_id' => 'm4', 'rating' => -1, 'tags' => ['boring'], 'device_id' => $device])
+        ->assertUnprocessable();
+    $this->postJson('/api/v3/agent-feedback', ['message_id' => 'a b', 'rating' => 1, 'device_id' => $device])
+        ->assertUnprocessable()->assertJsonValidationErrors('message_id');
+});
+
+it('requires a device id from guests', function () {
+    $this->postJson('/api/v3/agent-feedback', ['message_id' => 'm5', 'rating' => 1])
+        ->assertUnprocessable()->assertJsonValidationErrors('device_id');
+});
+
+it('remembers that a rating was asked for', function () {
+    $device = (string) Str::uuid();
+    $this->postJson('/api/v3/agent-feedback', ['message_id' => 'm6', 'rating' => 1, 'asked' => true, 'device_id' => $device]);
+    $this->postJson('/api/v3/agent-feedback', ['message_id' => 'm6', 'rating' => -1, 'device_id' => $device])
+        ->assertJsonPath('data.asked', true);
+});
+
+it('retracts a rating idempotently', function () {
+    $device = (string) Str::uuid();
+    $this->postJson('/api/v3/agent-feedback', ['message_id' => 'lc_run--x', 'rating' => 1, 'device_id' => $device]);
+
+    $this->deleteJson("/api/v3/agent-feedback/lc_run--x?device_id={$device}")->assertNoContent();
+    $this->deleteJson("/api/v3/agent-feedback/lc_run--x?device_id={$device}")->assertNoContent();
+    expect(AgentFeedback::count())->toBe(0);
+});
+
+it('cannot retract someone else\'s rating', function () {
+    $this->postJson('/api/v3/agent-feedback', ['message_id' => 'm7', 'rating' => 1, 'device_id' => (string) Str::uuid()]);
+
+    $this->deleteJson('/api/v3/agent-feedback/m7?device_id='.Str::uuid())->assertNoContent();
+    expect(AgentFeedback::count())->toBe(1);
+});
+
+/* ------------------------------------------------------------------ 隐式信号 */
+
+it('records implicit signals', function () {
+    $this->postJson('/api/v3/agent-events', ['message_id' => 'm8', 'kind' => 'copy', 'device_id' => (string) Str::uuid(), 'client' => 'web'])
+        ->assertCreated()->assertJsonPath('data.kind', 'copy');
+    $this->postJson('/api/v3/agent-events', ['message_id' => 'm8', 'kind' => 'citation_open'], authHeader((string) Str::uuid()))
+        ->assertCreated();
+
+    expect(AgentEvent::count())->toBe(2);
+});
+
+it('rejects an unknown signal', function () {
+    $this->postJson('/api/v3/agent-events', ['message_id' => 'm9', 'kind' => 'like', 'device_id' => (string) Str::uuid()])
+        ->assertUnprocessable();
+});
+
+/* ------------------------------------------------------------------ 评价即同意用于改进 */
+
+it('turns improve on for the rated run of the same account only', function () {
+    $device = (string) Str::uuid();
+    $mine = AgentThread::factory()->create(['account' => 'guest:'.$device, 'user_uid' => null, 'device_id' => $device]);
+    $run = AgentRun::factory()->for($mine, 'thread')->create(['assistant_message_id' => 'msg-c1', 'improve' => false]);
+    $other = AgentRun::factory()->for(AgentThread::factory(), 'thread')->create(['assistant_message_id' => 'msg-c2', 'improve' => false]);
+
+    $this->postJson('/api/v3/agent-feedback', ['message_id' => 'msg-c1', 'rating' => 1, 'device_id' => $device])->assertCreated();
+    // 别人的回答(消息 id 碰巧一样也不行)不受影响
+    $this->postJson('/api/v3/agent-feedback', ['message_id' => 'msg-c2', 'rating' => -1, 'device_id' => $device])->assertCreated();
+
+    expect($run->fresh()->improve)->toBeTrue()
+        ->and($other->fresh()->improve)->toBeFalse();
+});
+
+it('marks a trace improve when the rating arrived first', function () {
+    config(['mint.app.agent_service_key' => 'k']);
+    $device = (string) Str::uuid();
+    $this->postJson('/api/v3/agent-feedback', ['message_id' => 'msg-early', 'rating' => 1, 'device_id' => $device])->assertCreated();
+
+    $run = (string) Str::uuid();
+    $this->postJson('/api/v3/agent-traces', [
+        'run_id' => $run, 'thread_id' => (string) Str::uuid(), 'device_id' => $device, 'improve' => false,
+        'question' => '什么是慈?', 'status' => 'ok', 'answer' => '……', 'assistant_message_id' => 'msg-early',
+    ], ['X-Agent-Service-Key' => 'k'])->assertCreated();
+
+    expect(AgentRun::where('run_id', $run)->value('improve'))->toBeTrue();
+});
+
+/* ------------------------------------------------------------------ 管理员 */
+
+it('lists feedback with the run summary for admins only', function () {
+    $thread = AgentThread::factory()->create();
+    AgentRun::factory()->for($thread, 'thread')->create(['assistant_message_id' => 'msg-1', 'question' => '什么是慈?']);
+    $this->postJson('/api/v3/agent-feedback', ['message_id' => 'msg-1', 'rating' => -1, 'tags' => ['missed'], 'device_id' => (string) Str::uuid()]);
+    $this->postJson('/api/v3/agent-feedback', ['message_id' => 'msg-unknown', 'rating' => 1, 'device_id' => (string) Str::uuid()]);
+
+    $this->getJson('/api/v3/admin/agent-feedback')->assertUnauthorized();
+    $this->getJson('/api/v3/admin/agent-feedback', authHeader(makeStudio('np-'.Str::random(4))))->assertForbidden();
+
+    $admin = feedbackAdmin();
+    $this->getJson('/api/v3/admin/agent-feedback?filter[rating]=-1', $admin)
+        ->assertOk()
+        ->assertJsonCount(1, 'data')
+        ->assertJsonPath('data.0.question', '什么是慈?')
+        ->assertJsonPath('data.0.account_type', 'guest')
+        ->assertJsonMissingPath('data.0.account');
+    $this->getJson('/api/v3/admin/agent-feedback?filter[tag]=missed', $admin)->assertJsonCount(1, 'data');
+    $this->getJson('/api/v3/admin/agent-feedback', $admin)->assertJsonPath('meta.total', 2);
+});
+
+it('adds feedback to the agent stats', function () {
+    $thread = AgentThread::factory()->create();
+    AgentRun::factory()->for($thread, 'thread')->create([
+        'assistant_message_id' => 'msg-s', 'started_at' => '2026-10-20 10:00:00', 'route' => 'question',
+    ]);
+    $this->postJson('/api/v3/agent-feedback', ['message_id' => 'msg-s', 'rating' => -1, 'tags' => ['citation_wrong', 'slow'], 'asked' => true, 'device_id' => (string) Str::uuid()]);
+
+    $data = $this->getJson('/api/v3/admin/agent-stats?from=2026-10-20&to=2026-10-20', feedbackAdmin())->json('data');
+
+    expect($data['summary'])->toMatchArray(['feedback_down' => 1, 'feedback_asked' => 1])
+        ->and($data['summary'])->not->toHaveKey('quality_assessed')
+        ->and($data)->not->toHaveKey('quality_by_route')
+        ->and(collect($data['feedback_reasons'])->pluck('reason')->all())->toContain('citation_wrong', 'slow')
+        ->and($data['daily'][0]['feedback_down'])->toBe(1);
+});
+
+it('exports a digest without identities or opted-out runs', function () {
+    $user = (string) Str::uuid();
+    $thread = AgentThread::factory()->forUser($user)->create();
+    AgentRun::factory()->for($thread, 'thread')->create([
+        'user_uid' => $user, 'assistant_message_id' => 'd1', 'started_at' => '2026-10-20 10:00:00', 'question' => 'Q1',
+        'plan' => ['lemmas' => ['mettā'], 'keywords' => [['lemma' => 'mettā', 'tags' => 'sutta']]],
+    ]);
+    AgentRun::factory()->for($thread, 'thread')->create(['user_uid' => $user, 'started_at' => '2026-10-20 10:00:30', 'question' => 'Q2']);
+    AgentRun::factory()->for($thread, 'thread')->create(['user_uid' => $user, 'started_at' => '2026-10-20 10:05:00', 'question' => 'secret', 'improve' => false]);
+    $this->postJson('/api/v3/agent-events', ['message_id' => 'd1', 'kind' => 'copy'], authHeader($user));
+
+    $res = $this->getJson('/api/v3/admin/agent-runs/digest?from=2026-10-20&to=2026-10-20', feedbackAdmin())->assertOk();
+    $items = $res->json('data');
+
+    expect(array_column($items, 'question'))->toBe(['Q1', 'Q2'])
+        ->and($items[0])->toMatchArray(['lemmas' => ['mettā'], 'keywords' => ['mettā|sutta'], 'events' => ['copy' => 1], 'next_question_after_s' => 30])
+        ->and($items[0])->not->toHaveKeys(['user', 'user_uid', 'device_id', 'client_ip', 'account', 'answer', 'evidence'])
+        ->and($res->json('meta.has_more'))->toBeFalse();
+});
+
+it('adds answer, evidence and citations to the digest on request for agent evaluation', function () {
+    $thread = AgentThread::factory()->create();
+    AgentRun::factory()->for($thread, 'thread')->create([
+        'started_at' => '2026-10-20 10:00:00', 'answer' => 'A', 'evidence' => 'E', 'citations' => [['link' => 'https://x/1-2']],
+    ]);
+    $admin = feedbackAdmin();
+
+    $item = $this->getJson('/api/v3/admin/agent-runs/digest?from=2026-10-20&to=2026-10-20&full=1', $admin)->assertOk()->json('data.0');
+    expect($item)->toMatchArray(['answer' => 'A', 'evidence' => 'E', 'citations' => [['link' => 'https://x/1-2']]])
+        ->and($item)->not->toHaveKey('quality');
+
+    // 带全文时条数上限收紧到 200
+    $this->getJson('/api/v3/admin/agent-runs/digest?full=1&limit=201', $admin)->assertUnprocessable()->assertJsonValidationErrors('limit');
+    $this->getJson('/api/v3/admin/agent-runs/digest?limit=201', $admin)->assertOk();
+});
+
+it('leaves soft-deleted runs out of every admin read', function () {
+    $thread = AgentThread::factory()->create();
+    $kept = AgentRun::factory()->for($thread, 'thread')->create(['started_at' => '2026-10-20 10:00:00', 'question' => 'kept', 'assistant_message_id' => 'm-kept']);
+    $gone = AgentRun::factory()->for($thread, 'thread')->create(['started_at' => '2026-10-20 11:00:00', 'question' => 'gone', 'assistant_message_id' => 'm-gone']);
+    $gone->steps()->create(['seq' => 0, 'kind' => 'tool', 'name' => 'wikipali_search']);
+    $this->postJson('/api/v3/agent-feedback', ['message_id' => 'm-gone', 'rating' => -1, 'device_id' => (string) Str::uuid()]);
+    $gone->steps()->delete();
+    $gone->delete();
+    $admin = feedbackAdmin();
+
+    expect($this->getJson('/api/v3/admin/agent-runs', $admin)->json('data.*.question'))->toBe(['kept']);
+    $this->getJson("/api/v3/admin/agent-runs/{$gone->run_id}", $admin)->assertNotFound();
+    expect($this->getJson('/api/v3/admin/agent-runs/digest?from=2026-10-20&to=2026-10-20', $admin)->json('data.*.question'))->toBe(['kept']);
+    $stats = $this->getJson('/api/v3/admin/agent-stats?from=2026-10-20&to=2026-10-20', $admin)->json('data');
+    expect($stats['summary']['runs'])->toBe(1)
+        ->and($stats['tools'])->toBe([]);
+    // 评价本身还在,只是不再带出那次问答
+    $this->getJson('/api/v3/admin/agent-feedback', $admin)
+        ->assertJsonCount(1, 'data')
+        ->assertJsonPath('data.0.run_id', null)
+        ->assertJsonPath('data.0.question', null);
+});

+ 209 - 0
api-v13/tests/Feature/AgentThreadV3Test.php

@@ -0,0 +1,209 @@
+<?php
+
+use App\Models\AgentRun;
+use App\Models\AgentThread;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Str;
+
+uses(RefreshDatabase::class);
+
+/**
+ * v3 me/agent-threads:登录用户的 AI 对话会话历史(web chat 与 mobile 共用)。
+ *
+ *   GET    /api/v3/me/agent-threads                     列表(filter[archived])
+ *   GET    /api/v3/me/agent-threads/{thread}            详情(带可见的问答轮次)
+ *   PATCH  /api/v3/me/agent-threads/{thread}            改标题
+ *   DELETE /api/v3/me/agent-threads/{thread}            删除(软删,返回 200 + 资源)
+ *   PUT    /api/v3/me/agent-threads/{thread}/archive    存档
+ *   DELETE /api/v3/me/agent-threads/{thread}/archive    取消存档
+ *
+ * 这里断言的是形状而非契约(spectator 尚未安装,见 v3-resource skill 第 3 步)。
+ */
+
+/* ------------------------------------------------------------------ 列表 */
+
+it('lists my threads, most recent first', function () {
+    $me = (string) Str::uuid();
+    $older = AgentThread::factory()->forUser($me)->create(['last_run_at' => now()->subDay()]);
+    $newer = AgentThread::factory()->forUser($me)->create(['last_run_at' => now()]);
+    AgentThread::factory()->forUser((string) Str::uuid())->create();
+    AgentThread::factory()->create();
+
+    $data = $this->getJson('/api/v3/me/agent-threads', authHeader($me))
+        ->assertOk()
+        ->assertJsonStructure(['data' => [['thread_id', 'title', 'archived_at', 'last_run_at']], 'meta' => ['total']])
+        ->json('data');
+
+    expect(array_column($data, 'thread_id'))->toBe([$newer->thread_id, $older->thread_id])
+        ->and($data[0])->not->toHaveKey('runs');
+});
+
+it('filters threads by archived', function () {
+    $me = (string) Str::uuid();
+    $archived = AgentThread::factory()->forUser($me)->archived()->create();
+    $active = AgentThread::factory()->forUser($me)->create();
+
+    expect($this->getJson('/api/v3/me/agent-threads?filter[archived]=true', authHeader($me))->json('data.*.thread_id'))
+        ->toBe([$archived->thread_id])
+        ->and($this->getJson('/api/v3/me/agent-threads?filter[archived]=false', authHeader($me))->json('data.*.thread_id'))
+        ->toBe([$active->thread_id]);
+});
+
+it('does not list deleted threads', function () {
+    $me = (string) Str::uuid();
+    AgentThread::factory()->forUser($me)->create(['deleted_at' => now()]);
+
+    $this->getJson('/api/v3/me/agent-threads', authHeader($me))->assertOk()->assertJsonCount(0, 'data');
+});
+
+it('requires login to list threads', function () {
+    $this->getJson('/api/v3/me/agent-threads')->assertUnauthorized();
+});
+
+it('rejects an invalid archived filter', function () {
+    $this->getJson('/api/v3/me/agent-threads?filter[archived]=maybe', authHeader((string) Str::uuid()))
+        ->assertUnprocessable();
+});
+
+/* ------------------------------------------------------------------ 详情 */
+
+it('shows a thread with its visible runs in order', function () {
+    $me = (string) Str::uuid();
+    $thread = AgentThread::factory()->forUser($me)->create();
+    $first = AgentRun::factory()->for($thread, 'thread')->create(['started_at' => now()->subMinutes(10), 'question' => 'Q1']);
+    $replaced = AgentRun::factory()->for($thread, 'thread')->create(['started_at' => now()->subMinutes(5), 'question' => 'Q2']);
+    AgentRun::factory()->for($thread, 'thread')->create([
+        'started_at' => now()->subMinutes(4), 'question' => 'Q2', 'answer' => 'regenerated', 'replaces_run_id' => $replaced->run_id,
+    ]);
+
+    $runs = $this->getJson("/api/v3/me/agent-threads/{$thread->thread_id}", authHeader($me))
+        ->assertOk()
+        ->assertJsonPath('data.thread_id', $thread->thread_id)
+        ->json('data.runs');
+
+    expect($runs)->toHaveCount(2)
+        ->and($runs[0]['run_id'])->toBe($first->run_id)
+        ->and($runs[1]['answer'])->toBe('regenerated')
+        ->and($runs[0])->toHaveKeys(['question', 'answer', 'citations', 'deep', 'user_message_id', 'assistant_message_id'])
+        ->and($runs[0])->not->toHaveKeys(['evidence', 'plan', 'client_ip', 'improve']);
+});
+
+it('hides other users threads as 404', function () {
+    $other = AgentThread::factory()->forUser((string) Str::uuid())->create();
+
+    $this->getJson("/api/v3/me/agent-threads/{$other->thread_id}", authHeader((string) Str::uuid()))
+        ->assertNotFound();
+});
+
+it('does not expose guest threads through the user api', function () {
+    $guest = AgentThread::factory()->create();
+
+    $this->getJson("/api/v3/me/agent-threads/{$guest->thread_id}", authHeader((string) Str::uuid()))
+        ->assertNotFound();
+});
+
+it('returns 404 for a non-uuid thread id', function () {
+    $this->getJson('/api/v3/me/agent-threads/not-a-uuid', authHeader((string) Str::uuid()))->assertNotFound();
+});
+
+/* ------------------------------------------------------------------ 改名 */
+
+it('renames my thread', function () {
+    $me = (string) Str::uuid();
+    $thread = AgentThread::factory()->forUser($me)->create();
+
+    $this->patchJson("/api/v3/me/agent-threads/{$thread->thread_id}", ['title' => '新标题'], authHeader($me))
+        ->assertOk()
+        ->assertJsonPath('data.title', '新标题');
+});
+
+it('ignores fields other than title on rename', function () {
+    $me = (string) Str::uuid();
+    $thread = AgentThread::factory()->forUser($me)->create();
+
+    $this->patchJson("/api/v3/me/agent-threads/{$thread->thread_id}", ['account' => 'user:someone-else'], authHeader($me))
+        ->assertOk();
+
+    expect($thread->fresh()->account)->toBe('user:'.$me);
+});
+
+it('rejects an empty title', function () {
+    $me = (string) Str::uuid();
+    $thread = AgentThread::factory()->forUser($me)->create();
+
+    $this->patchJson("/api/v3/me/agent-threads/{$thread->thread_id}", ['title' => ''], authHeader($me))
+        ->assertUnprocessable();
+});
+
+it('does not register PUT on a thread', function () {
+    $me = (string) Str::uuid();
+    $thread = AgentThread::factory()->forUser($me)->create();
+
+    $this->putJson("/api/v3/me/agent-threads/{$thread->thread_id}", ['title' => 'x'], authHeader($me))
+        ->assertStatus(405);
+});
+
+/* ------------------------------------------------------------------ 存档 */
+
+it('archives and unarchives my thread', function () {
+    $me = (string) Str::uuid();
+    $thread = AgentThread::factory()->forUser($me)->create();
+
+    $archivedAt = $this->putJson("/api/v3/me/agent-threads/{$thread->thread_id}/archive", [], authHeader($me))
+        ->assertOk()
+        ->json('data.archived_at');
+    expect($archivedAt)->not->toBeNull();
+
+    // 幂等:再存档一次,时间不变
+    $this->putJson("/api/v3/me/agent-threads/{$thread->thread_id}/archive", [], authHeader($me))
+        ->assertOk()
+        ->assertJsonPath('data.archived_at', $archivedAt);
+
+    $this->deleteJson("/api/v3/me/agent-threads/{$thread->thread_id}/archive", [], authHeader($me))
+        ->assertOk()
+        ->assertJsonPath('data.archived_at', null);
+});
+
+it('cannot archive another users thread', function () {
+    $other = AgentThread::factory()->forUser((string) Str::uuid())->create();
+
+    $this->putJson("/api/v3/me/agent-threads/{$other->thread_id}/archive", [], authHeader((string) Str::uuid()))
+        ->assertNotFound();
+});
+
+it('requires login to archive', function () {
+    $thread = AgentThread::factory()->forUser((string) Str::uuid())->create();
+
+    $this->putJson("/api/v3/me/agent-threads/{$thread->thread_id}/archive")->assertUnauthorized();
+});
+
+/* ------------------------------------------------------------------ 删除 */
+
+it('soft deletes my thread together with its runs and steps', function () {
+    $me = (string) Str::uuid();
+    $thread = AgentThread::factory()->forUser($me)->create();
+    $run = AgentRun::factory()->for($thread, 'thread')->create();
+    $step = $run->steps()->create(['seq' => 0, 'kind' => 'tool', 'name' => 'wikipali_search']);
+    $otherRun = AgentRun::factory()->for(AgentThread::factory()->forUser($me), 'thread')->create();
+
+    $this->deleteJson("/api/v3/me/agent-threads/{$thread->thread_id}", [], authHeader($me))
+        ->assertOk()
+        ->assertJsonPath('data.thread_id', $thread->thread_id);
+
+    // 软删、不是真删:数据都还在
+    $this->assertSoftDeleted($thread);
+    $this->assertSoftDeleted($run);
+    $this->assertSoftDeleted($step);
+    expect(AgentRun::where('agent_thread_id', $thread->id)->count())->toBe(0)
+        ->and(AgentRun::withTrashed()->where('agent_thread_id', $thread->id)->count())->toBe(1)
+        ->and($otherRun->fresh()->deleted_at)->toBeNull();
+    $this->getJson("/api/v3/me/agent-threads/{$thread->thread_id}", authHeader($me))->assertNotFound();
+});
+
+it('cannot delete another users thread', function () {
+    $other = AgentThread::factory()->forUser((string) Str::uuid())->create();
+
+    $this->deleteJson("/api/v3/me/agent-threads/{$other->thread_id}", [], authHeader((string) Str::uuid()))
+        ->assertNotFound();
+    expect($other->fresh()->deleted_at)->toBeNull();
+});

+ 258 - 0
api-v13/tests/Feature/AgentTraceV3Test.php

@@ -0,0 +1,258 @@
+<?php
+
+use App\Models\AgentRun;
+use App\Models\AgentThread;
+use App\Models\AiModel;
+use App\Services\AuthService;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Str;
+
+uses(RefreshDatabase::class);
+
+/**
+ * v3 agent-traces:AI 对话研究过程入库(服务间接口)。数据永久保留,没有清理命令。
+ *
+ *   POST /api/v3/agent-traces   X-Agent-Service-Key 必带;Bearer 是透传的终端用户 token(可选)
+ *
+ * 这里断言的是形状而非契约(spectator 尚未安装,见 v3-resource skill 第 3 步)。
+ */
+beforeEach(function () {
+    config(['mint.app.agent_service_key' => 'test-agent-key']);
+});
+
+function agentHeaders(?string $userUid = null): array
+{
+    $headers = ['X-Agent-Service-Key' => 'test-agent-key'];
+
+    return $userUid ? $headers + authHeader($userUid) : $headers;
+}
+
+function tracePayload(array $overrides = []): array
+{
+    return array_merge([
+        'run_id' => (string) Str::uuid(),
+        'thread_id' => (string) Str::uuid(),
+        'device_id' => (string) Str::uuid(),
+        'client_ip' => '203.0.113.7',
+        'client' => 'mobile',
+        'question' => '什么是四圣谛?',
+        'deep' => false,
+        'improve' => true,
+        'route' => 'question',
+        'plan' => ['lemmas' => ['ariyasacca']],
+        'evidence' => '证据全文',
+        'answer' => '四圣谛是……',
+        'citations' => [['link' => 'https://wikipali.org/library/tipitaka/203-1677/read#1702']],
+        'llm_calls' => 2,
+        'tool_calls' => 3,
+        'status' => 'ok',
+        'user_message_id' => 'msg-u-1',
+        'assistant_message_id' => 'msg-a-1',
+        'started_at' => now()->toIso8601String(),
+        'steps' => [
+            ['seq' => 0, 'kind' => 'route', 'args' => ['route' => 'question']],
+            ['seq' => 1, 'kind' => 'tool', 'name' => 'wikipali_search', 'args' => ['q' => 'ariyasacca'], 'result' => '…', 'result_chars' => 9000, 'ms' => 120],
+            ['seq' => 2, 'kind' => 'llm', 'name' => 'deepseek-chat', 'tokens_in' => 1000, 'tokens_out' => 300, 'ms' => 2000],
+        ],
+    ], $overrides);
+}
+
+/* ------------------------------------------------------------------ 鉴权 */
+
+it('rejects a request without the service key', function () {
+    $this->postJson('/api/v3/agent-traces', tracePayload())->assertUnauthorized();
+});
+
+it('rejects a wrong service key', function () {
+    $this->postJson('/api/v3/agent-traces', tracePayload(), ['X-Agent-Service-Key' => 'nope'])
+        ->assertUnauthorized();
+});
+
+it('rejects everything when no service key is configured', function () {
+    config(['mint.app.agent_service_key' => '']);
+
+    $this->postJson('/api/v3/agent-traces', tracePayload(), ['X-Agent-Service-Key' => ''])
+        ->assertUnauthorized();
+});
+
+it('rejects an end-user token without the service key', function () {
+    $this->postJson('/api/v3/agent-traces', tracePayload(), authHeader((string) Str::uuid()))
+        ->assertUnauthorized();
+});
+
+/* ------------------------------------------------------------------ 游客 */
+
+it('records a guest run with device id and ip', function () {
+    $payload = tracePayload();
+
+    $this->postJson('/api/v3/agent-traces', $payload, agentHeaders())
+        ->assertCreated()
+        ->assertJsonPath('data.run_id', $payload['run_id'])
+        ->assertJsonPath('data.thread_id', $payload['thread_id'])
+        ->assertJsonPath('data.account_type', 'guest');
+
+    $run = AgentRun::where('run_id', $payload['run_id'])->firstOrFail();
+    expect($run->user_uid)->toBeNull()
+        ->and($run->device_id)->toBe($payload['device_id'])
+        ->and($run->client_ip)->toBe('203.0.113.7')
+        ->and($run->plan)->toBe(['lemmas' => ['ariyasacca']])
+        ->and($run->steps()->count())->toBe(3)
+        ->and($run->thread->account)->toBe('guest:'.$payload['device_id'])
+        ->and($run->thread->title)->toBe('什么是四圣谛?');
+});
+
+it('requires a device id from a guest', function () {
+    $this->postJson('/api/v3/agent-traces', tracePayload(['device_id' => null]), agentHeaders())
+        ->assertUnprocessable()
+        ->assertJsonValidationErrors('device_id');
+});
+
+it('falls back to guest when the user token is invalid', function () {
+    $payload = tracePayload();
+
+    $this->postJson('/api/v3/agent-traces', $payload, [
+        'X-Agent-Service-Key' => 'test-agent-key',
+        'Authorization' => 'Bearer not-a-jwt',
+    ])->assertCreated()->assertJsonPath('data.account_type', 'guest');
+});
+
+it('treats a model token as a guest', function () {
+    $human = makeStudio('owner');
+    $model = AiModel::factory()->ownedBy($human)->create();
+    $payload = tracePayload();
+
+    $this->postJson('/api/v3/agent-traces', $payload, [
+        'X-Agent-Service-Key' => 'test-agent-key',
+        'Authorization' => 'Bearer '.AuthService::getUserToken($model->uid),
+    ])->assertCreated()->assertJsonPath('data.account_type', 'guest');
+
+    expect(AgentRun::where('run_id', $payload['run_id'])->value('user_uid'))->toBeNull();
+});
+
+/* ------------------------------------------------------------------ 登录用户 */
+
+it('records a user run without device id or ip', function () {
+    $user = (string) Str::uuid();
+    $payload = tracePayload();
+
+    $this->postJson('/api/v3/agent-traces', $payload, agentHeaders($user))
+        ->assertCreated()
+        ->assertJsonPath('data.account_type', 'user');
+
+    $run = AgentRun::where('run_id', $payload['run_id'])->firstOrFail();
+    expect($run->user_uid)->toBe($user)
+        ->and($run->device_id)->toBeNull()
+        ->and($run->client_ip)->toBeNull()
+        ->and($run->thread->account)->toBe('user:'.$user);
+});
+
+it('records a run even when the user opted out of improvement', function () {
+    $payload = tracePayload(['improve' => false]);
+
+    $this->postJson('/api/v3/agent-traces', $payload, agentHeaders())->assertCreated();
+
+    expect(AgentRun::where('run_id', $payload['run_id'])->value('improve'))->toBeFalse();
+});
+
+it('rejects a thread id that belongs to another account', function () {
+    $user = (string) Str::uuid();
+    $thread = (string) Str::uuid();
+
+    $this->postJson('/api/v3/agent-traces', tracePayload(['thread_id' => $thread]), agentHeaders())->assertCreated();
+    $this->postJson('/api/v3/agent-traces', tracePayload(['thread_id' => $thread]), agentHeaders($user))
+        ->assertForbidden()
+        ->assertJsonPath('status', 403);
+
+    expect(AgentThread::where('thread_id', $thread)->count())->toBe(1)
+        ->and(AgentThread::where('thread_id', $thread)->value('account'))->toStartWith('guest:');
+});
+
+it('appends runs to the same thread and advances last_run_at', function () {
+    $user = (string) Str::uuid();
+    $thread = (string) Str::uuid();
+
+    $this->postJson('/api/v3/agent-traces', tracePayload([
+        'thread_id' => $thread, 'started_at' => now()->subHour()->toIso8601String(),
+    ]), agentHeaders($user))->assertCreated();
+    $this->postJson('/api/v3/agent-traces', tracePayload([
+        'thread_id' => $thread, 'question' => '第二个问题',
+    ]), agentHeaders($user))->assertCreated();
+
+    $row = AgentThread::where('thread_id', $thread)->firstOrFail();
+    expect($row->runs()->count())->toBe(2)
+        ->and($row->title)->toBe('什么是四圣谛?')
+        ->and($row->last_run_at->gt(now()->subMinutes(5)))->toBeTrue();
+});
+
+it('truncates a long first question into the title', function () {
+    $payload = tracePayload(['question' => str_repeat('缘', 80)]);
+
+    $this->postJson('/api/v3/agent-traces', $payload, agentHeaders())->assertCreated();
+
+    expect(AgentThread::where('thread_id', $payload['thread_id'])->value('title'))
+        ->toBe(str_repeat('缘', 60).'…');
+});
+
+/* ------------------------------------------------------------------ 幂等与校验 */
+
+it('is idempotent on run_id', function () {
+    $payload = tracePayload();
+
+    $this->postJson('/api/v3/agent-traces', $payload, agentHeaders())->assertCreated();
+    $this->postJson('/api/v3/agent-traces', $payload, agentHeaders())->assertOk();
+
+    expect(AgentRun::where('run_id', $payload['run_id'])->count())->toBe(1)
+        ->and(AgentRun::where('run_id', $payload['run_id'])->first()->steps()->count())->toBe(3);
+});
+
+it('keeps a deleted run deleted when the same trace is sent again', function () {
+    $payload = tracePayload();
+    $this->postJson('/api/v3/agent-traces', $payload, agentHeaders())->assertCreated();
+    $run = AgentRun::where('run_id', $payload['run_id'])->first();
+    $run->steps()->delete();
+    $run->delete();
+
+    // agent 端补发同一条:不重建、不复活
+    $this->postJson('/api/v3/agent-traces', $payload, agentHeaders())->assertOk();
+
+    expect(AgentRun::withTrashed()->where('run_id', $payload['run_id'])->count())->toBe(1)
+        ->and(AgentRun::where('run_id', $payload['run_id'])->exists())->toBeFalse();
+});
+
+it('links a regenerated answer to the round it replaces and hides the old one from history', function () {
+    $user = (string) Str::uuid();
+    $thread = (string) Str::uuid();
+    $first = tracePayload(['thread_id' => $thread, 'assistant_message_id' => 'msg-a-old', 'answer' => '旧回答']);
+    $this->postJson('/api/v3/agent-traces', $first, agentHeaders($user))->assertCreated();
+
+    $again = tracePayload(['thread_id' => $thread, 'assistant_message_id' => 'msg-a-new', 'answer' => '新回答', 'replaces_message_id' => 'msg-a-old']);
+    $this->postJson('/api/v3/agent-traces', $again, agentHeaders($user))->assertCreated();
+
+    expect(AgentRun::where('run_id', $again['run_id'])->value('replaces_run_id'))->toBe($first['run_id']);
+    $this->getJson("/api/v3/me/agent-threads/{$thread}", authHeader($user))
+        ->assertOk()
+        ->assertJsonCount(1, 'data.runs')
+        ->assertJsonPath('data.runs.0.answer', '新回答');
+});
+
+it('records a denied run that never reached the agent', function () {
+    $payload = tracePayload(['status' => 'denied', 'answer' => null, 'evidence' => null, 'steps' => []]);
+
+    $this->postJson('/api/v3/agent-traces', $payload, agentHeaders())->assertCreated();
+
+    expect(AgentRun::where('run_id', $payload['run_id'])->value('status'))->toBe('denied');
+});
+
+it('rejects an unknown status', function () {
+    $this->postJson('/api/v3/agent-traces', tracePayload(['status' => 'weird']), agentHeaders())
+        ->assertUnprocessable()
+        ->assertJsonValidationErrors('status');
+});
+
+it('rejects an unknown step kind', function () {
+    $this->postJson('/api/v3/agent-traces', tracePayload([
+        'steps' => [['seq' => 0, 'kind' => 'bogus']],
+    ]), agentHeaders())
+        ->assertUnprocessable()
+        ->assertJsonValidationErrors('steps.0.kind');
+});