@happyvertical/smrt-dev-mcp 0.40.60 → 0.40.62

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.
package/AGENTS.md CHANGED
@@ -65,11 +65,12 @@ member package owns, mirroring the member-excluded scan.
65
65
 
66
66
  ## Agent Skills
67
67
 
68
- Bundled skills live under `agent-skills/`. They are plain Markdown procedures
68
+ Bundled skills live under `skills/`, the Agent Plugins fixed discovery
69
+ location. They are plain Markdown procedures
69
70
  with YAML frontmatter (`name` and `description`) and harness-neutral body text.
70
71
  Skill-aware harnesses can parse the frontmatter; other harnesses can ignore it.
71
72
 
72
- - `agent-skills/smrt-code-review/SKILL.md` — downstream SMRT code review workflow.
73
+ - `skills/smrt-code-review/SKILL.md` — downstream SMRT code review workflow.
73
74
  Agents should fetch it with `get-agent-skill`, then call `smrt-review` for
74
75
  deterministic context, inspect the actual diff, and produce a findings-first
75
76
  review.
@@ -97,7 +98,8 @@ launcher or a small wrapper script with an absolute Node path.
97
98
  - `src/index.ts` — MCP server setup, tool registration
98
99
  - `src/knowledge/index.ts` — deterministic SMRT, SDK, and downstream domain knowledge discovery; workspace-glob expansion, provenance, coverage, and diagnostics
99
100
  - `src/agent-skills.ts` — bundled skill registry and file loader
100
- - `agent-skills/smrt-code-review/SKILL.md` — downstream SMRT review procedure
101
+ - `plugin.json` / `mcp.json` — Agent Plugins 1.0.0 portable root manifests
102
+ - `skills/smrt-code-review/SKILL.md` — downstream SMRT review procedure
101
103
  - `src/tools/generate-smrt-class.ts` — class generation logic and package-ready templates
102
104
  - `src/tools/introspect-project.ts` — manifest-first project scanning, falling back to `@happyvertical/smrt-scanner`
103
105
  - `src/tools/review-smrt-project.ts` — advisory ecosystem-alignment checks for downstream projects
@@ -112,6 +114,15 @@ launcher or a small wrapper script with an absolute Node path.
112
114
  fallback
113
115
  - **Skill loading**: bundled skills must be included in `package.json` `files`
114
116
  because runtime reads them from the installed package directory
117
+ - **Portable plugin boundary**: `mcp.json` launches only `./dist/index.js` from
118
+ the plugin root. Paths must remain contained after resolution. Clients, not
119
+ the package, provide the reserved `PLUGIN_ROOT` and `PLUGIN_DATA` environment
120
+ variables and manage OAuth or all other credentials; do not add secret-bearing
121
+ environment variables or headers to portable config.
122
+ - **Working Draft compatibility**: Agent Plugins 1.0.0 remains a Working Draft.
123
+ Keep `plugin.json` and `mcp.json` pinned to the canonical 1.0.0 schema IDs,
124
+ validate against the packaged `schemas/agent-plugins-1.0.0/` snapshots
125
+ offline, and do not add streamable HTTP until #2147 provides the endpoint.
115
126
  - **Field type mapping**: `text`, `integer`, `decimal`, `boolean`, `datetime`, `json` — maps to SMRT field helpers (but prefer TypeScript defaults per framework convention)
116
127
  - **Never call `ManifestGenerator` from a tool path**: `generateSchemas` and
117
128
  friends write progress lines to **stdout** through the SDK logger, which is the
package/README.md CHANGED
@@ -10,6 +10,37 @@ or architecture prompt bundles.
10
10
  pnpm install @happyvertical/smrt-dev-mcp
