# Enterprise after-sales Agent — continuous project v1

## Evidence-contract revision 1.0.1 · 2026-10-30

Source selection: the original `enterprise-after-sales-agent-v1.zip` is an immutable baseline. For revision 1.0.1 use the [dated source archive](../../downloads/enterprise-after-sales-agent-evidence-contract-20261030.zip) or the published article patch. Individual unversioned files from this directory must not be mixed with a different archive revision.


This source revision adds `after-sales-evidence-v1`: the model sees the decision-specific evidence requirements, while the runtime derives them again from the current order and selected context. A battery-only manual-review answer needs its actual exception evidence and a real trigger; an eligible proposal still needs general+proof and a bound proposal-tool receipt. Full candidates stay in the local audit; only selected context text reaches the model. The deterministic teaching generator is now v2 and returns unknown if the contract lacks proposal evidence.

The complete local suite passes 79 tests. The same six authored tasks produce v1 5/6 and v2 6/6 under this revision; this is a contract/reference-generator result, not a model accuracy improvement. New provider calls require a fresh explicit allowance; recorded-output replay does not use one. See [EVIDENCE_REVISION.md](EVIDENCE_REVISION.md) for the old/new scope, negative controls and the published repair article. Historical raw provider records are preserved unchanged.

[中文逐块说明](README.zh.md) · [Optional live model run](MODEL_GUIDE.md) · [Architecture](ARCHITECTURE.md) · [Policy exception task](EXTENSION.md)

Start with the fictional return-policy assistant, then carry **one task, `main-return`**, through order access, policy evidence, a return application proposal, human approval, execution, lost-response recovery, evaluation and delivery. Agent state lives in `work/agent.sqlite`; the independent merchant owns `work/merchant.sqlite`. Neither database is a substitute for the other's guarantees. This creates return applications in the local example, never refunds or real merchant transactions.

The default generator is an explicit deterministic teaching model. It computes function calls and answers from actual tool results; it is not measured model quality. `ResponsesModel` implements real HTTP requests and a multi-round function loop when the reader explicitly selects live mode. One authorized provider verification on 2026-10-11 stopped at its first request with HTTP 429; no model response or usage was returned. [LIVE_VALIDATION.json](LIVE_VALIDATION.json) records the actual request and failure. That historical attempt did not verify a live tool loop or model quality. A separate 2026-10-30 baseline and directed repair later made 12 actual provider requests and demonstrated model → tool → continuation, while failing to produce a successful eligible proposal or approved business completion. See [the bounded live record](../live-validation-20261030/README.md) and [directed repair](../../research-evidence/live-validation-20261030/battery-repair/README.md). The current evidence-contract revision has only local historical-output replay, not a new provider run; see [revision validation](../evidence-contract-validation/README.md). These records have different source digests and must not be merged into one success claim. Retrieval is actual authorized **lexical** retrieval; it does not claim vector inference. The older `agent-application-lab-v1.zip` and `agent-reliability-lab-v3.zip` remain separate readable archives.

## 0. Extract and set up

For revision 1.0.1 download [enterprise-after-sales-agent-evidence-contract-20261030.zip](../../downloads/enterprise-after-sales-agent-evidence-contract-20261030.zip), extract it, and enter **`enterprise-after-sales-agent-v1`**, the directory containing `lab.py`. The original v1 archive is only for reproducing its historical baseline. Use Python 3.10+ on macOS/Linux or WSL. Only the standard library is required. The validated bundled runtime is Python 3.12.14 with SQLite; no package installation, model key or cloud account is required for this route. All following commands run in that same directory. A fresh extraction and a fresh `work` directory prevent mixing observations. To repeat, use a new extraction rather than deleting business ledgers.

```sh
python3 --version
python3 lab.py setup
```

Both commands should exit 0. `lab.py` starts and stops a real merchant subprocess for each command, always using the same persistent database. No service remains in the background. A failure writes a safe error and exits 2; an assertion indicating a broken invariant exits 1. The one deliberate fault command below exits **75**. Execute it separately; do not paste it into a shell configured to stop before the recovery commands.

## Before following the route: five prerequisite checks

The route targets developers who can read Python dictionaries/JSON, HTTP requests and a local SQL transaction. It does not teach Python or SQL from zero. Read the **foundation** level of these units before their first use; follow the existing prerequisite links if a check is unfamiliar. Reading order and execution order differ: understanding an idempotency boundary before approval does not mean executing the recovery stage early.

