-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapply.ts
More file actions
246 lines (223 loc) · 7.69 KB
/
Copy pathapply.ts
File metadata and controls
246 lines (223 loc) · 7.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import * as path from 'path';
import { QueryBuilder } from '../db/queries';
import type { RelationKind } from '../types';
import {
assertBaseGraphVersion,
bumpGraphVersionAfterUpdate,
GraphVersionError,
readGraphVersion,
} from '../version';
import type {
AgentAssetPatch,
AgentRelationPatch,
AgentUpdatePayload,
ApplyError,
ApplyOptions,
ApplyResult,
} from './types';
import { RELATION_KINDS } from './types';
import { isValidAssetKind } from './baseline';
const MAX_PATH_LENGTH = 4096;
const MAX_NAME_LENGTH = 10000;
function isValidRelationKind(k: string): k is RelationKind {
return (RELATION_KINDS as string[]).includes(k);
}
function validateSourceFile(sourceFile: string): string | null {
if (!sourceFile || typeof sourceFile !== 'string') return 'sourceFile required';
if (sourceFile.length > MAX_PATH_LENGTH) return 'sourceFile too long';
if (path.isAbsolute(sourceFile)) return 'sourceFile must be relative';
if (sourceFile.includes('..')) return 'sourceFile must not contain ..';
return null;
}
function validateAssetPatch(patch: AgentAssetPatch, index: number): ApplyError | null {
if (!isValidAssetKind(patch.kind)) {
return { index, field: 'kind', message: `invalid kind: ${patch.kind}` };
}
if (!patch.name || patch.name.length > MAX_NAME_LENGTH) {
return { index, field: 'name', message: 'invalid or missing name' };
}
if (!patch.qualifiedName || patch.qualifiedName.length > MAX_NAME_LENGTH) {
return { index, field: 'qualifiedName', message: 'invalid or missing qualifiedName' };
}
const sfErr = validateSourceFile(patch.sourceFile);
if (sfErr) return { index, field: 'sourceFile', message: sfErr };
return null;
}
function mergeMetadataForUpsert(
existing: Record<string, unknown> | null,
patch: Record<string, unknown> | undefined,
): string {
const base = existing ?? {};
const merged = {
...base,
...(patch ?? {}),
enrichedBy: 'agent',
enrichedAt: new Date().toISOString(),
};
return JSON.stringify(merged);
}
function resolveApplyOptions(options?: ApplyOptions | boolean): ApplyOptions {
if (typeof options === 'boolean') {
throw new Error('applyUpdates requires projectRoot in ApplyOptions');
}
if (!options?.projectRoot) {
throw new Error('applyUpdates requires projectRoot in ApplyOptions');
}
return options;
}
export function applyUpdates(
queries: QueryBuilder,
payload: AgentUpdatePayload,
options: ApplyOptions,
): ApplyResult {
const { dryRun = false, baseVersion, projectRoot } = resolveApplyOptions(options);
const errors: ApplyError[] = [];
let assetsUpserted = 0;
let assetsDeleted = 0;
let relationsAdded = 0;
const base = baseVersion ?? payload.baseVersion;
if (base) {
try {
assertBaseGraphVersion(queries, projectRoot, base);
} catch (e) {
const message = e instanceof GraphVersionError ? e.message : String(e);
return {
assetsUpserted: 0,
assetsDeleted: 0,
relationsAdded: 0,
errors: [{ index: -1, field: 'baseVersion', message }],
dryRun,
graphVersion: readGraphVersion(queries, projectRoot),
};
}
}
const assets = payload.assets ?? [];
const relations = payload.relations ?? [];
for (let i = 0; i < assets.length; i++) {
const patch = assets[i];
if (!patch) continue;
const err = validateAssetPatch(patch, i);
if (err) {
errors.push(err);
continue;
}
const action = patch.action ?? 'upsert';
if (action === 'delete') {
if (!dryRun) {
const deleted = queries.deleteAsset(patch.kind, patch.qualifiedName, patch.sourceFile);
if (deleted) assetsDeleted++;
else errors.push({ index: i, field: 'action', message: 'asset not found for delete' });
} else {
assetsDeleted++;
}
continue;
}
const existing = queries.findAssetByQualified(patch.kind, patch.qualifiedName, patch.sourceFile);
let existingMeta: Record<string, unknown> | null = null;
if (existing) {
try {
existingMeta = JSON.parse(existing.metadataJson) as Record<string, unknown>;
} catch { /* ignore */ }
}
if (!dryRun) {
let definition: Record<string, unknown> = patch.definition ?? {};
if (!patch.definition && existing) {
try {
definition = JSON.parse(existing.definitionJson) as Record<string, unknown>;
} catch { /* keep {} */ }
}
queries.upsertAsset({
kind: patch.kind,
name: patch.name,
qualifiedName: patch.qualifiedName,
sourceFile: patch.sourceFile,
definitionJson: JSON.stringify(definition),
metadataJson: mergeMetadataForUpsert(existingMeta, patch.metadata),
});
}
assetsUpserted++;
}
for (let i = 0; i < relations.length; i++) {
const rel = relations[i];
if (!rel) continue;
if (!isValidRelationKind(rel.relation)) {
errors.push({ index: i, field: 'relation', message: `invalid relation: ${rel.relation}` });
continue;
}
if (!isValidAssetKind(rel.from.kind) || !isValidAssetKind(rel.to.kind)) {
errors.push({ index: i, field: 'kind', message: 'invalid from/to kind' });
continue;
}
const fromAsset = resolveRelationEndpoint(queries, rel.from, dryRun);
const toAsset = resolveRelationEndpoint(queries, rel.to, dryRun);
if (!fromAsset) {
errors.push({ index: i, field: 'from', message: `asset not found: ${rel.from.qualifiedName}` });
continue;
}
if (!toAsset) {
errors.push({ index: i, field: 'to', message: `asset not found: ${rel.to.qualifiedName}` });
continue;
}
if (!dryRun) {
queries.addRelation(rel.relation, fromAsset.id, toAsset.id);
}
relationsAdded++;
}
let graphVersion = readGraphVersion(queries, projectRoot);
const hadWrites = assetsUpserted > 0 || assetsDeleted > 0 || relationsAdded > 0;
if (!dryRun && hadWrites) {
queries.setMetadata('index_status', 'ready');
queries.setMetadata('enrichment_status', 'agent_augmented');
graphVersion = bumpGraphVersionAfterUpdate(queries, projectRoot);
}
return {
assetsUpserted,
assetsDeleted,
relationsAdded,
errors,
dryRun,
graphVersion,
};
}
function resolveRelationEndpoint(
queries: QueryBuilder,
ref: AgentRelationPatch['from'],
dryRun: boolean,
): { id: number } | null {
const found = queries.findAssetByQualified(ref.kind, ref.qualifiedName, ref.sourceFile);
if (found) return { id: found.id };
if (dryRun) return { id: -1 };
return null;
}
export function formatApplyResult(result: ApplyResult): string {
const lines = [
`# Apply Updates${result.dryRun ? ' (dry run)' : ''}`,
'',
`assetsUpserted: ${result.assetsUpserted}`,
`assetsDeleted: ${result.assetsDeleted}`,
`relationsAdded: ${result.relationsAdded}`,
];
if (result.errors.length > 0) {
lines.push('', '## Errors');
for (const e of result.errors) {
lines.push(`- [${e.field}#${e.index}] ${e.message}`);
}
}
if (result.graphVersion) {
lines.push(`graphVersion: ${result.graphVersion}`);
}
if (!result.dryRun && result.assetsUpserted + result.assetsDeleted + result.relationsAdded > 0) {
lines.push('', 'index_status set to ready.');
}
return lines.join('\n');
}
export function parseApplyPayload(raw: unknown): AgentUpdatePayload | { error: string } {
if (!raw || typeof raw !== 'object') return { error: 'payload must be an object' };
const obj = raw as Record<string, unknown>;
const payload: AgentUpdatePayload = {
assets: Array.isArray(obj.assets) ? obj.assets as AgentAssetPatch[] : [],
relations: Array.isArray(obj.relations) ? obj.relations as AgentRelationPatch[] : [],
};
if (typeof obj.baseVersion === 'string') payload.baseVersion = obj.baseVersion;
return payload;
}