> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# Unified Pipeline Reference Checklist

> **当前状态**: Reference / checklist。Canonical 入口请读 [Unified Pipeline Architecture 设计 Brief](/product-design/v2/unified-pipeline/research/unified-pipeline-design-brief.md)。本文件保留的是早期 execution checklist 和调研任务拆法，不再作为主 brief。
> **注意**: 本文件早于 Call/SMS `Processing Capability / Invocation Module` 的最新表述；如果和 canonical brief 不一致，以 canonical brief 为准。
> **日期**: 2026-05-31\
> **用途**: 给下一轮 design / research session 使用的任务 brief。这个文件不是最终架构结论，也不是 bug fix list。\
> **核心问题**: 从 task pipeline 设计扩展到整个系统，重新审视 call / SMS / lead / contact analysis / task 这些 pipeline 的职责边界、schema/API 设计、prompt 边界，以及未来 tool calling / AI agent 的兼容方向。\
> **重要约束**: 先调研和设计，不直接改代码。所有结论必须回到 live code、schema、现有 prompt 和 API route 验证。

***

## 我对这次目标的理解

这次不是“把 task pipeline 继续细化一下”，而是从 task pipeline 暴露出来的问题往外看整个系统。

你现在看到的问题是：

1. task 只是其中一个 business object，但它和 contact、call、lead、message、timeline 都互相影响。
2. 现在每条 pipeline 都有自己的写入逻辑、AI 调用方式、prompt 边界和状态处理方式。
3. 如果只设计 task，不统一看其他 pipeline，以后每加一个 workflow 都会重新讨论一次“哪些由 code 做，哪些由 prompt 做，哪些 schema/API 要改”。
4. 现在是 one-time AI call 模式，但未来可能会需要 tool calling / voice agent / interactive AI agent，所以现在的后端抽象不能把未来堵死。
5. 这次真正要产出的不是“马上做 agent”，而是先把 task、contact、content/message、call、lead 这些基础对象的职责分清楚。

一句话：**先把现有系统的 schema、pipeline、prompt、API 和 code-vs-AI 职责边界梳理清楚，再设计 Phase 1 应该落地的共享抽象。**

***

## 这次要交付什么

最终 deliverable 应该包含以下内容。

### 1. Schema / DB Contract Check

先调研现在 schema 是什么样子。这里的“数据库现在是什么样子”和“schema 是什么样子”基本可以当作一件事，因为项目的 source of truth 是 `callytics-common/src/db/schema/`。只有发现 migration drift 或线上疑点时，才需要额外查 live DB。

需要覆盖：

| Object / Table                  | 要检查什么                                                                             |
| ------------------------------- | --------------------------------------------------------------------------------- |
| `contacts`                      | lifecycle、`actionNeeded` / `suggestedActions` 语义、name trust、DNC、last activity、谁能写 |
| `tasks`                         | lifecycle、`status`、`closeResult`、`typeCategory`、priority、due date、dedup 约束、谁能写    |
| `contact_timeline`              | 是否是 audit log、是否是 projection、event type catalog 是否完整                              |
| proposed `task_progress_events` | 是否需要成为 task progress 的 source of truth，和 `contact_timeline` 怎么分工                  |
| `calls`                         | call state / disposition / AI analysis result 和 task progress 的关系                 |
| `messages`                      | SMS lifecycle、STOP/DNC、meaningful reply、是否触发 contact analysis                     |
| `leads`                         | lead 和 contact 的 merge 规则、lead task 创建规则                                          |
| store / tenant fields           | `storeId` / `store_id` null 行为、多门店隔离、跨 store phone 去重规则                           |

输出形式：

- 每个 object 的职责一句话定义。
- 当前 schema 是否支持这个职责。
- 哪些字段语义混了。
- 哪些 enum 值应该拆分或迁移。
- 哪些表缺 source-of-truth 字段或事件表。

### 2. Current Design / Prompt Inventory

不能只看 task doc，要把现在已有 pipeline 和 prompt surface 都列出来。

需要调研：