1. `model-response-contract`: identify text, a tool candidate, refusal, incomplete output and an HTTP error. Explain why an HTTP 200 is not a business receipt.
2. `context-budget`: distinguish complete request capacity, output limits and next-round growth. This project's 64,000-byte bound is a local request-size guard, not a tokenizer or fee ceiling.
3. `tool-contracts`: classify shape, business, authority, current-state and receipt gates. Identity comes from a trusted session, not model arguments. Read this before the retrieval stage, even though the main proposal stage is later.
4. `memory-scopes`: distinguish current-task transcript/state from a confirmed cross-task owner preference. Explain why tenant/owner names and a preference cannot grant resource permission. Read this before `memory-write-policy` and revocation.
5. `idempotency-recovery` and `evaluation-design`: draw a committed effect with a lost response, and name the independent receipt and hard outcome checks. Read these foundations before approval/fault injection; their larger exercises remain in stages five and six.

The focused labs are boundary experiments, not pieces to paste verbatim into this application. Their refund amount becomes a **return quantity**, Boolean eligibility becomes `eligible`/`manual_review`/`unknown`, and the local all-in-one authority becomes an independent merchant reached by HTTP. The RAG lab's opened-battery exclusion and this project's mandatory battery safety review are different explicit policies. The memory lab tests diet-event ordering and historical validity; this project only exercises scoped language-preference generation/expiry/revocation. Retain the common invariants, and restate the current business contract before transferring code.

## 1. response — first model/tool round

Read `model-response-contract` and `agent-loop-boundaries`, implementation level. Inspect `model_adapter.py`, `agent.py` and `store.py`.

```sh
python3 lab.py stage response
```

Expected exit 0; `main-return` is `queued`, with **1 model turn and 1 tool receipt**. Save `work/response.json`. Trace the model's `get_order` call, server-bound principal `alice`, resource authorization, matching `call_id` result and persisted next-round input. No proposal or merchant return exists. Tests separately reject refusal, incomplete response, malformed JSON, HTTP failure and invalid calls. Requests/responses in these tests are labeled contract stubs.

## 2. prompt — contract and next round

Read `prompt-output-iteration` and `context-budget`, implementation level. Inspect the strict tool schemas, `ANSWER_SCHEMA`, instructions and cumulative budgets in the same code.

```sh
python3 lab.py stage prompt
```

Expected exit 0; the **same task** remains `queued`, now with **2 model turns and 2 tool receipts**. Save `work/prompt.json`. This round actually calls `retrieve_policy` and saves the result for the next model request. The expected labels in `cases.json` are only read by the evaluator. Model input contains the user's question, current confirmed language preference and actual tool outputs. Maximum totals are 8 model turns, 6 tools and 64,000 input bytes; restarting does not reset these counters.

## 3. retrieval — evidence and scoped memory

Read `rag-pipeline`, `rag-evidence`, `rag-permission-boundary` and `memory-write-policy`, implementation level. Inspect `retrieval.py`, the policy cache and memory generation in `store.py`.

```sh
python3 lab.py stage retrieval
```

Expected exit 0. Save `work/retrieval.json`: authorized candidate ranking, **actual context already used by this task**, top-k-one probe, policy version, source text digests and current scoped memory. The merchant first selects the active tenant policy version; the Agent selects that tenant/version before scoring cached chunks. The main v2 context includes `d-general`, `d-proof` and `d-battery`; the battery task must cite its exception. The tax task has no supporting context and returns `unknown`. Cached cross-tenant or old-version text is not a candidate. Preferences have owner scope, a generation and expiry; they are not order facts or permission grants.

## 4. tool — frozen proposal and explicit approval

Read `tool-contracts`, `agent-security-approval` and `customer-service-action-design`, implementation level. Inspect `Agent.tool`, `Agent.approve` and merchant `check_proposal`/`/v1/approvals`.

```sh
python3 lab.py stage tool
python3 -m json.tool work/main-proposal.json
python3 lab.py approve --proposal-file work/main-proposal.json
```

Run the approval command after reading the proposal. All commands should exit 0. `work/tool.json` proves `awaiting_approval` after **4 model turns and 3 tool receipts** and zero merchant returns. `main-proposal.json` binds `create_return`, order, reason, quantity, policy and memory generation, proposal version and SHA-256. The approve command uses the seeded **reviewer session** to store the exact binding at the independent merchant; `work/approve.json` is `ready`. The 300-second approval lifetime is deliberate. If it expires before stage five, use a fresh route workspace; expired approvals are not silently renewed or bypassed. A local `approved=true`, changed hash/parameters/version or forged approval ID cannot authorize execution.

