Spaces:
Running
Running
Upload 168 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- ARCHITECTURE_V29.mdAdded+29
- CONTENT_PIPELINE_V29.mdAdded+21
- P29_MIGRATION_PLAN.mdAdded+29
- P29_STAGE3_CHANGELOG.mdAdded+20
- PHASE_10_REPAIR_POLICY_CONTROL.mdAdded+19
- PHASE_11_CONTROL_INTEGRATION.mdAdded+17
- PHASE_12_PLUGIN_ADAPTERS.mdAdded+29
- PHASE_13_NEWS_SPORTS_SEPARATION.mdAdded+23
- PHASE_14_INTEGRATED_HARDENING.mdAdded+15
- PHASE_15_RUNTIME_INTEGRATION.mdAdded+39
- PHASE_16_PRODUCTION_RELIABILITY.mdAdded+19
- PHASE_17_CHANGELOG.mdAdded+30
- PHASE_18_LEGACY_RUNTIME_CUTOVER.mdAdded+23
- PHASE_19_CHANGELOG.mdAdded+9
- PHASE_19_PRODUCTION_CONTROL_OBSERVABILITY.mdAdded+18
- PHASE_20_CHANGELOG.mdAdded+15
- PHASE_20_PERFORMANCE_CHAOS.mdAdded+16
- PHASE_21_SECURITY_HARDENING.mdAdded+8
- PHASE_22_23_CHANGELOG.mdAdded+8
- PHASE_22_23_PRODUCTION_READINESS_RELEASE.mdAdded+17
- PHASE_24_FINAL_GO_LIVE.mdAdded+22
- PHASE_4_AI_PROVIDER_POOL.mdAdded+25
- PHASE_5_AI_GATEWAY.mdAdded+20
- PHASE_6_PERSISTENT_JOB_QUEUE.mdAdded+13
- PHASE_7_PUBLISH_IDEMPOTENCY.mdAdded+15
- PHASE_8_HEALTH_SUPERVISOR.mdAdded+11
- PHASE_9_AI_AUTO_REPAIR.mdAdded+22
- PRODUCTION_READINESS_REPORT.jsonAdded+45
- README_P29.mdAdded+23
- RELEASE_MANIFEST.jsonAdded+849
- SECRET_COMPATIBILITY.mdAdded+28
- adapters/__init__.pyAdded
- bot_core.pyAdded
- config.pyAdded+24
- core/__init__.pyAdded
- core/ai/__init__.pyAdded+3
- core/ai/gateway.pyAdded+110
- core/ai/http_adapters.pyAdded+137
- core/app.pyAdded+68
- core/config/__init__.pyAdded
- core/config/settings.pyAdded+16
- core/content/__init__.pyAdded+3
- core/content/dedup.pyAdded+26
- core/content/orchestrator.pyAdded+22
- core/content/preflight.pyAdded+34
- core/content_pipeline.pyAdded+138
- core/control/__init__.pyAdded+1
- core/control/plane.pyAdded+56
- core/control/repair_buttons.pyAdded+18
- core/control/repair_control.pyAdded+58
1234567891011121314151617181920212223242526272829# P29 Refactor Architecture
## هدفإعادة الهيكلة تدريجيًا بدون كسر السلوك الحالي، مع إبقاء وحدات `modules/` متاحة أثناء الترحيل.
## الطبقات- `core/`: بنية تحتية مستقرة: jobs, health, secrets, plugins, events, supervisor, repair, storage.- `adapters/`: محولات للخدمات الخارجية مثل Telegram/Gemini/Groq/Blogger.- `modules/`: التنفيذ الحالي؛ يتم ترحيل وظيفة بعد أخرى إلى الخدمات الجديدة.- `tests/`: اختبارات التوافق والانحدار.
## قواعد مهمة1. لا تعديل مباشر على الإنتاج بواسطة AI.2. AI يقترح Patch -> Sandbox -> compile/tests/security -> backup -> apply -> monitor -> rollback.3. الأسرار لا تدخل logs ولا source code.4. كل job قابل للاستعادة بعد restart.5. كل provider قابل للفشل دون إسقاط التطبيق كله.6. إضافة secret/provider/plugin جديد تتم بالـ registry/metadata وليس بتعديل الـ core.
## خارطة الترحيل1. JobStore + Health + Supervisor.2. SecretManager + ProviderRouter.3. نقل Blogger scheduler إلى jobs.4. نقل database JSON إلى SQLite عبر adapter ثم إيقاف JSON بعد فترة تحقق.5. تقسيم `bot_core.py` إلى handlers/services.6. تفعيل Auto-Repair بعد اكتمال الاختبارات.
## التوافقالنسخة الحالية لا تحذف `bot_core.py` ولا وحدات Blogger؛ هذا مقصود لتقليل خطر الانقطاع أثناء الترحيل.123456789101112131415161718192021# P29 Global Content Pipeline
كل الأقسام (Blogger / News / Sports / مستقبلًا) تستخدم نفس البوابة قبل أي AI/API:
1. Empty check2. Global + channel blocked-word check3. Duplicate check4. Normalize + fingerprint5. AI processing (single package request where applicable)6. Post-AI blocked-word + duplicate check7. Queue / publish
المحتوى المرفوض في المرحلتين الأولى أو الثانية لا يستهلك أي طلب AI.
## Single AI Request
قسم Blogger يستخدم `SYSTEM_ARTICLE_PACKAGE` لطلب حزمة واحدة تشمل العنوان، النص، الملخص، SEO، الكلمات، الهاشتاكات، الملاحظات، الاستخراج وALT بدل عدة طلبات مستقلة.
## Extensibility
`core/content_pipeline.py` مستقل عن Blogger، لذلك أي Plugin جديد يستطيع استخدام `ContentGate` بدون نسخ منطق الحظر/التكرار.1234567891011121314151617181920212223242526272829# P29 Migration Plan
## What was changed now- Added `core/` foundation: durable jobs, health registry, supervisor, dynamic secrets, plugin registry, event bus, provider failover, repair validation.- Added `v29_app.py` as a composition root.- Added foundation tests under `tests/v29/`.- Fixed the confirmed scheduler reference bug (`db` -> `self.db`).- Changed Blogger DB read failure from silent `{}` fallback to an explicit error so corruption cannot masquerade as an empty database.
## What is intentionally NOT changed yetThe existing Telegram/Blogger runtime remains in place. This is deliberate: a big-bang rewrite would create a larger outage risk.
## Next migration slices1. Wrap existing AI manager/Gemini clients with `ProviderRouter`.2. Move scheduler queue persistence to `JobStore` and add claim/lease/idempotency.3. Put Blogger and Telegram operations behind adapters.4. Migrate JSON state to SQLite through a compatibility repository.5. Split `bot_core.py` by responsibility while preserving public functions.6. Add crash/restart integration tests.7. Enable AI auto-repair in proposal-only mode.8. Enable automatic patch application only after sandbox + tests + rollback checks are green.
## Safety ruleNo AI-generated patch is allowed to modify production directly. Production changes must have a backup, a validation result, and a rollback path.
## Phase 15 completed- RuntimeIntegration is now the shared orchestration path for new section traffic.- News/Sports/Blogger receive the same section control contract while legacy callbacks remain intact.- AI provider adapters, per-key rate limiting, bounded retry/backoff, persistent queue migration, publisher idempotency, health hooks, metrics and audit are wired together.1234567891011121314151617181920# P29 Stage 3 — Content Gate + AI Batch Processing
## Added- Global `ContentGate` shared by all future sections.- Blocked-word check before fingerprint/AI/API work.- Global + per-channel blocked-word compatibility with existing database/UI names.- Duplicate gate before AI.- SHA-256 normalized fingerprints for new pipeline records.- Post-AI blocked-word and duplicate gate.- Single AI article-package request for Blogger instead of separate rewrite/extract/summary/metadata/keyword/hashtag/alt calls.
## Compatibility- Existing blocked-word database methods are reused; no existing secret names changed.- Existing Blogger pending queue and legacy processor remain available.- New pipeline is additive and can be adopted by News/Sports/future plugins.
## Safety- A blocked or duplicate article is discarded before any AI session is acquired.- AI output is checked again before entering the processed state.- The gate is fail-open only for legacy DB read exceptions to avoid taking down ingestion; the item remains available for later processing.12345678910111213141516171819# Phase 10 — Auto-Repair Policy + Control Bot
Adds a conservative policy gate between sandbox-tested patches and production.
Rules:- secrets/credentials/tokens/keys/sessions/data/.git are blocked.- code changes are medium risk by default and require admin approval.- changes outside allowed roots are high risk and require admin approval.- per-incident attempt cap and cooldown prevent repair loops.- optional health check triggers rollback after application.
Control-bot buttons are additive and callback-style:- repair status- pending repairs- approve repair- rollback last repair- disable/enable auto-repair
Existing button callbacks are not renamed or removed by this phase. The host bot should attach these buttons to its existing menu/router using the same callback mechanism already used by the project.1234567891011121314151617# Phase 11 — Control Bot Integration + Common Content Pipeline
Adds an additive callback router and RepairControl façade for the existing control bot.
New callbacks:- `repair:status`- `repair:pending`- `repair:approve`- `repair:rollback`- `repair:disable`- `repair:enable`
The router does not replace or rename existing callbacks.
Also adds `ContentPipeline`, a common service façade intended for Blogger, News, Sports and future sections. It applies the existing gate before queueing and sends accepted articles to the common AI Gateway.
The actual Telegram framework handler should bind these callback strings to the project's existing button/menu code during final integration; this phase keeps framework-specific code isolated.1234567891011121314151617181920212223242526272829# Phase 12 — Plugin Adapters & Future Sections
Implemented a section adapter contract and registry for Blogger, News, Sports and future sections.
## Important compatibility ruleLegacy secret names are unchanged. Blogger continues to use:- BLOGGER_BLOG_ID- BLOGGER_CLIENT_ID- BLOGGER_CLIENT_SECRET- BLOGGER_REFRESH_TOKEN
No secret is renamed or copied to a new required name.
## New section flowA new section registers a `SectionSpec`/adapter. It inherits the shared:- blocked-word gate- duplicate gate- persistent queue- AI Gateway/key rotation- idempotent publisher- health/supervisor layer
The core pipeline does not need to be rewritten for each new section.
External packages can register under the `p29.plugins` entry-point group.
## Test noteAll phase tests that do not require the optional Telegram/Pyrogram runtime passed: **30 passed**.The full integration suite cannot be collected in this build environment because `pyrogram` is not installed; this is an environment dependency, not a code-test failure.1234567891011121314151617181920212223# Phase 13 — Separate News and Sports
News and Sports are now first-class independent sections.
Each section has:- its own key and namespace- its own settings/state- its own callbacks- its own enable/disable status- its own sources/blocked words/duplicate policy/AI settings/queue/repair controls
They share infrastructure:- ContentPipeline- AI Gateway/provider rotation- persistent Queue/Recovery- idempotent publishing- Health/Supervisor- Auto-Repair policy and Sandbox
Control buttons are generated with the same set for both sections, but callback namespaces are isolated:`news:*` vs `sports:*`.
No old secret names are changed.123456789101112131415# Phase 14 — Integrated Hardening Batch
This batch adds multiple production foundations together:- dynamic secret discovery while preserving legacy secret names- key health/cooldown tracking- log redaction- zero-AI preflight for blocked words- persistent content fingerprint deduplication- provider token-bucket rate limiting- audit log and metrics- plugin manifests/registry- common ContentGate for future sections
Important: dynamic secret discovery is additive. Existing environment-variable names are not renamed or removed.The gate is designed to run before any AI call, so blocked/duplicate content can be discarded without consuming AI quota.123456789101112131415161718192021222324252627282930313233343536373839# Phase 15 — Runtime Integration
## Runtime order
`article -> blocked words -> duplicate/fingerprint -> deterministic cleanup -> durable queue -> AI Gateway -> validation -> Publisher -> Idempotency -> Health`
The gate runs before queue/AI/API use. Blocked or duplicate content is rejected without AI calls.
## Integrated components
- `core/runtime/integration.py`: phase-15 composition/orchestration root.- News, Sports and Blogger use the same runtime contract with isolated section state.- Persistent P29 job table (`p29_jobs`) with schema metadata and migration from the two older `jobs` schemas.- AI Provider Pool rotates `GEMINI_KEY_N`, `GROQ_KEY_N`, `OPENROUTER_KEY_N` without renaming legacy secrets.- Per-key token-bucket rate limits, cooldown and bounded retry/backoff.- HTTP adapters for Gemini, Groq and OpenRouter.- Post-AI validation reuses the same blocked-word and duplicate protection.- Publisher remains idempotent through the durable publish ledger.- Health monitoring is registered per section/provider.- Auto-repair can be triggered by unhealthy services through the existing guarded sandbox/rollback policy; sensitive changes still require admin approval.- Audit and metrics are exposed through the runtime control snapshot.- Control Bot adds additive `news:*`, `sports:*`, and `blogger:*` callbacks while legacy callbacks remain unchanged.- Plugin discovery remains the extension point for future sections.
## Compatibility
Existing secret names are unchanged. Existing legacy Blogger modules and callbacks remain available. The phase-15 job store uses a namespaced table so incompatible historical `jobs` schemas do not break startup; queued legacy rows are copied forward when their schema is recognized.
## Verification
Phase-15 tests cover:- blocked content before queue/AI- persistent duplicate rejection- one structured AI package request- provider/key failover- idempotent publish- stale-worker recovery- legacy job schema migration- section isolation/control parity12345678910111213141516171819# PHASE 16 — Production Reliability & Control Plane
Phase 16 hardens the Phase-15 runtime for restarts and long-running operation without renaming legacy secrets or removing legacy callbacks.
## Changes- Durable per-section runtime/control state in `p29_runtime_state` with additive schema versioning.- Section settings survive process restart: enabled state, blocked words, duplicate protection, AI, Auto-Repair and source allowlist.- Source allowlist is enforced before Queue/AI; empty source is rejected when an allowlist is configured.- Duplicate protection toggle is now honored by the runtime gate.- Worker lease heartbeat prevents long AI/publish jobs from being reclaimed while still running.- Completion is worker-aware to reduce stale-worker races.- Auto-Repair respects each section's `auto_repair_enabled` flag.- Runtime state changes invalidate cached section gates/pipelines.- Existing legacy secrets and callback namespaces remain unchanged.
## Verification- `compileall` is required.- Phase-15 and Phase-16 runtime tests cover persistence, source gating, duplicate toggle, worker heartbeat and section repair policy.- Telegram-dependent legacy tests are reported separately when `pyrogram` is unavailable.123456789101112131415161718192021222324252627282930# P29 Phase 17 Changelog
## Runtime / Reliability- Added `attempt_started_at` to `publish_ledger` with additive migration.- Added stale publish lease recovery before each publish.- Preserved the same `(target, article_id)` idempotency key across recovery.- Added queue job listing and dead-letter requeue primitives.- Added safe operational queue snapshots without payload exposure.- Persisted global Auto-Repair enable/disable state.
## Control BotExisting section callbacks remain available. New additive callbacks:- `{section}:metrics`- `{section}:health`- `{section}:dead`
These are generated for News, Sports and Blogger using the same section-control contract.
## Security- Dead-letter requeue requires admin approval at the runtime API.- Operational queue views omit article payloads.- Audit logging continues through the existing redaction layer.- Secret names remain unchanged.
## Verification- `python3 -m compileall -q .` — PASS- Phase 16 + Phase 17 + runtime/core compatibility tests — PASS- Legacy non-Telegram test subset — PASS- Full pytest collection remains blocked by missing `pyrogram` in the execution environment; affected tests are Telegram/Blogger UI-dependent.- `python3 v29_app.py` — PASS; discovered `blogger, news, sports`.1234567891011121314151617181920212223# PHASE 18 — Full Legacy Runtime Migration & Production Cutover
Phase 18 turns the previously parallel legacy/new architecture into a controlled compatibility cutover.
## Runtime path
Telegram/legacy source -> legacy compatibility bridge -> RuntimeIntegration -> ContentGate -> persistent queue -> AI Gateway -> validation -> IdempotentPublisher -> legacy external target -> Health/Audit/Metrics.
## Compatibility
- Existing `BloggerPublisher`, `ArticleProcessor`, scheduler and UI APIs remain available.- Legacy `enqueue_raw_post()` now routes automatic Blogger ingestion into the durable P29 runtime when a runtime is supplied by `BloggerPublisher`.- Legacy direct/manual processing remains available for callers that construct `ArticleProcessor` without a runtime.- Existing secret names are untouched.- Existing callback modules remain untouched.
## Cutover safety
The bridge never bypasses the ContentGate. A rejected/duplicate item is stopped before the durable queue and therefore before AI/API consumption. Publisher idempotency remains owned by the core ledger.
## Recovery
The runtime worker uses the Phase 17 job lease/heartbeat/recovery path. The external Blogger client remains the legacy-compatible publishing adapter, so remote publishing semantics are not duplicated.123456789# Phase 19 Changelog
- Added `core/control/plane.py` operational alert/control layer.- Extended `core/infra/metrics.py` with thread-safe latency aggregates and timers.- Extended `core/infra/audit.py` with safe recent-event retrieval.- Integrated control-plane data into `RuntimeIntegration.control_snapshot()`.- Added runtime operational snapshot, recent audit access and alert acknowledgement APIs.- Added global control callback façade without renaming old callbacks.- Added regression tests for alerts, metrics compatibility and admin-gated control access.123456789101112131415161718# P29 — PHASE 19: Production Control Plane & Observability
## Integrated- Unified operational snapshot for News, Sports and Blogger.- Active alerts for unhealthy services, queue backlog and dead-letter jobs.- Detailed latency metrics while preserving the legacy flat `metrics_snapshot()` API.- Safe recent Audit Log viewer with existing redaction.- Additive global control callbacks: `control:overview`, `control:alerts`, `control:providers`, `control:audit`.- Existing section callbacks and legacy callback names remain unchanged.- Runtime control snapshot now includes queue, alerts and detailed metrics.- Admin gating is required for Audit Log access through the global control surface.- No legacy secret names were renamed or removed.
## Verification- Python compile: PASS.- Phase/core regression suite: 32 passed.- App smoke start: PASS; discovered `blogger`, `news`, `sports`.- Telegram-dependent tests remain environment-blocked because `pyrogram` is not installed.123456789101112131415# P29 Phase 20 Changelog — Performance, Concurrency & Chaos
- Added canonical bounded concurrent worker pool over the persistent queue.- Added compatibility facade so legacy `core.jobs.store.JobStore` callers use the canonical storage implementation without changing old call signatures.- Added deterministic load harness and chaos scenario matrix.- Added runtime helpers `build_concurrent_workers()` and `load_snapshot()`.- Added tests for duplicate enqueue, concurrent claims, lease recovery, 40-job load, and chaos coverage.- Existing secret names/callbacks/public runtime compatibility preserved.
## Verification- `python -m compileall -q .`: PASS- Phase 20 + regression/core suite selected for non-Telegram paths: **61 passed**- App smoke: PASS; `blogger, news, sports` discovered.- Load test: 200 jobs / 8 workers: **200 processed, 0 queued, 200 done, 0 dead**, ~175.35 jobs/s in the local test environment.- Full pytest collection is blocked by missing `pyrogram` in this environment; Telegram-dependent imports fail at collection. This is an environment dependency, not a compile/core test failure.12345678910111213141516# P29 — PHASE 20: Performance, Concurrency & Chaos Engineering
## Integrated- Added bounded `ConcurrentWorkers` using the existing persistent JobStore and lease/heartbeat logic.- Added deterministic in-process `LoadHarness` for repeatable load and chaos scenarios without external services.- Duplicate enqueue remains idempotent under repeated concurrent-style submission.- SQLite queue claim remains the single atomic source of truth; concurrent workers cannot double-claim a queued job.- Existing lease recovery is exercised as a worker-crash/restart simulation.- Added performance result reporting: processed, elapsed time, throughput, queue/done/dead counts.- Added a chaos matrix covering duplicate enqueue, concurrent claim, worker crash, lease expiry, provider 429/5xx, timeout, publish crash and restart recovery.- No legacy secret names, callbacks, section configuration names, or public runtime APIs were removed.
## Verification- `compileall`: required before packaging.- Core/regression suite plus Phase 20 concurrency/load tests required before delivery.- Telegram-dependent tests remain environment-dependent when `pyrogram` is unavailable.12345678# PHASE 21 — Security, Secrets & Production Hardening
- Added runtime secret-value redaction and security findings.- Added RBAC for control-plane sensitive operations.- Added encrypted SecretManager master-key rotation without changing existing secret names.- Existing SecretRegistry discovery and legacy environment names remain untouched.- Sensitive repair/rollback/rotation actions can be restricted to admin.- Added security regression tests.12345678# P29 Phase 22+23 Changelog
- Production readiness gate.- SQLite integrity checks.- Atomic, verifiable backup/restore foundation.- Release manifest and reproducible file hashes.- Disaster-recovery regression coverage.- Final-release candidate metadata.1234567891011121314151617# PHASE 22+23 — Production Readiness, Disaster Recovery & Final Release
## Integrated- Added deterministic production readiness gate with Python/database/queue/health/security checks.- Added atomic SQLite backup manager using SQLite online backup API, SHA-256 verification and backup discovery.- Added corrupt-database detection and recovery-readiness checks without mutating runtime state.- Added reproducible release manifest with SHA-256 file inventory while excluding runtime state, backups and bytecode.- Added regression tests for backup verification, corruption detection, readiness and release manifest safety.- Kept all legacy secret names, callbacks and public runtime APIs additive.
## Combined accelerationThis release intentionally combines the planned Phase 22 disaster-recovery/readiness work with the planned Phase 23 final-release/go-live gate so the project reaches a single auditable release candidate faster.
## Verification- compileall required before packaging.- Phase 22/23 and regression suite required before delivery.- Telegram-dependent tests remain environment-dependent when `pyrogram` is unavailable.12345678910111213141516171819202122# PHASE 24 — Final Go-Live / End-to-End Production Gate
Final hardening and release gate for P29.
## Integrated- Final Go-Live readiness gate.- Dry-run end-to-end verification for News, Sports and Blogger.- Atomic publish-lease claim to eliminate the final concurrent idempotency race.- CLI readiness and go-live checks.- Telegram dependency/credential checks are optional and explicitly gated by `--require-telegram`.- Legacy Telegram callbacks and runtime bridge remain unchanged.- Release manifest advanced to phase 24.
## Verification- `python -m compileall -q .`: PASS- Phase 24 + release/security/performance/cutover/runtime regression suite: 22/22 PASS- `python v29_app.py --go-live`: PASS in dry-run mode- `python v29_app.py --manifest`: PASS- Full pytest collection: blocked by missing `pyrogram` in the execution environment; 3 integration modules cannot be collected.
## Production noteA live Telegram publish cannot be truthfully marked successful without the deployment's real Telegram credentials and network access. The final gate therefore distinguishes deterministic offline readiness from live external-service verification.12345678910111213141516171819202122232425# P29 Phase 4 — AI Provider Pool
This phase adds a provider/key scheduler without renaming legacy secrets.
## Supported legacy names
- `GEMINI_KEY_1 ... GEMINI_KEY_N`- `GROQ_KEY_1 ... GROQ_KEY_N`- `OPENROUTER_KEY_1 ... OPENROUTER_KEY_N`
Any numbered key already present is discovered automatically.
## Selection policy
1. Ignore empty/unavailable keys.2. Prefer the least-used key.3. Break ties with least-recently-used.4. Put failed/rate-limited keys into cooldown.5. A future provider adapter can call `report_success()` / `report_failure()`.
## Important
This phase deliberately does not hard-wire provider HTTP SDKs into the pool. The existing provider clients remain responsible for making requests. The pool only decides which credential should be used, so migration is low-risk.
The next integration step is to route every real AI request through this pool and add persistent usage/quota state.1234567891011121314151617181920# P29 Phase 5 — AI Gateway
All future AI calls should go through `core.ai.AIGateway`.
## What it adds
- Uses the existing Provider Pool.- Preserves legacy secret names.- Automatic key/provider failover.- Rate-limit cooldown.- Token usage accounting when provider responses expose usage.- One structured `article_package()` request for title/body/summary/keywords/hashtags/SEO/category/slug.
## Migration rule
Do not rewrite the existing provider clients in one risky step. Register their HTTP/API functions as adapters, then migrate call sites one service at a time. This keeps the legacy bot operational during the transition.
## Token-minimization rule
Before invoking this gateway, the global content gate must reject blocked or duplicate articles. The gateway should only receive accepted content.12345678910111213# Phase 6 — Persistent Job Queue & Crash Recovery
Adds a SQLite/WAL job store with:- durable queued jobs- atomic-ish claim under SQLite locking- worker lease timestamps- recovery of jobs whose worker crashed- retry with max attempts- dead-letter (`dead`) state- idempotent enqueue by job id
This is a migration layer. Existing scheduler code is not deleted or replaced in this phase.The next migration step is to route actual article processing/publishing through this store and make publish idempotency explicit.123456789101112131415# Phase 7 — Publish Idempotency
Adds a durable publish ledger on the same SQLite/WAL store.
## Safety- One logical key per `(target, article_id)`.- A completed publish is never sent again.- A second worker seeing `publishing` will not issue another remote request.- Failed attempts remain retryable.- Remote IDs are retained when the adapter returns one.
## MigrationExisting Blogger/News/Sports adapters should be wrapped with `IdempotentPublisher` one target at a time. No legacy secret names are changed.
Important: a provider that supports an idempotency key should receive the generated key. For providers without native idempotency, the ledger still prevents duplicates within this application, while reconciliation by remote ID/search should be added before retrying ambiguous network failures.1234567891011# Phase 8 — Health Monitor + Supervisor
Adds:- service health checks- consecutive failure tracking- health snapshots- supervised restart with exponential backoff- restart caps and disable-on-persistent-failure
This is intentionally a migration layer. Existing services are not forcibly wrapped yet.The next phase can connect Telegram scheduler, workers, provider clients and publishers one by one.12345678910111213141516171819202122# Phase 9 — AI Auto-Repair: Sandbox + Tests + Rollback
AI never writes directly to production.
Flow:1. Error is classified outside the repair engine.2. AI proposes a unified diff patch.3. PatchSandbox rejects protected paths and traversal.4. Patch is applied to an isolated copy.5. Python compile + selected tests run in sandbox.6. Only a passing patch may be applied.7. Original files are backed up before apply.8. Health monitoring can trigger rollback if the repaired service becomes unhealthy.
Protected by default:- secrets / credentials / tokens / keys- `.env`- runtime `data/`- sessions- `.git`
This is deliberately conservative. Provider-specific AI proposal logic is not hard-wired here; it should use the existing AI Gateway and only return a patch.123456789101112131415161718192021222324252627282930313233343536373839404142434445{ "ready": true, "generated_at": 1787486536.9508731, "findings": [], "checks": { "python_version": "3.13.5", "database_integrity": "ok", "queue": { "queued": 0, "running": 0, "done": 0, "dead": 1 }, "health": { "section:blogger": { "name": "section:blogger", "status": "unknown", "consecutive_failures": 0, "last_error": "", "last_ok": 0.0, "last_check": 0.0, "metadata": {} }, "section:news": { "name": "section:news", "status": "unknown", "consecutive_failures": 0, "last_error": "", "last_ok": 0.0, "last_check": 0.0, "metadata": {} }, "section:sports": { "name": "section:sports", "status": "unknown", "consecutive_failures": 0, "last_error": "", "last_ok": 0.0, "last_check": 0.0, "metadata": {} } }, "security_findings": [] }}1234567891011121314151617181920212223# P29 Foundation
This package is a safe, incremental refactor of the P28 automatic publishing bot.
### Start foundation check`python v29_app.py`
### Generate a Fernet master key`python scripts_generate_secret_key.py`
Set it as `P29_SECRET_MASTER_KEY` before using `core.secrets.SecretManager`.
### Run new foundation tests`pytest -q tests/v29`
The legacy runtime is intentionally retained during migration so the refactor can be introduced service-by-service instead of risking a big-bang failure.
## Phase 17 — Operational Resilience- Durable publish leases with stale-operation recovery.- Dead-letter queue inspection/requeue with admin approval.- Persistent global Auto-Repair control state.- Section health/metrics/dead-letter control callbacks added additively.- No legacy secret names or callback namespaces were renamed.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849{ "files": [ { "path": "ARCHITECTURE_V29.md", "sha256": "44fed5976a284ab0ff1ec43f98b8fbe61208598a83e6c2c2f00ccf3e07eaa199", "size": 1673 }, { "path": "CONTENT_PIPELINE_V29.md", "sha256": "3354885a927709249c91918d99653742c31883ec915a37a75b4e5d8d9ff92969", "size": 978 }, { "path": "P29_MIGRATION_PLAN.md", "sha256": "60503554d687ab320016f41f20ff9899e1d424463e8399e4e90f73f6faaf77d3", "size": 1762 }, { "path": "P29_STAGE3_CHANGELOG.md", "sha256": "60e0e50d018dcd61e2494f6181f4c62b9a7f6b868b57580a4d528ff348b21e32", "size": 1064 }, { "path": "PHASE_10_REPAIR_POLICY_CONTROL.md", "sha256": "eaa54d073268c6e93ab541f5b22fedeb75fc518373377f9478b2c2ed2d45d75b", "size": 827 }, { "path": "PHASE_11_CONTROL_INTEGRATION.md", "sha256": "1cbc300cddd3d2df6f443ae81e511b5c9ab5d4092c7508ad2f6f4eb6a8cd96d4", "size": 747 }, { "path": "PHASE_12_PLUGIN_ADAPTERS.md", "sha256": "3b211c8de9c85f627cbd3236a76e473f4686e2fae04fcc493b8420423fd609c1", "size": 1038 }, { "path": "PHASE_13_NEWS_SPORTS_SEPARATION.md", "sha256": "13fbe7d8629a93a284da7a53611d1d64cf22b37938f514539dfb39f82bdbd3ae", "size": 652 }, { "path": "PHASE_14_INTEGRATED_HARDENING.md", "sha256": "056a3d602b6d82420f7951794bfccba15d8bad2ee48480728a6a88aaafdefc80", "size": 664 }, { "path": "PHASE_15_RUNTIME_INTEGRATION.md", "sha256": "c431d5471cfc6fca7e66049538478d60db7590fa73ef352a61713c9f38026206", "size": 2028 }, { "path": "PHASE_16_PRODUCTION_RELIABILITY.md", "sha256": "95c050c6ca42186840e7748af9cbb25998ebd752da4244d8d8eae62b557f1875", "size": 1239 }, { "path": "PHASE_17_CHANGELOG.md", "sha256": "63eefc10d46f1a5f95b290e7e69bb1809519a66a8a9c0fdaf2bfa5a99aeb3452", "size": 1283 }, { "path": "PHASE_18_LEGACY_RUNTIME_CUTOVER.md", "sha256": "6d247c663f37c95368accf8a3b8dc5ce33d8a3490e764e1821ccab26834fb9b6", "size": 1299 }, { "path": "PHASE_19_CHANGELOG.md", "sha256": "35701b51ecf10e705e4add6d31b34f4beca024fc61208d38693b693feb6ffed4", "size": 568 }, { "path": "PHASE_19_PRODUCTION_CONTROL_OBSERVABILITY.md", "sha256": "84acc97e4ef360e7b893583b5fba0636ec40292494813a09ea55bc1c29e99e62", "size": 990 }, { "path": "PHASE_20_CHANGELOG.md", "sha256": "671868193836b952c90bb3cf3f4ec90cb9e4a443d33ac9f903bda4fac5a1999a", "size": 1121 }, { "path": "PHASE_20_PERFORMANCE_CHAOS.md", "sha256": "3e57069ca12864660e9f8505366d3bf28cc19bc285ca468e3c1530aaf4a9cb16", "size": 1170 }, { "path": "PHASE_21_SECURITY_HARDENING.md", "sha256": "15f1760219dcd158e470ffc1b400e6b6880fd470bd4db4b3c3cfcfe0898e1af1", "size": 455 }, { "path": "PHASE_22_23_CHANGELOG.md", "sha256": "48569be0981a5e1109838ebe0a27316fd8be9f3873bab04bb3327db633375b3d", "size": 259 }, { "path": "PHASE_22_23_PRODUCTION_READINESS_RELEASE.md", "sha256": "5d87894cd88963c3c82ae0bc93d06151df8901f940ef63c7cfab8f5966ec117f", "size": 1146 }, { "path": "PHASE_24_FINAL_GO_LIVE.md", "sha256": "8508b06c4c5f37d4f89ddc4f3baf44dde7eb3f5f8e644fdd67f7b1531fc99958", "size": 1162 }, { "path": "PHASE_4_AI_PROVIDER_POOL.md", "sha256": "47cef98b91f1cfabade1d8a62044e1725d3da659ed511876ad47611d0423f767", "size": 919 }, { "path": "PHASE_5_AI_GATEWAY.md", "sha256": "535dedbe44474726a58e1015127ff5a095cfaa3dc8f5f0ca5cbd112b81662107", "size": 816 }, { "path": "PHASE_6_PERSISTENT_JOB_QUEUE.md", "sha256": "1cc6e8a5055c6e92ffedcbde61ada738aaacae325eb75f1ea62442eeff261303", "size": 526 }, { "path": "PHASE_7_PUBLISH_IDEMPOTENCY.md", "sha256": "060d50a0189b3a6fea011d02ccf10b13b1c62925345873527e734d116b1e941f", "size": 814 }, { "path": "PHASE_8_HEALTH_SUPERVISOR.md", "sha256": "f2eb3b743d198c4c2d02a6a51c4b6a5358af5651ce5ff44c963fcf8bb1233632", "size": 408 }, { "path": "PHASE_9_AI_AUTO_REPAIR.md", "sha256": "8c052f61e0910f2c718f0a436e309ec6f0937a607c6ea1bd51e1cc8cd7a1f21d", "size": 779 }, { "path": "PRODUCTION_READINESS_REPORT.json", "sha256": "eb88b88e9f73be63332fa6aca04e4cae006b6ca8a40af18f14c0522c6ca55469", "size": 999 }, { "path": "README_P29.md", "sha256": "187453f0cd77847b515452c4e790a28cee138bab770389e58b6ecc092997fe4e", "size": 845 }, { "path": "RELEASE_MANIFEST.json", "sha256": "6e8ddb3ccd4e94801791cbbf3ff412d3e6b939bbc3f327bd132f1765965eadf6", "size": 26874 }, { "path": "SECRET_COMPATIBILITY.md", "sha256": "29f31311f7be8e98a39478c1bf0533c04288f56dedbd6fca2229a4718f89fc39", "size": 917 }, { "path": "adapters/__init__.py", "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "size": 0 }, { "path": "bot_core.py", "sha256": "8766333fa0a7a4e31ad835f3ff45bfa082a6f6d8554404e829d86ec71ec10c90", "size": 379351 }, { "path": "config.py", "sha256": "0bd6fb5324b37d35d259d49cb2048bfd390742393c86ff388c28b13e928e48fd", "size": 1085 }, { "path": "core/__init__.py", "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "size": 0 }, { "path": "core/ai/__init__.py", "sha256": "1367728ac663ccdc3f9029fa71543a55ac9dd42bbefb8418c90a9f494188dffb", "size": 82 }, { "path": "core/ai/gateway.py", "sha256": "96866dc9d91be17b146bd36a388fce673a27aaf263087d5ebcacab062576d04e", "size": 4185 }, { "path": "core/ai/http_adapters.py", "sha256": "9baf3a4f69d7d501e16022f39d1c0392f07264c98f506d777d4a236925909391", "size": 4513 }, { "path": "core/app.py", "sha256": "81ed0107330edf1541f196896e02e306126fc6a2e4e54d3a6637e8066ed7ed1a", "size": 2563 }, { "path": "core/config/__init__.py", "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "size": 0 }, { "path": "core/config/settings.py", "sha256": "eb1ede72b85405fcf80a40a300a20327e25fe592b306f487daff70a357086bfc", "size": 779 }, { "path": "core/content/__init__.py", "sha256": "05a48970e396aacbd1c2559912e013f55274f56af2de8f1835228244e1928019", "size": 139 }, { "path": "core/content/dedup.py", "sha256": "131e15642e06b33a5c03ebc4ff7c9c02d2966744c6f8b326a0bbc60c4eef5c45", "size": 1176 }, { "path": "core/content/orchestrator.py", "sha256": "775a95fa9bfe7c8bbc34492859fe73b693e27fac5fc7c5fcf7d8ba68902b1777", "size": 794 }, { "path": "core/content/preflight.py", "sha256": "bf591b475b8a006f24ef86b076a2c9383e815809d6a32f14cd6ac90a98086aac", "size": 1219 }, { "path": "core/content_pipeline.py", "sha256": "a91974dcf6630d5415c8aaf1bd4be0535c20b360b99985f6a5347951a64a537a", "size": 5881 }, { "path": "core/control/__init__.py", "sha256": "76c67ce186facda0e92cae72064f5f9597f479ecdd920e72b36e73d10a201907", "size": 58 }, { "path": "core/control/plane.py", "sha256": "cefdd64451225e22770f9fb9416f1bd8d6d6e34ec650b6b85dec4a76f80e01df", "size": 2707 }, { "path": "core/control/repair_buttons.py", "sha256": "4a87ec8f5e74959dd9022cc7d9dc7e7dbc4cc1ac6fc90ac5526152b0d450f8e2", "size": 893 }, { "path": "core/control/repair_control.py", "sha256": "a91f8a00ad7c5bab5fe2fae00ad02fbbf3a9a5affc8bb95aa5bec208108a964d", "size": 2303 }, { "path": "core/control/router.py", "sha256": "ab18bec51946ab6e94997347adcf85fdf43dd36bd2c30f9ed2ebf292da516bea", "size": 768 }, { "path": "core/control/section_control.py", "sha256": "8fa76d61b9b36c8057125ed0836c1466371924156c0b0199c761b2dfe99e7014", "size": 3677 }, { "path": "core/events/__init__.py", "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "size": 0 }, { "path": "core/events/bus.py", "sha256": "56500b5221e248ad5d141f8cb20da17931df10f1f0e30f4eb5279eae008d281a", "size": 326 }, { "path": "core/health/__init__.py", "sha256": "9b7fa3e154467918688494c5ba8f5fda47deef951a8fabc5556dcf49d43d02ac", "size": 92 }, { "path": "core/health/monitor.py", "sha256": "82c7da1b434917e3c2b1aa40c50cfdc72dfbb899e5e189c49a1dee1129959aa0", "size": 2258 }, { "path": "core/health/registry.py", "sha256": "087e32751fbc1dae1d61b97ffe965af435881e1d93dd998278f4fc120df084ea", "size": 521 }, { "path": "core/infra/audit.py", "sha256": "b0df99430efbcbf07b215792136a0dc868e6829f834bfdae4b20967be00e1ea9", "size": 819 }, { "path": "core/infra/load.py", "sha256": "968612284646ad5c130b804fdbbd6dfd59c675337cef7c76cc9366e3bdd169ce", "size": 1563 }, { "path": "core/infra/metrics.py", "sha256": "642409bcae716d37f8b42b49e0705c439b9eb0dab638575814ab3d91d5172f13", "size": 1041 }, { "path": "core/infra/rate_limiter.py", "sha256": "46c51ef8977570a08888c3686a0bed3a3b4c7377b41e78439bdb70386c388eec", "size": 1079 }, { "path": "core/jobs/__init__.py", "sha256": "f5e17a175507583fde44aa8a4650f40df34ec5bd0ce7891f0a905829959a2c63", "size": 52 }, { "path": "core/jobs/concurrency.py", "sha256": "5ab342a30750a0bfbe7aea65db562adba1f1e27ce8f4a954132b56532fef6bcb", "size": 2060 }, { "path": "core/jobs/queue.py", "sha256": "75f1dff67ae30095af00a530b164811ff199e1e021e14624b51921d231a5e064", "size": 590 }, { "path": "core/jobs/store.py", "sha256": "8d1a9393e2041892d007a82b3697a14d4a15a99639c806ad70d6ad24bec80daf", "size": 1837 }, { "path": "core/jobs/worker.py", "sha256": "f8f6098bc1f8734a0bb3b2babb351b27e60f9fbdbd434e0bb5b338984a9dfd5b", "size": 1713 }, { "path": "core/pipeline/__init__.py", "sha256": "a596c64d3dacbecb19b23abb61d6afd9feaa4252440822fc758c1801dff26f9e", "size": 62 }, { "path": "core/pipeline/adapter.py", "sha256": "9c77de1b826b52fdce1e803db3ab49eaf839c4dcd2dc84cc88e43d51445a12a4", "size": 1181 }, { "path": "core/pipeline/content_pipeline.py", "sha256": "896308ec8822bcc68006c56fced0d97cb6990e478bc738b322f5bf677fbd1062", "size": 1359 }, { "path": "core/plugins/__init__.py", "sha256": "58e78856a6f30ec3253c707cae06a19e4b72f4b98dd1ad09467a7a93f6f26859", "size": 224 }, { "path": "core/plugins/builtin.py", "sha256": "65e74b9135eace9f454d80586c5da325856ec9cd5bb7d832a9e11d69f8858a62", "size": 543 }, { "path": "core/plugins/contracts.py", "sha256": "c666d845435950404d7d11dde2a3869cd06599bf00d334ad98372ce0eee39b6f", "size": 659 }, { "path": "core/plugins/manager.py", "sha256": "1026577ffd512570024dc1e57478dda10ecf23ef7b3ba5498b4ef3a70b2ebd68", "size": 505 }, { "path": "core/plugins/manifest.py", "sha256": "a2386943f2b46a435e60846b015649d994b22e8856dd20f066d4a601aea11ac5", "size": 555 }, { "path": "core/plugins/registry.py", "sha256": "49f6de7c1c874304de76079b795991662761a256222d0b78916115d8d4c59f29", "size": 893 }, { "path": "core/providers/__init__.py", "sha256": "e3542ea700e9c94c8c4a55b32e7aba4e039c75321a99b0430451eed0ef506385", "size": 85 }, { "path": "core/providers/pool.py", "sha256": "baeb75794d436006c2dd1e11e34edd41ebcc820d3cf0967d001ad43e3bb34d91", "size": 4891 }, { "path": "core/providers/router.py", "sha256": "8aa3cea570762612182fb7bdb66bd45c87402792a016b5a4cb7d545cda9d6756", "size": 594 }, { "path": "core/publishing/__init__.py", "sha256": "49358478cbf68d430548938969cf4ce24183f842cc9ecea3ee004acba4b5f613", "size": 60 }, { "path": "core/publishing/ledger.py", "sha256": "07565d42aa8938c41b18f7a13d4737ee29db090c23a020b378d5a0e1e17e73db", "size": 6019 }, { "path": "core/publishing/publisher.py", "sha256": "8a8071979ab63b789cf8060d7140c16c9c38f34e4b7fc8c5d275dba27a29c965", "size": 1741 }, { "path": "core/release/__init__.py", "sha256": "0f67c910abb7b7bec6ddf3d9c82116e4a86d45146c4768352808a8fd8cfbe2e9", "size": 289 }, { "path": "core/release/backup.py", "sha256": "2fe14f325fac5487c65bfe25ad4823c6cc04687f90118e02213fbb356b391c37", "size": 5737 }, { "path": "core/release/go_live.py", "sha256": "f2971108f26de0cd3f5f01df13c2838303230198801d64139199ca7011ddeb7b", "size": 2214 }, { "path": "core/release/readiness.py", "sha256": "60709e484b79dc103a34f0247baf8afbefb22d1cd2336b90044816d0e3b22d9a", "size": 3336 }, { "path": "core/release/release.py", "sha256": "b241d6975f2288a04d58858797bddabceb7da8cec82f8c9a7823cb1933a5aee9", "size": 1045 }, { "path": "core/repair/__init__.py", "sha256": "ed7aed61d211cb63222e37bc90b8b193701eb064d58e1cb0dc08ade19b2425ef", "size": 171 }, { "path": "core/repair/engine.py", "sha256": "9193c0375ed3f1e8e9b738db5924ae4ac4b8f2abb2a7ef4ce963d45458dbe186", "size": 2462 }, { "path": "core/repair/guarded.py", "sha256": "31a06a67ad2da071c4c0f6ef75ac1d5f9a52edcf1131d95f412b3c0bd06d7c50", "size": 1062 }, { "path": "core/repair/policy.py", "sha256": "d0cf78c1007b1a17222ba9021d1b796fc6bf476e544cc29b0cf78187c7107324", "size": 2177 }, { "path": "core/repair/sandbox.py", "sha256": "ad55e35d74410533d1d2efbdebd9ecdaae849021ef5616af61bbcd0512be2282", "size": 3294 }, { "path": "core/runtime/__init__.py", "sha256": "7f8f83aed7f61adbca76ec6e4d8884fa26bdb75c625652adb3e1a37c01835c31", "size": 110 }, { "path": "core/runtime/integration.py", "sha256": "889c4f6b70d27d71ecaf734845e5f5387567850032e981c6c3c83b8b9924136e", "size": 24254 }, { "path": "core/runtime/legacy_bridge.py", "sha256": "06e4a1e02a1e8003f760269f2744142fca6b86dd3b67ad5f4babcac537cc4d49", "size": 1816 }, { "path": "core/runtime/state_store.py", "sha256": "9a3c2513e8049eb9390d2affd8593ae299abac6806193fd49b201305af694288", "size": 2073 }, { "path": "core/secrets/__init__.py", "sha256": "55104b27336502968523805d754d4917c641b953aef2c926cde08e3aa94219b5", "size": 183 }, { "path": "core/secrets/compat.py", "sha256": "669ed3b056876df3c5cd04f59103479958760190441ec07e686881c6b3a578ce", "size": 1867 }, { "path": "core/secrets/manager.py", "sha256": "7ba68d240360c21d527c0700a9a59be7f6235540beaf7e8d1a90f11d2e27f510", "size": 2896 }, { "path": "core/sections/__init__.py", "sha256": "a0b32e81a8cce33514177c49454132de829e9aef4d0a00ce99d8a9d1f0f07383", "size": 264 }, { "path": "core/sections/base.py", "sha256": "1948bdd932a5b3cc62e0b8b25ece5e83ba078c568fe3d509364af83abfe285a1", "size": 1762 }, { "path": "core/sections/controls.py", "sha256": "d70f7cd513e3fc180d089cc28ba6ef1e4e52267eec2a7eab68f85ebc383d12c1", "size": 1427 }, { "path": "core/sections/registry.py", "sha256": "b48247ba36bcad32a96dcaa67397f71cf359325e9bc8c03782aa5662d795ede3", "size": 1055 }, { "path": "core/security/__init__.py", "sha256": "27f5a8f46b417077357d3462d428dfa9d5bba85b714417dd4fa2ce3271e4194d", "size": 301 }, { "path": "core/security/access.py", "sha256": "a796822274a76c104cdd0b12cc12fbd3a2821dedbeb58d13201f95588028fb51", "size": 1445 }, { "path": "core/security/hardening.py", "sha256": "5da19900182af6fa6551c9cea8ad28dee822ce6d0d2a934961af5d6b47f687ed", "size": 2213 }, { "path": "core/security/redaction.py", "sha256": "8036ba78b55fb7c71f30f85572e9a91fbcdb363a3fc5a04e801048ce57a217a3", "size": 632 }, { "path": "core/security/secret_registry.py", "sha256": "6b82f41d851c75088b82ed776b2b537bc275a6e38402b78689938ee30ee27a18", "size": 1594 }, { "path": "core/storage/__init__.py", "sha256": "31b608a029062f5a8667d64c82cfdb98528c2c14f33bc22a999a601a88aab899", "size": 53 }, { "path": "core/storage/job_store.py", "sha256": "f6c6861da781150ba0421a59d6706c9736fcc0f328b4c1bcc20b6b28f0cc045f", "size": 9139 }, { "path": "core/storage/sqlite.py", "sha256": "a099034a9b09183898479e759d863c437270eb3b7bea425bd53d9ebd1ed47ca9", "size": 1087 }, { "path": "core/supervisor/__init__.py", "sha256": "ea70f60799e2adbffc41667442476fd17254f54d03bc5bd528ad808f3db45d98", "size": 97 }, { "path": "core/supervisor/service.py", "sha256": "ef0eb2d3515a6f7a906f057ab8e5941f88f8b16e20ef9a7dee3b8b2adc11bc3a", "size": 813 }, { "path": "core/supervisor/supervisor.py", "sha256": "b85581df41a312ae5302b0b3c2c96133a338f73d6d736b5aed250e1bfcff053c", "size": 1775 }, { "path": "daily_limit_audit.md", "sha256": "750fa93935f47613bae322478faf6b712289f59b517384621c5463ef459d3e63", "size": 3521 }, { "path": "database.py", "sha256": "5c06db36d3d608aefcc842e8a54676301d6ed3dcd5cce30e5a39a2d870952718", "size": 94777 }, { "path": "modules/__init__.py", "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "size": 0 }, { "path": "modules/blogger/__init__.py", "sha256": "e68be9c5cf36d18f4e9bfb05a9b20e2632a84555ac07e3945c5ea0ba273f6599", "size": 408 }, { "path": "modules/blogger/ai_manager.py", "sha256": "334bb356f6c132db9d747652aa7022f855db003602e062c0996bf87ececfc99b", "size": 35876 }, { "path": "modules/blogger/blogger_client.py", "sha256": "446732b7f113b866676d4a5e8f27d6b2e212adaaae17c9538290fdb25abcf0ae", "size": 8066 }, { "path": "modules/blogger/config.py", "sha256": "ba895d67313799b53941a89340aec5aa20252162adb83c6b19b4f47cbe676ca0", "size": 2310 }, { "path": "modules/blogger/database.py", "sha256": "355e1a92ba6a0f3ad65a1787f8c6668c01fb6745ffbee2355a1352f062f2c061", "size": 14160 }, { "path": "modules/blogger/gemini.py", "sha256": "3e452bc364cbe9c799205a206e338b307b94f37f02b1981f0de2bcd0722cf8a7", "size": 22471 }, { "path": "modules/blogger/processor.py", "sha256": "91ae6f6b59567d6142b3e60a5bc4e469c05ff1744565d265d4e92c76e8a74238", "size": 45388 }, { "path": "modules/blogger/prompts.py", "sha256": "b4fd34780569f4dfa30e1d4c2d7a3df18a85d8d57908ca2f6e029e827246082f", "size": 16518 }, { "path": "modules/blogger/publisher.py", "sha256": "cb06660bec141be9c0f5e7b80727350fd2de8a4645d44a8b5d9921b95bbf7fd7", "size": 4938 }, { "path": "modules/blogger/scheduler.py", "sha256": "917db50001327ab9b5fc5244388c035e605cd2c8c09cf64fb4006195826c0347", "size": 47984 }, { "path": "modules/blogger/ui.py", "sha256": "a2b3935a77544ed832a318bb6c3173c1b5d30d75f20bcfde76041d7f4ad697de", "size": 95908 }, { "path": "modules/logging_security.py", "sha256": "972e444e75cf0ff735ca3744827a4ff6da970d7e8e84dde9c21e87c2abb3e422", "size": 2980 }, { "path": "modules/publish_target.py", "sha256": "5efeaac8be400e8d20a1917551456d1778c7d674d487a75c2ae69a2a1a2fd435", "size": 1115 }, { "path": "p27_design_notes.md", "sha256": "f59fa7eab2b07e4d158219f480136874bbc44305724394fcef7de8ba7e0fac6b", "size": 19214 }, { "path": "p28_design_notes.md", "sha256": "a4f85afbb912c8a7eb8ca8cee6188e8073bd9a8330229ea373fd9a7084c6926e", "size": 24318 }, { "path": "p28_progress.md", "sha256": "b04e58f284055c3bff81409d52aa560314867f026fdaa187174b16309a54bf70", "size": 21321 }, { "path": "p29_state.md", "sha256": "037d0adba87d7ce0e1b3ccfbe01a35921d2ce79c0fed8a4254159b5066c112d5", "size": 2065 }, { "path": "requirements-v29.txt", "sha256": "288bea19dea9f505702648cb4c6edf9947da5be88fd3a6f71b08eef587baf8e4", "size": 50 }, { "path": "requirements_audit.md", "sha256": "797077908c16604f47edbe13a6f357fe6186308dca0a59e9541dbbbe8df6ebba", "size": 4518 }, { "path": "scripts_generate_secret_key.py", "sha256": "46fc561d82104b33d6760a4554961d71b338f56932f6d55816d2463ba192cc57", "size": 183 }, { "path": "tests/__init__.py", "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "size": 0 }, { "path": "tests/integration/__init__.py", "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "size": 0 }, { "path": "tests/integration/test_channel_bot_verification.py", "sha256": "07b3db4704dcc69643460c16fb618f49d0d00f9c33a226e2029f14ac1d3cd1ed", "size": 36176 }, { "path": "tests/integration/test_full_pipeline.py", "sha256": "7993e679c65c372355fdb1665835919117bc0f1e5d512a39b57e6842b76baa0a", "size": 63671 }, { "path": "tests/test_ai_gateway.py", "sha256": "f736ca9d0795bcde12118fa74c0ea00cb41c6e27bb9146ca12cdfb578664fbf8", "size": 1209 }, { "path": "tests/test_auto_repair.py", "sha256": "49e8f05c584ec67ff3fb5bf2e0c90cab1d548bd7d3e28d8496c46fb1c6f85e7b", "size": 1177 }, { "path": "tests/test_control_integration.py", "sha256": "7364274672d917f340bf6bc9a7b5ee12c15cf36350df888c550936d8e8248972", "size": 725 }, { "path": "tests/test_health_supervisor.py", "sha256": "e766dd687e46ca28a7eb2811654752b165fe76006571e668803270cfece98a02", "size": 1054 }, { "path": "tests/test_job_store.py", "sha256": "2880f17f04ca954d2c7a37641ce512bcca59c855f38291f9e2894f49d71c2e2d", "size": 715 }, { "path": "tests/test_phase14.py", "sha256": "466ffd7759b53b421dd73acb305d46d49425d49cc11f9717f941bb280a308046", "size": 876 }, { "path": "tests/test_plugins_pipeline.py", "sha256": "db03691da1e7b2c53f72c74245522f2505cc76c7c12349652d3ed8aa60bd7a16", "size": 1001 }, { "path": "tests/test_preview_cleanliness.py", "sha256": "a43dc9472200a0f84f3bb2a6445be52690cd964227f228494671fdce682aa3dd", "size": 2924 }, { "path": "tests/test_provider_pool.py", "sha256": "7f97f0b66300d0b047e7038655bec34fd00b7ecebecd6b78614afc46b3cf2bbf", "size": 1131 }, { "path": "tests/test_publish_idempotency.py", "sha256": "4ff0ba960898b4abc9ea2de057b7e9c610c1a21ce1b2c8dddd4d3874aebba302", "size": 1252 }, { "path": "tests/test_repair_policy.py", "sha256": "1384453e8948071101621b17826d57ec7fb65434dd7c8ab72fe6939a3c46cbe7", "size": 671 }, { "path": "tests/test_sections_news_sports.py", "sha256": "aa46b1899a350e8038a3f4a2fc617f1cfdb470bb77a4a9fa0a570fab86b21369", "size": 1046 }, { "path": "tests/test_system_ui_move.py", "sha256": "1df969deff6db2e7ccebaf5aa35a1cea6596e5fee2a9766cad5b37c2024c4adc", "size": 3337 }, { "path": "tests/v29/conftest.py", "sha256": "993590cfa2be57cab132617bff46c8300d3ce78496651da91dedf0be04011a86", "size": 97 }, { "path": "tests/v29/test_article_package.py", "sha256": "26a838911c25be7f9462ac2cd597599487ac35eda3bebf87d1b1fb6df33366f3", "size": 597 }, { "path": "tests/v29/test_content_gate.py", "sha256": "87e27f7370bb92ec45491b2e56a9e8bac88d9d2292f7f22f6c89411eef9926c5", "size": 1865 }, { "path": "tests/v29/test_core_foundation.py", "sha256": "9a90303524e9040babe32493cd6860811dac31f7220a826b20bc8fd7bd1b0278", "size": 1122 }, { "path": "tests/v29/test_phase16_reliability.py", "sha256": "1156af92ccd907a6e836b8801cb630e55fcd6f8ffd83e59171812fc156bb8a92", "size": 2578 }, { "path": "tests/v29/test_phase17_operational_resilience.py", "sha256": "4a8849f7489a9157438f6823604c58a12427ad3a71f09f546a5c11e89009c172", "size": 4275 }, { "path": "tests/v29/test_phase18_cutover.py", "sha256": "a3bd167a14d20294255edb7e206e1e4282e3ae19fe31ed7309b74dabf093acfd", "size": 1523 }, { "path": "tests/v29/test_phase19_control_plane.py", "sha256": "b63414e50a47656a00ac6b059dc9030ff5dc5027e8b304d28fcf6376e3769667", "size": 1564 }, { "path": "tests/v29/test_phase20_performance_chaos.py", "sha256": "6ca87f7bcc4687ff70931ce0acd3eb834096980b3e09603d916a50f5e0614b8e", "size": 1636 }, { "path": "tests/v29/test_phase21_security.py", "sha256": "794d8473c979269a39b9ab05423f7bc5a26edd2051a0bdbb20a210a1046a2961", "size": 1399 }, { "path": "tests/v29/test_phase22_23_release.py", "sha256": "ebfb91e853df724e7b2423895ceddf4245ae3cb6bbd21865f14dd0ab56926a74", "size": 1668 }, { "path": "tests/v29/test_phase24_final.py", "sha256": "9c2a15145f90afeefe308d14022e7e327ba0d1abb58404514d7f9b0c04079769", "size": 2409 }, { "path": "tests/v29/test_runtime_integration.py", "sha256": "b38f297cdcbe6c1d506c96881143e51d2cc284c324f46ea97664030d2c5187f6", "size": 4341 }, { "path": "tests/v29/test_secret_compatibility.py", "sha256": "5c6fc39e885a960e0288fb6db56a60ed2a0fac727a5249bb1a16d331038c2591", "size": 948 }, { "path": "v29_app.py", "sha256": "3f803143e8011e6c777c4b9e1273e14beb4c240e60ff577854dd5b34b4f4bc1f", "size": 1193 } ], "generated_at": 1787486728.800977, "phase": "24", "product": "P29", "python_min": "3.10", "version": "29.0"}12345678910111213141516171819202122232425262728# P29 Secret Compatibility
The existing secret names are intentionally unchanged. Existing deployments cancontinue to use environment variables exactly as before.
## Existing names
- `API_ID`- `API_HASH`- `BOT_TOKEN`- `SESSION_STRING`- `ADMINS` (legacy fallback: `ADMIN_ID`)- `MIDDLE_CHANNEL`- `GEMINI_KEY_1`, `GEMINI_KEY_2`, and any additional `GEMINI_KEY_N`- `GROQ_KEY_1` and any additional `GROQ_KEY_N`- `OPENROUTER_KEY_1` and any additional `OPENROUTER_KEY_N`- `BLOGGER_BLOG_ID`- `BLOGGER_CLIENT_ID`- `BLOGGER_CLIENT_SECRET`- `BLOGGER_REFRESH_TOKEN`- `P29_SECRET_MASTER_KEY`
Environment values always have priority. If a value is absent from theenvironment, the encrypted SecretManager can supply it. This allows new secretsto be added at runtime without changing application code.
The master key itself remains an environment/host secret and is never storedinside the application database.123456789101112131415161718192021222324import osfrom core.secrets.compat import env_or_secret
API_ID = int(env_or_secret("API_ID", default="0") or "0")API_HASH = env_or_secret("API_HASH", default="") or ""BOT_TOKEN = env_or_secret("BOT_TOKEN", default="") or ""SESSION_STRING = env_or_secret("SESSION_STRING", default="") or ""
# قراءة قائمة الأدمن من متغير ADMINS (أرقام مفصولة بفواصل)admins_str = env_or_secret("ADMINS", default="") or ""ADMINS = [int(x.strip()) for x in admins_str.split(",") if x.strip()]
# إذا لم يُضبط ADMINS نحاول استخدام ADMIN_ID القديم (للتوافق)if not ADMINS: old_admin = env_or_secret("ADMIN_ID", default="") or "" if old_admin: ADMINS = [int(old_admin)]
MIDDLE_CHANNEL = int(env_or_secret("MIDDLE_CHANNEL", default="0") or "0")
if not all([API_ID, API_HASH, BOT_TOKEN, SESSION_STRING, MIDDLE_CHANNEL]): raise ValueError("جميع المتغيرات الأساسية مطلوبة")if not ADMINS: raise ValueError("يجب تعيين ADMINS على الأقل معرف أدمن واحد")123from .gateway import AIGateway, AIResponse
__all__ = ['AIGateway', 'AIResponse']123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110"""P29 AI Gateway — one entry point for all AI calls.
Goals:- Route every request through AIProviderPool.- Keep legacy secret names unchanged.- Fail over across keys/providers on rate limits/transient errors.- Support one structured "article package" request instead of many calls.- Track approximate usage when providers return token metadata."""from __future__ import annotations
from dataclasses import dataclassfrom typing import Any, Callable, Dict, Iterable, Optionalimport jsonimport time
from core.providers.pool import AIProviderPool, KeyState
@dataclassclass AIResponse: data: Any provider: str key_name: str attempts: int input_tokens: int = 0 output_tokens: int = 0
class AIGateway: def __init__(self, pool: AIProviderPool, adapters: Optional[Dict[str, Callable]] = None): self.pool = pool self.adapters = adapters or {}
def register(self, provider: str, adapter: Callable) -> None: self.adapters[provider.lower()] = adapter
def _invoke(self, key: KeyState, payload: Any) -> Any: adapter = self.adapters.get(key.provider) if adapter is None: raise RuntimeError(f"No adapter registered for provider: {key.provider}") return adapter(key.value, payload)
@staticmethod def _usage(result: Any) -> tuple[int, int]: if isinstance(result, dict): usage = result.get("usage") or result.get("token_usage") or {} return int(usage.get("prompt_tokens", usage.get("input_tokens", 0)) or 0), int( usage.get("completion_tokens", usage.get("output_tokens", 0)) or 0 ) return 0, 0
def request( self, payload: Any, providers: Optional[Iterable[str]] = None, max_attempts: int = 6, ) -> AIResponse: attempts = 0 last_error = None for _ in range(max(1, max_attempts)): key = self.pool.choose(providers) if key is None: break attempts += 1 try: result = self._invoke(key, payload) inp, out = self._usage(result) self.pool.report_success(key, inp + out) return AIResponse(result, key.provider, key.name, attempts, inp, out) except Exception as exc: last_error = exc # Provider adapters may classify 429/5xx/timeout failures. rate_limited = bool(getattr(exc, "rate_limited", False)) transient = bool(getattr(exc, "transient", False)) cooldown = int(getattr(exc, "cooldown_seconds", 30)) self.pool.report_failure(key, cooldown_seconds=cooldown, rate_limited=rate_limited) # Backoff is bounded so one broken key cannot stall the whole worker. retry_after = float(getattr(exc, "retry_after_seconds", 0) or 0) if retry_after <= 0: retry_after = min(5.0, 0.25 * (2 ** max(0, attempts - 1))) if transient or rate_limited: time.sleep(max(0.0, min(retry_after, 5.0))) if last_error: raise RuntimeError(f"All AI attempts failed: {last_error}") from last_error raise RuntimeError("No available AI provider keys")
def article_package( self, article: str, *, task: str = "process_article", fields: Optional[list[str]] = None, providers: Optional[Iterable[str]] = None, max_attempts: int = 6, ) -> AIResponse: """Build one compact structured request for all article outputs.""" fields = fields or [ "title", "article", "summary", "keywords", "hashtags", "seo_title", "seo_description", "category", "slug" ] payload = { "task": task, "output_format": "json", "fields": fields, "article": article, "instruction": "Return only the requested JSON object. Do not repeat the input outside the required fields.", } return self.request(payload, providers=providers, max_attempts=max_attempts)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137"""HTTP adapters for the supported P29 providers.
Adapters intentionally receive the selected secret as an argument from AIGateway;they never read or log environment secrets themselves."""from __future__ import annotations
import jsonimport refrom typing import Any
class ProviderHTTPError(RuntimeError): def __init__(self, message, *, status_code=0, rate_limited=False, transient=False, retry_after_seconds=0): super().__init__(message) self.status_code = status_code self.rate_limited = rate_limited self.transient = transient self.retry_after_seconds = retry_after_seconds self.cooldown_seconds = max(1, int(retry_after_seconds or (60 if rate_limited else 15)))
def _json_from_text(text: str) -> Any: text = (text or "").strip() # Models sometimes wrap JSON in markdown fences. text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.I) text = re.sub(r"\s*```$", "", text) try: return json.loads(text) except Exception: m = re.search(r"\{.*\}", text, flags=re.S) if m: return json.loads(m.group(0)) return {"text": text}
def _raise_response(response) -> None: if response.is_success: return status = int(response.status_code) retry_after = response.headers.get("retry-after", "0") try: retry = float(retry_after) except Exception: retry = 0 raise ProviderHTTPError( f"provider HTTP {status}", status_code=status, rate_limited=status == 429, transient=status == 429 or status >= 500, retry_after_seconds=retry, )
def gemini_adapter(api_key: str, payload: dict) -> dict: import httpx model = payload.get("model", "gemini-2.0-flash") prompt = json.dumps(payload, ensure_ascii=False) body = { "contents": [{"parts": [{"text": prompt}]}], "generationConfig": {"responseMimeType": "application/json"}, } with httpx.Client(timeout=45) as client: response = client.post( f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent", params={"key": api_key}, json=body, ) _raise_response(response) data = response.json() parts = data.get("candidates", [{}])[0].get("content", {}).get("parts", []) text = "".join(str(p.get("text", "")) for p in parts if isinstance(p, dict)) result = _json_from_text(text) usage = data.get("usageMetadata") or {} if isinstance(result, dict): result.setdefault("usage", { "prompt_tokens": usage.get("promptTokenCount", 0), "completion_tokens": usage.get("candidatesTokenCount", 0), }) return result
def _openai_compatible(api_key: str, payload: dict, base_url: str, model: str) -> dict: import httpx system = payload.get("system") or ( "Return only a JSON object matching the requested fields. " "Do not include markdown fences." ) user = json.dumps(payload, ensure_ascii=False) body = { "model": model, "messages": [ {"role": "system", "content": system}, {"role": "user", "content": user}, ], "response_format": {"type": "json_object"}, } with httpx.Client(timeout=45) as client: response = client.post( base_url, headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}, json=body, ) _raise_response(response) data = response.json() content = ( data.get("choices", [{}])[0] .get("message", {}) .get("content", "") ) result = _json_from_text(content) usage = data.get("usage") or {} if isinstance(result, dict): result.setdefault("usage", usage) return result
def groq_adapter(api_key: str, payload: dict) -> dict: return _openai_compatible( api_key, payload, "https://api.groq.com/openai/v1/chat/completions", payload.get("model", "llama-3.3-70b-versatile"), )
def openrouter_adapter(api_key: str, payload: dict) -> dict: return _openai_compatible( api_key, payload, "https://openrouter.ai/api/v1/chat/completions", payload.get("model", "openai/gpt-4o-mini"), )
def register_default_http_adapters(gateway) -> None: gateway.register("gemini", gemini_adapter) gateway.register("groq", groq_adapter) gateway.register("openrouter", openrouter_adapter)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""P29 phase-15 composition root.
The legacy runtime remains available, but all new section traffic can now use oneshared RuntimeIntegration instance. External adapters are registered by the host."""from __future__ import annotations
from .config.settings import settingsfrom .plugins.registry import PluginRegistryfrom .plugins.builtin import register_builtinsfrom .plugins.manager import SectionManagerfrom .events.bus import EventBusfrom .runtime.integration import RuntimeIntegrationfrom .ai.http_adapters import register_default_http_adaptersfrom .release.readiness import ProductionReadinessfrom .release.backup import BackupManagerfrom .release.release import ReleaseManifestfrom .release.go_live import GoLiveGate
class App: def __init__(self, legacy_db=None, project_root="."): self.settings = settings self.plugins = PluginRegistry() register_builtins(self.plugins) self.events = EventBus() self.runtime = RuntimeIntegration( db=legacy_db, db_path=settings.db_path, project_root=project_root, ) register_default_http_adapters(self.runtime.ai) self.sections = SectionManager(self.plugins) self.readiness = ProductionReadiness(self.runtime, project_root) self.backups = BackupManager(settings.data_dir, "backups") self.release_manifest_builder = ReleaseManifest(project_root) self.go_live = GoLiveGate(self)
def discover_plugins(self): return self.plugins.discover()
def register_ai_provider(self, provider, adapter): self.runtime.register_ai_provider(provider, adapter)
def register_publisher(self, target, adapter): self.runtime.register_publisher(target, adapter)
def health(self): return self.runtime.health_snapshot()
def metrics(self): return self.runtime.metrics_snapshot()
def controls(self): return self.runtime.control_snapshot()
def production_readiness(self, require_secrets=()): return self.readiness.evaluate(tuple(require_secrets))
def create_backup(self, databases=None, label="release"): dbs = databases or [self.settings.db_path] return self.backups.create(dbs, label=label)
def release_manifest(self, version="29.0", phase="24", output=None): return self.release_manifest_builder.build(version=version, phase=phase, output=output)
def go_live_report(self, require_telegram=False): return self.go_live.evaluate(require_telegram=require_telegram)12345678910111213141516"""Central, extensible settings loaded from environment without hard-coding secrets."""from dataclasses import dataclassimport os
@dataclass(frozen=True)class Settings: data_dir: str = os.getenv("APP_DATA_DIR", "data") runtime_dir: str = os.getenv("APP_RUNTIME_DIR", "runtime") db_path: str = os.getenv("APP_DB_PATH", "data/app.sqlite3") log_level: str = os.getenv("APP_LOG_LEVEL", "INFO") timezone: str = os.getenv("APP_TIMEZONE", "UTC") auto_repair_enabled: bool = os.getenv("AUTO_REPAIR_ENABLED", "false").lower() in {"1","true","yes","on"} auto_repair_apply: bool = os.getenv("AUTO_REPAIR_APPLY", "false").lower() in {"1","true","yes","on"} max_repair_attempts: int = int(os.getenv("AUTO_REPAIR_MAX_ATTEMPTS", "2"))
settings = Settings()123from .preflight import ContentPreflight, PreflightResultfrom .dedup import DedupStorefrom .orchestrator import ContentGate, GateDecision1234567891011121314151617181920212223242526from __future__ import annotationsimport sqlite3, timefrom pathlib import Path
class DedupStore: def __init__(self,path="data/jobs.sqlite3"): self.path=Path(path); self.path.parent.mkdir(parents=True,exist_ok=True) self._init() def _conn(self): c=sqlite3.connect(self.path,timeout=30,isolation_level=None) c.execute("PRAGMA journal_mode=WAL"); c.execute("PRAGMA synchronous=FULL") return c def _init(self): with self._conn() as c: c.execute("""CREATE TABLE IF NOT EXISTS content_dedup( fingerprint TEXT PRIMARY KEY, source TEXT NOT NULL, article_id TEXT, created_at REAL NOT NULL)""") def seen(self,fp): with self._conn() as c: return c.execute("SELECT 1 FROM content_dedup WHERE fingerprint=?",(fp,)).fetchone() is not None def remember(self,fp,source,article_id=None): with self._conn() as c: c.execute("INSERT OR IGNORE INTO content_dedup VALUES(?,?,?,?)",(fp,source,article_id,time.time()))
def forget(self, fp): with self._conn() as c: c.execute("DELETE FROM content_dedup WHERE fingerprint=?", (fp,))12345678910111213141516171819202122from __future__ import annotationsfrom dataclasses import dataclassfrom .preflight import ContentPreflightfrom .dedup import DedupStore
@dataclassclass GateDecision: accepted: bool reason: str fingerprint: str
class ContentGate: def __init__(self,blocked_words=(),dedup=None): self.preflight=ContentPreflight(blocked_words) self.dedup=dedup or DedupStore() def check(self,text,source="unknown",article_id=None): r=self.preflight.run(text) if not r.accepted: return GateDecision(False,r.reason,r.fingerprint) if self.dedup.seen(r.fingerprint): return GateDecision(False,"duplicate",r.fingerprint) self.dedup.remember(r.fingerprint,source,article_id) return GateDecision(True,"accepted",r.fingerprint)12345678910111213141516171819202122232425262728293031323334from __future__ import annotationsimport hashlib, refrom dataclasses import dataclass
@dataclass(frozen=True)class PreflightResult: accepted: bool reason: str cleaned: str fingerprint: str
class ContentPreflight: """Zero-AI-cost gate: blocked words and exact/normalized duplicates run first.""" def __init__(self, blocked_words=()): self.blocked={str(x).strip().casefold() for x in blocked_words if str(x).strip()}
@staticmethod def normalize(text): return re.sub(r'\s+',' ',re.sub(r'[^\w\s]',' ',str(text),flags=re.UNICODE)).strip().casefold()
def fingerprint(self,text): return hashlib.sha256(self.normalize(text).encode("utf-8")).hexdigest()
def run(self,text,seen_fingerprints=None): raw=str(text) norm=self.normalize(raw) hits=[w for w in self.blocked if w in norm] if hits: return PreflightResult(False,"blocked_word:"+hits[0],raw,self.fingerprint(raw)) fp=self.fingerprint(raw) if seen_fingerprints is not None and fp in seen_fingerprints: return PreflightResult(False,"duplicate",raw,fp) cleaned=raw return PreflightResult(True,"accepted",cleaned,fp)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138"""Global content gate used by every content section before AI or external APIs.
Order is intentionally strict: blocked-word gate -> duplicate gate -> normalize/fingerprint.This module is section-agnostic so Blogger, News, Sports and future plugins can reuse it."""from __future__ import annotations
import hashlibimport reimport unicodedatafrom dataclasses import dataclassfrom typing import Any, Iterable, Optionalfrom core.content.dedup import DedupStore
@dataclass(frozen=True)class GateResult: allowed: bool reason: str = "" matched: tuple[str, ...] = () fingerprint: str = ""
class ContentGate: def __init__(self, db: Any, dedup: Optional[DedupStore] = None): self.db = db self.dedup = dedup
@staticmethod def normalize(text: str) -> str: text = text or "" text = unicodedata.normalize("NFKC", text) text = text.replace("ـ", "") # Arabic diacritics / tatweel noise. text = re.sub(r"[\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06ED]", "", text) text = text.replace("أ", "ا").replace("إ", "ا").replace("آ", "ا") text = text.replace("ى", "ي").replace("ؤ", "و").replace("ئ", "ي") text = re.sub(r"https?://\S+", " URL ", text, flags=re.I) text = re.sub(r"@\w+", " USER ", text) text = re.sub(r"\s+", " ", text).strip().casefold() return text
@classmethod def fingerprint(cls, text: str, source_url: str = "") -> str: normalized = cls.normalize(text) url = cls.normalize(source_url) payload = f"{url}|{normalized}" return hashlib.sha256(payload.encode("utf-8", errors="replace")).hexdigest()
@classmethod def title_fingerprint(cls, title: str) -> str: return hashlib.sha256(cls.normalize(title).encode("utf-8")).hexdigest()
@classmethod def _contains(cls, text: str, words: Iterable[str]) -> tuple[str, ...]: normalized = cls.normalize(text) matches = [] for raw in words or []: word = str(raw or "").strip() if not word: continue nw = cls.normalize(word) if nw and nw in normalized: matches.append(word) return tuple(dict.fromkeys(matches))
def blocked_words(self, channel_id: str = "") -> list[str]: words = [] try: words.extend(self.db.get_blocked_words() or []) except Exception: pass if channel_id: try: words.extend(self.db.get_channel_blocked_words(channel_id) or []) except Exception: pass return list(dict.fromkeys(str(w) for w in words if str(w).strip()))
def check_blocked(self, text: str, channel_id: str = "") -> GateResult: matched = self._contains(text, self.blocked_words(channel_id)) if matched: return GateResult(False, "blocked_word", matched=matched) return GateResult(True)
def check_duplicate(self, text: str, source_url: str = "", fingerprint: Optional[str] = None, source: str = "", article_id: str = "") -> GateResult: fp = fingerprint or self.fingerprint(text, source_url) if self.dedup is not None: try: if self.dedup.seen(fp): return GateResult(False, "duplicate", fingerprint=fp) self.dedup.remember(fp, source or "unknown", article_id or None) except Exception: # Persistent dedup failure is fail-open only for compatibility with # the legacy JSON store; the runtime health monitor records the fault. pass try: if self.db.is_published(fp): return GateResult(False, "duplicate", fingerprint=fp) existing = self.db.get_article(fp) if existing and existing.get("status") not in ("failed_permanent", "discarded"): return GateResult(False, "duplicate", fingerprint=fp) # Conservative normalized title/content comparison for older records. norm = self.normalize(text) if norm: for article in self.db.get_all_articles() or []: if article.get("fingerprint") == fp: return GateResult(False, "duplicate", fingerprint=fp) except Exception: pass return GateResult(True, fingerprint=fp)
def preflight(self, text: str, source_url: str = "", channel_id: str = "", source: str = "", article_id: str = "") -> GateResult: if not (text or "").strip(): return GateResult(False, "empty") # Deliberately before fingerprint/AI work: blocked content costs zero AI requests. blocked = self.check_blocked(text, channel_id) if not blocked.allowed: return blocked return self.check_duplicate(text, source_url, source=source, article_id=article_id)
def postflight(self, article: dict, channel_id: str = "") -> GateResult: text = "\n".join( str(article.get(k, "") or "") for k in ("title", "introduction", "body", "conclusion", "summary", "keywords") ) blocked = self.check_blocked(text, channel_id) if not blocked.allowed: return blocked source_url = article.get("source_url", "") original_fp = article.get("fingerprint", "") candidate_fp = self.fingerprint(text, source_url) # The input fingerprint is already reserved at ingest. It is expected to # exist in the dedup store, so do not misclassify the same job as a duplicate. if original_fp and candidate_fp == original_fp: return GateResult(True, fingerprint=original_fp) return self.check_duplicate(text, source_url, fingerprint=candidate_fp)1from .repair_buttons import ControlButton, REPAIR_BUTTONS1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556from __future__ import annotationsimport timefrom dataclasses import dataclass, asdict
@dataclassclass Alert: key: str severity: str message: str first_seen: float last_seen: float count: int = 1 active: bool = True
class ControlPlane: """Read-only operational control surface with safe, actionable alerts.""" def __init__(self, runtime, dead_threshold=1, queue_threshold=50): self.runtime = runtime self.dead_threshold = int(dead_threshold) self.queue_threshold = int(queue_threshold) self._alerts: dict[str, Alert] = {}
def _upsert(self, key, severity, message): now=time.time(); old=self._alerts.get(key) if old: old.last_seen=now; old.count+=1; old.active=True; old.message=message else: self._alerts[key]=Alert(key,severity,message,now,now)
def evaluate(self): stats=self.runtime.queue.store.get_stats() if stats.get("dead",0)>=self.dead_threshold: self._upsert("queue.dead","critical",f"Dead-letter jobs: {stats['dead']}") else: self._resolve("queue.dead") if stats.get("queued",0)>=self.queue_threshold: self._upsert("queue.backlog","warning",f"Queue backlog: {stats['queued']}") else: self._resolve("queue.backlog") for name,item in self.runtime.health_snapshot().items(): key=f"health:{name}" if item.get("status")=="unhealthy": self._upsert(key,"critical",f"Unhealthy service: {name}") else: self._resolve(key) return self.active_alerts()
def _resolve(self,key): if key in self._alerts: self._alerts[key].active=False def active_alerts(self): return [asdict(a) for a in self._alerts.values() if a.active] def snapshot(self): return {"queue":self.runtime.queue.store.get_stats(),"health":self.runtime.health_snapshot(),"metrics":self.runtime.metrics_snapshot(),"providers":self.runtime.pool.snapshot(),"alerts":self.evaluate(),"sections":{s:self.runtime.get_section_state(s) for s in self.runtime._sections},"security":self.security_snapshot()} def security_snapshot(self): findings = self.runtime.security.validate_environment() if hasattr(self.runtime, "security") else [] return {"rotation_epoch": getattr(getattr(self.runtime, "security", None), "rotation_epoch", 0), "findings":[getattr(x, "__dict__", str(x)) for x in findings]}
def acknowledge(self,key,admin_approved=False): if not admin_approved:return {"ok":False,"reason":"admin_required"} alert=self._alerts.get(key) if not alert:return {"ok":False,"reason":"not_found"} alert.active=False return {"ok":True,"key":key}123456789101112131415161718from __future__ import annotationsfrom dataclasses import dataclass
@dataclass(frozen=True)class ControlButton: key: str label: str callback: str
# Additive only: existing button callbacks are not renamed or removed.REPAIR_BUTTONS = ( ControlButton("repair_status", "🛠️ حالة الإصلاح التلقائي", "repair:status"), ControlButton("repair_pending", "🛡️ الإصلاحات بانتظار الموافقة", "repair:pending"), ControlButton("repair_approve", "✅ الموافقة على الإصلاح", "repair:approve"), ControlButton("repair_rollback", "↩️ التراجع عن آخر إصلاح", "repair:rollback"), ControlButton("repair_disable", "⛔ إيقاف الإصلاح التلقائي", "repair:disable"), ControlButton("repair_enable", "▶️ تشغيل الإصلاح التلقائي", "repair:enable"),)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758from __future__ import annotationsfrom core.control.router import ControlRouterfrom core.control.repair_buttons import REPAIR_BUTTONS
class RepairControl: """Control-bot integration façade. Host Telegram layer only needs to dispatch callback strings.""" def __init__(self, repair_engine, guard, state: dict|None=None): self.engine=repair_engine self.guard=guard self.state=state if state is not None else {"enabled": True, "pending": [], "last": None} self.router=ControlRouter() self._register()
def _register(self): self.router.register("repair:status", lambda: { "enabled": self.state["enabled"], "pending": len(self.state["pending"]), "last": self.state["last"], }) self.router.register("repair:pending", lambda: list(self.state["pending"])) self.router.register("repair:disable", self.disable) self.router.register("repair:enable", self.enable) self.router.register("repair:rollback", self.rollback)
def disable(self): self.state["enabled"]=False return {"ok":True,"enabled":False}
def enable(self): self.state["enabled"]=True return {"ok":True,"enabled":True}
def queue_for_approval(self, record): self.state["pending"].append(record) self.state["last"]=record return record
def approve(self, repair_record_id: str, apply_fn): if not self.state["enabled"]: return {"ok":False,"reason":"auto-repair disabled"} match=next((x for x in self.state["pending"] if getattr(x,"repair_id",None)==repair_record_id),None) if not match: return {"ok":False,"reason":"repair not found"} result=apply_fn(match) self.state["pending"]=[x for x in self.state["pending"] if x is not match] self.state["last"]=result return {"ok":True,"result":result}
def rollback(self): last=self.state.get("last") if not last: return {"ok":False,"reason":"no repair recorded"} try: self.engine.rollback(last) self.state["last"]=last return {"ok":True,"status":"rolled_back"} except Exception as exc: return {"ok":False,"reason":str(exc)}ARCHITECTURE_V29.mdAdded+29
CONTENT_PIPELINE_V29.mdAdded+21
P29_MIGRATION_PLAN.mdAdded+29
P29_STAGE3_CHANGELOG.mdAdded+20
PHASE_10_REPAIR_POLICY_CONTROL.mdAdded+19
PHASE_11_CONTROL_INTEGRATION.mdAdded+17
PHASE_12_PLUGIN_ADAPTERS.mdAdded+29
PHASE_13_NEWS_SPORTS_SEPARATION.mdAdded+23
PHASE_14_INTEGRATED_HARDENING.mdAdded+15
PHASE_15_RUNTIME_INTEGRATION.mdAdded+39
PHASE_16_PRODUCTION_RELIABILITY.mdAdded+19
PHASE_17_CHANGELOG.mdAdded+30
PHASE_18_LEGACY_RUNTIME_CUTOVER.mdAdded+23
PHASE_19_CHANGELOG.mdAdded+9
PHASE_19_PRODUCTION_CONTROL_OBSERVABILITY.mdAdded+18
PHASE_20_CHANGELOG.mdAdded+15
PHASE_20_PERFORMANCE_CHAOS.mdAdded+16
PHASE_21_SECURITY_HARDENING.mdAdded+8
PHASE_22_23_CHANGELOG.mdAdded+8
PHASE_22_23_PRODUCTION_READINESS_RELEASE.mdAdded+17
PHASE_24_FINAL_GO_LIVE.mdAdded+22
PHASE_4_AI_PROVIDER_POOL.mdAdded+25
PHASE_5_AI_GATEWAY.mdAdded+20
PHASE_6_PERSISTENT_JOB_QUEUE.mdAdded+13
PHASE_7_PUBLISH_IDEMPOTENCY.mdAdded+15
PHASE_8_HEALTH_SUPERVISOR.mdAdded+11
PHASE_9_AI_AUTO_REPAIR.mdAdded+22
PRODUCTION_READINESS_REPORT.jsonAdded+45
README_P29.mdAdded+23
RELEASE_MANIFEST.jsonAdded+849
SECRET_COMPATIBILITY.mdAdded+28
adapters/__init__.pyAdded
bot_core.pyAdded
config.pyAdded+24
core/__init__.pyAdded
core/ai/__init__.pyAdded+3
core/ai/gateway.pyAdded+110
core/ai/http_adapters.pyAdded+137
core/app.pyAdded+68
core/config/__init__.pyAdded
core/config/settings.pyAdded+16
core/content/__init__.pyAdded+3
core/content/dedup.pyAdded+26
core/content/orchestrator.pyAdded+22
core/content/preflight.pyAdded+34
core/content_pipeline.pyAdded+138
core/control/__init__.pyAdded+1
core/control/plane.pyAdded+56
core/control/repair_buttons.pyAdded+18
core/control/repair_control.pyAdded+58