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
107 changes: 80 additions & 27 deletions pm-stack/aggregator/scripts/collect-fleet-feed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,19 @@
// state.json persists the keys already shown. Absent file = the
// pre-#1057 hand-fed charges only. No balances or debt data ever
// pass through: candidates are charge evidence only.
// - orchestration.json — the orchestration job's latest section
// (#899: tiers, dependencies, goal measurements), embedded only
// after normalizeOrchestrationSection accepts it (the collector
// gate in the publisher -> collector -> aggregator contract,
// #1176); absent/malformed = section omitted. The publisher's
// - the orchestration section (#899: tiers, dependencies, goal
// measurements) — read since the #10504 reader flip from the
// latest public.orch_runs.document on Supabase muse-dev2 (the
// writer cutover's store), through the same Management API SQL
// route and Bitwarden token as the AA section; orchestration.json
// (still regenerated by the writer every pass) is the fallback on
// any DB failure and the rollback source under
// ORCHESTRATION_SOURCE=file. Embedded only after
// normalizeOrchestrationSection accepts it (the collector gate in
// the publisher -> collector -> aggregator contract, #1176);
// absent/malformed = section omitted, and a DB failure that falls
// back to the file marks the section "error" so the aggregator
// surfaces it while serving the last good document. The publisher's
// pre-publish gate is `bun run contract:check -- --publisher
// <path>` (scripts/check-contract-corpus.ts), which runs this
// same validator; the shared corpus lives in
Expand Down Expand Up @@ -106,6 +114,12 @@ import {
type FeedSectionStatus,
type FleetFeed,
} from "../src/feed.ts";
import {
LATEST_ORCH_RUN_SQL,
orchestrationDocumentFromRows,
orchestrationSourceFromEnv,
resolveOrchestrationDocument,
} from "../src/orchestration-db.ts";
import { computeCheckoutDrift } from "../src/checkout-drift.ts";
import { assembleCollectorFeed } from "../src/feed-contract.ts";
import { defaultNeedsDrewFile, listAnswers } from "../src/needs-drew.ts";
Expand Down Expand Up @@ -1000,31 +1014,70 @@ async function main(): Promise<void> {
}
}