| Area                  | 要列出的内容                                                                                  |
| --------------------- | --------------------------------------------------------------------------------------- |
| Active pipelines      | call analysis、contact analysis、SMS/message、lead、analytics、manual API                    |
| Prompt surfaces       | per-call triage / classify / verify / coaching、contact-analyzer prompt、任何 legacy prompt |
| Code-only rules       | pre-triage、STOP keyword、DNC cascade、lead task creation、manual task close                |
| AI structured outputs | 每个 prompt 输出什么 JSON，谁 validate，谁 execute                                                |
| Shared writers        | 哪些地方直接写 `contacts` / `tasks` / `contact_timeline`                                       |

这里不要只数“有几个 prompt”。更重要的是回答：

- 每个 prompt 负责做什么 judgment？
- prompt 输出的是最终状态，还是 action proposal？
- code 有没有 validation / policy gate？
- prompt 有没有承担了本该由 schema/API/code 负责的东西？

### 3. Current Workflow Diagrams

必须画现状图，而且图要围绕 **Code vs Prompt 的职责划分**，不是围绕“数据存在哪张表”。

每个节点都要标清楚：

- `[Code]` deterministic rule / trigger / validation / writer
- `[Prompt]` semantic judgment / classification / generation
- `[Hybrid]` AI proposes, code validates / executes
- `[Shared Code]` future shared module boundary

现状图至少要有两张：

1. **Current state**: 现在各 pipeline 各自写、各自调用 AI、各自决定 state。
2. **Target state**: pipeline 只负责 trigger/context/AI proposal，共享 writer/orchestrator 负责状态转换和写入。

示例方向：

```mermaid
flowchart TD
  CallWebhook["[Code] RC call webhook"] --> CallPipeline["[Code] call pipeline"]
  CallPipeline --> P1["[Prompt] triage / classify / verify / coaching"]
  P1 --> CallWriter["[Code] writes calls + contacts + timeline"]

  MessageWebhook["[Code] SMS webhook"] --> MessagePipeline["[Code] message pipeline"]
  MessagePipeline --> StopRule["[Code] exact STOP rule"]
  StopRule --> MessageWriter["[Code] writes contacts + timeline + closes tasks"]

  LeadEvent["[Code] lead created event"] --> LeadProcessor["[Code] lead processor"]
  LeadProcessor --> LeadWriter["[Code] writes contacts + lead_outreach task + timeline"]

  ContactBatch["[Code] contact analysis trigger"] --> ContactPrompt["[Prompt] contact-analyzer"]
  ContactPrompt --> TaskDecision["[Hybrid] taskDecisions[]"]
  TaskDecision --> ContactWriterNow["[Code] writes contacts + tasks + timeline"]
```

```mermaid
flowchart TD
  PipelineTrigger["[Code] pipeline trigger"] --> ContextBuilder["[Code] context builder"]
  ContextBuilder --> AIProposal["[Prompt] semantic judgment / action proposal"]
  AIProposal --> PolicyGate["[Code] schema validation + policy gate"]

  PolicyGate --> ContactWriter["[Shared Code] Contact Writer"]
  PolicyGate --> TaskOrchestrator["[Shared Code] Task Orchestrator"]
  PolicyGate --> TimelineWriter["[Shared Code] Timeline Writer"]

  ManualAPI["[Code] Studio API"] --> PolicyGate
  FutureTool["[Future Tool] create_task / update_contact"] --> PolicyGate
```

### 4. Target Workflow Design

设计目标 workflow 时，不要从“新增几张表”开始，要从业务动作开始：

- 一通 call 结束后，系统应该如何更新 contact、call insight、task progress？
- 一条 SMS 到达后，哪些情况 code 立即处理，哪些情况触发 AI？
- 一个 lead 创建后，什么时候创建 task，什么时候合并 contact？
- 一个 task 关闭后，哪些结果是真 outcome，哪些只是 progress？
- 一次 retry / onboard / batch re-analysis 应该复用哪些模块？

每个 workflow 要写清楚：

- trigger 是什么。
- context 从哪里来。
- AI 是否参与，参与哪一步。
- code 必须执行哪些 guardrail。
- 最后调用哪些 shared module。
- 是否产生 audit event。

