@burnsred/entity-sync 0.0.0-stage → 3.0.0-rc.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 (50) hide show
  1. package/.claude-plugin/marketplace.json +14 -0
  2. package/.claude-plugin/plugin.json +11 -0
  3. package/CHANGELOG.md +15 -0
  4. package/LICENSE +21 -0
  5. package/README.md +240 -2
  6. package/agents/entity-editor.md +16 -0
  7. package/bin/entity-sync.mjs +36 -0
  8. package/dist/cli.d.mts +20 -0
  9. package/dist/commands/asserts.d.mts +4 -0
  10. package/dist/commands/check.d.mts +6 -0
  11. package/dist/commands/inspect.d.mts +30 -0
  12. package/dist/commands/plan.d.mts +28 -0
  13. package/dist/commands/schema.d.mts +39 -0
  14. package/dist/config.d.mts +175 -0
  15. package/dist/index.d.mts +5 -0
  16. package/dist/lib/cache.d.mts +120 -0
  17. package/dist/lib/diff.d.mts +228 -0
  18. package/dist/lib/field-map.d.mts +93 -0
  19. package/dist/lib/gen-asserts.d.mts +70 -0
  20. package/dist/lib/graph.d.mts +90 -0
  21. package/dist/lib/parse-entities.d.mts +257 -0
  22. package/dist/lib/parse-schema.d.mts +98 -0
  23. package/dist/lib/resolve.d.mts +135 -0
  24. package/dist/project.d.mts +60 -0
  25. package/hooks/editor-guard.mjs +86 -0
  26. package/hooks/hooks.json +15 -0
  27. package/package.json +54 -4
  28. package/skills/entity/SKILL.md +105 -0
  29. package/skills/entity/reference/create.md +74 -0
  30. package/skills/entity/reference/editor.md +80 -0
  31. package/skills/entity/reference/enums.md +89 -0
  32. package/skills/entity/reference/fields.md +101 -0
  33. package/skills/entity/reference/sync.md +191 -0
  34. package/src/cli.mjs +110 -0
  35. package/src/commands/asserts.mjs +52 -0
  36. package/src/commands/check.mjs +88 -0
  37. package/src/commands/inspect.mjs +290 -0
  38. package/src/commands/plan.mjs +542 -0
  39. package/src/commands/schema.mjs +206 -0
  40. package/src/config.mjs +205 -0
  41. package/src/index.mjs +19 -0
  42. package/src/lib/cache.mjs +323 -0
  43. package/src/lib/diff.mjs +706 -0
  44. package/src/lib/field-map.mjs +438 -0
  45. package/src/lib/gen-asserts.mjs +478 -0
  46. package/src/lib/graph.mjs +284 -0
  47. package/src/lib/parse-entities.mjs +935 -0
  48. package/src/lib/parse-schema.mjs +667 -0
  49. package/src/lib/resolve.mjs +455 -0
  50. package/src/project.mjs +115 -0
