@openparachute/vault 0.6.4-rc.1 → 0.6.4-rc.11

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 (52) hide show
  1. package/README.md +46 -11
  2. package/core/src/attribution.test.ts +273 -0
  3. package/core/src/conformance.test.ts +112 -0
  4. package/core/src/conformance.ts +214 -0
  5. package/core/src/core.test.ts +126 -0
  6. package/core/src/cursor.ts +8 -0
  7. package/core/src/enforced-writes.test.ts +533 -0
  8. package/core/src/mcp.ts +235 -9
  9. package/core/src/migrate-tag-field.test.ts +471 -0
  10. package/core/src/migrate-tag-field.ts +638 -0
  11. package/core/src/notes.ts +280 -7
  12. package/core/src/query-operators.ts +117 -0
  13. package/core/src/schema-defaults.ts +162 -9
  14. package/core/src/schema.ts +61 -2
  15. package/core/src/store.ts +70 -19
  16. package/core/src/tag-schemas.ts +12 -0
  17. package/core/src/triggers-store.ts +6 -0
  18. package/core/src/types.ts +50 -14
  19. package/core/src/vault-projection.ts +19 -0
  20. package/package.json +1 -1
  21. package/src/attribution-threading.test.ts +350 -0
  22. package/src/auth.ts +82 -4
  23. package/src/cli.ts +345 -9
  24. package/src/config.ts +11 -0
  25. package/src/first-boot-create.test.ts +155 -0
  26. package/src/import-daemon-busy.test.ts +8 -17
  27. package/src/mcp-http.ts +27 -0
  28. package/src/mcp-tools.ts +31 -4
  29. package/src/mirror-history.test.ts +426 -0
  30. package/src/mirror-manager.ts +164 -0
  31. package/src/mirror-routes.ts +182 -1
  32. package/src/module-config.ts +46 -80
  33. package/src/routes.ts +295 -48
  34. package/src/routing.test.ts +240 -25
  35. package/src/routing.ts +74 -4
  36. package/src/scale.bench.test.ts +82 -0
  37. package/src/scopes.test.ts +24 -0
  38. package/src/scopes.ts +63 -0
  39. package/src/self-register.test.ts +5 -5
  40. package/src/self-register.ts +8 -3
  41. package/src/server.ts +58 -38
  42. package/src/subscribe.test.ts +23 -2
  43. package/src/test-support/spawn.ts +85 -0
  44. package/src/triggers-api.ts +24 -0
  45. package/src/triggers.test.ts +33 -0
  46. package/src/triggers.ts +17 -0
  47. package/src/vault-remove.test.ts +4 -5
  48. package/src/vault.test.ts +188 -17
  49. package/web/ui/dist/assets/{index-UlvD8KHr.css → index-C5XqQM-c.css} +1 -1
  50. package/web/ui/dist/assets/index-TJ-XN4OZ.js +61 -0
  51. package/web/ui/dist/index.html +2 -2
  52. package/web/ui/dist/assets/index-DwYo23aY.js +0 -61
package/README.md CHANGED
@@ -273,6 +273,31 @@ description: |
273
273
 
274
274
  Sent as the MCP server instruction at session start.
275
275
 
