@openora/create 0.4.1-canary.40 → 0.4.1-canary.403

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 (104) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/generated/versions.d.ts +11 -0
  3. package/dist/generated/versions.d.ts.map +1 -0
  4. package/dist/generated/versions.js +11 -0
  5. package/dist/generated/versions.js.map +1 -0
  6. package/dist/index.js +48 -93
  7. package/dist/index.js.map +1 -1
  8. package/dist/render.d.ts +15 -0
  9. package/dist/render.d.ts.map +1 -0
  10. package/dist/render.js +125 -0
  11. package/dist/render.js.map +1 -0
  12. package/package.json +8 -6
  13. package/template/README.md.tpl +12 -7
  14. package/template/__dot__claude/settings.json.tpl +30 -12
  15. package/template/__dot__env.example +16 -0
  16. package/template/__dot__gitignore +5 -5
  17. package/template/__dot__rulesync/commands/check.md +11 -10
  18. package/template/__dot__rulesync/commands/doctor.md.tpl +17 -0
  19. package/template/__dot__rulesync/commands/scaffold-module.md +3 -2
  20. package/template/__dot__rulesync/commands/scaffold-plugin.md +23 -4
  21. package/template/__dot__rulesync/commands/scaffold-route.md +1 -0
  22. package/template/__dot__rulesync/commands/start.md +2 -2
  23. package/template/__dot__rulesync/hooks/_shared.mjs +25 -34
  24. package/template/__dot__rulesync/hooks/guard-core.mjs.tpl +98 -28
  25. package/template/__dot__rulesync/hooks/guard-generated.mjs +15 -16
  26. package/template/__dot__rulesync/hooks/guard-mr.mjs +143 -0
  27. package/template/__dot__rulesync/hooks/guard-review.mjs +280 -0
  28. package/template/__dot__rulesync/hooks/guard-stack.mjs +35 -0
  29. package/template/__dot__rulesync/hooks/guard-subagent.mjs +22 -6
  30. package/template/__dot__rulesync/hooks/post-edit.mjs.tpl +116 -0
  31. package/template/__dot__rulesync/hooks.json +37 -4
  32. package/template/__dot__rulesync/rules/conventions.md +99 -119
  33. package/template/__dot__rulesync/rules/db-conventions.md +6 -72
  34. package/template/__dot__rulesync/rules/e2e-conventions.md +33 -7
  35. package/template/__dot__rulesync/rules/frontend-conventions.md.tpl +35 -0
  36. package/template/__dot__rulesync/rules/oss-boundaries.md.tpl +78 -0
  37. package/template/__dot__rulesync/rules/overview.md +19 -82
  38. package/template/__dot__rulesync/skills/agent-retro/SKILL.md.tpl +81 -0
  39. package/template/__dot__rulesync/skills/agent-retro/scan.mjs +420 -0
  40. package/template/__dot__rulesync/skills/create-plugin/{SKILL.md → SKILL.md.tpl} +12 -23
  41. package/template/__dot__rulesync/skills/create-pr/SKILL.md.tpl +37 -0
  42. package/template/__dot__rulesync/skills/create-task/SKILL.md.tpl +96 -0
  43. package/template/__dot__rulesync/skills/create-ui-module/{SKILL.md → SKILL.md.tpl} +12 -10
  44. package/template/__dot__rulesync/skills/enhance-prompt/{SKILL.md → SKILL.md.tpl} +4 -4
  45. package/template/__dot__rulesync/skills/handoff/SKILL.md +4 -3
  46. package/template/__dot__rulesync/skills/review/SKILL.md.tpl +278 -0
  47. package/template/__dot__rulesync/skills/ship/SKILL.md.tpl +157 -0
  48. package/template/__dot__rulesync/skills/ship/handoff.md.tpl +48 -0
  49. package/template/__dot__rulesync/skills/ship/watch-pr.mjs +189 -0
  50. package/template/__dot__rulesync/skills/ui-verify/SKILL.md.tpl +120 -0
  51. package/template/__dot__rulesync/skills/ui-verify/layout-check.check.sh +58 -0
  52. package/template/__dot__rulesync/skills/ui-verify/layout-check.js +163 -0
  53. package/template/__dot__rulesync/subagents/builder.md.tpl +116 -0
  54. package/template/__dot__rulesync/subagents/compliance-reviewer.md +79 -0
  55. package/template/__dot__rulesync/subagents/debugger.md.tpl +89 -0
  56. package/template/__dot__rulesync/subagents/deployer.md.tpl +55 -0
  57. package/template/__dot__rulesync/subagents/expert.md +29 -34
  58. package/template/__dot__rulesync/subagents/planner.md.tpl +40 -0
  59. package/template/__dot__rulesync/subagents/quality-reviewer.md.tpl +113 -0
  60. package/template/__dot__rulesync/subagents/security-reviewer.md.tpl +86 -0
  61. package/template/__dot__rulesync/subagents/tester.md.tpl +103 -0
  62. package/template/__dot__rulesync/sync.json.tpl +26 -0
  63. package/template/apps/api/package.json.tpl +2 -2
  64. package/template/apps/api/src/extensions.config.ts.tpl +12 -0
  65. package/template/apps/api/src/main.ts.tpl +1 -4
  66. package/template/apps/api/src/seed.ts.tpl +24 -17
  67. package/template/docker-compose.yml +13 -0
  68. package/template/docs/agents/cross-repo.md.tpl +36 -0
  69. package/template/docs/agents/forge.md.tpl +56 -0
  70. package/template/docs/agents/issue-tracker.md.tpl +42 -0
  71. package/template/docs/standards/comments.md +16 -0
  72. package/template/docs/standards/database.md +77 -0
  73. package/template/docs/standards/enforcement.md +12 -0
  74. package/template/docs/standards/errors.md +30 -0
  75. package/template/docs/standards/frontend.md +60 -0
  76. package/template/docs/standards/functions.md +38 -0
  77. package/template/docs/standards/git-delivery.md +33 -0
  78. package/template/docs/standards/module-structure.md +37 -0
  79. package/template/docs/standards/testing.md +91 -0
  80. package/template/docs/standards/types.md +31 -0
  81. package/template/package.json.tpl +16 -10
  82. package/template/pnpm-workspace.yaml.tpl +6 -0
  83. package/template/rulesync.jsonc +4 -5
  84. package/template/tools/oss-worktree.mjs.tpl +105 -0
  85. package/template/tools/review-precheck.mjs +575 -0
  86. package/template/tools/sync-agents.mjs +273 -0
  87. package/dist/generated/core-version.d.ts +0 -2
  88. package/dist/generated/core-version.d.ts.map +0 -1
  89. package/dist/generated/core-version.js +0 -2
  90. package/dist/generated/core-version.js.map +0 -1
  91. package/template/__dot__rulesync/commands/doctor.md +0 -16
  92. package/template/__dot__rulesync/hooks/post-edit.mjs +0 -57
  93. package/template/__dot__rulesync/rules/oss-boundaries.md +0 -31
  94. package/template/__dot__rulesync/skills/add-feature/SKILL.md +0 -113
  95. package/template/__dot__rulesync/skills/add-feature/handoff.md +0 -58
  96. package/template/__dot__rulesync/skills/create-pr/SKILL.md +0 -55
  97. package/template/__dot__rulesync/skills/create-task/SKILL.md +0 -77
  98. package/template/__dot__rulesync/skills/review/SKILL.md +0 -110
  99. package/template/__dot__rulesync/subagents/builder.md +0 -93
  100. package/template/__dot__rulesync/subagents/debugger.md +0 -82
  101. package/template/__dot__rulesync/subagents/deployer.md +0 -66
  102. package/template/__dot__rulesync/subagents/qa.md +0 -88
  103. package/template/__dot__rulesync/subagents/quality-reviewer.md +0 -67
  104. package/template/__dot__rulesync/subagents/security-reviewer.md +0 -54
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  // PreToolUse(Task) guard: keep the orchestrator from spawning a GENERIC subagent
3
3
  // (general-purpose / claude) for work a roster agent is purpose-built for. The
