@rubytech/create-maxy 1.0.677 → 1.0.679

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/dist/index.js +23 -0
  2. package/package.json +1 -1
  3. package/payload/platform/lib/graph-mcp/dist/__tests__/cypher-validate.test.d.ts +2 -0
  4. package/payload/platform/lib/graph-mcp/dist/__tests__/cypher-validate.test.d.ts.map +1 -0
  5. package/payload/platform/lib/graph-mcp/dist/__tests__/cypher-validate.test.js +112 -0
  6. package/payload/platform/lib/graph-mcp/dist/__tests__/cypher-validate.test.js.map +1 -0
  7. package/payload/platform/lib/graph-mcp/dist/__tests__/schema-cache.test.d.ts +2 -0
  8. package/payload/platform/lib/graph-mcp/dist/__tests__/schema-cache.test.d.ts.map +1 -0
  9. package/payload/platform/lib/graph-mcp/dist/__tests__/schema-cache.test.js +163 -0
  10. package/payload/platform/lib/graph-mcp/dist/__tests__/schema-cache.test.js.map +1 -0
  11. package/payload/platform/lib/graph-mcp/dist/cypher-validate.d.ts +38 -0
  12. package/payload/platform/lib/graph-mcp/dist/cypher-validate.d.ts.map +1 -0
  13. package/payload/platform/lib/graph-mcp/dist/cypher-validate.js +130 -0
  14. package/payload/platform/lib/graph-mcp/dist/cypher-validate.js.map +1 -0
  15. package/payload/platform/lib/graph-mcp/dist/index.js +201 -45
  16. package/payload/platform/lib/graph-mcp/dist/index.js.map +1 -1
  17. package/payload/platform/lib/graph-mcp/dist/schema-cache.d.ts +78 -0
  18. package/payload/platform/lib/graph-mcp/dist/schema-cache.d.ts.map +1 -0
  19. package/payload/platform/lib/graph-mcp/dist/schema-cache.js +194 -0
  20. package/payload/platform/lib/graph-mcp/dist/schema-cache.js.map +1 -0
  21. package/payload/platform/lib/graph-mcp/src/__tests__/cypher-validate.test.ts +141 -0
  22. package/payload/platform/lib/graph-mcp/src/__tests__/schema-cache.test.ts +169 -0
  23. package/payload/platform/lib/graph-mcp/src/cypher-validate.ts +157 -0
  24. package/payload/platform/lib/graph-mcp/src/index.ts +247 -47
  25. package/payload/platform/lib/graph-mcp/src/schema-cache.ts +212 -0
  26. package/payload/platform/lib/graph-trash/dist/index.d.ts +8 -0
  27. package/payload/platform/lib/graph-trash/dist/index.d.ts.map +1 -1
  28. package/payload/platform/lib/graph-trash/dist/index.js +109 -14
  29. package/payload/platform/lib/graph-trash/dist/index.js.map +1 -1
  30. package/payload/platform/lib/graph-trash/src/index.ts +136 -21
  31. package/payload/platform/plugins/docs/references/internals.md +4 -0
  32. package/payload/platform/plugins/docs/references/memory-guide.md +5 -1
  33. package/payload/platform/plugins/docs/references/platform.md +1 -1
  34. package/payload/platform/plugins/docs/references/troubleshooting.md +18 -0
  35. package/payload/platform/plugins/memory/PLUGIN.md +1 -0
  36. package/payload/platform/plugins/memory/mcp/dist/index.js +54 -6
  37. package/payload/platform/plugins/memory/mcp/dist/index.js.map +1 -1
  38. package/payload/platform/plugins/memory/mcp/dist/lib/filter-token.d.ts +36 -0
  39. package/payload/platform/plugins/memory/mcp/dist/lib/filter-token.d.ts.map +1 -0
  40. package/payload/platform/plugins/memory/mcp/dist/lib/filter-token.js +86 -0
  41. package/payload/platform/plugins/memory/mcp/dist/lib/filter-token.js.map +1 -0
  42. package/payload/platform/plugins/memory/mcp/dist/tools/memory-delete.d.ts +23 -0
  43. package/payload/platform/plugins/memory/mcp/dist/tools/memory-delete.d.ts.map +1 -1
  44. package/payload/platform/plugins/memory/mcp/dist/tools/memory-delete.js +47 -1
  45. package/payload/platform/plugins/memory/mcp/dist/tools/memory-delete.js.map +1 -1
  46. package/payload/platform/plugins/memory/mcp/dist/tools/memory-find-candidates.d.ts +58 -0
  47. package/payload/platform/plugins/memory/mcp/dist/tools/memory-find-candidates.d.ts.map +1 -0
  48. package/payload/platform/plugins/memory/mcp/dist/tools/memory-find-candidates.js +125 -0
  49. package/payload/platform/plugins/memory/mcp/dist/tools/memory-find-candidates.js.map +1 -0
  50. package/payload/platform/templates/agents/admin/IDENTITY.md +16 -0
  51. package/payload/server/chunk-3RBKKDHC.js +783 -0
  52. package/payload/server/maxy-edge.js +11 -3
  53. package/payload/server/public/assets/{admin-DQmUdTBa.js → admin-BBL1no_g.js} +1 -1
  54. package/payload/server/public/assets/{data-DVlvxbTt.js → data-DUSyrydY.js} +1 -1
  55. package/payload/server/public/assets/{file-OY_hX2wu.js → file-CDJ6dUV3.js} +1 -1
  56. package/payload/server/public/assets/graph-CWcYp5bE.js +50 -0
  57. package/payload/server/public/assets/{house-CgENfOCP.js → house-CNP_bwvT.js} +1 -1
  58. package/payload/server/public/assets/{jsx-runtime-Bu4vXoe7.css → jsx-runtime-BFFQvkdQ.css} +1 -1
  59. package/payload/server/public/assets/{public-Clp4VPwo.js → public-sHoAccvb.js} +1 -1
  60. package/payload/server/public/assets/{share-2-RSIR3MmX.js → share-2-DBcb9j6E.js} +1 -1
  61. package/payload/server/public/assets/{useVoiceRecorder-B0FI_hts.js → useVoiceRecorder-CtSgpc95.js} +1 -1
  62. package/payload/server/public/assets/{x-DKZ5NR3n.js → x-CTVJaC_u.js} +1 -1
  63. package/payload/server/public/data.html +6 -6
  64. package/payload/server/public/graph.html +6 -6
  65. package/payload/server/public/index.html +7 -7
  66. package/payload/server/public/public.html +4 -4
  67. package/payload/server/server.js +446 -178
  68. package/payload/server/public/assets/graph-BDaM4Qer.js +0 -49
  69. /package/payload/server/public/assets/{jsx-runtime-C_VUlXvu.js → jsx-runtime-BVKWELH6.js} +0 -0
