@hxp-tools/godplans 0.0.0-stage → 2.0.1

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 (146) hide show
  1. package/CHANGELOG.md +1202 -0
  2. package/LICENSE +21 -0
  3. package/PROMPT.md +4006 -0
  4. package/README.md +245 -2
  5. package/bin/godplans.js +93 -0
  6. package/docs/ARCHITECTURE.md +136 -0
  7. package/docs/RELEASING.md +107 -0
  8. package/docs/assets/badge-approved.svg +12 -0
  9. package/docs/assets/badge-done.svg +11 -0
  10. package/docs/assets/badge-graded.svg +12 -0
  11. package/docs/assets/badge-validated.svg +10 -0
  12. package/docs/assets/hero.svg +37 -0
  13. package/docs/assets/quest-map.svg +53 -0
  14. package/evals/README.md +295 -0
  15. package/evals/cases/brownfield-cli/EXPECTATIONS +15 -0
  16. package/evals/cases/brownfield-cli/INPUT/package.json +9 -0
  17. package/evals/cases/brownfield-cli/INPUT/src/cli.js +4 -0
  18. package/evals/cases/brownfield-cli/INPUT/src/format.js +3 -0
  19. package/evals/cases/brownfield-cli/INPUT/test/cli.test.js +7 -0
  20. package/evals/cases/brownfield-cli/REQUEST.baseline.md +10 -0
  21. package/evals/cases/brownfield-cli/REQUEST.md +10 -0
  22. package/evals/cases/compliance-refusal/EXPECTATIONS +4 -0
  23. package/evals/cases/compliance-refusal/REQUEST.baseline.md +9 -0
  24. package/evals/cases/compliance-refusal/REQUEST.md +8 -0
  25. package/evals/cases/greenfield-saas/EXPECTATIONS +21 -0
  26. package/evals/cases/greenfield-saas/REQUEST.baseline.md +11 -0
  27. package/evals/cases/greenfield-saas/REQUEST.md +11 -0
  28. package/evals/cases/nested-pillars/EXPECTATIONS +12 -0
  29. package/evals/cases/nested-pillars/REQUEST.baseline.md +10 -0
  30. package/evals/cases/nested-pillars/REQUEST.md +11 -0
  31. package/evals/cases/observability-evidence/EXPECTATIONS +10 -0
  32. package/evals/cases/observability-evidence/REQUEST.baseline.md +10 -0
  33. package/evals/cases/observability-evidence/REQUEST.md +11 -0
  34. package/evals/cases/product-business/EXPECTATIONS +18 -0
  35. package/evals/cases/product-business/REQUEST.baseline.md +13 -0
  36. package/evals/cases/product-business/REQUEST.md +14 -0
  37. package/evals/cases/product-form-routing/EXPECTATIONS +13 -0
  38. package/evals/cases/product-form-routing/REQUEST.baseline.md +11 -0
  39. package/evals/cases/product-form-routing/REQUEST.md +11 -0
  40. package/evals/cases/prose-integrity/EXPECTATIONS +19 -0
  41. package/evals/cases/prose-integrity/REQUEST.baseline.md +19 -0
  42. package/evals/cases/prose-integrity/REQUEST.md +20 -0
  43. package/evals/cases/replan-preserves-history/EXPECTATIONS +9 -0
  44. package/evals/cases/replan-preserves-history/INPUT/.godplans/PLAN.mdx +115 -0
  45. package/evals/cases/replan-preserves-history/INPUT/package.json +5 -0
  46. package/evals/cases/replan-preserves-history/REQUEST.baseline.md +10 -0
  47. package/evals/cases/replan-preserves-history/REQUEST.md +10 -0
  48. package/evals/cases/stale-prepublication/EXPECTATIONS +10 -0
  49. package/evals/cases/stale-prepublication/REQUEST.baseline.md +12 -0
  50. package/evals/cases/stale-prepublication/REQUEST.md +13 -0
  51. package/evals/cases/stale-source-evidence/EXPECTATIONS +10 -0
  52. package/evals/cases/stale-source-evidence/INPUT/package.json +8 -0
  53. package/evals/cases/stale-source-evidence/REQUEST.baseline.md +11 -0
  54. package/evals/cases/stale-source-evidence/REQUEST.md +12 -0
  55. package/evals/cases/weekend-library/EXPECTATIONS +19 -0
  56. package/evals/cases/weekend-library/REQUEST.baseline.md +10 -0
  57. package/evals/cases/weekend-library/REQUEST.md +11 -0
  58. package/evals/cases-roster.txt +19 -0
  59. package/evals/external/GRADE.schema.json +39 -0
  60. package/evals/external/README.md +42 -0
  61. package/evals/external/RUBRIC.md +32 -0
  62. package/evals/metrics/context-cost.json +154 -0
  63. package/evals/outcomes/README.md +65 -0
  64. package/evals/outcomes/cases/tenant-notes-api/REQUEST.baseline.md +14 -0
  65. package/evals/outcomes/cases/tenant-notes-api/REQUEST.md +13 -0
  66. package/evals/outcomes/cases/tenant-notes-api/VERIFY.sh +13 -0
  67. package/evals/outcomes/results/2026-07-23-tenant-notes-api-codex/README.md +93 -0
  68. package/evals/outcomes/results/2026-07-23-tenant-notes-api-codex/treatment/plan/PLAN.json +547 -0
  69. package/evals/runners/claude-baseline.sh +4 -0
  70. package/evals/runners/claude-grade.sh +3 -0
  71. package/evals/runners/claude.sh +4 -0
  72. package/evals/runners/codex-baseline.sh +181 -0
  73. package/evals/runners/codex-builder.sh +96 -0
  74. package/evals/runners/codex-godaudits.sh +84 -0
  75. package/evals/runners/codex.sh +147 -0
  76. package/evals/runners/gemini-baseline.sh +4 -0
  77. package/evals/runners/gemini-grade.sh +3 -0
  78. package/evals/runners/gemini.sh +4 -0
  79. package/evals/runners/vendor-cli.sh +257 -0
  80. package/evals/runners/vendor-grade.sh +82 -0
  81. package/install.sh +323 -0
  82. package/package.json +91 -4
  83. package/requirements/skills-ref.txt +2 -0
  84. package/scripts/build-catalog.js +114 -0
  85. package/scripts/build-prompt.sh +257 -0
  86. package/scripts/context-metrics.js +118 -0
  87. package/scripts/eval-external.js +226 -0
  88. package/scripts/eval-matrix.sh +172 -0
  89. package/scripts/eval-outcome.js +143 -0
  90. package/scripts/eval.sh +321 -0
  91. package/scripts/lint-parity.js +331 -0
  92. package/scripts/lint.sh +743 -0
  93. package/scripts/outcome-summary.js +126 -0
  94. package/scripts/release-check.sh +108 -0
  95. package/scripts/release-prepare.js +41 -0
  96. package/scripts/summarize-eval.js +91 -0
  97. package/scripts/summarize-matrix.js +101 -0
  98. package/scripts/version-sync.js +65 -0
  99. package/skills/godplans/SKILL.md +192 -0
  100. package/skills/godplans/references/agent-memory.md +168 -0
  101. package/skills/godplans/references/architecture.md +189 -0
  102. package/skills/godplans/references/build.md +130 -0
  103. package/skills/godplans/references/business.md +252 -0
  104. package/skills/godplans/references/code-quality.md +165 -0
  105. package/skills/godplans/references/compliance.md +59 -0
  106. package/skills/godplans/references/database.md +157 -0
  107. package/skills/godplans/references/deploy.md +146 -0
  108. package/skills/godplans/references/discovery.md +297 -0
  109. package/skills/godplans/references/doc-set.md +243 -0
  110. package/skills/godplans/references/exemplar.md +228 -0
  111. package/skills/godplans/references/launch.md +162 -0
  112. package/skills/godplans/references/llm.md +132 -0
  113. package/skills/godplans/references/observe.md +178 -0
  114. package/skills/godplans/references/plan-format.md +340 -0
  115. package/skills/godplans/references/product.md +130 -0
  116. package/skills/godplans/references/repo.md +184 -0
  117. package/skills/godplans/references/roadmap.md +158 -0
  118. package/skills/godplans/references/security.md +156 -0
  119. package/skills/godplans/references/seo.md +133 -0
  120. package/skills/godplans/references/stack.md +133 -0
  121. package/skills/godplans/references/style-genome.md +198 -0
  122. package/skills/godplans/references/ui.md +153 -0
  123. package/skills/godplans/references/ux.md +150 -0
  124. package/skills/godplans/schemas/PLAN.schema.json +275 -0
  125. package/skills/godplans/schemas/PLAN.v1.schema.json +258 -0
  126. package/skills/godplans/scripts/plan-halflife.sh +76 -0
  127. package/skills/godplans/scripts/style-stats.py +630 -0
  128. package/skills/godplans/scripts/validate-plan.sh +1709 -0
  129. package/skills/godplans/templates/PLAN.template.mdx +269 -0
  130. package/tests/agent-memory-guidance.sh +32 -0
  131. package/tests/build-catalog.sh +81 -0
  132. package/tests/codex-runner.sh +139 -0
  133. package/tests/eval-harness.sh +377 -0
  134. package/tests/evidence-harnesses.sh +243 -0
  135. package/tests/fixtures/plan-json-v1-1.13.0.json +472 -0
  136. package/tests/install-regression.sh +246 -0
  137. package/tests/lib/plan-schema-check.js +163 -0
  138. package/tests/lint-selftest.sh +582 -0
  139. package/tests/package-contents.sh +143 -0
  140. package/tests/portable-prompt.test.sh +261 -0
  141. package/tests/release-tooling.sh +204 -0
  142. package/tests/run.sh +14 -0
  143. package/tests/script-usage.sh +37 -0
  144. package/tests/style-stats.sh +170 -0
  145. package/tests/validate-plan.sh +1970 -0
  146. package/tests/vendor-runner.sh +291 -0
