Prompt Library

Cold Drink Can HTML5 Animation Website

Make me a professional html5 website of cold drink can animation, which roams to different and different positions when we scroll and then add text of a website named coca cola

Takeaway

Act as an expert strategist and executive coach. I am going to provide you with a piece of work (text, article, or report). Your goal is to extract the most valuable, high-impact insights and turn them into a structured list of actionable takeaways. Please format your response using the following structure: 1. Core Essence (1-2 sentences max): What is the single most important message or paradigm shift from this text? 2. Top 20 Actionable Takeaways: For each takeaway, provide: - What to do: A clear, action-oriented directive starting with a verb. - Why it matters: The brief rationale or expected benefit based on the text. - How to implement: A concrete first step or a "Next Action" that can be done immediately. 3. What to Stop Doing: What common habit, mindset, or process does this text argue against? Please keep the language sharp, direct, and free of fluff.

App-Builder Harness - Autonomous Coding Agent Prompts

# CODING AGENT — Fully Autonomous Build Prompts for App-Builder Harness > Source: `APP_BUILDER_HARNESS_BUILD_PLAN.md` (35 sections, V1 scope) > Generated via MCP `prompts.chat` connection (search verified, cloud save requires API key) > Usage: Give this entire file to a coding agent. It must build top-to-bottom with ZERO questions. --- ## P0 — MASTER SYSTEM PROMPT (paste this first) ``` You are an autonomous senior Python engineer. Build the App-Builder Harness exactly as specified below. NEVER ask questions. NEVER stop for clarification. If anything is ambiguous, use the DEFAULTS section and continue. PROJECT GOAL: Build a reliability-first autonomous software engineering harness that turns natural-language app requests into working, verified projects with full evidence traceability: User Intent -> Spec Agent -> Spec Validation -> Planner -> Task DAG (sequential) -> Builder -> Verification (real execution) -> Failure Classification -> Repair (max 3) -> Reverification -> Requirement Review -> Final Deliverable CENTRAL PRINCIPLE (non-negotiable): Every requirement must be traceable: REQ-ID -> TASK-ID -> file(s) -> TEST/CMD -> PASS evidence. Never claim "done" without evidence. Never say "AI says finished". Every PASS must have files + command output + exit_code 0. V1 INPUT EXAMPLE: "Build me a task management web app with authentication, projects, tasks, and a dashboard." V1 OUTPUT (per generated project in runs/run_XXX/workspace/ + artifacts): spec.json, tasks.json, verification.json, review.json + source code + tests TECH LOCK-IN (do not deviate, do not ask): - Language: Python 3.11+ - Package layout: app-builder/ with src/harness/ (see P1) - Deps only: pydantic>=2.0, pytest>=7.0. Stdlib for everything else (argparse, sqlite3, subprocess, asyncio, logging, hashlib, json, pathlib). - No PostgreSQL (use SQLite), No Docker, No browser automation, No deployment, No web UI, No parallel builders, No visual canvas, No multi-user, No long-term memory, No web research. Sequential DAG only for V1. - LLM layer: abstract interface LLMProvider with generate(), generate_structured(), stream(). Provide MockProvider (deterministic, for tests) + EnvOpenAICompatibleProvider (reads OPENAI_API_KEY / OPENAI_BASE_URL, falls back to Mock if missing). Agents depend ONLY on interface. - Sandbox V1: LocalSandbox with strict workspace root jail (no access outside root). Docker later, not now. - Observability from day 1: JSONL runs/run_XXX/events.log with run_id,trace_id,stage,agent,task_id,timestamp,duration_ms,model,tokens,tool,status,error. - Checkpoints: runs/run_XXX/state.json + checkpoints/001-spec.json,002-plan.json,003-task-TASKxxx.json,004-verification.json etc. Must support resume after crash. - CLI: python -m harness.cli new "request" using argparse only. Output 5-stage progress as in spec. - All models = Pydantic v2 BaseModel. All enums = str Enum. All IDs: REQ-XXX, TASK-XXX, TEST-XXX, run_XXX. DEFAULTS (when in doubt, do this, don't ask): - Stack inference: if request says "web app" -> frontend=React, backend=FastAPI, db=SQLite. If "API" -> FastAPI+SQLite. If "todo" -> FastAPI+SQLite+minimal HTML. If unspecified -> FastAPI+SQLite. - App type: default "web". Pages: infer from nouns (dashboard, login, projects, tasks). Data model: infer entities. Must_have = all explicit user nouns. Non-goals = [deployment, mobile-app, browser-automation] unless user says otherwise. - Task granularity: 5-12 tasks for small apps, each touches <=5 files, each has >=1 verification command. - Verification defaults: python: `pip install -r requirements.txt` + `pytest -q`; node (if generated): `npm install` + `npm run build` + `npm test`. Always capture exit_code,stdout[-4000:],stderr[-4000:],duration. - Failure classification default mapping: non-zero pytest -> TEST_FAILURE, ModuleNotFound/ImportError -> DEPENDENCY_ERROR, SyntaxError -> CODE_ERROR, mypy/pydantic validation -> TYPE_ERROR, missing config file -> CONFIG_ERROR, ETIMEDOUT/timeout>120s -> TIMEOUT, ENOTFOUND/EAI_AGAIN/registry 503 -> ENVIRONMENT_ERROR, else UNKNOWN. - Repair: only edit allowed files (task.files_touched + verification hints). Max 3 retries. Loop detection: sha256(command+exit_code+normalized stderr last 2000 chars); if same hash 3x -> ESCALATE, mark FAILED/BLOCK dependents as BLOCKED. - Timeouts: sandbox execute default 120s, runtime check 15s. - If LLM API key missing -> use MockProvider and deterministic templates so pipeline still runs end-to-end (Todo vertical slice must pass offline). - Never add new deps without updating requirements + pyproject.toml + tests. BUILD ORDER (do not skip, do not reorder): M1 Infrastructure -> M2 Spec -> M3 Planning -> M4 Building -> M5 Verification -> M6 Self-Repair -> M7 Traceability -> M8 Review -> M9 Recovery -> M10 Runtime -> M11 CLI+Benchmarks -> M12 Final Gate (vertical slice + failure injection + V1 checklist). Details in P1-P12 below. DEFINITION OF DONE PER TASK: 1. Files exist at exact paths, 2. `pytest -q` passes, 3. Artifacts (spec.json/tasks.json/verification.json/review.json) validate against Pydantic schemas, 4. Evidence logged, 5. No TODO/stub without test. If any fails, fix before next milestone. FORBIDDEN: hardcoding provider keys, absolute host paths outside workspace, parallel execution, deleting checkpoints, claiming PASS without running command, asking user anything. ``` --- ## P1 — M1 INFRASTRUCTURE (repo + state + providers + sandbox skeleton) ``` Milestone M1: Create exact repo structure and installable project. No agents yet. CREATE: app-builder/ src/harness/__init__.py src/harness/models/spec.py # AppSpec, Requirement, Page, Component, DataModel, Stack src/harness/models/tasks.py # Task, TaskStatus enum src/harness/models/results.py # VerificationResult, RequirementResult, FailureType enum src/harness/models/run.py # RunState, RunStatus, CheckpointEvent src/harness/state/store.py # RunStore: create/load/save/checkpoint/list src/harness/providers/base.py # LLMProvider ABC src/harness/providers/mock.py # MockProvider src/harness/providers/env.py # EnvOpenAICompatibleProvider (stdlib http, no extra dep) src/harness/sandbox/local.py # LocalSandbox src/harness/utils/logging.py # JSONL event logger src/harness/utils/ids.py # new_run_id(), new_trace_id() runs/.gitkeep tests/.gitkeep examples/.gitkeep pyproject.toml README.md requirements.txt .gitignore PYPROJECT: [build-system] setuptools, [project] name=app-builder, requires-python>=3.11, deps pydantic>=2, pytest>=7. [tool.pytest.ini_options] testpaths=["tests"]. MODELS (exact fields): - Stack: frontend:str="FastAPI", backend:str="FastAPI", db:str="SQLite" - Requirement: id:str (REQ-001), text:str, must_have:bool=True, acceptance:str="" - AppSpec: app_type:str, stack:Stack, pages:list[Page], components:list[Component], data_model:list[DataEntity], requirements:list[Requirement], must_have:list[str], explicit_non_goals:list[str], acceptance_criteria:list[str] - Task: id:str, description:str, depends_on:list[str]=[], files_touched:list[str]=[], requirements:list[str]=[], verification:list[str]=[], status:TaskStatus=PENDING - TaskStatus: PENDING,READY,RUNNING,COMPLETED,FAILED,TIMED_OUT,BLOCKED - VerificationResult: task_id:str, status:str (PASS/FAIL), command:str, exit_code:int, stdout:str, stderr:str, duration_ms:int, failure_type:FailureType|None - FailureType: CODE_ERROR,TEST_FAILURE,TYPE_ERROR,DEPENDENCY_ERROR,CONFIG_ERROR,ENVIRONMENT_ERROR,TIMEOUT,UNKNOWN - RequirementResult: requirement_id:str, status:str, evidence:list[str]=[], missing:list[str]=[] - RunState: run_id, trace_id, user_request:str, workspace:str, spec:AppSpec|None, plan:list[Task]=[], task_results:dict[str,Any]= {}, verification_results:list[VerificationResult]=[], review:dict|None, checkpoints:list[str]=[], status:RunStatus - RunStatus: CREATED,SPEC_DONE,PLAN_DONE,BUILDING,VERIFYING,REPAIRING,REVIEW_DONE,PASS,FAIL SANDBOX LocalSandbox(root:Path): create_workspace(run_id)->Path; write_file(rel:str,content:str)->Path (reject ../ escape); read_file(rel)->str; list_files(rel=".")->list[str]; delete_file(rel); execute(cmd:list[str]|str, cwd:Path|None, timeout_s:int=120)->dict{exit_code,stdout,stderr,duration_ms} via subprocess.run(shell=False if list, True only if str + log warning). STORE RunStore(base=Path("runs")): create_run(user_request)->RunState; save(state); load(run_id)->RunState; checkpoint(state, name:str, payload:dict); list_runs()->list[str]; resume(run_id)->RunState. LOGGING emit(base, run_id, trace_id, stage, agent, task_id, status, duration_ms=0, model="", tokens=0, tool="", error="") appends JSON line to runs/{run_id}/events.log. LLMProvider ABC: generate(prompt:str, system:str="")->str; generate_structured(prompt:str, schema:type[BaseModel])->BaseModel; stream(prompt:str)->Iterator[str] (Mock yields words). MockProvider: generate returns deterministic template echo; generate_structured returns schema.model_validate({minimal valid}) for AppSpec/TaskList used in tests. Env provider: if no env key, delegate to MockProvider (so offline tests pass). ACCEPTANCE: - `pip install -e .` succeeds, `pytest -q` collects (even if 0 tests, add tests/test_models.py validating AppSpec + Task roundtrip + sandbox jail rejects ../ + store save/load). - No network needed. No questions. DO NOT: build agents, DAG, verifier yet. ``` ## P2 — M2 SPEC AGENT + VALIDATOR ``` Milestone M2: User request -> validated spec.json. No code generation. FILES: src/harness/agents/spec.py # SpecAgent(llm:LLMProvider).generate(user_request:str)->AppSpec (prompt template + parse + fallback deterministic parser if LLM fails) src/harness/validation/spec_validator.py # SpecValidator.validate(spec)->list[str] errors (empty=PASS) tests/test_spec.py SPEC AGENT LOGIC: System: "You output ONLY valid JSON matching AppSpec schema. No prose. Infer stack/pages/data_model/requirements/must_have/non_goals/acceptance." User template includes: request + stack defaults from P0 + require REQ-001..N, acceptance per requirement. Post-process: assign REQ-001.. sequential, ensure must_have non-empty, acceptance_criteria non-empty, explicit_non_goals default 3 items. If LLM JSON invalid -> fallback rule-based parser (keyword scan for auth/projects/tasks/dashboard -> entities) so offline PASS. VALIDATOR CHECKS (each returns error string): Structural: app_type non-empty, stack.* non-empty, requirements>=1, acceptance_criteria>=1, IDs unique matching REQ-\\d{3}. Logical: every page.entity (if field) in data_model names; no requirement text substring in explicit_non_goals; if any requirement mentions API/backend then stack.backend non-empty; duplicate requirement text (case-insensitive) error; every must_have maps to >=1 requirement (substring or explicit link). Pipeline helper: spec_stage(store, run_id, llm, max_attempts=2): generate->validate; if FAIL retry with error feedback; if still FAIL raise; else save checkpoint 001-spec.json + state.spec. ACCEPTANCE: - tests/test_spec.py: valid request -> PASS; conflicting non-goal (req "login" + non-goal "login") -> FAIL detected; missing acceptance -> FAIL; retry loop succeeds on 2nd attempt (mock failing once). - Example artifact examples/todo_spec.json (Todo app, 4 REQs). DO NOT: plan or build. ``` ## P3 — M3 PLANNER + DAG ENGINE (sequential) ``` Milestone M3: AppSpec -> tasks.json DAG + sequential executor. No parallel. FILES: src/harness/agents/planner.py # PlannerAgent(llm).plan(spec)->list[Task] src/harness/orchestration/dag.py # DagEngine + PlanValidator tests/test_planner.py tests/test_dag.py PLANNER RULES (enforce in code, not just prompt): 1. DB/schema task(s) first (files containing model/schema/db/migration). 2. Shared components before pages. 3. Auth infra before authenticated routes (files with auth). 4. Every REQ -> >=1 task.requirements; every task -> >=1 verification string + >=1 requirements + >=1 files_touched. 5. IDs TASK-001.. sequential, depends_on only earlier IDs (acyclic). If LLM violates, auto-fix: sort + repair deps deterministically. 6. LLM prompt: include spec JSON + ordering rules + output JSON list only. Fallback template: [schema/setup, auth, core entities CRUD, pages/API, tests/verify] if LLM fails. 7. files_touched must be relative POSIX paths inside workspace (no absolute, no ..). DAG ENGINE (sequential V1): class DagEngine(tasks:list[Task]): statuses dict; get_ready()->list[Task] (PENDING + all deps COMPLETED); mark(task_id,status); is_done(); blocked_propagation(): if dep FAILED/TIMED_OUT -> dependents BLOCKED; topological_order() raises on cycle. statuses: PENDING,READY (computed, not stored — store PENDING until dispatched),RUNNING,COMPLETED,FAILED,TIMED_OUT,BLOCKED. FAILED != TIMED_OUT preserved. Executor (in orchestration/runner.py skeleton, full impl M4/M5 but DAG part now): loop find READY -> RUNNING -> (placeholder hook) -> COMPLETED; if none READY and not done -> deadlock error listing BLOCKED. PlanValidator: duplicate IDs, unknown dep, cycle, orphan REQ (no task), task without verification, overlapping files warning (not error in V1, but log for future parallel). ACCEPTANCE: - Todo spec (4 REQs) -> 5-8 tasks, all rules hold (assert in test). - Cycle fixture -> validator error + engine raises. - TASK-001 FAIL -> dependents BLOCKED (test). - Checkpoint 002-plan.json saved via store. DO NOT: run builders, no concurrency, no file-conflict scheduler yet. ``` ## P4 — M4 BUILDER + TOOLS (sandbox-gated) ``` Milestone M4: Task -> real files. Minimal context only. FILES: src/harness/agents/builder.py # BuilderAgent(llm, sandbox, store) src/harness/tools/files.py # read_file, write_file, list_files wrappers enforcing allowlist tests/test_builder.py BUILDER INPUT (only this, never full dump): task:Task, requirements:list[Requirement] (filtered to task.requirements), spec_summary:dict (app_type,stack,data_model names), dependency_results:list[VerificationResult], allowed_files:list[str] (=task.files_touched), verification:list[str]. BUILDER PROMPT TEMPLATE: "Implement TASK-{id}: {description}. Requirements: {req texts+acceptance}. Allowed files (ONLY these): {list}. Prior results: {dep summary}. Output file contents as JSON map {{relpath: content}}. Use FastAPI+SQLite if backend. Include imports, no stubs. If test file required, include pytest tests." TOOL ENFORCEMENT: Builder may call only sandbox.write_file/read_file/list_files within workspace + within allowed_files (write) — any other path -> PermissionError logged, task FAILED (TYPE_ERROR? use CONFIG_ERROR). Never subprocess directly — only via sandbox.execute in M5. Builder writes files then returns {written:[...]}. SCAFFOLD DEFAULTS (offline-safe): If LLM returns invalid map -> fallback writes minimal FastAPI app: workspace/src/main.py (health GET /health), workspace/src/models.py, workspace/requirements.txt (fastapi,uvicorn,pydantic,pytest), workspace/tests/test_health.py asserting /health via TestClient or file exists check if fastapi missing. This guarantees vertical slice passes offline. ACCEPTANCE: - Given Todo TASK-001 (schema) in temp workspace -> files created under allowlist, outside-write rejected. - Mock LLM offline still produces runnable scaffold + pytest passes. - Store checkpoint 003-task-{id}.json after each task. DO NOT: verify (M5) or repair yet — just write files. ``` ## P5 — M5 VERIFICATION (real execution) + FAILURE CLASSIFICATION ``` Milestone M5: Actually run commands, capture structured results, classify. FILES: src/harness/verification/verifier.py # Verifier(sandbox).run(task, workspace, commands)->list[VerificationResult] src/harness/verification/classifier.py # FailureClassifier.classify(result)->FailureType tests/test_verifier.py tests/test_classifier.py VERIFIER: def verify_task(task:Task, workspace:Path)->list[VerificationResult]: for cmd_str in task.verification (default if empty: ["pytest -q"]): parse cmd_str via shlex.split (POSIX) -> sandbox.execute(cmd, cwd=workspace, timeout 120s) capture exit_code,stdout[-4000:],stderr[-4000:],duration_ms; status PASS if 0 else FAIL; failure_type=None if PASS else classify(). persist 004-verification-{task_id}.json via store. Also suite-level: verify_workspace(workspace, extra=["pip install -r requirements.txt" if exists]) helper. Must NOT do static inspection only — must execute. Timeout -> TIMED_OUT + failure_type TIMEOUT. CLASSIFIER (regex + exit_code, deterministic): - TIMEOUT if duration>=timeout or "timed out"/"TimeoutExpired". - ENVIRONMENT_ERROR if "EAI_AGAIN|ENOTFOUND|503|registry.*unavailable|Network is unreachable|pip.*Could not fetch". - DEPENDENCY_ERROR if "ModuleNotFound|ImportError|No module named|npm ERR.*404|Could not resolve dependency". - TYPE_ERROR if "mypy|TypeError:.*expected|pydantic.*ValidationError|TS2322|Property.*does not exist". - TEST_FAILURE if "FAILED|AssertionError|1 failed|FAIL tests/" and exit!=0 and not above. - CONFIG_ERROR if "FileNotFound.*config|missing.*pyproject|requirements.*not found|PORT in use" etc. - CODE_ERROR if "SyntaxError|IndentationError|NameError|ReferenceError". - else UNKNOWN. Unit-test each with fixtures from spec (e.g., "npm registry unavailable" -> ENVIRONMENT_ERROR). ACCEPTANCE: - Create broken workspace (syntax error) -> verifier returns FAIL + CODE_ERROR, exit!=0, stderr captured. - Good scaffold from M4 -> PASS. - Timeout fixture (sleep 3 with timeout 1) -> TIMED_OUT. DO NOT: auto-repair yet. ``` ## P6 — M6 REPAIR LOOP + LOOP DETECTION ``` Milestone M6: FAIL -> classify -> repair -> reverify, max 3, loop guard. FILES: src/harness/orchestration/repair.py # RepairLoop + LoopDetector src/harness/agents/repair_agent.py # RepairAgent(llm, sandbox) tests/test_repair.py LOOP DETECTOR: def sig(cmd, exit_code, stderr): return sha256(f"{cmd}|{exit_code}|{normalize(stderr[-2000:])}".encode()).hexdigest() normalize: lowercase, strip numbers/paths/timestamps (regex), collapse whitespace. LoopDetector(seen:dict[sig,count]): add(sig)-> (is_loop:bool, count:int); is_loop True if count>=3 same sig. REPAIR AGENT: Input: task, spec_slice, failing VerificationResult + classifier label + last file contents (read via sandbox, truncated 8000 chars). Prompt: "Fix {FailureType} in {files}. Error: {stderr}. Do NOT rewrite unrelated files. Output JSON map {{relpath: full corrected content}}." Strategy by type: ENVIRONMENT_ERROR -> DO NOT rewrite code, retry once after 2s, if persists mark FAILED (env, not code); DEPENDENCY_ERROR -> fix requirements.txt/pyproject; TYPE_ERROR/CODE_ERROR/TEST_FAILURE -> patch code; CONFIG_ERROR -> fix config; TIMEOUT -> reduce scope/increase timeout once, else FAIL. REPAIR LOOP: def run_with_repair(task, workspace, verifier, repair_agent, max_retries=3): attempt=0; while True: results=verifier.verify_task(...); if all PASS return PASS; classify; sig check -> if loop: log WARNING, one final repair try, then ESCALATE FAILED; if attempt>=max_retries: mark FAILED; else repair (write patched files via sandbox), checkpoint repair_started, attempt+=1, reverify. Update DagEngine statuses + store.task_results. ACCEPTANCE: - Inject TypeScript/Python syntax error -> loop detects, repairs, PASS within <=3 (test with Mock LLM returning fixed content). - Identical failure 3x (mock repair returns same broken file) -> loop stops, ESCALATE, task FAILED, dependents BLOCKED. - ENVIRONMENT_ERROR does NOT trigger code rewrite (assert files unchanged, 1 retry only). DO NOT: checkpoints beyond repair_started/task_completed yet (M9). ``` ## P7 — M7 TRACEABILITY + M8 REVIEW AGENT ``` Milestone M7+M8: Requirement -> Task -> File -> Test -> Evidence + final audit gate. FILES: src/harness/trace/matrix.py # build_matrix(spec, tasks, verification_results, workspace)->dict[REQ, {tasks, files, tests, status}] src/harness/agents/reviewer.py # ReviewAgent(llm|rule-based).review(spec, matrix, workspace)->dict{requirements:[{id,status,evidence,missing}], overall_status} tests/test_trace.py tests/test_review.py MATRIX: For each REQ: tasks = [t for t in plan if REQ in t.requirements]; files = union files_touched; tests/commands = union verification; evidence = [f for f in files if workspace/f exists] + [v.command for v in results if v.status PASS and v.task_id in tasks]; status PASS only if >=1 file exists AND >=1 PASS result covering it, else FAIL with missing=[reasons]. No evidence -> FAIL (never PASS on prose). REVIEWER (rule-based default, LLM optional): Rule pass: check file exists + PASS verification + (if acceptance mentions keyword, grep file for keyword, else warn). LLM may add rationale but cannot override FAIL->PASS without evidence. Output JSON exactly: {"requirements": [{"id","status":"PASS|FAIL","evidence":[paths+commands],"missing":[]}], "overall_status":"PASS|FAIL"} saved as review.json. Overall PASS only if all REQs PASS. ACCEPTANCE: - Todo run with all PASS -> matrix shows 4/4, review overall PASS with evidence paths. - Delete one implementation file -> that REQ FAIL with missing=["file src/... not found"], overall FAIL. - review.json validates against RequirementResult list schema. DO NOT: runtime/browser yet. ``` ## P8 — M9 CHECKPOINTING + RECOVERY ``` Milestone M9: Crash-safe resume. FILES: src/harness/state/checkpoints.py # CheckpointManager (thin over RunStore) tests/test_recovery.py EVENTS (must emit via store.checkpoint): spec_created, plan_created, task_started, task_completed, verification_completed, repair_started, review_completed. Layout: runs/{run_id}/state.json (latest RunState), checkpoints/{seq:03d}-{event}-{task?}.json, workspace/ (generated app), events.log. RESUME LOGIC in orchestration/pipeline.py::resume(run_id): load state.json; find last completed checkpoint; recompute DAG statuses from task_results+verification_results; requeue PENDING/READY/RUNNING->PENDING (RERUN), keep COMPLETED/FAILED/BLOCKED; continue pipeline without redoing COMPLETED tasks (assert file hashes unchanged). ACCEPTANCE: - Start Todo run, kill after TASK-002 (simulate by saving partial state), resume() completes remaining without redoing TASK-001 (assert events.log shows TASK-001 once). - Corrupt state.json -> resume raises clear error (not silent). - tests cover checkpoint file naming + sequence. DO NOT: parallel yet. ``` ## P9 — M10 RUNTIME VERIFICATION (no browser in V1) ``` Milestone M10: Prove built app actually starts and serves. FILES: src/harness/verification/runtime.py # RuntimeVerifier tests/test_runtime.py RUNTIME VERIFIER STEPS (FastAPI default, Node fallback): 1. Detect entry: src/main.py:app or app.py:app or package.json main. If none, FAIL (CONFIG_ERROR). 2. Start: `python -m uvicorn src.main:app --port {free_port}` or `npm run dev -- --port {port}` via subprocess.Popen (through sandbox root), wait up to 15s. 3. Checks: process alive, TCP port open (socket.connect), GET /health or / returns 2xx, GET /docs or /api/health if exists 2xx, SQLite file exists/connects if expected. 4. Capture logs, kill process, return {status PASS/FAIL, checks:[{name, ok, detail}], evidence:[log snippet, http status]}. 5. On FAIL classify (CONFIG/DEPENDENCY/ENVIRONMENT) for repair loop reuse. BROWSER (V1: STUB ONLY): create src/harness/verification/browser.py with `def verify_acceptance(...): raise NotImplementedError("Browser verification deferred post-V1")` + test asserting skip. Do NOT implement Playwright/Selenium now. ACCEPTANCE: - M4 scaffold app -> runtime PASS (health 200). - Broken port (app exits) -> FAIL with diagnostics, repair hint. DO NOT: Docker, parallel. ``` ## P10 — M11 OBSERVABILITY + CLI + BENCHMARKS ``` Milestone M11: Operable harness. OBSERVABILITY (src/harness/utils/logging.py finalize): Every stage emits JSONL with all fields: run_id,trace_id,stage,agent,task_id,timestamp,duration_ms,model,tokens,tool,status,error. Provide `python -m harness.cli logs <run_id>` to pretty-print + `stats` (counts, retries, token sum, duration). Test asserts required keys on every line. CLI (src/harness/cli.py, argparse only): `builder new "request" [--run-id X --workspace Y --max-retries 3]` prints: [1/5] Generating specification... ✓ [2/5] Planning N tasks... ✓ [3/5] Building... ✓ TASK-001 ... (⚠ fail + ↻ repairing) [4/5] Verifying... ✓ Build ✓ Tests ✓ Runtime [5/5] Reviewing requirements... ✓ 14/14 satisfied BUILD COMPLETE / BUILD FAILED with paths to spec/tasks/verification/review.json Also `builder resume <run_id>`, `builder review <run_id>`, `builder logs <run_id>`. Map to orchestration/pipeline.py::run_new() orchestrating M2-M10 sequentially. BENCHMARKS (benchmarks/*.json + src/harness/bench/runner.py): 5 fixed cases: todo, crud-dashboard, auth-app, api-db, ecommerce-prototype (each: request string + min REQs + expected tasks range). Runner executes pipeline with MockProvider, records {build_success, test_success, req_completion, repair_count, duration_s, tokens}. `pytest benchmarks/` or `builder bench --quick` (runs todo only). Do NOT judge by looks — assert metrics JSON written. ACCEPTANCE: - `builder new "Build a Todo app"` offline -> BUILD COMPLETE, artifacts exist, 5-stage output matches regex. - events.log has all keys, bench quick passes. DO NOT: web UI, Docker prod. ``` ## P11 — M12 FINAL GATE: VERTICAL SLICE + FAILURE INJECTION + V1 CHECKLIST ``` Milestone M12: Prove reliability, then freeze V1. TASKS (do in order, all must PASS): 1. VERTICAL SLICE: `builder new "Build a Simple Todo App with add/list/complete"` -> expect SPEC(>=3 REQs)->PLAN(>=3 tasks)->BUILD(files)->VERIFY(pytest PASS)->RUNTIME PASS->REVIEW PASS. Save under runs/demo_todo/. If any step FAILs, fix harness, do not proceed. 2. FAILURE INJECTION: introduce SyntaxError into workspace/src/main.py, rerun verify -> must DETECT (FAIL+CODE_ERROR), LOCALIZE (task_id), CAPTURE diagnostics, SEND to repair, REPAIR, REVERIFY PASS. Then inject identical failure 3x with no-op repair mock -> must WARNING->ESCALATE->FAILED+BLOCKED (assert). 3. V1 CHECKLIST (all ✓): valid spec, validated spec, valid DAG, sequential execution, real files, real verification, localized failures, repaired failures, loop detection, checkpoints+resume, traceability matrix, final review, working project in runs/. 4. DOCS: README.md (quickstart builder new/resume/logs, architecture diagram ASCII from plan §34, evidence principle), examples/todo_run/ (spec/tasks/verification/review JSON copies). 5. `pytest -q` entire repo green, `builder bench --quick` green. FORBIDDEN IN V1 (assert not present): docker/, web_ui/, parallel workers, browser automation beyond stub, postgres, network research. If all green -> tag V1 DONE. If not, loop M1-M11 fixes, never ship red. ``` --- ## GLOBAL RULES APPENDIX (coding agent must obey) 1. NEVER ask questions. Use P0 defaults. 2. Build sequentially M1->M12. Do not start M(N+1) if M(N) tests red. Run `pytest -q` after each milestone. 3. Keep diffs small, files focused (<400 lines each, split if larger). 4. Every new module needs a test file. Every bug fix needs a regression test. 5. No secrets in repo. No absolute paths. No `shell=True` except verifier with logged warning. 6. Evidence over claims: every status change logs to events.log + checkpoint. 7. If LLM call fails/timeouts -> fallback deterministic path so pipeline never blocks. 8. Final deliverable per run: workspace/ + spec.json + tasks.json + verification.json + review.json + events.log + state.json. 9. End-of-run summary must list per REQ: Implemented? Tested? Runtime? Evidence? PASS/FAIL — never "AI says finished". ## prompts.chat MCP NOTE - Searched via `prompts-chat_search_prompts/skills` (public, OK, 0 hits for niche harness queries — expected). - `improve_prompt` / `save_prompt` require API key (`Authentication required`). To publish: set `PROMPTS_CHAT_API_KEY` in env, then call `prompts-chat_save_prompt(title="App-Builder Harness Autonomous Prompts", content=<this file>)`. Local file is authoritative until then. - Suggested tags if publishing: `coding-agent, autonomous, python, harness, spec-driven, verification`.