## 5. recovery — lost response and failure matrix

Read `idempotency-recovery`, `run-state-outbox`, `memory-revocation` and `agent-fault-injection`, debugging level. Inspect `Agent.execute`, service `/v1/returns`/`receipts`, and `drills.py`.

```sh
python3 lab.py fault-main
# Expected exit 75. Run each following command separately.
python3 lab.py inspect-main --out work/lost-response-before.json
python3 lab.py recover-main
python3 lab.py stage recovery
```

`fault-main` makes the merchant commit, **closes the socket without a response**, saves `outcome_unknown`, and terminates the worker process with 75. The fault runner records that exit and also exits 75. `work/fault-main.json` and `lost-response-before.json` must show no local receipt but **one independent merchant return**. `recover-main` waits for the short 0.3-second lease to expire, queries the original operation key, compares the business binding and completes with the original receipt. It does not issue another write. Other commands exit 0.

`work/recovery.json` contains **10 additional drills using this same project, code, databases and task type**: exit after order collection, duplicate requests and changed-key conflict, two actual executor processes with service fencing, cancel before commit, cancel after commit, memory revocation, current-user permission revocation, approval expiry, approval revocation and current-policy version change. Each drill gets a distinct task ID so one scenario's cancellation does not contaminate another. Each record includes a separate authenticated merchant HTTP audit. Successful duplicate/takeover tasks have one return; cancelled/revoked/expired tasks have zero. A denied session cannot change a protected task's local state; its authentication rejection and zero merchant effect are the evidence. Cancelling after success reports `completed_after_cancel` and retains the receipt.

## 6. evaluation — fixed tasks, separate checks

Read `evaluation-design`, `agent-observability` and `agent-release-regression`, debugging level. Inspect `cases.json`, `evaluation.py` and the recorded model/retrieval/tool events.

```sh
python3 lab.py stage evaluation
python3 -m unittest discover -v > work/tests.log 2>&1
cat work/tests.log
```

Expected exits 0. The automated suite has **79 tests**. `work/evaluation.json` runs the same six tasks through v1/v2: ordinary, battery, missing evidence, another user, another tenant and expired window. Expected deterministic mechanical results are **v1 5/6 and v2 6/6**. Only retrieval top-k (1 versus 4) and the prompt version tag change; this is not an isolated prompt experiment or model accuracy. Every row keeps the actual state/decision, error, failed checks, actual context, trace path, measured latency and independent merchant count. Offline usage is labeled simulated character-based units; a live run records returned provider usage or `null` if unavailable. Structure, evidence, permissions and business receipt checks do not grade the full free-form answer. Review each material claim against source text and record unsupported claims separately.

## 7. deployment — API, migration, rollback and submission

Read `harness-contract`, `workflow-schema-upgrade` and `enterprise-agent-design`, design level. Inspect `api.py`, `ops.py`, `migrations/`, `Dockerfile` and `compose.yml`.

```sh
python3 lab.py stage deployment
python3 lab.py extension
python3 lab.py deliver --out work/submission
```

Expected exits 0. `work/deployment/rehearsal.json` proves actual local API processes, an ownership-denied API request, schema 1 → 2 migration, execution, **Agent-only backup restoration to schema 1**, an API restart at schema 1 and receipt reconciliation. The merchant is not rolled back; its business count stays one. It is a local deployment rehearsal, not a production rollout. Container/cloud execution is not claimed by these records.

The gift task in [EXTENSION.md](EXTENSION.md) is a **guided example with a supplied implementation**. Predict its results before reading `extension.py`: it adds a gift exception, rejects the earlier policy-version proposal, returns `manual_review` with `d-gift`, creates zero returns and reruns the unchanged v2 six-task regression. Stages one to seven run the supplied application; they do not establish that you can implement a new business requirement.

For independent implementation, complete the **unimplemented** [opened hygiene item task](HYGIENE_TASK.md) and then run its separate acceptance:

```sh
python3 verify_transfer.py --out work/transfer-review.json
```

