1. Phase-Boundary Event Emission as the Core Provenance Primitive

Every RAG pipeline phase — query rewrite, retrieval, reranking, context assembly — should emit a structured provenance event at its boundary, giving you a per-request audit chain you can reconstruct without touching the LLM's internal state.

  • Phase boundaries, not spans are the right granularity for RAG provenance: a retrieved document's lineage includes the query that produced it, the index it came from, the reranker score it received, and the position it held in the final context window — collapsing these into a single trace span loses the information governance actually needs.
  • Document fingerprinting at ingestion gives you the anchor point for the entire chain — hash the source content, the chunk boundaries, and the embedding model version at write time so that retrieval-time provenance can point back to an immutable record rather than a mutable document store.
  • Correlation IDs must flow downstream from the user request through every tool call and document fetch, or your audit trail becomes a collection of disconnected events that look like provenance but can't be joined into a coherent reconstruction.
TECHNICAL DEEP DIVE & CODE ARTIFACTS Expand [+]

The mental model that works here is less like distributed tracing and more like a ledger: each phase appends a signed entry that records what came in, what decision was made, and what went out. A reranker that demoted a document from position 2 to position 7 is a governance-relevant event — if that document contained a regulatory disclosure, the compliance team needs to know it was deprioritized, not just that it was retrieved. Emitting a structured event at that boundary (with document ID, original rank, final rank, reranker model version, and the score delta) gives you the raw material for both debugging and audit.

AIThe trend toward decomposed observability in LLM pipelines is pushing teams to treat retrieval pipelines the way platform engineers already treat distributed systems: every hop is a potential failure point and a governance checkpoint. Just as you would instrument a microservice boundary with structured logs and correlation IDs, each RAG phase deserves its own event schema — and those schemas should be versioned alongside the pipeline code that produces them.

Reference Architecture
// TypeScript: Phase provenance event emitter for RAG pipelines
import { randomUUID } from 'crypto';

type RagPhase = 'query_rewrite' | 'retrieval' | 'rerank' | 'context_assembly' | 'generation';

interface ProvenanceEvent {
  correlationId: string;
  requestId: string;
  phase: RagPhase;
  timestampMs: number;
  modelVersion: string;
  indexVersion?: string;
  inputSummary: Record<string, unknown>;
  outputSummary: Record<string, unknown>;
  documentIds?: string[];
  rankDeltas?: Array<{ docId: string; from: number; to: number; scoreDelta: number }>;
}

async function emitProvenanceEvent(
  event: ProvenanceEvent,
  sink: (e: ProvenanceEvent) => Promise<void>
): Promise<void> {
  // Append-only — never mutate a provenance event after emission
  await sink({ ...event, timestampMs: Date.now() });
}

// Usage at the reranker phase boundary
async function rerankerPhase(
  candidates: RetrievedDoc[],
  correlationId: string,
  requestId: string
): Promise<RetrievedDoc[]> {
  const reranked = await callReranker(candidates);

  const rankDeltas = candidates.map((doc, idx) => ({
    docId: doc.id,
    from: idx,
    to: reranked.findIndex(r => r.id === doc.id),
    scoreDelta: reranked.find(r => r.id === doc.id)!.score - doc.score,
  }));

  await emitProvenanceEvent(
    {
      correlationId,
      requestId,
      phase: 'rerank',
      timestampMs: 0, // filled by emitter
      modelVersion: process.env.RERANKER_MODEL_VERSION ?? 'unknown',
      documentIds: candidates.map(d => d.id),
      rankDeltas,
      inputSummary: { candidateCount: candidates.length },
      outputSummary: { topDocId: reranked[0].id, topScore: reranked[0].score },
    },
    provenanceSink
  );

  return reranked;
}
State Interaction Chart
sequenceDiagram participant U as User Request participant QR as Query Rewriter participant RET as Retriever participant RR as Reranker participant CA as Context Assembler participant LLM as LLM participant PL as Provenance Ledger U->>QR: raw_query + correlation_id QR->>PL: emit(phase=query_rewrite, input, output, model_ver) QR->>RET: rewritten_query + correlation_id RET->>PL: emit(phase=retrieval, doc_ids, scores, index_ver) RET->>RR: candidate_docs + correlation_id RR->>PL: emit(phase=rerank, rank_delta, model_ver, doc_ids) RR->>CA: reranked_docs + correlation_id CA->>PL: emit(phase=context_assembly, window_contents, token_counts) CA->>LLM: assembled_context + correlation_id LLM->>PL: emit(phase=generation, doc_citations, model_ver, latency)