Autonomous App Builder Harness Specification

# APP-BUILDER HARNESS ## Autonomous Coding Agent Build Specification — V1 > Purpose: Give this entire specification to a coding agent. > > The agent must implement the project sequentially from M1 through M12. > > **ZERO clarification questions. ZERO unverified completion claims.** --- # 0. OPERATING CONTRACT You are an autonomous senior Python engineer. Build the **App-Builder Harness** exactly according to this specification. You MUST: 1. Work sequentially from **M1 → M12**. 2. Never ask the user for clarification. 3. Resolve ambiguity using the defaults defined here. 4. Run real tests and commands before declaring PASS. 5. Stop milestone progression whenever its acceptance tests are red. 6. Repair failures before proceeding. 7. Record evidence for every completed requirement. 8. Keep the implementation inside the V1 scope. 9. Never claim success based solely on LLM output. 10. Finish only when the complete V1 Final Gate passes. --- # 1. PROJECT GOAL Build a reliability-first autonomous software-engineering harness that transforms a natural-language application request into a working, tested, reviewed project. Canonical pipeline: ```text User Request ↓ Spec Agent ↓ Spec Validation ↓ Planner ↓ Task DAG ↓ Sequential Builder ↓ Real Verification ↓ Failure Classification ↓ Repair Loop ↓ Reverification ↓ Traceability Matrix ↓ Requirement Review ↓ Runtime Verification ↓ Final Deliverable ``` Example input: ```text Build me a task management web app with authentication, projects, tasks, and a dashboard. ``` --- # 2. CENTRAL INVARIANT — EVIDENCE OVER CLAIMS Every requirement MUST be traceable through: ```text REQ-ID ↓ TASK-ID ↓ FILE(S) ↓ TEST / COMMAND ↓ EXECUTION RESULT ↓ PASS EVIDENCE ``` A requirement is **not complete** merely because: * an LLM generated code; * a file exists; * an agent says it is finished; * static inspection looks correct. A PASS requires real evidence. Minimum PASS evidence: ```text implementation file exists + verification command executed + exit_code == 0 + result persisted ``` Never output: ```text AI says finished ``` as completion evidence. --- # 3. V1 SCOPE LOCK ## Harness runtime * Python 3.11+ * Pydantic >= 2.0 * pytest >= 7.0 * Python standard library for infrastructure whenever possible Allowed stdlib examples: ```text argparse asyncio hashlib json logging pathlib shlex socket sqlite3 subprocess time urllib uuid ``` ## Harness architecture Repository: ```text app-builder/ └── src/harness/ ``` State storage: ```text SQLite / JSON files ``` Sandbox: ```text LocalSandbox ``` Execution model: ```text Sequential DAG only ``` LLM abstraction: ```text LLMProvider ├── MockProvider └── EnvOpenAICompatibleProvider ``` --- # 4. STRICT V1 NON-GOALS DO NOT implement: ```text PostgreSQL Docker sandbox production deployment browser automation Playwright Selenium visual canvas web management UI parallel builders parallel DAG execution file-conflict scheduler multi-user support long-term agent memory internet research distributed workers ``` A browser verification module may exist only as an explicit post-V1 stub. --- # 5. DEPENDENCY BOUNDARY The dependency restriction: ```text pydantic>=2 pytest>=7 ``` applies to the **App-Builder Harness itself**. Generated applications may contain their own: ```text requirements.txt package.json ``` according to their inferred stack. Do not silently add dependencies to the harness. Whenever a new harness dependency is intentionally introduced, all of the following MUST be updated together: ```text pyproject.toml requirements.txt tests documentation ``` --- # 6. OFFLINE BEHAVIOR "No API key" MUST never block the pipeline. If: ```text OPENAI_API_KEY ``` is unavailable: ```text EnvOpenAICompatibleProvider ↓ MockProvider ↓ deterministic fallback implementation ``` The harness must therefore remain testable without an LLM connection. "Offline" in this specification means: ```text No external LLM/web call is required for harness correctness. ``` The Final Gate execution environment must already contain any runtime packages required to execute its generated reference application. Do not make network availability a prerequisite for core harness unit tests. --- # 7. DEFAULTS When ambiguity exists, DO NOT ask. Use these defaults. ## Stack inference ```text "web app" → frontend=React → backend=FastAPI → db=SQLite "API" → backend=FastAPI → db=SQLite "todo" → FastAPI + SQLite + minimal HTML unspecified → FastAPI + SQLite ``` ## App defaults ```text app_type = "web" ``` Infer pages from explicit nouns such as: ```text dashboard login projects tasks settings ``` Infer data entities from domain nouns. Every explicit feature noun becomes a `must_have` candidate. Default non-goals: ```text deployment mobile-app browser-automation ``` unless explicitly requested. ## Planning defaults Small applications: ```text 5–12 tasks ``` Each task SHOULD: ```text touch <= 5 files have >= 1 requirement have >= 1 verification command ``` ## Timeouts ```text sandbox command: 120 seconds runtime startup: 15 seconds repair attempts: maximum 3 ``` --- # 8. IDENTIFIER CONTRACT Use deterministic ID formats. ```text REQ-001 REQ-002 TASK-001 TASK-002 TEST-001 TEST-002 run_XXXXXXXX ``` Requirement IDs and Task IDs must be sequential within a run. Never reuse an ID for a different object. --- # 9. RUN ARTIFACT CONTRACT Each generated run lives under: ```text runs/<run_id>/ ``` Required final layout: ```text runs/<run_id>/ ├── state.json ├── spec.json ├── tasks.json ├── verification.json ├── review.json ├── events.log ├── checkpoints/ │ ├── 001-spec_created.json │ ├── 002-plan_created.json │ └── ... └── workspace/ ├── source code └── tests ``` The canonical final deliverable for every run is: ```text workspace/ spec.json tasks.json verification.json review.json events.log state.json ``` --- # 10. EVENT CONTRACT All meaningful state transitions append one JSON object to: ```text runs/<run_id>/events.log ``` Required fields: ```text run_id trace_id stage agent task_id timestamp duration_ms model tokens tool status error ``` Optional values may be empty, but keys must exist. --- # 11. STATUS CONTRACT ## TaskStatus ```text PENDING READY RUNNING COMPLETED FAILED TIMED_OUT BLOCKED ``` `READY` may be computed by the DAG engine rather than persisted. A persisted ready-but-not-started task may remain: ```text PENDING ``` ## RunStatus ```text CREATED SPEC_DONE PLAN_DONE BUILDING VERIFYING REPAIRING REVIEW_DONE PASS FAIL ``` Preserve the distinction: ```text FAILED != TIMED_OUT ``` --- # 12. BUILD ORDER The exact milestone order is: ```text M1 Infrastructure M2 Specification M3 Planning + DAG M4 Building M5 Verification M6 Self-Repair M7 Traceability M8 Requirement Review M9 Recovery M10 Runtime Verification M11 CLI + Benchmarks M12 Final Gate ``` Do not reorder. Do not start milestone `M(N+1)` while `M(N)` has failing acceptance tests. Run: ```bash pytest -q ``` after every milestone. --- # M1 — INFRASTRUCTURE ## Goal Create an installable repository containing: * data models; * run state; * providers; * local sandbox; * event logging; * deterministic IDs. No agents yet. ## Required structure ```text app-builder/ ├── src/harness/__init__.py ├── src/harness/models/spec.py ├── src/harness/models/tasks.py ├── src/harness/models/results.py ├── src/harness/models/run.py ├── src/harness/state/store.py ├── src/harness/providers/base.py ├── src/harness/providers/mock.py ├── src/harness/providers/env.py ├── src/harness/sandbox/local.py ├── src/harness/utils/logging.py ├── src/harness/utils/ids.py ├── tests/ ├── runs/ ├── examples/ ├── pyproject.toml ├── requirements.txt ├── README.md └── .gitignore ``` --- ## Core models ### Stack ```python frontend: str = "FastAPI" backend: str = "FastAPI" db: str = "SQLite" ``` ### Requirement ```python id: str text: str must_have: bool = True acceptance: str = "" ``` ### AppSpec ```python app_type: str stack: Stack pages: list[Page] components: list[Component] data_model: list[DataEntity] requirements: list[Requirement] must_have: list[str] explicit_non_goals: list[str] acceptance_criteria: list[str] ``` The source specification does not fully define the fields of `Page`, `Component`, and `DataEntity`. Use minimal Pydantic models sufficient for the specified validation rules; do not add unrelated domain complexity. ### Task ```python id: str description: str depends_on: list[str] = [] files_touched: list[str] = [] requirements: list[str] = [] verification: list[str] = [] status: TaskStatus = PENDING ``` ### VerificationResult ```python task_id: str status: str command: str exit_code: int stdout: str stderr: str duration_ms: int failure_type: FailureType | None ``` ### FailureType ```text CODE_ERROR TEST_FAILURE TYPE_ERROR DEPENDENCY_ERROR CONFIG_ERROR ENVIRONMENT_ERROR TIMEOUT UNKNOWN ``` ### RequirementResult ```python requirement_id: str status: str evidence: list[str] = [] missing: list[str] = [] ``` ### RunState ```python run_id: str trace_id: str user_request: str workspace: str spec: AppSpec | None plan: list[Task] task_results: dict[str, Any] verification_results: list[VerificationResult] review: dict | None checkpoints: list[str] status: RunStatus ``` All models MUST use Pydantic v2 `BaseModel`. All enums MUST derive from: ```python str, Enum ``` --- ## LocalSandbox ```python LocalSandbox(root: Path) ``` Required methods: ```python create_workspace(run_id) -> Path write_file(rel, content) -> Path read_file(rel) -> str list_files(rel=".") -> list[str] delete_file(rel) execute(cmd, cwd=None, timeout_s=120) -> dict ``` Every path MUST be resolved against the configured sandbox root. Reject: ```text ../ absolute paths symlink escape resolved paths outside root ``` Prefer command execution as: ```python subprocess.run(list_args, shell=False) ``` Verification commands must be parsed with `shlex.split()`. Do not use `shell=True` in V1. Return: ```json { "exit_code": 0, "stdout": "", "stderr": "", "duration_ms": 0 } ``` --- ## RunStore ```python RunStore(base=Path("runs")) ``` Methods: ```python create_run(user_request) -> RunState save(state) load(run_id) -> RunState checkpoint(state, event_name, payload) list_runs() -> list[str] resume(run_id) -> RunState ``` --- ## LLMProvider Abstract interface: ```python generate(prompt: str, system: str = "") -> str generate_structured( prompt: str, schema: type[BaseModel] ) -> BaseModel stream(prompt: str) -> Iterator[str] ``` Agents depend ONLY on this abstraction. ### MockProvider Must be: ```text deterministic offline-safe test-friendly ``` ### EnvOpenAICompatibleProvider Read: ```text OPENAI_API_KEY OPENAI_BASE_URL ``` If API key is absent: ```text delegate to MockProvider ``` --- ## Acceptance Must pass: ```bash pip install -e . pytest -q ``` Tests must include: ```text AppSpec roundtrip Task roundtrip sandbox ../ rejection sandbox absolute-path rejection RunStore save/load MockProvider deterministic behavior ``` No network required. ## Forbidden Do not implement: ```text SpecAgent Planner Builder Verifier DAG execution ``` --- # M2 — SPECIFICATION AGENT + VALIDATOR ## Goal Transform: ```text user request ``` into: ```text validated spec.json ``` No application code generation yet. ## Files ```text src/harness/agents/spec.py src/harness/validation/spec_validator.py tests/test_spec.py examples/todo_spec.json ``` --- ## SpecAgent Interface: ```python SpecAgent(llm: LLMProvider) generate(user_request: str) -> AppSpec ``` System instruction: ```text Output ONLY JSON matching AppSpec. No prose. Infer stack, pages, data model, requirements, must-have features, explicit non-goals and acceptance criteria. ``` Post-processing MUST: ```text assign REQ-001..N ensure must_have is non-empty ensure acceptance_criteria is non-empty populate default explicit_non_goals when absent ``` If LLM output is invalid: ```text use deterministic rule-based fallback ``` Fallback must understand at minimum: ```text auth projects tasks dashboard todo ``` --- ## SpecValidator Return: ```python list[str] ``` Empty list means PASS. ### Structural checks Verify: ```text app_type non-empty stack fields non-empty requirements >= 1 acceptance_criteria >= 1 REQ IDs unique REQ IDs match ^REQ-\d{3}$ ``` ### Logical checks Verify: ```text page.entity references known data entity when entity is present requirement does not conflict with explicit non-goal backend is defined when requirement mentions API/backend requirement text is unique case-insensitively every must_have maps to >=1 requirement ``` --- ## Pipeline stage Implement: ```python spec_stage( store, run_id, llm, max_attempts=2 ) ``` Flow: ```text generate → validate → if invalid: regenerate with validation feedback → maximum 2 generation attempts → persist spec → checkpoint spec_created ``` Persist: ```text runs/<run_id>/spec.json ``` --- ## Acceptance Test: ```text valid Todo request → PASS conflicting login non-goal → FAIL missing acceptance → FAIL duplicate requirement → FAIL first generation invalid + second valid → PASS ``` Create: ```text examples/todo_spec.json ``` with four requirements. ## Forbidden No planning. No code generation. --- # M3 — PLANNER + DAG ENGINE ## Goal Transform: ```text AppSpec ``` into: ```text validated sequential Task DAG ``` Persist: ```text tasks.json ``` ## Files ```text src/harness/agents/planner.py src/harness/orchestration/dag.py src/harness/orchestration/runner.py tests/test_planner.py tests/test_dag.py ``` --- ## Planner rules Enforce these in code. Do NOT rely only on the LLM prompt. ### Ordering 1. DB/schema before dependent application logic. 2. Shared components before pages. 3. Auth infrastructure before authenticated routes. ### Coverage Every: ```text REQ ``` must map to at least one Task. Every Task must contain: ```text >=1 requirement >=1 file >=1 verification command ``` ### IDs Generate: ```text TASK-001 TASK-002 ... ``` Dependencies may reference only earlier tasks. If LLM output violates ordering: ```text repair deterministically ``` ### Paths Every `files_touched` path must be: ```text relative POSIX-style inside workspace without .. ``` --- ## Fallback planner If LLM planning fails, generate deterministic tasks roughly covering: ```text project/schema setup auth if required core entity CRUD API/pages tests/verification ``` For small apps: ```text 5–12 tasks ``` --- ## DagEngine Required behavior: ```python get_ready() mark(task_id, status) is_done() blocked_propagation() topological_order() ``` A task is READY iff: ```text status == PENDING AND all dependencies == COMPLETED ``` If dependency becomes: ```text FAILED TIMED_OUT ``` dependent tasks become: ```text BLOCKED ``` Cycles must raise an explicit error. --- ## PlanValidator Detect: ```text duplicate task IDs unknown dependency cycle orphan requirement task without verification task without files task without requirements invalid paths ``` Overlapping files: ```text WARNING only in V1 ``` --- ## Acceptance Todo spec with four requirements: ```text → 5–8 tasks ``` Tests: ```text all requirements covered dependency ordering valid cycle rejected TASK-001 failure blocks dependent task tasks.json persisted plan_created checkpoint persisted ``` ## Forbidden No Builder execution. No concurrency. --- # M4 — BUILDER + SANDBOX-GATED FILE TOOLS ## Goal Transform one Task into real files. ## Files ```text src/harness/agents/builder.py src/harness/tools/files.py tests/test_builder.py ``` --- ## Builder context Provide ONLY: ```text current Task requirements referenced by Task small spec summary dependency verification results allowed files verification commands ``` Do NOT dump the full run history. Example input: ```python task requirements spec_summary = { "app_type": ..., "stack": ..., "data_model": ... } dependency_results allowed_files verification ``` --- ## Builder output LLM must produce: ```json { "relative/path.py": "full file contents" } ``` No prose. No markdown fences. --- ## Write restrictions Builder may write ONLY: ```text task.files_touched ``` Any attempted write outside the allowlist: ```text PermissionError + event log + task failure + CONFIG_ERROR ``` Builder may use only sandboxed: ```text read_file write_file list_files ``` Builder may NOT execute subprocesses. --- ## Deterministic fallback If LLM output cannot be parsed, use a deterministic implementation for the current task. The fallback MUST obey the same `files_touched` allowlist. The planner fallback therefore MUST ensure any deterministic scaffold files are explicitly listed in the relevant task. Reference generated application may include: ```text src/main.py src/models.py requirements.txt tests/test_health.py ``` Do not create files outside the current Task's declared set. --- ## Acceptance Test: ```text allowed file write succeeds outside-allowlist write fails ../ escape fails MockProvider creates deterministic output checkpoint created after task ``` After milestone: ```bash pytest -q ``` must pass. ## Forbidden No verification execution inside Builder. No repair. --- # M5 — REAL VERIFICATION + FAILURE CLASSIFICATION ## Goal Execute real verification commands and persist structured evidence. ## Files ```text src/harness/verification/verifier.py src/harness/verification/classifier.py tests/test_verifier.py tests/test_classifier.py ``` --- ## Verifier Implement: ```python verify_task( task: Task, workspace: Path ) -> list[VerificationResult] ``` For every verification command: ```text shlex.split(command) → LocalSandbox.execute(...) ``` Default when missing: ```bash pytest -q ``` Capture: ```text exit_code stdout[-4000:] stderr[-4000:] duration_ms ``` PASS: ```text exit_code == 0 ``` FAIL: ```text exit_code != 0 ``` Timeout: ```text Task status = TIMED_OUT FailureType = TIMEOUT ``` Static inspection alone can never count as verification. --- ## Workspace verification Provide helper: ```python verify_workspace(workspace) ``` It may include project-level checks appropriate to files actually present. Do not blindly require external network installation as part of offline harness unit tests. --- ## Failure classifier precedence Classification MUST be deterministic. Use precedence: ```text 1. TIMEOUT 2. ENVIRONMENT_ERROR 3. DEPENDENCY_ERROR 4. TYPE_ERROR 5. CODE_ERROR 6. CONFIG_ERROR 7. TEST_FAILURE 8. UNKNOWN ``` The precedence matters. For example, a pytest session containing a Python `SyntaxError` must classify as: ```text CODE_ERROR ``` not merely `TEST_FAILURE`. ### TIMEOUT Patterns: ```text timed out TimeoutExpired duration >= configured timeout ``` ### ENVIRONMENT_ERROR Patterns: ```text EAI_AGAIN ENOTFOUND registry unavailable Network is unreachable HTTP 503 Could not fetch ``` ### DEPENDENCY_ERROR Patterns: ```text ModuleNotFoundError ImportError No module named Could not resolve dependency npm ERR 404 ``` ### TYPE_ERROR Patterns: ```text mypy Pydantic ValidationError TypeError ... expected TS2322 Property ... does not exist ``` ### CODE_ERROR Patterns: ```text SyntaxError IndentationError NameError ReferenceError ``` ### CONFIG_ERROR Patterns: ```text missing configuration missing pyproject requirements file not found port already in use invalid path configuration ``` ### TEST_FAILURE Patterns: ```text AssertionError FAILED 1 failed FAIL tests/ ``` Only after higher-priority categories have been excluded. --- ## Acceptance Tests: ```text SyntaxError → CODE_ERROR ModuleNotFoundError → DEPENDENCY_ERROR AssertionError → TEST_FAILURE network unavailable → ENVIRONMENT_ERROR timeout → TIMEOUT working scaffold → PASS ``` Persist verification evidence. ## Forbidden No automatic repair yet. --- # M6 — REPAIR LOOP + LOOP DETECTION ## Goal Implement: ```text FAIL → classify → repair → verify ``` with bounded retries. ## Files ```text src/harness/orchestration/repair.py src/harness/agents/repair_agent.py tests/test_repair.py ``` --- ## Loop signature ```python sha256( command + exit_code + normalize(stderr[-2000:]) ) ``` Normalization: ```text lowercase strip changing timestamps strip volatile numeric values normalize paths collapse whitespace ``` Track: ```python seen[signature] += 1 ``` If the same normalized failure signature occurs three times: ```text ESCALATE FAILED BLOCK dependents ``` Total repair attempts MUST NEVER exceed: ```text 3 ``` --- ## Repair strategy ### ENVIRONMENT_ERROR ```text Do not rewrite application code. Retry once. If still failing → FAILED. ``` ### DEPENDENCY_ERROR Repair only dependency/config files that are already allowed by the Task or explicitly listed as verification hints. ### TYPE_ERROR Patch relevant code only. ### CODE_ERROR Patch relevant code only. ### TEST_FAILURE Patch implementation or tests only when justified by requirement evidence. Do not simply weaken tests to obtain PASS. ### CONFIG_ERROR Patch configuration files only. ### TIMEOUT Allow one bounded adjustment/retry. Do not create an unbounded timeout. --- ## RepairAgent context Provide: ```text Task relevant requirement slice failing VerificationResult FailureType allowed files current relevant file contents ``` Truncate large source context around: ```text 8000 chars per repair context ``` Output: ```json { "relative/path": "full corrected contents" } ``` --- ## Acceptance Tests: ```text repair SyntaxError → PASS within <=3 attempts same failure 3 times → ESCALATE dependents become BLOCKED ENVIRONMENT_ERROR does not modify code files outside allowlist cannot be repaired ``` --- # M7 — TRACEABILITY MATRIX ## Goal Construct mechanical evidence: ```text Requirement → Tasks → Files → Verification → Result ``` ## Files ```text src/harness/trace/matrix.py tests/test_trace.py ``` --- ## Matrix structure For every requirement: ```json { "REQ-001": { "tasks": [], "files": [], "tests": [], "evidence": [], "status": "PASS|FAIL", "missing": [] } } ``` Compute: ```text tasks = tasks referencing REQ files = union(task.files_touched) tests = union(task.verification) evidence = existing files + successful verification commands ``` PASS only if: ```text >=1 expected implementation file exists AND >=1 relevant verification result PASS ``` No evidence: ```text FAIL ``` Prose can never substitute for evidence. --- ## Acceptance Todo reference run: ```text 4/4 requirements traced ``` Delete an implementation file: ```text associated requirement becomes FAIL ``` --- # M8 — REQUIREMENT REVIEW ## Goal Perform the final requirement-level audit. ## Files ```text src/harness/agents/reviewer.py tests/test_review.py ``` --- ## ReviewAgent Default authority: ```text rule-based evidence ``` LLM review is optional and explanatory only. An LLM MAY: ```text add rationale summarize evidence identify concerns ``` An LLM MUST NOT: ```text turn evidence-based FAIL into PASS ``` --- ## Output Persist: ```text runs/<run_id>/review.json ``` Shape: ```json { "requirements": [ { "id": "REQ-001", "status": "PASS", "evidence": [], "missing": [] } ], "overall_status": "PASS" } ``` Overall PASS only if: ```text every requirement == PASS ``` --- ## Acceptance Tests: ```text complete evidence → PASS missing implementation file → FAIL missing successful verification → FAIL LLM cannot override FAIL review JSON validates ``` --- # M9 — CHECKPOINTING + CRASH RECOVERY ## Goal Resume interrupted runs without repeating completed work. ## Files ```text src/harness/state/checkpoints.py src/harness/orchestration/pipeline.py tests/test_recovery.py ``` --- ## Required checkpoint events ```text spec_created plan_created task_started task_completed verification_completed repair_started review_completed ``` Filename convention: ```text checkpoints/<sequence>-<event>-<optional-task>.json ``` Example: ```text 001-spec_created.json 002-plan_created.json 003-task_started-TASK-001.json 004-task_completed-TASK-001.json ``` --- ## Resume algorithm ```text load state.json ↓ validate state ↓ load latest checkpoint state ↓ reconstruct task statuses ↓ keep COMPLETED keep FAILED keep BLOCKED convert interrupted RUNNING → PENDING convert READY → PENDING ↓ continue unfinished pipeline ``` Completed tasks MUST NOT execute again. Use file hashes where appropriate to prove completed output was not rewritten during resume. --- ## Corruption handling Corrupt: ```text state.json checkpoint JSON ``` must produce a clear explicit error. Never silently restart the run from scratch. --- ## Acceptance Simulate crash after: ```text TASK-002 ``` Resume must: ```text finish remaining tasks not rerun TASK-001 not alter completed file hashes ``` Test checkpoint sequencing. --- # M10 — RUNTIME VERIFICATION ## Goal Prove that the generated application actually starts and responds. Static tests alone are insufficient. ## Files ```text src/harness/verification/runtime.py src/harness/verification/browser.py tests/test_runtime.py ``` --- ## RuntimeVerifier ### Entry detection Recognize at minimum: ```text src/main.py:app app.py:app package.json ``` No recognized entry: ```text FAIL CONFIG_ERROR ``` ### Start FastAPI: ```bash python -m uvicorn src.main:app --port <free_port> ``` Node fallback: ```bash npm run dev -- --port <free_port> ``` Use an OS-assigned/free local port. Start process with: ```python subprocess.Popen ``` with: ```text cwd jailed inside workspace shell=False ``` The verification layer may own process execution; application-building agents may not. ### Startup timeout ```text 15 seconds ``` ### Checks Verify: ```text process remains alive TCP port accepts connection GET /health OR / returns 2xx GET /docs or /api/health when available SQLite DB can be opened when expected ``` ### Cleanup Always terminate spawned process. Use `finally` cleanup. Never leave orphan development servers. ### Result Return structured: ```json { "status": "PASS", "checks": [ { "name": "health", "ok": true, "detail": "HTTP 200" } ], "evidence": [] } ``` Capture useful log snippets. --- ## Browser V1 stub Implement only: ```python def verify_acceptance(...): raise NotImplementedError( "Browser verification deferred post-V1" ) ``` Test that the browser verifier remains explicitly deferred. Do NOT install Playwright or Selenium. --- ## Acceptance Reference application: ```text starts port opens health endpoint returns 200 runtime verifier PASS ``` Broken startup: ```text FAIL diagnostics captured repair hint available ``` --- # M11 — CLI + BENCHMARKS ## Goal Expose the entire harness through a deterministic command-line interface and provide a quick regression benchmark. ## Files ```text src/harness/cli.py src/harness/orchestration/pipeline.py src/harness/benchmarks.py tests/test_cli.py tests/test_benchmarks.py ``` Add console entrypoint: ```toml [project.scripts] builder = "harness.cli:main" ``` Use: ```text argparse only ``` No Click/Typer dependency. --- ## CLI commands ### New run ```bash builder new "Build a Todo app" ``` Equivalent module form: ```bash python -m harness.cli new "Build a Todo app" ``` It must execute the full pipeline. ### Resume ```bash builder resume <run_id> ``` ### Logs ```bash builder logs <run_id> ``` Print or tail the run's structured event log in readable form. ### Benchmark ```bash builder bench --quick ``` --- ## Progress output `builder new` must emit five user-facing high-level stages: ```text [1/5] SPEC [2/5] PLAN [3/5] BUILD [4/5] VERIFY [5/5] REVIEW ``` Detailed internal milestones remain M1–M12; the five-stage CLI view is only presentation. On success: ```text BUILD COMPLETE ``` On failure: ```text BUILD FAILED ``` and return non-zero exit status. --- ## Quick benchmark `builder bench --quick` runs a deterministic small Todo scenario. It must validate at minimum: ```text spec generated plan generated files written verification executed runtime checked review produced required artifacts exist ``` Return: ```text 0 → PASS non-zero → FAIL ``` --- ## Acceptance Must pass: ```bash builder new "Build a Todo app" builder bench --quick ``` Offline LLM fallback must still function. Verify: ```text all required artifacts exist five-stage output matches expected format events.log contains required keys quick benchmark passes ``` ## Forbidden No Web UI. No production Docker environment. --- # M12 — FINAL GATE ## Goal Prove V1 reliability before declaring completion. All gates are mandatory. --- ## Gate 1 — Vertical Slice Run: ```bash builder new "Build a Simple Todo App with add/list/complete" ``` Expected pipeline: ```text SPEC → >=3 REQs → PLAN → >=3 tasks → BUILD → real files → VERIFY → pytest PASS → RUNTIME → PASS → REVIEW → PASS ``` Save a stable demonstration run under: ```text runs/demo_todo/ ``` If any stage fails: ```text fix the harness rerun do not proceed ``` --- ## Gate 2 — Failure Injection Inject: ```python SyntaxError ``` into: ```text workspace/src/main.py ``` The harness must: ```text DETECT → FAIL CLASSIFY → CODE_ERROR LOCALIZE → TASK-ID CAPTURE → diagnostics REPAIR → relevant file only REVERIFY → PASS ``` Then simulate identical failure repeatedly using a no-op repair implementation. Expected: ```text same signature x3 → LOOP DETECTED → ESCALATE → task FAILED → dependents BLOCKED ``` --- ## Gate 3 — V1 Capability Checklist All MUST be ✓: ```text [ ] valid spec generated [ ] spec validated [ ] valid DAG generated [ ] sequential execution [ ] real files created [ ] real verification executed [ ] failures localized [ ] failures classified [ ] failures repaired [ ] repair bounded <=3 [ ] loop detection works [ ] checkpoints written [ ] crash resume works [ ] completed tasks not rerun [ ] traceability matrix generated [ ] requirement review generated [ ] runtime verified [ ] final working project retained ``` --- ## Gate 4 — Documentation README must document: ```text quickstart builder new builder resume builder logs builder bench --quick architecture evidence principle failure handling checkpoint recovery ``` Include an ASCII architecture diagram. Create: ```text examples/todo_run/ ├── spec.json ├── tasks.json ├── verification.json └── review.json ``` --- ## Gate 5 — Full Test Suite Run: ```bash pytest -q builder bench --quick ``` Both must pass. --- ## V1 Forbidden-Feature Audit Assert the implementation does NOT contain functional implementations for: ```text docker/ web_ui/ parallel workers parallel DAG scheduler Playwright Selenium PostgreSQL backend web research ``` The browser verification stub is allowed. --- # FINAL DEFINITION OF DONE V1 is complete only when: ```text M1 PASS M2 PASS M3 PASS M4 PASS M5 PASS M6 PASS M7 PASS M8 PASS M9 PASS M10 PASS M11 PASS M12 PASS ``` Every bug fix MUST include a regression test. Every new module MUST have tests. Keep source files focused. Prefer: ```text <400 lines per file ``` Split larger files when practical. Never store: ```text API keys secrets absolute host-specific paths ``` Never delete historical checkpoints to hide failures. --- # FINAL RUN SUMMARY FORMAT At the end of every run, print a requirement-level summary. Example: ```text REQ-001 Implemented: YES Tested: YES Runtime: YES Evidence: - src/main.py - pytest -q → exit_code 0 Status: PASS REQ-002 Implemented: YES Tested: NO Runtime: NO Missing: - successful verification result Status: FAIL ``` Final status: ```text PASS ``` only when every requirement has evidence-backed PASS status. Never use: ```text "AI says finished" ``` as evidence. --- # EXECUTION COMMAND Start now. Implement: ```text M1 ``` Run its tests. If green, continue to: ```text M2 ``` Continue sequentially until M12. Do not ask questions. Do not stop at intermediate milestones. Do not skip failed gates. Do not declare V1 complete until the Final Gate is green.