The unchanged application is expected to exit **1**, `passed=false`; this is the assignment's red baseline and is separate from the automated regression suite. After your own implementation, all nine mechanical checks must pass and this command exits 0. It separately probes current policy updates, actual evidence, an unsafe model candidate, direct merchant approval/commit, an unopened control and the unchanged six-task baseline. Human review still grades free-text claims and your implementation rationale.

`work/submission` contains the ordinary route's code, migrations, fictional databases, run records, evaluation, deployment records, architecture and file digests. After `deliver`, add `work/transfer-review-runs` as `work/submission/transfer-review-runs`, your before/after acceptance, your own commit/diff, source-backed claim review and incident analysis. The delivery command does not automatically copy the verifier's nested directory. A generated archive or running the provided gift answer is not proof of independent mastery.

## Manual API operation and optional container deployment

For a long-running local entrypoint, use two terminals in a separate workspace. These processes intentionally stay running until Ctrl-C.

```sh
# Terminal A
python3 merchant_service.py serve --db manual/merchant.sqlite --port 8789
# Terminal B
python3 api.py --db manual/agent.sqlite --merchant-url http://127.0.0.1:8789 --port 8790
```

The API accepts the seeded local `alice-token`, `bob-token`, `reviewer-token` and `admin-token`; they are public demo identities, not production credentials. Identity is resolved by the merchant, never model arguments. `GET /health` is public. `POST /tasks` takes `order_id`, `question` and optional `task_id`, `mode` and `prompt_version`. `GET /tasks/{id}` checks ownership. `POST /tasks/{id}/run`, `/execute` and `/cancel` accept `{}`; `/approve` requires reviewer authentication and `{expected_version,proposal_hash}`. For example, in a third terminal:

```sh
curl -sS http://127.0.0.1:8790/tasks -H 'Authorization: Bearer alice-token' -H 'Content-Type: application/json' --data '{"task_id":"api-return","order_id":"o-100","question":"Return my unused item."}'
curl -sS http://127.0.0.1:8790/tasks/api-return/run -H 'Authorization: Bearer alice-token' -H 'Content-Type: application/json' --data '{}'
curl -sS http://127.0.0.1:8790/tasks/api-return -H 'Authorization: Bearer alice-token'
```

For optional containers: `docker compose up --build`, verify both health endpoints, then `docker compose down`. The two services use separate named volumes and loopback host ports. Do not use `down -v` as a rollback: it destroys both ledgers. Container execution requires Docker and a base-image download and was not executed in this release environment. Static seeded sessions, fixed fictional order ages and Python's teaching HTTP server make this a deployable local lab, not a production authentication or availability implementation. Multi-Agent coordination, vector-index migration and real payment/refund integration are optional advanced branches outside this chain.

## Record and explain

For each stage record command/version → input or fault → actual output/receipt → each criterion and failure reason → fix and rerun → unverified items. Explain why the Agent cannot claim business completion from model text, a local checkpoint or an approval flag. Distinguish live HTTP, contract stubs, deterministic generation and actual local merchant effects. The website and miniapp present learning content; all execution happens on your computer/server. In the current miniapp, use the four-stage engineering overview and copy the complete project ZIP link from a core lesson's “Sources and validation scope”, then follow this README on your computer.

Sources: [OpenAI function calling](https://developers.openai.com/api/docs/guides/function-calling), [conversation state](https://developers.openai.com/api/docs/guides/conversation-state). The adapter's persisted output items and matching function outputs follow these contracts. No pricing, account access or unexecuted live result is inferred from these sources.


## Interview exit assessment

Choose the junior/intermediate/senior route in [CAREER_PATHS.md](CAREER_PATHS.md), then use [INTERVIEW_READINESS.md](INTERVIEW_READINESS.md) and project-experience-deep-dive. Keep the common seven stages; individual code, end-to-end change and senior architecture/operations require different evidence. Suggested mocks are 90/120/150 minutes with level-specific weights and required artifacts. Engineering, live API, mock performance and production responsibility remain separate. Teaching thresholds are not employer standards.


## Prerequisites and independent practice
Use the separate [practice package](https://ai.lwkjob.com/downloads/agent-interview-practice-v1.zip), [four prerequisite contracts](https://ai.lwkjob.com/lab/interview-practice/PREREQUISITES.md) and [independent evidence protocol](https://ai.lwkjob.com/lab/interview-practice/INDEPENDENT_PRACTICE.md) before the exit assessment. Local public-case passes and reference recovery do not automatically establish learner transfer, real-provider quality or production experience.
