feat(seo): atomic directive fencing and transactional blog publication
Deploy Canina / deploy (push) Successful in 4m45s
Deploy Canina / deploy (push) Successful in 4m45s
This commit is contained in:
1 parent
0a156fd7b4
commit
fb1deadbbc
10 files changed
+353
-187
No files matched your search
@@ -1,26 +1,42 @@
|
||||
# Dormant daily publisher research/directive consumer
|
||||
# Dormant research/directive publication boundary
|
||||
|
||||
No cron or active runtime is changed. The actual publisher is agent-driven by `/opt/data/publishers/e4c9b52eb040/cron-prompt.txt` (research line 11, draft/reviews line 13, guarded Admin creation line 17). Its directory and parent batch engine are outside Git. This repository previously contained no matching daily-publisher module. `daily_publisher.run_new` is the versioned integration boundary, not a claim of live enforcement.
|
||||
No runtime publisher, cron, Gate1/2, deployment, or live API is changed. `daily_publisher.run_new` remains a dormant integration boundary, not current cron enforcement.
|
||||
|
||||
## Authorized future caller wiring
|
||||
## Caller contract (breaking change to dormant callback)
|
||||
|
||||
Provision these modules through a reviewed Git/Stage/runtime process, then have the existing owner call `run_new(Consumer(journal, AdminTransport(verified_admin_origin, approved_bearer)), stable_run_id, finding_payload, Content_callback, independent_review_callback, existing_guarded_NEW_create_callback)`.
|
||||
`run_new(consumer, stable_run_id, research, draft_content, independent_review, publication_preflight)` saves research before drafting. Content and the independent reviewer receive the complete fetched finding and exact CEO free text/version. The draft must now be the actual Admin Blog payload, not a wrapper containing HTML. A nonempty directive requires reviewer identity, immutable evidence location and exact directive/draft SHA256 bindings. Hash checks establish binding, not reviewer authenticity or arbitrary prose compliance.
|
||||
|
||||
- finding_payload uses the backend CreateFindingDto contract (title, hypothesis, targetKeywords, primaryKeyword, expectedOutcome, optional metric goal). No article is created by the adapter itself.
|
||||
- Content callback receives the entire saved/fetched finding, including exact CEO free-text feedback/version. Save immutable draft artifacts; preserve the existing medical/SEO/QA chain.
|
||||
- Independent reviewer callback receives finding, draft and both SHA256 digests. A nonempty directive requires reviewer identity, evidence artifact URI/path, exact directiveHash and draftHash. Review must quote the directive and map every request to draft passages or explicit unresolved findings. The adapter verifies binding, not arbitrary semantic obedience or reviewer authenticity; trusted review orchestration remains essential. Empty feedback needs no CEO approval. No Gate1/2 is introduced.
|
||||
- Existing create callback must retain publisher_state ownership, fresh inventory/relations/quota checks, nonempty backup, independent exact-hash QA and write-ahead intent. Return confirmed blog UUID only. Never wrap an unguarded HTTP create callback in production.
|
||||
- Persist journal outside temporary storage, shared by all invocations, with stable run ID. It records consumed finding and feedback versions, review, draft digest and created identity. A concurrent invocation cannot enter create after a claim transition. Network ambiguity blocks retries. Existing daily quota guard still protects different run IDs and different journal files.
|
||||
- `reconcile_link(run_id)` only links the saved confirmed blog, never creates another article. If feedback changed after create, retain the blog and route independent repair. No automatic resave/update.
|
||||
`publication_preflight(draft)` MUST run the existing publisher ownership, fresh inventory/relations/quota, backup, independent QA and write-ahead intent guards, and return the **unchanged reviewed payload without creating a Blog**. The consumer alone sends the atomic publication POST. Do not pass the previous Blog-creating callback: a returned string is rejected, but a malicious/incorrect callback could already have written before returning; trusted orchestration and reviewed wiring remain essential. No active wiring is included here.
|
||||
|
||||
## Atomicity limit (not concealed)
|
||||
The SQLite journal persists intent before network writes. Failed/ambiguous POSTs are never automatically retried. `reconcile_link(run)` is now read-only: it confirms a matching committed actionId/blogId, including after later feedback, or blocks for independent repair. It never creates or relinks an article. Other run IDs still require the existing shared publisher quota/ownership guard.
|
||||
|
||||
Backend PATCH action atomically checks `expectedVersion` AND `feedbackVersion`; conflict prevents the callback. It does **not** participate in the later Blog create transaction. CEO edits after claim and before actual creation can therefore race. The adapter detects changed feedback on post-create link, retains the article identity and blocks linking/recreation, but cannot roll back the article. Full no-stale-publication requires an additional backend transaction/lease contract on the actual Blog creation boundary. Do not claim that consumption acknowledgement guarantees free-text implementation or that this dormant adapter protects current cron publication.
|
||||
## Backend endpoint and serialization boundary
|
||||
|
||||
## Executed evidence
|
||||
`POST /api/admin/seo-tracking/:id/publication`
|
||||
|
||||
- RED before implementation: unittest import failed because consumer module did not exist.
|
||||
- `python -B -m unittest discover -s scripts/content-research -v`: **11 passed**, covering real integration entrypoint with isolated transport/callback fixtures, feedback before/after claim, optional feedback, exact receipt hashes, contention, idempotency, research timeout and publication ambiguity, link-only repair.
|
||||
- Existing Git editorial suites: **2 passed, 3 skipped** (root-only ownership fixtures unavailable).
|
||||
- Existing untouched runtime `python -B -m unittest discover -s /opt/data/publishers/e4c9b52eb040 -p test_publisher_state.py -v`: **3 passed, 2 errors**. Both existing tests call intent without the now-required independent QA fixture and fail `QA_REQUIRED: current-day independent exact-hash approval`. Runtime/test files were not edited; this is a pre-existing fixture drift, not a green regression claim.
|
||||
- No live API request, publication, deployment, push, cron edit or activation. No backend/UI change. Tests establish local callback/API contract only, not live database/network acceptance.
|
||||
Authenticated JWT admin/superadmin only (same controller guards as existing SEO tracking). Request:
|
||||
|
||||
```json
|
||||
{"expectedVersion":0,"feedbackVersion":0,"actionId":"stable-run-id","blog":{"title":"...","slug":"...","content":"..."}}
|
||||
```
|
||||
|
||||
`blog` uses existing Admin BlogsService create rules, including current-user author fallback, relations/tags, dates, schedule/status defaults and reading-time conversion. The endpoint deliberately does not invent another Blog field schema. It does not accept an arbitrary Prisma create input or bypass Admin create policy. Missing/invalid author or relation fails the entire transaction.
|
||||
|
||||
One transaction performs row-locking compare-and-swap on finding id/version/feedbackVersion with `blogId = null`, creates Blog via the existing Admin service using the same transaction client, then stores blogId/actionId. Response contains `blog`, `finding`, `consumedFeedbackVersion`, `cacheRevalidation`. Missing finding is 404; stale version/directive or already-linked finding is 409. Repeat requests are not create-idempotent responses: they conflict; the consumer reconciles saved action identity read-only. Cache revalidation happens only after commit; failure returns `failed` plus the committed identity, not an error encouraging recreation. External generation, review and publisher preflight happen before the transaction, not while holding the row lock.
|
||||
|
||||
Feedback PATCH uses the same row and finding version. If feedback commits first, publication's old predicate fails and no Blog exists. If publication locks first, feedback waits; after commit its old expectedVersion fails with 409. A fresh feedback request after committed publication applies to the **next action**, not retroactively to the already committed article. This is a linearization boundary, not a guarantee that all directives arriving after the boundary rewrite published content.
|
||||
|
||||
The legacy generic Blog endpoint and PATCH action remain for existing callers: this endpoint does not magically protect callers bypassing it. PATCH action is an acknowledgement/link operation, not publication authorization. No Gate1/2 or semantic-compliance claim is added.
|
||||
|
||||
## Many-actions and goals: explicitly not implemented
|
||||
|
||||
Prisma currently has one nullable unique blogId, one scalar nonunique external actionId, and one independently nullable goalMetric/goalTarget pair per finding. PATCH replaces those slots; it does not append immutable action history. A finding has many measurement snapshots, but snapshots target the finding only and cannot attribute evidence to a particular action or goal. UI shows one article/expectedOutcome and omits typed action/metric/target fields; the measurement worker resolves one article URL and does not evaluate structured goals.
|
||||
|
||||
A future additive migration should introduce Finding 1:N ResearchAction (immutable identity/idempotency key, lifecycle, consumed feedback version, external reference), Finding 1:N ResearchGoal (metric, comparator, unit, target/baseline, window, source), ActionGoal joins, and explicit action article targets. Goal evaluations should reference measured evidence, not imply causal attribution from aggregate page totals. Backfill at most one marked legacy action; never invent historical acknowledgements or complete goals from partial scalar data. Specify legacy projection/conflict rules before dual writes and update backend/UI/worker/tests together. This patch intentionally preserves the initial model and rejects a second publication on a linked finding.
|
||||
|
||||
## Local evidence
|
||||
|
||||
- Disposable PostgreSQL 16.14, schema pushed only to loopback port 55447; `publication.postgres.spec.ts` exercises actual row-lock wait with distinct backend PIDs via pg_stat_activity, stale-feedback-first rejection, publication-first feedback conflict, full rollback on invalid author, duplicate rejection and cache-failure identity.
|
||||
- Same suite runs Python `run_new` over actual loopback TCP through Nest JWT/role guards and Prisma, proving successful atomic publication, changed feedback during preflight -> HTTP 409/no Blog, and unauthenticated publication -> HTTP 401. HTTPS production transport is not weakened: the test uses an explicit disposable-only loopback adapter.
|
||||
- Harness and machine-readable results are local evidence under `/opt/data/cache/scratch/run-publication-pg.mjs`, `publication-pg.log`, `publication-jest.json`. Server shuts down in finally. The existing PG16 npm tooling lives in the untracked evidence directory; it is not a release dependency.
|
||||
- No live writes, deploy, push, cron activation or runtime publisher edits.
|
||||
Reference in new issue
Block a user