@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,156 @@
1
+ # Security and hardening planning module
2
+
3
+ Plans the Security and hardening sections of PLAN.mdx by moving secauditor controls into explicit requirements, tasks, and reproduced-attack checks before implementation. The finished project still requires runtime verification and an independent audit. The orchestrator loads this module for every archetype and never excludes or defers it: a fully offline library with no network surface, auth, persistent data, secrets, CI/CD, containers, or LLM calls scales it down, declaring each absent surface under R-SEC-2.
4
+
5
+ ## Lineage
6
+
7
+ Descends from secauditor (an 11-dimension read-only vulnerability audit anchored to OWASP 2025/2021, API Top 10 2023, ASVS, NIST, SLSA, and the OWASP LLM Top 10, with source-to-sink evidence, per-dimension paper-control hunting, and a fixed automatic-Critical list that caps the overall score at 79) and harden-ready (post-deploy adversarial verification: reproduced-attack OWASP walkthroughs, control-to-code compliance mapping, class-not-instance hardening, and a functioning disclosure program). Two disciplines carry over. First, no control is planned without its wiring point and a test that proves it fires, because both ancestors hunt declared-but-unwired controls by name. Second, the automatic-Critical conditions are designed out at plan time, because any single one (user-settable role, unsigned JWT acceptance, fast-hashed passwords, live committed secret, open database ingress, prompt injection into a shell sink) invalidates every other point earned.
8
+
9
+ ## Decisions to force
10
+
11
+ 1. Authorization model and ownership boundary. What single mechanism decides who may touch which record, and where does it live? Hard to reverse because retrofitting ownership means rewriting every query and handler after data exists, and IDOR is the highest-weighted audit dimension (AUTHZ, 18%). Options: central deny-by-default policy middleware with ownership predicates inside the query (default); database row-level security (default for multi-tenant on Postgres or Supabase); scattered per-route checks (refused: new handlers silently bypass a blocklist). Multi-tenant designs must also pick the tenant-scoping mechanism now: R-DB-19 owns the isolation form; an ORM filter on the session's tenant id is defense in depth, never the only control, and tenant id never comes from a client-supplied header.
12
+ 2. Identity architecture. Server-side sessions, self-managed JWTs, or a hosted identity provider, and which password KDF? Hard to reverse because token formats leak into every client and stored hashes cannot be migrated without a login-time upgrade path. Options: hosted OIDC provider with Authorization Code + PKCE (default when the budget allows); server-side sessions with CSPRNG ids (default for classic web apps); self-managed JWT with a strict algorithm allowlist (only with a stated reason). KDF: argon2id default; scrypt, bcrypt, or PBKDF2-HMAC-SHA256 at current cost floors acceptable; anything faster is an automatic Critical.
13
+ 3. Secrets sourcing and rotation. Where do secrets live, and how do they rotate? Hard to reverse because anything ever committed is permanent in git history and must be rotated, not deleted. Options: cloud secrets manager with the SDK wiring named in the plan (default for deployed apps); platform-injected env vars (acceptable for small deployments); committed dotfiles (refused). Decide the CI credential mode now: OIDC federation over long-lived static cloud keys.
14
+ 4. Data classification and encryption-at-rest scope. Which fields are sensitive or regulated, and does the deletion story reach backups, caches, indexes, and logs? Hard to reverse because retrofitting encryption and erasure onto populated stores and shipped backups is a migration project. Options: classify at schema-design time and pick the regime from the data, PCI, GDPR, HIPAA, or SOC 2 (default when regulated data exists); an explicit "no regulated data" declaration with reason (acceptable).
15
+ 5. Deployment context and surface set. Internet-facing, internal, or local-only, and which conditional surfaces exist: API, uploads, outbound fetches, webhooks, containers/IaC, LLM calls? Every downstream security requirement calibrates against this; an undeclared surface becomes an unplanned control set discovered missing at audit. Default: declare every surface as present or absent in the plan, with a reason per absence.
16
+
17
+ ## Plan requirements
18
+
19
+ 1. R-SEC-1: The plan contains a threat-model subsection mirroring secauditor Phase 1: entry points (routes, webhooks, uploads, queue consumers, LLM inputs, CLI/env), trust boundaries (R-ARCH-13 when landed, else listed here) with their enforcement mechanism, sensitive assets, and principals/roles with what each may and may not do, plus a STRIDE pass per important boundary.
20
+ Criterion: WHEN the security section is emitted THE PLAN SHALL enumerate entry points, enforced trust boundaries, sensitive assets, and principals, and SHALL declare deployment context (internet-facing, internal, local) and data sensitivity.
21
+ 2. R-SEC-2: The plan declares every conditional security surface (web/API, auth, DB, uploads, outbound fetches, containers/IaC, CI/CD, AI/LLM, regulated data) as present or absent so conditional control sets are planned, never discovered missing.
22
+ Criterion: IF a surface is declared absent THE PLAN SHALL state the reason here and drop requirements only it needs in the module disposition (`dropped-by archetype`); IF present THE PLAN SHALL carry that surface's requirements onto tasks.
23
+ 3. R-SEC-3: The plan specifies a central deny-by-default authorization layer every route passes through, and object-level authorization binding each load and mutation to the current user or tenant inside the query itself (findOne({id, ownerId}) pattern or RLS), explicitly covering PUT/PATCH/DELETE, list, search, and export endpoints, plus a cross-tenant isolation test for multi-tenant designs.
24
+ Criterion: WHEN any resource endpoint is planned THE PLAN SHALL name the ownership predicate in the query and the middleware it mounts behind, and SHALL include a task whose test proves a cross-user request returns 403 or 404.
25
+ 4. R-SEC-4: The plan specifies server-side role checks on every admin or privileged route with mutating verbs guarded identically to their GET siblings, bans request-settable role/isAdmin/scope/tenant/plan/price fields, and mandates allowlist DTO binding for all writes (create and update) plus explicit response DTOs for all reads (no raw ORM objects, no fields='__all__').
26
+ Criterion: WHEN a privileged route or a write endpoint is planned THE PLAN SHALL name the enforced role check and the field allowlist, and SHALL never rely on UI hiding as the control.
27
+ 5. R-SEC-5: The plan states trust placement rules: JWT claims used only after signature verification, CORS never used as access control, client-supplied identity headers never trusted, signed URLs and storage keys scoped to the requester.
28
+ Criterion: WHEN tokens, CORS, or client headers appear in the design THE PLAN SHALL state where verification happens before any claim is trusted.
29
+ 6. R-SEC-6: The plan names the password KDF with per-user salts, requires constant-time comparison for every credential, token, MFA code, and webhook HMAC check, plans per-account and per-IP throttling with lockout on login, MFA-verify, and reset (routes mounted behind the limiter, not before it), breached-password screening, and recovery flows with CSPRNG single-use short-lived reset tokens, generic auth errors, and no default credentials or env==dev auth bypass branches.
30
+ Criterion: IF the project has an auth surface THE PLAN SHALL name the KDF, the constant-time comparison function, and the rate-limit placement relative to route mounting.
31
+ 7. R-SEC-7: The plan specifies the session or token design: CSPRNG session ids regenerated on privilege change, absolute and idle timeouts, server-side invalidation on logout, Secure/HttpOnly/SameSite cookies with the token never also exposed to JavaScript; for JWTs, an explicit algorithm allowlist rejecting alg:none and RS256-to-HS256 confusion with signature/exp/iss/aud validated; for OAuth/OIDC, Authorization Code + PKCE only with exact-match redirect_uri and session-bound state and nonce; MFA, if planned, enforced server-side on the actual auth path with no bypass route.
32
+ Criterion: WHEN sessions, JWTs, or OAuth are planned THE PLAN SHALL specify each listed property, and SHALL reject Implicit and Password grants.
33
+ 8. R-SEC-8: The plan mandates parameterized queries with values passed separately (never pre-substituted), allowlists for dynamic identifiers (table, column, ORDER BY), argv-array process invocation with the shell disabled and -- separators for input-derived arguments, and re-encoding at every use of stored data in queries, commands, or templates: "came from the database" confers no trust.
34
+ Criterion: WHEN any data access or process invocation is planned THE PLAN SHALL name the parameterized API and forbid string-built queries and shell=True equivalents.
35
+ 9. R-SEC-9: The plan sets auto-escaping templating as the default with a documented review gate for every raw-HTML escape hatch (|safe, dangerouslySetInnerHTML, v-html), forbids eval/exec/new Function/template compilation on user input, requires same-origin validation for redirect targets (?next=), and non-polluting merge utilities guarding __proto__.
36
+ Criterion: IF the project renders HTML THE PLAN SHALL list the permitted escape hatches with their review gate, and SHALL forbid DOM sinks fed by location or postMessage.
37
+ 10. R-SEC-10: The plan requires, for every outbound fetch of a user-influenced URL, a scheme and host destination allowlist with RFC1918/loopback/link-local/metadata-IP blocking and post-redirect resolved-IP re-checks (never a hostname blocklist); path canonicalization plus base-directory containment for every input-derived filesystem path including archive extraction; a ban on native deserialization of untrusted bytes in favor of data-only formats with schema validation; and DTDs and external entities disabled on every XML parser, not just one.
38
+ Criterion: WHEN webhooks, import-from-URL, uploads, or parsers are planned THE PLAN SHALL name the allowlist, the canonicalization call, and the safe-parser API per surface.
39
+ 11. R-SEC-11: The plan specifies crypto upfront: AEAD only (AES-GCM or ChaCha20-Poly1305), unique per-encryption nonces, CSPRNG for all security randomness, no home-rolled crypto, adequate key sizes (RSA >= 2048, EC >= P-256), keys from KMS or env with a key-id rotation scheme the code honors, TLS 1.2+ for all sensitive transit including internal DB and cache links, HSTS, and a hard rule that certificate validation is never disabled in any branch or client, including dev-reachable ones.
40
+ Criterion: WHEN encryption, signing, or transport is planned THE PLAN SHALL name the algorithm, the key source, and the rotation scheme, and SHALL contain the never-disable-verification rule verbatim as a task acceptance condition.
41
+ 12. R-SEC-12: The plan classifies sensitive data and specifies encryption at rest including backups, Cache-Control: no-store on sensitive responses, and no sensitive data in URL query strings or logs.
42
+ Criterion: IF PII, PHI, PAN, credentials, or tokens are stored THE PLAN SHALL map each class to its at-rest protection and its logging exclusion.
43
+ 13. R-SEC-13: The plan names the secrets source with SDK wiring (not just docs), gitignore entries for all credential file types before the first commit, no hardcoded fallback keys, a rotation procedure with the rule that anything ever committed is rotated rather than deleted, no client-exposed server secrets (NEXT_PUBLIC_/REACT_APP_/VITE_ prefixes), no secrets in Docker layers (--mount=type=secret), and CI secret refs never echoed, preferring OIDC federation over static keys.
44
+ Criterion: WHEN any credential is needed THE PLAN SHALL state where it lives, how code reads it, and how it rotates, with no fallback literal anywhere.
45
+ 14. R-SEC-14: The plan includes secret scanning (gitleaks, detect-secrets, or trufflehog) in pre-commit and CI, configured to fail the build, scanning full git history, with no continue-on-error, no || true, and no mass-allowlisted baseline.
46
+ Criterion: WHEN CI is planned THE PLAN SHALL contain a task whose Verify command runs the scanner and whose acceptance forbids soft-fail flags in the workflow file.
47
+ 15. R-SEC-15: The plan specifies the global security-header set (enforcing CSP without unsafe-inline or unsafe-eval, HSTS with HTTP-to-HTTPS redirect, nosniff, frame-ancestors, Referrer-Policy) mounted before the routes with a test asserting presence; a strict exact-match CORS allowlist (no reflection, no wildcard with credentials, null origin rejected); and production configuration with debug defaulting off, generic error handlers covering all exception types, no exposed Swagger, GraphQL introspection, Actuator, phpinfo, .git, or .env, no default keys, TRACE off, and secure cookie defaults not overridable later in the stack.
48
+ Criterion: WHEN the web surface is planned THE PLAN SHALL include a header-presence test task and SHALL state the CORS allowlist mechanism as exact string match.
49
+ 16. R-SEC-16: The plan sets resource controls per endpoint class: rate limits on auth, reset, OTP, search, export, and expensive endpoints; request body-size limits; server-enforced max page sizes; abuse quotas on operator-cost actions (SMS, email, LLM spend), separate from quotas a plan sells (R-BIZ-10); and upload handling with an extension allowlist plus magic-byte validation, size caps, sanitized filenames, and storage outside the web root.
50
+ Criterion: IF uploads or costly endpoints exist THE PLAN SHALL name the limit values or their config location per endpoint class, not a single global limiter.
51
+ 17. R-SEC-17: The plan requires committed lockfiles installed with integrity-enforcing commands (npm ci, yarn --immutable, pip --require-hashes), digest-pinned base images, third-party CI actions pinned to full commit SHAs, private-registry pinning for internal package names, an ignore-scripts policy in CI and Docker, no curl|sh installs without checksums, SCA gating CI on new high or critical advisories, SBOM generated at build from the real graph, and signed artifacts pulled by immutable digest.
52
+ Criterion: WHEN dependencies or CI are planned THE PLAN SHALL name the integrity-enforcing install command and SHALL forbid floating action tags and || true on audit steps.
53
+ 18. R-SEC-18: The plan specifies CI/CD access control: least-privilege job tokens (no write-all), environment-protection gates before prod with no self-approval, enforce_admins on, force-push to protected branches blocked, and no pull_request_target or workflow_run patterns that run fork code with secrets in scope.
54
+ Criterion: WHEN a deployment pipeline is planned THE PLAN SHALL state the token permission block and the protection rules as task acceptance conditions.
55
+ 19. R-SEC-19: For API surfaces, the plan covers the API Top 10 residue: GraphQL depth, complexity, and cost limits with introspection off in prod; an API inventory tied to the OpenAPI or GraphQL schema with a version-retirement policy (no stale /v1 or /internal mounts with weaker auth); anti-automation on high-value business flows; hardened outbound clients (TLS verify on, timeouts, bounded redirects that cannot leak bearer tokens); and webhooks secured both ways: inbound receivers verify the provider HMAC with replay protection, outbound senders sign payloads and pass the SSRF allowlist.
56
+ Criterion: IF an API surface exists THE PLAN SHALL contain each applicable control with its enforcement point, and SHALL include version retirement in the roadmap phases.
57
+ 20. R-SEC-20: The plan enumerates security events to log (auth success and failure, logout, reset, MFA, token issuance, 403 denials, payments, role grants, admin CRUD, bulk export, deletion) with actor, action, target, source IP, correlation id, UTC timestamp, and outcome at a level not dropped in production; log safety at the logging layer itself (redaction in every formatter, CR/LF neutralization, append-only shipping the app's own account cannot rewrite); and alerting on auth-failure spikes and privilege escalation routed to a monitored channel.
58
+ Criterion: WHEN logging is planned THE PLAN SHALL list the event enumeration verbatim and SHALL place redaction in the shared formatter, not per call site.
59
+ 21. R-SEC-21: If regulated data is planned, the plan picks the regime from the data (PCI, GDPR, HIPAA, SOC 2) and specifies a data classification map, minimization, retention and deletion jobs whose erasure reaches backups, caches, indexes, and logs, consent enforcement in code, audited reads of regulated records, bounded third-party sharing, and DSAR code paths.
60
+ Criterion: IF regulated data exists THE PLAN SHALL map each control to a named code path or job, never to a policy document alone.
61
+ 22. R-SEC-22: If containers, K8s, or IaC are planned, the plan specifies non-root digest-pinned minimal images with HEALTHCHECK and no layer secrets; K8s securityContext defaults (runAsNonRoot not overridden per-container, allowPrivilegeEscalation false, readOnlyRootFilesystem, drop ALL capabilities), least-privilege RBAC, default-deny NetworkPolicy, and Pod Security Admission at enforce; no public buckets (public-access-block attached), no 0.0.0.0/0 to SSH, RDP, or databases, no wildcard IAM, IMDSv2 on the templates actually used; and IaC plus image scanning in CI blocking on high or critical with no soft-fail.
62
+ Criterion: IF container or IaC files are planned THE PLAN SHALL carry these as task acceptance conditions on the files that will exist, with the scanner gate in CI.
63
+ 23. R-SEC-23: If LLM features are planned, the plan specifies role-separated prompt construction treating all retrieved, fetched, and tool content as untrusted; validation of model output before any sink (never into eval, shell, SQL, HTML, or URLs unvalidated); per-action authorization plus human-in-the-loop gating every call (not just the first) for high-impact tools with scoped per-user credentials; max-iteration and cost budgets on agent loops; no secrets or authorization rules living only in the system prompt; ACL and tenant filters inside the vector similarity query itself; pinned hash-verified model sources; and per-user rate, token, and spend limits.
64
+ Criterion: IF the project calls an LLM THE PLAN SHALL trace each model input to its trust label and each model output to its validated sink, and SHALL name the loop budget values.
65
+ 24. R-SEC-24: The plan adopts the anti-paper-control rule: every security control is specified with where it wires onto the execution path and a test proving it fires (a request that should 403, a header-presence assertion, a scanner that fails the build); and the plan designs out every automatic-Critical condition: no user-settable role fields, no unsigned-JWT acceptance, no fast-hashed or reversible passwords, no committed live secrets, no public buckets or open database ingress, no prompt-injection path into shell, eval, or SQL.
66
+ Criterion: WHEN any security control appears in the plan THE PLAN SHALL pair it with its mount point and its firing test; IF a design choice would create an automatic-Critical condition THE PLAN SHALL be revised before emission.
67
+ 25. R-SEC-25: The plan's final verification phase includes hardening checks in the harden-ready mold: reproduced-attack verification (a real cross-tenant request, a JWT alg:none rejection check, an RLS check via the anon-key endpoint where applicable), a disclosure baseline (SECURITY.md plus /.well-known/security.txt with a named inbox owner for deployed apps), class-level regression guards for any finding class fixed during the build, and a continuous cadence with a next execution date.
68
+ Criterion: WHEN the Verification phase is emitted THE PLAN SHALL name the exact commands or requests that reproduce each check, and SHALL not accept scanner output alone as the posture.
69
+
70
+ 26. R-SEC-26: For `public_release: true`, hardening emits revision-bound evidence that a later prepublication gate can verify. Every Critical finding has a status; a permitted acceptance has owner, justification, accepted_at, and expires_at; regulated hard gates remain non-bypassable. Any hardening evidence change invalidates a prior pass. Projects without a public release surface do not inherit a public-activation requirement.
71
+ Criterion: WHEN public release is planned THE PLAN SHALL schedule a fresh content hash or immutable hardening revision after all findings work and SHALL block activation on mismatched evidence, unresolved Criticals, incomplete or expired acceptance, or a regulated hard gate.
72
+
73
+ 27. R-SEC-27: The plan requires authorization parity across every caller path to a privileged operation, not only the primary interactive one. It enumerates the paths a backend function can be reached through (interactive session, API key or bearer token, a publicly exported function, an action whose authorization runs in a non-writable query context, and any agent or tool call) and specifies that the same authentication, tenant-suspension and soft-delete, step-up or MFA, and role gates apply on each. Suspension and step-up are enforced at the data or function tier, not only in a page or edge gate.
74
+ Criterion: WHEN a privileged operation is planned THE PLAN SHALL list every caller path that reaches it and SHALL require an identical gate on each, with a test that drives the operation through the non-primary path (an API key after tenant suspension, a token before MFA, the raw exported function) and asserts denial.
75
+ 28. R-SEC-28: The plan requires that any caller-supplied selector (id, email, slug, or hostname from the request body, query, or model output) that resolves a record is ownership-bound to the authenticated principal before the record is read, charged, mutated, or state-transitioned; for an email or hostname the caller must additionally prove control (a verified session or an out-of-band confirmation), and public checkout, unauthenticated verification, and agent or tool arguments are named as the highest-risk cases.
76
+ Criterion: WHEN a function resolves a record from caller-supplied input THE PLAN SHALL require a tenant or owner check binding it to the caller, SHALL forbid attaching or charging an existing party by unverified email, and SHALL include an IDOR and confused-deputy test (a cross-tenant id, a foreign email, a model-named id) that asserts denial.
77
+ 29. R-SEC-29: The plan handles consent and regulated-data governance when a consent regime or regulated data is present: consent or a lawful basis is captured before any non-essential cookie or third-party tracker fires; a genuine reject or opt-out exists and is honored in server code and in analytics or tag initialization, not only in the UI; and governance records exist in the repository or plan (a data classification or record of processing, data-processing or business-associate agreements for processors that receive regulated data, a cross-border transfer basis, and a stated regulated-data scope that minimizes what is stored or transmitted).
78
+ Criterion: WHEN the product sets non-essential trackers or processes regulated personal, card, or health data THE PLAN SHALL require consent-before-tracking with a server-honored opt-out and SHALL name the governance records (classification or ROPA, DPA or BAA, transfer basis, scope boundary) as plan artifacts with a Verify line.
79
+ 30. R-SEC-30: The plan identifies the applicable compliance frameworks by where the product's users live and what data it handles, not only where the business sits, and maps each to the controls that evidence it: privacy and sovereignty (GDPR, CCPA/CPRA, PIPEDA), accessibility (WCAG 2.2 AA, AODA, ADA/Section 508), security frameworks (SOC 2 Trust Services Criteria, ISO/IEC 27001), and industry standards (PCI DSS, HIPAA). It frames each as technical-readiness, the code-evidenced controls, never as a certification claim, and marks frameworks whose regulated surface is absent as not-applicable with a reason.
80
+ Criterion: WHEN regulated users, data, or an accessibility obligation exist THE PLAN SHALL enumerate the applicable frameworks with the controls or requirements that evidence each, SHALL mark absent surfaces not-applicable with a reason, and SHALL frame conformance as technical-readiness rather than certification.
81
+
82
+ ## Task seeds
83
+
84
+ - [ ] GP-xxx Central deny-by-default authorization layer
85
+ - Files: src/middleware/authorize.ts, src/policies/index.ts, src/app.ts
86
+ - Acceptance: authorize middleware mounted before all route registrations; every resource query includes an ownership or tenant predicate; unmatched routes resolve to deny
87
+ - Verify: grep -n "app.use(authorize" src/app.ts && npm test -- tests/security/authz
88
+ - Requirements: R-SEC-3, R-SEC-4, R-SEC-5
89
+ - [ ] GP-xxx Auth foundation: KDF, sessions, brute-force limits
90
+ - Files: src/auth/password.ts, src/auth/session.ts, src/middleware/ratelimit.ts
91
+ - Acceptance: argon2id is the only hashing call for credentials; timingSafeEqual used for every token and HMAC compare; login, reset, and MFA routes registered after the limiter mounts
92
+ - Verify: grep -rn "argon2id\|timingSafeEqual" src/auth/ && npm test -- tests/security/auth
93
+ - Requirements: R-SEC-6, R-SEC-7
94
+ - [ ] GP-xxx Security headers and production configuration
95
+ - Files: src/middleware/headers.ts, src/config/env.ts, tests/security/headers.test.ts
96
+ - Acceptance: enforcing CSP without unsafe-inline; HSTS, nosniff, frame-ancestors set; DEBUG defaults false; test asserts every header on a live response in each environment config
97
+ - Verify: npm test -- tests/security/headers.test.ts
98
+ - Requirements: R-SEC-15
99
+ - [ ] GP-xxx Secret hygiene: gitignore, scanning, CI references
100
+ - Files: .gitignore, .pre-commit-config.yaml, .github/workflows/ci.yml
101
+ - Acceptance: .env*, *.pem, and credential file patterns ignored before first commit; gitleaks scans full history in pre-commit and CI, run by the R-REPO-15 agent-safety task when it lands (no second step here); workflow contains no continue-on-error on scan steps and references secrets.* only
102
+ - Verify: gitleaks detect --no-banner && test -f .github/workflows/ci.yml && ! grep -n "continue-on-error" .github/workflows/ci.yml
103
+ - Requirements: R-SEC-13, R-SEC-14
104
+ - [ ] GP-xxx Supply chain pinning and SCA gate
105
+ - Files: package-lock.json, .github/workflows/ci.yml, .npmrc
106
+ - Acceptance: CI installs with npm ci; every third-party action pinned to a 40-char commit SHA; audit step gates on high with no || true; SBOM generated at build (when `public_release` is true or scale is enterprise, this is the R-REPO-14 dependency-inventory task's generator, not a second one)
107
+ - Verify: grep -q "npm ci" .github/workflows/ci.yml && ! grep -hE "^[ -]*uses:" .github/workflows/*.yml | grep -vE "@[0-9a-f]{40}|uses: *\./"
108
+ - Requirements: R-SEC-17, R-SEC-18
109
+ - [ ] GP-xxx Security event logging with formatter-level redaction
110
+ - Files: src/logging/logger.ts, src/logging/redact.ts, tests/security/logging.test.ts
111
+ - Acceptance: redaction wired into the shared formatter, not per call site; failed-auth and 403 branches emit actor, source IP, correlation id, outcome; alert rule on auth-failure spikes defined
112
+ - Verify: grep -n "redact" src/logging/logger.ts && npm test -- tests/security/logging
113
+ - Requirements: R-SEC-20
114
+ - [ ] GP-xxx Cross-tenant isolation and paper-control test suite
115
+ - Files: tests/security/isolation.test.ts, tests/security/paper-controls.test.ts
116
+ - Acceptance: user B token against user A resource returns 403 or 404 on GET, PUT, DELETE, list, and export; admin mutation without role returns 403; limiter fires on the 11th login attempt; JWT with alg:none rejected
117
+ - Verify: npm test -- tests/security/
118
+ - Requirements: R-SEC-3, R-SEC-4, R-SEC-16, R-SEC-24, R-SEC-25
119
+
120
+ - [ ] GP-xxx Seal hardening evidence for prepublication verification
121
+ - Files: docs/security/HARDENING.md
122
+ - Acceptance: every Critical records status; permitted acceptances include owner, justification, accepted_at, and expires_at; file records the regulated hard-gate policy; its content hash or immutable revision lives in the R-ROAD-21 gate; later changes require a new prepublication check
123
+ - Verify: grep -q '^policy:' docs/security/HARDENING.md && git hash-object docs/security/HARDENING.md
124
+ - Requirements: R-SEC-25, R-SEC-26
125
+
126
+ ## Self-audit rubric
127
+
128
+ - Threat model and surface declaration (10): entry points, enforced trust boundaries, assets, principals, STRIDE notes, deployment context, and every conditional surface declared present or absent with reasons.
129
+ - Authorization and tenancy (15): central deny-by-default layer named, ownership predicates in queries covering writes, list, search, export; role checks on privileged routes; no user-settable privilege fields; isolation test planned.
130
+ - Authentication and sessions (12): KDF named, constant-time comparisons, brute-force defenses behind correctly-ordered mounts, session or JWT properties specified, OAuth PKCE-only, recovery flows without enumeration.
131
+ - Injection and input handling (13): parameterized queries, identifier allowlists, argv exec, escape-hatch review gate, SSRF destination allowlist, path canonicalization, deserialization ban, XXE off, second-order re-encoding.
132
+ - Crypto and data protection (10): AEAD, nonce discipline, CSPRNG, key sourcing with rotation, TLS everywhere, cert validation never disabled, data classified with at-rest and no-store rules.
133
+ - Secrets management (8): source and SDK wiring named, rotation-not-deletion rule, no client-exposed or layered secrets, scanning that fails the build over full history.
134
+ - Misconfiguration and resource controls (8): header set with presence test, exact-match CORS, production hardening list, per-endpoint-class rate limits and caps, upload handling.
135
+ - Supply chain and CI/CD (8): integrity installs, SHA-pinned actions, digest-pinned images, SCA gate without soft-fail, SBOM, least-privilege tokens, environment gates, no PPE patterns.
136
+ - Logging, privacy, and API residue (6): event enumeration, formatter-level redaction, alerting to a monitored channel; regulated-data controls mapped to code paths; API Top 10 residue covered where applicable.
137
+ - Conditional surfaces (4): IaC and LLM requirements carried onto tasks when present, or dropped with a stated reason; never silently omitted.
138
+ - Anti-paper-control and verification handoff (6): every control has a mount point and firing test; automatic-Critical conditions are designed out; public release gets sealed hardening evidence and complete risk records for a fresh downstream check.
139
+
140
+ Total: 100. Any plan scoring below 85 on this rubric gets revised before emission.
141
+
142
+ ## Anti-patterns refused
143
+
144
+ - Paper controls (secauditor): a validator, policy decorator, or redact() defined but never on the execution path. Refusal: no control enters the plan without its mount point and a test proving it fires.
145
+ - Scanner-first security (harden-ready): a green Snyk or CodeQL run presented as the posture while an incrementing object ID leaks every tenant. Refusal: the verification phase budgets manual reproduced-attack checks with exact requests.
146
+ - Paper trust boundary (harden-ready, the Lovable CVE-2025-48757 class): a boundary declared in the architecture but unenforced in code. Refusal: every trust boundary in the threat model names its enforcement mechanism at plan time.
147
+ - Compliance-without-security (harden-ready): the checklist is green and the app is exploitable. Refusal: every compliance control maps to a named code path, config, or job, plus the question "what does the adversary do if this is weakly implemented".
148
+ - CVE-of-the-week (harden-ready): patching the instance and leaving the class. Refusal: any finding class fixed during the build gets a class survey and a class-level regression guard planned as a task.
149
+ - Hardening-as-ritual (harden-ready): an annual pen test with nothing between. Refusal: the plan declares a continuous cadence with a next execution date.
150
+ - Shallow-audit trap (harden-ready): findings a third party cannot reproduce. Refusal: every security acceptance condition is grep-verifiable or request-reproducible with the exact command in the Verify line.
151
+ - Vague-recommendation ban (secauditor): "validate input", "harden the config", "improve security". Refusal: every requirement names the safe pattern, the file it lands in, and the command that confirms it.
152
+ - Silent surface exclusion (secauditor conditional dimensions): skipping uploads, IaC, or LLM controls because nobody declared the surface. Refusal: the R-SEC-2 declaration records every surface as present or absent with a reason before any section is written.
153
+ - Automatic-Critical blindness (secauditor): shipping a design where one condition caps the audit at 79. Refusal: the R-SEC-24 design-out list is checked against the draft plan before emission, and any hit forces a revision.
154
+ - Late-Critical race: launch preparation finishes, hardening changes, and publication trusts the old pass. Refusal: seal current evidence, invalidate stale passes on any change, and require the fresh prepublication task only when a public release surface exists.
155
+ - Primary-path-only authorization: a control proven on the interactive session while an API key, a pre-MFA token, or a raw exported function reaches the same resource ungated. Refusal: every privileged operation lists its caller paths and carries an identical gate on each, tested through the non-primary path (R-SEC-27).
156
+ - Trusted-selector confused deputy: a caller-supplied id, email, or hostname that resolves and then acts on a record with no ownership binding, so anonymous checkout spends another member's credit by email or unauthenticated verification transitions another tenant's state. Refusal: every caller-supplied selector is ownership-bound before use, and email or hostname control is proven, with an IDOR test (R-SEC-28).
@@ -0,0 +1,133 @@
1
+ # SEO and AI visibility planning module
2
+
3
+ Plans classic-search visibility and AI answer-engine citability before any template is written. The orchestrator loads this module for any archetype with a public web surface (marketing-site, blog/publisher, e-commerce, docs, saas-dashboard with public pages); it is excluded with a stated reason for cli, library, and api-service archetypes with no site.
4
+
5
+ ## Lineage
6
+
7
+ Descends from seoauditor, the read-only audit of how a codebase makes a website visible to search engines and AI answer engines across 12 dimensions (CRAWL, RENDER, CONTENT, CANON, SCHEMA, AIVIS, URLARCH, PERF, SOCIAL, OBSV, I18N, FEEDS). The discipline that carries over: verify against what reaches the crawler, not against intent; hunt paper controls; distinguish AI training bots from citation bots; never score llms.txt as load-bearing; calibrate to site type so a monolingual site never gets hreflang recommendations. Audit checks that seoauditor runs after the fact become plan requirements here, reducing preventable visibility findings while leaving final verification to the shipped site audit.
8
+
9
+ ## Decisions to force
10
+
11
+ 1. Public URL architecture. Question: what is the canonical host, scheme, trailing-slash policy, slug scheme, and (if multilingual) locale URL scheme (subpath vs subdomain)? Why hard to reverse: public URLs are permanent identifiers; every later change costs a redirect map maintained forever and a re-indexation cycle. Options: apex vs www (default: pick one, enforce the other with a single-hop 301); no trailing slash (default) vs trailing slash; lowercase hyphenated slugs (default, non-negotiable); locale subpaths /en/ /de/ (default) vs subdomains.
12
+ 2. Rendering strategy per route class. Question: which routes are SSG, ISR, SSR, and which (if any) are CSR? Why hard to reverse: retrofitting server rendering onto a CSR app is a rewrite, and GPTBot, ClaudeBot, PerplexityBot, and OAI-SearchBot execute no JavaScript, so CSR-only content is permanently invisible to AI answer engines. Options: SSG/ISR for all indexable content (default), SSR where personalization requires it, CSR only behind auth. Never CSR for indexable content; never prerender-for-bots middleware.
13
+ 3. Site type and indexation split. Question: what site type is this (marketing, blog, e-commerce, docs, SPA app, local business) and which route classes are indexable vs deliberately noindexed? Why hard to reverse: the split drives robots.txt, sitemap scope, the env guard, and metadata templating; changing it later means auditing every route. Default: public content routes indexable; authenticated app routes, previews, and internal search results noindexed by design.
14
+ 4. AI-crawler policy. Question: which AI bots are allowed, classified by purpose: training (GPTBot, Google-Extended, ClaudeBot, CCBot, Applebot-Extended, Bytespider) vs search/citation (OAI-SearchBot, PerplexityBot, Claude-SearchBot) vs user-fetch (ChatGPT-User, Perplexity-User, Claude-User)? Why hard to reverse: robots.txt changes propagate over weeks, and blocking citation bots while courting AI visibility is self-defeating from day one. Default: allow all citation and user-fetch bots; decide training bots on business grounds; know that blocking Google-Extended opts out of Gemini training but does NOT remove the site from AI Overviews (served via Googlebot).
15
+ 5. Structured data model per template. Question: which JSON-LD types map to which page templates, and where does each required field come from in the content model? Why hard to reverse: missing fields (author, datePublished, price) must exist in the CMS/database schema; adding them later is a data migration. Default: Organization + WebSite sitewide, Article for posts (headline, image, datePublished, author, publisher), Product+Offer for commerce (price, priceCurrency, availability), BreadcrumbList on nested routes. Never plan FAQPage, HowTo, or SearchAction as SERP tactics: Google limited FAQ rich results to government and health sites (2023-08) and removed HowTo rich results (2023-09) and the sitelinks search box (2024-11).
16
+ 6. SEO observability baseline. Question: which SEO invariants are asserted in CI from the first commit? Why hard to reverse: a regression safety net added after launch cannot catch the launch-day env leak that noindexes production. Default: snapshot tests on title/canonical/robots/JSON-LD for key templates plus a robots/sitemap build-integrity gate, wired in the Verification phase.
17
+
18
+ ## Plan requirements
19
+
20
+ 1. R-SEO-1 The plan declares the site type and a route-class indexation matrix: every route class marked indexable or noindexed with a reason (authed app routes noindexed by design is correct, not a defect).
21
+ Criterion: WHEN the plan has a public web surface, THE PLAN SHALL contain a table mapping every route class to indexable or noindexed with a stated reason.
22
+ 2. R-SEO-2 The plan fixes the rendering strategy per route so that body content, title, canonical, robots meta, and JSON-LD exist in the initial server HTML for every indexable route: SSR/SSG/ISR, never CSR-only, never injected by client JS, react-helmet without a server pass, or a tag manager, and no "use client" at a content route root.
23
+ Criterion: WHEN a route is marked indexable, THE PLAN SHALL name its rendering mode and state that all SEO signals ship in server HTML, with no prerender-for-bots middleware anywhere in the plan.
24
+ 3. R-SEO-3 The plan specifies crawlable navigation and honest status codes: real anchor elements with href (no hash routing, no onClick navigation), unknown routes return a real 404 (no SPA catch-all serving 200), no JS or meta-refresh redirects, and paginated URLs for any infinite-scroll surface.
25
+ Criterion: WHEN the plan includes client-side routing or infinite scroll, THE PLAN SHALL include tasks for real-href navigation, a hard-404 handler, and paginated fallback URLs.
26
+ 4. R-SEO-4 The plan defines the robots.txt generator: no Disallow:/ under User-agent:* in prod, no dead directives (noindex:, crawl-delay, host:), no blocking of render-critical assets (/_next/, /static/, *.js, *.css), an absolute Sitemap: line, and robots.txt never used as an index control (noindex meta for keep-out pages; Disallow plus noindex on the same URL means the noindex is never seen).
27
+ Criterion: WHEN the plan emits a robots.txt task, THE PLAN SHALL list these five constraints in its acceptance criteria.
28
+ 5. R-SEO-5 The plan includes an environment indexability guard that fails safe: staging/preview deploys emit noindex, production never does, guard polarity is explicit and an unset or unknown env resolves to noindex (a misconfiguration can hide staging but can never silently deindex prod, because the CI assertion below fails the prod build first), plus a CI assertion that production builds contain no noindex.
29
+ Criterion: WHEN the plan has more than one deploy environment, THE PLAN SHALL contain both the guard task and the CI assertion task, cross-referenced.
30
+ 6. R-SEO-6 The plan derives the sitemap generator from the content model: only canonical, indexable, 200-status URLs; real per-URL lastmod from content modification time (never a uniform build stamp); chunked index above 50,000 URLs; no priority or changefreq elements.
31
+ Criterion: WHEN the plan emits a sitemap task, THE PLAN SHALL state the URL source query and exclude noindexed and redirected URLs by construction.
32
+ 7. R-SEO-7 The plan controls crawl traps: faceted navigation, sort orders, and session parameters consolidate to the clean base URL via canonical or noindex; pagination is crawlable and never canonicalizes to page 1.
33
+ Criterion: IF the plan includes faceted or parameterized listing pages, THE PLAN SHALL name the consolidation mechanism per parameter class.
34
+ 8. R-SEO-8 The plan commits to one canonical model: one host, scheme, and slash policy enforced by exactly ONE redirect layer with single-hop 301/308s (no competing framework plus edge plus server layers, no chains, no loops), and every indexable page emits exactly one absolute self-referencing canonical (metadataBase set in Next.js so canonicals never resolve to localhost; never built from the raw request URL with query strings; never client-side-only).
35
+ Criterion: WHEN the plan defines URL handling, THE PLAN SHALL name the single owning redirect layer and require an absolute self-referencing canonical in every page template task.
36
+ 9. R-SEO-9 The plan fixes URL design and slug lifecycle: lowercase, hyphenated, shallow, stable slugs; a redirect map entry is mandatory for any slug change; redirect status codes are correct per framework (Next redirect() is 307, permanentRedirect() is 308, Express default is 302, so permanent moves must be explicit).
37
+ Criterion: WHEN the plan defines content types with slugs, THE PLAN SHALL include the slug convention and the redirect-map mechanism as acceptance criteria on the routing task.
38
+ 10. R-SEO-10 The plan templates per-route titles and meta descriptions (unique per page, never a root-layout-only title making every page identical, no "React App" defaults), exactly one meaningful h1 per page, logical heading nesting, and semantic landmarks (header, nav, main, article, footer).
39
+ Criterion: WHEN the plan defines page templates, THE PLAN SHALL make unique title, unique description, single h1, and landmark elements grep-verifiable acceptance criteria on each template task.
40
+ 11. R-SEO-11 The plan requires descriptive alt text on content images, empty alt on decorative images, descriptive anchor text (no "click here"), and a visible E-E-A-T surface: author bylines, publish and update dates, About and Contact pages as real text.
41
+ Criterion: WHEN the plan includes content pages, THE PLAN SHALL contain tasks for the byline/date components and the About/Contact pages.
42
+ 12. R-SEO-12 The plan specifies server-rendered JSON-LD per template with all required fields per type, ISO 8601 dates, ISO 4217 currency, schema.org enum URLs for availability, and entity grounding (Organization/Person sameAs to authoritative profiles, author as a linked Person, publisher with logo).
43
+ Criterion: WHEN a template carries structured data, THE PLAN SHALL list the type, its required fields, and the content-model field each maps from.
44
+ 13. R-SEO-13 The plan bans fabricated structured data: no AggregateRating or Review without visible reviews in the rendered HTML, no hardcoded sample values, no schema asserting facts absent from the page (a manual-action trigger), and no restricted or removed rich-result types (FAQPage, HowTo, SearchAction) planned as tactics.
45
+ Criterion: WHEN the plan includes structured data tasks, THE PLAN SHALL state the content-match rule as an explicit acceptance criterion.
46
+ 14. R-SEO-14 The plan states the AI-crawler policy using the three-way bot taxonomy (training vs search/citation vs user-fetch) and, if AI visibility is a goal, allows OAI-SearchBot, ChatGPT-User, PerplexityBot, Perplexity-User, Claude-SearchBot, and Claude-User, and does not block Applebot; llms.txt, if planned, is labeled aspirational (no major search or AI engine documents using it; seoauditor facts.md, reviewed 2026-09-26) and is never a substitute for server-rendered HTML; noai meta is labeled non-enforcing.
47
+ Criterion: WHEN the plan targets AI visibility, THE PLAN SHALL contain an allow/block table by bot purpose and SHALL NOT place any load-bearing requirement on llms.txt.
48
+ 15. R-SEO-15 The plan makes content answer-extractable: templates structured with h2/h3 sections, lists, and tables rather than undifferentiated paragraph blocks, plus machine-readable datePublished and dateModified via time elements with datetime and matching schema fields.
49
+ Criterion: WHEN the plan defines article or docs templates, THE PLAN SHALL include heading-structured layout and machine-readable dates as acceptance criteria.
50
+ 16. R-SEO-16 The plan sets a Core Web Vitals code budget: the LCP/hero image is never lazy-loaded and gets fetchpriority=high or preload; all images, video, iframes, and embeds carry width+height or aspect-ratio; font-display with preload for critical fonts; code-splitting with no "use client" high in the tree; AVIF/WebP with srcset via the framework image component; immutable Cache-Control on hashed assets; third-party scripts async/defer; viewport meta present without user-scalable=no.
51
+ Criterion: WHEN the plan includes frontend tasks, THE PLAN SHALL attach these budget items as acceptance criteria on the relevant layout and asset tasks.
52
+ 17. R-SEO-17 The plan templates per-route social metadata: og:title, og:type, og:url, og:image plus description/site_name/locale, twitter:card=summary_large_image with an intact OG fallback chain, absolute HTTPS image URLs (metadataBase set so relative paths never ship localhost), an approximately 1200x630 image with width/height/alt, a square favicon of at least 48px, and an apple-touch-icon; any dynamic OG image route exports size and contentType, uses PNG or JPEG, loads explicit fonts, and caches.
53
+ Criterion: WHEN the plan includes shareable pages, THE PLAN SHALL contain a per-route social metadata task with absolute-URL verification.
54
+ 18. R-SEO-18 IF the plan is multilingual, the plan centralizes hreflang generation from one locales list with reciprocity and self-reference (a missing return tag voids the cluster), x-default pointing at a genuine neutral page, valid ISO 639-1 plus ISO 3166-1 codes (en-GB not en-UK, hyphen not underscore), per-locale self-canonicals (never cross-language to the default), coverage on all eligible pages, html lang and og:locale matching the route, and no IP or Accept-Language hard auto-redirects (a banner or selector instead).
55
+ Criterion: IF more than one locale is in scope, THE PLAN SHALL contain a central hreflang generation task with reciprocity as a tested acceptance criterion; otherwise THE PLAN SHALL drop R-SEO-18 in the module disposition (`dropped-by archetype`) with the reason.
56
+ 19. R-SEO-19 IF the plan has a content stream, feeds are planned: autodiscovery link elements pointing at feeds actually generated at those URLs, valid RSS/Atom/JSON with stable GUIDs (not build-derived), correct RFC 822/3339 dates; IF IndexNow is planned, the key file is hosted (and Google's non-consumption of IndexNow is noted); IF installable, the manifest has name, short_name, in-scope start_url, and 192/512/maskable icons, with PWA never framed as a ranking factor.
57
+ Criterion: IF a blog, changelog, or podcast is in scope, THE PLAN SHALL contain a feed task with validity checks; otherwise THE PLAN SHALL drop R-SEO-19 in the module disposition (`dropped-by archetype`) with the reason.
58
+ 20. R-SEO-20 The plan wires SEO observability into the Verification phase: CI snapshot tests asserting title, canonical, robots meta, hreflang, and JSON-LD on key templates; robots and sitemap build-integrity assertions against env leakage; broken-link and redirect-chain CI; exactly one search-engine verification token (none for properties nobody owns); Consent Mode v2 default-then-update wiring if analytics consent applies; and an explicit no-cloaking rule (no user-agent or isBot content branching anywhere).
59
+ Criterion: WHEN the plan reaches its Verification phase, THE PLAN SHALL list the SEO snapshot suite and the no-cloaking rule among the must-haves.
60
+ 21. R-SEO-21 The plan makes edge configuration crawl-safe: CSP that does not block the site's own render-critical assets, HSTS paired with an HTTP-to-HTTPS 301 (HSTS alone is theater), WAF and rate-limit rules that never 403 or 429 legitimate search crawlers or allowed AI crawlers, and no mixed content.
61
+ Criterion: WHEN the plan includes CDN, WAF, or security-header tasks, THE PLAN SHALL include crawler-safety acceptance criteria on each.
62
+ 22. R-SEO-22 The plan contains zero paper controls: no noindex: lines in robots.txt, no priority/changefreq sitemap elements, no rel=next/prev planned as a fix, no hardcoded homepage canonical, no dead-URL redirects to the homepage, and no llms.txt-as-strategy.
63
+ Criterion: WHEN the inversion pass distributes SEO requirements, THE PLAN SHALL NOT contain any task whose mechanism is on this banned list.
64
+
65
+ ## Task seeds
66
+
67
+ - [ ] GP-xxx Implement indexation control layer (robots.txt plus env noindex guard)
68
+ - Files: app/robots.ts, lib/seo/env-guard.ts, .github/workflows/ci.yml
69
+ - Acceptance: prod robots output has no "Disallow: /" under "User-agent: *"; output contains an absolute "Sitemap:" line; guard emits noindex only when DEPLOY_ENV is not "production"; CI job fails when prod build output contains "noindex"
70
+ - Verify: node scripts/check-robots.mjs && test -f .next/server/app/index.html && ! grep -q noindex .next/server/app/index.html
71
+ - Requirements: R-SEO-4, R-SEO-5
72
+ - [ ] GP-xxx Build sitemap generator from the content model
73
+ - Files: app/sitemap.ts, lib/seo/sitemap-source.ts
74
+ - Acceptance: URL source query excludes noindexed and redirected entries; each entry has lastmod from the row's updated_at; no priority or changefreq keys; chunking activates above 50000 URLs
75
+ - Verify: ! grep -Eq "priority|changefreq" app/sitemap.ts && node scripts/check-sitemap.mjs
76
+ - Requirements: R-SEO-6, R-SEO-22
77
+ - [ ] GP-xxx Establish canonical model and single redirect layer
78
+ - Files: next.config.js, lib/seo/metadata.ts, middleware.ts
79
+ - Acceptance: metadataBase set to the canonical origin; exactly one redirect layer handles host/scheme/slash with 308; every template emits one absolute self-referencing canonical; no second canonical emitter exists
80
+ - Verify: grep -q "metadataBase" lib/seo/metadata.ts && node scripts/check-canonicals.mjs
81
+ - Requirements: R-SEO-8, R-SEO-9
82
+ - [ ] GP-xxx Template per-route metadata (title, description, OG, twitter)
83
+ - Files: lib/seo/metadata.ts, app/(site)/*/page.tsx, app/og/route.tsx
84
+ - Acceptance: every routable page exports unique title and description; og:title/type/url/image and twitter:card present per route; og:image URLs absolute HTTPS; OG route exports size and contentType with PNG output
85
+ - Verify: node scripts/check-metadata.mjs --all-routes
86
+ - Requirements: R-SEO-10, R-SEO-17
87
+ - [ ] GP-xxx Add server-rendered JSON-LD per template with content matching
88
+ - Files: lib/seo/jsonld.ts, app/(site)/blog/[slug]/page.tsx
89
+ - Acceptance: Article JSON-LD includes headline, image, datePublished, author (Person), publisher with logo; all dates ISO 8601; every schema fact maps to a rendered field; no AggregateRating anywhere; no FAQPage/HowTo/SearchAction types
90
+ - Verify: ! grep -rEq "AggregateRating|FAQPage|HowTo|SearchAction" lib/seo/ app/ && node scripts/check-jsonld.mjs
91
+ - Requirements: R-SEO-12, R-SEO-13
92
+ - [ ] GP-xxx Declare AI-crawler policy in robots.txt by bot purpose
93
+ - Files: app/robots.ts, docs/seo-policy.md
94
+ - Acceptance: policy table classifies training vs citation vs user-fetch bots; OAI-SearchBot, PerplexityBot, Claude-SearchBot and user-fetch bots allowed; any training-bot blocks are per-UA groups, not a blanket Disallow:/; no llms.txt requirement marked load-bearing
95
+ - Verify: node scripts/check-robots.mjs --ai-policy
96
+ - Requirements: R-SEO-14, R-SEO-22
97
+ - [ ] GP-xxx Wire SEO regression suite into CI
98
+ - Files: tests/seo/snapshots.test.ts, scripts/check-links.mjs, .github/workflows/ci.yml
99
+ - Acceptance: snapshot tests assert title, canonical, robots meta, and JSON-LD for each key template; build-integrity test fails on prod noindex or empty sitemap; broken-link check runs on internal links; no isBot or user-agent content branching in source
100
+ - Verify: npm run test:seo && ! grep -rq "isBot(" app/ lib/
101
+ - Requirements: R-SEO-20, R-SEO-5
102
+
103
+ ## Self-audit rubric
104
+
105
+ Score the drafted SEO section 0-100. When I18N or FEEDS is dropped with a reason, redistribute its points proportionally across the remaining dimensions; never zero-and-keep.
106
+
107
+ - Crawlability and indexation control (14): full marks require the route-class indexation matrix, the five robots.txt constraints, the fail-safe env guard with its CI assertion, the content-model sitemap spec, and crawl-trap consolidation. (R-SEO-1, 4, 5, 6, 7)
108
+ - Rendering and content-in-HTML (13): full marks require a named rendering mode per indexable route, all signals in server HTML, real-href navigation, hard 404s, and no prerender-for-bots anywhere. (R-SEO-2, 3)
109
+ - On-page content and semantics (12): full marks require per-route title/description templating, single h1, landmarks, alt-text rules, and the E-E-A-T surface tasks. (R-SEO-10, 11)
110
+ - Canonicalization (11): full marks require the one-owner redirect layer, absolute self-referencing canonicals with metadataBase, and pagination never canonicalized to page 1. (R-SEO-8, 7)
111
+ - Structured data (10): full marks require per-template types with field-to-content-model mapping, entity grounding, the content-match ban, and zero restricted or removed rich-result types. (R-SEO-12, 13)
112
+ - AI and generative-engine visibility (9): full marks require the three-way bot policy table, the Google-Extended fact stated, llms.txt labeled aspirational, and answer-extractable template structure with machine-readable dates. (R-SEO-14, 15)
113
+ - URL architecture and edge config (8): full marks require the slug convention, redirect-map mechanism, correct framework status codes, and crawler-safe CSP/HSTS/WAF criteria. (R-SEO-9, 21)
114
+ - Core Web Vitals code budget (6): full marks require the never-lazy LCP rule, media dimensions, font strategy, and caching/splitting items attached to concrete tasks. (R-SEO-16)
115
+ - Social metadata (5): full marks require per-route OG/twitter tasks with absolute HTTPS images and the favicon/apple-touch-icon pair. (R-SEO-17)
116
+ - Internationalization (5, conditional): full marks require central hreflang generation with tested reciprocity, x-default, valid codes, and no IP auto-redirects; or a stated drop. (R-SEO-18)
117
+ - Feeds and installability (4, conditional): full marks require valid feeds with stable GUIDs and autodiscovery, hosted IndexNow key if planned; or a stated drop. (R-SEO-19)
118
+ - SEO observability (3): full marks require the CI snapshot suite, build-integrity assertions, single verification token, and the explicit no-cloaking rule in the Verification phase. (R-SEO-20)
119
+
120
+ Caps, stricter than the source auditor's visibility floor (one floor-dimension Critical holds seoauditor's overall at 69): if the drafted plan permits any of sitewide noindex reaching prod, CSR-only indexable content, user-agent content branching, a hardcoded homepage canonical, or blocking citation bots while targeting AI visibility, the section scores at most 59 regardless of the arithmetic. Below 85 total, revise before emission.
121
+
122
+ ## Anti-patterns refused
123
+
124
+ - Sitewide deindexing shipped to prod: a Disallow:/ or inverted env guard noindexes the whole site at launch. Refusal: the guard task and its CI assertion are mandatory whenever environments split; the plan does not emit without them.
125
+ - CSR-only shell: primary content, title, and canonical exist only after client JS runs, invisible to every non-JS AI crawler. Refusal: no indexable route may be planned as CSR; the rendering mode column is required in the route matrix.
126
+ - Cloaking and prerender-for-bots: user-agent branching or rendertron-style middleware serving crawlers different HTML. Refusal: the no-cloaking rule is a named Verification must-have; any dynamic-rendering proposal is replaced with SSR/SSG.
127
+ - Canonical collapse: a hardcoded homepage canonical on every page, or a per-locale constant, folds the site into one URL. Refusal: canonicals are always self-referencing by construction in one shared metadata helper; a second emitter is a plan defect.
128
+ - Self-defeating AI invisibility: blocking OAI-SearchBot or Perplexity bots while shipping llms.txt and answer schema. Refusal: the bot policy table is checked for consistency with the stated AI-visibility goal before the section is accepted.
129
+ - llms.txt-as-strategy: treating llms.txt, an aspirational file that no major engine documents using, as the AI visibility plan. Refusal: llms.txt may appear only as an optional task explicitly labeled non-load-bearing; server-rendered HTML carries the requirement.
130
+ - Paper controls: noindex: robots lines, priority/changefreq, rel=next/prev, dead-URL redirects to the homepage, verification tokens for unowned properties. Refusal: R-SEO-22 bans them; the inversion pass drops any task built on one.
131
+ - Fabricated structured data: AggregateRating with no visible reviews, schema asserting facts absent from the page. Refusal: every schema field must name its content-model source; unmatchable fields are cut from the schema plan, not stubbed.
132
+ - Cargo-cult calibration: hreflang on a monolingual site, e-commerce schema on a docs site, indexation for an authed dashboard. Refusal: conditional dimensions activate only from project facts recorded in the plan, and an inactive one is dropped in the module disposition with its reason; noindexing private routes is recorded as correct.
133
+ - Platitude requirements: "improve SEO", "add meta tags", "optimize performance" as acceptance criteria. Refusal: every SEO acceptance criterion must name the exact artifact, the stack-specific mechanism, and a command that verifies served output; anything failing the substitution test is rewritten or removed.
@@ -0,0 +1,133 @@
1
+ # Stack selection planning module
2
+
3
+ Turns tool choice into a constraint-filtered, weight-scored, dated decision inside PLAN.mdx. The orchestrator loads this module for every archetype whenever the stack domain is applicable: in greenfield mode it plans a fresh pick, in brownfield mode it plans from an inventory of the code that already exists, in replan mode it re-verifies the prior decision against flip-point signals before preserving it.
4
+
5
+ ## Lineage
6
+
7
+ Descends from stack-ready, the planning-tier skill that chooses a technology bundle for a specific job and refuses generic, undated, unaccountable recommendations. The discipline that carries over: hard constraints eliminate candidates before any scoring ranks them; every score sits under a published weight vector a reviewer can re-derive; and every recommendation ships with the three honesty fields (the failure mode that flips it, the scale ceiling as a metric, the switching cost in engineer-weeks). stack-ready stops at .stack-ready/DECISION.md; this module inverts its audit checks into obligations the plan satisfies before a single dependency is installed.
8
+
9
+ ## Decisions to force
10
+
11
+ Ordered by reversal cost. Each is answered in the plan's Decisions section as a grounded decision, a flagged hypothesis with a validation plan, or a named open question with a recommended default. Candidate generation starts from the domain profile plus the three pre-combined bundles: Safe Default (consensus tools, 12+ months of dominance, boring on purpose), Fast-to-Ship (managed everything, accepts vendor coupling to hit the time-to-ship answer), and Enterprise (SSO, audit logs, residency controls, self-host escape hatches). A bundle is a starting point, not an answer; every component still passes the constraint filter individually. In brownfield mode these same eight decisions are answered as keep, adjust, or replace verdicts against the inventory scan, and only replace verdicts trigger the migration requirements.
12
+
13
+ 1. **Database engine and data model shape.** Question: relational, document, or specialized store, and which engine? Hard to reverse because data outlives code: switching engines means dual-write, backfill, reconciliation, and a cutover window measured in engineer-weeks, and every query in the codebase is written against the old shape. Options: Postgres (default for anything with relations or future analytics), SQLite/libSQL (single-node tools, local-first), a document store only when the access pattern is genuinely key-shaped. Default: Postgres unless a hard constraint (offline, embedded, edge) rules it out.
14
+ 2. **Language and runtime.** Question: which language does the team write every file in? Hard to reverse because it touches 100 percent of the code and the hiring pool. Options: match the team's deepest language competence from pre-flight; a language the team does not know is a hypothesis, not a decision. Default: the team's strongest language with an actively maintained runtime.
15
+ 3. **Auth provider and identity ownership.** Question: managed auth, framework-native auth, or self-rolled sessions, and who owns the user table? Hard to reverse because user identities, password hashes, and sessions migrate poorly; an auth swap forces every user through re-verification or a risky hash import. Options: managed (Clerk, Auth0, Supabase Auth, WorkOS for enterprise SSO), library (Better Auth, Lucia-style), platform-native. Default: managed for SaaS with compliance needs, library when the user table must live in the app database.
16
+ 4. **Hosting posture and residency.** Question: managed platform, containers on a cloud, or self-host, and in which region? Hard to reverse because deploy pipelines, networking, secrets, and data residency contracts all bind to it. Options: managed PaaS (fastest to ship), containerized cloud (portable, more ops), self-host (only with named ops capacity). Default: managed PaaS unless a residency, self-host, or cost hard constraint eliminates it.
17
+ 5. **Framework.** Question: which application framework carries routing, rendering, and the request lifecycle? Hard to reverse because component and handler idioms permeate the codebase, though less deeply than language or data. Default: the consensus framework for the domain profile with 12+ months of dominance, not the newest entrant.
18
+ 6. **Payments provider.** Recorded from business decision 4 (billing system of record, merchant of record, tax) with its open merchant-of-record question; never re-decided here. When business is excluded or its decision 2 is no charge, R-STACK-4 records payments as not needed, citing that row or decision, whose revisit when: predicate reopens it.
19
+ 7. **Background jobs and queues.** Question: where does async work run? Semi-reversible, but job semantics (retries, idempotency, scheduling) leak into application code. Default: the queue native to the chosen hosting posture; exactly one.
20
+ 8. **ORM and client data layer.** Question: which single ORM and which single client cache/fetching layer? The most reversible of the forced bets, forced anyway because duplicates here are the most common coherence failure. Default: one ORM matched to the database, one client data layer matched to the framework.
21
+
22
+ ## Plan requirements
23
+
24
+ Each requirement is one plan-time obligation inverted from a stack-ready audit check. The orchestrator's inversion pass distributes these onto concrete tasks via Requirements: lines; a requirement with no task carrying it is an unmet requirement.
25
+
26
+ 1. **R-STACK-1 Mode declaration.** PLAN.mdx names the stack mode (greenfield pick, brownfield assessment, audit verdict, or migration) and, for brownfield or audit, records the stack inventory scan of the actual code before proposing anything. Criterion: WHEN the project has existing code, THE PLAN SHALL contain an inventory of the current stack per dimension before any recommendation, and IF the plan proposes changes THE PLAN SHALL label each dimension keep, adjust, or replace.
27
+ 2. **R-STACK-2 Pre-flight answers.** The stack section opens with the six pre-flight answers in writing: domain profile, team (size, language depth, on-call reality), a named budget posture (not a dollar figure), time-to-ship, an honest 12-month scale ceiling, and an explicit regulatory and data-residency statement, with "none apply" stated affirmatively rather than by silence. Criterion: WHEN the stack section is emitted, THE PLAN SHALL contain all six answers, and IF the user gave no answer for one, THE PLAN SHALL state a plausible default as an assumption rather than leave the field blank.
28
+ 3. **R-STACK-3 Constraint map before tools.** Every pre-flight answer is converted into either a hard constraint (rules candidates out: no-BAA in HIPAA paths, EU residency, self-host mandate, offline, cost ceiling, team language, SLA, vendor independence) or a weighted preference, and the map appears before any tool is named. Criterion: WHEN any candidate tool is listed, THE PLAN SHALL already contain the constraint map, and IF a candidate violates a hard constraint THE PLAN SHALL drop it unscored with the violated constraint named.
29
+ 4. **R-STACK-4 Twelve-dimension coverage.** The plan covers all 12 stack dimensions: framework, language/runtime, database, ORM, auth, UI library, client state/data fetching, hosting, observability, payments, email/notifications, background jobs. Criterion: WHEN the stack table is emitted, THE PLAN SHALL name a choice or an explicit "not needed because X" for each of the 12 dimensions.
30
+ 5. **R-STACK-5 Named alternatives with losers recorded.** Each decided dimension shows 2-4 post-filter candidates and records why each loser lost. Criterion: WHEN a dimension is decided, THE PLAN SHALL list at least one named rejected alternative with a one-line reason, and IF only one candidate survives filtering THE PLAN SHALL say which constraint eliminated the rest.
31
+ 6. **R-STACK-6 Published weight vector.** The weight vector used to rank candidates (DX, scale ceiling, ecosystem, cost, ops burden, compliance fit, or a stated override) is printed so a reviewer can re-derive the ranking. Criterion: WHEN scores are aggregated, THE PLAN SHALL state the weights, and IF the user overrode defaults THE PLAN SHALL show the override.
32
+ 7. **R-STACK-7 Score discipline.** Every scored candidate carries a 1-10 score with a one-line rationale naming what was scored; no score above 9 without consensus domain leadership of 12+ months, none below 3 without a documented failure mode in this domain. Criterion: IF any score is above 9 or below 3, THE PLAN SHALL attach the required special justification next to that score.
33
+ 8. **R-STACK-8 Pairing coherence.** The bundle passes the anti-pairing walk: exactly one ORM, one auth provider, one design system, one client cache layer, one job queue; no known-bad pairs (Convex+Prisma, Supabase+Firebase, Vercel+Lambda stacking, two of anything). Criterion: WHEN the bundle is finalized, THE PLAN SHALL state the coherence check passed, and IF a temporary dual-run is intentional (migration) THE PLAN SHALL name it and its end condition explicitly.
34
+ 9. **R-STACK-9 Flip point.** The chosen bundle carries a concrete failure-mode paragraph: the specific signal that would flip the decision. Criterion: WHEN the bundle is chosen, THE PLAN SHALL contain a flip-point paragraph that is neither "none" nor "unknown", specific enough that a reader six months later can tell whether it has been hit.
35
+ 10. **R-STACK-10 Scale ceiling as a metric.** The ceiling is a number or a named boundary: user count, data volume, query-pattern shift, or feature boundary. Criterion: WHEN the bundle is chosen, THE PLAN SHALL state the scale ceiling as a measurable quantity, not an adjective.
36
+ 11. **R-STACK-11 Switching cost.** The honest rebuild bill for leaving the bundle, in engineer-weeks or engineer-months, per hard-to-reverse component. Criterion: WHEN the bundle is chosen, THE PLAN SHALL state the switching cost as a time estimate with the dominant cost driver named.
37
+ 12. **R-STACK-12 Prior art.** Three real deployments running a comparable stack at comparable scale, each with status and date. Criterion: IF fewer than 3 comparable deployments can be named, THE PLAN SHALL flag the pick as more novel than claimed and downgrade it to a hypothesis with a validation task.
38
+ 13. **R-STACK-13 Compliance and ops fit.** Any managed service on a regulated path shows its BAA, SOC 2, or PCI documentation status; anything self-hosted names the ops cost for the actual team size from pre-flight. Criterion: IF the regulatory statement names a regime, THE PLAN SHALL record compliance documentation per managed service in that path, and IF any component is self-hosted THE PLAN SHALL name who operates it and at what recurring cost.
39
+ 14. **R-STACK-14 Version and maintenance hygiene.** Only released versions are pinned; no dependency whose repository is archived or whose last commit is older than 18 months. Criterion: WHEN the stack table pins versions, THE PLAN SHALL pin versions that exist at plan date, and IF a candidate fails the liveness check THE PLAN SHALL reject it with the last-commit date recorded.
40
+ 15. **R-STACK-15 True cost model.** Cost analysis includes egress, seat pricing, and the free-tier cliff, checked against the named budget posture. Criterion: WHEN hosting or managed services are chosen, THE PLAN SHALL state the expected monthly cost at the 12-month scale ceiling including egress and seats, and IF the choice sits on a free tier THE PLAN SHALL name the cliff and the cost after it.
41
+ 16. **R-STACK-16 Date stamp and staleness trigger.** The stack decision is dated and carries a re-check trigger at roughly 6 months or on flip-point signals, whichever comes first; auth, AI tooling, and hosting pricing churn fastest. Criterion: WHEN the stack section is emitted, THE PLAN SHALL carry the decision date and a named re-check condition.
42
+ 17. **R-STACK-17 Decision persistence and handoff.** The plan schedules a task that writes .stack-ready/DECISION.md at scaffold time so build, repo, and deploy phases consume the decision without re-litigating it, complete enough that a memory-less agent can start building without asking another stack question. Criterion: WHEN phases are laid out, THE PLAN SHALL contain a task emitting DECISION.md with pre-flight, constraints, weights, scored bundle, runner-up, flip point, ceiling, switching cost, and rejected bundles.
43
+ 18. **R-STACK-18 Open questions with owners.** Remaining stack unknowns appear only in the plan's single Open Questions section, each with an owner, a due date, and a recommended default. Criterion: IF any stack question remains open, THE PLAN SHALL list it in Open Questions with owner and due date, and THE PLAN SHALL NOT restate committed stack decisions there.
44
+ 19. **R-STACK-19 Migration path.** A stack migration includes all five components: blast radius, sequenced steps with dual-write/dual-read parallels and cutover points, a rollback checkpoint per phase, a data migration strategy (transforms, backfills, reconciliation, validation), and an honest engineer-week timeline. Criterion: IF the plan replaces any existing stack component that holds data, THE PLAN SHALL contain all five migration components with a rollback checkpoint in every migration phase.
45
+ 20. **R-STACK-20 Skip-the-rigor guard.** An experience-backed, reversible, low-stakes repeat pick gets a compact constraint check instead of the full scoring pass; formal scoring there is itself the paralysis failure mode. Criterion: IF the team has shipped this exact bundle before and every component is reversible under the stated constraints, THE PLAN SHALL record a compact constraint check with the prior deployment named instead of a full scoring table.
46
+ 21. **R-STACK-21 Named runner-up beyond the starting set.** The pre-combined bundles in Decisions to force are a starting set, not a ceiling. The plan names one viable alternative that was generated rather than selected from that set, together with the single condition under which it would have won, so a reader can tell a bundle that was chosen from one that was merely defaulted into. This records the alternative; it does not promote it, and the incumbent bias in R-STACK-7 and R-STACK-12 stands. Criterion: WHEN the bundle is chosen, THE PLAN SHALL name one runner-up that was not on the pre-combined bundle list together with the condition that would flip the decision to it, or SHALL state that generation produced no viable off-list candidate and name the constraint that eliminated them.
47
+
48
+ ## Task seeds
49
+
50
+ Instantiate with real paths, real tool names, and wave/parallel markers; replace the placeholder-shaped Verify commands with ones that name the chosen tools, and replace count placeholders like `<regulated-vendor-count>` with the real numbers from the plan.
51
+
52
+ - [ ] GP-xxx Run the brownfield stack inventory scan (brownfield and audit modes only)
53
+ - Files: docs/stack/inventory.md
54
+ - Acceptance: one row per stack dimension listing the tool actually in the code (from manifests and imports, not from memory), its installed version, its last-commit liveness, and the plan's keep/adjust/replace verdict; no dimension row is blank
55
+ - Verify: test $(grep -cE '^\| (framework|language|database|orm|auth|ui|client-data|hosting|observability|payments|email|jobs) ' docs/stack/inventory.md) -eq 12
56
+ - Requirements: R-STACK-1, R-STACK-4
57
+ - [ ] GP-xxx Scaffold the project with the pinned stack manifest
58
+ - Files: package.json (or the runtime's manifest), .tool-versions, scripts/check-stack.mjs
59
+ - Acceptance: every dependency in the plan's stack table appears at its exact pinned version; no dependency introduces a second ORM, auth provider, design system, client cache, or job queue; runtime version matches the plan; the check script exits 1 on drift or a duplicate
60
+ - Verify: node scripts/check-stack.mjs
61
+ - Requirements: R-STACK-4, R-STACK-8, R-STACK-14
62
+ - [ ] GP-xxx Emit .stack-ready/DECISION.md from the plan's stack section
63
+ - Files: .stack-ready/DECISION.md
64
+ - Acceptance: file contains decision date, six pre-flight answers, hard constraints, weight vector, scored bundle table, runner-up, flip point, scale ceiling, switching cost, prior art with dates, rejected bundles, open questions with owner and due date
65
+ - Verify: grep -q 'Flip point' .stack-ready/DECISION.md && grep -q 'Scale ceiling' .stack-ready/DECISION.md && grep -q 'Switching cost' .stack-ready/DECISION.md
66
+ - Requirements: R-STACK-16, R-STACK-17
67
+ - [ ] GP-xxx Verify dependency liveness and version existence
68
+ - Files: scripts/check-liveness.sh
69
+ - Acceptance: every pinned version resolves in the registry; no direct dependency's source repo is archived or silent for over 18 months; script exits nonzero on violation
70
+ - Verify: bash scripts/check-liveness.sh
71
+ - Requirements: R-STACK-14
72
+ - [ ] GP-xxx Record compliance documentation for regulated-path services
73
+ - Files: docs/compliance/vendors.md
74
+ - Acceptance: each managed service touching regulated data has a row with BAA/SOC 2/PCI status, document link or ticket, and review date; no regulated-path service has an empty status
75
+ - Verify: test "$(grep -cE 'BAA|SOC 2|PCI' docs/compliance/vendors.md)" -ge <regulated-vendor-count>
76
+ - Requirements: R-STACK-13
77
+ - [ ] GP-xxx Enforce pairing coherence in CI
78
+ - Files: scripts/check-pairing.sh, .github/workflows/lint.yml
79
+ - Acceptance: CI fails if the manifest matches more than one entry per category list (ORMs, auth providers, design systems, client caches, job queues); intentional dual-run entries are allowlisted with an expiry date
80
+ - Verify: bash scripts/check-pairing.sh
81
+ - Requirements: R-STACK-8
82
+ - [ ] GP-xxx Stand up migration dual-run with rollback checkpoint (migration plans only)
83
+ - Files: src/data/dual-write.ts, docs/migration/rollback-checkpoints.md
84
+ - Acceptance: writes go to old and new stores behind a flag; a reconciliation job compares row counts and checksums; each migration phase in the docs names its rollback checkpoint and cutover condition
85
+ - Verify: test "$(grep -c 'Rollback checkpoint' docs/migration/rollback-checkpoints.md)" -eq <migration-phase-count>
86
+ - Requirements: R-STACK-19
87
+
88
+ ## Self-audit rubric
89
+
90
+ Score the plan's stack section 0-100. Below 85 total, revise before emission. The dimensions mirror stack-ready's four completion tiers: Shortlist (constraint-filtered survivors each with a why), Scored (a reader can see why A beat B in the numbers), Justified (the honesty triple plus rejected-bundle reasons), Decided (a memory-less agent can start building without asking another stack question).
91
+
92
+ - **Pre-flight and constraint map (15).**
93
+ Full marks: all six pre-flight answers in writing with silence stated affirmatively, every answer converted to a hard constraint or weighted preference, the map appearing before any tool name, violators dropped unscored.
94
+ Typical losses: regulatory field answered by omission (-5), constraints listed after the recommendation they were supposed to filter (-5).
95
+ - **Candidate coverage (15).**
96
+ Full marks: all 12 dimensions decided or excluded with a stated reason, 2-4 named candidates per decided dimension, every loser's reason recorded, and one named runner-up generated outside the pre-combined bundle list with its flip condition (or the constraint that eliminated all off-list candidates).
97
+ Typical losses: observability, email, or background jobs skipped without an exclusion reason (-3 each), a dimension with one candidate and no eliminating constraint named (-3), every candidate traceable to the starting bundles with no off-list alternative named or excluded (-3).
98
+ - **Scoring discipline (15).**
99
+ Full marks: weight vector printed and re-derivable, every score carrying a rationale that names what was scored, 9+/3- caps respected with justification, top bundle ranked by the weighted aggregate.
100
+ Typical losses: scores with no rationale (-5), an unexplained 10 (-5), aggregate that does not follow from the printed weights (-5).
101
+ - **Pairing coherence (10).**
102
+ Full marks: exactly one of each single-slot category (ORM, auth, design system, client cache, job queue), the anti-pairing table walked, any intentional dual-run named with an end condition.
103
+ Typical losses: a second auth provider smuggled in via a starter template (-5), dual-run with no expiry (-3).
104
+ - **Honesty triple (15).**
105
+ Full marks: a flip point concrete enough to test in six months, a scale ceiling stated as a metric, a switching cost in engineer-weeks with the dominant driver named; none of the three reads "none" or "unknown".
106
+ Typical losses: flip point that is really a restated benefit (-5), ceiling given as an adjective (-5).
107
+ - **Prior art and hygiene (10).**
108
+ Full marks: 3 real deployments with status and dates, only released versions pinned, no dependency archived or silent for over 18 months.
109
+ Typical losses: prior art younger or smaller than the stated ceiling (-3), an unreleased version pinned (-5).
110
+ - **Cost and compliance fit (10).**
111
+ Full marks: monthly cost modeled at the 12-month ceiling including egress, seats, and the free-tier cliff; compliance documentation recorded for every regulated-path managed service; ops cost named for anything self-hosted.
112
+ Typical losses: free-tier pricing quoted at ceiling scale (-5), regulated-path vendor with blank compliance status (-5).
113
+ - **Handoff and staleness (10).**
114
+ Full marks: decision dated with a re-check trigger, the DECISION.md emission task scheduled with full contents, open questions carrying owner and due date, migration plans (when present) containing all five components with per-phase rollback.
115
+ Typical losses: undated decision (-5), open question with no owner (-2), migration phase missing its rollback checkpoint (-3).
116
+
117
+ ## Anti-patterns refused
118
+
119
+ - **Fake objectivity.** Scores with no stated weighting. Refusal: no score is written until the weight vector is printed.
120
+ - **Horoscope recommendation.** A pick with no flip-point paragraph, true no matter what happens. Refusal: the bundle is not committed until the flip point, ceiling, and switching cost are written.
121
+ - **"It depends" as a final answer.** Refusal: state the variable it depends on, assume a stated value, and decide; the assumption goes in the plan.
122
+ - **Trend chasing.** "Popular" or "new" as a rationale. Refusal: rationale must name domain fit; novelty without 3 prior deployments becomes a flagged hypothesis.
123
+ - **Dead-library pick.** Archived repo or last commit over 18 months old. Refusal: rejected with the last-commit date recorded next to the rejection.
124
+ - **Phantom versions.** Pinning a version that does not exist at plan date. Refusal: only released versions enter the stack table; the liveness task verifies.
125
+ - **Compliance blind spot.** A managed service in a regulated path with no BAA/SOC 2/PCI evidence. Refusal: the service is ineligible until documentation status is recorded.
126
+ - **Ops-cost amnesia.** Self-host recommended without naming who operates it. Refusal: self-host options are dropped unless the pre-flight team can absorb the named ops cost.
127
+ - **Free-tier mirage.** Cost analysis ignoring egress, seat pricing, or the cliff after the free tier. Refusal: cost is modeled at the 12-month ceiling or the choice is not costed at all, which fails R-STACK-15.
128
+ - **Anti-pairing incoherence.** Two ORMs, two auth providers, Convex+Prisma-class conflicts. Refusal: the bundle fails the coherence walk and is repaired before scoring output is kept.
129
+ - **Rollback-free migration.** A migration phase without a checkpoint. Refusal: the migration section is incomplete until every phase names its rollback point.
130
+ - **Microservices for two.** Distributed architecture for a team of 2 without a forcing function. Refusal: the plan defaults to the simplest topology the constraints allow and records the forcing function if one exists.
131
+ - **Undated recommendation.** A stack decision with no date and no staleness trigger. Refusal: the section is not emitted without both.
132
+ - **Undisclosed commercial ties.** Scoring shaded by an unstated affiliation. Refusal: any tie is disclosed next to the score or the candidate is scored by constraints alone.
133
+ - **Analysis paralysis.** Running the full scoring pass on an experience-backed, reversible repeat pick. Refusal: the skip-the-rigor guard applies; a compact constraint check with the prior deployment named replaces the ceremony.