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
53 changes: 41 additions & 12 deletions pm-stack/aggregator/scripts/collect-fleet-feed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ import { access, readFile, rename, stat, unlink, writeFile } from "node:fs/promi
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { dnsSectionFromRegister } from "../src/dns.ts";
import { dnsSectionFromRegister, dnsSectionFromRegisterJson, parseDnsRegister } from "../src/dns.ts";
import {
disabledProvidersFromConfig,
aaAbsent,
Expand Down Expand Up @@ -139,6 +139,9 @@ const orchestrationPath = process.env.ORCHESTRATION_PATH ?? join(HIDDEN, "orches
const dnsRegisterPath =
process.env.DNS_REGISTER_PATH ??
join(HOME, "workspace/goals/stand-up-lab-cluster-talm-talos-cozystack-postgres-rustfs/files/dns-domain-register.md");
// Slice 2 of #902: register.json sits beside the register Markdown and
// is the authoritative source for the fields it carries.
const dnsRegisterJsonPath = process.env.DNS_REGISTER_JSON_PATH ?? join(dirname(dnsRegisterPath), "register.json");
const launchRecordsPath = process.env.CLAUDE_LAUNCH_RECORDS_PATH ?? join(HIDDEN, "claude-launch-records.jsonl");
const quotaRegistryPath = process.env.QUOTA_REGISTRY_PATH ?? join(HIDDEN, "provider-quota-registry.md");
const snapshotOutboxPath = process.env.USAGE_SNAPSHOT_OUTBOX_PATH ?? join(HIDDEN, "usage-snapshot-outbox.jsonl");
Expand Down Expand Up @@ -662,22 +665,48 @@ async function main(): Promise<void> {
}
markSection("registry", registry.length ? "ok" : "skipped");

// --- DNS register (#902's file, parsed; #906 §1 owns the view) ---------
// --- DNS register (#902's files; #906 §1 owns the view) ----------------
// Slice 2: register.json is authoritative for the fields it carries;
// the Markdown parse supplies the editorial columns and is the
// FALLBACK when register.json is missing or malformed — the fallback
// is logged, never silent (see dnsSectionFromRegisterJson in dns.ts).
let dns: DnsSection | undefined;
let dnsSourcePath = dnsRegisterPath;
let mdText: string | null = null;
let mdErr: unknown = null;
try {
const md = await readFile(dnsRegisterPath, "utf8");
mdText = await readFile(dnsRegisterPath, "utf8");
} catch (err) {
mdErr = err;
}
const mdEntries = mdText ? parseDnsRegister(mdText) : [];
let jsonProblem: string | null = null;
try {
const jsonText = await readFile(dnsRegisterJsonPath, "utf8");
dns =
dnsSectionFromRegister(md, now.toISOString(), "register file (#902 pipeline) via fleet feed collector") ??
dnsSectionFromRegisterJson(jsonText, now.toISOString(), "register.json (#902 pipeline) via fleet feed collector", mdEntries) ??
undefined;
if (!dns) {
console.error("collector: DNS register parsed to zero entries; section omitted");
markSection("dns", "error", "register did not produce a valid DNS section");
if (!dns) jsonProblem = "register.json did not produce a valid DNS section";
} catch (err) {
jsonProblem = err instanceof Error ? err.message : String(err);
}
if (dns) {
dnsSourcePath = dnsRegisterJsonPath;
markSection("dns", "ok");
} else {
console.error(`collector: DNS register.json unusable (${jsonProblem ?? "unknown reason"}); FALLING BACK to the register Markdown parse`);
if (mdText) {
dns = dnsSectionFromRegister(mdText, now.toISOString(), "register file (#902 pipeline) via fleet feed collector") ?? undefined;
if (!dns) {
console.error("collector: DNS register parsed to zero entries; section omitted");
markSection("dns", "error", "register did not produce a valid DNS section");
} else {
markSection("dns", "ok");
}
} else {
markSection("dns", "ok");
console.error("collector: DNS register unreadable; section omitted");
markSection("dns", isMissingInput(mdErr) ? "skipped" : "error", mdErr);
}
} catch (err) {
console.error("collector: DNS register unreadable; section omitted");
markSection("dns", isMissingInput(err) ? "skipped" : "error", err);
}

// --- orchestration section (#899) --------------------------------------
Expand Down Expand Up @@ -815,7 +844,7 @@ async function main(): Promise<void> {
if (payg) snapshotRecords.push(...recordsFromPaygLines(payg, "fleet-feed-collector"));
if (dns) {
try {
const registerStat = await stat(dnsRegisterPath);
const registerStat = await stat(dnsSourcePath);
snapshotRecords.push(...recordsFromDns(dns, registerStat.mtime.toISOString(), "fleet-feed-collector"));
} catch {
console.error("collector: DNS register stat failed; dns snapshot records omitted this run");
Expand Down
90 changes: 82 additions & 8 deletions pm-stack/aggregator/src/dns.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
// The DNS/domain register (#902) as data. The register of record is a
// Markdown file produced by the #902 pipeline (a table sorted by next
// renewal); the collector parses it into a DnsSection for the fleet
// feed and the aggregator renders that — the page never edits the
// register. The parser keys off the register table's header row, so a
// re-worded prose section elsewhere in the file cannot corrupt it;
// if #902's job ever emits register.json, this parser is the fallback,
// not the competitor.
// The DNS/domain register (#902) as data. The register of record is
// produced by the #902 pipeline in two forms: register.json (slice 2 —
// the authoritative source for the fields it carries: domain,
// registrar, DNS host, next renewal, auto-renew, list price) and the
// register Markdown table, which still carries the editorial columns
// the JSON does not (prior-year cost, where-used, plan/status, review)
// and is the fallback when register.json is missing or malformed.
// The collector builds the DnsSection the fleet feed carries and the
// aggregator renders — the page never edits the register. The Markdown
// parser keys off the register table's header row, so a re-worded
// prose section elsewhere in the file cannot corrupt it.
import { addDaysYmd, chicagoYmd } from "./derive.ts";
import type { DnsEntry, DnsSection } from "./model.ts";

Expand Down Expand Up @@ -70,6 +73,77 @@ export function dnsSectionFromRegister(md: string, generatedAt: string, source:
return { generatedAt, source, totalAnnualListUsd, entries };
}

/** One domain row of register.json as the #902 job emits it. */
export interface DnsRegisterJsonDomain {
domain: string;
registrar: string;
dns_hosted_at: string;
next_renewal: string;
auto_renew: boolean | null;
renewal_price_usd: number | null;
source?: string;
}

/**
* Assemble the feed section from register.json (slice 2 of #902).
* The JSON is authoritative for the fields it carries; the editorial
* columns it does not carry (prior-year cost, where-used, plan/status,
* review) come from the Markdown parse (`mdEntries`, keyed by domain)
* so the rendered page is unchanged for current register data. A
* domain with no Markdown row renders with an empty plan, i.e.
* classified unused. Returns null on ANY malformation — unparseable
* JSON, a missing/empty domains list, a duplicate domain, or a row
* whose core fields are mistyped — so the caller falls back to the
* Markdown parse instead of serving a half-invented register.
*/
export function dnsSectionFromRegisterJson(
jsonText: string,
generatedAt: string,
source: string,
mdEntries: DnsEntry[] = [],
): DnsSection | null {
let parsed: unknown;
try {
parsed = JSON.parse(jsonText);
} catch {
return null;
}
if (typeof parsed !== "object" || parsed === null) return null;
const domains = (parsed as { domains?: unknown }).domains;
if (!Array.isArray(domains) || domains.length === 0) return null;
const mdByDomain = new Map(mdEntries.map((e) => [e.domain, e]));
const seen = new Set<string>();
const entries: DnsEntry[] = [];
for (const raw of domains as Partial<DnsRegisterJsonDomain>[]) {
if (typeof raw !== "object" || raw === null) return null;
const { domain, registrar, dns_hosted_at: dnsHost, next_renewal: renewal, auto_renew: autoRenew, renewal_price_usd: price } = raw;
if (typeof domain !== "string" || domain.length === 0 || seen.has(domain)) return null;
if (typeof registrar !== "string" || typeof dnsHost !== "string") return null;
if (typeof renewal !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(renewal)) return null;
if (price !== null && price !== undefined && (typeof price !== "number" || !Number.isFinite(price))) return null;
if (autoRenew !== null && autoRenew !== undefined && typeof autoRenew !== "boolean") return null;
seen.add(domain);
const md = mdByDomain.get(domain);
const plan = md?.plan ?? "";
entries.push({
domain,
registrar,
dnsHost,
renewal,
autoRenew: autoRenew === true ? "ON" : autoRenew === false ? "OFF" : "unknown",
priceUsd: price ?? null,
priorYearCost: md?.priorYearCost ?? "",
used: md?.used ?? "",
plan,
review: md?.review ?? "",
status: classifyDnsStatus(plan),
});
}
entries.sort((a, b) => a.renewal.localeCompare(b.renewal) || a.domain.localeCompare(b.domain));
const totalAnnualListUsd = Math.round(entries.reduce((sum, e) => sum + (e.priceUsd ?? 0), 0) * 100) / 100;
return { generatedAt, source, totalAnnualListUsd, entries };
}

/** Structural check shared by the collector and the live source. */
export function isDnsSection(v: unknown): v is DnsSection {
if (typeof v !== "object" || v === null) return false;
Expand Down
45 changes: 44 additions & 1 deletion pm-stack/aggregator/test/slice3.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { mkdtempSync, renameSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { CommentsStore, validateNewComment } from "../src/comments.ts";
import { dnsSectionFromRegister, isDnsSection, parseDnsRegister, summarizeDns } from "../src/dns.ts";
import { dnsSectionFromRegister, dnsSectionFromRegisterJson, isDnsSection, parseDnsRegister, summarizeDns } from "../src/dns.ts";
import type { SessionFeedEntry } from "../src/model.ts";
import { PAGES } from "../src/pages.ts";
import { agentIdentityOf, mergeRecords, parseLaunchRecords, recordFromSessionEntry } from "../src/registry.ts";
Expand Down Expand Up @@ -118,6 +118,49 @@ describe("dns register parser", () => {
expect(dnsSectionFromRegister("# nothing\n", "2026-10-25T00:00:00Z", "test")).toBeNull();
});

test("register.json section: JSON fields win, Markdown supplies editorial columns (#902 slice 2)", () => {
const mdEntries = parseDnsRegister(REGISTER_MD);
const json = JSON.stringify({
generated_at: "2026-11-01T16:26:34Z",
domains: [
{ domain: "first.de", registrar: "Porkbun", dns_hosted_at: "Porkbun", next_renewal: "2027-02-09", auto_renew: true, renewal_price_usd: 4.07, source: "porkbun-api" },
{ domain: "active.example", registrar: "Porkbun", dns_hosted_at: "Cloudflare", next_renewal: "2027-02-24", auto_renew: false, renewal_price_usd: 29.35, source: "porkbun-api" },
{ domain: "jsononly.example", registrar: "Porkbun", dns_hosted_at: "Porkbun", next_renewal: "2027-03-01", auto_renew: null, renewal_price_usd: null, source: "register-markdown" },
],
});
const section = dnsSectionFromRegisterJson(json, "2026-11-01T17:00:00Z", "test-json", mdEntries);
expect(section).not.toBeNull();
// JSON is authoritative and complete: a domain absent from the
// Markdown still renders; a Markdown-only domain does not.
expect(section?.entries.map((e) => e.domain)).toEqual(["first.de", "active.example", "jsononly.example"]);
expect(section?.totalAnnualListUsd).toBe(33.42);
const active = section?.entries.find((e) => e.domain === "active.example");
expect(active?.priceUsd).toBe(29.35);
expect(active?.autoRenew).toBe("OFF");
// Editorial columns come from the Markdown row for the same domain.
expect(active?.plan).toBe("Active — fleet infrastructure");
expect(active?.status).toBe("active");
const jsonOnly = section?.entries.find((e) => e.domain === "jsononly.example");
expect(jsonOnly?.autoRenew).toBe("unknown");
expect(jsonOnly?.priceUsd).toBeNull();
expect(jsonOnly?.status).toBe("unused");
expect(isDnsSection(section)).toBe(true);
});

test("register.json section: missing/malformed JSON yields null so the caller falls back (#902 slice 2)", () => {
const mdEntries = parseDnsRegister(REGISTER_MD);
expect(dnsSectionFromRegisterJson("{not json", "2026-11-01T17:00:00Z", "t", mdEntries)).toBeNull();
expect(dnsSectionFromRegisterJson('{"domains":[]}', "2026-11-01T17:00:00Z", "t", mdEntries)).toBeNull();
expect(dnsSectionFromRegisterJson('{"generated_at":"x"}', "2026-11-01T17:00:00Z", "t", mdEntries)).toBeNull();
const badRow = JSON.stringify({ domains: [{ domain: "x.dev", registrar: "Porkbun", dns_hosted_at: "Porkbun", next_renewal: "soon", auto_renew: true, renewal_price_usd: 1 }] });
expect(dnsSectionFromRegisterJson(badRow, "2026-11-01T17:00:00Z", "t", mdEntries)).toBeNull();
const dup = JSON.stringify({ domains: [
{ domain: "x.dev", registrar: "Porkbun", dns_hosted_at: "Porkbun", next_renewal: "2027-01-01", auto_renew: true, renewal_price_usd: 1 },
{ domain: "x.dev", registrar: "Porkbun", dns_hosted_at: "Porkbun", next_renewal: "2027-01-02", auto_renew: true, renewal_price_usd: 2 },
] });
expect(dnsSectionFromRegisterJson(dup, "2026-11-01T17:00:00Z", "t", mdEntries)).toBeNull();
});

test("isDnsSection owns the finite-number + status rules (#2412)", () => {
const good = dnsSectionFromRegister(REGISTER_MD, "2026-10-25T00:00:00Z", "test");
expect(good).not.toBeNull();
Expand Down
Loading