@@ -0,0 +1,252 @@
1
+ # Business planning module: the product-director lens
2
+
3
+ Loaded second in the domain-pass order, after Product. Product decides the problem, the primary user, and the requirements; this module decides who pays and for what, how a sale becomes access, what the customer lifecycle does to money, access, and data, how each number the team decides with is computed, how changes reach and leave customers, and how customers are heard.
4
+
5
+ Applicability: applicable when any of these holds: the plan charges money or displays a price; people outside the team create accounts or sign up; the product sends usage telemetry about people outside the team; or a contact-sales, waitlist, or feedback surface collects customer signals. Typical cases are a saas-dashboard, a mobile-app or extension with accounts or purchases, a sold game, a marketing-site with pricing or contact-sales, and an api-service or library with a hosted tier, a paid license, telemetry, or sign-up. Installing a free package or app is not an account. A project none of these signals reaches excludes the domain `by-design:` with a `revisit when:` predicate such as "any task adds a price, a checkout, a sign-up route reachable without an invite, an analytics SDK, or a feedback destination". An undecided revenue model is `unknown` and never licenses the exclusion. The domain is never deferred: the paying unit, the entitlement scope, and the billing system of record shape the data model.
6
+
7
+ The `monetized` overlay forbids excluding this domain. It fires when the request, an interview answer, or decision 2 charges money, sells plans or seats, or meters paid usage; a Phase 4 decision that starts charging adds `monetized` to the frontmatter overlays list and to the `- Overlays:` line of the `### Archetype confidence` block before emission, then rechecks the business matrix row. The overlay acts on the matrix row only; the floor in the Self-audit rubric is what keeps billing safety from dropping by scale.
8
+
9
+ Conditional requirements: a requirement whose criterion opens with IF binds only while its condition holds. Drop it through the layer that removed the condition: `archetype` when a plan decision removed it, citing the decision, for example `dropped-by archetype R-BIZ-11, R-BIZ-12 (D2: no charge in this plan)`; `scale` when the condition is a scale; `form` when the product form has no such surface. Cite several decisions with commas, never semicolons, because the validator splits disposition clauses on `;`. An unknown condition is never a reason to drop; it is an Open Question with a default.
10
+
11
+ Scale calibration: scale sets how much of this module binds, never whether a plan that charges protects the customer's money, access, and data. Weekend: R-BIZ-2 is one paragraph; every other requirement whose condition holds lands as acceptance lines on existing tasks, and the scale layer drops only the requirements whose condition is scale-bound, for example `dropped-by scale R-BIZ-1, R-BIZ-3, R-BIZ-4, R-BIZ-25 (weekend: success is the R-PRD-5 metrics alone)`. Analytics, metric, flag, and deprecation requirements (R-BIZ-20 to R-BIZ-24) drop through the archetype layer citing decision 6 or 9 when their conditions do not hold, never by scale. Side-project: R-BIZ-1, R-BIZ-3, and R-BIZ-4 land in the reduced forms their bodies name, R-BIZ-25 drops by scale, and R-BIZ-23 drops through the archetype layer citing decision 9 when no task introduces a flag. At weekend and side-project scale R-BIZ-19 drops by scale only when no invoice-term tier, custom deal, admin tooling, or SLA service credit is planned; otherwise its override records and the admin actions those features need land. Funded-product and enterprise: every requirement whose condition holds lands in full. At any scale, a plan that charges never drops R-BIZ-7 to R-BIZ-16 through the scale layer; at weekend scale they fold into at most two tasks (catalog and checkout; webhook and lifecycle). A plan whose appetite cannot hold them is mis-scaled: the scale changes, not the requirement, just as a weekend project with passwords still hashes them with argon2id.
12
+
13
+ ## Lineage
14
+
15
+ Descends from productauditor (hannsxpeter/auditor-suite, skills/productauditor), which audits a product "through a product manager's and head of product's lens" in nine dimensions; its 58 cards become the requirement groups below: CLM claims and delivery, ENT plans and entitlements, BILL billing lifecycle, CUST accounts and operations, MET instrumentation, KPI metric definitions, SHIP release and sunset, EXP experiments, and VOC feedback. The plan designs out the five classes productauditor treats as Critical: charging more than, other than, or after what the customer chose; refusing what a plan includes; destroying customer data in a lifecycle event without notice or a recovery window; a business model nothing enforces (sandbox checkout in production, access from the success redirect, an unknown plan falling through to paid, a trial nothing ends); and selling something that does not exist or is invented.
16
+
17
+ R-BIZ-1, R-BIZ-2, and R-BIZ-4 have no auditor counterpart, by design: productauditor files no strategy, market, pricing-level, or roadmap opinion and writes "Target customer: not stated" rather than invent one. An audit cannot judge the bet; a plan can decide it, and a later productaudit then has a promise inventory, a plan catalog, and a metric register to read. R-BIZ-3's register also inverts MET-R7 (a named metric nothing measures). Sources: the North Star Framework (Amplitude North Star Playbook); Ramanujam and Tacke, Monetizing Innovation (2016); Croll and Yoskovitz, Lean Analytics (2013); Kohavi, Tang, and Xu, Trustworthy Online Controlled Experiments (2020); Torres, Continuous Discovery Habits (2021); Hodgson, "Feature Toggles" (martinfowler.com, 2017); RFC 9745 (Deprecation header); RFC 8594 (Sunset header).
18
+
19
+ Dated sources, from the productauditor facts file in hannsxpeter/auditor-suite (reviewed 2026-10-01; recheck any fact older than six months before a plan cites it): ROSCA, 15 U.S.C. 8403, requires a simple mechanism to stop recurring charges. The California Automatic Renewal Law (Business and Professions Code 17600 and following, as amended by AB 2863, for contracts entered, amended, or extended on or after 1 July 2025, 17602(j)) sets express-consent and consent-record, same-medium cancellation, annual-reminder, price-change (notice 7 to 30 days before), and free-trial (trials over 31 days, notice 3 to 21 days before the end) duties. The FTC Negative Option ("click-to-cancel") Rule was vacated by the Eighth Circuit on 8 July 2025; an advance notice of proposed rulemaking of 13 March 2026 had produced no proposed or final rule at review, and the rule is never cited as law. The New York City subscription-cancellation rule applies from 1 October 2026. The EU Data Act (Regulation (EU) 2023/2854) Chapter VI governs switching and data export for software services from 12 September 2025. A legal window enters a plan only through a cited source or an Open Question; godplans names the signal and the regime it may trigger and never asserts that a regime applies.
20
+
21
+ Cited, not restated. Product: problem, user, requirements, NFRs, success targets, and the statement of which regulations apply (R-PRD-1 to R-PRD-7). UX: the activation event and its step budget (R-UX-14), fee, total, and cancellation-effort disclosure (R-UX-17), destructive confirmations (R-UX-5). Launch: positioning, landing, conversion waterfall, UTM values, waitlist double opt-in (R-LAUNCH-1, R-LAUNCH-4, R-LAUNCH-12, R-LAUNCH-16, R-LAUNCH-17), fed by this module's segment and catalog. Security: roles, tenancy, request-settable privilege fields, webhook signatures and retired mounts, abuse limits, erasure, and consent before trackers (R-SEC-3, R-SEC-4, R-SEC-16, R-SEC-19, R-SEC-21, R-SEC-29); "does this plan include this feature" stays here. Database: money types, delete behavior, idempotency, outbox, and amount reconciliation (R-DB-4, R-DB-6, R-DB-7, R-DB-9, R-DB-15, R-DB-23); subscription-state reconciliation stays here. Architecture: bounded contexts, entity ownership, API versioning (R-ARCH-5, R-ARCH-7, R-ARCH-20), fed by decisions 1 and 4. Code quality: read sites for stored gating values and lifecycle transitions (R-CODE-23). Deploy: canary, flag defaults per rung, flag-name lineage, rollback rehearsal (R-DEPLOY-7, R-DEPLOY-11, R-DEPLOY-14, R-DEPLOY-16). Observe: SLOs and alerts; product analytics and business KPIs, which R-OBS-20 excludes, live here. Repo: the developer changelog, SemVer, and generated platform release notes (R-REPO-8, R-REPO-13). LLM: model spend caps and output feedback (R-LLM-15, R-LLM-19); model-call quotas a plan sells are R-BIZ-10 quotas. Stack: the payments dimension (R-STACK-4) records decision 4. Build: the hollow-data grep (R-BUILD-16).
22
+
23
+ ## Decisions to force
24
+
25
+ Hardest to reverse first. Each lands in the plan's Decisions section as a grounded decision with a Falsifier block, a flagged hypothesis with a validation task, or an Open Question with a recommended default. When decision 2 is no charge, decisions 3, 4, and 7 and the payment transitions of decision 5 are not forced; they live in decision 2's `revisit when:` predicate. At weekend and side-project scale, decisions 9 and 11 take their scale defaults as one line each inside decision 2's entry.
26
+
27
+ 1. Paying unit and customer of record.
28
+ - Question: who holds the subscription, the entitlements, and the data: a workspace or organization, an individual user, or both?
29
+ - Why hard to reverse: it fixes entitlement scope, seat billing, the analytics group id, shared-work ownership, and the tenancy key; moving subscriptions from users to workspaces later is a data, billing, and customer-communication migration at once.
30
+ - Options: (a) the workspace holds subscription, entitlements, and shared content; (b) the user holds them; (c) both, with a written precedence rule and a test.
31
+ - Default: (a), with a workspace of one created at sign-up, whenever the buyer is a business or any roadmap horizon names sharing, seats, or a team plan; (b) only when the buyer is an individual consumer and no horizon names sharing. A product that fits neither is an Open Question that blocks build.
32
+ 2. Revenue model, value metric, and motion.
33
+ - Question: does this plan charge, for what unit of value, and through which motion?
34
+ - Why hard to reverse: meters, seat counts, and quota counters live in the data model and every consuming path.
35
+ - Options: no charge (with a `revisit when:` predicate), flat subscription, per seat, usage-based, base plus usage, one-time license, store in-app purchase, take rate; motion self-serve, sales-assisted, self-serve with a sales-assisted tier above a threshold, or store.
36
+ - Default: no charge when the request names no price and scale is weekend or side-project, with `revisit when: any task adds a price, a checkout, or a paid tier`. Otherwise one value metric the customer can see and predict, and a pricing model that constrains the data model takes a slot in the interview batch. Usage-based pricing only with a server-side meter and visible current-period usage.
37
+ 3. Free offer and conversion path.
38
+ - Question: what does a prospect get before paying (nothing; a trial of a named plan, with or without a payment method up front; a free plan with catalog limits; a reverse trial that falls to the free plan), and at which fence does the product ask for money?
39
+ - Why hard to reverse: a free plan withdrawn from an installed base needs grandfathering and notice; an auto-converting trial carries renewal-notice duties a no-card trial does not; the fence decides which limit counters ship first.
40
+ - Default: an explicit decision naming the trial plan and its end state; when undecided, an Open Question that blocks build.
41
+ 4. Billing system of record, merchant of record, and tax.
42
+ - Question: which system is the source of truth for subscription state, and who collects and remits tax?
43
+ - Why hard to reverse: a local subscription model that is not a projection becomes a second truth that drifts, and changing the merchant of record changes invoices, tax registration, and refunds.
44
+ - Options: (a) the provider is the source of truth and the app holds a webhook-written projection plus a reconciliation job; (b) the app owns subscription state (refused); (c) entitlement checks read the provider or its SDK live through a short-lived cache with no local projection, which fits merchant-of-record and store SDKs at small scale. Merchant of record (Paddle, Lemon Squeezy, Polar) or processor plus tax engine (Stripe with Stripe Tax); store billing for digital goods unlocked in native apps, under the storefront rules in effect.
45
+ - Default: (a) at funded-product scale and above, (c) below it. R-BIZ-9 to R-BIZ-12 name the entitlement source this decision picks: the webhook-written projection under (a), the provider read through its cache under (c). The merchant-of-record choice is an Open Question decided by tax posture unless the user has decided it.
46
+ 5. Lifecycle end states, refunds, and data on lapse.
47
+ - Question: what happens to access, members, and data at trial end, failed payment, cancellation, a downgrade below current usage or seat count, and account closure, and what does a refund return and revoke?
48
+ - Why hard to reverse: deletion cannot be undone, and the refund policy decides whether cancellation is immediate or at period end.
49
+ - Options per transition: convert, fall to a free plan, or read-only with export; refunds none, prorated on cancel, or full within a window.
50
+ - Default: access until the paid period ends on cancel; over-limit data and members read-only and exportable with an owner notice; deletion only after a sourced window.
51
+ 6. Event identity and analytics topology.
52
+ - Question: where do outcome and revenue events originate, and which ids tie them to a user and an account?
53
+ - Why hard to reverse: events already sent cannot be re-identified or backfilled.
54
+ - Options: server-side outcome events after commit with a dedup id and client events for intent only (default); client-only outcome or revenue events (refused); warehouse-first modeling from database rows.
55
+ - Default: server-side events identified with the stable internal user id and grouped by the decision 1 paying unit. At weekend and side-project scale, when every R-PRD-5 metric can be computed from rows the app already writes and no task plans client or server analytics events (the R-LAUNCH-17 waterfall included), saved queries over those rows with no event-tracking client; R-BIZ-20 and R-BIZ-21 then drop through the archetype layer citing this decision.
56
+ 7. Plan catalog source, currencies, and change policy.
57
+ - Question: where are plans, prices, features, limits, coupons, and provider price ids defined, which currencies and regions sell, and what happens to existing customers when terms change?
58
+ - Why hard to reverse: once copy, entitlements, and checkout each hold a plan, every price change ships three diverging edits and old-terms customers cannot be identified.
59
+ - Options: a code-owned catalog that generates pricing copy and entitlement constants and is checked against the provider (default); a provider-owned catalog read live through lookup keys; CMS-authored pricing (refused unless generated from the catalog).
60
+ - Default: legacy plan keys with effective dates for grandfathered customers, and one catalog price per currency sold.
61
+ 8. North star, inputs, and guardrails.
62
+ - Question: which one number says customers get the core value, which inputs move it, and which guardrail stops a harmful win?
63
+ - Why hard to reverse: it sets what is instrumented first, and redefining it mid-flight destroys the baseline.
64
+ - Options: a count of paying units, or users for consumer products, performing the core value action per window (default); revenue as the north star (refused: revenue is a lagging guardrail); a composite score (refused unless every component has a register entry).
65
+ - Default: revenue and one quality signal as guardrails.
66
+ 9. Release control and sunset policy.
67
+ - Question: how do unfinished features stay off, how is a feature stopped in production without a deploy, and how are features, plans, and public API versions retired?
68
+ - Why hard to reverse: a flag mechanism threads through every route, and a deprecation promise made without a policy becomes the policy.
69
+ - Options: one typed flag wrapper whose fallback is current production behavior, with kill switches for features that move money, send customer messages, or delete or export customer data (default at funded-product scale and above); environment-variable flags (refused for kill switches, which must be read at runtime); no flag mechanism at weekend or side-project scale unless a task introduces a flag (default there).
70
+ - Default: a deprecation notice period that is cited or an Open Question.
71
+ 10. The bet, its kill criterion, and principles.
72
+ - Question: what does this plan bet will be true, what observation would prove it wrong and when, who decides, and which principles settle trade-offs before they are argued?
73
+ - Why hard to reverse: sunk cost grows with every phase, and a bet with no kill criterion is never killed.
74
+ - Options: the R-BIZ-1 falsifier (default); no kill criterion (refused).
75
+ - Default: principles written as "X over Y" (R-BIZ-4).
76
+ 11. Experimentation posture.
77
+ - Question: will this plan run controlled experiments, and on what unit?
78
+ - Why hard to reverse: assignment keyed to the wrong unit invalidates every result collected.
79
+ - Options: none at weekend or side-project scale (default there, dropped by scale); at funded-product or enterprise scale, none until the north star has a measured baseline (default, R-BIZ-25 dropped through the archetype layer citing this decision); after that, flag-based experiments through decision 9, with the randomization unit equal to the paying unit when price or shared flows change.
80
+
81
+ ## Plan requirements
82
+
83
+ Consumed by the orchestrator's inversion pass; each becomes acceptance criteria on concrete tasks via `Requirements:` lines.
84
+
85
+ Director lens
86
+
87
+ 1. R-BIZ-1 The bet and its kill criterion. The bet is a `### D<n>` decision of at most two sentences that cites R-PRD-3, R-PRD-4, and R-PRD-12 instead of restating them and names the R-PRD-9 assumption ids it rests on. Its Falsifier carries the kill criterion in the validator's grammar. Signal opens with the register id (R-BIZ-3), never the word metric, and states the minimum exposure (paying units or users reaching the measured step) below which the verdict is extend once. Failure boundary states the numeric threshold, fixed before the first measurement by the user's answer, the decider's decision, a cited source, or an Open Question that blocks ship, plus the decide-by point, anchored to a milestone such as "launch + 60 days" unless a calendar date falls inside the current cycle (R-ROAD-11). Replan action reads "return to planning; <decider> decides to continue, reconsider <the segment or bet> (pivot), or remove <the product or feature> (stop)". A task citing R-BIZ-1 writes this record with `Verdict: pending`; the decider records the verdict at the review the authority map schedules, which at side-project scale is the R-PRD-17 30-day retrospective. No executing agent records a verdict.
88
+ Criterion: WHEN the business section is emitted at side-project scale or above THE PLAN SHALL state the bet as a decision whose Falsifier carries the R-BIZ-1 kill criterion, and SHALL contain a task citing R-BIZ-1 that records it with `Verdict: pending`.
89
+ 2. R-BIZ-2 Business model, segment, motion, and packaging. The plan states the paying unit (decision 1), buyer and user roles when they differ, the motion, the revenue model, the value metric, and the free offer (decision 3). Each tier names its fence as a catalog field, and copy that sells a plan for teams, agencies, or several locations requires the workspace paying unit. A price appears only when cited, given by the user, decided by the R-BIZ-4 price decider, or flagged as a hypothesis whose validation task (willingness-to-pay interviews with a stated count, a priced landing or checkout smoke test, or recorded sales conversations) precedes the task that makes the price public. A sales-assisted tier states invoice terms (collection method, payment terms, currency), the contract interval, how a signed order becomes an R-BIZ-19 override record, and the role that owns a new account until its R-UX-14 activation event fires; security questionnaires, DPAs, and order-form ownership are owned Open Questions. A native app that unlocks digital features names its purchase path per storefront from a dated store-policy source (App Store Review Guideline 3.1.1, the Google Play Payments policy) or an Open Question. When launch is applicable, R-LAUNCH-1's first sentence names this segment.
90
+ Criterion: WHEN the business section is emitted THE PLAN SHALL state paying unit, roles, motion, revenue model, value metric, and free offer; IF tiers exist THE PLAN SHALL name each tier's fence and SHALL NOT state an unsourced price; IF a tier is sales-assisted THE PLAN SHALL state its invoice terms, contract interval, order-to-override path, and onboarding owner.
91
+ 3. R-BIZ-3 North star and metric register. One register, the business-owned `design.metrics-register` document, holds every metric the plan names: when business is applicable, the R-PRD-5 instrumentation task and this register are one task citing both requirements, so one file and one task own the metrics; the register the north star, its inputs, guardrails, every R-PRD-5 success metric, and every kill-criterion and experiment metric. SLOs and other promise-compliance metrics stay with observe (R-OBS-20). The north star is one of the R-PRD-5 metrics and counts toward that cap; the other entries sit outside it. Each entry carries numerator, denominator (`none` for a count such as the default north star), the real-customer population filter, window, source event or query, owner, and the GP task that ships it. At funded-product and enterprise scale, and whenever the plan charges, the register holds at least one input and one guardrail; at side-project scale with no charge, the north star and one input suffice. Every next-horizon theme and later-horizon outcome (R-ROAD-11) names the register metric it targets, and phase Must-have KPIs (R-ROAD-14) resolve to register entries.
92
+ Criterion: WHEN the business section is emitted at side-project scale or above THE PLAN SHALL contain one register whose north star is an R-PRD-5 metric; every north-star, input, guardrail, R-PRD-5, kill-criterion, and experiment metric SHALL resolve to exactly one entry with the seven fields, and every next-horizon theme and later-horizon outcome SHALL name a register metric.
93
+ 4. R-BIZ-4 Principles and commercial decision rights. Each product principle is written "X over Y", where Y is a property a reasonable product would choose, and is cited by at least one Decisions entry whose rejected option embodies Y; a principle that fails either test is cut. The R-ROAD-18 authority map gains one row per commercial action the plan can take, each with exactly one decider on the R-PRD-14 roster: the bet verdict when R-BIZ-1 lands; price and packaging changes, discounts and custom deals, and plan retirement when the plan charges; deprecation dates when R-BIZ-24 lands; the experiment ship call when R-BIZ-25 lands. With one maintainer, one row naming that maintainer for every listed action satisfies it.
94
+ Criterion: WHEN the business section is emitted at side-project scale or above THE PLAN SHALL contain at least one principle phrased "X over Y" and cited by a decision whose rejected option embodies Y, and the authority map SHALL contain a decider row for each commercial action whose condition holds.
95
+
96
+ Claims and delivery
97
+
98
+ 5. R-BIZ-5 Promise inventory traced to delivery. Claims include pricing and plan feature lists, checkout and upgrade copy, onboarding, transactional and lifecycle email, store listing, help, terms, support promises, and technical guarantees (end-to-end encryption, data region, "no tracking"). Each maps to an implementing task, a vendor capability with the check that confirms it, or a "coming soon" or "beta" label beside the claim. A support channel or response time maps to a staffed owner and covered hours; an uptime SLA maps to an observe SLO at least as strict plus a service-credit admin action (R-BIZ-19). Plan feature lists render from the catalog (R-BIZ-7). Customer-facing output, paid or free, never comes from fixtures, random values, hardcoded literals, or mock clients on a production path, and sample data is labeled sample (R-BUILD-16 owns the hollow-data grep). Help names screens and settings by labels from the UI message catalog, and copy tasks grep pricing, checkout, sign-up, legal, and email templates for placeholder text (lorem ipsum, [Product Name], Your Company, example.com).
99
+ Criterion: WHEN customer-facing copy or a plan feature list is planned THE PLAN SHALL trace each claim to delivery and test that production selects no mock or stub client and that no sold handler throws not-implemented or returns a constant; IF the plan sells paid features the final Verification phase SHALL check that every paid feature is reachable under production configuration.
100
+ 6. R-BIZ-6 Committed numbers single-sourced. Trial length, retention period, plan limits, refund window, export formats, and data region, wherever copy states them, come from one constant or catalog field that copy and code both read, with the value from R-PRD-7 or a cited source.
101
+ Criterion: IF customer-facing copy states a committed number THE PLAN SHALL name the one constant or catalog field copy and code both read, and IF a deletion job is planned THE PLAN SHALL test it against the published retention period.
102
+
103
+ Plans, pricing, and entitlements
104
+
105
+ 7. R-BIZ-7 One plan catalog, coupons, and legacy terms. One catalog module defines plans, a price with currency and interval for each currency sold, feature keys, limits, provider price ids per environment, coupons with an expiry or redemption cap and the plans they apply to, and legacy plan keys with effective dates. Copy, entitlements, limits, and checkout import it; no second definition exists. A parity check proves each configured provider price exists in the catalog with the same amount, currency, and interval, read from the provider's test environment by a script or from a committed export that script refreshes. A recurring discount of 100 percent with no end date is refused. Changing an existing plan keeps the old terms under a legacy key until renewal after a cited notice period, and the notice task precedes the change task.
106
+ Criterion: WHEN plans are planned THE PLAN SHALL name one catalog imported by copy, entitlements, limits, and checkout, with provider parity on id, amount, currency, and interval; IF an existing plan changes THE PLAN SHALL schedule a cited notice first and test that legacy subscribers keep their terms.
107
+ 8. R-BIZ-8 Displayed price equals charged price. The checkout request carries only a plan key, interval, currency, coupon, and seat count; the server resolves the provider price and amount from the catalog and ignores any amount, price id, or plan in the body. Each market sold states whether displayed prices include tax. One test covers every self-serve plan, interval, currency, and coupon combination at seat counts 1, 2, and each tier's limit, including the shown variant of any pricing experiment, comparing pre-tax amount, currency, interval, and seats and asserting the tax label; another sends a tampered amount, price id, or plan and is charged the catalog amount or refused. A quote-only tier has no displayed price and is covered by R-BIZ-19 override records.
108
+ Criterion: WHEN a pricing surface or checkout is planned THE PLAN SHALL resolve the charged price on the server from the catalog and SHALL contain the sold-combination comparison test and the tampered-request test.
109
+ 9. R-BIZ-9 Entitlement map, scope, and safe default. One function maps every catalog price id (monthly, annual, legacy, regional, trial) to a plan key and every provider subscription status named in a dated source (for Stripe: incomplete, incomplete_expired, trialing, active, past_due, canceled, unpaid, paused) to an access state. Entitlements derive from the paying unit's entitlement source (decision 4), so a team plan bought by one member reaches every member and an add-on unlocks only the paying unit that bought it. Web and store purchases resolve to one entitlement set per paying unit, with store receipts verified on the server. A null or missing plan resolves to the free plan; an unknown price id resolves to free and raises an alert naming the id; nothing falls through to paid access. Tests run every catalog price id through the purchase event for the buyer and a second member, and cover each mapped status, a new sign-up, a null plan, and an unknown price id.
110
+ Criterion: WHEN entitlements are planned THE PLAN SHALL name one mapping function keyed to the paying unit over every price id and provider status, with a free default, an alert on unknown price ids, and the table-driven tests.
111
+ 10. R-BIZ-10 Server-enforced gates and sold limits. One server helper checks each paid feature and limit and is called by every route, job, import, and API mount that serves it, listed in the plan; the UI check is display only. The helper reads the paying unit's entitlement source on every check (the webhook-written projection under decision 4 option a, the provider through its short-lived cache under option c), never a session or token claim, so a plan change applies on the next request, or within the cache lifetime under option c. A quota counts the unit and scope the copy sells, resets on the subscription period, and is moved by every consuming path; jobs serving a paid configuration recheck the plan each run. A refusal names the plan that lifts the limit and the upgrade entry point, and tells a member without billing rights who holds them. Tests cover, per plan, use up to the sold limit succeeding and the next unit refused; each consuming path moving the one counter; a period boundary restoring the quota; a free account receiving 402 or 403 with no side effect and the upgrade target in the body; and a job skipped after downgrade.
112
+ Criterion: WHEN a paid feature or limit is planned THE PLAN SHALL name the server helper, every call site, the counted unit and reset period, and the five tests, plus a check that fails when a listed call site skips the helper.
113
+
114
+ Billing and subscription lifecycle
115
+
116
+ 11. R-BIZ-11 Checkout: access on confirmed payment, live mode, and tax. Self-serve paid access follows the provider's confirmed payment: under decision 4 option a it is granted by the provider's confirmed payment events, including the delayed-payment success event, keyed by the provider's customer and subscription ids, and under option c it is read live from the provider. The success page shows status and may also call an idempotent server function that retrieves the session and checks it is paid and belongs to the account, never as the only grant path. Production startup and the production client build fail on a test-mode key, a sandbox host, or a sandbox client environment. A tier sold on invoice terms grants access only through an R-BIZ-19 override record that references a signed order and carries a payment-due date; an invoice unpaid past that date enters the R-BIZ-14 failed-payment path. When the billing provider is not the merchant of record, checkout enables the provider's automatic tax or passes tax rates, plans sold to businesses collect a tax ID and issue invoices, and tax registration is an owned Open Question. Tests open the success URL with a forged session id and grant nothing, and start the server with production settings and a test key and refuse to start.
117
+ Criterion: IF the plan has a checkout THE PLAN SHALL grant self-serve access only from confirmed payment (the confirmed-payment handler under decision 4 option a, the live provider read under option c), fail production server and client builds on test or sandbox configuration, name the tax mechanism when the provider is not the merchant of record, and contain the forged-session and test-key tests; IF a tier is sold on invoice terms THE PLAN SHALL grant it only through an override record with a payment-due date.
118
+ 12. R-BIZ-12 Lifecycle event matrix and reconciliation. A table names, in the provider's own event names from a dated source, every lifecycle event the integration handles and the state each writes: created; updated, including plan changes made in the provider's customer portal; paused and resumed when pause is sold; ended; payment failed; payment recovered; refund; dispute; and store notifications for native apps (Paddle, for example, delivers refunds and chargebacks as adjustment events). The refund row states the decision 5 refund policy and revokes what the purchase granted (license keys, credits, seats, access). Each handler applies an event only when it is newer than the stored state, by event timestamp or a re-fetch. A scheduled reconciliation job corrects drifted subscription state, seat quantity, and recorded usage, unless entitlements read the provider live (decision 4 option c), in which case a test proves no entitlement path reads a local plan field. A task confirms the provider endpoint subscribes to every handled event. Signatures stay with R-SEC-19, idempotency with R-DB-9, and amount reconciliation with R-DB-23.
119
+ Criterion: IF the plan uses a billing provider THE PLAN SHALL contain the provider-named event table, a replay test per event, the out-of-order and refund-revocation tests, the endpoint subscription check, and either a reconciliation job or the live-read test.
120
+ 13. R-BIZ-13 One subscription, both sides, right time. Subscription changes go through one function that reuses the paying unit's provider customer, refuses a second active subscription across web and store billing, cancels every add-on and seat on cancellation or account deletion, keeps access until the paid period ends, replaces rather than stacks on upgrade, and changes provider and app state together. The plan states when an upgrade, a downgrade, and an interval switch take effect and how each is prorated, citing the provider's proration setting, and an upgrade grants the higher plan only after the provider confirms the change and its prorated charge. Mocked-provider tests cover checkout twice, cancel, delete account, downgrade, upgrade, a declined upgrade charge leaving the old plan, and a store subscriber starting web checkout.
121
+ Criterion: IF subscriptions can change THE PLAN SHALL route every change through one named function, state effective timing and proration per change type, and contain the seven mocked-provider tests.
122
+ 14. R-BIZ-14 Trial, grace, failed payment, and lifecycle notices. Trial end is enforced in the entitlement helper or a registered job, and the expired state keeps a reachable upgrade action. When serving the product costs money per use, the plan states a trial eligibility rule (one trial per paying unit, payment method, or verified domain). A failed payment keeps access through a grace period that is cited or an Open Question, shows an update-payment link, and ends access on the provider's final state; the plan names which provider state ends access after the last retry (for Stripe a dashboard setting) and schedules a task that sets it and records the value. Senders are wired for the trial-ending, renewal, payment-failed, and cancellation notices, with legal minimums cited from a dated source and each regime named in the R-PRD-7 statement of applicable regulations. Tests cover a trial that ended yesterday, failed then paid, and failed then canceled.
123
+ Criterion: IF the plan has a trial or a recurring charge THE PLAN SHALL enforce trial end, a sourced grace period with an update-payment path, the provider's final state, and wired notices with cited minimums, and SHALL contain the three tests.
124
+ 15. R-BIZ-15 Billed seats and usage match use. Every membership path (settings, invite acceptance, SCIM, admin action, API) updates the billed quantity through one function; a contract that commits a seat count states whether added seats bill immediately, at a scheduled true-up, or at renewal, and the function applies that rule. Usage is recorded on the server after the operation succeeds, once, with a stable identifier the provider deduplicates, and failed operations refund consumed credits. On usage-based plans customers see current-period usage and the projected charge, and the plan decides whether a spend cap or usage alert exists; a cap or alert in copy is an R-BIZ-5 claim. A test drives each membership and usage path.
125
+ Criterion: IF billing is per seat or per unit of usage THE PLAN SHALL name the single quantity-update function and the server-side usage recorder, state the committed-seat rule when contracts commit seats, and test every membership and usage path.
126
+ 16. R-BIZ-16 Data and members survive downgrade, lapse, and trial end. Over-limit data becomes read-only and exportable. When the lower plan allows fewer seats than are active, the owner chooses who keeps access, every other member is read-only until then, suspended members can sign in and export their own work, and no member or authored record is deleted. The owner notice carries an export link. Deletion happens only after a cited window, in a job that rechecks the plan before deleting, and a customer who resubscribes inside the window returns to the same paying unit with its data. A test moves a five-seat workspace with over-limit records to a one-seat plan and finds every member and record intact, read-only, and exportable, with the owner notice queued.
127
+ Criterion: IF the plan has a paid plan, a trial, or plan limits THE PLAN SHALL keep over-limit data and members read-only rather than deleted, delete only after a sourced window in a plan-rechecking job, and contain the intact-workspace test.
128
+
129
+ Customer accounts and operations
130
+
131
+ 17. R-BIZ-17 Shared work, ownership, and transfer. The workspace owns shared content and the creator is an attribute, an input to R-DB-6. Removing a member or deleting a user reassigns their shared work instead of deleting it. The last owner cannot be removed, demoted, or deleted until another member is promoted, and a transfer-ownership action exists for the owner and for support.
132
+ Criterion: IF workspaces have more than one member THE PLAN SHALL assign shared content to the workspace, reassign on member removal, block last-owner removal, and plan a transfer action, each with a test.
133
+ 18. R-BIZ-18 Closure stops everything; export covers everything. Closing an account or workspace stops every integration, webhook, schedule, and outbound send in one recorded job. When export is promised or a plan is sold to businesses, export covers every content type customers create in an open, re-importable format, and each per-type test creates more records than one page holds. A data processing service sold to customers in the EU names EU Data Act Chapter VI as a regime its signal may trigger, and its export and closure tasks cite the switching windows from a dated source (notice at most 2 months, transition at most 30 calendar days, at least 30 days to retrieve data, no switching charges from 12 January 2027) or an Open Question.
134
+ Criterion: IF the plan has customer accounts THE PLAN SHALL stop every scheduled effect on closure in one recorded job with a test that nothing remains scheduled; IF export is promised or sold to businesses THE PLAN SHALL export every content type and test each beyond one page.
135
+ 19. R-BIZ-19 Account operations as product actions; deals as records. Recurring support operations (plan change, trial extension, credit, refund, ownership transfer, account restore, account email change, account merge) are role-restricted admin actions built on the lifecycle functions, mounted in the production build behind the support role, calling the provider and taking a reason field, never database edits. Customer-specific arrangements and invoice-term tiers are override records (plan, limits, features, deal reference, payment-due date, end date), never branches on one customer's id, domain, or email.
136
+ Criterion: IF the plan has paying customers at funded-product or enterprise scale, admin tooling, invoice-term tiers, or custom deals THE PLAN SHALL plan each recurring support operation as a production-mounted admin action with a reason field, and SHALL store deals as override records.
137
+
138
+ Product metrics and instrumentation
139
+
140
+ 20. R-BIZ-20 Typed tracking plan and outcome events. One typed event catalog names every event in object-action form; CI compares the names the code sends against it and fails on any analytics SDK call outside the tracking wrapper. Outcome events (the core value action, activation, sign-up, purchase) fire once, server-side after commit or in the confirmed webhook, with a dedup id the analytics tool honors. Revenue and subscription events come from the billing webhook with amount, currency, plan, interval, and account id. Tests assert a failed request sends no outcome event, a successful one sends exactly one, and replayed payment, renewal, refund, and cancellation webhooks each send one event with those fields.
141
+ Criterion: IF analytics events are planned THE PLAN SHALL name the typed catalog and its CI check, send outcome and revenue events server-side with dedup ids, and contain the send-once and webhook-replay tests.
142
+ 21. R-BIZ-21 Identity, consent, and environment separation. The tracking wrapper identifies with the stable internal user id after sign-up and sign-in, groups by the paying unit, and resets on sign-out. It sends nothing for a user or account that rejected tracking, on the server path as well as the client path (R-SEC-29), and event properties carry ids, plan, platform, and amounts, never email, name, or free text. Sign-up stores the first-touch acquisition source (R-LAUNCH-16 UTM values) on the account. Each environment has its own analytics project key set by deploy configuration, tests and CI stub the client, a production-configuration test asserts the wrapper is enabled, and internal, test, and demo accounts carry a property every metric filters on.
143
+ Criterion: IF analytics events are planned THE PLAN SHALL specify identify, group, and reset points, a server-side opt-out, a property allowlist, per-environment keys, a stubbed client in tests, the production-enabled test, and the internal-account marker.
144
+
145
+ Business metric definitions
146
+
147
+ 22. R-BIZ-22 Business metrics defined once, as labeled. Each business metric the plan computes has one definition (a function, view, or semantic-layer metric) that every report reads. MRR normalizes each subscription's price times quantity to a month for the paying statuses the definition lists by name, net of recurring discounts, excluding tax, refunds, one-time charges, and trials. Amounts in different currencies are grouped per currency or converted at a recorded rate. The real-customer filter excludes internal, test, and demo accounts. Active means distinct users who performed a named key action in the window. Churn divides by the count at the start of the period, revenue churn includes contraction, a conversion rate takes numerator and denominator from one population, and closed accounts stay in historical cohorts as non-personal records. Windows are half-open in one stated time zone and match their labels.
148
+ Criterion: IF the plan computes MRR, active users, churn, retention, or conversion THE PLAN SHALL name one definition per metric that every report reads, applying each R-BIZ-22 rule, and SHALL contain a fixture test per rule.
149
+
150
+ Release, rollout, and sunset
151
+
152
+ 23. R-BIZ-23 Release flags and kill switches that work. One typed flag wrapper is the only way code reads a flag; when the flag service cannot answer it falls back to current production behavior and alerts. Keys are generated from the flag definitions, each with an owner and an expiry date, and unreleased features are evaluated on the server for every route they use. Features that move money, send customer messages, or delete or export customer data get a kill switch read per request and per job run on every path of the feature (routes, jobs, webhooks). Percentage rollouts bucket by a deterministic hash of the stable id; targeting rules read only attributes the code sends in the evaluation context, never a hardcoded staff email or id list; a beta or preview names its label beside the feature, its opt-in, and a graduation or removal date; a sold feature names the rule that enables it for the plans that bought it; a mobile app plans a remote minimum-version switch.
153
+ Criterion: IF the plan introduces flags, or at funded-product scale or above ships features that move money, send customer messages, or delete or export customer data, THE PLAN SHALL specify the typed wrapper as the only flag reader with an alerting production-behavior fallback, owned and expiring keys, and server evaluation, and SHALL test that a runtime kill-switch flip stops the next request and job run without a restart.
154
+ 24. R-BIZ-24 Deprecation, breaking changes, and customer release notes. A deprecated feature, plan, or public API version states its end date, its replacement, a cited notice period, the in-product notice to affected accounts, and the query that counts remaining callers. Deprecated API versions send `Deprecation` as an RFC 9745 date (`@<epoch>`) and `Sunset` as an RFC 8594 HTTP-date no earlier than it; deprecated SDK functions and CLI commands emit a runtime warning naming the end date and replacement. A breaking change to a public contract (API, SDK, webhook payload, CLI, export format) follows R-ARCH-20 for APIs and a SemVer major (R-REPO-13) for packages; this requirement adds the migration note and a contract test pinning the old shape, and removing the retired mount stays with R-SEC-19. Customer release notes and in-app what's-new entries are separate from the developer changelog (R-REPO-8) and generated platform notes (R-REPO-13), and each entry is published only after the task that enables the feature for its audience.
155
+ Criterion: IF the plan deprecates a feature, plan, or public API version THE PLAN SHALL state the end date, replacement, sourced notice period, in-product notice, caller-count query, and for API versions both headers; IF it breaks a public contract THE PLAN SHALL add a migration note and an old-shape contract test; WHEN customer release notes are planned THE PLAN SHALL gate each entry on its enabling task.
156
+
157
+ Experimentation
158
+
159
+ 25. R-BIZ-25 Experiments that can decide. Each experiment assigns variants by a deterministic hash of the stable id at the paying-unit level when price or shared flows change, logs exposure once where the variant renders, applies eligibility before assignment with weights summing to the allocation, sends every targeting attribute in the evaluation context, and names a layer or mutual-exclusion rule with any experiment that changes the same surface. It records its end date, the sample-size source, the primary metric and guardrail from the register, the decision rule, and a task that removes the losing branch.
160
+ Criterion: IF the plan runs a controlled experiment THE PLAN SHALL specify each R-BIZ-25 design field and schedule the cleanup task.
161
+
162
+ Customer feedback and demand signals
163
+
164
+ 26. R-BIZ-26 Customer signals reach a person with context. Each feedback, support, survey, bug-report, cancellation-reason, contact-sales, or demand surface (notify-me, request access, feature request, and any waitlist beyond R-LAUNCH-12) names its destination per environment and one reader, with a production startup check that rejects placeholder destinations; the R-PRD-17 runbook task links the readers. Submissions carry user, account, plan, page, and app version from the session, not from the form; demand signals also carry the item requested, and survey responses store the question and scale. Cancellation reasons are stored with account, plan, tenure, and date where churn is reviewed. Ratings on model output stay with R-LLM-19.
165
+ Criterion: WHEN a customer-signal surface is planned THE PLAN SHALL name its per-environment destination and reader, a placeholder-rejecting startup check, session-sourced context, and a delivery test.
166
+
167
+ ## Task seeds
168
+
169
+ - [ ] GP-xxx Define the plan catalog, render pricing copy from it, and prove displayed equals charged
170
+ - Files: src/billing/catalog.ts, src/billing/catalog.test.ts, src/billing/checkout.test.ts, scripts/check-provider-prices.mjs, src/routes/pricing/
171
+ - Acceptance: plans, per-currency prices, feature keys, limits, coupons, provider ids per environment, and legacy keys live only in catalog.ts and the pricing page imports it; check-provider-prices.mjs fails when a provider price differs from its catalog entry in id, amount, currency, or interval; a table-driven test compares the rendered amount with the server-resolved checkout price for every self-serve combination at seat counts 1, 2, and the tier limit; a tampered request is charged the catalog amount or refused
172
+ - Verify: npm test -- catalog checkout && node scripts/check-provider-prices.mjs
173
+ - Requirements: R-BIZ-7, R-BIZ-8
174
+ - [ ] GP-xxx Build the entitlement helper with a free-plan default and mount it on every paid call site
175
+ - Files: src/billing/entitlements.ts, src/billing/entitlements.test.ts, docs/paid-call-sites.md, scripts/check-gates.mjs
176
+ - Acceptance: one requireFeature(account, key) maps every price id and provider status, reads the paying unit's entitlement source, and resolves null or unknown plans to free with an alert on an unknown price id; docs/paid-call-sites.md names each call site, counted unit, and reset period, and check-gates.mjs fails when a listed call site does not call requireFeature; tests cover every price id for buyer and second member, each status, use up to the limit then one more refused, each consuming path moving the one counter, a period boundary restoring the quota, a free account getting 402 with the upgrade target and no side effect, and a job after downgrade
177
+ - Verify: npm test -- entitlements && node scripts/check-gates.mjs
178
+ - Requirements: R-BIZ-9, R-BIZ-10
179
+ - [ ] GP-xxx Grant access on confirmed payment and handle the lifecycle events
180
+ - Files: src/billing/webhook.ts, src/billing/webhook.test.ts, src/jobs/reconcile-subscriptions.ts, src/jobs/schedule.ts, src/config/startup.ts, scripts/check-webhook-events.mjs, docs/billing-events.md
181
+ - Acceptance: docs/billing-events.md maps every provider-named event to the state it writes, with one replay test each plus an out-of-order and a refund-revocation test, and check-webhook-events.mjs fails when the provider endpoint does not subscribe to a handled event; a forged success URL grants nothing, and production startup and the production client build fail on a test-mode key or sandbox host; the reconciliation job is registered in src/jobs/schedule.ts (decision 4 option a) or a test proves no entitlement path reads a local plan field (option c)
182
+ - Verify: npm test -- webhook && node scripts/check-webhook-events.mjs
183
+ - Requirements: R-BIZ-11, R-BIZ-12
184
+ - [ ] GP-xxx Route every subscription change through one function
185
+ - Files: src/billing/subscription.ts, src/billing/subscription.test.ts
186
+ - Acceptance: changeSubscription reuses the provider customer, refuses a second active subscription, cancels add-ons and seats, keeps access to period end, and grants an upgrade only after the prorated charge succeeds; mocked-provider tests cover checkout twice, cancel, delete account, downgrade, upgrade, a declined upgrade charge, and a store subscriber starting web checkout
187
+ - Verify: npm test -- subscription
188
+ - Requirements: R-BIZ-13
189
+ - [ ] GP-xxx Enforce trial end and grace, and keep data and members safe on lapse
190
+ - Files: src/billing/lifecycle.ts, src/jobs/lifecycle-notices.ts, src/jobs/schedule.ts, src/billing/lifecycle.test.ts
191
+ - Acceptance: a trial that ended yesterday gets free access with an upgrade action; failed then paid keeps access and failed then canceled ends it on the provider's final state; a five-seat workspace moved to a one-seat plan keeps every member and record, read-only and exportable, with the owner notice queued
192
+ - Verify: npm test -- lifecycle
193
+ - Requirements: R-BIZ-14, R-BIZ-16
194
+ - [ ] GP-xxx Write the metric register and ship the typed tracking plan
195
+ - Files: docs/metrics.md, src/analytics/events.ts, src/server/analytics.ts, src/server/analytics.test.ts, scripts/check-events.mjs
196
+ - Acceptance: every register metric has numerator, denominator or none, population filter, window, source, owner, and shipping task in docs/metrics.md, the single metrics file this task owns for R-PRD-5 and R-BIZ-3; outcome and revenue events are sent only from src/server/analytics.ts after commit with a dedup id, and check-events.mjs fails CI on an event name missing from events.ts or an SDK call outside the wrapper; tests assert a failed request sends no outcome event, a successful one sends exactly one, and replayed payment, renewal, refund, and cancellation webhooks each send one
197
+ - Verify: npm test -- analytics && node scripts/check-events.mjs && grep -q "Population filter:" docs/metrics.md
198
+ - Requirements: R-PRD-5, R-BIZ-3, R-BIZ-20
199
+ - [ ] GP-xxx Define business metrics once with fixture tests
200
+ - Files: src/metrics/definitions.ts, src/metrics/definitions.test.ts
201
+ - Acceptance: MRR, active users, churn, and conversion each have one exported definition every report imports; fixtures cover annual normalization, a three-seat subscription, a recurring discount, tax and a one-time charge excluded, a past-due and a trialing subscription, a refund, a contraction, two currencies, and an internal account; fixtures also cover the start-of-period churn denominator, one population for conversion, a closed account in a past cohort, and a half-open window boundary
202
+ - Verify: npm test -- definitions
203
+ - Requirements: R-BIZ-22
204
+ - [ ] GP-xxx Add the typed flag wrapper and runtime kill switches
205
+ - Files: src/flags/flags.ts, src/flags/definitions.json, src/flags/flags.test.ts
206
+ - Acceptance: every flag read goes through flags.ts, which falls back to production behavior and alerts; each definition has an owner and expiry; a test flips the payments kill switch at runtime and asserts the next request and the next job run take the off path without a restart
207
+ - Verify: npm test -- flags && ! grep -rn "process.env.FEATURE_" src/ | grep -v flags.ts
208
+ - Requirements: R-BIZ-23
209
+ - [ ] GP-xxx Route customer feedback and cancellation reasons to a monitored destination
210
+ - Files: src/feedback/submit.ts, src/feedback/submit.test.ts, src/billing/cancel-reasons.ts, src/config/startup.ts
211
+ - Acceptance: each surface posts to a destination and reader set per environment, and production startup rejects placeholder destinations; submissions carry user, account, plan, page, and app version from the session; cancellation reasons are stored with account, plan, tenure, and date; a delivery test per surface proves the submission reaches its destination
212
+ - Verify: npm test -- feedback
213
+ - Requirements: R-BIZ-26
214
+ - [ ] GP-xxx Record the bet's kill criterion for the decider's review
215
+ - Files: docs/decisions/bet.md
216
+ - Acceptance: the file states the bet, its R-PRD-9 assumption ids, the register metric, the minimum exposure, the threshold and its source, the decide-by point, the decider, and the three actions; it ends with `Verdict: pending`, which only the decider changes at the scheduled review
217
+ - Verify: grep -q "^Verdict: pending$" docs/decisions/bet.md && grep -q "^Decide-by:" docs/decisions/bet.md && grep -q "^Decider:" docs/decisions/bet.md
218
+ - Requirements: R-BIZ-1
219
+
220
+ ## Self-audit rubric
221
+
222
+ 100 points total. Below 85 total, revise before emission. A dimension whose requirements are all dropped leaves the denominator, and the rest re-normalize to 100.
223
+
224
+ Floor: when the plan charges money, R-BIZ-7 through R-BIZ-16 each bind wherever their own condition holds. Only an archetype-layer drop that cites the decision removing the condition counts; any other disposition, a scale-layer drop included, caps the module at 69. R-BIZ-5, R-BIZ-6, and R-BIZ-17 hold the same floor wherever their conditions hold, charging or not. Together they design out productauditor's five Critical classes, and a plan that would charge customers wrongly, refuse what they paid for, run a trial nothing ends, sell what does not exist, or lose their data cannot grade well however good the rest is.
225
+
226
+ - Director lens (15): R-BIZ-1 to R-BIZ-4 landed in the form their scale allows: the bet as a decision with a falsifier carrying metric, exposure, pre-set threshold, milestone-anchored decide-by point, decider, and three actions, recorded as `Verdict: pending`; model, segment, motion, free offer, and priced tiers with validated or decided prices; principles that cost something and are cited; commercial decider rows.
227
+ - Claims and committed numbers (10): R-BIZ-5 and R-BIZ-6 landed: every claim traced, including support promises and guarantees; no mock or stub on a production path; one constant per committed number; the paid-feature reachability check in the final Verification phase.
228
+ - Plans and entitlements (15): R-BIZ-7 to R-BIZ-10 landed with their named tests: one catalog with provider parity on amount, coupon limits, and legacy keys; server-resolved price with the comparison and tampered-request tests; one entitlement mapping over prices and statuses with a free default; one gate helper with every call site checked.
229
+ - Billing lifecycle (20): R-BIZ-11 to R-BIZ-16 landed with their named tests: confirmed-payment grants and live-mode checks; the provider-named event table with replay, ordering, refund, and reconciliation; one change function with timing and proration; enforced trial end, sourced grace, and the provider's final state; server-side seats and usage; members and data kept read-only through a lapse.
230
+ - Accounts and operations (10): R-BIZ-17 to R-BIZ-19 landed: workspace-owned shared work, last-owner guard, and transfer; closure stops every scheduled effect; export covers every content type beyond one page; support operations as production admin actions; deals as override records.
231
+ - Metrics and definitions (15): R-BIZ-3 and R-BIZ-20 to R-BIZ-22 landed: one register that resolves every north-star, input, guardrail, success, kill, and experiment metric; typed events sent once from the server; identity, consent, and per-environment keys; one definition per business metric with fixture tests.
232
+ - Release, experiments, and signals (15): R-BIZ-23 to R-BIZ-26 landed: a typed flag wrapper with a runtime kill-switch test on requests and jobs; deprecation, breaking-change, and release-note obligations with sourced notice periods; experiments with unit, exposure, exclusion, decision rule, and cleanup; every customer-signal surface reaches a named reader with session context.
233
+
234
+ ## Anti-patterns refused
235
+
236
+ - Strategy theater: a vision paragraph and a bet with no kill criterion, decide-by point, or decider, or a verdict an executing agent fills in after launch. Refusal: R-BIZ-1.
237
+ - Principles nobody pays for: "simple, fast, delightful", or "reliability over outages", where no product would choose the other side. Refusal: R-BIZ-4.
238
+ - Invented price: a price point chosen at plan time with no source, user answer, decision, or validation task. Refusal: R-BIZ-2.
239
+ - Fiction pricing page: copy that lists features or limits no entitlement code reads. Refusal: R-BIZ-5 and R-BIZ-7.
240
+ - Display-only currency: a currency switcher that converts the shown price while checkout charges another currency. Refusal: R-BIZ-7 prices each currency sold.
241
+ - Paper paywall: a plan-gate helper never mounted on the API, or a check that runs only in the client. Refusal: R-BIZ-10 names and checks every call site.
242
+ - Fall-through to paid: an unknown or null plan treated as the top tier. Refusal: R-BIZ-9.
243
+ - Success-redirect grant: paid access set on the checkout success page or from a query parameter. Refusal: R-BIZ-11.
244
+ - Checkout-only webhook: a handler that switches only on checkout completion and logs everything else. Refusal: R-BIZ-12.
245
+ - Local-only cancel: a cancel button that flips local state and never calls the provider, so the customer keeps paying. Refusal: R-BIZ-13.
246
+ - The trial that never ends: a `trial_ends_at` written at sign-up and read only by a countdown banner. Refusal: R-BIZ-14.
247
+ - Downgrade that deletes: over-limit records or members removed when a plan lapses. Refusal: R-BIZ-16.
248
+ - KPI theater: a north star or MRR figure with no register entry, definition, or source event. Refusal: R-BIZ-3 and R-BIZ-22.
249
+ - Client-only revenue: purchase events sent from the browser after the redirect. Refusal: R-BIZ-20.
250
+ - A flag that fails open, or a kill switch read once at start: nothing stops at the moment it is needed. Refusal: R-BIZ-23.
251
+ - Deprecation with no date: an endpoint marked deprecated forever. Refusal: R-BIZ-24.
252
+ - Feedback to nowhere: a feedback widget or contact form posting to a placeholder or to a route nobody reads. Refusal: R-BIZ-26.
@@ -0,0 +1,165 @@
1
+ # Code quality planning module
2
+
3
+ Plans the code quality sections of PLAN.mdx: quality budgets, testing discipline, error handling, performance rules, dependency hygiene, docs, and observability hooks. The orchestrator loads this module for every archetype. Code quality is never excluded or deferred: a site with no application code scales it down to its build, lint, and link checks, and its applicability row stays `applicable` with a scale note.
4
+
5
+ ## Lineage
6
+
7
+ Descends from codeauditor, the read-only end-of-project audit that scores a codebase 0-100 across nine weighted dimensions (SEC 20, ARC 15, QUAL 15, TEST 15, ERR 10, PERF 8, DEP 7, DOC 5, OBS 5) and hunts paper constructs: uncalled validators, assertion-free tests, unconditional-200 health checks. This module inverts every one of those checks into a plan-time obligation. What carries over is the discipline, not the report format: evidence over assertion, the substitution test (a line that reads equally true for any project is filler), named failure modes, one-change-one-verification, and the hard-cap rule that a single Critical never averages away. Security-dimension checks (SEC) are owned by security.md; this module owns the other eight dimensions and cross-references SEC where the audit lenses overlap.
8
+
9
+ ## Decisions to force
10
+
11
+ 1. Typing strictness. Question: does the project run with the strictest type checking the language offers, or with escape hatches allowed? Hard to reverse because retrofitting strict mode onto a lax codebase means touching every file, and every untyped any that ships becomes load-bearing. Options: (a) strict from commit one, escape hatches require a recorded reason inline; (b) gradual strictness with a ratchet (new files strict, legacy grandfathered); (c) dynamic, no checker. Default: (a) for greenfield, (b) for brownfield. Never (c) where the language supports checking.
12
+
13
+ 2. Test determinism architecture. Question: are clock, randomness, and network injected as dependencies, or reached for globally? Hard to reverse because code that calls the wall clock or live network directly cannot be made deterministic without rewriting call sites; flakiness is designed in on day one. Options: (a) injected clock, seeded RNG, no live network in tests, order-independent suites; (b) ad hoc, mock later. Default: (a); (b) is refused.
14
+
15
+ 3. Error propagation policy. Question: do errors propagate with cause preserved to a boundary that can act, or get caught and logged where they occur? Hard to reverse because a swallow-and-continue idiom, once copied across handlers, is a systemic pattern the audit clusters as one root-cause finding with dozens of members. Options: (a) rethrow-with-cause to a named boundary layer, empty catches banned by lint rule; (b) per-module discretion. Default: (a).
16
+
17
+ 4. Quality budget numbers. Question: what are the maximum function length, file length, nesting depth, and parameter count, and which lint config enforces them? Hard to reverse because budgets adopted after growth require mass refactors; budgets adopted first shape every function written. Options: (a) concrete numbers in the plan wired to lint rules in CI; (b) team judgment. Default: (a) with starting values of 50-line functions, 400-line files, nesting depth 4, 5 parameters, adjusted per language idiom and recorded in the plan.
18
+
19
+ 5. Data-access discipline on hot paths. Question: which queries are on hot paths, and what pagination, batching, and index rules govern them? Hard to reverse because N+1 shapes and unpaginated list endpoints work fine at demo scale and fail at real scale, after clients depend on the response shape. Options: (a) hot paths named in the plan with per-path rules (eager load or batch, pagination on every list, index plan matching query shapes); (b) optimize when it hurts. Default: (a). Coordinates with database.md for the index plan itself.
20
+
21
+ 6. Dependency intake bar. Question: what must be true before a package is added? Hard to reverse because removing an entrenched dependency is a project; a floating version that breaks reproducibility poisons every future bisect. Options: (a) committed lockfile with pinned versions from the first commit, plus selection criteria (maintained, minimal transitive surface, one package per job, license fits distribution model) and an advisory-audit tool in CI; (b) install as needed. Default: (a).
22
+
23
+ 7. Docs-with-code coupling. Question: do docs update in the same change as the feature, or on a separate track? Hard to reverse because drift is cumulative and invisible: once README instructions stop matching the scripts, no single change is to blame and nobody owns the fix. Options: (a) same-change rule, stated in the plan and checked at review; (b) periodic docs sprints. Default: (a).
24
+
25
+ ## Plan requirements
26
+
27
+ R-CODE-1: PLAN.mdx declares project maturity, ambition, and deployment context (prototype, internal tool, or production service) in one sentence near the objective, because every quality bar in this module scales to that declaration and the end-of-project audit calibrates its grading to it.
28
+ Criterion: WHEN the plan is emitted, THE PLAN SHALL contain an explicit maturity declaration that names the deployment context, and every quality requirement that scales with maturity SHALL reference it rather than assume production defaults.
29
+
30
+ R-CODE-2: PLAN.mdx contains a layer diagram (mermaid graph TD) with the allowed dependency direction stated as a rule (which layer may import which), so the audit finding "presentation reaches straight into the database" is impossible by construction.
31
+ Criterion: WHEN architecture is planned, THE PLAN SHALL name each layer, state the one allowed dependency direction, and forbid layer-skipping imports as a lintable or reviewable rule.
32
+
33
+ R-CODE-3: PLAN.mdx assigns module boundaries and single responsibilities, and names one canonical pattern per feature kind (e.g. "new endpoints copy the shape of the first endpoint task") so similar features are built the same way instead of each reinventing the wheel.
34
+ Criterion: WHEN two or more tasks build features of the same kind, THE PLAN SHALL name the canonical exemplar task the later ones copy, and the later tasks SHALL reference it in their descriptions.
35
+
36
+ R-CODE-4: PLAN.mdx states where state and config live and the abstraction policy: repeated logic gets a shared helper, and no speculative indirection is built for problems the project does not have (over-engineering and under-abstraction are both audit findings).
37
+ Criterion: IF a task introduces an abstraction layer, THE PLAN SHALL record the concrete duplication or variation it resolves; IF none exists yet, THE PLAN SHALL defer the abstraction to an open question with a default of "inline until the second use."
38
+
39
+ R-CODE-5: PLAN.mdx sets numeric quality budgets (max function length, max file length, max nesting depth, max parameter count), bans magic values in favor of named constants, bans dead code, and names the single lint and format config that enforces all of it in CI.
40
+ Criterion: WHEN quality budgets are planned, THE PLAN SHALL state each budget as a number wired to a named lint rule, and the CI task SHALL list the lint command whose exit code enforces them.
41
+
42
+ R-CODE-6: PLAN.mdx defines the typing policy per decision 1: no untyped any, no unchecked casts, no disabled checks without a recorded inline reason, with the checker's strict flags named.
43
+ Criterion: WHEN the language supports static checking, THE PLAN SHALL name the checker, its strict configuration, and the escape-hatch rule; IF the project is brownfield, THE PLAN SHALL state the ratchet mechanism for legacy files.
44
+
45
+ R-CODE-7: PLAN.mdx defines the TODO/FIXME/HACK marker policy: every marker references a tracked issue, and a CI or review check prevents silent accumulation.
46
+ Criterion: IF a task's code may legitimately carry a deferred-work marker, THE PLAN SHALL require the marker to embed an issue reference, and SHALL name the grep or lint check that fails on bare markers.
47
+
48
+ R-CODE-8: PLAN.mdx enumerates the critical paths by name (authentication, authorization, payments, data mutations, anything irreversible) and requires tests for each critical path before the owning feature task can be checked off.
49
+ Criterion: WHEN critical paths exist, THE PLAN SHALL list them in the requirements section, and every task touching one SHALL carry a test acceptance criterion naming that path.
50
+
51
+ R-CODE-9: PLAN.mdx specifies test types per layer (unit, integration, e2e) and a test-quality bar: no assertion-free tests, no unreviewed snapshot-only tests, no over-mocked tests that test the mock; edge and error cases are planned alongside happy paths.
52
+ Criterion: WHEN testing is planned, THE PLAN SHALL map each layer to a test type with at least one named example per type, and SHALL state the assertion-quality rules as review criteria, not aspirations.
53
+
54
+ R-CODE-10: PLAN.mdx requires deterministic tests by design per decision 2: injected clocks, seeded randomness, no live network calls in tests, order independence; and wires the full suite into CI from the first commit so tests run automatically rather than existing unrun.
55
+ Criterion: WHEN the first test task is planned, THE PLAN SHALL already contain a CI task that runs the suite on every push, ordered before or in the same wave, and the determinism rules SHALL appear as acceptance criteria on the test scaffolding task.
56
+
57
+ R-CODE-11: PLAN.mdx never plans a coverage claim (badge, threshold, percentage) it does not also plan the machinery to maintain, because coverage drift between claim and reality is an audit finding.
58
+ Criterion: IF the plan includes any coverage number or badge, THE PLAN SHALL include the CI step that computes and enforces it; otherwise THE PLAN SHALL make no coverage claim.
59
+
60
+ R-CODE-12: PLAN.mdx defines the error-handling policy per decision 3: no swallowed errors, no empty catch blocks, no catch-log-and-continue where continuing is wrong, rethrow with cause preserved, errors surfaced at a named boundary where someone can act.
61
+ Criterion: WHEN error handling is planned, THE PLAN SHALL name the boundary layer that renders or reports errors, and SHALL state the lint rule or review check that bans empty catches and ignored error returns.
62
+
63
+ R-CODE-13: PLAN.mdx states an I/O policy: every network and disk call has a timeout, retries use backoff (no retry storms), and the policy names the helper or client configuration that applies it uniformly.
64
+ Criterion: WHEN any task performs network or disk I/O, THE PLAN SHALL require timeout and backoff values via the shared client or helper, not per-call-site improvisation.
65
+
66
+ R-CODE-14: PLAN.mdx identifies multi-step operations and specifies their transactional boundaries and rollback behavior, so partial completion cannot leave inconsistent state; and specifies resource cleanup patterns (finally, defer, context managers) for files, connections, locks, and threads including error paths.
67
+ Criterion: IF a planned operation mutates more than one record, file, or external system, THE PLAN SHALL state its transaction or compensation boundary, and the owning task SHALL carry a cleanup-on-error acceptance criterion.
68
+
69
+ R-CODE-15: PLAN.mdx names the hot paths and sets data-access rules per decision 5: no N+1 (eager load or batch), no queries inside loops, pagination on every list query, and an index plan matching intended query shapes (index details delegated to the database section).
70
+ Criterion: WHEN a task implements a list endpoint or a per-item lookup inside iteration, THE PLAN SHALL require pagination or batching respectively as a grep-verifiable acceptance criterion on that task.
71
+
72
+ R-CODE-16: PLAN.mdx carries the cache and queue decisions made upstream into code obligations rather than settling them a second time: a cached read path carries the tier, staleness budget, invalidation trigger, and stampede protection set by R-ARCH-23, and a queue carries the bounded depth and full policy set by R-ARCH-24 (whether a cache is warranted at all is R-ARCH-23's arithmetic, not a judgement made here). This module owns what those decisions imply in code: non-blocking I/O on request and hot paths, and a growth bound on every long-lived in-process structure (caches, queues, buffers get a max size or eviction rule).
73
+ Criterion: IF the plan introduces a cache, THE PLAN SHALL carry the four R-ARCH-23 fields on that read path rather than an invalidation rule alone; IF the plan introduces a queue, THE PLAN SHALL carry its R-ARCH-24 depth bound and full policy; IF the plan introduces any long-lived in-process collection, THE PLAN SHALL state its growth bound.
74
+
75
+ R-CODE-17: PLAN.mdx requires a committed lockfile with pinned versions and reproducible installs from the first commit, and states the dependency selection criteria and update cadence per decision 6, with an advisory-audit tool named in the CI task.
76
+ Criterion: WHEN the scaffold task is planned, THE PLAN SHALL include committing the lockfile in its acceptance criteria, and the CI task SHALL name the audit command (e.g. the ecosystem's advisory scanner) that runs on every push.
77
+
78
+ R-CODE-18: PLAN.mdx plans the README to contain setup, build, and run instructions that will be verified by following them, states the docs-update-with-feature rule per decision 7, and requires every shipped endpoint, flag, and env var to be documented, so no phantom or missing docs exist at audit time.
79
+ Criterion: WHEN the docs task is planned, THE PLAN SHALL include an acceptance criterion that a fresh clone reaches a running state using only the README, and every task that adds an endpoint, flag, or env var SHALL carry a docs line in its acceptance criteria.
80
+
81
+ R-CODE-19: PLAN.mdx specifies structured logging at boundaries with secret and PII redaction, metrics or tracing for critical operations, and health and readiness checks that verify real dependencies, never returning 200 unconditionally (the paper health check is a named audit refusal). Depth of the observability stack is owned by observe.md; this requirement guarantees the code-level hooks exist.
82
+ Criterion: WHEN a service archetype is planned, THE PLAN SHALL contain a task whose acceptance criteria include a health check that exercises at least one real dependency, and the logging task SHALL name the redaction rule.
83
+
84
+ R-CODE-20: PLAN.mdx specifies config separated from code with per-environment settings, a reproducible build, a documented run procedure, and a schema or data migration story, all scaled to the declared maturity from R-CODE-1.
85
+ Criterion: WHEN operability is planned, THE PLAN SHALL place config in environment or a config layer with per-env values, and IF the project has a schema, THE PLAN SHALL name the migration mechanism before the first schema task.
86
+
87
+ R-CODE-21: PLAN.mdx structures every deliverable as a small, atomic, independently verifiable task with a stated Verify command, mirroring the audit protocol of one finding, one change, verified; no task bundles unrelated changes.
88
+ Criterion: WHEN tasks are emitted, EVERY task SHALL have 2-4 grep-verifiable acceptance conditions and one Verify command whose exit code proves completion; IF a task cannot state such a command, THE PLAN SHALL split or respecify it.
89
+
90
+ R-CODE-22: PLAN.mdx contains no banned vague obligations: "improve error handling", "add more tests", "refactor for clarity", or any line failing the substitution test. Every quality obligation says what to change, where, and how to confirm it worked.
91
+ Criterion: WHEN the self-audit gate runs, THE PLAN SHALL contain zero recommendations of the banned forms, verifiable by grep for the banned phrases and by spot-checking that each quality line names a file, rule, or command.
92
+
93
+ R-CODE-23: PLAN.mdx keeps controls live and state machines lawful and time-correct: every operator-configurable or stored flag meant to gate behavior is planned with the code path that READS it (not only writes and displays it); every lifecycle state machine names its legal transitions and a rule that no transition frees a still-committed resource (inventory slot, access grant, credit hold) before its end or runs out of lifecycle order; and all scheduling and availability arithmetic uses the entity's configured timezone with daylight-saving handling, never server UTC.
94
+ Criterion: WHEN a control flag, a state machine, or a scheduling or availability feature is planned THE PLAN SHALL name the read site for each gating flag, the transition table with its resource-release guard, and the timezone source, each with a test (a flag set on that changes behavior, an illegal or early-release transition that is rejected, a non-UTC-timezone slot that lands on the local wall clock).
95
+
96
+ R-CODE-24: PLAN.mdx verifies behavioral requirements against the running app, not only by static reading or unit tests. The class of requirement that static inspection can state but not prove (race conditions and TOCTOU, dead controls that are stored but never read, lifecycle transitions that free a resource early, authorization on non-primary caller paths, and consent or accessibility behavior that appears only at runtime) is confirmed in the Verification phase by an end-to-end or browser harness driving the real flow.
97
+ Criterion: WHEN a requirement is behavioral (concurrency, a gating flag, a state transition, a non-primary caller path, or runtime consent or accessibility) THE PLAN SHALL include an end-to-end or browser test that drives the real flow and asserts the expected outcome, not only a unit test or static grep.
98
+
99
+ ## Task seeds
100
+
101
+ - [ ] GP-xxx Wire lint, format, and type checking into CI with quality budgets
102
+ - Files: .github/workflows/ci.yml, eslint.config.js (or ruff.toml, .golangci.yml per stack), tsconfig.json
103
+ - Acceptance: lint config sets max function length, max nesting, and no-magic-numbers rules with the numbers from the Decisions section; type checker runs in strict mode with zero suppressions; CI fails on any lint or type error; a stack without ESLint or tsc puts its own lint and type-check commands in Verify
104
+ - Verify: npx eslint . && npx tsc --noEmit
105
+ - Requirements: R-CODE-5, R-CODE-6, R-CODE-7
106
+
107
+ - [ ] GP-xxx Scaffold deterministic test harness and run it in CI
108
+ - Files: tests/helpers/clock.ts, tests/helpers/seed.ts, tests/setup.ts, .github/workflows/ci.yml
109
+ - Acceptance: test setup injects a fake clock and seeded RNG; network access in tests fails fast by default; CI workflow runs the full suite on every push; at least one example test per layer (unit, integration) exists with real assertions
110
+ - Verify: npm test -- --run && test -z "$(grep -rLE --include='*.test.ts' 'expect\(' tests/)"
111
+ - Requirements: R-CODE-9, R-CODE-10, R-CODE-11
112
+
113
+ - [ ] GP-xxx Establish error boundary and I/O policy helpers
114
+ - Files: src/lib/errors.ts, src/lib/http-client.ts, src/middleware/error-handler.ts
115
+ - Acceptance: shared HTTP client sets a default timeout and backoff retry; error handler is the single boundary that logs with cause chain and returns generic client-facing messages; lint rule banning empty catch blocks is enabled
116
+ - Verify: ! grep -rnE 'catch *(\([^)]*\))? *\{ *\}' src/ && grep -q timeout src/lib/http-client.ts
117
+ - Requirements: R-CODE-12, R-CODE-13
118
+
119
+ - [ ] GP-xxx Write critical-path tests for auth and data mutations
120
+ - Files: tests/integration/auth.test.ts, tests/integration/mutations.test.ts
121
+ - Acceptance: every critical path named in the Requirements section has at least one test asserting both the success case and one failure case; no test relies on wall-clock time or live network; tests pass in CI
122
+ - Verify: npm test -- --run tests/integration/
123
+ - Requirements: R-CODE-8, R-CODE-9, R-CODE-10
124
+
125
+ - [ ] GP-xxx Pin dependencies and add advisory audit to CI
126
+ - Files: package-lock.json (or the ecosystem lockfile), .github/workflows/ci.yml
127
+ - Acceptance: lockfile committed; no floating major versions in the manifest; CI runs the ecosystem advisory scanner and fails on known-vulnerable versions; no two packages doing the same job in the manifest
128
+ - Verify: npm ci && npm audit --audit-level=high
129
+ - Requirements: R-CODE-17
130
+
131
+ - [ ] GP-xxx Implement real health check and structured logging hooks
132
+ - Files: src/routes/health.ts, src/lib/logger.ts
133
+ - Acceptance: health endpoint queries at least one real dependency (database ping or equivalent) and returns non-200 when it fails; logger emits structured output with a redaction list covering secrets and PII fields; no console.log calls outside the logger module
134
+ - Verify: test -f src/lib/logger.ts && ! grep -rn --include='*.ts' 'console.log' src/ | grep -v lib/logger
135
+ - Requirements: R-CODE-19, R-CODE-20
136
+
137
+ - [ ] GP-xxx Verify README from a clean clone
138
+ - Files: README.md, scripts/dev.sh
139
+ - Acceptance: README setup, build, and run sections name the exact commands from package scripts; following them from a fresh clone reaches a running state; every shipped env var appears in the configuration section
140
+ - Verify: bash -n scripts/dev.sh && node -e "const s=require('./package.json').scripts||{};const m=require('fs').readFileSync('README.md','utf8').match(/npm (run [A-Za-z0-9:_-]+|start|test)/g)||[];process.exit(m.length&&m.every(c=>s[c.replace(/^npm (run )?/,'')])?0:1)"
141
+ - Requirements: R-CODE-18
142
+
143
+ ## Self-audit rubric
144
+
145
+ Score the emitted code quality sections 0-100. Any dimension below its full-marks bar drags the module score; below 85 total, revise before emission.
146
+
147
+ - Budgets and typing (20): full marks when every quality budget is a number wired to a named lint rule, the typing policy names the checker and strict flags, the marker policy names its enforcement check, and all of it appears in a CI task's Verify line.
148
+ - Testing discipline (20): full marks when critical paths are enumerated by name, each has a test obligation on its owning task, test types map to layers with examples, determinism rules are acceptance criteria on the harness task, and CI runs the suite from the first wave.
149
+ - Error handling and resilience (15): full marks when the error boundary is named, empty catches are lint-banned, every I/O call inherits timeout and backoff from a shared helper, multi-step operations have stated transaction boundaries, and cleanup-on-error is an acceptance criterion where resources are held.
150
+ - Architecture conventions (15): full marks when the layer diagram exists with a stated dependency direction, canonical exemplar tasks are named for repeated feature kinds, and every abstraction in the plan cites the concrete duplication it resolves.
151
+ - Performance rules (10): full marks when hot paths are named, list queries carry pagination criteria, iteration-plus-query shapes carry batching criteria, and every cache or long-lived collection states its invalidation or growth bound.
152
+ - Dependencies (8): full marks when the lockfile commitment is in the scaffold task, selection criteria and update cadence are stated, and the advisory scanner is named in CI.
153
+ - Docs and drift (6): full marks when the README verification criterion exists, the docs-update-with-feature rule is stated, and endpoint, flag, and env var tasks carry docs lines.
154
+ - Operability hooks (6): full marks when the health check exercises a real dependency, logging is structured with a named redaction rule, and config, build, run, and migration stories match the declared maturity.
155
+
156
+ ## Anti-patterns refused
157
+
158
+ - Paper constructs: middleware defined but never mounted, validators never called, health checks returning 200 unconditionally, rate limiters that do not limit. The planner writes wiring proof into acceptance criteria (the grep that shows the middleware is applied), never just the artifact's existence.
159
+ - Assertion-free testing: tests that run without asserting, snapshot-only suites nobody reviews, mocks testing themselves. The planner refuses any test task whose acceptance criteria do not name what is asserted.
160
+ - Vague obligations: "improve error handling", "add more tests", "refactor for clarity". Refused outright; every obligation names the file, rule, or command and how to confirm it worked.
161
+ - Coverage theater: a badge or threshold claim with no CI machinery behind it. The planner either plans the enforcement step or plans no claim.
162
+ - Swallow-and-continue: empty catches and ignored error returns copied as an idiom. Refused by lint-banning the shape in the plan rather than hoping reviewers catch each instance.
163
+ - Averaging away risk: treating one Critical-grade gap as acceptable because other sections are strong. The source auditor caps the dimension at 69 and the overall at 79; the planner mirrors this by refusing to emit while any known Critical-class gap (untested critical path, no lockfile, no error boundary) remains unplanned.
164
+ - Substitution-test failures: quality prose that would read equally true for any project. Cut during the self-audit gate; only lines naming this project's paths, budgets, and commands survive.
165
+ - Silent scope widening: bundling unrelated cleanups into one task. Refused by the one-task-one-verifiable-change rule from R-CODE-21; extra work becomes its own task with its own Verify line.
@@ -0,0 +1,59 @@
1
+ # Compliance module: Anthropic Usage Policy gate and account safety
2
+
3
+ Loaded in Phase 1, before discovery, and standing for the whole session. Two halves: (A) rules for how this skill and its host agent use Claude, and (B) the plan-time gate applied to the project being planned. The point is practical: keep the user's account clean and keep the planned product on the right side of the Anthropic Usage Policy (anthropic.com/legal/aup, effective 2025-09-15), the Consumer Terms (anthropic.com/legal/consumer-terms), and the agent guidance at support.claude.com (article 12005017). Policies change; on compliance-sensitive projects, re-check those URLs rather than trusting this file's snapshot.
4
+
5
+ When this skill runs through a non-Claude provider, use this module as a conservative baseline and re-screen the project against that provider's current policy. Do not assume the policies are identical.
6
+
7
+ ## A. How the skill itself behaves
8
+
9
+ 1. **Never coach the model past a refusal.** Do not ask any model to ignore, work around, or bypass its guardrails; do not rephrase, fragment, or roleplay a refused request into innocuous-looking steps. Intentional guardrail bypass is a named Usage Policy violation. If a step is refused, route it to the human and move on.
10
+ 2. **Authentication hygiene.** Subscription credentials are used only through official clients and supported authentication flows. Never suggest extracting or reusing subscription tokens in third-party harnesses, scripts, or SDKs. Anything this plan schedules unattended (CI, cron, bots, background runs) must specify a supported service account, workload identity, or cloud-provider authentication flow. No account sharing, no reselling access, no parallel accounts to dodge limits, and no unattended background use of a consumer subscription.
11
+ 3. **Honest output.** No fabricated results, no presenting AI output as human-authored where disclosure is required. Where the planned product produces consumer-facing AI content, the plan carries the disclosure requirements from the gate below.
12
+ 4. **If a warning or suspension happens anyway**: use the appeal route shown while signed in to the restricted Claude account and follow the current Safeguards help-center guidance. Provide factual account and incident details. Do not create another account to evade enforcement.
13
+
14
+ ## B. The plan-time gate
15
+
16
+ Screen the project idea against these categories before discovery. Three outcomes:
17
+
18
+ - **Hard stop**: the core purpose is prohibited. Name the category, cite it, decline to plan. Examples: fake-review or engagement farms, phishing kits and lookalike domains, undisclosed AI persona networks, scrapers built to evade platform safeguards, malware and DDoS tooling, ban-evasion systems, voter-deception tooling.
19
+ - **Mitigate**: legitimate project, risky component. Plan it, and inject the matching mitigation requirements below as mandatory tasks with acceptance criteria.
20
+ - **Pass**: record "Compliance gate: pass" in the plan and move on. Do not lecture; one line suffices.
21
+
22
+ ### Prohibited-purpose checklist (hard stop when it is the core mechanic)
23
+
24
+ 1. **Deception**: fake reviews, comments, or engagement; fake personas; sites mimicking legitimate pages; phishing or social-engineering flows; AI output passed off as human.
25
+ 2. **Spam and ranking abuse**: mass unsolicited messaging; spam content generation at scale; manipulated rankings, traffic metrics, or polls; coordinated inauthentic behavior; click farming.
26
+ 3. **Dark patterns and predatory practices**: manipulative behavior-distortion techniques, exploitative lending, MLM and pyramid mechanics, abusive debt collection, exploiting age or disability or economic hardship.
27
+ 4. **Privacy and surveillance**: harvesting personal, health, or biometric data without consent; tracking individuals without notice; facial recognition without consent; mass surveillance; profiling on protected attributes.
28
+ 5. **Unauthorized access and malware**: backdoors, privilege escalation, credential abuse, botnets, DDoS, exploiting vulnerabilities without authorization. Authorized security work (pen tests with written permission, CTF, defensive tooling) is explicitly fine; the plan records the authorization.
29
+ 6. **Platform abuse**: bulk account creation, multi-account evasion, CAPTCHA and anti-bot circumvention at scale, scraping that violates a target's ToS or robots.txt.
30
+ 7. **Political manipulation**: voter or campaign micro-targeting, synthetic media of political figures, automated outreach to officials or voters that conceals its artificial origin.
31
+
32
+ ### Mitigation requirements (inject as plan tasks when the component applies)
33
+
34
+ - **Consumer-facing chatbot**: the product SHALL disclose that the user is interacting with AI, at minimum at session start. Acceptance: the disclosure string exists in the first-load UI path.
35
+ - **High-risk consumer domain** (legal, medical, financial, insurance, employment or housing eligibility, admissions, automated journalism): a qualified professional SHALL review outputs before dissemination, and AI involvement SHALL be disclosed. B2B internal tools are exempt; record which applies.
36
+ - **AI-generated content published at scale**: content SHALL be attributable and not plagiarized; where a platform requires AI labeling, the plan includes it.
37
+ - **Web automation and crawling**: the crawler SHALL honor robots.txt and the target's ToS, throttle requests, identify itself honestly in its user agent, and never operate multiple accounts on a third-party platform. Acceptance: rate limiter and robots.txt check exist as named components in the architecture section.
38
+ - **Outbound automated communications**: messages to people, officials, or support systems SHALL NOT conceal their artificial origin.
39
+ - **Products serving minors**: flag for Anthropic's additional minor-safety requirements and record the age-gating decision.
40
+ - **Anything running Claude unattended**: the task specifies a supported service account, workload identity, or cloud-provider authentication flow, never subscription credentials (see A2).
41
+
42
+ ### Do not over-block
43
+
44
+ The gate exists to catch real violations, not to harass legitimate work. Explicitly fine: authorized security testing and research, civic and policy research, B2B professional tools (exempt from the consumer disclosure duo), heavy individual use of a paid plan, automation and CI using supported workload authentication, adult themes in creative writing within policy, and competitive analysis. When a project is ambiguous, ask one clarifying question instead of refusing; record the answer in the plan.
45
+
46
+ ## What lands in the plan
47
+
48
+ One short section:
49
+
50
+ ```markdown
51
+ ## Compliance gate
52
+
53
+ Result: pass | mitigated | (hard stop never reaches a plan)
54
+ Screened: YYYY-MM-DD against anthropic.com/legal/aup (2025-09-15 version).
55
+ Mitigations injected: GP-xxx (AI disclosure banner), GP-yyy (crawler rate limiter). [omit line when pass]
56
+ Account safety: unattended runs use supported workload authentication; no subscription credentials outside official clients.
57
+ ```
58
+
59
+ Proportionate, checkable, done.