4
- // Agent roster in AGENTS.md is prose the model sometimes skips out of habit; this
5
- // is the deterministic backstop.
4
+ // Agent roster in the workflow rule is prose the model sometimes skips out of
5
+ // habit; this is the deterministic backstop.
6
6
  //
7
7
  // Conservative by design: it acts ONLY when (a) the chosen subagent is generic AND
8
8
  // (b) the task text contains a HIGH-SIGNAL phrase that maps unambiguously to one
@@ -16,14 +16,16 @@ const ti = payload.tool_input ?? {};
16
16
  const sub = String(ti.subagent_type ?? '').toLowerCase();
17
17
 
18
18
  const GENERIC = new Set(['general-purpose', 'claude', '']);
19
- if (!GENERIC.has(sub)) process.exit(0);
19
+ if (!GENERIC.has(sub)) {
20
+ process.exit(0);
21
+ }
20
22
 
21
23
  const text = `${ti.description ?? ''}\n${ti.prompt ?? ''}`.toLowerCase();
22
24
 
23
25
  // High-signal phrase -> the roster agent that owns it. Keep each pattern SPECIFIC;
24
26
  // err toward missing a case over false-blocking a generic task.
25
27
  const ROUTES = [
26
- { agent: 'qa', re: /\b(playwright|e2e test|end-to-end test|e2e coverage)\b/ },
28
+ { agent: 'tester', re: /\b(playwright|e2e test|end-to-end test|e2e coverage)\b/ },
27
29
  {
28
30
  agent: 'debugger',
29
31
  re: /\b(build (failure|error)|turbopack|tsc error|module resolution|runtime error|stack trace)\b/,
@@ -40,14 +42,28 @@ const ROUTES = [
40
42
  agent: 'deployer',
41
43
  re: /\b(dockerfile|containerize|deploy pipeline|deploy to (ecs|kubernetes|fly|railway|render)|ci\/cd deploy|helm chart)\b/,
42
44
  },
45
+ {
46
+ agent: 'compliance-reviewer',
47
+ re: /\b(compliance|responsible gambling|ledger|audit trail) review\b/,
48
+ },
49
+ {
50
+ agent: 'quality-reviewer',
51
+ re: /\b(quality review|code quality|over-engineer(ed|ing)?|simplification review|duplication review)\b|\breview (the )?(mr|pr|diff|changed files)\b/,
52
+ },
53
+ {
54
+ agent: 'security-reviewer',
55
+ re: /\bsecurity (review|audit)\b|\baudit\b[^.]*\bvulnerabilit|\b(authz|owasp)\b/,
56
+ },
43
57
  ];
44
58
 
45
59
  const hit = ROUTES.find((r) => r.re.test(text));
46
- if (!hit) process.exit(0);
60
+ if (!hit) {
61
+ process.exit(0);
62
+ }
47
63
 
48
64
  process.stderr.write(
49
65
  `Use the \`${hit.agent}\` subagent for this task, not \`${sub || 'general-purpose'}\`. ` +
50
- `It is pre-scoped for this work (tools + model + brief) - see the Agent roster in AGENTS.md. ` +
66
+ `It is pre-scoped for this work (tools + model + brief) - see the Agents list in the workflow rule. ` +
51
67
  `Re-issue the Task with subagent_type: "${hit.agent}". ` +
52
68
  `If it genuinely does not fit ${hit.agent}, rephrase the description to say why.\n`,
53
69
  );
@@ -0,0 +1,116 @@
1
+ #!/usr/bin/env node
2
+ // PostToolUse hook (Claude / Codex CLI / Gemini CLI).
3
+ // Lint-fixes the edited files, then typechecks the apps that own them and reports
4
+ // (exit 2) only if the error is in a file just edited. Output is capped so a
5
+ // failure can't balloon the model context. Fail-open on anything unexpected.
6
+
7
+ import { execFileSync } from 'node:child_process';
8
+ import { existsSync, readFileSync } from 'node:fs';
9
+ import { basename, join, isAbsolute } from 'node:path';
10
+ import { extractFilePaths, readPayload } from './_shared.mjs';
11
+
12
+ const CAP_LINES = 40;
13
+ const CAP_CHARS = 2000;
14
+
15
+ const filePaths = extractFilePaths(readPayload()).filter(
16
+ (filePath) =>
17
+ /\.(ts|tsx)$/.test(filePath) &&
18
+ !filePath.endsWith('.d.ts') &&
19
+ !filePath.includes('/templates/') &&
20
+ !filePath.includes('/generated/') &&
21
+ existsSync(filePath),
22
+ );
23
+ if (filePaths.length === 0) {
24
+ process.exit(0);
25
+ }
26
+ const edited = filePaths.join(', ');
27
+
28
+ /**
29
+ * node_modules/.bin/<name> when it exists, else the bare name off PATH. `pnpm exec`
30
+ * costs ~2.2s of package-manager startup per call against ~0.12s for the binary, and
31
+ * this hook runs on every edit.
32
+ */
33
+ function bin(name) {
34
+ const local = join(process.env.CLAUDE_PROJECT_DIR ?? process.cwd(), 'node_modules/.bin', name);
35
+ return existsSync(local) ? local : name;
36
+ }
37
+
38
+ function cap(text) {
39
+ const out = text.split('\n').slice(0, CAP_LINES).join('\n').slice(0, CAP_CHARS);
40
+ return out.length < text.length ? `${out}\n... (truncated)` : out;
41
+ }
42
+
43
+ // Lint-fix (best effort - never block on the linter).
44
+ try {
45
+ execFileSync(bin('oxlint'), ['--fix', ...filePaths], { stdio: 'pipe' });
46
+ } catch {
47
+ /* oxlint unavailable or errored - fall through to the re-lint / typecheck */
48
+ }
49
+
50
+ // Re-lint WITHOUT --fix to surface UNFIXABLE errors the agent must resolve by
51
+ // hand - import/no-cycle and the no-restricted-imports boundary rules (deep @openora
52
+ // or {{scope}}/ui imports, app-to-app imports). oxlint exits non-zero on errors
53
+ // only (warnings don't fail), so this blocks on a real boundary/cycle violation
54
+ // in an edited file and feeds the message back. Fail-open on anything else.
55
+ try {
56
+ execFileSync(bin('oxlint'), filePaths, { stdio: 'pipe' });
57
+ } catch (e) {
58
+ const out = (e.stdout?.toString() ?? '') + (e.stderr?.toString() ?? '');
59
+ if (/\berror\b/.test(out)) {
60
+ process.stderr.write(`Boundary/lint error in ${edited} - fix before continuing:\n${cap(out)}`);
61
+ process.exit(2);
62
+ }
63
+ }
64
+
65
+ // Resolve the owning workspace app (apps/<x> or packages/<x>).
66
+ function packageNameFor(fp) {
67
+ const m = fp.match(/(.*?\/(?:apps|packages)\/[^/]+)\//);
68
+ if (!m) {
69
+ return null;
70
+ }
71
+ try {
72
+ const pkg = JSON.parse(readFileSync(join(m[1], 'package.json'), 'utf8'));
73
+ if (!pkg.name || !pkg.scripts?.['check:types']) {
74
+ return null;
75
+ }
76
+ return pkg.name;
77
+ } catch {
78
+ return null;
79
+ }
80
+ }
81
+
82
+ const owners = [
83
+ ...new Set(
84
+ filePaths
85
+ .map((filePath) => packageNameFor(isAbsolute(filePath) ? filePath : join(process.cwd(), filePath)))
86
+ .filter(Boolean),
87
+ ),
88
+ ];
89
+ if (owners.length === 0) {
90
+ process.exit(0);
91
+ }
92
+
93
+ try {
94
+ execFileSync(
95
+ bin('turbo'),
96
+ [
97
+ 'run',
98
+ 'check:types',
99
+ ...owners.flatMap((owner) => ['--filter', owner]),
100
+ '--output-logs=errors-only',
101
+ '--ui=stream',
102
+ ],
103
+ { stdio: 'pipe' },
104
+ );
105
+ process.exit(0);
106
+ } catch (e) {
107
+ const output = (e.stdout?.toString() ?? '') + (e.stderr?.toString() ?? '');
108
+ const failing = filePaths.map((filePath) => basename(filePath)).filter((name) => output.includes(name));
109
+ if (failing.length > 0) {
110
+ process.stderr.write(
111
+ `Typecheck failed for ${owners.join(', ')} after editing ${failing.join(', ')}:\n${cap(output)}`,
112
+ );
113
+ process.exit(2);
114
+ }
115
+ process.exit(0);
116
+ }
@@ -2,10 +2,43 @@
2
2
  "version": 1,
3
3
  "hooks": {
4
4
  "preToolUse": [
5
- { "type": "command", "command": "node .rulesync/hooks/guard-core.mjs" },
6
- { "type": "command", "command": "node .rulesync/hooks/guard-generated.mjs" },
7
- { "type": "command", "matcher": "Task", "command": "node .rulesync/hooks/guard-subagent.mjs" }
5
+ {
6
+ "type": "command",
7
+ "matcher": "Bash|Edit|Write|MultiEdit|NotebookEdit",
8
+ "command": "node \"${CLAUDE_PROJECT_DIR:-.}/.rulesync/hooks/guard-core.mjs\""
9
+ },
10
+ {
11
+ "type": "command",
12
+ "matcher": "Bash|Edit|Write|MultiEdit|NotebookEdit",
13
+ "command": "node \"${CLAUDE_PROJECT_DIR:-.}/.rulesync/hooks/guard-generated.mjs\""
14
+ },
15
+ {
16
+ "type": "command",
17
+ "matcher": "Bash",
18
+ "command": "node \"${CLAUDE_PROJECT_DIR:-.}/.rulesync/hooks/guard-mr.mjs\""
19
+ },
20
+ {
21
+ "type": "command",
22
+ "matcher": "Bash",
23
+ "command": "node \"${CLAUDE_PROJECT_DIR:-.}/.rulesync/hooks/guard-review.mjs\""
24
+ },
25
+ {
26
+ "type": "command",
27
+ "matcher": "Bash",
28
+ "command": "node \"${CLAUDE_PROJECT_DIR:-.}/.rulesync/hooks/guard-stack.mjs\""
29
+ },
30
+ {
31
+ "type": "command",
32
+ "matcher": "Task|Agent",
33
+ "command": "node \"${CLAUDE_PROJECT_DIR:-.}/.rulesync/hooks/guard-subagent.mjs\""
34
+ }
8
35
  ],
9
- "postToolUse": [{ "type": "command", "command": "node .rulesync/hooks/post-edit.mjs" }]
36
+ "postToolUse": [
37
+ {
38
+ "type": "command",
39
+ "matcher": "Edit|Write|MultiEdit|NotebookEdit",
40
+ "command": "node \"${CLAUDE_PROJECT_DIR:-.}/.rulesync/hooks/post-edit.mjs\""
41
+ }
42
+ ]
10
43
  }
11
44
  }
@@ -3,132 +3,112 @@ root: false
3
3
  targets:
4
4
  - '*'
5
5
  globs:
6
- - '**/*'
7
- description: Engineering code conventions (TS, frontend, testing, git) - apply all of these to every change.
6
+ - 'apps/**'
7
+ - 'packages/**'
8
+ - 'tools/**'
9
+ - '*.config.*'
10
+ - 'package.json'
11
+ description: Engineering code conventions (TS, DB, frontend, testing, git) - the always-on core, with a routing table to full detail in docs/standards/.
8
12
  ---
9
13
 
10
14
  # Engineering conventions
11
15
 
12
- Portable code standard for this repo.
13
- The enforced import graph lives in `oss-boundaries`; SQL rules in `db-conventions`; Playwright rules in `e2e-conventions`.
16
+ The always-on core of the code standard: what you must obey while typing. Detail, examples, and
17
+ rationale live in `docs/standards/` - read the one file that matches the change instead of
18
+ carrying all of it. The enforced import graph lives in `oss-boundaries`; Playwright rules in
19
+ `e2e-conventions`; the always-on UI and SQL cores in `frontend-conventions` and `db-conventions`.
20
+
21
+ | Change you are making | Read first |
22
+ | ------------------------------------- | ------------------------------------ |
23
+ | schema, type, enum-like value set | `docs/standards/types.md` |
24
+ | function, service method, constructor | `docs/standards/functions.md` |
25
+ | new package, overlay, module layout | `docs/standards/module-structure.md` |
26
+ | a comment or JSDoc | `docs/standards/comments.md` |
27
+ | error class, catch, money path | `docs/standards/errors.md` |
28
+ | a test | `docs/standards/testing.md` |
29
+ | commit, PR | `docs/standards/git-delivery.md` |
30
+ | a failing gate, a new lint rule | `docs/standards/enforcement.md` |
31
+ | React/UI component, page, styling | `docs/standards/frontend.md` |
32
+ | SQL, Drizzle, migration, seed | `docs/standards/database.md` |
33
+
34
+ `docs/standards/frontend.md` doesn't apply to a headless/api-only repo - delete it (and its row
35
+ above) if this repo has no UI apps.
14
36
 