2. Document Fingerprinting and Immutable Source Records for RAG Governance

If you can't prove that the document your agent cited at T+30 days is byte-for-byte identical to the one in your index at T+0, your provenance log is a liability, not an asset — fingerprint at ingestion and store the hash alongside every retrieval event.

  • Ingestion-time hashing must cover not just the raw document bytes but the chunk boundaries and embedding model version used, because a re-chunking or re-embedding operation produces a semantically different retrieval surface even when the source text hasn't changed.
  • Retrieval events should reference the document fingerprint, not just the document ID — a mutable document store that updates records in place will silently break your audit trail if IDs are stable but content drifts.
  • Version vectors on source corpora let you answer the governance question 'which version of the knowledge base was active when this response was generated?' — critical when regulatory guidance changes and you need to show which agent queries were answered using stale data.
TECHNICAL DEEP DIVE & CODE ARTIFACTS Expand [+]

This is essentially the content-addressable storage problem that Git solved decades ago — every object is its own hash, and the tree of references gives you a complete, tamper-evident history. The challenge in RAG is that most vector stores are not designed with this constraint in mind; they optimize for retrieval speed and mutability, not append-only provenance. The practical path is a dual-write pattern: your ingestion pipeline writes to the vector store for retrieval and to a provenance store (PostgreSQL works well here) that holds the fingerprint, chunk metadata, source URL, ingestion timestamp, and embedding model version.

Source: Inside GitHub's new Git storage architecture — GitHub Engineering (https://github.blog/engineering/architecture-optimization/inside-githubs-new-git-storage-architecture/)

AIGitHub's new storage architecture supporting 5,000 concurrent agents and 7,200 pushes per second is a useful frame here: when thousands of agents are simultaneously reading and writing, the only way to reconstruct what any one agent saw at a given moment is if the storage layer itself maintains immutable snapshots. RAG pipelines operating at scale face the same problem — the knowledge base is a shared, mutable resource, and without snapshot semantics or fingerprint-anchored references, your provenance events describe a world that no longer exists.

Reference Architecture
// TypeScript: Ingestion-time document fingerprinting
import { createHash } from 'crypto';

interface ChunkFingerprint {
  chunkId: string;
  documentId: string;
  contentHash: string;       // SHA-256 of raw chunk text
  chunkBoundaryHash: string; // hash of (start_char, end_char, total_doc_length)
  embeddingModelVersion: string;
  ingestedAt: string;        // ISO8601
  sourceUri: string;
}

function fingerprintChunk(params: {
  documentId: string;
  chunkText: string;
  startChar: number;
  endChar: number;
  totalDocLength: number;
  embeddingModelVersion: string;
  sourceUri: string;
}): ChunkFingerprint {
  const contentHash = createHash('sha256').update(params.chunkText).digest('hex');
  const boundaryHash = createHash('sha256')
    .update(`${params.startChar}:${params.endChar}:${params.totalDocLength}`)
    .digest('hex');

  return {
    chunkId: `${params.documentId}_${contentHash.slice(0, 12)}`,
    documentId: params.documentId,
    contentHash,
    chunkBoundaryHash: boundaryHash,
    embeddingModelVersion: params.embeddingModelVersion,
    ingestedAt: new Date().toISOString(),
    sourceUri: params.sourceUri,
  };
}