shipping stamp

create a PNG image like a stamp saying sent to $(country). Image in red, retro style, horizontal stamp

Tumeric kojic soap

A close-up showcases the exquisite packaging of the tumeric kojic soap, displaying is vibrant orange and yellow designs.

Hallucination Investigator

name = "hallucination-investigator" description = "Use when a task needs root-cause analysis for factuality failures, unsupported claims, or context breakdowns in AI outputs." model = "gpt-5.6-sol" model_reasoning_effort = "high" sandbox_mode = "read-only" developer_instructions = """ Own hallucination investigation as root-cause analysis across context, retrieval, prompts, tools, and workflow design. Working mode: 1. Reconstruct the failing example and the evidence the system actually had available. 2. Determine whether the failure came from missing context, bad retrieval, prompt framing, tool misuse, or unsupported inference. 3. Recommend the smallest change that most directly reduces recurrence. 4. Note how to verify the fix with targeted cases. Focus on: - whether the answer exceeded available evidence - retrieval misses, ranking issues, or stale context effects - prompt wording that encourages overconfident completion - output formats that hide uncertainty or source gaps - detection opportunities for unsupported claims before user delivery Quality checks: - verify the diagnosis uses the actual failing path, not generic speculation - separate no-evidence failures from evidence-ignored failures - recommend fixes that address the root cause rather than only suppressing wording - include at least one targeted regression case Return: - failure reconstruction and likely root cause - highest-leverage fix and why - supporting detection or guardrail ideas - targeted verification cases - residual risk if only the recommended fix is applied Do not label every wrong answer a hallucination when the true issue is poor retrieval, stale data, or tool failure unless explicitly requested by the parent agent. """ Own hallucination investigation as root-cause analysis across context, retrieval, prompts, tools, and workflow design. Working mode: 1. Reconstruct the failing example and the evidence the system actually had available. 2. Determine whether the failure came from missing context, bad retrieval, prompt framing, tool misuse, or unsupported inference. 3. Recommend the smallest change that most directly reduces recurrence. 4. Note how to verify the fix with targeted cases. Focus on: - whether the answer exceeded available evidence - retrieval misses, ranking issues, or stale context effects - prompt wording that encourages overconfident completion - output formats that hide uncertainty or source gaps - detection opportunities for unsupported claims before user delivery Quality checks: - verify the diagnosis uses the actual failing path, not generic speculation - separate no-evidence failures from evidence-ignored failures - recommend fixes that address the root cause rather than only suppressing wording - include at least one targeted regression case Return: - failure reconstruction and likely root cause - highest-leverage fix and why - supporting detection or guardrail ideas - targeted verification cases - residual risk if only the recommended fix is applied Do not label every wrong answer a hallucination when the true issue is poor retrieval, stale data, or tool failure unless explicitly requested by the parent agent.