276
+ ### Schema enforcement & state machines (vault#299)
277
+
278
+ Tag-field schemas (`update-tag`'s `fields`) are **advisory by default** — a violating write succeeds and the response carries `validation_status` warnings the agent can self-correct on. That's right for organic single-vault use. Once a vault has multiple writers (humans + agents), opt individual fields into **strict** enforcement:
279
+
280
+ ```yaml
281
+ tag: concept-seed
282
+ fields:
283
+ state: { type: string, enum: [idea, drafted, scripted, produced, published, killed], strict: true }
284
+ title: { type: string, required: true, strict: true }
285
+ owners: { type: array, cardinality: many, strict: true }
286
+ priority: { type: number } # advisory (default)
287
+ notes: { type: string } # advisory — free-form stays free-form
288
+ ```
289
+
290
+ `strict: true` flips **all** of that field's declared constraints together — `type` + `enum` + `required` + `cardinality` — from warnings to hard write rejections (all-or-nothing per field). A violating create/update is rejected with a single `schema_validation` error carrying **every** per-field violation (MCP `data.error_type: "schema_validation"` / HTTP 422), and nothing is written. Strictness is **per-field**, so a free-form `notes` field stays advisory on an otherwise-strict tag. Declared strict fields surface in `vault-info` and the connect-time brief so an agent knows the contract before writing.
291
+
292
+ **Migration bypass.** A token holding the `vault:migrate` scope (broad) or `vault:<name>:migrate` (narrowed) skips strict enforcement — for backfilling/migrating existing non-conforming notes. It's an orthogonal capability (an `admin` token does **not** bypass unless it also holds `migrate`), and every bypassed write is logged to the daemon's structured log (`[schema-bypass] {...}` with the actor/via and waived violations) for later audit.
293
+
294
+ **Compare-and-set state transitions.** Advance a state machine race-safely in one round trip instead of read → check → conditional update. `update-note`'s `state_transition: { field, from, to }` atomically sets `field` to `to` **only if** it currently equals `from`; otherwise it's rejected with a distinct `transition_conflict` error. A **missing field** counts as a conflict; pass `from: null` to match a field that is absent or explicitly null. A **transition-only** update needs no `if_updated_at`/`force` — the compare-and-set IS the precondition. Combinable with other field updates in the same call (they land in the same atomic UPDATE), but a combined call still needs `if_updated_at`/`force` for the *other* fields — the CAS only guards the transitioned field, not the rest of the merge.
295
+
296
+ ```jsonc
297
+ // advance a seed from idea → drafted, race-safely
298
+ update-note { "id": "Seeds/my-idea", "state_transition": { "field": "state", "from": "idea", "to": "drafted" } }
299
+ ```
300
+
276
301
  ## Features
277
302
 
278
303
  ### Wikilink auto-linking
@@ -321,7 +346,19 @@ triggers:
321
346
  send: content
322
347
  ```
323
348
 
324
- **Predicate fields**: `tags` (all must match), `has_content` (true/false), `missing_metadata` (keys that must be absent), `has_metadata` (keys that must be present).
349
+ **Predicate fields**: `tags` (all must match), `has_content` (true/false), `missing_metadata` (keys that must be absent), `has_metadata` (keys that must be present), and `metadata` (value-matched — a field → operator-object map using the same operators as `query-notes`: `eq/ne/gt/gte/lt/lte/in/not_in/exists`). All predicate fields are ANDed. Value-matching lets a trigger fire on a specific transition rather than every edit (vault#299):
350
+
351
+ ```yaml
352
+ - name: announce-published
353
+ events: [updated]
354
+ when:
355
+ tags: [piece]
356
+ metadata:
357
+ state: { eq: published } # fire only when state reaches "published"
358
+ missing_metadata: [announced_at]
359
+ action:
360
+ webhook: https://example.com/announce
361
+ ```
325
362
 
326
363
  **Two-phase markers**: On match, the trigger sets `<name>_pending_at` metadata before calling the webhook, then replaces it with `<name>_rendered_at` on success. This prevents re-entry and concurrent runs.
327
364
 
@@ -549,16 +586,12 @@ Range params require content in the response — with `include_content=false` (o
549
586
 
550
587
  ### Incremental rebuilds: "what changed since X"
551
588
 
552
- The SSG / sync pattern. Two equivalent forms — bracket-style is canonical going forward; the flat form is the same shape that ships through the REST/MCP date filter today.
589
+ The SSG / sync pattern. Bracket-style is the query-string date filter. (The flat `date_field` / `date_from` / `date_to` params were removed in 0.6.4 vault#288 — and are now ignored.)
553
590
 
554
591
  ```bash
555
- # Bracket-style (canonical)
592
+ # Bracket-style (the query-string date filter)
556
593
  curl -H "Authorization: Bearer $VAULT_TOKEN" \
557
594
  "http://localhost:1940/vault/default/api/notes?meta[updated_at][gte]=2026-04-01T00:00:00Z"
558
-
559
- # Flat form (DEPRECATED in 0.4.3; planned removal in a later 0.x per vault#288)
560
- curl -H "Authorization: Bearer $VAULT_TOKEN" \
561
- "http://localhost:1940/vault/default/api/notes?date_field=updated_at&date_from=2026-04-01T00:00:00Z"
562
595
  ```
563
596
 
564
597
  ```jsonc
@@ -910,7 +943,7 @@ cp .env.example .env # edit with your config
910
943
  docker compose up -d
911
944
  ```
912
945
 
913
- Optionally set `PARACHUTE_VAULT_NAME` to choose a name for your first vault (defaults to `default`). Lowercase alphanumeric + hyphens or underscores, 2–32 chars.
946
+ Set `PARACHUTE_VAULT_NAME` to auto-create a first vault on startup (name: lowercase alphanumeric + hyphens or underscores, 2–32 chars). Without it the server boots with zero vaults — create one explicitly via the admin wizard, `parachute init --vault-name <name>`, or `parachute-vault create <name>`.
914
947
 
915
948
  ### Cloud platforms
916
949
 
@@ -935,9 +968,11 @@ typical v0.6 self-host wants. If you're not sure, use the hub-managed
935
968
  path above. The standalone Blueprint stays in tree because some
936
969
  operators specifically want this shape (vault#341).
937
970
 
938
- Optionally set `PARACHUTE_VAULT_NAME` to choose a name for your first
939
- vault (defaults to `default`). Lowercase alphanumeric + hyphens or
940
- underscores, 2–32 chars.
971
+ Set `PARACHUTE_VAULT_NAME` to auto-create a first vault on startup (name:
972
+ lowercase alphanumeric + hyphens or underscores, 2–32 chars). Without it
973
+ the server boots with zero vaults — create one explicitly via the admin
974
+ wizard, `parachute init --vault-name <name>`, or `parachute-vault create
975
+ <name>`.
941
976
 
942
977
  #### Other platforms
943
978
 
@@ -0,0 +1,273 @@
1
+ /**
2
+ * Write-attribution (vault#298) — per-identity (`*_by`) + per-interface
3
+ * (`*_via`) provenance at the store layer.
4
+ *
5
+ * Covers the core contract:
6
+ * - create stamps BOTH axes onto created_* AND mirrors into last_updated_*
7
+ * - update bumps ONLY last_updated_* (created_* is set-once)
8
+ * - a `skipUpdatedAt` machine write does NOT claim authorship
9
+ * - no-attribution writes leave the columns NULL (never "")
10
+ * - the four query-notes filters (created_by / last_updated_by /
11
+ * created_via / last_updated_via)
12
+ * - legacy rows written before the v23 migration stay NULL and don't crash
13
+ * - the cursor binds the attribution filters (changing them invalidates it)
14
+ *
15
+ * The auth → AuthResult → MCP/REST threading is exercised separately in
16
+ * src/attribution-threading.test.ts (it needs the server-side auth context).
17
+ */
18
+ import { describe, it, expect, beforeEach } from "bun:test";
19
+ import { Database } from "bun:sqlite";
20
+ import { SqliteStore } from "./store.js";
21
+ import { initSchema, SCHEMA_VERSION } from "./schema.js";
22
+
23
+ let store: SqliteStore;
24
+ let db: Database;
25
+
26
+ beforeEach(() => {
27
+ db = new Database(":memory:");
28
+ store = new SqliteStore(db);
29
+ });
30
+
31
+ function rawRow(id: string) {
32
+ return db
33
+ .prepare(
34
+ "SELECT created_by, created_via, last_updated_by, last_updated_via FROM notes WHERE id = ?",
35
+ )
36
+ .get(id) as {
37
+ created_by: string | null;
38
+ created_via: string | null;
39
+ last_updated_by: string | null;
40
+ last_updated_via: string | null;
41
+ };
42
+ }
43
+
44
+ describe("write-attribution — schema", () => {
45
+ it("bumped SCHEMA_VERSION to 23", () => {
46
+ expect(SCHEMA_VERSION).toBe(23);
47
+ });
48
+
49
+ it("the four columns exist and are indexed", () => {
50
+ const cols = (db.prepare("PRAGMA table_info(notes)").all() as { name: string }[]).map(
51
+ (r) => r.name,
52
+ );
53
+ expect(cols).toContain("created_by");
54
+ expect(cols).toContain("created_via");
55
+ expect(cols).toContain("last_updated_by");
56
+ expect(cols).toContain("last_updated_via");
57
+
58
+ const idx = (
59
+ db
60
+ .prepare("SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='notes'")
61
+ .all() as { name: string }[]
62
+ ).map((r) => r.name);
63
+ expect(idx).toContain("idx_notes_created_by");
64
+ expect(idx).toContain("idx_notes_created_via");
65
+ expect(idx).toContain("idx_notes_last_updated_by");
66
+ expect(idx).toContain("idx_notes_last_updated_via");
67
+ });
68
+ });
69
+
70
+ describe("write-attribution — per-identity (WHO) + per-interface (VIA)", () => {
71
+ it("create captures actor + via on BOTH the created_* and last_updated_* pairs", async () => {
72
+ const note = await store.createNote("hi", { actor: "aaron", via: "mcp" });
73
+ // Read-model surfaces both axes.
74
+ expect(note.createdBy).toBe("aaron");
75
+ expect(note.createdVia).toBe("mcp");
76
+ // First write IS the most-recent write — mirrored.
77
+ expect(note.lastUpdatedBy).toBe("aaron");
78
+ expect(note.lastUpdatedVia).toBe("mcp");
79
+
80
+ const row = rawRow(note.id);
81
+ expect(row.created_by).toBe("aaron");
82
+ expect(row.created_via).toBe("mcp");
83
+ expect(row.last_updated_by).toBe("aaron");
84
+ expect(row.last_updated_via).toBe("mcp");
85
+ });
86
+
87
+ it("update bumps last_updated_* but leaves created_* untouched (set-once)", async () => {
88
+ const note = await store.createNote("v1", { actor: "aaron", via: "mcp" });
89
+ const updated = await store.updateNote(note.id, {
90
+ content: "v2",
91
+ actor: "mathilda",
92
+ via: "surface:meeting-ingest",
93
+ });
94
+
95
+ // created_* pins the ORIGINAL author/channel forever.
96
+ expect(updated.createdBy).toBe("aaron");
97
+ expect(updated.createdVia).toBe("mcp");
98
+ // last_updated_* reflects the most recent writer.
99
+ expect(updated.lastUpdatedBy).toBe("mathilda");
100
+ expect(updated.lastUpdatedVia).toBe("surface:meeting-ingest");
101
+
102
+ const row = rawRow(note.id);
103
+ expect(row.created_by).toBe("aaron");
104
+ expect(row.last_updated_by).toBe("mathilda");
105
+ expect(row.last_updated_via).toBe("surface:meeting-ingest");
106
+ });
107
+
108
+ it("append/prepend updates also record the most-recent author", async () => {
109
+ const note = await store.createNote("base", { actor: "aaron", via: "mcp" });
110
+ const after = await store.updateNote(note.id, {
111
+ append: " +more",
112
+ actor: "agent:nightly",
113
+ via: "agent:nightly",
114
+ });
115
+ expect(after.content).toBe("base +more");
116
+ expect(after.createdBy).toBe("aaron");
117
+ expect(after.lastUpdatedBy).toBe("agent:nightly");
118
+ expect(after.lastUpdatedVia).toBe("agent:nightly");
119
+ });
120
+
121
+ it("a skipUpdatedAt machine write does NOT claim authorship", async () => {
122
+ const note = await store.createNote("x", { actor: "aaron", via: "mcp" });
123
+ const before = rawRow(note.id);
124
+ // A hook-style marker write: passes actor/via but skipUpdatedAt — should
125
+ // not bump updated_at NOR rewrite last_updated_*.
126
+ await store.updateNote(note.id, {
127
+ metadata: { marker: true },
128
+ skipUpdatedAt: true,
129
+ actor: "some-hook",
130
+ via: "operator",
131
+ });
132
+ const after = rawRow(note.id);
133
+ expect(after.last_updated_by).toBe(before.last_updated_by); // still "aaron"
134
+ expect(after.last_updated_by).toBe("aaron");
135
+ expect(after.last_updated_via).toBe("mcp");
136
+ });
137
+
138
+ it("an attribution-less update honestly clears the most-recent author (NULL, not stale)", async () => {
139
+ const note = await store.createNote("x", { actor: "aaron", via: "mcp" });
140
+ // A real edit arriving with no attribution context — the latest writer is
141
+ // unknown; we must NOT leave "aaron" as the apparent last editor.
142
+ const after = await store.updateNote(note.id, { content: "y" });
143
+ expect(after.createdBy).toBe("aaron"); // original author preserved
144
+ expect(after.lastUpdatedBy).toBeNull();
145
+ expect(after.lastUpdatedVia).toBeNull();
146
+ });
147
+ });
148
+
149
+ describe("write-attribution — no context → NULL (never empty string)", () => {
150
+ it("create without actor/via leaves all four columns NULL", async () => {
151
+ const note = await store.createNote("anon");
152
+ const row = rawRow(note.id);
153
+ expect(row.created_by).toBeNull();
154
+ expect(row.created_via).toBeNull();
155
+ expect(row.last_updated_by).toBeNull();
156
+ expect(row.last_updated_via).toBeNull();
157
+ expect(note.createdBy).toBeNull();
158
+ expect(note.createdVia).toBeNull();
159
+ });
160
+
161
+ it("empty / whitespace-only actor/via normalize to NULL", async () => {
162
+ const note = await store.createNote("e", { actor: " ", via: "" });
163
+ const row = rawRow(note.id);
164
+ expect(row.created_by).toBeNull();
165
+ expect(row.created_via).toBeNull();
166
+ });
167
+ });
168
+
169
+ describe("write-attribution — query filters", () => {
170
+ beforeEach(async () => {
171
+ await store.createNote("a", { actor: "aaron", via: "mcp" });
172
+ await store.createNote("b", { actor: "mathilda", via: "surface:meeting-ingest" });
173
+ const c = await store.createNote("c", { actor: "aaron", via: "api" });
174
+ // c's most-recent write is by the nightly agent via mcp.
175
+ await store.updateNote(c.id, { content: "c2", actor: "agent:nightly", via: "mcp" });
176
+ await store.createNote("legacy"); // no attribution
177
+ });
178
+
179
+ it("created_by selects only that principal's CREATED notes", async () => {
180
+ const aaron = await store.queryNotes({ createdBy: "aaron" });
181
+ expect(aaron.map((n) => n.content).sort()).toEqual(["a", "c2"]);
182
+ });
183
+
184
+ it("last_updated_by selects by MOST-RECENT author (agent's edit on c)", async () => {
185
+ const byAgent = await store.queryNotes({ lastUpdatedBy: "agent:nightly" });
186
+ expect(byAgent.map((n) => n.content)).toEqual(["c2"]);
187
+ // aaron created c but is no longer its last editor.
188
+ const aaronLatest = await store.queryNotes({ lastUpdatedBy: "aaron" });
189
+ expect(aaronLatest.map((n) => n.content)).toEqual(["a"]);
190
+ });
191
+
192
+ it("created_via / last_updated_via filter on the interface axis", async () => {
193
+ const viaSurface = await store.queryNotes({ createdVia: "surface:meeting-ingest" });
194
+ expect(viaSurface.map((n) => n.content)).toEqual(["b"]);
195
+ const lastViaMcp = await store.queryNotes({ lastUpdatedVia: "mcp" });
196
+ // "a" (created via mcp, never updated) + "c2" (last updated via mcp).
197
+ expect(lastViaMcp.map((n) => n.content).sort()).toEqual(["a", "c2"]);
198
+ });
199
+
200
+ it("an attribution filter never matches legacy/unattributed (NULL) rows", async () => {
201
+ const any = await store.queryNotes({ createdBy: "aaron" });
202
+ expect(any.some((n) => n.content === "legacy")).toBe(false);
203
+ });
204
+ });
205
+
206
+ describe("write-attribution — legacy backfill (v23 migration)", () => {
207
+ it("a pre-v23 vault: existing rows stay NULL, new rows attribute, no crash", () => {
208
+ // Build a v22-shaped notes table by hand (no attribution columns) +
209
+ // schema_version row, then run initSchema to drive the v23 migration.
210
+ const legacy = new Database(":memory:");
211
+ legacy.exec(`
212
+ CREATE TABLE notes (
213
+ id TEXT PRIMARY KEY,
214
+ content TEXT DEFAULT '',
215
+ path TEXT,
216
+ metadata TEXT DEFAULT '{}',
217
+ created_at TEXT NOT NULL,
218
+ updated_at TEXT,
219
+ extension TEXT NOT NULL DEFAULT 'md'
220
+ );
221
+ CREATE TABLE schema_version (version INTEGER PRIMARY KEY, applied_at TEXT);
222
+ INSERT INTO schema_version (version, applied_at) VALUES (22, '2026-01-01T00:00:00.000Z');
223
+ INSERT INTO notes (id, content, created_at, updated_at)
224
+ VALUES ('old-1', 'pre-existing', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z');
225
+ `);
226
+
227
+ // Should migrate without throwing.
228
+ initSchema(legacy);
229
+
230
+ const ver = (legacy.prepare("SELECT MAX(version) AS v FROM schema_version").get() as {
231
+ v: number;
232
+ }).v;
233
+ expect(ver).toBe(23);
234
+
235
+ // Legacy row: attribution columns exist now but are NULL (not fabricated).
236
+ const old = legacy
237
+ .prepare("SELECT created_by, last_updated_by, created_via FROM notes WHERE id = ?")
238
+ .get("old-1") as { created_by: string | null; last_updated_by: string | null; created_via: string | null };
239
+ expect(old.created_by).toBeNull();
240
+ expect(old.last_updated_by).toBeNull();
241
+ expect(old.created_via).toBeNull();
242
+
243
+ // A NEW write on the migrated DB attributes correctly.
244
+ const migratedStore = new SqliteStore(legacy);
245
+ return migratedStore.createNote("fresh", { actor: "aaron", via: "mcp" }).then((n) => {
246
+ expect(n.createdBy).toBe("aaron");
247
+ expect(n.createdVia).toBe("mcp");
248
+ // The legacy row is still NULL and still queryable.
249
+ return migratedStore.queryNotes({ createdBy: "aaron" }).then((res) => {
250
+ expect(res.map((x) => x.content)).toEqual(["fresh"]);
251
+ });
252
+ });
253
+ });
254
+
255
+ it("re-running the v23 migration is idempotent (no duplicate-column error)", () => {
256
+ const again = new Database(":memory:");
257
+ const s = new SqliteStore(again); // runs migrations once
258
+ initSchema(again); // run again — must not throw
259
+ expect(() => s.createNote("ok", { actor: "x", via: "api" })).not.toThrow();
260
+ });
261
+ });
262
+
263
+ describe("write-attribution — cursor binding", () => {
264
+ it("changing an attribution filter between cursor polls invalidates the cursor", async () => {
265
+ await store.createNote("a", { actor: "aaron", via: "mcp" });
266
+ const page = await store.queryNotesPaged({ createdBy: "aaron" });
267
+ // Reusing the cursor under a DIFFERENT createdBy must be rejected, not
268
+ // silently continue aaron's watermark.
269
+ await expect(
270
+ store.queryNotesPaged({ createdBy: "mathilda", cursor: page.next_cursor }),
271
+ ).rejects.toThrow(/different query/i);
272
+ });
273
+ });
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Conformance check (vault#283) — counting existing notes that would violate
3
+ * a proposed tightening of a tag's field spec. Backs the Schema editor's
4
+ * "N existing notes violate this" warning.
5
+ */
6
+ import { describe, it, expect, beforeEach } from "bun:test";
7
+ import { Database } from "bun:sqlite";
8
+ import { SqliteStore } from "./store.js";
9
+ import { countConformanceViolations } from "./conformance.js";
10
+
11
+ let db: Database;
12
+ let store: SqliteStore;
13
+
14
+ beforeEach(() => {
15
+ db = new Database(":memory:");
16
+ store = new SqliteStore(db);
17
+ });
18
+
19
+ describe("countConformanceViolations", () => {
20
+ it("returns zero violations when proposed fields is empty", async () => {
21
+ await store.createNote("n", { tags: ["task"], metadata: { status: "open" } });
22
+ const r = countConformanceViolations(db, "task", {});
23
+ expect(r.total_notes).toBe(1);
24
+ expect(r.violating_notes).toBe(0);
25
+ expect(r.checked_fields).toEqual([]);
26
+ });
27
+
28
+ it("counts notes missing a newly-required field", async () => {
29
+ await store.createNote("has", { tags: ["task"], metadata: { due: "2026-01-01" } });
30
+ await store.createNote("missing-1", { tags: ["task"], metadata: {} });
31
+ await store.createNote("missing-2", { tags: ["task"] });
32
+
33
+ const r = countConformanceViolations(db, "task", {
34
+ due: { type: "string", required: true },
35
+ });
36
+ expect(r.total_notes).toBe(3);
37
+ expect(r.violating_notes).toBe(2);
38
+ expect(r.checked_fields).toEqual(["due"]);
39
+ // missing_required reasons surface in the sample.
40
+ expect(r.sample.every((s) => s.fields.some((f) => f.reason === "missing_required"))).toBe(true);
41
+ });
42
+
43
+ it("counts notes whose value falls outside a narrowed enum", async () => {
44
+ await store.createNote("ok", { tags: ["task"], metadata: { status: "open" } });
45
+ await store.createNote("bad", { tags: ["task"], metadata: { status: "archived" } });
46
+
47
+ const r = countConformanceViolations(db, "task", {
48
+ status: { type: "string", enum: ["open", "done"] },
49
+ });
50
+ expect(r.violating_notes).toBe(1);
51
+ expect(r.sample[0]?.fields[0]?.reason).toBe("enum_mismatch");
52
+ });
53
+
54
+ it("counts notes whose value contradicts a changed type", async () => {
55
+ await store.createNote("num", { tags: ["task"], metadata: { count: 3 } });
56
+ await store.createNote("str", { tags: ["task"], metadata: { count: "three" } });
57
+
58
+ const r = countConformanceViolations(db, "task", {
59
+ count: { type: "integer" },
60
+ });
61
+ expect(r.violating_notes).toBe(1);
62
+ expect(r.sample[0]?.fields[0]?.reason).toBe("type_mismatch");
63
+ });
64
+
65
+ it("includes descendant-tag notes via inheritance", async () => {
66
+ // dev/log declares dev as a parent → a strict field on dev applies to
67
+ // dev/log notes too.
68
+ await store.upsertTagRecord("dev/log", { parent_names: ["dev"] });
69
+ await store.createNote("parent-note", { tags: ["dev"], metadata: {} });
70
+ await store.createNote("child-note", { tags: ["dev/log"], metadata: {} });
71
+
72
+ const r = countConformanceViolations(db, "dev", {
73
+ kind: { type: "string", required: true },
74
+ });
75
+ expect(r.total_notes).toBe(2);
76
+ expect(r.violating_notes).toBe(2);
77
+ });
78
+
79
+ it("ignores fields the proposal does not touch", async () => {
80
+ await store.createNote("n", { tags: ["task"], metadata: { other: 123 } });
81
+ // We only propose `status`; `other` being weird is irrelevant.
82
+ const r = countConformanceViolations(db, "task", {
83
+ status: { type: "string" },
84
+ });
85
+ // `status` absent + not required → no violation.
86
+ expect(r.violating_notes).toBe(0);
87
+ });
88
+
89
+ it("caps the sample at sampleLimit but counts all violations", async () => {
90
+ for (let i = 0; i < 5; i++) {
91
+ await store.createNote(`n${i}`, { tags: ["task"], metadata: {} });
92
+ }
93
+ const r = countConformanceViolations(
94
+ db,
95
+ "task",
96
+ { req: { type: "string", required: true } },
97
+ { sampleLimit: 2 },
98
+ );
99
+ expect(r.violating_notes).toBe(5);
100
+ expect(r.sample.length).toBe(2);
101
+ });
102
+ });
103
+
104
+ describe("store.countTagConformance", () => {
105
+ it("proxies to the core helper", async () => {
106
+ await store.createNote("n", { tags: ["task"], metadata: {} });
107
+ const r = await store.countTagConformance("task", {
108
+ due: { type: "string", required: true },
109
+ });
110
+ expect(r.violating_notes).toBe(1);
111
+ });
112
+ });