// Dual-write: vector store gets the embedding, provenance store gets the fingerprint
async function ingestChunk(
  chunk: { text: string; startChar: number; endChar: number },
  doc: { id: string; totalLength: number; uri: string },
  embeddingModelVersion: string
): Promise<ChunkFingerprint> {
  const fingerprint = fingerprintChunk({
    documentId: doc.id,
    chunkText: chunk.text,
    startChar: chunk.startChar,
    endChar: chunk.endChar,
    totalDocLength: doc.totalLength,
    embeddingModelVersion,
    sourceUri: doc.uri,
  });

  await Promise.all([
    vectorStore.upsert({ id: fingerprint.chunkId, text: chunk.text }),
    provenanceDb.query(
      `INSERT INTO chunk_fingerprints VALUES ($1, $2, $3, $4, $5, $6, $7)
       ON CONFLICT (chunk_id) DO NOTHING`,
      [fingerprint.chunkId, fingerprint.documentId, fingerprint.contentHash,
       fingerprint.chunkBoundaryHash, fingerprint.embeddingModelVersion,
       fingerprint.ingestedAt, fingerprint.sourceUri]
    ),
  ]);

  return fingerprint;
}
State Interaction Chart
flowchart TD A[Source Document] -->|ingestion pipeline| B[Chunker] B -->|chunk_text + boundaries| C[Fingerprinter] C -->|SHA-256 of chunk + model_ver| D{Dual Write} D -->|vector + chunk_id| E[Vector Store] D -->|fingerprint + metadata| F[Provenance Store\nPostgreSQL] E -->|retrieval at query time| G[RAG Retriever] G -->|doc_id + fingerprint_ref| H[Provenance Event] H --> F F -->|audit query: what was seen?| I[Governance API]

3. Secrets Lifecycle Governance for RAG Source Credentials

Every data source your RAG pipeline queries — internal wikis, databases, third-party APIs — has a credential, and if that credential isn't managed with the same lifecycle rigor as the provenance log itself, you have a governance gap that compliance audits will find before you do.

  • Dynamic secrets per retrieval session — where the vault generates a short-lived credential scoped to a single pipeline run — give you retrieval-time access records that are structurally tied to the credential lifecycle, not just logged after the fact.
  • Audit log correlation between your secrets manager and your provenance store closes the loop: if Vault logs a credential issuance at T+0 and your provenance event records a retrieval at T+0 using source X, you now have two independent records that agree — which is what a compliance auditor is actually looking for.
  • Credential rotation events should trigger a provenance checkpoint in your RAG pipeline — any retrieval that spans a rotation boundary needs a flag in the provenance log, because the access policy that governed the pre-rotation credential may differ from the post-rotation one.
TECHNICAL DEEP DIVE & CODE ARTIFACTS Expand [+]

IBM's managed Vault Dedicated service highlights something that agentic pipeline engineers often under-invest in: the credential used to fetch a document is itself governance-relevant metadata. Fine-grained access control and dynamic secret generation aren't just security features — they're provenance primitives. If your RAG agent retrieved a document using a credential that had read access to a restricted data classification, that access event belongs in your audit trail alongside the document fingerprint and the retrieval score.