@@ -0,0 +1,542 @@
1
+ // @ts-check
2
+ /**
3
+ * Produce the drift plan the `/entity sync` skill works from.
4
+ *
5
+ * The point of this script is that the model reads a few KB of report instead of
6
+ * the 296KB schema. Everything mechanical happens here; what reaches the model is
7
+ * only the part needing judgement.
8
+ *
9
+ * The report is deliberately terse and omits anything already correct - an
10
+ * entity with no drift does not appear at all. A report that lists everything
11
+ * trains a reader to skim it.
12
+ *
13
+ * Usage:
14
+ * entity-sync plan [--all]
15
+ *
16
+ * `--all` shows drift already seen on a previous run; by default it is collapsed
17
+ * to a one-line summary so only new drift competes for attention.
18
+ */
19
+
20
+ import { mkdirSync, writeFileSync } from 'node:fs';
21
+ import { resolve } from 'node:path';
22
+
23
+ import { display } from '../config.mjs';
24
+ import {
25
+ buildLock,
26
+ classifyStaleness,
27
+ readLock,
28
+ writeLock,
29
+ } from '../lib/cache.mjs';
30
+ import { ADVISORY_OP_KINDS, diffAll } from '../lib/diff.mjs';
31
+ import { buildGraph, findCycles, toWaves } from '../lib/graph.mjs';
32
+ import { loadProject } from '../project.mjs';
33
+
34
+ /** Op kinds that a human must decide, rather than the model applying directly. */
35
+ const BLOCKING_KINDS = new Set(['review']);
36
+
37
+ /**
38
+ * @param {import('../lib/diff.mjs').FieldOp} op
39
+ */
40
+ const isShapeOp = (op) => !ADVISORY_OP_KINDS.has(op.kind);
41
+
42
+ /**
43
+ * Build the entity dependency graph from the diffs.
44
+ *
45
+ * Edges point from a parent to the children it embeds, so `toWaves` emits leaves
46
+ * first - which is the order edits have to happen in, since a parent's field type
47
+ * names its child's Fields type.
48
+ *
49
+ * @param {import('../lib/diff.mjs').EntityDiff[]} diffs
50
+ */
51
+ function buildEntityGraph(diffs) {
52
+ const diffed = new Set(diffs.map((diff) => diff.className));
53
+
54
+ return buildGraph(
55
+ Object.fromEntries(
56
+ diffs.map((diff) => [
57
+ diff.className,
58
+ // Only edges to entities that are themselves being diffed; an edge to an
59
+ // unresolved entity carries no ordering information we can act on.
60
+ diff.nestedEntities.filter((name) => diffed.has(name)),
61
+ ]),
62
+ ),
63
+ );
64
+ }
65
+
66
+ /**
67
+ * @param {object} input
68
+ * @param {import('../lib/resolve.mjs').Resolution[]} input.resolutions
69
+ * @param {import('../lib/diff.mjs').EntityDiff[]} input.diffs
70
+ * @param {string[][]} input.waves
71
+ * @param {string[]} input.unordered
72
+ * @param {string[][]} input.cycles
73
+ * @param {Map<string, import('../lib/cache.mjs').Staleness>} input.staleness
74
+ * @param {import('../lib/resolve.mjs').EnumResolution[]} [input.enumResolutions]
75
+ * @param {Record<string, import('../lib/parse-schema.mjs').SchemaComponent>} [input.components]
76
+ * @param {boolean} [input.showAll] include drift already seen on a previous run
77
+ */
78
+ export function renderReport({
79
+ resolutions,
80
+ diffs,
81
+ waves,
82
+ unordered,
83
+ cycles,
84
+ staleness,
85
+ enumResolutions = [],
86
+ components = {},
87
+ showAll = false,
88
+ }) {
89
+ // Only shape ops decide whether an entity needs editing; advisory ops are
90
+ // collected separately so they cannot crowd out real drift.
91
+ const allWithOps = diffs.filter((diff) => diff.ops.some(isShapeOp));
92
+
93
+ // Drift already read on a previous run is collapsed by default: on a repeat
94
+ // sync it must not be indistinguishable from drift that just appeared.
95
+ const seenBefore = allWithOps.filter(
96
+ (diff) => staleness.get(diff.className) === 'unchanged',
97
+ );
98
+ const withOps = showAll
99
+ ? allWithOps
100
+ : allWithOps.filter(
101
+ (diff) => staleness.get(diff.className) !== 'unchanged',
102
+ );
103
+
104
+ const byClassName = new Map(withOps.map((diff) => [diff.className, diff]));
105
+
106
+ const totalShapeOps = withOps.reduce(
107
+ (sum, diff) => sum + diff.ops.filter(isShapeOp).length,
108
+ 0,
109
+ );
110
+ const advisory = diffs.flatMap((diff) =>
111
+ diff.ops
112
+ .filter((op) => op.kind === 'readonly-hint')
113
+ .map((op) => ({ diff, op })),
114
+ );
115
+ const blocking = diffs.flatMap((diff) =>
116
+ diff.ops
117
+ .filter((op) => BLOCKING_KINDS.has(op.kind))
118
+ .map((op) => ({ diff, op })),
119
+ );
120
+
121
+ const unresolved = resolutions.filter((r) => !r.component && !r.excluded);
122
+ const ambiguous = resolutions.filter((r) => r.component && r.ambiguous);
123
+
124
+ // Suppressions are never collapsed by staleness. They are an inventory of
125
+ // standing decisions rather than news, and the whole point is that one which
126
+ // has quietly stopped being necessary stays visible until someone removes it.
127
+ const suppressions = diffs.flatMap((diff) =>
128
+ diff.suppressions.map((suppression) => ({ diff, suppression })),
129
+ );
130
+ const reviewable = suppressions.filter(
131
+ ({ suppression }) => suppression.status !== 'needed',
132
+ );
133
+
134
+ const lines = ['# entity-sync plan', ''];
135
+
136
+ lines.push(
137
+ `${diffs.length} entities checked, ${diffs.length - allWithOps.length} clean, ` +
138
+ `${withOps.length} to edit (${totalShapeOps} ops).`,
139
+ `${unresolved.length} unresolved, ${ambiguous.length} ambiguous, ` +
140
+ `${blocking.length} needing a decision, ${advisory.length} advisory.`,
141
+ `${suppressions.length} suppressed by an annotation` +
142
+ `${reviewable.length ? `, ${reviewable.length} to review` : ''}.`,
143
+ '',
144
+ );
145
+
146
+ if (seenBefore.length && !showAll) {
147
+ const opCount = seenBefore.reduce(
148
+ (sum, diff) => sum + diff.ops.filter(isShapeOp).length,
149
+ 0,
150
+ );
151
+ lines.push(
152
+ `${seenBefore.length} entities have the same drift as the last run ` +
153
+ `(${opCount} ops), omitted below. Run with \`--all\` to include them:`,
154
+ seenBefore.map((diff) => diff.className).join(', '),
155
+ '',
156
+ );
157
+ }
158
+
159
+ if (unresolved.length) {
160
+ lines.push(
161
+ '## Unresolved',
162
+ '',
163
+ 'No component to compare against. Add a `@schema <Component>` annotation,',
164
+ 'or `@noSchema <reason>` if the entity models no API resource.',
165
+ '',
166
+ '| entity | file | reason |',
167
+ '| --- | --- | --- |',
168
+ );
169
+ for (const r of unresolved) {
170
+ lines.push(`| ${r.className} | ${r.file} | ${r.note ?? ''} |`);
171
+ }
172
+ lines.push('');
173
+ }
174
+
175
+ if (ambiguous.length) {
176
+ lines.push(
177
+ '## Ambiguous mappings',
178
+ '',
179
+ 'Confirm, then annotate so it is never re-derived.',
180
+ '',
181
+ '| entity | chosen | alternatives |',
182
+ '| --- | --- | --- |',
183
+ );
184
+ for (const r of ambiguous) {
185
+ const alternatives = r.candidates
186
+ .map((c) => `${c.component} (${c.via} ${c.score})`)
187
+ .join(', ');
188
+ lines.push(`| ${r.className} | ${r.component} | ${alternatives} |`);
189
+ }
190
+ lines.push('');
191
+ }
192
+
193
+ if (cycles.length) {
194
+ lines.push(
195
+ '## Cycles',
196
+ '',
197
+ 'Mutually recursive entities. Each group has no valid internal ordering,',
198
+ 'so edit its members together.',
199
+ '',
200
+ );
201
+ for (const cycle of cycles) lines.push(`- ${cycle.join(' <-> ')}`);
202
+ lines.push('');
203
+ }
204
+
205
+ if (blocking.length) {
206
+ lines.push(
207
+ '## Needs a decision',
208
+ '',
209
+ '| entity | field | issue |',
210
+ '| --- | --- | --- |',
211
+ );
212
+ for (const { diff, op } of blocking) {
213
+ lines.push(`| ${diff.className} | ${op.field} | ${op.detail} |`);
214
+ }
215
+ lines.push('');
216
+ }
217
+
218
+ if (withOps.length) {
219
+ lines.push(
220
+ '## Edits, in dependency order',
221
+ '',
222
+ "Children before parents: a parent's field type names its child's Fields",
223
+ 'type, so editing out of order means revisiting files. Entities within a',
224
+ 'wave are independent of each other.',
225
+ '',
226
+ );
227
+
228
+ const orderedGroups = [
229
+ ...waves.map((wave, index) => ({
230
+ title: `Wave ${index + 1}`,
231
+ members: wave,
232
+ })),
233
+ ...(unordered.length
234
+ ? [{ title: 'Unordered (in a cycle)', members: unordered }]
235
+ : []),
236
+ ];
237
+
238
+ for (const group of orderedGroups) {
239
+ const present = group.members.filter((name) => byClassName.has(name));
240
+ if (!present.length) continue;
241
+
242
+ lines.push(`### ${group.title}`, '');
243
+
244
+ for (const className of present) {
245
+ const diff = /** @type {import('../lib/diff.mjs').EntityDiff} */ (
246
+ byClassName.get(className)
247
+ );
248
+ const why = staleness.get(diff.className);
249
+ lines.push(
250
+ `#### ${diff.className} -> ${diff.component}` +
251
+ (why && why !== 'unchanged' ? ` _(${why})_` : ''),
252
+ '',
253
+ );
254
+ lines.push(`\`${diff.file}\``, '');
255
+ for (const op of diff.ops.filter(isShapeOp)) {
256
+ lines.push(`- **${op.kind}** \`${op.field}\` - ${op.detail}`);
257
+ }
258
+ lines.push('');
259
+ }
260
+ }
261
+ }
262
+
263
+ if (advisory.length) {
264
+ lines.push(
265
+ '## Advisory',
266
+ '',
267
+ '`Field.readOnly` is not implemented in the entity library, so these are',
268
+ 'statements of intent rather than behaviour. Worth adding when touching the',
269
+ 'entity anyway; not worth a pass of their own.',
270
+ '',
271
+ );
272
+ const byEntity = new Map();
273
+ for (const { diff, op } of advisory) {
274
+ const fields = byEntity.get(diff.className) ?? [];
275
+ fields.push(op.field);
276
+ byEntity.set(diff.className, fields);
277
+ }
278
+ for (const [className, fields] of byEntity) {
279
+ lines.push(`- ${className}: ${fields.join(', ')}`);
280
+ }
281
+ lines.push('');
282
+ }
283
+
284
+ const excluded = resolutions.filter((r) => r.excluded);
285
+ if (excluded.length) {
286
+ lines.push('## Excluded', '');
287
+ for (const r of excluded) lines.push(`- ${r.className} - ${r.note}`);
288
+ lines.push('');
289
+ }
290
+
291
+ // Value drift between a dict and the component it claims. `entity:check` is
292
+ // the authority here - the generated `Exact` assertion catches it in both
293
+ // directions - but the report is read first, and a failing assertion is
294
+ // easier to act on when the report has already named the values.
295
+ const enumDrift = enumResolutions
296
+ .filter((resolution) => resolution.component)
297
+ .map((resolution) => {
298
+ const wire = new Set(
299
+ components[/** @type {string} */ (resolution.component)]?.enumValues ??
300
+ [],
301
+ );
302
+ const dict = new Set(resolution.values);
303
+
304
+ return {
305
+ resolution,
306
+ missing: [...wire].filter((value) => !dict.has(value)),
307
+ extra: [...dict].filter((value) => !wire.has(value)),
308
+ };
309
+ })
310
+ .filter((entry) => entry.missing.length || entry.extra.length);
311
+
312
+ const enumNotes = enumResolutions.filter((resolution) => resolution.note);
313
+
314
+ // An untagged dict whose values already match a component is one `@schemaEnum`
315
+ // line away from being checked. Worth saying explicitly: the `enum-missing`
316
+ // ops say "a dict is needed", and without this the obvious reading is "write a
317
+ // new one" when the right move is to tag the one already sitting there.
318
+ const key = (/** @type {string[]} */ values) => [...values].sort().join('');
319
+ const componentsByValues = new Map(
320
+ Object.values(components)
321
+ .filter((component) => component.kind === 'enum')
322
+ .map((component) => [key(component.enumValues), component.name]),
323
+ );
324
+ const taggable = enumResolutions
325
+ .filter((resolution) => resolution.local)
326
+ .map((resolution) => ({
327
+ resolution,
328
+ component: componentsByValues.get(key(resolution.values)),
329
+ }))
330
+ .filter((entry) => entry.component);
331
+
332
+ if (enumDrift.length || enumNotes.length || taggable.length) {
333
+ lines.push('## Enums', '');
334
+
335
+ if (enumDrift.length) {
336
+ lines.push(
337
+ 'Choices dicts that disagree with the `*Enum` component they are tagged',
338
+ "against. The values are the broker's to decide, so a missing one is a",
339
+ 'value the app cannot represent and an extra one is a value the broker',
340
+ 'will never send.',
341
+ '',
342
+ );
343
+ }
344
+
345
+ for (const { resolution, missing, extra } of enumDrift) {
346
+ const parts = [
347
+ missing.length
348
+ ? `missing ${missing.map((v) => `\`${v}\``).join(', ')}`
349
+ : '',
350
+ extra.length ? `extra ${extra.map((v) => `\`${v}\``).join(', ')}` : '',
351
+ ].filter(Boolean);
352
+ lines.push(
353
+ `- ${resolution.name} -> ${resolution.component} (\`${resolution.file}\`): ${parts.join('; ')}`,
354
+ );
355
+ }
356
+
357
+ for (const resolution of enumNotes) {
358
+ lines.push(
359
+ `- ${resolution.name} (\`${resolution.file}\`): ${resolution.note}`,
360
+ );
361
+ }
362
+
363
+ if (taggable.length) {
364
+ if (enumDrift.length || enumNotes.length) lines.push('');
365
+ lines.push(
366
+ 'Already correct, just untagged - these dicts hold exactly their',
367
+ "component's values, so adding the tag brings them under `entity:check`",
368
+ 'without changing a line of behaviour:',
369
+ '',
370
+ );
371
+ for (const { resolution, component } of taggable) {
372
+ lines.push(
373
+ `- ${resolution.name} (\`${resolution.file}\`) - add \`@schemaEnum ${component}\``,
374
+ );
375
+ }
376
+ }
377
+
378
+ lines.push('');
379
+ }
380
+
381
+ const projections = diffs.filter((diff) => diff.schemaSubset !== null);
382
+
383
+ if (suppressions.length || projections.length) {
384
+ lines.push(
385
+ '## Suppressions',
386
+ '',
387
+ 'Standing decisions that hold drift back from the check, and what each one',
388
+ 'is currently hiding. A **redundant** entry means the schema and the entity',
389
+ 'now agree, so the annotation has outlived its reason and should be deleted;',
390
+ '**orphaned** means it names a field that exists in neither. Both keep a',
391
+ 'field excluded from `entity:check` for no remaining benefit.',
392
+ '',
393
+ );
394
+
395
+ if (reviewable.length) {
396
+ lines.push(
397
+ `To review: ${reviewable
398
+ .map(
399
+ ({ diff, suppression }) =>
400
+ `${diff.className}.${suppression.field} (${suppression.status})`,
401
+ )
402
+ .join(', ')}`,
403
+ '',
404
+ );
405
+ }
406
+
407
+ const byEntity = new Map();
408
+ for (const entry of suppressions) {
409
+ const group = byEntity.get(entry.diff.className) ?? [];
410
+ group.push(entry.suppression);
411
+ byEntity.set(entry.diff.className, group);
412
+ }
413
+
414
+ for (const [className, group] of byEntity) {
415
+ lines.push(`### ${className}`, '');
416
+ for (const suppression of group) {
417
+ lines.push(
418
+ `- \`${suppression.field}\` **${suppression.status}**` +
419
+ `${suppression.reason ? ` - ${suppression.reason}` : ' - no reason given'}`,
420
+ );
421
+ for (const op of suppression.ops) {
422
+ lines.push(` - **${op.kind}** ${op.detail}`);
423
+ }
424
+ }
425
+ lines.push('');
426
+ }
427
+
428
+ if (projections.length) {
429
+ lines.push(
430
+ '### Projections',
431
+ '',
432
+ 'Compared with `SubsetKeys` rather than `SameKeys`, so a field the entity',
433
+ 'does not declare is not drift. Extra and misnamed fields still surface.',
434
+ '',
435
+ );
436
+ for (const diff of projections) {
437
+ const dropped = diff.subsetDropped.length
438
+ ? `${diff.subsetDropped.length} not compared: ${diff.subsetDropped.join(', ')}`
439
+ : 'declares every field the component sends';
440
+ lines.push(
441
+ `- ${diff.className} - ${diff.schemaSubset || 'declared'} (${dropped})`,
442
+ );
443
+ }
444
+ lines.push('');
445
+ }
446
+ }
447
+
448
+ return lines.join('\n');
449
+ }
450
+
451
+ /**
452
+ * @param {import('../config.mjs').ResolvedConfig} config
453
+ * @param {string[]} [args]
454
+ */
455
+ export function run(config, args = []) {
456
+ const showAll = args.includes('--all');
457
+ const outDir = config.stateDir;
458
+ const lockPath = resolve(outDir, 'lock.json');
459
+
460
+ const {
461
+ schema,
462
+ entities,
463
+ resolutions,
464
+ entityByComponent,
465
+ enums,
466
+ enumResolutions,
467
+ enumByComponent,
468
+ } = loadProject(config);
469
+
470
+ const diffs = diffAll({
471
+ entities,
472
+ resolutions,
473
+ schema,
474
+ entityByComponent,
475
+ enumByComponent,
476
+ equivalentFieldClasses: config.equivalentFieldClasses,
477
+ });
478
+
479
+ const graph = buildEntityGraph(diffs);
480
+ const { waves, unordered } = toWaves(graph);
481
+ const cycles = findCycles(graph);
482
+
483
+ // Compare against the previous run before overwriting the lockfile.
484
+ const previous = readLock(lockPath);
485
+ const current = buildLock({ schema, entities, diffs, enums });
486
+ const staleness = classifyStaleness({ diffs, previous, current, graph });
487
+
488
+ mkdirSync(outDir, { recursive: true });
489
+
490
+ const markdown = renderReport({
491
+ resolutions,
492
+ diffs,
493
+ waves,
494
+ unordered,
495
+ cycles,
496
+ staleness,
497
+ enumResolutions,
498
+ components: schema.components,
499
+ showAll,
500
+ });
501
+
502
+ writeFileSync(resolve(outDir, 'report.md'), `${markdown}\n`);
503
+ writeFileSync(
504
+ resolve(outDir, 'plan.json'),
505
+ `${JSON.stringify(
506
+ {
507
+ resolutions,
508
+ diffs,
509
+ waves,
510
+ unordered,
511
+ cycles,
512
+ staleness: Object.fromEntries(staleness),
513
+ // Flattened out of `diffs` as well, so a consumer auditing standing
514
+ // decisions does not have to walk every entity to find four of them.
515
+ suppressions: diffs.flatMap((diff) =>
516
+ diff.suppressions.map((suppression) => ({
517
+ className: diff.className,
518
+ file: diff.file,
519
+ ...suppression,
520
+ })),
521
+ ),
522
+ },
523
+ null,
524
+ 2,
525
+ )}\n`,
526
+ );
527
+
528
+ // Written last, so a crash mid-run leaves the previous state intact rather
529
+ // than recording drift as "seen" when it was never shown.
530
+ writeLock(lockPath, current);
531
+
532
+ console.log(markdown);
533
+ if (config.knownNoise) {
534
+ console.log(
535
+ `known noise (not real drift): ${display(config, config.knownNoise)}`,
536
+ );
537
+ }
538
+ console.log(
539
+ `wrote ${display(config, outDir)}/report.md, plan.json and lock.json ` +
540
+ `(${Object.keys(schema.components).length} components, ${entities.length} entity classes)`,
541
+ );
542
+ }