@crombolo/server 0.24.1 → 0.26.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.
@@ -1,229 +0,0 @@
1
- /**
2
- * Changeset persistence for the assistant, over the tables migration 017 adds.
3
- *
4
- * A proposal has to outlive the conversation that produced it: one raised over
5
- * MCP by an agent in a terminal is reviewed in the backoffice by a person in a
6
- * browser, in another process. `body` and `params` are stored as JSON because
7
- * they are a prepared Management API request and nothing here inspects them —
8
- * only the approval path, which dispatches them.
9
- */
10
- import type {
11
- ChangeOrigin,
12
- ChangeStatus,
13
- Changeset,
14
- ChangesetStore,
15
- ProposedChange,
16
- } from '@crombolo/assistant'
17
- import { normaliseUuid } from '@crombolo/core'
18
- import { type Db, DbDate } from '@crombolo/data'
19
-
20
- interface ChangesetRow {
21
- key: string
22
- user_key: string
23
- title: string
24
- origin: string
25
- create_date: unknown
26
- update_date: unknown
27
- }
28
-
29
- interface ChangeRow {
30
- key: string
31
- kind: string
32
- summary: string
33
- status: string
34
- params: string
35
- body: string
36
- baseline: string | null
37
- problems: string
38
- error: string | null
39
- create_date: unknown
40
- }
41
-
42
- const iso = (value: unknown): string => (DbDate.fromDb(value) ?? new Date(0)).toISOString()
43
-
44
- const parse = <T>(value: string, fallback: T): T => {
45
- try {
46
- return JSON.parse(value) as T
47
- } catch {
48
- return fallback
49
- }
50
- }
51
-
52
- const hydrateChange = (row: ChangeRow): ProposedChange => ({
53
- key: normaliseUuid(String(row.key)),
54
- kind: String(row.kind) as ProposedChange['kind'],
55
- summary: String(row.summary),
56
- params: parse<Record<string, string>>(String(row.params), {}),
57
- body: parse<unknown>(String(row.body), null),
58
- baseline: row.baseline === null ? undefined : String(row.baseline),
59
- problems: parse<ProposedChange['problems']>(String(row.problems), []),
60
- status: String(row.status) as ChangeStatus,
61
- error: row.error === null ? undefined : String(row.error),
62
- createDate: iso(row.create_date),
63
- })
64
-
65
- export function createChangesetStore(db: Db): ChangesetStore {
66
- const changesOf = async (changesetKey: string): Promise<ProposedChange[]> => {
67
- const rows = await db.query<ChangeRow>(
68
- `SELECT key, kind, summary, status, params, body, baseline, problems, error, create_date
69
- FROM assistant_change WHERE changeset_key = ? ORDER BY sort_order, id`,
70
- [changesetKey],
71
- )
72
- return rows.map(hydrateChange)
73
- }
74
-
75
- const hydrate = async (row: ChangesetRow): Promise<Changeset> => ({
76
- key: normaliseUuid(String(row.key)),
77
- userKey: normaliseUuid(String(row.user_key)),
78
- title: String(row.title),
79
- origin: String(row.origin) as ChangeOrigin,
80
- changes: await changesOf(normaliseUuid(String(row.key))),
81
- createDate: iso(row.create_date),
82
- updateDate: iso(row.update_date),
83
- })
84
-
85
- const touch = (key: string) =>
86
- db.exec('UPDATE assistant_changeset SET update_date = ? WHERE key = ?', [
87
- DbDate.toDb(new Date()),
88
- key,
89
- ])
90
-
91
- return {
92
- async create(input) {
93
- const key = normaliseUuid(crypto.randomUUID())
94
- const now = new Date()
95
- await db.exec(
96
- `INSERT INTO assistant_changeset (key, user_key, title, origin, create_date, update_date)
97
- VALUES (?, ?, ?, ?, ?, ?)`,
98
- [
99
- key,
100
- normaliseUuid(input.userKey),
101
- input.title,
102
- input.origin,
103
- DbDate.toDb(now),
104
- DbDate.toDb(now),
105
- ],
106
- )
107
- return {
108
- key,
109
- userKey: normaliseUuid(input.userKey),
110
- title: input.title,
111
- origin: input.origin,
112
- changes: [],
113
- createDate: now.toISOString(),
114
- updateDate: now.toISOString(),
115
- }
116
- },
117
-
118
- async load(key) {
119
- const rows = await db.query<ChangesetRow>(
120
- `SELECT key, user_key, title, origin, create_date, update_date
121
- FROM assistant_changeset WHERE key = ?`,
122
- [normaliseUuid(key)],
123
- )
124
- return rows[0] ? await hydrate(rows[0]) : undefined
125
- },
126
-
127
- async listFor(userKey, limit = 20) {
128
- const rows = await db.query<ChangesetRow>(
129
- `SELECT key, user_key, title, origin, create_date, update_date
130
- FROM assistant_changeset WHERE user_key = ?
131
- ORDER BY update_date DESC, id DESC LIMIT ?`,
132
- [normaliseUuid(userKey), limit],
133
- )
134
- const out: Changeset[] = []
135
- for (const row of rows) out.push(await hydrate(row))
136
- return out
137
- },
138
-
139
- async changeFor(userKey, changeKey) {
140
- const rows = await db.query<ChangeRow>(
141
- `SELECT c.key, c.kind, c.summary, c.status, c.params, c.body, c.baseline, c.problems,
142
- c.error, c.create_date
143
- FROM assistant_change c
144
- JOIN assistant_changeset s ON s.key = c.changeset_key
145
- WHERE c.key = ? AND s.user_key = ?`,
146
- [normaliseUuid(changeKey), normaliseUuid(userKey)],
147
- )
148
- return rows[0] ? hydrateChange(rows[0]) : undefined
149
- },
150
-
151
- async openFor(userKey, origin) {
152
- const rows = await db.query<ChangesetRow>(
153
- `SELECT s.key, s.user_key, s.title, s.origin, s.create_date, s.update_date
154
- FROM assistant_changeset s
155
- WHERE s.user_key = ? AND s.origin = ?
156
- AND EXISTS (SELECT 1 FROM assistant_change c
157
- WHERE c.changeset_key = s.key AND c.status = 'proposed')
158
- ORDER BY s.update_date DESC, s.id DESC LIMIT 1`,
159
- [normaliseUuid(userKey), origin],
160
- )
161
- return rows[0] ? await hydrate(rows[0]) : undefined
162
- },
163
-
164
- async append(changesetKey, change) {
165
- const key = normaliseUuid(changesetKey)
166
- const counted = await db.query<{ next: number | null }>(
167
- 'SELECT MAX(sort_order) AS next FROM assistant_change WHERE changeset_key = ?',
168
- [key],
169
- )
170
- const sortOrder = (counted[0]?.next ?? -1) + 1
171
- await db.exec(
172
- `INSERT INTO assistant_change
173
- (key, changeset_key, sort_order, kind, summary, status, params, body, baseline, problems, error, create_date)
174
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
175
- [
176
- normaliseUuid(change.key),
177
- key,
178
- sortOrder,
179
- change.kind,
180
- change.summary,
181
- change.status,
182
- JSON.stringify(change.params),
183
- JSON.stringify(change.body ?? null),
184
- change.baseline ?? null,
185
- JSON.stringify(change.problems),
186
- change.error ?? null,
187
- DbDate.toDb(new Date(change.createDate)),
188
- ],
189
- )
190
- await touch(key)
191
- },
192
-
193
- async replaceBody(changeKey, body, problems) {
194
- const key = normaliseUuid(changeKey)
195
- await db.exec('UPDATE assistant_change SET body = ?, problems = ? WHERE key = ?', [
196
- JSON.stringify(body ?? null),
197
- JSON.stringify(problems),
198
- key,
199
- ])
200
- const rows = await db.query<{ changeset_key: string }>(
201
- 'SELECT changeset_key FROM assistant_change WHERE key = ?',
202
- [key],
203
- )
204
- const owner = rows[0]?.changeset_key
205
- if (owner) await touch(String(owner))
206
- },
207
-
208
- async settle(changeKey, outcome) {
209
- const key = normaliseUuid(changeKey)
210
- await db.exec('UPDATE assistant_change SET status = ?, error = ? WHERE key = ?', [
211
- outcome.status,
212
- outcome.error ?? null,
213
- key,
214
- ])
215
- const rows = await db.query<{ changeset_key: string }>(
216
- 'SELECT changeset_key FROM assistant_change WHERE key = ?',
217
- [key],
218
- )
219
- const owner = rows[0]?.changeset_key
220
- if (owner) await touch(String(owner))
221
- },
222
-
223
- async remove(key) {
224
- const owner = normaliseUuid(key)
225
- await db.exec('DELETE FROM assistant_change WHERE changeset_key = ?', [owner])
226
- await db.exec('DELETE FROM assistant_changeset WHERE key = ?', [owner])
227
- },
228
- }
229
- }
@@ -1,195 +0,0 @@
1
- /**
2
- * Schema proposals as the TOML files they become.
3
- *
4
- * A type is a file in `schema/`, and that file is what gets committed, so a
5
- * proposal holds the file rather than a request body full of keys. Applying one
6
- * writes it and imports it — the same path a commit or another node's publish
7
- * takes — instead of writing the database and deriving the file from it
8
- * afterwards, which is the wrong way round and is why an editor's change could
9
- * never be classified.
10
- *
11
- * Validation happens twice on purpose: when the proposal is made, so a reviewer
12
- * is never shown something that cannot be applied, and again at approval, because
13
- * the rest of the schema may have moved in between.
14
- */
15
-
16
- import { existsSync } from 'node:fs'
17
- import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'
18
- import { dirname, join } from 'node:path'
19
- import type { SchemaProposalPort } from '@crombolo/assistant'
20
- import type { Db } from '@crombolo/data'
21
- import type { SyncReport } from '@crombolo/schema'
22
- import {
23
- fileNameFor,
24
- loadSchemaDirectory,
25
- nextSchemaVersion,
26
- parseContentType,
27
- parseDataType,
28
- type SchemaProblem,
29
- TYPE_KIND_FILES,
30
- validateSchemaSet,
31
- writeContentType,
32
- writeDataType,
33
- writeSchemaVersion,
34
- } from '@crombolo/schema'
35
- import type { CromboloConfig } from '../config.ts'
36
- import { formTypesFor } from '../form-types.ts'
37
- import { logger } from '../logging.ts'
38
- import { componentAliasesIn, importSchema } from '../schema.ts'
39
- import { publishSchema, useSchemaStore } from '../schema-store.ts'
40
-
41
- const log = logger('schema')
42
-
43
- const isDataType = (kind: string) => kind.startsWith('data-type')
44
-
45
- /** Where a kind's files live, relative to the schema directory. */
46
- const directoryFor = (kind: string) =>
47
- isDataType(kind) ? 'data-types' : TYPE_KIND_FILES.document.dir
48
-
49
- export interface SchemaProposalOptions {
50
- db: Db
51
- config: CromboloConfig
52
- /** The node's identity and state, refreshed in place by an import. */
53
- boot: { nodeId: string; nodeState: { version: string; revision: string } }
54
- /** After an import applies: what a change to how URLs are built needs. */
55
- afterSync?(report: SyncReport | undefined): Promise<void>
56
- }
57
-
58
- export function createSchemaProposals(options: SchemaProposalOptions): SchemaProposalPort {
59
- const { config } = options
60
- const pathFor = (kind: string, alias: string) =>
61
- join(config.schemaDir, directoryFor(kind), fileNameFor(alias))
62
-
63
- /**
64
- * The proposal's file substituted into the schema as it stands, so a property
65
- * pointing at a data type that does not exist, or a composition that would
66
- * cycle, is a problem now rather than a surprise at approval.
67
- */
68
- const validate = async (kind: string, alias: string, toml: string): Promise<SchemaProblem[]> => {
69
- const file = `schema/${directoryFor(kind)}/${fileNameFor(alias)}`
70
- if (isDataType(kind)) {
71
- const parsed = parseDataType(file, toml)
72
- const dataType = parsed.value
73
- if (parsed.problems.length > 0 || !dataType) {
74
- return parsed.problems.length > 0
75
- ? parsed.problems
76
- : [{ file, path: '', message: 'the file defines no data type' }]
77
- }
78
- const set = loadSchemaDirectory(config.schemaDir, { formTypes: formTypesFor(config) }).set
79
- const dataTypes = [
80
- ...set.dataTypes.filter((existing) => existing.alias !== dataType.alias),
81
- dataType,
82
- ]
83
- return validateSchemaSet({ ...set, dataTypes }, { types: formTypesFor(config) })
84
- }
85
-
86
- const parsed = parseContentType(file, toml)
87
- const contentType = parsed.value
88
- if (parsed.problems.length > 0 || !contentType) {
89
- return parsed.problems.length > 0
90
- ? parsed.problems
91
- : [{ file, path: '', message: 'the file defines no content type' }]
92
- }
93
- const set = loadSchemaDirectory(config.schemaDir, { formTypes: formTypesFor(config) }).set
94
- const contentTypes = [
95
- ...set.contentTypes.filter((existing) => existing.alias !== contentType.alias),
96
- contentType,
97
- ]
98
- return validateSchemaSet(
99
- { ...set, contentTypes },
100
- { componentAliases: componentAliasesIn(config.componentsDir), types: formTypesFor(config) },
101
- )
102
- }
103
-
104
- return {
105
- fileFor: (kind, alias) => `schema/${directoryFor(kind)}/${fileNameFor(alias)}`,
106
-
107
- async read(kind, alias) {
108
- const path = pathFor(kind, alias)
109
- if (!existsSync(path)) return undefined
110
- return await readFile(path, 'utf8')
111
- },
112
-
113
- validate,
114
-
115
- async apply(kind, alias, toml) {
116
- if (!config.schemaWritable) {
117
- return {
118
- ok: false,
119
- error:
120
- 'Types are defined in schema/ and this environment is read-only; change the file in source control, or configure a schema store.',
121
- }
122
- }
123
- const problems = await validate(kind, alias, toml)
124
- if (problems.length > 0) {
125
- return { ok: false, error: problems.map((problem) => problem.message).join('; ') }
126
- }
127
-
128
- // Fresh from the store first, then written, imported and published without
129
- // materialising again, which would lay the store's copy over this write.
130
- await useSchemaStore(config)
131
- const path = pathFor(kind, alias)
132
- const versionFile = join(config.schemaDir, 'schema.toml')
133
- const previous = existsSync(path) ? await readFile(path, 'utf8') : undefined
134
- const previousVersion = existsSync(versionFile)
135
- ? await readFile(versionFile, 'utf8')
136
- : undefined
137
- await mkdir(dirname(path), { recursive: true })
138
- await writeFile(path, canonical(kind, alias, toml), 'utf8')
139
-
140
- const restore = async () => {
141
- if (previous === undefined) await rm(path, { force: true })
142
- else await writeFile(path, previous, 'utf8')
143
- if (previousVersion !== undefined) await writeFile(versionFile, previousVersion, 'utf8')
144
- }
145
-
146
- // Classified while the files and the database still differ: afterwards there
147
- // is nothing left to compare. The version moves in the same breath, or the
148
- // import lands at a version the other nodes already have and they never
149
- // learn they are behind.
150
- const ahead = await importSchema(options.db, config, options.boot, {
151
- dryRun: true,
152
- materialise: false,
153
- })
154
- const { version, urls } = loadSchemaDirectory(config.schemaDir, {
155
- formTypes: formTypesFor(config),
156
- }).set
157
- const next = nextSchemaVersion(version, ahead.classification)
158
- if (next !== version) await writeFile(versionFile, writeSchemaVersion(next, urls), 'utf8')
159
-
160
- const result = await importSchema(options.db, config, options.boot, { materialise: false })
161
- if (result.report && result.report.action !== 'applied') {
162
- // Put the files back: a refused import leaves the site with a file it will
163
- // not accept, which is worse than the change not having happened.
164
- await restore()
165
- return {
166
- ok: false,
167
- error: result.report.reason ?? `the import was ${result.report.action}`,
168
- }
169
- }
170
- if (config.schemaStore) await publishSchema(config.schemaStore, config.schemaDir)
171
- await options.afterSync?.(result.report)
172
- log.info('{alias} applied from a proposal: {classification}, schema at {version}', {
173
- alias,
174
- classification: ahead.classification,
175
- version: options.boot.nodeState.version,
176
- })
177
- return { ok: true, version: options.boot.nodeState.version }
178
- },
179
- }
180
-
181
- /**
182
- * Written back through the canonical writer, so what lands on disk is what the
183
- * backoffice itself would write — one layout, one key order — rather than
184
- * whatever the model's formatting happened to be.
185
- */
186
- function canonical(kind: string, alias: string, toml: string): string {
187
- const file = `schema/${directoryFor(kind)}/${fileNameFor(alias)}`
188
- if (isDataType(kind)) {
189
- const parsed = parseDataType(file, toml)
190
- return parsed.value ? writeDataType(parsed.value) : toml
191
- }
192
- const parsed = parseContentType(file, toml)
193
- return parsed.value ? writeContentType(parsed.value) : toml
194
- }
195
- }