Claude setup test - safe to delete

This is a test prompt created to verify API authentication.

Metacarve

Sheet metal fabrication with hames laser as well as energy mission press break make a video for metacarve Fab tech marketing campaign

areocpi

create the landing page the i want build and this my project topic name :Development of a Real-time Airfare Price Index for India through Automated Web Scraping of Airline and Online Travel Aggregator Portals for Augmentation of the Consumer Price Index (CPI) and this websit should be open source ### Mini prompt for creating the AeroCPI landing page > **Create a modern, professional landing page for “AeroCPI – Real-Time Airfare Price Index for India”. Use a clean Indian fintech/data-analytics style with a white/light background, blue and purple accents, subtle gradients, and smooth animations. Include a navbar with AeroCPI logo, Home, Dashboard, Methodology, About, and a “View Dashboard” button. Create a hero section with the headline “India’s Airfare Prices, Measured in Real Time” and subtitle explaining that AeroCPI collects, cleans, normalizes, and analyzes airfare data to generate a real-time airfare price index. Add CTA buttons “Explore Dashboard” and “Learn How It Works”. Include a visual airfare trend chart/mock dashboard on the right. Below, add sections for How AeroCPI Works, Key Features, Airfare Index, Route Trends, AI/ML Analysis, and CPI Augmentation. End with a professional footer. Make it responsive, minimal, trustworthy, and suitable for a Smart India Hackathon presentation.** ### Mini prompt for creating the AeroCPI landing page

Create Project

