From 216e05ba258cf7882350f00da9d9b659885d9816 Mon Sep 17 00:00:00 2001 From: Canina Hermes Date: Fri, 30 Oct 2026 12:28:51 +0000 Subject: [PATCH] feat(corporate): persist dated monthly plans and repair verified release gates --- .../src/admin/hermes/corporate-policy.spec.ts | 39 ++- backend/src/admin/hermes/corporate-policy.ts | 101 ++++++- .../src/admin/hermes/corporate.controller.ts | 17 ++ .../hermes/corporate.integration.spec.ts | 278 ++++++++++++++++++ backend/src/admin/hermes/corporate.service.ts | 124 ++++++++ .../seo-tracking/seo-tracking.service.spec.ts | 17 ++ .../src/seo-tracking/seo-tracking.service.ts | 47 +-- .../app/blog/[slug]/blog-slug-page.test.tsx | 4 +- frontend/application/app/blog/[slug]/page.tsx | 13 +- .../blog/[slug]/timestamp-metadata.test.tsx | 73 +++++ .../blog/[slug]/timestamp-visible.test.tsx | 17 ++ scripts/corporate_runtime.py | 16 +- scripts/corporate_runtime_test.py | 17 ++ specs/blog-timestamp-metadata/evidence.md | 12 + specs/blog-timestamp-metadata/plan.md | 4 + specs/blog-timestamp-metadata/spec.md | 12 + specs/blog-timestamp-metadata/tasks.md | 7 + .../monthly-plan-slice.md | 60 ++++ 18 files changed, 829 insertions(+), 29 deletions(-) create mode 100644 frontend/application/app/blog/[slug]/timestamp-metadata.test.tsx create mode 100644 frontend/application/app/blog/[slug]/timestamp-visible.test.tsx create mode 100644 specs/blog-timestamp-metadata/evidence.md create mode 100644 specs/blog-timestamp-metadata/plan.md create mode 100644 specs/blog-timestamp-metadata/spec.md create mode 100644 specs/blog-timestamp-metadata/tasks.md create mode 100644 specs/corporate-execution-observability/monthly-plan-slice.md diff --git a/backend/src/admin/hermes/corporate-policy.spec.ts b/backend/src/admin/hermes/corporate-policy.spec.ts index fa7bd23e..f3fbbd2a 100644 --- a/backend/src/admin/hermes/corporate-policy.spec.ts +++ b/backend/src/admin/hermes/corporate-policy.spec.ts @@ -1,5 +1,42 @@ -import { normalizeSearch, pagination, taskInput } from './corporate-policy'; +import { + normalizeSearch, + pagination, + taskInput, + monthlyPlanInput, +} from './corporate-policy'; describe('corporate contract policy', () => { + it.each([ + ['2027-02', 28], + ['2028-02', 29], + ['2028-04', 30], + ['2028-01', 31], + ])('enforces real calendar coverage for %s', (month, count) => { + const id = '11111111-1111-4111-8111-111111111111'; + const body = { + roadmapId: id, + month, + needs: [], + dailyArticles: Array.from({ length: Number(count) }, (_, i) => ({ + title: 'new article', + description: 'instruction', + actionType: 'BLOG_NEW', + department: 'CONTENT_SEO', + goalId: id, + sourceIds: [id], + dueCycle: `${month}-${String(i + 1).padStart(2, '0')}`, + })), + }; + expect(monthlyPlanInput(body).dailyArticles).toHaveLength(Number(count)); + expect(() => + monthlyPlanInput({ ...body, dailyArticles: body.dailyArticles.slice(1) }), + ).toThrow(); + expect(() => + monthlyPlanInput({ + ...body, + dailyArticles: [...body.dailyArticles, body.dailyArticles[0]], + }), + ).toThrow(); + }); it('normalizes Persian letters, digits and separators', () => { expect(normalizeSearch('كيك ۱۲۳ (ة)‌')).toBe('کیک 123 ه'); }); diff --git a/backend/src/admin/hermes/corporate-policy.ts b/backend/src/admin/hermes/corporate-policy.ts index 9d8e1cec..c9216c87 100644 --- a/backend/src/admin/hermes/corporate-policy.ts +++ b/backend/src/admin/hermes/corporate-policy.ts @@ -39,7 +39,7 @@ export function uuid(value: unknown): string { ) ) throw new BadRequestException('Invalid UUID'); - return id; + return id.toLowerCase(); } export function choice(value: unknown, values: string[]): string { if (typeof value !== 'string' || !values.includes(value)) @@ -124,12 +124,108 @@ export function taskInput(input: unknown) { 'BLOG_NEW', 'BLOG_UPDATE', 'CATALOG_ENRICH', + 'WIKI_ENRICH', 'RESEARCH', 'ENGINEERING', ]), dueCycle: b.dueCycle === undefined ? undefined : text(b.dueCycle, 40), }; } +export function planMonth(value: unknown): string { + const month = text(value, 7); + if (!/^(?:[2-9]\d{3})-(?:0[1-9]|1[0-2])$/.test(month)) + throw new BadRequestException('Invalid YYYY-MM month'); + return month; +} +export function monthlyPlanInput(input: unknown) { + const b = object(input, ['roadmapId', 'month', 'dailyArticles', 'needs']); + const month = planMonth(b.month); + const days = new Date( + Date.UTC(Number(month.slice(0, 4)), Number(month.slice(5)), 0), + ).getUTCDate(); + if ( + !Array.isArray(b.dailyArticles) || + b.dailyArticles.length !== days || + !Array.isArray(b.needs) || + b.needs.length > 200 + ) + throw new BadRequestException( + 'Full daily article coverage and bounded needs required', + ); + const mapping: Record = { + BLOG_NEW: 'CONTENT_SEO', + BLOG_UPDATE: 'CONTENT_SEO', + CATALOG_ENRICH: 'CATALOG_COMMERCE', + WIKI_ENRICH: 'WIKI_SCIENTIFIC', + ENGINEERING: 'TECH_DEVOPS', + }; + const parse = (raw: unknown, daily: boolean) => { + const t = object(raw, [ + 'title', + 'description', + 'department', + 'priority', + 'goalId', + 'actionType', + 'dueCycle', + 'sourceIds', + 'target', + 'reason', + ]); + const actionType = choice( + t.actionType, + daily + ? ['BLOG_NEW'] + : ['BLOG_UPDATE', 'CATALOG_ENRICH', 'WIKI_ENRICH', 'ENGINEERING'], + ); + const department = choice(t.department, [mapping[actionType]]); + const dueCycle = text(t.dueCycle, 10); + const date = new Date(dueCycle + 'T00:00:00Z'); + if ( + !/^\d{4}-\d{2}-\d{2}$/.test(dueCycle) || + !dueCycle.startsWith(month + '-') || + !Number.isFinite(date.getTime()) || + date.toISOString().slice(0, 10) !== dueCycle + ) + throw new BadRequestException('Invalid plan day'); + if ( + !Array.isArray(t.sourceIds) || + !t.sourceIds.length || + t.sourceIds.length > 30 + ) + throw new BadRequestException('Stored sources required'); + const sourceIds = t.sourceIds.map(uuid); + if (new Set(sourceIds).size !== sourceIds.length) + throw new BadRequestException('Duplicate source'); + if (daily && (t.target !== undefined || t.reason !== undefined)) + throw new BadRequestException('Daily new articles cannot be needs'); + return { + title: text(t.title, 300), + description: text(t.description), + department, + actionType, + dueCycle, + priority: choice(t.priority ?? 'MEDIUM', priorities), + goalId: uuid(t.goalId), + sourceIds, + ...(daily + ? {} + : { target: text(t.target, 2000), reason: text(t.reason) }), + }; + }; + const dailyArticles = b.dailyArticles.map((t) => parse(t, true)); + if (new Set(dailyArticles.map((t) => t.dueCycle)).size !== days) + throw new BadRequestException( + 'Exactly one new article per calendar day required', + ); + const needs = b.needs.map((t) => parse(t, false)); + if ( + new Set(needs.map((t) => canonical([t.actionType, t.target, t.dueCycle]))) + .size !== needs.length + ) + throw new BadRequestException('Duplicate need'); + return { roadmapId: uuid(b.roadmapId), month, dailyArticles, needs }; +} export function canonical(value: any): string { if (Array.isArray(value)) return '[' + value.map(canonical).join(',') + ']'; if (value && typeof value === 'object') @@ -158,7 +254,8 @@ export function publicData(value: any): any { export function httpsUrl(value: unknown): string { const raw = text(value, 2000); try { - if (!/^https:\/\/[a-z0-9]/i.test(raw) || /[\s\\]/.test(raw)) throw new Error(); + if (!/^https:\/\/[a-z0-9]/i.test(raw) || /[\s\\]/.test(raw)) + throw new Error(); const u = new URL(raw); const host = u.hostname.toLowerCase(); if ( diff --git a/backend/src/admin/hermes/corporate.controller.ts b/backend/src/admin/hermes/corporate.controller.ts index 701d27be..3a0c6ed6 100644 --- a/backend/src/admin/hermes/corporate.controller.ts +++ b/backend/src/admin/hermes/corporate.controller.ts @@ -108,6 +108,23 @@ export class CorporateController { ) { return this.service.roadmap(this.actor(req), this.key(key), body); } + @Post('monthly-plans') persistMonthlyPlan( + @Req() req: any, + @Headers('idempotency-key') key: string, + @Body() body: unknown, + ) { + return this.service.persistMonthlyPlan( + this.actor(req), + this.key(key), + body, + ); + } + @Get('monthly-plans/:roadmapId') monthlyPlan( + @Param('roadmapId') roadmapId: string, + @Query('month') month: string, + ) { + return this.service.monthlyPlan(roadmapId, month); + } @Get('reports') reports(@Query() q: Record) { return this.service.collection('reports', q); } diff --git a/backend/src/admin/hermes/corporate.integration.spec.ts b/backend/src/admin/hermes/corporate.integration.spec.ts index a1301fc1..0410b8a9 100644 --- a/backend/src/admin/hermes/corporate.integration.spec.ts +++ b/backend/src/admin/hermes/corporate.integration.spec.ts @@ -80,6 +80,284 @@ integration('corporate API / disposable PostgreSQL', () => { 'TRUNCATE corporate_operations, corporate_reports, corporate_effects, corporate_reviews, corporate_evidence, corporate_events, corporate_tasks, corporate_goals, corporate_roadmaps, corporate_sources, corporate_research CASCADE', ); }); + async function planFixture(month = '2996-02') { + const research = ( + await post('market-insights', { + title: 'monthly fixture', + category: 'TREND', + source: 'disposable receipt', + opportunity: 'test planning', + impact: 'LOW', + recommendedAction: 'plan', + cadence: 'MONTHLY', + provenance: { + method: 'fixture', + collector: 'jest', + context: 'disposable', + }, + sources: [ + { + url: 'https://pubmed.ncbi.nlm.nih.gov/', + title: 'fixture', + excerpt: 'test only', + retrievedAt: '2026-01-01T00:00:00Z', + sha256: 'a'.repeat(64), + }, + ], + }).expect(201) + ).body; + const roadmap = ( + await post('monthly-roadmap', { + researchId: research.id, + month, + cycleName: 'monthly fixture', + seasonalTheme: 'test', + strategicGoals: ['coverage'], + plannedArticlesCount: 29, + plannedRefreshesCount: 0, + plannedCatalogEnrichments: 0, + goals: [ + 'CONTENT_SEO', + 'CATALOG_COMMERCE', + 'WIKI_SCIENTIFIC', + 'TECH_DEVOPS', + ].map((department) => ({ + title: department, + department, + acceptanceCriteria: 'independent QA', + metric: 'coverage', + })), + }).expect(201) + ).body; + const task = ( + actionType: string, + department: string, + dueCycle: string, + ) => ({ + title: actionType + ' ' + dueCycle, + description: 'Evidence-backed instruction requiring QA', + actionType, + department, + dueCycle, + goalId: roadmap.goals.find((g: any) => g.department === department).id, + sourceIds: [research.sources[0].id], + ...(actionType === 'BLOG_NEW' + ? {} + : { + target: 'https://canina.ir/identified-gap', + reason: 'Documented coverage gap', + }), + }); + return { + research, + roadmap, + body: { + roadmapId: roadmap.id, + month, + dailyArticles: Array.from({ length: 29 }, (_, i) => + task( + 'BLOG_NEW', + 'CONTENT_SEO', + `${month}-${String(i + 1).padStart(2, '0')}`, + ), + ), + needs: [ + task('BLOG_UPDATE', 'CONTENT_SEO', month + '-01'), + task('CATALOG_ENRICH', 'CATALOG_COMMERCE', month + '-02'), + task('WIKI_ENRICH', 'WIKI_SCIENTIFIC', month + '-03'), + task('ENGINEERING', 'TECH_DEVOPS', month + '-04'), + ], + }, + }; + } + it('persists a complete leap-month daily-new plan, separate needs and evidence lineage with readback', async () => { + const { body, research, roadmap } = await planFixture(); + body.roadmapId = body.roadmapId.toUpperCase(); + for (const entry of [...body.dailyArticles, ...body.needs]) { + entry.goalId = entry.goalId.toUpperCase(); + entry.sourceIds = entry.sourceIds.map((id: string) => id.toUpperCase()); + } + const op = key(); + const created = ( + await post('monthly-plans', body, 'planner', op).expect(201) + ).body; + expect(created.tasks).toHaveLength(33); + const need = created.tasks.find((t: any) => t.actionType === 'WIKI_ENRICH'); + expect(need.logs[0].payload).toMatchObject({ + target: body.needs[2].target, + reason: body.needs[2].reason, + }); + expect( + created.tasks.filter((t: any) => t.actionType === 'BLOG_NEW'), + ).toHaveLength(29); + expect(created.tasks.every((t: any) => t.status === 'TODO')).toBe(true); + expect( + (await post('monthly-plans', body, 'planner', op).expect(201)).body, + ).toEqual(created); + const read = await request(app.getHttpServer()) + .get(`/admin/hermes/monthly-plans/${roadmap.id.toUpperCase()}?month=${body.month}`) + .set('x-api-key', 'executor') + .expect(200); + expect(read.body).toEqual(created); + const detail = await request(app.getHttpServer()) + .get('/admin/hermes/tasks/' + created.tasks[0].id) + .set('x-api-key', 'executor') + .expect(200); + expect(detail.body.logs[0].step).toBe('PLANNED'); + expect(detail.body.logs[0].payload).toMatchObject({ + researchId: research.id, + roadmapId: roadmap.id, + month: body.month, + dueCycle: body.month + '-01', + sourceIds: [research.sources[0].id], + }); + expect(await db.corporateOperation.count()).toBe(3); + expect((await post('claims', {}).expect(201)).body.task).toBeNull(); + }); + it('validates calendar, action separation, needs and stored lineage without partial writes', async () => { + const { body } = await planFixture(); + const mutations: Array<[number, (b: any) => void]> = [ + [400, (b) => b.dailyArticles.pop()], + [400, (b) => (b.dailyArticles[1].dueCycle = b.dailyArticles[0].dueCycle)], + [400, (b) => (b.dailyArticles[0].dueCycle = '2028-02-30')], + [400, (b) => (b.month = '2028-13')], + [400, (b) => (b.dailyArticles[0].actionType = 'BLOG_UPDATE')], + [400, (b) => (b.needs[0].actionType = 'BLOG_NEW')], + [400, (b) => (b.needs[0].reason = ' ')], + [400, (b) => delete b.needs[0].target], + [400, (b) => (b.needs[0].department = 'WIKI_SCIENTIFIC')], + [400, (b) => (b.dailyArticles[0].sourceIds = [])], + [409, (b) => (b.dailyArticles[0].sourceIds = [key()])], + [409, (b) => (b.dailyArticles[0].goalId = key())], + [409, (b) => (b.needs[0].goalId = b.needs[1].goalId)], + [409, (b) => (b.roadmapId = key())], + ]; + for (const [status, mutate] of mutations) { + const invalid = JSON.parse(JSON.stringify(body)); + mutate(invalid); + await post('monthly-plans', invalid).expect(status); + expect(await db.corporateTask.count()).toBe(0); + expect(await db.corporateEvent.count()).toBe(0); + expect(await db.corporateOperation.count()).toBe(2); + } + }); + it('serializes competing actors and keys on roadmap/month, rejects changed replay and keeps auth dormant', async () => { + const { body } = await planFixture(); + await request(app.getHttpServer()) + .post('/admin/hermes/monthly-plans') + .send(body) + .expect(401); + await post('monthly-plans', body, 'unscoped').expect(403); + const op = key(); + const otherOp = key(); + let release!: () => void; + let ready!: () => void; + const locked = new Promise((r) => (ready = r)); + const hold = new Promise((r) => (release = r)); + const scope = JSON.stringify(['monthly-plan', body.roadmapId, body.month]); + const blocker = db.$transaction(async (tx) => { + await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${scope}, 0))`; + ready(); + await hold; + }); + await locked; + const pending = [ + post('monthly-plans', body, 'planner', op).then((r) => r), + post('monthly-plans', body, 'other', otherOp).then((r) => r), + ]; + try { + let waiters = 0; + for (let i = 0; i < 100; i++) { + const rows = await db.$queryRaw`SELECT pid FROM pg_stat_activity + WHERE datname=current_database() AND wait_event_type='Lock' AND query LIKE '%pg_advisory_xact_lock%'`; + waiters = rows.length; + if (waiters >= 2) break; + await new Promise((r) => setTimeout(r, 10)); + } + expect(waiters).toBeGreaterThanOrEqual(2); + } finally { + release(); + await blocker; + } + const results = await Promise.all(pending); + expect(results.map((r) => r.status).sort()).toEqual([201, 409]); + expect(await db.corporateTask.count()).toBe(33); + expect(await db.corporateEvent.count({ where: { step: 'PLANNED' } })).toBe( + 33, + ); + const winner = results[0].status === 201 ? 'planner' : 'other'; + const winningOp = winner === 'planner' ? op : otherOp; + await post( + 'monthly-plans', + { ...body, needs: [] }, + winner, + winningOp, + ).expect(409); + expect( + (await post('monthly-plans', body, winner, winningOp).expect(201)).body, + ).toEqual(results[winner === 'planner' ? 0 : 1].body); + const runtime = await request(app.getHttpServer()) + .get('/admin/hermes/runtime') + .set('x-api-key', 'executor') + .expect(200); + expect(runtime.body).toEqual({ + mode: 'MANUAL_DORMANT', + schedulesEnabled: false, + externalExecutionEnabled: false, + }); + }); + it('rolls back a mid-plan database failure including tasks, events and idempotency receipt', async () => { + const { body } = await planFixture(); + // Disposable-only trigger fails after the first task/event have been written. + await db.$executeRawUnsafe( + `CREATE FUNCTION reject_plan_event() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.step='PLANNED' AND NEW.payload->>'dueCycle'='2996-02-02' THEN RAISE EXCEPTION 'injected plan failure'; END IF; RETURN NEW; END $$`, + ); + await db.$executeRawUnsafe( + 'CREATE TRIGGER reject_plan_event BEFORE INSERT ON corporate_events FOR EACH ROW EXECUTE FUNCTION reject_plan_event()', + ); + const op = key(); + try { + await post('monthly-plans', body, 'planner', op).expect(500); + expect(await db.corporateTask.count()).toBe(0); + expect(await db.corporateEvent.count()).toBe(0); + expect(await db.corporateOperation.count()).toBe(2); + } finally { + await db.$executeRawUnsafe( + 'DROP TRIGGER reject_plan_event ON corporate_events', + ); + await db.$executeRawUnsafe('DROP FUNCTION reject_plan_event()'); + } + await post('monthly-plans', body, 'planner', op).expect(201); + }); + it('gates only PLANNED future tasks while legacy future dueCycle remains claimable and UTC today is eligible', async () => { + const { body } = await planFixture(); + await post('monthly-plans', body).expect(201); + const legacy = ( + await post('tasks', { ...input, dueCycle: '2999-12-31' }).expect(201) + ).body; + expect((await post('claims', {}).expect(201)).body.task.id).toBe(legacy.id); + expect((await post('claims', {}).expect(201)).body.task).toBeNull(); + // Model the persisted event's due-day boundary in the disposable DB without changing system time. + const planned = await db.corporateTask.findFirstOrThrow({ + where: { actionType: 'BLOG_NEW' }, + }); + const day = new Date().toISOString().slice(0, 10); + await db.corporateTask.update({ + where: { id: planned.id }, + data: { dueCycle: day }, + }); + expect((await post('claims', {}).expect(201)).body.task).toBeNull(); // mismatch fails closed + const event = await db.corporateEvent.findFirstOrThrow({ + where: { taskId: planned.id, step: 'PLANNED' }, + }); + await db.corporateEvent.update({ + where: { id: event.id }, + data: { payload: { ...(event.payload as object), dueCycle: day } }, + }); + expect((await post('claims', {}).expect(201)).body.task.id).toBe( + planned.id, + ); + }); it('rejects children after a parent claim commits while child creation waits on its row lock', async () => { const parent = (await post('tasks', input).expect(201)).body; let release!: () => void, locked!: () => void; diff --git a/backend/src/admin/hermes/corporate.service.ts b/backend/src/admin/hermes/corporate.service.ts index 77e6de09..7c9a238f 100644 --- a/backend/src/admin/hermes/corporate.service.ts +++ b/backend/src/admin/hermes/corporate.service.ts @@ -9,6 +9,8 @@ import { createHash, randomUUID } from 'crypto'; import { PrismaService } from '../../prisma/prisma.service'; import { canonical, + monthlyPlanInput, + planMonth, publicData, choice, departments, @@ -188,6 +190,124 @@ export class CorporateService { return task; }); } + private plannedWhere( + roadmapId: string, + month: string, + ): Prisma.CorporateEventWhereInput { + return { + step: 'PLANNED', + AND: [ + { payload: { path: ['roadmapId'], equals: roadmapId } }, + { payload: { path: ['month'], equals: month } }, + ], + }; + } + private async readPlan(tx: Tx, roadmapId: string, month: string) { + const roadmap = await tx.corporateRoadmap.findUnique({ + where: { id: roadmapId }, + }); + const tasks = await tx.corporateTask.findMany({ + where: { logs: { some: this.plannedWhere(roadmapId, month) } }, + include: { + logs: { + where: this.plannedWhere(roadmapId, month), + orderBy: { id: 'asc' }, + }, + }, + orderBy: [{ dueCycle: 'asc' }, { actionType: 'asc' }, { id: 'asc' }], + }); + if (!roadmap || !tasks.length) + throw new NotFoundException('Monthly plan not found'); + return publicData({ + roadmapId, + month, + researchId: roadmap.researchId, + tasks, + }); + } + monthlyPlan(roadmapId: string, month: unknown) { + roadmapId = uuid(roadmapId); + const cycle = planMonth(month); + return this.db.$transaction((tx) => this.readPlan(tx, roadmapId, cycle), { + isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead, + }); + } + persistMonthlyPlan(actor: string, key: string, input: unknown) { + const b = monthlyPlanInput(input); + return this.operation(actor, 'monthly-plan', key, b, async (tx) => { + // Separate actor/key-independent fence: one complete plan per roadmap/month. + const scope = canonical(['monthly-plan', b.roadmapId, b.month]); + await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${scope}, 0))`; + if ( + await tx.corporateEvent.count({ + where: this.plannedWhere(b.roadmapId, b.month), + }) + ) + throw new ConflictException('Monthly plan already persisted'); + const roadmap = await tx.corporateRoadmap.findUnique({ + where: { id: b.roadmapId }, + include: { goals: true, research: { include: { sources: true } } }, + }); + if ( + !roadmap || + roadmap.month !== b.month || + !roadmap.research.sources.length + ) + throw new ConflictException( + 'Matching evidence-backed roadmap required', + ); + const entries = [...b.dailyArticles, ...b.needs]; + for (const entry of entries) { + if ( + !roadmap.goals.some( + (g) => g.id === entry.goalId && g.department === entry.department, + ) || + !entry.sourceIds.every((id) => + roadmap.research.sources.some((s) => s.id === id), + ) + ) + throw new ConflictException( + 'Goal/department and source lineage must match roadmap research', + ); + } + for (const entry of entries) { + const { sourceIds, target, reason, ...data } = entry; + const taskCode = 'TSK-' + randomUUID(); + const task = await tx.corporateTask.create({ + data: { + ...data, + priority: data.priority as CorporatePriority, + status: 'TODO', + taskCode, + normalizedCode: normalizeSearch(taskCode), + normalizedTitle: normalizeSearch(data.title), + createdBy: actor, + }, + }); + await this.event( + tx, + task.id, + actor, + 'PLANNED', + entry.description, + 'SYSTEM', + { + version: 1, + roadmapId: roadmap.id, + researchId: roadmap.researchId, + month: b.month, + goalId: entry.goalId, + department: entry.department, + actionType: entry.actionType, + dueCycle: entry.dueCycle, + sourceIds, + ...(target ? { target, reason } : {}), + }, + ); + } + return this.readPlan(tx, b.roadmapId, b.month); + }); + } claim(actor: string, key: string, input: unknown) { const b = object(input, ['department', 'leaseSeconds']); const department = @@ -205,6 +325,10 @@ export class CorporateService { { id: string }[] >`SELECT t.id FROM corporate_tasks t WHERE (t.status='TODO' OR (t.status='BLOCKED' AND EXISTS (SELECT 1 FROM corporate_tasks c WHERE c."parentId"=t.id)) OR (t.status='IN_PROGRESS' AND t."leasedUntil"<=clock_timestamp())) + AND NOT EXISTS (SELECT 1 FROM corporate_events e WHERE e."taskId"=t.id AND e.step='PLANNED' + AND (t."dueCycle" IS NULL OR t."dueCycle" !~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}$' + OR e.payload->>'dueCycle' IS DISTINCT FROM t."dueCycle" + OR t."dueCycle">to_char(clock_timestamp() AT TIME ZONE 'UTC','YYYY-MM-DD'))) AND (${department}::text IS NULL OR t.department=${department}) AND NOT EXISTS (SELECT 1 FROM corporate_tasks c WHERE c."parentId"=t.id AND c.status<>'DONE') ORDER BY t.priority ASC,t."updatedAt" ASC,t.id ASC FOR UPDATE OF t SKIP LOCKED LIMIT 1`; diff --git a/backend/src/seo-tracking/seo-tracking.service.spec.ts b/backend/src/seo-tracking/seo-tracking.service.spec.ts index 39743e50..c7a70056 100644 --- a/backend/src/seo-tracking/seo-tracking.service.spec.ts +++ b/backend/src/seo-tracking/seo-tracking.service.spec.ts @@ -72,6 +72,23 @@ run('SEO disposable PostgreSQL integration', () => { periodEnd: '2026-01-02T00:00:00Z', sourceMetadata: metadata, }; + it('replays exact non-round doubles and nested numeric JSON without accepting changed evidence', async () => { + const position = 3.1818181818181817; + const precise = { + ...snapshot, ingestionKey: 'precise-numeric-replay', gscPosition: position, + gscClicks: 35, gscImpressions: 11, + sourceMetadata: { ...metadata, + gsc: { ...metadata.gsc, status: 'available' }, + worker: { nested: [{ position, duration: 18.333333333333332 }] }, + }, + }; + const [a, b] = await Promise.all([service.addSnapshot(id, precise), service.addSnapshot(id, precise)]); + expect(a.id).toBe(b.id); + expect((await service.addSnapshot(id, precise)).id).toBe(a.id); + await expect(service.addSnapshot(id, { ...precise, gscPosition: position + Number.EPSILON * 2 })).rejects.toMatchObject({ status: 409 }); + await expect(service.addSnapshot(id, { ...precise, sourceMetadata: { ...precise.sourceMetadata, worker: { nested: [{ position: position + Number.EPSILON * 2, duration: 18.333333333333332 }] } } })).rejects.toMatchObject({ status: 409 }); + await db.contentPerformanceSnapshot.delete({ where: { id: a.id } }); + }); it('preserves null unavailable, idempotent concurrent retries, and conflicts', async () => { const [a, b] = await Promise.all([ service.addSnapshot(id, snapshot), diff --git a/backend/src/seo-tracking/seo-tracking.service.ts b/backend/src/seo-tracking/seo-tracking.service.ts index 5e0df928..4447f64e 100644 --- a/backend/src/seo-tracking/seo-tracking.service.ts +++ b/backend/src/seo-tracking/seo-tracking.service.ts @@ -239,21 +239,21 @@ export class SeoTrackingService { findingId_ingestionKey: { findingId, ingestionKey: dto.ingestionKey }, }, }); - const same = (row: any) => { - const canonical = (v: any): string => - JSON.stringify( - v && typeof v === 'object' && !(v instanceof Date) - ? Object.keys(v) - .sort() - .reduce( - (o, k) => ((o[k] = JSON.parse(canonical(v[k]))), o), - {} as Record, - ) - : v, - ); + const same = async (row: any) => { + // Compare numeric provenance and Float columns in PostgreSQL itself: + // Prisma's JSON protocol rounds some doubles on readback. A tolerance in + // JavaScript would also accept genuinely changed payloads. + const [stored] = await this.prisma.$queryRaw<{ matches: boolean }[]>` + SELECT source_metadata = ${JSON.stringify(dto.sourceMetadata)}::jsonb + AND gsc_position IS NOT DISTINCT FROM ${metrics.gscPosition === null ? null : String(metrics.gscPosition)}::double precision + AND ga4_avg_engagement_sec IS NOT DISTINCT FROM ${metrics.ga4AvgEngagementSec === null ? null : String(metrics.ga4AvgEngagementSec)}::double precision + AND ga4_bounce_rate IS NOT DISTINCT FROM ${metrics.ga4BounceRate === null ? null : String(metrics.ga4BounceRate)}::double precision + AND ga4_scroll_depth_rate IS NOT DISTINCT FROM ${metrics.ga4ScrollDepthRate === null ? null : String(metrics.ga4ScrollDepthRate)}::double precision AS matches + FROM content_performance_snapshots WHERE id = ${row.id}::uuid`; + if (!stored?.matches) return false; return Object.entries(data).every(([k, v]) => - k === 'sourceMetadata' - ? canonical(row[k]) === canonical(v) + ['sourceMetadata', 'gscPosition', 'ga4AvgEngagementSec', 'ga4BounceRate', 'ga4ScrollDepthRate'].includes(k) + ? true : k === 'periodStart' || k === 'periodEnd' ? new Date(row[k]).getTime() === (v as Date).getTime() : k === 'attributedSalesValue' @@ -264,13 +264,26 @@ export class SeoTrackingService { ); }; if (existing) { - if (!same(existing)) + if (!(await same(existing))) throw new ConflictException('Ingestion key reused with different data'); return existing; } await this.findOne(findingId); try { - return await this.prisma.contentPerformanceSnapshot.create({ data }); + return await this.prisma.$transaction(async (tx) => { + const row = await tx.contentPerformanceSnapshot.create({ data }); + // Preserve JSON/IEEE-754 input exactly despite Prisma's numeric JSON + // transport rounding. Text parameters are parsed by PostgreSQL, not + // reserialized as engine floats. This update is atomic with creation. + await tx.$executeRaw`UPDATE content_performance_snapshots SET + source_metadata = ${JSON.stringify(dto.sourceMetadata)}::jsonb, + gsc_position = ${metrics.gscPosition === null ? null : String(metrics.gscPosition)}::double precision, + ga4_avg_engagement_sec = ${metrics.ga4AvgEngagementSec === null ? null : String(metrics.ga4AvgEngagementSec)}::double precision, + ga4_bounce_rate = ${metrics.ga4BounceRate === null ? null : String(metrics.ga4BounceRate)}::double precision, + ga4_scroll_depth_rate = ${metrics.ga4ScrollDepthRate === null ? null : String(metrics.ga4ScrollDepthRate)}::double precision + WHERE id = ${row.id}::uuid`; + return row; + }); } catch (error) { if ((error as any).code === 'P2002') { const row = @@ -282,7 +295,7 @@ export class SeoTrackingService { }, }, }); - if (same(row)) return row; + if (await same(row)) return row; throw new ConflictException('Ingestion key reused with different data'); } throw error; diff --git a/frontend/application/app/blog/[slug]/blog-slug-page.test.tsx b/frontend/application/app/blog/[slug]/blog-slug-page.test.tsx index 501e649c..774417ba 100644 --- a/frontend/application/app/blog/[slug]/blog-slug-page.test.tsx +++ b/frontend/application/app/blog/[slug]/blog-slug-page.test.tsx @@ -113,9 +113,9 @@ describe('BlogPostPage FAQPage Schema injection (SEO-P1-07)', () => { const jsx=await BlogPostPage({params:Promise.resolve({slug:'fresh'})}); const script:any=React.Children.toArray(jsx.props.children)[0]; const json=JSON.parse(script.props.dangerouslySetInnerHTML.__html); expect(json.dateModified).toBe('2026-01-01T12:00:00.000Z'); expect(json.author['@type']).toBe('Organization'); expect(json.author.name).toBe('کنینا'); }); - it('omits dateModified when only technical updatedAt exists', async () => { + it('uses publication as dateModified when only technical updatedAt exists', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ok:true,json:async()=>({slug:'technical',title:'Technical',content:'

x

',publishedAt:'2026-01-01T01:00:00Z',updatedAt:'2026-01-01T12:00:00Z',contentUpdatedAt:null})})); - const jsx=await BlogPostPage({params:Promise.resolve({slug:'technical'})}); const script:any=React.Children.toArray(jsx.props.children)[0]; const json=JSON.parse(script.props.dangerouslySetInnerHTML.__html); expect(json.dateModified).toBeUndefined(); + const jsx=await BlogPostPage({params:Promise.resolve({slug:'technical'})}); const script:any=React.Children.toArray(jsx.props.children)[0]; const json=JSON.parse(script.props.dangerouslySetInnerHTML.__html); expect(json.dateModified).toBe('2026-01-01T01:00:00.000Z'); }); it('uses the stable Organization fallback visibly and in metadata', async () => { diff --git a/frontend/application/app/blog/[slug]/page.tsx b/frontend/application/app/blog/[slug]/page.tsx index 8c5fe16e..f6ea3c6c 100644 --- a/frontend/application/app/blog/[slug]/page.tsx +++ b/frontend/application/app/blog/[slug]/page.tsx @@ -1,4 +1,4 @@ -import { validContentUpdatedAt } from "../../../lib/blogDates"; +import { persianDate, validContentUpdatedAt } from "../../../lib/blogDates"; import { resolveBlogAuthorIdentity } from "../../../lib/blogAuthor"; import React from "react"; import { notFound } from 'next/navigation'; @@ -23,7 +23,7 @@ function safeLocalDate(val: any): string { if (!val) return ''; try { const d = new Date(val); - return isNaN(d.getTime()) ? '' : d.toLocaleDateString('fa-IR'); + return isNaN(d.getTime()) ? '' : persianDate(d.toISOString()); } catch { return ''; } @@ -95,7 +95,8 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str const resolvedAuthor = resolveBlogAuthorIdentity(blog); const publishedTime = safeIso(blog.publishedAt) || safeIso(blog.createdAt); - const modifiedTime = safeIso(validContentUpdatedAt(blog)); + // An unedited article was last modified at publication; technical writes are not editorial updates. + const modifiedTime = safeIso(validContentUpdatedAt(blog)) || publishedTime; const keywordsList = blog.focusKeywords ? blog.focusKeywords.split(',').map((k: string) => k.trim()) @@ -177,8 +178,8 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug: ? blog.canonicalUrl.replace(/\/+$/, '') : `${siteUrl}/blog/${slug}`; - const publishedIso = safeIso(blog.publishedAt) || safeIso(blog.createdAt) || new Date().toISOString(); - const modifiedIso = safeIso(validContentUpdatedAt(blog)); + const publishedIso = safeIso(blog.publishedAt) || safeIso(blog.createdAt); + const modifiedIso = safeIso(validContentUpdatedAt(blog)) || publishedIso; const sanitizedContent = sanitizeBlogHtml(blog.content); const schemaType = blog.schemaType || 'BlogPosting'; @@ -204,7 +205,7 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug: headline: blog.title, description: blog.excerpt || blog.metaDescription || blog.title, ...(blog.imageUrl?.trim() ? { image: [new URL(blog.imageUrl.trim(), `${siteUrl}/`).href] } : {}), - datePublished: publishedIso, + ...(publishedIso ? { datePublished: publishedIso } : {}), ...(modifiedIso ? { dateModified: modifiedIso } : {}), author: authorSchema, publisher: { diff --git a/frontend/application/app/blog/[slug]/timestamp-metadata.test.tsx b/frontend/application/app/blog/[slug]/timestamp-metadata.test.tsx new file mode 100644 index 00000000..7f92629d --- /dev/null +++ b/frontend/application/app/blog/[slug]/timestamp-metadata.test.tsx @@ -0,0 +1,73 @@ +import React from 'react'; +import { afterEach, expect, it, vi } from 'vitest'; +import { renderToStaticMarkup } from 'react-dom/server'; +import BlogPostPage, { generateMetadata } from './page'; +import { validContentUpdatedAt } from '../../../lib/blogDates'; + +vi.mock('../../../lib/seo', () => ({ + getSeoConfig: async () => ({ brandNameFa: 'کنینا', canonicalBaseUrl: 'https://canina.ir' }), + formatPageTitle: (title: string) => title, +})); +vi.mock('../../../components/BlogPostClient', () => ({ + default: ({ blog, publishedDate }: { blog: any; publishedDate: string }) =>
+ تاریخ انتشار: {publishedDate} + {validContentUpdatedAt(blog) && آخرین به‌روزرسانی} +
, +})); +afterEach(() => { vi.unstubAllGlobals(); vi.unstubAllEnvs(); }); +const published = '2026-10-29T07:11:40.925Z'; + +async function readDates(fields: Record) { + vi.stubEnv('NEXT_PUBLIC_APP_ENV', 'staging'); + vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({ + title: 'Timestamp contract', content: '

Article

', ...fields, + }) })); + const params = Promise.resolve({ slug: 'timestamp-contract' }); + const metadata = await generateMetadata({ params }); + const jsx = await BlogPostPage({ params }); + const script: any = React.Children.toArray(jsx.props.children)[0]; + return { og: metadata.openGraph as any, robots: metadata.robots, + article: JSON.parse(script.props.dangerouslySetInnerHTML.__html), html: renderToStaticMarkup(jsx) }; +} + +it.each([null, undefined, 'invalid', published, '2026-10-28T00:00:00Z'])( + 'uses real publication for unedited/invalid/chronologically inapplicable content date %s', async (contentUpdatedAt) => { + const { og, article, html, robots } = await readDates({ publishedAt: published, + contentUpdatedAt, updatedAt: '2026-10-30T09:00:00Z', imageUrl: '/attached.webp' }); + expect(og.publishedTime).toBe(published); + expect(og.modifiedTime).toBe(published); + expect(article.datePublished).toBe(published); + expect(article.dateModified).toBe(published); + expect(html).not.toContain('آخرین به‌روزرسانی'); + expect(robots).toMatchObject({ index: false }); + }); +it('uses actual substantive update consistently without changing publication', async () => { + const modified = '2026-10-29T12:00:00.000Z'; + const { og, article, html } = await readDates({ publishedAt: published, contentUpdatedAt: modified }); + expect(og.modifiedTime).toBe(modified); + expect(article.dateModified).toBe(modified); + expect(article.datePublished).toBe(published); + expect(html).toContain('آخرین به‌روزرسانی'); +}); +it.each([null, 'invalid'])('uses the valid existing createdAt fallback when publishedAt is %s', async (publishedAt) => { + const { og, article } = await readDates({ publishedAt, createdAt: published }); + expect(og.publishedTime).toBe(published); + expect(og.modifiedTime).toBe(published); + expect(article.datePublished).toBe(published); + expect(article.dateModified).toBe(published); +}); +it.each([{}, { publishedAt: 'invalid', createdAt: 'invalid', contentUpdatedAt: '2026-10-30T00:00:00Z' }])( + 'does not invent rendering-time publication or modification when unknown: %j', async (fields) => { + const { og, article } = await readDates(fields); + expect(og.publishedTime).toBeUndefined(); + expect(og.modifiedTime).toBeUndefined(); + expect(article).not.toHaveProperty('datePublished'); + expect(article).not.toHaveProperty('dateModified'); + }); +it('formats visible publication using Persian calendar and Tehran rather than server timezone', async () => { + const { html } = await readDates({ publishedAt: '2026-10-29T21:00:00Z' }); + const expected = new Intl.DateTimeFormat('fa-IR-u-ca-persian', { + year: 'numeric', month: 'numeric', day: 'numeric', timeZone: 'Asia/Tehran', + }).format(new Date('2026-10-29T21:00:00Z')); + expect(html).toContain(`تاریخ انتشار: ${expected}`); +}); diff --git a/frontend/application/app/blog/[slug]/timestamp-visible.test.tsx b/frontend/application/app/blog/[slug]/timestamp-visible.test.tsx new file mode 100644 index 00000000..438e8294 --- /dev/null +++ b/frontend/application/app/blog/[slug]/timestamp-visible.test.tsx @@ -0,0 +1,17 @@ +import React from 'react'; +import { renderToStaticMarkup } from 'react-dom/server'; +import { expect, it } from 'vitest'; +import BlogPostClient from '../../../components/BlogPostClient'; + +it.each([null, undefined, 'invalid', '2026-10-29T07:11:40.925Z', '2026-10-28T00:00:00Z'])( + 'actual client keeps publication but no visible update for %s despite later technical writes', (contentUpdatedAt) => { + const html = renderToStaticMarkup(); + expect(html).toContain('تاریخ انتشار'); + expect(html).toContain('۱۴۰۵/۸/۷'); + expect(html).not.toContain('آخرین به‌روزرسانی'); + }); diff --git a/scripts/corporate_runtime.py b/scripts/corporate_runtime.py index 6a5d9593..7b22ab94 100644 --- a/scripts/corporate_runtime.py +++ b/scripts/corporate_runtime.py @@ -202,6 +202,13 @@ def ingest(client, store, manifest, hosts, key): return {'research': result, 'requestDigest': request_digest} +def monthly_plan(client, store, body, key): + # Backend owns calendar and stored-lineage validation. Preserve the exact + # request before transmission; an ambiguous POST is never retried blindly. + digest = client.checkpoint(store, key, 'monthly-plans', body) + return {'plan': client.call('monthly-plans', body, key), 'checkpointDigest': digest} + + def fanout(client, roadmap, key): tasks = [] for goal in roadmap['goals']: @@ -261,6 +268,8 @@ def main(): i = sub.add_parser('replay-ingest'); i.add_argument('request_digest') i = sub.add_parser('replay-evidence'); i.add_argument('checkpoint_digest') i = sub.add_parser('roadmap'); i.add_argument('manifest') + i = sub.add_parser('plan-month'); i.add_argument('manifest') + i = sub.add_parser('read-plan'); i.add_argument('roadmap_id'); i.add_argument('month') i = sub.add_parser('fanout'); i.add_argument('roadmap_id') i = sub.add_parser('execute'); i.add_argument('--department', required=True) i = sub.add_parser('qa'); i.add_argument('task_id'); i.add_argument('evidence_id') @@ -268,7 +277,7 @@ def main(): i = sub.add_parser('report'); i.add_argument('manifest') sub.add_parser('status') a = p.parse_args() - if a.command != 'status' and not a.key: + if a.command not in ('status', 'read-plan') and not a.key: p.error('--key required for mutations') c = Client(a.api, 'CORPORATE_QA_API_KEY' if a.command == 'qa' else 'CORPORATE_API_KEY', a.allow_stage_https) s = Store(a.store) @@ -280,6 +289,11 @@ def main(): body = load() if body.get('isActive') is not False: raise ValueError('Manual roadmap must explicitly be inactive') result = c.call('monthly-roadmap', body, a.key) + elif a.command == 'plan-month': result = monthly_plan(c, s, load(), a.key) + elif a.command == 'read-plan': + if not re.fullmatch(r'[a-f0-9-]{36}', a.roadmap_id) or not re.fullmatch(r'[2-9][0-9]{3}-(0[1-9]|1[0-2])', a.month): + raise ValueError('Invalid roadmap/month') + result = c.call('monthly-plans/' + a.roadmap_id + '?month=' + a.month) elif a.command == 'fanout': page = 1 while True: diff --git a/scripts/corporate_runtime_test.py b/scripts/corporate_runtime_test.py index 3138834f..163afbb5 100644 --- a/scripts/corporate_runtime_test.py +++ b/scripts/corporate_runtime_test.py @@ -40,6 +40,23 @@ class Safety(unittest.TestCase): digest = client.checkpoint(store, 'stable-key', path, {'result': 'original timestamp'}) self.assertEqual(client.replay(store, digest), {'id': 'persisted'}) self.assertEqual(calls, [(path, {'result':'original timestamp'}, 'stable-key')]) + def test_monthly_plan_checkpoints_exact_request_before_post(self): + calls = [] + class Client: + def checkpoint(self, store, key, path, body): + calls.append(('checkpoint', key, path, body)) + return 'digest' + def call(self, path, body, key): + calls.append(('post', key, path, body)) + return {'tasks': [{'id': 'persisted'}]} + body = {'roadmapId': 'stored-roadmap', 'month': '2026-10', + 'dailyArticles': [{'dueCycle': '2026-10-01', 'sourceIds': ['stored-source']}], 'needs': []} + result = r.monthly_plan(Client(), object(), body, 'stable-plan-key') + self.assertEqual([c[0] for c in calls], ['checkpoint', 'post']) + self.assertEqual(calls[0][1:], calls[1][1:]) + self.assertEqual(calls[1][1:], ('stable-plan-key', 'monthly-plans', body)) + self.assertEqual(result, {'plan': {'tasks': [{'id': 'persisted'}]}, 'checkpointDigest': 'digest'}) + def test_api_target(self): with self.assertRaises(ValueError): r.api_target('http://example.com/api/admin/hermes',False) with self.assertRaises(ValueError): r.api_target('https://example.com/api/admin/hermes',False) diff --git a/specs/blog-timestamp-metadata/evidence.md b/specs/blog-timestamp-metadata/evidence.md new file mode 100644 index 00000000..c37adaed --- /dev/null +++ b/specs/blog-timestamp-metadata/evidence.md @@ -0,0 +1,12 @@ +# Local verification receipt +Base 18094f91a6babdd8e08e7b294e18557de9778d59; shared dirty develop. Scope only page.tsx, blog-slug-page.test.tsx, new timestamp-metadata.test.tsx, timestamp-visible.test.tsx, this feature directory. Parent backend/SEO/corporate changes untouched. + +RED: 11 tests, 10 actual behavior failures (missing modified timestamps, rendering-clock fabrication, server-timezone display) before page edits. Focused GREEN 25/25. Final full frontend 102 files / 540 tests passed. Typecheck exit0. Dedicated Next build exit0; first combined tool invocation hit transport timeout during build, retry completed. Build warns multiple lockfiles and unavailable local backend (127.0.0.1:4001) during prerender; this is not runtime API acceptance. + +Full ESLint fails on existing lib/slug.ts:30 prefer-const; pristine git archive of base18094f9 with same dependencies reproduces sole error. Baseline 511 warnings; current initial run 514 warnings; owned-file lint exit0. No unrelated lint fix or gate waiver. Final Stage release remains conditional on parent's existing quality-gate policy. + +Independent read-only review deleg_3a59d15b task0 agrees semantics and distinguishes daily report dual date convention from Persian/Tehran article date. Existing client visible predicate unchanged, actual client SSR negative tests cover null/missing/invalid/equal/earlier content timestamps despite technical writes. Substantive update test remains existing client suite coverage. + +Fresh production GET at 2026-10-30T12:20:42.508566+00:00 (Telegram UA): HTTP200, publication 2026-10-29T07:11:40.925Z, dateModified/OG modified still absent, image present. Raw HTML/headers retained. Earlier real-browser evidence in recovery-fresh-timestamp-evidence.json inspected. No claim this local fix is deployed; no record resave, commit/push/deploy/data/cron/global configuration. + +Machine-readable source/log manifest: /opt/data/content-maintenance/recovery-evidence-20261030/timestamp-source-manifest.json. Parent must review exact source hashes, commit authorized slice, deploy Stage via CI, validate actual HTML tags/JSON-LD/visible labels/noindex/canonical/image and unchanged record dates, then seek explicit production rollout authorization. Existing publisher gates are not waived. diff --git a/specs/blog-timestamp-metadata/plan.md b/specs/blog-timestamp-metadata/plan.md new file mode 100644 index 00000000..db1b1248 --- /dev/null +++ b/specs/blog-timestamp-metadata/plan.md @@ -0,0 +1,4 @@ +# Plan +Graph navigation: graphify-out/graph.json sha256 6a73473cee9e207543fdeeb668bea544f766200a1b16b8a3a9ce18d4e42e51af, built_at_commit e7ded849f6b1e3bdab2a20d89b3ec7dd0df79cab (stale, navigation only). Read-only traversal confirms page -> getBlog/getSeoConfig/safeIso and imports BlogPostClient; direct current source/tests verify page -> validContentUpdatedAt -> publicationDate and client visible predicate. No graph writes or global installs. No API/schema changes. +Use existing ISO normalization and substantive date predicate independently for OG and JSON-LD with publication fallback; remove runtime-date invention. Use existing persianDate formatter safely for publication display to align Tehran timezone. Tests cover null/invalid/equal/earlier content dates, actual later edit, system/image-only change, invalid or absent publication, createdAt compatibility and Tehran date boundary. Update previous omission assertion to new explicitly requested contract. Keep shared formatter/client/backend untouched. +Inspect current deployed public HTML read-only, retain raw responses and parsed timestamp evidence externally. Existing project .specify constitution inspected; no scaffold overwrite. No unresolved business question for this user-specified narrow contract. diff --git a/specs/blog-timestamp-metadata/spec.md b/specs/blog-timestamp-metadata/spec.md new file mode 100644 index 00000000..515f0b5f --- /dev/null +++ b/specs/blog-timestamp-metadata/spec.md @@ -0,0 +1,12 @@ +# Truthful article timestamp metadata +## Scope and decisions +Bound to base 18094f91a6babdd8e08e7b294e18557de9778d59 (dirty shared develop; unrelated backend/SEO/corporate files parent-owned). Only blog/[slug] page/tests and these specs are owned here. No record, cron, configuration, commit, push or deployment changes. +The Oct29 household-cleaner article has real publishedAt 2026-10-29T07:11:40.925Z and null contentUpdatedAt. Image attachment is not editorial freshness. +## Acceptance +- JSON-LD dateModified and OG modifiedTime equal valid substantive contentUpdatedAt, else the real publication timestamp. Generic updatedAt never creates freshness. +- Publication fallback preserves existing valid createdAt compatibility, consistently across metadata and JSON-LD. No render-clock fallback when both are invalid/missing; unknown dates are omitted. +- Visible update remains substantive-only through unchanged validContentUpdatedAt; publication display remains Persian calendar in Asia/Tehran (not daily report's dual timezone header). +- Retain Stage noindex, canonical, author, image and content behavior. +- RED behavior tests then GREEN full frontend unit suite, typecheck, lint and Next build. Local proof is not Stage acceptance or production authorization. +## Policy +SEO governance SKILL.md:19-20 and daily-content-publisher:139,145 require truthful complete timestamps without artificial freshness. Daily report dual timestamps apply at line150, not article display. Independent read-only policy review deleg_3a59d15b concurs with publication fallback and flags render-clock fabrication. diff --git a/specs/blog-timestamp-metadata/tasks.md b/specs/blog-timestamp-metadata/tasks.md new file mode 100644 index 00000000..43cc3a76 --- /dev/null +++ b/specs/blog-timestamp-metadata/tasks.md @@ -0,0 +1,7 @@ +# Tasks +- [x] Inspect evidence, base/dirty status, graph navigation and direct source. +- [x] Independent source-policy/date-convention review. +- [x] Write failing timestamp regression tests and record RED (10 failures / 11 tests). +- [x] Minimal page-only implementation and GREEN focused tests (25 tests). +- [x] Execute full frontend tests (540/540), typecheck (exit0), lint (baseline sole error reproduced, owned lint exit0), build (exit0); logs/source manifest in /opt/data/content-maintenance/recovery-evidence-20261030/. Full lint gate remains failing, not waived. +- [ ] Parent review and authorized Stage rollout (not this worker); production remains unauthorized. diff --git a/specs/corporate-execution-observability/monthly-plan-slice.md b/specs/corporate-execution-observability/monthly-plan-slice.md new file mode 100644 index 00000000..0a6fd67c --- /dev/null +++ b/specs/corporate-execution-observability/monthly-plan-slice.md @@ -0,0 +1,60 @@ +# Persisted dated monthly plan — local implementation receipt + +Base: `18094f91a6babdd8e08e7b294e18557de9778d59` (official develop, verified 2026-10-30). + +## Bounded acceptance audit + +- Existing `CorporateService.research()` and `roadmap()` persist research sources, roadmap and goals, but the roadmap contains aggregate counts rather than a dated execution calendar. +- Existing `scripts/corporate_runtime.py:fanout()` creates only RESEARCH inventory tasks. Existing department `plan_day()` reports unresolved audit findings in `dailyNew`; this is not a daily article calendar. +- Existing task goal relationship and event JSON payload support a no-schema slice. No schema design/apply is needed for this implementation. + +## Implemented contract + +`POST /api/admin/hermes/monthly-plans` uses existing controller authentication and required Idempotency-Key. Body: `roadmapId`, `month` (YYYY-MM), `dailyArticles` and `needs`. + +Every calendar day has exactly one BLOG_NEW entry. Entries carry title, description, department, priority, goalId, actionType, dueCycle (YYYY-MM-DD) and sourceIds. Source IDs must exist in the stored roadmap research; goal and department must belong to that roadmap. Missing, duplicate or impossible dates fail closed. Needs use BLOG_UPDATE, CATALOG_ENRICH, WIKI_ENRICH or ENGINEERING and additionally require target and reason. Needs never satisfy daily NEW coverage and empty needs are allowed rather than fabricating quotas. + +The backend transaction creates real task rows and PLANNED events containing research/roadmap/goal/source/date lineage. A roadmap/month advisory lock prevents duplicate plans across keys/actors. Existing operation replay returns the original response for exact same-key retries; conflicting payloads fail. Injection coverage proves partial writes roll back. + +`GET /api/admin/hermes/monthly-plans/:roadmapId?month=YYYY-MM` reads persisted tasks with their PLANNED lineage. Claim eligibility gates only planned tasks by matching dueCycle and UTC day; future planned work is not immediately claimable. Legacy undated directives retain existing behavior. + +Manual CLI `plan-month manifest.json` checkpoints the exact request before POST; `read-plan roadmap-id YYYY-MM` performs authenticated readback. No schedule, worker, publisher or claim is invoked by either command. Preserve stable mutation keys and read back after ambiguous transmission before any explicit retry. + +## Real local verification + +Evidence directory: `/opt/data/content-maintenance/corporate-plan-evidence-20261030/`. + +- Backend RED: `backend-red.log`; readback RED: `backend-readback-red.log`. +- Final focused PostgreSQL integration/policy GREEN: 2 suites, 24 tests, `backend-focused-final2.log`. Expected injected database failure is logged by the rollback test; suite passes. +- Backend TypeScript build: exit 0, `backend-build-final2.log`. +- Full backend attempt: 104 suites passed, 1 failed, 2 skipped; 942 tests passed, 1 failed, 3 skipped. `backend-full-final.log`. Blocker is SEO worker HTTP ingestion replay returning 409 (reproduced twice); not claimed fully green. +- Manual CLI checkpoint regression RED: missing monthly_plan AttributeError, `runtime-red.log`; all corporate Python suites GREEN: 19 tests, `runtime-green.log`. +- `git diff --check`: clean. + +## Safety and next dependencies + +No commit, push, deployment, live business-data mutation, migration, main, cron, Hermes config or admin approval module change. MANUAL_DORMANT remains unchanged. This is locally implemented planning, not enterprise DONE or live acceptance. + +Next: parent-owned single develop push and Stage CI; authenticated Stage plan creation/readback with real approved research; then implement action-specific execution/evidence/independent QA for planned tasks, public outcome readback, and explicit scheduling authorization only after those gates. Legacy department report's QA_REVIEW/TEST mismatch remains separate followup; it is not a monthly article planner. + +## Integrated review and regression repair (2026-10-30) + +Acceptance: preserve exact replay and reject changed numeric evidence, without tolerances, skipped gates, DDL or live writes. Preserve plan transactions, full calendar, daily BLOG_NEW versus separate needs, source lineage, and actor-independent roadmap/month uniqueness. + +Independent source review confirmed transaction/lineage/calendar/guard design. The graph SHA256 is `6a73473cee9e207543fdeeb668bea544f766200a1b16b8a3a9ce18d4e42e51af`; its revision is unbound and it lacks planner nodes, so it remains navigation only. UUID case normalization defect was reproduced RED (`review-uppercase-red.log`) and fixed: accepted uppercase roadmap/goal/source IDs now normalize before lineage, hashing, lock scope and readback. The API integration test sends uppercase IDs and GETs uppercase roadmap ID. Future claim fixtures moved to leap month 2996-02, preserving trigger rollback checks. + +Baseline full command on clean detached `18094f91` with the identical resolved node_modules and unchanged package-lock reproduced the SEO HTTP 409: 104 pass / 1 fail / 2 skipped suites, 933 pass / 1 fail / 3 skipped tests (`review-baseline-full.log`). The same HTTP test fails independently (`review-baseline-worker.log`). This is a pre-existing production numeric replay defect, not a monthly-plan regression. Diagnostic RED logs show 3.1818181818181817 returning as 3.181818181818182 and 18.333333333333332 as 18.33333333333333; nested JSON changes too. Prisma numeric transport loses exact double input. The repair uses text-bound PostgreSQL casts for Float and JSON writes atomically with create, and native PostgreSQL equality for replay. It does not use epsilon comparison. Concurrent real-PG numeric replay and single-ULP numeric/provenance changes are covered; changed evidence still returns 409. Previously rounded rows are not rewritten or silently accepted. + +Final local results (all logs in the evidence directory above): +- `review-full-final.log`: 105 suites passed, 2 existing opt-in suites skipped; 944 tests passed, 3 existing opt-in tests skipped. Fresh disposable SEO/publication/corporate PostgreSQL clusters, stopped by the runner. No new skips. +- `review-focused-final.log`: monthly policy/API and SEO real worker HTTP/service regressions, exit 0. +- `review-build-final.log`: `npm run build`, exit 0. +- `review-runtime-all-final.log`: all corporate Python unittest discovery, exit 0. +- Expected injected database ERROR during rollback coverage is not a failing suite. + +Review limitations: manual checkpoint submission has no dedicated monthly-plan replay subcommand (use stable original request/key and readback); action-specific consumers remain deferred/dormant. No Stage behavior or production identity is established by local JWT/PG tests. Parent must freeze the integrated commit, use official Stage CI, verify MANUAL_DORMANT and cron disconnection, and read back approved dated plan/actionType/lineage before calling Stage accepted. No commit/push/deploy performed by this worker. + +## Repository recovery + +Durable valid clone: `/opt/data/content-maintenance/corporate-durable-20261030`. +Broken original `/opt/data/content-maintenance/engine/worktree-concurrency-tdd` was not reset, cleaned or deleted. The missing scratch Git metadata was not recreated or rewritten. 332 source/spec/graph evidence files were copied with SHA256 manifest at `/opt/data/content-maintenance/recovery-evidence-20261030/manifest.json`; untracked owned specs/.specify were preserved without replacing tracked current develop files. Original graph and stamps remain external evidence. The recovered graph lacks corporate service/planner nodes, so source/tests, not graph inference, ground this slice.