@happyvertical/smrt-core 0.43.10 → 0.44.0
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/generators.md +70 -0
- package/agents/schema-paths.md +99 -0
- package/dist/generators/custom-action.d.ts.map +1 -1
- package/dist/generators/custom-action.js +1 -1
- package/dist/generators/custom-action.js.map +1 -1
- package/dist/index.js +2 -2
- package/dist/knowledge.d.ts +17 -1
- package/dist/knowledge.d.ts.map +1 -1
- package/dist/knowledge.js +33 -3
- package/dist/knowledge.js.map +1 -1
- package/dist/manifest/static-manifest.js +1 -1
- package/dist/manifest/static-manifest.js.map +1 -1
- package/dist/manifest/store.js +1 -1
- package/dist/manifest.json +1 -1
- package/dist/migrations/differ.d.ts +49 -0
- package/dist/migrations/differ.d.ts.map +1 -1
- package/dist/migrations/differ.js +220 -4
- package/dist/migrations/differ.js.map +1 -1
- package/dist/migrations/orchestrate.d.ts +23 -0
- package/dist/migrations/orchestrate.d.ts.map +1 -1
- package/dist/migrations/orchestrate.js +12 -3
- package/dist/migrations/orchestrate.js.map +1 -1
- package/dist/registry/types.d.ts +8 -3
- package/dist/registry/types.d.ts.map +1 -1
- package/dist/schema/foreign-key-ddl.d.ts +7 -0
- package/dist/schema/foreign-key-ddl.d.ts.map +1 -1
- package/dist/schema/foreign-key-ddl.js +7 -1
- package/dist/schema/foreign-key-ddl.js.map +1 -1
- package/dist/schema/schema-manager.d.ts +15 -0
- package/dist/schema/schema-manager.d.ts.map +1 -1
- package/dist/schema/schema-manager.js +52 -9
- package/dist/schema/schema-manager.js.map +1 -1
- package/dist/schema/types.d.ts +10 -0
- package/dist/schema/types.d.ts.map +1 -1
- package/dist/schema/uuid-convergence.d.ts +142 -0
- package/dist/schema/uuid-convergence.d.ts.map +1 -0
- package/dist/schema/uuid-convergence.js +0 -0
- package/dist/schema/uuid-convergence.js.map +1 -0
- package/dist/smrt-knowledge.json +7 -7
- package/dist/utils/scanner-module.d.ts +44 -0
- package/dist/utils/scanner-module.d.ts.map +1 -1
- package/dist/vite-plugin/index.d.ts +14 -1
- package/dist/vite-plugin/index.d.ts.map +1 -1
- package/dist/vite-plugin/index.js +54 -2
- package/dist/vite-plugin/index.js.map +1 -1
- package/dist/vite-plugin.js +3 -2
- package/package.json +4 -4
package/agents/generators.md
CHANGED
|
@@ -63,6 +63,76 @@ requested path rather than a hardcoded `index.js`.
|
|
|
63
63
|
Generated code also has to be valid in an ES module: `arguments` is not a legal
|
|
64
64
|
binding name there, however convenient it reads.
|
|
65
65
|
|
|
66
|
+
## Emitted agent surface (#2591)
|
|
67
|
+
|
|
68
|
+
Generated model tools have always been build-time artifacts — virtual module,
|
|
69
|
+
manifest, knowledge graph. View intents (#2588) and playbooks (#2589) existed
|
|
70
|
+
only once something mounted, so "what can an agent do in this app" had no answer
|
|
71
|
+
short of enumerating every route. This closes that.
|
|
72
|
+
|
|
73
|
+
The same OXC scan that builds the manifest also runs the scanner's
|
|
74
|
+
agent-surface matcher (`ScanResults.agentSurface`). `smrtPlugin()` captures it
|
|
75
|
+
in `scanWithOxc`, projects it with `toKnowledgeAgentSurface`, and passes it to
|
|
76
|
+
`buildDomainKnowledgeManifest` as `agentSurface`. Note that declaration
|
|
77
|
+
discovery is NOT bound to the plugin's `include` glob — an app that scans
|
|
78
|
+
`src/lib/objects/**` for models still has its `src/lib/agent/*.intents.ts`
|
|
79
|
+
sidecars found (see `packages/scanner/AGENTS.md`). Two more consequences worth
|
|
80
|
+
holding onto:
|
|
81
|
+
|
|
82
|
+
- **It never touches `manifest.json`.** The runtime manifest stays
|
|
83
|
+
runtime-focused; the agent-addressable surface is an agent/developer contract,
|
|
84
|
+
so it lands in `.smrt/smrt-knowledge.json` and `dist/smrt-knowledge.json`
|
|
85
|
+
only, under `agentSurface: { intents, playbooks, diagnostics }`.
|
|
86
|
+
- **It is passed in, not scanned in `knowledge.ts`.** The scanner carries a
|
|
87
|
+
native parser binary and `smrt-core`'s main entry is browser-reachable, so
|
|
88
|
+
core's sync knowledge builder must not import it. The Vite plugin already
|
|
89
|
+
imports the scanner lazily on the Node side and is the only caller that writes
|
|
90
|
+
this artifact.
|
|
91
|
+
|
|
92
|
+
The field is **omitted entirely** when a package declares nothing, which is what
|
|
93
|
+
makes it additive in practice rather than only on paper: every existing
|
|
94
|
+
package's checked-in artifact stays byte-identical.
|
|
95
|
+
|
|
96
|
+
Each declaring module gets a `sourceHashes` entry under the
|
|
97
|
+
`agentSurface:<package-relative path>` prefix (`AGENT_SURFACE_HASH_PREFIX`), so
|
|
98
|
+
EDITING an intent sidecar marks the artifact stale exactly like editing
|
|
99
|
+
`AGENTS.md` does (`stale-domain-knowledge`).
|
|
100
|
+
|
|
101
|
+
Hashes alone cannot see an **added** declaration, though: a brand-new sidecar
|
|
102
|
+
has no recorded hash to mismatch, the runtime manifest never carries intents,
|
|
103
|
+
and `AGENTS.md` is untouched — so every other signal stays green while the
|
|
104
|
+
artifact omits a real operation. `dev:knowledge-check` therefore also re-derives
|
|
105
|
+
the declaration SET from source and compares it to the artifact by identity,
|
|
106
|
+
reporting either direction as `stale-agent-surface`. The scan is bounded like
|
|
107
|
+
the numeric-precision lint: `src` only, behind the scanner's token pre-filter.
|
|
108
|
+
|
|
109
|
+
That re-derivation must model what the EMITTER sees, not merely what is on
|
|
110
|
+
disk, or it reports drift no rebuild can clear. Which files count is decided by
|
|
111
|
+
the scanner's exported `isAgentSurfaceSourcePath` — the same predicate the
|
|
112
|
+
emitter itself uses, never a list copied into the checker — and the per-file
|
|
113
|
+
results run through `mergeAgentSurfaces` before comparing, because the merge is
|
|
114
|
+
where a duplicate identity and a derived tool-name collision are resolved and
|
|
115
|
+
the artifact is the merged result.
|
|
116
|
+
Diagnostics are compared alongside identities: a sidecar containing only a
|
|
117
|
+
computed declaration adds no identity and has no prior hash, so without that,
|
|
118
|
+
"a diagnostic, never silence" would quietly become "a diagnostic, until the
|
|
119
|
+
artifact goes stale". The walk covers `<pkg>/src` while the emitter globs the
|
|
120
|
+
whole project root, so an emitted entry from outside `src` is not reported as
|
|
121
|
+
missing — this check did not look there, and claiming otherwise would be an
|
|
122
|
+
error nothing could clear.
|
|
123
|
+
|
|
124
|
+
Both `stale-*` codes are warnings by default and errors under `--strict`, which
|
|
125
|
+
is what CI runs. Alongside them: `agent-surface-missing-identity`,
|
|
126
|
+
`agent-surface-duplicate-identity`, and `agent-surface-empty-playbook` are
|
|
127
|
+
errors, and `agent-surface-not-static` is a warning. A cross-file duplicate
|
|
128
|
+
arrives as a *diagnostic* rather than two entries — the scanner's merge already
|
|
129
|
+
dropped the loser — so that diagnostic maps to the duplicate error rather than
|
|
130
|
+
the not-static warning; otherwise the error would be unreachable for the case it
|
|
131
|
+
exists to catch.
|
|
132
|
+
|
|
133
|
+
`smrt doctor` prints the whole surface — model tools, intents, playbooks — from
|
|
134
|
+
these artifacts alone, with no application running.
|
|
135
|
+
|
|
66
136
|
## Custom-action contract
|
|
67
137
|
|
|
68
138
|
`resolveCustomActionMetadata()` is the common discovery and invocation contract
|
package/agents/schema-paths.md
CHANGED
|
@@ -715,6 +715,105 @@ SQLite requires a deliberate table rebuild; DuckDB reports the unsupported ALTER
|
|
|
715
715
|
path. Neither engine treats an unsupported constraint addition as a successful
|
|
716
716
|
no-op.
|
|
717
717
|
|
|
718
|
+
### Pre-R11 `text` ids converge to `uuid` before any FK statement (#2608)
|
|
719
|
+
|
|
720
|
+
R11 made SMRT identifiers and references native `uuid` on PostgreSQL. A
|
|
721
|
+
database created before that change still stores its `id` columns as `text`
|
|
722
|
+
while every reference column added afterwards materializes as `uuid`.
|
|
723
|
+
PostgreSQL cannot implement a foreign key across two different physical types —
|
|
724
|
+
FK DDL admits no cast — so `ADD CONSTRAINT … NOT VALID` fails with SQLSTATE
|
|
725
|
+
42804 and aborts every later statement in the same migration batch.
|
|
726
|
+
|
|
727
|
+
Two rails handle it, and both are PostgreSQL-only. SQLite stores UUIDs as text
|
|
728
|
+
by design and DuckDB cannot rewrite a column type in place, so neither engine
|
|
729
|
+
emits anything for this drift.
|
|
730
|
+
|
|
731
|
+
**The runtime guard fails closed.** `SchemaManager.ensurePostgresForeignKey()`
|
|
732
|
+
reads both live column types and refuses to emit `ADD CONSTRAINT` when they
|
|
733
|
+
disagree, naming both columns, both live types, and the repair. It deliberately
|
|
734
|
+
skips the orphan probe in that case: across mismatched types the probe answers
|
|
735
|
+
a question about casted values, not about the constraint being refused, and it
|
|
736
|
+
has to run again after the columns converge anyway.
|
|
737
|
+
|
|
738
|
+
**The differ converges the columns.** `planUuidConvergence()`
|
|
739
|
+
(`src/schema/uuid-convergence.ts`) groups every manifest relationship that
|
|
740
|
+
declares UUID on both sides into connected components and converges a component
|
|
741
|
+
only when the live database already proves the target shape — at least one
|
|
742
|
+
member is native `uuid`. A component that is `text` on *every* side is the
|
|
743
|
+
tolerated pre-R11 deployment and is left alone; its foreign keys are
|
|
744
|
+
type-compatible today, and the R11 uuid/text equivalence in
|
|
745
|
+
`migrations/differ.ts` keeps it out of the column diff.
|
|
746
|
+
|
|
747
|
+
Components, not individual pairs, are the unit of decision: one legacy `text`
|
|
748
|
+
primary key can be referenced by several children, and converting it for one
|
|
749
|
+
of them would break every sibling that is still `text`. A self-referential
|
|
750
|
+
table falls out of the same grouping because both endpoints land in one
|
|
751
|
+
component. Convergence is relationship-driven, so a legacy `text` id that
|
|
752
|
+
nothing references keeps its R11 tolerance.
|
|
753
|
+
|
|
754
|
+
The planner never coerces data. Before emitting anything it probes each column
|
|
755
|
+
it would rewrite for values that are not uuid-shaped (the same `~*` canonical
|
|
756
|
+
pattern the orphan probe uses) and refuses the whole component — with the count
|
|
757
|
+
and a sample value — if any exist, if the probe cannot run, if a member carries
|
|
758
|
+
some third physical type, or if a live foreign key still constrains a column
|
|
759
|
+
that must change. `@happyvertical/sql` introspection does not expose live
|
|
760
|
+
PostgreSQL constraint names, so SMRT cannot drop and re-add those constraints
|
|
761
|
+
for you: drop them deliberately, rerun the migration to converge, and let SMRT
|
|
762
|
+
re-add the manifest constraints.
|
|
763
|
+
|
|
764
|
+
Refusals are reported, not silent. Each one becomes a warning advisory with no
|
|
765
|
+
executable SQL, so it reaches `unactionableChanges` / `hasManualDrift` and
|
|
766
|
+
`db:status` shows **blocked: incompatible column types** instead of *pending*.
|
|
767
|
+
The same check runs per relationship in `compareForeignKeys`, so a foreign key
|
|
768
|
+
whose live types will still disagree after this run's conversions is reported
|
|
769
|
+
blocked rather than emitted as pending DDL that cannot succeed.
|
|
770
|
+
|
|
771
|
+
The planner also inspects tables the manifest no longer declares. A live
|
|
772
|
+
foreign key from an orphan table onto a column that must convert still blocks
|
|
773
|
+
`ALTER COLUMN … TYPE`, so the differ introspects every existing table — not
|
|
774
|
+
only the manifest ones — whenever there is at least one conversion candidate,
|
|
775
|
+
and reports the dependency instead of emitting DDL PostgreSQL would reject. An
|
|
776
|
+
already-converged database has no candidates and pays nothing.
|
|
777
|
+
|
|
778
|
+
Ordering is a contract. Conversions carry `SchemaChange.phase =
|
|
779
|
+
'pre_foreign_key'`, and the orchestrator emits them **before every CREATE TABLE
|
|
780
|
+
and every foreign-key statement in the batch**. Both halves matter:
|
|
781
|
+
`planForeignKeyCreation()` only defers the constraints inside a mutual cycle,
|
|
782
|
+
so an acyclic new child table keeps its foreign key *inline in `CREATE TABLE`*
|
|
783
|
+
— a brand-new `uuid` child pointing at a legacy `text` parent fails exactly
|
|
784
|
+
like an existing one, before the parent could be converted. Conversions only
|
|
785
|
+
ever rewrite columns that already exist, so leading the batch is always safe. A
|
|
786
|
+
live `DEFAULT` on a converting column is dropped first (PostgreSQL refuses
|
|
787
|
+
`ALTER COLUMN … TYPE` when the default cannot be cast); the ordinary default
|
|
788
|
+
comparison re-establishes the manifest default on the next run.
|
|
789
|
+
|
|
790
|
+
There are **two** batch builders and both order on that marker:
|
|
791
|
+
`collectStatementsFromDiff()` in `migrations/orchestrate.ts` (used by
|
|
792
|
+
`getPendingSchemaStatements` / `migrateSmrtSchemas`) and the tracker batch
|
|
793
|
+
`db:migrate` assembles by hand in `@happyvertical/smrt-cli`
|
|
794
|
+
(`commands/utilities.ts`). `partitionSchemaChanges()` carries
|
|
795
|
+
`SchemaChange.phase` onto `MigrationAction.phase` so the CLI can partition the
|
|
796
|
+
same way, in both the applied batch and the `--dry-run` preview. If you add a
|
|
797
|
+
third consumer, order it the same way.
|
|
798
|
+
|
|
799
|
+
Convergence entries carry the manifest column definition. Every `type_upgrade`
|
|
800
|
+
consumer reads `SchemaChange.column` — `partitionSchemaChanges()` in
|
|
801
|
+
`@happyvertical/smrt-cli` skips an entry without one — so a conversion missing
|
|
802
|
+
it would drop out of the `db:migrate` batch while `compareForeignKeys()` still
|
|
803
|
+
assumed the converged type. Refused convergences carry the same column plus an
|
|
804
|
+
advisory and no SQL, and the CLI routes them to the report-only advisories
|
|
805
|
+
rather than to manual interventions or the tracker.
|
|
806
|
+
|
|
807
|
+
The uuid wording is gated on the manifest. Both the runtime guard and the
|
|
808
|
+
status planner reach their incompatible-type branch for *any* mismatched pair,
|
|
809
|
+
not only uuid/text. A `USING …::uuid` repair is suggested only when the
|
|
810
|
+
manifest declares UUID on both sides **and** a live side is actually `text`;
|
|
811
|
+
otherwise the diagnostic names the two live types and asks the operator to
|
|
812
|
+
align them deliberately.
|
|
813
|
+
|
|
814
|
+
The conversion is one-time and idempotent: once the column is native `uuid`,
|
|
815
|
+
the component is uniformly UUID and the planner emits nothing.
|
|
816
|
+
|
|
718
817
|
Properties to keep if you touch that module:
|
|
719
818
|
|
|
720
819
|
- **The plan is registry-derived and rebuilt per delete.** Registration is
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"custom-action.d.ts","sourceRoot":"","sources":["../../src/generators/custom-action.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAG5D,MAAM,MAAM,iBAAiB,GAAG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pB,gFAAgF;IAChF,YAAY,CAAC,EAAE,iBAAiB,CAAC;CAClC;AAED,KAAK,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAC1C,KAAK,QAAQ,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAExC;;;;GAIG;AACH,wBAAgB,2BAA2B,CACzC,OAAO,EAAE,kCAAkC,GAC1C,4BAA4B,CAmC9B;AAED,oEAAoE;AACpE,wBAAgB,4BAA4B,CAC1C,QAAQ,EAAE,oBAAoB,GAC7B,UAAU,CAuDZ;AAED;;;;GAIG;AACH,wBAAgB,+BAA+B,CAC7C,QAAQ,EAAE,oBAAoB,EAC9B,IAAI,EAAE,QAAQ,GACb,OAAO,EAAE,CAwBX;AAED;;;;GAIG;AACH,MAAM,WAAW,mBAAmB;IAClC,EAAE,EAAE,KAAK,CAAC;IACV,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,gFAAgF;AAChF,eAAO,MAAM,qCAAqC,0BAA0B,CAAC;AAE7E;;;;GAIG;AACH,wBAAgB,4BAA4B,CAC1C,KAAK,EAAE,OAAO,GACb,mBAAmB,GAAG,SAAS,CA6BjC"}
|
|
@@ -26,7 +26,7 @@ function resolveCustomActionMetadata(options) {
|
|
|
26
26
|
...options.method?.parameters ? { parameters: options.method.parameters } : {},
|
|
27
27
|
isStatic: options.method?.isStatic === true,
|
|
28
28
|
effect,
|
|
29
|
-
idempotent: configured.idempotent ??
|
|
29
|
+
idempotent: configured.idempotent ?? false,
|
|
30
30
|
openWorld: configured.openWorld ?? true
|
|
31
31
|
};
|
|
32
32
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"custom-action.js","names":[],"sources":["../../src/generators/custom-action.ts"],"sourcesContent":["/**\n * Canonical custom-action metadata and transport-safe result helpers.\n *\n * Custom actions are intentionally distinct from generated CRUD. Their target\n * is derived from method metadata: instance methods target an item and static\n * methods target the collection. API route configuration may shape an HTTP\n * route, but it cannot change a method's receiver.\n */\n\nimport type { ToolEffect } from '../registry/types.js';\nimport type { MethodDefinition } from '../scanner/types.js';\nimport { convertTypeToJsonSchema } from '../tools/tool-generator.js';\n\nexport type CustomActionScope = 'item' | 'collection';\nexport type { ToolEffect } from '../registry/types.js';\n\nexport interface CustomActionMetadata {\n scope: CustomActionScope;\n /** An item-targeted action requires its target identifier. */\n idRequired: boolean;\n /** Present only when scanner/manifest metadata is available. */\n parameters?: MethodDefinition['parameters'];\n /** Collection actions on a model class invoke its static method. */\n isStatic: boolean;\n /** Browser/agent-visible effect. Omitted declarations fail closed. */\n effect?: ToolEffect;\n /** Whether repeating the action with the same arguments is safe. */\n idempotent?: boolean;\n /** Whether the opaque action may interact outside the SMRT application. */\n openWorld?: boolean;\n}\n\n/** Fully resolved metadata returned by {@link resolveCustomActionMetadata}. */\nexport type ResolvedCustomActionMetadata = CustomActionMetadata &\n Required<Pick<CustomActionMetadata, 'effect' | 'idempotent' | 'openWorld'>>;\n\n/**\n * Return the transport field for a method parameter. Flat tool and CLI\n * transports reserve `id` for receiver parsing even when a collection action\n * rejects it, so every action parameter named `id` is exposed as `actionId`.\n * REST already has separate path/body namespaces.\n */\nexport function customActionParameterInputName(\n _metadata: Pick<CustomActionMetadata, 'idRequired'>,\n parameterName: string,\n): string {\n return parameterName === 'id' ? 'actionId' : parameterName;\n}\n\nexport interface ResolveCustomActionMetadataOptions {\n actionName: string;\n method?: {\n isStatic?: boolean;\n parameters?: MethodDefinition['parameters'];\n };\n apiConfig?: unknown;\n /** Collection-class actions have a collection receiver even when non-static. */\n defaultScope?: CustomActionScope;\n}\n\ntype JsonSchema = Record<string, unknown>;\ntype ToolArgs = Record<string, unknown>;\n\n/**\n * Resolve the target contract shared by MCP, generated REST, CLI discovery,\n * and WebMCP. A missing manifest method retains the historical item-shaped\n * schema; runtime callers may still provide their legacy collection fallback.\n */\nexport function resolveCustomActionMetadata(\n options: ResolveCustomActionMetadataOptions,\n): ResolvedCustomActionMetadata {\n const defaultScope =\n options.defaultScope ?? (options.method?.isStatic ? 'collection' : 'item');\n const requestedScope = readConfiguredScope(\n options.apiConfig,\n options.actionName,\n );\n // A route-only scope override cannot manufacture a receiver. A normal\n // instance method is always item-targeted; a static model method and a\n // recognized collection-class method are always collection-targeted. Keep\n // a matching explicit value for diagnostics/config round-tripping only.\n const scope = requestedScope === defaultScope ? requestedScope : defaultScope;\n const configured = readConfiguredToolMetadata(\n options.apiConfig,\n options.actionName,\n );\n const effect = configured.effect ?? 'destructive';\n\n return {\n scope,\n idRequired: scope === 'item',\n ...(options.method?.parameters\n ? { parameters: options.method.parameters }\n : {}),\n isStatic: options.method?.isStatic === true,\n effect,\n idempotent: configured.idempotent ?? effect === 'read',\n openWorld: configured.openWorld ?? true,\n };\n}\n\n/** Build the custom-action portion of an MCP/WebMCP JSON Schema. */\nexport function buildCustomActionInputSchema(\n metadata: CustomActionMetadata,\n): JsonSchema {\n const properties: Record<string, JsonSchema> = {};\n const required: string[] = [];\n\n if (metadata.idRequired) {\n properties.id = {\n type: 'string',\n description: 'ID of the object to execute action on',\n };\n required.push('id');\n }\n\n // Absent metadata is the legacy options-bag contract. Do not infer direct\n // positional arguments from runtime function arity: it is lossy after\n // transpilation and would make discovery non-deterministic.\n if (!metadata.parameters) {\n properties.options = {\n type: 'object',\n description: 'Additional options for the custom action',\n additionalProperties: true,\n };\n } else if (\n metadata.parameters.length === 1 &&\n metadata.parameters[0]?.name === 'options'\n ) {\n const parameter = metadata.parameters[0];\n properties.options = {\n ...convertTypeToJsonSchema(parameter.type),\n description: 'Options for the custom action',\n ...(parameter.default !== undefined\n ? { default: parameter.default }\n : {}),\n };\n if (!parameter.optional) required.push('options');\n } else {\n for (const parameter of metadata.parameters) {\n const inputName = customActionParameterInputName(\n metadata,\n parameter.name,\n );\n properties[inputName] = {\n ...convertTypeToJsonSchema(parameter.type),\n ...(parameter.default !== undefined\n ? { default: parameter.default }\n : {}),\n };\n if (!parameter.optional) required.push(inputName);\n }\n }\n\n return {\n type: 'object',\n properties,\n ...(required.length > 0 ? { required } : {}),\n };\n}\n\n/**\n * Translate a transport object into the method's call arguments. Legacy\n * actions retain their single options-bag invocation; scanner metadata enables\n * an exact positional projection without changing legacy action behavior.\n */\nexport function buildCustomActionInvocationArgs(\n metadata: CustomActionMetadata,\n args: ToolArgs,\n): unknown[] {\n const { id: _id, options, ...directArgs } = args;\n\n if (!metadata.parameters) {\n return [\n isRecord(options) && Object.keys(options).length > 0\n ? options\n : directArgs,\n ];\n }\n if (metadata.parameters.length === 0) return [];\n if (\n metadata.parameters.length === 1 &&\n metadata.parameters[0]?.name === 'options'\n ) {\n // Preserve `undefined` (and an explicit `null`) so JavaScript default\n // parameter initializers and intentional null handling retain their native\n // semantics. Legacy options bags still receive an empty object below.\n return [options];\n }\n return metadata.parameters.map(\n (parameter) =>\n args[customActionParameterInputName(metadata, parameter.name)],\n );\n}\n\n/**\n * Domain-neutral returned-failure convention for custom actions. The explicit\n * `ok: false` marker prevents successful opaque values such as `{ code,\n * message }` from being reclassified as failures by a transport.\n */\nexport interface CustomActionFailure {\n ok: false;\n code: string;\n message: string;\n status: number;\n details?: unknown;\n retryable?: boolean;\n correlationId?: string;\n}\n\n/** Stable MCP `_meta` member shared with the app discovery contract (#2181). */\nexport const SMRT_CUSTOM_ACTION_ERROR_METADATA_KEY = 'io.happyvertical/smrt';\n\n/**\n * Detect, validate, and redact an explicitly returned custom-action failure.\n * Unknown return values remain opaque successes. `status` defaults to 400 so\n * REST callers receive non-2xx semantics even when an adapter omits it.\n */\nexport function normalizeCustomActionFailure(\n value: unknown,\n): CustomActionFailure | undefined {\n if (!isRecord(value) || value.ok !== false) return undefined;\n if (typeof value.code !== 'string' || typeof value.message !== 'string') {\n return undefined;\n }\n\n const status =\n typeof value.status === 'number' &&\n Number.isInteger(value.status) &&\n value.status >= 400 &&\n value.status <= 599\n ? value.status\n : 400;\n\n return {\n ok: false,\n code: value.code,\n message: redactText(value.message),\n status,\n ...(Object.hasOwn(value, 'details')\n ? { details: redactValue(value.details) }\n : {}),\n ...(typeof value.retryable === 'boolean'\n ? { retryable: value.retryable }\n : {}),\n ...(typeof value.correlationId === 'string'\n ? { correlationId: value.correlationId }\n : {}),\n };\n}\n\nfunction readConfiguredScope(\n apiConfig: unknown,\n actionName: string,\n): CustomActionScope | undefined {\n if (!isRecord(apiConfig) || !isRecord(apiConfig.routes)) return undefined;\n const route = apiConfig.routes[actionName];\n return isRecord(route) &&\n (route.scope === 'item' || route.scope === 'collection')\n ? route.scope\n : undefined;\n}\n\nfunction readConfiguredToolMetadata(\n apiConfig: unknown,\n actionName: string,\n): {\n effect?: ToolEffect;\n idempotent?: boolean;\n openWorld?: boolean;\n} {\n if (!isRecord(apiConfig) || !isRecord(apiConfig.routes)) return {};\n const route = apiConfig.routes[actionName];\n if (!isRecord(route)) return {};\n const effect =\n route.effect === 'read' ||\n route.effect === 'write' ||\n route.effect === 'destructive'\n ? route.effect\n : undefined;\n if (\n effect === 'read' &&\n (route.method === 'PUT' ||\n route.method === 'PATCH' ||\n route.method === 'DELETE')\n ) {\n throw new Error(\n `Custom action ${actionName} cannot declare a read effect for a ${route.method} route`,\n );\n }\n return {\n ...(effect ? { effect } : {}),\n ...(typeof route.idempotent === 'boolean'\n ? { idempotent: route.idempotent }\n : {}),\n ...(typeof route.openWorld === 'boolean'\n ? { openWorld: route.openWorld }\n : {}),\n };\n}\n\nfunction redactValue(value: unknown, seen = new WeakSet<object>()): unknown {\n if (typeof value === 'string') return redactText(value);\n if (value === null || typeof value !== 'object') return value;\n if (seen.has(value)) return '[REDACTED]';\n seen.add(value);\n if (Array.isArray(value))\n return value.map((entry) => redactValue(entry, seen));\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) return '[REDACTED]';\n const result: Record<string, unknown> = {};\n for (const [key, nested] of Object.entries(value)) {\n result[key] = isSensitiveKey(key)\n ? '[REDACTED]'\n : redactValue(nested, seen);\n }\n return result;\n}\n\nfunction redactText(value: string): string {\n return value\n .replace(/\\bBearer\\s+[^\\s,;]+/giu, 'Bearer [REDACTED]')\n .replace(\n /\\b(token|secret|password|api[_-]?key)=([^\\s&]+)/giu,\n '$1=[REDACTED]',\n );\n}\n\nfunction isSensitiveKey(key: string): boolean {\n return /(?:token|secret|password|authorization|cookie|credential|api[_-]?key)/iu.test(\n key,\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n"],"mappings":";;;;;;;;AA0CA,SAAgB,+BACd,WACA,eACQ;CACR,OAAO,kBAAkB,OAAO,aAAa;AAC/C;;;;;;AAqBA,SAAgB,4BACd,SAC8B;CAC9B,MAAM,eACJ,QAAQ,iBAAiB,QAAQ,QAAQ,WAAW,eAAe;CACrE,MAAM,iBAAiB,oBACrB,QAAQ,WACR,QAAQ,UACV;CAKA,MAAM,QAAQ,mBAAmB,eAAe,iBAAiB;CACjE,MAAM,aAAa,2BACjB,QAAQ,WACR,QAAQ,UACV;CACA,MAAM,SAAS,WAAW,UAAU;CAEpC,OAAO;EACL;EACA,YAAY,UAAU;EACtB,GAAI,QAAQ,QAAQ,aAChB,EAAE,YAAY,QAAQ,OAAO,WAAW,IACxC,CAAC;EACL,UAAU,QAAQ,QAAQ,aAAa;EACvC;EACA,YAAY,WAAW,cAAc,WAAW;EAChD,WAAW,WAAW,aAAa;CACrC;AACF;;AAGA,SAAgB,6BACd,UACY;CACZ,MAAM,aAAyC,CAAC;CAChD,MAAM,WAAqB,CAAC;CAE5B,IAAI,SAAS,YAAY;EACvB,WAAW,KAAK;GACd,MAAM;GACN,aAAa;EACf;EACA,SAAS,KAAK,IAAI;CACpB;CAKA,IAAI,CAAC,SAAS,Y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AM,eAAe,YAC5B,EAAE,YAAY,MAAM,WAAW,IAC/B,CAAC;EACL,GAAI,OAAO,MAAM,cAAc,YAC3B,EAAE,WAAW,MAAM,UAAU,IAC7B,CAAC;CACP;AACF;AAEA,SAAS,YAAY,OAAgB,uBAAO,IAAI,QAAgB,GAAY;CAC1E,IAAI,OAAO,UAAU,UAAU,OAAO,WAAW,KAAK;CACtD,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CACxD,IAAI,KAAK,IAAI,KAAK,GAAG,OAAO;CAC5B,KAAK,IAAI,KAAK;CACd,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,KAAK,UAAU,YAAY,OAAO,IAAI,CAAC;CACtD,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,IAAI,cAAc,OAAO,aAAa,cAAc,MAAM,OAAO;CACjE,MAAM,SAAkC,CAAC;CACzC,KAAK,MAAM,CAAC,KAAK,WAAW,OAAO,QAAQ,KAAK,GAC9C,OAAO,OAAO,eAAe,GAAG,IAC5B,eACA,YAAY,QAAQ,IAAI;CAE9B,OAAO;AACT;AAEA,SAAS,WAAW,OAAuB;CACzC,OAAO,MACJ,QAAQ,0BAA0B,mBAAmB,CAAC,CACtD,QACC,sDACA,eACF;AACJ;AAEA,SAAS,eAAe,KAAsB;CAC5C,OAAO,0EAA0E,KAC/E,GACF;AACF;AAEA,SAAS,SAAS,OAAkD;CAClE,OAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAC5E"}
|
|
1
|
+
{"version":3,"file":"custom-action.js","names":[],"sources":["../../src/generators/custom-action.ts"],"sourcesContent":["/**\n * Canonical custom-action metadata and transport-safe result helpers.\n *\n * Custom actions are intentionally distinct from generated CRUD. Their target\n * is derived from method metadata: instance methods target an item and static\n * methods target the collection. API route configuration may shape an HTTP\n * route, but it cannot change a method's receiver.\n */\n\nimport type { ToolEffect } from '../registry/types.js';\nimport type { MethodDefinition } from '../scanner/types.js';\nimport { convertTypeToJsonSchema } from '../tools/tool-generator.js';\n\nexport type CustomActionScope = 'item' | 'collection';\nexport type { ToolEffect } from '../registry/types.js';\n\nexport interface CustomActionMetadata {\n scope: CustomActionScope;\n /** An item-targeted action requires its target identifier. */\n idRequired: boolean;\n /** Present only when scanner/manifest metadata is available. */\n parameters?: MethodDefinition['parameters'];\n /** Collection actions on a model class invoke its static method. */\n isStatic: boolean;\n /** Browser/agent-visible effect. Omitted declarations fail closed. */\n effect?: ToolEffect;\n /** Whether repeating the action with the same arguments is safe. */\n idempotent?: boolean;\n /** Whether the opaque action may interact outside the SMRT application. */\n openWorld?: boolean;\n}\n\n/** Fully resolved metadata returned by {@link resolveCustomActionMetadata}. */\nexport type ResolvedCustomActionMetadata = CustomActionMetadata &\n Required<Pick<CustomActionMetadata, 'effect' | 'idempotent' | 'openWorld'>>;\n\n/**\n * Return the transport field for a method parameter. Flat tool and CLI\n * transports reserve `id` for receiver parsing even when a collection action\n * rejects it, so every action parameter named `id` is exposed as `actionId`.\n * REST already has separate path/body namespaces.\n */\nexport function customActionParameterInputName(\n _metadata: Pick<CustomActionMetadata, 'idRequired'>,\n parameterName: string,\n): string {\n return parameterName === 'id' ? 'actionId' : parameterName;\n}\n\nexport interface ResolveCustomActionMetadataOptions {\n actionName: string;\n method?: {\n isStatic?: boolean;\n parameters?: MethodDefinition['parameters'];\n };\n apiConfig?: unknown;\n /** Collection-class actions have a collection receiver even when non-static. */\n defaultScope?: CustomActionScope;\n}\n\ntype JsonSchema = Record<string, unknown>;\ntype ToolArgs = Record<string, unknown>;\n\n/**\n * Resolve the target contract shared by MCP, generated REST, CLI discovery,\n * and WebMCP. A missing manifest method retains the historical item-shaped\n * schema; runtime callers may still provide their legacy collection fallback.\n */\nexport function resolveCustomActionMetadata(\n options: ResolveCustomActionMetadataOptions,\n): ResolvedCustomActionMetadata {\n const defaultScope =\n options.defaultScope ?? (options.method?.isStatic ? 'collection' : 'item');\n const requestedScope = readConfiguredScope(\n options.apiConfig,\n options.actionName,\n );\n // A route-only scope override cannot manufacture a receiver. A normal\n // instance method is always item-targeted; a static model method and a\n // recognized collection-class method are always collection-targeted. Keep\n // a matching explicit value for diagnostics/config round-tripping only.\n const scope = requestedScope === defaultScope ? requestedScope : defaultScope;\n const configured = readConfiguredToolMetadata(\n options.apiConfig,\n options.actionName,\n );\n const effect = configured.effect ?? 'destructive';\n\n return {\n scope,\n idRequired: scope === 'item',\n ...(options.method?.parameters\n ? { parameters: options.method.parameters }\n : {}),\n isStatic: options.method?.isStatic === true,\n effect,\n // Per-field fail-closed default (#2587, CapabilityDeclaration in\n // @happyvertical/smrt-types): an omitted `idempotent` resolves to\n // `false` regardless of the declared `effect` — a declared 'read'\n // action is not guaranteed idempotent (e.g. a dequeue-shaped read that\n // advances state), so a caller who wants the idempotent hint must\n // declare it explicitly.\n idempotent: configured.idempotent ?? false,\n openWorld: configured.openWorld ?? true,\n };\n}\n\n/** Build the custom-action portion of an MCP/WebMCP JSON Schema. */\nexport function buildCustomActionInputSchema(\n metadata: CustomActionMetadata,\n): JsonSchema {\n const properties: Record<string, JsonSchema> = {};\n const required: string[] = [];\n\n if (metadata.idRequired) {\n properties.id = {\n type: 'string',\n description: 'ID of the object to execute action on',\n };\n required.push('id');\n }\n\n // Absent metadata is the legacy options-bag contract. Do not infer direct\n // positional arguments from runtime function arity: it is lossy after\n // transpilation and would make discovery non-deterministic.\n if (!metadata.parameters) {\n properties.options = {\n type: 'object',\n description: 'Additional options for the custom action',\n additionalProperties: true,\n };\n } else if (\n metadata.parameters.length === 1 &&\n metadata.parameters[0]?.name === 'options'\n ) {\n const parameter = metadata.parameters[0];\n properties.options = {\n ...convertTypeToJsonSchema(parameter.type),\n description: 'Options for the custom action',\n ...(parameter.default !== undefined\n ? { default: parameter.default }\n : {}),\n };\n if (!parameter.optional) required.push('options');\n } else {\n for (const parameter of metadata.parameters) {\n const inputName = customActionParameterInputName(\n metadata,\n parameter.name,\n );\n properties[inputName] = {\n ...convertTypeToJsonSchema(parameter.type),\n ...(parameter.default !== undefined\n ? { default: parameter.default }\n : {}),\n };\n if (!parameter.optional) required.push(inputName);\n }\n }\n\n return {\n type: 'object',\n properties,\n ...(required.length > 0 ? { required } : {}),\n };\n}\n\n/**\n * Translate a transport object into the method's call arguments. Legacy\n * actions retain their single options-bag invocation; scanner metadata enables\n * an exact positional projection without changing legacy action behavior.\n */\nexport function buildCustomActionInvocationArgs(\n metadata: CustomActionMetadata,\n args: ToolArgs,\n): unknown[] {\n const { id: _id, options, ...directArgs } = args;\n\n if (!metadata.parameters) {\n return [\n isRecord(options) && Object.keys(options).length > 0\n ? options\n : directArgs,\n ];\n }\n if (metadata.parameters.length === 0) return [];\n if (\n metadata.parameters.length === 1 &&\n metadata.parameters[0]?.name === 'options'\n ) {\n // Preserve `undefined` (and an explicit `null`) so JavaScript default\n // parameter initializers and intentional null handling retain their native\n // semantics. Legacy options bags still receive an empty object below.\n return [options];\n }\n return metadata.parameters.map(\n (parameter) =>\n args[customActionParameterInputName(metadata, parameter.name)],\n );\n}\n\n/**\n * Domain-neutral returned-failure convention for custom actions. The explicit\n * `ok: false` marker prevents successful opaque values such as `{ code,\n * message }` from being reclassified as failures by a transport.\n */\nexport interface CustomActionFailure {\n ok: false;\n code: string;\n message: string;\n status: number;\n details?: unknown;\n retryable?: boolean;\n correlationId?: string;\n}\n\n/** Stable MCP `_meta` member shared with the app discovery contract (#2181). */\nexport const SMRT_CUSTOM_ACTION_ERROR_METADATA_KEY = 'io.happyvertical/smrt';\n\n/**\n * Detect, validate, and redact an explicitly returned custom-action failure.\n * Unknown return values remain opaque successes. `status` defaults to 400 so\n * REST callers receive non-2xx semantics even when an adapter omits it.\n */\nexport function normalizeCustomActionFailure(\n value: unknown,\n): CustomActionFailure | undefined {\n if (!isRecord(value) || value.ok !== false) return undefined;\n if (typeof value.code !== 'string' || typeof value.message !== 'string') {\n return undefined;\n }\n\n const status =\n typeof value.status === 'number' &&\n Number.isInteger(value.status) &&\n value.status >= 400 &&\n value.status <= 599\n ? value.status\n : 400;\n\n return {\n ok: false,\n code: value.code,\n message: redactText(value.message),\n status,\n ...(Object.hasOwn(value, 'details')\n ? { details: redactValue(value.details) }\n : {}),\n ...(typeof value.retryable === 'boolean'\n ? { retryable: value.retryable }\n : {}),\n ...(typeof value.correlationId === 'string'\n ? { correlationId: value.correlationId }\n : {}),\n };\n}\n\nfunction readConfiguredScope(\n apiConfig: unknown,\n actionName: string,\n): CustomActionScope | undefined {\n if (!isRecord(apiConfig) || !isRecord(apiConfig.routes)) return undefined;\n const route = apiConfig.routes[actionName];\n return isRecord(route) &&\n (route.scope === 'item' || route.scope === 'collection')\n ? route.scope\n : undefined;\n}\n\nfunction readConfiguredToolMetadata(\n apiConfig: unknown,\n actionName: string,\n): {\n effect?: ToolEffect;\n idempotent?: boolean;\n openWorld?: boolean;\n} {\n if (!isRecord(apiConfig) || !isRecord(apiConfig.routes)) return {};\n const route = apiConfig.routes[actionName];\n if (!isRecord(route)) return {};\n const effect =\n route.effect === 'read' ||\n route.effect === 'write' ||\n route.effect === 'destructive'\n ? route.effect\n : undefined;\n if (\n effect === 'read' &&\n (route.method === 'PUT' ||\n route.method === 'PATCH' ||\n route.method === 'DELETE')\n ) {\n throw new Error(\n `Custom action ${actionName} cannot declare a read effect for a ${route.method} route`,\n );\n }\n return {\n ...(effect ? { effect } : {}),\n ...(typeof route.idempotent === 'boolean'\n ? { idempotent: route.idempotent }\n : {}),\n ...(typeof route.openWorld === 'boolean'\n ? { openWorld: route.openWorld }\n : {}),\n };\n}\n\nfunction redactValue(value: unknown, seen = new WeakSet<object>()): unknown {\n if (typeof value === 'string') return redactText(value);\n if (value === null || typeof value !== 'object') return value;\n if (seen.has(value)) return '[REDACTED]';\n seen.add(value);\n if (Array.isArray(value))\n return value.map((entry) => redactValue(entry, seen));\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) return '[REDACTED]';\n const result: Record<string, unknown> = {};\n for (const [key, nested] of Object.entries(value)) {\n result[key] = isSensitiveKey(key)\n ? '[REDACTED]'\n : redactValue(nested, seen);\n }\n return result;\n}\n\nfunction redactText(value: string): string {\n return value\n .replace(/\\bBearer\\s+[^\\s,;]+/giu, 'Bearer [REDACTED]')\n .replace(\n /\\b(token|secret|password|api[_-]?key)=([^\\s&]+)/giu,\n '$1=[REDACTED]',\n );\n}\n\nfunction isSensitiveKey(key: string): boolean {\n return /(?:token|secret|password|authorization|cookie|credential|api[_-]?key)/iu.test(\n key,\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n"],"mappings":";;;;;;;;AA0CA,SAAgB,+BACd,WACA,eACQ;CACR,OAAO,kBAAkB,OAAO,aAAa;AAC/C;;;;;;AAqBA,SAAgB,4BACd,SAC8B;CAC9B,MAAM,eACJ,QAAQ,iBAAiB,QAAQ,QAAQ,WAAW,eAAe;CACrE,MAAM,iBAAiB,oBACrB,QAAQ,WACR,QAAQ,UACV;CAKA,MAAM,QAAQ,mBAAmB,eAAe,iBAAiB;CACjE,MAAM,aAAa,2BACjB,QAAQ,WACR,QAAQ,UACV;CACA,MAAM,SAAS,WAAW,UAAU;CAEpC,OAAO;EACL;EACA,YAAY,UAAU;EACtB,GAAI,QAAQ,QAAQ,aAChB,EAAE,YAAY,QAAQ,OAAO,WAAW,IACxC,CAAC;EACL,UAAU,QAAQ,QAAQ,aAAa;EACvC;EAOA,YAAY,WAAW,cAAc;EACrC,WAAW,WAAW,aAAa;CACrC;AACF;;AAGA,SAAgB,6BACd,UACY;CACZ,MAAM,aAAyC,CAAC;CAChD,MAAM,WAAqB,CAAC;CAE5B,IAAI,SAAS,YAAY;EACvB,WAAW,KAAK;GACd,MAAM;GACN,aAAa;EACf;EACA,SAAS,KAAK,IAAI;CACpB;CAKA,IAAI,CAAC,SAAS,YACZ,WAAW,UAAU;EACnB,MAAM;EACN,aAAa;EACb,sBAAsB;CACxB;MACK,IACL,SAAS,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M,cAAc,YAC3B,EAAE,WAAW,MAAM,UAAU,IAC7B,CAAC;CACP;AACF;AAEA,SAAS,YAAY,OAAgB,uBAAO,IAAI,QAAgB,GAAY;CAC1E,IAAI,OAAO,UAAU,UAAU,OAAO,WAAW,KAAK;CACtD,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CACxD,IAAI,KAAK,IAAI,KAAK,GAAG,OAAO;CAC5B,KAAK,IAAI,KAAK;CACd,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,KAAK,UAAU,YAAY,OAAO,IAAI,CAAC;CACtD,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,IAAI,cAAc,OAAO,aAAa,cAAc,MAAM,OAAO;CACjE,MAAM,SAAkC,CAAC;CACzC,KAAK,MAAM,CAAC,KAAK,WAAW,OAAO,QAAQ,KAAK,GAC9C,OAAO,OAAO,eAAe,GAAG,IAC5B,eACA,YAAY,QAAQ,IAAI;CAE9B,OAAO;AACT;AAEA,SAAS,WAAW,OAAuB;CACzC,OAAO,MACJ,QAAQ,0BAA0B,mBAAmB,CAAC,CACtD,QACC,sDACA,eACF;AACJ;AAEA,SAAS,eAAe,KAAsB;CAC5C,OAAO,0EAA0E,KAC/E,GACF;AACF;AAEA,SAAS,SAAS,OAAkD;CAClE,OAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAC5E"}
|
package/dist/index.js
CHANGED
|
@@ -66,7 +66,7 @@ import { generateOpenAPISpec, setupSwaggerUI } from "./generators/swagger.js";
|
|
|
66
66
|
import "./generators/index.js";
|
|
67
67
|
import { SmrtHierarchical } from "./hierarchical.js";
|
|
68
68
|
import { SmrtJunction } from "./junction.js";
|
|
69
|
-
import { MODULE_DOC_HASH_PREFIX, buildDomainKnowledgeManifest, readAgentModuleDocs, resolveAgentModuleDocPaths } from "./knowledge.js";
|
|
69
|
+
import { AGENT_SURFACE_HASH_PREFIX, MODULE_DOC_HASH_PREFIX, buildDomainKnowledgeManifest, readAgentModuleDocs, resolveAgentModuleDocPaths } from "./knowledge.js";
|
|
70
70
|
import { getClassConfigResolvers, getConfigResolver, isLazyConfigSentinel, listConfigResolvers, registerConfigResolver, resetConfigResolvers, resolveLazyConfig, unregisterConfigResolver } from "./lazy-config.js";
|
|
71
71
|
import { DEFAULT_LEARNING_CONFIG, LearningMemory } from "./learning/memory.js";
|
|
72
72
|
import { ManifestBuilder } from "./manifest/generator.js";
|
|
@@ -85,4 +85,4 @@ import "./system/index.js";
|
|
|
85
85
|
import { getTestDatabase } from "./testing/database.js";
|
|
86
86
|
import "./tools/index.js";
|
|
87
87
|
import { smrtPlugin } from "./vite-plugin/index.js";
|
|
88
|
-
export { AIError, APIGenerator, AiUsageCollector, AiUsagePersistenceHandler, CACHE_INVALIDATION_CHANNEL, CHANGE_FEED_INTERCEPTOR_NAME, CHANGE_FEED_TABLE, CHANGE_SIGNAL_CHANNEL, CLIGenerator, ConfigurationError, ContentHasher, CosineSimilarity, DEFAULT_AI_COST_RATES, DEFAULT_CHANGES_LIMIT, DEFAULT_DATA_QUERY_PAGE_LIMIT, DEFAULT_DATA_QUERY_RESULT_BYTES, DEFAULT_EMBEDDING_CONFIG, DEFAULT_EVENTS_HEARTBEAT_MS, DEFAULT_EVENTS_MAX_SUBSCRIBERS, DEFAULT_EVENTS_RETRY_AFTER_SECONDS, DEFAULT_FACET_LIMIT, DEFAULT_LEARNING_CONFIG, DEFAULT_LIST_LIMIT, DEFAULT_LIST_ORDER_BY, DEFAULT_POSTGRES_TIMEOUTS, DEFAULT_RETENTION_POLICY, DataQueryValidationError, DatabaseError, Dispatch, DispatchBus, DispatchCollection, DispatchSubscription, DispatchSubscriptionCollection, EmbeddingProvider, EmbeddingStorage, ErrorUtils, FilesystemError, GlobalInterceptors, LearningMemory, LiveSchemaParityError, MAX_CHANGES_LIMIT, MAX_DATA_QUERY_CURSOR_LENGTH, MAX_DATA_QUERY_FACETS, MAX_DATA_QUERY_FILTERS, MAX_DATA_QUERY_FILTER_DEPTH, MAX_DATA_QUERY_IN_VALUES, MAX_DATA_QUERY_OFFSET, MAX_DATA_QUERY_PAGE_LIMIT, MAX_DATA_QUERY_REQUEST_BYTES, MAX_DATA_QUERY_RESULT_BYTES, MAX_DATA_QUERY_WARNINGS, MAX_FACET_FIELDS, MAX_FACET_LIMIT, MAX_LIST_LIMIT, MAX_STI_READ_SCOPE_TYPES, MAX_SYNC_APPLY_BATCH_SIZE, MCPGenerator, MCP_STABLE_CATALOG_TTL_MS, MODULE_DOC_HASH_PREFIX, ManifestBuilder, ManifestGenerator, ManifestManager, MetricsAdapter, NetworkError, ObjectRegistry, POSTGRES_TIMEOUT_ENV_VARS, PRIVATE_READ_CACHE_CONTROL, PubSubAdapter, QueryBoundsError, QueryOrderByError, RuntimeError, SMRT_COLLECTION_BASE_NAMES, SMRT_CUSTOM_ACTION_ERROR_METADATA_KEY, SYNC_APPLY_ROUTE_SEGMENTS, SYNC_APPLY_UUID_PATTERN, SYSTEM_TABLE_NAMES, SchemaComparer, SignalBus, SignalSanitizer, SmrtClass, SmrtCollection, SmrtError, SmrtHierarchical, SmrtJunction, SmrtMCPServer, SmrtObject, SmrtPolymorphicAssociation, TenantIsolationError, ValidationError, ValidationReport, ValidationUtils, appendChange, applyOneToManyChildAccessors, applyPendingDecoratorRegistrations, applyPostgresRuntimeTimeouts, applySyncWritablePolicy, assertPostgresSystemTimestampsCurrent, broadcastCacheInvalidation, buildCascadePlan, buildChangeEventStream, buildCustomActionInputSchema, buildCustomActionInvocationArgs, buildDefaultListOrderBy, buildDomainKnowledgeManifest, bumpChangeFeed, canonicalReadRepresentation, canonicalizeDataQuery, cascadeReferencesTo, changeEventSubscribersAtCapacity, checkLiveSchemaParity, childAccessorName, classifyDatabaseError, classifyDialectMessage, clearRetentionTasks, clone, computeBodyEtag, computeRuntimeWebManifestHash, computeTableVersionEtag, conditionalJsonResponse, config, convertTypeToJsonSchema, createDataQueryFingerprint, createDispatchBus, createFilesystemAdapter, createInterceptorContext, createMCPServer, createQualifiedName, createRestServer, createSmrtClient, createSmrtServer, crossPackageRef, customActionParameterInputName, detectEngine, discoverManifestEntry, ensureBootstrapSystemTableCompatibility, ensureCacheInvalidationListener, ensureChangeFeedTable, ensureDeferredSystemTableCompatibility, ensureDispatchSubscriptionsSystemTableCompatibility, ensureDispatchSystemTableCompatibility, ensureJobEventsSystemTableCompatibility, ensureJobsSystemTableCompatibility, ensureLegacySystemTableCompatibility, ensureSystemTables, estimateAiUsageCost, eventStreamCapacityExceededResponse, executeCollectionReadPlan, executeToolCall, executeToolCalls, field, findManifestEntryByQualifiedName, foreignKey, formatToolResults, generateDDLForEngine, generateOpenAPISpec, generateSchemaDiff, generateToolFromMethod, generateToolManifest, getAdapterInfo, getCLIHandler, getCacheGeneration, getChangesSince, getClassConfigResolvers, getClassName, getConfigResolver, getDatabaseEngine, getManifest, getPackageFromQualifiedName, getRetentionTasks, getSQLFromDiff, getSystemTableShapes, getTableVersion, getTenantScopedChangesSince, getTestDatabase, hasActionableChanges, ifNoneMatchHasConcreteMatch, ifNoneMatchSatisfied, importOptionalDependency, invalidateCollectionCache, isAbortedTransactionError, isAdvisoryOnlyChange, isDatabaseInterface, isDeterministicDatabaseError, isEmbeddedDatabase, isFromPackage, isLazyConfigSentinel, isManualOrAdvisoryChange, isNotNullViolationError, isQualifiedName, isSmrtCollectionExtendsName, isStaleWrite, isTenantScopedClassResolved, isTransientDatabaseError, isType, isUniqueViolationError, isValid, listConfigResolvers, loadExternalManifest, loadExternalManifestSync, loadLocalTestManifestSync, loadManifestFromPathSync, manifest, manyToMany, meta, migratePostgresSystemTimestamps, normalizeCustomActionFailure, normalizeDataQueryRequest, normalizeDataQueryResult, normalizeDataQuerySchema, normalizeEventsMaxSubscribers, normalizeOnDelete, normalizeTypedHttpError, oneToMany, parse, parseQualifiedName, parseSyncApplyBatch, payloadMatchesRow, planForeignKeyCreation, planPostgresSystemTimestampMigrations, processSyncApplyBatch, pruneAiUsage, pruneChangeFeed, pruneExpiredContexts, qualifiedNamesEqual, readAgentModuleDocs, registerChangeFeedWriter, registerCompatibleFieldDecorator, registerConfigResolver, registerFilesystemAdapterFactory, registerOptionalDependency, registerRetentionTask, resetChangeFeedWarnings, resetChangeSignals, resetCollectionCache, resetConfigResolvers, resetVerifiedTables, resolveAgentModuleDocPaths, resolveCustomActionMetadata, resolveDatabase, resolveDbCacheKey, resolveDispatchTenantId, resolveDispatchTenantScope, resolveGetStringFilter, resolveLazyConfig, resolveListLimit, resolveListOffset, resolveMCPToolListCacheHint, resolvePostgresTimeouts, resolveReadCacheControl, resolveTenantEtagDiscriminator, runCascadeDelete, runRetentionSweep, runWithTenantGate, safeParse, safeStringify, setDispatchTenantResolver, setTenantEntryPointRunner, setTenantScopedClassResolver, setupCLI, setupSwaggerUI, shouldIncludeMethod, signalVisibleToTenant, smrt, smrtPlugin, smrt as smrtRegistry, sortMCPTools, startRestServer, staticManifest, stopCacheInvalidationListeners, stopChangeSignalListeners, stringify, subscribeToChangeSignals, tableExists, tryReserveChangeEventSubscriberSlot, unregisterChangeFeedWriter, unregisterConfigResolver, unregisterRetentionTask, usesEmbeddedRevisionFallback, validateSyncApplyItem, validateToolCall, versionConditionalResponse, warnIfSharedCacheNeutralized, withEmbeddedWriteQueue, withEmbeddedWriteTransaction };
|
|
88
|
+
export { AGENT_SURFACE_HASH_PREFIX, AIError, APIGenerator, AiUsageCollector, AiUsagePersistenceHandler, CACHE_INVALIDATION_CHANNEL, CHANGE_FEED_INTERCEPTOR_NAME, CHANGE_FEED_TABLE, CHANGE_SIGNAL_CHANNEL, CLIGenerator, ConfigurationError, ContentHasher, CosineSimilarity, DEFAULT_AI_COST_RATES, DEFAULT_CHANGES_LIMIT, DEFAULT_DATA_QUERY_PAGE_LIMIT, DEFAULT_DATA_QUERY_RESULT_BYTES, DEFAULT_EMBEDDING_CONFIG, DEFAULT_EVENTS_HEARTBEAT_MS, DEFAULT_EVENTS_MAX_SUBSCRIBERS, DEFAULT_EVENTS_RETRY_AFTER_SECONDS, DEFAULT_FACET_LIMIT, DEFAULT_LEARNING_CONFIG, DEFAULT_LIST_LIMIT, DEFAULT_LIST_ORDER_BY, DEFAULT_POSTGRES_TIMEOUTS, DEFAULT_RETENTION_POLICY, DataQueryValidationError, DatabaseError, Dispatch, DispatchBus, DispatchCollection, DispatchSubscription, DispatchSubscriptionCollection, EmbeddingProvider, EmbeddingStorage, ErrorUtils, FilesystemError, GlobalInterceptors, LearningMemory, LiveSchemaParityError, MAX_CHANGES_LIMIT, MAX_DATA_QUERY_CURSOR_LENGTH, MAX_DATA_QUERY_FACETS, MAX_DATA_QUERY_FILTERS, MAX_DATA_QUERY_FILTER_DEPTH, MAX_DATA_QUERY_IN_VALUES, MAX_DATA_QUERY_OFFSET, MAX_DATA_QUERY_PAGE_LIMIT, MAX_DATA_QUERY_REQUEST_BYTES, MAX_DATA_QUERY_RESULT_BYTES, MAX_DATA_QUERY_WARNINGS, MAX_FACET_FIELDS, MAX_FACET_LIMIT, MAX_LIST_LIMIT, MAX_STI_READ_SCOPE_TYPES, MAX_SYNC_APPLY_BATCH_SIZE, MCPGenerator, MCP_STABLE_CATALOG_TTL_MS, MODULE_DOC_HASH_PREFIX, ManifestBuilder, ManifestGenerator, ManifestManager, MetricsAdapter, NetworkError, ObjectRegistry, POSTGRES_TIMEOUT_ENV_VARS, PRIVATE_READ_CACHE_CONTROL, PubSubAdapter, QueryBoundsError, QueryOrderByError, RuntimeError, SMRT_COLLECTION_BASE_NAMES, SMRT_CUSTOM_ACTION_ERROR_METADATA_KEY, SYNC_APPLY_ROUTE_SEGMENTS, SYNC_APPLY_UUID_PATTERN, SYSTEM_TABLE_NAMES, SchemaComparer, SignalBus, SignalSanitizer, SmrtClass, SmrtCollection, SmrtError, SmrtHierarchical, SmrtJunction, SmrtMCPServer, SmrtObject, SmrtPolymorphicAssociation, TenantIsolationError, ValidationError, ValidationReport, ValidationUtils, appendChange, applyOneToManyChildAccessors, applyPendingDecoratorRegistrations, applyPostgresRuntimeTimeouts, applySyncWritablePolicy, assertPostgresSystemTimestampsCurrent, broadcastCacheInvalidation, buildCascadePlan, buildChangeEventStream, buildCustomActionInputSchema, buildCustomActionInvocationArgs, buildDefaultListOrderBy, buildDomainKnowledgeManifest, bumpChangeFeed, canonicalReadRepresentation, canonicalizeDataQuery, cascadeReferencesTo, changeEventSubscribersAtCapacity, checkLiveSchemaParity, childAccessorName, classifyDatabaseError, classifyDialectMessage, clearRetentionTasks, clone, computeBodyEtag, computeRuntimeWebManifestHash, computeTableVersionEtag, conditionalJsonResponse, config, convertTypeToJsonSchema, createDataQueryFingerprint, createDispatchBus, createFilesystemAdapter, createInterceptorContext, createMCPServer, createQualifiedName, createRestServer, createSmrtClient, createSmrtServer, crossPackageRef, customActionParameterInputName, detectEngine, discoverManifestEntry, ensureBootstrapSystemTableCompatibility, ensureCacheInvalidationListener, ensureChangeFeedTable, ensureDeferredSystemTableCompatibility, ensureDispatchSubscriptionsSystemTableCompatibility, ensureDispatchSystemTableCompatibility, ensureJobEventsSystemTableCompatibility, ensureJobsSystemTableCompatibility, ensureLegacySystemTableCompatibility, ensureSystemTables, estimateAiUsageCost, eventStreamCapacityExceededResponse, executeCollectionReadPlan, executeToolCall, executeToolCalls, field, findManifestEntryByQualifiedName, foreignKey, formatToolResults, generateDDLForEngine, generateOpenAPISpec, generateSchemaDiff, generateToolFromMethod, generateToolManifest, getAdapterInfo, getCLIHandler, getCacheGeneration, getChangesSince, getClassConfigResolvers, getClassName, getConfigResolver, getDatabaseEngine, getManifest, getPackageFromQualifiedName, getRetentionTasks, getSQLFromDiff, getSystemTableShapes, getTableVersion, getTenantScopedChangesSince, getTestDatabase, hasActionableChanges, ifNoneMatchHasConcreteMatch, ifNoneMatchSatisfied, importOptionalDependency, invalidateCollectionCache, isAbortedTransactionError, isAdvisoryOnlyChange, isDatabaseInterface, isDeterministicDatabaseError, isEmbeddedDatabase, isFromPackage, isLazyConfigSentinel, isManualOrAdvisoryChange, isNotNullViolationError, isQualifiedName, isSmrtCollectionExtendsName, isStaleWrite, isTenantScopedClassResolved, isTransientDatabaseError, isType, isUniqueViolationError, isValid, listConfigResolvers, loadExternalManifest, loadExternalManifestSync, loadLocalTestManifestSync, loadManifestFromPathSync, manifest, manyToMany, meta, migratePostgresSystemTimestamps, normalizeCustomActionFailure, normalizeDataQueryRequest, normalizeDataQueryResult, normalizeDataQuerySchema, normalizeEventsMaxSubscribers, normalizeOnDelete, normalizeTypedHttpError, oneToMany, parse, parseQualifiedName, parseSyncApplyBatch, payloadMatchesRow, planForeignKeyCreation, planPostgresSystemTimestampMigrations, processSyncApplyBatch, pruneAiUsage, pruneChangeFeed, pruneExpiredContexts, qualifiedNamesEqual, readAgentModuleDocs, registerChangeFeedWriter, registerCompatibleFieldDecorator, registerConfigResolver, registerFilesystemAdapterFactory, registerOptionalDependency, registerRetentionTask, resetChangeFeedWarnings, resetChangeSignals, resetCollectionCache, resetConfigResolvers, resetVerifiedTables, resolveAgentModuleDocPaths, resolveCustomActionMetadata, resolveDatabase, resolveDbCacheKey, resolveDispatchTenantId, resolveDispatchTenantScope, resolveGetStringFilter, resolveLazyConfig, resolveListLimit, resolveListOffset, resolveMCPToolListCacheHint, resolvePostgresTimeouts, resolveReadCacheControl, resolveTenantEtagDiscriminator, runCascadeDelete, runRetentionSweep, runWithTenantGate, safeParse, safeStringify, setDispatchTenantResolver, setTenantEntryPointRunner, setTenantScopedClassResolver, setupCLI, setupSwaggerUI, shouldIncludeMethod, signalVisibleToTenant, smrt, smrtPlugin, smrt as smrtRegistry, sortMCPTools, startRestServer, staticManifest, stopCacheInvalidationListeners, stopChangeSignalListeners, stringify, subscribeToChangeSignals, tableExists, tryReserveChangeEventSubscriberSlot, unregisterChangeFeedWriter, unregisterConfigResolver, unregisterRetentionTask, usesEmbeddedRevisionFallback, validateSyncApplyItem, validateToolCall, versionConditionalResponse, warnIfSharedCacheNeutralized, withEmbeddedWriteQueue, withEmbeddedWriteTransaction };
|
package/dist/knowledge.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DomainKnowledgeConfig, DomainKnowledgeManifest, DomainKnowledgeModuleDoc } from '@happyvertical/smrt-types';
|
|
1
|
+
import { DomainKnowledgeAgentSurface, DomainKnowledgeConfig, DomainKnowledgeManifest, DomainKnowledgeModuleDoc } from '@happyvertical/smrt-types';
|
|
2
2
|
import { SmartObjectManifest } from './scanner/types.js';
|
|
3
3
|
/**
|
|
4
4
|
* Minimal package.json shape consumed by the knowledge builder.
|
|
@@ -17,9 +17,25 @@ export interface BuildDomainKnowledgeOptions {
|
|
|
17
17
|
packageJson?: PackageJsonLike;
|
|
18
18
|
manifestPath?: string;
|
|
19
19
|
config?: DomainKnowledgeConfig;
|
|
20
|
+
/**
|
|
21
|
+
* The package's declared view intents and playbooks (#2591), produced by the
|
|
22
|
+
* scanner's agent-surface matcher.
|
|
23
|
+
*
|
|
24
|
+
* Passed in rather than scanned here for one reason: the scanner carries a
|
|
25
|
+
* native parser binary, and `smrt-core`'s main entry is browser-reachable.
|
|
26
|
+
* The Vite plugin already imports the scanner lazily on the Node side and is
|
|
27
|
+
* the one caller that writes this artifact, so it does the scan and hands the
|
|
28
|
+
* result over.
|
|
29
|
+
*/
|
|
30
|
+
agentSurface?: DomainKnowledgeAgentSurface;
|
|
20
31
|
}
|
|
21
32
|
/** `sourceHashes` key prefix for a linked module doc, e.g. `moduleDoc:agents/crm.md`. */
|
|
22
33
|
export declare const MODULE_DOC_HASH_PREFIX = "moduleDoc:";
|
|
34
|
+
/**
|
|
35
|
+
* `sourceHashes` key prefix for a module declaring a view intent or playbook,
|
|
36
|
+
* e.g. `agentSurface:src/lib/orders.intents.ts` (#2591).
|
|
37
|
+
*/
|
|
38
|
+
export declare const AGENT_SURFACE_HASH_PREFIX = "agentSurface:";
|
|
23
39
|
/**
|
|
24
40
|
* Module doc paths linked from a package's `AGENTS.md`, relative to the package
|
|
25
41
|
* root and in document order.
|
package/dist/knowledge.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"knowledge.d.ts","sourceRoot":"","sources":["../src/knowledge.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,qBAAqB,EAGrB,uBAAuB,EAEvB,wBAAwB,EAIzB,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EAEV,mBAAmB,EACpB,MAAM,oBAAoB,CAAC;AAG5B;;;;;GAKG;AACH,MAAM,WAAW,eAAe;IAC9B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED,MAAM,WAAW,2BAA2B;IAC1C,QAAQ,EAAE,mBAAmB,CAAC;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,eAAe,CAAC;IAC9B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,MAAM,CAAC,EAAE,qBAAqB,CAAC;
|
|
1
|
+
{"version":3,"file":"knowledge.d.ts","sourceRoot":"","sources":["../src/knowledge.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,2BAA2B,EAC3B,qBAAqB,EAGrB,uBAAuB,EAEvB,wBAAwB,EAIzB,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EAEV,mBAAmB,EACpB,MAAM,oBAAoB,CAAC;AAG5B;;;;;GAKG;AACH,MAAM,WAAW,eAAe;IAC9B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED,MAAM,WAAW,2BAA2B;IAC1C,QAAQ,EAAE,mBAAmB,CAAC;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,eAAe,CAAC;IAC9B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,MAAM,CAAC,EAAE,qBAAqB,CAAC;IAC/B;;;;;;;;;OASG;IACH,YAAY,CAAC,EAAE,2BAA2B,CAAC;CAC5C;AA2CD,yFAAyF;AACzF,eAAO,MAAM,sBAAsB,eAAe,CAAC;AAEnD;;;GAGG;AACH,eAAO,MAAM,yBAAyB,kBAAkB,CAAC;AAEzD;;;;;;;;;;GAUG;AACH,wBAAgB,0BAA0B,CACxC,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,GAAG,SAAS,GAC3B,MAAM,EAAE,CAgBV;AAED,yEAAyE;AACzE,wBAAgB,mBAAmB,CACjC,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,GAAG,SAAS,GAC3B,wBAAwB,EAAE,CAM5B;AAED,wBAAgB,4BAA4B,CAC1C,OAAO,EAAE,2BAA2B,GACnC,uBAAuB,CAgFzB"}
|
package/dist/knowledge.js
CHANGED
|
@@ -48,6 +48,11 @@ var MARKDOWN_MD_LINK = /\[[^\]]*\]\(\s*([^)\s#]+\.md)(?:#[^)\s]*)?(?:\s+"[^"]*")
|
|
|
48
48
|
/** `sourceHashes` key prefix for a linked module doc, e.g. `moduleDoc:agents/crm.md`. */
|
|
49
49
|
var MODULE_DOC_HASH_PREFIX = "moduleDoc:";
|
|
50
50
|
/**
|
|
51
|
+
* `sourceHashes` key prefix for a module declaring a view intent or playbook,
|
|
52
|
+
* e.g. `agentSurface:src/lib/orders.intents.ts` (#2591).
|
|
53
|
+
*/
|
|
54
|
+
var AGENT_SURFACE_HASH_PREFIX = "agentSurface:";
|
|
55
|
+
/**
|
|
51
56
|
* Module doc paths linked from a package's `AGENTS.md`, relative to the package
|
|
52
57
|
* root and in document order.
|
|
53
58
|
*
|
|
@@ -102,6 +107,7 @@ function buildDomainKnowledgeManifest(options) {
|
|
|
102
107
|
const objects = manifestObjects.map((object) => buildKnowledgeObject(object));
|
|
103
108
|
const surfaces = objects.flatMap((object) => object.surfaces);
|
|
104
109
|
const manifestJson = stableJson(normalizeManifestForHash(options.manifest));
|
|
110
|
+
const agentSurface = normalizeAgentSurface(options.agentSurface);
|
|
105
111
|
return {
|
|
106
112
|
schemaVersion: 1,
|
|
107
113
|
sensitiveFieldsExcluded: true,
|
|
@@ -114,7 +120,8 @@ function buildDomainKnowledgeManifest(options) {
|
|
|
114
120
|
manifest: { content: manifestJson },
|
|
115
121
|
packageJson: fileHashSource(existingPath(rootDir, "package.json")),
|
|
116
122
|
agents: fileHashSource(agentDocPath),
|
|
117
|
-
...Object.fromEntries(moduleDocPaths.map((path) => [`${MODULE_DOC_HASH_PREFIX}${path}`, fileHashSource(join(rootDir, path))]))
|
|
123
|
+
...Object.fromEntries(moduleDocPaths.map((path) => [`${MODULE_DOC_HASH_PREFIX}${path}`, fileHashSource(join(rootDir, path))])),
|
|
124
|
+
...Object.fromEntries(agentSurfaceSourcePaths(agentSurface).map((path) => [`${AGENT_SURFACE_HASH_PREFIX}${path}`, fileHashSource(join(rootDir, path))]))
|
|
118
125
|
}),
|
|
119
126
|
exports: exportKeys(packageJson.exports),
|
|
120
127
|
dependencies: allDependencies,
|
|
@@ -128,9 +135,32 @@ function buildDomainKnowledgeManifest(options) {
|
|
|
128
135
|
prompts: options.config?.includePrompts === false ? [] : readPrompts(rootDir),
|
|
129
136
|
relationshipsV2: summarizeRelationships(objects, manifestObjects),
|
|
130
137
|
agentDoc,
|
|
131
|
-
moduleDocs: includeDocs && moduleDocPaths.length > 0 ? readAgentModuleDocs(rootDir, agentDocContent) : void 0
|
|
138
|
+
moduleDocs: includeDocs && moduleDocPaths.length > 0 ? readAgentModuleDocs(rootDir, agentDocContent) : void 0,
|
|
139
|
+
agentSurface
|
|
132
140
|
};
|
|
133
141
|
}
|
|
142
|
+
/**
|
|
143
|
+
* Drop an agent surface that carries nothing.
|
|
144
|
+
*
|
|
145
|
+
* Keeping the key absent for a package that declares no intent, no playbook,
|
|
146
|
+
* and no diagnostic is what makes this field additive in practice: every
|
|
147
|
+
* checked-in artifact for such a package stays byte-identical to what it
|
|
148
|
+
* emitted before the field existed, so adding emission does not churn the
|
|
149
|
+
* repository's knowledge artifacts.
|
|
150
|
+
*/
|
|
151
|
+
function normalizeAgentSurface(surface) {
|
|
152
|
+
if (!surface) return void 0;
|
|
153
|
+
return surface.intents.length === 0 && surface.playbooks.length === 0 && surface.diagnostics.length === 0 ? void 0 : surface;
|
|
154
|
+
}
|
|
155
|
+
/** Every package-relative module that contributed to the emitted surface. */
|
|
156
|
+
function agentSurfaceSourcePaths(surface) {
|
|
157
|
+
if (!surface) return [];
|
|
158
|
+
const paths = /* @__PURE__ */ new Set();
|
|
159
|
+
for (const intent of surface.intents) paths.add(intent.sourceFile);
|
|
160
|
+
for (const playbook of surface.playbooks) paths.add(playbook.sourceFile);
|
|
161
|
+
for (const diagnostic of surface.diagnostics) paths.add(diagnostic.sourceFile);
|
|
162
|
+
return [...paths].sort();
|
|
163
|
+
}
|
|
134
164
|
function buildKnowledgeObject(object) {
|
|
135
165
|
const knowledge = typeof object.decoratorConfig?.knowledge === "object" ? object.decoratorConfig.knowledge : {};
|
|
136
166
|
const fields = Object.entries(object.fields).filter(([, field]) => !isSensitiveField(field)).map(([name, field]) => {
|
|
@@ -405,6 +435,6 @@ function sortJson(value) {
|
|
|
405
435
|
return value;
|
|
406
436
|
}
|
|
407
437
|
//#endregion
|
|
408
|
-
export { MODULE_DOC_HASH_PREFIX, buildDomainKnowledgeManifest, readAgentModuleDocs, resolveAgentModuleDocPaths };
|
|
438
|
+
export { AGENT_SURFACE_HASH_PREFIX, MODULE_DOC_HASH_PREFIX, buildDomainKnowledgeManifest, readAgentModuleDocs, resolveAgentModuleDocPaths };
|
|
409
439
|
|
|
410
440
|
//# sourceMappingURL=knowledge.js.map
|
package/dist/knowledge.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"knowledge.js","names":[],"sources":["../src/knowledge.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';\nimport { basename, join, relative, resolve, sep } from 'node:path';\nimport type {\n DomainKnowledgeConfig,\n DomainKnowledgeField,\n DomainKnowledgeFieldConstraints,\n DomainKnowledgeManifest,\n DomainKnowledgeMethodSignature,\n DomainKnowledgeModuleDoc,\n DomainKnowledgeObject,\n DomainKnowledgeSurface,\n DomainKnowledgeTenant,\n} from '@happyvertical/smrt-types';\nimport type {\n SmartObjectDefinition,\n SmartObjectManifest,\n} from './scanner/types.js';\nimport { toSnakeCase } from './utils/naming.js';\n\n/**\n * Minimal package.json shape consumed by the knowledge builder.\n * `name`/`version` are typed concretely because they flow into the manifest's\n * string-typed metadata fields; everything else is read via `unknown`-accepting\n * helpers (`record()`, `exportKeys()`), so an index signature is sufficient.\n */\nexport interface PackageJsonLike {\n name?: string;\n version?: string;\n [key: string]: unknown;\n}\n\nexport interface BuildDomainKnowledgeOptions {\n manifest: SmartObjectManifest;\n rootDir: string;\n packageJson?: PackageJsonLike;\n manifestPath?: string;\n config?: DomainKnowledgeConfig;\n}\n\nconst SDK_PACKAGE_NAMES = new Set([\n '@happyvertical/ai',\n '@happyvertical/cache',\n '@happyvertical/documents',\n '@happyvertical/email',\n '@happyvertical/encryption',\n '@happyvertical/files',\n '@happyvertical/geo',\n '@happyvertical/images',\n '@happyvertical/jobs',\n '@happyvertical/json',\n '@happyvertical/logger',\n '@happyvertical/messages',\n '@happyvertical/ocr',\n '@happyvertical/pdf',\n '@happyvertical/projects',\n '@happyvertical/repos',\n '@happyvertical/secrets',\n '@happyvertical/spider',\n '@happyvertical/sql',\n '@happyvertical/utils',\n]);\n\nconst RELATIONSHIP_FIELD_TYPES = new Set([\n 'foreignKey',\n 'crossPackageRef',\n 'oneToMany',\n 'manyToMany',\n]);\n\nconst STANDARD_OPERATIONS = ['list', 'get', 'create', 'update', 'delete'];\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 * 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\nexport function buildDomainKnowledgeManifest(\n options: BuildDomainKnowledgeOptions,\n): DomainKnowledgeManifest {\n const rootDir = options.rootDir;\n const packageJson = options.packageJson ?? readPackageJson(rootDir) ?? {};\n const packageName = options.manifest.packageName ?? packageJson.name;\n const packageVersion = options.manifest.packageVersion ?? packageJson.version;\n const agentDocPath = existingPath(rootDir, 'AGENTS.md');\n const agentDocContent = agentDocPath\n ? readFileSync(agentDocPath, 'utf8')\n : undefined;\n const includeDocs = options.config?.includeDocs !== false;\n const agentDoc = includeDocs ? agentDocContent : undefined;\n // Module doc PATHS are always resolved so their hashes gate freshness even\n // when doc bodies are excluded from the artifact — same stance as `agents`.\n const moduleDocPaths = resolveAgentModuleDocPaths(rootDir, agentDocContent);\n const allDependencies = {\n ...record(packageJson.dependencies),\n ...record(packageJson.devDependencies),\n ...record(packageJson.peerDependencies),\n };\n const manifestObjects = Object.values(options.manifest.objects).filter(\n (object) => object.decoratorConfig?.knowledge !== false,\n );\n const objects = manifestObjects.map((object) => buildKnowledgeObject(object));\n const surfaces = objects.flatMap((object) => object.surfaces);\n const manifestJson = stableJson(normalizeManifestForHash(options.manifest));\n\n return {\n schemaVersion: 1,\n sensitiveFieldsExcluded: true,\n generatedAt: new Date().toISOString(),\n packageName,\n packageVersion,\n sourceManifestPath: options.manifestPath\n ? relative(rootDir, options.manifestPath)\n : undefined,\n agentDocPath: agentDocPath ? relative(rootDir, agentDocPath) : undefined,\n sourceHashes: sourceHashes({\n manifest: { content: manifestJson },\n packageJson: fileHashSource(existingPath(rootDir, 'package.json')),\n agents: fileHashSource(agentDocPath),\n ...Object.fromEntries(\n moduleDocPaths.map((path) => [\n `${MODULE_DOC_HASH_PREFIX}${path}`,\n fileHashSource(join(rootDir, path)),\n ]),\n ),\n }),\n exports: exportKeys(packageJson.exports),\n dependencies: allDependencies,\n smrtDependencies: Object.keys(allDependencies)\n .filter((dep) => dep.startsWith('@happyvertical/smrt-'))\n .sort(),\n sdkDependencies: Object.keys(allDependencies)\n .filter((dep) => SDK_PACKAGE_NAMES.has(dep))\n .sort(),\n tags: options.config?.tags ?? [],\n summary: options.config?.summary,\n risks: options.config?.risks ?? [],\n objects,\n surfaces,\n prompts:\n options.config?.includePrompts === false ? [] : readPrompts(rootDir),\n relationshipsV2: summarizeRelationships(objects, manifestObjects),\n agentDoc,\n moduleDocs:\n includeDocs && moduleDocPaths.length > 0\n ? readAgentModuleDocs(rootDir, agentDocContent)\n : undefined,\n };\n}\n\nfunction buildKnowledgeObject(\n object: SmartObjectDefinition,\n): DomainKnowledgeObject {\n const knowledge =\n typeof object.decoratorConfig?.knowledge === 'object'\n ? object.decoratorConfig.knowledge\n : {};\n const fields = Object.entries(object.fields)\n .filter(([, field]) => !isSensitiveField(field))\n .map(([name, field]): DomainKnowledgeField => {\n const defaultValue = fieldValue(field, 'default');\n return {\n name,\n type: field.type,\n required: field.required,\n related: field.related,\n columnType: columnType(object, name),\n ...(defaultValue.present ? { default: defaultValue.value } : {}),\n constraints: fieldConstraints(field),\n readonly:\n field.readonly === true || field._meta?.readonly === true\n ? true\n : undefined,\n transient:\n field.transient === true || field._meta?.transient === true\n ? true\n : undefined,\n };\n });\n const sensitiveIdentifiers = sensitiveFieldIdentifiers(object.fields);\n const tenant = sanitizeTenantFacts(\n tenantFacts(object.decoratorConfig?.tenantScoped),\n sensitiveIdentifiers,\n );\n const conflictColumns = object.decoratorConfig?.conflictColumns?.filter(\n (column) => !sensitiveIdentifiers.has(column),\n );\n const relationships = fields\n .filter((field) => RELATIONSHIP_FIELD_TYPES.has(field.type))\n .map((field) => ({\n name: field.name,\n type: field.type,\n required: field.required,\n related: field.related,\n columnType: field.columnType,\n }));\n\n return {\n name: object.className,\n qualifiedName: object.qualifiedName,\n collection: object.collection,\n tableName: object.schema?.tableName,\n packageName: object.packageName,\n extends: object.extends,\n visibility: object.visibility,\n fields,\n relationships,\n methods: Object.keys(object.methods).sort(),\n methodSignatures: methodSignatures(object),\n tenant,\n tableStrategy: object.decoratorConfig?.tableStrategy,\n conflictColumns:\n conflictColumns && conflictColumns.length > 0\n ? conflictColumns\n : undefined,\n surfaces: objectSurfaces(object),\n relationshipFeatures: relationshipFeatures(object, fields),\n tags: knowledge.tags ?? [],\n summary: knowledge.summary,\n risks: knowledge.risks ?? [],\n };\n}\n\nfunction isSensitiveField(field: SmartObjectDefinition['fields'][string]) {\n return field.sensitive === true || field._meta?.sensitive === true;\n}\n\nfunction sensitiveFieldIdentifiers(\n fields: SmartObjectDefinition['fields'],\n): Set<string> {\n return new Set(\n Object.entries(fields)\n .filter(([, field]) => isSensitiveField(field))\n .flatMap(([name]) => [name, toSnakeCase(name), camelToSnake(name)]),\n );\n}\n\nfunction fieldValue(\n field: SmartObjectDefinition['fields'][string],\n key: 'default' | 'min' | 'max' | 'minLength' | 'maxLength',\n): { present: boolean; value: unknown } {\n if (Object.hasOwn(field, key)) {\n return { present: field[key] !== undefined, value: field[key] };\n }\n const value = field._meta?.[key];\n return { present: value !== undefined, value };\n}\n\nfunction fieldConstraints(\n field: SmartObjectDefinition['fields'][string],\n): DomainKnowledgeFieldConstraints | undefined {\n const constraints: DomainKnowledgeFieldConstraints = {};\n for (const key of ['min', 'max', 'minLength', 'maxLength'] as const) {\n const value = fieldValue(field, key);\n if (value.present && typeof value.value === 'number') {\n constraints[key] = value.value;\n }\n }\n const pattern = normalizePattern(\n (field as { pattern?: unknown }).pattern ?? field._meta?.pattern,\n );\n if (pattern !== undefined) constraints.pattern = pattern;\n return Object.keys(constraints).length > 0 ? constraints : undefined;\n}\n\nfunction normalizePattern(pattern: unknown): string | undefined {\n if (typeof pattern === 'string') return pattern;\n if (pattern instanceof RegExp) return pattern.source;\n if (\n pattern &&\n typeof pattern === 'object' &&\n typeof (pattern as { source?: unknown }).source === 'string'\n ) {\n return (pattern as { source: string }).source;\n }\n return undefined;\n}\n\nfunction tenantFacts(\n tenantScoped: SmartObjectDefinition['decoratorConfig']['tenantScoped'],\n): DomainKnowledgeTenant | undefined {\n if (!tenantScoped) return undefined;\n if (tenantScoped === true) {\n return { scoped: true, mode: 'required', field: 'tenantId' };\n }\n return {\n scoped: true,\n mode: tenantScoped.mode ?? 'required',\n field: tenantScoped.field ?? 'tenantId',\n };\n}\n\nfunction sanitizeTenantFacts(\n tenant: DomainKnowledgeTenant | undefined,\n sensitiveIdentifiers: Set<string>,\n): DomainKnowledgeTenant | undefined {\n if (!tenant?.field || !sensitiveIdentifiers.has(tenant.field)) return tenant;\n return { scoped: tenant.scoped, mode: tenant.mode };\n}\n\nfunction methodSignatures(\n object: SmartObjectDefinition,\n): DomainKnowledgeMethodSignature[] | undefined {\n const signatures = Object.values(object.methods)\n .sort((a, b) => a.name.localeCompare(b.name))\n .map((method) => ({\n name: method.name,\n async: method.async || undefined,\n static: method.isStatic || undefined,\n params:\n method.parameters.length > 0\n ? method.parameters.map(\n (parameter) =>\n `${parameter.name}${parameter.optional ? '?' : ''}: ${parameter.type}`,\n )\n : undefined,\n returns: method.returnType || undefined,\n }));\n return signatures.length > 0 ? signatures : undefined;\n}\n\nfunction objectSurfaces(\n object: SmartObjectDefinition,\n): DomainKnowledgeSurface[] {\n return [\n ...configuredSurfaces('api', object),\n ...configuredSurfaces('cli', object),\n ...configuredSurfaces('mcp', object),\n ...aiSurfaces(object),\n ];\n}\n\nfunction configuredSurfaces(\n kind: 'api' | 'cli' | 'mcp',\n object: SmartObjectDefinition,\n): DomainKnowledgeSurface[] {\n const config = object.decoratorConfig?.[kind];\n if (!config) return [];\n const operations = configuredOperations(config);\n return operations.map((operation) => ({\n kind,\n name:\n kind === 'api'\n ? `${object.collection}.${operation}`\n : `${object.className.toLowerCase()}_${operation}`,\n operation,\n objectName: object.qualifiedName ?? object.className,\n path: kind === 'api' ? apiPath(object, operation) : undefined,\n method: kind === 'api' ? apiMethod(operation) : undefined,\n }));\n}\n\nfunction configuredOperations(config: unknown): string[] {\n if (config === true) return [...STANDARD_OPERATIONS];\n if (!config || typeof config !== 'object' || Array.isArray(config)) {\n return [];\n }\n const recordConfig = config as { include?: string[]; exclude?: string[] };\n const base = Array.isArray(recordConfig.include)\n ? recordConfig.include\n : STANDARD_OPERATIONS;\n const excluded = new Set(recordConfig.exclude ?? []);\n return [...new Set(base.filter((operation) => !excluded.has(operation)))];\n}\n\nfunction aiSurfaces(object: SmartObjectDefinition): DomainKnowledgeSurface[] {\n return (object.tools ?? []).map((tool) => ({\n kind: 'ai',\n name: tool.function.name,\n operation: tool.function.name,\n description: tool.function.description,\n objectName: object.qualifiedName ?? object.className,\n }));\n}\n\nfunction apiPath(object: SmartObjectDefinition, operation: string): string {\n const collection = object.decoratorConfig?.api;\n const configuredPath =\n typeof collection === 'object' && typeof collection.path === 'string'\n ? collection.path\n : object.collection.replaceAll('_', '-');\n if (operation === 'list' || operation === 'create') {\n return `/${configuredPath}`;\n }\n if (STANDARD_OPERATIONS.includes(operation)) {\n return `/${configuredPath}/[id]`;\n }\n return `/${configuredPath}/${operation}`;\n}\n\nfunction apiMethod(operation: string): string {\n switch (operation) {\n case 'list':\n case 'get':\n return 'GET';\n case 'create':\n return 'POST';\n case 'update':\n return 'PATCH';\n case 'delete':\n return 'DELETE';\n default:\n return 'POST';\n }\n}\n\nfunction relationshipFeatures(\n object: SmartObjectDefinition,\n fields: DomainKnowledgeField[],\n): string[] {\n const features = new Set<string>();\n for (const field of fields) {\n if (field.type === 'foreignKey') features.add('foreignKey');\n if (field.type === 'crossPackageRef') features.add('crossPackageRef');\n if (field.type === 'oneToMany') features.add('oneToMany');\n if (field.type === 'manyToMany') features.add('manyToMany');\n }\n if (object.extends === 'SmrtJunction') features.add('SmrtJunction');\n if (object.extends === 'SmrtHierarchical') features.add('SmrtHierarchical');\n if (\n object.extends === 'SmrtPolymorphicAssociation' ||\n fields.some((field) => field.name === 'metaType') ||\n fields.some((field) => field.name === 'metaId')\n ) {\n features.add('SmrtPolymorphicAssociation');\n }\n if (\n Object.keys(object.schema?.columns ?? {}).some(\n (name) => object.schema?.columns[name]?.type === 'UUID',\n )\n ) {\n features.add('uuidColumns');\n }\n return [...features].sort();\n}\n\nfunction summarizeRelationships(\n objects: DomainKnowledgeObject[],\n manifestObjects: SmartObjectDefinition[],\n) {\n const fields = objects.flatMap((object) => object.fields);\n return {\n foreignKeyFields: fields.filter((field) => field.type === 'foreignKey')\n .length,\n crossPackageRefFields: fields.filter(\n (field) => field.type === 'crossPackageRef',\n ).length,\n junctionCollections: objects.filter((object) =>\n object.relationshipFeatures.includes('SmrtJunction'),\n ).length,\n hierarchicalObjects: objects.filter((object) =>\n object.relationshipFeatures.includes('SmrtHierarchical'),\n ).length,\n polymorphicAssociations: objects.filter((object) =>\n object.relationshipFeatures.includes('SmrtPolymorphicAssociation'),\n ).length,\n uuidColumns: manifestObjects.reduce(\n (count, object) =>\n count +\n Object.values(object.schema?.columns ?? {}).filter(\n (column) => column.type === 'UUID',\n ).length,\n 0,\n ),\n };\n}\n\nfunction columnType(\n object: SmartObjectDefinition,\n fieldName: string,\n): string | undefined {\n const columnName = camelToSnake(fieldName);\n return object.schema?.columns[columnName]?.type;\n}\n\nfunction readPrompts(\n rootDir: string,\n): Array<{ filePath: string; key?: string }> {\n const srcDir = join(rootDir, 'src');\n if (!existsSync(srcDir)) return [];\n const prompts: Array<{ filePath: string; key?: string }> = [];\n for (const filePath of walkFiles(srcDir)) {\n if (!filePath.endsWith('.ts')) continue;\n const content = readFileSync(filePath, 'utf8');\n if (!content.includes('definePrompt')) continue;\n const keyMatch = content.match(/definePrompt\\s*\\(\\s*['\"`]([^'\"`]+)['\"`]/);\n prompts.push({\n filePath: relative(rootDir, filePath),\n key: keyMatch?.[1],\n });\n }\n return prompts;\n}\n\nfunction walkFiles(dir: string): string[] {\n const files: string[] = [];\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n if (\n entry.name === 'node_modules' ||\n entry.name === 'dist' ||\n entry.name === '.svelte-kit'\n ) {\n continue;\n }\n const fullPath = join(dir, entry.name);\n if (entry.isDirectory()) {\n files.push(...walkFiles(fullPath));\n } else if (entry.isFile()) {\n files.push(fullPath);\n }\n }\n return files;\n}\n\nfunction sourceHashes(sources: Record<string, HashSource | undefined>) {\n const hashes: Record<string, string> = {};\n for (const [name, source] of Object.entries(sources)) {\n if (!source) continue;\n const content =\n 'content' in source ? source.content : readFileSync(source.path, 'utf8');\n hashes[name] = createHash('sha256').update(content).digest('hex');\n }\n return hashes;\n}\n\ntype HashSource = { content: string } | { path: string };\n\nfunction fileHashSource(path: string | undefined): HashSource | undefined {\n return path ? { path } : undefined;\n}\n\nfunction existingPath(rootDir: string, path: string): string | undefined {\n const fullPath = join(rootDir, path);\n return existsSync(fullPath) ? fullPath : undefined;\n}\n\nfunction readPackageJson(rootDir: string): PackageJsonLike | null {\n const path = join(rootDir, 'package.json');\n if (!existsSync(path)) return null;\n return JSON.parse(readFileSync(path, 'utf8'));\n}\n\nfunction record(value: unknown): Record<string, string> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, string>)\n : {};\n}\n\nfunction exportKeys(exportsField: unknown): string[] {\n if (typeof exportsField === 'string') return ['.'];\n if (\n typeof exportsField !== 'object' ||\n exportsField === null ||\n Array.isArray(exportsField)\n ) {\n return [];\n }\n return Object.keys(exportsField).sort();\n}\n\nfunction camelToSnake(value: string): string {\n return value\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[-\\s]+/g, '_')\n .toLowerCase();\n}\n\nfunction normalizeManifestForHash(manifest: SmartObjectManifest): unknown {\n const normalized = JSON.parse(JSON.stringify(manifest)) as Record<\n string,\n unknown\n >;\n delete normalized.timestamp;\n return normalized;\n}\n\nfunction stableJson(value: unknown): string {\n return JSON.stringify(sortJson(value), null, 2);\n}\n\nfunction sortJson(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(sortJson);\n if (value && typeof value === 'object') {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([key, entry]) => [key, sortJson(entry)]),\n );\n }\n return value;\n}\n"],"mappings":";;;;;AAwCA,IAAM,oCAAoB,IAAI,IAAI;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;C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iB,YACxB,iBAAiB,QACjB,MAAM,QAAQ,YAAY,GAE1B,OAAO,CAAC;CAEV,OAAO,OAAO,KAAK,YAAY,CAAC,CAAC,KAAK;AACxC;AAEA,SAAS,aAAa,OAAuB;CAC3C,OAAO,MACJ,QAAQ,sBAAsB,OAAO,CAAC,CACtC,QAAQ,WAAW,GAAG,CAAC,CACvB,YAAY;AACjB;AAEA,SAAS,yBAAyB,UAAwC;CACxE,MAAM,aAAa,KAAK,MAAM,KAAK,UAAU,QAAQ,CAAC;CAItD,OAAO,WAAW;CAClB,OAAO;AACT;AAEA,SAAS,WAAW,OAAwB;CAC1C,OAAO,KAAK,UAAU,SAAS,KAAK,GAAG,MAAM,CAAC;AAChD;AAEA,SAAS,SAAS,OAAyB;CACzC,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,MAAM,IAAI,QAAQ;CACnD,IAAI,SAAS,OAAO,UAAU,UAC5B,OAAO,OAAO,YACZ,OAAO,QAAQ,KAAgC,CAAC,CAC7C,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,cAAc,CAAC,CAAC,CAAC,CACtC,KAAK,CAAC,KAAK,WAAW,CAAC,KAAK,SAAS,KAAK,CAAC,CAAC,CACjD;CAEF,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"knowledge.js","names":[],"sources":["../src/knowledge.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';\nimport { basename, join, relative, resolve, sep } from 'node:path';\nimport type {\n DomainKnowledgeAgentSurface,\n DomainKnowledgeConfig,\n DomainKnowledgeField,\n DomainKnowledgeFieldConstraints,\n DomainKnowledgeManifest,\n DomainKnowledgeMethodSignature,\n DomainKnowledgeModuleDoc,\n DomainKnowledgeObject,\n DomainKnowledgeSurface,\n DomainKnowledgeTenant,\n} from '@happyvertical/smrt-types';\nimport type {\n SmartObjectDefinition,\n SmartObjectManifest,\n} from './scanner/types.js';\nimport { toSnakeCase } from './utils/naming.js';\n\n/**\n * Minimal package.json shape consumed by the knowledge builder.\n * `name`/`version` are typed concretely because they flow into the manifest's\n * string-typed metadata fields; everything else is read via `unknown`-accepting\n * helpers (`record()`, `exportKeys()`), so an index signature is sufficient.\n */\nexport interface PackageJsonLike {\n name?: string;\n version?: string;\n [key: string]: unknown;\n}\n\nexport interface BuildDomainKnowledgeOptions {\n manifest: SmartObjectManifest;\n rootDir: string;\n packageJson?: PackageJsonLike;\n manifestPath?: string;\n config?: DomainKnowledgeConfig;\n /**\n * The package's declared view intents and playbooks (#2591), produced by the\n * scanner's agent-surface matcher.\n *\n * Passed in rather than scanned here for one reason: the scanner carries a\n * native parser binary, and `smrt-core`'s main entry is browser-reachable.\n * The Vite plugin already imports the scanner lazily on the Node side and is\n * the one caller that writes this artifact, so it does the scan and hands the\n * result over.\n */\n agentSurface?: DomainKnowledgeAgentSurface;\n}\n\nconst SDK_PACKAGE_NAMES = new Set([\n '@happyvertical/ai',\n '@happyvertical/cache',\n '@happyvertical/documents',\n '@happyvertical/email',\n '@happyvertical/encryption',\n '@happyvertical/files',\n '@happyvertical/geo',\n '@happyvertical/images',\n '@happyvertical/jobs',\n '@happyvertical/json',\n '@happyvertical/logger',\n '@happyvertical/messages',\n '@happyvertical/ocr',\n '@happyvertical/pdf',\n '@happyvertical/projects',\n '@happyvertical/repos',\n '@happyvertical/secrets',\n '@happyvertical/spider',\n '@happyvertical/sql',\n '@happyvertical/utils',\n]);\n\nconst RELATIONSHIP_FIELD_TYPES = new Set([\n 'foreignKey',\n 'crossPackageRef',\n 'oneToMany',\n 'manyToMany',\n]);\n\nconst STANDARD_OPERATIONS = ['list', 'get', 'create', 'update', 'delete'];\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\nexport function buildDomainKnowledgeManifest(\n options: BuildDomainKnowledgeOptions,\n): DomainKnowledgeManifest {\n const rootDir = options.rootDir;\n const packageJson = options.packageJson ?? readPackageJson(rootDir) ?? {};\n const packageName = options.manifest.packageName ?? packageJson.name;\n const packageVersion = options.manifest.packageVersion ?? packageJson.version;\n const agentDocPath = existingPath(rootDir, 'AGENTS.md');\n const agentDocContent = agentDocPath\n ? readFileSync(agentDocPath, 'utf8')\n : undefined;\n const includeDocs = options.config?.includeDocs !== false;\n const agentDoc = includeDocs ? agentDocContent : undefined;\n // Module doc PATHS are always resolved so their hashes gate freshness even\n // when doc bodies are excluded from the artifact — same stance as `agents`.\n const moduleDocPaths = resolveAgentModuleDocPaths(rootDir, agentDocContent);\n const allDependencies = {\n ...record(packageJson.dependencies),\n ...record(packageJson.devDependencies),\n ...record(packageJson.peerDependencies),\n };\n const manifestObjects = Object.values(options.manifest.objects).filter(\n (object) => object.decoratorConfig?.knowledge !== false,\n );\n const objects = manifestObjects.map((object) => buildKnowledgeObject(object));\n const surfaces = objects.flatMap((object) => object.surfaces);\n const manifestJson = stableJson(normalizeManifestForHash(options.manifest));\n const agentSurface = normalizeAgentSurface(options.agentSurface);\n\n return {\n schemaVersion: 1,\n sensitiveFieldsExcluded: true,\n generatedAt: new Date().toISOString(),\n packageName,\n packageVersion,\n sourceManifestPath: options.manifestPath\n ? relative(rootDir, options.manifestPath)\n : undefined,\n agentDocPath: agentDocPath ? relative(rootDir, agentDocPath) : undefined,\n sourceHashes: sourceHashes({\n manifest: { content: manifestJson },\n packageJson: fileHashSource(existingPath(rootDir, 'package.json')),\n agents: fileHashSource(agentDocPath),\n ...Object.fromEntries(\n moduleDocPaths.map((path) => [\n `${MODULE_DOC_HASH_PREFIX}${path}`,\n fileHashSource(join(rootDir, path)),\n ]),\n ),\n // A module declaring an intent or a playbook is an authored source of\n // this artifact exactly like `AGENTS.md` is, so editing one must mark the\n // artifact stale (#2591).\n ...Object.fromEntries(\n agentSurfaceSourcePaths(agentSurface).map((path) => [\n `${AGENT_SURFACE_HASH_PREFIX}${path}`,\n fileHashSource(join(rootDir, path)),\n ]),\n ),\n }),\n exports: exportKeys(packageJson.exports),\n dependencies: allDependencies,\n smrtDependencies: Object.keys(allDependencies)\n .filter((dep) => dep.startsWith('@happyvertical/smrt-'))\n .sort(),\n sdkDependencies: Object.keys(allDependencies)\n .filter((dep) => SDK_PACKAGE_NAMES.has(dep))\n .sort(),\n tags: options.config?.tags ?? [],\n summary: options.config?.summary,\n risks: options.config?.risks ?? [],\n objects,\n surfaces,\n prompts:\n options.config?.includePrompts === false ? [] : readPrompts(rootDir),\n relationshipsV2: summarizeRelationships(objects, manifestObjects),\n agentDoc,\n moduleDocs:\n includeDocs && moduleDocPaths.length > 0\n ? readAgentModuleDocs(rootDir, agentDocContent)\n : undefined,\n agentSurface,\n };\n}\n\n/**\n * Drop an agent surface that carries nothing.\n *\n * Keeping the key absent for a package that declares no intent, no playbook,\n * and no diagnostic is what makes this field additive in practice: every\n * checked-in artifact for such a package stays byte-identical to what it\n * emitted before the field existed, so adding emission does not churn the\n * repository's knowledge artifacts.\n */\nfunction normalizeAgentSurface(\n surface: DomainKnowledgeAgentSurface | undefined,\n): DomainKnowledgeAgentSurface | undefined {\n if (!surface) return undefined;\n const empty =\n surface.intents.length === 0 &&\n surface.playbooks.length === 0 &&\n surface.diagnostics.length === 0;\n return empty ? undefined : surface;\n}\n\n/** Every package-relative module that contributed to the emitted surface. */\nfunction agentSurfaceSourcePaths(\n surface: DomainKnowledgeAgentSurface | undefined,\n): string[] {\n if (!surface) return [];\n const paths = new Set<string>();\n for (const intent of surface.intents) paths.add(intent.sourceFile);\n for (const playbook of surface.playbooks) paths.add(playbook.sourceFile);\n for (const diagnostic of surface.diagnostics)\n paths.add(diagnostic.sourceFile);\n return [...paths].sort();\n}\n\nfunction buildKnowledgeObject(\n object: SmartObjectDefinition,\n): DomainKnowledgeObject {\n const knowledge =\n typeof object.decoratorConfig?.knowledge === 'object'\n ? object.decoratorConfig.knowledge\n : {};\n const fields = Object.entries(object.fields)\n .filter(([, field]) => !isSensitiveField(field))\n .map(([name, field]): DomainKnowledgeField => {\n const defaultValue = fieldValue(field, 'default');\n return {\n name,\n type: field.type,\n required: field.required,\n related: field.related,\n columnType: columnType(object, name),\n ...(defaultValue.present ? { default: defaultValue.value } : {}),\n constraints: fieldConstraints(field),\n readonly:\n field.readonly === true || field._meta?.readonly === true\n ? true\n : undefined,\n transient:\n field.transient === true || field._meta?.transient === true\n ? true\n : undefined,\n };\n });\n const sensitiveIdentifiers = sensitiveFieldIdentifiers(object.fields);\n const tenant = sanitizeTenantFacts(\n tenantFacts(object.decoratorConfig?.tenantScoped),\n sensitiveIdentifiers,\n );\n const conflictColumns = object.decoratorConfig?.conflictColumns?.filter(\n (column) => !sensitiveIdentifiers.has(column),\n );\n const relationships = fields\n .filter((field) => RELATIONSHIP_FIELD_TYPES.has(field.type))\n .map((field) => ({\n name: field.name,\n type: field.type,\n required: field.required,\n related: field.related,\n columnType: field.columnType,\n }));\n\n return {\n name: object.className,\n qualifiedName: object.qualifiedName,\n collection: object.collection,\n tableName: object.schema?.tableName,\n packageName: object.packageName,\n extends: object.extends,\n visibility: object.visibility,\n fields,\n relationships,\n methods: Object.keys(object.methods).sort(),\n methodSignatures: methodSignatures(object),\n tenant,\n tableStrategy: object.decoratorConfig?.tableStrategy,\n conflictColumns:\n conflictColumns && conflictColumns.length > 0\n ? conflictColumns\n : undefined,\n surfaces: objectSurfaces(object),\n relationshipFeatures: relationshipFeatures(object, fields),\n tags: knowledge.tags ?? [],\n summary: knowledge.summary,\n risks: knowledge.risks ?? [],\n };\n}\n\nfunction isSensitiveField(field: SmartObjectDefinition['fields'][string]) {\n return field.sensitive === true || field._meta?.sensitive === true;\n}\n\nfunction sensitiveFieldIdentifiers(\n fields: SmartObjectDefinition['fields'],\n): Set<string> {\n return new Set(\n Object.entries(fields)\n .filter(([, field]) => isSensitiveField(field))\n .flatMap(([name]) => [name, toSnakeCase(name), camelToSnake(name)]),\n );\n}\n\nfunction fieldValue(\n field: SmartObjectDefinition['fields'][string],\n key: 'default' | 'min' | 'max' | 'minLength' | 'maxLength',\n): { present: boolean; value: unknown } {\n if (Object.hasOwn(field, key)) {\n return { present: field[key] !== undefined, value: field[key] };\n }\n const value = field._meta?.[key];\n return { present: value !== undefined, value };\n}\n\nfunction fieldConstraints(\n field: SmartObjectDefinition['fields'][string],\n): DomainKnowledgeFieldConstraints | undefined {\n const constraints: DomainKnowledgeFieldConstraints = {};\n for (const key of ['min', 'max', 'minLength', 'maxLength'] as const) {\n const value = fieldValue(field, key);\n if (value.present && typeof value.value === 'number') {\n constraints[key] = value.value;\n }\n }\n const pattern = normalizePattern(\n (field as { pattern?: unknown }).pattern ?? field._meta?.pattern,\n );\n if (pattern !== undefined) constraints.pattern = pattern;\n return Object.keys(constraints).length > 0 ? constraints : undefined;\n}\n\nfunction normalizePattern(pattern: unknown): string | undefined {\n if (typeof pattern === 'string') return pattern;\n if (pattern instanceof RegExp) return pattern.source;\n if (\n pattern &&\n typeof pattern === 'object' &&\n typeof (pattern as { source?: unknown }).source === 'string'\n ) {\n return (pattern as { source: string }).source;\n }\n return undefined;\n}\n\nfunction tenantFacts(\n tenantScoped: SmartObjectDefinition['decoratorConfig']['tenantScoped'],\n): DomainKnowledgeTenant | undefined {\n if (!tenantScoped) return undefined;\n if (tenantScoped === true) {\n return { scoped: true, mode: 'required', field: 'tenantId' };\n }\n return {\n scoped: true,\n mode: tenantScoped.mode ?? 'required',\n field: tenantScoped.field ?? 'tenantId',\n };\n}\n\nfunction sanitizeTenantFacts(\n tenant: DomainKnowledgeTenant | undefined,\n sensitiveIdentifiers: Set<string>,\n): DomainKnowledgeTenant | undefined {\n if (!tenant?.field || !sensitiveIdentifiers.has(tenant.field)) return tenant;\n return { scoped: tenant.scoped, mode: tenant.mode };\n}\n\nfunction methodSignatures(\n object: SmartObjectDefinition,\n): DomainKnowledgeMethodSignature[] | undefined {\n const signatures = Object.values(object.methods)\n .sort((a, b) => a.name.localeCompare(b.name))\n .map((method) => ({\n name: method.name,\n async: method.async || undefined,\n static: method.isStatic || undefined,\n params:\n method.parameters.length > 0\n ? method.parameters.map(\n (parameter) =>\n `${parameter.name}${parameter.optional ? '?' : ''}: ${parameter.type}`,\n )\n : undefined,\n returns: method.returnType || undefined,\n }));\n return signatures.length > 0 ? signatures : undefined;\n}\n\nfunction objectSurfaces(\n object: SmartObjectDefinition,\n): DomainKnowledgeSurface[] {\n return [\n ...configuredSurfaces('api', object),\n ...configuredSurfaces('cli', object),\n ...configuredSurfaces('mcp', object),\n ...aiSurfaces(object),\n ];\n}\n\nfunction configuredSurfaces(\n kind: 'api' | 'cli' | 'mcp',\n object: SmartObjectDefinition,\n): DomainKnowledgeSurface[] {\n const config = object.decoratorConfig?.[kind];\n if (!config) return [];\n const operations = configuredOperations(config);\n return operations.map((operation) => ({\n kind,\n name:\n kind === 'api'\n ? `${object.collection}.${operation}`\n : `${object.className.toLowerCase()}_${operation}`,\n operation,\n objectName: object.qualifiedName ?? object.className,\n path: kind === 'api' ? apiPath(object, operation) : undefined,\n method: kind === 'api' ? apiMethod(operation) : undefined,\n }));\n}\n\nfunction configuredOperations(config: unknown): string[] {\n if (config === true) return [...STANDARD_OPERATIONS];\n if (!config || typeof config !== 'object' || Array.isArray(config)) {\n return [];\n }\n const recordConfig = config as { include?: string[]; exclude?: string[] };\n const base = Array.isArray(recordConfig.include)\n ? recordConfig.include\n : STANDARD_OPERATIONS;\n const excluded = new Set(recordConfig.exclude ?? []);\n return [...new Set(base.filter((operation) => !excluded.has(operation)))];\n}\n\nfunction aiSurfaces(object: SmartObjectDefinition): DomainKnowledgeSurface[] {\n return (object.tools ?? []).map((tool) => ({\n kind: 'ai',\n name: tool.function.name,\n operation: tool.function.name,\n description: tool.function.description,\n objectName: object.qualifiedName ?? object.className,\n }));\n}\n\nfunction apiPath(object: SmartObjectDefinition, operation: string): string {\n const collection = object.decoratorConfig?.api;\n const configuredPath =\n typeof collection === 'object' && typeof collection.path === 'string'\n ? collection.path\n : object.collection.replaceAll('_', '-');\n if (operation === 'list' || operation === 'create') {\n return `/${configuredPath}`;\n }\n if (STANDARD_OPERATIONS.includes(operation)) {\n return `/${configuredPath}/[id]`;\n }\n return `/${configuredPath}/${operation}`;\n}\n\nfunction apiMethod(operation: string): string {\n switch (operation) {\n case 'list':\n case 'get':\n return 'GET';\n case 'create':\n return 'POST';\n case 'update':\n return 'PATCH';\n case 'delete':\n return 'DELETE';\n default:\n return 'POST';\n }\n}\n\nfunction relationshipFeatures(\n object: SmartObjectDefinition,\n fields: DomainKnowledgeField[],\n): string[] {\n const features = new Set<string>();\n for (const field of fields) {\n if (field.type === 'foreignKey') features.add('foreignKey');\n if (field.type === 'crossPackageRef') features.add('crossPackageRef');\n if (field.type === 'oneToMany') features.add('oneToMany');\n if (field.type === 'manyToMany') features.add('manyToMany');\n }\n if (object.extends === 'SmrtJunction') features.add('SmrtJunction');\n if (object.extends === 'SmrtHierarchical') features.add('SmrtHierarchical');\n if (\n object.extends === 'SmrtPolymorphicAssociation' ||\n fields.some((field) => field.name === 'metaType') ||\n fields.some((field) => field.name === 'metaId')\n ) {\n features.add('SmrtPolymorphicAssociation');\n }\n if (\n Object.keys(object.schema?.columns ?? {}).some(\n (name) => object.schema?.columns[name]?.type === 'UUID',\n )\n ) {\n features.add('uuidColumns');\n }\n return [...features].sort();\n}\n\nfunction summarizeRelationships(\n objects: DomainKnowledgeObject[],\n manifestObjects: SmartObjectDefinition[],\n) {\n const fields = objects.flatMap((object) => object.fields);\n return {\n foreignKeyFields: fields.filter((field) => field.type === 'foreignKey')\n .length,\n crossPackageRefFields: fields.filter(\n (field) => field.type === 'crossPackageRef',\n ).length,\n junctionCollections: objects.filter((object) =>\n object.relationshipFeatures.includes('SmrtJunction'),\n ).length,\n hierarchicalObjects: objects.filter((object) =>\n object.relationshipFeatures.includes('SmrtHierarchical'),\n ).length,\n polymorphicAssociations: objects.filter((object) =>\n object.relationshipFeatures.includes('SmrtPolymorphicAssociation'),\n ).length,\n uuidColumns: manifestObjects.reduce(\n (count, object) =>\n count +\n Object.values(object.schema?.columns ?? {}).filter(\n (column) => column.type === 'UUID',\n ).length,\n 0,\n ),\n };\n}\n\nfunction columnType(\n object: SmartObjectDefinition,\n fieldName: string,\n): string | undefined {\n const columnName = camelToSnake(fieldName);\n return object.schema?.columns[columnName]?.type;\n}\n\nfunction readPrompts(\n rootDir: string,\n): Array<{ filePath: string; key?: string }> {\n const srcDir = join(rootDir, 'src');\n if (!existsSync(srcDir)) return [];\n const prompts: Array<{ filePath: string; key?: string }> = [];\n for (const filePath of walkFiles(srcDir)) {\n if (!filePath.endsWith('.ts')) continue;\n const content = readFileSync(filePath, 'utf8');\n if (!content.includes('definePrompt')) continue;\n const keyMatch = content.match(/definePrompt\\s*\\(\\s*['\"`]([^'\"`]+)['\"`]/);\n prompts.push({\n filePath: relative(rootDir, filePath),\n key: keyMatch?.[1],\n });\n }\n return prompts;\n}\n\nfunction walkFiles(dir: string): string[] {\n const files: string[] = [];\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n if (\n entry.name === 'node_modules' ||\n entry.name === 'dist' ||\n entry.name === '.svelte-kit'\n ) {\n continue;\n }\n const fullPath = join(dir, entry.name);\n if (entry.isDirectory()) {\n files.push(...walkFiles(fullPath));\n } else if (entry.isFile()) {\n files.push(fullPath);\n }\n }\n return files;\n}\n\nfunction sourceHashes(sources: Record<string, HashSource | undefined>) {\n const hashes: Record<string, string> = {};\n for (const [name, source] of Object.entries(sources)) {\n if (!source) continue;\n const content =\n 'content' in source ? source.content : readFileSync(source.path, 'utf8');\n hashes[name] = createHash('sha256').update(content).digest('hex');\n }\n return hashes;\n}\n\ntype HashSource = { content: string } | { path: string };\n\nfunction fileHashSource(path: string | undefined): HashSource | undefined {\n return path ? { path } : undefined;\n}\n\nfunction existingPath(rootDir: string, path: string): string | undefined {\n const fullPath = join(rootDir, path);\n return existsSync(fullPath) ? fullPath : undefined;\n}\n\nfunction readPackageJson(rootDir: string): PackageJsonLike | null {\n const path = join(rootDir, 'package.json');\n if (!existsSync(path)) return null;\n return JSON.parse(readFileSync(path, 'utf8'));\n}\n\nfunction record(value: unknown): Record<string, string> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, string>)\n : {};\n}\n\nfunction exportKeys(exportsField: unknown): string[] {\n if (typeof exportsField === 'string') return ['.'];\n if (\n typeof exportsField !== 'object' ||\n exportsField === null ||\n Array.isArray(exportsField)\n ) {\n return [];\n }\n return Object.keys(exportsField).sort();\n}\n\nfunction camelToSnake(value: string): string {\n return value\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[-\\s]+/g, '_')\n .toLowerCase();\n}\n\nfunction normalizeManifestForHash(manifest: SmartObjectManifest): unknown {\n const normalized = JSON.parse(JSON.stringify(manifest)) as Record<\n string,\n unknown\n >;\n delete normalized.timestamp;\n return normalized;\n}\n\nfunction stableJson(value: unknown): string {\n return JSON.stringify(sortJson(value), null, 2);\n}\n\nfunction sortJson(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(sortJson);\n if (value && typeof value === 'object') {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([key, entry]) => [key, sortJson(entry)]),\n );\n }\n return value;\n}\n"],"mappings":";;;;;AAoDA,IAAM,oCAAoB,IAAI,IAAI;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,IAAM,2CAA2B,IAAI,IAAI;CACvC;CACA;CACA;CACA;AACF,CAAC;AAED,IAAM,sBAAsB;CAAC;CAAQ;CAAO;CAAU;CAAU;AAAQ;;;;;;;AAQxE,IAAM,mBACJ;;AAGF,IAAa,yBAAyB;;;;;AAMtC,IAAa,4BAA4B;;;;;;;;;;;;AAazC,SAAgB,2BACd,SACA,UACU;CACV,IAAI,CAAC,UAAU,OAAO,CAAC;CACvB,MAAM,OA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