feat:M6 草稿核对器落地并真机验收通过——UNKNOWN 任务草稿箱核对补回执:

1. DraftReconciler:UNKNOWN 任务→草稿 Tab 树定位导航→逐屏 OCR+标题分片模糊命中→recordReceipt 补回执;未命中保留 UNKNOWN 不盲判失败(设计口径)。
2. CrossPublishTaskStore.unknownTaskIds() 真库查询;造数模式广播(seedTitle 真库造 UNKNOWN attempt,验证命中路径)。
3. 真机全链验收:造数 UNKNOWN→草稿 Tab→OCR 88 行→模糊命中→CONFIRMED→任务 DRAFT_SAVED(真库 sqlite 验证);空场景正确早退。
4. 归账语义修正:recordReceipt 内部已转 DRAFT_SAVED,不 resume 到 READY(重复发布风险;resumeAfterPageCheck 是 PAUSED 任务专用)。
5. 状态机细节钉死:READY→EDITING 只能经 claimNextReady(transition 表无此边)。
6. 作品管理页真机取证(Tab/条目结构)——正式发布核对对象,待 M6 长跑后接入。
7. 282 项 JVM 全过。

Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
2026-11-16 07:59:30 +08:00
co-authored by Claude Code
parent d42a1ad05f
commit 294a80716a
4 changed files with 281 additions and 0 deletions
@@ -439,6 +439,8 @@ class HaoRuiAccessibilityService : AccessibilityService() {
addAction("com.haorui.app.ACTION_TEST_CROSS_VIDEO")
// M6 协调器真机接线端到端(debug APK:入队→门控→领取→落库→执行→归账)
addAction("com.haorui.app.ACTION_TEST_CROSS_DISPATCH")
// M6 草稿核对器(debug APK:UNKNOWN 任务→草稿箱 OCR 匹配→补回执归账)
addAction("com.haorui.app.ACTION_TEST_RECONCILE")
}
@Suppress("UnspecifiedRegisterReceiverFlag")
registerReceiver(cmdReceiver, filter)
@@ -687,6 +689,95 @@ class HaoRuiAccessibilityService : AccessibilityService() {
val accepted = startCrossVideoDraftSandbox()
RunLogger.i(TAG, "跨平台视频草稿沙盒受理=$accepted(广播 ACTION_TEST_CROSS_VIDEO)")
}
// M6 草稿核对器:UNKNOWN 任务→草稿箱核对→补回执归账(主体 IO 协程,同分发沙盒模式)
"com.haorui.app.ACTION_TEST_RECONCILE" -> {
val seedTitle = intent.getStringExtra("seedTitle")
automationScope.launch {
val taskStore = com.haorui.app.crossplatform.data.CrossPublishTaskStore.get(applicationContext)
// 造数模式(debug):往真实库登记 UNKNOWN 任务+attempt(验证核对器命中路径;
// seedTitle 必须是草稿箱里真实存在的草稿标题,命中后补回执+resume)
if (!seedTitle.isNullOrBlank()) {
RunLogger.i(TAG, "M6 核对造数:开始(seed=${seedTitle.take(20)})")
try {
val generation = currentCrossRunGeneration() ?: run {
crossRunSession?.configure(true)
crossRunSession?.start()
var opened: Long? = null
for (i in 1..15) {
kotlinx.coroutines.delay(1_000)
opened = currentCrossRunGeneration()
if (opened != null) break
}
opened
}
if (generation == null) {
RunLogger.w(TAG, "M6 核对造数:无运行代际")
return@launch
}
val now = System.currentTimeMillis()
val task = com.haorui.app.crossplatform.model.CrossPublishTask(
id = "m6-reconcile-${java.util.UUID.randomUUID().toString().take(8)}",
accountKey = "sandbox-reconcile",
eventId = "m6-evt-r-${System.currentTimeMillis()}",
contentKind = com.haorui.app.crossplatform.model.CrossContentKind.VIDEO,
title = seedTitle,
sourcePlatform = "sandbox",
sourceUrl = "https://sandbox.local/seed",
runGeneration = generation,
publishedAtMs = now - 3_600_000L,
expiresAtMs = now + 86_400_000L,
payloadHash = "ab".repeat(32),
evidenceJson = """{"titleSeed":"核对造数","sourceText":"沙盒核对造数素材。"}""",
mediaPath = "/data/media/seed.mp4",
rightsRef = "own-seed",
bodyText = "核对造数占位正文。",
)
taskStore.enqueue(task)
taskStore.transition(
task.id,
com.haorui.app.crossplatform.model.CrossTaskState.DISCOVERED,
com.haorui.app.crossplatform.model.CrossTaskState.FILTERED,
generation, "核对造数·筛选",
)
taskStore.transition(
task.id,
com.haorui.app.crossplatform.model.CrossTaskState.FILTERED,
com.haorui.app.crossplatform.model.CrossTaskState.PREPARED,
generation, "核对造数·准备",
)
taskStore.transition(
task.id,
com.haorui.app.crossplatform.model.CrossTaskState.PREPARED,
com.haorui.app.crossplatform.model.CrossTaskState.READY,
generation, "核对造数·就绪",
)
// READY→EDITING 必须经 claimNextReady(transition 表无此边,
// EDITING 由领取事务设置——与协调器同款)
val claimed = taskStore.claimNextReady(generation, "sandbox-reconcile")
if (claimed == null || claimed.id != task.id) {
RunLogger.w(TAG, "M6 核对造数:claimNextReady 失败或领取到其他任务")
return@launch
}
val attempt = taskStore.beginSubmission(task.id, generation, com.haorui.app.crossplatform.model.CrossSubmissionMode.DRAFT)
if (attempt != null) {
taskStore.markSubmissionUnknown(attempt.id, "核对造数:模拟崩溃后结果未知")
RunLogger.i(TAG, "M6 核对造数完成:task=${task.id} attempt=${attempt.id} → UNKNOWN")
} else {
RunLogger.w(TAG, "M6 核对造数:beginSubmission 失败(policy 拒绝——payloadHash/发布时间/有效期/媒体/许可校验未过或代际不符)")
}
} catch (t: Throwable) {
RunLogger.e(TAG, "M6 核对造数异常: ${t.javaClass.simpleName}:${t.message}", t)
}
}
val reconciler = com.haorui.app.crossplatform.publish.DraftReconciler(
this@HaoRuiAccessibilityService,
taskStore,
) { msg -> RunLogger.i(TAG, "M6-Reconcile: $msg") }
val report = reconciler.reconcileAll()
RunLogger.i(TAG, "M6 草稿核对结果:$report")
}
RunLogger.i(TAG, "草稿核对受理(广播 ACTION_TEST_RECONCILE seed=${!seedTitle.isNullOrBlank()})")
}
// M6 协调器真机接线端到端:入队→门控→领取→落库→桥接执行→归账
"com.haorui.app.ACTION_TEST_CROSS_DISPATCH" -> {
val accepted = startCrossDispatchSandbox()
@@ -321,6 +321,13 @@ class CrossPublishTaskStore private constructor(context: Context) : CrossRunPers
db.query("attempts", null, "task_id=?", arrayOf(taskId), null, null, "created_at,id").use { c -> buildList { while (c.moveToNext()) add(attemptRow(c)) } }
}
/** 全部 RESULT_UNKNOWN 任务的 id(草稿核对器遍历用;M6 恢复场景)。 */
suspend fun unknownTaskIds(): List<String> = read { db ->
db.query("tasks", arrayOf("id"), "state='RESULT_UNKNOWN'", null, null, null, "updated_at").use { c ->
buildList { while (c.moveToNext()) add(c.getString(0)) }
}
}
suspend fun budgetUsage(accountKey: String, dayKey: String): CrossBudgetUsage = read { db ->
val entries = ledger(db, accountKey)
val baseline = db.rawQuery("SELECT legacy_used FROM budgets WHERE account_key=? AND day_key=?", arrayOf(accountKey, dayKey)).use { if (it.moveToFirst()) it.getInt(0) else 0 }
@@ -0,0 +1,182 @@
package com.haorui.app.crossplatform.publish
import android.graphics.Bitmap
import com.haorui.app.automation.HaoRuiAccessibilityService
import com.haorui.app.automation.RunLogger
import com.haorui.app.crossplatform.data.CrossPublishTaskStore
import com.haorui.app.crossplatform.model.CrossAttemptState
import com.haorui.app.crossplatform.model.CrossTaskState
import com.haorui.app.ocr.OcrProcessor
import com.haorui.app.ocr.ScreenCapturer
import com.haorui.app.ocr.OcrTextLine
/**
* 草稿核对器(M6 恢复场景,2026-11-16):UNKNOWN 结果任务 → 草稿箱核对 → 归账。
*
* 设计口径(跨平台自动发布设计 §手机任务库与防重复):
* "崩溃后先核对作品管理。找到当前账号的匹配新作品则补回执;无法确认是否提交时
* RESULT_UNKNOWN,不盲目重发,列表暂未出现不能当作确定失败。"
*
* DRAFT 车道的核对对象=**草稿箱**(正式发布的作品管理核对待 M6 长跑验收后接入)。
*
* 页面取证(2026-11-16 真机):
* - 草稿箱入口:「我的」页底部 Tab「草稿」(与作品/收藏/赞过并列);
* - 草稿条目:封面+标题(可能截断)——OCR 按标题匹配;
* - 标题匹配用分片模糊(ArticleTextPolicy.fuzzyContains,OCR 单字误读容忍)。
*
* 归账语义(保守):
* - 草稿箱命中标题 → recordReceipt(补回执,额度结算);
* - 未命中 → **保留 UNKNOWN**(列表暂未出现≠未提交——草稿箱可能分页/加载中);
* - 「我的」页 Tab 用树定位(原生页),条目读用 OCR。
*/
class DraftReconciler(
private val service: HaoRuiAccessibilityService,
private val store: CrossPublishTaskStore,
private val logger: (String) -> Unit = {},
) {
companion object {
private const val TAG = "Draft-Reconcile"
private const val NAV_TIMEOUT_MS = 60_000L
private const val MAX_SCREENS = 6
private const val MIN_CAPTURE_INTERVAL_MS = 1_200L
}
/** 核对结果。 */
data class Report(
val matchedCount: Int,
val pendingCount: Int,
val reason: String = "",
)
private var lastCaptureAtMs = 0L
/**
* 核对全部 UNKNOWN 任务的草稿箱存在性并归账。
* 流程:我的页(launchApp+底部 tab)→ 草稿 Tab → 逐屏 OCR → 标题匹配 → 归账。
*/
suspend fun reconcileAll(): Report {
val unknownTasks = collectUnknownTasks()
if (unknownTasks.isEmpty()) {
logger("无 UNKNOWN 任务待核对")
return Report(0, 0, "无待核对任务")
}
logger("待核对 UNKNOWN 任务 ${unknownTasks.size} 个")
if (!openDraftTab()) {
return Report(0, unknownTasks.size, "草稿箱导航失败")
}
// 逐屏 OCR 收集草稿标题行
val lines = mutableListOf<String>()
val seen = HashSet<String>()
var noNewCount = 0
for (screen in 0 until MAX_SCREENS) {
val current = screenOcrLines()
if (current.isEmpty()) {
Thread.sleep(800)
continue
}
var appended = 0
current.forEach { if (seen.add(it)) { lines.add(it); appended++ } }
if (appended == 0) {
noNewCount++
if (noNewCount >= 2) break
} else {
noNewCount = 0
}
val scrolled = kotlinx.coroutines.runBlocking {
service.gestures.swipe(0.5f, 0.70f, 0.5f, 0.30f)
}
if (!scrolled) break
Thread.sleep(1_000)
}
logger("草稿箱 OCR 共 ${lines.size} 行")
// 标题匹配归账
var matched = 0
var pending = 0
val generation = store.currentGeneration()
for ((id, title) in unknownTasks) {
val hit = ArticleTextPolicy.fuzzyContains(lines.joinToString("\n"), title)
if (hit && generation != null) {
val attempts = store.attempts(id)
val unknown = attempts.firstOrNull { it.state == CrossAttemptState.UNKNOWN }
if (unknown != null) {
// recordReceipt 内部已把任务转 DRAFT_SAVED(草稿车道终态)——
// ⚠️ 不 resume 到 READY(重复发布风险;resumeAfterPageCheck 语义是
// PAUSED 任务复核后重入,UNKNOWN+CONFIRMED 不适用)
store.recordReceipt(unknown.id, "草稿箱核对命中:$title")
logger("任务 $id 补回执(recordReceipt 内部转 DRAFT_SAVED)")
} else {
logger("任务 $id 草稿命中但无 UNKNOWN attempt(已是终态),跳过")
}
matched++
} else {
pending++
logger("任务 $id 草稿箱未命中,保留 UNKNOWN(不盲判失败)")
}
}
kotlinx.coroutines.runBlocking { service.gestures.home() }
return Report(matched, pending)
}
/** 全部 UNKNOWN 任务的 (id, title)。 */
private suspend fun collectUnknownTasks(): List<Pair<String, String>> {
val result = mutableListOf<Pair<String, String>>()
for (id in store.unknownTaskIds()) {
store.find(id)?.let { result.add(id to it.title) }
}
return result
}
/** 导航到「我的」页草稿 Tab(树定位;原生页)。 */
private suspend fun openDraftTab(): Boolean {
val deadline = android.os.SystemClock.elapsedRealtime() + NAV_TIMEOUT_MS
while (android.os.SystemClock.elapsedRealtime() < deadline) {
if (service.currentPackage() != "com.ss.android.article.news") {
service.launchApp("com.ss.android.article.news")
Thread.sleep(1_500)
continue
}
// 已在「我的」页(关注/粉丝特征)→ 点草稿 Tab
val root = service.root()
val draftTab = try {
if (root?.packageName?.toString() == "com.ss.android.article.news") {
com.haorui.app.automation.NodeLocator.byText(root, "草稿")
} else null
} finally { root?.recycle() }
if (draftTab != null) {
val ok = kotlinx.coroutines.runBlocking { service.gestures.tapNode(draftTab) }
runCatching { draftTab.recycle() }
if (ok) {
logger("已进入草稿 Tab")
Thread.sleep(1_500)
return true
}
}
// 不在我的页 → 点底栏「我的」(等分第 5 格)
val myTab = kotlinx.coroutines.runBlocking {
service.gestures.tapAt(972, 2159)
}
if (!myTab) Thread.sleep(1_000)
Thread.sleep(1_500)
}
return false
}
/** 单屏 OCR(节流防 takeScreenshot 限流)。 */
private fun screenOcrLines(): List<String> {
val since = android.os.SystemClock.elapsedRealtime() - lastCaptureAtMs
if (since < MIN_CAPTURE_INTERVAL_MS) Thread.sleep(MIN_CAPTURE_INTERVAL_MS - since)
lastCaptureAtMs = android.os.SystemClock.elapsedRealtime()
val bitmap: Bitmap = kotlinx.coroutines.runBlocking {
ScreenCapturer(service).capture()
} ?: return emptyList()
return try {
kotlinx.coroutines.runBlocking { OcrProcessor.recognize(bitmap) }
.flatMap { it.lines }
.map { it.text.trim() }
.filter { it.isNotEmpty() }
} finally {
bitmap.recycle()
}
}
}