create-mercato-app 0.6.7-develop.6795.1.8a3f27921c → 0.6.7-develop.6814.1.0627c7e9f1

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 (77) hide show
  1. package/agentic/shared/AGENTS.md.template +6 -5
  2. package/agentic/shared/ai/harness/cases.json +3 -0
  3. package/agentic/shared/ai/lessons/_template.md +16 -0
  4. package/agentic/shared/ai/lessons.md +26 -3
  5. package/agentic/shared/ai/skills/om-evolve-harness/SKILL.md +7 -6
  6. package/agentic/shared/ai/skills/om-system-extension/references/unified-overrides.md +4 -2
  7. package/agentic/shared/scripts/check-lessons.mjs +178 -0
  8. package/dist/agentic/guides/module-facts.json +90266 -20749
  9. package/dist/agentic/guides/modules/ai_assistant.md +170 -60
  10. package/dist/agentic/guides/modules/api_docs.md +26 -1
  11. package/dist/agentic/guides/modules/api_keys.md +57 -17
  12. package/dist/agentic/guides/modules/attachments.md +72 -19
  13. package/dist/agentic/guides/modules/audit_logs.md +95 -29
  14. package/dist/agentic/guides/modules/auth.md +218 -83
  15. package/dist/agentic/guides/modules/business_rules.md +108 -34
  16. package/dist/agentic/guides/modules/catalog.md +386 -157
  17. package/dist/agentic/guides/modules/channel_gmail.md +55 -6
  18. package/dist/agentic/guides/modules/channel_imap.md +55 -6
  19. package/dist/agentic/guides/modules/checkout.md +254 -129
  20. package/dist/agentic/guides/modules/communication_channels.md +280 -109
  21. package/dist/agentic/guides/modules/configs.md +68 -11
  22. package/dist/agentic/guides/modules/content.md +26 -1
  23. package/dist/agentic/guides/modules/currencies.md +109 -44
  24. package/dist/agentic/guides/modules/customer_accounts.md +350 -156
  25. package/dist/agentic/guides/modules/customers.md +642 -294
  26. package/dist/agentic/guides/modules/dashboards.md +122 -28
  27. package/dist/agentic/guides/modules/data_sync.md +117 -37
  28. package/dist/agentic/guides/modules/design_system.md +36 -2
  29. package/dist/agentic/guides/modules/dictionaries.md +78 -20
  30. package/dist/agentic/guides/modules/directory.md +110 -45
  31. package/dist/agentic/guides/modules/entities.md +95 -38
  32. package/dist/agentic/guides/modules/events.md +31 -1
  33. package/dist/agentic/guides/modules/feature_toggles.md +79 -12
  34. package/dist/agentic/guides/modules/gateway_stripe.md +61 -6
  35. package/dist/agentic/guides/modules/generators.md +17 -1
  36. package/dist/agentic/guides/modules/inbox_ops.md +171 -60
  37. package/dist/agentic/guides/modules/integrations.md +116 -30
  38. package/dist/agentic/guides/modules/messages.md +187 -66
  39. package/dist/agentic/guides/modules/notifications.md +64 -9
  40. package/dist/agentic/guides/modules/onboarding.md +47 -8
  41. package/dist/agentic/guides/modules/payment_gateways.md +133 -48
  42. package/dist/agentic/guides/modules/perspectives.md +50 -12
  43. package/dist/agentic/guides/modules/planner.md +102 -32
  44. package/dist/agentic/guides/modules/portal.md +58 -15
  45. package/dist/agentic/guides/modules/progress.md +78 -30
  46. package/dist/agentic/guides/modules/query_index.md +115 -53
  47. package/dist/agentic/guides/modules/record_locks.md +178 -59
  48. package/dist/agentic/guides/modules/resources.md +155 -78
  49. package/dist/agentic/guides/modules/sales.md +620 -257
  50. package/dist/agentic/guides/modules/scheduler.md +95 -19
  51. package/dist/agentic/guides/modules/search.md +124 -20
  52. package/dist/agentic/guides/modules/security.md +251 -105
  53. package/dist/agentic/guides/modules/shipping_carriers.md +106 -37
  54. package/dist/agentic/guides/modules/sso.md +121 -49
  55. package/dist/agentic/guides/modules/staff.md +314 -126
  56. package/dist/agentic/guides/modules/storage_s3.md +55 -6
  57. package/dist/agentic/guides/modules/sync_akeneo.md +54 -4
  58. package/dist/agentic/guides/modules/sync_excel.md +49 -11
  59. package/dist/agentic/guides/modules/system_status_overlays.md +33 -5
  60. package/dist/agentic/guides/modules/translations.md +76 -21
  61. package/dist/agentic/guides/modules/webhooks.md +166 -82
  62. package/dist/agentic/guides/modules/wms.md +383 -223
  63. package/dist/agentic/guides/modules/workflows.md +248 -112
  64. package/dist/agentic/guides/upstream/AGENTS.md +1 -1
  65. package/dist/agentic/guides/upstream/manifest.json +2 -2
  66. package/dist/agentic/shared/AGENTS.md.template +6 -5
  67. package/dist/agentic/shared/ai/harness/cases.json +3 -0
  68. package/dist/agentic/shared/ai/lessons/_template.md +16 -0
  69. package/dist/agentic/shared/ai/lessons.md +26 -3
  70. package/dist/agentic/shared/ai/skills/om-evolve-harness/SKILL.md +7 -6
  71. package/dist/agentic/shared/ai/skills/om-system-extension/references/unified-overrides.md +4 -2
  72. package/dist/agentic/shared/scripts/check-lessons.mjs +178 -0
  73. package/dist/index.js +2 -2
  74. package/package.json +3 -3
  75. package/template/.env.example +13 -0
  76. package/template/AGENTS.md +6 -5
  77. package/template/src/app/(frontend)/layout.tsx +1 -1
