Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ GEMINI_API_KEY=
WRITER_MODEL=
# Optional model override for magazine story placement.
DESIGNER_MODEL=
# Reserved for a future compile workflow; not used by the current app.
# Legacy token; current PDF compilation uses temporary signed storage URLs.
GITHUB_DISPATCH_TOKEN=
# App URL used by GitHub Actions; also add as the APP_URL repository secret.
APP_URL=
182 changes: 182 additions & 0 deletions .github/workflows/compile-draft.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
name: Compile current magazine draft

on:
workflow_run:
workflows: ["Scheduled ingest"]
types: [completed]
branches: [main]
workflow_dispatch:
inputs:
edition_id:
description: Optional draft edition ID (leave blank for the current draft)
required: false
type: string

permissions: {}

concurrency:
group: compile-draft-main
cancel-in-progress: false

jobs:
compile:
if: github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success'
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Check out the default branch
uses: actions/checkout@v4
with:
ref: main

- name: Request temporary compile URLs
id: prepare
env:
APP_URL: ${{ secrets.APP_URL }}
CRON_SECRET: ${{ secrets.CRON_SECRET }}
EDITION_ID: ${{ github.event.inputs.edition_id || '' }}
run: |
if [[ -z "$APP_URL" || -z "$CRON_SECRET" ]]; then
echo "::error title=Configuration::APP_URL and CRON_SECRET are required."
exit 1
fi
APP_URL="${APP_URL%/}"
payload="{}"
if [[ -n "$EDITION_ID" ]]; then
payload=$(node -e 'process.stdout.write(JSON.stringify({editionId: process.env.EDITION_ID}))')
fi
http_code=$(curl --silent --show-error \
--output "$RUNNER_TEMP/compile-prepare.json" \
--write-out "%{http_code}" \
--request POST \
--header "Authorization: Bearer $CRON_SECRET" \
--header "Content-Type: application/json" \
--data "$payload" \
--max-time 30 \
"$APP_URL/api/cron/compile/prepare")
if [[ ! "$http_code" =~ ^2[0-9][0-9]$ ]]; then
echo "::error title=Compile preparation failed::The endpoint returned HTTP $http_code."
cat "$RUNNER_TEMP/compile-prepare.json"
exit 1
fi
node <<'NODE'
const fs = require('node:fs');
const crypto = require('node:crypto');
const data = JSON.parse(fs.readFileSync(process.env.RUNNER_TEMP + '/compile-prepare.json', 'utf8'));
if (!data.ok) throw new Error(data.error || 'Could not prepare the PDF compile.');
const outputs = fs.createWriteStream(process.env.GITHUB_OUTPUT, { flags: 'a' });
function setOutput(name, value) {
const delimiter = 'OUT_' + crypto.randomBytes(8).toString('hex');
outputs.write(`${name}<<${delimiter}\n${value}\n${delimiter}\n`);
}
setOutput('ready', String(data.ready));
if (!data.ready) {
console.log(`::notice title=No draft PDF::${data.reason || 'The current draft is not ready to compile.'}`);
outputs.end();
process.exit(0);
}
for (const value of [data.sourceUrl, data.pdfUploadUrl]) console.log(`::add-mask::${value}`);
setOutput('edition_id', data.editionId);
setOutput('tex_hash', data.texHash);
setOutput('pdf_path', data.pdfPath);
setOutput('source_url', data.sourceUrl);
setOutput('upload_url', data.pdfUploadUrl);
outputs.end();
NODE

- name: Download the current TeX source
if: steps.prepare.outputs.ready == 'true'
env:
SOURCE_URL: ${{ steps.prepare.outputs.source_url }}
run: |
mkdir -p magazine/build
curl --fail --silent --show-error "$SOURCE_URL" --output magazine/build/edition.tex

- name: Compile the magazine PDF
id: latex
if: steps.prepare.outputs.ready == 'true'
uses: xu-cheng/latex-action@v4
with:
texlive_version: 2026
root_file: magazine/build/edition.tex
work_in_root_file_dir: true
args: -pdf -file-line-error -halt-on-error -interaction=nonstopmode