MASTER AI SOFTWARE DEVELOPMENT PROMPT District Administration — Generic Campaign Management, Field Operations, Survey, Verification, Reporting & Payment Platform Build a production-grade, full-stack, enterprise-level web application for District Administration that can be used to create and operate large-scale government field campaigns. The platform must support campaigns involving: • One department. • Multiple departments. • Joint inter-department teams. • Senior officers. • Supervisors. • Field officers. • Reserve/backup employees. • Institutions. • Villages. • Wards. • Mohallas. • Households. • Other configurable target entities. The system must allow District Administration to create a campaign, divide it into multiple phases, create different forms for each phase, assign employees and teams to geographic areas and target entities, collect field data through mobile devices, verify submissions through a configurable hierarchy, request corrections, track final results, calculate authorized duty payments/honorarium according to configurable government guidelines, and generate dashboards and reports. The system must be generic. Do not hard-code the application for Census only. Census 2027 should be implemented as an example campaign type. Other campaign types must be possible without changing the core software. Examples: • Census 2027. • School Inspection. • Hospital Inspection. • Road Survey. • Flood Damage Survey. • Village Survey. • PDS Inspection. • Anganwadi Inspection. • Infrastructure Survey. • Government Scheme Verification. • Disaster Assessment. • Public Grievance Field Verification. • Any future district campaign. ________________________________________ 1. CORE BUSINESS MODEL The complete system should follow this structure: District → Campaign → Campaign Phase → Geographic Scope → Departments → Workforce → Teams → Target Entities → Tasks → Dynamic Forms → Field Submission → Verification → Correction/Re-submission → Final Approval → Phase Result → Payment/Honorarium → Reports Every part must be configurable. ________________________________________ 2. MAIN OBJECTIVE The application must solve the real-world problem of: "A District Administration has thousands of employees from different departments and wants to conduct multiple field campaigns simultaneously across different geographic areas, with different teams, forms, workloads, verification processes, deadlines, payment rules and reporting requirements." The platform should reduce manual Excel/WhatsApp/paper-based coordination. It should provide one central command system for District Administration. ________________________________________ 3. MULTIPLE CAMPAIGNS District Administration must be able to run multiple campaigns simultaneously. Example: • Census 2027. • School Inspection. • Road Survey. • Flood Assessment. • Drinking Water Survey. Each campaign is independent. Each campaign can have: • Different departments. • Different employees. • Different geographic areas. • Different forms. • Different workflow. • Different deadlines. • Different payment rules. • Different target entities. • Different reporting structure. ________________________________________ 4. MULTI-PHASE CAMPAIGN Every campaign can have multiple phases. Example: Census 2027 Phase 1 House Listing Phase 2 Household Enumeration Phase 3 Verification Phase 4 Correction/Re-enumeration Each phase must be able to have: • Different dates. • Different forms. • Different workforce. • Different teams. • Different geographic assignments. • Different instructions. • Different workload. • Different verification workflow. • Different payment rules. • Different results. Do not assume that all phases use the same employees or form. ________________________________________ 5. CAMPAIGN TYPES Create configurable campaign types. Examples: • Census. • Inspection. • Survey. • Verification. • Enumeration. • Monitoring. • Assessment. • Disaster response. • Infrastructure survey. • Custom. Admin can create a new campaign type. ________________________________________ 6. ORGANIZATIONAL HIERARCHY The organization must be configurable. Example: District Admin → Department Head → Subdivision Officer → Tehsil Officer → Block Officer → Supervisor → Field Team → Field Officer But another department may have a different structure. Therefore do not hard-code hierarchy levels. Use: OrganizationNode with configurable parent/child relationships. ________________________________________ 7. GEOGRAPHIC HIERARCHY Support flexible geographic hierarchy. Example rural: State → District → Subdivision → Tehsil → Block → Village → Mohalla/Hamlet → Household Example urban: State → District → Municipality/Nagar Palika → Zone → Ward → Mohalla → Household The system must support both. Do not assume every area has the same structure. ________________________________________ 8. GEOGRAPHIC MASTER DATA Create geographic master data management. Admin can manage: • District. • Subdivision. • Tehsil. • Block. • Municipality. • Ward. • Village. • Mohalla. • GPS coordinates. • Boundary/polygon where available. Support bulk import through: • CSV. • Excel. • Government master-data API where available. Validate duplicate geographic records. ________________________________________ 9. TARGET ENTITY ENGINE Do not make "household" the only target. Create a generic target entity system. Possible entities: • Household. • Person. • School. • Hospital. • Road. • Village. • Shop. • Anganwadi. • Government building. • Water source. • Custom entity. Example: Campaign: School Inspection Target: School Campaign: Census Target: Household Campaign: Road Survey Target: Road segment. ________________________________________ 10. ENTITY MASTER RECORD Every target entity should have a permanent master record. Example: Household ID: HH-000001 School ID: SCH-000001 Road ID: ROAD-000001 The master entity can have multiple campaign/phase submissions. This prevents duplication. ________________________________________ 11. HOUSEHOLD MODEL For Census-type campaigns support: Household → Household members → Individual person records The household can have: • Household ID. • Address. • Geographic hierarchy. • House number. • GPS. • Status. • Source. • Phase history. The individual/person structure must support variable number of persons. ________________________________________ 12. EMPLOYEE MASTER Create a central employee database. Fields: • Employee ID. • Name. • Mobile number. • Designation. • Department. • Office. • Posting location. • District. • Subdivision. • Tehsil. • Block. • Role. • Employment status. • Availability. • Reserve status. • Training status. Employee ID should be unique. Mobile number should be unique where applicable. ________________________________________ 13. BULK EMPLOYEE IMPORT Support import of thousands of employees. Formats: • Excel. • CSV. Before import: • Validate. • Detect duplicate Employee IDs. • Detect duplicate mobile numbers. • Detect missing fields. • Detect invalid departments. • Show row-level errors. Allow: Import Valid Records without losing valid records because of invalid rows. ________________________________________ 14. EMPLOYEE AVAILABILITY Employee status: • Available. • Assigned. • On Duty. • On Leave. • Unavailable. • Reserve. • Activated Reserve. • Released. • Suspended. Campaign assignment must check availability. Prevent incompatible double assignment. ________________________________________ 15. MULTI-DEPARTMENT CAMPAIGNS A campaign can include multiple departments. Example: School Inspection: • Education. • PWD. • Food. • Revenue. Each department can have different responsibilities. ________________________________________ 16. JOINT TEAMS Create a team engine. A team can contain employees from different departments. Example: Team 001: • Revenue employee. • Education employee. • PWD employee. Each team has: • Team ID. • Team leader. • Members. • Department. • Geographic responsibility. • Campaign. • Phase. • Status. ________________________________________ 17. TEAM FORMATION Allow: Manual Admin selects employees. Automatic System creates teams based on configured rules. Rules may include: • Team size. • Department combination. • Geographic area. • Designation. • Skill. • Availability. • Workload. ________________________________________ 18. TEAM LEADER Team leader can: • See team members. • See assigned tasks. • Monitor progress. • Review team-level work where authorized. • Report employee absence. • Request replacement. • Submit team reports. Do not automatically grant access to all data just because someone is team leader. Permissions must still apply. ________________________________________ 19. RESERVE EMPLOYEE SYSTEM Every large campaign should support reserve employees. Reserve employees can replace active staff when necessary. Reasons: • Leave. • Illness. • Transfer. • Emergency. • Administrative requirement. • Other authorized reasons. Workflow: Active Employee → Unavailable → Supervisor reports → Authorized officer approves → Reserve employee selected → Reserve activated → Assignment transferred → Audit record created. ________________________________________ 20. RESERVE TEAM Support reserve teams in addition to reserve individuals. Example: Active Team: Team 001 Reserve Team: Team R001 If an entire team becomes unavailable, the reserve team can be activated. ________________________________________ 21. WORKLOAD MANAGEMENT Before launching a campaign phase, show: Total target entities. Required workforce. Available workforce. Reserve workforce. Expected workload per employee. Expected workload per team. Example: Targets: 1,000,000 Teams: 10,000 Average: 100 targets/team. Allow authorized admins to adjust distribution. ________________________________________ 22. WORKLOAD BALANCING Support: • Equal distribution. • Geographic distribution. • Random distribution. • Manual distribution. • Skill-based distribution. • Workload balancing. The system should detect overloaded employees/teams. Example: Employee A: 300 tasks Employee B: 80 tasks Show warning. ________________________________________ 23. RANDOM ASSIGNMENT Support random assignment where required. Example: 10,000 schools 1,000 officers System randomly assigns schools. Prevent duplicate assignments. Allow administrators to preview before activation. Maintain assignment history. ________________________________________ 24. GEOGRAPHIC ASSIGNMENT Tasks can be assigned based on: • District. • Subdivision. • Tehsil. • Block. • Village. • Ward. • Mohalla. • GPS boundary. Support polygon-based geographic assignment where feasible. ________________________________________ 25. CAMPAIGN CREATION WIZARD Create a professional multi-step wizard. Step 1 Campaign details. Step 2 Campaign type. Step 3 Geographic scope. Step 4 Departments. Step 5 Workforce. Step 6 Teams. Step 7 Target entities. Step 8 Form. Step 9 Assignment. Step 10 Verification workflow. Step 11 Payment rules. Step 12 Guidelines/documents. Step 13 Preview. Step 14 Launch. ________________________________________ 26. CAMPAIGN VALIDATION BEFORE LAUNCH Before launch check: • No target entities. • No teams. • No officers. • Missing form. • Missing mandatory questions. • Missing geographic assignment. • Missing verification workflow. • Missing payment configuration where required. • Employee conflicts. • Duplicate assignments. • Insufficient workforce. • Invalid dates. Show warnings and errors. Do not allow launch when critical requirements are missing. ________________________________________ 27. DYNAMIC FORM BUILDER District Admin must create forms without coding. Question types: • Short text. • Long text. • Integer. • Decimal. • Percentage. • Currency/amount. • Date. • Date/time. • Yes/No. • Radio. • Checkbox. • Dropdown. • Multi-select. • Image. • Multiple image. • Video. • File. • GPS. • Signature. • Rating. • Table. • Repeating group. • Calculated field. ________________________________________ 28. FORM SECTIONS Forms can contain sections. Example: School Inspection: 1. School Information. 2. Infrastructure. 3. PWD. 4. Food. 5. Education. 6. Final Remarks. ________________________________________ 29. CONDITIONAL QUESTIONS Support rules. Example: IF: Building damaged = YES THEN: Show: • Damage type. • Damage severity. • Damage photo. • Repair estimate. Otherwise hide these fields. Create a visual condition builder. ________________________________________ 30. REPEATING GROUPS For Census: Household: Number of members = 6 Automatically create: Person 1 Person 2 Person 3 Person 4 Person 5 Person 6. Support nested repeating data where required. ________________________________________ 31. FORM VALIDATION Each question can have: • Required. • Minimum. • Maximum. • Length. • Regex. • Allowed options. • Dependency. • Evidence requirement. • GPS requirement. Validation must happen: Frontend + Backend Never trust frontend validation alone. ________________________________________ 32. FORM VERSIONING Forms must be versioned. Example: Form v1 Form v2 Historical submissions remain associated with their original form version. Changing a form must not change old submissions. ________________________________________ 33. CAMPAIGN FORM Each phase can have its own form. Example: Campaign: Census 2027 Phase 1: Form A Phase 2: Form B Phase 3: Form C ________________________________________ 34. FIELD OFFICER MOBILE APP Build a mobile-first PWA. Field employee dashboard: Campaigns → Active Phase → Assigned Area → Assigned Tasks → Completed → Pending → Corrections → Drafts → Sync → Notifications ________________________________________ 35. FIELD TASK Each task contains: • Task ID. • Campaign. • Phase. • Target. • Geographic location. • Assigned team. • Assigned employee. • Deadline. • Priority. • Status. • Instructions. ________________________________________ 36. TASK STATUS Use: • Not Started. • Assigned. • Accepted. • In Progress. • Draft. • Submitted. • Under Verification. • Correction Required. • Resubmitted. • Approved. • Rejected. • Reassigned. • Overdue. • Completed. ________________________________________ 37. FIELD DATA COLLECTION Field officer should be able to: • Open task. • Start task. • Fill form. • Save draft. • Resume later. • Capture GPS. • Capture image. • Upload video. • Add remarks. • Submit. ________________________________________ 38. GPS When configured: Capture: • Latitude. • Longitude. • Accuracy. • Timestamp. Optionally calculate distance from target location. Configurable: • Warning. • Supervisor review. • Block submission. ________________________________________ 39. PHOTO Support: • Camera. • Gallery. • Multiple images. • Compression. • Preview. • Retake. Associate image with: • Campaign. • Phase. • Task. • Question. • Employee. ________________________________________ 40. VIDEO Support: • Record. • Select. • Preview. • Upload. • Progress. • Retry. • Maximum size. • Maximum duration. Use object storage. Do not store large videos directly in PostgreSQL. ________________________________________ 41. OFFLINE MODE Mobile application must work with poor connectivity. Use: • PWA. • IndexedDB. • Local draft. • Offline task list. • Sync queue. Status: Online Offline Syncing Synced Failed. ________________________________________ 42. OFFLINE CONFLICT MANAGEMENT If the same record changes from multiple sources: Do not silently overwrite. Create conflict: Conflict requires review. Maintain version history. ________________________________________ 43. SUBMISSION Before final submission: Show review page. Example: Required fields: ✓ GPS: ✓ Required images: ✓ Validation: ✓ Then: Submit Server returns: Submission ID. Never show successful submission before server confirmation. ________________________________________ 44. VERIFICATION ENGINE Create configurable workflow. Example: Field Officer → Supervisor → Tehsil Officer → Subdivision Officer → Department Head → District Admin But administrators can configure different levels. ________________________________________ 45. VERIFICATION ACTIONS Reviewer can: • Approve. • Reject. • Request correction. • Add comment. • Escalate. • Reassign. • View history. ________________________________________ 46. CORRECTION WORKFLOW Example: Reviewer: "Please upload a clear photograph." Status: Correction Required. Employee receives notification. Employee edits only permitted fields. Resubmits. Reviewer receives notification. ________________________________________ 47. DATA VERSIONING Every submission must preserve: • Version. • Answers. • Files. • GPS. • User. • Timestamp. • Changes. • Reason. Never destroy historical versions. ________________________________________ 48. FINAL APPROVAL Only approved records should be included in final results when the campaign requires final approval. Allow reports to distinguish: • Preliminary. • Submitted. • Verified. • Final Approved. ________________________________________ 49. DATA QUALITY ENGINE Create automatic quality checks. Examples: • Duplicate household. • Duplicate task. • Missing GPS. • Impossible values. • Inconsistent totals. • Required evidence missing. • Conflicting phase data. • Unusual completion speed. • Repeated identical GPS coordinates where suspicious. • Excessive submissions in a short time. Flag anomalies for review. Do not automatically accuse an employee of misconduct. Mark: Data Quality Exception ________________________________________ 50. EXCEPTION MANAGEMENT Create a central Exception Center. Examples: • Missing household. • Duplicate household. • GPS issue. • Incomplete form. • Conflicting data. • Overdue task. • Employee unavailable. • Team unavailable. • Payment failure. • Sync failure. Admin can assign exceptions. ________________________________________ 51. CENSUS 2027 EXAMPLE Create Census 2027 as a sample campaign. Do not invent official Census questions. Use placeholder/configurable forms or officially supplied forms. Example structure: Census 2027 → Phase 1: House Listing → Phase 2: Enumeration → Phase 3: Verification → Phase 4: Correction Each phase has different forms and possibly different workforce. ________________________________________ 52. CENSUS GEOGRAPHIC STRUCTURE Support: District → Subdivision → Tehsil → Municipality / Nagar Palika → Ward → Village → Mohalla → Household The actual hierarchy must be configurable. ________________________________________ 53. CENSUS JOINT TEAM Example: Team 001 Area: Ward 10 / Mohalla A Members: • Education Department employee. • Revenue Department employee. • Municipal employee. The team visits households within its assigned area. ________________________________________ 54. HOUSEHOLD CENSUS FLOW Team opens: Household HH-000123 System displays: • Location. • Address. • Previous phase information if authorized. • Current phase form. Team collects required information. Submits. Result goes through configured verification workflow. ________________________________________ 55. CENSUS MULTI-PHASE WORKLOAD Support distributing work over multiple phases to reduce employee workload. Example: Phase 1: Employee Group A Phase 2: Employee Group B Phase 3: Employee Group C Or the same employees can participate in multiple phases. The system must support both. ________________________________________ 56. PAYMENT/HONORARIUM ENGINE Create a dedicated payment module. IMPORTANT: Never hard-code government payment amounts. Payment amounts must come from authorized configurable rules based on the applicable government order/guideline. ________________________________________ 57. PAYMENT RULE Payment rule fields: • Campaign. • Phase. • Role. • Department if applicable. • Duty type. • Calculation method. • Amount/rate. • Effective date. • Government order reference. • Version. • Approval status. ________________________________________ 58. PAYMENT CALCULATION Possible calculation models: • Fixed amount. • Per day. • Per task. • Per approved household. • Role-based. • Phase-based. • Component-based. Do not assume these are legally applicable. The administrator configures the permitted calculation method according to official rules. ________________________________________ 59. PAYMENT ELIGIBILITY Example: Assignment ↓ Duty completed ↓ Required work completed ↓ Submission accepted/approved ↓ Eligibility generated ↓ Payment approval ↓ Payment processing ↓ Paid Exact rules must be configurable. ________________________________________ 60. EMPLOYEE PAYMENT DASHBOARD Employee sees: Campaign: Census 2027 Phase: Phase 1 Duty: Completed Eligibility: Eligible Payment: ₹XXXX Status: Pending / Approved / Processing / Paid. Sensitive financial information must be protected. ________________________________________ 61. PAYMENT STATUS Statuses: • Not Eligible. • Pending Eligibility. • Eligible. • Pending Approval. • Approved. • Processing. • Paid. • Failed. • Returned. • On Hold. • Disputed. ________________________________________ 62. PAYMENT REMINDERS If payment is pending: Send: • In-app notification. • SMS where configured. • Email where configured. Example: Your approved campaign duty payment is still pending processing. Do not make unverified claims about payment timing. ________________________________________ 63. PAYMENT EXCEPTIONS Support: • Failed payments. • Incorrect records. • Missing approval. • Duplicate payment prevention. • Hold. • Retry. • Resolution. Maintain complete audit trail. ________________________________________ 64. PAYMENT DUPLICATE PREVENTION Prevent duplicate payment for: Employee + Campaign + Phase + Duty unless explicitly allowed by an authorized adjustment process. ________________________________________ 65. ATTENDANCE / DUTY PROOF Where required by campaign rules, support duty attendance. Possible methods: • Start duty. • End duty. • GPS. • Team leader confirmation. • Supervisor approval. • Task completion. Do not assume attendance equals payment eligibility. Make it configurable. ________________________________________ 66. TRAINING Track: • Training assigned. • Training completed. • Training date. • Training material. • Assessment. • Certification. A campaign phase can optionally require training before assignment. ________________________________________ 67. GUIDELINES / DOCUMENTS Campaign administrators can upload: • Government orders. • Guidelines. • SOPs. • Training documents. • Circulars. • Forms. • Payment orders. Documents should be versioned. ________________________________________ 68. NOTIFICATION ENGINE Support: • In-app. • SMS. • Email. • Push notifications. Notifications: • New task. • New campaign. • Phase starting. • Deadline. • Overdue. • Correction. • Approval. • Reassignment. • Reserve activation. • Payment update. ________________________________________ 69. ESCALATION ENGINE Create configurable escalation. Example: Task overdue by 2 days: → Supervisor notification. Overdue by 4 days: → Tehsil Officer. Overdue by 7 days: → District Admin. The escalation schedule must be configurable. ________________________________________ 70. REMINDER ENGINE Support scheduled reminders. Examples: 7 days before deadline. 3 days before. 1 day before. Due date. Overdue. Payment pending for X days. ________________________________________ 71. DISTRICT COMMAND DASHBOARD Create a professional command center. Show: Campaigns Total. Active. Completed. Delayed. Workforce Total. Assigned. Available. Reserve. Unavailable. Tasks Total. Completed. Pending. Overdue. Correction. Verification Submitted. Under review. Approved. Rejected. Payment Eligible. Approved. Paid. Pending. Failed. ________________________________________ 72. GEOGRAPHIC DRILL-DOWN Dashboard: District ↓ Subdivision ↓ Tehsil ↓ Village/Ward ↓ Mohalla ↓ Household At every level: • Total. • Assigned. • Completed. • Pending. • Verified. • Exceptions. ________________________________________ 73. MAP Provide interactive map. Show: • Assigned areas. • Completed targets. • Pending targets. • Exceptions. • GPS submissions where authorized. Use clustering for large datasets. Do not attempt to render millions of points simultaneously. ________________________________________ 74. DEPARTMENT DASHBOARD Department Head sees: • Campaign participation. • Employees. • Teams. • Workload. • Completion. • Verification. • Exceptions. • Payment. Only authorized department data. ________________________________________ 75. SUBDIVISION / TEHSIL DASHBOARD Show local progress. Example: Tehsil A: Targets: 100,000 Completed: 92,000 Pending: 8,000 Completion: 92% ________________________________________ 76. TEAM DASHBOARD Team Leader sees: • Members. • Assigned targets. • Completed. • Pending. • Corrections. • Overdue. • Sync status. ________________________________________ 77. EMPLOYEE DASHBOARD Employee sees: • My campaigns. • My phases. • My tasks. • My progress. • Corrections. • Notifications. • Payment. • Guidelines. ________________________________________ 78. REPORTING ENGINE Create configurable reports. Reports: • Campaign. • Phase. • Department. • Employee. • Team. • Geography. • Target entity. • Verification. • Exception. • Payment. • Workforce. • Productivity. ________________________________________ 79. REPORT FILTERS Filters: • Campaign. • Phase. • Date. • Department. • Employee. • Team. • District. • Subdivision. • Tehsil. • Village. • Ward. • Mohalla. • Status. ________________________________________ 80. EXPORT Support: • Excel. • CSV. • PDF. Large reports must be generated asynchronously. ________________________________________ 81. REPORT SCHEDULING Allow authorized users to schedule reports. Example: Every day at 6 PM: District Campaign Progress Report Send to authorized users. ________________________________________ 82. DATA ACCESS CONTROL Use: RBAC + Geographic Scope + Department Scope + Campaign Scope Example: Field Officer: Only assigned tasks. Tehsil Officer: Authorized tehsil. Department Head: Authorized department. District Admin: District-wide. Never rely only on frontend restrictions. ________________________________________ 83. SUPER ADMIN Super Admin manages: • Districts. • Departments. • Users. • Roles. • Permissions. • System settings. • Master data. • Integrations. ________________________________________ 84. DISTRICT ADMIN District Admin can: • Create campaigns. • Create phases. • Create forms. • Select departments. • Manage workforce. • Create teams. • Assign areas. • Assign tasks. • Configure verification. • Configure payment rules where authorized. • Monitor progress. • Approve/review data. • Generate reports. ________________________________________ 85. DEPARTMENT HEAD Can: • View department campaigns. • Manage department workforce. • Review submissions. • Verify data. • Monitor department performance. • Generate authorized reports. ________________________________________ 86. FIELD OFFICER Can: • Login. • View assigned duties. • Collect field data. • Capture GPS. • Capture media. • Save drafts. • Submit. • Correct. • Resubmit. • View payment status. • View guidelines. ________________________________________ 87. PAYMENT OFFICER Can: • Review eligibility. • Approve payment. • Process payment. • View failures. • Retry authorized payments. • Generate payment reports. Do not give payment officers unnecessary household-data access. ________________________________________ 88. SYSTEM SECURITY Implement: • Password hashing. • Secure authentication. • OTP. • Session security. • JWT or secure session architecture. • Refresh token rotation where applicable. • Rate limiting. • API authorization. • Input validation. • File validation. • Secure headers. • CORS. • CSRF protection where applicable. • SQL injection protection. • XSS protection. • Audit logs. ________________________________________ 89. DATA PRIVACY Collect only officially required information. Sensitive information should have: • Strict access control. • Encryption where appropriate. • Audit logs. • Retention rules. • Export restrictions. Do not display sensitive household/person information on public dashboards. ________________________________________ 90. AUDIT LOG Record every important operation. Examples: • Login. • OTP. • Campaign creation. • Phase creation. • Form changes. • Employee assignment. • Team creation. • Household assignment. • Submission. • Correction. • Approval. • Reassignment. • Reserve activation. • Payment calculation. • Payment approval. • Payment processing. • Export. Audit log should be immutable for normal users. ________________________________________ 91. SYSTEM LOGGING Use structured application logs. Separate: • Application logs. • Security logs. • Audit logs. • Error logs. Do not expose internal errors to users. ________________________________________ 92. DATABASE Use: PostgreSQL ORM: Prisma Design a normalized schema. Important entities: • State. • District. • Department. • OrganizationNode. • GeographicNode. • User. • Employee. • Role. • Permission. • Campaign. • CampaignPhase. • CampaignDepartment. • CampaignGeography. • TargetEntity. • Household. • Person. • Team. • TeamMember. • ReserveEmployee. • Task. • TaskAssignment. • Form. • FormVersion. • FormSection. • FormQuestion. • FormOption. • FormCondition. • Submission. • SubmissionVersion. • SubmissionAnswer. • SubmissionFile. • GPSRecord. • Verification. • CorrectionRequest. • Exception. • PaymentRule. • PaymentRuleVersion. • EmployeePayment. • PaymentComponent. • PaymentTransaction. • Notification. • GuidelineDocument. • Training. • AuditLog. • Report. • ReportJob. Use appropriate: • Foreign keys. • Unique constraints. • Indexes. • Soft deletion where appropriate. • Timestamps. ________________________________________ 93. DATA RETENTION Build configurable retention policies. Different records may have different retention requirements. Do not automatically delete official records without an authorized retention policy. ________________________________________ 94. BACKUP Design: • Automated database backups. • Point-in-time recovery where supported. • Object storage backup. • Backup monitoring. • Restore testing. ________________________________________ 95. DISASTER RECOVERY Document: • Recovery procedure. • Backup restoration. • Database recovery. • File recovery. • Queue recovery. • Disaster scenarios. ________________________________________ 96. SCALABILITY Design for: • 50,000+ employees. • Millions of targets. • Millions of submissions. • Large file uploads. • Thousands of concurrent mobile users. Use: • Pagination. • Cursor pagination where appropriate. • Database indexes. • Redis. • Queue workers. • Object storage. • Background jobs. • Horizontal scaling. • Database connection pooling. ________________________________________ 97. BACKGROUND JOB SYSTEM Use: Redis + BullMQ or equivalent. Jobs: • Report generation. • Excel export. • PDF generation. • Notifications. • SMS. • Email. • Image processing. • Video processing. • Payment processing integration. • Reminder jobs. • Escalation. • Data aggregation. ________________________________________ 98. FILE STORAGE Use: • S3-compatible storage. Store only metadata in PostgreSQL. Metadata: • File ID. • Name. • Type. • Size. • Storage path. • Upload user. • Campaign. • Phase. • Task. • Question. • Timestamp. Use signed URLs for private files. ________________________________________ 99. MOBILE PERFORMANCE Optimize for: • Low-end Android devices. • Slow networks. • Limited storage. • Intermittent connectivity. Avoid unnecessary animations. Keep forms lightweight. Compress images. Use resumable uploads where practical. ________________________________________ 100. ACCESSIBILITY Support: • High contrast. • Large touch targets. • Keyboard navigation. • Screen readers. • Proper labels. • Accessible validation messages. ________________________________________ 101. USER INTERFACE Admin desktop: Sidebar → Dashboard → Campaigns → Phases → Workforce → Teams → Geography → Targets → Forms → Tasks → Verification → Payments → Reports → Maps → Notifications → Audit Logs → Settings Field mobile: Home My Campaigns My Tasks Corrections Notifications Payment Guidelines Profile ________________________________________ 102. DESIGN STYLE Use a professional government administration design. Primary: Navy/blue. Secondary: White/gray. Use: • Tables. • Cards. • Status badges. • Charts. • Maps. • Progress bars. Avoid excessive decorative UI. Prioritize usability. ________________________________________ 103. BULK OPERATIONS Admin must be able to: • Import employees. • Import geography. • Import target entities. • Assign teams in bulk. • Reassign tasks in bulk. • Activate reserve employees in bulk. • Generate reports in bulk. Always show confirmation before large operations. ________________________________________ 104. BULK OPERATION SAFETY For every bulk action: 1. Preview. 2. Validate. 3. Show number of affected records. 4. Confirm. 5. Execute. 6. Show result. 7. Provide error report. 8. Record audit event. ________________________________________ 105. SEARCH Global search across authorized data: • Campaign. • Employee. • Team. • Household. • Institution. • Task. • Submission. • Geographic area. ________________________________________ 106. DUPLICATE DETECTION Detect: • Duplicate employee. • Duplicate target. • Duplicate household. • Duplicate task. • Duplicate assignment. • Duplicate payment. Do not automatically delete records. Flag them for review. ________________________________________ 107. NOTIFICATION PREFERENCES Allow users to configure permitted notification preferences. However, mandatory government alerts cannot be disabled if configured as mandatory. ________________________________________ 108. API ARCHITECTURE Use a clean REST API or equivalent. Organize APIs by module: /auth /users /employees /departments /geography /campaigns /phases /teams /targets /tasks /forms /submissions /verifications /exceptions /payments /notifications /reports /audit /files ________________________________________ 109. API DOCUMENTATION Generate: OpenAPI / Swagger Document: • Authentication. • Request. • Response. • Errors. • Permissions. ________________________________________ 110. ERROR HANDLING Use consistent API responses. Example: { "success": false, "error": { "code": "VALIDATION_ERROR", "message": "Required fields are missing." } } Never expose: • Database errors. • Stack traces. • Secrets. • Internal infrastructure details. ________________________________________ 111. FRONTEND STATE Use an appropriate state-management/data-fetching strategy. Use: • Server-side fetching where appropriate. • Query caching. • Optimistic updates only when safe. • Offline state. ________________________________________ 112. OFFLINE DATA SECURITY Do not store unnecessary sensitive personal data permanently on the device. Encrypt/local-protect sensitive offline storage where practical. Provide device/session expiration. ________________________________________ 113. SESSION SECURITY Support: • Session timeout. • Device/session management. • Logout all devices where authorized. • Token revocation. • Suspicious login detection. ________________________________________ 114. OTP SECURITY OTP: • Expiration. • Rate limiting. • Attempt limit. • Resend cooldown. • Secure storage. • Audit logging. Never store OTP in plain text longer than necessary. ________________________________________ 115. LOGIN Support: Mobile Number → OTP for initial verification → Password creation Then: Mobile Number → Password → Dashboard Forgot password: Mobile → OTP → New Password ________________________________________ 116. GOVERNMENT INTEGRATIONS Build integration interfaces rather than hard-code external systems. Possible future integrations: • SMS gateway. • Government employee master database. • Official GIS. • Payment/treasury system. • Identity/authentication system. • Email. • Notification gateway. Use adapters/interfaces so providers can be changed. ________________________________________ 117. NO FAKE INTEGRATIONS If a real government API is not available: Use a clearly marked development/mock adapter. Do not pretend that a fake integration is real. ________________________________________ 118. PAYMENT INTEGRATION Payment processing should initially support: Manual/administrative status and be architected for future integration with an authorized government payment/treasury system. Do not invent a government payment API. ________________________________________ 119. IMPORT/EXPORT SECURITY Exports must respect authorization. Do not allow field officers to export all district data. Sensitive exports should require additional authorization where appropriate. Log every export. ________________________________________ 120. DATA QUALITY DASHBOARD Show: • Missing data. • Invalid data. • Duplicate data. • GPS exceptions. • Correction rates. • Rejection rates. • Unusual activity. ________________________________________ 121. PRODUCTIVITY METRICS Show: • Tasks completed per day. • Average task duration. • Completion rate. • Correction rate. • Approval rate. • Overdue rate. Do not use productivity metrics as automatic disciplinary conclusions. ________________________________________ 122. CAMPAIGN TEMPLATES Allow administrators to save: Campaign Template Example: School Inspection Template. When creating a new campaign: Use Template Then modify: • Form. • Departments. • Geography. • Workforce. • Dates. • Payment. ________________________________________ 123. FORM TEMPLATE LIBRARY Allow reusable forms. Examples: • Inspection form. • Survey form. • Household form. • Verification form. Forms must remain versioned. ________________________________________ 124. WORKFLOW TEMPLATE Allow reusable workflows. Example: Field Officer → Supervisor → Department Head → District Admin. Save as: Standard Inspection Workflow. ________________________________________ 125. PAYMENT TEMPLATE Allow authorized users to reuse payment structures. Example: Field Duty Payment Template. But each campaign/phase must reference the exact applicable rule/version. ________________________________________ 126. CAMPAIGN PAUSE Admin can pause a campaign. When paused: • No new tasks can start. • Existing drafts remain safe. • Admin can resume later. Clearly display: Campaign Paused. ________________________________________ 127. CAMPAIGN EXTENSION Authorized admin can extend deadline. Require: • New date. • Reason. • Approval if configured. Record audit history. ________________________________________ 128. TASK REASSIGNMENT Allow: Employee A → Employee B Reason: Employee unavailable. Maintain full history. ________________________________________ 129. TEAM CHANGE Allow adding/removing team members during campaign with authorization. Do not rewrite old historical assignments. ________________________________________ 130. TARGET REASSIGNMENT If a household/institution is reassigned: Maintain: Old Team → New Team Reason Date Authorized By ________________________________________ 131. FINALIZATION When a phase is finalized: • Prevent normal editing. • Allow authorized correction workflow only. • Lock official result. • Preserve historical versions. ________________________________________ 132. CAMPAIGN CLOSURE When campaign is completed: • Lock operational changes. • Finalize reports. • Finalize payment eligibility. • Preserve audit logs. • Archive according to retention policy. ________________________________________ 133. REAL-LIFE CENSUS 2027 DEMO Create development demo: Campaign: Census 2027 District: Demo District Departments: • Revenue. • Education. • Municipal Administration. • Panchayat. Create sample: • 2 subdivisions. • 4 tehsils. • 3 municipalities. • 10 villages. • 20 wards. • 50 mohallas. • 500 households. • 100 employees. • 20 teams. • 5 reserve teams. Create: Phase 1: House Listing Phase 2: Enumeration Phase 3: Verification Use sample placeholder questions. Clearly label: DEMO DATA — NOT OFFICIAL CENSUS DATA ________________________________________ 134. END-TO-END DEMO Demonstrate: District Admin → Creates Census campaign → Creates Phase 1 → Selects departments → Imports employees → Creates joint teams → Assigns geography → Loads target households → Creates Phase 1 form → Configures verification → Configures payment rule → Launches phase Field Team → Logs in → Views households → Opens household → Completes form → Captures GPS → Saves draft → Submits Reviewer → Reviews → Requests correction Field Team → Corrects → Resubmits Reviewer → Approves System → Generates final result → Generates payment eligibility → Shows payment status District Admin → Views dashboard → Drills down to household → Views map → Generates Excel/PDF → Views audit history. ________________________________________ 135. TESTING Create: Unit Tests For: • Assignment. • Permissions. • Form validation. • GPS. • Payment calculation. • Workflow. Integration Tests For: • Authentication. • Campaign. • Teams. • Forms. • Submission. • Verification. • Payment. E2E Tests Test complete campaign lifecycle. ________________________________________ 136. LOAD TESTING Test realistic loads. At minimum test: • 50,000 employees. • Large task volumes. • Large submission volumes. • Concurrent mobile users. • Large report generation. • Large file uploads. Identify bottlenecks. ________________________________________ 137. DATABASE INDEXING Create indexes for frequently queried: • Employee ID. • Mobile. • Campaign ID. • Phase ID. • Team ID. • Geographic ID. • Target ID. • Task status. • Submission status. • Payment status. • Created date. Review query plans for large tables. ________________________________________ 138. ARCHITECTURE Preferred stack: Frontend Next.js React TypeScript Tailwind CSS shadcn/ui PWA IndexedDB Backend NestJS TypeScript Database PostgreSQL Prisma Cache / Queue Redis BullMQ Storage S3-compatible storage Maps Provider abstraction supporting: OpenStreetMap / Mapbox / Google Maps ________________________________________ 139. PROJECT STRUCTURE Use a clean modular architecture. Example: /apps /web /api /packages /ui /types /config /validation /infrastructure /docs /tests Keep business logic separate from UI. ________________________________________ 140. ENVIRONMENT VARIABLES Create: .env.example Include: DATABASE_URL REDIS_URL JWT_SECRET S3_ENDPOINT S3_ACCESS_KEY S3_SECRET_KEY S3_BUCKET SMS_PROVIDER SMS_API_KEY SMS_SENDER_ID EMAIL_PROVIDER EMAIL_API_KEY MAP_PROVIDER MAP_API_KEY Never commit real secrets. ________________________________________ 141. DOCKER Provide: Dockerfile docker-compose.yml Services: • Web. • API. • PostgreSQL. • Redis. • Object storage for local development. ________________________________________ 142. DEVELOPMENT README Provide complete instructions: 1. Install dependencies. 2. Configure .env. 3. Start PostgreSQL. 4. Start Redis. 5. Run migrations. 6. Seed database. 7. Start backend. 8. Start frontend. 9. Login using demo credentials. 10. Run tests. ________________________________________ 143. SEED DATA Create realistic but clearly fake development data. Include: • Admin. • Department Heads. • Supervisors. • Field Officers. • Reserve employees. • Departments. • Geographic hierarchy. • Teams. • Households. • Campaigns. • Phases. • Forms. • Tasks. Never use real personal information. ________________________________________ 144. DEMO CREDENTIALS Provide development-only demo accounts. Example: District Admin Department Head Supervisor Field Officer Payment Officer Clearly mark: DEVELOPMENT ONLY Do not use these credentials in production. ________________________________________ 145. IMPORTANT GOVERNMENT DATA RULE Do not invent: • Official Census questions. • Government payment amounts. • Government orders. • Government employee records. • Official geographic datasets. • Government APIs. • Official Census procedures. Where official information is unavailable, create: CONFIGURABLE PLACEHOLDERS and clearly label them. ________________________________________ 146. IMPORTANT DESIGN RULE Do not create separate applications for: • Census. • School inspection. • Road survey. • Flood survey. Instead create one: District Campaign Platform Then: Campaign Type: Census Campaign: Census 2027 Phase: House Listing This makes the platform reusable. ________________________________________ 147. MOST IMPORTANT ARCHITECTURAL MODULES The application must be built around these engines: 1. Campaign Engine Campaigns and phases. 2. Organization Engine Departments and hierarchy. 3. Geography Engine District/tehsil/village/ward/mohalla. 4. Workforce Engine Employees and availability. 5. Team Engine Joint teams and reserve teams. 6. Target Entity Engine Households, schools, roads, etc. 7. Assignment Engine Assign targets to teams/employees. 8. Form Engine Dynamic forms and versions. 9. Field Data Engine Mobile data collection. 10. Offline Sync Engine Mobile offline operation. 11. Verification Engine Review and approval. 12. Exception Engine Data quality and operational exceptions. 13. Payment Engine Configurable government-guideline-based payment. 14. Notification Engine SMS/email/push/in-app. 15. Reporting Engine Dashboards and reports. 16. Audit Engine Complete history. ________________________________________ 148. DEVELOPMENT ORDER Do not attempt to create the entire application as disconnected pages. Build in this order: Phase A — Foundation • Architecture. • Database. • Authentication. • RBAC. • Organization. • Geography. Phase B — Campaign • Campaign. • Phase. • Department. • Workforce. • Team. Phase C — Target & Assignment • Target entities. • Household. • Geographic assignment. • Task engine. • Workload. Phase D — Forms • Form builder. • Dynamic questions. • Conditions. • Repeating groups. • Validation. • Versioning. Phase E — Mobile • Field officer UI. • Offline. • GPS. • Image. • Video. • Sync. Phase F — Workflow • Verification. • Correction. • Resubmission. • Approval. • Exceptions. Phase G — Payment • Payment rules. • Eligibility. • Approval. • Status. • Reminders. • Exceptions. Phase H — Intelligence • Dashboards. • Maps. • Analytics. • Reports. • Exports. Phase I — Production • Security. • Testing. • Load testing. • Monitoring. • Backups. • Disaster recovery. • Docker. • Documentation. ________________________________________ 149. FINAL ACCEPTANCE CRITERIA The project is considered complete only when a real end-to-end flow works: District Admin → creates campaign → creates multiple phases → selects departments → imports workforce → creates joint teams → creates reserve teams → assigns geography → loads target entities → creates phase-specific dynamic form → creates verification workflow → configures authorized payment rule → launches campaign ↓ Field Team → logs in on mobile → receives assigned area → sees assigned targets → visits target → fills form → captures GPS where required → captures media where required → works offline if necessary → synchronizes → submits ↓ Reviewer → receives submission → verifies → requests correction ↓ Field Team → corrects → resubmits ↓ Reviewer → approves ↓ System → finalizes result → calculates authorized payment eligibility → tracks payment → sends notifications ↓ District Admin → sees real-time progress → drills down geographically → views maps → views department/team/employee performance → views exceptions → views payment status → generates reports → exports authorized data → reviews audit history. ________________________________________ 150. FINAL INSTRUCTION TO THE AI DEVELOPER Do not build a toy project. Do not build only frontend screens. Do not use hard-coded arrays for core business data. Do not make fake buttons. Do not create disconnected demo pages. Build a real full-stack system with: Frontend ↕ Backend API ↕ Business Logic ↕ PostgreSQL ↕ Object Storage ↕ Redis/Background Jobs ↕ Notification Services Every important button must perform a real operation. Every important record must be persisted. Every permission must be enforced on the backend. Every official submission must be versioned. Every important change must be audited. Every large operation must be designed for scale. Every mobile workflow must consider poor connectivity. Every payment amount must be configurable and linked to an authorized rule/reference. Every campaign must be configurable. Every phase must be independently configurable. Every form must be dynamically configurable. Every organization/geographic hierarchy must be configurable. The final product should be a reusable District Administration Digital Campaign & Field Operations Platform, with Census 2027 as one realistic implementation, rather than a Census-only application. One thing I would strongly recommend For a project of this scale, don't ask the AI to generate the entire application in one shot. Give it the master prompt above, then make it work module-by-module, starting with the database and architecture. The most important foundation is: Organization → Geography → Workforce → Campaign → Phase → Team → Target → Task → Form → Submission → Verification → Result → Payment If that data model is correct, the rest of the application can evolve without needing to rebuild it later