15
37
  ## Philosophy
16
38
 
17
- - Functional and declarative: pure functions, immutable data, composition. No stateful classes, no imperative accumulation loops.
18
- - Explicit over magic: no decorators, no auto-discovery, no reflection. Every wiring point is a greppable typed call (`ctx.provide(TOKEN, factory)`).
39
+ - Functional and declarative: pure functions, immutable data, composition. No stateful classes, no
40
+ imperative accumulation loops.
41
+ - Explicit over magic: no decorators, no auto-discovery, no reflection. Every wiring point is a
42
+ greppable typed call (`ctx.provide(TOKEN, factory)`).
19
43
  - Self-documenting: clear names beat comments (`percentChange`, not `d` + a comment).
20
- - YAGNI then DRY: don't build for imagined futures; abstract on the third occurrence, not the first.
44
+ - YAGNI then DRY: don't build for imagined futures; abstract on the third occurrence, not the
45
+ first.
21
46
  - Boring and consistent: match the surrounding code's idiom, naming, and density.
22
47
 
23
- ## Naming
24
-
25
- - Files `kebab-case.ts`, one concept per file, filename names the concept (`wallet.service.ts`; never `helpers.ts`, `utils2.ts`).
26
- - Types `PascalCase`; values/functions `camelCase`; true global constants `SCREAMING_SNAKE_CASE`.
27
- - Zod schemas `<Name>Schema`; the inferred type is the bare `<Name>`.
28
- - Booleans read as predicates (`isActive`, `canEdit`); IO functions as verbs (`fetchInvoice`); names carry units/intent (`delayMs`, `maxRetries`).
29
- - Money is a decimal string plus a `currency` field alongside it - `amount`, `balance`, `threshold`, never `amountCents`.
30
-
31
- ## Types
32
-
33
- - One source of truth per shape - infer, never hand-write a type that already exists: `z.infer<typeof UserSchema>`, `typeof users.$inferSelect`, `Omit<User, 'id'>`.
34
- - Schema-first at every boundary (HTTP, config, env, messages, events): validate once at the edge, trust the type after. oRPC + Zod does this for routes; do the same elsewhere.
35
- - Never re-infer a schema you imported - the owning contract exports the type once; import it.
36
- - No `any` outside tests - `unknown` + narrowing.
37
- - No `as` casts to silence the compiler - fix the root cause (`as const` is fine).
38
- - Never `!` non-null assertions - narrow explicitly, or restructure so the value is provably present (carry it on the object instead of re-looking it up).
39
- - Under `noUncheckedIndexedAccess`: `.at()`, destructure-with-default (`const [first = ''] = parts`), or an explicit guard - never `arr[i]!`.
40
- - `type` over `interface` (lint-enforced).
41
- - Type entity ids through their owning type (`playerId: Player['id']`), never a bare `string`.
42
- - Derive related schemas with `.pick()/.omit()/.partial()/.extend()/.merge()` - never re-type fields.
43
- - Enum-like value sets are a values + schema + type triple declared once on the contract surface: `X_STATUSES = [...] as const` -> `XStatusSchema = z.enum(X_STATUSES)` -> inferred `XStatus`. Never a TS `enum`, never a second hand-typed copy - import the one from `@openora/*`.
44
- - Make illegal states unrepresentable - discriminated unions (`{ status: 'ok'; data } | { status: 'error'; error }`) over optional-flag soup.
45
-
46
- ## Functions and modules
47
-
48
- - Pure functions with dependencies passed in as arguments; side effects only at the edges (services, adapters, plugins, handlers) - never in helpers.
49
- - Immutability: derive new objects (`{ ...user, roles: [...] }`), don't mutate.
50
- - Construct objects by spread + override, never field-by-field hand-copy. Keep fields explicit only for order-sensitive serialization, when the target must not receive some source fields, or when null-vs-undefined matters at a boundary.
51
- - A `class` is only a thin dependency-holding shell at a composition root; methods delegate to pure functions. No inheritance for reuse, no decorators - compose.
52
- - Short, single-purpose functions - if you'd write `// step 2` inside one, extract it.
53
- - Guard clauses first, main path last.
54
- - More than 3 parameters -> a single named-object param.
55
- - Don't annotate a return type TypeScript can infer. Annotate only when: inference can't (recursion), you deliberately widen/narrow, or it's the exported public API of a shared `packages/*` module - there the explicit type IS the contract. Argument types always stay explicit.
56
- - Named exports only - no default exports (exceptions: `*.config.*` files, `plugin.ts` whose loader reads `mod.default`, and Next.js App Router files; lint-enforced).
57
-
58
- ## Comments
59
-
60
- - Comment WHY, never WHAT: hidden constraint, invariant, bug workaround (link it), trade-off. If a block needs a comment to be understood, rename/extract instead.
61
- - No section-divider comments (`// ---`, `// ===`).
62
- - Every JSDoc is multi-line, always - `/**`, the text, and `*/` each on their own line. A single-line `/** ... */` is never allowed, even for one sentence. Add one only on an independent function/class (not a React component or hook) that is >~15 lines or has non-obvious params. One sentence; document the surprising contract, not the name.
63
- - Never JSDoc a React component or hook - a genuinely surprising note goes on the specific prop/param type, or an inline comment at the call site.
64
- - Deferred work: `// TODO:` with the concrete follow-up, never a bare TODO.
65
- - Placeholder/sample data and stubs: greppable `// mock:` comment so throwaway code stays findable.
66
-
67
- ## Frontend (any `apps/*` UI app and your shared UI package)
68
-
69
- Applies when this repo hosts UI apps; a headless api-only consumer can skip this section.
70
-
71
- - React Compiler is ON. Never hand-write `useMemo`/`useCallback`/`React.memo` - a compiler bail is a Rules-of-React violation to fix. Exception: your shared UI package is consumed pre-built, so hand-write stability there when it's part of a hook's contract (same reason `@openora/core/react` does).
72
- - Pick ONE component library and use its classes customized via utility classes + theme tokens. Don't hand-roll what the library provides.
73
- - Never hand-write component CSS selectors (`.btn-*{}`, `.table th{}`). A per-app `styles.css` holds only the theme plus custom properties for raw values with no token; every other style is a utility class on the element.
74
- - App-specific looks live in that app's `styles.css`; shared UI components stay visually neutral.
75
- - No hardcoded user-facing copy - every label goes through `t()` with a key in the module's `locales/`. Pattern: `locales/index.ts` exports `export const ns = registerTranslations('<module>', locales)`; components use `useTranslation(ns)`. Non-`en` files mirror `en.json` keys exactly.
76
- - Theme tokens and CSS variables are declared once in the shared UI package - style with semantic tokens (`bg-base-100`, `text-base-content`, `btn-primary`), never inline raw hex. A design color with no token: add it to BOTH dark and light theme blocks. A new token without a design source: ask the user first.
77
- - Hoist long class strings into a module-scope `const styles = { ... } as const` keyed by role - never inline long strings in JSX; merge with `cn()`.
78
- - Extract a repeated utility-class recipe into a shared component or constant on the third occurrence.
79
- - Import helpers like `cn()` from the shared UI package barrel - never deep-import.
80
- - Server state is not client state - key/cache/invalidate via the query lib, never `useEffect(fetch)`, never shadowed in ad-hoc caches.
81
-
82
- ## Modular architecture (every app)
83
-
84
- - Feature modules live in `src/modules/<m>/` with the same internal folders: `pages/`, `components/`, `hooks/`, `utils/`, `locales/`, and a public barrel `index.ts`.
85
- - App-level (non-module) code splits the same way: `src/lib/` holds stateful/integration code (API clients, SDK wrappers, config); `src/utils/` holds pure stateless helpers (formatters, converters).
86
- - No cross-module imports, ever. Cross-module communication is query invalidation or a domain event, never a direct import.
87
- - Outer composition code (`src/app/`, `src/routes/`, `extensions.config.ts`) imports modules only through their barrel; deep-importing internals is forbidden. Files inside a module use relative paths to siblings only, never `../../` out of the module.
88
- - Components in `components/` and `pages/` are presentation-only: props in, JSX out - no fetching, no side effects. Business logic, queries, and mutations live in `hooks/`, which accept external dependencies (oRPC calls, API clients) as parameters.
89
- - Next.js client components: `'use client'` on line 1 + `.client.tsx` suffix; server components are the default (no marker). All-client apps (Vite/TanStack) use no suffix.
90
- - One concept per file, exported name matches the kebab-case filename; split hooks and components into separate files.
91
-
92
- ## Package structure (`packages/*` and overlay packages)
93
-
94
- - One package = one concern, named `@<scope>/<kebab>`, with an explicit `exports` map. The entrypoint IS the public API; everything else is internal and off-limits to consumers (`oss-boundaries`).
95
- - Overlay/add-on packages mirror the platform module shape: `contract/`, `schema/`, `service/`, `router/`, `adapters/`, `__tests__/`, plus `plugin.ts` at the root as the single wiring point.
96
- - Each overlay owns its `drizzle.config.ts` and its own migration history - never share one migration folder across packages.
97
- - Pin exact dependency versions in every package; a package never depends on an app.
98
-
99
- ## Errors
100
-
101
- - Fail fast at boundaries with typed errors (`CreateOrderSchema.parse(raw)` throws early).
102
- - No silent catches - log with context and rethrow.
103
- - Typed, named error classes via the shared factories (`makeNotFoundError`/`makeOwnershipError`/`makeConflictError`); the router's `mapErrors` keys off the exported class.
104
- - `ORPCError.message` is an English fallback for logs, not player-facing copy - UI copy keys off `.code` plus typed `.data` fields.
105
- - Money/critical paths are transactional AND idempotent: a DB guard inside the transaction, not just an `idempotencyKey` (delivery is at-least-once).
106
-
107
- ## Testing
108
-
109
- - Co-locate as `src/__tests__/<name>.test.ts` (Vitest); service tests use a vi-mocked Drizzle.
110
- - Test behavior, not implementation - tests must survive a safe refactor (assert outputs, not private caches).
111
- - Cover new logic as part of the same change: unit tests for pure functions, authz negatives included.
112
- - Deterministic and isolated: no shared mutable state, no real network, seedable data.
113
-
114
- ## Dependencies
115
-
116
- - Pin exact versions - no `^`/`~`.
117
- - No inline `fetch`/`axios` in module code - third-party integrations are ports + adapters bound at the composition root (`ctx.provide(KYC_ADAPTER, ...)`).
118
- - Add a dependency deliberately - std lib or a few lines often beat a tree.
119
-
120
- ## Git and delivery
121
-
122
- - Conventional commits, enforced by commitlint (husky + CI): `feat`, `fix`, `refactor`, `chore`, `docs`, `test`, `ci`, `perf`. E.g. `feat(wallet): atomic debit command port`.
123
- - Subject starts lowercase, acronyms included (`feat(pam): kyc status filter`). This applies to the PR title too - squash merges derive the commit message from it.
124
- - One PR = one concern. Stage files explicitly; never `git add -A` when foreign changes are in the tree.
125
- - Green before review: typecheck + lint + unit tests pass; `pnpm verify` is the full gate (adds format:check + boundaries + build).
126
- - Branch off `dev`; never commit directly to a shared branch; never push without an explicit per-action "yes push".
127
- - PR description carries intent: what / why / acceptance criteria / ticket link. No secrets, internal hostnames, or PII - it is the public record.
128
-
129
- ## Enforcement
130
-
131
- - `pnpm check:types` + `pnpm check:lint` (oxlint) + `pnpm test:unit` is the fast gate; `pnpm check:boundaries` (dependency-cruiser) is the whole-graph boundary/cycle check, also run by the pre-commit hook and CI.
132
- - oxlint extends the platform's shared config (`./node_modules/@openora/core/oxlint/oxlintrc.json`) - add local rules on top, never fork it.
133
- - Don't work around a lint/boundary violation - fix the import.
134
- - Agent rules are generated from `.rulesync/` via `pnpm gen:agents` - never hand-edit a generated file.
48
+ ## Never (lint-enforced unless noted)
49
+
50
+ - `any` outside tests, `!` non-null assertions, `as` casts to silence the compiler (`as const` is
51
+ fine). Two sanctioned casts: test doubles through one `mock<T>()` helper (never inline in a
52
+ test), and a third-party inference boundary a library gives no honest way to satisfy (one cast,
53
+ one-line `// Library boundary:` note).
54
+ - `interface`, TS `enum`, decorators, inheritance for reuse, default exports (exceptions:
55
+ `*.config.*`, `plugin.ts`, Next.js App Router files).
56
+ - Hand-written duplicates of an inferrable type, re-inferring an imported schema, re-typing
57
+ derived schema fields, ad-hoc/duplicated Zod schemas outside a module's `contract/`.
58
+ - Re-exporting types "to be nice" - import from where defined.
59
+ - Inline `fetch`/`axios` in module code - third-party access is a port + adapter bound at the
60
+ composition root.
61
+ - Deep (`../../`+) relative imports that leave your module/zone, imports of another module's
62
+ internals, import cycles, deep `dist/`/`src/` paths into another package.
63
+ - SQL anti-patterns (bare `timestamp()`, CamelCase identifiers, hand-edited migrations) - detail
64
+ in `docs/standards/database.md`.
65
+ - Silent catches - log with context and rethrow. `ORPCError.message` rendered to a player - UI copy
66
+ keys off `.code` + typed `.data` through `t()`.
67
+ - Comments, unless one states a fact the code cannot contain (an external system's behaviour, a
68
+ spec constraint); a reason goes in the commit or PR, never inline. Never in tests. Detail:
69
+ `docs/standards/comments.md`.
70
+ - An in-process test that mocks the database, a repository, or a sibling service - found one in
71
+ the diff, delete it and replace it with the API E2E; never add to it.
72
+
73
+ ## Always
74
+
75
+ - **Naming:** files `kebab-case.ts`, one concept per file, filename names the concept
76
+ (`wallet.service.ts`, never `helpers.ts`); types `PascalCase`; values/functions `camelCase`;
77
+ true global constants `SCREAMING_SNAKE_CASE`; Zod schemas `<Name>Schema` with inferred type
78
+ `<Name>`; booleans read as predicates (`isActive`, `canEdit`); money is a decimal string plus a
79
+ `currency` field alongside it, never `amountCents`; IO functions are verbs (`fetchInvoice`); names
80
+ carry units and intent (`delayMs`, `maxRetries`).
81
+ - **One source of truth per shape** - infer, never hand-write: `z.infer<typeof XSchema>`,
82
+ `typeof x.$inferSelect`. Full detail: `docs/standards/types.md`.
83
+ - **Literal config arrays/objects (option lists, key sets) use `as const`**, not an explicit union
84
+ type annotation - let TypeScript infer the literal types.
85
+ - **Schema-first at every boundary** (HTTP, config, env, events); validate once at the edge, trust
86
+ the type after.
87
+ - **Entity ids typed through their owning type** (`playerId: Player['id']`), never a bare
88
+ `string`.
89
+ - **Guard clauses first, main path last; more than 3 params -> one named object** (a leading
90
+ `tx` handle may stay positional). Always brace control statements, even one-liners (lint:
91
+ `curly`). Detail: `docs/standards/functions.md`.
92
+ - **Construct objects by spread + override**, never a hand-copied field list.
93
+ - **Side effects at the edges**; money paths are transactional AND idempotent (a DB guard inside
94
+ the transaction, not just an idempotency key). Detail: `docs/standards/errors.md`.
95
+ - **Typed, named error classes** from the shared factories, mapped to transport in the router's
96
+ `mapErrors`.
97
+ - **Pin exact dependency versions** (no `^`/`~`); add a dependency deliberately - std lib or a few
98
+ lines often beat a tree.
99
+ - **A feature or fix PR ships its own tests** - no separate test PR. It ships the change, the
100
+ manual verification pass that proves it (drive the running stack by hand, attach a short video
101
+ per acceptance criterion, or the request/response trace for an API-only change, to the PR
102
+ description), and the tests that pass exercised. The diff shows them; the description does not list them.
103
+ Which tier each one belongs to, and how to run the manual pass: `docs/standards/testing.md`.
104
+ - **Green before review:** `/check` (typecheck + lint + unit tests) while iterating, `pnpm verify`
105
+ on the committed tree before the PR (the `guard-mr` hook refuses to open one until it passed on
106
+ HEAD). Conventional commits, lowercase subject (PR
107
+ title too - a squash merge turns it into the commit), one PR per concern. Never push without
108
+ explicit confirmation. The description carries what / why / acceptance criteria / bare ticket
109
+ key, the manual-verification evidence (a short video per acceptance criterion, before and after on
110
+ a fix) - but no test list or CI checklist the diff and pipeline already show, no URLs,
111
+ hostnames, secrets, or PII. Detail: `docs/standards/git-delivery.md`.
112
+ - **Fix the import, never work around a lint or boundary violation.** Agent rules are generated
113
+ from `.rulesync/` via `pnpm gen:agents` - never hand-edit a generated file. Detail:
114
+ `docs/standards/enforcement.md`.
@@ -4,80 +4,14 @@ targets:
4
4
  - '*'
