@openparachute/vault 0.6.4-rc.9 → 0.6.5-rc.1

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.
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Schema conformance check — count how many EXISTING notes would violate a
3
+ * PROPOSED field spec for a tag, before the operator commits a tightening
4
+ * (vault#283, the MW2/#314 tie-in).
5
+ *
6
+ * Motivation: marking a field `strict`/`required`, narrowing an `enum`, or
7
+ * changing a `type` is a backwards-incompatible move — notes written under
8
+ * the old contract may now reject on their next write
9
+ * (`enforceStrictSchema` → `SchemaValidationError`). The Schema editor in
10
+ * the admin SPA calls this BEFORE save so the operator sees "N existing
11
+ * notes violate this — they'll reject on next write" and is pointed at the
12
+ * `parachute-vault schema migrate-field` CLI (#314) rather than silently
13
+ * shipping a contract their own data breaks.
14
+ *
15
+ * What "violate" means here: we overlay the PROPOSED `fields` for `tag` on
16
+ * top of the live schema config, treating every proposed field as if it
17
+ * were `strict:true` for the purpose of the count (so the count is "notes
18
+ * that would hard-reject IF this field were strict" — the worst case the
19
+ * operator is being warned about). We then walk every note carrying `tag`
20
+ * (descendants included, per the hierarchy) and run the SAME `validateNote`
21
+ * resolver the write path uses, counting notes with ≥1 violation on a field
22
+ * the proposal touches.
23
+ *
24
+ * This is a READ — no mutation. It's deliberately scoped to the proposed
25
+ * tag's own fields (the columns the operator is editing); inherited fields
26
+ * from ancestors are already enforced and aren't what the operator is
27
+ * tightening in this edit.
28
+ */
29
+
30
+ import { Database } from "bun:sqlite";
31
+ import {
32
+ loadSchemaConfig,
33
+ validateNote,
34
+ type SchemaField,
35
+ type ResolvedSchemas,
36
+ } from "./schema-defaults.ts";
37
+ import type { TagFieldSchema } from "./tag-schemas.ts";
38
+ import { getTagDescendants, loadTagHierarchy } from "./tag-hierarchy.ts";
39
+ import { queryNotes, getNoteTagsForNotes } from "./notes.ts";
40
+
41
+ export interface ConformanceViolation {
42
+ /** Note id of a non-conforming note. */
43
+ id: string;
44
+ /** Note path, when set (helps the operator find it). */
45
+ path?: string | null;
46
+ /** The proposed-field violations on this note (reasons + messages). */
47
+ fields: { field: string; reason: string; message: string }[];
48
+ }
49
+
50
+ export interface ConformanceReport {
51
+ tag: string;
52
+ /** Total notes carrying the tag (descendants included). */
53
+ total_notes: number;
54
+ /** Count of notes that would violate the proposed spec. */
55
+ violating_notes: number;
56
+ /** The field names the proposal touches (the ones checked). */
57
+ checked_fields: string[];
58
+ /**
59
+ * A bounded sample of violating notes (id + path + which fields), so the
60
+ * SPA can show examples without paging the whole vault. Capped at
61
+ * `sampleLimit` (default 20).
62
+ */
63
+ sample: ConformanceViolation[];
64
+ }
65
+
66
+ /**
67
+ * Convert the on-disk `TagFieldSchema` shape to the resolver's `SchemaField`
68
+ * shape, FORCING `strict:true` so `validateNote` flags every constraint as a
69
+ * (strict) violation we can count. `indexed` is dropped — it's not a
70
+ * note-data constraint. `type` is narrowed to the resolver's union; an
71
+ * unknown type string is dropped (no type check) rather than throwing.
72
+ */
73
+ function toStrictSchemaField(spec: TagFieldSchema): SchemaField {
74
+ const out: SchemaField = { strict: true };
75
+ if (
76
+ spec.type === "string" ||
77
+ spec.type === "number" ||
78
+ spec.type === "integer" ||
79
+ spec.type === "boolean" ||
80
+ spec.type === "array" ||
81
+ spec.type === "object"
82
+ ) {
83
+ out.type = spec.type;
84
+ }
85
+ if (Array.isArray(spec.enum)) out.enum = spec.enum;
86
+ if (spec.required === true) out.required = true;
87
+ if (spec.cardinality === "one" || spec.cardinality === "many") {
88
+ out.cardinality = spec.cardinality;
89
+ }
90
+ if (typeof spec.description === "string") out.description = spec.description;
91
+ return out;
92
+ }
93
+
94
+ /**
95
+ * Build a `ResolvedSchemas` snapshot with the proposed fields overlaid on
96
+ * `tag`'s OWN field map. We start from the live config (so inheritance +
97
+ * other tags are intact) and replace just `tag`'s field declarations with
98
+ * the strict-forced proposed set.
99
+ */
100
+ function overlayProposedSchema(
101
+ base: ResolvedSchemas,
102
+ tag: string,
103
+ proposedFields: Record<string, TagFieldSchema>,
104
+ ): ResolvedSchemas {
105
+ const tagToFields = new Map(base.tagToFields);
106
+ const forced: Record<string, SchemaField> = {};
107
+ for (const [name, spec] of Object.entries(proposedFields)) {
108
+ forced[name] = toStrictSchemaField(spec);
109
+ }
110
+ if (Object.keys(forced).length > 0) {
111
+ tagToFields.set(tag, forced);
112
+ } else {
113
+ tagToFields.delete(tag);
114
+ }
115
+ return {
116
+ allTags: new Set(base.allTags).add(tag),
117
+ tagToFields,
118
+ tagToParents: base.tagToParents,
119
+ };
120
+ }
121
+
122
+ /**
123
+ * Count existing notes that would violate the PROPOSED field spec for `tag`.
124
+ *
125
+ * `proposedFields` is the full merged field map the operator intends to save
126
+ * (the same object the PUT body carries). Only the fields in this map are
127
+ * checked — the violation count answers "if I tighten THESE fields, how many
128
+ * notes break?" The check runs against every note carrying `tag` or any of
129
+ * its descendants.
130
+ *
131
+ * Pure read; no mutation. Returns 0 violating notes when `proposedFields` is
132
+ * empty (nothing to enforce).
133
+ */
134
+ export function countConformanceViolations(
135
+ db: Database,
136
+ tag: string,
137
+ proposedFields: Record<string, TagFieldSchema>,
138
+ opts: { sampleLimit?: number } = {},
139
+ ): ConformanceReport {
140
+ const sampleLimit = opts.sampleLimit ?? 20;
141
+ const checkedFields = Object.keys(proposedFields);
142
+
143
+ const empty: ConformanceReport = {
144
+ tag,
145
+ total_notes: 0,
146
+ violating_notes: 0,
147
+ checked_fields: checkedFields,
148
+ sample: [],
149
+ };
150
+
151
+ // Resolve the tag's descendant set so we count notes on subtype tags too
152
+ // (a strict field on `#dev` applies to `#dev/log` notes via inheritance).
153
+ const hierarchy = loadTagHierarchy(db);
154
+ const tagSet = Array.from(getTagDescendants(hierarchy, tag));
155
+ if (tagSet.length === 0) return empty;
156
+
157
+ // All notes carrying the tag (or a descendant). `tagMatch: "any"` over the
158
+ // expanded set — a note on ANY of these tags is in scope. We hydrate tags
159
+ // ourselves (batched) so the resolver sees the full ancestor set per note.
160
+ const notes = queryNotes(db, { tags: tagSet, tagMatch: "any" });
161
+ if (notes.length === 0) return empty;
162
+
163
+ if (checkedFields.length === 0) {
164
+ return { ...empty, total_notes: notes.length };
165
+ }
166
+
167
+ const base = loadSchemaConfig(db);
168
+ const resolved = overlayProposedSchema(base, tag, proposedFields);
169
+ const checkedSet = new Set(checkedFields);
170
+
171
+ const tagsById = getNoteTagsForNotes(
172
+ db,
173
+ notes.map((n) => n.id),
174
+ );
175
+
176
+ let violating = 0;
177
+ const sample: ConformanceViolation[] = [];
178
+
179
+ for (const note of notes) {
180
+ const tags = tagsById.get(note.id) ?? note.tags ?? [];
181
+ const status = validateNote(resolved, {
182
+ path: note.path ?? null,
183
+ tags,
184
+ metadata: note.metadata ?? {},
185
+ });
186
+ if (!status) continue;
187
+ // Keep only violations on a field the PROPOSAL touches (ignore conflicts
188
+ // + violations on inherited/other fields the operator isn't editing).
189
+ const relevant = status.warnings.filter(
190
+ (w) => w.reason !== "schema_conflict" && checkedSet.has(w.field),
191
+ );
192
+ if (relevant.length === 0) continue;
193
+ violating++;
194
+ if (sample.length < sampleLimit) {
195
+ sample.push({
196
+ id: note.id,
197
+ path: note.path ?? null,
198
+ fields: relevant.map((w) => ({
199
+ field: w.field,
200
+ reason: w.reason,
201
+ message: w.message,
202
+ })),
203
+ });
204
+ }
205
+ }
206
+
207
+ return {
208
+ tag,
209
+ total_notes: notes.length,
210
+ violating_notes: violating,
211
+ checked_fields: checkedFields,
212
+ sample,
213
+ };
214
+ }