Building Enterprise Agent Architecture: AI Coding, Ontology & Harness from Prototype to Production
The article presents a practical enterprise AI agent architecture combining AI Coding for prototyping, Ontology for business modeling, and Harness for execution orchestration, demonstrated through an invoice exception handling case study covering investigation, waiting, idempotency, and evaluation.
Reading font
Overall Architecture
The architecture centers on four components: AI Coding, Ontology, Harness, and Runtime with task workflows, supported by Forward Deployed Engineers (FDE). AI Coding implements code from business specs and runs checks. Ontology defines business objects, relationships, and action semantics so data across systems can correspond. Harness prepares context, calls models and tools, and processes feedback to organize each agent round. Runtime provides execution environment, persistent state, and scheduling for pause, resume, and follow-up. FDEs work on-site to connect requirements, integration, validation, and handover.
At runtime, a user request to follow up an invoice enters the task workflow which logs goal and progress. When investigation is needed, Harness organizes the model to call tools reading procurement, warehousing, and finance records. The agent finds missing goods receipts, returns evidence and suggestions, and the workflow creates a to-do item with wait conditions. After the warehouse adds the receipt, the workflow re-checks conditions, optionally invokes the agent again, and finally submits the payment application via the business interface.
The author emphasizes: leave investigation paths to the agent, keep formal action validation in business services, and hand cross-round follow-up to the persistent workflow. Investigation may need multiple directions, but approval and amount rules already have owning systems; waiting a day cannot rely on a chat transcript alone.
Task Boundary
The example task: a finance clerk asks why an invoice cannot be paid and requests follow-up until a payment application is created. This splits into investigation (reading invoice, purchase order, goods receipts, emails) and business push (warehouse data entry, finance approval, application submission). The first version scopes to one legal entity, one purchase type, one invoice linked to one purchase order, stopping at payment application created . Actual payment is handled by downstream finance processes. Merged invoicing, partial payment, and credit notes are left as manual branches for later.
A concrete spec is written:
Input: current user identity, invoice number
Investigation: read related documents, explain blocking reason, attach evidence IDs
Follow-up: create to-do when material missing, record assignee and wait condition
Execution: create payment application when material satisfies rules and formal approval valid
Completion: finance system returns valid application number, key fields match
Handover to human: documents cannot be linked, evidence conflicts, or submission result unconfirmed"Valid approval" means an existing approval flow has authorized this application content; if approval happens after creation, adjust the workflow to treat "create pending-approval application" as the stage result. Confirm the real sequence with business people first so the state machine has basis.
FDEs participate by shadowing finance on historical exceptions, tracing to warehouse and procurement systems, confirming who enters data, who decides, and which results are queryable. They cross-check the spec against actual processes to quickly find gaps.
AI Coding: Prototype Validation
With the spec, a Coding Agent first builds a read-only investigation: input invoice number, return related documents, exception explanation, and evidence. Desensitized samples and mocked interfaces get the page-to-result path working. Materials given to the Coding Agent include existing service interface docs, auth methods, sample responses, business rules, and check commands so generated code integrates easily.
First prototype samples cover three cases: normal match, missing goods receipt, invoice amount mismatch with purchase order. Each sample has expected output. For "missing goods receipt", the agent should state insufficient evidence, suggest warehouse verification, and attach found documents — not conclude "goods not arrived".
These expected behaviors form the Spec-Driven Development (SDD) starting point. Deterministic logic like amount comparison, identity check, field mapping uses Test-Driven Development (TDD): write a failing test, let the Coding Agent implement to pass, then refactor under test protection. Whether the model finds causes or hallucinates is evaluated repeatedly with fixed tasks and sample data. The same business spec constrains both code and agent behavior; passing unit tests does not mean the whole business task works correctly.
OpenAI's "Harness Engineering" describes a similar division: engineers clarify intent, organize repo knowledge, build feedback environments so agents see application, logs, and check results. In this prototype, after the Coding Agent changes an interface, it runs samples, opens the page, sees actual issues like "evidence ID not displayed", and continues fixing.
A short AGENTS.md in the repo points to the business spec, interface contracts, and test entry. When business rules change, update the spec and samples; code follows. Subsequent development reads the same conventions from the repo, reducing repeated explanations and drift.
Integration order follows dependencies: first run investigation with samples, then replace with real read-only interfaces in test env, verify return semantics, finally add write operations. Mocked interfaces prove the code path works; real system permissions, data latency, and error returns must be verified one by one during integration. At this stage, the most common exposure is business meaning: the same field in two systems may mean completely different things.
Ontology: Business Modeling
Example: "Completed" in procurement may mean procurement process ended; in warehousing it may mean goods fully received. Mapping both to completed makes the model's view blurrier.
Ontology here solves: what business objects exist, how they relate, which states and actions matter for this task. Palantir's official definition places Ontology on top of existing data assets, including objects, properties, relationships, actions, functions, and dynamic security. Borrowing for your own system, start with a small model around the invoice task, no need to cover the whole enterprise initially.
First-version objects and required details:
Invoice : legal entity, supplier, amount and currency, valid status, linked purchase order
Purchase Order : line items, quantity, pricing basis, change version
Goods Receipt : corresponding PO line, actual received quantity, confirmation status and time
Approval Record : approved application content, current status, applicable version
Payment Application : business ID, linked invoice, applied amount, processing status
Objects link via stable IDs. Supplier name can retrieve candidates, but executing actions must resolve to master data IDs and their system mappings. Two similarly named suppliers cannot be merged just because the model "thinks they're the same".
Relationships must be concrete. Invoice links to PO, PO lines link to receipt lines; quantity reconciliation needs to know if units match. Amount comparison must specify tax-inclusive vs exclusive, currency same or not. If conversion isn't handled in v1, return non-directly-comparable cases for human confirmation.
Check the model with business questions: which documents link to this invoice? What's missing? Who can fill it? After filling, which action is allowed? If every question traces through objects, relationships, and rules to an answer, the model serves the task.
AI can draft objects, field mappings, and rules from interface docs; business owners confirm with samples. The model may suggest "completed equals payable", exposing the exact definition needing verification; it cannot approve that mapping itself.
Implementation can start with database views, typed object structures, and domain services. When cross-source formal semantics exchange or logical reasoning is needed, evaluate RDF, OWL, etc. For v1, being able to traverse object relations to find data and trigger actions by explicit conditions already gives verifiable utility.
This continues the earlier "Ontology First" discussion: RAG queries regulations and emails, MCP provides tool access, business object model explains IDs, relationships, and action meanings. An email saying "goods delivered" and a formal goods receipt record are different evidence types in this model.
Tools: Queries and Actions
With clear object relations, tools are designed around "investigate this invoice". Exposing all procurement, warehousing, finance interfaces directly forces the model to find supplier, then PO, then paginate receipts, then stitch fields — much of which has deterministic rules that can be pre-packaged into query services.
Example: get_invoice_context(invoice_id) reads invoice and related docs within current user permissions, returns fields needed for this investigation, evidence IDs, update timestamps per source, and parts still unknown. For large data, provide line-item query tools to avoid dumping all history into context.
Anthropic's tool design article discusses this: design few tools around valuable workflows, compose multiple API calls inside tools when needed, return task-relevant info; more tools don't automatically yield better results.
This query tool must distinguish three return types: truly no record, currently no permission, upstream query failed . If timeout returns empty array, the model easily concludes "no receipt". When returning multi-source data, indicate which queries succeeded and which haven't; they usually aren't a single transaction snapshot.
Supplier emails can enter results as clues, but embedded instructions cannot change tool permissions or approval rules. Execution identity comes from service-side auth context; a user ID passed by the model cannot decide "act as whom".
Write actions are designed around explicit business intent, e.g., create_payment_request. Interface contract (field names illustrative):
Model proposes: invoice number, applied amount and currency, application basis
Execution layer adds: authenticated identity, stable operation ID, versions to verify
Business service validates: permission, document validity, amount rules, applicable approval
Success returns: application ID, actual amount and currency, current status
Other returns: condition changed, no permission, business rejected, result pending confirmationThe model may suggest amount; business service still validates by its own rules. Approval, version, and operation ID are verified or generated by execution layer — not accepted just because the model wrote "approved" in parameters.
Palantir's Action Types similarly include parameters, mutation rules, submission conditions, and side effects in action definitions. Ontology-internal transaction semantics cannot be directly extrapolated to atomic commits across multiple external systems; your own finance interface guarantees must be confirmed separately.
Now business objects have become query and action interfaces the agent can use. Next, see how Harness organizes these calls and who continues after one round.
Harness: Organizing Execution
One investigation can start as a simple loop: read task and necessary context, call model; model requests tools, program validates and executes, returns results to model; until investigation conclusion, need for human input, or round budget reached.
Harness is the surrounding program that organizes input, model calls, tool execution, and result processing. Harrison Chase's long post separates business logic, Harness, and runtime infrastructure, listing post-interruption recovery as a production issue.
Runtime leans toward execution support: where executors start, how run state is saved, how to reschedule after process exit, how to provide isolated env for code execution. Frameworks differ in naming and coverage of Harness vs Runtime. In this design, Harness organizes the current round; persistent storage and scheduling support subsequent execution; business task workflow defines when to wait, continue, or end.
V1 can keep one investigation agent with a set of query tools and controlled actions. Components pass task ID, document IDs, structured results; page shows explanation and progress. Existing workflows, databases, executors that can handle parts can be reused directly — no need to build a separate platform for each name.
This division also decides context preparation. Each round carries task goal, current phase, valid rules, relevant evidence; full documents, long emails, historical tool logs fetched on demand. Analysis summary retains "what evidence missing, why stopped last time"; external state is re-queried to avoid yesterday's receipt count becoming today's default fact.
Model version, prompt version, tool version, round duration, and exit reason saved with run records. When a query fails, you can tell if investigation strategy changed, tool response changed, or upstream interface unavailable. Log task IDs link model calls to business requests.
Stop conditions in Harness: max tool calls, round time and cost budget, consecutive no-progress count. On limit, save evidence and unfinished items, hand task back to workflow. Need to wait for warehouse a day? Register wait condition, end this execution.
This shares similarities with R&D Harness Engineering: both give agents usable tools, context, feedback. But R&D Harness faces code repos, tests, PRs; production business agent Harness faces invoices, permissions, business actions. Credentials and executable operations configured separately per environment.
When tasks grow, consider multi-agent. If contract terms and email threads are long, need different tools, independent contexts, and can investigate separately, split into subtasks; just querying three deterministic interfaces concurrently, normal program parallel calls suffice.
After splitting, agree on aggregation. Each subtask carries the same invoice business ID, returns conclusion, evidence, source timestamps, unknowns. Main agent or task workflow aggregates; evidence conflicts trigger re-query or human handoff; subtask failure clarifies which conclusions lack basis. Formal write actions still go through unified entry. This adds call, wait, coordination overhead — compare with same task set to confirm it actually improves investigation quality or latency before keeping the split.
Waiting and Recovery
Suppose investigation result: current goods receipt insufficient, supplier email claims delivery, need warehouse verification. System creates to-do, saves assignee, linked documents, next check time, then waits.
Three record types answer different questions:
Business facts : actual received quantity, approval validity — per the system owning that business
Task progress : waiting for whom, next check time, which action result unconfirmed
Analysis records : what was queried, basis, suggestions given
They can live in existing platforms, linked by IDs, no need for three new services. Chat saying "notified warehouse" still needs an actual to-do ID so next round knows where to query.
Warehouse adds receipt next day; event wakes task. If no event interface, poll on schedule. On resume, re-read receipts, PO, and application status first. If only quantity filled, program re-checks conditions; if PO amount also changed, pass changes and original investigation to agent for analysis. Re-querying facts is the recovery starting point; whether to re-reason depends on what changed.
LangGraph can use checkpointer to save graph state, with persistent storage in production. If company already has a workflow system managing this business, let agent be one step; if LangGraph manages the whole task, it handles wait and resume. Same business progress must have a clear owner.
Integration detail: LangGraph resuming from interrupt() re-executes from node start. Putting "create to-do" and "wait for human" in one node risks creating duplicate to-dos on resume. Split steps, save IDs, and make the create operation itself idempotent.
External approval cannot rely on resume messages. LangGraph docs explicitly state: out-of-graph approval should re-query external task state. A human "ok" can trigger a check, but formal approval result still comes from business system.
Duplicate or late events: deduplicate by event ID, then verify current task phase and record version. Task already completed? Don't revert to wait because of an old notification. Add scheduled reconciliation to plug gaps — neither requiring events never lost nor letting model spin idle.
Idempotency and Result Confirmation
When material and approval satisfy conditions, system prepares to create payment application. On submit, business service re-checks permission, related versions, valid approval; for its own data, uses conditional write or transaction to bind validation with creation, preventing condition change after query passes. Cross-system facts remain constrained by each interface; must agree on version, validity period, or re-confirmation method — cannot treat one pre-query as a common lock across all systems.
Assume request times out. Application may not have been created, or created but response lost. Task enters "result pending confirmation", queries along this operation's ID, cannot just mark failed and submit a new application.
AWS Builders' Library on idempotent APIs discusses this: caller uses stable request ID to express same intent, service recognizes retry and returns semantically equivalent result. Applied here, retry of same application reuses original ID, key parameters stay consistent.
Receiver must actually implement deduplication: define ID scope, retention period, how to reject same ID with different parameters. Consistency between deduplication record and business write is service-side responsibility. Adding a UUID to the request alone does nothing.
If application content changed, first clarify old request result, then amend or revoke per business rules; cannot bypass an unconfirmed application by switching IDs. When legacy interfaces lack reliable query and deduplication, keep such write actions for human confirmation while pushing service improvements.
After finance system returns application ID, still verify linked invoice, amount, currency, then write result back to task. If process exits just before write-back, on resume still query by original operation ID. Rolling back local checkpoint won't auto-revoke remote application; revocation calls corresponding business flow.
User should see concrete progress: "Payment application created, ID ..., currently in ... status." Model can add reason explanation; completion state comes from business receipt. Post-creation approval, payment, or receipt follow the enterprise's actual processes.
Evaluation and Regression
The three prototype samples only covered normal match and two anomalies. After adding wait, approval, and write operations, evaluation must expand: besides checking if cause found correctly, also verify recovery doesn't use stale data, submit doesn't create duplicate applications.
Anthropic's agent evaluation article distinguishes run records from final environment results: agent says booking done doesn't mean DB has valid booking. Chip Huyen separates planning failures, tool failures, efficiency, warning about agents thinking they're done when they're not.
Following the invoice task, add these evaluation samples:
Email claims delivery, system has no receipt → states evidence gap, initiates verification, doesn't fabricate receipt
Query timeout or no permission → returns corresponding reason, doesn't interpret as no business record
PO price changes during wait → re-validates against current version, handles original approval per rules
Same event delivered twice → doesn't create duplicate to-do or payment application
Application succeeds but response lost → retrieves existing application, doesn't blindly resubmit
Human already handled manually → verifies current state and ends or adjusts task, doesn't execute stale action
Document linking, state transitions, permissions, idempotency mainly verified by deterministic tests and fault injection; cause explanation accuracy and evidence sufficiency combine business-annotated samples and model evaluation. Model review helps check phrasing; duplicate applications in DB checked by querying system results directly.
Each sample needs fixed input, initial data, success criteria; test data restored between runs. Model behavior varies; same task can run repeatedly, keeping each tool trace and result. Evaluation focuses on correct completion and constraint adherence, not forcing identical query order every time.
Development samples for prompt and tool tuning kept separate from final hold-out samples. Stable capabilities enter regression; after model swap, tool description change, or business rule update, compare with same task set. Human spot-check adds business meaning auto-scoring misses.
Field feedback also changes samples and implementation. Example: business says "receipt already entered, just sync delay." Fix may be adding source update timestamp, adjusting query location and wait strategy — not just telling model "look more carefully".
Another example: same supplier has different IDs in two systems. Fix may be improving supplier ID mapping and adding a linkage test. Interface errors wrapped as empty results → fix tool return; approval meaning misunderstood → fix business rules and descriptions. These changes plus regression samples stay in project so next delivery doesn't need verbal re-explanation.
FDE: On-Site Delivery
If procurement, warehousing, approval, finance systems exist, v1 reuses their fact records and action interfaces. New parts kept small: one business adapter module, a set of agent tools, one investigation agent, and a persistent task workflow. Deployment can start with one service and one database; model calls and existing business systems connect via interfaces.
Delivery can be incremental. First read-only investigation, let business compare causes and evidence. Then shadow run generating handling suggestions, original process continues normally, compare differences. This phase keeps real write operations closed to avoid "shadow" tasks creating documents.
After investigation stabilizes, open human-confirmed write operations. System validates formal approval and request content per earlier agreements before submitting; then expand automation only for task types with clear rules and sufficient evaluation. Every scope expansion needs corresponding samples and a rollback-to-human path.
On-site work includes defining human takeover: page shows blocking cause and obtained evidence, allows authorized person to pause, take over, or cancel subsequent tasks. Already-sent business requests still need result verification; clicking cancel cannot make in-flight applications vanish.
After model, prompt, or tool version updates, enable in small task scope first, compare with old version. On anomaly, stop new auto writes first, hand unfinished tasks back to human, then handle version rollback; already-submitted applications continue result verification. Restoring program version and revoking business actions handled separately.
Worth observing beyond model correctness: per-exception handling time, human takeover count, duplicate or invalid operations, invocation cost per task. If time mainly spent waiting for warehouse entry, improving to-do dispatch and resume timing often beats further reducing single model latency.
Handover to maintenance team should leave usable materials: business scope and exceptions, object and action conventions, interface and permission configs, task states and human takeover methods, evaluation samples and run entry points. Customer-specific ID mappings, approval rules, system addresses configured separately; capabilities verified across multiple engagements extracted for reuse.
V1 gets one invoice from stuck to application created, explaining every step's basis. When expanding to more business later, whether to add object relations, change tools, increase parallel investigation, or improve human collaboration — there will be actual records to judge.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.
Published
AI-assisted summary