5
5
  globs:
6
6
  - 'apps/api/**'
7
- description: SQL / Drizzle conventions for tables an overlay or local add-on owns.
7
+ description: SQL / Drizzle conventions for tables an overlay or local add-on owns - the always-on core; full detail in docs/standards/database.md.
8
8
  ---
9
9
 
10
10
  # Database conventions (SQL / Drizzle)
11
11
 
12
- Applies to every table an overlay or local add-on owns (`apps/api/src/extensions/<name>/src/schema/`).
13
- Tables live in `@openora/*` core for platform domains - never edit those; these rules govern the
14
- tables you add. Boundary/import rules live in `oss-boundaries`; this file is SQL only.
12
+ Applies to every table an overlay or local add-on owns (`apps/api/src/extensions/<name>/src/schema/`). Platform-domain tables live in `@openora/*` core - never edit those. Identifiers, timestamps, keys, indexes, N+1, idempotency and migrations are specified in `docs/standards/database.md` - read it before touching a schema, query, migration, or seed. The rules below are the ones that file does not state.
15
13
 
16
- ## Identifiers - snake_case everywhere
17
-
18
- Every drizzle instance sets `casing: 'snake_case'`, so the SQL name derives from the camelCase key.
19
- Pass an explicit name only where casing can't derive it: table names, `pgEnum` types, index names.
20
-
21
- ```ts
22
- // good - key derives the column; const camelCase; explicit snake_case only for table + index
23
- export const playerNote = pgTable(
24
- 'player_note',
25
- {
26
- id: uuid().primaryKey().defaultRandom(),
27
- playerId: uuid().notNull(), // -> player_id
28
- createdAt: timestamp({ withTimezone: true }).notNull().defaultNow(),
29
- },
30
- (t) => [index('player_note_player_id_idx').on(t.playerId)],
31
- );
32
-
33
- // bad - explicit/camelCase column names, PascalCase table
34
- pgTable('PlayerNote', { player_id: uuid('playerId') });
35
- ```
36
-
37
- ## Timestamps - always timestamptz
38
-
39
- ```ts
40
- createdAt: timestamp({ withTimezone: true }); // good - Postgres timestamptz, store UTC
41
- createdAt: timestamp(); // bad - naive, drops the zone
42
- ```
43
-
44
- Every datetime column (`createdAt`, `updatedAt`, `expiresAt`, any `*At`) carries the zone.
45
-
46
- ## Keys, references, indexes
47
-
48
- - UUID primary keys (`uuid().primaryKey().defaultRandom()`).
49
- - **No foreign keys across a module/overlay boundary** - store a plain ID string and resolve via the
50
- oRPC client or a schema subpath. FKs only within the same add-on.
51
- - `NOT NULL` by default; push defaults to the DB (`.notNull().default(...)`), not app code.
52
- - Index every column you filter or join on; name it `<table>_<cols>_idx`.
53
-
54
- ## Efficient operations
55
-
56
- ```ts
57
- // bad - N+1
58
- for (const id of ids) await db.select().from(wallet).where(eq(wallet.playerId, id));
59
- // good - one batched query
60
- await db.select().from(wallet).where(inArray(wallet.playerId, ids));
61
- ```
62
-
63
- - Select only the columns you use; don't `select(*)` wide rows to read one field.
64
- - **Build rows by spread + override, never hand-copy field-by-field.** When a row mostly mirrors a
65
- validated input, spread it and set only the server-computed fields - `db.insert(x).values({ ...input,
66
- id, createdAt })` - never re-list `field: input.field` per key (it silently drifts the moment a
67
- column is added). Keep fields explicit only for: an order-sensitive hash/signature payload; a source
68
- carrying columns the row must not receive (spread then omit them); or a null-vs-undefined boundary
69
- that won't coerce (`actorId: input.actorId ?? null`).
70
- - **Money / critical paths are transactional and idempotent** - a DB guard inside the transaction,
71
- not just an `idempotencyKey` (delivery is at-least-once).
72
-
73
- ```ts
74
- await db.transaction(async (t) => {
75
- if (await ledgerExists(t, idempotencyKey)) return; // guard, not just a key
76
- await insertLedger(t, { idempotencyKey, amountCents });
77
- });
78
- ```
79
-
80
- ## Migrations
81
-
82
- - Never hand-edit generated migrations. Change the `pgTable`, then `pnpm db:migrate`.
83
- - One migration per schema change; review the generated SQL before committing.
14
+ - Money: exact decimal, never float, never a scaled integer. Every money column is `decimal()` (Postgres `NUMERIC`) - never `real`/`float`, never an `integer` "cents" column. Pair it with a `currency` column; on the wire use `MoneyAmountSchema` (decimal string) + `currency`, never `z.number()`. Balance math runs in SQL, never JS float arithmetic.
15
+ - `pgEnum` derives from a values + schema + type triple declared once (never an inline value array): `X_STATUSES = [...] as const` -> `XStatusSchema = z.enum(X_STATUSES)` -> `pgEnum('x_status', X_STATUSES)`.
16
+ - Bound the fan-out: never `Promise.all(rows.map(fn))` when `rows` is a query result and `fn` calls out per row (a vendor adapter, another service) - it opens unbounded concurrent connections/requests and starves everything else at scale. Use `mapConcurrent(items, limit, fn)` (`@openora/core/server`).
17
+ - Audit every mutation: each state-changing action emits a domain event the `audit` add-on subscribes to, or resolves `AUDIT_WRITER` and calls `record(...)`. A mutation with no audit trail is not done.
@@ -4,23 +4,49 @@ targets:
4
4
  - '*'