11
11
  ```
12
12
 
13
+ ## Agent Plugins package
14
+
15
+ The published package root is a self-contained [Agent Plugins 1.0.0](https://agent-plugins.org/specification)
16
+ plugin. Compatible clients discover `plugin.json`, `mcp.json`, and
17
+ `skills/smrt-code-review/SKILL.md` directly from the installed package root.
18
+ The shipped `mcp.json` declares only the local stdio server:
19
+
20
+ ```json
21
+ {
22
+ "$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
23
+ "mcpServers": {
24
+ "smrt-dev-mcp": { "type": "stdio", "command": "./dist/index.js" }
25
+ }
26
+ }
27
+ ```
28
+
29
+ The executable path is plugin-relative and must remain inside the resolved
30
+ plugin root. Clients provide `PLUGIN_ROOT` (the resolved package root) and the
31
+ client-managed, persistent `PLUGIN_DATA` directory; this package does not set
32
+ or override either reserved environment variable. Portable configuration never
33
+ contains credentials, secrets, authorization headers, or OAuth settings.
34
+ Clients own authorization interaction and credential storage.
35
+
36
+ Agent Plugins 1.0.0 is a Working Draft. This package targets only the canonical
37
+ 1.0.0 schema identifiers and includes pinned schema snapshots for offline
38
+ validation; clients must not fetch schemas when loading the package.
39
+
40
+ `streamable-http` is not shipped: its endpoint is gated on #2147. A future,
41
+ credential-free configuration could declare a `streamable-http` URL only after
42
+ that endpoint exists; it must not be inferred from this package today.
43
+
13
44
  ## Usage
14
45
 
15
46
  Add to your project-local `.mcp.json`, Codex MCP config, or Claude Desktop
@@ -135,6 +166,14 @@ manifest artifacts before falling back to raw manifest/doc scanning. The runtime
135
166
  `manifest.json` stays focused on object registration; `smrt-knowledge.json` is
136
167
  the agent/developer contract.
137
168
 
169
+ ## Cache Metadata
170
+
171
+ The deploy-static `tools/list` and `prompts/list` catalogs advertise a one-day
172
+ `private` cache lifetime. Workspace knowledge resources (`resources/list` and
173
+ `resources/read`) are also `private`, but use `ttlMs: 0`: they are rebuilt from
174
+ the current workspace on each request and have no transport-visible invalidation
175
+ signal that could make a positive freshness promise honest.
176
+
138
177
  After using a model to update package docs or expertise, always run the
139
178
  deterministic checker again:
140
179
 
@@ -163,7 +202,8 @@ smrt knowledge:architecture-context "tenant-aware publishing workflow" --format
163
202
 
164
203
  ## Agent Skills
165
204
 
166
- The package ships harness-agnostic agent skills under `agent-skills/`.
205
+ The package ships harness-agnostic agent skills under `skills/`, the fixed
206
+ Agent Plugins discovery location.
167
207
 
168
208
  Downstream agents should fetch the review procedure before starting a formal
169
209
  s-m-r-t review:
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAKH,OAAO,EAGL,MAAM,EACN,KAAK,IAAI,EACV,MAAM,8BAA8B,CAAC;AAqBtC,eAAO,MAAM,cAAc,QAAuB,CAAC;AAydnD,eAAO,MAAM,KAAK,EAAE,IAAI,EAOrB,CAAC;AAEJ,wBAAgB,YAAY,IAAI,MAAM,CA0erC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAKH,OAAO,EAGL,MAAM,EACN,KAAK,IAAI,EACV,MAAM,8BAA8B,CAAC;AAqBtC,eAAO,MAAM,cAAc,QAAuB,CAAC;AAwenD,eAAO,MAAM,KAAK,EAAE,IAAI,EAO0C,CAAC;AAEnE,wBAAgB,YAAY,IAAI,MAAM,CAgfrC"}
package/dist/index.js CHANGED
@@ -12,9 +12,9 @@ import { ManifestGenerator } from "@happyvertical/smrt-core/scanner";
12
12
  var AGENT_SKILLS = [{
13
13
  name: "smrt-code-review",
14
14
  description: "Harness-agnostic downstream SMRT code review workflow using smrt-dev-mcp deterministic context and prompt bundles.",
15
- path: "agent-skills/smrt-code-review/SKILL.md",
16
- skillFile: "agent-skills/smrt-code-review/SKILL.md",
17
- references: ["agent-skills/smrt-code-review/references/review-output.md"]
15
+ path: "skills/smrt-code-review/SKILL.md",
16
+ skillFile: "skills/smrt-code-review/SKILL.md",
17
+ references: ["skills/smrt-code-review/references/review-output.md"]
18
18
  }];
19
19
  function listAgentSkills() {
20
20
  return AGENT_SKILLS.map(({ skillFile: _skillFile, ...skill }) => skill);
@@ -1067,7 +1067,18 @@ var DOMAIN_CODE_REVIEW_PROMPT = "domain-code-review";
1067
1067
  var DOMAIN_ARCHITECTURE_PROMPT = "domain-architecture";
1068
1068
  var KNOWLEDGE_PROJECT_URI = "smrt://knowledge/project";
1069
1069
  var KNOWLEDGE_PACKAGE_PREFIX = "smrt://knowledge/package/";
1070
+ var DEPLOY_STATIC_CATALOG_CACHE_HINT = {
1071
+ ttlMs: 864e5,
1072
+ cacheScope: "private"
1073
+ };
1074
+ var LIVE_KNOWLEDGE_CACHE_HINT = {
1075
+ ttlMs: 0,
1076
+ cacheScope: "private"
1077
+ };
1070
1078
  var JSON_SCHEMA_2020_12 = "https://json-schema.org/draft/2020-12/schema";
1079
+ function compareToolNames(left, right) {
1080
+ return left < right ? -1 : left > right ? 1 : 0;
1081
+ }
1071
1082
  /**
1072
1083
  * Stable success/error envelope for development tools. `data` preserves each
1073
1084
  * tool's existing payload exactly; coverage/diagnostics are promoted only when
@@ -1557,17 +1568,25 @@ var TOOLS = [
1557
1568
  $schema: JSON_SCHEMA_2020_12
1558
1569
  },
1559
1570
  outputSchema: DEV_MCP_OUTPUT_SCHEMA
1560
- }));
1571
+ })).sort((left, right) => compareToolNames(left.name, right.name));
1561
1572
  function createServer() {
1562
1573
  if (DEBUG) console.error(`[${SERVER_NAME}] Starting server v${SERVER_VERSION}`);
1563
1574
  const server = new Server({
1564
1575
  name: SERVER_NAME,
1565
1576
  version: SERVER_VERSION
1566
- }, { capabilities: {
1567
- prompts: {},
1568
- resources: {},
1569
- tools: {}
1570
- } });
1577
+ }, {
1578
+ capabilities: {
1579
+ prompts: {},
1580
+ resources: {},
1581
+ tools: {}
1582
+ },
1583
+ cacheHints: {
1584
+ "tools/list": DEPLOY_STATIC_CATALOG_CACHE_HINT,
1585
+ "prompts/list": DEPLOY_STATIC_CATALOG_CACHE_HINT,
1586
+ "resources/list": LIVE_KNOWLEDGE_CACHE_HINT,
1587
+ "resources/read": LIVE_KNOWLEDGE_CACHE_HINT
1588
+ }
1589
+ });
1571
1590
  server.setRequestHandler("tools/list", async () => {
1572
1591
  if (DEBUG) console.error(`[${SERVER_NAME}] ListTools request`);
1573
1592
  return { tools: TOOLS };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/agent-skills.ts","../src/tools/generate-smrt-class.ts","../src/tools/introspect-project.ts","../src/tools/review-smrt-project.ts","../src/index.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nexport interface AgentSkillSummary {\n name: string;\n description: string;\n path: string;\n references: string[];\n}\n\nexport interface AgentSkillBundle extends AgentSkillSummary {\n skillMarkdown: string;\n referenceFiles: Array<{\n path: string;\n content: string;\n }>;\n}\n\ninterface AgentSkillDefinition extends AgentSkillSummary {\n skillFile: string;\n}\n\nconst AGENT_SKILLS: AgentSkillDefinition[] = [\n {\n name: 'smrt-code-review',\n description:\n 'Harness-agnostic downstream SMRT code review workflow using smrt-dev-mcp deterministic context and prompt bundles.',\n path: 'agent-skills/smrt-code-review/SKILL.md',\n skillFile: 'agent-skills/smrt-code-review/SKILL.md',\n references: ['agent-skills/smrt-code-review/references/review-output.md'],\n },\n];\n\nexport function listAgentSkills(): AgentSkillSummary[] {\n return AGENT_SKILLS.map(({ skillFile: _skillFile, ...skill }) => skill);\n}\n\nexport function getAgentSkill(options: {\n name: string;\n includeReferences?: boolean;\n}): AgentSkillBundle {\n const skill = AGENT_SKILLS.find((item) => item.name === options.name);\n if (!skill) {\n throw new Error(`Unknown agent skill: ${options.name}`);\n }\n\n return {\n name: skill.name,\n description: skill.description,\n path: skill.path,\n references: skill.references,\n skillMarkdown: readPackageFile(skill.skillFile),\n referenceFiles:\n options.includeReferences === false\n ? []\n : skill.references.map((path) => ({\n path,\n content: readPackageFile(path),\n })),\n };\n}\n\nfunction readPackageFile(relativePath: string): string {\n const packageRoot = resolvePackageRoot();\n return readFileSync(join(packageRoot, relativePath), 'utf8');\n}\n\nfunction resolvePackageRoot(): string {\n // Works in both source tests (`src/agent-skills.ts`) and built packages\n // (`dist/agent-skills.js`); guard it so packaging layout drift fails clearly.\n const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));\n if (!existsSync(join(packageRoot, 'package.json'))) {\n throw new Error(\n `Unable to resolve smrt-dev-mcp package root from ${import.meta.url}`,\n );\n }\n return packageRoot;\n}\n","/**\n * Generate SMRT Class Tool\n * Creates a package-ready SMRT class using current object-package patterns.\n */\n\ntype PropertyType =\n | 'text'\n | 'integer'\n | 'decimal'\n | 'boolean'\n | 'datetime'\n | 'json';\ntype BaseClass = 'SmrtObject' | 'SmrtCollection';\ntype TemplateVariant =\n | 'basic'\n | 'global-catalog'\n | 'optional-catalog'\n | 'tenant-project-object'\n | 'tenant-event-log-object'\n | 'cross-package-reference';\ntype RelationshipType =\n | 'foreignKey'\n | 'crossPackageRef'\n | 'oneToMany'\n | 'manyToMany';\n\ninterface PropertyDefinition {\n name: string;\n type: PropertyType;\n required?: boolean;\n nullable?: boolean;\n description?: string;\n defaultValue?: unknown;\n}\n\ninterface RelationshipDefinition {\n name: string;\n type: RelationshipType;\n related: string;\n required?: boolean;\n nullable?: boolean;\n description?: string;\n validate?: boolean;\n foreignKey?: string;\n through?: string;\n sourceKey?: string;\n targetKey?: string;\n}\n\ninterface TenantScopedDefinition {\n mode?: 'required' | 'optional';\n field?: string;\n autoFilter?: boolean;\n autoPopulate?: boolean;\n allowSuperAdminBypass?: boolean;\n}\n\ninterface GenerateSmrtClassArgs {\n className: string;\n properties: PropertyDefinition[];\n baseClass?: BaseClass;\n template?: TemplateVariant;\n tableName?: string;\n conflictColumns?: string[];\n tenantScoped?: boolean | TenantScopedDefinition;\n includeTenantIdField?: boolean;\n relationships?: RelationshipDefinition[];\n includeApiConfig?: boolean;\n includeMcpConfig?: boolean;\n includeCliConfig?: boolean;\n includeCompanionSnippets?: boolean;\n}\n\ninterface NormalizedGenerateSmrtClassArgs {\n className: string;\n properties: PropertyDefinition[];\n baseClass: BaseClass;\n template: TemplateVariant;\n tableName?: string;\n conflictColumns: string[];\n tenantScoped?: TenantScopedDefinition;\n includeTenantIdField: boolean;\n relationships: RelationshipDefinition[];\n includeApiConfig: boolean;\n includeMcpConfig: boolean;\n includeCliConfig: boolean;\n includeCompanionSnippets: boolean;\n}\n\nconst TYPE_MAPPING: Record<\n PropertyType,\n { tsType: string; defaultValue: string }\n> = {\n text: { tsType: 'string', defaultValue: \"''\" },\n integer: { tsType: 'number', defaultValue: '0' },\n decimal: { tsType: 'number', defaultValue: '0.0' },\n boolean: { tsType: 'boolean', defaultValue: 'false' },\n datetime: { tsType: 'Date', defaultValue: 'new Date()' },\n json: { tsType: 'any', defaultValue: '{}' },\n};\n\nexport async function generateSmrtClass(\n args: GenerateSmrtClassArgs,\n): Promise<string> {\n const normalized = normalizeArgs(args);\n const {\n className,\n properties,\n relationships,\n baseClass,\n tableName,\n conflictColumns,\n tenantScoped,\n includeTenantIdField,\n includeApiConfig,\n includeMcpConfig,\n includeCliConfig,\n includeCompanionSnippets,\n } = normalized;\n\n const coreImports = new Set<string>([baseClass, 'smrt']);\n if (needsFieldDecorator(properties)) coreImports.add('field');\n for (const relationship of relationships) {\n coreImports.add(relationship.type);\n }\n\n const imports = [\n `import { ${Array.from(coreImports).join(', ')} } from '@happyvertical/smrt-core';`,\n ];\n\n if (tenantScoped) {\n const tenancyImports = ['TenantScoped'];\n if (includeTenantIdField) tenancyImports.push('tenantId');\n imports.push(\n `import { ${tenancyImports.join(', ')} } from '@happyvertical/smrt-tenancy';`,\n );\n }\n\n const decoratorLines = [\n ...(tenantScoped\n ? [`@TenantScoped(${renderObjectLiteral({ ...tenantScoped })})`]\n : []),\n renderSmrtDecorator({\n includeApiConfig,\n includeMcpConfig,\n includeCliConfig,\n tableName,\n conflictColumns,\n }),\n ];\n\n const classMembers = [\n ...(includeTenantIdField && tenantScoped\n ? [renderTenantIdField(tenantScoped)]\n : []),\n ...properties.map(renderProperty),\n ...relationships.map(renderRelationship),\n ].filter(Boolean);\n\n const companionSnippets = includeCompanionSnippets\n ? `\\n${renderCompanionSnippets(className, Boolean(tenantScoped))}`\n : '';\n\n return `${imports.join('\\n')}\n\n${decoratorLines.join('\\n')}\nexport class ${className} extends ${baseClass} {\n${classMembers.join('\\n\\n')}\n\n constructor(options: any = {}) {\n super(options);\n Object.assign(this, options);\n }\n}\n${companionSnippets}`;\n}\n\nfunction normalizeArgs(\n args: GenerateSmrtClassArgs,\n): NormalizedGenerateSmrtClassArgs {\n const template = args.template ?? 'basic';\n const templateDefaults = defaultsForTemplate(template);\n const tenantScoped =\n args.tenantScoped === true\n ? (templateDefaults.tenantScoped ?? { mode: 'required' as const })\n : args.tenantScoped === false\n ? undefined\n : (args.tenantScoped ?? templateDefaults.tenantScoped);\n\n return {\n className: args.className,\n properties: args.properties,\n baseClass: args.baseClass ?? 'SmrtObject',\n template,\n tableName: args.tableName ?? templateDefaults.tableName,\n conflictColumns:\n args.conflictColumns ?? templateDefaults.conflictColumns ?? [],\n tenantScoped: normalizeTenantScoped(tenantScoped),\n includeTenantIdField:\n args.includeTenantIdField ??\n templateDefaults.includeTenantIdField ??\n Boolean(tenantScoped),\n relationships: args.relationships ?? [],\n includeApiConfig: args.includeApiConfig ?? true,\n includeMcpConfig: args.includeMcpConfig ?? true,\n includeCliConfig: args.includeCliConfig ?? true,\n includeCompanionSnippets: args.includeCompanionSnippets ?? false,\n };\n}\n\nfunction defaultsForTemplate(template: TemplateVariant): {\n tableName?: string;\n conflictColumns?: string[];\n tenantScoped?: TenantScopedDefinition;\n includeTenantIdField?: boolean;\n} {\n switch (template) {\n case 'optional-catalog':\n return {\n tenantScoped: { mode: 'optional' },\n includeTenantIdField: true,\n conflictColumns: ['tenant_id', 'slug'],\n };\n case 'tenant-project-object':\n return {\n tenantScoped: { mode: 'required' },\n includeTenantIdField: true,\n };\n case 'tenant-event-log-object':\n return {\n tenantScoped: { mode: 'optional' },\n includeTenantIdField: true,\n };\n case 'global-catalog':\n return { conflictColumns: ['slug'] };\n case 'cross-package-reference':\n case 'basic':\n return {};\n }\n}\n\nfunction normalizeTenantScoped(\n value: boolean | TenantScopedDefinition | undefined,\n): TenantScopedDefinition | undefined {\n if (!value) return undefined;\n return {\n mode: typeof value === 'object' ? (value.mode ?? 'required') : 'required',\n field: typeof value === 'object' ? (value.field ?? 'tenantId') : 'tenantId',\n autoFilter: typeof value === 'object' ? value.autoFilter : undefined,\n autoPopulate: typeof value === 'object' ? value.autoPopulate : undefined,\n allowSuperAdminBypass:\n typeof value === 'object' ? value.allowSuperAdminBypass : undefined,\n };\n}\n\nfunction renderSmrtDecorator(options: {\n includeApiConfig: boolean;\n includeMcpConfig: boolean;\n includeCliConfig: boolean;\n tableName?: string;\n conflictColumns: string[];\n}): string {\n const decoratorConfig: Record<string, unknown> = {};\n\n if (options.tableName) {\n decoratorConfig.tableName = options.tableName;\n }\n\n if (options.conflictColumns.length > 0) {\n decoratorConfig.conflictColumns = options.conflictColumns;\n }\n\n if (options.includeApiConfig) {\n decoratorConfig.api = {\n include: ['list', 'get', 'create', 'update'],\n exclude: ['delete'],\n };\n }\n\n if (options.includeMcpConfig) {\n decoratorConfig.mcp = {\n include: ['list', 'get'],\n };\n }\n\n if (options.includeCliConfig) {\n decoratorConfig.cli = true;\n }\n\n return Object.keys(decoratorConfig).length > 0\n ? `@smrt(${JSON.stringify(decoratorConfig, null, 2)})`\n : '@smrt()';\n}\n\nfunction renderTenantIdField(tenantScoped: TenantScopedDefinition): string {\n const nullable = tenantScoped.mode === 'optional';\n const field = tenantScoped.field ?? 'tenantId';\n return nullable\n ? ` @tenantId({ nullable: true })\\n ${field}: string | null = null;`\n : ` @tenantId()\\n ${field}: string = '';`;\n}\n\nfunction renderProperty(prop: PropertyDefinition): string {\n const mapping = TYPE_MAPPING[prop.type];\n const nullable = prop.nullable === true;\n const tsType = nullable ? `${mapping.tsType} | null` : mapping.tsType;\n const defaultValue =\n prop.defaultValue !== undefined\n ? renderLiteral(prop.defaultValue)\n : nullable\n ? 'null'\n : mapping.defaultValue;\n const fieldOptions = compactObject({\n required: prop.required,\n nullable: prop.nullable,\n description: prop.description,\n });\n const jsdoc = prop.description ? ` /** ${prop.description} */\\n` : '';\n const decorator =\n Object.keys(fieldOptions).length > 0\n ? ` @field(${JSON.stringify(fieldOptions)})\\n`\n : '';\n\n return `${jsdoc}${decorator} ${prop.name}: ${tsType} = ${defaultValue};`;\n}\n\nfunction renderRelationship(relationship: RelationshipDefinition): string {\n const options = compactObject({\n required: relationship.required,\n nullable: relationship.nullable,\n description: relationship.description,\n validate: relationship.validate,\n foreignKey: relationship.foreignKey,\n through: relationship.through,\n sourceKey: relationship.sourceKey,\n targetKey: relationship.targetKey,\n });\n const args = [\n renderLiteral(relationship.related),\n ...(Object.keys(options).length > 0 ? [JSON.stringify(options)] : []),\n ];\n const decorator = `@${relationship.type}(${args.join(', ')})`;\n const fieldType =\n relationship.type === 'oneToMany' || relationship.type === 'manyToMany'\n ? 'unknown[]'\n : relationship.nullable\n ? 'string | null'\n : 'string';\n const defaultValue =\n relationship.type === 'oneToMany' || relationship.type === 'manyToMany'\n ? '[]'\n : relationship.nullable\n ? 'null'\n : \"''\";\n\n return ` ${decorator}\\n ${relationship.name}: ${fieldType} = ${defaultValue};`;\n}\n\nfunction needsFieldDecorator(properties: PropertyDefinition[]): boolean {\n return properties.some(\n (property) =>\n property.required !== undefined ||\n property.nullable !== undefined ||\n property.description !== undefined,\n );\n}\n\nfunction renderCompanionSnippets(\n className: string,\n usesTenantScoped: boolean,\n): string {\n const dependencyNote = usesTenantScoped\n ? `\\n * - Ensure package.json declares \"@happyvertical/smrt-tenancy\".`\n : '';\n return `/*\n * Package wiring:\n * - Export ${className} from the package entrypoint used by consumers.\n * - Import this module from any package registration file that eagerly loads objects.${dependencyNote}\n */`;\n}\n\nfunction renderObjectLiteral(value: Record<string, unknown>): string {\n return JSON.stringify(compactObject(value), null, 2);\n}\n\nfunction renderLiteral(value: unknown): string {\n if (typeof value === 'string') return JSON.stringify(value);\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (value === null) return 'null';\n return JSON.stringify(value, null, 2);\n}\n\nfunction compactObject<T extends Record<string, unknown>>(value: T): T {\n return Object.fromEntries(\n Object.entries(value).filter(([, entry]) => entry !== undefined),\n ) as T;\n}\n","/**\n * Project Introspection Tool\n * Returns a manifest-equivalent inventory of SMRT objects in a project.\n */\n\nimport type { Dirent } from 'node:fs';\nimport { access, readdir, readFile } from 'node:fs/promises';\nimport { isAbsolute, join, relative, resolve } from 'node:path';\nimport {\n ManifestGenerator,\n type SmartObjectManifest,\n} from '@happyvertical/smrt-core/scanner';\nimport type { ScanError } from '@happyvertical/smrt-scanner';\nimport { ManifestAdapter, OxcScanner } from '@happyvertical/smrt-scanner';\n\n/**\n * `summary` (default) returns one compact record per object; `full` returns the\n * verbose shape. A 42-object project produced 338,462 characters in the only\n * mode that used to exist, which put every call over tool-result budgets and\n * forced callers to write-to-file and `jq` (#2143).\n */\nexport type IntrospectDetail = 'summary' | 'full';\n\n/** Common shape both detail modes emit, so the two branches share a list. */\ntype IntrospectedObject = Record<string, unknown> & { className: string };\n\ninterface IntrospectProjectArgs {\n directory?: string;\n manifestPath?: string;\n includeFields?: boolean;\n includeRelationships?: boolean;\n includeMethods?: boolean;\n detail?: IntrospectDetail;\n /**\n * Overrides the default character budget for the serialized `objects` array.\n *\n * Project metadata and diagnostics are deliberately exempt: a diagnostic is\n * how discovery reports that it found nothing (#2143), so budgeting it away\n * would hide the very failure the caller needs to see. The full response is\n * therefore somewhat larger than this budget.\n */\n maxChars?: number;\n}\n\ntype DiagnosticSeverity = 'error' | 'warning' | 'info';\n\ninterface Diagnostic {\n severity: DiagnosticSeverity;\n message: string;\n filePath?: string;\n line?: number;\n column?: number;\n}\n\ninterface ManifestLike {\n version?: string;\n packageName?: string;\n packageVersion?: string;\n objects?: Record<string, ManifestObject>;\n}\n\ninterface ManifestObject {\n name?: string;\n className: string;\n qualifiedName?: string;\n collection?: string;\n filePath: string;\n packageName?: string;\n packageVersion?: string;\n importPath?: string;\n modulePath?: string;\n exportName?: string;\n collectionExportName?: string;\n fields?: Record<string, ManifestField>;\n methods?: Record<string, ManifestMethod>;\n decoratorConfig?: Record<string, unknown>;\n extends?: string;\n extendsTypeArg?: string;\n schema?: ManifestSchema;\n staticProperties?: Record<string, unknown>;\n validationRules?: Record<string, unknown>;\n}\n\ninterface ManifestField {\n type: string;\n required?: boolean;\n default?: unknown;\n related?: string;\n description?: string;\n _meta?: Record<string, unknown>;\n transient?: boolean;\n}\n\ninterface ManifestMethod {\n name?: string;\n async?: boolean;\n parameters?: Array<{\n name: string;\n type?: string;\n optional?: boolean;\n default?: unknown;\n }>;\n returnType?: string;\n description?: string;\n isStatic?: boolean;\n isPublic?: boolean;\n}\n\ninterface ManifestSchema {\n tableName?: string;\n ddl?: string;\n columns?: Record<string, unknown>;\n indexes?: Array<{\n name?: string;\n columns?: string[];\n unique?: boolean;\n where?: string;\n jsonPath?: unknown;\n }>;\n version?: string;\n}\n\ninterface PackageMetadata {\n name?: string;\n version?: string;\n json?: Record<string, unknown>;\n}\n\nconst DEFAULT_MANIFEST_PATHS = [\n '.smrt/manifest.json',\n 'dist/manifest.json',\n 'src/manifest/manifest.json',\n];\n\nconst SCAN_EXCLUDE = [\n '**/node_modules/**',\n '**/dist/**',\n '**/build/**',\n '**/.git/**',\n '**/.smrt/**',\n '**/*.d.ts',\n '**/*.test.ts',\n '**/*.spec.ts',\n '**/__tests__/**',\n];\n\nconst RELATIONSHIP_TYPES = new Set([\n 'foreignKey',\n 'crossPackageRef',\n 'oneToMany',\n 'manyToMany',\n]);\n\n/**\n * Response budget in characters. Generous enough that a 42-object summary never\n * truncates, while still capping a runaway payload instead of emitting one.\n */\nconst DEFAULT_MAX_CHARS = 50_000;\n\nconst DEFAULT_MCP_OPERATIONS = ['list', 'get', 'create', 'update', 'delete'];\n\nexport async function introspectProject(\n args: IntrospectProjectArgs,\n): Promise<string> {\n const {\n directory = process.cwd(),\n includeFields = true,\n includeRelationships = true,\n includeMethods = true,\n detail = 'summary',\n maxChars = DEFAULT_MAX_CHARS,\n } = args;\n const projectPath = resolve(directory);\n\n const exists = await pathExists(projectPath);\n if (!exists) {\n return JSON.stringify(\n {\n projectPath,\n manifestSource: 'none',\n objectCount: 0,\n objects: [],\n diagnostics: [\n {\n severity: 'warning',\n message: `Project directory does not exist: ${projectPath}`,\n },\n ],\n },\n null,\n 2,\n );\n }\n\n const packageMetadata = await readPackageMetadata(projectPath);\n const tenantScopes = await scanTenantScopes(projectPath);\n const manifestResult =\n (await loadManifestArtifact(projectPath, args.manifestPath)) ??\n (await scanSourceManifest(projectPath, packageMetadata));\n\n const entries = Object.entries(manifestResult.manifest.objects ?? {});\n const objects: IntrospectedObject[] =\n detail === 'summary'\n ? entries.map(([manifestKey, object]) =>\n summarizeObject({\n manifestKey,\n object,\n projectPath,\n tenantScope: tenantScopes.get(object.className),\n }),\n )\n : entries.map(([manifestKey, object]) =>\n formatObject({\n manifestKey,\n object,\n projectPath,\n includeFields,\n includeRelationships,\n includeMethods,\n tenantScope: tenantScopes.get(object.className),\n }),\n );\n objects.sort((left, right) => left.className.localeCompare(right.className));\n\n const { kept, omitted } = applyObjectBudget(objects, maxChars);\n\n const output = {\n projectPath,\n manifestSource: manifestResult.source,\n manifestPath:\n 'path' in manifestResult\n ? relative(projectPath, manifestResult.path)\n : undefined,\n packageName:\n manifestResult.manifest.packageName ?? packageMetadata.name ?? undefined,\n packageVersion:\n manifestResult.manifest.packageVersion ??\n packageMetadata.version ??\n undefined,\n detail,\n objectCount: objects.length,\n scannedFileCount: manifestResult.scannedFileCount,\n parseTimeMs: manifestResult.parseTimeMs,\n ...(omitted > 0\n ? {\n truncated: {\n returnedObjectCount: kept.length,\n omittedObjectCount: omitted,\n budgetChars: maxChars,\n guidance:\n 'The object list hit its character budget; metadata and diagnostics are still complete. Narrow the scan with `directory` (a single package), keep `detail: \"summary\"`, or raise `maxChars` deliberately. Object names are sorted alphabetically, so omitted objects are the alphabetical tail.',\n },\n }\n : {}),\n objects: kept,\n diagnostics: manifestResult.diagnostics,\n };\n\n return JSON.stringify(output, null, 2);\n}\n\n/**\n * Trims the object list to the character budget, always keeping at least one so\n * a caller sees the shape rather than an empty list.\n */\nfunction applyObjectBudget<T>(\n objects: T[],\n maxChars: number,\n): { kept: T[]; omitted: number } {\n const kept: T[] = [];\n let used = 0;\n\n for (const object of objects) {\n const size = JSON.stringify(object, null, 2).length + 2;\n if (used + size > maxChars && kept.length > 0) break;\n used += size;\n kept.push(object);\n }\n\n return { kept, omitted: objects.length - kept.length };\n}\n\nfunction summarizeObject({\n manifestKey,\n object,\n projectPath,\n tenantScope,\n}: {\n manifestKey: string;\n object: ManifestObject;\n projectPath: string;\n tenantScope?: Record<string, unknown>;\n}) {\n const fields = Object.entries(object.fields ?? {});\n const decoratorConfig = object.decoratorConfig ?? {};\n\n return compactObject({\n manifestKey,\n className: object.className,\n qualifiedName: object.qualifiedName,\n filePath: sanitizePath(projectPath, object.filePath),\n extends: object.extends,\n collection: object.collection,\n tableName:\n object.schema?.tableName ??\n stringFromConfig(decoratorConfig.tableName) ??\n object.collection,\n tenantScope:\n tenantScope ?? normalizeTenantScopedConfig(decoratorConfig.tenantScoped),\n fieldCount: fields.length,\n relationships:\n fields\n .filter(([, field]) => RELATIONSHIP_TYPES.has(field.type))\n .map(\n ([name, field]) =>\n `${name} -> ${field.related ?? ''} (${field.type})`,\n )\n .join(', ') || undefined,\n mcpOperations: mcpOperationsFromConfig(decoratorConfig.mcp),\n });\n}\n\n/**\n * An omitted `mcp` config means full CRUD, not a closed surface — the same rule\n * the knowledge index applies.\n */\nfunction mcpOperationsFromConfig(config: unknown): string[] {\n if (config === false) return [];\n if (typeof config !== 'object' || config === null || Array.isArray(config)) {\n return [...DEFAULT_MCP_OPERATIONS];\n }\n\n const record = config as Record<string, unknown>;\n const include = Array.isArray(record.include)\n ? record.include.filter((item): item is string => typeof item === 'string')\n : DEFAULT_MCP_OPERATIONS;\n const exclude = new Set(\n Array.isArray(record.exclude)\n ? record.exclude.filter(\n (item): item is string => typeof item === 'string',\n )\n : [],\n );\n\n return include.filter((operation) => !exclude.has(operation));\n}\n\nasync function loadManifestArtifact(\n projectPath: string,\n manifestPath: string | undefined,\n): Promise<\n | {\n source: 'manifest';\n path: string;\n manifest: ManifestLike;\n diagnostics: Diagnostic[];\n scannedFileCount?: number;\n parseTimeMs?: number;\n }\n | undefined\n> {\n const candidates = manifestPath\n ? [resolve(projectPath, manifestPath)]\n : DEFAULT_MANIFEST_PATHS.map((candidate) => join(projectPath, candidate));\n\n const diagnostics: Diagnostic[] = [];\n for (const candidate of candidates) {\n if (!(await pathExists(candidate))) {\n continue;\n }\n\n try {\n const parsed = JSON.parse(await readFile(candidate, 'utf-8')) as unknown;\n if (isManifestLike(parsed)) {\n return {\n source: 'manifest',\n path: candidate,\n manifest: parsed,\n diagnostics,\n };\n }\n\n diagnostics.push({\n severity: 'warning',\n filePath: candidate,\n message: 'Manifest artifact is present but does not contain objects.',\n });\n } catch (error) {\n diagnostics.push({\n severity: 'error',\n filePath: candidate,\n message: `Unable to parse manifest artifact: ${messageFromError(error)}`,\n });\n }\n }\n\n return manifestPath\n ? {\n source: 'manifest',\n path: resolve(projectPath, manifestPath),\n manifest: { objects: {} },\n diagnostics: [\n ...diagnostics,\n {\n severity: 'warning',\n filePath: resolve(projectPath, manifestPath),\n message: 'Requested manifest artifact was not found.',\n },\n ],\n }\n : undefined;\n}\n\nasync function scanSourceManifest(\n projectPath: string,\n packageMetadata: PackageMetadata,\n): Promise<{\n source: 'scanner';\n manifest: ManifestLike;\n diagnostics: Diagnostic[];\n scannedFileCount: number;\n parseTimeMs: number;\n}> {\n const scanner = new OxcScanner({\n cwd: projectPath,\n include: ['**/*.ts', '**/*.tsx', '**/*.js', '**/*.jsx'],\n exclude: SCAN_EXCLUDE,\n });\n const { results, resolved } = await scanner.scanAndResolve();\n const adapter = new ManifestAdapter();\n const manifest = adapter.toManifest(\n resolved.filter((classDef) => classDef.hasSmartDecorator),\n {\n packageName: packageMetadata.name,\n packageVersion: packageMetadata.version,\n typeAliases: results.typeAliases,\n },\n ) as ManifestLike;\n finalizeScannerManifest(manifest, packageMetadata);\n\n return {\n source: 'scanner',\n manifest,\n diagnostics: results.errors.map(scanErrorToDiagnostic),\n scannedFileCount: results.fileCount,\n parseTimeMs: Math.round(results.totalParseTimeMs),\n };\n}\n\nfunction finalizeScannerManifest(\n manifest: ManifestLike,\n packageMetadata: PackageMetadata,\n): void {\n const manifestGen = new ManifestGenerator();\n const fullManifest = manifest as unknown as SmartObjectManifest;\n withSuppressedConsoleLog(() => {\n manifestGen.injectTenantScopedFields(fullManifest);\n manifestGen.mergeInheritedFields(fullManifest);\n manifestGen.generateValidationRules(fullManifest);\n manifestGen.generateSchemas(fullManifest);\n manifestGen.assertTenantScopedSchemaContract(fullManifest);\n manifestGen.generateAgentManifests(\n fullManifest,\n packageMetadata.name,\n packageMetadata.json,\n );\n });\n}\n\nfunction withSuppressedConsoleLog<T>(callback: () => T): T {\n const originalLog = console.log;\n console.log = () => undefined;\n try {\n return callback();\n } finally {\n console.log = originalLog;\n }\n}\n\nfunction formatObject({\n manifestKey,\n object,\n projectPath,\n includeFields,\n includeRelationships,\n includeMethods,\n tenantScope,\n}: {\n manifestKey: string;\n object: ManifestObject;\n projectPath: string;\n includeFields: boolean;\n includeRelationships: boolean;\n includeMethods: boolean;\n tenantScope?: Record<string, unknown>;\n}) {\n const fieldDetails = Object.entries(object.fields ?? {}).map(\n ([name, field]) => ({\n name,\n type: field.type,\n ...(field.required !== undefined ? { required: field.required } : {}),\n ...(field.default !== undefined ? { default: field.default } : {}),\n ...(field.related ? { related: field.related } : {}),\n ...(field.description ? { description: field.description } : {}),\n ...(field._meta ? { meta: field._meta } : {}),\n ...(field.transient !== undefined ? { transient: field.transient } : {}),\n }),\n );\n const relationshipDetails = fieldDetails\n .filter((field) => RELATIONSHIP_TYPES.has(field.type))\n .map((field) => ({\n field: field.name,\n relatedClass: field.related ?? '',\n type: field.type,\n ...(field.meta ? { meta: field.meta } : {}),\n }));\n const methodDetails = Object.entries(object.methods ?? {}).map(\n ([name, method]) => ({\n name: method.name ?? name,\n isAsync: method.async === true,\n isStatic: method.isStatic === true,\n isPublic: method.isPublic !== false,\n parameters: method.parameters ?? [],\n returnType: method.returnType ?? 'unknown',\n ...(method.description ? { description: method.description } : {}),\n }),\n );\n\n const decoratorConfig = object.decoratorConfig ?? {};\n const effectiveTenantScope =\n tenantScope ?? normalizeTenantScopedConfig(decoratorConfig.tenantScoped);\n const schema = object.schema;\n\n return compactObject({\n manifestKey,\n name: object.name,\n className: object.className,\n qualifiedName: object.qualifiedName,\n filePath: sanitizePath(projectPath, object.filePath),\n packageName: object.packageName,\n packageVersion: object.packageVersion,\n importPath: object.importPath,\n modulePath: object.modulePath,\n exportName: object.exportName,\n collectionExportName: object.collectionExportName,\n collection: object.collection,\n extends: object.extends,\n extendsTypeArg: object.extendsTypeArg,\n tableName:\n schema?.tableName ??\n stringFromConfig(decoratorConfig.tableName) ??\n object.collection,\n tableStrategy: stringFromConfig(decoratorConfig.tableStrategy) ?? 'cti',\n conflictColumns: arrayFromConfig(decoratorConfig.conflictColumns),\n tenantScope: effectiveTenantScope,\n decoratorConfig,\n schema: schema\n ? {\n tableName: schema.tableName,\n columns: schema.columns,\n indexes: schema.indexes ?? [],\n version: schema.version,\n }\n : undefined,\n indexes: schema?.indexes ?? [],\n staticProperties: object.staticProperties,\n validationRules: object.validationRules,\n ...(includeFields && {\n fields: fieldDetails\n .map((field) => `${field.name}: ${field.type}`)\n .join(', '),\n fieldDetails,\n }),\n ...(includeRelationships &&\n relationshipDetails.length > 0 && {\n relationships: relationshipDetails\n .map(\n (relationship) =>\n `${relationship.field} -> ${relationship.relatedClass} (${relationship.type})`,\n )\n .join(', '),\n relationshipDetails,\n }),\n ...(includeMethods &&\n methodDetails.length > 0 && {\n methods: methodDetails\n .map((method) => `${method.isAsync ? 'async ' : ''}${method.name}()`)\n .join(', '),\n methodDetails,\n }),\n });\n}\n\nasync function scanTenantScopes(\n projectPath: string,\n): Promise<Map<string, Record<string, unknown>>> {\n const files = await listSourceFiles(projectPath);\n const scopes = new Map<string, Record<string, unknown>>();\n\n await Promise.all(\n files.map(async (filePath) => {\n const content = await readFile(filePath, 'utf-8');\n const classMatches = content.matchAll(/class\\s+([A-Za-z_]\\w*)\\b/g);\n for (const match of classMatches) {\n const className = match[1];\n if (!className || match.index === undefined) continue;\n const prefix = content.slice(\n Math.max(0, match.index - 800),\n match.index,\n );\n const tenantMatches = Array.from(\n prefix.matchAll(/@TenantScoped\\s*\\(([\\s\\S]*?)\\)/g),\n );\n const tenantMatch = tenantMatches.at(-1);\n if (!tenantMatch) continue;\n scopes.set(className, {\n source: 'TenantScoped',\n ...parseTenantScopedOptions(tenantMatch[1]),\n });\n }\n }),\n );\n\n return scopes;\n}\n\nasync function listSourceFiles(projectPath: string): Promise<string[]> {\n const files: string[] = [];\n\n async function visit(dir: string): Promise<void> {\n let entries: Dirent[];\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n const fullPath = join(dir, entry.name);\n if (entry.isDirectory()) {\n if (\n [\n 'node_modules',\n 'dist',\n 'build',\n '.git',\n '.smrt',\n '__tests__',\n ].includes(entry.name) ||\n entry.name.startsWith('.')\n ) {\n continue;\n }\n await visit(fullPath);\n continue;\n }\n\n if (\n entry.isFile() &&\n /\\.(tsx?|jsx?)$/.test(entry.name) &&\n !entry.name.endsWith('.d.ts') &&\n !entry.name.endsWith('.test.ts') &&\n !entry.name.endsWith('.spec.ts')\n ) {\n files.push(fullPath);\n }\n }\n }\n\n await visit(projectPath);\n return files;\n}\n\nfunction parseTenantScopedOptions(raw: string): Record<string, unknown> {\n const mode = raw.match(/mode\\s*:\\s*['\"`](required|optional)['\"`]/)?.[1];\n const field = raw.match(/field\\s*:\\s*['\"`]([A-Za-z_]\\w*)['\"`]/)?.[1];\n const allowSuperAdminBypass = raw.match(\n /allowSuperAdminBypass\\s*:\\s*(true|false)/,\n )?.[1];\n const autoFilter = raw.match(/autoFilter\\s*:\\s*(true|false)/)?.[1];\n const autoPopulate = raw.match(/autoPopulate\\s*:\\s*(true|false)/)?.[1];\n\n return compactObject({\n mode: mode ?? 'required',\n field: field ?? 'tenantId',\n autoFilter: autoFilter === undefined ? undefined : autoFilter === 'true',\n autoPopulate:\n autoPopulate === undefined ? undefined : autoPopulate === 'true',\n allowSuperAdminBypass:\n allowSuperAdminBypass === undefined\n ? undefined\n : allowSuperAdminBypass === 'true',\n });\n}\n\nfunction normalizeTenantScopedConfig(\n tenantScoped: unknown,\n): Record<string, unknown> | undefined {\n if (!tenantScoped) return undefined;\n const options =\n typeof tenantScoped === 'object' && !Array.isArray(tenantScoped)\n ? (tenantScoped as Record<string, unknown>)\n : {};\n return {\n source: 'smrt',\n mode: options.mode ?? 'required',\n field: options.field ?? 'tenantId',\n autoFilter: options.autoFilter ?? true,\n autoPopulate: options.autoPopulate ?? true,\n allowSuperAdminBypass: options.allowSuperAdminBypass ?? false,\n };\n}\n\nasync function readPackageMetadata(\n projectPath: string,\n): Promise<PackageMetadata> {\n const packageJsonPath = join(projectPath, 'package.json');\n if (!(await pathExists(packageJsonPath))) return {};\n\n try {\n const json = JSON.parse(await readFile(packageJsonPath, 'utf-8')) as Record<\n string,\n unknown\n >;\n return {\n name: typeof json.name === 'string' ? json.name : undefined,\n version: typeof json.version === 'string' ? json.version : undefined,\n json,\n };\n } catch {\n return {};\n }\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction isManifestLike(value: unknown): value is ManifestLike {\n return (\n !!value &&\n typeof value === 'object' &&\n !!(value as ManifestLike).objects &&\n typeof (value as ManifestLike).objects === 'object'\n );\n}\n\nfunction scanErrorToDiagnostic(error: ScanError): Diagnostic {\n return {\n severity: error.severity,\n message: error.message,\n filePath: error.filePath,\n line: error.line,\n column: error.column,\n };\n}\n\nfunction sanitizePath(projectPath: string, filePath: string): string {\n const absolute = isAbsolute(filePath)\n ? filePath\n : resolve(projectPath, filePath);\n const relativePath = relative(projectPath, absolute);\n if (!relativePath.startsWith('..')) {\n return relativePath || filePath;\n }\n return filePath;\n}\n\nfunction stringFromConfig(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction arrayFromConfig(value: unknown): string[] | undefined {\n return Array.isArray(value)\n ? value.filter((item): item is string => typeof item === 'string')\n : undefined;\n}\n\nfunction compactObject<T extends Record<string, unknown>>(value: T): T {\n return Object.fromEntries(\n Object.entries(value).filter(([, entry]) => entry !== undefined),\n ) as T;\n}\n\nfunction messageFromError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * Ecosystem-aware downstream project review.\n * Advisory only: scans manifests and source files, then reports alignment risks.\n */\n\nimport { type Dirent, existsSync } from 'node:fs';\nimport { access, readdir, readFile } from 'node:fs/promises';\nimport { dirname, join, relative, resolve, sep } from 'node:path';\n\ninterface ReviewSmrtProjectArgs {\n directory?: string;\n rootDir?: string;\n includeSourceEvidence?: boolean;\n maxFindings?: number;\n}\n\ntype Severity = 'high' | 'medium' | 'low';\n\ninterface Evidence {\n filePath: string;\n line?: number;\n detail: string;\n}\n\ninterface Finding {\n severity: Severity;\n area:\n | 'dependencies'\n | 'storage'\n | 'api-shell'\n | 'manifest'\n | 'auth-tenancy'\n | 'ui-shell';\n code: string;\n title: string;\n evidence: Evidence[];\n recommendation: string;\n suggestedIssueTitle: string;\n}\n\ninterface PackageInventory {\n name: string;\n path: string;\n private?: boolean;\n scripts: string[];\n declaredHappyVerticalDependencies: string[];\n importedHappyVerticalPackages: string[];\n missingHappyVerticalDependencies: string[];\n hasSvelteKit: boolean;\n hasSmrtSvelte: boolean;\n}\n\ninterface PackageContext {\n directory: string;\n relativePath: string;\n packageJsonPath: string;\n json: Record<string, unknown>;\n dependencies: Set<string>;\n scripts: Record<string, unknown>;\n imports: Map<string, Evidence[]>;\n sourceFiles: SourceFile[];\n}\n\ninterface SourceFile {\n path: string;\n packageDir: string;\n content: string;\n}\n\nconst SOURCE_EXTENSIONS = /\\.(tsx?|jsx?|svelte)$/;\nconst SKIP_DIRS = new Set([\n 'node_modules',\n 'dist',\n 'build',\n '.git',\n '.smrt',\n '.svelte-kit',\n 'coverage',\n]);\nconst DEPENDENCY_SECTIONS = [\n 'dependencies',\n 'devDependencies',\n 'peerDependencies',\n 'optionalDependencies',\n];\nconst SMRT_PACKAGE_PREFIX = '@happyvertical/smrt-';\nconst HAPPYVERTICAL_PACKAGE_PREFIX = '@happyvertical/';\n\nexport async function reviewSmrtProject(\n args: ReviewSmrtProjectArgs,\n): Promise<string> {\n const projectPath = resolve(args.directory ?? args.rootDir ?? process.cwd());\n if (!(await pathExists(projectPath))) {\n return JSON.stringify(\n {\n projectPath,\n packageCount: 0,\n packages: [],\n findings: [],\n summary: { high: 0, medium: 0, low: 0 },\n diagnostics: [\n {\n severity: 'warning',\n message: `Project directory does not exist: ${projectPath}`,\n },\n ],\n },\n null,\n 2,\n );\n }\n\n const packageContexts = await buildPackageContexts(projectPath);\n const sourceFiles = await listSourceFiles(projectPath, packageContexts);\n await attachSourceFiles(sourceFiles, packageContexts, projectPath);\n\n const findings = limitFindings(\n [\n ...findMissingHappyVerticalDependencies(packageContexts),\n ...findCustomManifestGeneration(sourceFiles, projectPath),\n ...findDirectStorageBypasses(sourceFiles, packageContexts, projectPath),\n ...findCustomHttpShells(sourceFiles, packageContexts, projectPath),\n ...findLocalAuthTenancy(sourceFiles, packageContexts, projectPath),\n ...findUiShellDrift(packageContexts, projectPath),\n ...findMissingManifestArtifacts(\n sourceFiles,\n packageContexts,\n projectPath,\n ),\n ],\n args.maxFindings,\n );\n\n const packages = packageContexts\n .map(packageInventory)\n .sort((left, right) => left.path.localeCompare(right.path));\n const summary = summarizeFindings(findings);\n\n return JSON.stringify(\n {\n projectPath,\n packageCount: packages.length,\n packages,\n findings:\n args.includeSourceEvidence === false\n ? findings.map(({ evidence: _evidence, ...finding }) => finding)\n : findings,\n summary,\n referenceChecks: [\n 'Prefer SMRT scanner/runtime manifests over custom manifest builders.',\n 'Prefer SvelteKit plus @happyvertical/smrt-svelte for app shells.',\n 'Prefer @happyvertical/sql and @happyvertical/files/assets/content over direct durable node:fs storage.',\n 'Prefer smrt-users, smrt-tenancy, and profile/audit packages over local static auth seams.',\n ],\n suggestedFollowUpIssues: findings.map((finding) => ({\n title: finding.suggestedIssueTitle,\n severity: finding.severity,\n area: finding.area,\n })),\n },\n null,\n 2,\n );\n}\n\nasync function buildPackageContexts(\n projectPath: string,\n): Promise<PackageContext[]> {\n const packageJsonPaths = await listPackageJsonFiles(projectPath);\n const contexts = await Promise.all(\n packageJsonPaths.map(async (packageJsonPath) => {\n const json = JSON.parse(\n await readFile(packageJsonPath, 'utf-8'),\n ) as Record<string, unknown>;\n const directory = dirname(packageJsonPath);\n return {\n directory,\n relativePath: relative(projectPath, directory) || '.',\n packageJsonPath,\n json,\n dependencies: collectDependencies(json),\n scripts: isRecord(json.scripts)\n ? (json.scripts as Record<string, unknown>)\n : {},\n imports: new Map<string, Evidence[]>(),\n sourceFiles: [],\n };\n }),\n );\n\n if (contexts.length === 0) {\n contexts.push({\n directory: projectPath,\n relativePath: '.',\n packageJsonPath: join(projectPath, 'package.json'),\n json: {},\n dependencies: new Set(),\n scripts: {},\n imports: new Map(),\n sourceFiles: [],\n });\n }\n\n return contexts.sort(\n (left, right) => left.directory.length - right.directory.length,\n );\n}\n\nasync function listPackageJsonFiles(projectPath: string): Promise<string[]> {\n const files: string[] = [];\n await visit(projectPath, async (filePath, entryName) => {\n if (entryName === 'package.json') files.push(filePath);\n });\n return files;\n}\n\nasync function listSourceFiles(\n projectPath: string,\n packages: PackageContext[],\n): Promise<SourceFile[]> {\n const files: SourceFile[] = [];\n await visit(projectPath, async (filePath, entryName) => {\n if (!SOURCE_EXTENSIONS.test(entryName)) return;\n if (\n entryName.endsWith('.d.ts') ||\n entryName.endsWith('.test.ts') ||\n entryName.endsWith('.spec.ts')\n ) {\n return;\n }\n\n const packageDir = findOwningPackage(filePath, packages).directory;\n const content = await readFile(filePath, 'utf-8');\n files.push({ path: filePath, packageDir, content });\n });\n return files;\n}\n\nasync function attachSourceFiles(\n sourceFiles: SourceFile[],\n packages: PackageContext[],\n projectPath: string,\n): Promise<void> {\n for (const sourceFile of sourceFiles) {\n const owner = packages.find(\n (pkg) => pkg.directory === sourceFile.packageDir,\n );\n if (!owner) continue;\n owner.sourceFiles.push(sourceFile);\n for (const importedPackage of extractImports(sourceFile.content)) {\n if (!importedPackage.startsWith(HAPPYVERTICAL_PACKAGE_PREFIX)) continue;\n const evidence = {\n filePath: relative(projectPath, sourceFile.path),\n line: lineNumber(sourceFile.content, importedPackage),\n detail: `Imports ${importedPackage}`,\n };\n const existing = owner.imports.get(importedPackage) ?? [];\n existing.push(evidence);\n owner.imports.set(importedPackage, existing);\n }\n }\n}\n\nfunction findMissingHappyVerticalDependencies(\n packages: PackageContext[],\n): Finding[] {\n return packages.flatMap((pkg) => {\n const ownName =\n typeof pkg.json.name === 'string' ? pkg.json.name : undefined;\n const missing = Array.from(pkg.imports.keys()).filter(\n (importedPackage) =>\n importedPackage !== ownName && !pkg.dependencies.has(importedPackage),\n );\n if (missing.length === 0) return [];\n\n const hasSmrtMissing = missing.some((name) =>\n name.startsWith(SMRT_PACKAGE_PREFIX),\n );\n return [\n {\n severity: hasSmrtMissing ? 'high' : 'medium',\n area: 'dependencies',\n code: 'missing-happyvertical-dependencies',\n title: `${packageLabel(pkg)} imports HappyVertical packages that package.json does not declare`,\n evidence: missing.flatMap((name) => pkg.imports.get(name) ?? []),\n recommendation:\n 'Declare every imported @happyvertical package in the owning package manifest so downstream installs and generated knowledge stay reproducible.',\n suggestedIssueTitle: `Declare missing HappyVertical dependencies in ${packageLabel(pkg)}`,\n },\n ];\n });\n}\n\nfunction findCustomManifestGeneration(\n sourceFiles: SourceFile[],\n projectPath: string,\n): Finding[] {\n return sourceFiles\n .filter(\n (file) =>\n /manifest\\.json/.test(file.content) &&\n /objects\\s*:/.test(file.content) &&\n /\\b(writeFile|writeFileSync)\\b/.test(file.content) &&\n !/@happyvertical\\/smrt-scanner/.test(file.content),\n )\n .map((file) => ({\n severity: 'high',\n area: 'manifest',\n code: 'custom-object-manifest-generation',\n title: 'Custom SMRT object manifest generation detected',\n evidence: [\n {\n filePath: relative(projectPath, file.path),\n line: lineNumber(file.content, 'manifest.json'),\n detail:\n 'Writes a manifest.json object inventory outside the SMRT scanner/runtime path.',\n },\n ],\n recommendation:\n 'Use the SMRT scanner/runtime manifest path so defaults, relationships, schemas, tenant fields, and cross-package references match framework behavior.',\n suggestedIssueTitle:\n 'Replace custom object manifest generation with SMRT scanner/runtime manifest generation',\n }));\n}\n\nfunction findDirectStorageBypasses(\n sourceFiles: SourceFile[],\n packages: PackageContext[],\n projectPath: string,\n): Finding[] {\n return sourceFiles.flatMap((file) => {\n const owner = findOwningPackage(file.path, packages);\n const usesFs =\n /from\\s+['\"](?:node:fs|node:fs\\/promises|fs|fs\\/promises)['\"]|require\\(['\"](?:node:fs|node:fs\\/promises|fs|fs\\/promises)['\"]\\)/.test(\n file.content,\n );\n const writesDurableData =\n /\\b(writeFile|appendFile|mkdir|rm|rename)\\b/.test(file.content) &&\n /(\\.json|data|storage|persist|cache|db)/i.test(file.content);\n const usesDirectSql =\n /from\\s+['\"](?:better-sqlite3|sqlite3|pg|mysql2?|knex|drizzle-orm)['\"]/.test(\n file.content,\n );\n if ((!usesFs || !writesDurableData) && !usesDirectSql) return [];\n\n const hasApprovedStorage =\n owner.dependencies.has('@happyvertical/sql') ||\n owner.dependencies.has('@happyvertical/files') ||\n owner.dependencies.has('@happyvertical/smrt-assets') ||\n owner.dependencies.has('@happyvertical/smrt-content');\n\n if (hasApprovedStorage) return [];\n\n return [\n {\n severity: 'medium',\n area: 'storage',\n code: 'direct-storage-bypass',\n title: `${packageLabel(owner)} appears to bypass HappyVertical storage packages`,\n evidence: [\n {\n filePath: relative(projectPath, file.path),\n line: lineNumber(\n file.content,\n usesDirectSql ? 'sqlite' : 'writeFile',\n ),\n detail: usesDirectSql\n ? 'Imports a direct SQL/storage library without @happyvertical/sql.'\n : 'Uses node:fs-style durable writes without @happyvertical/files/assets/content.',\n },\n ],\n recommendation:\n 'Route durable data through @happyvertical/sql, @happyvertical/files, SMRT assets, or SMRT content unless this is explicitly build-only tooling.',\n suggestedIssueTitle: `Review direct storage usage in ${packageLabel(owner)}`,\n },\n ];\n });\n}\n\nfunction findCustomHttpShells(\n sourceFiles: SourceFile[],\n packages: PackageContext[],\n projectPath: string,\n): Finding[] {\n const evidenceByPackage = new Map<PackageContext, Evidence[]>();\n\n for (const pkg of packages) {\n if (pkg.dependencies.has('@sveltejs/kit')) continue;\n\n const routerDependencies = ['express', 'fastify', 'hono', 'koa'].filter(\n (dep) => pkg.dependencies.has(dep),\n );\n if (routerDependencies.length === 0) continue;\n\n appendEvidence(evidenceByPackage, pkg, {\n filePath: relative(projectPath, pkg.packageJsonPath),\n detail: `Declares custom router package(s): ${routerDependencies.join(', ')}.`,\n });\n }\n\n for (const file of sourceFiles) {\n const owner = findOwningPackage(file.path, packages);\n if (owner.dependencies.has('@sveltejs/kit')) continue;\n\n const usesNodeHttp =\n /from\\s+['\"](?:node:http|http|node:https|https)['\"]|createServer\\s*\\(/.test(\n file.content,\n );\n if (!usesNodeHttp) continue;\n\n appendEvidence(evidenceByPackage, owner, {\n filePath: relative(projectPath, file.path),\n line: lineNumber(file.content, 'createServer'),\n detail:\n 'Custom HTTP routing found without the SvelteKit/SMRT app-shell dependency pattern.',\n });\n }\n\n return Array.from(evidenceByPackage.entries()).map(([owner, evidence]) => ({\n severity: 'medium',\n area: 'api-shell',\n code: 'custom-http-shell',\n title: `${packageLabel(owner)} uses a custom HTTP shell`,\n evidence,\n recommendation:\n 'Compare the app shell against the Anytown/Ergot SvelteKit + SMRT shell pattern before adding custom HTTP infrastructure.',\n suggestedIssueTitle: `Align ${packageLabel(owner)} app shell with SMRT/SvelteKit conventions`,\n }));\n}\n\nfunction appendEvidence(\n evidenceByPackage: Map<PackageContext, Evidence[]>,\n pkg: PackageContext,\n evidence: Evidence,\n): void {\n const existing = evidenceByPackage.get(pkg);\n if (existing) {\n existing.push(evidence);\n return;\n }\n\n evidenceByPackage.set(pkg, [evidence]);\n}\n\nfunction findLocalAuthTenancy(\n sourceFiles: SourceFile[],\n packages: PackageContext[],\n projectPath: string,\n): Finding[] {\n return sourceFiles.flatMap((file) => {\n const owner = findOwningPackage(file.path, packages);\n const pathSignal = /(auth|tenant|audit|session|rbac|user)/i.test(file.path);\n const codeSignal =\n /\\b(tenantId|tenant|role|permission|session|auditLog|apiKey)\\b/.test(\n file.content,\n );\n if (!pathSignal || !codeSignal) return [];\n\n const hasApprovedPackages =\n owner.dependencies.has('@happyvertical/smrt-users') ||\n owner.dependencies.has('@happyvertical/smrt-tenancy') ||\n owner.dependencies.has('@happyvertical/smrt-profiles');\n if (hasApprovedPackages) return [];\n\n return [\n {\n severity: 'medium',\n area: 'auth-tenancy',\n code: 'local-auth-tenancy',\n title: `${packageLabel(owner)} contains local auth/tenancy/audit logic`,\n evidence: [\n {\n filePath: relative(projectPath, file.path),\n line: lineNumber(file.content, 'tenant'),\n detail:\n 'Auth, tenancy, session, role, or audit terminology appears without smrt-users/smrt-tenancy/smrt-profiles dependencies.',\n },\n ],\n recommendation:\n 'Add explicit adapters to smrt-users, smrt-tenancy, and profile/audit models or document why this local implementation is intentionally isolated.',\n suggestedIssueTitle: `Review auth and tenancy adapters in ${packageLabel(owner)}`,\n },\n ];\n });\n}\n\nfunction findUiShellDrift(\n packages: PackageContext[],\n projectPath: string,\n): Finding[] {\n return packages.flatMap((pkg) => {\n const hasUiSource = pkg.sourceFiles.some((file) =>\n file.path.endsWith('.svelte'),\n );\n const likelyUiPackage =\n hasUiSource ||\n /(?:web|ui|app|site|frontend)/i.test(packageLabel(pkg)) ||\n pkg.dependencies.has('svelte') ||\n pkg.dependencies.has('vite');\n if (!likelyUiPackage) return [];\n if (pkg.dependencies.has('@happyvertical/smrt-svelte')) return [];\n\n return [\n {\n severity: 'low',\n area: 'ui-shell',\n code: 'missing-smrt-svelte-shell',\n title: `${packageLabel(pkg)} looks like UI work without @happyvertical/smrt-svelte`,\n evidence: [\n {\n filePath: relative(projectPath, pkg.packageJsonPath),\n detail:\n 'UI-facing package does not declare @happyvertical/smrt-svelte.',\n },\n ],\n recommendation:\n 'Use @happyvertical/smrt-svelte and the SvelteKit shell pattern for downstream app UI unless this package is intentionally framework-agnostic.',\n suggestedIssueTitle: `Check SMRT Svelte shell alignment for ${packageLabel(pkg)}`,\n },\n ];\n });\n}\n\nfunction findMissingManifestArtifacts(\n sourceFiles: SourceFile[],\n packages: PackageContext[],\n projectPath: string,\n): Finding[] {\n return packages.flatMap((pkg) => {\n const hasSmrtSource = pkg.sourceFiles.some((file) =>\n /@smrt\\s*\\(/.test(file.content),\n );\n if (!hasSmrtSource) return [];\n const hasManifest =\n sourceFiles.some(\n (file) =>\n file.packageDir === pkg.directory &&\n /@happyvertical\\/smrt-scanner/.test(file.content),\n ) ||\n pathExistsSyncHint(join(pkg.directory, '.smrt', 'manifest.json')) ||\n pathExistsSyncHint(join(pkg.directory, 'dist', 'manifest.json'));\n if (hasManifest) return [];\n\n return [\n {\n severity: 'low',\n area: 'manifest',\n code: 'missing-generated-manifest-artifact',\n title: `${packageLabel(pkg)} has @smrt objects but no generated manifest artifact was found`,\n evidence: [\n {\n filePath: relative(projectPath, pkg.packageJsonPath),\n detail:\n 'No .smrt/manifest.json or dist/manifest.json was visible during review.',\n },\n ],\n recommendation:\n 'Run the package build/test manifest generation path and verify it uses the SMRT scanner/runtime manifest pipeline.',\n suggestedIssueTitle: `Verify SMRT manifest generation for ${packageLabel(pkg)}`,\n },\n ];\n });\n}\n\nasync function visit(\n dir: string,\n onFile: (filePath: string, entryName: string) => Promise<void> | void,\n): Promise<void> {\n let entries: Dirent[];\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n const fullPath = join(dir, entry.name);\n if (entry.isDirectory()) {\n if (SKIP_DIRS.has(entry.name)) continue;\n await visit(fullPath, onFile);\n continue;\n }\n if (entry.isFile()) await onFile(fullPath, entry.name);\n }\n}\n\nfunction collectDependencies(\n packageJson: Record<string, unknown>,\n): Set<string> {\n const dependencies = new Set<string>();\n for (const sectionName of DEPENDENCY_SECTIONS) {\n const section = packageJson[sectionName];\n if (!isRecord(section)) continue;\n for (const dependencyName of Object.keys(section)) {\n dependencies.add(dependencyName);\n }\n }\n return dependencies;\n}\n\nfunction extractImports(content: string): string[] {\n const imports = new Set<string>();\n const patterns = [\n /(?:import|export)\\s+(?:type\\s+)?(?:[^'\"]+\\s+from\\s+)?['\"]([^'\"]+)['\"]/g,\n /\\bimport\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g,\n /\\brequire\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g,\n ];\n for (const pattern of patterns) {\n for (const match of content.matchAll(pattern)) {\n const imported = normalizePackageImport(match[1]);\n if (imported) imports.add(imported);\n }\n }\n return Array.from(imports);\n}\n\nfunction normalizePackageImport(value: string | undefined): string | undefined {\n if (!value || value.startsWith('.') || value.startsWith('/'))\n return undefined;\n if (value.startsWith('@')) {\n const [scope, name] = value.split('/');\n return scope && name ? `${scope}/${name}` : value;\n }\n return value.split('/')[0];\n}\n\nfunction findOwningPackage(\n filePath: string,\n packages: PackageContext[],\n): PackageContext {\n const normalized = resolve(filePath);\n const matches = packages\n .filter(\n (pkg) =>\n normalized === pkg.directory ||\n normalized.startsWith(`${pkg.directory}${sep}`),\n )\n .sort((left, right) => right.directory.length - left.directory.length);\n return matches[0] ?? packages[0];\n}\n\nfunction packageInventory(pkg: PackageContext): PackageInventory {\n const declaredHappyVerticalDependencies = Array.from(pkg.dependencies)\n .filter((dependency) => dependency.startsWith(HAPPYVERTICAL_PACKAGE_PREFIX))\n .sort();\n const importedHappyVerticalPackages = Array.from(pkg.imports.keys()).sort();\n const ownName = typeof pkg.json.name === 'string' ? pkg.json.name : undefined;\n return {\n name: packageLabel(pkg),\n path: pkg.relativePath,\n private:\n typeof pkg.json.private === 'boolean' ? pkg.json.private : undefined,\n scripts: Object.keys(pkg.scripts).sort(),\n declaredHappyVerticalDependencies,\n importedHappyVerticalPackages,\n missingHappyVerticalDependencies: importedHappyVerticalPackages.filter(\n (name) => name !== ownName && !pkg.dependencies.has(name),\n ),\n hasSvelteKit: pkg.dependencies.has('@sveltejs/kit'),\n hasSmrtSvelte: pkg.dependencies.has('@happyvertical/smrt-svelte'),\n };\n}\n\nfunction summarizeFindings(findings: Finding[]): Record<Severity, number> {\n return findings.reduce(\n (summary, finding) => {\n summary[finding.severity]++;\n return summary;\n },\n { high: 0, medium: 0, low: 0 },\n );\n}\n\nfunction limitFindings(\n findings: Finding[],\n maxFindings: number | undefined,\n): Finding[] {\n const sorted = findings.sort(\n (left, right) =>\n severityRank(left.severity) - severityRank(right.severity) ||\n left.area.localeCompare(right.area) ||\n left.title.localeCompare(right.title),\n );\n return maxFindings && maxFindings > 0 ? sorted.slice(0, maxFindings) : sorted;\n}\n\nfunction severityRank(severity: Severity): number {\n return severity === 'high' ? 0 : severity === 'medium' ? 1 : 2;\n}\n\nfunction packageLabel(pkg: PackageContext): string {\n return typeof pkg.json.name === 'string' ? pkg.json.name : pkg.relativePath;\n}\n\nfunction lineNumber(content: string, needle: string): number | undefined {\n const index = content.indexOf(needle);\n if (index < 0) return undefined;\n return content.slice(0, index).split('\\n').length;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value);\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction pathExistsSyncHint(path: string): boolean {\n return existsSync(path);\n}\n","/**\n * SMRT Development MCP Server\n * Provides code generation, project introspection, knowledge context,\n * review/architecture prompt bundles, and portable agent skills.\n */\n\nimport { readFileSync, realpathSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport {\n ProtocolError,\n ProtocolErrorCode,\n Server,\n type Tool,\n} from '@modelcontextprotocol/server';\nimport { serveStdio } from '@modelcontextprotocol/server/stdio';\n\nimport { getAgentSkill, listAgentSkills } from './agent-skills.js';\nimport {\n buildArchitectureContext,\n buildKnowledgeIndex,\n buildReviewContext,\n checkKnowledgeFreshness,\n checkKnowledgeFreshnessFromIndex,\n packageDocPaths,\n smrtArchitecture,\n smrtReview,\n} from './knowledge/index.js';\nimport {\n generateSmrtClass,\n introspectProject,\n reviewSmrtProject,\n} from './tools/index.js';\n\nconst SERVER_NAME = 'smrt-dev-mcp';\nexport const SERVER_VERSION = readPackageVersion();\nconst DEBUG = process.env.DEBUG === 'true';\nconst REVIEW_SKILL_NAME = 'smrt-code-review';\nconst REVIEW_SKILL_URI = `smrt-dev-mcp://agent-skills/${REVIEW_SKILL_NAME}`;\nconst DOMAIN_CODE_REVIEW_PROMPT = 'domain-code-review';\nconst DOMAIN_ARCHITECTURE_PROMPT = 'domain-architecture';\nconst KNOWLEDGE_PROJECT_URI = 'smrt://knowledge/project';\nconst KNOWLEDGE_PACKAGE_PREFIX = 'smrt://knowledge/package/';\n\ntype KnowledgeIndexResult = Awaited<ReturnType<typeof buildKnowledgeIndex>>;\ntype KnowledgePackageResult = KnowledgeIndexResult['packages'][number];\ntype PromptArguments = Record<string, string> | undefined;\n\nconst JSON_SCHEMA_2020_12 = 'https://json-schema.org/draft/2020-12/schema';\n\n/**\n * Stable success/error envelope for development tools. `data` preserves each\n * tool's existing payload exactly; coverage/diagnostics are promoted only when\n * the underlying result actually reports them.\n */\nconst DEV_MCP_OUTPUT_SCHEMA: NonNullable<Tool['outputSchema']> = {\n $schema: JSON_SCHEMA_2020_12,\n type: 'object',\n additionalProperties: false,\n required: ['ok', 'coverage', 'diagnostics', 'data'],\n properties: {\n ok: { type: 'boolean' },\n coverage: { type: ['object', 'null'], additionalProperties: true },\n diagnostics: {\n type: 'array',\n items: { type: 'object', additionalProperties: true },\n },\n data: {},\n },\n};\n\n// Tool definitions\nconst TOOL_DEFINITIONS: Array<\n Pick<Tool, 'name' | 'description' | 'inputSchema'>\n> = [\n // Code Generation Tools\n {\n name: 'generate-smrt-class',\n description: 'Generate a complete SMRT class with @smrt() decorator',\n inputSchema: {\n type: 'object',\n properties: {\n className: {\n type: 'string',\n description: 'Name of the class (PascalCase)',\n },\n properties: {\n type: 'array',\n description: 'Array of property definitions',\n items: {\n type: 'object',\n properties: {\n name: { type: 'string' },\n type: {\n type: 'string',\n enum: [\n 'text',\n 'integer',\n 'decimal',\n 'boolean',\n 'datetime',\n 'json',\n ],\n },\n required: { type: 'boolean' },\n nullable: { type: 'boolean' },\n description: { type: 'string' },\n defaultValue: {\n oneOf: [\n { type: 'string' },\n { type: 'number' },\n { type: 'boolean' },\n { type: 'object' },\n { type: 'null' },\n ],\n },\n },\n required: ['name', 'type'],\n },\n },\n baseClass: {\n type: 'string',\n enum: ['SmrtObject', 'SmrtCollection'],\n default: 'SmrtObject',\n },\n template: {\n type: 'string',\n enum: [\n 'basic',\n 'global-catalog',\n 'optional-catalog',\n 'tenant-project-object',\n 'tenant-event-log-object',\n 'cross-package-reference',\n ],\n default: 'basic',\n },\n tableName: { type: 'string' },\n conflictColumns: {\n type: 'array',\n items: { type: 'string' },\n },\n tenantScoped: {\n oneOf: [\n { type: 'boolean' },\n {\n type: 'object',\n properties: {\n mode: { type: 'string', enum: ['required', 'optional'] },\n field: { type: 'string' },\n autoFilter: { type: 'boolean' },\n autoPopulate: { type: 'boolean' },\n allowSuperAdminBypass: { type: 'boolean' },\n },\n },\n ],\n },\n includeTenantIdField: { type: 'boolean' },\n relationships: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n name: { type: 'string' },\n type: {\n type: 'string',\n enum: [\n 'foreignKey',\n 'crossPackageRef',\n 'oneToMany',\n 'manyToMany',\n ],\n },\n related: { type: 'string' },\n required: { type: 'boolean' },\n nullable: { type: 'boolean' },\n description: { type: 'string' },\n validate: { type: 'boolean' },\n foreignKey: { type: 'string' },\n through: { type: 'string' },\n sourceKey: { type: 'string' },\n targetKey: { type: 'string' },\n },\n required: ['name', 'type', 'related'],\n },\n },\n includeCompanionSnippets: { type: 'boolean', default: false },\n includeApiConfig: { type: 'boolean', default: true },\n includeMcpConfig: { type: 'boolean', default: true },\n includeCliConfig: { type: 'boolean', default: true },\n },\n required: ['className', 'properties'],\n },\n },\n // Project Introspection Tools\n {\n name: 'introspect-project',\n description:\n 'Scan a directory for SMRT objects. Returns a compact summary by default; pass detail: \"full\" for field, schema, and method details.',\n inputSchema: {\n type: 'object',\n properties: {\n directory: {\n type: 'string',\n description: 'Project directory (default: cwd)',\n },\n manifestPath: {\n type: 'string',\n description:\n 'Optional manifest path. Defaults to .smrt/manifest.json, dist/manifest.json, then source scanning.',\n },\n detail: {\n type: 'string',\n enum: ['summary', 'full'],\n default: 'summary',\n description:\n 'summary: one compact record per object. full: complete field/schema/method detail (large).',\n },\n maxChars: {\n type: 'number',\n description:\n 'Character budget for the `objects` payload. Objects past the budget are omitted and reported under `truncated`. Project metadata and diagnostics are always returned in full, so the serialized response is somewhat larger than this budget.',\n },\n includeFields: {\n type: 'boolean',\n description: 'Include field details (detail: \"full\" only)',\n },\n includeRelationships: {\n type: 'boolean',\n description: 'Analyze relationships (detail: \"full\" only)',\n },\n includeMethods: {\n type: 'boolean',\n description: 'Include public method details (detail: \"full\" only)',\n },\n },\n },\n },\n {\n name: 'review-smrt-project',\n description:\n 'Advisory ecosystem alignment review for downstream SMRT projects',\n inputSchema: {\n type: 'object',\n properties: {\n directory: {\n type: 'string',\n description: 'Project directory (default: cwd)',\n },\n rootDir: {\n type: 'string',\n description: 'Compatibility alias for directory',\n },\n includeSourceEvidence: {\n type: 'boolean',\n description: 'Include file and line evidence in findings',\n default: true,\n },\n maxFindings: {\n type: 'number',\n description: 'Optional maximum number of findings to return',\n },\n },\n },\n },\n {\n name: 'reflect-knowledge',\n description:\n 'Report deterministic SMRT + HappyVertical SDK knowledge coverage and freshness',\n inputSchema: {\n type: 'object',\n properties: {\n rootDir: {\n type: 'string',\n description: 'Project root directory (default: cwd)',\n },\n },\n },\n },\n {\n name: 'reflect-domain-knowledge',\n description:\n 'Report domain-scoped SMRT knowledge artifacts, SDK packages, and freshness',\n inputSchema: {\n type: 'object',\n properties: {\n rootDir: { type: 'string' },\n scope: {\n type: 'string',\n enum: ['project', 'local', 'package', 'sdk'],\n default: 'project',\n },\n package: { type: 'string' },\n },\n },\n },\n {\n name: 'check-knowledge-freshness',\n description: 'Run deterministic freshness checks for SMRT agent knowledge',\n inputSchema: {\n type: 'object',\n properties: {\n rootDir: { type: 'string' },\n changed: {\n type: 'boolean',\n description: 'Limit stale-pattern checks to changed files',\n },\n strict: {\n type: 'boolean',\n description: 'Treat stale-pattern findings as errors',\n },\n },\n },\n },\n {\n name: 'check-domain-knowledge',\n description:\n 'Run deterministic freshness checks for domain knowledge artifacts',\n inputSchema: {\n type: 'object',\n properties: {\n rootDir: { type: 'string' },\n changed: { type: 'boolean' },\n strict: { type: 'boolean' },\n scope: {\n type: 'string',\n enum: ['project', 'local', 'package', 'sdk'],\n default: 'project',\n },\n package: { type: 'string' },\n },\n },\n },\n {\n name: 'build-review-context',\n description:\n 'Build model-ready SMRT review context from changed files and optional focus text',\n inputSchema: {\n type: 'object',\n properties: {\n rootDir: { type: 'string' },\n changedFiles: { type: 'array', items: { type: 'string' } },\n focus: { type: 'string' },\n documentation: { type: 'string' },\n detail: {\n type: 'string',\n enum: ['summary', 'full'],\n default: 'summary',\n description:\n 'summary: authored package docs are listed by path to stay inside tool-result budgets. full: embed them.',\n },\n },\n },\n },\n {\n name: 'build-domain-review-context',\n description:\n 'Build domain-scoped model-ready SMRT review context and prompt bundle',\n inputSchema: {\n type: 'object',\n properties: {\n rootDir: { type: 'string' },\n changedFiles: { type: 'array', items: { type: 'string' } },\n focus: { type: 'string' },\n documentation: { type: 'string' },\n scope: {\n type: 'string',\n enum: ['project', 'local', 'package', 'sdk'],\n default: 'project',\n },\n package: { type: 'string' },\n detail: {\n type: 'string',\n enum: ['summary', 'full'],\n default: 'summary',\n description:\n 'summary: authored package docs are listed by path to stay inside tool-result budgets. full: embed them.',\n },\n },\n },\n },\n {\n name: 'smrt-review',\n description:\n 'Return deterministic review findings and/or a reusable model prompt bundle. For a formal downstream review, first call get-agent-skill with { \"name\": \"smrt-code-review\" } or load the smrt-code-review MCP prompt/resource.',\n inputSchema: {\n type: 'object',\n properties: {\n rootDir: { type: 'string' },\n changedFiles: { type: 'array', items: { type: 'string' } },\n focus: { type: 'string' },\n documentation: { type: 'string' },\n mode: {\n type: 'string',\n enum: ['findings', 'prompt-bundle', 'both'],\n default: 'both',\n },\n detail: {\n type: 'string',\n enum: ['summary', 'full'],\n default: 'summary',\n description:\n 'summary: authored package docs are listed by path to stay inside tool-result budgets. full: embed them.',\n },\n },\n },\n },\n {\n name: 'build-architecture-context',\n description:\n 'Build model-ready SMRT architecture context from an idea or documentation',\n inputSchema: {\n type: 'object',\n properties: {\n rootDir: { type: 'string' },\n idea: { type: 'string' },\n documentation: { type: 'string' },\n focus: { type: 'string' },\n detail: {\n type: 'string',\n enum: ['summary', 'full'],\n default: 'summary',\n description:\n 'summary: authored package docs are listed by path to stay inside tool-result budgets. full: embed them.',\n },\n },\n },\n },\n {\n name: 'build-domain-architecture-context',\n description:\n 'Build domain-scoped model-ready SMRT architecture context and prompt bundle',\n inputSchema: {\n type: 'object',\n properties: {\n rootDir: { type: 'string' },\n idea: { type: 'string' },\n documentation: { type: 'string' },\n focus: { type: 'string' },\n scope: {\n type: 'string',\n enum: ['project', 'local', 'package', 'sdk'],\n default: 'project',\n },\n package: { type: 'string' },\n detail: {\n type: 'string',\n enum: ['summary', 'full'],\n default: 'summary',\n description:\n 'summary: authored package docs are listed by path to stay inside tool-result budgets. full: embed them.',\n },\n },\n },\n },\n {\n name: 'smrt-architecture',\n description:\n 'Suggest SMRT and HappyVertical SDK packages and return an architecture prompt bundle',\n inputSchema: {\n type: 'object',\n properties: {\n rootDir: { type: 'string' },\n idea: { type: 'string' },\n documentation: { type: 'string' },\n focus: { type: 'string' },\n detail: {\n type: 'string',\n enum: ['summary', 'full'],\n default: 'summary',\n description:\n 'summary: authored package docs are listed by path to stay inside tool-result budgets. full: embed them.',\n },\n },\n },\n },\n {\n name: 'list-agent-skills',\n description:\n 'List bundled harness-agnostic agent skills shipped with smrt-dev-mcp',\n inputSchema: {\n type: 'object',\n properties: {},\n },\n },\n {\n name: 'get-agent-skill',\n description:\n 'Return a bundled harness-agnostic agent skill as Markdown plus optional references',\n inputSchema: {\n type: 'object',\n properties: {\n name: {\n type: 'string',\n enum: [REVIEW_SKILL_NAME],\n description: 'Bundled agent skill name',\n },\n includeReferences: {\n type: 'boolean',\n default: true,\n description: 'Include referenced files with the skill bundle',\n },\n },\n required: ['name'],\n },\n },\n];\n\nexport const TOOLS: Tool[] = TOOL_DEFINITIONS.map((tool) => ({\n ...tool,\n inputSchema: {\n ...tool.inputSchema,\n $schema: JSON_SCHEMA_2020_12,\n },\n outputSchema: DEV_MCP_OUTPUT_SCHEMA,\n}));\n\nexport function createServer(): Server {\n if (DEBUG) {\n console.error(`[${SERVER_NAME}] Starting server v${SERVER_VERSION}`);\n }\n\n const server = new Server(\n {\n name: SERVER_NAME,\n version: SERVER_VERSION,\n },\n {\n capabilities: {\n prompts: {},\n resources: {},\n tools: {},\n },\n },\n );\n\n // List tools handler\n server.setRequestHandler('tools/list', async () => {\n if (DEBUG) {\n console.error(`[${SERVER_NAME}] ListTools request`);\n }\n return { tools: TOOLS };\n });\n\n server.setRequestHandler('prompts/list', async () => {\n return {\n prompts: [\n {\n name: REVIEW_SKILL_NAME,\n title: 'SMRT Code Review',\n description:\n 'Harness-agnostic downstream SMRT review procedure that uses smrt-dev-mcp deterministic context and prompt bundles.',\n },\n {\n name: DOMAIN_CODE_REVIEW_PROMPT,\n title: 'Domain Code Review',\n description:\n 'Model-ready domain-scoped SMRT code review prompt bundle.',\n arguments: [\n {\n name: 'rootDir',\n description: 'Project root directory. Defaults to server cwd.',\n required: false,\n },\n {\n name: 'changedFiles',\n description:\n 'Changed file paths as newline-separated, comma-separated, or JSON array text.',\n required: false,\n },\n {\n name: 'focus',\n description: 'Review focus text.',\n required: false,\n },\n {\n name: 'documentation',\n description: 'Additional documentation or notes.',\n required: false,\n },\n {\n name: 'scope',\n description: 'Knowledge scope: project, local, package, or sdk.',\n required: false,\n },\n {\n name: 'package',\n description: 'Package name or short package selector.',\n required: false,\n },\n ],\n },\n {\n name: DOMAIN_ARCHITECTURE_PROMPT,\n title: 'Domain Architecture',\n description:\n 'Model-ready domain-scoped SMRT architecture planning prompt bundle.',\n arguments: [\n {\n name: 'rootDir',\n description: 'Project root directory. Defaults to server cwd.',\n required: false,\n },\n {\n name: 'idea',\n description: 'Architecture idea or product concept.',\n required: false,\n },\n {\n name: 'documentation',\n description: 'Additional documentation or notes.',\n required: false,\n },\n {\n name: 'focus',\n description: 'Planning focus text.',\n required: false,\n },\n {\n name: 'scope',\n description: 'Knowledge scope: project, local, package, or sdk.',\n required: false,\n },\n {\n name: 'package',\n description: 'Package name or short package selector.',\n required: false,\n },\n ],\n },\n ],\n };\n });\n\n server.setRequestHandler('prompts/get', async (request) => {\n const { name } = request.params;\n if (name === REVIEW_SKILL_NAME) {\n return {\n description:\n 'Use this procedure when reviewing downstream SMRT projects.',\n messages: [\n {\n role: 'user' as const,\n content: {\n type: 'text' as const,\n text: renderAgentSkillMarkdown(REVIEW_SKILL_NAME),\n },\n },\n ],\n };\n }\n\n if (name === DOMAIN_CODE_REVIEW_PROMPT) {\n const context = await buildReviewContext(\n reviewPromptArguments(request.params.arguments),\n );\n return {\n description: 'Review downstream SMRT code with domain knowledge.',\n messages: [\n {\n role: 'user' as const,\n content: {\n type: 'text' as const,\n text: context.promptBundle.contextMarkdown,\n },\n },\n ],\n };\n }\n\n if (name === DOMAIN_ARCHITECTURE_PROMPT) {\n const context = await buildArchitectureContext(\n architecturePromptArguments(request.params.arguments),\n );\n return {\n description: 'Plan a downstream SMRT project with domain knowledge.',\n messages: [\n {\n role: 'user' as const,\n content: {\n type: 'text' as const,\n text: context.promptBundle.contextMarkdown,\n },\n },\n ],\n };\n }\n\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Unknown prompt: ${name}`,\n );\n });\n\n server.setRequestHandler('resources/list', async () => {\n const index = await buildKnowledgeIndex();\n return {\n resources: [\n {\n uri: REVIEW_SKILL_URI,\n name: REVIEW_SKILL_NAME,\n title: 'SMRT Code Review Skill',\n description:\n 'Bundled Markdown skill for downstream SMRT code reviews.',\n mimeType: 'text/markdown',\n },\n {\n uri: KNOWLEDGE_PROJECT_URI,\n name: 'smrt-domain-knowledge-project',\n title: 'SMRT Domain Knowledge Project Index',\n description:\n 'Composed SMRT, downstream domain, and HappyVertical SDK knowledge index.',\n mimeType: 'application/json',\n },\n ...index.packages.map((pkg) => ({\n uri: `${KNOWLEDGE_PACKAGE_PREFIX}${encodeURIComponent(pkg.name)}`,\n name: `smrt-domain-knowledge-${pkg.name}`,\n title: `SMRT Domain Knowledge: ${pkg.name}`,\n description:\n 'Package-scoped SMRT domain knowledge, generated surfaces, and authored context.',\n mimeType: 'application/json',\n })),\n ],\n };\n });\n\n server.setRequestHandler('resources/read', async (request) => {\n const { uri } = request.params;\n if (uri === REVIEW_SKILL_URI) {\n return {\n contents: [\n {\n uri,\n mimeType: 'text/markdown',\n text: renderAgentSkillMarkdown(REVIEW_SKILL_NAME),\n },\n ],\n };\n }\n\n if (uri === KNOWLEDGE_PROJECT_URI) {\n const index = await buildKnowledgeIndex();\n return {\n contents: [\n {\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(sanitizeKnowledgeIndex(index), null, 2),\n },\n ],\n };\n }\n\n if (uri.startsWith(KNOWLEDGE_PACKAGE_PREFIX)) {\n const packageName = decodeURIComponent(\n uri.slice(KNOWLEDGE_PACKAGE_PREFIX.length),\n );\n const index = await buildKnowledgeIndex();\n const pkg = index.packages.find((item) => item.name === packageName);\n if (!pkg) {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Unknown knowledge package: ${packageName}`,\n );\n }\n return {\n contents: [\n {\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(sanitizeKnowledgePackage(pkg), null, 2),\n },\n ],\n };\n }\n\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Unknown resource: ${uri}`,\n );\n });\n\n // Call tool handler\n server.setRequestHandler('tools/call', async (request) => {\n const { name, arguments: args } = request.params;\n\n if (DEBUG) {\n console.error(`[${SERVER_NAME}] CallTool: ${name}`);\n console.error(\n `[${SERVER_NAME}] Arguments:`,\n JSON.stringify(args, null, 2),\n );\n }\n\n try {\n let result: string;\n\n switch (name) {\n case 'generate-smrt-class':\n result = await generateSmrtClass(\n args as unknown as Parameters<typeof generateSmrtClass>[0],\n );\n break;\n\n case 'introspect-project':\n result = await introspectProject(\n args as unknown as Parameters<typeof introspectProject>[0],\n );\n break;\n\n case 'review-smrt-project':\n result = await reviewSmrtProject(\n args as unknown as Parameters<typeof reviewSmrtProject>[0],\n );\n break;\n\n case 'reflect-knowledge': {\n const index = await buildKnowledgeIndex(\n args as unknown as Parameters<typeof buildKnowledgeIndex>[0],\n );\n const freshness = await checkKnowledgeFreshnessFromIndex(\n index,\n args as unknown as Parameters<\n typeof checkKnowledgeFreshnessFromIndex\n >[1],\n );\n result = JSON.stringify(\n {\n rootDir: index.rootDir,\n packageCount: index.packages.length,\n smrtPackageCount: index.smrtPackages.length,\n sdkPackageCount: index.sdkPackages.length,\n relationshipsV2: index.relationshipsV2,\n coverage: index.coverage,\n diagnostics: index.diagnostics,\n freshness,\n },\n null,\n 2,\n );\n break;\n }\n\n case 'reflect-domain-knowledge': {\n const index = await buildKnowledgeIndex(\n args as unknown as Parameters<typeof buildKnowledgeIndex>[0],\n );\n const freshness = await checkKnowledgeFreshnessFromIndex(\n index,\n args as unknown as Parameters<\n typeof checkKnowledgeFreshnessFromIndex\n >[1],\n );\n result = JSON.stringify(\n {\n rootDir: index.rootDir,\n packageCount: index.packages.length,\n smrtPackageCount: index.smrtPackages.length,\n sdkPackageCount: index.sdkPackages.length,\n domainKnowledgePackageCount: index.packages.filter(\n (pkg) => pkg.hasDomainKnowledge,\n ).length,\n missingDomainKnowledgePackages: index.packages\n .filter(\n (pkg) =>\n pkg.exportKeys.includes('./smrt-knowledge.json') &&\n !pkg.hasDomainKnowledge,\n )\n .map((pkg) => pkg.name),\n relationshipsV2: index.relationshipsV2,\n coverage: index.coverage,\n diagnostics: index.diagnostics,\n freshness,\n },\n null,\n 2,\n );\n break;\n }\n\n case 'check-knowledge-freshness':\n result = JSON.stringify(\n await checkKnowledgeFreshness(\n args as unknown as Parameters<typeof checkKnowledgeFreshness>[0],\n ),\n null,\n 2,\n );\n break;\n\n case 'check-domain-knowledge':\n result = JSON.stringify(\n await checkKnowledgeFreshness(\n args as unknown as Parameters<typeof checkKnowledgeFreshness>[0],\n ),\n null,\n 2,\n );\n break;\n\n case 'build-review-context':\n case 'build-domain-review-context':\n result = JSON.stringify(\n compactContextResult(\n await buildReviewContext(\n args as unknown as Parameters<typeof buildReviewContext>[0],\n ),\n detailArg(args),\n ),\n null,\n 2,\n );\n break;\n\n case 'smrt-review':\n result = JSON.stringify(\n compactContextResult(\n await smrtReview(\n args as unknown as Parameters<typeof smrtReview>[0],\n ),\n detailArg(args),\n ),\n null,\n 2,\n );\n break;\n\n case 'build-architecture-context':\n case 'build-domain-architecture-context':\n result = JSON.stringify(\n compactContextResult(\n await buildArchitectureContext(\n args as unknown as Parameters<\n typeof buildArchitectureContext\n >[0],\n ),\n detailArg(args),\n ),\n null,\n 2,\n );\n break;\n\n case 'smrt-architecture':\n result = JSON.stringify(\n compactContextResult(\n await smrtArchitecture(\n args as unknown as Parameters<typeof smrtArchitecture>[0],\n ),\n detailArg(args),\n ),\n null,\n 2,\n );\n break;\n\n case 'list-agent-skills':\n result = JSON.stringify({ skills: listAgentSkills() }, null, 2);\n break;\n\n case 'get-agent-skill':\n result = JSON.stringify(\n await getAgentSkill(\n args as unknown as Parameters<typeof getAgentSkill>[0],\n ),\n null,\n 2,\n );\n break;\n\n default:\n throw new Error(`Unknown tool: ${name}`);\n }\n\n return {\n content: [\n {\n type: 'text',\n text: result,\n },\n ],\n structuredContent: toDevToolStructuredContent(result),\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : 'Unknown error';\n console.error(`[${SERVER_NAME}] Error:`, error);\n\n return {\n content: [\n {\n type: 'text',\n text: `Error executing tool ${name}: ${errorMessage}`,\n },\n ],\n isError: true,\n structuredContent: {\n ok: false,\n coverage: null,\n diagnostics: [{ severity: 'error', message: errorMessage }],\n data: null,\n },\n };\n }\n });\n\n return server;\n}\n\nasync function main() {\n const handle = serveStdio(() => createServer(), {\n onerror: (error) =>\n console.error(`[${SERVER_NAME}] Protocol error:`, error),\n });\n\n if (DEBUG) {\n console.error(`[${SERVER_NAME}] Server connected via stdio`);\n }\n\n // Graceful shutdown\n process.on('SIGINT', async () => {\n if (DEBUG) {\n console.error(`[${SERVER_NAME}] Shutting down...`);\n }\n await handle.close();\n process.exit(0);\n });\n\n process.on('SIGTERM', async () => {\n if (DEBUG) {\n console.error(`[${SERVER_NAME}] Shutting down...`);\n }\n await handle.close();\n process.exit(0);\n });\n}\n\nfunction isEntrypoint(): boolean {\n const entry = process.argv[1];\n if (!entry) return false;\n try {\n return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(entry);\n } catch {\n return import.meta.url === pathToFileURL(entry).href;\n }\n}\n\nfunction readPackageVersion(): string {\n try {\n const packageRoot = dirname(fileURLToPath(import.meta.url));\n const packageJsonPath = join(packageRoot, '..', 'package.json');\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8')) as {\n version?: unknown;\n };\n return typeof packageJson.version === 'string'\n ? packageJson.version\n : '0.0.0';\n } catch {\n return '0.0.0';\n }\n}\n\nfunction renderAgentSkillMarkdown(name: string): string {\n const skill = getAgentSkill({ name, includeReferences: true });\n const references = skill.referenceFiles.map(\n (file) => `## Reference: ${file.path}\\n\\n${file.content.trim()}`,\n );\n return [skill.skillMarkdown.trim(), ...references].join('\\n\\n');\n}\n\nfunction reviewPromptArguments(args: PromptArguments): Record<string, unknown> {\n return compactRecord({\n rootDir: args?.rootDir,\n changedFiles: parseStringList(args?.changedFiles),\n focus: args?.focus,\n documentation: args?.documentation,\n scope: args?.scope,\n package: args?.package,\n });\n}\n\nfunction architecturePromptArguments(\n args: PromptArguments,\n): Record<string, unknown> {\n return compactRecord({\n rootDir: args?.rootDir,\n idea: args?.idea,\n documentation: args?.documentation,\n focus: args?.focus,\n scope: args?.scope,\n package: args?.package,\n });\n}\n\nfunction parseStringList(value: string | undefined): string[] | undefined {\n if (!value?.trim()) return undefined;\n\n try {\n const parsed = JSON.parse(value);\n if (Array.isArray(parsed)) {\n return parsed.filter((item): item is string => typeof item === 'string');\n }\n } catch {\n // Fall through to delimiter parsing.\n }\n\n return value\n .split(/[\\n,]/)\n .map((item) => item.trim())\n .filter(Boolean);\n}\n\nfunction compactRecord(\n value: Record<string, unknown>,\n): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(value).filter(([, entry]) => entry !== undefined),\n );\n}\n\nfunction sanitizeKnowledgeIndex(index: KnowledgeIndexResult) {\n const packages = index.packages.map((pkg) => sanitizeKnowledgePackage(pkg));\n return {\n ...index,\n rootDir: '.',\n packages,\n smrtPackages: packages.filter((pkg) => pkg.kind === 'smrt'),\n sdkPackages: packages.filter((pkg) => pkg.kind === 'sdk'),\n };\n}\n\n/**\n * Compact projection of a context result for MCP callers (#2143).\n *\n * `selectedPackages` carries each package's whole authored `agentDoc`, its\n * module-doc contents, and its full domain manifest. A three-package downstream\n * product serialized to 329,003 characters that way, which is what made these\n * tools unusable as planning aids. `detail: \"full\"` returns the whole shape.\n */\nfunction compactContextResult(\n result: object,\n detail: string | undefined,\n): Record<string, unknown> {\n const source = result as Record<string, unknown>;\n if (detail === 'full') return source;\n\n const compact: Record<string, unknown> = { ...source, detail: 'summary' };\n for (const key of ['selectedPackages', 'selectedSdkPackages']) {\n const packages = source[key];\n if (!Array.isArray(packages)) continue;\n compact[key] = (packages as KnowledgePackageResult[]).map(\n compactKnowledgePackage,\n );\n }\n return compact;\n}\n\nfunction compactKnowledgePackage(pkg: KnowledgePackageResult) {\n return {\n name: pkg.name,\n version: pkg.version,\n kind: pkg.kind,\n directory: pkg.relativeDirectory,\n objectSource: pkg.objectSource,\n ...(pkg.objectSourceReason\n ? { objectSourceReason: pkg.objectSourceReason }\n : {}),\n // Paths, not prose: the caller reads what it needs.\n docs: packageDocPaths(pkg),\n domainKnowledgePath: pkg.domainKnowledgePath,\n relationshipFeatures: pkg.relationshipFeatures,\n smrtDependencies: pkg.smrtDependencies,\n sdkDependencies: pkg.sdkDependencies,\n exportKeys: pkg.exportKeys,\n objectCount: pkg.objects.length,\n objects: pkg.objects.map((object) =>\n object.tableName\n ? `${object.qualifiedName ?? object.className} (${object.tableName})`\n : (object.qualifiedName ?? object.className),\n ),\n mcpToolCount: pkg.mcpTools.length,\n };\n}\n\nfunction detailArg(args: unknown): string | undefined {\n const detail = (args as Record<string, unknown> | undefined)?.detail;\n return typeof detail === 'string' ? detail : undefined;\n}\n\nfunction toDevToolStructuredContent(result: string) {\n let data: unknown = result;\n try {\n data = JSON.parse(result);\n } catch {\n // `generate-smrt-class` intentionally returns source text, not JSON.\n }\n\n const source = isRecord(data) ? data : undefined;\n const coverage = isRecord(source?.coverage) ? source.coverage : null;\n const diagnostics = Array.isArray(source?.diagnostics)\n ? source.diagnostics.filter(isRecord)\n : [];\n return { ok: true, coverage, diagnostics, data };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction sanitizeKnowledgePackage(pkg: KnowledgePackageResult) {\n const { directory: _directory, objects, checkedObjectPaths, ...rest } = pkg;\n return {\n ...rest,\n // Paths outside the workspace root stay absolute in the index; redact them\n // here the same way object file paths are redacted.\n checkedObjectPaths: checkedObjectPaths.map(\n (path) => sanitizePath(path) ?? path,\n ),\n objects: objects.map((object) => ({\n ...object,\n filePath: sanitizePath(object.filePath),\n })),\n };\n}\n\nfunction sanitizePath(path: string | undefined): string | undefined {\n if (!path) return path;\n if (path.startsWith('/') || /^[A-Za-z]:[\\\\/]/.test(path)) {\n return '<absolute-path>';\n }\n return path;\n}\n\nif (isEntrypoint()) {\n main().catch((error) => {\n console.error(`[${SERVER_NAME}] Fatal error:`, error);\n process.exit(1);\n });\n}\n"],"mappings":";;;;;;;;;;;AAuBA,IAAM,eAAuC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CACxE,OAAO;EACL,GAAG;EAGH,oBAAoB,mBAAmB,KACpC,SAAS,aAAa,IAAI,KAAK,IAClC;EACA,SAAS,QAAQ,KAAK,YAAY;GAChC,GAAG;GACH,UAAU,aAAa,OAAO,QAAQ;EACxC,EAAE;CACJ;AACF;AAEA,SAAS,aAAa,MAA8C;CAClE,IAAI,CAAC,MAAM,OAAO;CAClB,IAAI,KAAK,WAAW,GAAG,KAAK,kBAAkB,KAAK,IAAI,GACrD,OAAO;CAET,OAAO;AACT;AAEA,IAAI,aAAa,GACf,KAAK,CAAC,CAAC,OAAO,UAAU;CACtB,QAAQ,MAAM,IAAI,YAAY,iBAAiB,KAAK;CACpD,QAAQ,KAAK,CAAC;AAChB,CAAC"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/agent-skills.ts","../src/tools/generate-smrt-class.ts","../src/tools/introspect-project.ts","../src/tools/review-smrt-project.ts","../src/index.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nexport interface AgentSkillSummary {\n name: string;\n description: string;\n path: string;\n references: string[];\n}\n\nexport interface AgentSkillBundle extends AgentSkillSummary {\n skillMarkdown: string;\n referenceFiles: Array<{\n path: string;\n content: string;\n }>;\n}\n\ninterface AgentSkillDefinition extends AgentSkillSummary {\n skillFile: string;\n}\n\nconst AGENT_SKILLS: AgentSkillDefinition[] = [\n {\n name: 'smrt-code-review',\n description:\n 'Harness-agnostic downstream SMRT code review workflow using smrt-dev-mcp deterministic context and prompt bundles.',\n path: 'skills/smrt-code-review/SKILL.md',\n skillFile: 'skills/smrt-code-review/SKILL.md',\n references: ['skills/smrt-code-review/references/review-output.md'],\n },\n];\n\nexport function listAgentSkills(): AgentSkillSummary[] {\n return AGENT_SKILLS.map(({ skillFile: _skillFile, ...skill }) => skill);\n}\n\nexport function getAgentSkill(options: {\n name: string;\n includeReferences?: boolean;\n}): AgentSkillBundle {\n const skill = AGENT_SKILLS.find((item) => item.name === options.name);\n if (!skill) {\n throw new Error(`Unknown agent skill: ${options.name}`);\n }\n\n return {\n name: skill.name,\n description: skill.description,\n path: skill.path,\n references: skill.references,\n skillMarkdown: readPackageFile(skill.skillFile),\n referenceFiles:\n options.includeReferences === false\n ? []\n : skill.references.map((path) => ({\n path,\n content: readPackageFile(path),\n })),\n };\n}\n\nfunction readPackageFile(relativePath: string): string {\n const packageRoot = resolvePackageRoot();\n return readFileSync(join(packageRoot, relativePath), 'utf8');\n}\n\nfunction resolvePackageRoot(): string {\n // Works in both source tests (`src/agent-skills.ts`) and built packages\n // (`dist/agent-skills.js`); guard it so packaging layout drift fails clearly.\n const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));\n if (!existsSync(join(packageRoot, 'package.json'))) {\n throw new Error(\n `Unable to resolve smrt-dev-mcp package root from ${import.meta.url}`,\n );\n }\n return packageRoot;\n}\n","/**\n * Generate SMRT Class Tool\n * Creates a package-ready SMRT class using current object-package patterns.\n */\n\ntype PropertyType =\n | 'text'\n | 'integer'\n | 'decimal'\n | 'boolean'\n | 'datetime'\n | 'json';\ntype BaseClass = 'SmrtObject' | 'SmrtCollection';\ntype TemplateVariant =\n | 'basic'\n | 'global-catalog'\n | 'optional-catalog'\n | 'tenant-project-object'\n | 'tenant-event-log-object'\n | 'cross-package-reference';\ntype RelationshipType =\n | 'foreignKey'\n | 'crossPackageRef'\n | 'oneToMany'\n | 'manyToMany';\n\ninterface PropertyDefinition {\n name: string;\n type: PropertyType;\n required?: boolean;\n nullable?: boolean;\n description?: string;\n defaultValue?: unknown;\n}\n\ninterface RelationshipDefinition {\n name: string;\n type: RelationshipType;\n related: string;\n required?: boolean;\n nullable?: boolean;\n description?: string;\n validate?: boolean;\n foreignKey?: string;\n through?: string;\n sourceKey?: string;\n targetKey?: string;\n}\n\ninterface TenantScopedDefinition {\n mode?: 'required' | 'optional';\n field?: string;\n autoFilter?: boolean;\n autoPopulate?: boolean;\n allowSuperAdminBypass?: boolean;\n}\n\ninterface GenerateSmrtClassArgs {\n className: string;\n properties: PropertyDefinition[];\n baseClass?: BaseClass;\n template?: TemplateVariant;\n tableName?: string;\n conflictColumns?: string[];\n tenantScoped?: boolean | TenantScopedDefinition;\n includeTenantIdField?: boolean;\n relationships?: RelationshipDefinition[];\n includeApiConfig?: boolean;\n includeMcpConfig?: boolean;\n includeCliConfig?: boolean;\n includeCompanionSnippets?: boolean;\n}\n\ninterface NormalizedGenerateSmrtClassArgs {\n className: string;\n properties: PropertyDefinition[];\n baseClass: BaseClass;\n template: TemplateVariant;\n tableName?: string;\n conflictColumns: string[];\n tenantScoped?: TenantScopedDefinition;\n includeTenantIdField: boolean;\n relationships: RelationshipDefinition[];\n includeApiConfig: boolean;\n includeMcpConfig: boolean;\n includeCliConfig: boolean;\n includeCompanionSnippets: boolean;\n}\n\nconst TYPE_MAPPING: Record<\n PropertyType,\n { tsType: string; defaultValue: string }\n> = {\n text: { tsType: 'string', defaultValue: \"''\" },\n integer: { tsType: 'number', defaultValue: '0' },\n decimal: { tsType: 'number', defaultValue: '0.0' },\n boolean: { tsType: 'boolean', defaultValue: 'false' },\n datetime: { tsType: 'Date', defaultValue: 'new Date()' },\n json: { tsType: 'any', defaultValue: '{}' },\n};\n\nexport async function generateSmrtClass(\n args: GenerateSmrtClassArgs,\n): Promise<string> {\n const normalized = normalizeArgs(args);\n const {\n className,\n properties,\n relationships,\n baseClass,\n tableName,\n conflictColumns,\n tenantScoped,\n includeTenantIdField,\n includeApiConfig,\n includeMcpConfig,\n includeCliConfig,\n includeCompanionSnippets,\n } = normalized;\n\n const coreImports = new Set<string>([baseClass, 'smrt']);\n if (needsFieldDecorator(properties)) coreImports.add('field');\n for (const relationship of relationships) {\n coreImports.add(relationship.type);\n }\n\n const imports = [\n `import { ${Array.from(coreImports).join(', ')} } from '@happyvertical/smrt-core';`,\n ];\n\n if (tenantScoped) {\n const tenancyImports = ['TenantScoped'];\n if (includeTenantIdField) tenancyImports.push('tenantId');\n imports.push(\n `import { ${tenancyImports.join(', ')} } from '@happyvertical/smrt-tenancy';`,\n );\n }\n\n const decoratorLines = [\n ...(tenantScoped\n ? [`@TenantScoped(${renderObjectLiteral({ ...tenantScoped })})`]\n : []),\n renderSmrtDecorator({\n includeApiConfig,\n includeMcpConfig,\n includeCliConfig,\n tableName,\n conflictColumns,\n }),\n ];\n\n const classMembers = [\n ...(includeTenantIdField && tenantScoped\n ? [renderTenantIdField(tenantScoped)]\n : []),\n ...properties.map(renderProperty),\n ...relationships.map(renderRelationship),\n ].filter(Boolean);\n\n const companionSnippets = includeCompanionSnippets\n ? `\\n${renderCompanionSnippets(className, Boolean(tenantScoped))}`\n : '';\n\n return `${imports.join('\\n')}\n\n${decoratorLines.join('\\n')}\nexport class ${className} extends ${baseClass} {\n${classMembers.join('\\n\\n')}\n\n constructor(options: any = {}) {\n super(options);\n Object.assign(this, options);\n }\n}\n${companionSnippets}`;\n}\n\nfunction normalizeArgs(\n args: GenerateSmrtClassArgs,\n): NormalizedGenerateSmrtClassArgs {\n const template = args.template ?? 'basic';\n const templateDefaults = defaultsForTemplate(template);\n const tenantScoped =\n args.tenantScoped === true\n ? (templateDefaults.tenantScoped ?? { mode: 'required' as const })\n : args.tenantScoped === false\n ? undefined\n : (args.tenantScoped ?? templateDefaults.tenantScoped);\n\n return {\n className: args.className,\n properties: args.properties,\n baseClass: args.baseClass ?? 'SmrtObject',\n template,\n tableName: args.tableName ?? templateDefaults.tableName,\n conflictColumns:\n args.conflictColumns ?? templateDefaults.conflictColumns ?? [],\n tenantScoped: normalizeTenantScoped(tenantScoped),\n includeTenantIdField:\n args.includeTenantIdField ??\n templateDefaults.includeTenantIdField ??\n Boolean(tenantScoped),\n relationships: args.relationships ?? [],\n includeApiConfig: args.includeApiConfig ?? true,\n includeMcpConfig: args.includeMcpConfig ?? true,\n includeCliConfig: args.includeCliConfig ?? true,\n includeCompanionSnippets: args.includeCompanionSnippets ?? false,\n };\n}\n\nfunction defaultsForTemplate(template: TemplateVariant): {\n tableName?: string;\n conflictColumns?: string[];\n tenantScoped?: TenantScopedDefinition;\n includeTenantIdField?: boolean;\n} {\n switch (template) {\n case 'optional-catalog':\n return {\n tenantScoped: { mode: 'optional' },\n includeTenantIdField: true,\n conflictColumns: ['tenant_id', 'slug'],\n };\n case 'tenant-project-object':\n return {\n tenantScoped: { mode: 'required' },\n includeTenantIdField: true,\n };\n case 'tenant-event-log-object':\n return {\n tenantScoped: { mode: 'optional' },\n includeTenantIdField: true,\n };\n case 'global-catalog':\n return { conflictColumns: ['slug'] };\n case 'cross-package-reference':\n case 'basic':\n return {};\n }\n}\n\nfunction normalizeTenantScoped(\n value: boolean | TenantScopedDefinition | undefined,\n): TenantScopedDefinition | undefined {\n if (!value) return undefined;\n return {\n mode: typeof value === 'object' ? (value.mode ?? 'required') : 'required',\n field: typeof value === 'object' ? (value.field ?? 'tenantId') : 'tenantId',\n autoFilter: typeof value === 'object' ? value.autoFilter : undefined,\n autoPopulate: typeof value === 'object' ? value.autoPopulate : undefined,\n allowSuperAdminBypass:\n typeof value === 'object' ? value.allowSuperAdminBypass : undefined,\n };\n}\n\nfunction renderSmrtDecorator(options: {\n includeApiConfig: boolean;\n includeMcpConfig: boolean;\n includeCliConfig: boolean;\n tableName?: string;\n conflictColumns: string[];\n}): string {\n const decoratorConfig: Record<string, unknown> = {};\n\n if (options.tableName) {\n decoratorConfig.tableName = options.tableName;\n }\n\n if (options.conflictColumns.length > 0) {\n decoratorConfig.conflictColumns = options.conflictColumns;\n }\n\n if (options.includeApiConfig) {\n decoratorConfig.api = {\n include: ['list', 'get', 'create', 'update'],\n exclude: ['delete'],\n };\n }\n\n if (options.includeMcpConfig) {\n decoratorConfig.mcp = {\n include: ['list', 'get'],\n };\n }\n\n if (options.includeCliConfig) {\n decoratorConfig.cli = true;\n }\n\n return Object.keys(decoratorConfig).length > 0\n ? `@smrt(${JSON.stringify(decoratorConfig, null, 2)})`\n : '@smrt()';\n}\n\nfunction renderTenantIdField(tenantScoped: TenantScopedDefinition): string {\n const nullable = tenantScoped.mode === 'optional';\n const field = tenantScoped.field ?? 'tenantId';\n return nullable\n ? ` @tenantId({ nullable: true })\\n ${field}: string | null = null;`\n : ` @tenantId()\\n ${field}: string = '';`;\n}\n\nfunction renderProperty(prop: PropertyDefinition): string {\n const mapping = TYPE_MAPPING[prop.type];\n const nullable = prop.nullable === true;\n const tsType = nullable ? `${mapping.tsType} | null` : mapping.tsType;\n const defaultValue =\n prop.defaultValue !== undefined\n ? renderLiteral(prop.defaultValue)\n : nullable\n ? 'null'\n : mapping.defaultValue;\n const fieldOptions = compactObject({\n required: prop.required,\n nullable: prop.nullable,\n description: prop.description,\n });\n const jsdoc = prop.description ? ` /** ${prop.description} */\\n` : '';\n const decorator =\n Object.keys(fieldOptions).length > 0\n ? ` @field(${JSON.stringify(fieldOptions)})\\n`\n : '';\n\n return `${jsdoc}${decorator} ${prop.name}: ${tsType} = ${defaultValue};`;\n}\n\nfunction renderRelationship(relationship: RelationshipDefinition): string {\n const options = compactObject({\n required: relationship.required,\n nullable: relationship.nullable,\n description: relationship.description,\n validate: relationship.validate,\n foreignKey: relationship.foreignKey,\n through: relationship.through,\n sourceKey: relationship.sourceKey,\n targetKey: relationship.targetKey,\n });\n const args = [\n renderLiteral(relationship.related),\n ...(Object.keys(options).length > 0 ? [JSON.stringify(options)] : []),\n ];\n const decorator = `@${relationship.type}(${args.join(', ')})`;\n const fieldType =\n relationship.type === 'oneToMany' || relationship.type === 'manyToMany'\n ? 'unknown[]'\n : relationship.nullable\n ? 'string | null'\n : 'string';\n const defaultValue =\n relationship.type === 'oneToMany' || relationship.type === 'manyToMany'\n ? '[]'\n : relationship.nullable\n ? 'null'\n : \"''\";\n\n return ` ${decorator}\\n ${relationship.name}: ${fieldType} = ${defaultValue};`;\n}\n\nfunction needsFieldDecorator(properties: PropertyDefinition[]): boolean {\n return properties.some(\n (property) =>\n property.required !== undefined ||\n property.nullable !== undefined ||\n property.description !== undefined,\n );\n}\n\nfunction renderCompanionSnippets(\n className: string,\n usesTenantScoped: boolean,\n): string {\n const dependencyNote = usesTenantScoped\n ? `\\n * - Ensure package.json declares \"@happyvertical/smrt-tenancy\".`\n : '';\n return `/*\n * Package wiring:\n * - Export ${className} from the package entrypoint used by consumers.\n * - Import this module from any package registration file that eagerly loads objects.${dependencyNote}\n */`;\n}\n\nfunction renderObjectLiteral(value: Record<string, unknown>): string {\n return JSON.stringify(compactObject(value), null, 2);\n}\n\nfunction renderLiteral(value: unknown): string {\n if (typeof value === 'string') return JSON.stringify(value);\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (value === null) return 'null';\n return JSON.stringify(value, null, 2);\n}\n\nfunction compactObject<T extends Record<string, unknown>>(value: T): T {\n return Object.fromEntries(\n Object.entries(value).filter(([, entry]) => entry !== undefined),\n ) as T;\n}\n","/**\n * Project Introspection Tool\n * Returns a manifest-equivalent inventory of SMRT objects in a project.\n */\n\nimport type { Dirent } from 'node:fs';\nimport { access, readdir, readFile } from 'node:fs/promises';\nimport { isAbsolute, join, relative, resolve } from 'node:path';\nimport {\n ManifestGenerator,\n type SmartObjectManifest,\n} from '@happyvertical/smrt-core/scanner';\nimport type { ScanError } from '@happyvertical/smrt-scanner';\nimport { ManifestAdapter, OxcScanner } from '@happyvertical/smrt-scanner';\n\n/**\n * `summary` (default) returns one compact record per object; `full` returns the\n * verbose shape. A 42-object project produced 338,462 characters in the only\n * mode that used to exist, which put every call over tool-result budgets and\n * forced callers to write-to-file and `jq` (#2143).\n */\nexport type IntrospectDetail = 'summary' | 'full';\n\n/** Common shape both detail modes emit, so the two branches share a list. */\ntype IntrospectedObject = Record<string, unknown> & { className: string };\n\ninterface IntrospectProjectArgs {\n directory?: string;\n manifestPath?: string;\n includeFields?: boolean;\n includeRelationships?: boolean;\n includeMethods?: boolean;\n detail?: IntrospectDetail;\n /**\n * Overrides the default character budget for the serialized `objects` array.\n *\n * Project metadata and diagnostics are deliberately exempt: a diagnostic is\n * how discovery reports that it found nothing (#2143), so budgeting it away\n * would hide the very failure the caller needs to see. The full response is\n * therefore somewhat larger than this budget.\n */\n maxChars?: number;\n}\n\ntype DiagnosticSeverity = 'error' | 'warning' | 'info';\n\ninterface Diagnostic {\n severity: DiagnosticSeverity;\n message: string;\n filePath?: string;\n line?: number;\n column?: number;\n}\n\ninterface ManifestLike {\n version?: string;\n packageName?: string;\n packageVersion?: string;\n objects?: Record<string, ManifestObject>;\n}\n\ninterface ManifestObject {\n name?: string;\n className: string;\n qualifiedName?: string;\n collection?: string;\n filePath: string;\n packageName?: string;\n packageVersion?: string;\n importPath?: string;\n modulePath?: string;\n exportName?: string;\n collectionExportName?: string;\n fields?: Record<string, ManifestField>;\n methods?: Record<string, ManifestMethod>;\n decoratorConfig?: Record<string, unknown>;\n extends?: string;\n extendsTypeArg?: string;\n schema?: ManifestSchema;\n staticProperties?: Record<string, unknown>;\n validationRules?: Record<string, unknown>;\n}\n\ninterface ManifestField {\n type: string;\n required?: boolean;\n default?: unknown;\n related?: string;\n description?: string;\n _meta?: Record<string, unknown>;\n transient?: boolean;\n}\n\ninterface ManifestMethod {\n name?: string;\n async?: boolean;\n parameters?: Array<{\n name: string;\n type?: string;\n optional?: boolean;\n default?: unknown;\n }>;\n returnType?: string;\n description?: string;\n isStatic?: boolean;\n isPublic?: boolean;\n}\n\ninterface ManifestSchema {\n tableName?: string;\n ddl?: string;\n columns?: Record<string, unknown>;\n indexes?: Array<{\n name?: string;\n columns?: string[];\n unique?: boolean;\n where?: string;\n jsonPath?: unknown;\n }>;\n version?: string;\n}\n\ninterface PackageMetadata {\n name?: string;\n version?: string;\n json?: Record<string, unknown>;\n}\n\nconst DEFAULT_MANIFEST_PATHS = [\n '.smrt/manifest.json',\n 'dist/manifest.json',\n 'src/manifest/manifest.json',\n];\n\nconst SCAN_EXCLUDE = [\n '**/node_modules/**',\n '**/dist/**',\n '**/build/**',\n '**/.git/**',\n '**/.smrt/**',\n '**/*.d.ts',\n '**/*.test.ts',\n '**/*.spec.ts',\n '**/__tests__/**',\n];\n\nconst RELATIONSHIP_TYPES = new Set([\n 'foreignKey',\n 'crossPackageRef',\n 'oneToMany',\n 'manyToMany',\n]);\n\n/**\n * Response budget in characters. Generous enough that a 42-object summary never\n * truncates, while still capping a runaway payload instead of emitting one.\n */\nconst DEFAULT_MAX_CHARS = 50_000;\n\nconst DEFAULT_MCP_OPERATIONS = ['list', 'get', 'create', 'update', 'delete'];\n\nexport async function introspectProject(\n args: IntrospectProjectArgs,\n): Promise<string> {\n const {\n directory = process.cwd(),\n includeFields = true,\n includeRelationships = true,\n includeMethods = true,\n detail = 'summary',\n maxChars = DEFAULT_MAX_CHARS,\n } = args;\n const projectPath = resolve(directory);\n\n const exists = await pathExists(projectPath);\n if (!exists) {\n return JSON.stringify(\n {\n projectPath,\n manifestSource: 'none',\n objectCount: 0,\n objects: [],\n diagnostics: [\n {\n severity: 'warning',\n message: `Project directory does not exist: ${projectPath}`,\n },\n ],\n },\n null,\n 2,\n );\n }\n\n const packageMetadata = await readPackageMetadata(projectPath);\n const tenantScopes = await scanTenantScopes(projectPath);\n const manifestResult =\n (await loadManifestArtifact(projectPath, args.manifestPath)) ??\n (await scanSourceManifest(projectPath, packageMetadata));\n\n const entries = Object.entries(manifestResult.manifest.objects ?? {});\n const objects: IntrospectedObject[] =\n detail === 'summary'\n ? entries.map(([manifestKey, object]) =>\n summarizeObject({\n manifestKey,\n object,\n projectPath,\n tenantScope: tenantScopes.get(object.className),\n }),\n )\n : entries.map(([manifestKey, object]) =>\n formatObject({\n manifestKey,\n object,\n projectPath,\n includeFields,\n includeRelationships,\n includeMethods,\n tenantScope: tenantScopes.get(object.className),\n }),\n );\n objects.sort((left, right) => left.className.localeCompare(right.className));\n\n const { kept, omitted } = applyObjectBudget(objects, maxChars);\n\n const output = {\n projectPath,\n manifestSource: manifestResult.source,\n manifestPath:\n 'path' in manifestResult\n ? relative(projectPath, manifestResult.path)\n : undefined,\n packageName:\n manifestResult.manifest.packageName ?? packageMetadata.name ?? undefined,\n packageVersion:\n manifestResult.manifest.packageVersion ??\n packageMetadata.version ??\n undefined,\n detail,\n objectCount: objects.length,\n scannedFileCount: manifestResult.scannedFileCount,\n parseTimeMs: manifestResult.parseTimeMs,\n ...(omitted > 0\n ? {\n truncated: {\n returnedObjectCount: kept.length,\n omittedObjectCount: omitted,\n budgetChars: maxChars,\n guidance:\n 'The object list hit its character budget; metadata and diagnostics are still complete. Narrow the scan with `directory` (a single package), keep `detail: \"summary\"`, or raise `maxChars` deliberately. Object names are sorted alphabetically, so omitted objects are the alphabetical tail.',\n },\n }\n : {}),\n objects: kept,\n diagnostics: manifestResult.diagnostics,\n };\n\n return JSON.stringify(output, null, 2);\n}\n\n/**\n * Trims the object list to the character budget, always keeping at least one so\n * a caller sees the shape rather than an empty list.\n */\nfunction applyObjectBudget<T>(\n objects: T[],\n maxChars: number,\n): { kept: T[]; omitted: number } {\n const kept: T[] = [];\n let used = 0;\n\n for (const object of objects) {\n const size = JSON.stringify(object, null, 2).length + 2;\n if (used + size > maxChars && kept.length > 0) break;\n used += size;\n kept.push(object);\n }\n\n return { kept, omitted: objects.length - kept.length };\n}\n\nfunction summarizeObject({\n manifestKey,\n object,\n projectPath,\n tenantScope,\n}: {\n manifestKey: string;\n object: ManifestObject;\n projectPath: string;\n tenantScope?: Record<string, unknown>;\n}) {\n const fields = Object.entries(object.fields ?? {});\n const decoratorConfig = object.decoratorConfig ?? {};\n\n return compactObject({\n manifestKey,\n className: object.className,\n qualifiedName: object.qualifiedName,\n filePath: sanitizePath(projectPath, object.filePath),\n extends: object.extends,\n collection: object.collection,\n tableName:\n object.schema?.tableName ??\n stringFromConfig(decoratorConfig.tableName) ??\n object.collection,\n tenantScope:\n tenantScope ?? normalizeTenantScopedConfig(decoratorConfig.tenantScoped),\n fieldCount: fields.length,\n relationships:\n fields\n .filter(([, field]) => RELATIONSHIP_TYPES.has(field.type))\n .map(\n ([name, field]) =>\n `${name} -> ${field.related ?? ''} (${field.type})`,\n )\n .join(', ') || undefined,\n mcpOperations: mcpOperationsFromConfig(decoratorConfig.mcp),\n });\n}\n\n/**\n * An omitted `mcp` config means full CRUD, not a closed surface — the same rule\n * the knowledge index applies.\n */\nfunction mcpOperationsFromConfig(config: unknown): string[] {\n if (config === false) return [];\n if (typeof config !== 'object' || config === null || Array.isArray(config)) {\n return [...DEFAULT_MCP_OPERATIONS];\n }\n\n const record = config as Record<string, unknown>;\n const include = Array.isArray(record.include)\n ? record.include.filter((item): item is string => typeof item === 'string')\n : DEFAULT_MCP_OPERATIONS;\n const exclude = new Set(\n Array.isArray(record.exclude)\n ? record.exclude.filter(\n (item): item is string => typeof item === 'string',\n )\n : [],\n );\n\n return include.filter((operation) => !exclude.has(operation));\n}\n\nasync function loadManifestArtifact(\n projectPath: string,\n manifestPath: string | undefined,\n): Promise<\n | {\n source: 'manifest';\n path: string;\n manifest: ManifestLike;\n diagnostics: Diagnostic[];\n scannedFileCount?: number;\n parseTimeMs?: number;\n }\n | undefined\n> {\n const candidates = manifestPath\n ? [resolve(projectPath, manifestPath)]\n : DEFAULT_MANIFEST_PATHS.map((candidate) => join(projectPath, candidate));\n\n const diagnostics: Diagnostic[] = [];\n for (const candidate of candidates) {\n if (!(await pathExists(candidate))) {\n continue;\n }\n\n try {\n const parsed = JSON.parse(await readFile(candidate, 'utf-8')) as unknown;\n if (isManifestLike(parsed)) {\n return {\n source: 'manifest',\n path: candidate,\n manifest: parsed,\n diagnostics,\n };\n }\n\n diagnostics.push({\n severity: 'warning',\n filePath: candidate,\n message: 'Manifest artifact is present but does not contain objects.',\n });\n } catch (error) {\n diagnostics.push({\n severity: 'error',\n filePath: candidate,\n message: `Unable to parse manifest artifact: ${messageFromError(error)}`,\n });\n }\n }\n\n return manifestPath\n ? {\n source: 'manifest',\n path: resolve(projectPath, manifestPath),\n manifest: { objects: {} },\n diagnostics: [\n ...diagnostics,\n {\n severity: 'warning',\n filePath: resolve(projectPath, manifestPath),\n message: 'Requested manifest artifact was not found.',\n },\n ],\n }\n : undefined;\n}\n\nasync function scanSourceManifest(\n projectPath: string,\n packageMetadata: PackageMetadata,\n): Promise<{\n source: 'scanner';\n manifest: ManifestLike;\n diagnostics: Diagnostic[];\n scannedFileCount: number;\n parseTimeMs: number;\n}> {\n const scanner = new OxcScanner({\n cwd: projectPath,\n include: ['**/*.ts', '**/*.tsx', '**/*.js', '**/*.jsx'],\n exclude: SCAN_EXCLUDE,\n });\n const { results, resolved } = await scanner.scanAndResolve();\n const adapter = new ManifestAdapter();\n const manifest = adapter.toManifest(\n resolved.filter((classDef) => classDef.hasSmartDecorator),\n {\n packageName: packageMetadata.name,\n packageVersion: packageMetadata.version,\n typeAliases: results.typeAliases,\n },\n ) as ManifestLike;\n finalizeScannerManifest(manifest, packageMetadata);\n\n return {\n source: 'scanner',\n manifest,\n diagnostics: results.errors.map(scanErrorToDiagnostic),\n scannedFileCount: results.fileCount,\n parseTimeMs: Math.round(results.totalParseTimeMs),\n };\n}\n\nfunction finalizeScannerManifest(\n manifest: ManifestLike,\n packageMetadata: PackageMetadata,\n): void {\n const manifestGen = new ManifestGenerator();\n const fullManifest = manifest as unknown as SmartObjectManifest;\n withSuppressedConsoleLog(() => {\n manifestGen.injectTenantScopedFields(fullManifest);\n manifestGen.mergeInheritedFields(fullManifest);\n manifestGen.generateValidationRules(fullManifest);\n manifestGen.generateSchemas(fullManifest);\n manifestGen.assertTenantScopedSchemaContract(fullManifest);\n manifestGen.generateAgentManifests(\n fullManifest,\n packageMetadata.name,\n packageMetadata.json,\n );\n });\n}\n\nfunction withSuppressedConsoleLog<T>(callback: () => T): T {\n const originalLog = console.log;\n console.log = () => undefined;\n try {\n return callback();\n } finally {\n console.log = originalLog;\n }\n}\n\nfunction formatObject({\n manifestKey,\n object,\n projectPath,\n includeFields,\n includeRelationships,\n includeMethods,\n tenantScope,\n}: {\n manifestKey: string;\n object: ManifestObject;\n projectPath: string;\n includeFields: boolean;\n includeRelationships: boolean;\n includeMethods: boolean;\n tenantScope?: Record<string, unknown>;\n}) {\n const fieldDetails = Object.entries(object.fields ?? {}).map(\n ([name, field]) => ({\n name,\n type: field.type,\n ...(field.required !== undefined ? { required: field.required } : {}),\n ...(field.default !== undefined ? { default: field.default } : {}),\n ...(field.related ? { related: field.related } : {}),\n ...(field.description ? { description: field.description } : {}),\n ...(field._meta ? { meta: field._meta } : {}),\n ...(field.transient !== undefined ? { transient: field.transient } : {}),\n }),\n );\n const relationshipDetails = fieldDetails\n .filter((field) => RELATIONSHIP_TYPES.has(field.type))\n .map((field) => ({\n field: field.name,\n relatedClass: field.related ?? '',\n type: field.type,\n ...(field.meta ? { meta: field.meta } : {}),\n }));\n const methodDetails = Object.entries(object.methods ?? {}).map(\n ([name, method]) => ({\n name: method.name ?? name,\n isAsync: method.async === true,\n isStatic: method.isStatic === true,\n isPublic: method.isPublic !== false,\n parameters: method.parameters ?? [],\n returnType: method.returnType ?? 'unknown',\n ...(method.description ? { description: method.description } : {}),\n }),\n );\n\n const decoratorConfig = object.decoratorConfig ?? {};\n const effectiveTenantScope =\n tenantScope ?? normalizeTenantScopedConfig(decoratorConfig.tenantScoped);\n const schema = object.schema;\n\n return compactObject({\n manifestKey,\n name: object.name,\n className: object.className,\n qualifiedName: object.qualifiedName,\n filePath: sanitizePath(projectPath, object.filePath),\n packageName: object.packageName,\n packageVersion: object.packageVersion,\n importPath: object.importPath,\n modulePath: object.modulePath,\n exportName: object.exportName,\n collectionExportName: object.collectionExportName,\n collection: object.collection,\n extends: object.extends,\n extendsTypeArg: object.extendsTypeArg,\n tableName:\n schema?.tableName ??\n stringFromConfig(decoratorConfig.tableName) ??\n object.collection,\n tableStrategy: stringFromConfig(decoratorConfig.tableStrategy) ?? 'cti',\n conflictColumns: arrayFromConfig(decoratorConfig.conflictColumns),\n tenantScope: effectiveTenantScope,\n decoratorConfig,\n schema: schema\n ? {\n tableName: schema.tableName,\n columns: schema.columns,\n indexes: schema.indexes ?? [],\n version: schema.version,\n }\n : undefined,\n indexes: schema?.indexes ?? [],\n staticProperties: object.staticProperties,\n validationRules: object.validationRules,\n ...(includeFields && {\n fields: fieldDetails\n .map((field) => `${field.name}: ${field.type}`)\n .join(', '),\n fieldDetails,\n }),\n ...(includeRelationships &&\n relationshipDetails.length > 0 && {\n relationships: relationshipDetails\n .map(\n (relationship) =>\n `${relationship.field} -> ${relationship.relatedClass} (${relationship.type})`,\n )\n .join(', '),\n relationshipDetails,\n }),\n ...(includeMethods &&\n methodDetails.length > 0 && {\n methods: methodDetails\n .map((method) => `${method.isAsync ? 'async ' : ''}${method.name}()`)\n .join(', '),\n methodDetails,\n }),\n });\n}\n\nasync function scanTenantScopes(\n projectPath: string,\n): Promise<Map<string, Record<string, unknown>>> {\n const files = await listSourceFiles(projectPath);\n const scopes = new Map<string, Record<string, unknown>>();\n\n await Promise.all(\n files.map(async (filePath) => {\n const content = await readFile(filePath, 'utf-8');\n const classMatches = content.matchAll(/class\\s+([A-Za-z_]\\w*)\\b/g);\n for (const match of classMatches) {\n const className = match[1];\n if (!className || match.index === undefined) continue;\n const prefix = content.slice(\n Math.max(0, match.index - 800),\n match.index,\n );\n const tenantMatches = Array.from(\n prefix.matchAll(/@TenantScoped\\s*\\(([\\s\\S]*?)\\)/g),\n );\n const tenantMatch = tenantMatches.at(-1);\n if (!tenantMatch) continue;\n scopes.set(className, {\n source: 'TenantScoped',\n ...parseTenantScopedOptions(tenantMatch[1]),\n });\n }\n }),\n );\n\n return scopes;\n}\n\nasync function listSourceFiles(projectPath: string): Promise<string[]> {\n const files: string[] = [];\n\n async function visit(dir: string): Promise<void> {\n let entries: Dirent[];\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n const fullPath = join(dir, entry.name);\n if (entry.isDirectory()) {\n if (\n [\n 'node_modules',\n 'dist',\n 'build',\n '.git',\n '.smrt',\n '__tests__',\n ].includes(entry.name) ||\n entry.name.startsWith('.')\n ) {\n continue;\n }\n await visit(fullPath);\n continue;\n }\n\n if (\n entry.isFile() &&\n /\\.(tsx?|jsx?)$/.test(entry.name) &&\n !entry.name.endsWith('.d.ts') &&\n !entry.name.endsWith('.test.ts') &&\n !entry.name.endsWith('.spec.ts')\n ) {\n files.push(fullPath);\n }\n }\n }\n\n await visit(projectPath);\n return files;\n}\n\nfunction parseTenantScopedOptions(raw: string): Record<string, unknown> {\n const mode = raw.match(/mode\\s*:\\s*['\"`](required|optional)['\"`]/)?.[1];\n const field = raw.match(/field\\s*:\\s*['\"`]([A-Za-z_]\\w*)['\"`]/)?.[1];\n const allowSuperAdminBypass = raw.match(\n /allowSuperAdminBypass\\s*:\\s*(true|false)/,\n )?.[1];\n const autoFilter = raw.match(/autoFilter\\s*:\\s*(true|false)/)?.[1];\n const autoPopulate = raw.match(/autoPopulate\\s*:\\s*(true|false)/)?.[1];\n\n return compactObject({\n mode: mode ?? 'required',\n field: field ?? 'tenantId',\n autoFilter: autoFilter === undefined ? undefined : autoFilter === 'true',\n autoPopulate:\n autoPopulate === undefined ? undefined : autoPopulate === 'true',\n allowSuperAdminBypass:\n allowSuperAdminBypass === undefined\n ? undefined\n : allowSuperAdminBypass === 'true',\n });\n}\n\nfunction normalizeTenantScopedConfig(\n tenantScoped: unknown,\n): Record<string, unknown> | undefined {\n if (!tenantScoped) return undefined;\n const options =\n typeof tenantScoped === 'object' && !Array.isArray(tenantScoped)\n ? (tenantScoped as Record<string, unknown>)\n : {};\n return {\n source: 'smrt',\n mode: options.mode ?? 'required',\n field: options.field ?? 'tenantId',\n autoFilter: options.autoFilter ?? true,\n autoPopulate: options.autoPopulate ?? true,\n allowSuperAdminBypass: options.allowSuperAdminBypass ?? false,\n };\n}\n\nasync function readPackageMetadata(\n projectPath: string,\n): Promise<PackageMetadata> {\n const packageJsonPath = join(projectPath, 'package.json');\n if (!(await pathExists(packageJsonPath))) return {};\n\n try {\n const json = JSON.parse(await readFile(packageJsonPath, 'utf-8')) as Record<\n string,\n unknown\n >;\n return {\n name: typeof json.name === 'string' ? json.name : undefined,\n version: typeof json.version === 'string' ? json.version : undefined,\n json,\n };\n } catch {\n return {};\n }\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction isManifestLike(value: unknown): value is ManifestLike {\n return (\n !!value &&\n typeof value === 'object' &&\n !!(value as ManifestLike).objects &&\n typeof (value as ManifestLike).objects === 'object'\n );\n}\n\nfunction scanErrorToDiagnostic(error: ScanError): Diagnostic {\n return {\n severity: error.severity,\n message: error.message,\n filePath: error.filePath,\n line: error.line,\n column: error.column,\n };\n}\n\nfunction sanitizePath(projectPath: string, filePath: string): string {\n const absolute = isAbsolute(filePath)\n ? filePath\n : resolve(projectPath, filePath);\n const relativePath = relative(projectPath, absolute);\n if (!relativePath.startsWith('..')) {\n return relativePath || filePath;\n }\n return filePath;\n}\n\nfunction stringFromConfig(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\nfunction arrayFromConfig(value: unknown): string[] | undefined {\n return Array.isArray(value)\n ? value.filter((item): item is string => typeof item === 'string')\n : undefined;\n}\n\nfunction compactObject<T extends Record<string, unknown>>(value: T): T {\n return Object.fromEntries(\n Object.entries(value).filter(([, entry]) => entry !== undefined),\n ) as T;\n}\n\nfunction messageFromError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * Ecosystem-aware downstream project review.\n * Advisory only: scans manifests and source files, then reports alignment risks.\n */\n\nimport { type Dirent, existsSync } from 'node:fs';\nimport { access, readdir, readFile } from 'node:fs/promises';\nimport { dirname, join, relative, resolve, sep } from 'node:path';\n\ninterface ReviewSmrtProjectArgs {\n directory?: string;\n rootDir?: string;\n includeSourceEvidence?: boolean;\n maxFindings?: number;\n}\n\ntype Severity = 'high' | 'medium' | 'low';\n\ninterface Evidence {\n filePath: string;\n line?: number;\n detail: string;\n}\n\ninterface Finding {\n severity: Severity;\n area:\n | 'dependencies'\n | 'storage'\n | 'api-shell'\n | 'manifest'\n | 'auth-tenancy'\n | 'ui-shell';\n code: string;\n title: string;\n evidence: Evidence[];\n recommendation: string;\n suggestedIssueTitle: string;\n}\n\ninterface PackageInventory {\n name: string;\n path: string;\n private?: boolean;\n scripts: string[];\n declaredHappyVerticalDependencies: string[];\n importedHappyVerticalPackages: string[];\n missingHappyVerticalDependencies: string[];\n hasSvelteKit: boolean;\n hasSmrtSvelte: boolean;\n}\n\ninterface PackageContext {\n directory: string;\n relativePath: string;\n packageJsonPath: string;\n json: Record<string, unknown>;\n dependencies: Set<string>;\n scripts: Record<string, unknown>;\n imports: Map<string, Evidence[]>;\n sourceFiles: SourceFile[];\n}\n\ninterface SourceFile {\n path: string;\n packageDir: string;\n content: string;\n}\n\nconst SOURCE_EXTENSIONS = /\\.(tsx?|jsx?|svelte)$/;\nconst SKIP_DIRS = new Set([\n 'node_modules',\n 'dist',\n 'build',\n '.git',\n '.smrt',\n '.svelte-kit',\n 'coverage',\n]);\nconst DEPENDENCY_SECTIONS = [\n 'dependencies',\n 'devDependencies',\n 'peerDependencies',\n 'optionalDependencies',\n];\nconst SMRT_PACKAGE_PREFIX = '@happyvertical/smrt-';\nconst HAPPYVERTICAL_PACKAGE_PREFIX = '@happyvertical/';\n\nexport async function reviewSmrtProject(\n args: ReviewSmrtProjectArgs,\n): Promise<string> {\n const projectPath = resolve(args.directory ?? args.rootDir ?? process.cwd());\n if (!(await pathExists(projectPath))) {\n return JSON.stringify(\n {\n projectPath,\n packageCount: 0,\n packages: [],\n findings: [],\n summary: { high: 0, medium: 0, low: 0 },\n diagnostics: [\n {\n severity: 'warning',\n message: `Project directory does not exist: ${projectPath}`,\n },\n ],\n },\n null,\n 2,\n );\n }\n\n const packageContexts = await buildPackageContexts(projectPath);\n const sourceFiles = await listSourceFiles(projectPath, packageContexts);\n await attachSourceFiles(sourceFiles, packageContexts, projectPath);\n\n const findings = limitFindings(\n [\n ...findMissingHappyVerticalDependencies(packageContexts),\n ...findCustomManifestGeneration(sourceFiles, projectPath),\n ...findDirectStorageBypasses(sourceFiles, packageContexts, projectPath),\n ...findCustomHttpShells(sourceFiles, packageContexts, projectPath),\n ...findLocalAuthTenancy(sourceFiles, packageContexts, projectPath),\n ...findUiShellDrift(packageContexts, projectPath),\n ...findMissingManifestArtifacts(\n sourceFiles,\n packageContexts,\n projectPath,\n ),\n ],\n args.maxFindings,\n );\n\n const packages = packageContexts\n .map(packageInventory)\n .sort((left, right) => left.path.localeCompare(right.path));\n const summary = summarizeFindings(findings);\n\n return JSON.stringify(\n {\n projectPath,\n packageCount: packages.length,\n packages,\n findings:\n args.includeSourceEvidence === false\n ? findings.map(({ evidence: _evidence, ...finding }) => finding)\n : findings,\n summary,\n referenceChecks: [\n 'Prefer SMRT scanner/runtime manifests over custom manifest builders.',\n 'Prefer SvelteKit plus @happyvertical/smrt-svelte for app shells.',\n 'Prefer @happyvertical/sql and @happyvertical/files/assets/content over direct durable node:fs storage.',\n 'Prefer smrt-users, smrt-tenancy, and profile/audit packages over local static auth seams.',\n ],\n suggestedFollowUpIssues: findings.map((finding) => ({\n title: finding.suggestedIssueTitle,\n severity: finding.severity,\n area: finding.area,\n })),\n },\n null,\n 2,\n );\n}\n\nasync function buildPackageContexts(\n projectPath: string,\n): Promise<PackageContext[]> {\n const packageJsonPaths = await listPackageJsonFiles(projectPath);\n const contexts = await Promise.all(\n packageJsonPaths.map(async (packageJsonPath) => {\n const json = JSON.parse(\n await readFile(packageJsonPath, 'utf-8'),\n ) as Record<string, unknown>;\n const directory = dirname(packageJsonPath);\n return {\n directory,\n relativePath: relative(projectPath, directory) || '.',\n packageJsonPath,\n json,\n dependencies: collectDependencies(json),\n scripts: isRecord(json.scripts)\n ? (json.scripts as Record<string, unknown>)\n : {},\n imports: new Map<string, Evidence[]>(),\n sourceFiles: [],\n };\n }),\n );\n\n if (contexts.length === 0) {\n contexts.push({\n directory: projectPath,\n relativePath: '.',\n packageJsonPath: join(projectPath, 'package.json'),\n json: {},\n dependencies: new Set(),\n scripts: {},\n imports: new Map(),\n sourceFiles: [],\n });\n }\n\n return contexts.sort(\n (left, right) => left.directory.length - right.directory.length,\n );\n}\n\nasync function listPackageJsonFiles(projectPath: string): Promise<string[]> {\n const files: string[] = [];\n await visit(projectPath, async (filePath, entryName) => {\n if (entryName === 'package.json') files.push(filePath);\n });\n return files;\n}\n\nasync function listSourceFiles(\n projectPath: string,\n packages: PackageContext[],\n): Promise<SourceFile[]> {\n const files: SourceFile[] = [];\n await visit(projectPath, async (filePath, entryName) => {\n if (!SOURCE_EXTENSIONS.test(entryName)) return;\n if (\n entryName.endsWith('.d.ts') ||\n entryName.endsWith('.test.ts') ||\n entryName.endsWith('.spec.ts')\n ) {\n return;\n }\n\n const packageDir = findOwningPackage(filePath, packages).directory;\n const content = await readFile(filePath, 'utf-8');\n files.push({ path: filePath, packageDir, content });\n });\n return files;\n}\n\nasync function attachSourceFiles(\n sourceFiles: SourceFile[],\n packages: PackageContext[],\n projectPath: string,\n): Promise<void> {\n for (const sourceFile of sourceFiles) {\n const owner = packages.find(\n (pkg) => pkg.directory === sourceFile.packageDir,\n );\n if (!owner) continue;\n owner.sourceFiles.push(sourceFile);\n for (const importedPackage of extractImports(sourceFile.content)) {\n if (!importedPackage.startsWith(HAPPYVERTICAL_PACKAGE_PREFIX)) continue;\n const evidence = {\n filePath: relative(projectPath, sourceFile.path),\n line: lineNumber(sourceFile.content, importedPackage),\n detail: `Imports ${importedPackage}`,\n };\n const existing = owner.imports.get(importedPackage) ?? [];\n existing.push(evidence);\n owner.imports.set(importedPackage, existing);\n }\n }\n}\n\nfunction findMissingHappyVerticalDependencies(\n packages: PackageContext[],\n): Finding[] {\n return packages.flatMap((pkg) => {\n const ownName =\n typeof pkg.json.name === 'string' ? pkg.json.name : undefined;\n const missing = Array.from(pkg.imports.keys()).filter(\n (importedPackage) =>\n importedPackage !== ownName && !pkg.dependencies.has(importedPackage),\n );\n if (missing.length === 0) return [];\n\n const hasSmrtMissing = missing.some((name) =>\n name.startsWith(SMRT_PACKAGE_PREFIX),\n );\n return [\n {\n severity: hasSmrtMissing ? 'high' : 'medium',\n area: 'dependencies',\n code: 'missing-happyvertical-dependencies',\n title: `${packageLabel(pkg)} imports HappyVertical packages that package.json does not declare`,\n evidence: missing.flatMap((name) => pkg.imports.get(name) ?? []),\n recommendation:\n 'Declare every imported @happyvertical package in the owning package manifest so downstream installs and generated knowledge stay reproducible.',\n suggestedIssueTitle: `Declare missing HappyVertical dependencies in ${packageLabel(pkg)}`,\n },\n ];\n });\n}\n\nfunction findCustomManifestGeneration(\n sourceFiles: SourceFile[],\n projectPath: string,\n): Finding[] {\n return sourceFiles\n .filter(\n (file) =>\n /manifest\\.json/.test(file.content) &&\n /objects\\s*:/.test(file.content) &&\n /\\b(writeFile|writeFileSync)\\b/.test(file.content) &&\n !/@happyvertical\\/smrt-scanner/.test(file.content),\n )\n .map((file) => ({\n severity: 'high',\n area: 'manifest',\n code: 'custom-object-manifest-generation',\n title: 'Custom SMRT object manifest generation detected',\n evidence: [\n {\n filePath: relative(projectPath, file.path),\n line: lineNumber(file.content, 'manifest.json'),\n detail:\n 'Writes a manifest.json object inventory outside the SMRT scanner/runtime path.',\n },\n ],\n recommendation:\n 'Use the SMRT scanner/runtime manifest path so defaults, relationships, schemas, tenant fields, and cross-package references match framework behavior.',\n suggestedIssueTitle:\n 'Replace custom object manifest generation with SMRT scanner/runtime manifest generation',\n }));\n}\n\nfunction findDirectStorageBypasses(\n sourceFiles: SourceFile[],\n packages: PackageContext[],\n projectPath: string,\n): Finding[] {\n return sourceFiles.flatMap((file) => {\n const owner = findOwningPackage(file.path, packages);\n const usesFs =\n /from\\s+['\"](?:node:fs|node:fs\\/promises|fs|fs\\/promises)['\"]|require\\(['\"](?:node:fs|node:fs\\/promises|fs|fs\\/promises)['\"]\\)/.test(\n file.content,\n );\n const writesDurableData =\n /\\b(writeFile|appendFile|mkdir|rm|rename)\\b/.test(file.content) &&\n /(\\.json|data|storage|persist|cache|db)/i.test(file.content);\n const usesDirectSql =\n /from\\s+['\"](?:better-sqlite3|sqlite3|pg|mysql2?|knex|drizzle-orm)['\"]/.test(\n file.content,\n );\n if ((!usesFs || !writesDurableData) && !usesDirectSql) return [];\n\n const hasApprovedStorage =\n owner.dependencies.has('@happyvertical/sql') ||\n owner.dependencies.has('@happyvertical/files') ||\n owner.dependencies.has('@happyvertical/smrt-assets') ||\n owner.dependencies.has('@happyvertical/smrt-content');\n\n if (hasApprovedStorage) return [];\n\n return [\n {\n severity: 'medium',\n area: 'storage',\n code: 'direct-storage-bypass',\n title: `${packageLabel(owner)} appears to bypass HappyVertical storage packages`,\n evidence: [\n {\n filePath: relative(projectPath, file.path),\n line: lineNumber(\n file.content,\n usesDirectSql ? 'sqlite' : 'writeFile',\n ),\n detail: usesDirectSql\n ? 'Imports a direct SQL/storage library without @happyvertical/sql.'\n : 'Uses node:fs-style durable writes without @happyvertical/files/assets/content.',\n },\n ],\n recommendation:\n 'Route durable data through @happyvertical/sql, @happyvertical/files, SMRT assets, or SMRT content unless this is explicitly build-only tooling.',\n suggestedIssueTitle: `Review direct storage usage in ${packageLabel(owner)}`,\n },\n ];\n });\n}\n\nfunction findCustomHttpShells(\n sourceFiles: SourceFile[],\n packages: PackageContext[],\n projectPath: string,\n): Finding[] {\n const evidenceByPackage = new Map<PackageContext, Evidence[]>();\n\n for (const pkg of packages) {\n if (pkg.dependencies.has('@sveltejs/kit')) continue;\n\n const routerDependencies = ['express', 'fastify', 'hono', 'koa'].filter(\n (dep) => pkg.dependencies.has(dep),\n );\n if (routerDependencies.length === 0) continue;\n\n appendEvidence(evidenceByPackage, pkg, {\n filePath: relative(projectPath, pkg.packageJsonPath),\n detail: `Declares custom router package(s): ${routerDependencies.join(', ')}.`,\n });\n }\n\n for (const file of sourceFiles) {\n const owner = findOwningPackage(file.path, packages);\n if (owner.dependencies.has('@sveltejs/kit')) continue;\n\n const usesNodeHttp =\n /from\\s+['\"](?:node:http|http|node:https|https)['\"]|createServer\\s*\\(/.test(\n file.content,\n );\n if (!usesNodeHttp) continue;\n\n appendEvidence(evidenceByPackage, owner, {\n filePath: relative(projectPath, file.path),\n line: lineNumber(file.content, 'createServer'),\n detail:\n 'Custom HTTP routing found without the SvelteKit/SMRT app-shell dependency pattern.',\n });\n }\n\n return Array.from(evidenceByPackage.entries()).map(([owner, evidence]) => ({\n severity: 'medium',\n area: 'api-shell',\n code: 'custom-http-shell',\n title: `${packageLabel(owner)} uses a custom HTTP shell`,\n evidence,\n recommendation:\n 'Compare the app shell against the Anytown/Ergot SvelteKit + SMRT shell pattern before adding custom HTTP infrastructure.',\n suggestedIssueTitle: `Align ${packageLabel(owner)} app shell with SMRT/SvelteKit conventions`,\n }));\n}\n\nfunction appendEvidence(\n evidenceByPackage: Map<PackageContext, Evidence[]>,\n pkg: PackageContext,\n evidence: Evidence,\n): void {\n const existing = evidenceByPackage.get(pkg);\n if (existing) {\n existing.push(evidence);\n return;\n }\n\n evidenceByPackage.set(pkg, [evidence]);\n}\n\nfunction findLocalAuthTenancy(\n sourceFiles: SourceFile[],\n packages: PackageContext[],\n projectPath: string,\n): Finding[] {\n return sourceFiles.flatMap((file) => {\n const owner = findOwningPackage(file.path, packages);\n const pathSignal = /(auth|tenant|audit|session|rbac|user)/i.test(file.path);\n const codeSignal =\n /\\b(tenantId|tenant|role|permission|session|auditLog|apiKey)\\b/.test(\n file.content,\n );\n if (!pathSignal || !codeSignal) return [];\n\n const hasApprovedPackages =\n owner.dependencies.has('@happyvertical/smrt-users') ||\n owner.dependencies.has('@happyvertical/smrt-tenancy') ||\n owner.dependencies.has('@happyvertical/smrt-profiles');\n if (hasApprovedPackages) return [];\n\n return [\n {\n severity: 'medium',\n area: 'auth-tenancy',\n code: 'local-auth-tenancy',\n title: `${packageLabel(owner)} contains local auth/tenancy/audit logic`,\n evidence: [\n {\n filePath: relative(projectPath, file.path),\n line: lineNumber(file.content, 'tenant'),\n detail:\n 'Auth, tenancy, session, role, or audit terminology appears without smrt-users/smrt-tenancy/smrt-profiles dependencies.',\n },\n ],\n recommendation:\n 'Add explicit adapters to smrt-users, smrt-tenancy, and profile/audit models or document why this local implementation is intentionally isolated.',\n suggestedIssueTitle: `Review auth and tenancy adapters in ${packageLabel(owner)}`,\n },\n ];\n });\n}\n\nfunction findUiShellDrift(\n packages: PackageContext[],\n projectPath: string,\n): Finding[] {\n return packages.flatMap((pkg) => {\n const hasUiSource = pkg.sourceFiles.some((file) =>\n file.path.endsWith('.svelte'),\n );\n const likelyUiPackage =\n hasUiSource ||\n /(?:web|ui|app|site|frontend)/i.test(packageLabel(pkg)) ||\n pkg.dependencies.has('svelte') ||\n pkg.dependencies.has('vite');\n if (!likelyUiPackage) return [];\n if (pkg.dependencies.has('@happyvertical/smrt-svelte')) return [];\n\n return [\n {\n severity: 'low',\n area: 'ui-shell',\n code: 'missing-smrt-svelte-shell',\n title: `${packageLabel(pkg)} looks like UI work without @happyvertical/smrt-svelte`,\n evidence: [\n {\n filePath: relative(projectPath, pkg.packageJsonPath),\n detail:\n 'UI-facing package does not declare @happyvertical/smrt-svelte.',\n },\n ],\n recommendation:\n 'Use @happyvertical/smrt-svelte and the SvelteKit shell pattern for downstream app UI unless this package is intentionally framework-agnostic.',\n suggestedIssueTitle: `Check SMRT Svelte shell alignment for ${packageLabel(pkg)}`,\n },\n ];\n });\n}\n\nfunction findMissingManifestArtifacts(\n sourceFiles: SourceFile[],\n packages: PackageContext[],\n projectPath: string,\n): Finding[] {\n return packages.flatMap((pkg) => {\n const hasSmrtSource = pkg.sourceFiles.some((file) =>\n /@smrt\\s*\\(/.test(file.content),\n );\n if (!hasSmrtSource) return [];\n const hasManifest =\n sourceFiles.some(\n (file) =>\n file.packageDir === pkg.directory &&\n /@happyvertical\\/smrt-scanner/.test(file.content),\n ) ||\n pathExistsSyncHint(join(pkg.directory, '.smrt', 'manifest.json')) ||\n pathExistsSyncHint(join(pkg.directory, 'dist', 'manifest.json'));\n if (hasManifest) return [];\n\n return [\n {\n severity: 'low',\n area: 'manifest',\n code: 'missing-generated-manifest-artifact',\n title: `${packageLabel(pkg)} has @smrt objects but no generated manifest artifact was found`,\n evidence: [\n {\n filePath: relative(projectPath, pkg.packageJsonPath),\n detail:\n 'No .smrt/manifest.json or dist/manifest.json was visible during review.',\n },\n ],\n recommendation:\n 'Run the package build/test manifest generation path and verify it uses the SMRT scanner/runtime manifest pipeline.',\n suggestedIssueTitle: `Verify SMRT manifest generation for ${packageLabel(pkg)}`,\n },\n ];\n });\n}\n\nasync function visit(\n dir: string,\n onFile: (filePath: string, entryName: string) => Promise<void> | void,\n): Promise<void> {\n let entries: Dirent[];\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n const fullPath = join(dir, entry.name);\n if (entry.isDirectory()) {\n if (SKIP_DIRS.has(entry.name)) continue;\n await visit(fullPath, onFile);\n continue;\n }\n if (entry.isFile()) await onFile(fullPath, entry.name);\n }\n}\n\nfunction collectDependencies(\n packageJson: Record<string, unknown>,\n): Set<string> {\n const dependencies = new Set<string>();\n for (const sectionName of DEPENDENCY_SECTIONS) {\n const section = packageJson[sectionName];\n if (!isRecord(section)) continue;\n for (const dependencyName of Object.keys(section)) {\n dependencies.add(dependencyName);\n }\n }\n return dependencies;\n}\n\nfunction extractImports(content: string): string[] {\n const imports = new Set<string>();\n const patterns = [\n /(?:import|export)\\s+(?:type\\s+)?(?:[^'\"]+\\s+from\\s+)?['\"]([^'\"]+)['\"]/g,\n /\\bimport\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g,\n /\\brequire\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g,\n ];\n for (const pattern of patterns) {\n for (const match of content.matchAll(pattern)) {\n const imported = normalizePackageImport(match[1]);\n if (imported) imports.add(imported);\n }\n }\n return Array.from(imports);\n}\n\nfunction normalizePackageImport(value: string | undefined): string | undefined {\n if (!value || value.startsWith('.') || value.startsWith('/'))\n return undefined;\n if (value.startsWith('@')) {\n const [scope, name] = value.split('/');\n return scope && name ? `${scope}/${name}` : value;\n }\n return value.split('/')[0];\n}\n\nfunction findOwningPackage(\n filePath: string,\n packages: PackageContext[],\n): PackageContext {\n const normalized = resolve(filePath);\n const matches = packages\n .filter(\n (pkg) =>\n normalized === pkg.directory ||\n normalized.startsWith(`${pkg.directory}${sep}`),\n )\n .sort((left, right) => right.directory.length - left.directory.length);\n return matches[0] ?? packages[0];\n}\n\nfunction packageInventory(pkg: PackageContext): PackageInventory {\n const declaredHappyVerticalDependencies = Array.from(pkg.dependencies)\n .filter((dependency) => dependency.startsWith(HAPPYVERTICAL_PACKAGE_PREFIX))\n .sort();\n const importedHappyVerticalPackages = Array.from(pkg.imports.keys()).sort();\n const ownName = typeof pkg.json.name === 'string' ? pkg.json.name : undefined;\n return {\n name: packageLabel(pkg),\n path: pkg.relativePath,\n private:\n typeof pkg.json.private === 'boolean' ? pkg.json.private : undefined,\n scripts: Object.keys(pkg.scripts).sort(),\n declaredHappyVerticalDependencies,\n importedHappyVerticalPackages,\n missingHappyVerticalDependencies: importedHappyVerticalPackages.filter(\n (name) => name !== ownName && !pkg.dependencies.has(name),\n ),\n hasSvelteKit: pkg.dependencies.has('@sveltejs/kit'),\n hasSmrtSvelte: pkg.dependencies.has('@happyvertical/smrt-svelte'),\n };\n}\n\nfunction summarizeFindings(findings: Finding[]): Record<Severity, number> {\n return findings.reduce(\n (summary, finding) => {\n summary[finding.severity]++;\n return summary;\n },\n { high: 0, medium: 0, low: 0 },\n );\n}\n\nfunction limitFindings(\n findings: Finding[],\n maxFindings: number | undefined,\n): Finding[] {\n const sorted = findings.sort(\n (left, right) =>\n severityRank(left.severity) - severityRank(right.severity) ||\n left.area.localeCompare(right.area) ||\n left.title.localeCompare(right.title),\n );\n return maxFindings && maxFindings > 0 ? sorted.slice(0, maxFindings) : sorted;\n}\n\nfunction severityRank(severity: Severity): number {\n return severity === 'high' ? 0 : severity === 'medium' ? 1 : 2;\n}\n\nfunction packageLabel(pkg: PackageContext): string {\n return typeof pkg.json.name === 'string' ? pkg.json.name : pkg.relativePath;\n}\n\nfunction lineNumber(content: string, needle: string): number | undefined {\n const index = content.indexOf(needle);\n if (index < 0) return undefined;\n return content.slice(0, index).split('\\n').length;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value);\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction pathExistsSyncHint(path: string): boolean {\n return existsSync(path);\n}\n","/**\n * SMRT Development MCP Server\n * Provides code generation, project introspection, knowledge context,\n * review/architecture prompt bundles, and portable agent skills.\n */\n\nimport { readFileSync, realpathSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport {\n ProtocolError,\n ProtocolErrorCode,\n Server,\n type Tool,\n} from '@modelcontextprotocol/server';\nimport { serveStdio } from '@modelcontextprotocol/server/stdio';\n\nimport { getAgentSkill, listAgentSkills } from './agent-skills.js';\nimport {\n buildArchitectureContext,\n buildKnowledgeIndex,\n buildReviewContext,\n checkKnowledgeFreshness,\n checkKnowledgeFreshnessFromIndex,\n packageDocPaths,\n smrtArchitecture,\n smrtReview,\n} from './knowledge/index.js';\nimport {\n generateSmrtClass,\n introspectProject,\n reviewSmrtProject,\n} from './tools/index.js';\n\nconst SERVER_NAME = 'smrt-dev-mcp';\nexport const SERVER_VERSION = readPackageVersion();\nconst DEBUG = process.env.DEBUG === 'true';\nconst REVIEW_SKILL_NAME = 'smrt-code-review';\nconst REVIEW_SKILL_URI = `smrt-dev-mcp://agent-skills/${REVIEW_SKILL_NAME}`;\nconst DOMAIN_CODE_REVIEW_PROMPT = 'domain-code-review';\nconst DOMAIN_ARCHITECTURE_PROMPT = 'domain-architecture';\nconst KNOWLEDGE_PROJECT_URI = 'smrt://knowledge/project';\nconst KNOWLEDGE_PACKAGE_PREFIX = 'smrt://knowledge/package/';\nconst DEPLOY_STATIC_CATALOG_CACHE_HINT = {\n ttlMs: 86_400_000,\n cacheScope: 'private' as const,\n};\n// Knowledge resources are rebuilt from the workspace on every request. There\n// is no transport-visible project-graph invalidation signal, so a nonzero TTL\n// would promise stale data could not be served after an edit.\nconst LIVE_KNOWLEDGE_CACHE_HINT = {\n ttlMs: 0,\n cacheScope: 'private' as const,\n};\n\ntype KnowledgeIndexResult = Awaited<ReturnType<typeof buildKnowledgeIndex>>;\ntype KnowledgePackageResult = KnowledgeIndexResult['packages'][number];\ntype PromptArguments = Record<string, string> | undefined;\n\nconst JSON_SCHEMA_2020_12 = 'https://json-schema.org/draft/2020-12/schema';\n\nfunction compareToolNames(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0;\n}\n\n/**\n * Stable success/error envelope for development tools. `data` preserves each\n * tool's existing payload exactly; coverage/diagnostics are promoted only when\n * the underlying result actually reports them.\n */\nconst DEV_MCP_OUTPUT_SCHEMA: NonNullable<Tool['outputSchema']> = {\n $schema: JSON_SCHEMA_2020_12,\n type: 'object',\n additionalProperties: false,\n required: ['ok', 'coverage', 'diagnostics', 'data'],\n properties: {\n ok: { type: 'boolean' },\n coverage: { type: ['object', 'null'], additionalProperties: true },\n diagnostics: {\n type: 'array',\n items: { type: 'object', additionalProperties: true },\n },\n data: {},\n },\n};\n\n// Tool definitions\nconst TOOL_DEFINITIONS: Array<\n Pick<Tool, 'name' | 'description' | 'inputSchema'>\n> = [\n // Code Generation Tools\n {\n name: 'generate-smrt-class',\n description: 'Generate a complete SMRT class with @smrt() decorator',\n inputSchema: {\n type: 'object',\n properties: {\n className: {\n type: 'string',\n description: 'Name of the class (PascalCase)',\n },\n properties: {\n type: 'array',\n description: 'Array of property definitions',\n items: {\n type: 'object',\n properties: {\n name: { type: 'string' },\n type: {\n type: 'string',\n enum: [\n 'text',\n 'integer',\n 'decimal',\n 'boolean',\n 'datetime',\n 'json',\n ],\n },\n required: { type: 'boolean' },\n nullable: { type: 'boolean' },\n description: { type: 'string' },\n defaultValue: {\n oneOf: [\n { type: 'string' },\n { type: 'number' },\n { type: 'boolean' },\n { type: 'object' },\n { type: 'null' },\n ],\n },\n },\n required: ['name', 'type'],\n },\n },\n baseClass: {\n type: 'string',\n enum: ['SmrtObject', 'SmrtCollection'],\n default: 'SmrtObject',\n },\n template: {\n type: 'string',\n enum: [\n 'basic',\n 'global-catalog',\n 'optional-catalog',\n 'tenant-project-object',\n 'tenant-event-log-object',\n 'cross-package-reference',\n ],\n default: 'basic',\n },\n tableName: { type: 'string' },\n conflictColumns: {\n type: 'array',\n items: { type: 'string' },\n },\n tenantScoped: {\n oneOf: [\n { type: 'boolean' },\n {\n type: 'object',\n properties: {\n mode: { type: 'string', enum: ['required', 'optional'] },\n field: { type: 'string' },\n autoFilter: { type: 'boolean' },\n autoPopulate: { type: 'boolean' },\n allowSuperAdminBypass: { type: 'boolean' },\n },\n },\n ],\n },\n includeTenantIdField: { type: 'boolean' },\n relationships: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n name: { type: 'string' },\n type: {\n type: 'string',\n enum: [\n 'foreignKey',\n 'crossPackageRef',\n 'oneToMany',\n 'manyToMany',\n ],\n },\n related: { type: 'string' },\n required: { type: 'boolean' },\n nullable: { type: 'boolean' },\n description: { type: 'string' },\n validate: { type: 'boolean' },\n foreignKey: { type: 'string' },\n through: { type: 'string' },\n sourceKey: { type: 'string' },\n targetKey: { type: 'string' },\n },\n required: ['name', 'type', 'related'],\n },\n },\n includeCompanionSnippets: { type: 'boolean', default: false },\n includeApiConfig: { type: 'boolean', default: true },\n includeMcpConfig: { type: 'boolean', default: true },\n includeCliConfig: { type: 'boolean', default: true },\n },\n required: ['className', 'properties'],\n },\n },\n // Project Introspection Tools\n {\n name: 'introspect-project',\n description:\n 'Scan a directory for SMRT objects. Returns a compact summary by default; pass detail: \"full\" for field, schema, and method details.',\n inputSchema: {\n type: 'object',\n properties: {\n directory: {\n type: 'string',\n description: 'Project directory (default: cwd)',\n },\n manifestPath: {\n type: 'string',\n description:\n 'Optional manifest path. Defaults to .smrt/manifest.json, dist/manifest.json, then source scanning.',\n },\n detail: {\n type: 'string',\n enum: ['summary', 'full'],\n default: 'summary',\n description:\n 'summary: one compact record per object. full: complete field/schema/method detail (large).',\n },\n maxChars: {\n type: 'number',\n description:\n 'Character budget for the `objects` payload. Objects past the budget are omitted and reported under `truncated`. Project metadata and diagnostics are always returned in full, so the serialized response is somewhat larger than this budget.',\n },\n includeFields: {\n type: 'boolean',\n description: 'Include field details (detail: \"full\" only)',\n },\n includeRelationships: {\n type: 'boolean',\n description: 'Analyze relationships (detail: \"full\" only)',\n },\n includeMethods: {\n type: 'boolean',\n description: 'Include public method details (detail: \"full\" only)',\n },\n },\n },\n },\n {\n name: 'review-smrt-project',\n description:\n 'Advisory ecosystem alignment review for downstream SMRT projects',\n inputSchema: {\n type: 'object',\n properties: {\n directory: {\n type: 'string',\n description: 'Project directory (default: cwd)',\n },\n rootDir: {\n type: 'string',\n description: 'Compatibility alias for directory',\n },\n includeSourceEvidence: {\n type: 'boolean',\n description: 'Include file and line evidence in findings',\n default: true,\n },\n maxFindings: {\n type: 'number',\n description: 'Optional maximum number of findings to return',\n },\n },\n },\n },\n {\n name: 'reflect-knowledge',\n description:\n 'Report deterministic SMRT + HappyVertical SDK knowledge coverage and freshness',\n inputSchema: {\n type: 'object',\n properties: {\n rootDir: {\n type: 'string',\n description: 'Project root directory (default: cwd)',\n },\n },\n },\n },\n {\n name: 'reflect-domain-knowledge',\n description:\n 'Report domain-scoped SMRT knowledge artifacts, SDK packages, and freshness',\n inputSchema: {\n type: 'object',\n properties: {\n rootDir: { type: 'string' },\n scope: {\n type: 'string',\n enum: ['project', 'local', 'package', 'sdk'],\n default: 'project',\n },\n package: { type: 'string' },\n },\n },\n },\n {\n name: 'check-knowledge-freshness',\n description: 'Run deterministic freshness checks for SMRT agent knowledge',\n inputSchema: {\n type: 'object',\n properties: {\n rootDir: { type: 'string' },\n changed: {\n type: 'boolean',\n description: 'Limit stale-pattern checks to changed files',\n },\n strict: {\n type: 'boolean',\n description: 'Treat stale-pattern findings as errors',\n },\n },\n },\n },\n {\n name: 'check-domain-knowledge',\n description:\n 'Run deterministic freshness checks for domain knowledge artifacts',\n inputSchema: {\n type: 'object',\n properties: {\n rootDir: { type: 'string' },\n changed: { type: 'boolean' },\n strict: { type: 'boolean' },\n scope: {\n type: 'string',\n enum: ['project', 'local', 'package', 'sdk'],\n default: 'project',\n },\n package: { type: 'string' },\n },\n },\n },\n {\n name: 'build-review-context',\n description:\n 'Build model-ready SMRT review context from changed files and optional focus text',\n inputSchema: {\n type: 'object',\n properties: {\n rootDir: { type: 'string' },\n changedFiles: { type: 'array', items: { type: 'string' } },\n focus: { type: 'string' },\n documentation: { type: 'string' },\n detail: {\n type: 'string',\n enum: ['summary', 'full'],\n default: 'summary',\n description:\n 'summary: authored package docs are listed by path to stay inside tool-result budgets. full: embed them.',\n },\n },\n },\n },\n {\n name: 'build-domain-review-context',\n description:\n 'Build domain-scoped model-ready SMRT review context and prompt bundle',\n inputSchema: {\n type: 'object',\n properties: {\n rootDir: { type: 'string' },\n changedFiles: { type: 'array', items: { type: 'string' } },\n focus: { type: 'string' },\n documentation: { type: 'string' },\n scope: {\n type: 'string',\n enum: ['project', 'local', 'package', 'sdk'],\n default: 'project',\n },\n package: { type: 'string' },\n detail: {\n type: 'string',\n enum: ['summary', 'full'],\n default: 'summary',\n description:\n 'summary: authored package docs are listed by path to stay inside tool-result budgets. full: embed them.',\n },\n },\n },\n },\n {\n name: 'smrt-review',\n description:\n 'Return deterministic review findings and/or a reusable model prompt bundle. For a formal downstream review, first call get-agent-skill with { \"name\": \"smrt-code-review\" } or load the smrt-code-review MCP prompt/resource.',\n inputSchema: {\n type: 'object',\n properties: {\n rootDir: { type: 'string' },\n changedFiles: { type: 'array', items: { type: 'string' } },\n focus: { type: 'string' },\n documentation: { type: 'string' },\n mode: {\n type: 'string',\n enum: ['findings', 'prompt-bundle', 'both'],\n default: 'both',\n },\n detail: {\n type: 'string',\n enum: ['summary', 'full'],\n default: 'summary',\n description:\n 'summary: authored package docs are listed by path to stay inside tool-result budgets. full: embed them.',\n },\n },\n },\n },\n {\n name: 'build-architecture-context',\n description:\n 'Build model-ready SMRT architecture context from an idea or documentation',\n inputSchema: {\n type: 'object',\n properties: {\n rootDir: { type: 'string' },\n idea: { type: 'string' },\n documentation: { type: 'string' },\n focus: { type: 'string' },\n detail: {\n type: 'string',\n enum: ['summary', 'full'],\n default: 'summary',\n description:\n 'summary: authored package docs are listed by path to stay inside tool-result budgets. full: embed them.',\n },\n },\n },\n },\n {\n name: 'build-domain-architecture-context',\n description:\n 'Build domain-scoped model-ready SMRT architecture context and prompt bundle',\n inputSchema: {\n type: 'object',\n properties: {\n rootDir: { type: 'string' },\n idea: { type: 'string' },\n documentation: { type: 'string' },\n focus: { type: 'string' },\n scope: {\n type: 'string',\n enum: ['project', 'local', 'package', 'sdk'],\n default: 'project',\n },\n package: { type: 'string' },\n detail: {\n type: 'string',\n enum: ['summary', 'full'],\n default: 'summary',\n description:\n 'summary: authored package docs are listed by path to stay inside tool-result budgets. full: embed them.',\n },\n },\n },\n },\n {\n name: 'smrt-architecture',\n description:\n 'Suggest SMRT and HappyVertical SDK packages and return an architecture prompt bundle',\n inputSchema: {\n type: 'object',\n properties: {\n rootDir: { type: 'string' },\n idea: { type: 'string' },\n documentation: { type: 'string' },\n focus: { type: 'string' },\n detail: {\n type: 'string',\n enum: ['summary', 'full'],\n default: 'summary',\n description:\n 'summary: authored package docs are listed by path to stay inside tool-result budgets. full: embed them.',\n },\n },\n },\n },\n {\n name: 'list-agent-skills',\n description:\n 'List bundled harness-agnostic agent skills shipped with smrt-dev-mcp',\n inputSchema: {\n type: 'object',\n properties: {},\n },\n },\n {\n name: 'get-agent-skill',\n description:\n 'Return a bundled harness-agnostic agent skill as Markdown plus optional references',\n inputSchema: {\n type: 'object',\n properties: {\n name: {\n type: 'string',\n enum: [REVIEW_SKILL_NAME],\n description: 'Bundled agent skill name',\n },\n includeReferences: {\n type: 'boolean',\n default: true,\n description: 'Include referenced files with the skill bundle',\n },\n },\n required: ['name'],\n },\n },\n];\n\nexport const TOOLS: Tool[] = TOOL_DEFINITIONS.map((tool) => ({\n ...tool,\n inputSchema: {\n ...tool.inputSchema,\n $schema: JSON_SCHEMA_2020_12,\n },\n outputSchema: DEV_MCP_OUTPUT_SCHEMA,\n})).sort((left, right) => compareToolNames(left.name, right.name));\n\nexport function createServer(): Server {\n if (DEBUG) {\n console.error(`[${SERVER_NAME}] Starting server v${SERVER_VERSION}`);\n }\n\n const server = new Server(\n {\n name: SERVER_NAME,\n version: SERVER_VERSION,\n },\n {\n capabilities: {\n prompts: {},\n resources: {},\n tools: {},\n },\n cacheHints: {\n 'tools/list': DEPLOY_STATIC_CATALOG_CACHE_HINT,\n 'prompts/list': DEPLOY_STATIC_CATALOG_CACHE_HINT,\n 'resources/list': LIVE_KNOWLEDGE_CACHE_HINT,\n 'resources/read': LIVE_KNOWLEDGE_CACHE_HINT,\n },\n },\n );\n\n // List tools handler\n server.setRequestHandler('tools/list', async () => {\n if (DEBUG) {\n console.error(`[${SERVER_NAME}] ListTools request`);\n }\n return { tools: TOOLS };\n });\n\n server.setRequestHandler('prompts/list', async () => {\n return {\n prompts: [\n {\n name: REVIEW_SKILL_NAME,\n title: 'SMRT Code Review',\n description:\n 'Harness-agnostic downstream SMRT review procedure that uses smrt-dev-mcp deterministic context and prompt bundles.',\n },\n {\n name: DOMAIN_CODE_REVIEW_PROMPT,\n title: 'Domain Code Review',\n description:\n 'Model-ready domain-scoped SMRT code review prompt bundle.',\n arguments: [\n {\n name: 'rootDir',\n description: 'Project root directory. Defaults to server cwd.',\n required: false,\n },\n {\n name: 'changedFiles',\n description:\n 'Changed file paths as newline-separated, comma-separated, or JSON array text.',\n required: false,\n },\n {\n name: 'focus',\n description: 'Review focus text.',\n required: false,\n },\n {\n name: 'documentation',\n description: 'Additional documentation or notes.',\n required: false,\n },\n {\n name: 'scope',\n description: 'Knowledge scope: project, local, package, or sdk.',\n required: false,\n },\n {\n name: 'package',\n description: 'Package name or short package selector.',\n required: false,\n },\n ],\n },\n {\n name: DOMAIN_ARCHITECTURE_PROMPT,\n title: 'Domain Architecture',\n description:\n 'Model-ready domain-scoped SMRT architecture planning prompt bundle.',\n arguments: [\n {\n name: 'rootDir',\n description: 'Project root directory. Defaults to server cwd.',\n required: false,\n },\n {\n name: 'idea',\n description: 'Architecture idea or product concept.',\n required: false,\n },\n {\n name: 'documentation',\n description: 'Additional documentation or notes.',\n required: false,\n },\n {\n name: 'focus',\n description: 'Planning focus text.',\n required: false,\n },\n {\n name: 'scope',\n description: 'Knowledge scope: project, local, package, or sdk.',\n required: false,\n },\n {\n name: 'package',\n description: 'Package name or short package selector.',\n required: false,\n },\n ],\n },\n ],\n };\n });\n\n server.setRequestHandler('prompts/get', async (request) => {\n const { name } = request.params;\n if (name === REVIEW_SKILL_NAME) {\n return {\n description:\n 'Use this procedure when reviewing downstream SMRT projects.',\n messages: [\n {\n role: 'user' as const,\n content: {\n type: 'text' as const,\n text: renderAgentSkillMarkdown(REVIEW_SKILL_NAME),\n },\n },\n ],\n };\n }\n\n if (name === DOMAIN_CODE_REVIEW_PROMPT) {\n const context = await buildReviewContext(\n reviewPromptArguments(request.params.arguments),\n );\n return {\n description: 'Review downstream SMRT code with domain knowledge.',\n messages: [\n {\n role: 'user' as const,\n content: {\n type: 'text' as const,\n text: context.promptBundle.contextMarkdown,\n },\n },\n ],\n };\n }\n\n if (name === DOMAIN_ARCHITECTURE_PROMPT) {\n const context = await buildArchitectureContext(\n architecturePromptArguments(request.params.arguments),\n );\n return {\n description: 'Plan a downstream SMRT project with domain knowledge.',\n messages: [\n {\n role: 'user' as const,\n content: {\n type: 'text' as const,\n text: context.promptBundle.contextMarkdown,\n },\n },\n ],\n };\n }\n\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Unknown prompt: ${name}`,\n );\n });\n\n server.setRequestHandler('resources/list', async () => {\n const index = await buildKnowledgeIndex();\n return {\n resources: [\n {\n uri: REVIEW_SKILL_URI,\n name: REVIEW_SKILL_NAME,\n title: 'SMRT Code Review Skill',\n description:\n 'Bundled Markdown skill for downstream SMRT code reviews.',\n mimeType: 'text/markdown',\n },\n {\n uri: KNOWLEDGE_PROJECT_URI,\n name: 'smrt-domain-knowledge-project',\n title: 'SMRT Domain Knowledge Project Index',\n description:\n 'Composed SMRT, downstream domain, and HappyVertical SDK knowledge index.',\n mimeType: 'application/json',\n },\n ...index.packages.map((pkg) => ({\n uri: `${KNOWLEDGE_PACKAGE_PREFIX}${encodeURIComponent(pkg.name)}`,\n name: `smrt-domain-knowledge-${pkg.name}`,\n title: `SMRT Domain Knowledge: ${pkg.name}`,\n description:\n 'Package-scoped SMRT domain knowledge, generated surfaces, and authored context.',\n mimeType: 'application/json',\n })),\n ],\n };\n });\n\n server.setRequestHandler('resources/read', async (request) => {\n const { uri } = request.params;\n if (uri === REVIEW_SKILL_URI) {\n return {\n contents: [\n {\n uri,\n mimeType: 'text/markdown',\n text: renderAgentSkillMarkdown(REVIEW_SKILL_NAME),\n },\n ],\n };\n }\n\n if (uri === KNOWLEDGE_PROJECT_URI) {\n const index = await buildKnowledgeIndex();\n return {\n contents: [\n {\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(sanitizeKnowledgeIndex(index), null, 2),\n },\n ],\n };\n }\n\n if (uri.startsWith(KNOWLEDGE_PACKAGE_PREFIX)) {\n const packageName = decodeURIComponent(\n uri.slice(KNOWLEDGE_PACKAGE_PREFIX.length),\n );\n const index = await buildKnowledgeIndex();\n const pkg = index.packages.find((item) => item.name === packageName);\n if (!pkg) {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Unknown knowledge package: ${packageName}`,\n );\n }\n return {\n contents: [\n {\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(sanitizeKnowledgePackage(pkg), null, 2),\n },\n ],\n };\n }\n\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Unknown resource: ${uri}`,\n );\n });\n\n // Call tool handler\n server.setRequestHandler('tools/call', async (request) => {\n const { name, arguments: args } = request.params;\n\n if (DEBUG) {\n console.error(`[${SERVER_NAME}] CallTool: ${name}`);\n console.error(\n `[${SERVER_NAME}] Arguments:`,\n JSON.stringify(args, null, 2),\n );\n }\n\n try {\n let result: string;\n\n switch (name) {\n case 'generate-smrt-class':\n result = await generateSmrtClass(\n args as unknown as Parameters<typeof generateSmrtClass>[0],\n );\n break;\n\n case 'introspect-project':\n result = await introspectProject(\n args as unknown as Parameters<typeof introspectProject>[0],\n );\n break;\n\n case 'review-smrt-project':\n result = await reviewSmrtProject(\n args as unknown as Parameters<typeof reviewSmrtProject>[0],\n );\n break;\n\n case 'reflect-knowledge': {\n const index = await buildKnowledgeIndex(\n args as unknown as Parameters<typeof buildKnowledgeIndex>[0],\n );\n const freshness = await checkKnowledgeFreshnessFromIndex(\n index,\n args as unknown as Parameters<\n typeof checkKnowledgeFreshnessFromIndex\n >[1],\n );\n result = JSON.stringify(\n {\n rootDir: index.rootDir,\n packageCount: index.packages.length,\n smrtPackageCount: index.smrtPackages.length,\n sdkPackageCount: index.sdkPackages.length,\n relationshipsV2: index.relationshipsV2,\n coverage: index.coverage,\n diagnostics: index.diagnostics,\n freshness,\n },\n null,\n 2,\n );\n break;\n }\n\n case 'reflect-domain-knowledge': {\n const index = await buildKnowledgeIndex(\n args as unknown as Parameters<typeof buildKnowledgeIndex>[0],\n );\n const freshness = await checkKnowledgeFreshnessFromIndex(\n index,\n args as unknown as Parameters<\n typeof checkKnowledgeFreshnessFromIndex\n >[1],\n );\n result = JSON.stringify(\n {\n rootDir: index.rootDir,\n packageCount: index.packages.length,\n smrtPackageCount: index.smrtPackages.length,\n sdkPackageCount: index.sdkPackages.length,\n domainKnowledgePackageCount: index.packages.filter(\n (pkg) => pkg.hasDomainKnowledge,\n ).length,\n missingDomainKnowledgePackages: index.packages\n .filter(\n (pkg) =>\n pkg.exportKeys.includes('./smrt-knowledge.json') &&\n !pkg.hasDomainKnowledge,\n )\n .map((pkg) => pkg.name),\n relationshipsV2: index.relationshipsV2,\n coverage: index.coverage,\n diagnostics: index.diagnostics,\n freshness,\n },\n null,\n 2,\n );\n break;\n }\n\n case 'check-knowledge-freshness':\n result = JSON.stringify(\n await checkKnowledgeFreshness(\n args as unknown as Parameters<typeof checkKnowledgeFreshness>[0],\n ),\n null,\n 2,\n );\n break;\n\n case 'check-domain-knowledge':\n result = JSON.stringify(\n await checkKnowledgeFreshness(\n args as unknown as Parameters<typeof checkKnowledgeFreshness>[0],\n ),\n null,\n 2,\n );\n break;\n\n case 'build-review-context':\n case 'build-domain-review-context':\n result = JSON.stringify(\n compactContextResult(\n await buildReviewContext(\n args as unknown as Parameters<typeof buildReviewContext>[0],\n ),\n detailArg(args),\n ),\n null,\n 2,\n );\n break;\n\n case 'smrt-review':\n result = JSON.stringify(\n compactContextResult(\n await smrtReview(\n args as unknown as Parameters<typeof smrtReview>[0],\n ),\n detailArg(args),\n ),\n null,\n 2,\n );\n break;\n\n case 'build-architecture-context':\n case 'build-domain-architecture-context':\n result = JSON.stringify(\n compactContextResult(\n await buildArchitectureContext(\n args as unknown as Parameters<\n typeof buildArchitectureContext\n >[0],\n ),\n detailArg(args),\n ),\n null,\n 2,\n );\n break;\n\n case 'smrt-architecture':\n result = JSON.stringify(\n compactContextResult(\n await smrtArchitecture(\n args as unknown as Parameters<typeof smrtArchitecture>[0],\n ),\n detailArg(args),\n ),\n null,\n 2,\n );\n break;\n\n case 'list-agent-skills':\n result = JSON.stringify({ skills: listAgentSkills() }, null, 2);\n break;\n\n case 'get-agent-skill':\n result = JSON.stringify(\n await getAgentSkill(\n args as unknown as Parameters<typeof getAgentSkill>[0],\n ),\n null,\n 2,\n );\n break;\n\n default:\n throw new Error(`Unknown tool: ${name}`);\n }\n\n return {\n content: [\n {\n type: 'text',\n text: result,\n },\n ],\n structuredContent: toDevToolStructuredContent(result),\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : 'Unknown error';\n console.error(`[${SERVER_NAME}] Error:`, error);\n\n return {\n content: [\n {\n type: 'text',\n text: `Error executing tool ${name}: ${errorMessage}`,\n },\n ],\n isError: true,\n structuredContent: {\n ok: false,\n coverage: null,\n diagnostics: [{ severity: 'error', message: errorMessage }],\n data: null,\n },\n };\n }\n });\n\n return server;\n}\n\nasync function main() {\n const handle = serveStdio(() => createServer(), {\n onerror: (error) =>\n console.error(`[${SERVER_NAME}] Protocol error:`, error),\n });\n\n if (DEBUG) {\n console.error(`[${SERVER_NAME}] Server connected via stdio`);\n }\n\n // Graceful shutdown\n process.on('SIGINT', async () => {\n if (DEBUG) {\n console.error(`[${SERVER_NAME}] Shutting down...`);\n }\n await handle.close();\n process.exit(0);\n });\n\n process.on('SIGTERM', async () => {\n if (DEBUG) {\n console.error(`[${SERVER_NAME}] Shutting down...`);\n }\n await handle.close();\n process.exit(0);\n });\n}\n\nfunction isEntrypoint(): boolean {\n const entry = process.argv[1];\n if (!entry) return false;\n try {\n return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(entry);\n } catch {\n return import.meta.url === pathToFileURL(entry).href;\n }\n}\n\nfunction readPackageVersion(): string {\n try {\n const packageRoot = dirname(fileURLToPath(import.meta.url));\n const packageJsonPath = join(packageRoot, '..', 'package.json');\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8')) as {\n version?: unknown;\n };\n return typeof packageJson.version === 'string'\n ? packageJson.version\n : '0.0.0';\n } catch {\n return '0.0.0';\n }\n}\n\nfunction renderAgentSkillMarkdown(name: string): string {\n const skill = getAgentSkill({ name, includeReferences: true });\n const references = skill.referenceFiles.map(\n (file) => `## Reference: ${file.path}\\n\\n${file.content.trim()}`,\n );\n return [skill.skillMarkdown.trim(), ...references].join('\\n\\n');\n}\n\nfunction reviewPromptArguments(args: PromptArguments): Record<string, unknown> {\n return compactRecord({\n rootDir: args?.rootDir,\n changedFiles: parseStringList(args?.changedFiles),\n focus: args?.focus,\n documentation: args?.documentation,\n scope: args?.scope,\n package: args?.package,\n });\n}\n\nfunction architecturePromptArguments(\n args: PromptArguments,\n): Record<string, unknown> {\n return compactRecord({\n rootDir: args?.rootDir,\n idea: args?.idea,\n documentation: args?.documentation,\n focus: args?.focus,\n scope: args?.scope,\n package: args?.package,\n });\n}\n\nfunction parseStringList(value: string | undefined): string[] | undefined {\n if (!value?.trim()) return undefined;\n\n try {\n const parsed = JSON.parse(value);\n if (Array.isArray(parsed)) {\n return parsed.filter((item): item is string => typeof item === 'string');\n }\n } catch {\n // Fall through to delimiter parsing.\n }\n\n return value\n .split(/[\\n,]/)\n .map((item) => item.trim())\n .filter(Boolean);\n}\n\nfunction compactRecord(\n value: Record<string, unknown>,\n): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(value).filter(([, entry]) => entry !== undefined),\n );\n}\n\nfunction sanitizeKnowledgeIndex(index: KnowledgeIndexResult) {\n const packages = index.packages.map((pkg) => sanitizeKnowledgePackage(pkg));\n return {\n ...index,\n rootDir: '.',\n packages,\n smrtPackages: packages.filter((pkg) => pkg.kind === 'smrt'),\n sdkPackages: packages.filter((pkg) => pkg.kind === 'sdk'),\n };\n}\n\n/**\n * Compact projection of a context result for MCP callers (#2143).\n *\n * `selectedPackages` carries each package's whole authored `agentDoc`, its\n * module-doc contents, and its full domain manifest. A three-package downstream\n * product serialized to 329,003 characters that way, which is what made these\n * tools unusable as planning aids. `detail: \"full\"` returns the whole shape.\n */\nfunction compactContextResult(\n result: object,\n detail: string | undefined,\n): Record<string, unknown> {\n const source = result as Record<string, unknown>;\n if (detail === 'full') return source;\n\n const compact: Record<string, unknown> = { ...source, detail: 'summary' };\n for (const key of ['selectedPackages', 'selectedSdkPackages']) {\n const packages = source[key];\n if (!Array.isArray(packages)) continue;\n compact[key] = (packages as KnowledgePackageResult[]).map(\n compactKnowledgePackage,\n );\n }\n return compact;\n}\n\nfunction compactKnowledgePackage(pkg: KnowledgePackageResult) {\n return {\n name: pkg.name,\n version: pkg.version,\n kind: pkg.kind,\n directory: pkg.relativeDirectory,\n objectSource: pkg.objectSource,\n ...(pkg.objectSourceReason\n ? { objectSourceReason: pkg.objectSourceReason }\n : {}),\n // Paths, not prose: the caller reads what it needs.\n docs: packageDocPaths(pkg),\n domainKnowledgePath: pkg.domainKnowledgePath,\n relationshipFeatures: pkg.relationshipFeatures,\n smrtDependencies: pkg.smrtDependencies,\n sdkDependencies: pkg.sdkDependencies,\n exportKeys: pkg.exportKeys,\n objectCount: pkg.objects.length,\n objects: pkg.objects.map((object) =>\n object.tableName\n ? `${object.qualifiedName ?? object.className} (${object.tableName})`\n : (object.qualifiedName ?? object.className),\n ),\n mcpToolCount: pkg.mcpTools.length,\n };\n}\n\nfunction detailArg(args: unknown): string | undefined {\n const detail = (args as Record<string, unknown> | undefined)?.detail;\n return typeof detail === 'string' ? detail : undefined;\n}\n\nfunction toDevToolStructuredContent(result: string) {\n let data: unknown = result;\n try {\n data = JSON.parse(result);\n } catch {\n // `generate-smrt-class` intentionally returns source text, not JSON.\n }\n\n const source = isRecord(data) ? data : undefined;\n const coverage = isRecord(source?.coverage) ? source.coverage : null;\n const diagnostics = Array.isArray(source?.diagnostics)\n ? source.diagnostics.filter(isRecord)\n : [];\n return { ok: true, coverage, diagnostics, data };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction sanitizeKnowledgePackage(pkg: KnowledgePackageResult) {\n const { directory: _directory, objects, checkedObjectPaths, ...rest } = pkg;\n return {\n ...rest,\n // Paths outside the workspace root stay absolute in the index; redact them\n // here the same way object file paths are redacted.\n checkedObjectPaths: checkedObjectPaths.map(\n (path) => sanitizePath(path) ?? path,\n ),\n objects: objects.map((object) => ({\n ...object,\n filePath: sanitizePath(object.filePath),\n })),\n };\n}\n\nfunction sanitizePath(path: string | undefined): string | undefined {\n if (!path) return path;\n if (path.startsWith('/') || /^[A-Za-z]:[\\\\/]/.test(path)) {\n return '<absolute-path>';\n }\n return path;\n}\n\nif (isE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,SAAS,IAAI,OACjB;EACE,MAAM;EACN,SAAS;CACX,GACA;EACE,cAAc;GACZ,SAAS,CAAC;GACV,WAAW,CAAC;GACZ,OAAO,CAAC;EACV;EACA,YAAY;GACV,cAAc;GACd,gBAAgB;GAChB,kBAAkB;GAClB,kBAAkB;EACpB;CACF,CACF;CAGA,OAAO,kBAAkB,cAAc,YAAY;EACjD,IAAI,OACF,QAAQ,MAAM,IAAI,YAAY,oBAAoB;EAEpD,OAAO,EAAE,OAAO,MAAM;CACxB,CAAC;CAED,OAAO,kBAAkB,gBAAgB,YAAY;EACnD,OAAO,EACL,SAAS;GACP;IACE,MAAM;IACN,OAAO;IACP,aACE;GACJ;GACA;IACE,MAAM;IACN,OAAO;IACP,aACE;IACF,WAAW;KACT;MACE,MAAM;MACN,aAAa;MACb,UAAU;KACZ;KACA;MACE,MAAM;MACN,aACE;MACF,UAAU;KACZ;KACA;MACE,MAAM;MACN,aAAa;MACb,UAAU;KACZ;KACA;MACE,MAAM;MACN,aAAa;MACb,UAAU;KACZ;KACA;MACE,MAAM;MACN,aAAa;MACb,UAAU;KACZ;KACA;MACE,MAAM;MACN,aAAa;MACb,UAAU;KACZ;IACF;GACF;GACA;IACE,MAAM;IACN,OAAO;IACP,aACE;IACF,WAAW;KACT;MACE,MAAM;MACN,aAAa;MACb,UAAU;KACZ;KACA;MACE,MAAM;MACN,aAAa;MACb,UAAU;KACZ;KACA;MACE,MAAM;MACN,aAAa;MACb,UAAU;KACZ;KACA;MACE,MAAM;MACN,aAAa;MACb,UAAU;KACZ;KACA;MACE,MAAM;MACN,aAAa;MACb,UAAU;KACZ;KACA;MACE,MAAM;MACN,aAAa;MACb,UAAU;KACZ;IACF;GACF;EACF,EACF;CACF,CAAC;CAED,OAAO,kBAAkB,eAAe,OAAO,YAAY;EACzD,MAAM,EAAE,SAAS,QAAQ;EACzB,IAAI,SAAS,mBACX,OAAO;GACL,aACE;GACF,UAAU,CACR;IACE,MAAM;IACN,SAAS;KACP,MAAM;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AAM,MAAM;CAC1B,QAAQ,CAER;CAEA,MAAM,SAAS,SAAS,IAAI,IAAI,OAAO,KAAA;CAKvC,OAAO;EAAE,IAAI;EAAM,UAJF,SAAS,QAAQ,QAAQ,IAAI,OAAO,WAAW;EAInC,aAHT,MAAM,QAAQ,QAAQ,WAAW,IACjD,OAAO,YAAY,OAAO,QAAQ,IAClC,CAAC;EACqC;CAAK;AACjD;AAEA,SAAS,SAAS,OAAkD;CAClE,OAAO,CAAC,CAAC,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AACrE;AAEA,SAAS,yBAAyB,KAA6B;CAC7D,MAAM,EAAE,WAAW,YAAY,SAAS,oBAAoB,GAAG,SAAS;CACxE,OAAO;EACL,GAAG;EAGH,oBAAoB,mBAAmB,KACpC,SAAS,aAAa,IAAI,KAAK,IAClC;EACA,SAAS,QAAQ,KAAK,YAAY;GAChC,GAAG;GACH,UAAU,aAAa,OAAO,QAAQ;EACxC,EAAE;CACJ;AACF;AAEA,SAAS,aAAa,MAA8C;CAClE,IAAI,CAAC,MAAM,OAAO;CAClB,IAAI,KAAK,WAAW,GAAG,KAAK,kBAAkB,KAAK,IAAI,GACrD,OAAO;CAET,OAAO;AACT;AAEA,IAAI,aAAa,GACf,KAAK,CAAC,CAAC,OAAO,UAAU;CACtB,QAAQ,MAAM,IAAI,YAAY,iBAAiB,KAAK;CACpD,QAAQ,KAAK,CAAC;AAChB,CAAC"}
package/mcp.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
3
+ "mcpServers": {
4
+ "smrt-dev-mcp": {
5
+ "type": "stdio",
6
+ "command": "./dist/index.js"
7
+ }
8
+ }
9
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happyvertical/smrt-dev-mcp",
3
- "version": "0.40.60",
3
+ "version": "0.40.62",
4
4
  "description": "Development MCP server for SMRT framework knowledge, review context, architecture context, and code generation",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -23,7 +23,10 @@
23
23
  "README.md",
24
24
  "dist",
25
25
  "AGENTS.md",
26
- "agent-skills"
26
+ "plugin.json",
27
+ "mcp.json",
28
+ "skills",
29
+ "schemas"
27
30
  ],