### 5. Schema / API Check

需要从未来 API 和 AI agent 的角度反推现在的数据模型。

要问的问题：

| 视角                   | 要检查的问题                                                                           |
| -------------------- | -------------------------------------------------------------------------------- |
| Human UI             | 前台员工需要看到的是 task、contact summary、timeline，还是混在一起的 action list？                    |
| Backend API          | 是否有清晰 API 表达 `create_task`、`record_task_progress`、`close_task`、`update_contact`？ |
| AI structured output | AI 输出的是 business decision，还是直接输出 DB 字段？                                          |
| Future tool API      | 如果未来注册 `create_task` tool，它能否直接调用 Task Orchestrator？                             |
| Voice agent          | 如果以后 voice agent 调 tool，是否能复用同一套 tenant-scoped API？                              |
| Audit / replay       | 能否解释“为什么这个 task 被创建 / 关闭 / 延后”？                                                  |

重要原则：

**AI 不应该直接“写数据库”。AI 应该提出 action proposal；code 用 schema、policy、idempotency 和权限检查后执行。**

这也是这次设计里 `Code as Guardrail, AI as Judgment` 的核心。

### 6. One-time AI Call + Code Orchestration vs Tool Calling

这次必须明确比较当前模式和未来模式，但结论不应该默认“马上上 tool calling”。

| 维度    | One-time AI call + code orchestration                      | Tool calling                                  |
| ----- | ---------------------------------------------------------- | --------------------------------------------- |
| 信息获取  | code 预先聚合 context 后一次性给 AI                                 | AI 按需请求 tool 获取 context                       |
| AI 输出 | structured JSON proposal                                   | tool call requests + final answer/proposal    |
| 执行权   | code validate + execute                                    | backend tool validate + execute               |
| 成本    | 可预测，适合 batch                                               | 多轮调用，成本和 latency 更难控                          |
| 适合场景  | daily batch、contact analysis、call analysis、lead processing | interactive diagnosis、voice agent、复杂问答、未知查询路径 |
| 当前必要性 | Phase 1 应优先做好                                              | 先兼容，不急着实现                                     |

需要讲清楚：

- `tool calling` 不是让 AI 随意操作数据库。
- model 只是返回 `tool_calls`，真正执行 tool 的还是我们的 backend。
- OpenRouter 的 tool calling 文档说明的是接口模式，不等于我们要把 backend 改成 agent runtime。
- Pi.dev 更像 coding-agent / development harness 方向，不能直接当作 Retaintive backend runtime 的结论。
- 如果 Phase 1 的 shared modules 设计正确，以后 tool 只是这些 modules 的另一层入口。

判断是否需要 tool calling 的标准：

| 问题                                                            | 如果答案是 yes，才更适合 tool calling |
| ------------------------------------------------------------- | --------------------------- |
| AI 是否无法预先知道需要哪些数据？                                            |                             |
| 是否是 interactive / user-in-the-loop 场景？                        |                             |
| 是否需要多轮查询、比较、解释？                                               |                             |
| 是否能接受更高 latency 和更难预测的 cost？                                  |                             |
| 是否已有 tenant-scoped tool API、audit、budget cap、permission gate？ |                             |

Phase 1 的建议默认是：

**先保留 one-time AI call，但把 AI output 变成更严格的 action proposal，并通过 shared modules 执行。**

### 7. Phase 1 Plan

最终必须产出一个 Phase 1，不要只写长远愿景。

Phase 1 应该聚焦：

1. **Task Orchestrator contract**
   - 支持 `create` / `update` / `close`。
   - 评估是否需要 `record_progress` / `create_closed`。
   - 拆清 `closeResult` 中 progress-like value 和 true outcome。
   - task 写入和 task timeline/progress event 原子化。

2. **Contact Writer contract**
   - 集中 name trust 逻辑。
   - 集中 DNC、lastActivityAt、lifecycleStage 的 policy。
   - 所有 writer 都必须声明 source / trust / actor。