5
5
  globs:
6
6
  - 'apps/e2e/**'
7
- description: Playwright E2E conventions - dual-mode (USE_MOCKS) specs, fixtures, mocks, page objects.
7
+ description: Playwright E2E conventions - specs run against the real stack; mocking is a narrow, justified exception.
8
8
  ---
9
9
 
10
10
  # E2E conventions (`apps/e2e`)
11
11
 
12
- Every spec is written ONCE and runs in two modes, switched by `USE_MOCKS`:
12
+ Applies once this repo has an `apps/e2e` Playwright suite; a repo without one is not covered by this rule, and adding the suite is what turns it on.
13
13
 
14
- - `USE_MOCKS=true` - CI / pull request: requests fulfilled from `mocks/`, no stack needed, blocks merge.
15
- - unset - scheduled/local run against the real seeded API (`pnpm dev` stack must be up); failures alert, don't block.
14
+ This file governs **how** a spec is written. A feature or fix PR ships its specs in the same branch as the change, after the manual verification pass (`docs/standards/testing.md`).
15
+
16
+ Two kinds of spec live here:
17
+
18
+ - **Browser specs** (`tests/<app>/**`) - a player or admin journey through the UI.
19
+ - **API specs** (`tests/api/**`) - the `api` Playwright project: no browser, no `page`. Drives the real API over HTTP against real Postgres, with each external vendor replaced by a stub HTTP server the API is pointed at by env. This is the tier that proves an overlay end to end: request -> route -> service -> rows -> webhook -> resulting state. `USE_MOCKS` does not apply here at all.
20
+
21
+ ## Real stack by default
22
+
23
+ Every spec runs against the real seeded stack - API, Postgres, and the apps under test - and that
24
+ run is what blocks merge. A test that never executes the backend cannot tell you the backend works.
25
+
26
+ `USE_MOCKS=true` intercepts responses in the browser and exists only for a state you cannot produce
27
+ for real: a third-party widget or redirect you are not allowed to run in CI. It is an exception you
28
+ justify per spec, never the mode a suite is written for. Anything reachable by seeding data or by
29
+ scripting a vendor stub is NOT such a state - script the stub instead, and prefer the API tier when
30
+ the behaviour under test is the backend's.
31
+
32
+ Existing mocked specs are converted as they are touched; delete the fixture with the last spec that
33
+ used it.
16
34
 