- name: Upload the PDF to private draft storage
id: upload
if: steps.prepare.outputs.ready == 'true' && steps.latex.outcome == 'success'
env:
UPLOAD_URL: ${{ steps.prepare.outputs.upload_url }}
run: |
node <<'NODE'
const fs = require('node:fs/promises');
(async () => {
const pdf = await fs.readFile('magazine/build/edition.pdf');
const response = await fetch(process.env.UPLOAD_URL, {
method: 'POST',
headers: {
'content-type': 'application/pdf',
'cache-control': 'max-age=3600',
'x-upsert': 'true',
},
body: pdf,
});
if (!response.ok) {
throw new Error(`Supabase PDF upload returned HTTP ${response.status}.`);
}
console.log(`Uploaded compiled PDF (${pdf.byteLength} bytes).`);
})().catch((error) => {
console.error(error);
process.exitCode = 1;
});
NODE

- name: Record the compile result
if: always() && steps.prepare.outputs.ready == 'true'
env:
APP_URL: ${{ secrets.APP_URL }}
CRON_SECRET: ${{ secrets.CRON_SECRET }}
EDITION_ID: ${{ steps.prepare.outputs.edition_id }}
TEX_HASH: ${{ steps.prepare.outputs.tex_hash }}
PDF_PATH: ${{ steps.prepare.outputs.pdf_path }}
COMPILE_SUCCESS: ${{ steps.upload.outcome == 'success' }}
run: |
APP_URL="${APP_URL%/}"
node <<'NODE'
(async () => {
const payload = {
editionId: process.env.EDITION_ID,
texHash: process.env.TEX_HASH,
success: process.env.COMPILE_SUCCESS === 'true',
pdfPath: process.env.COMPILE_SUCCESS === 'true' ? process.env.PDF_PATH : undefined,
error: process.env.COMPILE_SUCCESS === 'true' ? undefined : 'LaTeX compilation or PDF upload failed. See this workflow run for details.',
};
const response = await fetch(`${process.env.APP_URL.replace(/\/$/, '')}/api/compile/callback`, {
method: 'POST',
headers: {
authorization: `Bearer ${process.env.CRON_SECRET}`,
'content-type': 'application/json',
},
body: JSON.stringify(payload),
});
if (!response.ok) {
throw new Error(`Compile callback returned HTTP ${response.status}.`);
}
console.log('Compile result recorded.');
})().catch((error) => {
console.error(error);
process.exitCode = 1;
});
NODE

- name: Keep the PDF and compile log as a run artifact
if: always() && steps.prepare.outputs.ready == 'true'
uses: actions/upload-artifact@v4
with:
name: magazine-${{ steps.prepare.outputs.edition_id }}
path: |
magazine/build/edition.pdf
magazine/build/edition.log
if-no-files-found: ignore
retention-days: 14
3 changes: 2 additions & 1 deletion .github/workflows/ingest.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ name: Scheduled ingest

on:
schedule:
- cron: "0 1,8,15 * * *"
# 08:00 and 20:00 Pakistan Standard Time (UTC+5).
- cron: "0 3,15 * * *"
workflow_dispatch:

permissions: {}
Expand Down
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@

The newsroom behind **Machine Intelligence**, the magazine of the Department of Artificial Intelligence at NFC IET Multan.

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.
The newsroom collects stories from an explicit trusted-feed allowlist twice a day, asks Gemini to summarize and arrange approved AI news, and builds a complete private LaTeX/PDF draft for editors to review. An issue cannot be published until it has been open for at least 14 days, trusted-source collection succeeds, all AI and editor queues are clear, every approved story is included, the editor's note is reviewed, and the current PDF is compiled.

## 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 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.
- **Ingest:** authenticated twice-daily RSS collection from explicitly trusted sources, robots-aware article text extraction, URL-hash deduplication, conservative title-based grouping, 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:** 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.
- **Publication:** GitHub Actions compiles the current private draft PDF after each scheduled ingest attempt. Editors get a visible checklist and a disabled publish button until the 14-day and editorial checks pass. Publishing atomically freezes the issue, marks its stories used, and opens the next draft.
- **Automation:** CI checks, twice-daily 08:00/20:00 Pakistan-time ingest, automatic draft PDF compilation, and a LaTeX reference compile workflow.
- **Editorial control:** Gemini grounds stories in trusted source text and flags unsupported numbers. Editors still need to inspect the linked evidence and approve the stories and editor's note; AI output is not automatically published.

