From d8eda165ec005c2ead02874c2b03ddc8677a2c22 Mon Sep 17 00:00:00 2001 From: 07xh <3267597860@qq.com> Date: Wed, 18 Nov 2026 11:31:35 +0800 Subject: [PATCH 1/9] feat(cortex): add isolated secure gateway and durable feedback ledger --- .../personal/momoflow/CortexGatewayService.kt | 83 +++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 app/src/main/java/io/github/personal/momoflow/CortexGatewayService.kt diff --git a/app/src/main/java/io/github/personal/momoflow/CortexGatewayService.kt b/app/src/main/java/io/github/personal/momoflow/CortexGatewayService.kt new file mode 100644 index 0000000..e290f61 --- /dev/null +++ b/app/src/main/java/io/github/personal/momoflow/CortexGatewayService.kt @@ -0,0 +1,83 @@ +package io.github.personal.momoflow + +import org.json.JSONObject +import java.net.HttpURLConnection +import java.net.URL + +/** + * Isolated Cortex HTTP boundary, based on the supplied 5.6.10 gateway evidence. + * Only verified read endpoints and explicit legacy-token exchange are exposed. + * The speculative protobuf uplink is intentionally NOT available here. + */ +class CortexGatewayService { + private val origin = "https://cortex.maimemo.com/cortex" + + fun exchangeLegacyToken(legacyToken: String): String { + require(legacyToken.isNotBlank()) { "旧版登录 Token 不能为空" } + val result = request("POST", "/api/v1/tokens/exchange", null, + JSONObject().put("legacy_token", legacyToken.trim())) + val payload = result.optJSONObject("data") ?: result + val tokens = payload.optJSONObject("tokens") ?: payload + val access = tokens.optString("access_token").ifBlank { + tokens.optString("accessToken") + } + if (access.isBlank()) throw ApiException("Cortex 换取接口未返回 access_token;未保存凭证") + return access + } + + /** Unmodified server JSON: callers must not assume a checkpoint field's shape. */ + fun checkpoints(accessToken: String): JSONObject = + request("GET", "/api/v1/study/checkpoints", accessToken) + + /** Aggregate-only read, never treated as per-word feedback confirmation. */ + fun overview(accessToken: String): JSONObject = + request("GET", "/api/v1/study/overview", accessToken) + + private fun request( + method: String, path: String, accessToken: String?, + payload: JSONObject? = null + ): JSONObject { + require(path in setOf( + "/api/v1/tokens/exchange", "/api/v1/study/checkpoints", "/api/v1/study/overview" + )) { "未登记的 Cortex 端点" } + if (method == "GET") require(!accessToken.isNullOrBlank()) + val connection = (URL(origin + path).openConnection() as HttpURLConnection) + try { + connection.requestMethod = method + connection.instanceFollowRedirects = false // never forward credentials + connection.connectTimeout = 10_000 + connection.readTimeout = 15_000 + connection.setRequestProperty("Accept", "application/json") + if (!accessToken.isNullOrBlank()) + connection.setRequestProperty("Authorization", "Bearer ${accessToken.trim()}") + if (payload != null) { + connection.doOutput = true + connection.setRequestProperty("Content-Type", "application/json; charset=utf-8") + connection.outputStream.use { + it.write(payload.toString().toByteArray(Charsets.UTF_8)) + } + } + val status = connection.responseCode + if (status == 401 || status == 403) throw ApiException("Cortex 身份验证失败(HTTP $status)") + if (status == 429) throw ApiException("Cortex 请求过于频繁,请稍后再试") + if (status !in 200..299) throw ApiException("Cortex 接口返回 HTTP $status") + val raw = connection.inputStream.use { input -> + val bytes = input.readBytes() + if (bytes.size > 512 * 1024) throw ApiException("Cortex 响应过大") + bytes.toString(Charsets.UTF_8) + } + val json = try { JSONObject(raw) } + catch (_: Exception) { throw ApiException("Cortex 响应不是有效 JSON") } + if (json.has("success") && !json.optBoolean("success", true)) + throw ApiException("Cortex 服务端表示请求失败") + return json + } catch (e: ApiException) { + throw e + } catch (_: Exception) { + // Never expose request URLs with query parameters, headers, or tokens. + throw ApiException("Cortex 网络连接异常,请检查网络与账号会话") + } finally { + connection.disconnect() + } + } +} From 13883781ac42c570e9f3502ca0967e7b0f1b7195 Mon Sep 17 00:00:00 2001 From: 07xh <3267597860@qq.com> Date: Wed, 18 Nov 2026 11:31:38 +0800 Subject: [PATCH 2/9] feat(cortex): add isolated secure gateway and durable feedback ledger --- .../momoflow/CortexCredentialStore.kt | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 app/src/main/java/io/github/personal/momoflow/CortexCredentialStore.kt diff --git a/app/src/main/java/io/github/personal/momoflow/CortexCredentialStore.kt b/app/src/main/java/io/github/personal/momoflow/CortexCredentialStore.kt new file mode 100644 index 0000000..4e5fc1d --- /dev/null +++ b/app/src/main/java/io/github/personal/momoflow/CortexCredentialStore.kt @@ -0,0 +1,59 @@ +package io.github.personal.momoflow + +import android.content.Context +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import android.util.Base64 +import java.security.KeyStore +import javax.crypto.Cipher +import javax.crypto.KeyGenerator +import javax.crypto.spec.GCMParameterSpec + +/** + * Cortex access token is separate from the Open API token. Do not persist the + * legacy token supplied to exchangeLegacyToken(), or put secrets in preferences. + */ +class CortexCredentialStore(context: Context) { + private val prefs = context.getSharedPreferences("momoflow_cortex_secret", Context.MODE_PRIVATE) + private val alias = "momoflow_cortex_access_v1" + private val flags = Base64.NO_WRAP + + fun saveAccessToken(token: String) { + require(token.isNotBlank()) + val ks = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } + if (!ks.containsAlias(alias)) { + val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore") + generator.init(KeyGenParameterSpec.Builder( + alias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT + ).setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .setKeySize(256).build()) + generator.generateKey() + } + val cipher = Cipher.getInstance("AES/GCM/NoPadding") + cipher.init(Cipher.ENCRYPT_MODE, ks.getKey(alias, null)) + val ciphertext = cipher.doFinal(token.trim().toByteArray(Charsets.UTF_8)) + check(prefs.edit() + .putString("iv", Base64.encodeToString(cipher.iv, flags)) + .putString("ciphertext", Base64.encodeToString(ciphertext, flags)) + .commit()) { "Cortex 凭证未能安全保存" } + } + + fun accessToken(): String? { + val iv = prefs.getString("iv", null) ?: return null + val ciphertext = prefs.getString("ciphertext", null) ?: return null + return try { + val ks = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } + val cipher = Cipher.getInstance("AES/GCM/NoPadding") + cipher.init(Cipher.DECRYPT_MODE, ks.getKey(alias, null), + GCMParameterSpec(128, Base64.decode(iv, flags))) + String(cipher.doFinal(Base64.decode(ciphertext, flags)), Charsets.UTF_8) + } catch (_: Exception) { + null + } + } + + fun clear() { + check(prefs.edit().clear().commit()) { "Cortex 凭证清除失败" } + } +} From 0330e4da2154a70033934b6ffaafd65393587ed8 Mon Sep 17 00:00:00 2001 From: 07xh <3267597860@qq.com> Date: Wed, 18 Nov 2026 11:31:40 +0800 Subject: [PATCH 3/9] feat(cortex): add isolated secure gateway and durable feedback ledger --- .../personal/momoflow/CortexFeedbackLedger.kt | 112 ++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 app/src/main/java/io/github/personal/momoflow/CortexFeedbackLedger.kt diff --git a/app/src/main/java/io/github/personal/momoflow/CortexFeedbackLedger.kt b/app/src/main/java/io/github/personal/momoflow/CortexFeedbackLedger.kt new file mode 100644 index 0000000..0a5b410 --- /dev/null +++ b/app/src/main/java/io/github/personal/momoflow/CortexFeedbackLedger.kt @@ -0,0 +1,112 @@ +package io.github.personal.momoflow + +import android.content.Context +import org.json.JSONObject +import java.security.MessageDigest +import java.util.UUID + +/** Three states shown to users, regardless of whether transport was foreground or Cortex. */ +enum class FeedbackOutcome(val label: String) { + PENDING("待确认"), SUCCEEDED("已成功"), FAILED("已失败") +} + +object FeedbackOutcomePolicy { + fun fromOfficialReadback(status: OfficialSyncStatus): FeedbackOutcome = when (status) { + OfficialSyncStatus.OBSERVED_MATCH -> FeedbackOutcome.SUCCEEDED + OfficialSyncStatus.CONFLICT, OfficialSyncStatus.INVALID_WORD -> FeedbackOutcome.FAILED + else -> FeedbackOutcome.PENDING + } +} + +data class FeedbackOperation( + val id: String, + val vocId: String, + val mark: LocalMark, + val day: String, + val accountDigest: String, + val outcome: FeedbackOutcome, + val explanation: String, +) { + fun toJson(): JSONObject = JSONObject() + .put("id", id).put("voc_id", vocId).put("mark", mark.wire) + .put("day", day).put("account_digest", accountDigest) + .put("outcome", outcome.name).put("explanation", explanation) + + companion object { + fun parse(o: JSONObject) = FeedbackOperation( + o.getString("id"), o.getString("voc_id"), + LocalMark.entries.first { it.wire == o.getString("mark") }, + o.getString("day"), o.getString("account_digest"), + FeedbackOutcome.valueOf(o.getString("outcome")), + o.optString("explanation"), + ) + } +} + +/** + * Committed before the user leaves for a foreground action. A pending item + * survives process death; it is never silently treated as a successful write. + * Transaction records contain no Bearer token, cookies or passwords. + */ +class CortexFeedbackLedger(context: Context) { + private val prefs = context.getSharedPreferences("momoflow_cortex_ledger", Context.MODE_PRIVATE) + + private fun digest(token: String): String = + MessageDigest.getInstance("SHA-256") + .digest(token.toByteArray(Charsets.UTF_8)) + .joinToString("") { "%02x".format(it.toInt() and 0xff) } + + private fun key(vocId: String): String = "operation." + MessageDigest.getInstance("SHA-256") + .digest(vocId.toByteArray(Charsets.UTF_8)) + .joinToString("") { "%02x".format(it.toInt() and 0xff) } + + @Synchronized + fun current(vocId: String, openApiToken: String): FeedbackOperation? = try { + prefs.getString(key(vocId), null)?.let { FeedbackOperation.parse(JSONObject(it)) } + ?.takeIf { it.accountDigest == digest(openApiToken) && it.day == StudyDay.today() } + } catch (_: Exception) { null } + + /** + * A second notification tap does not mint another operation while the + * original is unresolved; a different mark must be cancelled first. + */ + @Synchronized + fun begin(vocId: String, mark: LocalMark, openApiToken: String): FeedbackOperation { + val existing = current(vocId, openApiToken) + if (existing?.outcome == FeedbackOutcome.PENDING) { + check(existing.mark == mark) { "该单词已有待确认的另一种反馈,请先核验或取消" } + return existing + } + val operation = FeedbackOperation( + UUID.randomUUID().toString(), vocId, mark, StudyDay.today(), + digest(openApiToken), FeedbackOutcome.PENDING, "已建立基线,等待墨墨官方记录回读" + ) + check(prefs.edit().putString(key(vocId), operation.toJson().toString()).commit()) { + "无法保存反馈事务,未执行任何操作" + } + return operation + } + + @Synchronized + fun recordReadback( + vocId: String, openApiToken: String, + status: OfficialSyncStatus, explanation: String + ): FeedbackOperation? { + val existing = current(vocId, openApiToken) ?: return null + if (existing.outcome != FeedbackOutcome.PENDING) return existing + val updated = existing.copy( + outcome = FeedbackOutcomePolicy.fromOfficialReadback(status), + explanation = explanation.take(800) + ) + check(prefs.edit().putString(key(vocId), updated.toJson().toString()).commit()) + return updated + } + + @Synchronized + fun cancel(vocId: String, openApiToken: String) { + val existing = current(vocId, openApiToken) ?: return + if (existing.outcome != FeedbackOutcome.PENDING) return + val updated = existing.copy(outcome = FeedbackOutcome.FAILED, explanation = "操作已取消,未确认服务端反馈") + check(prefs.edit().putString(key(vocId), updated.toJson().toString()).commit()) + } +} From 1b559ad29e25ea1fd3646d279079f36789574835 Mon Sep 17 00:00:00 2001 From: 07xh <3267597860@qq.com> Date: Wed, 18 Nov 2026 11:32:12 +0800 Subject: [PATCH 4/9] fix(cortex): prevent repeated foreground actions while a transaction is pending --- .../java/io/github/personal/momoflow/CortexFeedbackLedger.kt | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/io/github/personal/momoflow/CortexFeedbackLedger.kt b/app/src/main/java/io/github/personal/momoflow/CortexFeedbackLedger.kt index 0a5b410..2ffbd61 100644 --- a/app/src/main/java/io/github/personal/momoflow/CortexFeedbackLedger.kt +++ b/app/src/main/java/io/github/personal/momoflow/CortexFeedbackLedger.kt @@ -73,9 +73,8 @@ class CortexFeedbackLedger(context: Context) { @Synchronized fun begin(vocId: String, mark: LocalMark, openApiToken: String): FeedbackOperation { val existing = current(vocId, openApiToken) - if (existing?.outcome == FeedbackOutcome.PENDING) { - check(existing.mark == mark) { "该单词已有待确认的另一种反馈,请先核验或取消" } - return existing + check(existing?.outcome != FeedbackOutcome.PENDING) { + "该单词已有待确认反馈,请先核验或取消,不能重复发起" } val operation = FeedbackOperation( UUID.randomUUID().toString(), vocId, mark, StudyDay.today(), From c1a3e660b73b250f7ebf3cf8e452f6b04fdc1b8c Mon Sep 17 00:00:00 2001 From: 07xh <3267597860@qq.com> Date: Wed, 18 Nov 2026 11:32:53 +0800 Subject: [PATCH 5/9] feat(cortex): wire secure account connectivity and three-state official readback into UI --- .../github/personal/momoflow/MainActivity.kt | 133 +++++++++++++++++- 1 file changed, 131 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/io/github/personal/momoflow/MainActivity.kt b/app/src/main/java/io/github/personal/momoflow/MainActivity.kt index 49ace56..e19ef5a 100644 --- a/app/src/main/java/io/github/personal/momoflow/MainActivity.kt +++ b/app/src/main/java/io/github/personal/momoflow/MainActivity.kt @@ -39,6 +39,8 @@ class MainActivity : Activity() { private var syncing = false private var trialBusy = false private var trialStatus = "" + private var cortexBusy = false + private var cortexStatus = "" private var queryingWordId: String? = null private var message: String = "" @@ -305,8 +307,9 @@ class MainActivity : Activity() { trialPane.addView(horizontal( button(if (trialBusy) "核对中…" else "验证官方记录") { verifyOfficialTrial() }, button("取消本次验证", false) { + store.token()?.let { CortexFeedbackLedger(this).cancel(pending.wordId, it) } OfficialTrialStore(this).clear() - trialStatus = "已取消验证,未向墨墨提交任何操作。" + trialStatus = "已取消本次验证;事务记为已失败,没有确认官方写回。" draw() } )) @@ -340,6 +343,68 @@ class MainActivity : Activity() { column.addView(trialPane) column.addView(gap(14)) + // Cortex connectivity and persisted result are independent of the + // existing notification and foreground action path. + val cortexPane = pane() + cortexPane.addView(label("Cortex 连接与三态结果", 16f, ink, true)) + cortexPane.addView(gap(6)) + val cortexCredentials = CortexCredentialStore(this) + cortexPane.addView(label( + if (cortexCredentials.accessToken() == null) + "尚未配置 Cortex 授权(与开放 API Token 独立)。" + else "已加密保存 Cortex 授权;可读取检查点。", + 12f, muted + )) + if (snapshot != null && snapshot.words.isNotEmpty()) { + val current = snapshot.words[store.index().coerceIn(0, snapshot.words.lastIndex)] + val token = store.token() + val ledger = if (token == null) null else CortexFeedbackLedger(this).current(current.id, token) + cortexPane.addView(gap(7)) + cortexPane.addView(label( + if (ledger == null) "当前词:无待确认事务" + else "当前词:${ledger.outcome.label} · ${ledger.mark.label}(${ledger.explanation})", + 12f, if (ledger?.outcome == FeedbackOutcome.FAILED) Color.parseColor("#A34A36") else muted + )) + } + cortexPane.addView(gap(9)) + val legacyTokenEntry = EditText(this).apply { + hint = "旧版登录 Token(仅用于单次交换)" + setSingleLine(true) + inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD + textSize = 13f + background = rounded(Color.parseColor("#F1F6FF"), 12, Color.parseColor("#D8E6F7")) + setPadding(dp(12), dp(8), dp(12), dp(8)) + } + cortexPane.addView(legacyTokenEntry, LinearLayout.LayoutParams(-1, dp(46))) + cortexPane.addView(gap(7)) + val exchangeButton = button("交换并加密保存 Cortex 授权", false) { + val submittedToken = legacyTokenEntry.text.toString() + legacyTokenEntry.text.clear() + exchangeCortex(submittedToken) + } + exchangeButton.isEnabled = !cortexBusy + cortexPane.addView(exchangeButton) + cortexPane.addView(gap(7)) + cortexPane.addView(horizontal( + button("检查连接与检查点", false) { inspectCortex() }, + button("清除 Cortex 授权", false) { + cortexCredentials.clear() + cortexStatus = "Cortex 授权已清除" + draw() + } + )) + if (cortexStatus.isNotBlank()) { + cortexPane.addView(gap(7)) + cortexPane.addView(label(cortexStatus, 12f, muted)) + } + cortexPane.addView(gap(6)) + cortexPane.addView(label( + "已接入授权交换和只读同步检查;Cortex 直接上传仍需真实字段号及同词回读验证。原有前台反馈可以继续使用。", + 11f, muted + )) + column.addView(cortexPane) + column.addView(gap(14)) + val toolsPane = pane() toolsPane.addView(label("流体云与快捷入口", 16f, ink, true)) toolsPane.addView(gap(6)) @@ -424,6 +489,14 @@ class MainActivity : Activity() { ?: throw ApiException("官方今日列表未返回该词;请先在墨墨完成当天初始化并重新同步") runOnUiThread { if (token != store.token()) { trialBusy = false; trialStatus = "账号已变化,本次验证取消"; draw(); return@runOnUiThread } + try { + CortexFeedbackLedger(this).begin(word.id, mark, token) + } catch (error: Exception) { + trialBusy = false + trialStatus = error.message ?: "已有待确认的反馈事务" + draw() + return@runOnUiThread + } OfficialTrialStore(this).clear() OfficialForegroundActionStore(this).clear() OfficialTrialStore(this).save(OfficialWritebackTrial( @@ -468,9 +541,13 @@ class MainActivity : Activity() { runOnUiThread { if (token != store.token()) { trialBusy = false; trialStatus = "账号已变化,不可比较"; draw(); return@runOnUiThread } trialBusy = false - trialStatus = OfficialSyncAssessment.explain( + val evaluation = OfficialSyncAssessment.evaluate( trial.before, current, trial.beforeToday, currentToday, trial.expected ) + trialStatus = evaluation.message + CortexFeedbackLedger(this).recordReadback( + trial.wordId, token, evaluation.status, trialStatus + ) OfficialTrialStore(this).saveReport(trialStatus) draw() } @@ -484,6 +561,58 @@ class MainActivity : Activity() { }.start() } + private fun exchangeCortex(legacyToken: String) { + if (cortexBusy) return + if (legacyToken.isBlank()) return hint("请填写本人旧版登录 Token;不能自动把开放 API Token 当作 Cortex 登录凭证") + cortexBusy = true + cortexStatus = "正在交换 Cortex 授权…" + draw() + Thread { + try { + val access = CortexGatewayService().exchangeLegacyToken(legacyToken) + CortexCredentialStore(this).saveAccessToken(access) + runOnUiThread { + cortexBusy = false + cortexStatus = "Cortex 授权交换成功,已独立加密存储;尚未执行任何写回" + draw() + } + } catch (error: Exception) { + runOnUiThread { + cortexBusy = false + cortexStatus = "授权交换未完成:${error.message ?: "网络异常"}" + draw() + } + } + }.start() + } + + private fun inspectCortex() { + if (cortexBusy) return + val access = CortexCredentialStore(this).accessToken() + ?: return hint("请先配置 Cortex 授权") + cortexBusy = true + cortexStatus = "正在检查 Cortex 服务…" + draw() + Thread { + try { + val gateway = CortexGatewayService() + gateway.checkpoints(access) + gateway.overview(access) + runOnUiThread { + cortexBusy = false + cortexStatus = "Cortex 授权、检查点与概览接口读取成功(只读);这不代表反馈已写入" + draw() + } + } catch (error: Exception) { + runOnUiThread { + cortexBusy = false + cortexStatus = "Cortex 读取失败:${error.message ?: "网络异常"}" + draw() + } + } + }.start() + } + private fun inspectMomo(word: StudyWord) { MomoInspectionStore(this).begin(word) trialStatus = "只读识别已开启 2 分钟。进入墨墨对应单词页面后返回,查看按钮识别报告。" From 53881bb0327e12e37b61d717118f8d63671a2dd6 Mon Sep 17 00:00:00 2001 From: 07xh <3267597860@qq.com> Date: Wed, 18 Nov 2026 11:33:40 +0800 Subject: [PATCH 6/9] test(cortex): document verification and cover conservative tri-state mapping --- .../momoflow/FeedbackOutcomePolicyTest.kt | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 app/src/test/java/io/github/personal/momoflow/FeedbackOutcomePolicyTest.kt diff --git a/app/src/test/java/io/github/personal/momoflow/FeedbackOutcomePolicyTest.kt b/app/src/test/java/io/github/personal/momoflow/FeedbackOutcomePolicyTest.kt new file mode 100644 index 0000000..e3c6430 --- /dev/null +++ b/app/src/test/java/io/github/personal/momoflow/FeedbackOutcomePolicyTest.kt @@ -0,0 +1,33 @@ +package io.github.personal.momoflow + +import org.junit.Assert.* +import org.junit.Test + +class FeedbackOutcomePolicyTest { + @Test fun serverReadbackHasThreeConservativeStates() { + assertEquals(FeedbackOutcome.SUCCEEDED, + FeedbackOutcomePolicy.fromOfficialReadback(OfficialSyncStatus.OBSERVED_MATCH)) + assertEquals(FeedbackOutcome.FAILED, + FeedbackOutcomePolicy.fromOfficialReadback(OfficialSyncStatus.CONFLICT)) + assertEquals(FeedbackOutcome.FAILED, + FeedbackOutcomePolicy.fromOfficialReadback(OfficialSyncStatus.INVALID_WORD)) + for (unresolved in listOf( + OfficialSyncStatus.INCOMPLETE, OfficialSyncStatus.UNCHANGED, + OfficialSyncStatus.UNCONFIRMED_CHANGE + )) assertEquals(FeedbackOutcome.PENDING, + FeedbackOutcomePolicy.fromOfficialReadback(unresolved)) + } + + @Test fun neverConfusesAndroidLocalMarkWithUnverifiedWireEnum() { + val adapter = CortexStudyAdapter() + val sample = StudyWord("test-12", "example", 1, false, false) + assertEquals(setOf(CortexResponseTag.FAMILIAR), + adapter.draft(sample, LocalMark.FAMILIAR).responseCandidates) + assertEquals(setOf(CortexResponseTag.UNCERTAIN, CortexResponseTag.VAGUE), + adapter.draft(sample, LocalMark.VAGUE).responseCandidates) + assertEquals(setOf(CortexResponseTag.FORGET), + adapter.draft(sample, LocalMark.FORGET).responseCandidates) + assertEquals(CortexSubmissionState.NOT_SENT_UNVERIFIED, + adapter.submit(adapter.draft(sample, LocalMark.FORGET)).state) + } +} From ceac98d412ac00b7a30e566fe0197dbd07342f4c Mon Sep 17 00:00:00 2001 From: 07xh <3267597860@qq.com> Date: Wed, 18 Nov 2026 11:33:43 +0800 Subject: [PATCH 7/9] test(cortex): document verification and cover conservative tri-state mapping --- docs/CORTEX_SERVICE_V1.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 docs/CORTEX_SERVICE_V1.md diff --git a/docs/CORTEX_SERVICE_V1.md b/docs/CORTEX_SERVICE_V1.md new file mode 100644 index 0000000..25a84f6 --- /dev/null +++ b/docs/CORTEX_SERVICE_V1.md @@ -0,0 +1,25 @@ +# Cortex 独立服务第一阶段接入(2026-11-18) + +## 本次实际代码 + +- `CortexGatewayService`:独立 HTTPS 通道,支持本人旧版登录 Token 的显式交换、`study/checkpoints` 与 `study/overview` 只读查询。禁止重定向携带授权;不记录完整 HTTP 响应、Token 或请求体。 +- `CortexCredentialStore`:独立 Android Keystore AES-GCM,避免把开放 API Token 当作 Cortex Token。旧版 Token 仅在内存中使用,交换完成后不落盘。 +- `CortexFeedbackLedger`:每个词的事务 ID、账号摘要、三态结果跨进程持久化。同词未决事务阻止重复触发;`OfficialSyncAssessment` 回读匹配后才将结果从「待确认」变为「已成功」,冲突变为「已失败」,延迟保持「待确认」。 +- `MainActivity`:增加 Cortex 授权交换与只读检查页面区域;现有通知按钮仍通过官方 App 前台点击,官方回读结果驱动三态展示。 +- `FeedbackOutcomePolicyTest`:验证回读三态判定,以及未验证上传不可误发。 + +## 必须区分 + +目前的「已成功」仅表示 **墨墨官方 Open API 记录观察到目标词、目标反馈的匹配变化**,不证明由 MomoFlow 发起,更不代表独立 Cortex 写入已成功。Cortex 的概览或检查点变化也不能替代单词级回读。 + +**本次没有启用自动 Cortex POST /study/oplog。** 上传包的 `mm_cortex_client.py` 采用猜测字段号,存在两套枚举混淆;其中 `verify` 会覆盖快照而不对比单词记录。将其直接塞进通知按钮会冒错误提交、重复提交的风险。 + +## 真机验收 + +1. 确认旧版登录 Token 换取 Cortex Bearer Token 真实可用(**不要**在日志、截图或仓库上传凭证)。 +2. 点击「检查连接与检查点」,明确只读成功或具体拒绝状态。 +3. 从现有通知按钮发起一个本人真实未完成词,确认重进 App 事务仍显示「待确认」,连续点击不会触发第二次操作。 +4. 在墨墨官方 App 中完成同词反馈,核对记录并显示「已成功」或「已失败」,离线/超时仍保持「待确认」。 +5. 下一阶段从真实、脱敏的运行时请求确认完整上传封包、字段号、同步顺序、幂等/冲突语义后,才把 `CortexAuthorizedSender` 从禁写换成真实发送器。 + +未运行 Android CI 或真机验证之前,不能将其标为发布可用。原有流体云及前台反馈行为未改动。 From 76e90bea4c87f4a014c17e87256d7e0cd4b2eaad Mon Sep 17 00:00:00 2001 From: 07xh <3267597860@qq.com> Date: Wed, 18 Nov 2026 11:35:05 +0800 Subject: [PATCH 8/9] fix(cortex): clear account-bound feedback history when Open API account changes --- .../java/io/github/personal/momoflow/CortexFeedbackLedger.kt | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/app/src/main/java/io/github/personal/momoflow/CortexFeedbackLedger.kt b/app/src/main/java/io/github/personal/momoflow/CortexFeedbackLedger.kt index 2ffbd61..386d3e6 100644 --- a/app/src/main/java/io/github/personal/momoflow/CortexFeedbackLedger.kt +++ b/app/src/main/java/io/github/personal/momoflow/CortexFeedbackLedger.kt @@ -101,6 +101,11 @@ class CortexFeedbackLedger(context: Context) { return updated } + @Synchronized + fun clear() { + check(prefs.edit().clear().commit()) { "无法清理旧账号的 Cortex 反馈事务" } + } + @Synchronized fun cancel(vocId: String, openApiToken: String) { val existing = current(vocId, openApiToken) ?: return From f588f0c4d49286464a4d964cdd26284364365d82 Mon Sep 17 00:00:00 2001 From: 07xh <3267597860@qq.com> Date: Wed, 18 Nov 2026 11:35:09 +0800 Subject: [PATCH 9/9] fix(cortex): invalidate prior Cortex credentials and ledger on account switch --- .../java/io/github/personal/momoflow/MainActivity.kt | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/io/github/personal/momoflow/MainActivity.kt b/app/src/main/java/io/github/personal/momoflow/MainActivity.kt index e19ef5a..f8d2385 100644 --- a/app/src/main/java/io/github/personal/momoflow/MainActivity.kt +++ b/app/src/main/java/io/github/personal/momoflow/MainActivity.kt @@ -169,6 +169,8 @@ class MainActivity : Activity() { try { LiveWordNotification.stop(this) store.clearStudyData() // no cross-account vocabulary leakage + CortexCredentialStore(this).clear() + CortexFeedbackLedger(this).clear() store.saveToken(token) WordWidget.updateAll(this) message = "Token 已保存,请点击同步;今天需先在墨墨 App 完成初始化。" @@ -177,7 +179,10 @@ class MainActivity : Activity() { }, button("清除授权", false) { LiveWordNotification.stop(this) - store.forgetToken(); store.clearStudyData(); message = "授权与学习缓存已清除"; draw() + store.forgetToken(); store.clearStudyData() + CortexCredentialStore(this).clear() + CortexFeedbackLedger(this).clear() + message = "授权与学习缓存已清除"; draw() WordWidget.updateAll(this) } )) @@ -362,7 +367,7 @@ class MainActivity : Activity() { cortexPane.addView(gap(7)) cortexPane.addView(label( if (ledger == null) "当前词:无待确认事务" - else "当前词:${ledger.outcome.label} · ${ledger.mark.label}(${ledger.explanation})", + else "当前词:${ledger.outcome.label} · ${ledger.mark.label}(官方前台反馈回读:${ledger.explanation})", 12f, if (ledger?.outcome == FeedbackOutcome.FAILED) Color.parseColor("#A34A36") else muted )) }