17
35
  ## Rules
18
36
 
19
37
  - Import `test`/`expect` from `fixtures.ts`, NEVER from `@playwright/test` - fixtures add `cleanup()` and shared setup.
20
- - `mockApi(page, routes)` (from `lib/mocks.ts`) registers interceptions only under `USE_MOCKS`; in real mode it's a no-op, so the same assertions exercise the live backend. Never branch test logic on the mode.
21
- - Mocks are typed: fixture shapes in `mocks/<domain>.ts` mirror the response contract - type platform-endpoint fixtures with the `z.infer` contract type from `@openora/*` so a contract change fails typecheck. No loose hand-written JSON.
38
+ - Set up state through the product: seed data or drive the API, so the spec exercises the same path a player would. `mockApi(page, routes)` (from `lib/mocks.ts`) is the escape hatch above - reach for it only after the real setup is genuinely impossible, and never branch test logic on the mode.
39
+ - A mock that stays is typed: fixture shapes in `mocks/<domain>.ts` mirror the response contract - type platform-endpoint fixtures with the `z.infer` contract type from `@openora/*` so a contract change fails typecheck. No loose hand-written JSON.
22
40
  - Selectors use `data-testid` - kebab-case, domain-prefixed (`chat-message`, `chat-input`). Never assert on CSS classes or component-library structure; shared UI components spread props so `data-testid` passes through.
