@abarcenas/ai-workflow-template 1.45.0 → 1.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/.agents/config/README.md +43 -0
  2. package/.agents/config/domain.md +37 -0
  3. package/.agents/instructions/learned-knowledge.instructions.md +110 -0
  4. package/.agents/instructions/memory-bank.instructions.md +11 -0
  5. package/.agents/skills/domain-modeling/ADR-FORMAT.md +47 -0
  6. package/.agents/skills/domain-modeling/GLOSSARY-FORMAT.md +60 -0
  7. package/.agents/skills/domain-modeling/SKILL.md +74 -0
  8. package/.agents/skills/grill-me/SKILL.md +7 -0
  9. package/.agents/skills/grill-with-docs/SKILL.md +7 -0
  10. package/.agents/skills/grilling/SKILL.md +28 -0
  11. package/.agents/skills/prototype/LOGIC.md +67 -0
  12. package/.agents/skills/prototype/SKILL.md +26 -0
  13. package/.agents/skills/prototype/UI.md +112 -0
  14. package/.github/workflows/npm-publish.yml +10 -0
  15. package/.github/workflows/pr-test.yml +31 -0
  16. package/.opencode/agents/orchestrator/orchestrator.agent.md +68 -3
  17. package/.opencode/agents/scope.agent.md +299 -0
  18. package/AGENTS.md +42 -3
  19. package/README.md +5 -2
  20. package/package.json +1 -1
  21. package/scripts/bump-version.test.js +238 -0
  22. package/scripts/mcp/playwright-mcp-launcher.js +55 -29
  23. package/scripts/mcp/playwright-mcp-launcher.test.js +217 -0
  24. package/scripts/mcp-memory-server.js +93 -76
  25. package/scripts/mcp-memory-server.test.js +398 -0
  26. package/scripts/memory-cli.test.js +297 -0
  27. package/scripts/memory-index.js +119 -31
  28. package/scripts/memory-index.test.js +1173 -0
  29. package/scripts/normalize-memory.js +26 -1
  30. package/scripts/normalize-memory.test.js +753 -0
  31. package/scripts/setup/discover.test.js +124 -2
  32. package/scripts/setup/hooks.test.js +188 -1
  33. package/scripts/setup/husky-init.test.js +311 -0
  34. package/scripts/setup/index.js +35 -5
  35. package/scripts/setup/index.test.js +279 -0
  36. package/scripts/setup/knowledgebase.test.js +100 -0
  37. package/scripts/setup/skills-phase.js +568 -0
  38. package/scripts/setup/skills-phase.test.js +1274 -0
  39. package/scripts/setup/sync-phase.js +6 -1
  40. package/scripts/setup/sync-phase.test.js +180 -2
  41. package/scripts/setup/ui.test.js +579 -0
  42. package/scripts/setup/utils.test.js +586 -0
  43. package/scripts/sync-unit.test.js +1342 -0
  44. package/scripts/sync.js +540 -246
  45. package/scripts/sync.test.js +283 -0
  46. package/scripts/vocab-sync.test.js +88 -0
  47. package/skills-lock.json +90 -0
@@ -0,0 +1,43 @@
1
+ ---
2
+ title: "Agent skills and configuration"
3
+ description: "Discovery pointer for the scoping skills, the scope agent, and domain documentation locations."
4
+ ---
5
+
6
+ ## Why this file exists
7
+
8
+ Root-file sync skips any file you have modified locally. If you edited `AGENTS.md`, newer
9
+ versions of the template will not overwrite it, so a `## Agent skills` section added upstream
10
+ will never reach your copy. This file is the discovery path in that case: it lives under
11
+ `.agents/`, which syncs on every update.
12
+
13
+ ## Scoping skills
14
+
15
+ Each skill lives at `.agents/skills/<name>/SKILL.md` and is loaded with the skill tool.
16
+
17
+ | Skill | Use it when |
18
+ |-------|-------------|
19
+ | `grilling` | A plan, decision, or idea needs stress-testing, or a request is too vague to plan — rounds of numbered questions narrow the frontier, each with a recommended answer. |
20
+ | `grill-me` | You want the same interview with no repository context and no document output — a stateless, one-shot entry point. |
21
+ | `grill-with-docs` | You want the interview plus the written record — the glossary and ADRs are created as decisions settle. |
22
+ | `domain-modeling` | Project terminology or architectural decisions are being introduced or changed, and `GLOSSARY.md` or an ADR needs to capture them. |
23
+ | `prototype` | A design question can only be settled by running throwaway code — the logic branch for state models and data flow, the UI branch for look and feel. |
24
+
25
+ `grill-me` and `grill-with-docs` are human-invoked wrappers: the first calls `grilling` alone,
26
+ the second calls `grilling` and `domain-modeling` together.
27
+
28
+ ## Scope agent
29
+
30
+ `.opencode/agents/scope.agent.md` is the front door for underspecified feature requests. It
31
+ runs grilling in rounds against a draft file, emits the current frontier as numbered questions,
32
+ and finishes by writing a spike document at `docs/spike-<feature>.md` — the input
33
+ `researcher.agent.md` already expects.
34
+
35
+ It never builds or runs code. When a question needs a prototype it emits
36
+ `prototype needed: <question>`, and the orchestrator delegates the work to `coder` (logic) or
37
+ `designer` (UI).
38
+
39
+ ## Domain docs
40
+
41
+ `.agents/config/domain.md` declares where domain documentation lives: `GLOSSARY.md` at the
42
+ repository root and ADRs under `docs/adr/`. The `domain-modeling` skill reads it; when the file
43
+ or the docs it names are absent, the skill proceeds silently.
@@ -0,0 +1,37 @@
1
+ ---
2
+ description: "Domain artifact paths for domain-modeling and grill-with-docs"
3
+ applyTo: "**"
4
+ ---
5
+
6
+ # Domain Documentation
7
+
8
+ Read this file to locate the project's domain artifacts before exploring the
9
+ codebase or changing the domain model.
10
+
11
+ ## Layout
12
+
13
+ This repository uses a single-context layout:
14
+
15
+ - `GLOSSARY.md` at the repository root — the project's domain vocabulary.
16
+ - `docs/adr/` — Architecture Decision Records, numbered `0001-slug.md`,
17
+ `0002-slug.md`, and so on.
18
+
19
+ Read only the ADRs that touch the area you are about to work in.
20
+
21
+ ## When a file or directory is absent
22
+
23
+ Proceed silently. Do not report the absence, do not treat it as an error, and
24
+ do not scaffold `GLOSSARY.md` or `docs/adr/` unprompted. Create them lazily,
25
+ only when a term or decision has actually been resolved.
26
+
27
+ ## Use the glossary's vocabulary
28
+
29
+ Name domain concepts exactly as `GLOSSARY.md` defines them. Do not drift to
30
+ synonyms the glossary avoids. If a concept is missing, treat it as a gap to
31
+ resolve with the user rather than inventing new language.
32
+
33
+ ## Flag ADR conflicts
34
+
35
+ If your output contradicts an existing ADR, state the conflict explicitly and
36
+ cite the ADR number. Never silently override or quietly reinterpret a recorded
37
+ decision.
@@ -467,3 +467,113 @@
467
467
  - **reviewer**: Verify the opt-out guard is placed BEFORE any read/write (additive, default unchanged) and probe the truthy-string edge — `SKIP_BUMP=0`/`false` also skip (M-1). Confirm comment-only changes leave duplicate files byte-identical and runtime unchanged. Distinguish pre-existing drift (`package-lock.json` at `1.34.0`; missing `architecture-context` vocab entity) from issues introduced by the change; a historical tracker entry referencing the pre-settle version is a frozen-record artifact, not a defect.