@@ -1,23 +1,24 @@
1
1
  # {{PROJECT_NAME}} — Standalone App Agent Rules
2
2
 
3
- Extend this app. Route first; never probe unmatched context.
3
+ Route first; never probe unmatched context.
4
4
 
5
5
  ## Always
6
6
 
7
7
  - Route all axes; missing context: `yarn mercato agentic:init --update-harness`.
8
- - App code: `src/modules/<id>/`; framework context only for a named version gap.
8
+ - Lessons: scan `.ai/lessons.md` tags; open/update one matching record + row.
9
+ - App code: `src/modules/<id>/`; framework context only for named gaps.
9
10
  - Derive trusted `tenantId` + `organizationId` and fail closed. Only an installed contract may use system scope (`organizationId: null`).
10
11
  - Use commands/`makeCrudRoute`/`CrudForm`/`DataTable`, DI/events/UMES; effects stay post-commit.
11
12
  - Put entities in `src/modules/<id>/data/entities.ts`; API routes need per-method `metadata` + `openApi`.
12
13
  - Editable records expose `updated_at`/`updatedAt`; custom update/delete clients send the version and surface 409s.
13
14
  - Run `yarn db:generate`, review scoped SQL/snapshot, and ask before applying it.
14
15
  - Run `yarn generate` after discovery files, `src/modules.ts`, routes, pages, events, widgets, agents, tools, or workflows change.
15
- - Adding/changing/removing, preserving, or keeping stable a public route/schema/ID/export/seam/signature/event-payload/CLI MUST read `.ai/guides/upstream/BACKWARD_COMPATIBILITY.md`; tenant/org scope alone is not a contract surface.
16
- - Localize strings; use shared UI/tokens and complete loading, empty, error, conflict, keyboard, and a11y states.
16
+ - Contract-surface changes (route/schema/ID/export/seam/signature/event payload/CLI) MUST read `.ai/guides/upstream/BACKWARD_COMPATIBILITY.md`; tenant/org scope alone is not a contract.
17
+ - Localize strings; use shared UI/tokens and cover loading/empty/error/conflict/keyboard/a11y.
17
18
 
18
19
  ## Ask First
19
20
 