## Stack

Expand Down
146 changes: 134 additions & 12 deletions app/api/compile/callback/route.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,156 @@
import { z } from "zod";
import { createSupabaseAdminClient } from "@/lib/supabase/admin";
import { getCronSecret } from "@/lib/env";
import { recordStubRun } from "@/lib/api/record-stub-run";
import { hasValidCronBearer } from "@/lib/security/cron-auth";
import type { Json } from "@/lib/supabase/types";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

const callbackSchema = z.object({
editionId: z.string().uuid(),
success: z.boolean(),
texHash: z.string().regex(/^[a-f0-9]{64}$/),
pdfPath: z.string().max(300).optional(),
error: z.string().trim().max(1000).optional(),
});

export async function POST(request: Request) {
let secret: string;
try {
secret = getCronSecret();
} catch (error) {
const message =
error instanceof Error
? error.message
: "CRON_SECRET is missing or invalid.";
return Response.json({ ok: false, error: message }, { status: 503 });
} catch {
return Response.json(
{ ok: false, error: "Cron authentication is not configured." },
{ status: 503 },
);
}

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 },
);
}

let input: z.infer<typeof callbackSchema>;
try {
// TODO(phase-2): validate the compile result and store its artifacts.
const runId = await recordStubRun("compile_callback");
return Response.json({ ok: true, runId, stub: true });
input = callbackSchema.parse(await request.json());
} catch {
return Response.json(
{ ok: false, error: "Could not record the compile callback." },
{ ok: false, error: "Invalid compile callback." },
{ status: 400 },
);
}

const admin = createSupabaseAdminClient();
const now = new Date().toISOString();
const expectedPdfPath = `${input.editionId}/${input.texHash}.pdf`;
if (input.success && input.pdfPath !== expectedPdfPath) {
return Response.json(
{ ok: false, error: "The PDF path does not match the draft." },
{ status: 400 },
);
}

const { data: draft, error: draftError } = await admin
.from("editions")
.select("id, tex_hash")
.eq("id", input.editionId)
.eq("status", "draft")
.maybeSingle();
if (draftError || !draft) {
return Response.json(
{ ok: false, error: "The draft edition could not be found." },
{ status: 409 },
);
}
if (draft.tex_hash !== input.texHash) {
return Response.json(
{
ok: false,
error:
"The draft changed while its PDF was compiling. Compile the latest draft again.",
},
{ status: 409 },
);
}

if (input.success) {
const { data: files, error: storageError } = await admin.storage
.from("drafts")
.list(input.editionId, {
limit: 100,
search: `${input.texHash}.pdf`,
});
if (
storageError ||
!files?.some((file) => file.name === `${input.texHash}.pdf`)
) {
return Response.json(
{
ok: false,
error: "The compiled PDF was not found in draft storage.",
},
{ status: 409 },
);
}
}

const { data: edition, error: editionError } = await admin
.from("editions")
.update({
pdf_path: input.success ? expectedPdfPath : null,
pdf_tex_hash: input.success ? input.texHash : null,
})
.eq("id", input.editionId)
.eq("status", "draft")
.eq("tex_hash", input.texHash)
.select("id")
.maybeSingle();
if (editionError || !edition) {
return Response.json(
{ ok: false, error: "The draft edition could not be updated." },
{ status: 409 },
);
}

const details = {
editionId: input.editionId,
texHash: input.texHash,
pdfPath: input.success ? expectedPdfPath : null,
error: input.success ? null : (input.error ?? "LaTeX compilation failed."),
} as unknown as Json;
const { data: run, error: runError } = await admin
.from("runs")
.insert({
kind: "compile",
started_at: now,
finished_at: now,
ok: input.success,
details,
errors: input.success
? ([] as unknown as Json)
: ([
{
source: "LaTeX compiler",
message: input.error ?? "Compilation failed.",
},
] as unknown as Json),
})
.select("id")
.single();

if (runError || !run) {
return Response.json(
{ ok: false, error: "Could not record the compile result." },
{ status: 503 },
);
}
return Response.json({
ok: true,
runId: run.id,
editionId: edition.id,
compiled: input.success,
});
}
Loading
Loading