23
41
  - Page objects in `pages/<name>.page.ts` are functional factories - no classes, no `this`; locators + actions returned as a plain object.
24
42
  - Test names are behavioural: "shows masked standings", not "table renders".
25
- - `cleanup(fn)` reverses any real data a test creates (runs in reverse order; no-op under mocks).
43
+ - `cleanup(fn)` reverses any data a test creates (runs in reverse order) - the suite shares one database, so a spec that leaks rows breaks the next one.
26
44
  - Layout: `tests/<app>/<domain>/<scenario>.spec.ts` (one Playwright project per app, sharing fixtures/mocks/pages; run one with `--project=<app>`), `mocks/<domain>.ts`, `pages/<name>.page.ts`.
45
+
46
+ ## API specs (`tests/api/**`)
47
+
48
+ - Use `request` (Playwright's APIRequestContext), never `page`. Assert status, body, and the state a follow-up request reports - not internals.
49
+ - A vendor stub is a plain `node:http` server under `apps/e2e/`, modelled on `mock-identity-server.mjs`: it answers only the vendor endpoints the flow reaches and records the calls a spec asserts on. Point the API at it with the vendor's base-URL env var; every vendor adapter must accept one.
50
+ - Drive the vendor's inbound side the way the vendor does - post the real webhook shape to the real route with a signature the stub's key material produces. Never call the adapter directly.
51
+ - Own your data: create the player the spec needs and reverse it with `cleanup(fn)`. The suite shares one database.
52
+ - Layout: `tests/api/<domain>/<scenario>.spec.ts`.