Skip to content

A Claude Code / Codex plugin that helps you learn how to build while AI writes the code.

Python

test: add repeatable notes-app demo scenarios

Noah Kimaf46896c1dbd
diff --git a/docs/demos/notion-dupe.md b/docs/demos/notion-dupe.md
new file mode 100644
index 0000000..fe4c570
--- /dev/null
+++ b/docs/demos/notion-dupe.md
@@ -0,0 +1,188 @@
+# Notion-style notes app demo
+
+Rehearse the learning flow from the playground conversation: define the scope,
+explore folder deletion, propose the data relationships, and discuss sign-in.
+The scenario uses paraphrased learner inputs and synthetic notes. It includes no
+private transcript, credentials, or generated application source.
+
+The original conversation loaded VibeWise 0.1.23 and had an existing starter.
+This demo loads the current checkout and starts clean, so the current card titles
+and wording apply. Expect the same learning opportunities, not identical replies
+or checkpoint ordering. No changes to the plugin's teaching prompts are needed.
+
+## Start a fresh recording
+
+From the VibeWise repository, in a terminal with Claude Code installed and signed in:
+
+```sh
+python3 scripts/notion_demo.py prepare --launch
+```
+
+The helper creates a new temporary project and launches interactive Claude with
+this checkout. It skips user/project/local settings and external MCP configuration
+to keep other installed plugins out of the rehearsal. Managed settings still apply.
+It doesn't reset or modify your existing playground. No dependencies or database
+are installed, and you don't need to run `git init`.
+
+In Claude, enter `/vibe-wise:learn`. Choose **New project**, describe a Notion-style
+notes app, choose **Beginner**, then **Use defaults**. Stack familiarity can wait
+until you choose a stack.
+
+Use these responses when the relevant question comes up. Follow the actual
+conversation; don't paste the whole script or jump past a question you don't
+understand. Claude may need a different follow-up.
+
+| Moment | Learner input | What to look for |
+| :--- | :--- | :--- |
+| Scope | “Sign in, create/read/edit/delete private notes, and organize them in folders.” | Requirements get clarified without choosing a stack. |
+| Folder behavior | “A note can be in several folders. Folders can't contain folders. Deleting a folder should delete its notes.” | A concrete example reveals that a shared note could disappear from another folder too. |
+| Revise the rule | “Keep it in any other folders. If none are left, leave it outside every folder.” | Your revision changes the requirements. Claude leaves the representation for you to propose. |
+| Main flow | “The browser sends the note to our backend, which checks who I am and saves it in a database. Later it loads my notes.” | Feedback examines responsibilities and gaps in your proposal. |
+| Privacy | “Send a session key. The backend checks it, then checks the note's owner against that user. Browser-only checks could be bypassed.” | Reasoning is evaluated before confirming the access design. |
+| Data model | “Use a links table with note_id and folder_id. Deleting a folder removes link rows, not notes.” | Claude evaluates your relationship model instead of supplying it first. |
+| Sign-in | “We should store a hashed password, not the password itself.” | Missing concepts are explained; additional details remain labeled as proposals. |
+| Discuss an addition | Select **Discuss**: “What is a salt, and why does it help?” | The agent explains and keeps implementation paused. |
+| Zoom out | “Can we trace the whole design so far?” | A system diagram distinguishes your choices from open questions. |
+
+Choose **Confirm and continue** only when the displayed design makes sense to you.
+It records the choice; it doesn't authorize implementation. If recording ends
+here, you've shown the reasoning and discussion loop. To continue building, choose
+the remaining technology decisions and approve one concrete scope with
+**Implement this step**. Expect an implementation report afterward. Dependency
+setup, Docker, and app implementation are outside the automated scenes below.
+
+Each `prepare` makes a new project. For another take, exit Claude and run the
+command again. `/vibe-wise:reset` resets learning notes but keeps application
+code, so it isn't a clean-project reset. Run folders remain in the system temp
+directory for inspection; save anything you want to keep before your OS cleans it.
+
+## Rehearse a specific scene
+
+```sh
+python3 scripts/notion_demo.py prepare --scene folders --launch
+python3 scripts/notion_demo.py prepare --scene data-model --launch
+python3 scripts/notion_demo.py prepare --scene sign-in --launch
+```
+
+These start with **synthetic saved decisions** to skip earlier conversation.
+The helper prints the first message to send. When filming a shortcut, describe
+where you're picking up; these fixtures aren't evidence of earlier learner reasoning.
+Omit `--launch` to prepare only and print the launch commands.
+
+## Run conversation checks
+
+These use your signed-in Claude account and consume usage. Each invocation gets
+a `--max-budget-usd` limit (default 1) and a 180-second timeout; multi-turn scenes
+invoke Claude more than once. They use the configured default model and record
+its reported name. Use `--claude /path/to/claude` if it isn't on PATH.
+
+```sh
+python3 scripts/notion_demo.py check --scene fresh
+python3 scripts/notion_demo.py check --scene folders
+python3 scripts/notion_demo.py check --scene data-model
+python3 scripts/notion_demo.py check --scene sign-in
+```
+
+The runner resumes the same session for each learner turn. It exposes file tools
+and the Skill tool, but no shell, network tools, or native question picker. This
+tests the text fallback; use the interactive demo to review pickers and rendering.
+It stops on CLI failures, budget exhaustion, or application files appearing before
+approval. Those mechanical checks do **not** establish that the teaching was good.
+
+Every run prints its artifact directory:
+
+```text
+vibe-wise-notion-<unique>/
+├── project/ Empty project or synthetic .vibe-wise notes
+├── run.json Scene, plugin version, guide hashes, session ID
+├── review.json Human-review criteria for that scene
+├── turn-01.json Learner input, visible response, tools, model, result
+└── conversation.txt Visible conversation across completed turns
+```
+
+Review the conversation and saved notes against `review.json`. Check that no
+future solution appears before a learner attempt and that proposed additions
+haven't become confirmed choices without approval. Future scripted answers and
+review criteria aren't copied into the project or included in the model prompts.
+
+Don't preserve mistakes from the original as expected answers. In particular,
+flag unsupported absolutes about database access or data types, praise without
+evaluation, and claims that one architecture is required merely for learning.
+Avoid exact wording snapshots: a different, sound follow-up should still pass review.
+
+The runner and fixtures live in the repo; generated conversations stay outside it.
+The regular unit tests validate fixture isolation and runner failure handling
+without invoking Claude:
+
+```sh
+python3 -B -m unittest discover -s tests -v
+```
+
+## Initial verification
+
+On 2026-09-30, all four live scenes completed without creating application files
+before approval. These runs preceded the separate Implementation checkpoint label.
+Fresh onboarding asked only the project-situation question. The
+staged reasoning scenes emitted the current Build checkpoint table with padding
+rows, and the data-model scene waited for the learner's links-table proposal.
+
+Human review found differences from the original: the folder scene repeated a
+clarification after the learner revised the deletion rule, and sign-in asked a
+further reasoning question instead of immediately presenting proposed additions.
+The later request for an explanation received one, but this run did not exercise
+a native Discuss picker or the proposed-additions table. Those remain interactive
+review points, not claimed passes. The 42 unit tests validate the tooling and
+existing hook/reset behavior; they do not grade the conversations.
+
+## Example: discussing an unfamiliar detail
+
+This condensed adaptation of the original sign-in discussion shows why **Discuss**
+matters. It illustrates the interaction, not an exact transcript or a required
+password-storage design. The folder example in the [README](../../README.md#what-it-feels-like)
+shows Build, Decision, and Implementation checkpoints together.
+
+```text
+Claude:
+ | ✦ Build checkpoint: Password storage |
+ | :--- |
+ | |
+ | **What would you store so we can check someone's password when they sign in?** |
+ | |
+
+You:
+ A hashed password, not the password itself.
+
+Claude:
+ A hash lets us verify a password without storing the original. Password storage
+ also needs a method designed to make repeated guesses expensive, and a unique
+ salt so equal passwords don't produce equal stored hashes.
+
+ ✦ Decision checkpoint: Password storage
+
+ Your proposal: store a password hash. Details to discuss before confirming:
+
+ | Detail | Proposal | Why it matters |
+ | --- | --- | --- |
+ | Hashing method | Use a password-hashing library with scrypt | Makes each guess expensive |
+ | Salt | Let the library generate a fresh random salt per password | Prevents reuse of precomputed guesses across users |
+
+ ❯ 1. Confirm and continue
+ This approach makes sense to me; move to the next piece.
+ 2. Discuss
+ Ask questions or clarify anything that doesn't make sense before deciding.
+
+You:
+ Discuss. What is a salt?
+
+Claude:
+ Extra random data mixed into the password before hashing. Two people with the
+ same password get different hashes because their salts differ. We store the salt
+ alongside the hash so we can repeat the check at sign-in; it doesn't need to be secret.
+
+ The hashing method and salt handling are still proposals. We haven't confirmed
+ them or started implementing.
+```
+
+An Implementation checkpoint comes when a specific coding step is ready. It can
+confirm the design and authorize that step together; don't add a separate Decision
+checkpoint just to repeat the same approval.
diff --git a/scripts/notion_demo.py b/scripts/notion_demo.py
new file mode 100644
index 0000000..ac09d71
--- /dev/null
+++ b/scripts/notion_demo.py
@@ -0,0 +1,158 @@
+"""Prepare an isolated demo or run opt-in, planning-only Claude conversation checks."""
+
+import argparse
+import hashlib
+import json
+import os
+from pathlib import Path
+import shlex
+import shutil
+import subprocess
+import sys
+import tempfile
+import uuid
+
+
+ROOT = Path(__file__).resolve().parents[1]
+SCENARIO = ROOT / "tests/scenarios/notion-dupe.json"
+FILE_TOOLS = "Read,Glob,Grep,Write,Edit,Skill"
+
+
+def load_scenario():
+ return json.loads(SCENARIO.read_text(encoding="utf-8"))
+
+
+def prepare(scene_name, parent=None):
+ scenario = load_scenario()
+ scene = scenario["scenes"][scene_name]
+ run = Path(tempfile.mkdtemp(prefix="vibe-wise-notion-", dir=parent))
+ project = run / "project"
+ project.mkdir()
+ if scene["files"]:
+ state = project / ".vibe-wise"
+ state.mkdir()
+ (state / "profile.md").write_text(scenario["profile"], encoding="utf-8")
+ for name, content in scene["files"].items():
+ (state / name).write_text(content, encoding="utf-8")
+ # These instructions and future learner answers stay OUTSIDE the demo project.
+ metadata = {
+ "scene": scene_name,
+ "plugin_version": json.loads((ROOT / ".claude-plugin/plugin.json").read_text())["version"],
+ "plugin_root": str(ROOT),
+ "scenario_sha256": hashlib.sha256(SCENARIO.read_bytes()).hexdigest(),
+ "guide_hashes": {
+ str(path.relative_to(ROOT)): hashlib.sha256(path.read_bytes()).hexdigest()
+ for path in sorted((ROOT / "skills/learn").glob("*.md"))
+ },
+ "session_id": str(uuid.uuid4()),
+ }
+ (run / "run.json").write_text(json.dumps(metadata, indent=2) + "\n")
+ (run / "review.json").write_text(json.dumps(scene["review"], indent=2) + "\n")
+ return run, scene, metadata
+
+
+def base_command(claude):
+ return [claude, "--plugin-dir", str(ROOT), "--setting-sources", "",
+ "--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}']
+
+
+def environment():
+ return {**os.environ, "CLAUDE_CODE_AUTO_CONNECT_IDE": "false"}
+
+
+def summarize_output(stdout):
+ """Keep visible responses and tool calls; omit hidden reasoning and init details."""
+ texts, calls, model, result = [], [], None, None
+ for line in stdout.splitlines():
+ row = json.loads(line)
+ if row.get("type") == "system" and row.get("subtype") == "init":
+ model = row.get("model")
+ if row.get("type") == "assistant":
+ for block in row.get("message", {}).get("content", []):
+ if block.get("type") == "text":
+ texts.append(block["text"])
+ elif block.get("type") == "tool_use":
+ calls.append({"name": block["name"], "input": block.get("input", {})})
+ if row.get("type") == "result":
+ result = row.get("subtype")
+ return {"assistant": "\n\n".join(texts), "tools": calls,
+ "model": model, "result": result}
+
+
+def application_files(project):
+ # Planning scenes may only create/update their learning notes.
+ return sorted(str(p.relative_to(project)) for p in project.rglob("*")
+ if p.is_file() and p.relative_to(project).parts[0] != ".vibe-wise")
+
+
+def check(run, scene, metadata, claude, budget, timeout):
+ project = run / "project"
+ transcript = []
+ for number, prompt in enumerate(scene["turns"], 1):
+ print("Turn {}/{}".format(number, len(scene["turns"])), flush=True)
+ command = base_command(claude) + [
+ "--print", "--tools", FILE_TOOLS, "--allowedTools", FILE_TOOLS,
+ "--permission-mode", "dontAsk", "--output-format", "stream-json",
+ "--verbose", "--max-budget-usd", str(budget),
+ "--session-id" if number == 1 else "--resume", metadata["session_id"], prompt,
+ ]
+ completed = subprocess.run(command, cwd=project, env=environment(),
+ capture_output=True, text=True, timeout=timeout)
+ # Save errors locally, even if a failed process didn't produce valid JSON.
+ if completed.stderr:
+ (run / "turn-{:02d}.stderr.txt".format(number)).write_text(completed.stderr)
+ output = summarize_output(completed.stdout)
+ output["user"] = prompt
+ output["exit_code"] = completed.returncode
+ output["application_files"] = application_files(project)
+ (run / "turn-{:02d}.json".format(number)).write_text(
+ json.dumps(output, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ transcript.append("You:\n{}\n\nClaude:\n{}\n".format(prompt, output["assistant"]))
+ (run / "conversation.txt").write_text("\n".join(transcript), encoding="utf-8")
+ print(output["assistant"], flush=True)
+ if completed.returncode or output["result"] != "success" or not output["assistant"]:
+ raise RuntimeError("Claude did not finish successfully; inspect the run artifacts.")
+ if output["application_files"]:
+ raise RuntimeError("Application files appeared before approval: " +
+ ", ".join(output["application_files"]))
+ print("\nMechanical checks passed: completed turns; no application files created.")
+ print("Teaching quality still needs review against review.json and the demo guide.")
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("action", choices=("prepare", "check"))
+ parser.add_argument("--scene", choices=tuple(load_scenario()["scenes"]), default="fresh")
+ parser.add_argument("--launch", action="store_true", help="Open interactive Claude after prepare")
+ parser.add_argument("--claude", default="claude", help="Claude executable name or path")
+ parser.add_argument("--budget", type=float, default=1.0,
+ help="Pass this --max-budget-usd to each check invocation (default: 1)")
+ parser.add_argument("--timeout", type=int, default=180, help="Seconds allowed per check turn")
+ args = parser.parse_args()
+ if args.budget <= 0 or args.timeout <= 0:
+ parser.error("budget and timeout must be positive")
+ if args.action == "check" and args.launch:
+ parser.error("--launch is only for prepare")
+ if (args.action == "check" or args.launch) and not shutil.which(args.claude):
+ parser.error("Claude executable not found; set --claude to its path")
+ run, scene, metadata = prepare(args.scene)
+ print("Run folder: " + str(run), flush=True)
+ print("Project: " + str(run / "project"), flush=True)
+ try:
+ if args.action == "check":
+ check(run, scene, metadata, args.claude, args.budget, args.timeout)
+ else:
+ command = base_command(args.claude)
+ print("\n" + shlex.join(["cd", str(run / "project")]))
+ print(shlex.join(command))
+ print("\nFirst message: " + scene["turns"][0], flush=True)
+ if args.launch:
+ return subprocess.call(command, cwd=run / "project", env=environment())
+ except (OSError, ValueError, RuntimeError, subprocess.TimeoutExpired) as error:
+ print("Check failed: {}\nArtifacts: {}".format(error, run), file=sys.stderr)
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/scenarios/notion-dupe.json b/tests/scenarios/notion-dupe.json
new file mode 100644
index 0000000..581a745
--- /dev/null
+++ b/tests/scenarios/notion-dupe.json
@@ -0,0 +1,67 @@
+{
+ "description": "Notion-style notes app: learner-owned scope, folder behavior, data model, and sign-in.",
+ "profile": "# Learner Profile\n\nLearning mode: active\nOnboarding: complete\n\n## Project\nSituation: New\nBuilding: A Notion-style notes app\n\n## Experience\nOverall programming: Beginner\nStack familiarity: Not specified; no stack chosen\n\n## Goals\nPrimary: Understand the system end to end while building it.\n\n## Preferences\nCheckpoint frequency: Normal\nQuestion style: Open-ended\nImplementation style: AI writes code\n\n## Strong Concepts\nNo demonstrated understanding recorded yet.\n",
+ "scenes": {
+ "fresh": {
+ "description": "Empty project; start real onboarding and perform the walkthrough interactively.",
+ "files": {},
+ "turns": ["/vibe-wise:learn"],
+ "review": [
+ "Onboarding starts with one project-situation question, without choosing a stack or writing application code.",
+ "The live demo uses native pickers. Print-mode testing covers only their text fallback."
+ ]
+ },
+ "folders": {
+ "description": "Clarify the consequences of a note belonging to multiple folders.",
+ "files": {
+ "project-map.md": "# Project Map\n\n## Purpose\nNotion-style notes app. Nothing implemented.\n\n## Requirements\nSign in; create, read, edit, and delete private notes; organize notes in folders.\n\n## Unknowns\nFolder behavior, architecture, data model, authentication, stack, and deployment.\n",
+ "progress.md": "# Learning Progress\n\n## Pending decision\nStage: awaiting requirements clarification\nCheckpoint: Folder behavior\nAsked whether notes can belong to several folders, whether folders nest, and what deleting a folder should do. No data structures have been proposed.\n"
+ },
+ "turns": [
+ "A note can be in several folders, folders cannot contain other folders, and deleting a folder should delete its notes.",
+ "If a note is in other folders, keep it there. Otherwise leave it outside any folder."
+ ],
+ "review": [
+ "Makes the consequence of deleting a shared note concrete, with a small example or diagram, and lets the learner decide.",
+ "Does not claim deletion everywhere is logically impossible; explains why it could surprise a user.",
+ "After the revised rule, records the behavior without supplying the links-table design before a learner attempt.",
+ "Uses a Build checkpoint card with sentence case, a colon, one star, and no emojis."
+ ]
+ },
+ "data-model": {
+ "description": "Ask for the learner's representation, then evaluate their links-table proposal.",
+ "files": {
+ "project-map.md": "# Project Map\n\n## Purpose\nPrivate Notion-style notes app. Nothing implemented.\n\n## Requirements\nNote CRUD; a note can be in multiple folders or none; folders do not nest. Deleting a folder keeps all notes: shared notes remain in other folders, others become unfiled.\n\n## Chosen design\nBrowser -> backend -> database. Backend validates a session key and checks ownership. Users, notes, and folders have IDs; notes and folders record their owner.\n\n## Unknowns\nHow folder membership is represented; stack and deployment. No links structure has been proposed.\n",
+ "progress.md": "# Learning Progress\n\n## Pending decision\nStage: awaiting reasoning\nCheckpoint: Representing folder membership\nRequirements are settled. Invite the learner's data model before supplying one. No implementation approval.\n"
+ },
+ "turns": [
+ "Let's work out how to store which notes are in which folders.",
+ "I'd have a links table with note_id and folder_id. That lets one note be in multiple folders without copies. Deleting a folder removes its link rows, not the notes."
+ ],
+ "review": [
+ "First response invites the learner's structure before revealing a junction table, schema, or completed model diagram.",
+ "Feedback evaluates the proposed relationship and deletion behavior, rather than inventing the learner's rationale.",
+ "Any additional constraints remain explicit proposals or open decisions. Confirmation does not approve unspecified details.",
+ "No application code is written; a ready design can use Confirm and continue / Discuss."
+ ]
+ },
+ "sign-in": {
+ "description": "Explain password-hashing concepts and let the learner discuss proposed additions.",
+ "files": {
+ "project-map.md": "# Project Map\n\n## Purpose\nPrivate Notion-style notes app. Nothing implemented.\n\n## Chosen design\nBrowser -> backend -> relational database. Email/password sign-in with server-side sessions. Users own notes and folders; note_id/folder_id links allow membership in several folders. Deleting a folder removes links and preserves notes.\n\n## Unknowns\nWhat is stored to verify a password, hashing algorithm, session lifecycle, technology choices. No implementation approved.\n",
+ "progress.md": "# Learning Progress\n\n## Pending decision\nStage: awaiting reasoning\nCheckpoint: Password storage\nAsk what the learner would store to check a password at sign-in. Password hashing has not yet been explained or proposed.\n"
+ },
+ "turns": [
+ "Let's work out what we store to check passwords when people sign in.",
+ "We should store a hashed password, not the password itself.",
+ "Discuss. What is a salt, and why does it help?"
+ ],
+ "review": [
+ "Lets the learner propose hashing first, then explains missing knowledge directly without a terminology-guessing exercise.",
+ "Separates the learner's decision from Claude's proposed details in a short list or Detail / Proposal / Why it matters table.",
+ "Does not mark a specific algorithm, session lifetime, or other unconfirmed addition as chosen.",
+ "Discuss leads to clarification and preserves the pending decision; no application code is written."
+ ]
+ }
+ }
+}
diff --git a/tests/test_notion_demo.py b/tests/test_notion_demo.py
new file mode 100644
index 0000000..045659e
--- /dev/null
+++ b/tests/test_notion_demo.py
@@ -0,0 +1,107 @@
+"""Check demo isolation and smoke-run failure handling without calling an LLM."""
+
+import importlib.util
+import json
+from pathlib import Path
+import subprocess
+import tempfile
+import unittest
+from unittest.mock import patch
+
+
+ROOT = Path(__file__).resolve().parents[1]
+spec = importlib.util.spec_from_file_location("notion_demo", ROOT / "scripts/notion_demo.py")
+demo = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(demo)
+
+
+def response(text="A checkpoint question", result="success"):
+ return "\n".join(json.dumps(row) for row in [
+ {"type": "system", "subtype": "init", "model": "fixture-model"},
+ {"type": "assistant", "message": {"content": [
+ {"type": "thinking", "thinking": "omitted from artifacts"},
+ {"type": "text", "text": text},
+ ]}},
+ {"type": "result", "subtype": result},
+ ])
+
+
+class NotionDemoTests(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.parent = Path(self.temp.name)
+
+ def test_fresh_runs_are_empty_unique_and_preserve_previous_work(self):
+ first, _, _ = demo.prepare("fresh", self.parent)
+ self.assertEqual(list((first / "project").iterdir()), [])
+ (first / "project/app.py").write_text("keep my work")
+ second, _, _ = demo.prepare("fresh", self.parent)
+ self.assertNotEqual(first, second)
+ self.assertEqual(list((second / "project").iterdir()), [])
+ self.assertEqual((first / "project/app.py").read_text(), "keep my work")
+
+ def test_staged_scenes_copy_only_notes_not_future_answers(self):
+ scenario = demo.load_scenario()
+ for name in ("folders", "data-model", "sign-in"):
+ with self.subTest(scene=name):
+ run, scene, metadata = demo.prepare(name, self.parent)
+ project = run / "project"
+ state = project / ".vibe-wise"
+ self.assertEqual({p.name for p in state.iterdir()},
+ {"profile.md", "progress.md", "project-map.md"})
+ content = "\n".join(p.read_text() for p in state.iterdir())
+ for prompt in scene["turns"]:
+ self.assertNotIn(prompt, content)
+ self.assertEqual(demo.application_files(project), [])
+ self.assertTrue((run / "review.json").is_file())
+ self.assertEqual(metadata["scene"], name)
+ self.assertEqual(metadata["plugin_version"],
+ json.loads((ROOT / ".claude-plugin/plugin.json").read_text())["version"])
+ self.assertTrue(metadata["guide_hashes"])
+ self.assertNotIn("links table", scenario["scenes"]["data-model"]["files"]["project-map.md"])
+
+ @patch.object(demo.subprocess, "run")
+ def test_check_resumes_same_session_and_writes_reviewable_artifacts(self, run_cli):
+ run, scene, metadata = demo.prepare("data-model", self.parent)
+ run_cli.return_value = subprocess.CompletedProcess([], 0, response(), "")
+ with patch("builtins.print"):
+ demo.check(run, scene, metadata, "claude", 1, 180)
+ self.assertEqual(run_cli.call_count, 2)
+ first, second = [call.args[0] for call in run_cli.call_args_list]
+ self.assertIn("--session-id", first)
+ self.assertIn("--resume", second)
+ for command in (first, second):
+ self.assertIn(metadata["session_id"], command)
+ self.assertNotIn("--dangerously-skip-permissions", command)
+ self.assertNotIn("Bash", command[command.index("--tools") + 1])
+ saved = json.loads((run / "turn-02.json").read_text())
+ self.assertEqual(saved["user"], scene["turns"][1])
+ self.assertEqual(saved["model"], "fixture-model")
+ self.assertNotIn("omitted from artifacts", (run / "conversation.txt").read_text())
+
+ @patch.object(demo.subprocess, "run")
+ def test_budget_failure_is_not_a_pass(self, run_cli):
+ run, scene, metadata = demo.prepare("fresh", self.parent)
+ run_cli.return_value = subprocess.CompletedProcess(
+ [], 0, response(result="error_max_budget_usd"), "")
+ with patch("builtins.print"), self.assertRaises(RuntimeError):
+ demo.check(run, scene, metadata, "claude", 1, 180)
+ self.assertTrue((run / "turn-01.json").exists())
+
+ @patch.object(demo.subprocess, "run")
+ def test_unapproved_application_file_fails_the_check(self, run_cli):
+ run, scene, metadata = demo.prepare("folders", self.parent)
+
+ def premature_code(*args, **kwargs):
+ (run / "project/app.py").write_text("# premature implementation")
+ return subprocess.CompletedProcess([], 0, response(), "")
+
+ run_cli.side_effect = premature_code
+ with patch("builtins.print"), self.assertRaisesRegex(RuntimeError, "before approval"):
+ demo.check(run, scene, metadata, "claude", 1, 180)
+ self.assertEqual(run_cli.call_count, 1)
+
+
+if __name__ == "__main__":
+ unittest.main()