28
31
  "publishConfig": {
29
32
  "registry": "https://registry.npmjs.org",
@@ -41,15 +44,16 @@
41
44
  "license": "MIT",
42
45
  "dependencies": {
43
46
  "@modelcontextprotocol/server": "2.0.0",
44
- "@happyvertical/smrt-core": "0.40.60",
45
- "@happyvertical/smrt-scanner": "0.40.60",
46
- "@happyvertical/smrt-types": "0.40.60"
47
+ "@happyvertical/smrt-core": "0.40.62",
48
+ "@happyvertical/smrt-scanner": "0.40.62",
49
+ "@happyvertical/smrt-types": "0.40.62"
47
50
  },
48
51
  "devDependencies": {
49
52
  "@modelcontextprotocol/client": "2.0.0",
50
53
  "@modelcontextprotocol/conformance": "0.2.0-alpha.10",
51
54
  "@modelcontextprotocol/node": "2.0.0",
52
55
  "@types/node": "24.13.2",
56
+ "ajv": "8.18.0",
53
57
  "typescript": "5.9.3",
54
58
  "vite": "8.1.4",
55
59
  "vite-plugin-dts": "^4.5.4",
package/plugin.json ADDED
@@ -0,0 +1,5 @@
1
+ {
2
+ "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
3
+ "name": "smrt-dev-mcp",
4
+ "description": "Development MCP server and SMRT code-review skill."
5
+ }
@@ -0,0 +1,16 @@
1
+ # Pinned Agent Plugins 1.0.0 schemas
2
+
3
+ These are byte-for-byte snapshots of the canonical Agent Plugins 1.0.0 schema
4
+ documents. They are intentionally packaged so package verification and offline
5
+ clients never fetch schemas while loading a plugin.
6
+
7
+ Source (retrieved 2026-08-08):
8
+
9
+ - `https://raw.githubusercontent.com/agentplugins/agent-plugins-spec/main/schemas/1.0.0/plugin.schema.json`
10
+ — SHA-256 `0a4aad95ce337878ad38802ebf0daa3fde76abe3f65400c86bcbb1ec0b3ab883`
11
+ - `https://raw.githubusercontent.com/agentplugins/agent-plugins-spec/main/schemas/1.0.0/mcp.schema.json`
12
+ — SHA-256 `6539175bfcdf43085855183e86da40ea94b166547a72b47ae9a0a390516d3acb`
13
+
14
+ Agent Plugins 1.0.0 is a Working Draft. The canonical `$schema` identifiers in
15
+ these snapshots are this package's compatibility boundary; update both only as
16
+ one reviewed compatibility change.
@@ -0,0 +1,120 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
4
+ "title": "Agent Plugins MCP Configuration",
5
+ "description": "Machine-readable schema for mcp.json in Agent Plugins 1.0.0. The Agent Plugins specification defines additional semantic and operational requirements.",
6
+ "type": "object",
7
+ "properties": {
8
+ "$schema": {
9
+ "const": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
10
+ "description": "Canonical identifier of the MCP configuration schema for the Agent Plugins version targeted by this document."
11
+ },
12
+ "mcpServers": {
13
+ "type": "object",
14
+ "additionalProperties": {
15
+ "$ref": "#/$defs/server"
16
+ }
17
+ }
18
+ },
19
+ "required": ["$schema", "mcpServers"],
20
+ "additionalProperties": false,
21
+ "$defs": {
22
+ "server": {
23
+ "title": "MCP server",
24
+ "oneOf": [
25
+ {
26
+ "$ref": "#/$defs/stdioServer"
27
+ },
28
+ {
29
+ "$ref": "#/$defs/streamableHttpServer"
30
+ },
31
+ {
32
+ "$ref": "#/$defs/sseServer"
33
+ }
34
+ ]
35
+ },
36
+ "stdioServer": {
37
+ "title": "stdio MCP server",
38
+ "type": "object",
39
+ "properties": {
40
+ "type": {
41
+ "const": "stdio"
42
+ },
43
+ "command": {
44
+ "type": "string",
45
+ "minLength": 1,
46
+ "description": "Executable token. Resolution rules are defined by the Agent Plugins specification."
47
+ },
48
+ "args": {
49
+ "type": "array",
50
+ "items": {
51
+ "type": "string"
52
+ }
53
+ },
54
+ "env": {
55
+ "type": "object",
56
+ "propertyNames": {
57
+ "not": {
58
+ "enum": ["PLUGIN_ROOT", "PLUGIN_DATA"]
59
+ }
60
+ },
61
+ "additionalProperties": {
62
+ "type": "string"
63
+ }
64
+ },
65
+ "cwd": {
66
+ "type": "string",
67
+ "pattern": "^(?:\\./|\\$\\{PLUGIN_ROOT\\}(?:/|$)|\\$\\{PLUGIN_DATA\\}(?:/|$))",
68
+ "description": "Plugin-relative, PLUGIN_ROOT-rooted, or PLUGIN_DATA-rooted working directory. Filesystem containment is validated separately."
69
+ }
70
+ },
71
+ "required": ["type", "command"],
72
+ "additionalProperties": false
73
+ },
74
+ "streamableHttpServer": {
75
+ "title": "Streamable HTTP MCP server",
76
+ "type": "object",
77
+ "properties": {
78
+ "type": {
79
+ "const": "streamable-http"
80
+ },
81
+ "url": {
82
+ "type": "string",
83
+ "minLength": 1,
84
+ "description": "MCP endpoint URL. URL semantics are defined by the Agent Plugins specification."
85
+ },
86
+ "headers": {
87
+ "$ref": "#/$defs/headers"
88
+ }
89
+ },
90
+ "required": ["type", "url"],
91
+ "additionalProperties": false
92
+ },
93
+ "sseServer": {
94
+ "title": "Legacy HTTP+SSE MCP server",
95
+ "type": "object",
96
+ "properties": {
97
+ "type": {
98
+ "const": "sse"
99
+ },
100
+ "url": {
101
+ "type": "string",
102
+ "minLength": 1,
103
+ "description": "MCP endpoint URL. URL semantics are defined by the Agent Plugins specification."
104
+ },
105
+ "headers": {
106
+ "$ref": "#/$defs/headers"
107
+ }
108
+ },
109
+ "required": ["type", "url"],
110
+ "additionalProperties": false
111
+ },
112
+ "headers": {
113
+ "title": "HTTP headers",
114
+ "type": "object",
115
+ "additionalProperties": {
116
+ "type": "string"
117
+ }
118
+ }
119
+ }
120
+ }
@@ -0,0 +1,65 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
4
+ "title": "Agent Plugins Manifest",
5
+ "description": "Machine-readable schema for plugin.json in Agent Plugins 1.0.0. The Agent Plugins specification defines additional semantic and operational requirements.",
6
+ "type": "object",
7
+ "properties": {
8
+ "$schema": {
9
+ "const": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
10
+ "description": "Canonical identifier of the plugin manifest schema for the Agent Plugins version targeted by this document."
11
+ },
12
+ "name": {
13
+ "type": "string",
14
+ "minLength": 1,
15
+ "maxLength": 64,
16
+ "pattern": "^(?!.*(?:--|\\.\\.))[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$",
17
+ "description": "Human-readable plugin name."
18
+ },
19
+ "version": {
20
+ "type": "string"
21
+ },
22
+ "description": {
23
+ "type": "string"
24
+ },
25
+ "author": {
26
+ "type": "object",
27
+ "properties": {
28
+ "name": {
29
+ "type": "string"
30
+ },
31
+ "email": {
32
+ "type": "string"
33
+ },
34
+ "url": {
35
+ "type": "string"
36
+ }
37
+ },
38
+ "additionalProperties": false
39
+ },
40
+ "homepage": {
41
+ "type": "string"
42
+ },
43
+ "repository": {
44
+ "type": "string"
45
+ },
46
+ "license": {
47
+ "type": "string"
48
+ },
49
+ "keywords": {
50
+ "type": "array",
51
+ "items": {
52
+ "type": "string"
53
+ }
54
+ },
55
+ "extensions": {
56
+ "type": "object",
57
+ "description": "Client-specific manifest data keyed by reverse-domain extension namespace. Agent Plugins assigns no semantics to namespace object contents.",
58
+ "additionalProperties": {
59
+ "type": "object"
60
+ }
61
+ }
62
+ },
63
+ "required": ["$schema", "name"],
64
+ "additionalProperties": false
65
+ }