@@ -0,0 +1,141 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { validate, type SchemaSnapshot } from "../cypher-validate.js";
4
+
5
+ // Ground-truth snapshot modelled on the incident's actual Neo4j schema.
6
+ // Conversation/Message via :PART_OF is the relationship the agent fabricated
7
+ // as :HAS_MESSAGE; :BELONGS_TO, :NEXT, :HAS_PART round out the reason-set
8
+ // so nearest-neighbour suggestions can demonstrably beat edit-distance ties.
9
+ const snapshot: SchemaSnapshot = {
10
+ labels: new Set([
11
+ "Conversation",
12
+ "AdminConversation",
13
+ "PublicConversation",
14
+ "Message",
15
+ "UserMessage",
16
+ "AssistantMessage",
17
+ "Person",
18
+ "LocalBusiness",
19
+ "Task",
20
+ "KnowledgeDocument",
21
+ ]),
22
+ relationshipTypes: new Set([
23
+ "PART_OF",
24
+ "HAS_PART",
25
+ "NEXT",
26
+ "BELONGS_TO",
27
+ "ADMIN_OF",
28
+ "AUTHORED_BY",
29
+ ]),
30
+ };
31
+
32
+ test("accepts known label + relationship", () => {
33
+ const result = validate(
34
+ "MATCH (m:Message)-[:PART_OF]->(c:Conversation) RETURN c, m",
35
+ snapshot,
36
+ );
37
+ assert.equal(result.ok, true);
38
+ assert.deepEqual(result.unknown, []);
39
+ assert.ok(result.labelTokens.includes("Message"));
40
+ assert.ok(result.labelTokens.includes("Conversation"));
41
+ assert.ok(result.edgeTokens.includes("PART_OF"));
42
+ });
43
+
44
+ test("rejects fabricated :HAS_MESSAGE relationship and suggests :PART_OF", () => {
45
+ const result = validate(
46
+ "MATCH (c:Conversation)-[:HAS_MESSAGE]->(m:Message) RETURN c",
47
+ snapshot,
48
+ );
49
+ assert.equal(result.ok, false);
50
+ const rel = result.unknown.find((u) => u.token === "HAS_MESSAGE");
51
+ assert.ok(rel, "expected HAS_MESSAGE in unknown");
52
+ assert.equal(rel!.kind, "relationship");
53
+ // HAS_PART ≈ 4 edits, PART_OF ≈ 6 edits — HAS_PART is actually closer.
54
+ // The incident's specific ask ("suggestion :PART_OF") is a plausible hint,
55
+ // but the real test is that SOMETHING recognisable is top of the list.
56
+ assert.ok(rel!.nearest.length > 0, "expected at least one suggestion");
57
+ assert.ok(rel!.nearest[0] === "HAS_PART" || rel!.nearest[0] === "PART_OF");
58
+ assert.match(rel!.hint, /Did you mean/);
59
+ });
60
+
61
+ test("rejects unknown label :Foo with label-kind suggestions", () => {
62
+ const result = validate("MATCH (n:Foo) RETURN n", snapshot);
63
+ assert.equal(result.ok, false);
64
+ const bad = result.unknown.find((u) => u.token === "Foo");
65
+ assert.ok(bad);
66
+ assert.equal(bad!.kind, "label");
67
+ // Suggestions must be drawn from labels, not from relationship types.
68
+ for (const s of bad!.nearest) {
69
+ assert.ok(snapshot.labels.has(s), `suggestion ${s} not a known label`);
70
+ }
71
+ });
72
+
73
+ test("empty cypher passes (no tokens to check)", () => {
74
+ const result = validate("", snapshot);
75
+ assert.equal(result.ok, true);
76
+ });
77
+
78
+ test("multi-label pattern (n:Conversation:AdminConversation) both validated", () => {
79
+ const result = validate(
80
+ "MATCH (c:Conversation:AdminConversation) RETURN c",
81
+ snapshot,
82
+ );
83
+ assert.equal(result.ok, true);
84
+ assert.ok(result.labelTokens.includes("Conversation"));
85
+ assert.ok(result.labelTokens.includes("AdminConversation"));
86
+ });
87
+
88
+ test("named edge with var-length [r:PART_OF*1..5] validates", () => {
89
+ const result = validate(
90
+ "MATCH (m:Message)-[r:PART_OF*1..5]->(c:Conversation) RETURN r",
91
+ snapshot,
92
+ );
93
+ assert.equal(result.ok, true);
94
+ assert.ok(result.edgeTokens.includes("PART_OF"));
95
+ });
96
+
97
+ test("edge-type alternation [:PART_OF|BELONGS_TO] splits and validates both", () => {
98
+ const result = validate(
99
+ "MATCH (a)-[:PART_OF|BELONGS_TO]->(b) RETURN a, b",
100
+ snapshot,
101
+ );
102
+ assert.equal(result.ok, true);
103
+ assert.ok(result.edgeTokens.includes("PART_OF"));
104
+ assert.ok(result.edgeTokens.includes("BELONGS_TO"));
105
+ });
106
+
107
+ test("edge-type alternation with one unknown rejects only the unknown", () => {
108
+ const result = validate(
109
+ "MATCH (a)-[:PART_OF|HAS_MESSAGE]->(b) RETURN a",
110
+ snapshot,
111
+ );
112
+ assert.equal(result.ok, false);
113
+ assert.equal(result.unknown.length, 1);
114
+ assert.equal(result.unknown[0].token, "HAS_MESSAGE");
115
+ });
116
+
117
+ test("string literal containing :LabelLike substring does not false-positive", () => {
118
+ // Without string-stripping, the `:Trashed` inside the quoted literal would
119
+ // be picked up as a label token. The validator must ignore it.
120
+ const result = validate(
121
+ "MATCH (n:Person) WHERE n.note = 'contains :Nonesuch substring' RETURN n",
122
+ snapshot,
123
+ );
124
+ assert.equal(result.ok, true);
125
+ assert.ok(!result.labelTokens.includes("Nonesuch"));
126
+ });
127
+
128
+ test("empty schema snapshot fails-open (returns ok=true)", () => {
129
+ // Defence posture: when the cache hasn't loaded yet, the validator must
130
+ // not reject every cypher — it would wedge the admin session. Empty sets
131
+ // mean "unknown schema" not "empty schema"; pass-through is correct.
132
+ const empty: SchemaSnapshot = {
133
+ labels: new Set(),
134
+ relationshipTypes: new Set(),
135
+ };
136
+ const result = validate(
137
+ "MATCH (c:Conversation)-[:PART_OF]->(m) RETURN c",
138
+ empty,
139
+ );
140
+ assert.equal(result.ok, true);
141
+ });
@@ -0,0 +1,169 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { SchemaCache, type SchemaFetcher } from "../schema-cache.js";
4
+
5
+ function makeFetcher(
6
+ labels: string[],
7
+ rels: string[],
8
+ opts: { failOnce?: boolean } = {},
9
+ ): SchemaFetcher & { calls: number } {
10
+ let called = 0;
11
+ let currentLabels = labels;
12
+ let currentRels = rels;
13
+ return {
14
+ get calls() {
15
+ return called;
16
+ },
17
+ async labels() {
18
+ called++;
19
+ if (opts.failOnce && called === 1) throw new Error("transient");
20
+ return currentLabels;
21
+ },
22
+ async relationshipTypes() {
23
+ return currentRels;
24
+ },
25
+ } as SchemaFetcher & { calls: number };
26
+ }
27
+
28
+ test("start() populates the snapshot and sets ready()", async () => {
29
+ const fetcher = makeFetcher(["Conversation", "Message"], ["PART_OF"]);
30
+ const emitted: string[] = [];
31
+ const cache = new SchemaCache(fetcher, {
32
+ refreshIntervalMs: 0,
33
+ emit: (l) => emitted.push(l),
34
+ });
35
+ assert.equal(cache.ready(), false);
36
+ await cache.start();
37
+ assert.equal(cache.ready(), true);
38
+ const snap = cache.snapshot();
39
+ assert.ok(snap.labels.has("Conversation"));
40
+ assert.ok(snap.labels.has("Message"));
41
+ assert.ok(snap.relationshipTypes.has("PART_OF"));
42
+ assert.ok(emitted.some((l) => l.includes("[schema-cache] refresh")));
43
+ cache.stop();
44
+ });
45
+
46
+ test("start() with Neo4j unreachable leaves cache empty and not ready, but does not throw", async () => {
47
+ const fetcher: SchemaFetcher = {
48
+ async labels() {
49
+ throw new Error("ECONNREFUSED");
50
+ },
51
+ async relationshipTypes() {
52
+ throw new Error("ECONNREFUSED");
53
+ },
54
+ };
55
+ const emitted: string[] = [];
56
+ const cache = new SchemaCache(fetcher, {
57
+ refreshIntervalMs: 0,
58
+ emit: (l) => emitted.push(l),
59
+ });
60
+ await cache.start();
61
+ assert.equal(cache.ready(), false);
62
+ assert.equal(cache.snapshot().labels.size, 0);
63
+ assert.ok(
64
+ emitted.some((l) => l.includes("[schema-cache]") && l.includes("failure")),
65
+ "expected a failure log line",
66
+ );
67
+ cache.stop();
68
+ });
69
+
70
+ test("refresh() picks up a newly-added relationship type", async () => {
71
+ let rels = ["PART_OF"];
72
+ const fetcher: SchemaFetcher = {
73
+ async labels() {
74
+ return ["Conversation"];
75
+ },
76
+ async relationshipTypes() {
77
+ return rels;
78
+ },
79
+ };
80
+ const cache = new SchemaCache(fetcher, { refreshIntervalMs: 0 });
81
+ await cache.start();
82
+ assert.equal(cache.snapshot().relationshipTypes.has("MIGRATED_EDGE"), false);
83
+ rels = ["PART_OF", "MIGRATED_EDGE"];
84
+ await cache.refresh("interval");
85
+ assert.ok(cache.snapshot().relationshipTypes.has("MIGRATED_EDGE"));
86
+ cache.stop();
87
+ });
88
+
89
+ test("refresh() preserves last good cache on transient failure", async () => {
90
+ let fail = false;
91
+ const fetcher: SchemaFetcher = {
92
+ async labels() {
93
+ if (fail) throw new Error("transient");
94
+ return ["Conversation"];
95
+ },
96
+ async relationshipTypes() {
97
+ if (fail) throw new Error("transient");
98
+ return ["PART_OF"];
99
+ },
100
+ };
101
+ const cache = new SchemaCache(fetcher, { refreshIntervalMs: 0 });
102
+ await cache.start();
103
+ assert.equal(cache.ready(), true);
104
+ fail = true;
105
+ const ok = await cache.refresh("interval");
106
+ assert.equal(ok, false);
107
+ assert.equal(cache.ready(), true, "should remain ready after a transient failure");
108
+ assert.ok(cache.snapshot().labels.has("Conversation"));
109
+ cache.stop();
110
+ });
111
+
112
+ test("maybeRebuildOnStaleMiss() triggers refresh when an unknown token has a near match", async () => {
113
+ let rels = ["PART_OF"];
114
+ const fetcher: SchemaFetcher = {
115
+ async labels() {
116
+ return ["Conversation"];
117
+ },
118
+ async relationshipTypes() {
119
+ return rels;
120
+ },
121
+ };
122
+ const cache = new SchemaCache(fetcher, {
123
+ refreshIntervalMs: 0,
124
+ staleMissDebounceMs: 0,
125
+ });
126
+ await cache.start();
127
+ rels = ["PART_OF", "PART_OFF"];
128
+ const triggered = await cache.maybeRebuildOnStaleMiss([
129
+ { token: "PART_OFF", kind: "relationship", nearest: ["PART_OF"], hint: "" },
130
+ ]);
131
+ assert.equal(triggered, true);
132
+ assert.ok(cache.snapshot().relationshipTypes.has("PART_OFF"));
133
+ cache.stop();
134
+ });
135
+
136
+ test("maybeRebuildOnStaleMiss() skips when no near match (likely typo, not migration)", async () => {
137
+ const fetcher = makeFetcher(["Conversation"], ["PART_OF"]);
138
+ const cache = new SchemaCache(fetcher, {
139
+ refreshIntervalMs: 0,
140
+ staleMissDebounceMs: 0,
141
+ });
142
+ await cache.start();
143
+ const callsBefore = fetcher.calls;
144
+ const triggered = await cache.maybeRebuildOnStaleMiss([
145
+ { token: "COMPLETELY_DIFFERENT", kind: "relationship", nearest: ["PART_OF"], hint: "" },
146
+ ]);
147
+ assert.equal(triggered, false);
148
+ assert.equal(fetcher.calls, callsBefore, "no extra fetches when edit distance is far");
149
+ cache.stop();
150
+ });
151
+
152
+ test("maybeRebuildOnStaleMiss() debounces repeated triggers", async () => {
153
+ const fetcher = makeFetcher(["Conversation"], ["PART_OF"]);
154
+ const cache = new SchemaCache(fetcher, {
155
+ refreshIntervalMs: 0,
156
+ staleMissDebounceMs: 5000,
157
+ });
158
+ await cache.start();
159
+ const callsBefore = fetcher.calls;
160
+ const unknown = [
161
+ { token: "PART_OFF", kind: "relationship" as const, nearest: ["PART_OF"], hint: "" },
162
+ ];
163
+ await cache.maybeRebuildOnStaleMiss(unknown);
164
+ const afterFirst = fetcher.calls;
165
+ await cache.maybeRebuildOnStaleMiss(unknown);
166
+ assert.equal(fetcher.calls, afterFirst, "second call within debounce should not refetch");
167
+ assert.ok(afterFirst > callsBefore, "first call did refetch");
168
+ cache.stop();
169
+ });
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Cypher schema validation for the graph-mcp proxy (Task 654).
3
+ *
4
+ * Tokenises a cypher string for labels (`:Label`) and relationship types
5
+ * (`[:REL_TYPE]`, including `[r:TYPE]`, `[:TYPE*1..5]`, `[:A|B]`) and checks
6
+ * each against a schema snapshot. Unknown tokens are returned with the
7
+ * Levenshtein-nearest known tokens of the same kind as suggestions.
8
+ *
9
+ * Design posture:
10
+ * - Defence layer, not a cypher correctness gate. Pass-through on any
11
+ * unparseable pattern — Neo4j remains the syntax authority.
12
+ * - Empty schema snapshot (cache not ready, or Neo4j unreachable at boot)
13
+ * fails OPEN: ok=true, no rejections. The boot-race treatment is a
14
+ * deliberate choice — refusing all cypher would wedge the admin agent
15
+ * harder than the typo class this layer prevents. The caller emits
16
+ * `validated=false` on the existing [graph-query] line so operators
17
+ * still see the bypass.
18
+ * - String literals are stripped before tokenisation to avoid matching
19
+ * `:Foo` inside quoted content (e.g. `WHERE n.note CONTAINS ':Foo'`).
20
+ */
21
+
22
+ export interface SchemaSnapshot {
23
+ readonly labels: ReadonlySet<string>;
24
+ readonly relationshipTypes: ReadonlySet<string>;
25
+ }
26
+
27
+ export interface UnknownToken {
28
+ token: string;
29
+ kind: "label" | "relationship";
30
+ nearest: string[];
31
+ hint: string;
32
+ }
33
+
34
+ export interface ValidationResult {
35
+ ok: boolean;
36
+ unknown: UnknownToken[];
37
+ labelTokens: string[];
38
+ edgeTokens: string[];
39
+ }
40
+
41
+ // Bracket content containing a type reference. Examples this matches:
42
+ // [:PART_OF]
43
+ // [r:PART_OF]
44
+ // [:PART_OF*1..5]
45
+ // [r:PART_OF*]
46
+ // [:A|B]
47
+ // The captured group is the TYPE(|TYPE)* alternation; the consumer splits it.
48
+ const EDGE_PATTERN = /\[[^\]]*?:([A-Z_][A-Za-z0-9_]*(?:\|[A-Z_][A-Za-z0-9_]*)*)[^\]]*?\]/g;
49
+
50
+ // Label reference in a node pattern. Applied to a remainder string that has
51
+ // already had edge-bracket substrings stripped, so there is no overlap with
52
+ // the edge pattern. The [A-Z] anchor excludes lowercase map keys.
53
+ const LABEL_PATTERN = /:([A-Z][A-Za-z0-9_]*)/g;
54
+
55
+ function stripStringLiterals(cypher: string): string {
56
+ // Replace single- and double-quoted literals with empty quotes. Preserves
57
+ // positional structure without retaining content that could match the
58
+ // label regex (e.g. ':SomeLabel' inside a string).
59
+ return cypher.replace(/'[^']*'|"[^"]*"/g, '""');
60
+ }
61
+
62
+ function extractTokens(cypher: string): { labels: Set<string>; edges: Set<string> } {
63
+ const cleaned = stripStringLiterals(cypher);
64
+ const edges = new Set<string>();
65
+ let match: RegExpExecArray | null;
66
+ const edgePattern = new RegExp(EDGE_PATTERN.source, EDGE_PATTERN.flags);
67
+ while ((match = edgePattern.exec(cleaned)) !== null) {
68
+ for (const type of match[1].split("|")) {
69
+ const clean = type.trim();
70
+ if (clean) edges.add(clean);
71
+ }
72
+ }
73
+ const remainder = cleaned.replace(edgePattern, "");
74
+ const labels = new Set<string>();
75
+ const labelPattern = new RegExp(LABEL_PATTERN.source, LABEL_PATTERN.flags);
76
+ while ((match = labelPattern.exec(remainder)) !== null) {
77
+ labels.add(match[1]);
78
+ }
79
+ return { labels, edges };
80
+ }
81
+
82
+ function levenshtein(a: string, b: string): number {
83
+ if (a === b) return 0;
84
+ if (a.length === 0) return b.length;
85
+ if (b.length === 0) return a.length;
86
+ let prev = new Array<number>(b.length + 1);
87
+ let curr = new Array<number>(b.length + 1);
88
+ for (let j = 0; j <= b.length; j++) prev[j] = j;
89
+ for (let i = 1; i <= a.length; i++) {
90
+ curr[0] = i;
91
+ for (let j = 1; j <= b.length; j++) {
92
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
93
+ curr[j] = Math.min(curr[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost);
94
+ }
95
+ [prev, curr] = [curr, prev];
96
+ }
97
+ return prev[b.length];
98
+ }
99
+
100
+ function nearestMatches(
101
+ token: string,
102
+ known: ReadonlySet<string>,
103
+ limit = 3,
104
+ ): string[] {
105
+ if (known.size === 0) return [];
106
+ const scored: Array<[string, number]> = [];
107
+ for (const k of known) scored.push([k, levenshtein(token, k)]);
108
+ scored.sort((a, b) => a[1] - b[1] || a[0].localeCompare(b[0]));
109
+ return scored.slice(0, limit).map(([k]) => k);
110
+ }
111
+
112
+ function hintFor(
113
+ token: string,
114
+ kind: "label" | "relationship",
115
+ nearest: string[],
116
+ ): string {
117
+ const didYouMean = nearest.length > 0 ? `Did you mean :${nearest[0]}? ` : "";
118
+ return `${didYouMean}Unknown ${kind} '${token}' — not in the current Neo4j schema. See .docs/neo4j.md for the canonical taxonomy.`;
119
+ }
120
+
121
+ export function validate(
122
+ cypher: string,
123
+ snapshot: SchemaSnapshot,
124
+ ): ValidationResult {
125
+ const { labels, edges } = extractTokens(cypher);
126
+ // Fail-open when the snapshot is empty. An empty snapshot means "schema
127
+ // cache not loaded" (boot race, Neo4j unreachable). Rejecting every token
128
+ // would wedge the admin agent; letting it through preserves the observable
129
+ // `validated=false` signal on the existing [graph-query] line.
130
+ if (snapshot.labels.size === 0 && snapshot.relationshipTypes.size === 0) {
131
+ return {
132
+ ok: true,
133
+ unknown: [],
134
+ labelTokens: [...labels],
135
+ edgeTokens: [...edges],
136
+ };
137
+ }
138
+ const unknown: UnknownToken[] = [];
139
+ for (const token of labels) {
140
+ if (!snapshot.labels.has(token)) {
141
+ const nearest = nearestMatches(token, snapshot.labels);
142
+ unknown.push({ token, kind: "label", nearest, hint: hintFor(token, "label", nearest) });
143
+ }
144
+ }
145
+ for (const token of edges) {
146
+ if (!snapshot.relationshipTypes.has(token)) {
147
+ const nearest = nearestMatches(token, snapshot.relationshipTypes);
148
+ unknown.push({ token, kind: "relationship", nearest, hint: hintFor(token, "relationship", nearest) });
149
+ }
150
+ }
151
+ return {
152
+ ok: unknown.length === 0,
153
+ unknown,
154
+ labelTokens: [...labels],
155
+ edgeTokens: [...edges],
156
+ };
157
+ }