// --- orchestration section (#899) --------------------------------------
// --- orchestration section (#899; reader flip #10504) ------------------
// Post-flip the section is read from the latest orch_runs.document;
// orchestration.json is the fallback + rollback path only (see
// src/orchestration-db.ts for the contract and its tests).
let orchestration: OrchestrationSection | undefined;
try {
const parsed: unknown = JSON.parse(await readFile(orchestrationPath, "utf8"));
// Embed the normalized form (#1110): the feed carries the section
// in the one canonical shape the aggregator serves, whatever
// provenance form the publisher emitted.
const normalized = normalizeOrchestrationSection(parsed);
if (normalized) {
orchestration = normalized;
markSection("orchestration", "ok");
{
const resolution = await resolveOrchestrationDocument({
source: orchestrationSourceFromEnv(process.env),
readDb: async () => {
const token = await resolveBwsSecret("supabase.muse-dev2.access-token-muse-cli");
if (!token) throw new Error("no Supabase management token available (bws)");
const ref = await resolveSupabaseProjectRef(resolveBwsSecret);
if (!ref) throw new Error("no Supabase project ref available (bws)");
const row = orchestrationDocumentFromRows(await supabaseQuery(token, ref, LATEST_ORCH_RUN_SQL));
if (!row) throw new Error("orch_runs returned no usable latest row");
return row.document;
},
readFile: async (): Promise<unknown> => JSON.parse(await readFile(orchestrationPath, "utf8")),
validate: (document) => orchestrationSectionProblem(document),
});
if (resolution.document !== null) {
// Embed the normalized form (#1110): the feed carries the section
// in the one canonical shape the aggregator serves, whatever
// provenance form the publisher emitted.
const normalized = normalizeOrchestrationSection(resolution.document);
if (normalized) {
orchestration = normalized;
if (resolution.dbError) {
// Serving the last good document (the file export) with the
// DB failure surfaced: the aggregator's provenance reads
// "error — collector error: …; serving embedded section …".
console.error(
`collector: orch_runs read failed (${resolution.dbError}); serving the orchestration.json export`,
);
markSection(
"orchestration",
"error",
`orch_runs read failed (${resolution.dbError}); serving orchestration.json export`,
);
} else {
markSection("orchestration", "ok");
}
} else {
console.error(
`collector: orchestration document failed its structural check (${orchestrationSectionProblem(resolution.document)}); section omitted`,
);
markSection(
"orchestration",
"error",
`orchestration section failed structural check: ${orchestrationSectionProblem(resolution.document)}`,
);
}
} else if (resolution.fileMissing && !resolution.dbError) {
// No orchestration file yet (the job has not run) is the normal
// pre-#899 state — omit the section silently.
markSection("orchestration", "skipped");
} else {
console.error(
`collector: orchestration.json failed its structural check (${orchestrationSectionProblem(parsed)}); section omitted`,
);
markSection(
"orchestration",
"error",
`orchestration section failed structural check: ${orchestrationSectionProblem(parsed)}`,
);
const reason =
resolution.dbError && resolution.fileMissing
? `orch_runs read failed (${resolution.dbError}); orchestration.json export is also missing`
: (resolution.dbError ?? resolution.fileError ?? "orchestration document unavailable");
console.error(`collector: orchestration section unavailable (${reason}); section omitted`);
markSection("orchestration", "error", reason);
}
} catch (err) {
// No orchestration file yet (the job has not run) is the normal
// pre-#899 state — omit the section silently.
markSection("orchestration", isMissingInput(err) ? "skipped" : "error", err);
}

// --- GitHub Project pool (#910 stage 5) --------------------------------
Expand Down
112 changes: 112 additions & 0 deletions pm-stack/aggregator/src/orchestration-db.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
// Orchestration reader flip (#10504, phase 1 of #3142): the fleet-feed
// collector's orchestration section is read from the latest
// public.orch_runs.document on Supabase muse-dev2 — the writer cutover
// (task 14838, PR #10381) has written every hourly pass there since
// 2026-11-15 — and orchestration.json, which the writer still
// regenerates every pass, becomes the export + rollback path only.
//
// Fallback contract (from #10504): on any DB read failure the reader
// serves the last good document — the file, which is never behind
// because the writer's step 3 keeps regenerating it from the stored
// document — and surfaces the failure; a partial or invalid DB
// document is never served. Rollback is ORCHESTRATION_SOURCE=file,
// which points the reader back at the file and loses nothing.
//
// This module is the decision logic only: the collector injects its
// own Supabase query route (Management API SQL, the same one the AA
// section uses) and its file read, so the flip is unit-testable
// without a database.

/** The latest run's complete document, newest first. generated_at is
* the document's own generatedAt (writer contract, ORCHESTRATION.md);
* run_id breaks ties deterministically. */
export const LATEST_ORCH_RUN_SQL =
"SELECT run_id, document FROM public.orch_runs ORDER BY generated_at DESC, run_id DESC LIMIT 1";

/** Extract the document from a Management API result for
* LATEST_ORCH_RUN_SQL. Returns null for anything that is not exactly
* one usable row shape (no rows, a non-object document, a missing
* run_id): the caller treats null as a DB read failure and falls
* back — a partial document is never served. */
export function orchestrationDocumentFromRows(rows: unknown): { runId: string; document: unknown } | null {
if (!Array.isArray(rows) || rows.length === 0) return null;
const row: unknown = rows[0];
if (typeof row !== "object" || row === null) return null;
const { run_id: runId, document } = row as { run_id?: unknown; document?: unknown };
if (typeof runId !== "string" || runId.length === 0) return null;
if (typeof document !== "object" || document === null || Array.isArray(document)) return null;
return { runId, document };
}

/** Which source the reader consults first. "file" is the rollback
* position (#10504): the export the writer still regenerates every
* pass, so pointing back at it loses nothing. Anything but the exact
* string "file" selects the DB, the post-flip default. */
export function orchestrationSourceFromEnv(env: Readonly<Record<string, string | undefined>>): "db" | "file" {
return env.ORCHESTRATION_SOURCE?.trim().toLowerCase() === "file" ? "file" : "db";
}

export interface OrchestrationResolution {
/** The document to serve, or null when neither source produced one. */
document: unknown | null;
/** Where the served document came from; null when none was served. */
source: "db" | "file" | null;
/** Why the DB read failed, when it was attempted and failed. Set
* alongside a file-sourced document so the caller can surface the
* failure while serving the last good document. */
dbError?: string;
/** Why the file read failed, when it was attempted and failed. */
fileError?: string;
/** True when the file read failed because the file does not exist
* (the pre-#899 normal state), as opposed to an unreadable file. */
fileMissing?: boolean;
}

const errorText = (err: unknown): string => (err instanceof Error ? err.message : "read failed");

const isMissing = (err: unknown): boolean =>
typeof err === "object" && err !== null && "code" in err && (err as { code?: unknown }).code === "ENOENT";

/**
* Resolve the orchestration document per the flip contract.
*
* - DB source (default): read the latest orch_runs.document and
* validate it with `validate` (the shared structural check —
* orchestrationSectionProblem). A read failure *or* an invalid
* document is a DB failure: fall back to the file and carry the
* reason in `dbError` so it is surfaced, never hidden.
* - File source (rollback): the DB is not consulted at all.
* - The file read's own failure is reported, not hidden: `fileError`,
* plus `fileMissing` for the not-yet-published case, so the caller
* keeps today's skipped-vs-error distinction.
*/
export async function resolveOrchestrationDocument(deps: {
source: "db" | "file";
readDb: () => Promise<unknown>;
readFile: () => Promise<unknown>;
validate: (document: unknown) => string | null;
}): Promise<OrchestrationResolution> {
let dbError: string | undefined;
if (deps.source === "db") {
try {
const document = await deps.readDb();
const problem = deps.validate(document);
if (problem === null) return { document, source: "db" };
dbError = `latest orch_runs.document failed its structural check (${problem})`;
} catch (err) {
dbError = errorText(err);
}
}
try {
const document = await deps.readFile();
return { document, source: "file", ...(dbError ? { dbError } : {}) };
} catch (err) {
return {
document: null,
source: null,
...(dbError ? { dbError } : {}),
fileError: errorText(err),
fileMissing: isMissing(err),
};
}
}
4 changes: 3 additions & 1 deletion pm-stack/aggregator/src/sources/live.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2072,7 +2072,9 @@ export function liveSource(
},
async orchestration(): Promise<OrchestrationSection | null> {
// #899: the orchestration section rides the fleet feed, embedded
// by the collector from the orchestrator's own output file. The
// by the collector from the latest orch_runs.document since the
// #10504 reader flip (orchestration.json export as its fallback).
// The
// section carries its own provenance; absent = not measured yet.
// #1140: three states, told apart — live (accepted, served in
// the normalized contract shape, #1110), invalid (a section is
Expand Down
Loading