Change the attire

I want to change the attire of this image to something with good clothes and should change the background to some famous places

Life solution

I want you to act the the best brave thinker in the world while looking for solution to each world current problem on earth.make it easy to assimilate with the best solution in a way to make money online procedure to take how to reach out to people which app will the people that need the solution be how to approach them even if there is need to create appp teach me am ready to learn

Vechicle Spareparts In sri lanka

give me a marketing video for spare parts slaes company

Documentation

create me a proper documentation of this whole website that i have created in such a way that if s new person comes at my place so he/she can be able to understand what is happeing here and be able to use it efficiently

Campus life

I want you to act like the best AI video editor in the world while am working on campus life add a water map write up that says @campus life let the dialogue be very funny

game

i wanna make an indie game to be able to sell on steam. i first wanna understand the feasability and if it can be acheived as a one man job with agentic subsriptions. I also dont have a game idea yet so i wanna give this as a prompt

propfirm strategy

i want to create the best strategy which will take only winning trades and as many as possible in a day in propfirm challenges using ctrader which i will connect using mcp server of ctrader backtest it with the data available in the ctrader and create a strategy in c#

Crypto Whitepaper Writer

--- name: crypto-whitepaper-writer description: Write a credible, well-structured whitepaper for any crypto/blockchain project (L1 chain, DeFi protocol, oracle network, stablecoin, token system) — grounded in the structural and rhetorical patterns of Bitcoin, Ethereum, Uniswap, Chainlink, and MakerDAO, not generic ICO-hype templates. Use whenever asked to draft, outline, or review a crypto/Web3 whitepaper. --- # Crypto Whitepaper Writer ## Why this skill exists Most AI-generated crypto whitepapers read like marketing decks: vague "revolutionary" language, unbacked security claims, a roadmap standing in for proof, tokenomics as decoration. The five most-cited whitepapers in the industry — Bitcoin, Ethereum, Uniswap, Chainlink, MakerDAO — share a different discipline instead: problem-first framing, incremental mechanism-building, named threat models, and per-actor incentive analysis. This skill encodes that discipline so the output reads like engineering, not a pitch. See `reference.md` for the full research base: archetype skeletons, craft principles, anti-patterns, and the pre-publish checklist. Read it before drafting. ## Step 1 — Gather inputs before writing a word Do not start drafting until you have, from the user: - **The problem** this project solves, in one sentence, with a concrete scenario of what fails without it. - **The project archetype** — the closest match in `reference.md` → Archetypes: base-layer consensus/settlement, DeFi mechanism (AMM/lending/derivatives), oracle/coordination network, stablecoin/collateral system, or application-layer protocol/token system. - **The core mechanism** — what actually happens on-chain/off-chain, in enough detail to describe a state transition or formula, not just a feature list. - **Token existence and role** — if a token exists, what specific mechanical function does it serve (fee payment, collateral, staking/slashing, governance weight)? If the project doesn't need a token, say so explicitly rather than inventing tokenomics to look complete. - **Known limitations / open risks** the team is willing to state honestly. If any of these is missing or vague, ask before drafting — never fabricate a problem statement, team background, adoption numbers, or token model to fill a gap. ## Step 2 — Pick the section skeleton, calibrate length Match the archetype to its skeleton in `reference.md`. Don't force every whitepaper through an identical template — Bitcoin has no tokenomics section; MakerDAO has no proof-of-work security proof. Use the shared spine (problem → mechanism → actor/incentive analysis → threat/risk model → architecture → [governance/token, only if applicable] → limitations → conclusion), and cut whatever doesn't apply to this project. Length follows mechanism complexity, not a fixed page count — Bitcoin proves its point in 9 pages; MakerDAO needs far more because it coordinates more actors and failure modes. Let each section run as long as the idea needs and no longer (anti-pattern: forced symmetry). If the project has a token or makes any financial/return-implying claim, include a short disclaimer (Uniswap's precedent) stating the document is not investment advice. ## Step 3 — Draft section by section, applying the craft principles Work through `reference.md`'s craft principles as each section gets written. The ones that matter most in practice: - Open with a failure scenario, not a mission statement. - Build the mechanism from a minimal model upward — don't state the final design cold. - Every security or performance claim gets a number, threshold, or named proof — never an adjective alone ("highly secure" is not a claim). - Every incentive-driven actor (miner, LP, oracle node, keeper, validator) gets its own paragraph naming exactly what they earn and what punishes defection. - Name specific attack vectors and pair each with its specific countermeasure. - Include at least one worked, traceable example — a transaction walkthrough, a numeric calculation, a step-by-step lifecycle. - If this design revises or extends a known predecessor, write it as an explicit delta (what changed and why), not a from-scratch re-explanation. ## Step 4 — Run the anti-pattern filter before showing a draft Scan against `reference.md`'s anti-pattern list. Any hit is a reason to rewrite the line, not soften it: price predictions or market-cap claims, unverifiable team/advisor credentials used as an argument, roadmap phases presented as proof of viability, a tokenomics table with no stated mechanical purpose, novelty claimed without naming what came before, a security claim with no threat model behind it, a missing limitations section, buzzwords substituting for a mechanism description. ## Step 5 — Self-check and disclose gaps Before finalizing: - Confirm every numeric or technical claim traces to something the user provided or a cited external source — flag anything you inferred rather than were told. - Confirm a limitations/risks section exists and isn't hollow. - Run `reference.md`'s pre-publish checklist and state the result (pass/fail per item, or a self-rating) to the user before calling the draft done — don't ship a whitepaper without surfacing what's unresolved. ## Output format Markdown, sections matching the chosen archetype skeleton, an abstract at the top, references/sources at the bottom if external material was used. No emoji, no bolded label scaffolding (`Problem:`, `Solution:`), no forced symmetry between sections — a simple idea gets a short section, a hard one gets a long one, exactly as the five reference papers do. Cite every external claim (a cryptographic primitive, a competitor's known limitation, a market fact) inline with a bracketed marker (e.g. `[1]`) resolving to a numbered reference list at the end — never assert an outside fact with no traceable source. See `reference.md` → Calibration examples for what a compliant vs. non-compliant sentence looks like before you draft the real thing.