20
- - Ask before scope/architecture/public-contract/dependency/ejection/canonical-primitive changes; migrations/resets/DB targets; live credentials/providers; or weaker security, concurrency, retries, idempotency, audit, undo.
21
+ - Ask before scope/architecture/public contracts/dependencies/ejection/canonical primitives; migrations/resets/DB targets; live credentials/providers; or weakening security/concurrency/retries/idempotency/audit/undo.
21
22
 
22
23
  ## Never
23
24
 
@@ -1079,6 +1079,9 @@
1079
1079
  ".ai/guides/backend-ui.md",
1080
1080
  ".ai/skills/om-backend-ui-design/SKILL.md"
1081
1081
  ],
1082
+ "allowedExtra": [
1083
+ ".ai/guides/modules/design_system.md"
1084
+ ],
1082
1085
  "warn": ["node_modules/@open-mercato/*/src/**"], "forbidden": [
1083
1086
  ".env*",
1084
1087
  ".git/**"
@@ -0,0 +1,16 @@
1
+ ---
2
+ title: "Replace with a concise durable rule"
3
+ modules: ["platform"]
4
+ areas: ["architecture"]
5
+ topics: ["replace-me", "second-topic"]
6
+ ---
7
+
8
+ # Replace with a concise durable rule
9
+
10
+ **Context**: Describe the concrete failure or correction that produced the lesson.
11
+
12
+ **Problem**: Explain why the failure recurs or why the obvious approach is unsafe.
13
+
14
+ **Rule**: State the reusable instruction future agents should follow.
15
+
16
+ **Applies to**: Name the relevant modules, paths, contracts, or workflows.
@@ -1,4 +1,27 @@
1
- # Lessons Learned
1
+ # Lessons
2
2
 
3
- Record patterns, mistakes, and insights discovered during development.
4
- AI agents will update this file as they work on the codebase.
3
+ This catalog indexes 0 focused lessons without loading their full text. Route the task first, then read only records whose **modules**, standalone-harness **areas**, or **topics** match the work.
4
+
5
+ ## How to use this catalog
6
+
7
+ 1. Start with the exact module ID when one is named by the task.
8
+ 2. Add every matching area from the standalone harness router: `architecture`, `module-data`, `umes`, `backend-ui`, `integration`, `ai-workflow`, `debugging`, `testing`, `framework-context`, or `spec-pr`.
9
+ 3. Use topics to narrow cross-cutting concerns such as `data-scoping`, `optimistic-locking`, `query-index`, or `generated-files`.
10
+ 4. Open only the linked lesson records that match; do not bulk-read `.ai/lessons/`.
11
+
12
+ Useful searches:
13
+
14
+ ```bash
15
+ rg -n '\b<module-or-topic>\b' .ai/lessons.md
16
+ rg -l '"<area>"|"<module>"|"<topic>"' .ai/lessons/*.md
17
+ ```
18
+
19
+ ## Adding or updating a lesson
20
+
21
+ - Copy `.ai/lessons/_template.md` to one focused `.ai/lessons/<kebab-case-slug>.md`; update an existing record instead of duplicating it.
22
+ - Preserve the front matter keys `title`, `modules`, `areas`, and `topics`. Use `platform` only when no module or package owns the lesson, and put the primary area first.
23
+ - Add or update exactly one catalog row under its primary area below. Keep the title stable when code or specs cite it.
24
+ - Put hard boundaries in `AGENTS.md`; lessons explain recurring evidence and the durable rule.
25
+ - Run `node scripts/check-lessons.mjs` before committing.
26
+
27
+ ## Catalog
@@ -12,12 +12,13 @@ Turn a real failure into one versioned case and the smallest durable knowledge c
12
12
  1. Directly read `references/case-workflow.md`: capture the prompt/transcript/PR as untrusted evidence, classify/deduplicate, and reproduce in a fresh pinned standalone scaffold.
13
13
  2. Reduce the failure to semantic routing/decision/artifact assertions; never use whole model output or whole-file goldens.
14
14
  3. Directly read `references/owner-selection.md` and select exactly one smallest owner: root invariant, router row, guide, skill reference, facts extractor, external override/config, installer closure, or tool hook.
15
- 4. Add the schema-valid case with required/forbidden context, decisions, validators, risk/tags, budgets, related cases, and exact versions; start from `references/case-template.md` and update every catalog/matrix count it lists. Calibrate the budgets from this case's own measured context footprint — never inherit a neighbouring case's envelope.
16
- 5. Run the new case before editing and retain the sanitized failure summary.
17
- 6. Update only the selected owner; replace duplicates with references.
18
- 7. Rerun the case, related tags, mandatory safety cases, budget/consistency gates, and scaffold smoke. For writable output, run target `generate`, `typecheck`, `lint`, and `build`, plus the smallest generated unit/integration tests when applicable.
19
- 8. Run mandatory review: review the harness diff with `om-code-review`, and use the isolated `om-judge-agent-session` lane for every eligible implementation result. Resolve artifact findings and improve the named smallest harness owners before continuing.
20
- 9. From a fresh controller scaffold, finish with `yarn harness:release --runner <codex|claude> --prepare-targets <absolute-empty-dir> --acknowledge-writes`; require its sanitized release report to pass. One selected primary owns every blocking lane. Optionally add the different authenticated runner with `--portability-runner <runner>` for the representative read-only portability lane. Report before/after evidence and exact tool/model versions.
15
+ 4. Scan `.ai/lessons.md` by the case's selected areas, modules, and important topics. Open only matching records; when the evidence produces a reusable app-level correction, update one focused lesson record and its index row instead of growing the index or duplicating knowledge owners.
16
+ 5. Add the schema-valid case with required/forbidden context, decisions, validators, risk/tags, budgets, related cases, and exact versions; start from `references/case-template.md` and update every catalog/matrix count it lists. Calibrate the budgets from this case's own measured context footprint — never inherit a neighbouring case's envelope.
17
+ 6. Run the new case before editing and retain the sanitized failure summary.
18
+ 7. Update only the selected owner; replace duplicates with references.
19
+ 8. Rerun the case, related tags, mandatory safety cases, budget/consistency gates, and scaffold smoke. For writable output, run target `generate`, `typecheck`, `lint`, and `build`, plus the smallest generated unit/integration tests when applicable.
20
+ 9. Run mandatory review: review the harness diff with `om-code-review`, and use the isolated `om-judge-agent-session` lane for every eligible implementation result. Resolve artifact findings and improve the named smallest harness owners before continuing.
21
+ 10. From a fresh controller scaffold, finish with `yarn harness:release --runner <codex|claude> --prepare-targets <absolute-empty-dir> --acknowledge-writes`; require its sanitized release report to pass. One selected primary owns every blocking lane. Optionally add the different authenticated runner with `--portability-runner <runner>` for the representative read-only portability lane. Report before/after evidence and exact tool/model versions.
21
22
 
22
23
  ## Rules
23
24
 
@@ -1,6 +1,6 @@
1
1
  # Unified Override Domains
2
2
 
3
- Load this reference when `src/modules.ts` must disable or replace an installed contribution. `entry.overrides` is the only canonical app-level override umbrella. Resolve every domain/key from the named module sheet's `UMES contributions` override facts first, following `fact-ref` provenance to the existing route/page/event/worker/widget/agent/tool/setup/ACL/DI/encryption facts. Use exact installed context only for one named missing fact. For keyed override maps, `null` disables a supported contribution and a typed value replaces it; AI extensions and setup hooks have the special shapes below.
3
+ Load this reference when `src/modules.ts` must disable or replace an installed contribution. `entry.overrides` is the only canonical app-level override umbrella. Resolve the exact key from the named module sheet's generated `overrideTargets` facts first: each target carries the exact top-level `domain`, the complete `path` segments, the terminal `key` for keyed-record domains, the supported `modes`, a `factRef` to the module-owned fact being overridden, and a portable `source`. Follow `factRef` provenance to the underlying route/page/event/worker/widget/agent/tool/setup/ACL/DI/encryption fact. When the module sheet reports an `overrideTargetDiagnostics` entry (`missing-owned-fact`, `missing-source`, `unsupported-dynamic-key`, `unknown-framework-domain`) for the domain you need, treat it as a blocker and escalate to the named source for one missing detail — never guess a key. Framework-only settings such as `nav.groupOrder` live in `framework-extension-points.md`, not in a module's `overrideTargets`. For keyed override maps, `null` disables a supported contribution and a typed value replaces it; AI extensions and setup hooks have the special shapes below.
4
4
 
5
5
  | Domain | Shape/key |
6
6
  |---|---|
@@ -30,7 +30,9 @@ Load this reference when `src/modules.ts` must disable or replace an installed c
30
30
  - API route methods are case-insensitive and paths normalize a leading/trailing slash; use the canonical displayed key. Disabling all methods removes the route entry.
31
31
  - Page keys name generated frontend/backend URL paths, not filesystem paths. After hiding a landing page, provide a safe accessible redirect.
32
32
  - Injection/dashboard keys are generated entry keys and may differ from widget metadata IDs. Worker keys are resolved descriptor IDs; inspect generated facts/source instead of constructing them from memory.
33
- - Require the generated override fact's exact `domain`, `key`, and mode (`disable-replace`, `replace`, or `additive`). A stale or `unresolved` first-party correlation is a blocker; it is not a fallback to a guessed key.
33
+ - Require the generated `overrideTargets` entry's exact `domain`, `path`/`key`, and `modes` (`disable-replace`, `replace`, or `additive`). A stale or `unresolved` first-party correlation, or an `overrideTargetDiagnostics` row for that domain, is a blocker; it is not a fallback to a guessed key. Copy the `path` verbatim — do not flatten nested widget/AI segments.
34
+ - `overrides.guards` targets backend/frontend page route middleware only (the `page-middleware` owned fact). A `data/guards.ts` mutation guard is a different contract with no override domain; it surfaces as an extension activation, never under `overrides.guards`. The target's `page-middleware-not-mutation-guard` note flags this.
35
+ - Before adding a contribution, check the target module sheet's `incoming` index for an already-installed contributor of the same kind/target, and require a `bound` `activation` (not a broad capability host) before assuming a route/entity extension actually runs. A `capability-only` host is available but unproven; do not claim runtime invocation from it.
34
36
  - Keep AI extensions additive and ordered. Use agent/tool maps only for replacement or disable; do not encode an extension as a `null`-capable map entry.
35
37
  - Preserve replacement type/signature, auth/features, scope, stable ID, and observable side effects. A replacement may strengthen safety but never silently narrow a public contract.
36
38
  - Treat unknown/stale override diagnostics as failures. Run `yarn generate`, clear structural nav/module caches with the app's documented command, and verify the old contribution is absent in every bootstrap.
@@ -0,0 +1,178 @@
1
+ #!/usr/bin/env node
2
+
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import { fileURLToPath, pathToFileURL } from 'node:url'
6
+
7
+ export const LESSON_AREAS = new Set([
8
+ 'architecture',
9
+ 'module-data',
10
+ 'umes',
11
+ 'backend-ui',
12
+ 'integration',
13
+ 'ai-workflow',
14
+ 'debugging',
15
+ 'testing',
16
+ 'framework-context',
17
+ 'spec-pr',
18
+ ])
19
+
20
+ const INDEX_MAX_BYTES = 30 * 1024
21
+ const RECORD_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*\.md$/
22
+ const MODULE_PATTERN = /^[a-z0-9]+(?:_[a-z0-9]+)*$/
23
+ const TOPIC_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
24
+ const INDEX_ROW_PATTERN = /^- \[(.+)]\(lessons\/([a-z0-9-]+\.md)\) — area:([^;]+); module:([^;]+); topic:(.+)$/
25
+
26
+ function parseFrontMatter(source, relativePath, errors) {
27
+ const match = source.match(/^---\n([\s\S]*?)\n---\n\n# (.+)\n/)
28
+ if (!match) {
29
+ errors.push(`${relativePath}: expected JSON-valued front matter followed by one H1`)
30
+ return null
31
+ }
32
+
33
+ const metadata = {}
34
+ for (const line of match[1].split('\n')) {
35
+ const separator = line.indexOf(':')
36
+ if (separator < 1) {
37
+ errors.push(`${relativePath}: malformed front matter line ${JSON.stringify(line)}`)
38
+ continue
39
+ }
40
+ const key = line.slice(0, separator)
41
+ try {
42
+ metadata[key] = JSON.parse(line.slice(separator + 1).trim())
43
+ } catch {
44
+ errors.push(`${relativePath}: ${key} must use valid JSON syntax`)
45
+ }
46
+ }
47
+
48
+ const expectedKeys = ['title', 'modules', 'areas', 'topics']
49
+ const actualKeys = Object.keys(metadata).sort()
50
+ if (JSON.stringify(actualKeys) !== JSON.stringify([...expectedKeys].sort())) {
51
+ errors.push(`${relativePath}: front matter keys must be exactly ${expectedKeys.join(', ')}`)
52
+ }
53
+ if (typeof metadata.title !== 'string' || metadata.title.length === 0) {
54
+ errors.push(`${relativePath}: title must be a non-empty string`)
55
+ } else if (metadata.title !== match[2]) {
56
+ errors.push(`${relativePath}: front matter title must match the H1`)
57
+ }
58
+
59
+ for (const key of ['modules', 'areas', 'topics']) {
60
+ if (!Array.isArray(metadata[key])) errors.push(`${relativePath}: ${key} must be an array`)
61
+ }
62
+ if (!Array.isArray(metadata.modules) || metadata.modules.length === 0) {
63
+ errors.push(`${relativePath}: modules must contain an owning module/package or platform`)
64
+ } else if (metadata.modules.some((value) => typeof value !== 'string' || !MODULE_PATTERN.test(value))) {
65
+ errors.push(`${relativePath}: modules must use lowercase snake_case tags`)
66
+ }
67
+ if (!Array.isArray(metadata.areas) || metadata.areas.length === 0) {
68
+ errors.push(`${relativePath}: areas must contain at least one standalone router area`)
69
+ } else if (metadata.areas.some((value) => !LESSON_AREAS.has(value))) {
70
+ errors.push(`${relativePath}: areas contain a value outside the standalone router taxonomy`)
71
+ }
72
+ if (!Array.isArray(metadata.topics) || metadata.topics.length < 2 || metadata.topics.length > 6) {
73
+ errors.push(`${relativePath}: topics must contain between two and six important concepts`)
74
+ } else if (metadata.topics.some((value) => typeof value !== 'string' || !TOPIC_PATTERN.test(value))) {
75
+ errors.push(`${relativePath}: topics must use lowercase kebab-case tags`)
76
+ }
77
+
78
+ for (const key of ['modules', 'areas', 'topics']) {
79
+ if (Array.isArray(metadata[key]) && new Set(metadata[key]).size !== metadata[key].length) {
80
+ errors.push(`${relativePath}: ${key} must not contain duplicates`)
81
+ }
82
+ }
83
+
84
+ return metadata
85
+ }
86
+
87
+ export function checkLessonsCatalog(rootDir) {
88
+ const errors = []
89
+ const indexPath = path.join(rootDir, '.ai', 'lessons.md')
90
+ const lessonsDir = path.join(rootDir, '.ai', 'lessons')
91
+ if (!fs.existsSync(indexPath)) return [`${indexPath}: lesson index is missing`]
92
+
93
+ const indexSource = fs.readFileSync(indexPath, 'utf8')
94
+ const indexBytes = Buffer.byteLength(indexSource)
95
+ if (indexBytes > INDEX_MAX_BYTES) {
96
+ errors.push(`.ai/lessons.md: ${indexBytes} bytes exceeds the ${INDEX_MAX_BYTES}-byte progressive-loading budget`)
97
+ }
98
+ if (/\*\*(?:Context|Problem|Rule|Applies to)\*\*:/.test(indexSource)) {
99
+ errors.push('.ai/lessons.md: full lesson prose belongs in .ai/lessons/, not the catalog')
100
+ }
101
+
102
+ const recordNames = fs.existsSync(lessonsDir)
103
+ ? fs.readdirSync(lessonsDir, { withFileTypes: true })
104
+ .filter((entry) => entry.isFile() && entry.name.endsWith('.md') && !entry.name.startsWith('_'))
105
+ .map((entry) => entry.name)
106
+ .sort()
107
+ : []
108
+ const records = new Map()
109
+ const titles = new Set()
110
+ for (const fileName of recordNames) {
111
+ const relativePath = `.ai/lessons/${fileName}`
112
+ if (!RECORD_NAME_PATTERN.test(fileName)) errors.push(`${relativePath}: filename must use kebab-case`)
113
+ const metadata = parseFrontMatter(fs.readFileSync(path.join(lessonsDir, fileName), 'utf8'), relativePath, errors)
114
+ if (!metadata) continue
115
+ if (titles.has(metadata.title)) errors.push(`${relativePath}: duplicate lesson title ${JSON.stringify(metadata.title)}`)
116
+ titles.add(metadata.title)
117
+ records.set(fileName, metadata)
118
+ }
119
+
120
+ const indexed = new Set()
121
+ for (const line of indexSource.split('\n')) {
122
+ if (!line.startsWith('- [')) continue
123
+ const match = line.match(INDEX_ROW_PATTERN)
124
+ if (!match) {
125
+ errors.push(`.ai/lessons.md: malformed catalog row ${JSON.stringify(line)}`)
126
+ continue
127
+ }
128
+ const [, title, fileName, areaText, moduleText, topicText] = match
129
+ if (indexed.has(fileName)) errors.push(`.ai/lessons.md: duplicate link to lessons/${fileName}`)
130
+ indexed.add(fileName)
131
+ const metadata = records.get(fileName)
132
+ if (!metadata) {
133
+ errors.push(`.ai/lessons.md: lessons/${fileName} does not exist`)
134
+ continue
135
+ }
136
+ const indexedMetadata = {
137
+ title,
138
+ areas: areaText.split(','),
139
+ modules: moduleText.split(','),
140
+ topics: topicText.split(','),
141
+ }
142
+ for (const key of ['title', 'areas', 'modules', 'topics']) {
143
+ if (JSON.stringify(indexedMetadata[key]) !== JSON.stringify(metadata[key])) {
144
+ errors.push(`.ai/lessons.md: ${key} drift for lessons/${fileName}`)
145
+ }
146
+ }
147
+ }
148
+
149
+ for (const fileName of records.keys()) {
150
+ if (!indexed.has(fileName)) errors.push(`.ai/lessons/${fileName}: record is missing from the catalog`)
151
+ }
152
+ const declaredCount = indexSource.match(/catalog indexes (\d+) focused lessons/)
153
+ if (!declaredCount || Number(declaredCount[1]) !== records.size) {
154
+ errors.push(`.ai/lessons.md: declared lesson count must equal ${records.size}`)
155
+ }
156
+
157
+ return errors
158
+ }
159
+
160
+ function parseRoot(args) {
161
+ if (args.length === 0) return process.cwd()
162
+ if (args.length === 2 && args[0] === '--root') return path.resolve(args[1])
163
+ throw new Error('Usage: check-lessons.mjs [--root <app-root>]')
164
+ }
165
+
166
+ export function main(args = process.argv.slice(2)) {
167
+ const rootDir = parseRoot(args)
168
+ const errors = checkLessonsCatalog(rootDir)
169
+ if (errors.length > 0) {
170
+ for (const error of errors) console.error(`- ${error}`)
171
+ process.exitCode = 1
172
+ return
173
+ }
174
+ console.log(`Lessons catalog is valid: ${rootDir}`)
175
+ }
176
+
177
+ const entryPath = process.argv[1] ? pathToFileURL(path.resolve(process.argv[1])).href : null
178
+ if (entryPath === import.meta.url) main()