diff --git a/.env.example b/.env.example index 53ab9cb..a2d587e 100644 --- a/.env.example +++ b/.env.example @@ -8,13 +8,13 @@ NEXT_PUBLIC_SUPABASE_ANON_KEY= SUPABASE_SERVICE_ROLE_KEY= # Shared secret for GitHub Actions API calls. CRON_SECRET= -# Reserved for the later AI phase; unused by the foundation. +# Gemini API key used by the story writer and magazine layout builder. GEMINI_API_KEY= -# Reserved model name for the later writing phase. +# Optional model override for story writing and editor notes. WRITER_MODEL= -# Reserved model name for the later design phase. +# Optional model override for magazine story placement. DESIGNER_MODEL= -# Reserved for later workflow dispatch; unused by the foundation. +# Reserved for a future compile workflow; not used by the current app. GITHUB_DISPATCH_TOKEN= # App URL used by GitHub Actions; also add as the APP_URL repository secret. APP_URL= diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dc57737..9053827 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -33,6 +33,10 @@ jobs: cache: npm - name: Install dependencies run: npm ci + - name: Ingest tests + run: npm run test:ingest + - name: Magazine rendering tests + run: npm run test:magazine - name: Lint run: npm run lint - name: Typecheck diff --git a/.github/workflows/ingest.yml b/.github/workflows/ingest.yml index add5916..b3a136e 100644 --- a/.github/workflows/ingest.yml +++ b/.github/workflows/ingest.yml @@ -15,7 +15,7 @@ jobs: call-ingest: runs-on: ubuntu-latest steps: - - name: Call the ingest stub + - name: Call the authenticated ingest endpoint env: APP_URL: ${{ secrets.APP_URL }} CRON_SECRET: ${{ secrets.CRON_SECRET }} @@ -28,11 +28,13 @@ jobs: echo "::error title=Configuration::CRON_SECRET is not set." exit 1 fi + APP_URL="${APP_URL%/}" http_code=$(curl --silent --show-error \ --output "$RUNNER_TEMP/ingest-response.json" \ --write-out "%{http_code}" \ --request POST \ --header "Authorization: Bearer $CRON_SECRET" \ + --max-time 75 \ "$APP_URL/api/cron/ingest") cat "$RUNNER_TEMP/ingest-response.json" if [[ ! "$http_code" =~ ^2[0-9][0-9]$ ]]; then diff --git a/.github/workflows/latex-check.yml b/.github/workflows/latex-check.yml index 7cae823..9bd0dd5 100644 --- a/.github/workflows/latex-check.yml +++ b/.github/workflows/latex-check.yml @@ -24,6 +24,12 @@ jobs: steps: - name: Check out repository uses: actions/checkout@v4 + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version-file: .nvmrc + - name: Generate magazine renderer smoke file + run: WRITE_LATEX_SMOKE=1 node --experimental-strip-types --test tests/magazine-render.test.mjs - name: Compile the May reference uses: xu-cheng/latex-action@v4 with: @@ -31,6 +37,13 @@ jobs: root_file: latex/reference/may-2026.tex work_in_root_file_dir: true args: -pdf -file-line-error -halt-on-error -interaction=nonstopmode + - name: Compile the generated magazine template with special characters + uses: xu-cheng/latex-action@v4 + with: + texlive_version: 2026 + root_file: latex/generated-render-smoke.tex + work_in_root_file_dir: true + args: -pdf -file-line-error -halt-on-error -interaction=nonstopmode - name: Upload PDF artifact uses: actions/upload-artifact@v4 with: diff --git a/.gitignore b/.gitignore index 7ae6edd..23e79fc 100644 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,4 @@ pnpm-debug.log* /coverage/ *.tsbuildinfo next-env.d.ts +/latex/generated-render-smoke.tex diff --git a/README.md b/README.md index f6741d4..98c6afd 100644 --- a/README.md +++ b/README.md @@ -2,61 +2,66 @@ The newsroom behind **Machine Intelligence**, the magazine of the Department of Artificial Intelligence at NFC IET Multan. -The foundation is in place: a public magazine site, a Supabase-backed editor allowlist, a mobile-friendly editor desk, secure API stubs, and GitHub Actions for CI, scheduled ingest calls, and LaTeX checks. The first issue and editor story cards still use clearly labeled sample data. +The foundation, RSS ingestion, AI story review, and first magazine-draft builder are in place. Approved stories can be arranged into a configurable issue, edited by the newsroom, and rendered as a private LaTeX source file for review. ## Foundation status - **Public site:** home, issue archive and issue detail, About, How it is made, Privacy, sitemap, robots, Open Graph image, and a custom not-found page. -- **Editor desk:** Supabase email-and-password sign-in for accounts on the editor list; Draft, Stories, Quarantine, Sources, Images, Issues, and admin-only Editors pages. -- **Supabase:** editors, editions, and runs tables; row-level security; public issues and private drafts buckets; vector extension. -- **API:** health endpoint plus authenticated ingest and compile-callback stubs. The stubs only write run records. +- **Editor desk:** Supabase email-and-password sign-in for approved addresses on the editor list; Supabase-backed story review and quarantine; editable issue title, publication masthead, cover and back-cover copy, theme, section names, slot targets, supervisor, editor credits, and editor note. +- **Supabase:** editor, edition, run, source, article, story, and image tables; row-level security; public issues and private drafts buckets; vector extension. +- **Ingest:** authenticated RSS collection, robots-aware article text extraction, URL-hash deduplication, conservative title-based grouping, optional Gemini summaries and scoring, and a numeric claim check against stored source text. +- **Draft builder:** Gemini arranges approved stories within their editor-assigned sections, chooses story order and presentation, and can draft an editor note using structured JSON. Editable section slot targets guide the layout; overflow stories become briefs so no approved story is dropped. The app validates the plan, renders trusted TeX with escaped story text, and stores the source file in the private `drafts` bucket. +- **API:** health endpoint, scheduled RSS ingestion, and an authenticated compile-callback stub. - **Automation:** CI checks, a three-times-daily GitHub Actions request, and a LaTeX reference compile workflow. -- **Not active yet:** RSS ingestion, Gemini calls, story clustering or scoring, draft rendering, PDF publishing, and publication logic. +- **Not active yet:** embedding-based clustering, PDF compilation, and issue publication/archive workflow. The builder creates a private `.tex` file for review. A human must check the story claims and editor note before publication. ## Stack -Next.js App Router, React, TypeScript, Tailwind CSS, Supabase Auth/Postgres/Storage, GitHub Actions, Vercel, and TeX Live. Gemini is reserved for a later phase. +Next.js App Router, React, TypeScript, Tailwind CSS, Supabase Auth/Postgres/Storage, Google GenAI, GitHub Actions, Vercel, and TeX Live. ## Development Use Node.js 26.13.1, matching .nvmrc. -~~~bash +```bash nvm install nvm use npm ci cp .env.example .env.local npm run dev -~~~ +``` -The public site can show its sample preview without Supabase credentials. Sign-in, the editor desk, and API stubs need the required values in .env.local. See [the setup guide](docs/SETUP.md). +The public site can show its sample preview without Supabase credentials. Sign-in, the editor desk, and ingestion need the required values in .env.local. See [the setup guide](docs/SETUP.md) and [the ingestion notes](docs/INGEST.md). -~~~bash +```bash npm run lint npm run typecheck npm run build -~~~ +``` ## Project documents - [Developer setup](docs/SETUP.md) - [Build specification](docs/SPEC.md) - [May 2026 LaTeX design reference](latex/reference/may-2026.tex) +- [RSS source and ingestion notes](docs/INGEST.md) ## Project layout -~~~text +```text app/ public pages, editor desk, and API routes +app/icon.svg supplied magazine favicon and app icons components/ shared site, editor, and UI components config/ magazine identity, sections, and slot counts content/site.ts public and editor-facing copy lib/data/ clearly labeled sample issue and story data -lib/ingest/ phase 2 feed collection -lib/ai/ phase 2 model providers -lib/render/ later LaTeX rendering +lib/ingest/ feed collection, story enrichment, and scoring +lib/magazine/ editable template, AI layout planning, and safe TeX rendering +public/brand/ supplied Machine Intelligence logo pack +latex/templates/ source template used by the issue renderer supabase/migrations/ database schema and access policies -.github/workflows/ CI, ingest request, and LaTeX check -~~~ +.github/workflows/ CI, ingest request, and LaTeX reference checks +``` A [Coding Moves](https://codingmoves.com) project. diff --git a/app/(site)/privacy/page.tsx b/app/(site)/privacy/page.tsx index 83c92e7..d660e62 100644 --- a/app/(site)/privacy/page.tsx +++ b/app/(site)/privacy/page.tsx @@ -16,22 +16,46 @@ export default function PrivacyPage() { title={siteCopy.privacy.title} description={siteCopy.privacy.intro} /> -
+
-