3. **Timeline Writer contract**
   - 统一 event catalog。
   - 定义 payload schema。
   - 支持 idempotency key。
   - 明确和 `task_progress_events` 的关系。

4. **Prompt output schema cleanup**
   - contacts-analyzer 不直接表达 DB patch。
   - AI 输出 business action proposal。
   - code 层做 Zod / JSON Schema validation、policy gate、idempotency。

5. **API alignment**
   - Studio API 的 manual close / task list / contact update 要和 shared modules 对齐。
   - UI 上的 task progress 和 final outcome 要拆开。

6. **Concrete workflow coverage**
   - call retry。
   - new store onboard historical scan。
   - SMS meaningful reply trigger。
   - prompt update 后 batch re-analysis。
   - lead created downstream processing。

***

## 我认为容易漏掉的点

下面这些是我觉得你现在已经意识到一部分，但 brief 里必须强制检查的盲区。

### 1. Trigger / re-entry path 可能比 pipeline 数量更重要

不要只数“有几条 pipeline”。同一套逻辑可能从很多入口进来：

- cron batch
- SQS event
- EventBridge event
- manual API
- retry button
- onboarding backfill
- prompt migration backfill
- future AI agent tool call

如果 shared module 只适配 daily batch，不适配 retry / backfill / manual API，那以后还是会重新复制逻辑。

### 2. `closeResult` 里混了 progress 和 outcome

task deliverable 已经指出这个问题，但在 unified pipeline 里还要扩大检查：

- `no_answer`
- `left_voicemail`
- `callback_later`
- `text_sent`

这些更像 progress，不像 final outcome。现在如果 API 用 close task 表达这些动作，就会导致 task lifecycle 被污染。

这会影响：

- task schema
- task prompt
- UI button
- attempt count
- follow-up task generation
- contact timeline
- analytics

### 3. `contact_timeline` 和 `task_progress_events` 不能混成一个概念

`contact_timeline` 更像用户可见的 contact-level audit / activity feed。

`task_progress_events` 更像 task lifecycle 内部的 source of truth。

它们可以互相投影，但不应该互相替代。否则以后会出现：

- task attempt count 只能靠 closed task 数推算。
- timeline event payload 变成各种 workflow 的垃圾桶。
- task detail 页面无法稳定 reconstruct progress。

### 4. Contact-level action 和 task-level action 要分清

`contacts.actionNeeded` / `contacts.suggestedActions` 和 `tasks.actionNeeded` / `tasks.suggestedActions` 看起来很像，但语义可能不同：

- contact-level action 是“这个人整体需要关注吗？”
- task-level action 是“这一个工作目标下一步做什么？”

如果不分清，prompt 会混，UI 会混，API 也会混。

这次要明确：

- contact action 是否只是 summary/projection？
- task 是否才是 actual work object？
- 如果两者都保留，谁是 source of truth？

### 5. STOP / DNC 不是普通 AI 判断

exact STOP 应该 code 立即处理；自然语言 DNC 可以 AI 判断，但执行必须由 code gate。

需要明确：

- exact STOP 是否已经在 message pipeline 里处理。
- natural language DNC 从哪里进入 AI。
- DNC 是否关闭所有 pending tasks。
- DNC cascade 是否必须变成 shared policy，而不是某个 pipeline 的私有逻辑。

### 6. `storeId = null` policy 要统一

多门店隔离是基础约束。不同 pipeline 如果对 `storeId` null 的处理不一致，会导致：

- contact merge 错误。
- task dedup 失败。
- timeline 无法归属。
- future tool API 无法做 tenant-scoped permission check。

Phase 1 至少要定义：

- 哪些 writer 可以接受 null store。
- null store 时允许写哪些字段。
- 什么时候必须 skip / quarantine / retry。

### 7. Lead retry downstream gap 要检查

lead pipeline 不是只看 happy path。要检查 retry / DLQ 路径是否也会触发 downstream：

- lead persisted 后是否一定会创建 contact。
- 是否一定会创建 `lead_outreach` task。
- 是否一定会写 timeline。
- retry success 是否会重新 publish downstream event。

