football-docs 0.12.4 → 0.13.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/README.md +62 -0
- package/data/docs.db +0 -0
- package/dist/data-format.d.ts +96 -0
- package/dist/data-format.js +207 -0
- package/dist/data-source.d.ts +66 -0
- package/dist/data-source.js +147 -0
- package/dist/data-update.d.ts +48 -0
- package/dist/data-update.js +236 -0
- package/dist/index.js +60 -5
- package/dist/ingest.d.ts +2 -2
- package/dist/ingest.js +36 -28
- package/dist/tools.d.ts +5 -1
- package/dist/tools.js +91 -46
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -94,6 +94,42 @@ Add to `claude_desktop_config.json`:
|
|
|
94
94
|
|
|
95
95
|
Provider filters use the indexed provider keys shown by `list_providers`, but common aliases are accepted. Examples: `fbref`, `understat`, `ClubElo`, `football-data.co.uk`, and `engsoccerdata` search `free-sources`; `Sofascore` searches `soccerdata`; `ESPN`, `ESPN FC`, and `espn-soccer` search `espn`; `FMDB` searches `fmdb-pro`; `Transfer Room` searches `transferroom`; `Hudl Wyscout` searches `wyscout`; `Stats Perform` / `Opta F24` / `WhoScored` search `opta`; `Metrica`, `Sportec` / `DFL`, and `TRACAB` search `databallpy`; `Second Spectrum` searches `kloppy`; `Hawk-Eye`, `SciSports`, `Signality`, `Respovision`, `GradientSports` and `OptaVision` search `fast-forward`; `unravel` searches `unravelsports`; `SportRadar API` / `Soccer Extended` search `sportradar`; `The Sports DB` / `TSDB` search `thesportsdb`; `StatsBomb Open Data` searches `statsbomb`.
|
|
96
96
|
|
|
97
|
+
## How the index stays current
|
|
98
|
+
|
|
99
|
+
The package ships a docs index, but doc fixes do not wait for a new package
|
|
100
|
+
version. Once a day at most, the server checks the
|
|
101
|
+
[`data-latest`](https://github.com/withqwerty/football-docs/releases/tag/data-latest)
|
|
102
|
+
release of this repository for a newer index built from `main`:
|
|
103
|
+
|
|
104
|
+
- It reads a small manifest (`manifest-v1.json`) and, only when that names a
|
|
105
|
+
newer build, downloads the index (about 6 MB).
|
|
106
|
+
- It checks the download's size and SHA-256, its SQLite integrity, its exact
|
|
107
|
+
schema and its metadata before using it, and keeps the one it had on any failure.
|
|
108
|
+
- It stores downloads in `$XDG_DATA_HOME/football-docs/data/` (by default
|
|
109
|
+
`~/.local/share/football-docs/data/`). The next tool call uses the new file; no
|
|
110
|
+
restart is needed.
|
|
111
|
+
- It runs in the background after start-up and never delays a tool call.
|
|
112
|
+
`list_providers` ends with the build time of the index in use and whether it is
|
|
113
|
+
bundled or downloaded.
|
|
114
|
+
|
|
115
|
+
Privacy: the check is one HTTPS request a day to GitHub, plus the download when
|
|
116
|
+
there is one. No search queries or other usage data are sent.
|
|
117
|
+
|
|
118
|
+
Settings, as environment variables in the server's MCP configuration:
|
|
119
|
+
|
|
120
|
+
- `FOOTBALL_DOCS_DATA=bundled`: use only the index inside the package. No network,
|
|
121
|
+
no downloads.
|
|
122
|
+
- `FOOTBALL_DOCS_DATA=auto`: the default for an installed package. Check daily and
|
|
123
|
+
use the newest valid index.
|
|
124
|
+
- `FOOTBALL_DOCS_DB_PATH=<file>`: use exactly this index file.
|
|
125
|
+
- `FOOTBALL_DOCS_DATA_BASE_URL=<url>`: read the manifest and index from a mirror
|
|
126
|
+
(HTTPS only).
|
|
127
|
+
|
|
128
|
+
Offline, or behind a proxy that Node's built-in `fetch` does not use, the check
|
|
129
|
+
fails quietly and the server keeps the index it has. Under CI (`CI` set) the check
|
|
130
|
+
does not run. A server running from a git checkout defaults to `bundled`, so
|
|
131
|
+
development and tests always use the working tree's docs.
|
|
132
|
+
|
|
97
133
|
## Example queries
|
|
98
134
|
|
|
99
135
|
- "What is Opta qualifier 76?" (big chance)
|
|
@@ -248,6 +284,32 @@ npm run ingest -- --provider kloppy # re-ingest one provider (incremental)
|
|
|
248
284
|
|
|
249
285
|
Each crawled doc carries provenance metadata (source URL, source type, upstream version, crawl timestamp) that is surfaced in search results, so agents can distinguish between curated content and upstream documentation.
|
|
250
286
|
|
|
287
|
+
### How doc changes reach users
|
|
288
|
+
|
|
289
|
+
A merge to `main` that touches `docs/` or `providers.json` runs
|
|
290
|
+
`.github/workflows/data.yml`, which rebuilds the index, runs the tests against it,
|
|
291
|
+
checks that the **published** server can use it (`scripts/check-data-compat.mjs`),
|
|
292
|
+
and publishes it to the `data-latest` release. Installed servers pick it up within
|
|
293
|
+
about a day, including servers that have been running for days (they check again
|
|
294
|
+
every six hours, at most once a day). Merging a doc PR is therefore also shipping it; there is no later step at
|
|
295
|
+
which to stop it. To undo a bad doc change, revert it on `main`, which publishes a
|
|
296
|
+
newer build.
|
|
297
|
+
|
|
298
|
+
The index carries its own metadata (`meta` table, `src/data-format.ts`): a schema
|
|
299
|
+
version, the oldest server version that can read it, the build stamp and the
|
|
300
|
+
provider registry. Two rules follow:
|
|
301
|
+
|
|
302
|
+
- **Changing the schema** (`SCHEMA_SQL`) needs `DATA_SCHEMA_VERSION` raised and an
|
|
303
|
+
npm release. Servers read only `manifest-v<their schema>.json`, so older servers
|
|
304
|
+
keep their last compatible data rather than breaking.
|
|
305
|
+
- **Data that relies on new server code** (for example a new `providers.json` field
|
|
306
|
+
the tools must read) needs `MIN_SERVER_VERSION` raised, and that server released
|
|
307
|
+
first. Until then the compatibility check fails, and no installed server would
|
|
308
|
+
accept the build anyway.
|
|
309
|
+
|
|
310
|
+
Code changes, including changes to `src/ingest.ts`, still ship only through a
|
|
311
|
+
release.
|
|
312
|
+
|
|
251
313
|
### Cutting a release
|
|
252
314
|
|
|
253
315
|
**Pushing the tag is the release.** `.github/workflows/release.yml` runs on any
|
package/data/docs.db
CHANGED
|
Binary file
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The on-disk format of the docs index, shared by ingest and the server.
|
|
3
|
+
*
|
|
4
|
+
* The index can reach a server two ways: inside the npm package, or downloaded
|
|
5
|
+
* later from the data-latest release (see data-update.ts). Both paths must agree
|
|
6
|
+
* on what a usable file looks like, so the schema, the metadata keys and the
|
|
7
|
+
* validation all live here.
|
|
8
|
+
*/
|
|
9
|
+
import Database from "better-sqlite3";
|
|
10
|
+
import { z } from "zod";
|
|
11
|
+
/** Bump when the table layout changes. Servers only use data with their own version. */
|
|
12
|
+
export declare const DATA_SCHEMA_VERSION = 1;
|
|
13
|
+
/**
|
|
14
|
+
* The oldest server release that can read data built by this code. Raise it when
|
|
15
|
+
* the data starts to rely on server code that older releases lack (a new field in
|
|
16
|
+
* providers.json the tools must read, for example), and release that server first.
|
|
17
|
+
*/
|
|
18
|
+
export declare const MIN_SERVER_VERSION = "0.13.0";
|
|
19
|
+
export declare const SCHEMA_SQL = "\n CREATE TABLE IF NOT EXISTS docs (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n provider TEXT NOT NULL,\n category TEXT NOT NULL,\n title TEXT NOT NULL,\n content TEXT NOT NULL,\n source_url TEXT,\n source_type TEXT NOT NULL DEFAULT 'curated',\n upstream_version TEXT,\n crawled_at TEXT\n );\n\n CREATE VIRTUAL TABLE IF NOT EXISTS docs_fts USING fts5(\n provider,\n category,\n title,\n content,\n content='docs',\n content_rowid='id',\n tokenize='porter unicode61'\n );\n\n CREATE TRIGGER IF NOT EXISTS docs_ai AFTER INSERT ON docs BEGIN\n INSERT INTO docs_fts(rowid, provider, category, title, content)\n VALUES (new.id, new.provider, new.category, new.title, new.content);\n END;\n\n CREATE TABLE IF NOT EXISTS meta (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n );\n";
|
|
20
|
+
declare const providerEntrySchema: z.ZodObject<{
|
|
21
|
+
description: z.ZodString;
|
|
22
|
+
display_name: z.ZodString;
|
|
23
|
+
aliases: z.ZodArray<z.ZodString>;
|
|
24
|
+
access_level: z.ZodString;
|
|
25
|
+
licence_status: z.ZodString;
|
|
26
|
+
public_safety_notes: z.ZodString;
|
|
27
|
+
version: z.ZodNullable<z.ZodString>;
|
|
28
|
+
sources: z.ZodArray<z.ZodObject<{
|
|
29
|
+
url: z.ZodOptional<z.ZodString>;
|
|
30
|
+
type: z.ZodString;
|
|
31
|
+
note: z.ZodOptional<z.ZodString>;
|
|
32
|
+
}, z.core.$loose>>;
|
|
33
|
+
last_crawled: z.ZodNullable<z.ZodString>;
|
|
34
|
+
}, z.core.$loose>;
|
|
35
|
+
export declare const providersFileSchema: z.ZodObject<{
|
|
36
|
+
providers: z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
37
|
+
description: z.ZodString;
|
|
38
|
+
display_name: z.ZodString;
|
|
39
|
+
aliases: z.ZodArray<z.ZodString>;
|
|
40
|
+
access_level: z.ZodString;
|
|
41
|
+
licence_status: z.ZodString;
|
|
42
|
+
public_safety_notes: z.ZodString;
|
|
43
|
+
version: z.ZodNullable<z.ZodString>;
|
|
44
|
+
sources: z.ZodArray<z.ZodObject<{
|
|
45
|
+
url: z.ZodOptional<z.ZodString>;
|
|
46
|
+
type: z.ZodString;
|
|
47
|
+
note: z.ZodOptional<z.ZodString>;
|
|
48
|
+
}, z.core.$loose>>;
|
|
49
|
+
last_crawled: z.ZodNullable<z.ZodString>;
|
|
50
|
+
}, z.core.$loose>>;
|
|
51
|
+
}, z.core.$loose>;
|
|
52
|
+
export type ProvidersFile = z.infer<typeof providersFileSchema>;
|
|
53
|
+
export type ProviderRegistryEntry = z.infer<typeof providerEntrySchema>;
|
|
54
|
+
export interface DataMeta {
|
|
55
|
+
schemaVersion: number;
|
|
56
|
+
minServerVersion: string;
|
|
57
|
+
/** ISO-8601 time of the source commit. */
|
|
58
|
+
dataStamp: string;
|
|
59
|
+
/** dataStamp as epoch milliseconds; compare this, never the string. */
|
|
60
|
+
stampMs: number;
|
|
61
|
+
commit: string | null;
|
|
62
|
+
providers: ProvidersFile;
|
|
63
|
+
}
|
|
64
|
+
/** Compare two x.y.z versions; a pre-release suffix is ignored. */
|
|
65
|
+
export declare function compareVersions(a: string, b: string): number;
|
|
66
|
+
/**
|
|
67
|
+
* Read and check the meta table. Returns null when the file predates the table
|
|
68
|
+
* (older releases, and the in-memory databases some tests build).
|
|
69
|
+
*/
|
|
70
|
+
export declare function readMeta(db: Database.Database): DataMeta | null;
|
|
71
|
+
export interface MetaInput {
|
|
72
|
+
dataStamp: string;
|
|
73
|
+
commit: string | null;
|
|
74
|
+
providersJson: string;
|
|
75
|
+
}
|
|
76
|
+
/** Replace the meta table's contents. Used by ingest. */
|
|
77
|
+
export declare function writeMeta(db: Database.Database, input: MetaInput): void;
|
|
78
|
+
/** Settings for any docs database this process opens, bundled or downloaded. */
|
|
79
|
+
export declare function hardenConnection(db: Database.Database): void;
|
|
80
|
+
export type ValidationResult = {
|
|
81
|
+
ok: true;
|
|
82
|
+
meta: DataMeta;
|
|
83
|
+
} | {
|
|
84
|
+
ok: false;
|
|
85
|
+
reason: string;
|
|
86
|
+
};
|
|
87
|
+
/**
|
|
88
|
+
* Decide whether a file is a docs index this server can use: the exact schema,
|
|
89
|
+
* a supported schema version, a minimum server version it meets, a valid provider
|
|
90
|
+
* registry and at least one chunk. `integrity` adds a full quick_check, used for
|
|
91
|
+
* freshly downloaded files.
|
|
92
|
+
*/
|
|
93
|
+
export declare function validateDatabase(path: string, serverVersion: string, options?: {
|
|
94
|
+
integrity?: boolean;
|
|
95
|
+
}): ValidationResult;
|
|
96
|
+
export {};
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The on-disk format of the docs index, shared by ingest and the server.
|
|
3
|
+
*
|
|
4
|
+
* The index can reach a server two ways: inside the npm package, or downloaded
|
|
5
|
+
* later from the data-latest release (see data-update.ts). Both paths must agree
|
|
6
|
+
* on what a usable file looks like, so the schema, the metadata keys and the
|
|
7
|
+
* validation all live here.
|
|
8
|
+
*/
|
|
9
|
+
import Database from "better-sqlite3";
|
|
10
|
+
import { z } from "zod";
|
|
11
|
+
/** Bump when the table layout changes. Servers only use data with their own version. */
|
|
12
|
+
export const DATA_SCHEMA_VERSION = 1;
|
|
13
|
+
/**
|
|
14
|
+
* The oldest server release that can read data built by this code. Raise it when
|
|
15
|
+
* the data starts to rely on server code that older releases lack (a new field in
|
|
16
|
+
* providers.json the tools must read, for example), and release that server first.
|
|
17
|
+
*/
|
|
18
|
+
export const MIN_SERVER_VERSION = "0.13.0";
|
|
19
|
+
export const SCHEMA_SQL = `
|
|
20
|
+
CREATE TABLE IF NOT EXISTS docs (
|
|
21
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
22
|
+
provider TEXT NOT NULL,
|
|
23
|
+
category TEXT NOT NULL,
|
|
24
|
+
title TEXT NOT NULL,
|
|
25
|
+
content TEXT NOT NULL,
|
|
26
|
+
source_url TEXT,
|
|
27
|
+
source_type TEXT NOT NULL DEFAULT 'curated',
|
|
28
|
+
upstream_version TEXT,
|
|
29
|
+
crawled_at TEXT
|
|
30
|
+
);
|
|
31
|
+
|
|
32
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS docs_fts USING fts5(
|
|
33
|
+
provider,
|
|
34
|
+
category,
|
|
35
|
+
title,
|
|
36
|
+
content,
|
|
37
|
+
content='docs',
|
|
38
|
+
content_rowid='id',
|
|
39
|
+
tokenize='porter unicode61'
|
|
40
|
+
);
|
|
41
|
+
|
|
42
|
+
CREATE TRIGGER IF NOT EXISTS docs_ai AFTER INSERT ON docs BEGIN
|
|
43
|
+
INSERT INTO docs_fts(rowid, provider, category, title, content)
|
|
44
|
+
VALUES (new.id, new.provider, new.category, new.title, new.content);
|
|
45
|
+
END;
|
|
46
|
+
|
|
47
|
+
CREATE TABLE IF NOT EXISTS meta (
|
|
48
|
+
key TEXT PRIMARY KEY,
|
|
49
|
+
value TEXT NOT NULL
|
|
50
|
+
);
|
|
51
|
+
`;
|
|
52
|
+
const providerSourceSchema = z.looseObject({
|
|
53
|
+
url: z.string().optional(),
|
|
54
|
+
type: z.string(),
|
|
55
|
+
note: z.string().optional(),
|
|
56
|
+
});
|
|
57
|
+
const providerEntrySchema = z.looseObject({
|
|
58
|
+
description: z.string(),
|
|
59
|
+
display_name: z.string(),
|
|
60
|
+
aliases: z.array(z.string()),
|
|
61
|
+
access_level: z.string(),
|
|
62
|
+
licence_status: z.string(),
|
|
63
|
+
public_safety_notes: z.string(),
|
|
64
|
+
version: z.string().nullable(),
|
|
65
|
+
sources: z.array(providerSourceSchema),
|
|
66
|
+
last_crawled: z.string().nullable(),
|
|
67
|
+
});
|
|
68
|
+
export const providersFileSchema = z.looseObject({
|
|
69
|
+
providers: z.record(z.string(), providerEntrySchema),
|
|
70
|
+
});
|
|
71
|
+
/** Compare two x.y.z versions; a pre-release suffix is ignored. */
|
|
72
|
+
export function compareVersions(a, b) {
|
|
73
|
+
const parts = (version) => version
|
|
74
|
+
.split("-")[0]
|
|
75
|
+
.split(".")
|
|
76
|
+
.map((part) => Number.parseInt(part, 10) || 0);
|
|
77
|
+
const [left, right] = [parts(a), parts(b)];
|
|
78
|
+
for (let i = 0; i < 3; i += 1) {
|
|
79
|
+
const diff = (left[i] ?? 0) - (right[i] ?? 0);
|
|
80
|
+
if (diff !== 0)
|
|
81
|
+
return Math.sign(diff);
|
|
82
|
+
}
|
|
83
|
+
return 0;
|
|
84
|
+
}
|
|
85
|
+
function hasMetaTable(db) {
|
|
86
|
+
return Boolean(db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'meta'").get());
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Read and check the meta table. Returns null when the file predates the table
|
|
90
|
+
* (older releases, and the in-memory databases some tests build).
|
|
91
|
+
*/
|
|
92
|
+
export function readMeta(db) {
|
|
93
|
+
if (!hasMetaTable(db))
|
|
94
|
+
return null;
|
|
95
|
+
const rows = db.prepare("SELECT key, value FROM meta").all();
|
|
96
|
+
const values = new Map(rows.map((row) => [row.key, row.value]));
|
|
97
|
+
const schemaVersion = Number.parseInt(values.get("schema_version") ?? "", 10);
|
|
98
|
+
const minServerVersion = values.get("min_server_version") ?? "";
|
|
99
|
+
const dataStamp = values.get("data_stamp") ?? "";
|
|
100
|
+
const stampMs = Date.parse(dataStamp);
|
|
101
|
+
if (!Number.isInteger(schemaVersion))
|
|
102
|
+
throw new Error("meta.schema_version is missing or not an integer");
|
|
103
|
+
if (!/^\d+\.\d+\.\d+/.test(minServerVersion))
|
|
104
|
+
throw new Error("meta.min_server_version is missing");
|
|
105
|
+
if (!Number.isFinite(stampMs))
|
|
106
|
+
throw new Error("meta.data_stamp is missing or not a date");
|
|
107
|
+
let providersJson;
|
|
108
|
+
try {
|
|
109
|
+
providersJson = JSON.parse(values.get("providers_json") ?? "");
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
throw new Error("meta.providers_json is not JSON");
|
|
113
|
+
}
|
|
114
|
+
const providers = providersFileSchema.safeParse(providersJson);
|
|
115
|
+
if (!providers.success)
|
|
116
|
+
throw new Error("meta.providers_json does not match the provider registry format");
|
|
117
|
+
return {
|
|
118
|
+
schemaVersion,
|
|
119
|
+
minServerVersion,
|
|
120
|
+
dataStamp,
|
|
121
|
+
stampMs,
|
|
122
|
+
commit: values.get("commit") || null,
|
|
123
|
+
providers: providers.data,
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
/** Replace the meta table's contents. Used by ingest. */
|
|
127
|
+
export function writeMeta(db, input) {
|
|
128
|
+
const insert = db.prepare("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)");
|
|
129
|
+
db.transaction(() => {
|
|
130
|
+
db.prepare("DELETE FROM meta").run();
|
|
131
|
+
insert.run("schema_version", String(DATA_SCHEMA_VERSION));
|
|
132
|
+
insert.run("min_server_version", MIN_SERVER_VERSION);
|
|
133
|
+
insert.run("data_stamp", new Date(input.dataStamp).toISOString());
|
|
134
|
+
if (input.commit)
|
|
135
|
+
insert.run("commit", input.commit);
|
|
136
|
+
insert.run("providers_json", input.providersJson);
|
|
137
|
+
})();
|
|
138
|
+
}
|
|
139
|
+
/** FTS5's internal tables. Their SQL is written by SQLite, not by us. */
|
|
140
|
+
const FTS_SHADOW_TABLE = /^docs_fts_(data|idx|content|docsize|config)$/;
|
|
141
|
+
/**
|
|
142
|
+
* The schema as comparable rows. The objects SCHEMA_SQL defines are compared
|
|
143
|
+
* exactly; the FTS5 shadow tables by name and type only, because users' installs
|
|
144
|
+
* may build a different SQLite whose FTS5 writes their SQL differently.
|
|
145
|
+
*/
|
|
146
|
+
function schemaRows(db) {
|
|
147
|
+
return db
|
|
148
|
+
.prepare("SELECT type, name, tbl_name, sql FROM sqlite_master ORDER BY type, name")
|
|
149
|
+
.all()
|
|
150
|
+
.filter((row) => row.name !== "sqlite_sequence")
|
|
151
|
+
.map((row) => (FTS_SHADOW_TABLE.test(row.name) ? { ...row, sql: null } : row));
|
|
152
|
+
}
|
|
153
|
+
let referenceSchema;
|
|
154
|
+
/** The exact sqlite_master rows a database built from SCHEMA_SQL has. */
|
|
155
|
+
function expectedSchema() {
|
|
156
|
+
if (!referenceSchema) {
|
|
157
|
+
const reference = new Database(":memory:");
|
|
158
|
+
reference.exec(SCHEMA_SQL);
|
|
159
|
+
referenceSchema = JSON.stringify(schemaRows(reference));
|
|
160
|
+
reference.close();
|
|
161
|
+
}
|
|
162
|
+
return referenceSchema;
|
|
163
|
+
}
|
|
164
|
+
/** Settings for any docs database this process opens, bundled or downloaded. */
|
|
165
|
+
export function hardenConnection(db) {
|
|
166
|
+
db.pragma("trusted_schema = OFF");
|
|
167
|
+
db.pragma("cell_size_check = ON");
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Decide whether a file is a docs index this server can use: the exact schema,
|
|
171
|
+
* a supported schema version, a minimum server version it meets, a valid provider
|
|
172
|
+
* registry and at least one chunk. `integrity` adds a full quick_check, used for
|
|
173
|
+
* freshly downloaded files.
|
|
174
|
+
*/
|
|
175
|
+
export function validateDatabase(path, serverVersion, options = {}) {
|
|
176
|
+
let db;
|
|
177
|
+
try {
|
|
178
|
+
db = new Database(path, { readonly: true, fileMustExist: true });
|
|
179
|
+
hardenConnection(db);
|
|
180
|
+
if (options.integrity) {
|
|
181
|
+
const check = db.pragma("quick_check", { simple: true });
|
|
182
|
+
if (check !== "ok")
|
|
183
|
+
return { ok: false, reason: `integrity check failed (${String(check)})` };
|
|
184
|
+
}
|
|
185
|
+
if (JSON.stringify(schemaRows(db)) !== expectedSchema()) {
|
|
186
|
+
return { ok: false, reason: "schema does not match this server's schema" };
|
|
187
|
+
}
|
|
188
|
+
const meta = readMeta(db);
|
|
189
|
+
if (!meta)
|
|
190
|
+
return { ok: false, reason: "no meta table" };
|
|
191
|
+
if (meta.schemaVersion !== DATA_SCHEMA_VERSION) {
|
|
192
|
+
return { ok: false, reason: `schema version ${meta.schemaVersion}, server reads ${DATA_SCHEMA_VERSION}` };
|
|
193
|
+
}
|
|
194
|
+
if (compareVersions(serverVersion, meta.minServerVersion) < 0) {
|
|
195
|
+
return { ok: false, reason: `needs server ${meta.minServerVersion} or newer (this is ${serverVersion})` };
|
|
196
|
+
}
|
|
197
|
+
if (!db.prepare("SELECT 1 FROM docs LIMIT 1").get())
|
|
198
|
+
return { ok: false, reason: "no chunks" };
|
|
199
|
+
return { ok: true, meta };
|
|
200
|
+
}
|
|
201
|
+
catch (error) {
|
|
202
|
+
return { ok: false, reason: error instanceof Error ? error.message : String(error) };
|
|
203
|
+
}
|
|
204
|
+
finally {
|
|
205
|
+
db?.close();
|
|
206
|
+
}
|
|
207
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which docs index the server opens.
|
|
3
|
+
*
|
|
4
|
+
* The npm package ships an index, and data-update.ts can download newer ones
|
|
5
|
+
* into the data directory. The server uses the newest file it can validate.
|
|
6
|
+
* Downloaded files are named by stamp and never overwritten, so several server
|
|
7
|
+
* processes can share the directory without replacing a file another one reads.
|
|
8
|
+
*/
|
|
9
|
+
import { type DataMeta } from "./data-format.js";
|
|
10
|
+
export type DataMode = "auto" | "bundled";
|
|
11
|
+
export interface DataSourceOptions {
|
|
12
|
+
/** The index inside the npm package. */
|
|
13
|
+
bundledPath: string;
|
|
14
|
+
/** Where downloaded indexes live. */
|
|
15
|
+
dataDir: string;
|
|
16
|
+
/** This server's package version, checked against each file's min_server_version. */
|
|
17
|
+
serverVersion: string;
|
|
18
|
+
mode: DataMode;
|
|
19
|
+
/** FOOTBALL_DOCS_DB_PATH: use exactly this file. */
|
|
20
|
+
pinnedPath?: string;
|
|
21
|
+
log?: (message: string) => void;
|
|
22
|
+
}
|
|
23
|
+
export interface DataSelection {
|
|
24
|
+
path: string;
|
|
25
|
+
source: "bundled" | "downloaded" | "pinned";
|
|
26
|
+
meta: DataMeta | null;
|
|
27
|
+
}
|
|
28
|
+
export declare function defaultDataDir(env?: NodeJS.ProcessEnv): string;
|
|
29
|
+
/**
|
|
30
|
+
* FOOTBALL_DOCS_DATA picks the mode. Without it, a server running from a git
|
|
31
|
+
* checkout uses its own bundled file, so development and tests always see the
|
|
32
|
+
* working tree's docs and never touch the network or the user's cache.
|
|
33
|
+
*/
|
|
34
|
+
export declare function dataModeFor(env: NodeJS.ProcessEnv, packageRoot: string): DataMode;
|
|
35
|
+
export declare function cachedFileName(stampMs: number): string;
|
|
36
|
+
/**
|
|
37
|
+
* Choose the index to open. The newest valid file wins; on a tie the bundled
|
|
38
|
+
* file wins. If the bundled file fails validation (an index built before the
|
|
39
|
+
* meta table existed, in a development checkout) it is still the fallback, so
|
|
40
|
+
* the server behaves as it did before downloads existed.
|
|
41
|
+
*/
|
|
42
|
+
export declare function selectDatabase(options: DataSourceOptions): DataSelection;
|
|
43
|
+
/** The newest stamp among downloaded files, or null. Cheap: one directory listing. */
|
|
44
|
+
export declare function newestCachedStamp(dataDir: string): number | null;
|
|
45
|
+
/**
|
|
46
|
+
* Holds the chosen index for a long-running server and chooses again when
|
|
47
|
+
* needed: when the chosen file has gone (another process cleaned it up), or when
|
|
48
|
+
* a newer downloaded file appears. The server may run for days, and another
|
|
49
|
+
* server process sharing the data directory may be the one that downloads the
|
|
50
|
+
* newer file, so this checks the directory on each call rather than waiting for
|
|
51
|
+
* its own update check.
|
|
52
|
+
*/
|
|
53
|
+
export declare class IndexChooser {
|
|
54
|
+
private readonly options;
|
|
55
|
+
private selection;
|
|
56
|
+
private newestSeen;
|
|
57
|
+
constructor(options: DataSourceOptions);
|
|
58
|
+
current(): DataSelection;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Remove leftovers from the data directory: temporary downloads older than an
|
|
62
|
+
* hour, and downloaded indexes older than the active one that have not changed
|
|
63
|
+
* for a week. Errors are ignored; a file that cannot be removed now is tried again
|
|
64
|
+
* at the next start.
|
|
65
|
+
*/
|
|
66
|
+
export declare function cleanDataDir(dataDir: string, activeStampMs: number | null, now?: number): void;
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which docs index the server opens.
|
|
3
|
+
*
|
|
4
|
+
* The npm package ships an index, and data-update.ts can download newer ones
|
|
5
|
+
* into the data directory. The server uses the newest file it can validate.
|
|
6
|
+
* Downloaded files are named by stamp and never overwritten, so several server
|
|
7
|
+
* processes can share the directory without replacing a file another one reads.
|
|
8
|
+
*/
|
|
9
|
+
import { existsSync, readdirSync, rmSync, statSync } from "node:fs";
|
|
10
|
+
import { homedir } from "node:os";
|
|
11
|
+
import { join, resolve } from "node:path";
|
|
12
|
+
import { validateDatabase } from "./data-format.js";
|
|
13
|
+
const CACHED_FILE = /^docs-(\d+)\.db$/;
|
|
14
|
+
const TEMP_FILE = /^tmp-.*\.db$/;
|
|
15
|
+
const SIDE_FILES = ["", "-journal", "-wal", "-shm"];
|
|
16
|
+
/** Another running server may still use a recent older file, so keep it this long. */
|
|
17
|
+
const OLD_FILE_GRACE_MS = 7 * 24 * 60 * 60 * 1000;
|
|
18
|
+
const TEMP_FILE_GRACE_MS = 60 * 60 * 1000;
|
|
19
|
+
export function defaultDataDir(env = process.env) {
|
|
20
|
+
return resolve(env.XDG_DATA_HOME ?? resolve(homedir(), ".local", "share"), "football-docs", "data");
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* FOOTBALL_DOCS_DATA picks the mode. Without it, a server running from a git
|
|
24
|
+
* checkout uses its own bundled file, so development and tests always see the
|
|
25
|
+
* working tree's docs and never touch the network or the user's cache.
|
|
26
|
+
*/
|
|
27
|
+
export function dataModeFor(env, packageRoot) {
|
|
28
|
+
const setting = env.FOOTBALL_DOCS_DATA?.trim().toLowerCase();
|
|
29
|
+
if (setting === "auto" || setting === "bundled")
|
|
30
|
+
return setting;
|
|
31
|
+
return existsSync(join(packageRoot, ".git")) ? "bundled" : "auto";
|
|
32
|
+
}
|
|
33
|
+
export function cachedFileName(stampMs) {
|
|
34
|
+
return `docs-${stampMs}.db`;
|
|
35
|
+
}
|
|
36
|
+
/** Downloaded files, newest first. */
|
|
37
|
+
function cachedFiles(dataDir) {
|
|
38
|
+
if (!existsSync(dataDir))
|
|
39
|
+
return [];
|
|
40
|
+
return readdirSync(dataDir)
|
|
41
|
+
.map((name) => ({ name, match: CACHED_FILE.exec(name) }))
|
|
42
|
+
.filter((entry) => entry.match !== null)
|
|
43
|
+
.map((entry) => ({ path: join(dataDir, entry.name), stampMs: Number(entry.match[1]) }))
|
|
44
|
+
.sort((a, b) => b.stampMs - a.stampMs);
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Choose the index to open. The newest valid file wins; on a tie the bundled
|
|
48
|
+
* file wins. If the bundled file fails validation (an index built before the
|
|
49
|
+
* meta table existed, in a development checkout) it is still the fallback, so
|
|
50
|
+
* the server behaves as it did before downloads existed.
|
|
51
|
+
*/
|
|
52
|
+
export function selectDatabase(options) {
|
|
53
|
+
const log = options.log ?? (() => { });
|
|
54
|
+
if (options.pinnedPath) {
|
|
55
|
+
const result = validateDatabase(options.pinnedPath, options.serverVersion);
|
|
56
|
+
if (!result.ok) {
|
|
57
|
+
throw new Error(`FOOTBALL_DOCS_DB_PATH ${options.pinnedPath} cannot be used: ${result.reason}`);
|
|
58
|
+
}
|
|
59
|
+
return { path: options.pinnedPath, source: "pinned", meta: result.meta };
|
|
60
|
+
}
|
|
61
|
+
const bundled = validateDatabase(options.bundledPath, options.serverVersion);
|
|
62
|
+
const bundledSelection = {
|
|
63
|
+
path: options.bundledPath,
|
|
64
|
+
source: "bundled",
|
|
65
|
+
meta: bundled.ok ? bundled.meta : null,
|
|
66
|
+
};
|
|
67
|
+
if (options.mode === "bundled")
|
|
68
|
+
return bundledSelection;
|
|
69
|
+
const bundledStamp = bundled.ok ? bundled.meta.stampMs : Number.NEGATIVE_INFINITY;
|
|
70
|
+
for (const file of cachedFiles(options.dataDir)) {
|
|
71
|
+
if (file.stampMs <= bundledStamp)
|
|
72
|
+
break;
|
|
73
|
+
const result = validateDatabase(file.path, options.serverVersion);
|
|
74
|
+
if (result.ok && result.meta.stampMs === file.stampMs) {
|
|
75
|
+
return { path: file.path, source: "downloaded", meta: result.meta };
|
|
76
|
+
}
|
|
77
|
+
log(`football-docs: skipping cached index ${file.path}: ${result.ok ? "stamp does not match its name" : result.reason}`);
|
|
78
|
+
}
|
|
79
|
+
return bundledSelection;
|
|
80
|
+
}
|
|
81
|
+
/** The newest stamp among downloaded files, or null. Cheap: one directory listing. */
|
|
82
|
+
export function newestCachedStamp(dataDir) {
|
|
83
|
+
const [newest] = cachedFiles(dataDir);
|
|
84
|
+
return newest ? newest.stampMs : null;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Holds the chosen index for a long-running server and chooses again when
|
|
88
|
+
* needed: when the chosen file has gone (another process cleaned it up), or when
|
|
89
|
+
* a newer downloaded file appears. The server may run for days, and another
|
|
90
|
+
* server process sharing the data directory may be the one that downloads the
|
|
91
|
+
* newer file, so this checks the directory on each call rather than waiting for
|
|
92
|
+
* its own update check.
|
|
93
|
+
*/
|
|
94
|
+
export class IndexChooser {
|
|
95
|
+
options;
|
|
96
|
+
selection;
|
|
97
|
+
newestSeen = Number.NEGATIVE_INFINITY;
|
|
98
|
+
constructor(options) {
|
|
99
|
+
this.options = options;
|
|
100
|
+
}
|
|
101
|
+
current() {
|
|
102
|
+
if (this.options.mode === "auto" && !this.options.pinnedPath) {
|
|
103
|
+
const newest = newestCachedStamp(this.options.dataDir);
|
|
104
|
+
if (newest !== null && newest > this.newestSeen) {
|
|
105
|
+
this.newestSeen = newest;
|
|
106
|
+
this.selection = undefined;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
if (this.selection && !existsSync(this.selection.path))
|
|
110
|
+
this.selection = undefined;
|
|
111
|
+
this.selection ??= selectDatabase(this.options);
|
|
112
|
+
return this.selection;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
function removeWithSideFiles(path) {
|
|
116
|
+
for (const suffix of SIDE_FILES) {
|
|
117
|
+
rmSync(`${path}${suffix}`, { force: true });
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Remove leftovers from the data directory: temporary downloads older than an
|
|
122
|
+
* hour, and downloaded indexes older than the active one that have not changed
|
|
123
|
+
* for a week. Errors are ignored; a file that cannot be removed now is tried again
|
|
124
|
+
* at the next start.
|
|
125
|
+
*/
|
|
126
|
+
export function cleanDataDir(dataDir, activeStampMs, now = Date.now()) {
|
|
127
|
+
if (!existsSync(dataDir))
|
|
128
|
+
return;
|
|
129
|
+
for (const name of readdirSync(dataDir)) {
|
|
130
|
+
const path = join(dataDir, name);
|
|
131
|
+
try {
|
|
132
|
+
const age = now - statSync(path).mtimeMs;
|
|
133
|
+
if (TEMP_FILE.test(name)) {
|
|
134
|
+
if (age > TEMP_FILE_GRACE_MS)
|
|
135
|
+
removeWithSideFiles(path);
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
const match = CACHED_FILE.exec(name);
|
|
139
|
+
if (match && activeStampMs !== null && Number(match[1]) < activeStampMs && age > OLD_FILE_GRACE_MS) {
|
|
140
|
+
removeWithSideFiles(path);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
// Best effort only.
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Background check for a newer docs index.
|
|
3
|
+
*
|
|
4
|
+
* CI publishes each data build to the data-latest release of this repository
|
|
5
|
+
* with a manifest (see .github/workflows/data.yml). At most once a day the
|
|
6
|
+
* server reads the manifest for its schema version, and when it names a newer
|
|
7
|
+
* build it downloads the file, checks its size, hash, schema and metadata, and
|
|
8
|
+
* adds it to the data directory under its stamp. The next tool call uses it.
|
|
9
|
+
*
|
|
10
|
+
* Every failure leaves the current index in use. Nothing is written to stdout,
|
|
11
|
+
* which is the MCP channel.
|
|
12
|
+
*/
|
|
13
|
+
import { z } from "zod";
|
|
14
|
+
export declare const DEFAULT_DATA_BASE_URL = "https://github.com/withqwerty/football-docs/releases/download/data-latest/";
|
|
15
|
+
export declare const MANIFEST_NAME = "manifest-v1.json";
|
|
16
|
+
export declare const MAX_DOWNLOAD_BYTES: number;
|
|
17
|
+
declare const manifestSchema: z.ZodObject<{
|
|
18
|
+
schema_version: z.ZodNumber;
|
|
19
|
+
min_server_version: z.ZodString;
|
|
20
|
+
data_stamp: z.ZodString;
|
|
21
|
+
commit: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
22
|
+
file: z.ZodString;
|
|
23
|
+
sha256: z.ZodString;
|
|
24
|
+
size: z.ZodNumber;
|
|
25
|
+
}, z.core.$strip>;
|
|
26
|
+
export type Manifest = z.infer<typeof manifestSchema>;
|
|
27
|
+
export type UpdateOutcome = "skipped-ci" | "skipped-recent" | "not-published" | "up-to-date" | "installed" | "rejected" | "failed";
|
|
28
|
+
export interface UpdateOptions {
|
|
29
|
+
dataDir: string;
|
|
30
|
+
serverVersion: string;
|
|
31
|
+
/** Stamp of the index in use, in epoch milliseconds, or null if unknown. */
|
|
32
|
+
currentStampMs: number | null;
|
|
33
|
+
baseUrl?: string;
|
|
34
|
+
env?: NodeJS.ProcessEnv;
|
|
35
|
+
fetch?: typeof fetch;
|
|
36
|
+
now?: () => number;
|
|
37
|
+
signal?: AbortSignal;
|
|
38
|
+
maxBytes?: number;
|
|
39
|
+
log?: (message: string) => void;
|
|
40
|
+
}
|
|
41
|
+
export interface UpdateResult {
|
|
42
|
+
outcome: UpdateOutcome;
|
|
43
|
+
detail?: string;
|
|
44
|
+
/** Path of the newly added index, for outcome "installed". */
|
|
45
|
+
path?: string;
|
|
46
|
+
}
|
|
47
|
+
export declare function checkForUpdate(options: UpdateOptions): Promise<UpdateResult>;
|
|
48
|
+
export {};
|