@happyvertical/smrt-scanner 0.57.37 → 0.57.38
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/dist/knowledge-graph.d.ts.map +1 -1
- package/dist/knowledge.js +15 -2
- package/dist/knowledge.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"knowledge-graph.d.ts","sourceRoot":"","sources":["../src/knowledge-graph.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAKH,OAAO,KAAK,EACV,uBAAuB,EAExB,MAAM,2BAA2B,CAAC;AAEnC;;;;;;;;;GASG;AACH,wBAAgB,8BAA8B,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,CAexE;AAED,+EAA+E;AAC/E,MAAM,WAAW,mBAAmB;IAClC,wEAAwE;IACxE,YAAY,EAAE,MAAM,CAAC;IACrB,QAAQ,EAAE,uBAAuB,CAAC;CACnC;AAED,MAAM,WAAW,yBAAyB;IACxC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC;IACrB,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,wBAAwB;IACvC,8EAA8E;IAC9E,EAAE,EAAE,MAAM,CAAC;IACX,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,KAAK,GAAG,KAAK,CAAC;IAC9B,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,MAAM,sBAAsB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MAAM,CAAC;IACZ,yDAAyD;IACzD,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,kBAAkB;IACjC,aAAa,EAAE,CAAC,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,6EAA6E;IAC7E,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACrC,QAAQ,EAAE,yBAAyB,EAAE,CAAC;IACtC,OAAO,EAAE,wBAAwB,EAAE,CAAC;IACpC,KAAK,EAAE,kBAAkB,EAAE,CAAC;CAC7B;AAUD,MAAM,WAAW,0BAA0B;IACzC;;;;;;;;OAQG;IACH,aAAa,CAAC,EAAE,kBAAkB,CAAC;CACpC;AAED,qEAAqE;AACrE,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,mBAAmB,EAAE,EAC7B,OAAO,GAAE,0BAA+B,GACvC,kBAAkB,CAgMpB;AAOD,8EAA8E;AAC9E,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAEtD;AA+BD,MAAM,WAAW,4BAA4B;IAC3C,QAAQ,EAAE,OAAO,GAAG,SAAS,CAAC;IAC9B,IAAI,EACA,yBAAyB,GACzB,uBAAuB,GACvB,gCAAgC,CAAC;IACrC,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED;;;;;;;GAOG;AACH,wBAAgB,4BAA4B,CAC1C,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,MAAM,EACjB,OAAO,GAAE;IAAE,eAAe,CAAC,EAAE,OAAO,CAAA;CAAO,GAC1C,4BAA4B,EAAE,CA+GhC"}
|
package/dist/knowledge.js
CHANGED
|
@@ -265,8 +265,21 @@ function checkKnowledgeGraphFreshness(rootDir, graphPath, options = {}) {
|
|
|
265
265
|
});
|
|
266
266
|
return issues;
|
|
267
267
|
}
|
|
268
|
-
const
|
|
269
|
-
|
|
268
|
+
const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
269
|
+
const graphValue = graph;
|
|
270
|
+
const sourceHashesValue = isPlainObject(graphValue) ? graphValue.sourceHashes ?? {} : void 0;
|
|
271
|
+
if (!isPlainObject(graphValue) || !isPlainObject(sourceHashesValue) || Object.values(sourceHashesValue).some((hash) => typeof hash !== "string")) {
|
|
272
|
+
issues.push({
|
|
273
|
+
severity: "error",
|
|
274
|
+
code: "stale-knowledge-graph",
|
|
275
|
+
message: `${graphPath} is malformed (expected an object with a \`sourceHashes\` map of string hashes); run \`pnpm knowledge:graph\``,
|
|
276
|
+
file: graphPath
|
|
277
|
+
});
|
|
278
|
+
return issues;
|
|
279
|
+
}
|
|
280
|
+
const sourceHashes = sourceHashesValue;
|
|
281
|
+
const recordedPaths = Object.keys(sourceHashes);
|
|
282
|
+
for (const [artifactPath, expectedHash] of Object.entries(sourceHashes)) {
|
|
270
283
|
const absoluteArtifactPath = `${rootDir}/${artifactPath}`;
|
|
271
284
|
if (!existsSync(absoluteArtifactPath)) {
|
|
272
285
|
issues.push({
|
package/dist/knowledge.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"knowledge.js","names":[],"sources":["../src/knowledge-discovery.ts","../src/knowledge-graph.ts"],"sourcesContent":["/** Filesystem-only discovery shared by docs snapshots and knowledge indexing. */\nimport type { Dirent } from 'node:fs';\nimport {\n existsSync,\n readdirSync,\n readFileSync,\n realpathSync,\n statSync,\n} from 'node:fs';\nimport { basename, join, relative, resolve, sep } from 'node:path';\nimport type { DomainKnowledgeModuleDoc } from '@happyvertical/smrt-types';\n\nexport interface ScopedPackageDirectory {\n /** Scope entry name; consumers may select by alias rather than manifest name. */\n name: string;\n /** Original node_modules path, retained for workspace-relative reporting. */\n directory: string;\n /** Resolved path for identity comparisons or absolute snapshot links. */\n realDirectory: string;\n}\n\n/**\n * Enumerate scope entries without descending into pnpm's linked dependency graph.\n * Selection, workspace discovery and enrichment remain caller policies.\n */\nexport function discoverScopedPackageDirectories(\n scopeDirectories: string[],\n): ScopedPackageDirectory[] {\n const packages: ScopedPackageDirectory[] = [];\n for (const scopeDirectory of new Set(scopeDirectories)) {\n let entries: Dirent[];\n try {\n entries = readdirSync(scopeDirectory, { withFileTypes: true });\n } catch {\n continue;\n }\n for (const entry of entries) {\n if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;\n const directory = join(scopeDirectory, entry.name);\n try {\n packages.push({\n name: entry.name,\n directory,\n realDirectory: realpathSync(directory),\n });\n } catch {\n // Dangling links are not installed packages.\n }\n }\n }\n return packages;\n}\n\n/** Read authored docs only; never load artifacts, package code or object scans. */\nexport function readPackageAgentDoc(\n directory: string,\n options: { inspectAdapter?: boolean } = {},\n) {\n const agentsPath = join(directory, 'AGENTS.md');\n const claudePath = join(directory, 'CLAUDE.md');\n const hasAgentsMd = existsSync(agentsPath);\n const hasClaudeMd = existsSync(claudePath);\n const agentsContent = hasAgentsMd ? readFileSync(agentsPath, 'utf8') : '';\n const claudeContent =\n hasClaudeMd && (!hasAgentsMd || options.inspectAdapter)\n ? readFileSync(claudePath, 'utf8')\n : '';\n const hasClaudeShim = hasClaudeMd && claudeContent.trim() === '@AGENTS.md';\n const source: 'AGENTS.md' | 'CLAUDE.md' | null = hasAgentsMd\n ? 'AGENTS.md'\n : hasClaudeMd && !hasClaudeShim\n ? 'CLAUDE.md'\n : null;\n return {\n hasAgentsMd,\n hasClaudeMd,\n hasClaudeShim,\n agentsContent,\n claudeContent,\n source,\n content: hasAgentsMd ? agentsContent : source ? claudeContent : null,\n };\n}\n\n/**\n * Markdown inline links whose target is a `.md` file — `[label](agents/x.md)`,\n * tolerating an `#anchor` and a `\"title\"`. This is how a package registers a\n * sibling module doc (#2108): the link in `AGENTS.md` IS the registration, so\n * there is no separate index to drift out of sync.\n */\nconst MARKDOWN_MD_LINK =\n /\\[[^\\]]*\\]\\(\\s*([^)\\s#]+\\.md)(?:#[^)\\s]*)?(?:\\s+\"[^\"]*\")?\\s*\\)/g;\n\n/** `sourceHashes` key prefix for a linked module doc, e.g. `moduleDoc:agents/crm.md`. */\nexport const MODULE_DOC_HASH_PREFIX = 'moduleDoc:';\n\n/**\n * `sourceHashes` key prefix for a module declaring a view intent or playbook,\n * e.g. `agentSurface:src/lib/orders.intents.ts` (#2591).\n */\nexport const AGENT_SURFACE_HASH_PREFIX = 'agentSurface:';\n\n/**\n * Module doc paths linked from a package's `AGENTS.md`, relative to the package\n * root and in document order.\n *\n * Instruction chains are additive (see `scripts/check-agents-chain.mjs`), so an\n * oversized package doc is split into `packages/<pkg>/agents/<module>.md` siblings\n * instead of nested `AGENTS.md` files. Only links resolving to an existing file\n * INSIDE the package are accepted — a cross-package reference such as\n * `packages/affiliates/MIGRATION.md` belongs to that package's own chain and is\n * ignored here.\n */\nexport function resolveAgentModuleDocPaths(\n rootDir: string,\n agentDoc: string | undefined,\n): string[] {\n if (!agentDoc) return [];\n const root = resolve(rootDir);\n const paths: string[] = [];\n for (const match of agentDoc.matchAll(MARKDOWN_MD_LINK)) {\n const target = match[1];\n if (target.includes('://')) continue;\n const absolute = resolve(root, target);\n if (absolute !== root && !absolute.startsWith(root + sep)) continue;\n const relativePath = relative(root, absolute).split(sep).join('/');\n if (relativePath === 'AGENTS.md' || relativePath === 'CLAUDE.md') continue;\n if (paths.includes(relativePath)) continue;\n if (!existsSync(absolute) || !statSync(absolute).isFile()) continue;\n paths.push(relativePath);\n }\n return paths;\n}\n\n/** {@link resolveAgentModuleDocPaths}, with each doc's contents read. */\nexport function readAgentModuleDocs(\n rootDir: string,\n agentDoc: string | undefined,\n): DomainKnowledgeModuleDoc[] {\n return resolveAgentModuleDocPaths(rootDir, agentDoc).map((path) => ({\n path,\n module: basename(path, '.md'),\n content: readFileSync(join(rootDir, path), 'utf8'),\n }));\n}\n","/**\n * Cross-package knowledge graph (#2863).\n *\n * Each package's own `smrt-knowledge.json` (see `knowledge.ts`) is a\n * per-package projection. Nothing merges them, so cross-package invariants\n * that the scanner manifest already carries — `@crossPackageRef` targets, STI\n * parent/child pairs, junction/hierarchical/polymorphic base usage, and\n * `_smrt_` system-table ownership — live only as prose in the root\n * `AGENTS.md`. This module builds the merged, deterministic root artifact\n * (`.smrt/smrt-knowledge-graph.json`) from whichever per-package artifacts\n * are present, and checks it for staleness the same way `knowledge.ts` checks\n * a package artifact: by comparing recorded `sourceHashes` against the\n * current file content.\n *\n * This module never invents an edge: every edge is a direct read of a field\n * already emitted into a package's `DomainKnowledgeManifest` (`related`,\n * `tableStrategy`, `extends`, `relationshipFeatures`, `tableName`).\n */\n\nimport { createHash } from 'node:crypto';\nimport { existsSync, readdirSync, readFileSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport type {\n DomainKnowledgeManifest,\n DomainKnowledgeObject,\n} from '@happyvertical/smrt-types';\n\n/**\n * Discovers every currently-buildable per-package artifact path under\n * `<rootDir>/packages/*`, preferring the published `dist/smrt-knowledge.json`\n * over the local dev `.smrt/smrt-knowledge.json` when both exist. Shared by\n * the generator (which needs the manifest content) and the freshness check\n * (which only needs to know whether the current SET of artifacts matches\n * what the graph was built from — a newly built package, or a package that\n * newly started exporting `./smrt-knowledge.json`, must mark the graph stale\n * even though every artifact the graph already knows about is unchanged).\n */\nexport function discoverKnowledgeArtifactPaths(rootDir: string): string[] {\n const packagesDir = join(rootDir, 'packages');\n if (!existsSync(packagesDir)) return [];\n const paths: string[] = [];\n for (const entry of readdirSync(packagesDir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const packageDir = join(packagesDir, entry.name);\n const candidates = [\n join(packageDir, 'dist', 'smrt-knowledge.json'),\n join(packageDir, '.smrt', 'smrt-knowledge.json'),\n ];\n const found = candidates.find((path) => existsSync(path));\n if (found) paths.push(relative(rootDir, found).split('\\\\').join('/'));\n }\n return paths.sort();\n}\n\n/** One package's `smrt-knowledge.json`, located relative to the graph root. */\nexport interface KnowledgeGraphInput {\n /** Path to the artifact, relative to the repo root, POSIX-separated. */\n artifactPath: string;\n manifest: DomainKnowledgeManifest;\n}\n\nexport interface KnowledgeGraphPackageNode {\n name: string;\n version?: string;\n artifactPath: string;\n tags: string[];\n risks: string[];\n summary?: string;\n objectCount: number;\n}\n\nexport interface KnowledgeGraphObjectNode {\n /** `<packageName>#<qualifiedName-or-name>`, this graph's stable object id. */\n id: string;\n packageName: string;\n name: string;\n qualifiedName?: string;\n collection: string;\n tableName?: string;\n tableStrategy?: 'cti' | 'sti';\n extends?: string;\n}\n\nexport type KnowledgeGraphEdgeType =\n | 'crossPackageRef'\n | 'sti'\n | 'junction'\n | 'hierarchical'\n | 'polymorphic'\n | 'systemTable';\n\nexport interface KnowledgeGraphEdge {\n type: KnowledgeGraphEdgeType;\n /** Object id (or `<packageName>#<extends>`-style unresolved target) this edge starts from. */\n from: string;\n /**\n * Object id the edge points to when resolvable against a scanned object;\n * otherwise the raw declared target (e.g. a qualified name this run did\n * not scan), so the edge is still readable rather than dropped.\n */\n to?: string;\n /** Declaring field name, for `crossPackageRef` edges. */\n field?: string;\n}\n\nexport interface SmrtKnowledgeGraph {\n schemaVersion: 1;\n generatedAt: string;\n /** `artifactPath -> sha256(content)`, sorted by key; the freshness input. */\n sourceHashes: Record<string, string>;\n packages: KnowledgeGraphPackageNode[];\n objects: KnowledgeGraphObjectNode[];\n edges: KnowledgeGraphEdge[];\n}\n\nfunction hashContent(content: string): string {\n return createHash('sha256').update(content).digest('hex');\n}\n\nfunction objectId(packageName: string, object: DomainKnowledgeObject): string {\n return `${packageName}#${object.qualifiedName ?? object.name}`;\n}\n\nexport interface BuildKnowledgeGraphOptions {\n /**\n * The graph currently on disk, when regenerating. `generatedAt` is\n * preserved from it rather than reset to the clock whenever the rebuilt\n * graph is otherwise semantically identical — the same pattern\n * `preserveKnowledgeGeneratedAt` uses for per-package artifacts\n * (`packages/core/src/vite-plugin/index.ts`) — so re-running the generator\n * with nothing merged actually changed does not churn the file (#2872\n * review).\n */\n previousGraph?: SmrtKnowledgeGraph;\n}\n\n/** Builds the merged graph. Deterministic: every array is sorted. */\nexport function buildKnowledgeGraph(\n inputs: KnowledgeGraphInput[],\n options: BuildKnowledgeGraphOptions = {},\n): SmrtKnowledgeGraph {\n const sortedInputs = [...inputs].sort((a, b) =>\n a.artifactPath.localeCompare(b.artifactPath),\n );\n\n const sourceHashes: Record<string, string> = {};\n const packages: KnowledgeGraphPackageNode[] = [];\n const objects: KnowledgeGraphObjectNode[] = [];\n const edges: KnowledgeGraphEdge[] = [];\n\n // Qualified-name -> object id, so a crossPackageRef/STI target declared in\n // one package can be resolved to the node emitted by whichever package\n // scanned it, regardless of scan order.\n const idByQualifiedName = new Map<string, string>();\n // Distinct ids per simple name, not a plain array: the same external\n // object can appear in more than one input (e.g. a package artifact and a\n // smrtConsumer aggregate that also scanned it), and counting the\n // duplicate would make resolveTarget's `.length === 1` uniqueness check\n // see a false ambiguity for an otherwise-unique name (#2872 review).\n const idBySimpleName = new Map<string, Set<string>>();\n // A `tableStrategy: 'sti'` object's `extends` is an unqualified simple name;\n // a parent imported from another package also carries `extendsQualified`\n // (#4145), which resolves first. Otherwise a same-package simple-name match\n // must win over an ambiguous or wrong-package GLOBAL simple-name match:\n // two packages both declaring `Account` must not point one package's\n // subclass at the other package's `Account` (#2863 review).\n const idBySimpleNamePerPackage = new Map<string, Map<string, string>>();\n const aliasIds: Array<[string, string]> = [];\n\n for (const input of sortedInputs) {\n const manifestPackageName =\n input.manifest.packageName ?? input.artifactPath;\n for (const object of input.manifest.objects) {\n // A merged consumer manifest (`smrtConsumer`) aggregates objects\n // scanned from multiple external packages under one local artifact;\n // each object then carries its own `packageName` and that must own\n // the id, or every external object misattributes to the local\n // project and edges resolve to the wrong node (#2872 review).\n const packageName = object.packageName ?? manifestPackageName;\n const perPackage =\n idBySimpleNamePerPackage.get(packageName) ?? new Map<string, string>();\n const id = objectId(packageName, object);\n idByQualifiedName.set(object.qualifiedName ?? id, id);\n const bySimple = idBySimpleName.get(object.name) ?? new Set<string>();\n bySimple.add(id);\n idBySimpleName.set(object.name, bySimple);\n perPackage.set(object.name, id);\n idBySimpleNamePerPackage.set(packageName, perPackage);\n for (const alias of object.previousQualifiedNames ?? []) {\n aliasIds.push([alias, id]);\n }\n }\n }\n // A moved object's deprecated qualified names (#3338) resolve to it, but\n // never shadow a live object's own qualified name. Ownership is tracked\n // separately so two distinct objects claiming one old name fail the build,\n // as the runtime registry refuses them, instead of the first in sort order\n // silently winning; the same object repeated across artifacts is one claim.\n const aliasOwners = new Map<string, Set<string>>();\n for (const [alias, id] of aliasIds) {\n const owners = aliasOwners.get(alias) ?? new Set<string>();\n owners.add(id);\n aliasOwners.set(alias, owners);\n }\n for (const [alias, owners] of aliasOwners) {\n if (owners.size > 1) {\n throw new Error(\n `[knowledge-graph] previousQualifiedNames \"${alias}\" is claimed by more than one object: ` +\n `${[...owners].sort().join(', ')}. An old qualified name can resolve to only one class; ` +\n 'remove the alias from all but one owner.',\n );\n }\n if (!idByQualifiedName.has(alias)) {\n idByQualifiedName.set(alias, [...owners][0]);\n }\n }\n\n const resolveTarget = (\n raw: string | undefined,\n declaringPackageName?: string,\n ): string | undefined => {\n if (!raw) return undefined;\n if (idByQualifiedName.has(raw)) return idByQualifiedName.get(raw);\n if (declaringPackageName) {\n const sameId = idBySimpleNamePerPackage\n .get(declaringPackageName)\n ?.get(raw);\n if (sameId) return sameId;\n }\n const bySimple = idBySimpleName.get(raw);\n if (bySimple && bySimple.size === 1) return [...bySimple][0];\n return undefined;\n };\n\n const seenObjectIds = new Set<string>();\n for (const input of sortedInputs) {\n sourceHashes[input.artifactPath] = hashContent(\n stableStringify(input.manifest),\n );\n const packageName = input.manifest.packageName ?? input.artifactPath;\n\n packages.push({\n name: packageName,\n version: input.manifest.packageVersion,\n artifactPath: input.artifactPath,\n tags: [...input.manifest.tags].sort(),\n risks: [...input.manifest.risks].sort(),\n summary: input.manifest.summary,\n objectCount: input.manifest.objects.length,\n });\n\n for (const object of input.manifest.objects) {\n // See the id-map pass above: an aggregated consumer manifest attributes\n // each object to its own scanned package, not the local project.\n const objectPackageName = object.packageName ?? packageName;\n const id = objectId(objectPackageName, object);\n if (!seenObjectIds.has(id)) {\n seenObjectIds.add(id);\n objects.push({\n id,\n packageName: objectPackageName,\n name: object.name,\n qualifiedName: object.qualifiedName,\n collection: object.collection,\n tableName: object.tableName,\n tableStrategy: object.tableStrategy,\n extends: object.extends,\n });\n }\n\n for (const field of object.relationships) {\n if (field.type !== 'crossPackageRef') continue;\n edges.push({\n type: 'crossPackageRef',\n from: id,\n to: resolveTarget(field.related) ?? field.related,\n field: field.name,\n });\n }\n\n if (object.tableStrategy === 'sti' && object.extends) {\n edges.push({\n type: 'sti',\n from: id,\n to:\n resolveTarget(object.extendsQualified) ??\n resolveTarget(object.extends, objectPackageName) ??\n `${objectPackageName}#${object.extends}`,\n });\n }\n\n for (const feature of object.relationshipFeatures) {\n if (feature === 'SmrtJunction') {\n edges.push({ type: 'junction', from: id });\n } else if (feature === 'SmrtHierarchical') {\n edges.push({ type: 'hierarchical', from: id });\n } else if (feature === 'SmrtPolymorphicAssociation') {\n edges.push({ type: 'polymorphic', from: id });\n }\n }\n\n if (object.tableName?.startsWith('_smrt_')) {\n edges.push({ type: 'systemTable', from: id, to: object.tableName });\n }\n }\n }\n\n packages.sort((a, b) => a.name.localeCompare(b.name));\n objects.sort((a, b) => a.id.localeCompare(b.id));\n edges.sort((a, b) => {\n const key = (edge: KnowledgeGraphEdge) =>\n `${edge.type}|${edge.from}|${edge.to ?? ''}|${edge.field ?? ''}`;\n return key(a).localeCompare(key(b));\n });\n\n const graph: SmrtKnowledgeGraph = {\n schemaVersion: 1,\n generatedAt: new Date().toISOString(),\n sourceHashes: sortRecord(sourceHashes),\n packages,\n objects,\n edges,\n };\n\n const { previousGraph } = options;\n if (\n previousGraph &&\n semanticGraphJson(previousGraph) === semanticGraphJson(graph)\n ) {\n return { ...graph, generatedAt: previousGraph.generatedAt };\n }\n return graph;\n}\n\nfunction semanticGraphJson(graph: SmrtKnowledgeGraph): string {\n const { generatedAt: _generatedAt, ...rest } = graph;\n return stableStringify(rest);\n}\n\n/** Deterministic `JSON.stringify` — object keys are sorted at every level. */\nexport function stableStringify(value: unknown): string {\n return JSON.stringify(sortValue(value));\n}\n\nfunction sortValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(sortValue);\n if (value && typeof value === 'object') {\n // Null-prototype target: on an ordinary `{}`, assigning the key\n // `\"__proto__\"` through bracket notation invokes `Object.prototype`'s\n // `__proto__` accessor instead of creating an own property, so that key\n // silently vanishes from the result and `JSON.stringify()` never emits\n // it — two inputs that differ only by an own `\"__proto__\"` key (which\n // `JSON.parse()` does create as a real own property) then serialize\n // identically. An object with no prototype has no such accessor to\n // shadow the assignment, so every own key — including `\"__proto__\"` —\n // becomes a real own data property. `JSON.stringify()` does not care\n // about an object's prototype, only its own enumerable properties, so\n // this changes no other output.\n const sorted: Record<string, unknown> = Object.create(null);\n for (const key of Object.keys(value as Record<string, unknown>).sort()) {\n sorted[key] = sortValue((value as Record<string, unknown>)[key]);\n }\n return sorted;\n }\n return value;\n}\n\nfunction sortRecord(record: Record<string, string>): Record<string, string> {\n const sorted: Record<string, string> = {};\n for (const key of Object.keys(record).sort()) sorted[key] = record[key];\n return sorted;\n}\n\nexport interface KnowledgeGraphFreshnessIssue {\n severity: 'error' | 'warning';\n code:\n | 'missing-knowledge-graph'\n | 'stale-knowledge-graph'\n | 'knowledge-graph-source-missing';\n message: string;\n file?: string;\n}\n\n/**\n * Checks the merged graph's recorded `sourceHashes` against the current\n * content of each per-package artifact it was built from — the same pattern\n * `knowledge.ts`/`smrt-dev-mcp` use for a single package's `sourceHashes`.\n *\n * `graphPath` and each `artifactPath` in the graph are resolved relative to\n * `rootDir` (the repo root).\n */\nexport function checkKnowledgeGraphFreshness(\n rootDir: string,\n graphPath: string,\n options: { requireArtifact?: boolean } = {},\n): KnowledgeGraphFreshnessIssue[] {\n const issues: KnowledgeGraphFreshnessIssue[] = [];\n const absoluteGraphPath = `${rootDir}/${graphPath}`;\n if (!existsSync(absoluteGraphPath)) {\n if (!options.requireArtifact) return issues;\n issues.push({\n severity: 'error',\n code: 'missing-knowledge-graph',\n message: `${graphPath} does not exist; run \\`pnpm knowledge:graph\\``,\n file: graphPath,\n });\n return issues;\n }\n\n let graph: SmrtKnowledgeGraph;\n try {\n graph = JSON.parse(readFileSync(absoluteGraphPath, 'utf8'));\n } catch (error) {\n issues.push({\n severity: 'error',\n code: 'stale-knowledge-graph',\n message: `${graphPath} is not valid JSON: ${\n error instanceof Error ? error.message : String(error)\n }`,\n file: graphPath,\n });\n return issues;\n }\n\n const recordedPaths = Object.keys(graph.sourceHashes ?? {});\n for (const [artifactPath, expectedHash] of Object.entries(\n graph.sourceHashes ?? {},\n )) {\n const absoluteArtifactPath = `${rootDir}/${artifactPath}`;\n if (!existsSync(absoluteArtifactPath)) {\n issues.push({\n severity: 'error',\n code: 'knowledge-graph-source-missing',\n message: `${artifactPath} used to build ${graphPath} no longer exists`,\n file: graphPath,\n });\n continue;\n }\n let manifest: unknown;\n try {\n manifest = JSON.parse(readFileSync(absoluteArtifactPath, 'utf8'));\n } catch (error) {\n issues.push({\n severity: 'error',\n code: 'stale-knowledge-graph',\n message: `${artifactPath} is not valid JSON (${\n error instanceof Error ? error.message : String(error)\n }); run \\`pnpm knowledge:graph\\``,\n file: graphPath,\n });\n continue;\n }\n const actualHash = hashContent(stableStringify(manifest));\n if (actualHash !== expectedHash) {\n issues.push({\n severity: 'error',\n code: 'stale-knowledge-graph',\n message: `${artifactPath} changed since ${graphPath} was generated; run \\`pnpm knowledge:graph\\``,\n file: graphPath,\n });\n }\n }\n\n // A per-key hash comparison alone cannot see an ADDED artifact: a package\n // that just finished its first build, or just started exporting\n // `./smrt-knowledge.json`, contributes a path the graph never recorded, so\n // every recorded hash still matches. Compare the current discoverable SET\n // against the recorded set to catch that (#2863 review).\n const currentPaths = discoverKnowledgeArtifactPaths(rootDir);\n const recordedSet = new Set(recordedPaths);\n const newPaths = currentPaths.filter((path) => !recordedSet.has(path));\n if (newPaths.length > 0) {\n issues.push({\n severity: 'error',\n code: 'stale-knowledge-graph',\n message: `${newPaths.join(', ')} ${\n newPaths.length === 1\n ? 'is a new package artifact'\n : 'are new package artifacts'\n } not yet merged into ${graphPath}; run \\`pnpm knowledge:graph\\``,\n file: graphPath,\n });\n }\n\n return issues;\n}\n"],"mappings":";;;;AAyBO,SAAS,iCACd,kBAC0B;CAC1B,MAAM,WAAqC,CAAC;CAC5C,KAAA,MAAW,kBAAkB,IAAI,IAAI,gBAAgB,GAAG;EACtD,IAAI;EACJ,IAAI;GACF,UAAU,YAAY,gBAAgB,EAAE,eAAe,KAAK,CAAC;EAC/D,QAAQ;GACN;EACF;EACA,KAAA,MAAW,SAAS,SAAS;GAC3B,IAAI,CAAC,MAAM,YAAY,KAAK,CAAC,MAAM,eAAe,GAAG;GACrD,MAAM,YAAY,KAAK,gBAAgB,MAAM,IAAI;GACjD,IAAI;IACF,SAAS,KAAK;KACZ,MAAM,MAAM;KACZ;KACA,eAAe,aAAa,SAAS;IACvC,CAAC;GACH,QAAQ,CAER;EACF;CACF;CACA,OAAO;AACT;AAGO,SAAS,oBACd,WACA,UAAwC,CAAC,GACzC;CACA,MAAM,aAAa,KAAK,WAAW,WAAW;CAC9C,MAAM,aAAa,KAAK,WAAW,WAAW;CAC9C,MAAM,cAAc,WAAW,UAAU;CACzC,MAAM,cAAc,WAAW,UAAU;CACzC,MAAM,gBAAgB,cAAc,aAAa,YAAY,MAAM,IAAI;CACvE,MAAM,gBACJ,gBAAgB,CAAC,eAAe,QAAQ,kBACpC,aAAa,YAAY,MAAM,IAC/B;CACN,MAAM,gBAAgB,eAAe,cAAc,KAAK,MAAM;CAC9D,MAAM,SAA2C,cAC7C,cACA,eAAe,CAAC,gBACd,cACA;CACN,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA,SAAS,cAAc,gBAAgB,SAAS,gBAAgB;CAClE;AACF;AAQA,IAAM,mBACJ;AAGK,IAAM,yBAAyB;AAM/B,IAAM,4BA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MAAM,eAAe,+BAA+B,OAAO;CAC3D,MAAM,cAAc,IAAI,IAAI,aAAa;CACzC,MAAM,WAAW,aAAa,QAAQ,SAAS,CAAC,YAAY,IAAI,IAAI,CAAC;CACrE,IAAI,SAAS,SAAS,GACpB,OAAO,KAAK;EACV,UAAU;EACV,MAAM;EACN,SAAS,GAAG,SAAS,KAAK,IAAI,EAAC,GAC7B,SAAS,WAAW,IAChB,8BACA,4BACN,uBAAwB,UAAS;EACjC,MAAM;CACR,CAAC;CAGH,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"knowledge.js","names":[],"sources":["../src/knowledge-discovery.ts","../src/knowledge-graph.ts"],"sourcesContent":["/** Filesystem-only discovery shared by docs snapshots and knowledge indexing. */\nimport type { Dirent } from 'node:fs';\nimport {\n existsSync,\n readdirSync,\n readFileSync,\n realpathSync,\n statSync,\n} from 'node:fs';\nimport { basename, join, relative, resolve, sep } from 'node:path';\nimport type { DomainKnowledgeModuleDoc } from '@happyvertical/smrt-types';\n\nexport interface ScopedPackageDirectory {\n /** Scope entry name; consumers may select by alias rather than manifest name. */\n name: string;\n /** Original node_modules path, retained for workspace-relative reporting. */\n directory: string;\n /** Resolved path for identity comparisons or absolute snapshot links. */\n realDirectory: string;\n}\n\n/**\n * Enumerate scope entries without descending into pnpm's linked dependency graph.\n * Selection, workspace discovery and enrichment remain caller policies.\n */\nexport function discoverScopedPackageDirectories(\n scopeDirectories: string[],\n): ScopedPackageDirectory[] {\n const packages: ScopedPackageDirectory[] = [];\n for (const scopeDirectory of new Set(scopeDirectories)) {\n let entries: Dirent[];\n try {\n entries = readdirSync(scopeDirectory, { withFileTypes: true });\n } catch {\n continue;\n }\n for (const entry of entries) {\n if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;\n const directory = join(scopeDirectory, entry.name);\n try {\n packages.push({\n name: entry.name,\n directory,\n realDirectory: realpathSync(directory),\n });\n } catch {\n // Dangling links are not installed packages.\n }\n }\n }\n return packages;\n}\n\n/** Read authored docs only; never load artifacts, package code or object scans. */\nexport function readPackageAgentDoc(\n directory: string,\n options: { inspectAdapter?: boolean } = {},\n) {\n const agentsPath = join(directory, 'AGENTS.md');\n const claudePath = join(directory, 'CLAUDE.md');\n const hasAgentsMd = existsSync(agentsPath);\n const hasClaudeMd = existsSync(claudePath);\n const agentsContent = hasAgentsMd ? readFileSync(agentsPath, 'utf8') : '';\n const claudeContent =\n hasClaudeMd && (!hasAgentsMd || options.inspectAdapter)\n ? readFileSync(claudePath, 'utf8')\n : '';\n const hasClaudeShim = hasClaudeMd && claudeContent.trim() === '@AGENTS.md';\n const source: 'AGENTS.md' | 'CLAUDE.md' | null = hasAgentsMd\n ? 'AGENTS.md'\n : hasClaudeMd && !hasClaudeShim\n ? 'CLAUDE.md'\n : null;\n return {\n hasAgentsMd,\n hasClaudeMd,\n hasClaudeShim,\n agentsContent,\n claudeContent,\n source,\n content: hasAgentsMd ? agentsContent : source ? claudeContent : null,\n };\n}\n\n/**\n * Markdown inline links whose target is a `.md` file — `[label](agents/x.md)`,\n * tolerating an `#anchor` and a `\"title\"`. This is how a package registers a\n * sibling module doc (#2108): the link in `AGENTS.md` IS the registration, so\n * there is no separate index to drift out of sync.\n */\nconst MARKDOWN_MD_LINK =\n /\\[[^\\]]*\\]\\(\\s*([^)\\s#]+\\.md)(?:#[^)\\s]*)?(?:\\s+\"[^\"]*\")?\\s*\\)/g;\n\n/** `sourceHashes` key prefix for a linked module doc, e.g. `moduleDoc:agents/crm.md`. */\nexport const MODULE_DOC_HASH_PREFIX = 'moduleDoc:';\n\n/**\n * `sourceHashes` key prefix for a module declaring a view intent or playbook,\n * e.g. `agentSurface:src/lib/orders.intents.ts` (#2591).\n */\nexport const AGENT_SURFACE_HASH_PREFIX = 'agentSurface:';\n\n/**\n * Module doc paths linked from a package's `AGENTS.md`, relative to the package\n * root and in document order.\n *\n * Instruction chains are additive (see `scripts/check-agents-chain.mjs`), so an\n * oversized package doc is split into `packages/<pkg>/agents/<module>.md` siblings\n * instead of nested `AGENTS.md` files. Only links resolving to an existing file\n * INSIDE the package are accepted — a cross-package reference such as\n * `packages/affiliates/MIGRATION.md` belongs to that package's own chain and is\n * ignored here.\n */\nexport function resolveAgentModuleDocPaths(\n rootDir: string,\n agentDoc: string | undefined,\n): string[] {\n if (!agentDoc) return [];\n const root = resolve(rootDir);\n const paths: string[] = [];\n for (const match of agentDoc.matchAll(MARKDOWN_MD_LINK)) {\n const target = match[1];\n if (target.includes('://')) continue;\n const absolute = resolve(root, target);\n if (absolute !== root && !absolute.startsWith(root + sep)) continue;\n const relativePath = relative(root, absolute).split(sep).join('/');\n if (relativePath === 'AGENTS.md' || relativePath === 'CLAUDE.md') continue;\n if (paths.includes(relativePath)) continue;\n if (!existsSync(absolute) || !statSync(absolute).isFile()) continue;\n paths.push(relativePath);\n }\n return paths;\n}\n\n/** {@link resolveAgentModuleDocPaths}, with each doc's contents read. */\nexport function readAgentModuleDocs(\n rootDir: string,\n agentDoc: string | undefined,\n): DomainKnowledgeModuleDoc[] {\n return resolveAgentModuleDocPaths(rootDir, agentDoc).map((path) => ({\n path,\n module: basename(path, '.md'),\n content: readFileSync(join(rootDir, path), 'utf8'),\n }));\n}\n","/**\n * Cross-package knowledge graph (#2863).\n *\n * Each package's own `smrt-knowledge.json` (see `knowledge.ts`) is a\n * per-package projection. Nothing merges them, so cross-package invariants\n * that the scanner manifest already carries — `@crossPackageRef` targets, STI\n * parent/child pairs, junction/hierarchical/polymorphic base usage, and\n * `_smrt_` system-table ownership — live only as prose in the root\n * `AGENTS.md`. This module builds the merged, deterministic root artifact\n * (`.smrt/smrt-knowledge-graph.json`) from whichever per-package artifacts\n * are present, and checks it for staleness the same way `knowledge.ts` checks\n * a package artifact: by comparing recorded `sourceHashes` against the\n * current file content.\n *\n * This module never invents an edge: every edge is a direct read of a field\n * already emitted into a package's `DomainKnowledgeManifest` (`related`,\n * `tableStrategy`, `extends`, `relationshipFeatures`, `tableName`).\n */\n\nimport { createHash } from 'node:crypto';\nimport { existsSync, readdirSync, readFileSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport type {\n DomainKnowledgeManifest,\n DomainKnowledgeObject,\n} from '@happyvertical/smrt-types';\n\n/**\n * Discovers every currently-buildable per-package artifact path under\n * `<rootDir>/packages/*`, preferring the published `dist/smrt-knowledge.json`\n * over the local dev `.smrt/smrt-knowledge.json` when both exist. Shared by\n * the generator (which needs the manifest content) and the freshness check\n * (which only needs to know whether the current SET of artifacts matches\n * what the graph was built from — a newly built package, or a package that\n * newly started exporting `./smrt-knowledge.json`, must mark the graph stale\n * even though every artifact the graph already knows about is unchanged).\n */\nexport function discoverKnowledgeArtifactPaths(rootDir: string): string[] {\n const packagesDir = join(rootDir, 'packages');\n if (!existsSync(packagesDir)) return [];\n const paths: string[] = [];\n for (const entry of readdirSync(packagesDir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const packageDir = join(packagesDir, entry.name);\n const candidates = [\n join(packageDir, 'dist', 'smrt-knowledge.json'),\n join(packageDir, '.smrt', 'smrt-knowledge.json'),\n ];\n const found = candidates.find((path) => existsSync(path));\n if (found) paths.push(relative(rootDir, found).split('\\\\').join('/'));\n }\n return paths.sort();\n}\n\n/** One package's `smrt-knowledge.json`, located relative to the graph root. */\nexport interface KnowledgeGraphInput {\n /** Path to the artifact, relative to the repo root, POSIX-separated. */\n artifactPath: string;\n manifest: DomainKnowledgeManifest;\n}\n\nexport interface KnowledgeGraphPackageNode {\n name: string;\n version?: string;\n artifactPath: string;\n tags: string[];\n risks: string[];\n summary?: string;\n objectCount: number;\n}\n\nexport interface KnowledgeGraphObjectNode {\n /** `<packageName>#<qualifiedName-or-name>`, this graph's stable object id. */\n id: string;\n packageName: string;\n name: string;\n qualifiedName?: string;\n collection: string;\n tableName?: string;\n tableStrategy?: 'cti' | 'sti';\n extends?: string;\n}\n\nexport type KnowledgeGraphEdgeType =\n | 'crossPackageRef'\n | 'sti'\n | 'junction'\n | 'hierarchical'\n | 'polymorphic'\n | 'systemTable';\n\nexport interface KnowledgeGraphEdge {\n type: KnowledgeGraphEdgeType;\n /** Object id (or `<packageName>#<extends>`-style unresolved target) this edge starts from. */\n from: string;\n /**\n * Object id the edge points to when resolvable against a scanned object;\n * otherwise the raw declared target (e.g. a qualified name this run did\n * not scan), so the edge is still readable rather than dropped.\n */\n to?: string;\n /** Declaring field name, for `crossPackageRef` edges. */\n field?: string;\n}\n\nexport interface SmrtKnowledgeGraph {\n schemaVersion: 1;\n generatedAt: string;\n /** `artifactPath -> sha256(content)`, sorted by key; the freshness input. */\n sourceHashes: Record<string, string>;\n packages: KnowledgeGraphPackageNode[];\n objects: KnowledgeGraphObjectNode[];\n edges: KnowledgeGraphEdge[];\n}\n\nfunction hashContent(content: string): string {\n return createHash('sha256').update(content).digest('hex');\n}\n\nfunction objectId(packageName: string, object: DomainKnowledgeObject): string {\n return `${packageName}#${object.qualifiedName ?? object.name}`;\n}\n\nexport interface BuildKnowledgeGraphOptions {\n /**\n * The graph currently on disk, when regenerating. `generatedAt` is\n * preserved from it rather than reset to the clock whenever the rebuilt\n * graph is otherwise semantically identical — the same pattern\n * `preserveKnowledgeGeneratedAt` uses for per-package artifacts\n * (`packages/core/src/vite-plugin/index.ts`) — so re-running the generator\n * with nothing merged actually changed does not churn the file (#2872\n * review).\n */\n previousGraph?: SmrtKnowledgeGraph;\n}\n\n/** Builds the merged graph. Deterministic: every array is sorted. */\nexport function buildKnowledgeGraph(\n inputs: KnowledgeGraphInput[],\n options: BuildKnowledgeGraphOptions = {},\n): SmrtKnowledgeGraph {\n const sortedInputs = [...inputs].sort((a, b) =>\n a.artifactPath.localeCompare(b.artifactPath),\n );\n\n const sourceHashes: Record<string, string> = {};\n const packages: KnowledgeGraphPackageNode[] = [];\n const objects: KnowledgeGraphObjectNode[] = [];\n const edges: KnowledgeGraphEdge[] = [];\n\n // Qualified-name -> object id, so a crossPackageRef/STI target declared in\n // one package can be resolved to the node emitted by whichever package\n // scanned it, regardless of scan order.\n const idByQualifiedName = new Map<string, string>();\n // Distinct ids per simple name, not a plain array: the same external\n // object can appear in more than one input (e.g. a package artifact and a\n // smrtConsumer aggregate that also scanned it), and counting the\n // duplicate would make resolveTarget's `.length === 1` uniqueness check\n // see a false ambiguity for an otherwise-unique name (#2872 review).\n const idBySimpleName = new Map<string, Set<string>>();\n // A `tableStrategy: 'sti'` object's `extends` is an unqualified simple name;\n // a parent imported from another package also carries `extendsQualified`\n // (#4145), which resolves first. Otherwise a same-package simple-name match\n // must win over an ambiguous or wrong-package GLOBAL simple-name match:\n // two packages both declaring `Account` must not point one package's\n // subclass at the other package's `Account` (#2863 review).\n const idBySimpleNamePerPackage = new Map<string, Map<string, string>>();\n const aliasIds: Array<[string, string]> = [];\n\n for (const input of sortedInputs) {\n const manifestPackageName =\n input.manifest.packageName ?? input.artifactPath;\n for (const object of input.manifest.objects) {\n // A merged consumer manifest (`smrtConsumer`) aggregates objects\n // scanned from multiple external packages under one local artifact;\n // each object then carries its own `packageName` and that must own\n // the id, or every external object misattributes to the local\n // project and edges resolve to the wrong node (#2872 review).\n const packageName = object.packageName ?? manifestPackageName;\n const perPackage =\n idBySimpleNamePerPackage.get(packageName) ?? new Map<string, string>();\n const id = objectId(packageName, object);\n idByQualifiedName.set(object.qualifiedName ?? id, id);\n const bySimple = idBySimpleName.get(object.name) ?? new Set<string>();\n bySimple.add(id);\n idBySimpleName.set(object.name, bySimple);\n perPackage.set(object.name, id);\n idBySimpleNamePerPackage.set(packageName, perPackage);\n for (const alias of object.previousQualifiedNames ?? []) {\n aliasIds.push([alias, id]);\n }\n }\n }\n // A moved object's deprecated qualified names (#3338) resolve to it, but\n // never shadow a live object's own qualified name. Ownership is tracked\n // separately so two distinct objects claiming one old name fail the build,\n // as the runtime registry refuses them, instead of the first in sort order\n // silently winning; the same object repeated across artifacts is one claim.\n const aliasOwners = new Map<string, Set<string>>();\n for (const [alias, id] of aliasIds) {\n const owners = aliasOwners.get(alias) ?? new Set<string>();\n owners.add(id);\n aliasOwners.set(alias, owners);\n }\n for (const [alias, owners] of aliasOwners) {\n if (owners.size > 1) {\n throw new Error(\n `[knowledge-graph] previousQualifiedNames \"${alias}\" is claimed by more than one object: ` +\n `${[...owners].sort().join(', ')}. An old qualified name can resolve to only one class; ` +\n 'remove the alias from all but one owner.',\n );\n }\n if (!idByQualifiedName.has(alias)) {\n idByQualifiedName.set(alias, [...owners][0]);\n }\n }\n\n const resolveTarget = (\n raw: string | undefined,\n declaringPackageName?: string,\n ): string | undefined => {\n if (!raw) return undefined;\n if (idByQualifiedName.has(raw)) return idByQualifiedName.get(raw);\n if (declaringPackageName) {\n const sameId = idBySimpleNamePerPackage\n .get(declaringPackageName)\n ?.get(raw);\n if (sameId) return sameId;\n }\n const bySimple = idBySimpleName.get(raw);\n if (bySimple && bySimple.size === 1) return [...bySimple][0];\n return undefined;\n };\n\n const seenObjectIds = new Set<string>();\n for (const input of sortedInputs) {\n sourceHashes[input.artifactPath] = hashContent(\n stableStringify(input.manifest),\n );\n const packageName = input.manifest.packageName ?? input.artifactPath;\n\n packages.push({\n name: packageName,\n version: input.manifest.packageVersion,\n artifactPath: input.artifactPath,\n tags: [...input.manifest.tags].sort(),\n risks: [...input.manifest.risks].sort(),\n summary: input.manifest.summary,\n objectCount: input.manifest.objects.length,\n });\n\n for (const object of input.manifest.objects) {\n // See the id-map pass above: an aggregated consumer manifest attributes\n // each object to its own scanned package, not the local project.\n const objectPackageName = object.packageName ?? packageName;\n const id = objectId(objectPackageName, object);\n if (!seenObjectIds.has(id)) {\n seenObjectIds.add(id);\n objects.push({\n id,\n packageName: objectPackageName,\n name: object.name,\n qualifiedName: object.qualifiedName,\n collection: object.collection,\n tableName: object.tableName,\n tableStrategy: object.tableStrategy,\n extends: object.extends,\n });\n }\n\n for (const field of object.relationships) {\n if (field.type !== 'crossPackageRef') continue;\n edges.push({\n type: 'crossPackageRef',\n from: id,\n to: resolveTarget(field.related) ?? field.related,\n field: field.name,\n });\n }\n\n if (object.tableStrategy === 'sti' && object.extends) {\n edges.push({\n type: 'sti',\n from: id,\n to:\n resolveTarget(object.extendsQualified) ??\n resolveTarget(object.extends, objectPackageName) ??\n `${objectPackageName}#${object.extends}`,\n });\n }\n\n for (const feature of object.relationshipFeatures) {\n if (feature === 'SmrtJunction') {\n edges.push({ type: 'junction', from: id });\n } else if (feature === 'SmrtHierarchical') {\n edges.push({ type: 'hierarchical', from: id });\n } else if (feature === 'SmrtPolymorphicAssociation') {\n edges.push({ type: 'polymorphic', from: id });\n }\n }\n\n if (object.tableName?.startsWith('_smrt_')) {\n edges.push({ type: 'systemTable', from: id, to: object.tableName });\n }\n }\n }\n\n packages.sort((a, b) => a.name.localeCompare(b.name));\n objects.sort((a, b) => a.id.localeCompare(b.id));\n edges.sort((a, b) => {\n const key = (edge: KnowledgeGraphEdge) =>\n `${edge.type}|${edge.from}|${edge.to ?? ''}|${edge.field ?? ''}`;\n return key(a).localeCompare(key(b));\n });\n\n const graph: SmrtKnowledgeGraph = {\n schemaVersion: 1,\n generatedAt: new Date().toISOString(),\n sourceHashes: sortRecord(sourceHashes),\n packages,\n objects,\n edges,\n };\n\n const { previousGraph } = options;\n if (\n previousGraph &&\n semanticGraphJson(previousGraph) === semanticGraphJson(graph)\n ) {\n return { ...graph, generatedAt: previousGraph.generatedAt };\n }\n return graph;\n}\n\nfunction semanticGraphJson(graph: SmrtKnowledgeGraph): string {\n const { generatedAt: _generatedAt, ...rest } = graph;\n return stableStringify(rest);\n}\n\n/** Deterministic `JSON.stringify` — object keys are sorted at every level. */\nexport function stableStringify(value: unknown): string {\n return JSON.stringify(sortValue(value));\n}\n\nfunction sortValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(sortValue);\n if (value && typeof value === 'object') {\n // Null-prototype target: on an ordinary `{}`, assigning the key\n // `\"__proto__\"` through bracket notation invokes `Object.prototype`'s\n // `__proto__` accessor instead of creating an own property, so that key\n // silently vanishes from the result and `JSON.stringify()` never emits\n // it — two inputs that differ only by an own `\"__proto__\"` key (which\n // `JSON.parse()` does create as a real own property) then serialize\n // identically. An object with no prototype has no such accessor to\n // shadow the assignment, so every own key — including `\"__proto__\"` —\n // becomes a real own data property. `JSON.stringify()` does not care\n // about an object's prototype, only its own enumerable properties, so\n // this changes no other output.\n const sorted: Record<string, unknown> = Object.create(null);\n for (const key of Object.keys(value as Record<string, unknown>).sort()) {\n sorted[key] = sortValue((value as Record<string, unknown>)[key]);\n }\n return sorted;\n }\n return value;\n}\n\nfunction sortRecord(record: Record<string, string>): Record<string, string> {\n const sorted: Record<string, string> = {};\n for (const key of Object.keys(record).sort()) sorted[key] = record[key];\n return sorted;\n}\n\nexport interface KnowledgeGraphFreshnessIssue {\n severity: 'error' | 'warning';\n code:\n | 'missing-knowledge-graph'\n | 'stale-knowledge-graph'\n | 'knowledge-graph-source-missing';\n message: string;\n file?: string;\n}\n\n/**\n * Checks the merged graph's recorded `sourceHashes` against the current\n * content of each per-package artifact it was built from — the same pattern\n * `knowledge.ts`/`smrt-dev-mcp` use for a single package's `sourceHashes`.\n *\n * `graphPath` and each `artifactPath` in the graph are resolved relative to\n * `rootDir` (the repo root).\n */\nexport function checkKnowledgeGraphFreshness(\n rootDir: string,\n graphPath: string,\n options: { requireArtifact?: boolean } = {},\n): KnowledgeGraphFreshnessIssue[] {\n const issues: KnowledgeGraphFreshnessIssue[] = [];\n const absoluteGraphPath = `${rootDir}/${graphPath}`;\n if (!existsSync(absoluteGraphPath)) {\n if (!options.requireArtifact) return issues;\n issues.push({\n severity: 'error',\n code: 'missing-knowledge-graph',\n message: `${graphPath} does not exist; run \\`pnpm knowledge:graph\\``,\n file: graphPath,\n });\n return issues;\n }\n\n let graph: SmrtKnowledgeGraph;\n try {\n graph = JSON.parse(readFileSync(absoluteGraphPath, 'utf8'));\n } catch (error) {\n issues.push({\n severity: 'error',\n code: 'stale-knowledge-graph',\n message: `${graphPath} is not valid JSON: ${\n error instanceof Error ? error.message : String(error)\n }`,\n file: graphPath,\n });\n return issues;\n }\n\n const isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n const graphValue: unknown = graph;\n // A graph without `sourceHashes` records no artifacts (as before #3075);\n // only shapes that used to throw are reported as malformed.\n const sourceHashesValue = isPlainObject(graphValue)\n ? (graphValue.sourceHashes ?? {})\n : undefined;\n if (\n !isPlainObject(graphValue) ||\n !isPlainObject(sourceHashesValue) ||\n Object.values(sourceHashesValue).some((hash) => typeof hash !== 'string')\n ) {\n issues.push({\n severity: 'error',\n code: 'stale-knowledge-graph',\n message: `${graphPath} is malformed (expected an object with a \\`sourceHashes\\` map of string hashes); run \\`pnpm knowledge:graph\\``,\n file: graphPath,\n });\n return issues;\n }\n\n const sourceHashes = sourceHashesValue as Record<string, string>;\n const recordedPaths = Object.keys(sourceHashes);\n for (const [artifactPath, expectedHash] of Object.entries(sourceHashes)) {\n const absoluteArtifactPath = `${rootDir}/${artifactPath}`;\n if (!existsSync(absoluteArtifactPath)) {\n issues.push({\n severity: 'error',\n code: 'knowledge-graph-source-missing',\n message: `${artifactPath} used to build ${graphPath} no longer exists`,\n file: graphPath,\n });\n continue;\n }\n let manifest: unknown;\n try {\n manifest = JSON.parse(readFileSync(absoluteArtifactPath, 'utf8'));\n } catch (error) {\n issues.push({\n severity: 'error',\n code: 'stale-knowledge-graph',\n message: `${artifactPath} is not valid JSON (${\n error instanceof Error ? error.message : String(error)\n }); run \\`pnpm knowledge:graph\\``,\n file: graphPath,\n });\n continue;\n }\n const actualHash = hashContent(stableStringify(manifest));\n if (actualHash !== expectedHash) {\n issues.push({\n severity: 'error',\n code: 'stale-knowledge-graph',\n message: `${artifactPath} changed since ${graphPath} was generated; run \\`pnpm knowledge:graph\\``,\n file: graphPath,\n });\n }\n }\n\n // A per-key hash comparison alone cannot see an ADDED artifact: a package\n // that just finished its first build, or just started exporting\n // `./smrt-knowledge.json`, contributes a path the graph never recorded, so\n // every recorded hash still matches. Compare the current discoverable SET\n // against the recorded set to catch that (#2863 review).\n const currentPaths = discoverKnowledgeArtifactPaths(rootDir);\n const recordedSet = new Set(recordedPaths);\n const newPaths = currentPaths.filter((path) => !recordedSet.has(path));\n if (newPaths.length > 0) {\n issues.push({\n severity: 'error',\n code: 'stale-knowledge-graph',\n message: `${newPaths.join(', ')} ${\n newPaths.length === 1\n ? 'is a new package artifact'\n : 'are new package artifacts'\n } not yet merged into ${graphPath}; run \\`pnpm knowledge:graph\\``,\n file: graphPath,\n });\n }\n\n return issues;\n}\n"],"mappings":";;;;AAyBO,SAAS,iCACd,kBAC0B;CAC1B,MAAM,WAAqC,CAAC;CAC5C,KAAA,MAAW,kBAAkB,IAAI,IAAI,gBAAgB,GAAG;EACtD,IAAI;EACJ,IAAI;GACF,UAAU,YAAY,gBAAgB,EAAE,eAAe,KAAK,CAAC;EAC/D,QAAQ;GACN;EACF;EACA,KAAA,MAAW,SAAS,SAAS;GAC3B,IAAI,CAAC,MAAM,YAAY,KAAK,CAAC,MAAM,eAAe,GAAG;GACrD,MAAM,YAAY,KAAK,gBAAgB,MAAM,IAAI;GACjD,IAAI;IACF,SAAS,KAAK;KACZ,MAAM,MAAM;KACZ;KACA,eAAe,aAAa,SAAS;IACvC,CAAC;GACH,QAAQ,CAER;EACF;CACF;CACA,OAAO;AACT;AAGO,SAAS,oBACd,WACA,UAAwC,CAAC,GACzC;CACA,MAAM,aAAa,KAAK,WAAW,WAAW;CAC9C,MAAM,aAAa,KAAK,WAAW,WAAW;CAC9C,MAAM,cAAc,WAAW,UAAU;CACzC,MAAM,cAAc,WAAW,UAAU;CACzC,MAAM,gBAAgB,cAAc,aAAa,YAAY,MAAM,IAAI;CACvE,MAAM,gBACJ,gBAAgB,CAAC,eAAe,QAAQ,kBACpC,aAAa,YAAY,MAAM,IAC/B;CACN,MAAM,gBAAgB,eAAe,cAAc,KAAK,MAAM;CAC9D,MAAM,SAA2C,cAC7C,cACA,eAAe,CAAC,gBACd,cACA;CACN,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA,SAAS,cAA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UAAU;IACV,MAAM;IACN,SAAS,GAAG,aAAY,iBAAkB,UAAS;IACnD,MAAM;GACR,CAAC;GACD;EACF;EACA,IAAI;EACJ,IAAI;GACF,WAAW,KAAK,MAAM,aAAa,sBAAsB,MAAM,CAAC;EAClE,SAAS,OAAO;GACd,OAAO,KAAK;IACV,UAAU;IACV,MAAM;IACN,SAAS,GAAG,aAAY,sBACtB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EACvD;IACA,MAAM;GACR,CAAC;GACD;EACF;EAEA,IADmB,YAAY,gBAAgB,QAAQ,CACnD,MAAe,cACjB,OAAO,KAAK;GACV,UAAU;GACV,MAAM;GACN,SAAS,GAAG,aAAY,iBAAkB,UAAS;GACnD,MAAM;EACR,CAAC;CAEL;CAOA,MAAM,eAAe,+BAA+B,OAAO;CAC3D,MAAM,cAAc,IAAI,IAAI,aAAa;CACzC,MAAM,WAAW,aAAa,QAAQ,SAAS,CAAC,YAAY,IAAI,IAAI,CAAC;CACrE,IAAI,SAAS,SAAS,GACpB,OAAO,KAAK;EACV,UAAU;EACV,MAAM;EACN,SAAS,GAAG,SAAS,KAAK,IAAI,EAAC,GAC7B,SAAS,WAAW,IAChB,8BACA,4BACN,uBAAwB,UAAS;EACjC,MAAM;CACR,CAAC;CAGH,OAAO;AACT"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@happyvertical/smrt-scanner",
|
|
3
|
-
"version": "0.57.
|
|
3
|
+
"version": "0.57.38",
|
|
4
4
|
"description": "High-performance TypeScript scanner using OXC for SMRT manifest generation",
|
|
5
5
|
"author": "HappyVertical",
|
|
6
6
|
"type": "module",
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
}
|
|
35
35
|
},
|
|
36
36
|
"dependencies": {
|
|
37
|
-
"@happyvertical/smrt-types": "0.57.
|
|
37
|
+
"@happyvertical/smrt-types": "0.57.38",
|
|
38
38
|
"minimatch": "10.2.6",
|
|
39
39
|
"oxc-parser": "^0.150.0",
|
|
40
40
|
"oxc-resolver": "^11.24.2",
|