如果 retry path 和 happy path 不一致，这就是 unified pipeline 要解决的典型问题。

### 8. Prompt count 不是重点，prompt ownership 才是重点

“现在大概有几个 prompt”要列，但不要停在数量。

真正要问：

- 哪个 prompt owns 哪类 judgment？
- 哪个 prompt 可以创建 task decision？
- 哪个 prompt 只能做 call classification？
- 哪个 prompt 输出是 user-visible content？
- 哪个 prompt 输出会导致 state mutation？

只有 mutation 相关 prompt 才必须严格接入 action proposal + code execution。

### 9. Tool calling 的风险不是技术接不接得上，而是权限和成本

OpenRouter / model provider 支持 tool calling 只是接口层问题。真正难的是：

- tool permission。
- tenant isolation。
- audit。
- idempotency。
- budget cap。
- retry / timeout。
- prompt injection。
- tool result 是否进入 long-term memory。

如果这些没有准备好，tool calling 只会把现在散落的 writer 问题放大。

### 10. Analytics / reporting 也会被 schema 语义影响

如果 `closeResult`、task progress、contact action、timeline event 的语义混乱，reporting 会跟着错。

例如：

- “完成几个 task”到底包含 no answer 吗？
- “converted” 是 call result、task outcome，还是 lead status？
- “attempt count” 应该从 task progress events 读，还是从 closed tasks 推？

所以 schema cleanup 不是纯 backend 内部问题，会直接影响 dashboard 和 manager view。

***

## 需要阅读的材料

### Source of truth

| 文件 / 目录                                                                                   | 目的                                             |
| ----------------------------------------------------------------------------------------- | ---------------------------------------------- |
| `callytics-common/src/db/schema/`                                                         | 当前 DB contract、enum、constraint                 |
| `callytics-infrastructure/lambda/*/src/`                                                  | 各 pipeline 的真实 trigger、writer、AI 调用            |
| `callytics-infrastructure/lambda/contacts-analyzer/src/core/prompt-builder.ts`            | contact analysis prompt 和 task decisions       |
| `callytics-infrastructure/lambda/contacts-analyzer/src/core/models.ts`                    | AI structured output schema                    |
| `callytics-infrastructure/lambda/contacts-analyzer/src/infrastructure/neon-repository.ts` | contact analysis 如何真正写 contacts/tasks/timeline |
| `callytics-infrastructure/lambda/ai-analysis-processor/src/core/stages/`                  | per-call AI stages                             |
| `callytics-infrastructure/lambda/message-processor/src/`                                  | SMS、STOP、DNC、timeline 写入                       |
| `callytics-infrastructure/lambda/lead-processor/src/core/persist-downstream.ts`           | lead downstream contacts/tasks/timeline        |
| `studio-website-monorepo/apps/api/src/routes/tasks/`                                      | manual task API 和 UI-facing behavior           |

### Design reference

| 文档                                                                                                              | 用途                                                           |
| --------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
| [Task Pipeline Deliverable (Codex)](/product-design/v2/tasks-feature/design/task-pipeline-deliverable-codex.md) | 已讨论通过的 task architecture baseline                            |
| [Task Pipeline 设计 Brief](/product-design/v2/tasks-feature/design/research/task-pipeline-design-brief.md)        | 方法论、expected output、workflow diagram 思路                      |
| [Product Design Principles](index.md)                                                                           | Schema-first / API-first / State-machine-first / Prompt-last |
| [System Overview](/architecture/0-system-overview.md)                                                           | 系统边界和 service layout                                         |
| [Backend Patterns](/system-design/backend-patterns.md)                                                          | Lambda / repository / domain patterns                        |
| `docs/product-design/v1/`                                                                                       | 旧设计参考，不能当现在代码事实                                              |
| `docs/product-design/v2/`                                                                                       | 新设计整理中的方向，仍需代码验证                                             |

### Historical reference only

