You are the bootstrap agent for a new Search App Monorepo.
Before creating or modifying any file: 1. Inspect the target directory without writing. Confirm it is empty and that `git rev-parse --is-inside-work-tree` does not report an existing repository. Stop on any existing file, `.git` directory, or repository. 2. Ask the human to approve the target directory, the allowed network scope, the toolchain, the dependency set, and the database and infrastructure policies. 3. Run only version and help commands for installed tools. Record the exact command and output for Python, Node.js, uv, pnpm, PostgreSQL client, Docker, Terraform, kubectl, Git, and the selected Agent tool. 4. Do not infer or upgrade a version. Do not install a tool or dependency. Do not select a package, framework plugin, database driver, lockfile format, or Kubernetes provider without explicit approval. 5. Produce a version-and-dependency proposal with three states for every item: verified, missing, or awaiting approval. Do not create the project until all required approvals are recorded.
After approval: 6. Create only this repository shape: apps/web, apps/api, packages/contracts, infra/terraform, infra/k8s, scripts, tests, .agents/skills, and .github/workflows. 7. Generate a minimal runnable React and TypeScript app in apps/web and a minimal runnable FastAPI app in apps/api using only the approved dependency set. Write the approved versions and dependencies to manifests and lockfiles. 8. Create pnpm-workspace.yaml, the root package.json with Playwright ownership, packages/contracts/package.json, and the approved pnpm and uv lockfiles. 9. Define a minimal Search API contract and a health or search vertical slice in packages/contracts and apps/api, then connect the approved web client to that slice without crossing the PostgreSQL boundary. 10. Add README.md, AGENTS.md, .gitignore, CODEOWNERS, scripts/bootstrap.sh, scripts/verify-fast.sh, scripts/verify.sh, and .github/workflows/verify.yml. Create `.agents/skills/project-bootstrap/SKILL.md` explicitly, using the template later in this article. Compute SHA-256 for every created file and write each path and hash to `.bootstrap-created-files.json`. Add the exact reviewed `generated_artifact_exclusions` list to the manifest. 11. Replace placeholders with verified commands for this repository; leave only genuinely unavailable checks marked unconfigured and fail-safe. 12. Implement `scripts/bootstrap.sh --ci` to install only committed lockfile dependencies and verify every configured Playwright project, its lockfile-matched browser executable, and required system dependencies without downloading browsers. 13. Run and record the real contracts test command and root Playwright command, including exact output and exit status. If either command cannot be established, mark it UNCONFIGURED and block final acceptance. 14. Run the first fast and full baseline after the skeleton is created. Record every command, exit status, duration, and pre-existing or environment-dependent failure. 15. Never create credentials, production configuration, cloud resources, migrations, or deployment applies.
Report: exact version commands and outputs, approved dependencies and lockfiles, created-file manifest with paths and SHA-256 hashes, package and Playwright ownership files, project-bootstrap Skill path, contract and vertical-slice files, contracts test evidence, root Playwright evidence, verified commands, baseline results, unresolved checks, commands not run, and the next human approval point. Stop immediately on ambiguity or an existing user file.
Inspect the Git state without changing it. Verify that the initial commit is parseable, the working tree has no unintended changes, CODEOWNERS covers application, contract, and infrastructure paths, and the feature worktree points to the recorded baseline. Report evidence. Do not push, merge, rewrite history, change branch protection, or delete anything.
- Purpose: Provide a search web application with a React client and a FastAPI service. - Frontend: `apps/web` uses React and TypeScript. - Backend: `apps/api` uses FastAPI and Python. - Shared contract: `packages/contracts` is the source of truth for API request and response shapes. - Database: PostgreSQL is accessed by the API only. - Tests: Pytest covers Python behavior; Playwright covers approved browser journeys. - Infrastructure: Terraform describes infrastructure; Kubernetes manifests describe workloads.
## Repository map
-`apps/web/`: browser UI, client state, and browser-facing API calls. -`apps/api/`: HTTP routes, validation, service logic, database access, and migrations. -`packages/contracts/`: versioned API contract and generated client types when approved. -`infra/terraform/`: infrastructure declarations; never apply from an Agent session. -`infra/k8s/`: Kubernetes manifests; never apply to a real cluster from an Agent session. -`scripts/`: repository-owned bootstrap and verification entry points. -`tests/`: cross-application, integration, and Playwright tests. -`.agents/skills/`: reviewed, pinned, repository-local Agent workflows. -`.github/workflows/`: approved CI workflows that call repository verification scripts. -`README.md`: verified setup and command reference.
## Boundaries
-`apps/web` may call the public API contract but must not access PostgreSQL. -`apps/api` owns validation, authorization, query construction, and database access. - Contract changes require updates to compatibility tests, documentation, and affected clients. - Edit generators instead of generated files. - Do not modify migrations, Terraform, Kubernetes manifests, dependency locks, or production configuration without explicit approval. - Do not create cloud resources, run production applies, expose services, or change database schema automatically. - Do not read, print, commit, or transmit secrets. Use approved environment injection. - Keep changes inside the requested scope and preserve existing user modifications.
## Authoritative commands
Run only commands verified in `README.md`, CI, or repository scripts.
If a command is not verified, report it as unconfigured and fail the corresponding script.
## Testing
- Add focused Pytest coverage for API and data behavior. - Add contract compatibility tests when `packages/contracts` changes. - Use Playwright only against an approved local or test environment. - Run the fast check after each vertical slice. - Run the full check before delivery. - Record commands, exit status, duration, skipped checks, and pre-existing failures.
## Git permissions
- Work on a dedicated branch or worktree. - Do not push, merge, rewrite history, delete branches, or change repository settings without approval. - Do not commit credentials, local state, database dumps, build output, or generated secrets. - Keep commits small and explain the user-visible result.
## Approval gates
- Human approval is required for dependencies, public API changes, database schema or migrations, Terraform changes, Kubernetes changes, network access, external writes, and production actions. - Rules, Skills, AGENTS.md files, and prompts are not security boundaries. - Sandbox, permissions, Allow/Deny policy, Hooks, CI, and branch protection provide separate controls.
## Completion report
Report changed files, contract and behavior changes, exact commands, exit status, duration, test evidence, skipped or unconfigured checks, known failures, approvals requested, security-sensitive actions, and rollback instructions.
Read the root AGENTS.md and every existing nested AGENTS.md. Compare them with the Search App directory tree, README, package manifests, CI files, and scripts. Report contradictions, invented commands, missing approval gates, and files that are outside the declared map. Do not edit files.
For the selected Agent tool, identify its official repository instruction file, rule directory, skill directory, MCP entry point, hook entry point, and initialization commands. Compare each claim with the current official documentation. Then inspect this repository and report exactly which adapter files are needed. Do not create a universal init command, copy another tool's configuration, or edit files before approval.
run_required() { local label="$1" shift if [[ "$#" -lt 1 ]]; then printf'ERROR: %s has no configured command.\n'"$label" >&2 return 1 fi local argument for argument in"$@"; do if [[ -z "$argument" || "$argument" == *REPLACE_WITH_* || "$argument" == *UNCONFIGURED* ]]; then printf'ERROR: %s is not configured with a verified command.\n'"$label" >&2 return 1 fi done printf'Running %s\n'"$label" "$@" }
run_required() { local label="$1" shift if [[ "$#" -lt 1 ]]; then printf'ERROR: %s has no configured command.\n'"$label" >&2 return 1 fi local argument for argument in"$@"; do if [[ -z "$argument" || "$argument" == *REPLACE_WITH_* || "$argument" == *UNCONFIGURED* ]]; then printf'ERROR: %s is not configured with a verified command.\n'"$label" >&2 return 1 fi done printf'Running %s\n'"$label" "$@" }
CI 应直接调用 ./scripts/verify-fast.sh 和 ./scripts/verify.sh,不要在 workflow 中另写一套命令。Agent 检查 Prompt:
1
Inspect scripts/verify-fast.sh and scripts/verify.sh. Map every command to apps/web, apps/api, packages/contracts, tests, infra/terraform, or infra/k8s. Execute the fast check only after confirming commands are verified. Confirm that an unconfigured command, missing tool, failed test, Terraform validation failure, or Kubernetes validation failure returns non-zero. Report the CI command reuse path. Do not replace placeholders with guesses.
Inspect the approved CI workflow and both repository verification scripts. Prove that the workflow invokes ./scripts/verify-fast.sh and ./scripts/verify.sh, and that it does not duplicate their underlying commands. Use the workflow file, CI configuration, and a completed CI run as evidence. Record the CI run URL or log reference, commit SHA, job names, exit statuses, and skipped checks. Do not push, approve, merge, or change branch protection.
人工打开一个 Pull Request 后,检查 workflow 的实际日志和 run URL;对照脚本逐项确认 CI 没有复制另一套命令。还要验证 container 中的工具版本与 Step 1 记录一致、playwright test --list 列出的每个 project 都有匹配且可执行的 browser binary、最小 browser launch/smoke test 在所有 configured projects 中通过、system dependencies 存在、./scripts/bootstrap.sh --ci 使用 lockfiles 且没有隐式浏览器下载。没有可访问的 CI run 时,验收状态必须是未验证,而不是通过。
CI bootstrap 失败验收 Prompt:
1
Run the approved CI workflow on a clean runner using the reviewed digest-pinned container image. Verify the exact Node.js, pnpm, Python, uv, Terraform, kubectl, and Playwright system dependency versions against the Step 1 record. Verify that ./scripts/bootstrap.sh --ci installs only the committed lockfile dependencies, lists every configured Playwright project, validates the matching browser executable and system dependencies for every project, runs the minimal browser launch/smoke test for every project, and does not download an unapproved browser. A missing lockfile, dependency installation failure, project mismatch, browser mismatch, missing executable, missing system dependency, smoke-test failure, or tool version mismatch must fail the job before verification. Record the CI run URL, commit SHA, image digest, tool outputs, logs, exit statuses, and failure evidence. Do not push, approve, merge, or change repository settings.
安装前检查来源、许可证、最近变更、SKILL.md、scripts/、references/、assets/、依赖、网络、凭据、自动触发和破坏性动作。固定 Tag 或 Commit SHA,记录负责人和更新策略。Skill 可以携带可执行脚本,不能按“纯提示词”信任。
审查 Prompt:
1
Create a Skill security review report before installing anything. For each proposed Skill, inspect the pinned source, tag or commit, license, SKILL.md, scripts, references, assets, dependencies, network access, credential access, automatic triggers, file writes, shell commands, and destructive actions. Classify findings as allow, allow-after-human-approval, or reject. Include exact evidence and an update owner. Do not install, execute, or modify the repository until a human approves the report.
For the configured MCP server, produce an execution checklist covering startup, server list, tool list, allowed tools, denied tools, approval prompts, timeout, missing-token behavior, process failure, invalid response, audit evidence, and rollback. Run read-only checks only. Do not call a write tool, connect to production PostgreSQL, apply Terraform, apply Kubernetes manifests, or expose credentials.
Agent 产物:逐工具权限矩阵、启动与工具列表证据、allow/deny/approval/timeout/failure 验收报告。 人工审批点:批准服务器、scope、环境变量、工具白名单、网络范围和任何写入权限;确认数据库与 infra 只走受控流程。 完成标志:只读 MCP 能启动并展示预期工具,拒绝和失败行为可观察,凭据未进入配置,生产操作没有直接入口。
input="$(cat)" ifprintf'%s'"$input" | grep -Eq '(^|[[:space:]])(kubectl|terraform)[[:space:]].*(apply|delete|destroy)'; then printf'%s\n''{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny","permissionDecisionReason":"Production mutation blocked by hook."}}' fi
Execute the Hook acceptance checklist in a disposable test repository. Test an allowed read-only command, a blocked production mutation, a timeout, a crashed hook, invalid JSON, and missing input. Record the actual event, exit status, stdout, stderr, decision, and whether the underlying tool ran. Do not use real credentials, production endpoints, Terraform apply, Kubernetes apply, database writes, or destructive commands.
--- name: project-bootstrap description: Bootstrap an approved Search App Monorepo from verified local tools and repository decisions. ---
# Project Bootstrap Skill
## Trigger
Use only when a human explicitly requests initialization of a new Search App Monorepo. Do not trigger automatically for existing repositories, migrations, production changes, or dependency upgrades.
## Inputs
Require the target directory, approved tool versions, approved dependencies, network scope, repository owner, verification commands, database policy, and infrastructure policy. Stop if any input is missing or conflicts with existing files.
## Initialization
1. Inspect the directory without changing it. 2. Record exact version and help command outputs for approved tools. 3. Create only `apps/web`, `apps/api`, `packages/contracts`, `infra/terraform`, `infra/k8s`, `scripts`, `tests`, `.agents/skills`, and `.github/workflows`. 4. Create a minimal runnable React and TypeScript web app and FastAPI Python API, write approved dependency manifests and lockfiles, and define a minimal Search API slice. 5. Create documentation, ignore rules, and fail-safe verification entry points. 6. Do not install unapproved tools or dependencies.
## Verification
Run only verified commands. Fail when a command is missing, unconfigured, or exits non-zero. Verify the directory map, Git baseline, contract boundary, fast check, full check wiring, and the first fast and full baseline.
## Boundaries
Never read, print, commit, or transmit secrets. Never overwrite user changes. Never run database writes, migrations, Terraform apply, Kubernetes apply, production commands, external writes, or Git history operations without explicit human approval. Rules, Skills, prompts, and AGENTS.md are not security boundaries.
## Completion report
Report exact tool outputs, approved dependencies and lockfiles, created-file manifest, contract and vertical-slice files, commands and exit statuses, baseline results, unconfigured checks, skipped actions, approval requests, risks, and rollback instructions.
简化调用 Prompt:
1
Explicitly discover and invoke the reviewed project-bootstrap Skill for the approved Search App Monorepo. Verify and record tool versions first, stop for missing approvals or existing files, create only the approved directory map, generate the minimal React and FastAPI vertical slice with approved lockfiles, wire fail-safe checks, run fast and full baselines, and return the required completion report. Do not install, apply, migrate, push, or overwrite anything.
Step 9:运行一次 Agent-ready 验收
实际操作入口:在独立测试分支或 worktree 中发送一个只改文档的小任务。下面 Prompt 要求 Agent 解释仓库、运行 fast check、做可逆变更、重新验证并报告证据:
1 2 3 4 5 6 7 8 9 10 11 12 13
You are performing the final Agent-ready acceptance for the Search App Monorepo.
1. Read the root AGENTS.md, README.md, the repository map, verification scripts, applicable tool adapter files, and `.agents/skills/project-bootstrap/SKILL.md`. 2. In a disposable empty fixture, ask the selected Agent tool to discover and explicitly invoke the repository `project-bootstrap` Skill. Record the discovery path and invocation evidence. Explain that it is not automatically triggered. Do not invoke it against this existing repository. 3. Explain the roles and boundaries of apps/web, apps/api, packages/contracts, infra/terraform, infra/k8s, scripts, tests, and .agents/skills. 4. Verify pnpm-workspace.yaml, the root package.json with Playwright ownership, packages/contracts/package.json, and the approved lockfiles. Verify the recorded contracts test and root Playwright command evidence. If either command is UNCONFIGURED, stop and fail acceptance. 5. Run the verified fast-check entry point exactly as documented. Report the command, exit status, duration, pre-existing failures, and any unconfigured check. Do not invent a replacement command. 6. Make one small, reversible documentation-only change in an approved documentation file. Do not touch application code, contracts, dependencies, migrations, PostgreSQL data, Terraform, Kubernetes manifests, credentials, hooks, or settings. 7. Show the diff and explain why the change is reversible. 8. Run the same fast-check entry point again and compare the evidence with the baseline. 9. Do not commit, push, merge, create infrastructure, access production, or call write-capable MCP tools.
Return a completion report with: repository explanation, changed file, diff summary, exact commands, exit statuses, durations, test evidence, skipped or unconfigured checks, approval requests, security-sensitive actions, and rollback instructions.
# Feature Bootstrap Prompt: Search App Status Filter
You are working on an existing Search App. Do not edit files, run write-capable commands, change data, or call external write tools until a human approves the task contract.
## Goal
Add an optional `status` search filter across the FastAPI API, PostgreSQL query path, React TypeScript UI, Pytest coverage, and Playwright coverage.
## Required contract questions
Before implementation, inspect the repository and mark every answer as verified, proposed, or unknown:
- What is the canonical search endpoint and response schema? - What are the business-approved status values? - Does an omitted `status` differ from an empty `status`? - What must happen for an invalid value: HTTP 422, HTTP 400, or an existing domain error? - Which database column and existing query abstraction are authoritative? - Which frontend selector naming convention and accessible label are required? - Which URL and request behavior is expected when the selector changes? - Which old clients and old URLs must remain compatible?
## API query parameter
The parameter is optional and named exactly `status`. The FastAPI/Pydantic parameter-validation boundary first receives the raw query value; `BeforeValidator` only normalizes the exact `""` and `None` cases to `None`, and then validates the result as `Literal["active", "archived"] | None`. The dependency or route receives the validated value before it reaches the query builder. An explicit raw dependency is equivalent only when it preserves this same order.
- Omitted `status`: normalize to `None` and apply no status filter. -`?status`: normalize to `None` and apply no status filter. -`?status=`: normalize to `None` and apply no status filter. -`active` and `archived`: valid non-empty values that filter results by the selected value. - Any other non-empty value: return the approved validation response using the existing FastAPI/Pydantic error envelope; do not silently broaden the query. - Repeated values, whitespace, casing, and URL encoding: inspect existing conventions and obtain approval for any new behavior.
## Case convention for this tutorial
Case agreement only: valid values are `active` and `archived`; omitted, `?status`, and `?status=` normalize to `None` and mean no status filter; other non-empty values return the existing HTTP 422 validation shape. Replace this agreement with business-approved values before implementation.
## Frontend behavior
- Add an accessible selector with a stable test selector: `status-filter`. - The selector must expose an explicit empty option. - The URL is the source of truth for shareable filter state. - On initial load and browser back/forward, derive React state from the normalized URL. - A user selection updates the URL only; the request is derived from normalized URL state. - Selecting `all` or the empty option removes the `status` parameter instead of serializing an empty value. - Avoid bidirectional effects that update URL from state and state from URL in a loop. - The request includes `status` only when normalized URL state is `active` or `archived`. - Loading, error, reset, back/forward navigation, and stale-response behavior must follow existing Search App conventions.
## Compatibility
- Existing requests without `status` must keep their response shape and result semantics. - Do not rename existing query parameters or response fields. - Do not require old clients to send `status`. - Preserve the existing API version and content type. - Treat omitted, `?status`, and `?status=` as backward-compatible no-filter requests.
## Constraints
- Use the existing FastAPI route, Pydantic validation style, query builder, and database access abstraction where possible. - Keep PostgreSQL queries parameterized; never concatenate user input into SQL. - Do not change the database schema, migrations, ranking, pagination, authentication, or unrelated UI. - Do not add dependencies without explicit approval. - Use test databases and test services only.
## Non-goals
- No new status taxonomy. - No data migration or backfill. - No production database access or write. - No redesign of search ranking, pagination, caching, or error presentation. - No unrelated refactor or formatting sweep.
## Approval points
Ask a human to approve:
1. The canonical status values and empty-value semantics. 2. The invalid-value HTTP status and error shape if not already authoritative. 3. Any public API, URL, response, schema, migration, dependency, or database-access change. 4. The file-level implementation plan and any unresolved unknown. 5. The final diff, verification evidence, risks, and rollback.
## Completion contract
Return a Task Contract containing verified facts, proposed case agreement, unknowns, files to inspect, compatibility invariants, non-goals, approval points, and acceptance criteria. Do not edit until approval is recorded.
# Read-only Explore Prompt: Search App Status Filter
Explore the repository in read-only mode. Do not edit, create, delete, format, migrate, install, commit, push, call write-capable MCP tools, or access production systems.
## Feature context
The proposed feature adds an optional `status` filter to the existing Search App. Treat the approved Task Contract as the source of intended behavior, and flag any mismatch instead of inventing a decision.
## Required investigation
1. Identify the canonical API route, HTTP method, query parameters, response model, error envelope, and API version. 2. Identify the authoritative FastAPI route symbol and Pydantic validation symbol for query parameters. 3. Trace the query builder and PostgreSQL access path, including parameter binding and transaction boundaries. 4. Identify the React TypeScript search component, state owner, request client, URL synchronization, reset behavior, loading state, and error state. 5. Locate existing API tests, frontend tests, Playwright tests, fixtures, factories, and test database configuration. 6. Find similar filters and record their exact conventions. 7. Identify generated files, shared contracts, snapshots, schema artifacts, and files that must not be edited directly. 8. List risks: contract drift, SQL injection, invalid-value handling, stale responses, URL loops, accessibility, and compatibility. 9. List unknowns that require human decisions. Do not resolve them by assumption.
## Evidence format
For every finding, provide:
- repository-relative file path - symbol, test name, or configuration key - relevant behavior - evidence status: verified, proposed, or unknown - impact on the status-filter feature
## Output
Return only an exploration report with:
- system map - authoritative contract - API and validation path - database query path - React state and request flow - test and verification entry points - risks - unknowns - files likely to change - files explicitly out of scope
# File-level Plan Prompt: Search App Status Filter
Use the approved Task Contract and read-only exploration report. Do not edit files.
Create a file-level implementation plan with three vertical slices:
## Slice A: API contract
- canonical route and method - query parameter name and type - valid, empty, omitted, repeated, whitespace, casing, and invalid-value behavior - response and error compatibility - exact files and symbols to change - Pytest tests to add or update
## Slice B: Backend behavior
- FastAPI/Pydantic boundary - query builder and PostgreSQL access symbol - parameterized query shape - fixture and test-database changes, if any - exact files and symbols to change - focused verification command: `TO_BE_VERIFIED_FROM_REPOSITORY`
## Slice C: Frontend integration
- React state owner and selector component - accessible label and stable selector `status-filter` - URL synchronization and request serialization - reset, loading, error, and stale-response behavior - Playwright tests for selector, URL, request, and result behavior - exact files and symbols to change
1. changing a public route, query parameter contract, response shape, or error shape; 2. changing schema, migrations, dependencies, shared generated contracts, or database configuration; 3. editing files outside the approved file list; 4. choosing behavior for an unresolved Task Contract question; 5. running anything against a non-test database or production service.
End with a decision log containing verified facts, approved choices, unresolved questions, and "No files were edited."
Agent 产物:按 API contract、backend behavior、frontend integration 划分的文件级计划、测试矩阵、命令和回滚方案。 人工审批点:批准文件列表、公共 contract、数据库边界、依赖边界和每个未知项的决定。 完成标志:每个切片都有允许/禁止范围、符号、测试、验证命令和可观察完成条件。
Use only the approved file list and test environment. Do not change production data or services.
## Phase 1: Write failing tests first
Add focused tests before implementation:
- API/Pytest: a valid `active` or `archived` value filters results. - API/Pytest: omitted `status`, `?status`, and `?status=` each normalize to `None` and preserve current behavior. - API/Pytest: another non-empty value returns the approved validation status and error shape. - API/Pytest: the FastAPI/Pydantic parameter-validation boundary receives the raw query value, `BeforeValidator` normalizes exact empty values before `Literal["active", "archived"] | None` validation, and the dependency or route receives the validated value. - React/Playwright: the selector has the stable selector `status-filter`. - React/Playwright: initial load and back/forward derive state from the normalized URL. - React/Playwright: selecting a valid value updates the URL, then derives the request from URL state. - React/Playwright: selecting `all` or the empty option removes `status` and does not create an effect loop.
Run `TO_BE_VERIFIED_FROM_REPOSITORY` after replacing it with the real focused command discovered during Explore and approved by a human. Save the unedited command, exit code, duration, and complete failure output to the task evidence. Label this evidence RED. Do not claim RED if the command failed because the test environment was unavailable.
## Phase 2: Minimal implementation
After a human confirms that the RED failures represent the missing feature:
- implement the smallest API/Pydantic boundary change; - pass the validated value to the existing parameterized query path; - normalize omitted `status`, `?status`, and `?status=` to `None` before validation and query construction; - preserve the old query and response behavior for all three no-filter forms; - add the selector without changing unrelated layout; - derive React state and requests from normalized URL state, and remove `status` for `all` or empty selection; - avoid concatenating user input into SQL; - do not broaden the allowed status set.
## Phase 3: Re-run focused tests
Run the same human-approved focused command, no longer represented by `TO_BE_VERIFIED_FROM_REPOSITORY`. Save command, exit code, duration, and output. Label evidence GREEN only when the tests actually pass. If a test fails, report the failure and continue debugging within the approved scope; never replace evidence with an expected result.
## Stop conditions
Stop and request approval for contract changes, migrations, dependency changes, production access, generated-file changes, or out-of-scope edits.
Agent 产物:失败测试及真实 RED 证据、最小实现 diff、真实 GREEN 证据;若环境失败则是独立的环境阻塞记录。 人工审批点:确认 RED 原因是功能缺失;确认实现不会改变未携带 status 的旧请求行为。 完成标志:合法/空/非法值和 selector/request 行为都有测试;GREEN 由实际命令和退出码证明。
Implement only the approved API contract for the optional `status` query parameter.
## Allowed
- approved FastAPI route and Pydantic query-validation files - approved API contract tests and fixtures - test-only configuration required by those tests
## Forbidden
- React files, Playwright files, database schema, migrations, dependencies, production services, unrelated refactors - changing response fields, existing query parameter names, or old-client requirements - inventing status values or invalid-value semantics
## Required behavior
- valid values follow the approved Task Contract; - omitted and approved empty values preserve the old behavior; - invalid values use the existing validation envelope; - the route remains backward compatible.
## Verification
Run `TO_BE_VERIFIED_FROM_REPOSITORY` after replacing it with the real approved focused Pytest command discovered during Explore. Cover valid values, omitted `status`, `?status`, `?status=`, and invalid values. Record command, exit code, duration, and evidence.
## Completion
The API tests demonstrate the approved contract, the diff contains only approved files, and a human has approved any public contract change.
Implement only backend propagation of the approved `status` value into the existing PostgreSQL query path.
## Allowed
- approved query builder, repository, or data-access symbols - approved backend tests, fixtures, and test-database setup
## Forbidden
- raw SQL string interpolation, schema or migration changes, production database access, React or Playwright changes, unrelated query rewrites
## Required behavior
- use the existing parameterized query mechanism; - bind `status` as a query parameter; - preserve the old query shape when no filter is requested; - verify that an invalid value cannot reach the query layer as an unvalidated value.
## Verification
Run `TO_BE_VERIFIED_FROM_REPOSITORY` after replacing it with the real approved backend focused Pytest command. Where available, assert the bound parameter or query-builder behavior without exposing real credentials.
## Completion
Valid filtering and no-filter compatibility pass in the test database, parameterization is visible in the diff, and no schema or production access occurred.
Implement only the approved React TypeScript integration for the `status` filter.
## Allowed
- approved selector component, search state, request client, URL adapter, and Playwright files - approved frontend fixtures or test helpers
## Forbidden
- backend or database files, dependency changes, unrelated UI refactors, inaccessible hidden-only controls, production endpoints
## Required behavior
- render an accessible selector with `data-testid="status-filter"` only if that is the approved project convention; - keep the explicit empty option; - derive selector state from the normalized URL on initial load and back/forward; - update the URL only when the user changes the selector, then derive the request from URL state; - remove `status` for `all` or empty selection and avoid bidirectional effect loops; - preserve loading, error, reset, back/forward, and stale-response behavior; - assert request behavior through the test environment, not a production service.
## Verification
Run `TO_BE_VERIFIED_FROM_REPOSITORY` after replacing it with the real approved React and Playwright command(s). Cover selector visibility, initial URL state, selection, back/forward, request query, clearing, `all`, and result behavior.
## Completion
The user-visible flow works in the test browser, the request contains only the approved parameter behavior, accessibility checks pass, and the diff stays within the approved frontend files.
Agent 产物:三个独立切片的代码 diff、focused test 输出和完成声明。 人工审批点:每个切片完成后检查 diff;尤其确认 API 兼容性、参数化查询和前端 URL/request 契约。 完成标志:三个切片均达到各自完成条件,且没有跨切片越界或把测试环境连接到生产。
Verify the approved implementation in the test environment only. Do not write to production databases, production APIs, external services, or infrastructure.
## Order
1. Run `TO_BE_VERIFIED_FROM_REPOSITORY` after replacing it with the real focused Pytest, React, and Playwright check command(s) discovered during Explore and approved by a human. 2. Run the existing repository entry point:
./scripts/verify-fast.sh
3. Run the existing repository entry point:
./scripts/verify.sh
Read both scripts before execution if their scope is not already known. Do not edit the scripts as part of this feature.
## Evidence record
For every command, record:
- exact command - working directory - start and end time - duration - exit code - relevant output or artifact path - checks skipped and why - pre-existing failures confirmed against the baseline
## Required checks
- valid, omitted, empty, and invalid API values; - response and error compatibility; - parameterized PostgreSQL query behavior in the test database; - React selector accessibility and state; - URL and request synchronization; - Playwright browser behavior; - focused verification; - verify-fast verification; - full verification.
## Honesty rules
Do not convert a timeout, unavailable service, missing browser, missing database, or pre-existing failure into a pass. If a command is not run, mark it unverified and explain why. Compare failures with the recorded baseline before attributing them to this feature.
Return a verification report and do not modify files.
Review the uncommitted diff and verification evidence. Start with the complete diff, changed-file list, and baseline; do not rely on the implementation summary.
## Review questions
1. Does the implementation cover every approved requirement and no unapproved requirement? 2. Are FastAPI and Pydantic boundaries correct for valid, omitted, empty, repeated, and invalid values? 3. Can any user-controlled value reach SQL through string concatenation or unparameterized interpolation? 4. Does the React selector preserve state, URL, request, reset, loading, error, back/forward, and stale-response behavior? 5. Did response, error, query-parameter, accessibility, or URL contracts drift? 6. Are API/Pytest, React, and Playwright tests complete and meaningful? 7. Are changed files limited to the approved plan? 8. Are there generated files, migrations, dependencies, credentials, production URLs, or external writes that were not approved? 9. Are verification claims supported by exact commands, exit codes, durations, and artifacts?
## Output
Return findings ordered by severity with file path and symbol references, followed by:
- Preserve API contract compatibility unless a human approves a contract change. - Keep user-controlled values out of SQL text; use parameterized queries. - Treat the shareable URL as the source of truth for filter state; derive requests from normalized URL state. - Cover API behavior with backend tests and user-visible behavior with frontend or browser tests. - Run focused checks first, then the repository's approved fast and full verification entry points. - Use test databases, test services, and test browsers for feature verification.
--- name: feature-delivery description: Deliver a bounded feature with contract-first exploration, TDD, vertical slices, verification, and review. ---
# Feature Delivery
## Trigger
Use only when a human explicitly invokes this skill. Do not claim automatic triggering.
## Inputs
Require the feature goal, approved acceptance criteria, repository path, allowed files, non-goals, test environment, and verified repository commands. Mark missing decisions as unknown.
## Explore
Read only. Map the authoritative contract, API route and validation boundary, database query path, frontend state and URL flow, tests, verification entry points, risks, and unknowns. Report paths and symbols. Do not edit, install, migrate, access production, or call write-capable tools.
## Plan
Create a file-level plan with API contract, backend behavior, and frontend integration slices. List allowed and forbidden files, symbols, tests, commands, evidence, completion criteria, rollback, and human approval gates.
## TDD
Add focused failing tests first. Preserve real RED evidence. Implement the smallest approved change, then rerun the same checks and preserve real GREEN evidence. Never fabricate results or convert environment failures into passes.
## Slices
- API contract: normalize and validate at the approved boundary; preserve compatibility. - Backend behavior: pass validated values through parameterized database queries. - Frontend integration: derive state and requests from normalized shareable URL state; test selector, URL, request, reset, and browser behavior.
## Verify
Replace every `TO_BE_VERIFIED_FROM_REPOSITORY` with a real command discovered during Explore and approved by a human. Run focused checks, then the approved fast entry point, then the approved full entry point. Record command, exit code, duration, evidence, skips, and pre-existing failures. Use test services only.
## Review
Review the complete diff first. Check requirement coverage, validation boundaries, SQL injection, URL/state synchronization, contract drift, test gaps, and out-of-scope edits. Do not edit, commit, push, merge, or access production.
## Report
Return changed files, behavior, contract, tests, commands, evidence, risks, approvals, rollback, and unverified items. A final report must contain no command placeholder and must not claim pass while any required evidence is missing.
## Boundaries
- No production access or writes. - No real credentials or internal URLs. - No schema, dependency, public contract, or external-service change without approval. - No edits outside the approved file list.
## Explicit Invocation Prompt
Use this prompt to invoke the skill:
Use the feature-delivery skill for this repository and feature. Feature goal: Approved contract: Non-goals: Repository path: Allowed files: Test environment: Focused command: TO_BE_VERIFIED_FROM_REPOSITORY Fast command: Full command:
Start with read-only exploration. Do not edit until a human approves the Task Contract and file-level plan. Preserve real RED and GREEN evidence, use parameterized queries, test only against test services, review the complete diff, and return a delivery report with no unresolved placeholders.
- RED evidence: - GREEN evidence: - browser artifacts: - API response artifacts: - database/query evidence: - review report:
## Risks and mitigations
- risk: - mitigation: - owner: - residual risk:
## Approvals
- Task Contract: - status values and empty semantics: - public contract: - file-level plan: - migrations or dependencies: - final diff: - final verification:
## Rollback
- revert commit or approved file diff: - database rollback: `NOT_APPLICABLE_OR_APPROVED_TEST_ONLY_PLAN` - API compatibility fallback: - frontend feature-disable plan:
No production database, production API, infrastructure, real credential, external write, commit, push, or merge was used unless explicitly listed above with human approval.
You are investigating a Search App regression. Read repository documentation, package manifests, CI configuration, route definitions, and existing tests in read-only mode.
Bug contract: - Omitted status, bare ?status, and ?status= mean no status filter. - A non-empty valid status applies the filter. - A non-empty invalid status remains a validation error.
Observed symptom: - A React TypeScript frontend or legacy client sends ?status=. - FastAPI currently returns the observed response recorded by the reporter, commonly 422 Unprocessable Entity. - Do not replace the observed response with an assumption such as 400.
Do not edit code, install dependencies, write to PostgreSQL, call production services, or create files. Return only: 1. Repository-derived commands, each marked VERIFIED or TO_BE_VERIFIED_FROM_REPOSITORY. 2. The exact route and client call sites you found. 3. The data-flow boundaries: React serialization, FastAPI/Pydantic pre-validation, route dependency, service/query builder, and PostgreSQL query. 4. Missing evidence that a human must provide. 5. A redacted Bug Intake record with method, path, query, headers, response body, status, logs, version, and frequency.
Hypothesis: After React serialization is confirmed to send status=, FastAPI/Pydantic pre-validation rejects the empty string before the route handler receives it. Probe: Log or inspect the parsed route input in an isolated test and compare it with the raw query for omitted, bare, and empty status. Expected falsifier: The handler receives an empty string and the service or query builder creates the wrong filter. Stop condition: If the probe cannot distinguish layers, gather boundary evidence before proposing a fix.
Use the repository's reviewed systematic-debugging Skill for this incident. Follow its root-cause-first process: read the complete error, reproduce consistently, inspect recent changes, trace data across React, FastAPI/Pydantic, route dependency, service/query builder, and PostgreSQL boundaries, then form one falsifiable hypothesis. Do not propose or apply a fix before the RED regression test proves the target bug. Count every action that changes observable system behavior, including code, configuration, tests, dependencies, runtime flags, proxy or deployment configuration, migrations, and generated clients. Append the same attempt index across sessions and agents; changing the prompt or agent never resets it. After three invalid attempts, stop editing and produce an investigation report for human review. If the Skill is unavailable, do not pretend it exists or trigger it automatically. Use only the minimal project-level fallback template supplied below, after a human reviews it.
## Gates 1. Capture redacted evidence before edits. 2. Reproduce with exact commands and outputs. 3. Trace one data-flow boundary at a time. 4. State one falsifiable hypothesis. 5. Add a failing regression test before a fix. 6. Make one minimal fix at the confirmed normalization boundary. 7. Verify focused, fast, full, and real HTTP paths. 8. Stop after three invalid fix attempts.
## Safety - No production writes. - No credentials or internal URLs. - No dependency upgrades during a bug fix. - Mark unknown commands as TO_BE_VERIFIED_FROM_REPOSITORY.
@pytest.fixture defclient(repository): # app must be the same FastAPI instance passed to TestClient. # Replace provide_repository with the dependency used by the real app. app.dependency_overrides[provide_repository] = lambda: repository with TestClient(app) as test_client: yield test_client app.dependency_overrides.clear()
Review the diff before reading the success summary. Confirm that only the confirmed normalization boundary and regression tests changed. Confirm omitted, bare, and empty status produce no filter. Confirm valid non-empty status still filters. Confirm invalid non-empty status still fails. Confirm SQL remains parameterized. Confirm no credential, internal URL, production write, dependency upgrade, unrelated refactor, or generated file was introduced. Record browser/API compatibility for React TypeScript, legacy clients, FastAPI, Pytest, and Playwright.
## Summary - Issue: TO_BE_VERIFIED_FROM_REPOSITORY - Contract: omitted, bare, and empty status mean no filter - Observed response: TO_BE_VERIFIED_FROM_REPOSITORY - Root cause layer: TO_BE_VERIFIED_FROM_REPOSITORY - Final disposition: fixed, unresolved, or architecture review required
## Attempts - Shared attempt index: append-only across sessions and agents - Attempt 1: change category, observed behavior, hypothesis, exact command, exit code, result - Attempt 2: change category, observed behavior, hypothesis, exact command, exit code, result - Attempt 3: change category, observed behavior, hypothesis, exact command, exit code, result
## Evidence - RED: exact command and output - GREEN: exact command and output - Fast tests: exact command and output - Full tests: exact command and output - Real HTTP path: exact command and output - Browser path: exact command and output
You are auditing a legacy FastAPI Search Service in strict read-only mode.
System context: - React frontend and FastAPI service share a historical repository layout. - PostgreSQL is part of the data layer. - Commands may be scattered across README files, CI workflows, manifests, scripts, container files, and build configuration. - The repository may contain .cursorrules, duplicated prompts, or oversized guidance files.
Safety: - Do not edit, create, delete, rename, format, generate, install, migrate, or commit anything. - Do not run repository scripts, Make, Task, tests, builds, Docker, Compose, package managers, database clients, migrations, network clients, or services. - Do not run Git aliases or commands that can invoke hooks, pagers, editors, filters, or external programs. - Do not call production endpoints or read secret values. - Use only dedicated file-reading tools and the allowlisted read-only Git metadata queries with pager, hook, and alias execution disabled. - Do not use Git commands outside rev-parse, log, branch --show-current, and status --short metadata reads. - A local audit cannot observe platform branch protection; mark it BLOCKED until a platform owner supplies evidence. - If a credential or secret is discovered, stop immediately. Record only the minimum file location and risk category, notify the owner, and wait for a separately approved remediation task. Do not remove, rotate, copy, or print it.
Audit these areas: 1. README and other developer documentation. 2. CI workflows, required checks, branch protections if visible, and release jobs. 3. Package manifests, lockfiles, Python metadata, frontend build configuration, and environment examples. 4. Application entry points, API routes, React entry points, database adapters, migrations, and generated code. 5. Scripts, Makefiles, task runners, Dockerfiles, compose files, Kubernetes manifests, and deployment files. 6. Test configuration, unit tests, integration tests, API tests, browser tests, fixtures, and test databases. 7. Git history for recent changes, ownership clues, generated-file patterns, and risky modules. 8. Guidance files such as AGENTS.md, CLAUDE.md, .cursorrules, and project-local instruction files.
For every command or workflow you discover without executing it: - Quote the exact source file and line or section. - Mark it SOURCE_CONFIRMED, BLOCKED, or TO_BE_VERIFIED_FROM_REPOSITORY. - Do not invent a replacement command.
Return a proposed docs/agent-readiness/BASELINE.md draft with: - Repository map and runtime/tool versions. - Authoritative commands and evidence sources. - Known failures and missing prerequisites. - Test layers and coverage gaps. - Risk modules and secrets boundaries. - Owners, generated files, approval gates, and unknowns. - A separation between source evidence and execution evidence.
Use TO_BE_VERIFIED_FROM_REPOSITORY for missing facts. Do not claim readiness, passing tests, or production safety.
Agent 产物
Agent 应输出一份只读审计结果和 docs/agent-readiness/BASELINE.md 草稿,至少包含仓库地图、运行时、命令来源、测试入口、风险模块、秘密边界、生成文件、负责人和未知项。它还应列出冲突的 README 命令、失效 CI job、未确认的数据库启动方式以及任何无法从仓库证明的结论。
人工审批点
人工确认审计范围确实只读;确认 Agent 没有启动服务、写数据库、读取或复制凭据;确认每条“权威命令”都有仓库证据。若 README 与 CI 冲突,先批准“记录冲突”,不要让 Agent 自行选择一个命令。
Using the approved BASELINE.md, create only these verification adapters: - scripts/bootstrap.sh - scripts/verify-fast.sh - scripts/verify.sh
Rules: - Reuse only commands marked EXECUTION_VERIFIED. - Use fixed argv arrays or approved repository scripts and Make targets. - Do not use bash -lc, eval, sh -c, or dynamically assembled shell strings. - Preserve the repository's existing package managers, environments, test selectors, and service boundaries. - If a required command is empty, unknown, contains any placeholder, or is not in the approved command mapping, exit non-zero. - Use strict shell failure behavior and propagate child exit codes. - Do not ignore failures, use unconditional success, or hide output needed for diagnosis. - Do not install from the network unless the approved repository command explicitly requires it. - Do not write to production, use real credentials, or run destructive migrations. - In terminal and CI, log only a stable command ID and a pre-approved sanitized argv summary. - Write the complete sanitized argv only to controlled execution evidence. - Never print an argv that may contain tokens, private URLs, or secret values. - Show the proposed diff before execution.
The adapters must: 1. Fail fast on missing prerequisites. 2. Log the stable command ID and sanitized argv summary before running it. 3. Return non-zero when a delegated command fails. 4. Distinguish unverified commands from successful verification. 5. Be reusable by local development and CI.
这里的 fail-safe 核心模板只展示控制结构,不假装知道目标仓库的真实命令。实际项目应把每条已批准命令写成固定数组;若仓库已有经过审查的脚本或 Make target,优先直接委托该入口。
run_verified() { local label="$1" local command_id="$2" local argv_summary="$3" shift 3 if [[ "$#" -lt 1 ]]; then printf'ERROR: %s has no configured argv.\n'"$label" >&2 return 1 fi printf'==> %s\n'"$label" printf'Command ID: %s\n'"$command_id" printf'Argv summary: %s\n'"$argv_summary" "$@" }
require_approved_argv() { local argv_name="$1" shift case"$argv_name"in "api bootstrap"|"web bootstrap"|"api fast verification"|"web fast verification") ;; *) printf'Unapproved argv mapping: %s\n'"$argv_name" >&2 exit 2 ;; esac if [[ "$#" -eq 0 ]]; then printf'Empty approved argv: %s\n'"$argv_name" >&2 exit 2 fi local argument for argument in"$@"; do if [[ -z "$argument" || "$argument" == *TO_BE_VERIFIED_FROM_REPOSITORY* ]]; then printf'Invalid approved argv: %s\n'"$argv_name" >&2 exit 2 fi done }
You are migrating repository guidance under a strict two-gate approval process.
Hard boundary: - Use only the human-approved docs/agent-readiness/BASELINE.md. - SOURCE_CONFIRMED means the source was confirmed; it does not authorize execution. - Only EXECUTION_VERIFIED commands may become verification entry points. - Do not guess unknown commands, owners, scopes, URLs, credentials, or tool behavior. - Do not edit files during Gate 1.
Gate 1 — read-only audit: 1. Read only the human-approved docs/agent-readiness/BASELINE.md entries that are not marked secret or user configuration, README files, CI configuration, the existing CLAUDE.md and .cursorrules, repository instructions, available Skills, and the directory structure. The existing CLAUDE.md, .cursorrules, and instructions are classification sources, not fact authorities. Reuse a shared fact or directory rule only when it maps exactly to an approved BASELINE entry; otherwise set its disposition to unresolved. 2. Reuse the strict read-only boundary from Step 1. Allow only file reads and Git metadata queries with pagers, hooks, and aliases disabled. The only permitted Git metadata query forms are `git --no-pager -c core.hooksPath=/dev/null rev-parse`, `git --no-pager -c core.hooksPath=/dev/null log`, `git --no-pager -c core.hooksPath=/dev/null branch --show-current`, and `git --no-pager -c core.hooksPath=/dev/null status --short`. The allowlist accepts only built-in Git subcommands; aliases are not accepted as commands. Do not run repository scripts, Make, Task, tests, builds, Docker, package managers, databases, services, startup, migration, deployment, network access, or any command inferred from repository content. 3. Do not read any path that the BASELINE marks as secret or user configuration. 4. Classify every candidate item as exactly one of: shared facts, directory-scoped rules, on-demand workflows, personal preferences, secrets/user configuration. 5. Propose the smallest file set. Prefer a concise root AGENTS.md, directory-level files only for local deltas, and Skills for reusable workflows. 6. Produce a migration table with one row per item and these columns: row_id, source, baseline_reference, target, scope, status, owner, reason, disposition. baseline_reference must identify the exact approved BASELINE entry, or be unresolved. Use status values such as confirmed, proposed, unresolved, blocked, or do-not-commit. 7. Return the proposed files, migration table, conflicts, unknowns, and deletion candidates. 8. Stop and wait for explicit human approval. Do not edit, generate a patch, or delete any old file in Gate 1.
Gate 2 — patch generation after explicit human approval: - Require and echo all of these inputs before generating anything: approved BASELINE revision, approved migration row IDs, exact file allowlist, and each old file's retain/deprecate/delete disposition. If any input is missing, stop. - For every approved migration row ID, require an exact approved BASELINE reference and an eligible disposition. Never generate a patch for a row whose disposition is unresolved, blocked, or do-not-commit, even when its row ID was supplied. - Generate a patch only for the approved proposed files. - Generate a patch only; do not execute adapters, tests, services, startup, migration, deployment, or any command. - Set verification evidence to NOT_RUN. Running an EXECUTION_VERIFIED adapter requires a separate independent human approval and an isolated environment; this Guidance task does not execute it. - Keep root AGENTS.md concise and write only shared repository facts and global boundaries. - Directory-level AGENTS.md files may contain only incremental local facts; do not copy root rules. - Move repeatable workflows into Skills instead of embedding procedures in AGENTS.md. - Never commit personal preferences, user configuration, credentials, secrets, internal URLs, production values, or one-off task details. - If a secret is discovered, stop immediately and return only its file path and risk category. Do not print, copy, delete, rotate, or expose the secret. - Keep conflicts and unknowns unresolved. Do not choose an interpretation without owner approval. - Do not delete old guidance files unless the owner separately approves that exact deletion. - Do not invent commands. A verification entry point must be marked EXECUTION_VERIFIED in the approved BASELINE.md and must run through an approved adapter. - Starting the backend may run migrations, seed data, create or modify S3 objects, or start background jobs. It is not ordinary verification. Never run production migration/apply.
Required final report: 1. changed files 2. migration decisions 3. unresolved conflicts 4. commands referenced, including each command status and adapter 5. verification evidence 6. rollback procedure
## Scope - This file contains shared repository facts and safe working boundaries. - Read the nearest nested AGENTS.md before editing a scoped directory. - Use only the human-approved `docs/agent-readiness/BASELINE.md`. -`SOURCE_CONFIRMED` is not executable; only `EXECUTION_VERIFIED` commands are verification entry points.
## Repository Map -`backend/`: FastAPI and PostgreSQL application; Alembic owns schema migrations. -`frontend/`: Vue 3, TypeScript, and Vite application. -`cli/`: Typer command-line interface. -`k8s/`: Kustomize overlays and Kubernetes manifests. -`scripts/`: approved adapters for setup and verification; do not infer commands from filenames. -`docs/agent-readiness/BASELINE.md`: human-approved facts, command status, known failures, and owners.
## Working Rules - Explore before editing. - Change the smallest approved scope. - Use only `EXECUTION_VERIFIED` commands through approved `scripts/` adapters. - Unknown commands remain unresolved; never guess. - Keep secrets, personal configuration, and production data outside the repository. - Show the diff before running broad verification.
## Verification - Verification entry points are only approved `EXECUTION_VERIFIED` adapters in `scripts/`. - Do not promote `SOURCE_CONFIRMED` or `TO_BE_VERIFIED_FROM_REPOSITORY` to a runnable command. - This Guidance task generates a patch only and does not execute verification. - Verification evidence is `NOT_RUN` unless a separate independent human approval authorizes an approved adapter in an isolated environment.
## Approval Gates - Human approval is required for migrations, deployment files, authentication, shared schemas, cross-module changes, production configuration, and scope expansion.
## Boundaries - Keep FastAPI routes thin: validate transport concerns and delegate business behavior to services. - Keep services independent from HTTP concerns and make database access explicit through the repository/DB boundary. - Routes must not bypass the approved service-to-repository/DB ownership boundary. - Alembic owns backend schema migrations; creation or application requires explicit human approval.
## Testing and Startup - Use an isolated test database approved for the current task. - Backend startup may run migrations, seed data, create or modify S3 objects, or start background jobs. - Treat startup as side-effectful; it is not ordinary verification. - Never run migration or apply commands against production.
Review the generated guidance migration as a read-only reviewer.
Check every item: - Trace every migrated fact to its exact baseline_reference and confirm that the reference points to a human-approved BASELINE entry. Treat legacy CLAUDE.md, .cursorrules, and instructions only as classification sources; do not require those legacy sources themselves to be approved authorities. - Confirm each migration row has a row_id, baseline_reference, source, target, scope, status, owner, reason, and disposition. Reject a migration without an approved BASELINE mapping. - Confirm every approved row has an eligible disposition; reject patch content for rows marked unresolved, blocked, or do-not-commit, regardless of supplied row ID. - Check AGENTS.md hierarchy: root rules are concise, nested files contain only local deltas, and no nested file duplicates the root. - Check every referenced command and adapter status. Only EXECUTION_VERIFIED commands may be verification entry points; SOURCE_CONFIRMED and unknown commands must not be executable. - Confirm the Gate 1 read-only boundary excludes scripts, Make/Task, tests, builds, Docker, package managers, databases, network access, secret paths, and user-configuration paths. - Confirm Gate 2 only generated a patch, did not execute adapters or other commands, and reports verification evidence as NOT_RUN. - Confirm the approved BASELINE revision, migration row IDs, exact file allowlist, and every old-file retain/deprecate/delete disposition were supplied and echoed. - Detect duplicated, contradictory, guessed, stale, or scope-leaking rules. - Detect secrets, credentials, internal URLs, production values, personal preferences, user configuration, and one-off task details. - Check that backend startup side effects are explicit in the backend guidance and that production migration/apply is prohibited. - Check every old guidance file and confirm deletion has separate owner approval. - Check that reusable workflows moved to Skills and that the migration table is complete.
Classify each finding as Critical, Important, or Minor. Critical and Important findings must be fixed or block approval. Minor findings are recorded as non-blocking improvements. Return: findings, source trace, hierarchy result, command-status result, deletion-approval result, required fixes, and final approval status.
Create characterization tests for the existing Search API behavior.
Explore first: - Find the real FastAPI route, request model, service, query builder, database fixture, test client, and existing API test command. - Find the React request serialization only if it is part of the observed behavior.
Rules: - Do not fix, normalize, refactor, rename, or improve behavior. - Preserve odd but compatible responses as observations. - Require TEST_DATABASE_URL and an approved test-database record. - Require the host to be in APPROVED_TEST_HOSTS. - Require the name to be in APPROVED_TEST_DATABASE_NAMES or to match an approved test-database prefix. - Require a temporary schema that matches the approved schema rule. - Require a dedicated low-privilege role. - Use transaction rollback only when the behavior under test does not cross a commit boundary. - Never use production data, credentials, or production endpoints. - Record before evidence before adding assertions. - Mark unknown paths, commands, response fields, and status meanings as TO_BE_VERIFIED_FROM_REPOSITORY or BLOCKED.
Return: 1. A behavior matrix with request, response, database effect, and evidence. 2. The smallest test diff that captures current behavior. 3. Exact commands and outputs. 4. Behaviors that are intentionally not asserted because evidence is missing. 5. A human approval request before any implementation change.
Before running characterization tests, enforce these guards: 1. TEST_DATABASE_URL must be present and parse successfully. 2. Load the approved record containing APPROVED_TEST_HOSTS, APPROVED_TEST_DATABASE_NAMES, approved database prefixes, APPROVED_TEST_SERVER_IDENTITIES, APPROVED_TEST_ROLES, and the temporary schema rule. 3. Require the configured host and database name to match the positive allowlist and require a dedicated low-privilege role. 4. Connect and require server, database, and current_user identity to match the approved record exactly. 5. Create a temporary schema that matches the approved schema rule. 6. Keep production host and database denylist checks as a second layer only. 7. Record redacted pre-test identity evidence. 8. Disable migrations and external writes by default. 9. Run the focused test. 10. Record redacted post-test identity evidence and verify teardown leaves no temporary database, schema, table, role, or fixture residue. 11. Stop with BLOCKED on any failed guard; never continue with a fallback URL.
defrequire_test_database(): raw_url = os.environ.get("TEST_DATABASE_URL") ifnot raw_url: raise RuntimeError("TEST_DATABASE_URL is required")
database = parse_database_url(raw_url) ifany("TO_BE_VERIFIED_FROM_REPOSITORY"in value for value in ( database.host, database.name, database.role, APPROVED_TEST_SCHEMA_PREFIX, )): raise RuntimeError("Database approval record is incomplete") if database.host notin APPROVED_TEST_HOSTS: raise RuntimeError("Database host is not allowlisted") if ( database.name notin APPROVED_TEST_DATABASE_NAMES andnotany( database.name.startswith(prefix) for prefix in APPROVED_TEST_DATABASE_PREFIXES ) ): raise RuntimeError("Database name is not allowlisted") if database.role notin APPROVED_TEST_ROLES: raise RuntimeError("Database role is not allowlisted") if database.host in APPROVED_PRODUCTION_HOSTS: raise RuntimeError("Production database host is forbidden") if database.name in APPROVED_PRODUCTION_DATABASES: raise RuntimeError("Production database name is forbidden")
identity_before = query_database_identity(database) if identity_before.server notin APPROVED_TEST_SERVER_IDENTITIES: raise RuntimeError("Database server identity is not approved") if identity_before.database != database.name: raise RuntimeError("Database identity does not match the URL") if identity_before.current_user != database.role: raise RuntimeError("Database user identity does not match the role") assert_identity_is_low_privilege(identity_before) temporary_schema = create_temporary_schema( database, prefix=APPROVED_TEST_SCHEMA_PREFIX, ) assert_schema_matches_approved_rule(temporary_schema) return database, temporary_schema, identity_before
--- name: legacy-agent-readiness description: Prepare legacy repositories for safe, evidence-based Agent work. Use when auditing an existing repository, establishing verified commands and guidance, adding characterization tests, or running an approved readiness pilot. disable-model-invocation: true ---
# Legacy Agent Readiness
## Purpose Make a legacy repository safe to explore, verify, and change incrementally.
## Inputs - Approved repository scope. - Current `docs/agent-readiness/BASELINE.md`. - Human owner for the requested change. - A non-production environment.
## Workflow 1.`audit`: inspect repository facts in read-only mode. 2.`baseline`: record verified commands, failures, risks, owners, and unknowns. 3.`scripts`: create fail-safe bootstrap and verification adapters from execution-verified commands. 4.`guidance`: maintain concise AGENTS.md files and migrate stale guidance. 5.`tests`: add characterization tests before behavior changes. 6.`pilot`: execute one low-risk reversible task. 7.`adoption`: expand scope only after evidence and approval. 8.`boundaries`: enforce secret, production, generated-file, and migration limits. 9.`report`: record changed files, commands, outputs, approvals, risks, and rollback.
## Evidence Rules - Mark missing facts as TO_BE_VERIFIED_FROM_REPOSITORY or BLOCKED. - Mark unknown commands as TO_BE_VERIFIED_FROM_REPOSITORY. - Never treat a placeholder as success. - Preserve command IDs, sanitized argv evidence, exit codes, relevant output, commit, and environment in controlled execution evidence. - Redact credentials, tokens, cookies, personal data, internal URLs, and secret values.
## Change Rules - Explore before editing. - Use the smallest approved scope. - Do not refactor unrelated legacy code. - Do not upgrade dependencies during readiness work without separate approval. - Do not write to production or use production credentials. - Do not modify generated files without an approved regeneration path.
## Stop Conditions Stop and request human review when: - A command, owner, contract, or boundary is unverified. - The task requires migration, deployment, authentication, or cross-module changes. - Verification fails for an unknown reason. - A secret or production access path is encountered. - The approved scope must expand.
## Completion Report Report: - Scope and changed files. - Exact verification commands and exit codes. - Before and after evidence. - Known failures and unverified items. - Approval records and rollback procedure.
Use the project Skill `.agents/skills/legacy-agent-readiness/SKILL.md`. Run only the `pilot` workflow for this approved scope: - Scope: TO_BE_VERIFIED_FROM_REPOSITORY - Owner: TO_BE_VERIFIED_FROM_REPOSITORY - Environment: isolated non-production - Rollback: TO_BE_VERIFIED_FROM_REPOSITORY
First read BASELINE.md and the nearest AGENTS.md. Stop before editing if any command, boundary, owner, or rollback procedure is unverified. Return the proposed plan and approval request before implementation.
- Pilot ID: TO_BE_VERIFIED_FROM_REPOSITORY - Task type: documentation update or characterization test only - Owner: TO_BE_VERIFIED_FROM_REPOSITORY - Read-only exploration scope: TO_BE_VERIFIED_FROM_REPOSITORY - Production access: false - Credential and secret boundary: no secret values may be read or copied - Pre-Explore decision: approved or BLOCKED - Approver: TO_BE_VERIFIED_FROM_REPOSITORY
Implementation Gate
Explore 完成后、Implement 之前,必须单独填写并批准以下门禁:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Implementation Gate
- Pilot ID: TO_BE_VERIFIED_FROM_REPOSITORY - Exact file allowlist: TO_BE_VERIFIED_FROM_REPOSITORY - Explicitly forbidden paths: generated files, shared configuration, migrations, deployment files, credentials, and production configuration - Risk level: low - Rollback procedure: TO_BE_VERIFIED_FROM_REPOSITORY - Database isolation evidence: not applicable or TO_BE_VERIFIED_FROM_REPOSITORY - Related command IDs: TO_BE_VERIFIED_FROM_REPOSITORY - Every related command status: EXECUTION_VERIFIED - Production access: false - Credential or secret exposure: false - Implementation decision: approved or BLOCKED - Approver: TO_BE_VERIFIED_FROM_REPOSITORY - Approval recorded at: TO_BE_VERIFIED_FROM_REPOSITORY
Use `.agents/skills/legacy-agent-readiness/SKILL.md` for this pilot.
Pilot task: - Type: documentation update or characterization test only - Scope: TO_BE_VERIFIED_FROM_REPOSITORY - Issue: TO_BE_VERIFIED_FROM_REPOSITORY - Owner: TO_BE_VERIFIED_FROM_REPOSITORY - Rollback: revert the approved commit or restore the approved file change
Explore: - Read BASELINE.md, the nearest AGENTS.md, the relevant README, source, tests, and CI entry. - Do not edit anything. - Return facts, execution-verified command IDs, affected files, risks, and unknowns.
Plan: - Propose the smallest reversible diff. - State what is explicitly out of scope. - State the approval needed before implementation. - Stop for human approval.
Implement: - Edit only approved files. - Do not change business behavior, dependencies, migrations, deployment, or generated files. - Show the diff immediately after editing.
Verify: - Run the approved fast verification command by command ID. - Run the focused test or documentation check from the repository. - Return command IDs, exit codes, relevant output, and environment. - Stop if any command is not EXECUTION_VERIFIED or fails unexpectedly.
Review: - Review the diff before the success summary. - Confirm scope, evidence, redaction, rollback, and no unrelated changes. - Return a completion report with changed files, approvals, risks, and unverified items.
Agent 产物
Pilot 应产生 Explore 事实清单、Plan、经批准的最小 diff、验证报告、diff-first review 和完成报告。文档任务的证据应证明链接/命令来自仓库;characterization test 任务的证据应证明测试捕获当前行为而没有修复它。
## Stage 0: Read-only Entry evidence: - Approved read-only audit. - BASELINE.md with SOURCE_CONFIRMED, EXECUTION_VERIFIED, FAILED, BLOCKED, and SKIPPED facts. - Secret and production boundaries identified. Allowed: - Repository reading, history inspection, and evidence planning. Rollback: - Stop the session and discard local evidence that is not approved.
## Stage 1: Documentation and Tests Entry evidence: - Stage 0 approved. - Root and nested guidance reviewed. - Isolated test database or fixtures confirmed. - Fast verification adapter returns correct non-zero failures. Allowed: - README, AGENTS.md, project Skill, and characterization tests. Rollback: - Revert the small approved commit and remove unapproved evidence.
## Stage 2: Scoped Code Entry evidence: - Stage 1 pilot completed with diff-first review. - Characterization tests cover the selected boundary. - Owner, rollback, and exact verification commands are approved. Allowed: - One named module or route path with no migration, deployment, or dependency upgrade. Rollback: - Revert the scoped change, rerun characterization and verification, and request review.
## Stage 3: Cross-module Entry evidence: - Multiple scoped changes have stable evidence. - API, web, and database owners approve the dependency map. - Full verification and CI entry are reproducible. - Rollback and compatibility plans are tested. Allowed: - Explicitly approved cross-module work. Never implicit: - Production access, infrastructure changes, migrations, secret handling, or deployment approval. Rollback: - Stop at the first unexpected boundary change and return to the last approved stage.
## Stage 2 Admission - Three consecutive approved pilots completed. - Two weeks of observation after the third pilot. - Required CI passed on 100 percent of approved commits. - Zero unexplained verification failures. - One successful rollback drill. - API, web, and database owners signed off.
## Stage 3 Admission - Five consecutive approved scoped PRs completed. - Four weeks of observation after the fifth scoped PR. - Required CI passed on 100 percent of approved commits. - Zero unexplained verification failures. - Rollback drill completed for each relevant boundary. - API, web, database, and release owners signed off.
## Demotion - Any threshold becomes false: demote to the previous stage. - Any unexplained failure: pause scope expansion until explained and approved. - Any boundary, secret, production, or rollback violation: stop immediately. - No stage grants implicit production, infrastructure, migration, or deployment access.
You are the bootstrap agent for a large repository change.
Goal: Migrate the legacy search module to a new implementation while preserving the existing public API, response shape, error behavior, and supported client behavior unless an approved decision says otherwise.
Scope: 1. Compatibility contract and characterization tests. 2. Backend implementation behind the existing interface. 3. Client integration and explicit loading, empty, and error states. 4. Migration cleanup only after adoption evidence and approval.
Non-goals: - Do not redesign the public API. - Do not change unrelated modules, dependencies, lock files, or generated files. - Do not run production writes, deploy, push, merge, or delete user changes.
Required read-only exploration: - Read the repository README, contribution guide, CI configuration, build files, package or dependency manifests, existing search code, client code, tests, migration files, and verification scripts. - Locate the public search interface, request and response types, error mapping, persistence boundary, client call sites, and existing test commands. - Do not edit files during exploration. - If a path or command cannot be verified, mark it as unknown instead of guessing.
Required output before writing: - A file-and-symbol evidence map. - Four independently verifiable slices with dependencies and non-goals. - Compatibility invariants and characterization-test candidates. - Risks, approval points, rollback points, and unresolved questions. - Verified repository commands for focused, fast, full, integration, and end-to-end checks, or an explicit unconfigured marker.
Approval points: - Ask before changing a public interface or response shape. - Ask before changing a database schema, migration, external service, or production configuration. - Ask before adding or upgrading a dependency or changing a lock file. - Ask before any push, merge, deployment, deletion, or production write.
After the read-only report: - Create only docs/roadmaps/search-migration/ROADMAP.md. - Do not create STATE.md yet. - Include the goal, scope, four slices, dependencies, evidence paths, verification commands, approval points, rollback strategy, and stop conditions. - Report the exact created file and keep all unknowns explicit.
Done when: - The read-only evidence report is complete. - ROADMAP.md exists and is internally consistent. - No source, test, dependency, migration, or configuration file was edited.
Replace the legacy search implementation behind the existing public API. Existing clients must continue to receive the same successful response shape and documented error behavior during the migration.
## Evidence Map
- Public interface: `REPLACE_WITH_VERIFIED_INTERFACE_SYMBOL` in `REPLACE_WITH_VERIFIED_PATH` - Legacy implementation: `REPLACE_WITH_VERIFIED_SYMBOL` in `REPLACE_WITH_VERIFIED_PATH` - Client entry point: `REPLACE_WITH_VERIFIED_SYMBOL` in `REPLACE_WITH_VERIFIED_PATH` - Existing tests: `REPLACE_WITH_VERIFIED_TEST_PATH` - Verified fast check: `REPLACE_WITH_VERIFIED_COMMAND` - Verified full check: `REPLACE_WITH_VERIFIED_COMMAND`
## Slices
1. Compatibility contract and characterization tests - Capture current request, response, status, error, ordering, and edge-case behavior. - Write focused tests without changing the public interface. 2. Backend implementation behind the existing interface - Implement the new search engine behind the existing adapter or interface. - Keep old and new implementations comparable until adoption evidence exists. 3. Client integration and error states - Switch the client through the existing API. - Cover loading, empty, invalid-input, authorization, timeout, and server-error states. 4. Migration cleanup after adoption - Remove obsolete paths only after approval, adoption evidence, rollback readiness, and the integration matrix are complete. ## Dependencies
- Slice 2 depends on the contract and tests from Slice 1. - Slice 3 depends on the stable API behavior from Slice 2. - Slice 4 depends on adoption evidence and explicit approval.
## Compatibility Invariants
- Preserve the public method or route signature. - Preserve successful response fields, types, and documented ordering. - Preserve status codes and error envelope for known failures. - Preserve authentication, authorization, timeout, and retry behavior.
- Public interface or response change: required. - Schema, migration, or external service change: required. - Dependency or lock-file change: required. - Production write, deployment, push, or merge: required.
## Rollback
- Keep each slice in a separate branch or worktree. - Revert to the latest verified checkpoint after confirming the checkpoint and working-tree state; do not rewrite history or remove user changes.
## Stop Conditions
- A compatibility test contradicts the proposed behavior. - A required command is unknown or fails for an unexplained reason. - Two tasks need to edit the same shared file or public interface. - A migration, dependency, production, or external write needs approval.
Create docs/roadmaps/search-migration/STATE.md from ROADMAP.md. Read ROADMAP.md, the current branch, and the current worktree first. Do not edit source, tests, dependency files, migrations, or configuration. Use only verified facts. Mark assumptions as assumptions and preserve unknowns. After creating the file, report its path and the evidence used.
- Roadmap exists at `docs/roadmaps/search-migration/ROADMAP.md`. - Public interface is `REPLACE_WITH_VERIFIED_SYMBOL` in `REPLACE_WITH_VERIFIED_PATH`. - Characterization test command is `REPLACE_WITH_VERIFIED_COMMAND`. - Last verified checkpoint: `REPLACE_WITH_VERIFIED_COMMIT`. - Last verification result: `REPLACE_WITH_VERIFIED_COMMAND` exited with `0`.
## Decisions
- Preserve the existing public API and response envelope. - Keep the legacy implementation available until adoption is verified. - Do not change schema, dependencies, or lock files without approval.
## Open Questions
- [ ] Confirm the adoption threshold and observation window. - [ ] Confirm whether the timeout behavior is part of the supported contract.
- For a large task, read `docs/roadmaps/<feature>/ROADMAP.md` and `docs/roadmaps/<feature>/STATE.md` before editing. - After every slice has been verified, update `STATE.md` with the verified checkpoint, commands, exit statuses, changed scope, skipped checks, risks, current slice, and next slice. - Before ending a session, update `STATE.md` and create or update `docs/roadmaps/<feature>/HANDOFF.md`. - Do not claim that state is current unless the relevant files, branch, worktree, and verification commands were checked in this session. - Prompt, Skill, or explicit task instructions must trigger these updates; agents must not assume that state files are maintained automatically.
--- name: large-task-workflow description: Execute a tracked eight-step workflow for large changes across slices and sessions. ---
# Large Task Workflow
## Trigger
Use when a task spans multiple modules, sessions, agents, branches, worktrees, or a compatibility-sensitive migration.
## Required inputs
- User-visible goal, scope, non-goals, and approval points. - Existing repository facts and verified commands. - Roadmap path and state path, or permission to create them. - Named slice, allowed files, dependencies, and rollback checkpoint.
## Required workflow
1. Read-only exploration and Roadmap creation. 2. State creation and explicit state-maintenance trigger. 3. Clean baseline, verification, commit recording, and isolated worktree. 4. Read-only and non-overlapping implementation delegation. 5. Explore, Plan, Implement, Verify, and Review for one slice. 6. Cross-slice integration matrix and evidence log. 7. Handoff creation and fresh-session revalidation. 8. Stop, recover, or continue only from a verified checkpoint.
- Read `AGENTS.md` and the roadmap state before editing. - Do not guess commands, paths, business status, or compatibility facts. - Do not parallelize edits to a public interface, migration, lock file, or shared source file. - Do not push, merge, deploy, delete user changes, rewrite history, or perform production writes without explicit approval. - Do not use `git reset --hard` or `git clean`. - Do not treat this Skill, a Prompt, an instruction file, or a Hook as a security boundary.
## Verification and handoff
- Record actual commands and exit statuses. - A checkpoint is verified only after required verification exits `0` and Review passes. - Before ending a session, update `STATE.md` and write `HANDOFF.md`. - A new session must revalidate the checkpoint, worktree, and key facts before editing.
## Recovery
- Stop on unexplained failures, contradictory contract evidence, scope overlap, or missing approval. - Find the latest verified checkpoint using read-only Git commands. - Create a new worktree from that checkpoint and continue with a new Prompt.
之后用精简任务 Prompt 调用该 Skill:
1 2 3 4 5
Use the project skill large-task-workflow for the search migration. Read AGENTS.md, ROADMAP.md, and STATE.md first. Work only on the named slice, record actual commands and exit statuses, update state after verification and before session end, and stop for approval or scope overlap. Do not push, merge, deploy, delete user changes, use git reset --hard, or use git clean.
You are a read-only investigation subagent for Slice 1 of the search migration.
Task: Map the existing public search contract and identify characterization tests needed before replacing the legacy implementation.
Read only: - AGENTS.md - docs/roadmaps/search-migration/ROADMAP.md - docs/roadmaps/search-migration/STATE.md - The verified public search interface and its implementation - Existing search tests and client call sites - Relevant README, CI, build, dependency, and verification files
Write scope: None. Do not edit, create, delete, format, or generate files.
Investigate: - Request method, path or method signature, headers, parameters, and defaults. - Success response fields, types, ordering, pagination, and empty results. - Status codes and error envelope for invalid input, unauthorized access, timeout, unavailable backend, and unexpected failure. - Authentication, authorization, retry, idempotency, and persistence boundaries. - Existing test coverage, test fixtures, generated files, migrations, and shared files that must not be changed in parallel.
Output: 1. A table of claims with evidence paths and symbols. 2. A characterization-test list with expected current behavior. 3. Unknowns and assumptions, clearly labeled. 4. Risks, approval points, and a recommended non-breaking test plan. 5. Verified commands and their exit statuses if you run any read-only checks.
Constraints: - Do not infer business behavior from names alone. - Do not modify public interfaces, migrations, dependencies, lock files, or shared source files. - Do not push, merge, deploy, or perform external writes. - Stop if a required fact cannot be verified.
You are an implementation subagent for the named search migration slice.
Preconditions: - Read AGENTS.md, ROADMAP.md, STATE.md, and the approved investigation report. - Confirm the current branch and worktree. - Confirm the exact allowed files below and stop if they are already modified.
Slice: Compatibility contract and characterization tests only.
Forbidden write scope: - Public interfaces, routes, request or response types. - Legacy or new implementation code. - Client code. - Database migrations or schema files. - Dependency manifests and lock files. - Generated files and shared configuration. - Any file outside the allowed write scope.
Implementation requirements: - Capture current behavior, including documented edge cases and known behavior that must remain compatible during migration. - Make tests deterministic and focused. - Do not “fix” production behavior in this slice. - If actual behavior contradicts the Roadmap, stop and report evidence.
Verification: - Run the verified focused test command. - Run the verified fast command if this slice permits it. - Record exact commands, exit statuses, skipped checks, and remaining risks.
Review handoff: - Report changed files, test names, behavior captured, and evidence paths. - Do not commit, push, merge, deploy, or change shared files. - Stop after producing the implementation diff and verification report.
Read AGENTS.md, ROADMAP.md, STATE.md, and the read-only investigation report. Explore only the legacy search interface, implementation, client call sites, fixtures, and existing tests. Do not edit files. Return an evidence map, compatibility invariants, test candidates, forbidden files, verified commands, and unresolved questions.
Create a file-level implementation plan for Slice 1 only. The plan must list each allowed file, each characterization behavior, test data, expected current result, verification command, and rollback point. Do not change source files, public interfaces, migrations, dependencies, lock files, or client code. Ask for approval if the plan requires any forbidden file.
Implement only the approved Slice 1 plan. Add deterministic characterization tests for the verified current search contract. Keep production code, public interfaces, migrations, dependency manifests, lock files, client files, generated files, and shared configuration unchanged. After editing, show the diff and stop before any commit, push, or merge.
Review the complete diff for Slice 1 against ROADMAP.md, STATE.md, the approved plan, and the compatibility evidence. Check scope, test fidelity, determinism, public API preservation, forbidden file changes, generated-file rules, dependency changes, and verification evidence. Return PASS or FAIL with file-and-symbol findings. Do not edit files, commit, push, merge, or deploy.
The human owner will create the checkpoint after verification and review pass. Update STATE.md with the checkpoint only after the owner provides its commit identifier. Do not create a remote branch, push, merge, or deploy.
Implement Slice 2 of the search migration behind the existing public interface. Read AGENTS.md, ROADMAP.md, STATE.md, and the approved Slice 2 exploration and plan first. Use only the implementation and test paths explicitly verified in those artifacts; replace no path or command from guesswork.
Keep the legacy implementation available for fallback and side-by-side comparison. Preserve the existing request, response, status-code, error mapping, authentication, timeout, retry, and ordering behavior.
Before editing, confirm the allowed files and stop on scope overlap. Do not modify public interfaces, client code, migrations, dependency manifests, lock files, generated files, or shared configuration unless separately approved. Add focused tests for equivalent results, error mapping, concurrent requests, fallback behavior, and the performance threshold recorded in the plan. Run only the verified focused commands, report exact exit statuses, and stop before commit, push, merge, deploy, or production writes.
允许修改范围如何确定:只读探索现有 API client、搜索页面或调用组件、状态管理、类型、测试 fixture 和 UI 测试入口;只把探索报告确认的客户端文件加入计划。UI 证据按仓库能力和需求风险决定是否需要。
禁止范围:后端公共接口、服务端迁移、依赖和锁文件、无关页面、生成文件、未批准的 API 类型变更及其他切片正在使用的源文件。
专属 Agent Prompt:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Implement Slice 3 of the search migration through the existing API. Read AGENTS.md, ROADMAP.md, STATE.md, and the approved Slice 3 exploration and plan. Use only verified client paths, symbols, fixtures, and commands from those artifacts.
Connect the client without changing the public API. Implement and test loading, empty, server-error, authorization-error, invalid-input, and timeout states. Preserve existing successful data rendering, request cancellation, retry, and accessibility behavior where verified.
Write only the approved client and client-test files. Do not edit backend interfaces, migrations, dependency manifests, lock files, generated files, unrelated screens, or shared files outside the plan. If visual evidence is required, capture the approved user path, states, viewport, console, network, and accessibility evidence. Run verified focused checks and report commands and exit statuses. Do not commit, push, merge, deploy, or perform external writes.
Prepare Slice 4 cleanup for the search migration only after adoption evidence and explicit human approval are present in STATE.md.
Read AGENTS.md, ROADMAP.md, STATE.md, HANDOFF.md, the adoption evidence, and the approved cleanup plan. Reconfirm every cleanup path from repository facts. If adoption evidence, rollback evidence, or approval is missing, stop without editing and report the missing item.
Before editing, list the exact legacy files, migration files, lock-file changes, and public-interface references in scope. Preserve a tested rollback or restore path. Treat deletion, schema or data migration, lock-file modification, and public-interface change as separate approval points; do not bundle them into implicit approval.
After approval, make only the approved cleanup changes. Run the verified focused cleanup, compatibility, migration-order, rollback, and recovery checks. Report actual commands, exit statuses, skipped checks, and evidence. Do not push, merge, deploy, or perform production writes.
- Branch: `REPLACE_WITH_BRANCH` - Worktree: `REPLACE_WITH_WORKTREE` - Base commit: `REPLACE_WITH_BASELINE_COMMIT` - Last verified checkpoint: `REPLACE_WITH_COMMIT` - Working tree status result: `REPLACE_WITH_STATUS_OUTPUT`
- Decision: `REPLACE_WITH_DECISION` - Open question: `REPLACE_WITH_QUESTION`
## Next safe action
`REPLACE_WITH_READ_ONLY_OR_APPROVED_COMMAND`
## Boundaries
- Do not push, merge, deploy, delete user changes, rewrite history, use `git reset --hard`, or use `git clean`. - Ask before changing public interfaces, migrations, dependencies, lock files, production configuration, or external systems.
Before editing: 1. Read AGENTS.md, ROADMAP.md, STATE.md, and HANDOFF.md. 2. Confirm the current branch and worktree. 3. Confirm the working-tree status without changing it. 4. Re-verify that the last checkpoint exists and inspect its diff. 5. Re-run the key verification command recorded in the handoff. 6. Re-check the public search interface, current slice, and next-slice preconditions against repository files.
If any fact, command, checkpoint, or worktree differs from the handoff, stop and report the discrepancy. Otherwise continue only with the named next slice and its allowed files. Record actual commands and exit statuses, update STATE.md after verification, and update HANDOFF.md before ending.
Do not push, merge, deploy, delete user changes, rewrite history, use git reset --hard, or use git clean.
The previous search migration attempt is blocked or needs a fix. Read AGENTS.md, ROADMAP.md, STATE.md, HANDOFF.md, and the failure evidence. Determine the current status from STATE.md before taking any action. If the status is blocked, resume only through blocked -> exploring after the missing fact, dependency, or human approval is present and related facts have been revalidated read-only. If the status is needs-fix, resume only through needs-fix -> ready-for-implementation after the failure cause, allowed fix scope, and revised plan have been confirmed by a human. Never transition needs-fix directly to implementing. Record the recovery transition in STATE.md with trigger evidence, human owner, approver, original status, target status, time, revalidation command, exit status, and result. If any precondition is missing, preserve the original status and stop editing. Use only the latest checkpoint explicitly marked verified in STATE.md. The human owner will create a new worktree from that checkpoint; do not rewrite history or modify the existing worktree. In the new worktree, verify the checkpoint, branch, working-tree status, public search contract, and recorded verification command before editing. Continue only with the named slice and approved files. Preserve the existing API. Record the failed evidence, new commands, exit statuses, review result, and state transitions. Do not use git reset --hard or git clean, and do not push, merge, deploy, delete user changes, or perform external writes.
You are classifying a Search App change for read-only verification.
Read only: - The current diff and merge plan. - The verified public API contract. - The repository map, real scripts, and environment documentation. - The large-task STATE.md and HANDOFF.md when present. - React and TypeScript UI paths. - FastAPI routes, dependencies, schemas, and tests. - PostgreSQL and Alembic migration paths. - Terraform and Kubernetes paths.
Do not edit source files, tests, migrations, infrastructure state, or external systems. Do not run production commands or print secrets.
Classify the change as UI, API, database, infrastructure, or a combination. For every affected domain, report observable acceptance criteria, failure impact, environment prerequisites, required checks, owner, approval gate, rollback compatibility, read-only actions, forbidden writes, and unknowns. Use TO_BE_VERIFIED_FROM_REPOSITORY for every unverified path or command. Write only the requested classification report to: artifacts/verification/<change-id>/classification.md If artifacts is ignored, report the controlled external evidence index strategy instead of changing ignore rules.
Create an append-only, versioned evidence bundle for a Search App change.
Read the verified repository evidence entry points, classification report, and approved storage policy first. Use TO_BE_VERIFIED_FROM_REPOSITORY for any unknown command or storage adapter. Do not edit source files or change ignore rules.
Create a new bundle version instead of overwriting an earlier bundle. For every saved, redacted artifact record the hash algorithm, byte size, generated_at timestamp, digest, redaction summary, command, exit status, and owner. Keep original sensitive plans or logs only in controlled storage; never print them in ordinary logs.
Finalize the manifest and delivery report in a separate step. Generate their independent digests and anchor them to an immutable external version, timestamp, and access-control evidence. Define the self-reference boundary: the manifest may describe its own pre-finalization digest input, while the final digest covers the finalized manifest and report bytes without recursively embedding their own final digest.
Verify the Search App UI in the approved test environment.
First read the repository's verified UI start command, Playwright configuration, test fixtures, route paths, and the classification report. Replace no command from guesswork; use TO_BE_VERIFIED_FROM_REPOSITORY until repository exploration confirms it.
Exercise the real user-observable flow: sign in with approved test credentials -> search -> apply a filter -> open a result. Cover loading, success, empty, error, disabled, and long-text states. Run approved desktop and mobile viewports. Capture before and after screenshots, browser trace, console errors, failed network requests, and accessibility results. Use keyboard navigation for the complete flow.
Do not use production credentials, print secrets, mutate production data, or delete failed evidence. Run automated axe and semantic checks, manual keyboard checks, manual visual and contrast checks, and a real screen reader when the approved scope requires it. Automated checks do not prove full WCAG compliance. Write results and artifact paths to the verification evidence directory. Report pass, fail, blocked, skipped, and pre-existing failures separately.
Verify the Search App FastAPI contract in the approved isolated environment.
Read the verified route, dependency, schema, authentication, authorization, test fixture, and test command from the repository. Use the real route and dependency boundary. Do not infer paths, statuses, headers, or response shapes. Replace unknowns with TO_BE_VERIFIED_FROM_REPOSITORY.
Cover valid, empty, invalid, unauthenticated, unauthorized, and timeout behavior. Run retry checks only when the contract explicitly allows retries and the isolated fixture is cleanable. For non-idempotent operations, record N/A or verify that the client does not retry; never create duplicate external side effects. Test idempotency only for an operation where the contract requires it. Check request and response schemas, error envelope, pagination, ordering, and backward compatibility. Use only an isolated service and database or an approved sandbox. Do not write production data and do not print credentials.
Record commands, exit statuses, sanitized request and response summaries, uncovered real-service behavior, failures, and artifacts in the verification evidence directory.
Verify the PostgreSQL and Alembic change in a temporary isolated database.
Read the verified database URL mechanism, migration command, revision range, schema invariants, data invariants, compatibility requirements, and repository backup or restore procedure. Use only the minimum migration privileges and object ownership scoped to the isolated database, plus an explicit positive allowlist of migration actions. Use TO_BE_VERIFIED_FROM_REPOSITORY for unknown commands.
Run the migration upgrade in the temporary database. Check schema and data invariants, old-application compatibility, new-application compatibility, lock-sensitive behavior, and migration duration. If downgrade is safe and approved, run a downgrade rehearsal. If it is not safely reversible, do not run downgrade; perform the approved restore rehearsal or document a tested forward-fix path.
Never connect to production or staging. Do not print connection strings, credentials, secrets, or raw sensitive data. Preserve failed evidence and record the backup point, restore result, exit status, and reviewer.
命令占位:
1 2 3 4
TO_BE_VERIFIED_FROM_REPOSITORY TO_BE_VERIFIED_FROM_REPOSITORY upgrade head TO_BE_VERIFIED_FROM_REPOSITORY downgrade REPLACE_WITH_APPROVED_REVISION TO_BE_VERIFIED_FROM_REPOSITORY --check-invariants
Verify Terraform and Kubernetes changes without external production writes.
Read the repository's verified Terraform entry points, backend, account, workspace, provider, lock and refresh policy, policy checks, Kubernetes manifests, schema validator, and approved sandbox cluster procedure. Before running checks, record the read-only cluster URL, identity, context, namespace, Terraform account, backend, and workspace, then match them against the explicit allowlist. Use TO_BE_VERIFIED_FROM_REPOSITORY for unknown commands.
Run only fmt, validate, plan, policy checks, schema validation, `kubectl diff`, and `kubectl apply --server-side --dry-run=server` against an approved sandbox cluster. These Kubernetes commands require explicit fixed context and namespace. The server dry-run contacts the API server and admission webhooks and is not a purely local check. Review resource replacement, network exposure, IAM or RBAC changes, Secret references, cost, and irreversible actions. Do not run production apply, delete, destroy, permission expansion, or state mutation. Do not print credentials or raw plan secrets. Do not show raw `terraform show` output in ordinary logs.
If no approved sandbox cluster exists, mark the cluster checks SKIPPED or BLOCKED with the exact missing prerequisite, owner, and next safe action. Redact sensitive plan and diff output before storing evidence.
Build the Search App cross-layer compatibility matrix from verified evidence.
Read the classification, manifest, UI and API evidence, database migration evidence, infrastructure evidence, approved contract, and STATE.md or HANDOFF.md when present. Use TO_BE_VERIFIED_FROM_REPOSITORY for any missing repository command or path. Do not run production actions or edit source files.
Evaluate old and new schema against old and new API, and old and new UI. For each combination record compatible, incompatible, not applicable, or unknown. For every incompatible combination state whether the safe path is rollback, forward-fix only, or restore required. For an irreversible data change, require API and UI forward-fix evidence or an approved restore path.
List required evidence for every gate: classification, environment identity, artifact digests, schema and data invariants, API contract and auth results, UI observable and accessibility results, Terraform and Kubernetes read-only results, observation results, rollback or restore rehearsal, and human approvals. Produce the gate record and stop on missing required evidence.
| Row | Schema | API | UI | Status | Evidence | Rollback class | | --- | --- | --- | --- | --- | --- | --- | | 1 | old | old | old | REPLACE_WITH_STATUS | REPLACE_WITH_EVIDENCE | rollback | | 2 | old | old | new | REPLACE_WITH_STATUS | REPLACE_WITH_EVIDENCE | rollback/forward-fix only/restore required | | 3 | old | new | old | REPLACE_WITH_STATUS | REPLACE_WITH_EVIDENCE | rollback/forward-fix only/restore required | | 4 | old | new | new | REPLACE_WITH_STATUS | REPLACE_WITH_EVIDENCE | rollback/forward-fix only/restore required | | 5 | new | old | old | REPLACE_WITH_STATUS | REPLACE_WITH_EVIDENCE | rollback/forward-fix only/restore required | | 6 | new | old | new | REPLACE_WITH_STATUS | REPLACE_WITH_EVIDENCE | rollback/forward-fix only/restore required | | 7 | new | new | old | REPLACE_WITH_STATUS | REPLACE_WITH_EVIDENCE | rollback/forward-fix only/restore required | | 8 | new | new | new | REPLACE_WITH_STATUS | REPLACE_WITH_EVIDENCE | rollback/forward-fix only/restore required |
For every row, use `N/A` plus a reason when the combination is not applicable. Do not omit a row. A missing evidence reference is `BLOCKED` or `UNKNOWN`, not `passed`.
## Required Evidence
- Classification and approved environment identity: - Schema and data invariants: - API contract, authn, authz, timeout, and retry result: - UI observable, keyboard, and scoped accessibility result: - Terraform and Kubernetes read-only result: - Raw kubectl diff exit code, verified kubectl version, and interpreted result: - Observation result: - Rollback, forward-fix, or restore rehearsal: - Human approvals:
--- name: change-verification-matrix description: Build an auditable cross-layer verification matrix from verified evidence. ---
# Change Verification Matrix
## Trigger
Use after a UI, API, database, infrastructure, or cross-layer change has a verified classification and an approved non-production verification environment.
## Inputs
-`artifacts/verification/<change-id>/classification.md` -`artifacts/verification/<change-id>/manifest.json` - Domain evidence for UI, API, database, and infrastructure - Cross-layer gate records -`STATE.md` and `HANDOFF.md` when present - The complete diff and approved change contract
## Procedure
1. Confirm the baseline commit, candidate commit, environment, scope, and owners. 2. Read every manifest record and verify its artifact hash. 3. Reconcile each result with the command exit status and observed artifact. 4. Mark each check as `passed`, `failed`, `blocked`, `skipped`, or `unknown`. 5. Preserve pre-existing failures and distinguish them from new regressions. 6. Check the order `DB expand -> backward-compatible API -> UI enable -> observe -> cleanup`. 7. Collect independent findings from UI, API, database, and infrastructure reviewers. 8. Mark Critical and Important findings as release blockers until fixed or explicitly accepted by the authorized human owner. 9. Verify that every saved redacted artifact records algorithm, digest, size, and generated_at, and that final manifest/report digests are independently anchored. For the manifest digest, remove `finalization.manifest_digest`, serialize the remaining object with RFC 8785 JCS as UTF-8 bytes, and compute SHA-256. 10. Produce the verification matrix, reviewer findings, and delivery report.
## Evidence Rules
- Never invent a command, result, artifact, approval, or hash. - Never overwrite an earlier evidence directory or mutate its manifest. - Never include credentials, tokens, cookies, raw secrets, or unredacted sensitive logs. - A skipped check is never a passed check. - A plan or dry-run is evidence of intent, not proof of a successful apply. - Evidence bundles are append-only, versioned, and stored under controlled access. - Artifact hashes cover the redacted saved file, not an unsaved or raw source. - The final manifest and report have independent digests anchored to an immutable external version, timestamp, and access-control evidence. - The manifest digest input removes `finalization.manifest_digest` before RFC 8785 JCS serialization; record the RFC/JCS version and SHA-256 algorithm. - The self-reference boundary must be explicit: a final digest does not recursively include its own embedded final digest value. - Production writes, deletes, destroys, permission expansion, and data mutation are forbidden in this workflow.
## Review Gates
- UI owner: observable behavior, visual regression, keyboard flow, accessibility. - API owner: contract, authentication, authorization, errors, timeout, retry, idempotency. - Database owner: invariants, lock risk, compatibility, rollback or restore rehearsal. - Infrastructure owner: target, policy, permissions, network, cost, replacement risk. - Authorized human delivery owner: final decision and any explicit risk acceptance.
Complete only when every required check has evidence, every skip or block has a reason and owner, Critical and Important findings are fixed or explicitly block delivery, required approvals are recorded, final digests are independently anchored, production promotion authorization is explicitly recorded as `NOT_AUTHORIZED` by default or approved by an authorized human with approver, scope, and expiration, and no production action was run.
Read the classification, manifest, all domain evidence, cross-layer gate records, the complete diff, the approved contract, and STATE.md or HANDOFF.md when present. Verify artifact hashes and reconcile commands with exit statuses. Do not invent missing evidence, approvals, commands, or results. Preserve failed, skipped, blocked, unknown, and pre-existing statuses.
Apply the order DB expand -> backward-compatible API -> UI enable -> observe -> cleanup. Treat Critical and Important findings as blockers until fixed or explicitly accepted by the authorized human owner. Do not self-approve production. Set production promotion authorization to NOT_AUTHORIZED unless an authorized human provides approver, scope, and expires_at. Non-production verification is not production authorization. Do not run production writes and do not include secrets.
--- description: API contract checks for server and client API files globs: - "src/**/api/**/*" - "tests/**/api/**/*" alwaysApply: false ---
Read the root `AGENTS.md` before editing.
- Preserve the existing public response shape unless the task contract approves a change. - Add tests for success, invalid input, authentication, authorization, timeout, retry, and idempotency. - Do not change migrations or external service configuration without explicit approval. - Run the repository's focused API checks after each vertical slice. - Report commands, exit status, skipped checks, and remaining risks.
--- name: release-check description: Run a read-only release readiness check and produce evidence. ---
# Release Check
## Use when
Use this workflow before proposing a release or delivery.
## Steps
1. Read `AGENTS.md` and `STATE.md` if present. 2. Confirm the current branch and working tree. 3. Run the repository's verified fast and full checks. 4. Review the diff without editing files. 5. Report commands, exit status, skipped checks, risks, and rollback steps.
## Boundaries
- Do not push, merge, deploy, delete, or change production state. - Do not print secrets or long-lived tokens. - Do not claim a skipped check passed.
- [ ] Runtime and package manager are documented. - [ ] Repository map exists. - [ ] Generated and dangerous areas are marked. - [ ] Secrets are excluded from source and instructions.
## Commands
- [ ] Bootstrap is real and repeatable. - [ ] Fast verification is real and repeatable. - [ ] Full verification is real and repeatable. - [ ] CI reuses repository verification scripts. - [ ] Baseline failures are recorded.
## Guidance
- [ ] Root `AGENTS.md` contains facts and hard boundaries. - [ ] Path-specific rules are short and scoped. - [ ] Skills describe repeatable workflows. - [ ] Tool-specific formats are not copied across products.
## Isolation and safety
- [ ] Agent work uses a branch or worktree. - [ ] Sandbox and network boundaries are configured. - [ ] Allow/Deny policies are reviewed. - [ ] Hooks are tested and fail closed where required. - [ ] Production writes require human approval. - [ ] CI and branch protection remain authoritative.
## Delivery
- [ ] Task contract includes non-goals and approval points. - [ ] Evidence includes commands and exit statuses. - [ ] Skipped checks are explicit. - [ ] Rollback is documented.
- [ ] The PR has one clear user-visible purpose. - [ ] The task contract and non-goals are included. - [ ] The diff contains no unrelated cleanup. - [ ] Generated files were changed only through their generator.
## Evidence
- [ ] Baseline commit is recorded. - [ ] Focused tests passed. - [ ] Fast verification passed. - [ ] Full verification passed, or every skip has a reason. - [ ] UI, API, database, or infrastructure evidence is attached as applicable.
## Safety
- [ ] No secret, token, private URL, or sensitive log is included. - [ ] Production, deletion, permission, and external-write actions were not run without approval. - [ ] Dependencies and Skill changes were reviewed. - [ ] Migration and rollback steps are documented.
## Review
- [ ] Complete diff was reviewed independently. - [ ] Required code owners approved. - [ ] CI passed on the PR head commit. - [ ] Branch protection requirements are satisfied. - [ ] The merge and deployment decision is made by a human owner.
- [ ] The repository has an initial parseable commit. - [ ] The baseline commit hash is recorded. - [ ] A new task worktree can be created from that commit.
## Startup
- [ ] A clean checkout can run bootstrap. - [ ] Runtime and dependency versions are documented. - [ ] Development and test entry points are verified.
## Guidance
- [ ] Root `AGENTS.md` contains verified facts and boundaries. - [ ] Tool-specific adapters are scoped and current. - [ ] No rule claims to be a security boundary.
## Verification
- [ ] `verify-fast.sh` fails clearly when placeholders remain. - [ ] `verify.sh` fails clearly when placeholders remain. - [ ] CI reuses the repository scripts. - [ ] A baseline failure record exists.
## Isolation and safety
- [ ] Agent work is isolated by branch or worktree. - [ ] Sandbox and network policy are documented. - [ ] Hooks were tested for allow, deny, timeout, and failure behavior. - [ ] MCP starts with read-only tools and environment-injected credentials. - [ ] Branch protection and required review are enabled.
## Trial task
- [ ] An Agent explained the repository map. - [ ] An Agent completed a reversible change. - [ ] Verification evidence includes commands and exit statuses. - [ ] Unverified items were reported honestly.
- [ ] README, CI, build files, and real scripts were inspected. - [ ] Runtime, dependencies, entry points, generated files, secrets, and dangerous areas are catalogued.
## Baseline
- [ ] Existing build and tests ran before source changes. - [ ] Known failures, duration, environment dependencies, and flaky tests are recorded. - [ ] Baseline results are distinguishable from new regressions.
## Characterization tests
- [ ] High-risk and high-coupling behavior has characterization coverage. - [ ] Tests preserve current behavior, including known defects that cannot change yet. - [ ] A human reviewed that tests describe the current system accurately.
## Operational entry points
- [ ] Bootstrap, fast verification, and full verification adapters exist. - [ ] Every adapter command is present in the repository or marked unconfigured. - [ ] CI and local verification share the same core entry points.
## Guidance migration
- [ ] `.cursorrules`, duplicate prompts, and oversized `CLAUDE.md` files were inventoried. - [ ] Facts moved to public `AGENTS.md` or native project instructions. - [ ] Path-specific constraints moved to Rules. - [ ] Repeatable workflows moved to Skills. - [ ] Conflicting and obsolete instructions were removed.
## Progressive adoption
- [ ] Documentation and tests came before broad refactoring. - [ ] Small Bugs and mechanical migrations are delivered as small changes. - [ ] Each subsystem is adopted separately. - [ ] Cross-module work waits until earlier evidence is stable. - [ ] Every change has a real verification result and rollback entry point.