@ecubelabs/mysql-mcp 0.0.1 → 1.0.0-next.2

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.
@@ -1,294 +1,79 @@
1
- import { execFile } from 'child_process';
2
- import { promisify } from 'util';
3
- const execFileAsync = promisify(execFile);
4
- const THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1_000;
5
- const GIT_TIMEOUT_MS = 10_000;
6
- export function modelPaths(output) {
7
- return output.split('\0').filter((path) => path.endsWith('model.md'));
1
+ import * as path from 'path';
2
+ const GITHUB_REPO_FORMS = [
3
+ /^https:\/\/github\.com\/([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/i,
4
+ /^git@github\.com:([^/\s]+)\/([^/\s]+?)(?:\.git)?$/i,
5
+ /^([^/\s:@]+)\/([^/\s:@]+?)(?:\.git)?$/,
6
+ ];
7
+ export function normalizeGithubRepo(input) {
8
+ const trimmed = typeof input === 'string' ? input.trim() : '';
9
+ for (const form of GITHUB_REPO_FORMS) {
10
+ const match = form.exec(trimmed);
11
+ if (!match) {
12
+ continue;
13
+ }
14
+ const [, owner, name] = match;
15
+ if (/^[A-Za-z0-9-]+$/.test(owner) && /^[A-Za-z0-9._-]+$/.test(name) && name !== '.' && name !== '..') {
16
+ return `${owner}/${name}`;
17
+ }
18
+ }
19
+ throw new Error(`Document repo must be a GitHub repository as owner/name, https://github.com/owner/name, ` +
20
+ `or git@github.com:owner/name: "${input}".`);
8
21
  }
9
- export function parseDiff(output) {
10
- const entries = [];
11
- const fields = output.split('\0');
12
- let index = 0;
13
- while (index < fields.length) {
14
- const kind = fields[index]?.[0];
15
- if (kind === 'R' || kind === 'C') {
16
- const oldPath = fields[index + 1];
17
- const path = fields[index + 2];
18
- if (kind === 'R' && oldPath && path) {
19
- entries.push({ status: 'R', oldPath, path });
20
- }
21
- index += 3;
22
- }
23
- else if (kind) {
24
- const path = fields[index + 1];
25
- if ((kind === 'A' || kind === 'D' || kind === 'M') && path) {
26
- entries.push({ status: kind, path });
27
- }
28
- index += 2;
29
- }
30
- else {
31
- index += 1;
32
- }
22
+ export function normalizeDocumentPath(input) {
23
+ const trimmed = input.trim();
24
+ if (!trimmed) {
25
+ throw new Error('Document path must not be empty.');
33
26
  }
34
- return entries;
35
- }
36
- function linkedDocumentPaths(catalog) {
37
- const linked = new Set();
38
- for (const schema of Object.values(catalog.schemas)) {
39
- for (const table of Object.values(schema.tables)) {
40
- if (table.curated.doc) {
41
- linked.add(table.curated.doc.path);
42
- }
43
- }
27
+ if (path.posix.isAbsolute(trimmed) || path.win32.isAbsolute(trimmed)) {
28
+ throw new Error(`Document path must be relative to the repository root (e.g. apps/<app>/.../model.md): "${input}".`);
44
29
  }
45
- return linked;
46
- }
47
- function refreshUnlinked(catalog) {
48
- const linked = linkedDocumentPaths(catalog);
49
- catalog.docs.unlinked = catalog.docs.paths.filter((path) => !linked.has(path));
50
- }
51
- function shellQuote(value) {
52
- if (/^[A-Za-z0-9_./:@+-]+$/.test(value)) {
53
- return value;
30
+ const segments = trimmed.split(/[\\/]+/);
31
+ if (segments.includes('..')) {
32
+ throw new Error(`Document path must not contain "..": "${input}".`);
33
+ }
34
+ const normalized = segments.filter((segment) => segment !== '' && segment !== '.').join('/');
35
+ if (!normalized) {
36
+ throw new Error(`Document path must name a file: "${input}".`);
54
37
  }
55
- return `'${value.replace(/'/g, `'"'"'`)}'`;
38
+ return normalized;
56
39
  }
57
40
  export class CatalogDocuments {
58
41
  store;
59
- options;
60
- attempted = false;
61
- wakePromise = null;
62
- wakeSpent = false;
63
- disabledReason = null;
64
- constructor(store, options) {
42
+ constructor(store) {
65
43
  this.store = store;
66
- this.options = options;
67
- }
68
- isConfigured() {
69
- return Boolean(this.options.repo && this.options.ref);
70
- }
71
- isAvailable() {
72
- return this.isConfigured() && this.disabledReason === null;
73
- }
74
- error() {
75
- return this.disabledReason;
76
44
  }
77
- resetWake() {
78
- this.attempted = false;
79
- this.disabledReason = null;
80
- this.wakeSpent = this.wakePromise !== null;
81
- }
82
- async git(args) {
83
- if (!this.options.repo) {
84
- throw new Error('MYSQL_DOCS_REPO is not configured.');
85
- }
86
- console.error(`[catalog] git -C ${this.options.repo} ${args.join(' ')}`);
87
- const { stdout } = await execFileAsync('git', ['-C', this.options.repo, ...args], {
88
- encoding: 'utf8',
89
- maxBuffer: 5 * 1024 * 1024,
90
- timeout: GIT_TIMEOUT_MS,
91
- });
92
- return stdout;
93
- }
94
- async ensureAwake() {
95
- if (!this.isConfigured()) {
96
- throw new Error('The document catalog is disabled because MYSQL_DOCS_REPO or MYSQL_CODE_BRANCH is not configured.');
97
- }
98
- if (this.disabledReason) {
99
- throw new Error(this.disabledReason);
100
- }
101
- if (this.attempted && !this.wakePromise) {
102
- return;
103
- }
104
- let promise = this.wakePromise;
105
- if (!promise || this.wakeSpent) {
106
- this.attempted = true;
107
- const previous = promise && this.wakeSpent ? promise.catch(() => undefined) : null;
108
- this.wakeSpent = false;
109
- promise = (previous ?? Promise.resolve())
110
- .then(() => this.wake())
111
- .catch((error) => {
112
- this.disabledReason = `The document catalog is unavailable: ${error instanceof Error ? error.message : String(error)}`;
113
- console.error(`[catalog] document axis disabled: ${this.disabledReason}`);
114
- throw new Error(this.disabledReason);
115
- });
116
- this.wakePromise = promise;
117
- }
118
- try {
119
- await promise;
120
- }
121
- finally {
122
- if (this.wakePromise === promise) {
123
- this.wakePromise = null;
124
- }
125
- }
126
- }
127
- async wake() {
128
- const ref = this.options.ref;
129
- const commit = (await this.git(['rev-parse', '--verify', `${ref}^{commit}`])).trim();
130
- const cached = this.store.docsView();
131
- if (cached.refCommit === commit) {
132
- return;
133
- }
134
- let entries = null;
135
- if (cached.refCommit) {
136
- try {
137
- entries = parseDiff(await this.git(['diff', '--name-status', '-z', cached.refCommit, commit, '--', '*model.md']));
138
- }
139
- catch (error) {
140
- console.error(`[catalog] cached document commit is unavailable; rebuilding path list: ${error instanceof Error ? error.message : String(error)}`);
141
- }
142
- }
143
- if (entries === null) {
144
- const paths = modelPaths(await this.git(['ls-tree', '-r', '-z', '--name-only', commit]));
145
- this.store.update((catalog) => {
146
- catalog.docs.paths = paths;
147
- for (const schema of Object.values(catalog.schemas)) {
148
- for (const table of Object.values(schema.tables)) {
149
- if (table.curated.doc && !paths.includes(table.curated.doc.path)) {
150
- delete table.curated.doc;
151
- }
152
- }
153
- }
154
- refreshUnlinked(catalog);
155
- });
156
- }
157
- else {
158
- this.store.update((catalog) => {
159
- for (const entry of entries) {
160
- if (entry.status === 'M') {
161
- continue;
162
- }
163
- if (entry.status === 'A') {
164
- if (!catalog.docs.paths.includes(entry.path)) {
165
- catalog.docs.paths.push(entry.path);
166
- }
167
- continue;
168
- }
169
- if (entry.status === 'D') {
170
- catalog.docs.paths = catalog.docs.paths.filter((path) => path !== entry.path);
171
- for (const schema of Object.values(catalog.schemas)) {
172
- for (const table of Object.values(schema.tables)) {
173
- if (table.curated.doc?.path === entry.path) {
174
- delete table.curated.doc;
175
- }
176
- }
177
- }
178
- continue;
179
- }
180
- const oldPath = entry.oldPath;
181
- catalog.docs.paths = catalog.docs.paths.map((path) => (path === oldPath ? entry.path : path));
182
- if (!catalog.docs.paths.includes(entry.path)) {
183
- catalog.docs.paths.push(entry.path);
184
- }
185
- for (const schema of Object.values(catalog.schemas)) {
186
- for (const table of Object.values(schema.tables)) {
187
- if (table.curated.doc?.path === oldPath) {
188
- table.curated.doc.path = entry.path;
189
- }
190
- }
191
- }
192
- }
193
- catalog.docs.paths = [...new Set(catalog.docs.paths)].sort();
194
- refreshUnlinked(catalog);
195
- });
196
- }
197
- let refUpdatedAt = null;
198
- try {
199
- const seconds = Number((await this.git(['show', '-s', '--format=%ct', commit])).trim());
200
- if (Number.isFinite(seconds)) {
201
- refUpdatedAt = new Date(seconds * 1_000).toISOString();
202
- }
203
- }
204
- catch (error) {
205
- console.error(`[catalog] could not read document ref timestamp: ${error instanceof Error ? error.message : String(error)}`);
206
- }
207
- this.store.update((catalog) => {
208
- catalog.docs.repo = this.options.repo;
209
- catalog.docs.ref = this.options.ref;
210
- catalog.docs.refCommit = commit;
211
- catalog.docs.refUpdatedAt = refUpdatedAt;
212
- });
213
- console.error(`[catalog] document paths refreshed: ${this.store.docsView().paths.length} files at ${ref}`);
214
- }
215
- async list(schemaName) {
216
- await this.ensureAwake();
217
- const mapping = this.options.appSchemas.find((entry) => entry.schema.toLowerCase() === schemaName.toLowerCase());
218
- if (!mapping) {
219
- throw new Error(`Schema "${schemaName}" is not declared in MYSQL_APP_SCHEMAS.`);
220
- }
221
- const catalog = this.store.snapshot();
222
- const prefix = `apps/${mapping.app}/`;
223
- const inPrefix = catalog.docs.paths.filter((path) => path.startsWith(prefix));
224
- const scoped = inPrefix.length > 0;
225
- const selected = scoped ? inPrefix : catalog.docs.paths;
226
- const linkedTablesFor = (path) => Object.entries(catalog.schemas).flatMap(([knownSchema, schema]) => Object.entries(schema.tables)
227
- .filter(([, table]) => table.curated.doc?.path === path)
228
- .map(([table]) => `${knownSchema}.${table}`));
229
- const paths = selected.map((path) => ({
230
- path,
231
- linkedTables: linkedTablesFor(path),
45
+ link(links) {
46
+ const resolved = links.map((link) => ({
47
+ ...link,
48
+ doc: normalizeDocumentPath(link.doc),
49
+ repo: normalizeGithubRepo(link.repo),
232
50
  }));
233
- const outsidePrefix = catalog.docs.paths.length - inPrefix.length;
234
- const notice = scoped
235
- ? outsidePrefix > 0
236
- ? `${outsidePrefix}개 문서는 "${prefix}" 밖에 있어 제외했습니다. ` +
237
- 'map의 unlinkedDocuments에 전체 목록이 있고, docs_read는 카탈로그에 ' +
238
- '있는 어떤 경로든 읽습니다.'
239
- : null
240
- : `"${prefix}" 로 시작하는 문서가 없어 카탈로그의 모든 문서를 반환했습니다. ` +
241
- `MYSQL_APP_SCHEMAS의 앱 이름("${mapping.app}")이 저장소 디렉토리와 다를 수 있습니다.`;
242
- const warning = this.staleWarning();
243
- return JSON.stringify({
244
- schema: schemaName,
245
- app: mapping.app,
246
- ref: catalog.docs.ref,
247
- scopedToApp: scoped,
248
- paths,
249
- ...(notice ? { notice } : {}),
250
- ...(warning ? { warning } : {}),
251
- }, null, 2);
252
- }
253
- async read(documentPath) {
254
- await this.ensureAwake();
255
- const catalog = this.store.snapshot();
256
- if (!catalog.docs.paths.includes(documentPath)) {
257
- throw new Error(`Document "${documentPath}" is not present at ${catalog.docs.ref}. Use docs_list or map to choose a cataloged path.`);
258
- }
259
- const content = await this.git(['show', `${catalog.docs.ref}:${documentPath}`]);
260
- const warning = this.staleWarning();
261
- return warning ? `${warning}\n\n${content}` : content;
262
- }
263
- async link(links) {
264
- await this.ensureAwake();
265
51
  const snapshot = this.store.snapshot();
266
- for (const link of links) {
267
- if (!snapshot.docs.paths.includes(link.doc)) {
268
- throw new Error(`Document "${link.doc}" is not present at ${snapshot.docs.ref}.`);
269
- }
52
+ for (const link of resolved) {
270
53
  if (!snapshot.schemas[link.schema]?.tables[link.table]) {
271
54
  throw new Error(`Unknown table "${link.schema}.${link.table}".`);
272
55
  }
273
56
  }
274
57
  const now = new Date().toISOString();
275
58
  this.store.update((catalog) => {
276
- for (const link of links) {
277
- catalog.schemas[link.schema].tables[link.table].curated.doc = {
278
- path: link.doc,
279
- linkedBy: 'model',
280
- linkedAt: now,
281
- linkedAtCommit: catalog.docs.refCommit,
282
- };
59
+ for (const link of resolved) {
60
+ const table = catalog.schemas[link.schema]?.tables[link.table];
61
+ if (table) {
62
+ table.curated.doc = {
63
+ path: link.doc,
64
+ repo: link.repo,
65
+ linkedBy: 'model',
66
+ linkedAt: now,
67
+ };
68
+ }
283
69
  }
284
- refreshUnlinked(catalog);
285
70
  });
286
71
  return JSON.stringify({
287
- linked: links.map((link) => ({
72
+ linked: resolved.map((link) => ({
288
73
  table: `${link.schema}.${link.table}`,
289
74
  doc: link.doc,
75
+ repo: link.repo,
290
76
  })),
291
- ...(this.staleWarning() ? { warning: this.staleWarning() } : {}),
292
77
  }, null, 2);
293
78
  }
294
79
  unlink(schemaName, tableName) {
@@ -298,31 +83,11 @@ export class CatalogDocuments {
298
83
  }
299
84
  this.store.update((catalog) => {
300
85
  catalog.schemas[schemaName].tables[tableName].curated.doc = null;
301
- refreshUnlinked(catalog);
302
86
  });
303
87
  return JSON.stringify({
304
88
  table: `${schemaName}.${tableName}`,
305
89
  doc: null,
306
90
  status: '문서 없음 또는 연결 해제를 확인했습니다.',
307
- ...(this.staleWarning() ? { warning: this.staleWarning() } : {}),
308
91
  }, null, 2);
309
92
  }
310
- staleWarning() {
311
- const updatedAt = this.store.docsView().refUpdatedAt;
312
- if (!updatedAt) {
313
- return null;
314
- }
315
- const age = Date.now() - Date.parse(updatedAt);
316
- if (!Number.isFinite(age) || age <= THIRTY_DAYS_MS) {
317
- return null;
318
- }
319
- return (`[카탈로그 경고] ${this.options.ref}의 마지막 커밋이 30일 이상 지났습니다. ` +
320
- '필요하면 사용자가 문서 저장소에서 git fetch를 실행해야 합니다.');
321
- }
322
- documentCommand(documentPath) {
323
- if (!this.options.repo || !this.options.ref) {
324
- return null;
325
- }
326
- return `git -C ${shellQuote(this.options.repo)} show ${shellQuote(`${this.options.ref}:${documentPath}`)}`;
327
- }
328
93
  }
@@ -3,7 +3,8 @@ import * as os from 'os';
3
3
  import * as path from 'path';
4
4
  import { CatalogCollector } from './collect.js';
5
5
  import { CatalogDocuments } from './docs.js';
6
- import { renderDescribe, renderMap, renderToolDescriptionSuffix, searchCatalog } from './render.js';
6
+ import { normalizeBranchName } from './branch.js';
7
+ import { missingBranchNotice, renderDescribe, renderMap, renderToolDescriptionSuffix, searchCatalog, } from './render.js';
7
8
  import { CatalogStore } from './store.js';
8
9
  import { emptyUsage, normalizeName, pruneJoins } from './types.js';
9
10
  import { prepareCatalogQuery, resultColumnNames } from './usage.js';
@@ -58,15 +59,39 @@ export class SchemaCatalog {
58
59
  schemas: options.appSchemas.map((entry) => entry.schema),
59
60
  ttlHours: options.ttlHours,
60
61
  });
61
- this.documents = new CatalogDocuments(this.store, {
62
- repo: options.docsRepo,
63
- ref: options.docsRef,
64
- appSchemas: options.appSchemas,
65
- });
62
+ this.documents = new CatalogDocuments(this.store);
66
63
  }
67
64
  isEnabled() {
68
65
  return this.store.isEnabled();
69
66
  }
67
+ codeBranch() {
68
+ return this.isEnabled() ? this.store.codeBranch() : null;
69
+ }
70
+ setCodeBranch(input) {
71
+ if (!this.isEnabled()) {
72
+ throw new Error('The schema catalog is disabled.');
73
+ }
74
+ const branch = normalizeBranchName(input);
75
+ const previous = this.store.codeBranch();
76
+ if (previous === branch) {
77
+ return JSON.stringify({ branch, changed: false, status: `이미 ${branch} 브랜치가 기록돼 있습니다.` }, null, 2);
78
+ }
79
+ this.store.update((catalog) => {
80
+ catalog.codeBranch = branch;
81
+ });
82
+ if (this.store.codeBranch() !== branch) {
83
+ throw new Error('The catalog cache is disabled, so the branch was not recorded.');
84
+ }
85
+ return JSON.stringify({
86
+ branch,
87
+ ...(previous ? { previous } : {}),
88
+ changed: true,
89
+ status: previous
90
+ ? `브랜치를 바꿨습니다: ${previous} → ${branch}`
91
+ : `${branch} 브랜치를 기록했습니다. 다음 세션에도 이어 씁니다.`,
92
+ note: 'banner와 describe는 바로 이 값을 씁니다. mysql_query 툴 설명의 CODE REVISION은 서버를 다시 띄우면 바뀝니다.',
93
+ }, null, 2);
94
+ }
70
95
  startInventory() {
71
96
  if (!this.isEnabled() || this.closing) {
72
97
  return;
@@ -146,16 +171,7 @@ export class SchemaCatalog {
146
171
  if (this.collector.inventoryNeedsRefresh()) {
147
172
  await this.collector.collectInventory(false);
148
173
  }
149
- let documentWarning = null;
150
- if (this.documents.isConfigured()) {
151
- try {
152
- await this.documents.ensureAwake();
153
- }
154
- catch (error) {
155
- documentWarning = error instanceof Error ? error.message : String(error);
156
- }
157
- }
158
- return renderMap(this.store.snapshot(), documentWarning ?? this.documents.staleWarning());
174
+ return renderMap(this.store.snapshot());
159
175
  }
160
176
  async search(query, requestedLimit) {
161
177
  if (!this.isEnabled()) {
@@ -173,27 +189,11 @@ export class SchemaCatalog {
173
189
  }
174
190
  const resolved = await this.ensureKnownTable(input);
175
191
  await this.collector.collectTableDetail(resolved.schema, resolved.table);
176
- let documentError = null;
177
- if (this.documents.isConfigured()) {
178
- try {
179
- await this.documents.ensureAwake();
180
- }
181
- catch (error) {
182
- documentError = error instanceof Error ? error.message : String(error);
183
- }
184
- }
185
192
  const entry = this.store.readTable(resolved.schema, resolved.table);
186
193
  if (!entry) {
187
194
  throw new Error(`Table disappeared during refresh: ${input}`);
188
195
  }
189
- return renderDescribe(`${resolved.schema}.${resolved.table}`, entry, {
190
- configured: this.documents.isConfigured(),
191
- available: this.documents.isAvailable(),
192
- ref: this.options.docsRef,
193
- command: entry.curated.doc ? this.documents.documentCommand(entry.curated.doc.path) : null,
194
- warning: documentError ?? this.documents.staleWarning(),
195
- schema: resolved.schema,
196
- }, this.store.readJoins(resolved.schema, resolved.table));
196
+ return renderDescribe(`${resolved.schema}.${resolved.table}`, entry, this.store.codeBranch(), this.store.readJoins(resolved.schema, resolved.table), this.options.profile);
197
197
  }
198
198
  async refresh(target) {
199
199
  if (!this.isEnabled()) {
@@ -206,15 +206,6 @@ export class SchemaCatalog {
206
206
  return JSON.stringify({
207
207
  refreshed: 'inventory',
208
208
  ...this.inventoryReport(),
209
- ...(this.documents.isConfigured() ? { documents: await this.refreshDocuments() } : {}),
210
- at,
211
- }, null, 2);
212
- }
213
- if (normalizeName(requested) === 'docs') {
214
- return JSON.stringify({
215
- refreshed: 'documents',
216
- documents: await this.refreshDocuments(),
217
- hint: 'A table actually named "docs" must be written as schema.docs.',
218
209
  at,
219
210
  }, null, 2);
220
211
  }
@@ -250,8 +241,8 @@ export class SchemaCatalog {
250
241
  }, null, 2);
251
242
  }
252
243
  throw new Error(`Unknown refresh target "${requested}". Use schema.table for one table's ` +
253
- 'columns, a declared schema name for the table inventory, "docs" for the ' +
254
- 'document axis, or omit target for both.');
244
+ 'columns, a declared schema name for the table inventory, or omit target ' +
245
+ 'for the inventory.');
255
246
  }
256
247
  inventoryReport() {
257
248
  const catalog = this.store.snapshot();
@@ -262,45 +253,6 @@ export class SchemaCatalog {
262
253
  scannedAt: schemas[0]?.scannedAt ?? null,
263
254
  };
264
255
  }
265
- async refreshDocuments() {
266
- if (!this.documents.isConfigured()) {
267
- return {
268
- refreshed: false,
269
- ref: null,
270
- error: 'The document axis is disabled because MYSQL_DOCS_REPO or MYSQL_CODE_BRANCH is not configured.',
271
- };
272
- }
273
- this.documents.resetWake();
274
- try {
275
- await this.documents.ensureAwake();
276
- const docs = this.store.docsView();
277
- return {
278
- refreshed: true,
279
- ref: docs.ref,
280
- refCommit: docs.refCommit,
281
- paths: docs.paths.length,
282
- };
283
- }
284
- catch (error) {
285
- return {
286
- refreshed: false,
287
- ref: this.options.docsRef,
288
- error: error instanceof Error ? error.message : String(error),
289
- };
290
- }
291
- }
292
- async docsList(schemaName) {
293
- if (!this.isEnabled()) {
294
- throw new Error('The schema catalog is disabled.');
295
- }
296
- return this.documents.list(schemaName);
297
- }
298
- async docsRead(documentPath) {
299
- if (!this.isEnabled()) {
300
- throw new Error('The schema catalog is disabled.');
301
- }
302
- return this.documents.read(documentPath);
303
- }
304
256
  async link(links) {
305
257
  if (!this.isEnabled()) {
306
258
  throw new Error('The schema catalog is disabled.');
@@ -315,6 +267,7 @@ export class SchemaCatalog {
315
267
  schema: table.schema,
316
268
  table: table.table,
317
269
  doc: link.doc,
270
+ repo: link.repo,
318
271
  });
319
272
  }
320
273
  return this.documents.link(resolvedLinks);
@@ -441,35 +394,24 @@ export class SchemaCatalog {
441
394
  }, null, 2);
442
395
  }
443
396
  queryDocumentGuidance(prepared) {
444
- if (!this.isEnabled() || !this.documents.isConfigured()) {
397
+ if (!this.isEnabled()) {
445
398
  return null;
446
399
  }
447
- const notices = [];
448
- const documentError = this.documents.error();
449
- if (documentError) {
450
- notices.push(`[카탈로그 경고] ${documentError}`);
451
- }
452
- else {
453
- const stale = this.documents.staleWarning();
454
- if (stale) {
455
- notices.push(stale);
456
- }
457
- }
458
- if (!this.documents.isAvailable()) {
459
- return notices.join('\n') || null;
460
- }
461
- const unresolved = new Map();
400
+ const unreviewed = new Set();
462
401
  for (const reference of prepared.references) {
463
402
  const resolved = this.resolveTable(reference.schema ? `${reference.schema}.${reference.table}` : reference.table);
464
403
  if (resolved && !this.documentReviewed(resolved.schema, resolved.table)) {
465
- unresolved.set(`${resolved.schema}.${resolved.table}`, resolved.schema);
404
+ unreviewed.add(`${resolved.schema}.${resolved.table}`);
466
405
  }
467
406
  }
468
- notices.push(...[...unresolved.entries()].map(([table, schema]) => `[카탈로그] ${table} 에 연결된 문서가 없습니다.\n` +
469
- `mysql_catalog {action:"docs_list", schema:"${schema}"} 로 후보를 보고\n` +
470
- 'mysql_catalog {action:"link", links:[{table:"' +
471
- `${table}", doc:"..."}]} 로 연결하세요.`));
472
- return notices.join('\n\n') || null;
407
+ const [first] = unreviewed;
408
+ if (!first) {
409
+ return null;
410
+ }
411
+ return (`[카탈로그] ${[...unreviewed].join(', ')} 에 연결된 문서가 없습니다.\n` +
412
+ `도메인 문서(model.md)를 찾으면 mysql_catalog {action:"link", links:[{table:"${first}", doc:"<저장소 기준 상대 경로>", repo:"<owner/name>"}]} 로 연결하고,\n` +
413
+ `없으면 mysql_catalog {action:"unlink", table:"${first}"} 로 기록하세요.` +
414
+ (this.store.codeBranch() ? '' : `\n${missingBranchNotice(this.options.profile)}`));
473
415
  }
474
416
  indexFacts(reference) {
475
417
  if (!this.isEnabled()) {
@@ -508,27 +450,15 @@ export class SchemaCatalog {
508
450
  }
509
451
  const task = new Promise((resolve) => {
510
452
  setImmediate(() => {
511
- const documentWake = this.referencesNeedDocuments(prepared.references)
512
- ? this.documents.ensureAwake().catch(() => {
513
- })
514
- : Promise.resolve();
515
- const queryUpdate = this.processQuery(prepared, result, error).catch((cause) => {
453
+ void this.processQuery(prepared, result, error)
454
+ .catch((cause) => {
516
455
  console.error(`[catalog] post-query update failed: ${cause instanceof Error ? cause.message : String(cause)}`);
517
- });
518
- void Promise.all([documentWake, queryUpdate]).then(() => resolve());
456
+ })
457
+ .then(() => resolve());
519
458
  });
520
459
  });
521
460
  this.trackBackgroundTask(task);
522
461
  }
523
- referencesNeedDocuments(references) {
524
- if (!this.documents.isAvailable()) {
525
- return false;
526
- }
527
- return references.some((reference) => {
528
- const resolved = this.resolveTable(reference.schema ? `${reference.schema}.${reference.table}` : reference.table);
529
- return Boolean(resolved && !this.documentReviewed(resolved.schema, resolved.table));
530
- });
531
- }
532
462
  async processQuery(prepared, result, error) {
533
463
  const { references } = prepared;
534
464
  const code = error && typeof error === 'object' && 'code' in error ? String(error.code) : '';
@@ -561,11 +491,6 @@ export class SchemaCatalog {
561
491
  }
562
492
  }
563
493
  const unique = new Map(resolved.map((value) => [`${value.schema}.${value.table}`, value]));
564
- if (this.documents.isAvailable() &&
565
- [...unique.values()].some((value) => !this.documentReviewed(value.schema, value.table))) {
566
- await this.documents.ensureAwake().catch(() => {
567
- });
568
- }
569
494
  const columns = resultColumnNames(result.content?.[0]?.text ?? '');
570
495
  const now = new Date().toISOString();
571
496
  this.store.update((catalog) => {