{siteCopy.privacy.trackingTitle}

-

{siteCopy.privacy.trackingText}

+

+ {siteCopy.privacy.trackingTitle} +

+

+ {siteCopy.privacy.trackingText} +

-

{siteCopy.privacy.editorTitle}

-

{siteCopy.privacy.editorText}

+

+ {siteCopy.privacy.editorTitle} +

+

+ {siteCopy.privacy.editorText} +

-

{siteCopy.privacy.storageTitle}

-

{siteCopy.privacy.storageText}

+

+ {siteCopy.privacy.storageTitle} +

+

+ {siteCopy.privacy.storageText} +

-

{siteCopy.privacy.contactTitle}

-

{siteCopy.privacy.contactText}

+

+ {siteCopy.privacy.aiTitle} +

+

+ {siteCopy.privacy.aiText} +

+
+
+

+ {siteCopy.privacy.contactTitle} +

+

+ {siteCopy.privacy.contactText} +

diff --git a/app/api/cron/ingest/route.ts b/app/api/cron/ingest/route.ts index 8cc5fed..398344f 100644 --- a/app/api/cron/ingest/route.ts +++ b/app/api/cron/ingest/route.ts @@ -1,9 +1,10 @@ import { getCronSecret } from "@/lib/env"; -import { recordStubRun } from "@/lib/api/record-stub-run"; import { hasValidCronBearer } from "@/lib/security/cron-auth"; +import { runIngest } from "@/lib/ingest/pipeline"; export const runtime = "nodejs"; export const dynamic = "force-dynamic"; +export const maxDuration = 60; export async function POST(request: Request) { let secret: string; @@ -18,16 +19,19 @@ export async function POST(request: Request) { } if (!hasValidCronBearer(request.headers.get("authorization"), secret)) { - return Response.json({ ok: false, error: "Unauthorized." }, { status: 401 }); + return Response.json( + { ok: false, error: "Unauthorized." }, + { status: 401 }, + ); } try { - // TODO(phase-2): fetch feeds, cluster stories, and rebuild the draft. - const runId = await recordStubRun("ingest"); - return Response.json({ ok: true, runId, stub: true }); - } catch { + const result = await runIngest(); + return Response.json(result, { status: result.ok ? 200 : 502 }); + } catch (error) { + console.error("The authenticated ingest request failed.", error); return Response.json( - { ok: false, error: "Could not record the ingest run." }, + { ok: false, error: "The ingest run could not be completed." }, { status: 503 }, ); } diff --git a/app/apple-icon.png b/app/apple-icon.png new file mode 100644 index 0000000..0956204 Binary files /dev/null and b/app/apple-icon.png differ diff --git a/app/desk/actions.ts b/app/desk/actions.ts index 5c9e81b..cd4d019 100644 --- a/app/desk/actions.ts +++ b/app/desk/actions.ts @@ -4,9 +4,20 @@ import { revalidatePath } from "next/cache"; import { redirect } from "next/navigation"; import { z } from "zod"; import { siteCopy } from "@/content/site"; -import { requireAdmin } from "@/lib/auth/require-editor"; +import { requireAdmin, requireEditor } from "@/lib/auth/require-editor"; import { createSupabaseServerClient } from "@/lib/supabase/server"; import { createSupabaseAdminClient } from "@/lib/supabase/admin"; +import { + rebuildMagazineDraft, + refreshDraftTex, + saveDraftEditorNote, + saveDraftTemplate, +} from "@/lib/magazine/build"; +import { sectionLayoutChanged } from "@/lib/magazine/layout"; +import { + magazineTemplateSchema, + readMagazineTemplate, +} from "@/lib/magazine/template"; export type EditorActionState = { message: string; @@ -15,6 +26,14 @@ export type EditorActionState = { const emailSchema = z.string().trim().email(); const nameSchema = z.string().trim().min(2).max(80); +const storyIdSchema = z.string().uuid(); +const storyStatusSchema = z.enum(["candidate", "approved", "rejected"]); +const storySectionSchema = z.enum([ + "pakistan", + "global", + "research", + "industry", +]); async function verifyAdmin() { const { user, editor } = await requireAdmin(); @@ -108,3 +127,206 @@ export async function signOut() { revalidatePath("/", "layout"); redirect("/"); } + +export async function setStoryStatus(formData: FormData) { + await requireEditor(); + const id = storyIdSchema.safeParse(formData.get("storyId")); + const status = storyStatusSchema.safeParse(formData.get("status")); + const rejectReason = z + .string() + .trim() + .max(500) + .safeParse(formData.get("rejectReason") ?? ""); + if (!id.success || !status.success || !rejectReason.success) { + throw new Error("Invalid story review update."); + } + + const admin = createSupabaseAdminClient(); + const { data: story, error: lookupError } = await admin + .from("stories") + .select("headline, summary, section, is_ai_related, status") + .eq("id", id.data) + .maybeSingle(); + if (lookupError || !story) throw new Error("Could not find that story."); + if ( + status.data === "approved" && + (!story.headline.trim() || !story.summary?.trim() || !story.section) + ) { + throw new Error( + "Add a summary and choose a section before approving this story.", + ); + } + if (status.data === "approved" && story.is_ai_related === false) { + throw new Error( + "This story is marked as not AI-related. Edit its AI relevance after checking the source before approval.", + ); + } + + const { error } = await admin + .from("stories") + .update({ + status: status.data, + reject_reason: + status.data === "rejected" ? rejectReason.data || null : null, + }) + .eq("id", id.data) + .neq("status", "published"); + if (error) throw new Error("Could not save the story review decision."); + if (story.status === "approved" || status.data === "approved") { + await rebuildMagazineDraft(); + } + revalidatePath("/desk/stories"); + revalidatePath("/desk/quarantine"); + revalidatePath("/desk"); +} + +export async function saveStoryEdit(formData: FormData) { + await requireEditor(); + const id = storyIdSchema.safeParse(formData.get("storyId")); + const headline = z + .string() + .trim() + .min(8) + .max(300) + .safeParse(formData.get("headline")); + const summary = z + .string() + .trim() + .min(40) + .max(3000) + .safeParse(formData.get("summary")); + const section = storySectionSchema.safeParse(formData.get("section")); + const aiRelated = z + .enum(["true", "false", "unknown"]) + .safeParse(formData.get("aiRelated")); + if ( + !id.success || + !headline.success || + !summary.success || + !section.success || + !aiRelated.success + ) { + throw new Error( + "Enter a headline, summary, section, and AI relevance before saving.", + ); + } + + const admin = createSupabaseAdminClient(); + const { data: story, error: lookupError } = await admin + .from("stories") + .select("status") + .eq("id", id.data) + .maybeSingle(); + if (lookupError || !story) throw new Error("Could not find that story."); + const { error } = await admin + .from("stories") + .update({ + headline: headline.data, + summary: summary.data, + section: section.data, + is_ai_related: + aiRelated.data === "unknown" ? null : aiRelated.data === "true", + }) + .eq("id", id.data) + .neq("status", "published"); + if (error) throw new Error("Could not save the story changes."); + if (story.status === "approved") await rebuildMagazineDraft(); + revalidatePath("/desk/stories"); + revalidatePath("/desk"); +} + +export async function saveDraftTemplateAction(formData: FormData) { + await requireEditor(); + const admin = createSupabaseAdminClient(); + const { data: edition, error } = await admin + .from("editions") + .select("id, layout") + .eq("status", "draft") + .maybeSingle(); + if (error || !edition) + throw new Error("Could not find the current draft issue."); + + const current = readMagazineTemplate(edition.layout); + const sections = current.sections.map((section) => { + const label = z + .string() + .trim() + .min(2) + .max(40) + .safeParse(formData.get(`section.${section.id}.label`)); + const slots = z + .string() + .regex(/^(?:[0-9]|1[0-2])$/) + .transform(Number) + .safeParse(formData.get(`section.${section.id}.slots`)); + if (!label.success || !slots.success) + throw new Error( + "Each section needs a label and a slot count from 0 to 12.", + ); + return { ...section, label: label.data, slots: slots.data }; + }); + const editorsValue = z.string().max(1000).safeParse(formData.get("editors")); + const template = magazineTemplateSchema.safeParse({ + publicationName: formData.get("publicationName"), + coverSubtitle: formData.get("coverSubtitle"), + coverTagline: formData.get("coverTagline"), + backCoverNote: formData.get("backCoverNote"), + supervisorName: formData.get("supervisorName"), + supervisorTitle: formData.get("supervisorTitle"), + editors: editorsValue.success + ? editorsValue.data + .split(/[\n,]/) + .map((name) => name.trim()) + .filter(Boolean) + : [], + theme: formData.get("theme"), + sections, + }); + const title = z + .string() + .trim() + .min(4) + .max(100) + .safeParse(formData.get("title")); + if (!template.success || !title.success) { + throw new Error( + "Check the issue title, cover details, editor list, theme, and section settings.", + ); + } + const editionId = await saveDraftTemplate({ + title: title.data, + template: template.data, + }); + if (sectionLayoutChanged(current.sections, template.data.sections)) { + await rebuildMagazineDraft({ preserveEditorNote: true }); + } else { + await refreshDraftTex(editionId); + } + revalidatePath("/desk"); + revalidatePath("/desk/issues"); +} + +export async function saveDraftEditorNoteAction(formData: FormData) { + await requireEditor(); + const note = z + .string() + .trim() + .max(1800) + .safeParse(formData.get("editorNote")); + const approved = formData.get("reviewed") === "on"; + if (!note.success || (approved && note.data.length < 40)) { + throw new Error( + "Write at least 40 characters before marking the editor's note reviewed.", + ); + } + const editionId = await saveDraftEditorNote({ note: note.data, approved }); + await refreshDraftTex(editionId); + revalidatePath("/desk"); +} + +export async function rebuildDraftAction() { + await requireEditor(); + await rebuildMagazineDraft(); + revalidatePath("/desk"); + revalidatePath("/desk/stories"); +} diff --git a/app/desk/layout.tsx b/app/desk/layout.tsx index fd0422c..9ee5258 100644 --- a/app/desk/layout.tsx +++ b/app/desk/layout.tsx @@ -1,4 +1,5 @@ import type { ReactNode } from "react"; +import Image from "next/image"; import Link from "next/link"; import { DeskNavigation } from "@/components/desk-navigation"; import { magazine } from "@/config/magazine"; @@ -17,33 +18,50 @@ export default async function DeskLayout({ const { user, editor } = await requireEditor(); return ( -
-