Skip to content

The agent that grows with you

feat(gateway): tell home channels once when a cron store goes unwritable and recovers

kshitijk4poor91fc7badafd2
diff --git a/gateway/cron_store_notices.py b/gateway/cron_store_notices.py
new file mode 100644
index 00000000000..ff36f92eb36
--- /dev/null
+++ b/gateway/cron_store_notices.py
@@ -0,0 +1,64 @@
+"""Home-channel notices for cron store degraded-state transitions (see ``cron/store_health.py``).
+
+The cron tick runs on a worker thread inside the gateway. When a profile's cron store becomes
+unwritable it reports ONE transition, and again when it recovers. Each one is posted to that
+profile's home channels, honouring that profile's warning-notification opt-out, through the same
+send path the state.db warning uses.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import logging
+from pathlib import Path
+
+from agent.i18n import t
+
+logger = logging.getLogger(__name__)
+
+
+def install_cron_store_notices(runner, loop: asyncio.AbstractEventLoop) -> None:
+ """Route store transitions from the ticker thread onto the gateway loop. Installed once the
+ adapters are connected, so a store that degraded during boot is announced then."""
+ from cron.store_health import degraded_records, set_transition_listener
+
+ def on_transition(event, record) -> None:
+ asyncio.run_coroutine_threadsafe(send_cron_store_notice(runner, event, record), loop)
+
+ set_transition_listener(on_transition)
+ for record in degraded_records():
+ on_transition("unwritable", record)
+
+
+def _profile_home(profile):
+ from hermes_constants import get_routing_process_hermes_home
+ if profile is None:
+ return get_routing_process_hermes_home()
+ from hermes_cli.profiles import get_profile_dir
+ return get_profile_dir(profile)
+
+
+async def send_cron_store_notice(runner, event: str, record) -> None:
+ """Post one ``unwritable``/``recovered`` notice to the home channels of the store's profile."""
+ from gateway.run import _async_profile_runtime_scope
+ from gateway.warning_notifications import present_notification
+ from hermes_constants import hermes_home_key
+
+ fields = record.notice_fields()
+ key = "gateway.cron_store.unwritable" if event == "unwritable" else "gateway.cron_store.recovered"
+ message = t(key, **fields)
+ store_home = hermes_home_key(Path(record.store).parent)
+ logger.info("Broadcasting cron store %s notice for %s", event, record.store)
+ for profile, platform, _cfg, home, transport in list(runner._served_home_channel_transports()):
+ profile_home = _profile_home(profile)
+ if hermes_home_key(profile_home) != store_home:
+ continue
+ # The opt-out is the owning profile's; the launch profile needs no extra scope.
+ scope = (_async_profile_runtime_scope(Path(profile_home)) if profile is not None
+ else contextlib.nullcontext())
+ async with scope:
+ await present_notification(
+ lambda: runner._send_home_channel_message(
+ platform, home, transport, message, "Cron store notice failed for %s:%s: %s"),
+ platform=platform)
diff --git a/gateway/run_startup.py b/gateway/run_startup.py
index 94b94172888..49d7b6bac44 100644
--- a/gateway/run_startup.py
+++ b/gateway/run_startup.py
@@ -1536,6 +1536,8 @@ class GatewayStartupMixin:
# Surface state.db init failures to messaging platforms before the user loses data.
# See #88235.
await self._send_session_db_warning_notifications()
+ from gateway.cron_store_notices import install_cron_store_notices
+ install_cron_store_notices(self, asyncio.get_running_loop())
# Resume recovered process watchers. Detach the batch atomically (fresh list, not clear(): a
# concurrent append during the yield must not be lost); yield every 100 to keep the loop live.
with _log_suppressed(logging.ERROR, "Recovered watcher setup error: %s"):
diff --git a/locales/af.yaml b/locales/af.yaml
index f2adeb8cc10..739c7e28d4d 100644
--- a/locales/af.yaml
+++ b/locales/af.yaml
@@ -847,6 +847,9 @@ gateway:
db_fts_corrupt: "⚠️ Sessie-databasis het 'n korrupsiefout gerapporteer wat beperk is tot die soekindeks (FTS5); die boodskaptabelle is nie beskadig nie. Boodskappe word moontlik nie bewaar totdat dit herstel is nie: voer `hermes {profile_arg}doctor --fix` uit en herbegin dan die gateway. Voer nie herstelgereedskap uit of herstel 'n rugsteun nie tensy `hermes {profile_arg}doctor` skade bevestig."
db_then_restart: "{action} Dan `hermes {profile_arg}gateway restart`."
db_unavailable: "⚠️ Sessie-databasis onbeskikbaar — boodskappe word moontlik nie gestoor nie en /resume sal leeg wees. Oorsaak: {cause}. {action}"
+ cron_store:
+ unwritable: "⚠️ Cron store {store} is not writable ({error}) since {since}. Scheduled jobs are being skipped until it accepts writes again. Fix: {fix}."
+ recovered: "✅ Cron store {store} is writable again; {skipped} skipped run(s), catching up once per job."
whoami:
scope_dm: "privaatgesprek"
scope_group: "groep/kanaal"
diff --git a/locales/ar.yaml b/locales/ar.yaml
index dfd656992d8..56c35c15724 100644
--- a/locales/ar.yaml
+++ b/locales/ar.yaml
@@ -847,6 +847,9 @@ gateway:
db_fts_corrupt: "⚠️ أفادت قاعدة بيانات الجلسات بخطأ تلف محصور في فهرس البحث (FTS5)؛ جداول الرسائل غير متضررة. قد لا تُحفظ الرسائل حتى إصلاحه: شغّل `hermes {profile_arg}doctor --fix` ثم أعد تشغيل البوّابة. لا تشغّل أدوات الاستعادة ولا تستعد نسخة احتياطية إلا إذا أكّد `hermes {profile_arg}doctor` وجود تلف."
db_then_restart: "{action} ثم `hermes {profile_arg}gateway restart`."
db_unavailable: "⚠️ قاعدة بيانات الجلسات غير متاحة — قد لا تُحفظ الرسائل وسيكون /resume فارغًا. السبب: {cause}. {action}"
+ cron_store:
+ unwritable: "⚠️ Cron store {store} is not writable ({error}) since {since}. Scheduled jobs are being skipped until it accepts writes again. Fix: {fix}."
+ recovered: "✅ Cron store {store} is writable again; {skipped} skipped run(s), catching up once per job."
whoami:
scope_dm: "رسالة خاصة"
scope_group: "مجموعة/قناة"
diff --git a/locales/de.yaml b/locales/de.yaml
index 05936df4814..a579efd7fb4 100644
--- a/locales/de.yaml
+++ b/locales/de.yaml
@@ -847,6 +847,9 @@ gateway:
db_fts_corrupt: "⚠️ Die Sitzungsdatenbank hat einen Beschädigungsfehler gemeldet, der auf den Suchindex (FTS5) beschränkt ist; die Nachrichtentabellen sind nicht beschädigt. Nachrichten werden bis zur Reparatur möglicherweise nicht gespeichert: Führen Sie `hermes {profile_arg}doctor --fix` aus und starten Sie dann das Gateway neu. Verwenden Sie keine Wiederherstellungstools und stellen Sie kein Backup wieder her, sofern `hermes {profile_arg}doctor` keinen Schaden bestätigt."
db_then_restart: "{action} Danach `hermes {profile_arg}gateway restart`."
db_unavailable: "⚠️ Sitzungsdatenbank nicht verfügbar — Nachrichten werden möglicherweise nicht gespeichert und /resume bleibt leer. Ursache: {cause}. {action}"
+ cron_store:
+ unwritable: "⚠️ Cron store {store} is not writable ({error}) since {since}. Scheduled jobs are being skipped until it accepts writes again. Fix: {fix}."
+ recovered: "✅ Cron store {store} is writable again; {skipped} skipped run(s), catching up once per job."
whoami:
scope_dm: "Direktnachricht"
scope_group: "Gruppe/Kanal"
diff --git a/locales/en.yaml b/locales/en.yaml
index 5415202a5dc..2c4b28cd29c 100644
--- a/locales/en.yaml
+++ b/locales/en.yaml
@@ -873,6 +873,9 @@ gateway:
db_fts_corrupt: "⚠️ Session database reported a corruption error confined to the search index (FTS5); the message tables are not damaged. Messages may not be persisted until it is repaired: run `hermes {profile_arg}doctor --fix`, then restart the gateway. Do not run recovery tools or restore a backup unless `hermes {profile_arg}doctor` confirms damage."
db_then_restart: "{action} Then `hermes {profile_arg}gateway restart`."
db_unavailable: "⚠️ Session database unavailable — messages may not be saved and /resume will be empty. Cause: {cause}. {action}"
+ cron_store:
+ unwritable: "⚠️ Cron store {store} is not writable ({error}) since {since}. Scheduled jobs are being skipped until it accepts writes again. Fix: {fix}."
+ recovered: "✅ Cron store {store} is writable again; {skipped} skipped run(s), catching up once per job."
whoami:
scope_dm: "DM"
diff --git a/locales/es.yaml b/locales/es.yaml
index 276124e4d57..4609856d8b3 100644
--- a/locales/es.yaml
+++ b/locales/es.yaml
@@ -847,6 +847,9 @@ gateway:
db_fts_corrupt: "⚠️ La base de datos de sesiones informó un error de corrupción limitado al índice de búsqueda (FTS5); las tablas de mensajes no están dañadas. Es posible que los mensajes no se guarden hasta repararlo: ejecuta `hermes {profile_arg}doctor --fix` y luego reinicia el gateway. No ejecutes herramientas de recuperación ni restaures una copia de seguridad a menos que `hermes {profile_arg}doctor` confirme daños."
db_then_restart: "{action} Luego ejecuta `hermes {profile_arg}gateway restart`."
db_unavailable: "⚠️ Base de datos de sesiones no disponible — es posible que los mensajes no se guarden y /resume estará vacío. Causa: {cause}. {action}"
+ cron_store:
+ unwritable: "⚠️ Cron store {store} is not writable ({error}) since {since}. Scheduled jobs are being skipped until it accepts writes again. Fix: {fix}."
+ recovered: "✅ Cron store {store} is writable again; {skipped} skipped run(s), catching up once per job."
whoami:
scope_dm: "MD"
scope_group: "grupo/canal"
diff --git a/locales/fr.yaml b/locales/fr.yaml
index 92614517902..e506bd1fdb0 100644
--- a/locales/fr.yaml
+++ b/locales/fr.yaml
@@ -1011,6 +1011,9 @@ gateway:
db_fts_corrupt: "⚠️ La base de données des sessions a signalé une erreur de corruption limitée à l'index de recherche (FTS5) ; les tables de messages ne sont pas endommagées. Les messages risquent de ne pas être persistés tant qu'elle n'est pas réparée : exécutez `hermes {profile_arg}doctor --fix`, puis redémarrez le gateway. N'exécutez pas d'outils de récupération et ne restaurez pas de sauvegarde à moins que `hermes {profile_arg}doctor` ne confirme des dégâts."
db_then_restart: "{action} Puis `hermes {profile_arg}gateway restart`."
db_unavailable: "⚠️ Base de données des sessions indisponible — les messages risquent de ne pas être enregistrés et /resume sera vide. Cause : {cause}. {action}"
+ cron_store:
+ unwritable: "⚠️ Cron store {store} is not writable ({error}) since {since}. Scheduled jobs are being skipped until it accepts writes again. Fix: {fix}."
+ recovered: "✅ Cron store {store} is writable again; {skipped} skipped run(s), catching up once per job."
whoami:
scope_dm: "MP"
scope_group: "groupe/canal"
diff --git a/locales/ga.yaml b/locales/ga.yaml
index 8faa9d51716..48e3cb5ac49 100644
--- a/locales/ga.yaml
+++ b/locales/ga.yaml
@@ -847,6 +847,9 @@ gateway:
db_fts_corrupt: "⚠️ Thuairiscigh bunachar sonraí na seisiún earráid truaillithe atá teoranta don innéacs cuardaigh (FTS5); níl damáiste ar na táblaí teachtaireachtaí. Seans nach sábhálfar teachtaireachtaí go dtí go ndeiseofar é: rith `hermes {profile_arg}doctor --fix`, ansin atosaigh an gateway. Ná rith uirlisí athshlánaithe agus ná hathchóirigh cúltaca mura ndearbhaíonn `hermes {profile_arg}doctor` damáiste."
db_then_restart: "{action} Ansin `hermes {profile_arg}gateway restart`."
db_unavailable: "⚠️ Níl bunachar sonraí na seisiún ar fáil — seans nach sábhálfar teachtaireachtaí agus beidh /resume folamh. Cúis: {cause}. {action}"
+ cron_store:
+ unwritable: "⚠️ Cron store {store} is not writable ({error}) since {since}. Scheduled jobs are being skipped until it accepts writes again. Fix: {fix}."
+ recovered: "✅ Cron store {store} is writable again; {skipped} skipped run(s), catching up once per job."
whoami:
scope_dm: "DM"
scope_group: "grúpa/cainéal"
diff --git a/locales/hu.yaml b/locales/hu.yaml
index 17ddc59d3b7..0ecf8853430 100644
--- a/locales/hu.yaml
+++ b/locales/hu.yaml
@@ -859,6 +859,9 @@ gateway:
db_fts_corrupt: "⚠️ A munkamenet-adatbázis a keresőindexre (FTS5) korlátozódó sérülési hibát jelzett; az üzenettáblák nem sérültek. A javításig az üzenetek mentése sikertelen lehet: futtasd a `hermes {profile_arg}doctor --fix` parancsot, majd indítsd újra az átjárót. Ne futtass helyreállító eszközöket, és ne állíts vissza biztonsági mentést, hacsak a `hermes {profile_arg}doctor` nem igazol sérülést."
db_then_restart: "{action} Ezután: `hermes {profile_arg}gateway restart`."
db_unavailable: "⚠️ A munkamenet-adatbázis nem érhető el — az üzenetek mentése sikertelen lehet, és a /resume üres lesz. Ok: {cause}. {action}"
+ cron_store:
+ unwritable: "⚠️ Cron store {store} is not writable ({error}) since {since}. Scheduled jobs are being skipped until it accepts writes again. Fix: {fix}."
+ recovered: "✅ Cron store {store} is writable again; {skipped} skipped run(s), catching up once per job."
whoami:
scope_dm: "DM"
scope_group: "csoport/csatorna"
diff --git a/locales/it.yaml b/locales/it.yaml
index 2fd315e4861..a8490d998d4 100644
--- a/locales/it.yaml
+++ b/locales/it.yaml
@@ -847,6 +847,9 @@ gateway:
db_fts_corrupt: "⚠️ Il database delle sessioni ha segnalato un errore di corruzione limitato all'indice di ricerca (FTS5); le tabelle dei messaggi non sono danneggiate. I messaggi potrebbero non essere salvati finché non viene riparato: esegui `hermes {profile_arg}doctor --fix`, poi riavvia il gateway. Non eseguire strumenti di ripristino né ripristinare un backup a meno che `hermes {profile_arg}doctor` non confermi il danno."
db_then_restart: "{action} Poi `hermes {profile_arg}gateway restart`."
db_unavailable: "⚠️ Database delle sessioni non disponibile — i messaggi potrebbero non essere salvati e /resume sarà vuoto. Causa: {cause}. {action}"
+ cron_store:
+ unwritable: "⚠️ Cron store {store} is not writable ({error}) since {since}. Scheduled jobs are being skipped until it accepts writes again. Fix: {fix}."
+ recovered: "✅ Cron store {store} is writable again; {skipped} skipped run(s), catching up once per job."
whoami:
scope_dm: "DM"
scope_group: "gruppo/canale"
diff --git a/locales/ja.yaml b/locales/ja.yaml
index 10a5b37e53d..14b3eb52f00 100644
--- a/locales/ja.yaml
+++ b/locales/ja.yaml
@@ -847,6 +847,9 @@ gateway:
db_fts_corrupt: "⚠️ セッションデータベースが検索インデックス (FTS5) に限定された破損エラーを報告しました。メッセージテーブルは損傷していません。修復されるまでメッセージが永続化されない可能性があります: `hermes {profile_arg}doctor --fix` を実行し、ゲートウェイを再起動してください。`hermes {profile_arg}doctor` が損傷を確認しない限り、復旧ツールの実行やバックアップからの復元は行わないでください。"
db_then_restart: "{action} その後 `hermes {profile_arg}gateway restart` を実行してください。"
db_unavailable: "⚠️ セッションデータベースが利用できません — メッセージが保存されず、/resume が空になる可能性があります。原因: {cause}。{action}"
+ cron_store:
+ unwritable: "⚠️ Cron store {store} is not writable ({error}) since {since}. Scheduled jobs are being skipped until it accepts writes again. Fix: {fix}."
+ recovered: "✅ Cron store {store} is writable again; {skipped} skipped run(s), catching up once per job."
whoami:
scope_dm: "DM"
scope_group: "グループ/チャンネル"
diff --git a/locales/ko.yaml b/locales/ko.yaml
index d8f4966b207..5271d043d35 100644
--- a/locales/ko.yaml
+++ b/locales/ko.yaml
@@ -847,6 +847,9 @@ gateway:
db_fts_corrupt: "⚠️ 세션 데이터베이스가 검색 인덱스(FTS5)에 한정된 손상 오류를 보고했어요. 메시지 테이블은 손상되지 않았어요. 수리될 때까지 메시지가 저장되지 않을 수 있어요: `hermes {profile_arg}doctor --fix`를 실행한 뒤 게이트웨이를 재시작하세요. `hermes {profile_arg}doctor`가 손상을 확인하지 않는 한 복구 도구를 실행하거나 백업을 복원하지 마세요."
db_then_restart: "{action} 그런 다음 `hermes {profile_arg}gateway restart`를 실행하세요."
db_unavailable: "⚠️ 세션 데이터베이스를 사용할 수 없어요 — 메시지가 저장되지 않을 수 있고 /resume이 비어 있을 거예요. 원인: {cause}. {action}"
+ cron_store:
+ unwritable: "⚠️ Cron store {store} is not writable ({error}) since {since}. Scheduled jobs are being skipped until it accepts writes again. Fix: {fix}."
+ recovered: "✅ Cron store {store} is writable again; {skipped} skipped run(s), catching up once per job."
whoami:
scope_dm: "DM"
scope_group: "그룹/채널"
diff --git a/locales/pt.yaml b/locales/pt.yaml
index eaef651d547..b694b67725c 100644
--- a/locales/pt.yaml
+++ b/locales/pt.yaml
@@ -847,6 +847,9 @@ gateway:
db_fts_corrupt: "⚠️ O banco de dados de sessões relatou um erro de corrupção restrito ao índice de busca (FTS5); as tabelas de mensagens não estão danificadas. As mensagens podem não ser persistidas até o reparo: execute `hermes {profile_arg}doctor --fix` e depois reinicie o gateway. Não execute ferramentas de recuperação nem restaure um backup a menos que `hermes {profile_arg}doctor` confirme o dano."
db_then_restart: "{action} Em seguida, `hermes {profile_arg}gateway restart`."
db_unavailable: "⚠️ Banco de dados de sessões indisponível — as mensagens podem não ser salvas e /resume ficará vazio. Causa: {cause}. {action}"
+ cron_store:
+ unwritable: "⚠️ Cron store {store} is not writable ({error}) since {since}. Scheduled jobs are being skipped until it accepts writes again. Fix: {fix}."
+ recovered: "✅ Cron store {store} is writable again; {skipped} skipped run(s), catching up once per job."
whoami:
scope_dm: "DM"
scope_group: "grupo/canal"
diff --git a/locales/ru.yaml b/locales/ru.yaml
index 9a57f0ee66a..7e14582f9c0 100644
--- a/locales/ru.yaml
+++ b/locales/ru.yaml
@@ -847,6 +847,9 @@ gateway:
db_fts_corrupt: "⚠️ База данных сеансов сообщила об ошибке повреждения, ограниченной поисковым индексом (FTS5); таблицы сообщений не повреждены. Сообщения могут не сохраняться до починки: выполните `hermes {profile_arg}doctor --fix`, затем перезапустите шлюз. Не запускайте инструменты восстановления и не восстанавливайте резервную копию, пока `hermes {profile_arg}doctor` не подтвердит повреждение."
db_then_restart: "{action} Затем `hermes {profile_arg}gateway restart`."
db_unavailable: "⚠️ База данных сеансов недоступна — сообщения могут не сохраняться, а /resume будет пуст. Причина: {cause}. {action}"
+ cron_store:
+ unwritable: "⚠️ Cron store {store} is not writable ({error}) since {since}. Scheduled jobs are being skipped until it accepts writes again. Fix: {fix}."
+ recovered: "✅ Cron store {store} is writable again; {skipped} skipped run(s), catching up once per job."
whoami:
scope_dm: "ЛС"
scope_group: "группа/канал"
diff --git a/locales/tr.yaml b/locales/tr.yaml
index 7c27a63b4e5..86243b81133 100644
--- a/locales/tr.yaml
+++ b/locales/tr.yaml
@@ -847,6 +847,9 @@ gateway:
db_fts_corrupt: "⚠️ Oturum veritabanı yalnızca arama dizinini (FTS5) etkileyen bir bozulma hatası bildirdi; mesaj tabloları hasarlı değil. Onarılana kadar mesajlar kalıcı olarak kaydedilmeyebilir: `hermes {profile_arg}doctor --fix` çalıştırıp gateway'i yeniden başlatın. `hermes {profile_arg}doctor` hasarı doğrulamadıkça kurtarma araçlarını çalıştırmayın veya yedek geri yüklemeyin."
db_then_restart: "{action} Ardından `hermes {profile_arg}gateway restart` çalıştırın."
db_unavailable: "⚠️ Oturum veritabanı kullanılamıyor — mesajlar kaydedilmeyebilir ve /resume boş olacak. Neden: {cause}. {action}"
+ cron_store:
+ unwritable: "⚠️ Cron store {store} is not writable ({error}) since {since}. Scheduled jobs are being skipped until it accepts writes again. Fix: {fix}."
+ recovered: "✅ Cron store {store} is writable again; {skipped} skipped run(s), catching up once per job."
whoami:
scope_dm: "DM"
scope_group: "grup/kanal"
diff --git a/locales/uk.yaml b/locales/uk.yaml
index b48871e0355..7d538c05330 100644
--- a/locales/uk.yaml
+++ b/locales/uk.yaml
@@ -847,6 +847,9 @@ gateway:
db_fts_corrupt: "⚠️ База даних сеансів повідомила про пошкодження, обмежене пошуковим індексом (FTS5); таблиці повідомлень не пошкоджено. Повідомлення можуть не зберігатися, доки його не полагоджено: виконайте `hermes {profile_arg}doctor --fix`, потім перезапустіть шлюз. Не запускайте інструменти відновлення й не відновлюйте резервну копію, якщо `hermes {profile_arg}doctor` не підтвердить пошкодження."
db_then_restart: "{action} Потім `hermes {profile_arg}gateway restart`."
db_unavailable: "⚠️ База даних сеансів недоступна — повідомлення можуть не зберігатися, а /resume буде порожнім. Причина: {cause}. {action}"
+ cron_store:
+ unwritable: "⚠️ Cron store {store} is not writable ({error}) since {since}. Scheduled jobs are being skipped until it accepts writes again. Fix: {fix}."
+ recovered: "✅ Cron store {store} is writable again; {skipped} skipped run(s), catching up once per job."
whoami:
scope_dm: "DM"
scope_group: "група/канал"
diff --git a/locales/zh-hant.yaml b/locales/zh-hant.yaml
index d55aa342c27..5bc8e4364cd 100644
--- a/locales/zh-hant.yaml
+++ b/locales/zh-hant.yaml
@@ -847,6 +847,9 @@ gateway:
db_fts_corrupt: "⚠️ 工作階段資料庫回報的損毀錯誤僅限於搜尋索引(FTS5);訊息資料表並未受損。修復前訊息可能無法保存:請執行 `hermes {profile_arg}doctor --fix`,然後重新啟動閘道。除非 `hermes {profile_arg}doctor` 確認有損毀,否則請勿執行復原工具或還原備份。"
db_then_restart: "{action} 然後執行 `hermes {profile_arg}gateway restart`。"
db_unavailable: "⚠️ 工作階段資料庫無法使用 — 訊息可能不會被儲存,且 /resume 將是空的。原因:{cause}。{action}"
+ cron_store:
+ unwritable: "⚠️ Cron store {store} is not writable ({error}) since {since}. Scheduled jobs are being skipped until it accepts writes again. Fix: {fix}."
+ recovered: "✅ Cron store {store} is writable again; {skipped} skipped run(s), catching up once per job."
whoami:
scope_dm: "私訊"
scope_group: "群組/頻道"
diff --git a/locales/zh.yaml b/locales/zh.yaml
index f549ba16e11..09a4212361c 100644
--- a/locales/zh.yaml
+++ b/locales/zh.yaml
@@ -847,6 +847,9 @@ gateway:
db_fts_corrupt: "⚠️ 会话数据库报告了仅限于搜索索引(FTS5)的损坏错误;消息表未受损。修复前消息可能无法持久化:请运行 `hermes {profile_arg}doctor --fix`,然后重启网关。除非 `hermes {profile_arg}doctor` 确认存在损坏,否则不要运行恢复工具或还原备份。"
db_then_restart: "{action} 然后执行 `hermes {profile_arg}gateway restart`。"
db_unavailable: "⚠️ 会话数据库不可用——消息可能无法保存,/resume 将为空。原因:{cause}。{action}"
+ cron_store:
+ unwritable: "⚠️ Cron store {store} is not writable ({error}) since {since}. Scheduled jobs are being skipped until it accepts writes again. Fix: {fix}."
+ recovered: "✅ Cron store {store} is writable again; {skipped} skipped run(s), catching up once per job."
whoami:
scope_dm: "私聊"
scope_group: "群组/频道"
diff --git a/tests/cron/test_due_scan_save_failure.py b/tests/cron/test_due_scan_save_failure.py
index 5385e5711cb..aa21fa227f7 100644
--- a/tests/cron/test_due_scan_save_failure.py
+++ b/tests/cron/test_due_scan_save_failure.py
@@ -15,7 +15,9 @@ dispatch (no durable advance) without raising or mutating the store.
import errno
import json
+import asyncio
import logging
+import os
import sqlite3
from datetime import timedelta
@@ -219,3 +221,53 @@ def test_unwritable_store_degrades_once_throttles_and_catches_up_once(cron_store
assert store_health.degraded_record(cron_store / "cron") is None
once_rows = executions.list_executions(job_id="once")
assert [r["status"] for r in once_rows].count("failed") == 1
+
+
[email protected]("posix") # POSIX mode bits; root ignores them
[email protected](hasattr(os, "geteuid") and os.geteuid() == 0, reason="root bypasses directory modes")
+def test_unwritable_store_is_shown_in_cron_status_and_announced_once(cron_store, monkeypatch, capsys):
+ """`hermes cron status` probes the store itself (a real 0500 dir) and leads with the red
+ headline + fix; the gateway posts ONE home-channel notice on entry and ONE on recovery,
+ each naming the store, the error, since-when and the skipped runs."""
+ from types import SimpleNamespace
+ from gateway.cron_store_notices import install_cron_store_notices
+ from hermes_cli import cron as cron_cli
+
+ save_jobs([_due_job()])
+ cron_dir = cron_store / "cron"
+ monkeypatch.setattr(cron_cli, "_active_cron_provider_name", lambda: "chronos")
+ os.chmod(cron_dir, 0o500)
+ try:
+ cron_cli.cron_status()
+ finally:
+ os.chmod(cron_dir, 0o700)
+ out = capsys.readouterr().out
+ assert out.lstrip().startswith("⚠ Cron store is NOT writable — scheduled jobs are being skipped")
+ assert f"{cron_dir}: EACCES" in out and "1 due run(s) not fired" in out
+ assert f"fix permissions on {cron_dir}" in out
+
+ sent = []
+
+ async def send(platform, home, transport, message, failure_fmt):
+ sent.append(message)
+ return True
+
+ home = SimpleNamespace(chat_id="c1", thread_id=None)
+ runner = SimpleNamespace(_send_home_channel_message=send, _served_home_channel_transports=lambda: iter(
+ [(None, "telegram", None, home, object())]))
+ monkeypatch.setattr("hermes_constants.get_routing_process_hermes_home", lambda: cron_store)
+ loop = asyncio.new_event_loop()
+ try:
+ install_cron_store_notices(runner, loop)
+ enospc = OSError(errno.ENOSPC, "No space left on device")
+ for site in ("scan", "advance", "claim"): # one outage, many failing sites
+ cronjobs.warn_store_unwritable(enospc, "x", site, [_due_job()])
+ save_jobs([_due_job()])
+ save_jobs([_due_job()])
+ loop.run_until_complete(asyncio.sleep(0.05))
+ finally:
+ loop.close()
+ assert len(sent) == 2
+ assert str(cron_dir) in sent[0] and "ENOSPC: No space left on device" in sent[0] and "since " in sent[0]
+ assert f"fix permissions on {cron_dir}" in sent[0]
+ assert "writable again; 1 skipped run(s), catching up once per job" in sent[1]