fnloom 0.1.0 → 0.2.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.
Files changed (113) hide show
  1. package/README.md +31 -18
  2. package/package.json +2 -7
  3. package/packages/build/package.json +1 -1
  4. package/packages/cli/package.json +1 -1
  5. package/packages/cli/src/commands/available.ts +63 -22
  6. package/packages/cli/src/commands/install.ts +86 -28
  7. package/packages/cli/src/index.ts +3 -2
  8. package/packages/cli/src/local.ts +6 -0
  9. package/packages/cli/src/premade.ts +80 -0
  10. package/packages/core/package.json +1 -1
  11. package/packages/hub/package.json +1 -1
  12. package/packages/hub/src/link/process.ts +6 -1
  13. package/packages/sdk/package.json +1 -1
  14. package/packages/web/package.json +1 -1
  15. package/premade/claude.zip +0 -0
  16. package/premade/database.zip +0 -0
  17. package/premade/web.zip +0 -0
  18. package/scripts/dev-env.ts +4 -4
  19. package/scripts/stack.ts +42 -27
  20. package/scripts/start.ts +26 -16
  21. package/systems/api/package.json +1 -1
  22. package/systems/code/package.json +1 -1
  23. package/systems/embedder/package.json +1 -1
  24. package/systems/fs/package.json +1 -1
  25. package/systems/google-calendar/package.json +1 -1
  26. package/systems/input/package.json +1 -1
  27. package/systems/mcp/package.json +1 -1
  28. package/systems/ollama/package.json +1 -1
  29. package/systems/schedule/package.json +1 -1
  30. package/systems/template/package.json +1 -1
  31. package/systems/widgets/package.json +1 -1
  32. package/systems/claude/client/FleetPage.vue +0 -132
  33. package/systems/claude/client/NewSessionForm.vue +0 -62
  34. package/systems/claude/client/SessionList.vue +0 -64
  35. package/systems/claude/client/SessionPage.vue +0 -199
  36. package/systems/claude/client/TaskList.vue +0 -61
  37. package/systems/claude/client/fakes.ts +0 -186
  38. package/systems/claude/client/host.ts +0 -23
  39. package/systems/claude/client/index.ts +0 -15
  40. package/systems/claude/client/logic.ts +0 -270
  41. package/systems/claude/client/state.ts +0 -344
  42. package/systems/claude/package.json +0 -23
  43. package/systems/claude/server/agent-sdk.ts +0 -379
  44. package/systems/claude/server/driver.ts +0 -153
  45. package/systems/claude/server/env.ts +0 -64
  46. package/systems/claude/server/fake-driver.ts +0 -112
  47. package/systems/claude/server/fleet.ts +0 -376
  48. package/systems/claude/server/impl.ts +0 -568
  49. package/systems/claude/server/index.ts +0 -8
  50. package/systems/claude/server/main.ts +0 -38
  51. package/systems/claude/server/preview.ts +0 -76
  52. package/systems/claude/server/questions.ts +0 -117
  53. package/systems/claude/server/transcript.ts +0 -83
  54. package/systems/claude/shared/index.ts +0 -262
  55. package/systems/claude/shared/session.ts +0 -284
  56. package/systems/claude/shared/shapes.ts +0 -106
  57. package/systems/claude/system.json +0 -18
  58. package/systems/claude/tsconfig.json +0 -6
  59. package/systems/database/package.json +0 -25
  60. package/systems/database/server/author.ts +0 -41
  61. package/systems/database/server/authoring.ts +0 -322
  62. package/systems/database/server/catalog.ts +0 -117
  63. package/systems/database/server/compile.ts +0 -332
  64. package/systems/database/server/dialects.ts +0 -17
  65. package/systems/database/server/drivers/database.ts +0 -71
  66. package/systems/database/server/drivers/index.ts +0 -23
  67. package/systems/database/server/drivers/postgres.ts +0 -157
  68. package/systems/database/server/drivers/sqlite.ts +0 -151
  69. package/systems/database/server/drivers/sqlserver.ts +0 -176
  70. package/systems/database/server/env.ts +0 -35
  71. package/systems/database/server/fixture.ts +0 -169
  72. package/systems/database/server/impl.ts +0 -793
  73. package/systems/database/server/index.ts +0 -7
  74. package/systems/database/server/instance.ts +0 -398
  75. package/systems/database/server/main.ts +0 -47
  76. package/systems/database/server/pick.ts +0 -97
  77. package/systems/database/server/queries.ts +0 -390
  78. package/systems/database/server/results.ts +0 -39
  79. package/systems/database/server/schema.ts +0 -59
  80. package/systems/database/server/table-fns.ts +0 -237
  81. package/systems/database/server/types.ts +0 -253
  82. package/systems/database/shared/index.ts +0 -544
  83. package/systems/database/shared/shapes.ts +0 -413
  84. package/systems/database/system.json +0 -14
  85. package/systems/database/tsconfig.json +0 -6
  86. package/systems/web/client/ReadView.vue +0 -110
  87. package/systems/web/client/SearchView.vue +0 -215
  88. package/systems/web/client/StatusChip.vue +0 -38
  89. package/systems/web/client/fakes.ts +0 -48
  90. package/systems/web/client/index.ts +0 -15
  91. package/systems/web/client/view.ts +0 -131
  92. package/systems/web/package.json +0 -22
  93. package/systems/web/server/chrome.ts +0 -121
  94. package/systems/web/server/crawl.ts +0 -333
  95. package/systems/web/server/env.ts +0 -63
  96. package/systems/web/server/guard.ts +0 -60
  97. package/systems/web/server/http.ts +0 -89
  98. package/systems/web/server/impl.ts +0 -203
  99. package/systems/web/server/index.ts +0 -71
  100. package/systems/web/server/loader.ts +0 -104
  101. package/systems/web/server/main.ts +0 -70
  102. package/systems/web/server/mentions.ts +0 -111
  103. package/systems/web/server/problem.ts +0 -72
  104. package/systems/web/server/renderer.ts +0 -243
  105. package/systems/web/server/robots.ts +0 -75
  106. package/systems/web/server/searches.ts +0 -29
  107. package/systems/web/server/tavily.ts +0 -144
  108. package/systems/web/server/testing.ts +0 -165
  109. package/systems/web/server/uploads.ts +0 -33
  110. package/systems/web/shared/index.ts +0 -343
  111. package/systems/web/shared/urls.ts +0 -60
  112. package/systems/web/system.json +0 -15
  113. package/systems/web/tsconfig.json +0 -6