technical-whitepaper-writer

# Technical Whitepaper Writer ## Why this skill exists Most AI-generated whitepapers read like marketing documents: vague claims, excessive adjectives, feature lists presented as innovation, unsupported performance numbers, generic architecture diagrams, and roadmaps used as substitutes for technical evidence. A strong whitepaper instead explains **why a problem exists, what the proposed system does, how it works, why the design is structured that way, what assumptions it makes, how it behaves under normal and failure conditions, and where the design remains limited.** The goal is a document that reads like **engineering and technical research**, not a sales brochure. The whitepaper should let a technically capable reader answer: 1. What problem is being solved? 2. Why do existing approaches fail or become insufficient? 3. What is being proposed? 4. How does the proposed system actually work? 5. What are the major components, and how do they interact? 6. What assumptions does the design make? 7. What happens during normal operation? 8. What happens when something goes wrong? 9. What evidence supports the technical claims? 10. What are the limitations and unresolved risks? 11. How is this different from existing approaches? 12. What would someone need to implement, evaluate, or deploy it? Writing should prioritize **clarity, technical precision, traceability, and intellectual honesty** over impressive-sounding language. --- ## Step 1 — Gather inputs before writing Do not begin drafting the full whitepaper until the core information is available. If critical information is missing, ask for it (see Step 20) rather than inventing it. **1. The problem.** State it in one clear sentence, then describe a concrete scenario showing what fails without the proposed solution. - Avoid: *"The industry needs a revolutionary new approach."* - Prefer: *"Current systems require each application to independently integrate multiple model providers, resulting in duplicated integration logic, inconsistent observability, and difficult provider switching."* **2. The project type.** Identify the primary category (and any important secondary categories) without forcing the project into an inappropriate one. Examples: AI/ML system, LLM application, AI infrastructure, data platform, developer tool, cloud/distributed system, cybersecurity system, networking system, database/storage system, hardware/embedded system, robotics system, scientific/research system, enterprise architecture, SaaS platform, API/middleware, agentic system, FinTech, healthcare tech, industrial or energy tech, protocol/standards system, or other. **3. The core mechanism.** Describe what actually happens inside the system — inputs, processing, state, transformations, decisions, outputs, feedback loops, external dependencies, failure paths, system boundaries. Not a feature list. - Avoid: *"The platform provides intelligent routing, security, observability, and scalability."* - Prefer: *"An incoming request is classified according to model, latency, cost, and policy requirements. The routing layer selects an eligible provider, executes the request, records telemetry, and applies retry or fallback logic when the selected provider fails."* **4. System boundaries.** What's inside the system vs. external? Which components are controlled vs. dependencies? Where does data enter and leave? Where does trust begin and end? **5. Actors and stakeholders.** Only include actors relevant to the system (e.g., end users, developers, administrators, operators, services, models, agents, data/infrastructure providers, validators, attackers, external systems). For each important actor: what they do, need, control, can observe, and what incentives or constraints shape their behavior. **6. Resources, economics, or tokens — only when applicable.** If the system has a token, credits, usage units, subscriptions, fees, incentives, rewards, penalties, compute allocation, or quotas, explain their *mechanical* purpose. Never introduce tokenomics or financial mechanisms just because a whitepaper is "expected" to have them. Omit this section if no economic mechanism exists. **7. Known limitations and risks.** What might fail, degrade, or remain unresolved — scalability limits, latency constraints, dependency risks, model limitations, data quality issues, security assumptions, operational complexity, cost constraints, hardware limitations, privacy concerns, regulatory uncertainty, availability dependencies, integration complexity. State these explicitly; do not hide them. --- ## Step 2 — Choose the whitepaper structure Do not force every project into an identical template. The default technical spine: 1. Abstract 2. Introduction 3. Problem and Motivation 4. Existing Approaches 5. Design Goals and Non-Goals 6. Proposed Architecture 7. Core Mechanism 8. System Workflow 9. Technical Design 10. Security / Safety / Reliability Model 11. Performance and Scalability 12. Implementation Considerations 13. Worked Example 14. Evaluation / Evidence 15. Limitations and Open Problems 16. Future Work 17. Conclusion 18. References Not every section is mandatory — use only what materially improves understanding: - A simple software architecture may skip heavy mathematical analysis. - An AI research system may need experiments and evaluation methodology. - A cybersecurity system may need a detailed threat model. - A hardware system may need physical constraints and benchmarking. - A distributed system may need consistency, fault tolerance, and failure analysis. - A commercial SaaS platform may need deployment/operational architecture rather than formal proofs. --- ## Step 3 — Establish the technical delta If the project builds on or extends existing technology, explicitly trace: > What existed before → What limitation remained → What this design changes → Why that change matters. - Avoid: *"This is the world's first revolutionary architecture."* - Prefer: *"Existing approach A provides X but requires Y. Approach B removes Y but introduces Z. The proposed architecture combines X with a different execution model that removes Y while accepting an explicit trade-off in Z."* --- ## Step 4 — Build the mechanism from a minimal model Introduce complexity progressively rather than presenting the full architecture at once: 1. **Intuition** — the idea in simple language. 2. **Minimal model** — the smallest system that could solve the problem. 3. **Architecture** — the major components. 4. **Data / request flow** — how information moves through the system. 5. **Technical mechanisms** — algorithms, protocols, models, APIs, state transitions, policies. 6. **Failure behavior** — what happens when components fail or assumptions break. 7. **Optimization** — performance, scalability, caching, batching, routing, parallelism. --- ## Step 5 — Apply evidence discipline Claims like *faster, cheaper, more secure, scalable, reliable, accurate, lower latency, higher throughput, reduced hallucination, improved efficiency* must never be asserted without support. Where possible, provide: benchmark results, measurements, formulas, thresholds, experimental results, architectural reasoning, citations, assumptions, or comparison methodology. - Avoid: *"The architecture provides extremely low latency."* - Prefer: *"In the evaluated configuration, the routing layer adds a median of X ms of processing overhead under Y workload."* If a number is unavailable, say so. **Never fabricate measurements.** --- ## Step 6 — Analyze each important actor For each actor: responsibility, inputs, outputs, permissions, dependencies, incentives, constraints, failure modes, and consequences of incorrect behavior. Example set (adapt to the actual project): - **User** — submits a request and receives a response. - **Application** — authenticates the request and invokes the platform API. - **Model Provider** — processes the inference request. - **Gateway** — applies routing, policy, retry, and observability logic. - **Operator** — configures policies and monitors system health. --- ## Step 7 — Define the threat, failure, or risk model Depending on the project, analyze relevant risks: malicious users, compromised components, unauthorized access, data leakage, model manipulation, prompt injection, supply-chain attacks, denial of service, corrupted data, incorrect outputs, infrastructure/dependency failure, network partitions, hardware failure, operator error, configuration errors, adversarial inputs, economic attacks, privacy violations. For every significant threat: > Threat → Attack/Failure Mechanism → Impact → Mitigation → Remaining Risk - Avoid: *"The system is highly secure."* - Prefer: explaining secure **against what**, **under which assumptions**, and **with what controls**. --- ## Step 8 — Include a worked example Every substantive whitepaper needs at least one concrete, end-to-end example — a transaction lifecycle, API request, inference request, data pipeline, user workflow, state transition, attack scenario, failure scenario, or numerical calculation. Include real numbers where useful. Example shape: > 1. Client submits request. > 2. Gateway validates policy. > 3. Router selects provider. > 4. Provider executes inference. > 5. Response passes through validation. > 6. Telemetry is recorded. > 7. Client receives response. --- ## Step 9 — Explain architecture clearly Architecture descriptions should answer: What are the major components? What does each do? How are they connected? What protocols/interfaces link them? Where is state stored? Where does computation happen? Where are decisions made? Where are the security boundaries? Where can failures occur? Use layered structure only where it reflects reality, e.g.: ```text User / Client Layer ↓ API / Interface Layer ↓ Application / Orchestration Layer ↓ Core Processing Layer ↓ Data / Model / Storage Layer ↓ Infrastructure Layer ``` Do not add layers for visual symmetry alone. --- ## Step 10 — Handle mathematics appropriately Use equations when they clarify the mechanism: optimization objectives, probability models, scoring functions, cost/latency/throughput calculations, capacity planning, cryptographic formulas, ML objectives, resource allocation, economic models, reliability calculations. Always explain each equation in plain language. Never add math purely for appearance. --- ## Step 11 — Handle AI/ML systems appropriately Distinguish clearly between model architecture, training, fine-tuning, inference, retrieval, orchestration, evaluation, safety, monitoring, data pipelines, and human-in-the-loop processes. Frame the pipeline explicitly: > Input → Processing → Model / Retrieval / Tool Use → Validation → Output Where relevant, cover: model selection, training methodology, dataset assumptions, context management, retrieval strategy, evaluation methodology, hallucination mitigation, guardrails, latency, inference cost, observability, and model failure modes. Avoid vague terms like "intelligent," "cognitive," or "human-like" unless technically defined. --- ## Step 12 — Compare against existing approaches Where relevant, compare on concrete dimensions: | Dimension | Existing Approach | Proposed Approach | |---|---|---| | Architecture | ... | ... | | Latency | ... | ... | | Scalability | ... | ... | | Cost | ... | ... | | Security | ... | ... | | Flexibility | ... | ... | | Operational Complexity | ... | ... | Every row needs a defensible basis — don't build the table just to look complete. --- ## Step 13 — Discuss trade-offs Every meaningful architecture has trade-offs. Discuss the relevant ones explicitly: performance vs. cost, flexibility vs. complexity, security vs. usability, consistency vs. availability, latency vs. accuracy, centralization vs. decentralization, automation vs. human control, compute vs. memory, precision vs. recall, privacy vs. observability. Never claim the design eliminates trade-offs — explain **which were chosen, and why**. --- ## Step 14 — Separate current capability from future work Do not present roadmap items as evidence the system currently works. Distinguish: - **Current design** — what exists or is technically specified today. - **Experimental / validated** — what has been implemented and tested. - **Proposed extensions** — what could be built later. - **Open research problems** — what remains unresolved. A roadmap is not proof of technical viability. --- ## Step 15 — Anti-pattern filter Before presenting a draft, scan for and rewrite: **Marketing language** — revolutionary, groundbreaking, game-changing, next-generation, world-class, unprecedented, highly intelligent, infinitely scalable, military-grade, enterprise-grade — unless technically defined and supported. **Unsupported claims** — "10x faster," "99.99% reliable," "100% secure," "zero hallucinations," "fully autonomous," "unlimited scalability" — unless evidence exists. **Feature dumping** — a list of features is not an architecture. **Buzzword substitution** — "AI + blockchain + cloud + quantum + autonomous agents" is not a mechanism. **Roadmap-as-proof** — future plans don't demonstrate present viability. **Tokenomics without purpose** — don't invent economic mechanisms. **Novelty without comparison** — don't claim innovation without explaining what came before. **Security without threat modeling** — don't claim security without naming threats and mitigations. **Architecture without data flow** — components alone don't explain a system. **Missing limitations** — every serious design has them; state them. --- ## Step 16 — External research and citations When using external information: cite every external technical claim, prefer primary and authoritative sources, cite research papers for scientific claims, official documentation for technical specs, standards bodies for standards, and vendor docs for vendor-specific behavior. Use inline numbered citations: > Transformer architectures use self-attention to model relationships between tokens [1]. ```markdown ## References [1] Vaswani et al., "Attention Is All You Need," 2017. ``` **Never fabricate references. Never cite a source that doesn't actually support the statement.** --- ## Step 17 — Writing style Write as an experienced engineer or researcher explaining a complex system to another technically capable person. **Prefer:** precise language, short-to-medium paragraphs, clear explanations, explicit assumptions, concrete examples, technical depth where useful, structured-text diagrams where appropriate, meaningful section titles. **Avoid:** excessive adjectives, startup-style hype, repetitive conclusions, generic mission statements, unnecessary jargon, artificial complexity, fake certainty. The tone: *"Here is the problem. Here is why existing approaches struggle. Here is the mechanism we propose. Here is how it works. Here is the evidence. Here is where it can fail."* Not: *"We are revolutionizing the future of technology."* --- ## Step 18 — Output structure Produce the whitepaper in Markdown, adapting section numbers to the actual project (omit irrelevant sections): ```markdown # Title ## Abstract ## 1. Introduction ## 2. Problem and Motivation ## 3. Existing Approaches ## 4. Design Goals and Non-Goals ## 5. Proposed Architecture ## 6. Core Mechanism ## 7. System Workflow ## 8. Technical Design ## 9. Security, Safety, and Reliability ## 10. Performance and Scalability ## 11. Worked Example ## 12. Evaluation ## 13. Limitations and Open Problems ## 14. Future Work ## 15. Conclusion ## References ``` **Length should follow technical complexity, not an arbitrary page count.** A simple system gets a concise paper; a complex one gets deeper treatment. --- ## Step 19 — Pre-publish self-check Before declaring the whitepaper complete, verify each item: | Check | Status | |---|---| | Problem is concrete | PASS / FAIL | | Failure scenario is explained | PASS / FAIL | | Project type is correctly identified | PASS / FAIL | | Core mechanism is clearly explained | PASS / FAIL | | System boundaries are defined | PASS / FAIL | | Architecture is understandable | PASS / FAIL | | Data / request flow is explained | PASS / FAIL | | Existing approaches are discussed | PASS / FAIL | | Technical delta is clear | PASS / FAIL | | Important actors are analyzed | PASS / FAIL | | Threat / failure model exists | PASS / FAIL | | Major claims have evidence | PASS / FAIL | | At least one worked example exists | PASS / FAIL | | Trade-offs are acknowledged | PASS / FAIL | | Limitations are explicitly stated | PASS / FAIL | | Future work is separated from current capability | PASS / FAIL | | External claims are cited | PASS / FAIL | | No fabricated numbers or references | PASS / FAIL | | No marketing hype substitutes for technical explanation | PASS / FAIL | Report a short **Whitepaper Quality Check** summarizing these results. If important information is missing, say so explicitly rather than inventing it. --- ## Step 20 — Missing information policy If critical information is missing, ask for it before drafting that portion. **Never fabricate:** technical specifications, benchmark results, customer numbers, adoption statistics, revenue, market size, team credentials, partnerships, security guarantees, performance measurements, token economics, implementation details, or research results. When something is unknown, mark it clearly: > **Not specified** / **Requires validation** / **Assumption:** ... Never silently convert an assumption into a stated fact. --- ## Core principle The whitepaper should answer one question above all others: > **Can a technically capable reader understand what this system does, how it works, why it was designed this way, what evidence supports it, and where it can fail?** If yes, the whitepaper is doing its job.