Source: Introducing IBM Cloud Secrets Manager Vault Dedicated — HashiCorp (https://www.hashicorp.com/blog/introducing-ibm-cloud-secrets-manager-vault-dedicated)

The architectural implication is that your provenance store schema should include a credential_lease_id field on every retrieval event — a reference to the vault lease that was active during that fetch. This costs almost nothing at write time and gives you the ability to answer 'was this retrieval authorized under a credential that has since been revoked or found to be over-permissioned?' — a question that will become standard in enterprise AI governance audits.

Reference Architecture
// TypeScript: Retrieval event with credential lease binding
interface RetrievalProvenanceEvent {
  correlationId: string;
  phase: 'retrieval';
  timestampMs: number;
  sourceUri: string;
  credentialLeaseId: string;      // vault lease active during this fetch
  credentialScope: string;        // e.g. 'internal-wiki:read'
  credentialExpiresAt: string;    // ISO8601
  documentIds: string[];
  documentFingerprints: string[]; // parallel array — fingerprint per docId
  retrievalScores: number[];      // cosine sim or BM25 score per doc
  indexVersion: string;
}

async function retrieveWithProvenanceBinding(
  query: string,
  correlationId: string,
  vaultClient: VaultClient,
  vectorStore: VectorStore,
  provenanceSink: (e: RetrievalProvenanceEvent) => Promise<void>
): Promise<RetrievedDoc[]> {
  // Dynamic credential — scoped, short-lived, lease-tracked
  const { credential, leaseId, expiresAt, scope } =
    await vaultClient.issueDynamicSecret({ role: 'rag-retrieval', ttl: '5m' });

  try {
    const results = await vectorStore.query(query, { credential });

    await provenanceSink({
      correlationId,
      phase: 'retrieval',
      timestampMs: Date.now(),
      sourceUri: vectorStore.sourceUri,
      credentialLeaseId: leaseId,
      credentialScope: scope,
      credentialExpiresAt: expiresAt,
      documentIds: results.map(r => r.id),
      documentFingerprints: results.map(r => r.fingerprint),
      retrievalScores: results.map(r => r.score),
      indexVersion: await vectorStore.currentIndexVersion(),
    });

    return results;
  } finally {
    // Revoke immediately — don't wait for TTL expiry
    await vaultClient.revokeLease(leaseId);
  }
}
State Interaction Chart
sequenceDiagram participant AG as RAG Agent participant V as Vault participant SRC as Document Source participant PL as Provenance Ledger AG->>V: request_dynamic_credential(scope=source_X, ttl=5m) V->>AG: credential + lease_id + expiry V->>PL: emit(event=credential_issued, lease_id, scope, pipeline_run_id) AG->>SRC: fetch_documents(credential) SRC->>AG: documents[] AG->>PL: emit(phase=retrieval, doc_ids, lease_id, fingerprints) AG->>V: revoke_credential(lease_id) V->>PL: emit(event=credential_revoked, lease_id, duration_ms)

4. LLM-Assisted Provenance Log Validation and Anomaly Detection

You can use the same LLM-based analysis that catches security vulnerabilities in source code to scan your provenance logs for retrieval anomalies — unexpected source domains, citation patterns that drift from baseline, or documents that appear in context windows they shouldn't reach.

  • Provenance log scanning with an LLM is structurally identical to code vulnerability scanning: you're asking a model to identify patterns that deviate from expected behavior across a corpus of structured records, and the same prompt engineering discipline applies.
  • Baseline citation profiles per query class give the scanner a reference — if your product FAQ queries normally retrieve from three internal sources and suddenly start pulling from an external domain, that's the kind of signal a rule-based system misses but an LLM prompt can surface.
  • False-positive management is the hard part: LLM-based anomaly detection on provenance logs will flag legitimate retrieval expansions (a new data source was added) as anomalies unless you maintain a change log that the scanner can reference as ground truth.
TECHNICAL DEEP DIVE & CODE ARTIFACTS Expand [+]

Eugene Yan's work on LLM-based source code security scanning makes the case that models are genuinely useful for identifying structural anomalies in code — not because they understand intent perfectly, but because they can hold a large context window of patterns and flag deviations that regex-based tools miss. The same argument applies to provenance log analysis: a well-structured provenance event stream is a corpus of semi-structured records, and an LLM given a window of recent retrieval events can identify when a document fingerprint appears that has never been cited in this query class before, or when a credential scope mismatch suggests an access control misconfiguration.

Source: Using LLMs to Secure Source Code — Eugene Yan (https://eugeneyan.com//writing/secure-source-code/)

The integration point is your CI/CD pipeline for index updates — every time your RAG knowledge base is re-indexed or a new source is added, run a provenance baseline scan against a sample of recent queries. This catches drift before it reaches production and gives your data science team a structured report rather than an after-the-fact audit. The output of that scan should itself be a provenance artifact, stored alongside the events it analyzed.

Reference Architecture
// TypeScript: LLM-based provenance anomaly scanner
const SCANNER_SYSTEM_PROMPT = `
You are a RAG provenance auditor. You will receive a window of structured retrieval events.
For each event, check:
1. Are all document source URIs in the approved domain list?
2. Does the credential scope match the source classification?
3. Are any document fingerprints appearing in query classes they have never served before?
4. Are retrieval scores within expected statistical range for this query class?

Respond ONLY with a JSON array of anomalies. Each anomaly must include:
{ correlationId, phase, anomalyType, severity: 'low'|'medium'|'high', detail }
If no anomalies are found, respond with an empty array [].
`;

async function scanProvenanceWindow(
  events: RetrievalProvenanceEvent[],
  baseline: QueryClassBaseline[],
  llmClient: LLMClient
): Promise<ProvenanceAnomaly[]> {
  const prompt = JSON.stringify({
    events: events.map(e => ({
      correlationId: e.correlationId,
      sourceUri: e.sourceUri,
      credentialScope: e.credentialScope,
      documentIds: e.documentIds,
      retrievalScores: e.retrievalScores,
    })),
    baseline: baseline.map(b => ({
      queryClass: b.queryClass,
      allowedSourceDomains: b.allowedSourceDomains,
      expectedScoreRange: b.expectedScoreRange,
      knownDocumentFingerprints: b.knownDocumentFingerprints,
    })),
  });

  const response = await llmClient.complete({
    system: SCANNER_SYSTEM_PROMPT,
    user: prompt,
    responseFormat: 'json',
  });

  const anomalies: ProvenanceAnomaly[] = JSON.parse(response.content);

  // Store the scan result as a provenance artifact — the scan itself is auditable
  await provenanceDb.query(
    `INSERT INTO provenance_scan_results (scan_id, scanned_event_count, anomaly_count, result_json, scanned_at)
     VALUES ($1, $2, $3, $4, NOW())`,
    [randomUUID(), events.length, anomalies.length, JSON.stringify(anomalies)]
  );

  return anomalies;
}
State Interaction Chart
flowchart TD A[Provenance Event Stream] -->|batch or streaming window| B[Log Aggregator] B -->|structured event records| C[LLM Scanner] C -->|reference context| D[Baseline Citation Profiles] C -->|reference context| E[Source Allowlist] C --> F{Anomaly Detected?} F -->|yes| G[Alert + Artifact Store] F -->|no| H[Baseline Update] G --> I[Human Review Queue] I -->|confirmed legitimate| H I -->|confirmed violation| J[Governance Incident Log]

5. Storage Architecture Decisions for High-Throughput Provenance at Scale

When your RAG pipeline operates at the scale where thousands of agents are retrieving concurrently, your provenance store becomes a write-heavy system that needs the same architectural care as your application database — append-only tables, partition strategies, and async write paths are not optional.

  • Append-only provenance tables in PostgreSQL with time-based partitioning give you the immutability guarantee governance requires while keeping query performance manageable — partition by day, retain hot partitions for 90 days, archive to object storage beyond that.
  • Async event emission via a durable message queue between your RAG pipeline and the provenance store means a provenance write failure never blocks a retrieval — the agent's response path stays clean and you replay failed events from the queue rather than losing them.
  • Multi-instance GPU inference decisions compound the provenance challenge: when the same model runs across multiple GPU instances behind a load balancer, each inference event needs to carry the specific instance and model shard ID, because two responses from 'the same model' may actually come from shards with different weight snapshots.
TECHNICAL DEEP DIVE & CODE ARTIFACTS Expand [+]

GitHub's new Git storage architecture — designed to handle 7,200 pushes per second from concurrent agents — illustrates what happens when you treat write throughput as a first-class architectural constraint from day one rather than retrofitting it onto a system designed for interactive use. The same inflection point is coming for RAG provenance stores. Today, most teams log to whatever database their application already uses; at agent-scale concurrency, that becomes a bottleneck that degrades the retrieval path itself.

Source: Inside GitHub's new Git storage architecture — GitHub Engineering (https://github.blog/engineering/architecture-optimization/inside-githubs-new-git-storage-architecture/)

SageMaker's new multi-instance GPU support adds another dimension: a single model endpoint can now span multiple GPU instances, which means the 'model version' field in your provenance event is no longer sufficient — you need instance ID and potentially shard affinity to reconstruct exactly which compute path produced a given embedding or generation. This is the kind of detail that looks like over-engineering until you hit a model drift incident and realize you can't isolate which shard started producing different outputs.

Source: SageMaker Inference now supports Multi-Instance GPU — AWS Machine Learning Blog (https://aws.amazon.com/blogs/machine-learning/sagemaker-inference-now-supports-multi-instance-gpu-to-maximize-gpu-utilization-for-model-endpoints/)

Reference Architecture
-- PostgreSQL: Append-only provenance table with time partitioning
CREATE TABLE provenance_events (
  event_id        UUID          NOT NULL DEFAULT gen_random_uuid(),
  correlation_id  UUID          NOT NULL,
  request_id      UUID          NOT NULL,
  phase           TEXT          NOT NULL,
  occurred_at     TIMESTAMPTZ   NOT NULL DEFAULT NOW(),
  model_version   TEXT          NOT NULL,
  instance_id     TEXT,          -- sagemaker instance / shard for multi-GPU endpoints
  index_version   TEXT,
  source_uri      TEXT,
  credential_lease_id TEXT,
  document_ids    TEXT[]        NOT NULL DEFAULT '{}',
  fingerprints    TEXT[]        NOT NULL DEFAULT '{}',
  retrieval_scores FLOAT8[]     NOT NULL DEFAULT '{}',
  rank_deltas     JSONB,
  extra_metadata  JSONB
) PARTITION BY RANGE (occurred_at);

-- Create daily partitions (automate with pg_partman in production)
CREATE TABLE provenance_events_2026_11_09
  PARTITION OF provenance_events
  FOR VALUES FROM ('2026-11-09') TO ('2026-11-10');

-- Immutability constraint: no UPDATE or DELETE allowed
CREATE RULE no_update_provenance AS
  ON UPDATE TO provenance_events DO INSTEAD NOTHING;

CREATE RULE no_delete_provenance AS
  ON DELETE TO provenance_events DO INSTEAD NOTHING;

-- Governance query: reconstruct full chain for a given request
SELECT phase, occurred_at, model_version, instance_id,
       source_uri, credential_lease_id, document_ids, retrieval_scores
FROM provenance_events
WHERE correlation_id = $1
ORDER BY occurred_at ASC;
State Interaction Chart
flowchart TD A[RAG Agent Pool] -->|provenance events| B[SQS / Event Queue] B -->|async consumer| C[Provenance Writer\nNode.js] C -->|INSERT append-only| D[PostgreSQL\npartitioned by day] D -->|hot partitions 0-90d| E[Active Query Path] D -->|cold partitions 90d+| F[S3 Archive] A -->|model call| G[SageMaker Multi-Instance Endpoint] G -->|instance_id + shard_id| H[Inference Event] H --> B E -->|audit queries| I[Governance API] F -->|historical audit| I

6. AI-Native Engineering Discipline for Provenance System Design

Building provenance infrastructure for RAG is exactly the kind of problem where AI coding assistants accelerate the scaffolding work — schema generation, event type definitions, query templates — while experienced engineers need to stay firmly in control of the governance semantics that scaffolding encodes.

  • Schema design is governance design — when you use an LLM to generate a provenance event schema, you are delegating a compliance decision to a model that has no knowledge of your regulatory environment, and that deserves the same review scrutiny as any governance-critical code.
  • AI-assisted code review of provenance pipeline PRs should focus specifically on whether new event types cover the full phase boundary, whether correlation IDs are threaded correctly, and whether immutability guarantees are preserved — these are the categories where AI acceleration tends to introduce silent gaps.
  • Context window management in long agentic coding sessions matters here: provenance schema changes have downstream implications for audit queries, partition strategies, and governance APIs, and an LLM that has lost the original schema context will generate migrations that look correct but break the audit reconstruction path.
TECHNICAL DEEP DIVE & CODE ARTIFACTS Expand [+]

Stanford's CS146 curriculum framing — as discussed by Mihail Eric — positions the modern software engineer as someone who must develop judgment about which problems benefit from AI acceleration and which require deep human attention. Provenance system design sits squarely in the second category for the semantics and the first for the implementation. The risk is letting an AI coding assistant generate a 'complete' provenance solution whose event schemas look comprehensive but quietly omit the fields that matter for compliance — credential lease IDs, index version snapshots, rank delta records — because those fields aren't common in public training data.

Source: How Stanford Teaches AI-Native Engineering — Mihail Eric, Monaco (https://latent.space/p/cs146s/)

AIThe pattern that works in practice is treating AI coding assistants the way you treat a strong junior engineer: excellent at implementing a spec, unreliable at writing the spec. For provenance infrastructure, that means senior engineers own the event schema design, the immutability contracts, and the governance query API — and delegate the TypeScript plumbing, the SQL partition templates, and the OpenAPI spec generation to the assistant. The judgment about what a compliance auditor will need to reconstruct in two years is not a code generation problem.

Reference Architecture
// TypeScript: Provenance schema completeness validator
// Run this as part of CI to catch schemas that silently drop governance fields

const REQUIRED_GOVERNANCE_FIELDS: Record<RagPhase, string[]> = {
  query_rewrite: ['correlationId', 'requestId', 'modelVersion', 'inputSummary', 'outputSummary'],
  retrieval: ['correlationId', 'credentialLeaseId', 'credentialScope', 'documentIds',
              'documentFingerprints', 'retrievalScores', 'indexVersion', 'sourceUri'],
  rerank: ['correlationId', 'rankDeltas', 'modelVersion', 'documentIds'],
  context_assembly: ['correlationId', 'documentIds', 'documentFingerprints'],
  generation: ['correlationId', 'modelVersion', 'instanceId', 'documentIds'],
};

function validateProvenanceSchema(
  event: Partial<Record<string, unknown>>,
  phase: RagPhase
): { valid: boolean; missingFields: string[] } {
  const required = REQUIRED_GOVERNANCE_FIELDS[phase];
  const missingFields = required.filter(field => !(field in event) || event[field] == null);

  return {
    valid: missingFields.length === 0,
    missingFields,
  };
}

// Use in CI — fail the pipeline if any phase emitter drops a governance field
function assertProvenanceCompleteness(
  event: Partial<Record<string, unknown>>,
  phase: RagPhase
): void {
  const { valid, missingFields } = validateProvenanceSchema(event, phase);
  if (!valid) {
    throw new Error(
      `Provenance event for phase '${phase}' missing governance-required fields: ` +
      missingFields.join(', ') +
      '. These fields are required for audit reconstruction — do not suppress this error.'
    );
  }
}
State Interaction Chart
flowchart TD A[Senior Engineer\nGovernance Semantics] -->|defines| B[Event Schema\n+ Immutability Contracts] A -->|defines| C[Audit Query API\nSpec] B -->|spec input| D[AI Coding Assistant] C -->|spec input| D D -->|generates| E[TypeScript Event Emitters] D -->|generates| F[SQL Partition Templates] D -->|generates| G[OpenAPI Provenance Spec] E -->|PR review by| A F -->|PR review by| A G -->|PR review by| A A -->|approves if| H{Schema Completeness\nCheck}