Tenderflow
Local AI bid evaluation for public buyers: verified evidence, locked rubric, human sign-off.
- Multi-agent systems
- Document AI
- Role
- Founder and architect, solo
- Client
- Own product idea, no client yet
- Timeline
- May 22 - 31, 2026
- Status
- Prototype
No public screens for this system. The interactive architecture below walks through how it works.
- automated tests in 81 files
- 259
- automated tests in 81 files
- commits in 10 days
- 126
- commits in 10 days
- schema-validated LLM sub-agents
- 6
- schema-validated LLM sub-agents
- lines of production / test TypeScript
- 9,145 / 6,604
- lines of production / test TypeScript
The problem
A public buyer who receives a stack of proposals has to rank them against published criteria, and the ranking has to survive a legal challenge. Done by hand it is slow, inconsistent and hard to audit. Criteria can drift after the bids are opened, and a score rarely points to the sentence that justified it.
An AI evaluator makes this worse unless it is built for it: a model can invent a quote, and a government buyer will not upload confidential bids to a vendor's cloud. The design spec set two hard constraints. Integrity: locked criteria, evidence behind every score, every action auditable. Data sovereignty: evaluation runs on the buyer's machine with the buyer's own model.
Architecture
Seal in the browser
The dashboard seals each bid PDF to the harness's X25519 public key, uploads the ciphertext to Blob and posts a job with its SHA-256. The relay never holds a key that can open it.
- Service
- Data
- AI model
- External
Hard problems I solved
Evidence the model cannot invent
A language model asked to justify a score will sometimes quote a sentence that is not in the bid. In procurement, a score backed by a fabricated quote is worse than no score.
Approach. The scorer must return at least one verbatim quote per criterion under a Zod schema. Code then normalizes case and whitespace and substring-matches every quote against the extracted bid pages. Unmatched quotes are kept, marked verified: false and printed in an 'Unverifiable Evidence (human review required)' section. A later review found these signals were computed but never shown, and added four report sections: unverifiable evidence, conflict-of-interest flags, low-confidence scores and bids needing manual review.
The golden 4-bid road tender test asserts every citation is found in its bid, the non-compliant bid ranks last, the director name match is flagged and the collusion pair is caught.
A rubric that cannot move after bids arrive
Favoritism often looks like criteria that shift once the bids are known. An auditor also needs to replay what happened without trusting the vendor.
Approach. At lock, the rubric is hashed over canonical JSON and the hash goes into the audit chain. assertRubricIntact re-checks it before every scoring run and hard-stops on a mismatch. Each event hashes {prevHash, tenderId, eventType, payload, createdAt} from GENESIS; chain heads are Ed25519-signed and anchored in the cloud through an outbox, and audit-export produces a package an auditor can replay offline.
A human override that never reached the signed report
Overriding a score rewrote one criterion inside the stored score but left the weighted total stale, which corrupted the ranking. Approval then signed the report already on disk, so the reviewer's override never reached the artifact they signed.
Approach. Overrides became append-only score_overridden audit events with {scoreId, score, reason}. The signed report stays the AI's output, and the auditor reconciles it with the human decisions in the chain.
A web UI where the cloud stays blind
Buyers want a browser interface, but the bids must never be readable by the cloud. The browser and the Node harness also have to derive the same key from a passphrase.
Approach. Uploads are sealed in the browser to the harness's X25519 key. Results are encrypted with a data key that the relay only holds wrapped; the browser unwraps it with Argon2id (hash-wasm, in a Web Worker so the 64 MiB derivation does not freeze the page). A parity test proves libsodium in Node and hash-wasm in the browser produce byte-identical 32-byte keys.
An integration test runs browser to relay to harness and back, records every body crossing the relay, and asserts that none contains the passphrase, the vault or data key or a private key, and that no stored blob contains the plaintext bid marker.
Job delivery over serverless HTTP
The spec started with WebSockets, which Vercel discourages. Two daemons could also claim the same job, and a relay 5xx while fetching bid 2 was acked as a permanent error, so the job was lost.
Approach. A 20 s short-hold long-poll behind a contract that lets SSE or WebSockets replace only poll() later. A concurrent-poll gate is one conditional UPDATE that returns 409 and self-heals after 30 s. Transport errors now raise RetryableTransportError and stay unacked for redelivery, while a SHA-256 mismatch remains a non-retryable integrity stop.
Scanned pages and crash safety
Real bids mix text PDFs with scanned pages, and a crash halfway through a bid must not leave half its facts and scores in the database.
Approach. Pages with under 16 characters of text are rasterized at 2x and OCR'd with Tesseract; a bid still unreadable is marked needs_manual_review and excluded, never silently dropped. Per bid, all LLM work finishes first, every write commits in one better-sqlite3 transaction, and only then is the audit event appended. A resumed run skips bids already scored.
Code
The model must quote; code decides whether the quote exists. Unmatched quotes are surfaced to the reviewer instead of being dropped.
function normalize(s: string): string {
return s.toLowerCase().replace(/\s+/g, " ").trim();
}
/** Returns every citation quote that does not substring-match the bid text
* (spec §9b/§10: hallucinated citations are surfaced, not trusted). */
export function verifyScoreCitations(
criterionScores: CriterionScore[],
pages: PdfPage[],
): UnverifiedQuote[] {
const haystack = normalize(pages.map((p) => p.text).join(" "));
const unverified: UnverifiedQuote[] = [];
for (const cs of criterionScores) {
for (const cite of cs.citations) {
if (!haystack.includes(normalize(cite.quote))) {
unverified.push({ criterionId: cs.criterionId, quote: cite.quote });
}
}
}
return unverified;
}export async function evaluateBid(db: Db, generate: StructuredGenerator, input: EvaluateBidInput): Promise<void> {
// All async LLM work first. A crash here leaves nothing written, so the bid
// remains a clean resumable checkpoint (spec §10).
const facts = await runBidParser(generate, { bidId: input.bid.id, pages: input.pages });
const { score, unverifiedQuotes } = await runBidScorer(generate, {
tenderId: input.tenderId, bidId: input.bid.id, rubric: input.rubric, pages: input.pages,
});
const coiFlags = await runCoiChecker(generate, {
tenderId: input.tenderId, bidId: input.bid.id, facts, buyerProfile: input.buyerProfile,
});
// Then commit every write for this bid atomically: a crash mid-transaction
// rolls back, never leaving a partially-written bid.
db.transaction(() => {
saveBidFacts(db, facts);
insertScore(db, score);
for (const flag of coiFlags) insertCoiFlag(db, flag);
updateBidParseStatus(db, input.bid.id, "parsed");
})();
// Only once the bid's data is durably committed do we extend the audit chain.
appendAuditAndEnqueue(db, input.tenderId, "bid_evaluated", {
bidId: input.bid.id, totalWeighted: score.totalWeighted, unverifiedQuoteCount: unverifiedQuotes.length,
}, input.now);
}/** Throws if a rubric is not locked, or if its current criteria no longer hash
* to the anchored value: a hard stop on tampering (spec §9a, §10). */
export function assertRubricIntact(rubric: Rubric): void {
if (rubric.status !== "locked" || !rubric.lockedHash) {
throw new Error("rubric is not locked, cannot evaluate");
}
if (rubricHash(rubric) !== rubric.lockedHash) {
throw new Error("rubric hash mismatch, possible tampering (spec §9a)");
}
}
/** Records the mandatory human sign-off (spec §9e): hashes the final report,
* signs the hash with the harness identity key and anchors the signature. */
export function approveTender(db: Db, signPrivateKey: string, tenderId: string, now: string): string {
const report = getReportByTender(db, tenderId);
if (!report) throw new Error(`no report for tender ${tenderId}`);
const reportHash = sha256Hex(canonicalJson(report));
const signature = sign(signPrivateKey, reportHash);
updateTenderStatus(db, tenderId, "approved");
appendAuditAndEnqueue(db, tenderId, "report_approved", { reportHash, signature }, now);
return signature;
}What I built
Evaluation pipeline
- Six sub-agents: tender drafter, rubric extractor, bid parser, bid scorer, conflict-of-interest checker, report writer
- Deterministic state machine from draft to approved, resumable bid by bid
- Weighted ranking computed in code; the model only writes the narrative
- Pairwise 3-word-shingle Jaccard check across bids flags possible collusion, no LLM involved
Integrity controls
- Rubric hashed over canonical JSON at lock and re-checked before every scoring run
- Every citation substring-checked against the bid text; unmatched quotes go to a human-review section
- SHA-256 audit hash chain per tender; the final approval is Ed25519-signed
- Human score overrides stored as append-only audit events
Local harness
- CLI: init, tender create, tender lock, evaluate, report, approve
- PDF text via pdf.js; near-empty pages rasterized at 2x and read with Tesseract OCR
- SQLite store (11 tables), PDFs kept as encrypted blobs, Argon2id key vault
- Provider adapter for Anthropic, OpenAI or local Ollama; API keys read from env only
Cloud relay and dashboard
- Next.js relay that only ever stores ciphertext and metadata
- Browser seals bid PDFs to the harness's X25519 key before upload
- Device pairing, long-poll job queue, signed audit anchors, 30-day retention cron
- Dashboard: tender wizard, rubric editor, results, score override, sign-off
Stack
Agents
- Vercel AI SDK 6 (generateObject)
- Zod schemas
- Anthropic, OpenAI or Ollama (BYOK)
Local harness
- Node 20
- TypeScript
- better-sqlite3
- pdfjs-dist
- tesseract.js
- pdfkit
Crypto
- libsodium (Ed25519, X25519 sealed box, XChaCha20-Poly1305)
- Argon2id
- hash-wasm
Relay and dashboard
- Next.js 15
- React 19
- Better Auth
- Drizzle ORM
- Postgres 16
- Vercel Blob
Quality
- Vitest
- pnpm workspaces
- Golden-fixture end-to-end tests
How it was built
Built solo and spec-first: three design specs and three implementation plans (about 11.8k lines of Markdown) came before the code, then Claude Code executed the plans task by task with test-driven development while I owned the architecture, reviews and fixes. 38 of the 126 commits carry a Claude co-author trailer. An earlier 2025 prototype for the bidder side was a team effort, mostly coded by teammates, and is not part of this case study.