| 文档 / 链接                                                   | 使用方式                                                      |
| --------------------------------------------------------- | --------------------------------------------------------- |
| `docs/ai/product/ai-integration-roadmap.md`               | 早期 AI agent 想法，可能 outdated，只能当历史参考                        |
| `docs/ai/product/voice-agent-feasibility.md`              | voice agent tool API 兼容性参考，不是本次目标                         |
| `https://openrouter.ai/docs/guides/features/tool-calling` | 理解 tool calling 的 provider-level interface                |
| `https://pi.dev/`                                         | 理解 coding-agent / dev harness 方向，不能直接当 backend runtime 结论 |
| Gemini share / 其他工程师调研                                    | 可以吸收观点，但每个结论都要被代码和产品约束验证                                  |

***

## Design Principles

### Schema-first

先搞清楚 business object 和 state machine，再写 prompt。

如果 schema 语义混了，prompt 只会把混乱放大。

### API-first

先设计系统允许哪些 business action，再决定 AI 输出什么。

AI output 不应该直接暴露 DB field patch；它应该输出 API-level action proposal。

### State-machine-first

所有 lifecycle transition 都应该由 code 控制。

AI 可以建议：

- create a task
- close a task with reason
- record progress
- mark contact DNC

但 code 决定：

- 是否允许。
- 是否幂等。
- 是否跨 tenant。
- 是否要 cascade。
- 是否写 audit。

### Prompt-last

只有当 schema/API/state machine 清楚后，才去写 prompt。

prompt 里应该少写“怎么写数据库”，多写“怎么判断业务意图”。

### Code as Guardrail, AI as Judgment

| 职责               | 谁做        | 原因                           |
| ---------------- | --------- | ---------------------------- |
| 状态转换             | Code      | 可审计、可回滚、幂等                   |
| 权限检查             | Code      | 不能受 prompt injection 影响      |
| tenant isolation | Code      | 多门店隔离是硬约束                    |
| DNC / compliance | Code gate | 允许 AI 提案，但执行必须 deterministic |
| 自然语言理解           | AI        | 语义判断适合模型                     |
| 内容生成             | AI        | 文本生成适合模型                     |
| action 参数提取      | AI + Code | AI 提取，code schema validation |

***

## Final Deliverable Template

下一轮 session 最终应该输出一个设计文档，结构建议如下：

1. **Executive Summary**
   - 现在架构最大问题是什么。
   - Phase 1 该做什么。
   - 现在是否上 tool calling。

2. **Current State Inventory**
   - schema inventory。
   - pipeline inventory。
   - prompt inventory。
   - writer inventory。

3. **Business Object Boundary Check**
   - contact / task / call / lead / message / timeline 的职责。
   - 哪些概念混了。
   - 哪些 schema/API 要调整。

4. **Current Workflow Diagrams**
   - 当前 code vs prompt 混合图。
   - 当前 writers 分散图。

5. **Target Workflow Diagrams**
   - shared module 后的 workflow。
   - code vs prompt 职责图。
   - future tool calling compatible 图。

6. **Shared Module Contracts**
   - Task Orchestrator。
   - Contact Writer。
   - Timeline Writer。
   - DNC / policy guard。

7. **Schema / API Recommendations**
   - 必改。
   - 可延后。
   - 不建议改。

8. **One-time AI vs Tool Calling Decision**
   - 现在结论。
   - 何时切换。
   - 需要提前预留什么。

9. **Phase 1 Plan**
   - 文件/模块级别的改造范围。
   - 测试策略。
   - rollout 顺序。
   - 风险和回滚。

***

## 本 brief 的判断倾向

当前倾向结论是：

**Phase 1 不应该直接改成 tool calling。Phase 1 应该先把 shared modules、schema/API 边界、AI structured output 和 code guardrail 做好。**

原因：

1. 现在主要 workload 是 batch / async pipeline，不是 interactive agent。
2. one-time AI call 的 cost 和 latency 更可控。
3. 现有问题的根因不是“AI 不会调用 tool”，而是 writers、schema 语义、prompt ownership 和 state transition 没统一。
4. 如果 Task Orchestrator / Contact Writer / Timeline Writer 设计正确，未来 tool calling 只是新增入口，不是推倒重来。

换句话说：

**不要先做 agent runtime。先把系统变成 agent-ready。**