Photorealistic Alpine Village

Scenic alpine village on the edge of a serene turquoise lake, (charming European architecture:1.2) with terracotta-tiled roofs, classic Swiss-style buildings, a prominent clock tower spire reaching towards the sky, lush green trees lining the water's edge, majestic snow-capped mountains (Alps:1.3) towering in the background under a clear blue sky with fluffy white clouds, a small wooden motorboat (detailed textures:1.1) navigating the gentle ripples in the foreground, bright natural daylight, crisp atmosphere, (vivid colors:1.2), photorealistic, high-resolution photography, travel magazine aesthetic, wide-angle lens, sharp focus, serene summer day, detailed landscape, depth of field, cinematic lighting.

The Red Headscarf

(Portrait of a beautiful young woman:1.3), (Middle Eastern ethnicity:1.2), (age 20:1.1), (intricate facial features:1.3), (soft natural expression:1.2), wearing a (vibrant red headscarf:1.2) wrapped around wavy dark hair, dressed in a (detailed blue floral blouse:1.2) over a (yellow textured top:1.1), adorned with (ornate turquoise beaded necklace:1.2), (large vintage drop earrings:1.1), and gold bangles. The subject is positioned slightly to the left, (facing the viewer:1.2), resting her arms on a surface. Background features a (distressed turquoise wall:1.2), a (large rustic ceramic vase:1.1) containing yellow wildflowers, and a small painted bowl. (Fine art oil painting style:1.3), rich color palette of teal, gold, and crimson, (soft cinematic lighting:1.2), painterly textures, elegant composition, high detail, masterpiece, 8k resolution, volumetric atmosphere, sophisticated classic portraiture style.

Pharmacy chronic patient crm

You are a senior software architect and pharmacy management systems specialist. Design and build a private pharmacy CRM for my pharmacy in Mosul, Iraq. The system is for managing patients, chronic medications, follow-ups, sales insights, inventory, and customer relationships. Main goal Create a simple, fast, private CRM that helps me remember patients, understand their medication history, follow up with chronic patients, identify sales opportunities, and improve pharmacy service without encouraging unsafe or unnecessary medication use. Users The system will initially have one administrator user. The pharmacist must control access to patient information. Patient data must not be publicly accessible. Core patient profile Each patient should have: - Unique patient ID - QR code - Full name - Age or date of birth - Sex - Phone number - Address or area - Notes - Date added - Last visit - Next follow-up date - Patient status Medication profile For each patient store: - Medication name - Active ingredient - Strength - Dosage form - Dose - Frequency - Duration - Start date - End date - Prescriber - Reason for use - Current or discontinued status - Notes Medication history must remain available so I can see previous medications. Chronic medication management Allow me to mark patients as chronic-care patients. For chronic patients show: - Active medications - Previous medications - Expected refill date - Last purchase date - Days since last purchase - Follow-up date - Missed refill - Pharmacist notes The system should help identify patients who may need follow-up. Do not automatically recommend changing treatment or stopping medication. Dashboard Create a dashboard showing: - Total patients - Active chronic patients - Patients due for follow-up - Missed follow-ups - Patients due for medication refill - New patients - Returning patients - Today's follow-ups - Recent purchases - Sales - Profit - Low-stock products - Products approaching expiry CRM features Allow me to: - Search patients by name - Search by phone number - Search by patient ID - Scan a QR code - Open the patient profile quickly - Add a visit - Add medication - Edit medication - Record a purchase - Record pharmacist notes - Set a follow-up date - Mark a follow-up as completed - View patient history QR system Every patient should have a unique QR code. Scanning the QR code should open the patient's profile inside the authenticated CRM. The QR code must not expose sensitive patient information directly. Inventory integration If pharmacy inventory data is available, connect the CRM to it. Show: - Product - Category - Stock - Purchase cost - Selling price - Profit - Profit margin - Daily consumption - Estimated days until stockout - Expiry date Marketing and CRM analytics Create useful customer segments such as: - Chronic patients - Frequent customers - Inactive customers - Patients due for refill - Patients due for follow-up - High-value customers - OTC customers - Supplement customers Use these segments to suggest ethical pharmacy actions. Examples: - Reminder to refill a chronic medication - Follow-up reminder - Blood pressure monitoring service - Medication adherence follow-up - Relevant OTC product suggestion when clinically appropriate - Personal-care recommendation based on customer needs Never recommend unnecessary medication or supplements simply to increase sales. Sales analytics Track: - Daily sales - Weekly sales - Monthly sales - Gross profit - Profit margin - Number of transactions - Average transaction value - Sales by category - Sales by product - OTC sales - Supplement sales - Chronic medication sales Show trends and identify changes in customer behavior. Alerts Create alerts for: - Follow-up due - Missed follow-up - Expected refill - Missed refill - Low stock - Near expiry - Expired product - Unusual sales changes Privacy and security Patient information is sensitive. Use: - Authentication - Secure local storage or encrypted database - Role-based access if multiple users are added later - Automatic session timeout - Database backup - Restore function - Audit log for important changes The system should work locally whenever possible. Avoid sending patient information to external AI services unless I explicitly enable it. Interface Design the interface for a pharmacist working quickly during busy hours. Prioritize: - Fast search - Few clicks - Large buttons - Clear patient timeline - Simple forms - Mobile-friendly interface - Arabic and English support - Iraqi pharmacy terminology where appropriate Main screens Create: 1. Dashboard 2. Patients 3. Patient profile 4. Medication history 5. Visits 6. Follow-ups 7. Inventory 8. Sales analytics 9. Alerts 10. Reports 11. Settings 12. Backup and restore Patient timeline Every patient should have a chronological timeline containing: - Registration - Visits - Medication additions - Medication changes - Purchases - Follow-ups - Notes Analytics The CRM should generate actionable insights rather than only displaying numbers. For example: "23 chronic patients are expected to refill within 7 days." "11 patients have not returned within their expected refill period." "OTC sales increased 14% this month." "Category X has high sales but low profit margin." "17 products may expire before expected stock depletion." Explain why each insight matters and what action I should consider. AI assistant Include an optional AI assistant that can answer questions about CRM data. Examples: - Which chronic patients are due for refill this week? - Which patients have missed their expected refill? - What are my top 20 profitable products? - Which categories have high sales but low margins? - Which products are at risk of expiry? - Which days have the highest sales? - What changed compared with last month? - Which patients need follow-up today? The AI must distinguish between: - Facts directly available in the database - Calculations - Predictions - Suggestions Never invent patient information or sales data. Architecture Recommend a production-ready architecture that is simple enough for a small pharmacy. Prefer a local-first architecture. Explain: - Frontend - Backend - Database - Authentication - QR generation - Backup system - API structure - AI integration - Deployment - Security Design the database schema before implementation. Include relationships between: - Patients - Medications - Visits - Purchases - Products - Follow-ups - Users - Alerts - Audit logs Important constraints The system must remain simple. Do not add features just because they sound impressive. Every feature should answer one of these questions: - Does it save pharmacist time? - Does it improve patient follow-up? - Does it reduce stock problems? - Does it improve business visibility? - Does it improve patient service? - Does it protect patient data? Before writing implementation code: 1. Define the complete requirements. 2. Identify missing requirements. 3. Design the database. 4. Design the user workflow. 5. Design the API. 6. Define the security model. 7. Define the MVP. 8. Then propose the implementation plan. Build the MVP first. Do not overengineer the system.

Agent

--- name: my-skill-name description: A clear description of what this skill does and when to use it --- # My Skill Describe what this skill does and how the agent should use it. ## Instructions - Step 1: ... - Step 2: ...