468
468
  - **deployer**: Use the newly added `SKIP_BUMP=1` on the commits that introduce it, rather than `--no-verify` — the guard is the targeted mitigation and keeps the other hooks (memory-schema validation, vocab-sync) running. After a version settle, verify the manifest version at HEAD and that it was committed exactly once (no re-bump), and confirm the hook logged the skip.
469
469
  - **tracker**: Record the `SKIP_BUMP` guard as IMPLEMENTED (closing the 2026-08-02 / 2026-09-14 recommendation) with the exact settle delta (`1.49.0 → 1.45.0`), and carry the non-blocking minors forward (M-1 truthy string, M-2 missing SDK qualifier in README, M-3 lockfile drift, M-4 vocab entity gap, M-5 stale historical "1.49.0" narrative). Reuse the canonical `projectId` from `require('./package.json').name` (`@abarcenas/ai-workflow-template`) when re-indexing this session.
470
+
471
+ ## Session: 2026-10-24 — Matt Pocock Skills Integration + Scope Agent (pinned vendored skills + new setup phase)
472
+
473
+ **Pipeline:** implementer (bootstrap + read-only pre-flight) → coder ∥(T1,T2,T3) → coder(T4) → coder ∥(T5,T6) → coder(T7) → coder(T8+T9) → coder(T10+T11) → coder ∥(T12,T13,T14) → coder(T15) → coder ∥(T16,T17) → tracker
474
+ **Coverage:** 16 files / 331 tests, 0 failures; `scripts/setup/` 7 files / 142 tests; `scripts/sync.test.js` 15/15; `spec-orchestrator-parity` 8/8; `spec-knowledge-retrieval` 6/6; `scripts/setup/skills-phase.js` 99.42% stmts / 97.34% branch / 100% funcs / 100% lines
475
+ **TDD Iterations:** 0 (feature pipeline, not TDD)
476
+
477
+ **New knowledge:**
478
+ - **`bin/setup.js` is a 26-line shim — every setup phase lives in `scripts/setup/`.** `index.js` orchestrates; siblings are `sync-phase.js`, `prepare.js`, `husky-init.js`,
479
+ `knowledgebase.js`, `constants.js`, `ui.js`.
480
+ The plan targeted `bin/setup.js` for a new install phase; the correct home was a new `skills-phase.js` module plus a step in `index.js`'s Phase 6. **Universal pattern:** before
481
+ planning an edit to an entry-point file, check whether it is a shim that delegates to a phase directory — targeting the entry point produces a feature that lives in the wrong
482
+ layer and is untestable in the project's established style.
483
+ - **`vitest.config.ts` enforces 90% coverage over `scripts/**`, and every setup module has a sibling `.test.js` — but the GLOBAL threshold already fails at HEAD.** New `scripts/`
484
+ code must ship with tests (the per-file numbers matter), yet the repo-wide number was **48.05% statements at HEAD** and **~50.69%** after this feature. **Universal pattern:**
485
+ distinguish the *per-file* coverage contract from the *repo-wide* threshold.
486
+ A pre-existing global failure is not a regression and must not be "fixed" opportunistically by changing thresholds or exclusions; record the baseline you measured at HEAD so the
487
+ delta is auditable.
488
+ - **The v8 coverage provider reads 0% for code exercised only through `spawnSync` child processes.** `scripts/sync.js` executes at import (no exported `main`), so its tests spawn
489
+ it as a child; v8 cannot instrument across the process boundary.
490
+ Its 0% coverage is structural and pre-existing. **Universal pattern:** for child-process entry points, rely on behavioural assertions (exit code, stdout/stderr, filesystem/tree
491
+ diffs) and state in the record that the coverage number is meaningless — never chase it by refactoring the entry point purely for coverage.
492
+ - **`tests/spec-orchestrator-parity.test.js` asserts EXACT OCCURRENCE COUNTS of literal phrases** (2× `knowledge-retrieval`, 2× `knowledgebase`) in `orchestrator.agent.md`.
493
+ **Universal pattern:** before editing an orchestrator spec, grep the parity test for occurrence-count guards; an edit that quotes the same literal a third time fails the suite
494
+ even though the change is correct.
495
+ Either avoid duplicating the string or update the counts deliberately and say so.
496
+ - **`tests/spec-knowledge-retrieval.test.js` derives the pipeline agent set by scanning `.opencode/agents/*.agent.md` minus `plan.agent.md` and asserts an exact length.** Adding
497
+ `scope.agent.md` broke it until `EXPECTED_PIPELINE_AGENTS` went 10 → 11. **Universal pattern:** a new agent file is a two-part change — the spec plus every enumeration of agents
498
+ (this one, `CHECK_PATHS`, docs tables, registry rows).
499
+ Grep for the expected count, not just the file list.
500
+ - **`tests/spec-kb-consolidation.test.js` holds a SEPARATE `CHECK_PATHS` enumeration of every agent spec** — the second place that must be updated when an agent is added.
501
+ It was discovered only during the verification phase. **Universal pattern:** after adding an agent/skill/instruction, grep the whole test tree for the old count and for
502
+ enumerations of sibling paths; two independent lists drifting is the normal failure mode, not the exception.
503
+ - **The pre-commit hook runs `bump-version` → `vocab-sync` → `validate-memory-schema`, and the auto-bump is PRE-commit, not post-commit.** `SKIP_BUMP=1` is honored at
504
+ `scripts/bump-version.js:9-15` (the guard sits before any read/write).
505
+ The plan's DEP-03 stated the opposite ordering; the read-only pre-flight caught it. **Universal pattern:** read the hook file itself before planning version strategy.
506
+ Edit the version ONCE by hand per PR and commit with `SKIP_BUMP=1`; do not let N commits produce N minor bumps, and do not use `--no-verify` (it also skips memory-schema
507
+ validation).
508
+ - **Upstream `mattpocock/skills` has ASYMMETRIC category paths** — `skills/productivity/` for `grilling` and `grill-me`, `skills/engineering/` for
509
+ `grill-with-docs`/`domain-modeling`/`prototype` — so a raw URL must **never** be derived from a skill name. **Universal pattern:** when pinning remote files, record the full
510
+ upstream path per file in the lock (`upstreamPath`) and build URLs from the lock alone; deriving paths from names silently 404s for exactly the entries whose category differs.
511
+ - **`grill-me` and `grill-with-docs` are `disable-model-invocation: true`** — they are human-invoked routers, not agent-loadable skills.
512
+ Agents must invoke `grilling` directly (plus `domain-modeling` when a term or decision settles) and must never delegate to the wrappers. **Universal pattern:** check
513
+ `disable-model-invocation` on every vendored skill before wiring it into an agent; a router that only a human can start cannot be a pipeline step (the same reason `wayfinder` was
514
+ dropped).
515
+ - **`docs/` is neither in `package.json` `files` nor in `scripts/sync.js`'s root-file list (CON-09).** Configuration placed under `docs/agents/` would never reach consumers, no
516
+ matter how correct it is. **Universal pattern:** before choosing a location for distributed configuration, verify the path is actually packaged AND synced — pick
517
+ `.agents/config/` (synced recursively) over a conventional `docs/` location.
518
+ - **Root-file sync (`AGENTS.md`, `opencode.json`, `skills-lock.json`) SKIPS locally modified consumer files.** A consumer who edited `AGENTS.md` will never receive a new section.
519
+ **Universal pattern:** every user-facing instruction added to a root-synced file needs a backstop under `.agents/` (here `.agents/config/README.md`) plus a visible install-time
520
+ warning.
521
+ The warning itself must be printed in non-verbose mode — see DEF-01.
522
+ - **`scripts/sync.js` executes at import (no exported `main`); tests use `spawnSync('node', ['scripts/sync.js', ...])` with `INIT_CWD`.** Prune iterates only manifest keys that
523
+ existed **before** the run, so it never deletes files the same run just scaffolded. **Universal pattern:** a newly added destructive path must snapshot its input set at
524
+ start-of-run; otherwise "prune what the package no longer ships" deletes the files the current install just created (all of which are absent from the pre-run manifest).
525
+
526
+ **Agent tuning notes:**
527
+ - **implementer / orchestrator (pre-flight)**: One read-only pre-flight before dispatching any implementation batch is high-value and should be standard whenever a plan references
528
+ specific files.
529
+ Here it caught **9 plan errors** — wrong file target (`bin/setup.js`), the coverage gate's sibling-test requirement, an inverted dependency (DEP-03), the parity-test
530
+ occurrence-count trap, an incomplete lock schema (per-file `upstreamPath`), and others — each of which would have cost a full rework cycle.
531
+ It must stay read-only (no edits, no builds) so it cannot invalidate the plan before the gate is approved.
532
+ - **orchestrator (parallel batches)**: Parallel subagents that each append to `memory-bank/activeContext.md` / `progress.md` cause write races. Parallel batches should either skip memory-bank updates (and say so explicitly in the delegation) or the orchestrator must serialize that write. Disjoint source files are not sufficient — the shared documentation sink is the collision point.
533
+ - **orchestrator (interruption recovery)**: Subagents that mark their own plan checkboxes are reliable, but an interrupted subagent leaves the work done and the rows unmarked. Always re-verify disk state after an interruption (grep for the artifact, run the targeted test) before re-dispatching; re-dispatching an interrupted-but-complete task duplicates work and risks conflicting edits.
534
+ - **orchestrator (concurrent verification)**: Verify-by-diff beats verify-by-test when two agents edit related files concurrently — have one agent diff against sibling files instead of running a suite the other agent is about to change. Tests are a moving target during a parallel batch; diffs against a stable sibling are not.
535
+ - **all agents (knowledgebase_search)**: `knowledgebase_search` was unavailable repo-wide (`DATABASE_URL` unset). Every agent should report it as "NOT executed (PG vector unavailable)" and continue — never retry, never treat it as a task failure, and never block the pipeline on it. The explicit report is the accountability mechanism that keeps a graceful degradation from becoming a silent one.
536
+
537
+ ## Session: 2026-10-25 — Repo-Wide Coverage Gate Met (in-process refactors) + MCP Launcher ESM Bug
538
+
539
+ **Pipeline:** coder (10 new test files, 6 extended, 4 source refactors) → deployer (commit + this record)
540
+ **Coverage:** repo-wide **96.93% stmts / 95.23% branch / 96.62% funcs / 97.16% lines** (was ~50.6% pre-change, 48.05% at HEAD before Feature Pipeline 12); `scripts/` 94.97 / 93.76 / 93.16 / 95.24; `scripts/setup/` 99.88 / 97.80 / 100 / 100. Suite **331 → 746 tests** (16 → 26 files), 0 failures. `npm test` 7 passed / 1 skipped. **0 thresholds lowered, 0 excludes added, 0 `v8 ignore` comments.**
541
+ **TDD Iterations:** 0 (coverage-remediation pipeline, not TDD)
542
+
543
+ **New knowledge:**
544
+ - **v8 coverage cannot instrument CHILD PROCESSES — a module exercised only through `spawnSync` reads 0% forever.** `scripts/sync.js` had 15 behavioural tests and still reported **0.00%** because every test ran `spawnSync('node', ['scripts/sync.js', …])`; the instrumented parent never executes the child's code. The fix is **not** to lower the threshold: extract the top-level body into named functions (`parseArgs`, `createSyncContext`, `readManifest`/`writeManifest`, `isUntouched`, `isPathInside`, `resolvePruneEntry`, `isRegularFile`, `syncProject`, `runSync`), export them, and add an `isEntryPoint()` guard. The same 15 spawn tests then pass **unmodified** while in-process tests cover the units — 0% → **99.65%** with zero assertion changes. **Universal pattern:** "0% but well tested" almost always means child-process execution, not missing tests; refactor for importability, never reduce the gate.
545
+ - **An entry point that runs on import is untestable AND can have side effects on import.** `scripts/mcp-memory-server.js` opened a **stdio transport** the moment it was imported, which is worse than a missing export — importing it in a test would hijack the test process's stdio. Extract `main()`, add `bootstrap()` + a direct-run guard, and the module becomes importable. **Universal pattern:** any module an MCP server / CLI exposes must separate *definition* from *invocation*; a guard is the seam that makes the difference.
546
+ - **macOS reports the same file as `/var/...` through `import.meta.url` and `/private/var/...` through `process.argv[1]`.** A naive `fileURLToPath(import.meta.url) === resolve(process.argv[1])` comparison therefore **fails on macOS temp paths** (and `/tmp` is a symlink to `/private/tmp`). Entry-point detection must compare **`realpathSync()` of both sides**, inside a `try/catch` (a path may not exist): `realpathSync(modulePath) === realpathSync(argvPath)`. Keep the cheap string comparison first as a fast path. **Universal pattern:** any path-identity comparison — entry points, containment checks, dedupe keys — must normalise symlinks on macOS.
547
+ - **Under `"type": "module"`, a `.js` file using `require(...)` throws `ReferenceError: require is not defined` — and import-time-only tests never notice.** `scripts/mcp/playwright-mcp-launcher.js` was **dead on arrival**: CJS `require` in an ESM package. No test executed it (it lives at module top level, so importing it would spawn `npx`), so nothing caught the failure until it was actually exercised. This session converted it to `import` + `buildArgs()` / `launch()` helpers. **Universal pattern:** the `.status?` equivalent for ESM is "is it ever executed, not merely imported?" — a file with no sibling test and top-level side effects can be broken for months; when a package is `"type": "module"`, grep for `require(`/`module.exports` in `.js` files as a lint step.
548
+ - **`better-sqlite3` + `sqlite-vec` DO load in this environment; real temp DBs are the right fixture.** Memory tests use `mkdtempSync` + a real SQLite file, so schema, joins, and `vec_memory` behaviour are exercised for real. Only **`@xenova/transformers`** needs mocking, because its real use downloads a **~90 MB** model — that is the one legitimate mock boundary. **Universal pattern:** mock only what is slow/network-bound; a real temp DB is a better fixture than a fake DB object and costs milliseconds.
549
+ - **`memory-index.js` has a latent orphan-row bug (documented, NOT fixed).** Around lines 242–263 the `SELECT` fetches only `id, content_hash`, so `existing.vec_rowid` is always `undefined`; the update path's `if (oldVecRowid != null)` is dead, and re-indexing a changed chunk **orphans its old `vec_memory` row**. Invisible to search (the JOIN keys on `memory_chunks.vec_rowid`) but a storage leak that grows per changed chunk. **Universal pattern:** when a `SELECT` feeds a conditional that deletes from another table, verify every column the condition reads is actually selected — a column silently missing from the projection turns cleanup into dead code that no test catches.
550
+ - **`.agents-sync-manifest.json` is gitignored — never commit it.** Stale hashes there only make `scripts/sync.js` skip local copies in a consumer tree; it is derived state, not source. **Universal pattern:** before staging a large diff, check `git status` for derived manifests/databases/reports — they are regenerated, not reviewed.
551
+ - **Established entry-point-guard pattern in this repo** (copy it rather than inventing one): `scripts/vocab-sync.js`, `scripts/validate-memory-schema.js`, `scripts/normalize-memory.js`, and now `scripts/sync.js` / `mcp-memory-server.js` / `mcp/playwright-mcp-launcher.js` — named exports + `isEntryPoint()`/`isDirectRun` + invoke only when run directly.
552
+
553
+ **Agent tuning notes:**
554
+ - **coder (coverage remediation)**: Inventory coverage by module first and classify each 0% file as (a) never tested, (b) tested only via a child process, or (c) untestable because of import-time side effects. Each class has a different fix; only (c) needs a `bootstrap()` seam. Preserve existing spawn tests verbatim as the behavioural backstop — if a refactor forces you to change them, the refactor changed behaviour. Never reach for `/* v8 ignore */`, excludes, or threshold edits; if you are tempted, the module is untestable by design and needs the seam instead.
555
+ - **coder (SQLite/vector tests)**: Use `mkdtempSync` + a real DB. Mock only the embedding model (`@xenova/transformers`) — it is the sole network/size boundary. Clean up temp dirs in `afterEach`.
556
+ - **deployer**: Re-verify all three gates (`--coverage`, `vitest run`, `npm test`) **before** committing, and prove the gate is honest with `git diff vitest.config.ts` (must be empty) plus a grep for ignore comments. Stage exactly the enumerated modified/untracked set; never `git add -A` when derived artifacts (`.agents-sync-manifest.json`, `playwright-report/`, `test-results/`, `memory-bank/.index/`) may be present. Use `SKIP_BUMP=1` so a test-only commit does not bump the minor version.
557
+ - **tracker**: Record the before/after coverage as a table plus the explicit "no thresholds/excludes/ignore comments" proof — the credibility of a coverage claim rests on that negative evidence. Always carry a deliberately-unfixed latent bug forward as an open follow-up with its mechanism, not just its name.
558
+ - **all agents (knowledge retrieval)**: `memory_search` returned "No results found. The index may be empty" and `knowledgebase_search` returned "Knowledgebase not available: DATABASE_URL is not configured" — both reported as skipped/unavailable, neither retried nor treated as a task failure.
559
+
560
+ ## Session: 2026-10-25 — `vec_memory` Orphan Leaks Fixed (vec0 has no foreign keys; audit removal paths)
561
+
562
+ **Pipeline:** coder (test-first: 7 tests written and failing before the fix) → deployer (commit + this record)
563
+ **Scope:** `scripts/memory-index.js`, `scripts/memory-index.test.js`
564
+ **Verification:** `npx vitest run` → 26 files / **753 tests** (746 → 753, 68 in `memory-index.test.js`), 0 failures; `npx vitest run --coverage` → exit 0, **97.02 / 95.28 / 96.74 / 97.25** (was 96.93 / 95.23 / 96.62 / 97.16); `memory-index.js` **98.83 / 96.33 / 96.87 / 99.56**; `npm test` → 7 passed / 1 skipped.
565
+
566
+ **New knowledge:**
567
+ - **`vec0` virtual tables have NO foreign keys; reachability is only via `memory_chunks.vec_rowid`.** A `vec_memory` row that loses its link is unreachable by `search` (the JOIN keys on `memory_chunks.vec_rowid`) yet still occupies storage — an unbounded leak that no query can reveal. The correct invariant is **one vector per *linked* chunk**, i.e. `COUNT(vec_memory) === COUNT(memory_chunks WHERE vec_rowid IS NOT NULL) === COUNT(DISTINCT vec_rowid)`, **not** `vec_memory == memory_chunks`: embed failures legitimately leave `vec_rowid IS NULL` and must be allowed (assert the expected null count explicitly per test, don't hide it). **Universal pattern:** any table without referential integrity needs an explicit integrity assertion in tests, because the database will not enforce it and the query path will not expose it.
568
+ - **A `LEFT JOIN` on the vector row is required to detect *dangling* links, not just `NULL` ones.** `WHERE vec_rowid IS NOT NULL` catches an unlinked chunk but **misses a legacy row whose `vec_rowid` points at a vector that no longer exists** (or a crash between vector insert and link update). Selecting `v.rowid AS vec_exists` via `LEFT JOIN vec_memory v ON v.rowid = mc.vec_rowid` distinguishes live / dangling / null in one query, and the skip path must require `hash matches AND vec_exists != null` — otherwise a dangling chunk is "unchanged" forever and never repaired.
569
+ - **Test SQLite vector integrity by counting rows before/after a content edit, never by trusting `search`.** Orphans are invisible to queries **by construction** — the leak is precisely the rows the JOIN cannot reach. The test helper `assertVectorIntegrity()` counts vectors, linked chunks, distinct links, orphans (`LEFT JOIN … WHERE mc.id IS NULL`), and dangling links (`LEFT JOIN … WHERE vec_rowid IS NOT NULL AND v.rowid IS NULL`). **Universal pattern:** for any cache/index, assert the storage invariant directly against the tables; a passing `search` proves nothing about leaked rows.
570
+ - **Pattern: detach-then-delete-then-reinsert inside `db.transaction()`.** On update, first set `vec_rowid = NULL` and `DELETE` the old vector in one transaction, **then** re-embed and insert + relink in a second transaction. A failed embed then leaves a retryable `NULL` link rather than a dangling reference, and an interruption can never produce an orphan. **Universal pattern:** when two side-effect writes must agree but the store cannot enforce it, order them so every intermediate state is self-consistent and retryable.
571
+ - **`incrementalUpdate` had no deleted-file pruning at all — deleted files remained searchable.** Both `memory_chunks` and `vec_memory` rows survived, so `search` could return content from a source file that no longer existed. Fixed with `pruneMissingSources()` (delete chunks + vectors for sources absent from the current file set) and `pruneOrphanVectors()` (sweep any vector row no chunk references, healing DBs corrupted by the old code). **Universal pattern:** when auditing a cache/index for leaks, audit the **removal** paths too — update paths get the tests, deletion paths get forgotten, and stale entries are worse than stale bytes because they are still served.
572
+ - **SQLite `.db` files do not shrink after `DELETE` without `VACUUM`.** Row growth stops immediately (verifiable by `COUNT(*)`), but the file keeps its high-water mark (visible in `memory_stats` size). **Never use file size as the leak metric** in a test or an audit — assert row counts.
573
+ - **A `SELECT` feeding a cross-table cleanup must project every column the cleanup condition reads.** The original bug was a projection omitting `vec_rowid`: `existing.vec_rowid` was always `undefined`, so `if (oldVecRowid != null)` was dead code. No test noticed for months because the symptom (orphan rows) was outside the normal query path. **Universal pattern:** when a condition guards a `DELETE`/cleanup in another table, assert the guard is non-vacuous — mutation-test it or write the failing-first test that observes the cleanup, not just the read path.
574
+
575
+ **Agent tuning notes:**
576
+ - **coder (test-first bug fix)**: Write the failing tests **first** and record the predicted failure messages — here every one landed as predicted (`vec_memory` 3 vs 2, 2 chunks vs 1, `indexed 0 / skipped 2`, deleted-file chunks present, invariant 5 vectors vs 4 linked). A predicted-then-observed failure is much stronger evidence than a test that passes after the fact.
577
+ - **coder (index audits)**: Enumerate all mutating paths — create, update, shrink, delete-source, failure — then assert the same invariant helper on each. The bug was in the paths that had never been tested, not in the one that had.
578
+ - **deployer**: This was a **follow-up fix** to a bug deliberately recorded as open in commit `308c90f`; the tracker entry must explicitly mark that follow-up **resolved** so the audit trail does not keep an open defect that no longer exists. Re-run all three gates before and after, stage only the enumerated files, and use `SKIP_BUMP=1` so the fix does not bump the minor version.
579
+ - **all agents (knowledge retrieval)**: `memory_search` returned "No results found. The index may be empty"; `knowledgebase_search` was **not executed** (PG vector unavailable — `DATABASE_URL` not configured). Both reported as skipped/unavailable, neither retried, neither treated as a task failure.
@@ -134,6 +134,17 @@ All `memory-bank/**/*.md` files must have YAML frontmatter for search indexing.
134
134
 
135
135
  ### Plan Mode
136
136
 
137
+ Scope comes before planning. Underspecified work enters through the `scope` agent; planning starts only once the request is narrowed.
138
+
139
+ 1. **Scope first** — for an underspecified request, the front door is the `scope` agent (`.opencode/agents/scope.agent.md`). It runs grilling rounds against a single draft file, then writes a terminal spike document at `docs/spike-<feature>.md`.
140
+ 2. **Hand the spike to research** — that spike document is the input `researcher.agent.md` expects; pass its path as the required spike argument.
141
+ 3. **Continue the pipeline** — after research (or directly, when no research is needed), the work continues to `implementer`, `architect`, or `coder`, following the recommended next step recorded in the spike.
142
+ 4. **Deep planning is optional** — `plan.agent.md` remains available as an optional deep-planning mode for work that is already scoped. It is demoted in the default flow, not removed or deprecated.
143
+
144
+ When scope runs, record the spike document in the memory bank (a task entry in `tasks/` and/or `activeContext.md`) before implementation planning begins, so the settled and deferred decisions survive a session reset.
145
+
146
+ The flow below applies once the scope is settled:
147
+
137
148
  ```mermaid
138
149
  flowchart TD
139
150
  Start[Start] --> CheckGraph{graphify-out/graph.json exists?}
@@ -0,0 +1,47 @@
1
+ # ADR Format
2
+
3
+ ADRs live in `docs/adr/` and use sequential numbering: `0001-slug.md`, `0002-slug.md`, etc.
4
+
5
+ Create the `docs/adr/` directory lazily: only when the first ADR is needed.
6
+
7
+ ## Template
8
+
9
+ ```md
10
+ # {Short title of the decision}
11
+
12
+ {1-3 sentences: what's the context, what did we decide, and why.}
13
+ ```
14
+
15
+ That's it. An ADR can be a single paragraph. The value is in recording *that* a decision was made and *why*, not in filling out sections.
16
+
17
+ ## Optional sections
18
+
19
+ Only include these when they add genuine value. Most ADRs won't need them.
20
+
21
+ - **Status** frontmatter (`proposed | accepted | deprecated | superseded by ADR-NNNN`): useful when decisions are revisited
22
+ - **Considered Options**: only when the rejected alternatives are worth remembering
23
+ - **Consequences**: only when non-obvious downstream effects need to be called out
24
+
25
+ ## Numbering
26
+
27
+ Scan `docs/adr/` for the highest existing number and increment by one.
28
+
29
+ ## When to offer an ADR
30
+
31
+ All three of these must be true:
32
+
33
+ 1. **Hard to reverse**: the cost of changing your mind later is meaningful
34
+ 2. **Surprising without context**: a future reader will look at the code and wonder "why on earth did they do it this way?"
35
+ 3. **The result of a real trade-off**: there were genuine alternatives and you picked one for specific reasons
36
+
37
+ If a decision is easy to reverse, skip it: you'll just reverse it. If it's not surprising, nobody will wonder why. If there was no real alternative, there's nothing to record beyond "we did the obvious thing."
38
+
39
+ ### What qualifies
40
+
41
+ - **Architectural shape.** "We're using a monorepo." "The write model is event-sourced, the read model is projected into Postgres."
42
+ - **Integration patterns between contexts.** "Ordering and Billing communicate via domain events, not synchronous HTTP."
43
+ - **Technology choices that carry lock-in.** Database, message bus, auth provider, deployment target. Not every library: just the ones that would take a quarter to swap out.
44
+ - **Boundary and scope decisions.** "Customer data is owned by the Customer context; other contexts reference it by ID only." The explicit no-s are as valuable as the yes-s.
45
+ - **Deliberate deviations from the obvious path.** "We're using manual SQL instead of an ORM because X." Anything where a reasonable reader would assume the opposite. These stop the next engineer from "fixing" something that was deliberate.
46
+ - **Constraints not visible in the code.** "We can't use AWS because of compliance requirements." "Response times must be under 200ms because of the partner API contract."
47
+ - **Rejected alternatives when the rejection is non-obvious.** If you considered GraphQL and picked REST for subtle reasons, record it; otherwise someone will suggest GraphQL again in six months.
@@ -0,0 +1,60 @@
1
+ # GLOSSARY.md Format
2
+
3
+ ## Structure
4
+
5
+ ```md
6
+ # {Context Name}
7
+
8
+ {One or two sentence description of what this context is and why it exists.}
9
+
10
+ ## Language
11
+
12
+ **Order**:
13
+ {A one or two sentence description of the term}
14
+ _Avoid_: Purchase, transaction
15
+
16
+ **Invoice**:
17
+ A request for payment sent to a customer after delivery.
18
+ _Avoid_: Bill, payment request
19
+
20
+ **Customer**:
21
+ A person or organization that places orders.
22
+ _Avoid_: Client, buyer, account
23
+ ```
24
+
25
+ ## Rules
26
+
27
+ - **Be opinionated.** When multiple words exist for the same concept, pick the best one and list the others under `_Avoid_`.
28
+ - **Keep definitions tight.** One or two sentences max. Define what it IS, not what it does.
29
+ - **Only include terms specific to this project's context.** General programming concepts (timeouts, error types, utility patterns) don't belong even if the project uses them extensively. Before adding a term, ask: is this a concept unique to this context, or a general programming concept? Only the former belongs.
30
+ - **Group terms under subheadings** when natural clusters emerge. If all terms belong to a single cohesive area, a flat list is fine.
31
+
32
+ ## Single vs multi-context repos
33
+
34
+ **Single context (most repos):** One `GLOSSARY.md` at the repo root.
35
+
36
+ **Multiple contexts:** A `GLOSSARY-MAP.md` at the repo root lists the contexts, where they live, and how they relate to each other:
37
+
38
+ ```md
39
+ # Glossary Map
40
+
41
+ ## Contexts
42
+
43
+ - [Ordering](./src/ordering/GLOSSARY.md): receives and tracks customer orders
44
+ - [Billing](./src/billing/GLOSSARY.md): generates invoices and processes payments
45
+ - [Fulfillment](./src/fulfillment/GLOSSARY.md): manages warehouse picking and shipping
46
+
47
+ ## Relationships
48
+
49
+ - **Ordering → Fulfillment**: Ordering emits `OrderPlaced` events; Fulfillment consumes them to start picking
50
+ - **Fulfillment → Billing**: Fulfillment emits `ShipmentDispatched` events; Billing consumes them to generate invoices
51
+ - **Ordering ↔ Billing**: Shared types for `CustomerId` and `Money`
52
+ ```
53
+
54
+ The skill infers which structure applies:
55
+
56
+ - If `GLOSSARY-MAP.md` exists, read it to find contexts
57
+ - If only a root `GLOSSARY.md` exists, single context
58
+ - If neither exists, create a root `GLOSSARY.md` lazily when the first term is resolved
59
+
60
+ When multiple contexts exist, infer which one the current topic relates to. If unclear, ask.
@@ -0,0 +1,74 @@
1
+ ---
2
+ name: domain-modeling
3
+ description: Build and sharpen a project's domain model. Use when discussing codebase terminology, writing or editing a GLOSSARY.md, or recording or editing an ADR.
4
+ ---
5
+
6
+ # Domain Modeling
7
+
8
+ Actively build and sharpen the project's domain model as you design. This is the *active* discipline: challenging terms, inventing edge-case scenarios, and writing the glossary and decisions down the moment they crystallise. (Merely *reading* `GLOSSARY.md` for vocabulary is not this skill: that's a one-line habit any skill can do. This skill is for when you're changing the model, not just consuming it.)
9
+
10
+ ## File structure
11
+
12
+ Most repos have a single context:
13
+
14
+ ```
15
+ /
16
+ ├── GLOSSARY.md
17
+ ├── docs/
18
+ │ └── adr/
19
+ │ ├── 0001-event-sourced-orders.md
20
+ │ └── 0002-postgres-for-write-model.md
21
+ └── src/
22
+ ```
23
+
24
+ If a `GLOSSARY-MAP.md` exists at the root, the repo has multiple contexts. The map points to where each one lives:
25
+
26
+ ```
27
+ /
28
+ ├── GLOSSARY-MAP.md
29
+ ├── docs/
30
+ │ └── adr/ ← system-wide decisions
31
+ ├── src/
32
+ │ ├── ordering/
33
+ │ │ ├── GLOSSARY.md
34
+ │ │ └── docs/adr/ ← context-specific decisions
35
+ │ └── billing/
36
+ │ ├── GLOSSARY.md
37
+ │ └── docs/adr/
38
+ ```
39
+
40
+ Create files lazily: only when you have something to write. If no `GLOSSARY.md` exists, create one when the first term is resolved. If no `docs/adr/` exists, create it when the first ADR is needed.
41
+
42
+ ## During the session
43
+
44
+ ### Challenge against the glossary
45
+
46
+ When the user uses a term that conflicts with the existing language in `GLOSSARY.md`, call it out immediately. "Your glossary defines 'cancellation' as X, but you seem to mean Y. Which is it?"
47
+
48
+ ### Sharpen fuzzy language
49
+
50
+ When the user uses vague or overloaded terms, propose a precise canonical term. "You're saying 'account': do you mean the Customer or the User? Those are different things."
51
+
52
+ ### Discuss concrete scenarios
53
+
54
+ When domain relationships are being discussed, stress-test them with specific scenarios. Invent scenarios that probe edge cases and force the user to be precise about the boundaries between concepts.
55
+
56
+ ### Cross-reference with code
57
+
58
+ When the user states how something works, check whether the code agrees. If you find a contradiction, surface it: "Your code cancels entire Orders, but you just said partial cancellation is possible. Which is right?"
59
+
60
+ ### Update GLOSSARY.md inline
61
+
62
+ When a term is resolved, update `GLOSSARY.md` right there. Don't batch these up: capture them as they happen. Use the format in [GLOSSARY-FORMAT.md](./GLOSSARY-FORMAT.md).
63
+
64
+ `GLOSSARY.md` should be totally devoid of implementation details. Do not treat `GLOSSARY.md` as a spec, a scratch pad, or a repository for implementation decisions. It is a glossary and nothing else.
65
+
66
+ ### Offer ADRs sparingly
67
+
68
+ Only offer to create an ADR when all three are true:
69
+
70
+ 1. **Hard to reverse**: the cost of changing your mind later is meaningful
71
+ 2. **Surprising without context**: a future reader will wonder "why did they do it this way?"
72
+ 3. **The result of a real trade-off**: there were genuine alternatives and you picked one for specific reasons
73
+
74
+ If any of the three is missing, skip the ADR. Use the format in [ADR-FORMAT.md](./ADR-FORMAT.md).
@@ -0,0 +1,7 @@
1
+ ---
2
+ name: grill-me
3
+ description: A relentless interview to sharpen a plan or design.
4
+ disable-model-invocation: true
5
+ ---
6
+
7
+ Call the Skill tool with "grilling".
@@ -0,0 +1,7 @@
1
+ ---
2
+ name: grill-with-docs
3
+ description: A relentless interview to sharpen a plan or design, which also creates docs (ADR's and glossary) as we go.
4
+ disable-model-invocation: true
5
+ ---
6
+
7
+ Call the Skill tool twice, for "grilling" and "domain-modeling".
@@ -0,0 +1,28 @@
1
+ ---
2
+ name: grilling
3
+ description: Grill the user relentlessly about a plan, decision, or idea. Use when the user wants to stress-test their thinking, or uses any 'grill' trigger phrases.
4
+ ---
5
+
6
+ Interview the user relentlessly until you reach a shared understanding. Map this as a **design tree**: every decision branches into the decisions that hang off it.
7
+
8
+ Work the tree in **rounds**. The **frontier** is every decision whose prerequisites are already settled: the questions you can ask _now_ without guessing at answers you haven't heard yet. Ask the whole frontier in one round: number each question and give your recommended answer. Then wait for the user's answers before the next round.
9
+
10
+ Format a round like so:
11
+
12
+ ```
13
+ ❓ **Q1** - **<question title>**: <question body, might be multiple paragraphs, including multiple choices>
14
+
15
+ ➡️ <your recommended answer>
16
+
17
+ ---
18
+
19
+ ❓ **Q2** - **<question title>**: <question body, might be multiple paragraphs, including multiple choices>
20
+
21
+ ➡️ <your recommended answer>
22
+ ```
23
+
24
+ Each round the user answers reshapes the tree: settled decisions push the frontier outward and unblock questions that depended on them. Recompute the frontier and ask the next round. A question whose answer depends on another question still open in this round belongs to a _later_ round, not this one.
25
+
26
+ Finding _facts_ is your job, never the user's. When a frontier question needs a fact from the environment (filesystem, tools, etc.), dispatch a sub-agent to find it; don't ask the user for anything you could look up yourself. Don't block on it: a running exploration is an unsettled prerequisite, so only the questions downstream of it wait for the sub-agent to report; ask the rest of the frontier now. The _decisions_ are the user's: put each to them and wait.
27
+
28
+ The session is done when the frontier is empty: every branch of the design tree visited, nothing left silently assumed. Do not act on it until the user confirms you have reached a shared understanding.
@@ -0,0 +1,67 @@
1
+ # Logic Prototype
2
+
3
+ A single, self-contained HTML file (a **shareable demo**) that lets anyone drive a state model by clicking buttons. Use this when the question is about **business logic, state transitions, or data shape**: the kind of thing that looks reasonable on paper but only feels wrong once you push it through real cases.
4
+
5
+ Because it's one file with nothing to install, you can hand it to a non-developer (a designer, a PM, a domain expert) and let them feel the model for themselves. So it speaks their language, not the code's.
6
+
7
+ ## When this is the right shape
8
+
9
+ - "I'm not sure if this state machine handles the edge case where X then Y."
10
+ - "Does this data model actually let me represent the case where..."
11
+ - "I want to feel out what the API should look like before writing it."
12
+ - Anything where someone wants to **press buttons and watch state change**.
13
+
14
+ If the question is "what should this look like," this is the wrong branch. Use [UI.md](UI.md).
15
+
16
+ ## Process
17
+
18
+ ### 1. State the question
19
+
20
+ Before writing code, write down what state model and what question you're prototyping. One paragraph, at the top of the demo (in a visible intro, not just a comment). A logic prototype that answers the wrong question is pure waste, so make the question explicit so it can be checked later, whether the user is watching now or returning to it AFK.
21
+
22
+ ### 2. Isolate the logic in a portable module
23
+
24
+ Put the actual logic (the bit that's answering the question) in a single `<script>` block written as a small, pure module that could be lifted out and dropped into the real codebase later. The page around it is throwaway; this module isn't.
25
+
26
+ The right shape depends on the question:
27
+
28
+ - **A pure reducer**: `(state, action) => state`. Good when actions are discrete events and state is a single value.
29
+ - **A state machine**: explicit states and transitions. Good when "which actions are even legal right now" is part of the question.
30
+ - **A small set of pure functions** over a plain data type. Good when there's no implicit current state, just transformations.
31
+ - **A class or module with a clear method surface** when the logic genuinely owns ongoing internal state.
32
+
33
+ Pick whichever shape best fits the question being asked, *not* whichever is easiest to wire to a page. Keep it pure: no DOM, no `document`, no button handlers reaching inside it. The page calls into it; nothing flows the other direction. This is what makes the prototype useful past its own lifetime: once the question's answered, the validated reducer / machine / function set lifts into the real module on its own.
34
+
35
+ ### 3. Build the shareable HTML file
36
+
37
+ One file, plain HTML/CSS/JS: no framework, no bundler, no server, everything inline so it opens by double-click and survives being emailed around. Anyone should be able to run it by opening it.
38
+
39
+ Write it for a non-developer. Every label is in **domain language**, not code: buttons and state read like the business, not the reducer. Explain in plain words what's happening.
40
+
41
+ Lay it out with a clean hierarchy, top to bottom:
42
+
43
+ 1. **Title and one-line explanation** of what this demo lets you explore (the question from step 1).
44
+ 2. **Current state**: the full relevant state, rendered as a readable panel (labelled fields, not a raw JSON dump), re-rendered after every click so the change is visible. Where it helps a non-developer follow, call out what just changed.
45
+ 3. **Free-play buttons**: one button per action, always available, so anyone can poke at the model in any order. Each click dispatches its action and re-renders the state.
46
+ 4. **Guided walkthroughs**: a set of **scenarios**, one per tab. Each tab holds a short plain-language description of the scenario (the situation it sets up and what to watch for) and underneath it, the ordered **buttons to press** for that scenario. Each step is a real button: clicking it performs that action and moves to the next step. Starting a walkthrough resets to a known initial state so the scenario runs the same way every time.
47
+
48
+ Choose scenarios that demonstrate the awkward cases, the ones hard to reason about on paper: the happy path, a tricky edge case, an attempt at something that should be illegal.
49
+
50
+ Keep it beautiful but restrained: clean typography, generous spacing, one accent colour. No animations, no gimmicks: nothing that competes with the state and the buttons.
51
+
52
+ ### 4. Hand it over
53
+
54
+ Send them the file, or open it for them. They'll click through the walkthroughs and free-play whenever they get to it; the interesting moments are when they say "wait, that shouldn't be possible" or "huh, I assumed X would be different"; those are the bugs in the _idea_, which is the whole point. If they want new actions or a new scenario, add them. Prototypes evolve.
55
+
56
+ ### 5. Capture the answer and the prototype
57
+
58
+ Once the prototype has answered its question, capture the answer, then capture the prototype the way the [SKILL](SKILL.md) describes. The logic-specific mapping: the validated reducer / machine / function set lifts into the real module (the decision, absorbed); the HTML shell rides along to the throwaway branch that keeps the prototype as a primary source, and being one self-contained file, it stays trivially re-runnable there.
59
+
60
+ ## Anti-patterns
61
+
62
+ - **Don't add tests.** A prototype that needs tests is no longer a prototype.
63
+ - **Don't wire it to the real database.** Use in-memory state unless the question is specifically about persistence.
64
+ - **Don't generalise.** No "what if we wanted to support X later." The prototype answers one question.
65
+ - **Don't blur the logic and the page together.** If the pure module references the DOM, `document`, or button handlers, it's no longer liftable. Keep the page as a thin shell over a pure module.
66
+ - **Don't reach for a framework, bundler, or server.** One file the recipient double-clicks; a React app or a dev server defeats "shareable".
67
+ - **Don't ship the HTML shell into production.** The page is optimised for being clicked through by hand. The logic module behind it is the bit worth keeping.
@@ -0,0 +1,26 @@
1
+ ---
2
+ name: prototype
3
+ description: Build a throwaway prototype to answer a design question. Use when the user wants to sanity-check whether a state model or logic feels right, or explore what a UI should look like.
4
+ ---
5
+
6
+ # Prototype
7
+
8
+ A prototype is **throwaway code that answers a question**. The question decides the shape.
9
+
10
+ ## Pick a branch
11
+
12
+ Identify which question is being answered, using the user's prompt, the surrounding code, or by asking if the user is around:
13
+
14
+ - **"Does this logic / state model feel right?"** → [LOGIC.md](LOGIC.md). Build a single shareable HTML file (free-play buttons plus tabbed guided walkthroughs) that pushes the state machine through cases that are hard to reason about on paper, and that a non-developer can drive.
15
+ - **"What should this look like?"** → [UI.md](UI.md). Generate several radically different UI variations on a single route, switchable via a URL search param and a floating bottom bar.
16
+
17
+ The two branches produce very different artifacts, so getting this wrong wastes the whole prototype. If the question is genuinely ambiguous and the user isn't reachable, default to whichever branch better matches the surrounding code (a backend module → logic; a page or component → UI) and state the assumption at the top of the prototype.
18
+
19
+ ## Rules that apply to both
20
+
21
+ 1. **Throwaway from day one, and clearly marked as such.** Locate the prototype code close to where it will actually be used (next to the module or page it's prototyping for) so context is obvious, but name it so a casual reader can see it's a prototype, not production. For throwaway UI routes, obey whatever routing convention the project already uses; don't invent a new top-level structure.
22
+ 2. **Trivial to run.** A UI prototype starts from one command in the project's task runner: `pnpm <name>`, `python <path>`, `bun <path>`, etc. A logic demo is a single HTML file the user double-clicks. Either way, no thinking required to start it.
23
+ 3. **No persistence by default.** State lives in memory. Persistence is the thing the prototype is _checking_, not something it should depend on. If the question explicitly involves a database, hit a scratch DB or a local file with a clear "PROTOTYPE, wipe me" name.
24
+ 4. **Skip the polish.** No tests, no error handling beyond what makes the prototype _runnable_, no abstractions. The point is to learn something fast.
25
+ 5. **Surface the state.** After every action (logic) or on every variant switch (UI), print or render the full relevant state so the user can see what changed.
26
+ 6. **Capture it when done.** Fold any validated decision into the real code, then capture the prototype itself as a **primary source**: commit it to a throwaway branch, out of main, and leave a context pointer to that branch on the implementation issue. Capture the answer too (the verdict and the question it settled) in the issue or a commit. The main branch keeps only the validated decision.