@@ -1,151 +0,0 @@
1
- /**
2
- * SQLite through better-sqlite3: a new file in the instance's data folder or an existing one. The schema comes from
3
- * `sqlite_master` and the table pragmas, read into `TableSpec`s by the SQLite DDL writer; a column's closed set of
4
- * values from a `CHECK (col IN (...))` in its table's SQL. Booleans bind as 0 and 1. A read runs only a statement
5
- * SQLite says changes nothing; a read-only database opens the file read-only.
6
- */
7
- import type { ColumnSpec, ForeignKeySpec, TableSpec, UniqueSpec } from '@aeye/query';
8
- import BetterSqlite3 from 'better-sqlite3';
9
- import { z } from 'zod';
10
- import { dialectFor } from '../dialects.ts';
11
- import { ScannedTable, checkValues } from '../schema.ts';
12
- import { READ_ONLY, bindValue, jsonValue, type Database, type Rows, type Statement, type Written } from './database.ts';
13
-
14
- const TableRow = z.object({ name: z.string(), sql: z.string().nullable() });
15
- const ColumnRow = z.object({ name: z.string(), type: z.string(), notnull: z.number(), dflt_value: z.string().nullable(), pk: z.number(), hidden: z.number().optional() });
16
- const ForeignRow = z.object({ id: z.number(), seq: z.number(), table: z.string(), from: z.string(), to: z.string().nullable() });
17
- const IndexRow = z.object({ name: z.string(), unique: z.number(), origin: z.string() });
18
- const IndexColumnRow = z.object({ seqno: z.number(), name: z.string().nullable() });
19
- const CountRow = z.object({ n: z.number() });
20
-
21
- /** A param as SQLite binds it. */
22
- function sqliteValue(value: Parameters<typeof bindValue>[0]): string | number | null {
23
- const bound = bindValue(value);
24
- return typeof bound === 'boolean' ? (bound ? 1 : 0) : bound;
25
- }
26
-
27
- /** A name as a SQLite identifier. */
28
- function quote(name: string): string {
29
- return `"${name.replace(/"/g, '""')}"`;
30
- }
31
-
32
- /** Thrown inside a dry run's transaction to roll it back. */
33
- class RolledBack extends Error {}
34
-
35
- /** A SQLite database file. */
36
- export class SqliteDatabase implements Database {
37
- readonly dialect = 'sqlite' as const;
38
- readonly #db: BetterSqlite3.Database;
39
- readonly #readonly: boolean;
40
-
41
- /** Open (or, with `create`, make) the file; a new file that is read-only is made first, then opened read-only. */
42
- constructor(file: string, options: { create: boolean; readonly: boolean }) {
43
- this.#readonly = options.readonly;
44
- if (options.create && options.readonly) { new BetterSqlite3(file).close(); }
45
- this.#db = new BetterSqlite3(file, { fileMustExist: !options.create || options.readonly, readonly: options.readonly });
46
- this.#db.pragma('foreign_keys = ON');
47
- }
48
-
49
- read(statement: Statement): Promise<Rows> {
50
- if (!this.#db.prepare(statement.sql).readonly) { return Promise.reject(new Error('A read may not change data.')); }
51
- return Promise.resolve(this.#run(statement));
52
- }
53
-
54
- write(statements: readonly Statement[]): Promise<Written> {
55
- if (this.#readonly) { return Promise.reject(new Error(READ_ONLY)); }
56
- return Promise.resolve(this.#db.transaction(() => this.#apply(statements))());
57
- }
58
-
59
- dryRun(statements: readonly Statement[]): Promise<Written> {
60
- let written: Written = { affected: 0, columns: [], rows: [] };
61
- try {
62
- this.#db.transaction(() => {
63
- written = this.#apply(statements);
64
- throw new RolledBack();
65
- })();
66
- } catch (error) {
67
- if (!(error instanceof RolledBack)) { throw error; }
68
- }
69
- return Promise.resolve(written);
70
- }
71
-
72
- schema(): Promise<ScannedTable[]> {
73
- const tables = z.array(TableRow).parse(this.#db.prepare('SELECT name, sql FROM sqlite_master WHERE type = \'table\' AND name NOT LIKE \'sqlite_%\' ORDER BY name').all());
74
- const read = tables.map((table) => this.#table(table.name, table.sql ?? ''));
75
- // a foreign key that names no columns refers to its table's primary key
76
- const keys = new Map(read.map((table) => [table.spec.name, table.spec.primaryKey]));
77
- return Promise.resolve(read.map((table) => ScannedTable.parse({
78
- ...table,
79
- spec: {
80
- ...table.spec,
81
- foreignKeys: table.spec.foreignKeys.map((key) => (key.references.every((name) => name === '?') ? { ...key, references: keys.get(key.table) ?? key.references } : key)),
82
- },
83
- })));
84
- }
85
-
86
- close(): Promise<void> {
87
- this.#db.close();
88
- return Promise.resolve();
89
- }
90
-
91
- #apply(statements: readonly Statement[]): Written {
92
- let affected = 0;
93
- let last: Rows = { columns: [], rows: [] };
94
- for (const statement of statements) {
95
- const prepared = this.#db.prepare(statement.sql);
96
- if (prepared.reader) {
97
- last = this.#run(statement);
98
- affected += last.rows.length;
99
- } else {
100
- affected += prepared.run(...statement.params.map(sqliteValue)).changes;
101
- last = { columns: [], rows: [] };
102
- }
103
- }
104
- return { affected, ...last };
105
- }
106
-
107
- #run(statement: Statement): Rows {
108
- const prepared = this.#db.prepare(statement.sql);
109
- const columns = prepared.columns().map((column) => column.name);
110
- const rows = prepared.raw(true).all(...statement.params.map(sqliteValue));
111
- return { columns, rows: rows.map((row) => (Array.isArray(row) ? row.map(jsonValue) : [])) };
112
- }
113
-
114
- #pragma<T>(schema: z.ZodType<T>, sql: string): T[] {
115
- return z.array(schema).parse(this.#db.prepare(sql).all());
116
- }
117
-
118
- #table(name: string, sql: string): ScannedTable {
119
- const ddl = dialectFor('sqlite').ddl;
120
- const columns = this.#pragma(ColumnRow, `PRAGMA table_xinfo(${quote(name)})`).filter((column) => (column.hidden ?? 0) === 0);
121
- const primaryKey = columns.filter((column) => column.pk > 0).sort((a, b) => a.pk - b.pk).map((column) => column.name);
122
- // a lone INTEGER PRIMARY KEY is the rowid: SQLite fills it in
123
- const rowid = primaryKey.length === 1 && columns.some((column) => column.name === primaryKey[0] && column.type.toUpperCase() === 'INTEGER');
124
- const foreign = new Map<number, z.infer<typeof ForeignRow>[]>();
125
- for (const row of this.#pragma(ForeignRow, `PRAGMA foreign_key_list(${quote(name)})`)) { foreign.set(row.id, [...(foreign.get(row.id) ?? []), row]); }
126
- const unique: UniqueSpec[] = this.#pragma(IndexRow, `PRAGMA index_list(${quote(name)})`)
127
- .filter((index) => index.unique === 1 && index.origin !== 'pk')
128
- .flatMap((index) => {
129
- const parts = this.#pragma(IndexColumnRow, `PRAGMA index_info(${quote(index.name)})`).sort((a, b) => a.seqno - b.seqno).flatMap((column) => (column.name === null ? [] : [column.name]));
130
- return parts.length > 0 ? [{ columns: parts }] : [];
131
- });
132
- const foreignKeys: ForeignKeySpec[] = [...foreign.values()].map((parts) => {
133
- const sorted = [...parts].sort((a, b) => a.seq - b.seq);
134
- return { columns: sorted.map((part) => part.from), table: sorted[0]?.table ?? '', references: sorted.map((part) => part.to ?? '?') };
135
- });
136
- const specColumns: ColumnSpec[] = columns.map((column) => {
137
- const values = checkValues(sql, column.name);
138
- const fallback = column.dflt_value === null ? undefined : ddl.readDefault(column.dflt_value);
139
- return {
140
- name: column.name,
141
- type: ddl.readColumnType(column.type),
142
- nullable: column.notnull === 0 && column.pk === 0,
143
- ...(fallback === undefined ? {} : { default: fallback }),
144
- ...(rowid && column.name === primaryKey[0] ? { generated: true } : {}),
145
- ...(values === undefined ? {} : { values }),
146
- };
147
- });
148
- const spec: TableSpec = { name, columns: specColumns, primaryKey, foreignKeys, unique };
149
- return { spec, rows: z.number().parse(CountRow.parse(this.#db.prepare(`SELECT count(*) AS n FROM ${quote(name)}`).get()).n) };
150
- }
151
- }
@@ -1,176 +0,0 @@
1
- /**
2
- * SQL Server through `mssql` (tedious), the `dbo` schema. Params bind by name as `@p1`, `@p2`, … in placeholder
3
- * order. Columns come from `INFORMATION_SCHEMA`, keys from its constraints, foreign keys and checks from `sys`, row
4
- * counts from `sys.partitions`. SQL Server keeps `col IN ('a', 'b')` checks as `[col]='a' OR [col]='b'`; both read.
5
- * SQL Server has no read-only transaction, so every read runs in a transaction that is always rolled back: whatever a
6
- * read did to data is undone. A read-only database also refuses writes outright.
7
- */
8
- import mssql from 'mssql';
9
- import { z } from 'zod';
10
- import type { Connection } from '../../shared/shapes.ts';
11
- import type { ColumnSpec, TableSpec } from '@aeye/query';
12
- import { dialectFor } from '../dialects.ts';
13
- import { ScannedTable, checkValues, orValues } from '../schema.ts';
14
- import { READ_ONLY, bindValue, jsonValue, type Database, type Rows, type Statement, type Written } from './database.ts';
15
-
16
- const ColumnRow = z.object({
17
- table_name: z.string(), column_name: z.string(), data_type: z.string(), is_nullable: z.string(),
18
- column_default: z.string().nullable(), default_name: z.string().nullable(), max_length: z.number().nullable(), is_identity: z.number().nullable(),
19
- });
20
- const KeyRow = z.object({ table_name: z.string(), name: z.string(), type: z.string(), column_name: z.string(), position: z.number() });
21
- const ForeignRow = z.object({ name: z.string(), table_name: z.string(), column_name: z.string(), ftable: z.string(), fcolumn: z.string(), position: z.number() });
22
- const CheckRow = z.object({ table_name: z.string(), column_name: z.string().nullable(), name: z.string(), definition: z.string() });
23
- const CountRow = z.object({ table_name: z.string(), rows: z.number() });
24
-
25
- const COLUMNS_SQL = `SELECT c.TABLE_NAME AS table_name, c.COLUMN_NAME AS column_name, c.DATA_TYPE AS data_type, c.IS_NULLABLE AS is_nullable,
26
- c.COLUMN_DEFAULT AS column_default, c.CHARACTER_MAXIMUM_LENGTH AS max_length,
27
- COLUMNPROPERTY(OBJECT_ID(c.TABLE_SCHEMA + '.' + c.TABLE_NAME), c.COLUMN_NAME, 'IsIdentity') AS is_identity, dc.name AS default_name
28
- FROM INFORMATION_SCHEMA.COLUMNS c JOIN INFORMATION_SCHEMA.TABLES t ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME
29
- LEFT JOIN sys.default_constraints dc ON dc.parent_object_id = OBJECT_ID(c.TABLE_SCHEMA + '.' + c.TABLE_NAME) AND dc.parent_column_id = COLUMNPROPERTY(OBJECT_ID(c.TABLE_SCHEMA + '.' + c.TABLE_NAME), c.COLUMN_NAME, 'ColumnId')
30
- WHERE c.TABLE_SCHEMA = 'dbo' AND t.TABLE_TYPE = 'BASE TABLE' ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION`;
31
-
32
- const KEYS_SQL = `SELECT tc.TABLE_NAME AS table_name, tc.CONSTRAINT_NAME AS name, tc.CONSTRAINT_TYPE AS type, k.COLUMN_NAME AS column_name, k.ORDINAL_POSITION AS position
33
- FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE k ON k.CONSTRAINT_NAME = tc.CONSTRAINT_NAME AND k.TABLE_SCHEMA = tc.TABLE_SCHEMA
34
- WHERE tc.TABLE_SCHEMA = 'dbo' AND tc.CONSTRAINT_TYPE IN ('PRIMARY KEY', 'UNIQUE') ORDER BY tc.CONSTRAINT_NAME, k.ORDINAL_POSITION`;
35
-
36
- const FOREIGN_SQL = `SELECT fk.name AS name, tp.name AS table_name, cp.name AS column_name, tr.name AS ftable, cr.name AS fcolumn, fkc.constraint_column_id AS position
37
- FROM sys.foreign_keys fk JOIN sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
38
- JOIN sys.tables tp ON tp.object_id = fkc.parent_object_id JOIN sys.columns cp ON cp.object_id = fkc.parent_object_id AND cp.column_id = fkc.parent_column_id
39
- JOIN sys.tables tr ON tr.object_id = fkc.referenced_object_id JOIN sys.columns cr ON cr.object_id = fkc.referenced_object_id AND cr.column_id = fkc.referenced_column_id
40
- ORDER BY fk.name, fkc.constraint_column_id`;
41
-
42
- const CHECKS_SQL = `SELECT t.name AS table_name, c.name AS column_name, cc.name AS name, cc.definition AS definition FROM sys.check_constraints cc
43
- JOIN sys.tables t ON t.object_id = cc.parent_object_id LEFT JOIN sys.columns c ON c.object_id = cc.parent_object_id AND c.column_id = cc.parent_column_id`;
44
-
45
- const COUNTS_SQL = `SELECT t.name AS table_name, CAST(SUM(p.rows) AS int) AS rows FROM sys.tables t JOIN sys.partitions p ON p.object_id = t.object_id
46
- WHERE p.index_id IN (0, 1) GROUP BY t.name`;
47
-
48
- /** A SQL Server database. */
49
- export class SqlServerDatabase implements Database {
50
- readonly dialect = 'sqlserver' as const;
51
- readonly #pool: mssql.ConnectionPool;
52
- readonly #readonly: boolean;
53
- #connected: Promise<mssql.ConnectionPool> | undefined;
54
-
55
- constructor(connection: Extract<Connection, { kind: 'sqlserver' }>, options: { readonly: boolean }) {
56
- this.#readonly = options.readonly;
57
- this.#pool = new mssql.ConnectionPool({
58
- server: connection.host, port: connection.port ?? 1433, database: connection.database, user: connection.user, password: connection.password,
59
- options: { encrypt: connection.encrypt ?? true, trustServerCertificate: true },
60
- pool: { max: 4 },
61
- });
62
- }
63
-
64
- async read(statement: Statement): Promise<Rows> {
65
- const { columns, rows } = await this.#transaction([statement], false);
66
- return { columns, rows };
67
- }
68
-
69
- write(statements: readonly Statement[]): Promise<Written> {
70
- if (this.#readonly) { return Promise.reject(new Error(READ_ONLY)); }
71
- return this.#transaction(statements, true);
72
- }
73
-
74
- dryRun(statements: readonly Statement[]): Promise<Written> {
75
- return this.#transaction(statements, false);
76
- }
77
-
78
- async #transaction(statements: readonly Statement[], commit: boolean): Promise<Written> {
79
- const pool = await this.#pool_();
80
- const transaction = new mssql.Transaction(pool);
81
- await transaction.begin();
82
- try {
83
- let affected = 0;
84
- let last: Rows = { columns: [], rows: [] };
85
- for (const statement of statements) {
86
- const result = await this.#request(transaction, statement).query(statement.sql);
87
- affected += result.rowsAffected.reduce((sum, n) => sum + n, 0);
88
- last = rowsOf(result);
89
- }
90
- if (commit) { await transaction.commit(); } else { await transaction.rollback(); }
91
- return { affected, ...last };
92
- } catch (error) {
93
- await transaction.rollback();
94
- throw error;
95
- }
96
- }
97
-
98
- async schema(): Promise<ScannedTable[]> {
99
- const ddl = dialectFor('sqlserver').ddl;
100
- const [columns, keys, foreign, checks, counts] = await Promise.all([
101
- this.#rows(ColumnRow, COLUMNS_SQL), this.#rows(KeyRow, KEYS_SQL), this.#rows(ForeignRow, FOREIGN_SQL), this.#rows(CheckRow, CHECKS_SQL), this.#rows(CountRow, COUNTS_SQL),
102
- ]);
103
- const names = [...new Set(columns.map((row) => row.table_name))].sort();
104
- return names.map((name) => {
105
- const mine = checks.filter((row) => row.table_name === name);
106
- const constraints = groupBy(keys.filter((row) => row.table_name === name), (row) => row.name);
107
- const primary = constraints.find((parts) => parts[0]?.type === 'PRIMARY KEY') ?? [];
108
- const specColumns: ColumnSpec[] = columns.filter((row) => row.table_name === name).map((row) => {
109
- const check = mine.find((item) => item.column_name === row.column_name);
110
- const values = check === undefined ? undefined : orValues(check.definition, row.column_name) ?? checkValues(check.definition, row.column_name);
111
- const length = row.max_length === null ? '' : row.max_length < 0 ? '(max)' : `(${row.max_length})`;
112
- const fallback = row.column_default === null ? undefined : ddl.readDefault(row.column_default);
113
- return {
114
- name: row.column_name,
115
- type: ddl.readColumnType(`${row.data_type}${length}`),
116
- nullable: row.is_nullable === 'YES',
117
- ...(fallback === undefined ? {} : { default: fallback }),
118
- ...(row.default_name === null ? {} : { defaultName: row.default_name }),
119
- ...(row.is_identity === 1 ? { generated: true } : {}),
120
- ...(values === undefined || check === undefined ? {} : { values, checkName: check.name }),
121
- };
122
- });
123
- const spec: TableSpec = {
124
- name,
125
- schema: 'dbo',
126
- columns: specColumns,
127
- primaryKey: primary.map((part) => part.column_name),
128
- ...(primary[0] === undefined ? {} : { primaryKeyName: primary[0].name }),
129
- unique: constraints.filter((parts) => parts[0]?.type === 'UNIQUE').map((parts) => ({ name: parts[0]?.name ?? '', columns: parts.map((part) => part.column_name) })),
130
- foreignKeys: groupBy(foreign.filter((row) => row.table_name === name), (row) => row.name).map((parts) => ({
131
- name: parts[0]?.name ?? '', columns: parts.map((part) => part.column_name), table: parts[0]?.ftable ?? '', references: parts.map((part) => part.fcolumn),
132
- })),
133
- };
134
- return ScannedTable.parse({ spec, rows: counts.find((row) => row.table_name === name)?.rows ?? 0 });
135
- });
136
- }
137
-
138
- async close(): Promise<void> {
139
- if (this.#connected !== undefined) { await this.#pool.close(); }
140
- }
141
-
142
- #pool_(): Promise<mssql.ConnectionPool> {
143
- this.#connected ??= this.#pool.connect();
144
- return this.#connected;
145
- }
146
-
147
- #request(on: mssql.ConnectionPool | mssql.Transaction, statement: Statement): mssql.Request {
148
- const request = on instanceof mssql.Transaction ? new mssql.Request(on) : new mssql.Request(on);
149
- statement.params.forEach((value, index) => { request.input(`p${index + 1}`, bindValue(value)); });
150
- return request;
151
- }
152
-
153
- async #rows<T>(schema: z.ZodType<T>, sql: string): Promise<T[]> {
154
- return z.array(schema).parse((await new mssql.Request(await this.#pool_()).query(sql)).recordset);
155
- }
156
- }
157
-
158
- /** Items grouped by a key, in first-seen order. */
159
- function groupBy<T>(items: readonly T[], key: (item: T) => string): T[][] {
160
- const groups = new Map<string, T[]>();
161
- for (const item of items) { groups.set(key(item), [...(groups.get(key(item)) ?? []), item]); }
162
- return [...groups.values()];
163
- }
164
-
165
- /** A result's last record set as rows; none for a statement that returns no rows. */
166
- export function rowsOf(result: { readonly recordset?: mssql.IRecordSet<unknown> | undefined }): Rows {
167
- // mssql gives no record set for a statement without rows (an UPDATE without OUTPUT, DDL), whatever its types say
168
- const set = result.recordset;
169
- if (set === undefined) { return { columns: [], rows: [] }; }
170
- const columns = Object.keys(set.columns);
171
- const rows: Rows['rows'] = [];
172
- for (const record of set) {
173
- rows.push(columns.map((column) => (typeof record === 'object' && record !== null && column in record ? jsonValue(Reflect.get(record, column)) : null)));
174
- }
175
- return { columns, rows };
176
- }
@@ -1,35 +0,0 @@
1
- /**
2
- * The database system's tunables, an `@ayepi/env` slice.
3
- */
4
- import { env } from '@ayepi/env';
5
- import { systemFields, systemState } from '@harness/sdk/server';
6
- import { z } from 'zod';
7
-
8
- export const databaseEnv = env({
9
- ...systemFields(),
10
- /** How many names saving a query tries (`orders`, `orders_2`, …) before giving up on a taken name. */
11
- DATABASE_NAME_TRIES: z.number().int().min(1).max(50).default(10),
12
- /** Rows a list query reads when the caller gives no `limit`. */
13
- DATABASE_PAGE_ROWS: z.number().int().min(1).default(50),
14
- /** The most rows one call may read (and the person's result holds; more is paged with `offset`). */
15
- DATABASE_MAX_ROWS: z.number().int().min(1).default(500),
16
- /** Rows a clean draft's check shows the query authoring agent. */
17
- DATABASE_DRAFT_ROWS: z.number().int().min(1).max(50).default(5),
18
- /** Rows a write's approval preview shows. */
19
- DATABASE_PREVIEW_ROWS: z.number().int().min(1).default(20),
20
- /** A text column with at most this many distinct values has them all shown to the enricher. */
21
- DATABASE_DISTINCT_MAX: z.number().int().min(1).default(12),
22
- /** How many tables a scan enriches at once (each a sample read and a model call, which waits its turn on the hub's LLM queue); 1 enriches them one after another. */
23
- DATABASE_ENRICH_PARALLEL: z.number().int().min(1).default(2),
24
- /** How many relation hops a table's generated fns follow for derived fields. */
25
- DATABASE_TABLE_FNS_DEPTH: z.number().int().min(0).max(4).default(2),
26
- /** The most fns table_fns_available lists for a table (the rest are counted as more). */
27
- DATABASE_TABLE_FNS_CAP: z.number().int().min(5).max(200).default(40),
28
- /** With the decision model off or failed: the least share of a request's words a database's tables must match to be picked. */
29
- DATABASE_PICK_MIN: z.number().min(0).max(1).default(0.2),
30
- /** With the decision model off or failed: how far the best database's match must lead the next one to be picked without asking. */
31
- DATABASE_PICK_MARGIN: z.number().min(0).max(1).default(0.15),
32
- }).add(systemState('database'));
33
-
34
- /** The database system's settings, resolved. */
35
- export type DatabaseSettings = ReturnType<typeof databaseEnv.parse>;
@@ -1,169 +0,0 @@
1
- /**
2
- * Test fixtures: a small shop database in a fresh SQLite file (customers and their orders), the config of an
3
- * instance over it, and an instance with a scripted enricher over a recording hub that keeps its types and their meta.
4
- */
5
- import { mkdirSync, mkdtempSync, readFileSync } from 'node:fs';
6
- import { join } from 'node:path';
7
- import { InstanceName, Json, SystemName, SystemPackageManifest, TypeRecord, qualify, type FleetInstance, type FnSearchQuery, type OutcomeWire, type RunSettled, type TypeDecl, type TypeDefinitions } from '@harness/core';
8
- import { serve, type RunningSystem } from '@harness/sdk/server';
9
- import { FakeHub } from '@harness/sdk/server/testing';
10
- import BetterSqlite3 from 'better-sqlite3';
11
- import { database } from '../shared/index.ts';
12
- import type { DatabaseConfig } from '../shared/shapes.ts';
13
- import type { Enricher } from './author.ts';
14
- import { databaseEnv } from './env.ts';
15
- import { SELF_FLEET, createDatabaseImpl, type DatabaseServer } from './impl.ts';
16
- import { DatabaseInstance, type HubSide } from './instance.ts';
17
- import { tableMetaOf, type KeptType } from './types.ts';
18
-
19
- /** The shop's schema and rows. */
20
- export const SHOP_SQL = `
21
- CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT NOT NULL, email TEXT, tier TEXT NOT NULL DEFAULT 'basic' CHECK (tier IN ('basic', 'gold')));
22
- CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL REFERENCES customers(id), total REAL NOT NULL, status TEXT NOT NULL, placed DATE NOT NULL);
23
- INSERT INTO customers (name, email, tier) VALUES ('Ada', 'ada@example.com', 'gold'), ('Bo', 'bo@example.com', 'basic'), ('Cy', NULL, 'basic');
24
- INSERT INTO orders (customer_id, total, status, placed) VALUES
25
- (1, 120.5, 'paid', '2026-10-01'), (1, 80, 'open', '2026-10-20'), (2, 15, 'paid', '2026-09-12'),
26
- (2, 42, 'open', '2026-11-02'), (3, 7.25, 'refunded', '2026-08-30');
27
- `;
28
-
29
- /** The projects/owners sample: an enum, a number, a date, a unique column and a foreign key (generated table fns, e2e). */
30
- export const PROJECTS_SQL = `
31
- CREATE TABLE owners (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
32
- CREATE TABLE projects (
33
- id INTEGER PRIMARY KEY, code TEXT NOT NULL UNIQUE, name TEXT NOT NULL, owner_id INTEGER NOT NULL REFERENCES owners(id),
34
- value REAL NOT NULL, status TEXT NOT NULL CHECK (status IN ('active', 'done')), started DATE NOT NULL
35
- );
36
- INSERT INTO owners (name) VALUES ('Ada'), ('Bo');
37
- INSERT INTO projects (code, name, owner_id, value, status, started) VALUES
38
- ('P1', 'Roof', 1, 100, 'done', '2026-01-05'), ('P2', 'Deck', 1, 300, 'active', '2026-02-10'),
39
- ('P3', 'Shed', 2, 50, 'active', '2026-03-15');
40
- `;
41
-
42
- /** A fresh folder under `.harness-test/`. */
43
- export function testFolder(name: string): string {
44
- mkdirSync('.harness-test', { recursive: true });
45
- return mkdtempSync(join('.harness-test', `${name}-`));
46
- }
47
-
48
- /** A shop database file in a fresh folder: its folder and file name. */
49
- export function shopFile(name = 'shop'): { dir: string; file: string } {
50
- const dir = testFolder(name);
51
- const db = new BetterSqlite3(join(dir, 'shop.db'));
52
- db.exec(SHOP_SQL);
53
- db.close();
54
- return { dir, file: 'shop.db' };
55
- }
56
-
57
- /** An instance's config over a new SQLite file in its data folder. */
58
- export function shopConfig(overrides: Partial<DatabaseConfig> = {}): DatabaseConfig {
59
- return {
60
- label: 'Shop',
61
- connection: { kind: 'sqlite-new', path: 'shop.db' },
62
- data: 'read-write',
63
- schema: 'allowed',
64
- enrich: { on: false },
65
- audience: { visibility: 'public', with: [] },
66
- ...overrides,
67
- };
68
- }
69
-
70
- /** An enricher that never runs (enrichment is off), or one that answers from a script. */
71
- export const NO_ENRICHER: Enricher = { enrich: () => Promise.reject(new Error('Enrichment is not in this test.')) };
72
-
73
- /** The hub's side, recording what it was given and keeping the table types as the hub would. */
74
- export class RecordingHub implements HubSide {
75
- readonly upserts: string[][] = [];
76
- readonly removals: string[][] = [];
77
- /** The saved query fns the hub says read each type. */
78
- readonly reading = new Map<string, string[]>();
79
- /** The table types the hub keeps, by local name. */
80
- readonly kept = new Map<string, TypeDecl>();
81
-
82
- known(): Promise<ReadonlyMap<string, KeptType>> {
83
- return Promise.resolve(new Map([...this.kept].map(([name, decl]) => [name, { def: decl.def, meta: tableMetaOf(decl.meta) }])));
84
- }
85
-
86
- /** The hub's fleet as `ctx.fleet()` lists it: one online instance with this config and the kept types. */
87
- fleet(instance: InstanceName, config: Json): FleetInstance[] {
88
- return [{ instance, description: '', online: true, config, types: [...this.kept.values()].map((decl) => ({ name: qualify('database', decl.name), description: decl.description })) }];
89
- }
90
-
91
- /** The kept types' definitions, as `ctx.types.definitions` answers. */
92
- definitions(names: readonly string[]): TypeDefinitions {
93
- const types = [...this.kept.values()].flatMap(({ name, methods: _methods, ...decl }) => (names.includes(qualify('database', name))
94
- ? [TypeRecord.parse({ ...decl, name: qualify('database', name), system: SystemName.parse('database'), references: [], updatedAt: 1_000 })]
95
- : []));
96
- return { types, missing: [] };
97
- }
98
-
99
- readers(type: string): Promise<string[]> {
100
- return Promise.resolve(this.reading.get(type) ?? []);
101
- }
102
-
103
- types(upsert: readonly TypeDecl[], remove: readonly string[]): Promise<void> {
104
- this.upserts.push(upsert.map((decl) => decl.name));
105
- this.removals.push([...remove]);
106
- for (const decl of upsert) { this.kept.set(decl.name, decl); }
107
- for (const name of remove) { this.kept.delete(name); }
108
- return Promise.resolve();
109
- }
110
- }
111
-
112
- /** An instance over a fresh shop database. */
113
- export function shopInstance(options: { config?: Partial<DatabaseConfig>; enricher?: Enricher; hub?: RecordingHub; dir?: string; enrichParallel?: number } = {}): { instance: DatabaseInstance; hub: RecordingHub; dir: string } {
114
- const dir = options.dir ?? shopFile().dir;
115
- const hub = options.hub ?? new RecordingHub();
116
- const instance = new DatabaseInstance(shopConfig(options.config), {
117
- instance: InstanceName.parse('main'), dataDir: dir, enricher: options.enricher ?? NO_ENRICHER, hub,
118
- limits: { page: 50, max: 500 }, distinctMax: 12, enrichParallel: options.enrichParallel, now: () => 1_000,
119
- });
120
- return { instance, hub, dir };
121
- }
122
-
123
- /** The system's version, as its `system.json` says. */
124
- const SYSTEM_VERSION = SystemPackageManifest.parse(JSON.parse(readFileSync(new URL('../system.json', import.meta.url), 'utf8'))).version;
125
-
126
- /** The database system served over the SDK's link runtime to a fake hub, on one instance, ready for calls. */
127
- export interface ServedDatabase {
128
- readonly hub: FakeHub;
129
- readonly server: DatabaseServer;
130
- readonly types: RecordingHub;
131
- stop(): Promise<void>;
132
- }
133
-
134
- /** A run's outcome as a child call settles. */
135
- export function settledOf(outcome: OutcomeWire): RunSettled {
136
- if (outcome.status === 'done') { return { status: 'done', result: outcome.result }; }
137
- if (outcome.status === 'invalid-input') { return { status: 'failed', error: { class: 'caller', message: outcome.invalid.problems.map((problem) => problem.message).join(' ') } }; }
138
- if (outcome.status === 'failed') { return { status: 'failed', error: outcome.error }; }
139
- return { status: 'cancelled' };
140
- }
141
-
142
- /**
143
- * Serve the database system over the link to a fake hub: the hub keeps the table types it is sent and lists them on
144
- * its fleet, searches its saved fns (and, for `types.reads`, the saved queries whose payload names a table), and
145
- * forwards a tool's work to this instance. `afterPatch` runs after each table type patch reaches the hub.
146
- */
147
- export async function serveDatabase(options: { dir: string; config?: DatabaseConfig; afterPatch?: () => Promise<void> }): Promise<ServedDatabase> {
148
- const config = options.config ?? shopConfig();
149
- const hub = new FakeHub({ config });
150
- const types = new RecordingHub();
151
- hub.onFleet = () => Promise.resolve(types.fleet(InstanceName.parse('main'), Json.parse(config)));
152
- hub.onTypes = (names) => Promise.resolve(types.definitions(names));
153
- const searchFns = (query: FnSearchQuery) => {
154
- const reads = query.types?.reads?.map((type) => type.slice(type.lastIndexOf('.') + 1)) ?? [];
155
- const page = hub.fns.search({ ...query, types: undefined });
156
- return Promise.resolve(reads.length === 0 ? page : {
157
- items: page.items.filter((hit) => reads.some((table) => JSON.stringify(hub.fns.kept.get(hit.name)?.saved.payload).includes(`"${table}"`))),
158
- });
159
- };
160
- const server = createDatabaseImpl({
161
- settings: databaseEnv.parse(), instance: InstanceName.parse('main'), dataDir: options.dir, fleet: SELF_FLEET, enricher: NO_ENRICHER, now: () => 1_000,
162
- hub: () => ({ types: async (upsert, remove) => { await types.types(upsert, remove); await options.afterPatch?.(); }, searchFns }),
163
- });
164
- hub.onCall = async (call) => hub.fns.settle(call) ?? settledOf(await hub.run(call.fn, call.args));
165
- const running: RunningSystem<'database'> = await serve(database, server.impl, { hub: 'ws://hub.test/link', state: 'unused', version: SYSTEM_VERSION }, hub.host());
166
- await running.ready();
167
- for (let wait = 0; server.current() === undefined && wait < 200; wait += 1) { await new Promise((resolve) => setTimeout(resolve, 10)); }
168
- return { hub, server, types, stop: async () => { await running.stop(); await server.close(); } };
169
- }