@mulmoclaude/core 0.24.0 → 0.25.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.
Files changed (103) hide show
  1. package/assets/helps/collection-skills.md +51 -0
  2. package/assets/helps/custom-view.md +37 -3
  3. package/assets/helps/error-recovery.md +30 -0
  4. package/assets/helps/google-calendar-collection.md +79 -0
  5. package/assets/helps/index.md +1 -0
  6. package/dist/collection/core/project.d.ts +3 -0
  7. package/dist/collection/core/schema.d.ts +13 -1
  8. package/dist/collection/core/schemaZ.d.ts +45 -0
  9. package/dist/collection/index.cjs +18 -14
  10. package/dist/collection/index.cjs.map +1 -1
  11. package/dist/collection/index.d.ts +1 -0
  12. package/dist/collection/index.js +4 -2
  13. package/dist/collection/index.js.map +1 -1
  14. package/dist/collection/paths.cjs +5 -55
  15. package/dist/collection/paths.js +1 -51
  16. package/dist/collection/registry/server/index.cjs +20 -19
  17. package/dist/collection/registry/server/index.cjs.map +1 -1
  18. package/dist/collection/registry/server/index.js +3 -2
  19. package/dist/collection/registry/server/index.js.map +1 -1
  20. package/dist/collection/server/csvStore.d.ts +8 -1
  21. package/dist/collection/server/discoveredCollection.d.ts +4 -0
  22. package/dist/collection/server/discovery.d.ts +1 -0
  23. package/dist/collection/server/index.cjs +58 -54
  24. package/dist/collection/server/index.d.ts +1 -0
  25. package/dist/collection/server/index.js +5 -4
  26. package/dist/collection/server/queryRunner.d.ts +4 -0
  27. package/dist/collection/server/spawn.d.ts +2 -1
  28. package/dist/collection/server/sqliteStore.d.ts +14 -0
  29. package/dist/collection/server/store.d.ts +43 -8
  30. package/dist/collection/server/storePage.d.ts +32 -0
  31. package/dist/collection-watchers/index.cjs +131 -44
  32. package/dist/collection-watchers/index.cjs.map +1 -1
  33. package/dist/collection-watchers/index.d.ts +1 -1
  34. package/dist/collection-watchers/index.js +125 -39
  35. package/dist/collection-watchers/index.js.map +1 -1
  36. package/dist/collection-watchers/reconciler.d.ts +13 -11
  37. package/dist/collection-watchers/watcher.d.ts +4 -3
  38. package/dist/{server-BpEo0FOd.js → discovery-QUi_7aNG.js} +414 -1495
  39. package/dist/discovery-QUi_7aNG.js.map +1 -0
  40. package/dist/{server-CkysfLh4.cjs → discovery-cwtfyDxl.cjs} +463 -1658
  41. package/dist/discovery-cwtfyDxl.cjs.map +1 -0
  42. package/dist/feeds/index.cjs +4 -4
  43. package/dist/feeds/index.js +2 -2
  44. package/dist/feeds/server/index.cjs +35 -22
  45. package/dist/feeds/server/index.cjs.map +1 -1
  46. package/dist/feeds/server/index.js +26 -13
  47. package/dist/feeds/server/index.js.map +1 -1
  48. package/dist/google/apiClient.d.ts +8 -1
  49. package/dist/google/calendar.d.ts +35 -0
  50. package/dist/google/calendarSyncStore.d.ts +7 -0
  51. package/dist/google/collectionSync.d.ts +70 -0
  52. package/dist/google/index.cjs +294 -4
  53. package/dist/google/index.cjs.map +1 -1
  54. package/dist/google/index.d.ts +4 -2
  55. package/dist/google/index.js +279 -5
  56. package/dist/google/index.js.map +1 -1
  57. package/dist/ids-Dl9Ij63K.cjs +163 -0
  58. package/dist/ids-Dl9Ij63K.cjs.map +1 -0
  59. package/dist/ids-P2T89Gou.js +92 -0
  60. package/dist/ids-P2T89Gou.js.map +1 -0
  61. package/dist/{ingestTypes-CFEgTItj.js → ingestTypes-C-IQB4nw.js} +2 -2
  62. package/dist/{ingestTypes-CFEgTItj.js.map → ingestTypes-C-IQB4nw.js.map} +1 -1
  63. package/dist/{ingestTypes-Stc7iQyA.cjs → ingestTypes-DZpAC3N_.cjs} +3 -3
  64. package/dist/{ingestTypes-Stc7iQyA.cjs.map → ingestTypes-DZpAC3N_.cjs.map} +1 -1
  65. package/dist/project-BWI5w_BT.cjs +17 -0
  66. package/dist/project-BWI5w_BT.cjs.map +1 -0
  67. package/dist/project-bU98ycsy.js +12 -0
  68. package/dist/project-bU98ycsy.js.map +1 -0
  69. package/dist/{promptSafety-BLUcImzd.js → promptSafety-Boz5qOs-.js} +2 -84
  70. package/dist/promptSafety-Boz5qOs-.js.map +1 -0
  71. package/dist/{promptSafety-DI_1Rvhk.cjs → promptSafety-Co4cYQ_Z.cjs} +1 -149
  72. package/dist/promptSafety-Co4cYQ_Z.cjs.map +1 -0
  73. package/dist/remote-host/server/index.cjs +6 -4
  74. package/dist/remote-host/server/index.cjs.map +1 -1
  75. package/dist/remote-host/server/index.js +6 -4
  76. package/dist/remote-host/server/index.js.map +1 -1
  77. package/dist/remote-view/index.cjs +5 -3
  78. package/dist/remote-view/index.cjs.map +1 -1
  79. package/dist/remote-view/index.d.ts +3 -1
  80. package/dist/remote-view/index.js +5 -3
  81. package/dist/remote-view/index.js.map +1 -1
  82. package/dist/scheduler/index.cjs +3 -1
  83. package/dist/scheduler/index.cjs.map +1 -1
  84. package/dist/scheduler/index.js +3 -1
  85. package/dist/scheduler/index.js.map +1 -1
  86. package/dist/server-BI3wnTwl.js +1529 -0
  87. package/dist/server-BI3wnTwl.js.map +1 -0
  88. package/dist/server-CKdWENZ-.cjs +1704 -0
  89. package/dist/server-CKdWENZ-.cjs.map +1 -0
  90. package/dist/skill-bridge/index.cjs +2 -2
  91. package/dist/skill-bridge/index.cjs.map +1 -1
  92. package/dist/skill-bridge/index.js +1 -1
  93. package/dist/templatePath-27vUZowm.cjs +75 -0
  94. package/dist/templatePath-27vUZowm.cjs.map +1 -0
  95. package/dist/templatePath-k_WNbL_Q.js +52 -0
  96. package/dist/templatePath-k_WNbL_Q.js.map +1 -0
  97. package/package.json +1 -1
  98. package/dist/collection/paths.cjs.map +0 -1
  99. package/dist/collection/paths.js.map +0 -1
  100. package/dist/promptSafety-BLUcImzd.js.map +0 -1
  101. package/dist/promptSafety-DI_1Rvhk.cjs.map +0 -1
  102. package/dist/server-BpEo0FOd.js.map +0 -1
  103. package/dist/server-CkysfLh4.cjs.map +0 -1
@@ -0,0 +1,1529 @@
1
+ import { f as storageKindFor, l as embedTargetId, o as COMPUTED_TYPES, u as isFieldDrivenEvery } from "./ids-P2T89Gou.js";
2
+ import { D as rollupValue, E as projectBacklinkRow, O as actionVisible, S as itemIsDone, T as coerceNumeric, b as resolveIcon, d as parseIsoDateTime, g as deriveAll, t as defangForPrompt, u as parseIsoDate, w as backlinkRows, x as selectDynamicRecord, y as firstDateField } from "./promptSafety-Boz5qOs-.js";
3
+ import { $ as isPresetSlug$1, B as writeFileAtomic, C as compileJsonlQuery, G as resolveDataDir, H as isContainedInRoot, J as safeSlugName, K as resolveTemplatePath, Q as getWorkspaceRoot, R as resolveCreateItemId, V as SCHEMA_FILE$1, Y as archiveDir, b as normalizeCsvValue, d as checkpointSqliteDatabase, et as log, h as cacheDir, j as isRegularFile, l as readOnlyRefusal, n as discoverCollections, o as CollectionSchemaZ, r as loadCollection, rt as skillsStagingDir, s as resolveMutateSet, u as storeFor, w as CollectionQueryZ, x as queryCsv } from "./discovery-QUi_7aNG.js";
4
+ import { dataSkillDir, mirrorSkillWrite } from "./skill-bridge/index.js";
5
+ import path from "node:path";
6
+ import { cp, lstat, mkdir, open, readFile, readdir, rm, rmdir, stat, unlink, writeFile } from "node:fs/promises";
7
+ import { randomBytes, randomUUID } from "node:crypto";
8
+ import { z } from "zod";
9
+ //#region src/collection/server/jsonlQuery.ts
10
+ /** SQL semantics for an aggregate-only query over ZERO rows: one scalar
11
+ * row (`count` = 0, everything else NULL) — the same shape the CSV path
12
+ * produces for a header-only file, so callers reading `rows[0]` never
13
+ * break on storage kind or emptiness. A grouped query over zero rows is
14
+ * zero groups (`[]`), also matching SQL. Synthesized here because DuckDB
15
+ * has no empty file to infer a schema from. */
16
+ function emptyCollectionResult(query) {
17
+ if ((query.groupBy?.length ?? 0) > 0) return [];
18
+ const aggregates = Object.entries(query.aggregates ?? {});
19
+ return [Object.fromEntries(aggregates.map(([alias, aggregate]) => [alias, aggregate.op === "count" ? 0 : null]))];
20
+ }
21
+ /** The SOURCE columns a query reads: groupBy columns, aggregate input
22
+ * columns, and where fields. (orderBy resolves to groupBy columns or
23
+ * aggregate ALIASES — never to a new source column — so it adds none.) */
24
+ function referencedSourceColumns(query) {
25
+ const columns = new Set(query.groupBy ?? []);
26
+ for (const aggregate of Object.values(query.aggregates ?? {})) if (aggregate.column !== void 0) columns.add(aggregate.column);
27
+ for (const cond of query.where ?? []) columns.add(cond.field);
28
+ return [...columns];
29
+ }
30
+ /** Referenced columns that appear in NO row — a freshly-added optional
31
+ * field, or a derived field whose inputs no record has yet. DuckDB only
32
+ * infers columns from keys that occur in the JSONL, so without help a
33
+ * valid query on such a field binder-errors here while the CSV path
34
+ * (whose header always declares the column) returns NULLs. Padding the
35
+ * FIRST line with `col: null` makes the column exist (full-scan
36
+ * inference unions keys across lines) with matching NULL semantics. */
37
+ function absentReferencedColumns(rows, query) {
38
+ const present = /* @__PURE__ */ new Set();
39
+ for (const row of rows) for (const key of Object.keys(row)) present.add(key);
40
+ return referencedSourceColumns(query).filter((column) => !present.has(column));
41
+ }
42
+ /** Run a validated query over enriched collection rows. */
43
+ async function runQueryOverRows(rows, query) {
44
+ if (rows.length === 0) return emptyCollectionResult(query);
45
+ await mkdir(cacheDir(), {
46
+ recursive: true,
47
+ mode: 448
48
+ });
49
+ const jsonlPath = path.join(cacheDir(), `q-${randomBytes(8).toString("hex")}.jsonl`);
50
+ try {
51
+ const nullPads = Object.fromEntries(absentReferencedColumns(rows, query).map((column) => [column, null]));
52
+ const handle = await open(jsonlPath, "wx", 384);
53
+ try {
54
+ let first = true;
55
+ for (const row of rows) {
56
+ await handle.write(`${JSON.stringify(first ? {
57
+ ...nullPads,
58
+ ...row
59
+ } : row)}\n`);
60
+ first = false;
61
+ }
62
+ } finally {
63
+ await handle.close();
64
+ }
65
+ const { sql, params } = compileJsonlQuery(query);
66
+ return (await queryCsv(sql, [jsonlPath, ...params])).map((row) => Object.fromEntries(Object.entries(row).map(([key, value]) => [key, normalizeCsvValue(value)])));
67
+ } finally {
68
+ await unlink(jsonlPath).catch((err) => {
69
+ if (err.code !== "ENOENT") log.warn("collections", "temp JSONL cleanup failed", {
70
+ path: jsonlPath,
71
+ error: String(err)
72
+ });
73
+ });
74
+ }
75
+ }
76
+ //#endregion
77
+ //#region src/collection/server/derive.ts
78
+ /** Slugs of every collection referenced by a `ref` field — top-level
79
+ * and one level into `table` sub-fields (nested tables are
80
+ * schema-rejected). Mirrors the client's `uniqueRefTargets`. */
81
+ function uniqueRefTargets(schema) {
82
+ const targets = /* @__PURE__ */ new Set();
83
+ const walk = (fields) => {
84
+ for (const field of Object.values(fields)) {
85
+ if (field.type === "ref" && typeof field.to === "string" && field.to.length > 0) targets.add(field.to);
86
+ if (field.type === "table" && field.of) walk(field.of);
87
+ }
88
+ };
89
+ walk(schema.fields);
90
+ return [...targets];
91
+ }
92
+ /** Slugs of every collection referenced by an `embed` field (top-level
93
+ * only, like the client). */
94
+ function uniqueEmbedTargets(schema) {
95
+ const targets = /* @__PURE__ */ new Set();
96
+ for (const field of Object.values(schema.fields)) if (field.type === "embed" && typeof field.to === "string" && field.to.length > 0) targets.add(field.to);
97
+ return [...targets];
98
+ }
99
+ /** Slugs of every SOURCE collection a `backlinks` or `rollup` field
100
+ * reverses over — loaded exactly like ref/embed targets (whole
101
+ * collection, once; the two field kinds share one load). */
102
+ function uniqueBacklinkSources(schema) {
103
+ const sources = /* @__PURE__ */ new Set();
104
+ for (const field of Object.values(schema.fields)) if ((field.type === "backlinks" || field.type === "rollup") && field.from.length > 0) sources.add(field.from);
105
+ return [...sources];
106
+ }
107
+ async function loadTarget(slug, opts) {
108
+ const target = await loadCollection(slug, opts);
109
+ if (!target) return null;
110
+ const items = await storeFor(target, { workspaceRoot: opts.workspaceRoot }).list();
111
+ const byId = {};
112
+ for (const item of items) {
113
+ const itemId = item[target.schema.primaryKey];
114
+ if (typeof itemId === "string" && itemId.length > 0) byId[itemId] = deriveAll(target.schema, item, {});
115
+ }
116
+ return {
117
+ schema: target.schema,
118
+ byId
119
+ };
120
+ }
121
+ /** Load every ref/embed target and backlink source collection once.
122
+ * Unknown / unloadable targets are simply absent — downstream derefs
123
+ * resolve to null (em-dash) and backlinks to an empty row set, the
124
+ * same fail-soft the UI renders. */
125
+ async function loadLinkedTargets(schema, opts) {
126
+ const slugs = [.../* @__PURE__ */ new Set([
127
+ ...uniqueRefTargets(schema),
128
+ ...uniqueEmbedTargets(schema),
129
+ ...uniqueBacklinkSources(schema)
130
+ ])];
131
+ const loaded = {};
132
+ for (const slug of slugs) {
133
+ const target = await loadTarget(slug, opts);
134
+ if (target) loaded[slug] = target;
135
+ }
136
+ return loaded;
137
+ }
138
+ function toRefRecords(linked) {
139
+ return Object.fromEntries(Object.entries(linked).map(([slug, target]) => [slug, target.byId]));
140
+ }
141
+ /** The matching source rows for one `backlinks` field, projected to the
142
+ * source primaryKey + `display` columns — so getItems on a
143
+ * heavily-referenced record stays a summary, not a dump of the source
144
+ * collection. Missing source ⇒ [] (fail-soft). The rows come from the
145
+ * DERIVED source records (`byId`), so `display`/`filter` on a derived
146
+ * source column (an invoice `total`) works. */
147
+ function projectBacklinks(field, schema, enriched, linked) {
148
+ const source = linked[field.from];
149
+ if (!source) return [];
150
+ return backlinkRows(field, String(enriched[schema.primaryKey] ?? ""), Object.values(source.byId)).map((row) => projectBacklinkRow(row, field.display, source.schema.primaryKey));
151
+ }
152
+ /** Project the computed (never-stored) field kinds onto one derived
153
+ * record: `toggle` → boolean off its enum, `embed` → the target record
154
+ * (fixed `id` or per-record `idField`), or null when missing,
155
+ * `backlinks` → the matching source rows (see `projectBacklinks`). */
156
+ function projectComputed(schema, enriched, linked) {
157
+ for (const [key, field] of Object.entries(schema.fields)) {
158
+ if (field.type === "toggle" && field.field) enriched[key] = String(enriched[field.field] ?? "") === field.onValue;
159
+ if (field.type === "embed" && field.to) {
160
+ const targetId = embedTargetId(field, enriched);
161
+ enriched[key] = targetId && linked[field.to]?.byId[targetId] || null;
162
+ }
163
+ if (field.type === "backlinks") enriched[key] = projectBacklinks(field, schema, enriched, linked);
164
+ }
165
+ return enriched;
166
+ }
167
+ /** Resolve every rollup field onto a COPY of the record, BEFORE the
168
+ * formula pass — a `derived` formula may reference rollup values as
169
+ * plain identifiers (`played = homePlayed + awayPlayed`). Same reverse
170
+ * machinery as backlinks, collapsed to a number: an unresolvable source
171
+ * is null (a formula reading it fails soft to em-dash); an empty match
172
+ * set is a real 0. Returns `record` unchanged when the schema declares
173
+ * no rollups. */
174
+ function projectRollups(schema, record, linked) {
175
+ let out = record;
176
+ for (const [key, field] of Object.entries(schema.fields)) {
177
+ if (field.type !== "rollup") continue;
178
+ if (out === record) out = { ...record };
179
+ const source = linked[field.from];
180
+ const selfId = String(record[schema.primaryKey] ?? "");
181
+ out[key] = source ? rollupValue(field, selfId, Object.values(source.byId)) : null;
182
+ }
183
+ return out;
184
+ }
185
+ /** Enrich records with every host-computed field: derived formulas
186
+ * evaluated (cross-collection derefs included), toggles projected,
187
+ * embeds resolved. Loads each linked collection ONCE per call. Input
188
+ * records are not mutated. */
189
+ async function enrichItems(collection, items, opts = {}) {
190
+ const { schema } = collection;
191
+ const linked = await loadLinkedTargets(schema, opts);
192
+ const refRecords = toRefRecords(linked);
193
+ return items.map((item) => projectComputed(schema, deriveAll(schema, projectRollups(schema, item, linked), refRecords), linked));
194
+ }
195
+ //#endregion
196
+ //#region src/collection/server/queryRunner.ts
197
+ async function runCollectionQuery(collection, query, opts = {}) {
198
+ const store = storeFor(collection, { workspaceRoot: opts.workspaceRoot });
199
+ if (store.query) return store.query(query);
200
+ return runQueryOverRows(await enrichItems(collection, await store.list(), opts), query);
201
+ }
202
+ //#endregion
203
+ //#region src/collection/core/recordZ.ts
204
+ /** The emptiness rule shared by `required` and the "only check present
205
+ * values" gate. NOT a truthiness check — `0` and `false` are filled. */
206
+ var isEmptyValue = (value) => value === void 0 || value === null || value === "";
207
+ /** The historical write-gate checks, verbatim: required non-empty, enum
208
+ * membership (compared as strings, so a numeric `5` satisfies `"5"`). */
209
+ function enforcedProblem(key, spec, value) {
210
+ const empty = isEmptyValue(value);
211
+ if (spec.required && empty) return `missing required field '${key}'`;
212
+ if (!empty && spec.type === "enum" && !spec.values.includes(String(value))) return `'${key}' = '${String(value)}' is not one of [${spec.values.join(", ")}]`;
213
+ return null;
214
+ }
215
+ /** Report-only per-type checks on a PRESENT value. Date / datetime reuse the
216
+ * calendar's STRICT civil parsers (`parseIsoDate` / `parseIsoDateTime`), so
217
+ * the lint flags exactly the values the calendar / trigger / spawn code
218
+ * would silently drop — impossible days like `2026-02-30`, and datetimes
219
+ * outside the canonical `YYYY-MM-DDTHH:MM[:SS]` shape (e.g. a `Z` suffix,
220
+ * which the day view can't place). `string`-backed types accept anything
221
+ * stringifiable; `ref` existence is out of scope. */
222
+ function strictTypeProblem(key, spec, value) {
223
+ switch (spec.type) {
224
+ case "number":
225
+ case "money": return Number.isFinite(coerceNumeric(value)) ? null : `'${key}' = '${String(value)}' is not numeric (a '${spec.type}' field stores a plain number)`;
226
+ case "boolean": return value === true || value === false ? null : `'${key}' = '${String(value)}' is not a boolean (store true or false, unquoted)`;
227
+ case "date": return parseIsoDate(value) !== null ? null : `'${key}' = '${String(value)}' is not a real YYYY-MM-DD date`;
228
+ case "datetime": return parseIsoDateTime(value) !== null ? null : `'${key}' = '${String(value)}' is not a YYYY-MM-DDTHH:MM datetime (seconds optional, no timezone suffix — the shape the calendar parses)`;
229
+ default: return null;
230
+ }
231
+ }
232
+ /** Strict check for a PRESENT `table` value: an array of row objects, each
233
+ * row conforming to the sub-schema (required / enum / typed sub-values).
234
+ * First row problem wins, prefixed with the row number so the fix is
235
+ * locatable. */
236
+ function strictTableProblem(key, spec, value) {
237
+ if (!Array.isArray(value)) return `'${key}' = '${String(value)}' is not an array of rows (a 'table' field stores an array of row objects)`;
238
+ for (let index = 0; index < value.length; index++) {
239
+ const row = value[index];
240
+ if (!row || typeof row !== "object" || Array.isArray(row)) return `'${key}' row ${index + 1} is not an object`;
241
+ for (const [subKey, subSpec] of Object.entries(spec.of)) {
242
+ const subValue = row[subKey];
243
+ const problem = enforcedProblem(subKey, subSpec, subValue) ?? (isEmptyValue(subValue) ? null : strictTypeProblem(subKey, subSpec, subValue));
244
+ if (problem) return `'${key}' row ${index + 1}: ${problem}`;
245
+ }
246
+ }
247
+ return null;
248
+ }
249
+ /** First problem for one field's stored value under `tier`, or null.
250
+ * Enforced checks always run (and their messages never vary by tier — the
251
+ * scan and the write gate must agree on them); strict adds the per-type
252
+ * layer on present values only. */
253
+ function recordFieldProblem(key, spec, value, tier) {
254
+ const enforced = enforcedProblem(key, spec, value);
255
+ if (enforced || tier === "enforced") return enforced;
256
+ if (isEmptyValue(value)) return null;
257
+ if (spec.type === "table") return strictTableProblem(key, spec, value);
258
+ return strictTypeProblem(key, spec, value);
259
+ }
260
+ var compiled = /* @__PURE__ */ new WeakMap();
261
+ /** Compile `schema.fields` into a zod validator for a stored record.
262
+ * Loose object: unknown keys are allowed and any declared key may be
263
+ * absent (records are user files, not parse-and-rewrite targets —
264
+ * callers validate, they never persist the parse output). The checks run
265
+ * as ONE object-level refine iterating fields in declaration order —
266
+ * per-key shape schemas can't express "key may be absent BUT its absence
267
+ * must still reach the required check", and the single loop keeps the
268
+ * first reported issue identical to the historical first-problem-wins
269
+ * contract. */
270
+ function compileRecordZ(schema, tier) {
271
+ const cached = compiled.get(schema)?.[tier];
272
+ if (cached) return cached;
273
+ const stored = Object.entries(schema.fields).filter(([, spec]) => !COMPUTED_TYPES.has(spec.type));
274
+ const validator = z.looseObject({}).superRefine((record, ctx) => {
275
+ for (const [key, spec] of stored) {
276
+ const problem = recordFieldProblem(key, spec, record[key], tier);
277
+ if (problem) ctx.addIssue({
278
+ code: "custom",
279
+ message: problem,
280
+ path: [key]
281
+ });
282
+ }
283
+ });
284
+ const entry = compiled.get(schema) ?? {};
285
+ entry[tier] = validator;
286
+ compiled.set(schema, entry);
287
+ return validator;
288
+ }
289
+ /** First schema problem on an in-memory record under `tier`, or null. One
290
+ * issue per record keeps the report short and the fix obvious (the
291
+ * historical contract of `validateRecordObject`). */
292
+ function firstRecordProblem(record, schema, tier) {
293
+ const result = compileRecordZ(schema, tier).safeParse(record);
294
+ if (result.success) return null;
295
+ return result.error.issues[0]?.message ?? "record failed schema validation";
296
+ }
297
+ //#endregion
298
+ //#region src/collection/server/validate.ts
299
+ var MAX_ISSUES = 25;
300
+ /** Read every `<id>.json` under the collection's dataDir and report the
301
+ * ones that won't load or violate the schema. An empty list means every
302
+ * record is fine. */
303
+ /** List entries under the data dir, guarding realpath containment (against a
304
+ * symlinked dir swapped in after discovery, like `listItems`) and treating a
305
+ * missing dir as empty while surfacing real I/O faults. */
306
+ async function listRecordFilenames(dataDir, workspaceRoot) {
307
+ if (!isContainedInRoot(dataDir, workspaceRoot)) {
308
+ log.warn("collections", "validate refused: dataDir escapes workspace via symlink", { dataDir });
309
+ return [];
310
+ }
311
+ try {
312
+ return await readdir(dataDir);
313
+ } catch (err) {
314
+ if (err.code === "ENOENT") return [];
315
+ throw err;
316
+ }
317
+ }
318
+ async function validateCollectionRecords(collection, opts = {}) {
319
+ if (collection.schema.dataSource !== void 0) return [];
320
+ if (collection.schema.storage !== void 0) return validateStoreRecords(collection, opts);
321
+ const workspaceRoot = opts.workspaceRoot ?? getWorkspaceRoot();
322
+ const entries = await listRecordFilenames(collection.dataDir, workspaceRoot);
323
+ const issues = [];
324
+ for (const name of entries.sort()) {
325
+ if (!name.endsWith(".json") || name.startsWith(".")) continue;
326
+ if (issues.length >= MAX_ISSUES) break;
327
+ const issue = await inspectRecord(path.join(collection.dataDir, name), name, collection.schema);
328
+ if (issue) issues.push(issue);
329
+ }
330
+ return issues;
331
+ }
332
+ /** Store-backed twin of the file scan: list every record through the
333
+ * collection's store and lint it with the same "strict" report-only tier.
334
+ * A row the store can't even parse is invisible here (the store skips
335
+ * it), so the read/parse classifications of the file scan don't apply —
336
+ * schema violations are what this catches. `file` carries the record id
337
+ * (there is no per-record filename). */
338
+ async function validateStoreRecords(collection, opts) {
339
+ let items;
340
+ try {
341
+ items = await storeFor(collection, { workspaceRoot: opts.workspaceRoot }).list();
342
+ } catch (err) {
343
+ return [{
344
+ file: "(store)",
345
+ problem: `records could not be read from the storage backend: ${err instanceof Error ? err.message : String(err)}`
346
+ }];
347
+ }
348
+ const issues = [];
349
+ for (const item of items) {
350
+ if (issues.length >= MAX_ISSUES) break;
351
+ const itemId = String(item[collection.schema.primaryKey] ?? "");
352
+ const problem = validateRecordObject(item, itemId, collection.schema, "strict");
353
+ if (problem) issues.push({
354
+ file: itemId,
355
+ problem
356
+ });
357
+ }
358
+ return issues;
359
+ }
360
+ async function readRecordText(fullPath, name) {
361
+ try {
362
+ if (!(await lstat(fullPath)).isFile()) return {
363
+ file: name,
364
+ problem: "not a regular file (symlink?) — skipped, won't appear"
365
+ };
366
+ return { raw: await readFile(fullPath, "utf-8") };
367
+ } catch {
368
+ return {
369
+ file: name,
370
+ problem: "could not be read — skipped, won't appear"
371
+ };
372
+ }
373
+ }
374
+ /** Classify a single record file: unreadable / unparseable / non-object /
375
+ * schema violation, or null when it's fine. */
376
+ async function inspectRecord(fullPath, name, schema) {
377
+ const read = await readRecordText(fullPath, name);
378
+ if ("problem" in read) return read;
379
+ let parsed;
380
+ try {
381
+ parsed = JSON.parse(read.raw);
382
+ } catch (err) {
383
+ return {
384
+ file: name,
385
+ problem: `invalid JSON (${err instanceof Error ? err.message : String(err)}) — SKIPPED, won't appear. Usual cause: an unescaped " inside a string value; use 「」/『』 or write \\" instead.`
386
+ };
387
+ }
388
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {
389
+ file: name,
390
+ problem: "not a JSON object — skipped, won't appear"
391
+ };
392
+ const problem = validateRecordObject(parsed, name.replace(/\.json$/, ""), schema, "strict");
393
+ return problem ? {
394
+ file: name,
395
+ problem
396
+ } : null;
397
+ }
398
+ /** First schema problem on an in-memory record (primaryKey↔id mismatch,
399
+ * then the compiled per-field checks — see `../core/recordZ` for the two
400
+ * tiers), or null when it's fine. One issue per record keeps the report
401
+ * short and the fix obvious. Pure + exported so write paths
402
+ * (manageCollection putItems) can gate on the SAME enforced rules the
403
+ * post-hoc file scan reports — `itemId` is the id the record is (or
404
+ * would be) stored under. The default `"enforced"` tier keeps every
405
+ * write gate on the historical three checks; only pass `"strict"` from
406
+ * report-only surfaces. */
407
+ function validateRecordObject(record, itemId, schema, tier = "enforced") {
408
+ const idValue = record[schema.primaryKey];
409
+ if (typeof idValue !== "string" || idValue !== itemId) return `'${schema.primaryKey}' is '${String(idValue ?? "")}' but must equal the filename ('${itemId}'), or the record can't be opened`;
410
+ return firstRecordProblem(record, schema, tier);
411
+ }
412
+ //#endregion
413
+ //#region src/collection/server/mutate.ts
414
+ /** First problem with the submitted params, or null. Every declared param
415
+ * is checked by the shared record-field validator; keys the action never
416
+ * declared are rejected outright — a stray key would otherwise ride the
417
+ * resolved `set` semantics silently. */
418
+ function firstMutateParamProblem(action, params) {
419
+ const declared = action.params ?? {};
420
+ for (const key of Object.keys(params)) if (declared[key] === void 0) return `unknown param '${key}' — not declared by action '${action.id}'`;
421
+ for (const [key, spec] of Object.entries(declared)) {
422
+ const problem = recordFieldProblem(key, spec, params[key], "strict");
423
+ if (problem) return problem;
424
+ }
425
+ return null;
426
+ }
427
+ /** Apply one mutate action to one record. Never throws for data-shaped
428
+ * failures — the outcome's `problem` doubles as agent feedback when an
429
+ * LLM (not the user) pressed the button. */
430
+ async function applyMutateAction(collection, action, itemId, params, opts = {}) {
431
+ const paramProblem = firstMutateParamProblem(action, params);
432
+ if (paramProblem) return {
433
+ ok: false,
434
+ status: "invalid-params",
435
+ problem: paramProblem
436
+ };
437
+ const store = storeFor(collection, opts);
438
+ if (!store.write) return {
439
+ ok: false,
440
+ status: "write-refused",
441
+ problem: "write refused (read-only collection)"
442
+ };
443
+ const existing = await store.read(itemId);
444
+ if (!existing) return {
445
+ ok: false,
446
+ status: "not-found",
447
+ problem: `item '${itemId}' not found`
448
+ };
449
+ if (!actionVisible(action, existing)) return {
450
+ ok: false,
451
+ status: "require-unmet",
452
+ problem: `action '${action.id}' is not available for item '${itemId}' in its current state`
453
+ };
454
+ const stored = Object.entries(existing).filter(([key]) => {
455
+ const spec = collection.schema.fields[key];
456
+ return !spec || !COMPUTED_TYPES.has(spec.type);
457
+ });
458
+ const merged = {
459
+ ...Object.fromEntries(stored),
460
+ ...resolveMutateSet(action.set, params)
461
+ };
462
+ const invalid = validateRecordObject(merged, itemId, collection.schema);
463
+ if (invalid) return {
464
+ ok: false,
465
+ status: "invalid-record",
466
+ problem: invalid
467
+ };
468
+ const result = await store.write(itemId, merged);
469
+ if (result.kind !== "ok") return {
470
+ ok: false,
471
+ status: "write-refused",
472
+ problem: `write refused (${result.kind})`
473
+ };
474
+ return {
475
+ ok: true,
476
+ item: merged
477
+ };
478
+ }
479
+ //#endregion
480
+ //#region src/collection/server/ontology.ts
481
+ /** Extract the relations a schema declares, in field declaration order:
482
+ * top-level `ref` / `embed` / `backlinks` fields plus `ref` sub-fields
483
+ * inside `table` columns. Pure — exported so the phase-2 graph panel
484
+ * can reuse it on already-loaded schemas. */
485
+ function schemaRelations(schema) {
486
+ const relations = [];
487
+ for (const [key, spec] of Object.entries(schema.fields)) {
488
+ if (spec.type === "ref" || spec.type === "embed") relations.push({
489
+ field: key,
490
+ kind: spec.type,
491
+ to: spec.to
492
+ });
493
+ if (spec.type === "backlinks" || spec.type === "rollup") relations.push({
494
+ field: key,
495
+ kind: spec.type,
496
+ to: spec.from
497
+ });
498
+ if (spec.type !== "table") continue;
499
+ for (const [subKey, subSpec] of Object.entries(spec.of)) if (subSpec.type === "ref") relations.push({
500
+ field: `${key}.${subKey}`,
501
+ kind: "ref",
502
+ to: subSpec.to
503
+ });
504
+ }
505
+ return relations;
506
+ }
507
+ /** Count the record files in a collection's data dir — the same
508
+ * `<id>.json` entries `listItems` considers, WITHOUT parsing them (the
509
+ * ontology is a summary; a malformed record is still a record). Each
510
+ * candidate is classified by the SHARED `isRegularFile` lstat helper —
511
+ * the exact file-disclosure defense `listItems` applies — so a
512
+ * symlinked record never counts and the count can't diverge from the
513
+ * readable set on any filesystem (Codex review on PR #2099, twice).
514
+ * Fail-soft: a missing dir or a dataDir escaping the workspace via
515
+ * symlink counts 0. */
516
+ async function countRecordFiles(dataDir, workspaceRoot) {
517
+ if (!isContainedInRoot(dataDir, workspaceRoot)) return 0;
518
+ try {
519
+ const names = (await readdir(dataDir)).filter((name) => name.endsWith(".json") && !name.startsWith("."));
520
+ return (await Promise.all(names.map((name) => isRegularFile(path.join(dataDir, name))))).filter(Boolean).length;
521
+ } catch {
522
+ return 0;
523
+ }
524
+ }
525
+ /** A collection's record count for the ontology. File-backed: the cheap
526
+ * readdir count. Every other backend (`dataSource` CSV, `storage`
527
+ * sqlite): the store's page total — the dataDir is a phantom there, so
528
+ * the readdir count would always misreport 0. Fail-soft to 0 like
529
+ * `countRecordFiles` (an unreadable file / missing engine must not
530
+ * break the whole ontology). */
531
+ async function countRecords(collection, workspaceRoot) {
532
+ if (storageKindFor(collection.schema) !== "file") try {
533
+ return (await storeFor(collection, { workspaceRoot }).page({ limit: 0 })).total;
534
+ } catch {
535
+ return 0;
536
+ }
537
+ return countRecordFiles(collection.dataDir, workspaceRoot);
538
+ }
539
+ async function toOntologyEntry(collection, workspaceRoot) {
540
+ const { schema } = collection;
541
+ return {
542
+ slug: collection.slug,
543
+ title: schema.title,
544
+ icon: schema.icon,
545
+ primaryKey: schema.primaryKey,
546
+ displayField: schema.displayField ?? schema.primaryKey,
547
+ recordCount: await countRecords(collection, workspaceRoot),
548
+ relations: schemaRelations(schema)
549
+ };
550
+ }
551
+ /** Build the workspace ontology: every discovered collection (slug-sorted,
552
+ * discovery's order), each with its outbound relations and a
553
+ * readdir-cheap record count — fine to call on demand. */
554
+ async function buildWorkspaceOntology(opts = {}) {
555
+ const workspaceRoot = opts.workspaceRoot ?? getWorkspaceRoot();
556
+ const collections = await discoverCollections(opts);
557
+ return Promise.all(collections.map((collection) => toOntologyEntry(collection, workspaceRoot)));
558
+ }
559
+ //#endregion
560
+ //#region src/collection/server/dynamicIcon.ts
561
+ /** Index `items` by their `primaryKey` value — the `recordsById` map a
562
+ * `valueFrom` reference (e.g. `_config.defaultCity`) resolves against.
563
+ * Items whose primary key isn't a string (shouldn't happen for a valid
564
+ * schema, but records are untyped storage) are skipped rather than
565
+ * coerced, so a broken key never silently shadows a real one. */
566
+ function buildRecordsById(items, primaryKey) {
567
+ const entries = items.filter((item) => typeof item[primaryKey] === "string").map((item) => [String(item[primaryKey]), item]);
568
+ return Object.fromEntries(entries);
569
+ }
570
+ /** Order records by their `primaryKey` so record selection is deterministic:
571
+ * `listItems` returns filesystem `readdir` order (arbitrary across machines),
572
+ * which would let `from: "first"`, the no-`orderBy` `latest`, and `orderBy`
573
+ * ties pick a different record — and thus a different icon — between
574
+ * reconciles. A stable id sort pins one answer. */
575
+ function sortByPrimaryKey(items, primaryKey) {
576
+ return [...items].sort((left, right) => String(left[primaryKey] ?? "").localeCompare(String(right[primaryKey] ?? "")));
577
+ }
578
+ /** Compute the effective launcher icon for `collection`: its static
579
+ * `schema.icon` when it declares no `dynamicIcon`, else the icon
580
+ * resolved from `dynamicIcon.source`'s RAW stored records (no
581
+ * derive/enrich — the icon rules match against stored values) via the
582
+ * pure resolver. Fails soft on any read/discovery error (missing source
583
+ * collection, filesystem error): falls back to `dynamicIcon.fallback ??
584
+ * schema.icon` rather than surfacing to the collections list. */
585
+ async function computeCollectionIcon(collection, opts = {}) {
586
+ const { schema } = collection;
587
+ const spec = schema.dynamicIcon;
588
+ if (!spec) return schema.icon;
589
+ try {
590
+ const source = await loadCollection(spec.source.collection, opts);
591
+ if (!source) return spec.fallback ?? schema.icon;
592
+ const ordered = sortByPrimaryKey(await storeFor(source, { workspaceRoot: opts.workspaceRoot }).list(), source.schema.primaryKey);
593
+ const orderBy = spec.source.orderBy ?? firstDateField(source.schema);
594
+ const recordsById = buildRecordsById(ordered, source.schema.primaryKey);
595
+ return resolveIcon(selectDynamicRecord(ordered, spec.source, orderBy, recordsById), spec, schema.icon, recordsById);
596
+ } catch (err) {
597
+ log.warn("collections", "dynamic icon compute failed, falling back", {
598
+ slug: collection.slug,
599
+ source: spec.source.collection,
600
+ error: String(err)
601
+ });
602
+ return spec.fallback ?? schema.icon;
603
+ }
604
+ }
605
+ //#endregion
606
+ //#region src/collection/server/util.ts
607
+ /** Human-readable message from an unknown thrown value. */
608
+ function errorMessage(err) {
609
+ return err instanceof Error ? err.message : String(err);
610
+ }
611
+ var ONE_SECOND_MS = 1e3;
612
+ var ONE_DAY_MS = 1440 * 60 * 1e3;
613
+ //#endregion
614
+ //#region src/collection/server/spawn.ts
615
+ var YMD_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
616
+ function pad2(value) {
617
+ return String(value).padStart(2, "0");
618
+ }
619
+ function pad4(value) {
620
+ return String(value).padStart(4, "0");
621
+ }
622
+ /** Days in `month` (1-12) of `year`, leap-year-aware. `new Date(y, m, 0)`
623
+ * is day 0 of the *next* month = the last day of `month`; `.getDate()`
624
+ * reads the civil day regardless of timezone. */
625
+ function daysInMonth(year, month) {
626
+ return new Date(year, month, 0).getDate();
627
+ }
628
+ /** Parse a `YYYY-MM-DD` string into a CivilDate, or null when the value
629
+ * isn't a well-formed in-range calendar date. */
630
+ function parseCivil(raw) {
631
+ if (typeof raw !== "string") return null;
632
+ const match = YMD_PATTERN.exec(raw.trim());
633
+ if (!match) return null;
634
+ const year = Number(match[1]);
635
+ const month = Number(match[2]);
636
+ const day = Number(match[3]);
637
+ if (month < 1 || month > 12) return null;
638
+ if (day < 1 || day > daysInMonth(year, month)) return null;
639
+ return {
640
+ y: year,
641
+ m: month,
642
+ d: day
643
+ };
644
+ }
645
+ /** `YYYY-MM-DD` for storage in a `date` field. */
646
+ function formatCivil(date) {
647
+ return `${pad4(date.y)}-${pad2(date.m)}-${pad2(date.d)}`;
648
+ }
649
+ /** A monotonic integer key for a civil date (YYYYMMDD), for ordering /
650
+ * equality without timezone concerns. */
651
+ function ordinal(date) {
652
+ return date.y * 1e4 + date.m * 100 + date.d;
653
+ }
654
+ /** Add `n` whole days to a civil date. Uses UTC epoch arithmetic so it
655
+ * is DST-immune (we only ever read back the civil Y/M/D). */
656
+ function addDays(date, days) {
657
+ const shifted = new Date(Date.UTC(date.y, date.m - 1, date.d) + days * ONE_DAY_MS);
658
+ return {
659
+ y: shifted.getUTCFullYear(),
660
+ m: shifted.getUTCMonth() + 1,
661
+ d: shifted.getUTCDate()
662
+ };
663
+ }
664
+ /** Advance a civil date by one `every` step. Month/year units preserve
665
+ * the rule's day-of-month anchor, clamped to the target month's length
666
+ * (no drift); day/week units do civil day arithmetic. */
667
+ function advanceTriggerDate(source, every) {
668
+ const { unit, interval } = every;
669
+ if (unit === "day") return addDays(source, interval);
670
+ if (unit === "week") return addDays(source, interval * 7);
671
+ const monthsToAdd = interval * (unit === "year" ? 12 : 1);
672
+ const total = source.y * 12 + (source.m - 1) + monthsToAdd;
673
+ const nextYear = Math.floor(total / 12);
674
+ const nextMonth = total % 12 + 1;
675
+ const dim = daysInMonth(nextYear, nextMonth);
676
+ const anchor = every.dayOfMonth === "last" ? dim : every.dayOfMonth ?? source.d;
677
+ return {
678
+ y: nextYear,
679
+ m: nextMonth,
680
+ d: Math.min(anchor, dim)
681
+ };
682
+ }
683
+ /** True iff `now`'s civil date (local timezone) has reached the fire date
684
+ * for `triggerRaw` — i.e. the trigger date minus `leadDays` (so a 10-day
685
+ * lead fires 10 days early). Returns null when `triggerRaw` isn't a
686
+ * parseable date — callers treat that as "don't fire" and warn. */
687
+ function isTriggerDue(triggerRaw, now, leadDays = 0) {
688
+ const due = parseCivil(triggerRaw);
689
+ if (due === null) return null;
690
+ const fireDate = leadDays > 0 ? addDays(due, -leadDays) : due;
691
+ return ordinal({
692
+ y: now.getFullYear(),
693
+ m: now.getMonth() + 1,
694
+ d: now.getDate()
695
+ }) >= ordinal(fireDate);
696
+ }
697
+ var DATE_SUFFIX_PATTERN = /-\d{8}$/;
698
+ /** Deterministic successor id: `<stem>-<YYYYMMDD>`, where `<stem>` is the
699
+ * source id with a trailing `-YYYYMMDD` stripped if present. So a chain
700
+ * shares one stem and each instance is dated:
701
+ * `rent` → `rent-20260610`
702
+ * `rent-20260610` → `rent-20260710`
703
+ * Slug-safe (alphanumeric + hyphen) and a pure function of the inputs,
704
+ * which is what makes create-if-absent idempotent. */
705
+ function successorId(sourceId, next) {
706
+ return `${sourceId.replace(DATE_SUFFIX_PATTERN, "")}-${pad4(next.y)}${pad2(next.m)}${pad2(next.d)}`;
707
+ }
708
+ /** True iff `item` satisfies the spawn predicate. With an explicit
709
+ * `when`, matches `String(item[when.field]) ∈ when.in`. Without one,
710
+ * defaults to the completion-done condition — the shared, flag-aware
711
+ * `itemIsDone` (core/completion; downhill import, so the module graph
712
+ * stays acyclic). */
713
+ function matchesWhen(when, schema, item) {
714
+ if (when) {
715
+ const raw = item[when.field];
716
+ return raw !== void 0 && raw !== null && when.in.includes(String(raw));
717
+ }
718
+ return itemIsDone(schema, item);
719
+ }
720
+ /** Resolve the literal `every` that applies to `sourceItem`. Literal-arm
721
+ * `spawn.every` passes through unchanged. Field-driven `spawn.every` reads
722
+ * `sourceItem[fromField]` and looks it up in `map`; an empty field or a
723
+ * value with no map entry yields null (caller skips + logs — see plan §5).
724
+ * Discovery rejects a map that doesn't cover the enum's values, so null
725
+ * here means a record that predates a map/enum edit. */
726
+ function resolveEvery(every, sourceItem) {
727
+ if (!isFieldDrivenEvery(every)) return every;
728
+ const raw = sourceItem[every.fromField];
729
+ if (raw === void 0 || raw === null || raw === "") return null;
730
+ return every.map[String(raw)] ?? null;
731
+ }
732
+ /** Build the successor record purely from (schema, source record, source
733
+ * id). Returns null when the schema has no spawn/triggerField or the
734
+ * source's trigger date is unparseable. */
735
+ function computeSuccessor(schema, sourceItem, sourceId) {
736
+ const { spawn, triggerField } = schema;
737
+ if (!spawn || !triggerField) return null;
738
+ const srcDate = parseCivil(sourceItem[triggerField]);
739
+ if (srcDate === null) return null;
740
+ const every = resolveEvery(spawn.every, sourceItem);
741
+ if (every === null) return null;
742
+ const next = advanceTriggerDate(srcDate, every);
743
+ const nextId = successorId(sourceId, next);
744
+ const record = {};
745
+ for (const field of spawn.carry ?? []) if (Object.prototype.hasOwnProperty.call(sourceItem, field)) record[field] = sourceItem[field];
746
+ Object.assign(record, spawn.set ?? {});
747
+ record[triggerField] = formatCivil(next);
748
+ record[schema.primaryKey] = nextId;
749
+ return {
750
+ id: nextId,
751
+ record
752
+ };
753
+ }
754
+ /** Warn precisely about which of `computeSuccessor`'s two null causes fired
755
+ * (plan §5): an unparseable source trigger date (the original cause), or a
756
+ * field-driven `every` whose record value has no `map` entry (a record that
757
+ * predates a map/enum edit — discovery rejects this statically otherwise). */
758
+ function logSpawnSkip(slug, triggerField, every, sourceItem, sourceId) {
759
+ if (parseCivil(sourceItem[triggerField]) === null) {
760
+ log.warn("collections", "spawn skipped: source trigger date unparseable", {
761
+ slug,
762
+ sourceId,
763
+ triggerField
764
+ });
765
+ return;
766
+ }
767
+ const fromField = isFieldDrivenEvery(every) ? every.fromField : void 0;
768
+ log.warn("collections", "spawn skipped: no `every` mapping for frequency value", {
769
+ slug,
770
+ sourceId,
771
+ fromField,
772
+ value: fromField === void 0 ? void 0 : sourceItem[fromField]
773
+ });
774
+ }
775
+ /** Idempotently create the successor for `sourceItem` when it matches the
776
+ * spawn predicate. No-op when the schema declares no spawn, the
777
+ * predicate doesn't match, the trigger date is unparseable, or the
778
+ * successor already exists (create-if-absent). Never overwrites an
779
+ * existing successor — protects any edits the user made to it. */
780
+ async function maybeSpawnSuccessor(collection, sourceItem, sourceId, ioOpts = {}) {
781
+ const { slug, schema } = collection;
782
+ const { spawn } = schema;
783
+ if (!spawn || !schema.triggerField) return;
784
+ if (!matchesWhen(spawn.when, schema, sourceItem)) return;
785
+ const computed = computeSuccessor(schema, sourceItem, sourceId);
786
+ if (computed === null) {
787
+ logSpawnSkip(slug, schema.triggerField, spawn.every, sourceItem, sourceId);
788
+ return;
789
+ }
790
+ if (matchesWhen(spawn.when, schema, computed.record)) {
791
+ log.warn("collections", "spawn skipped: successor would be born matching its own predicate (unbounded respawn)", {
792
+ slug,
793
+ sourceId,
794
+ successorId: computed.id
795
+ });
796
+ return;
797
+ }
798
+ try {
799
+ const { write } = storeFor(collection, ioOpts);
800
+ if (!write) {
801
+ log.warn("collections", "spawn skipped: collection store is read-only", {
802
+ slug,
803
+ sourceId
804
+ });
805
+ return;
806
+ }
807
+ const result = await write(computed.id, computed.record, { refuseOverwrite: true });
808
+ if (result.kind === "ok") log.info("collections", "spawned successor", {
809
+ slug,
810
+ sourceId,
811
+ successorId: computed.id
812
+ });
813
+ else if (result.kind !== "conflict") log.warn("collections", "spawn write failed", {
814
+ slug,
815
+ sourceId,
816
+ successorId: computed.id,
817
+ kind: result.kind
818
+ });
819
+ } catch (err) {
820
+ log.warn("collections", "spawn write threw", {
821
+ slug,
822
+ sourceId,
823
+ successorId: computed.id,
824
+ error: errorMessage(err)
825
+ });
826
+ }
827
+ }
828
+ //#endregion
829
+ //#region src/collection/server/delete.ts
830
+ /** Human-readable reason for a non-`ok` delete result. Exported so the
831
+ * route maps `kind` → message without inlining the switch (keeps the
832
+ * handler short and the mapping unit-testable). The `Record` is
833
+ * exhaustive — a new refusal kind won't compile until it's added. */
834
+ function deleteCollectionRefusalMessage(result) {
835
+ const { slug } = result;
836
+ return {
837
+ "user-scope": `collection '${slug}' is user-scope (~/.claude/skills/) and is read-only from MulmoClaude`,
838
+ preset: `collection '${slug}' is a preset (mc-*) and re-seeds on restart; unstar it from the catalog instead`,
839
+ "unsafe-data-path": `collection '${slug}' declares a dataPath outside its own data/${slug}/ subtree; refusing to delete`,
840
+ "path-escape": `a directory for collection '${slug}' escapes the workspace`
841
+ }[result.kind];
842
+ }
843
+ /** The canonical staging dir for a slug: `data/skills/<slug>`. */
844
+ function stagingSkillDir(workspaceRoot, slug) {
845
+ return path.join(skillsStagingDir(workspaceRoot), slug);
846
+ }
847
+ async function pathExists(target) {
848
+ try {
849
+ await stat(target);
850
+ return true;
851
+ } catch {
852
+ return false;
853
+ }
854
+ }
855
+ /** UTC `YYYY-MM-DD` — keeps the archive folder human-sortable. */
856
+ function todayStamp() {
857
+ return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
858
+ }
859
+ /** Every directory the delete will touch must resolve under the
860
+ * workspace root — guards against a symlinked ancestor escaping it. */
861
+ function deleteTargets(collection, workspaceRoot) {
862
+ return [
863
+ stagingSkillDir(workspaceRoot, collection.slug),
864
+ collection.skillDir,
865
+ collection.dataDir,
866
+ ...collection.storageFile !== void 0 ? [collection.storageFile] : []
867
+ ];
868
+ }
869
+ /** The records directory the delete recursively archives + removes
870
+ * (`collection.dataDir`) must live in this collection's OWN per-slug
871
+ * subtree. `dataDir` is normally derived from `schema.dataPath`, but
872
+ * `deleteCollection` accepts a `LoadedCollection` whose fields could be
873
+ * inconsistent — so we validate the RESOLVED target the destructive ops
874
+ * actually touch, not the schema string. A shared root like `data` or
875
+ * `data/skills` would otherwise turn the recursive removal into a
876
+ * workspace-wide wipe whose archive captures only this collection.
877
+ * `path.resolve` collapses any `..` before the prefix test (symlink
878
+ * escapes are caught separately by the realpath containment check in
879
+ * `deleteTargets`).
880
+ *
881
+ * TWO acceptable per-slug subtrees:
882
+ * - `data/<slug>/...` — the convention authored collections default to.
883
+ * - `data/collections/<slug>/...` — what `normalizedDataPath` in the
884
+ * registry-import path stamps onto every imported schema (so imported
885
+ * collections never collide with `data/<slug>/`-shaped authored ones).
886
+ * Both are equally per-collection and equally safe; a delete that targets
887
+ * anything else (e.g. raw `data/`, `data/wiki/`, a sibling slug) is
888
+ * refused. */
889
+ function isDataDirSafe(dataDir, slug, workspaceRoot) {
890
+ const acceptableRoots = [path.resolve(workspaceRoot, "data", slug), path.resolve(workspaceRoot, "data", "collections", slug)];
891
+ const resolved = path.resolve(dataDir);
892
+ return acceptableRoots.some((root) => resolved === root || resolved.startsWith(root + path.sep));
893
+ }
894
+ /** Step 2 of the restore doc — how to bring the records back. A
895
+ * `dataSource` collection has no record files to copy (its rows live in
896
+ * the external data file, which the delete never touches). */
897
+ function restoreRecordsStep(schema) {
898
+ if (schema.storage !== void 0) return `2. Records: copy the archived database file
899
+ \`${path.basename(schema.storage.path)}\` (next to this document) back to
900
+ \`${schema.storage.path}\` (workspace-relative, \`cp\`). It holds every
901
+ record. If \`-wal\`/\`-journal\` sidecar files were archived alongside
902
+ it, copy them back too.`;
903
+ if (schema.dataPath === void 0) return `2. Records: nothing to copy. This is a \`dataSource\` collection —
904
+ its records are the rows of \`${schema.dataSource?.path}\`, which the
905
+ delete never touched.`;
906
+ return `2. Copy the item data: \`cp\` every file under \`records/\` into
907
+ \`${schema.dataPath}/\`. The records are part of the collection and
908
+ must be restored. They are plain data files (NOT bridged), so use
909
+ \`cp\` — the Write-tool rule in step 1 applies ONLY to the skill
910
+ files, not to these records (there may be many; copy them, do not
911
+ Write them one by one).`;
912
+ }
913
+ function buildRestoreDoc(collection) {
914
+ const { slug, schema } = collection;
915
+ return `# Restore "${schema.title}" (collection \`${slug}\`)
916
+
917
+ This folder is an automatic backup made when the collection was deleted.
918
+ Follow these steps to restore it.
919
+
920
+ 1. Recreate the skill files in \`data/skills/${slug}/\` using the **Write
921
+ tool**: read each file under \`skill/\` and Write it to the matching
922
+ path — \`SKILL.md\`, \`schema.json\`, and any \`templates/*\`.
923
+
924
+ IMPORTANT — use the Write tool, NOT \`cp\` / \`mv\` / a shell redirect.
925
+ The skill-bridge hook mirrors \`data/skills/${slug}/\` into
926
+ \`.claude/skills/${slug}/\`, and that mirror is what actually registers
927
+ the collection. The hook only fires on Write/Edit tool calls, so a
928
+ \`cp\` would leave the files in staging with no \`.claude/skills/\`
929
+ mirror — the collection would stay invisible. (Writing
930
+ \`.claude/skills/\` directly is not an option either: that path is
931
+ permission-gated.)
932
+
933
+ ${restoreRecordsStep(schema)}
934
+
935
+ 3. Confirm the collection reappears at \`/collections/${slug}\`.
936
+
937
+ - slug: \`${slug}\`
938
+ - title: ${schema.title}
939
+ - dataPath: \`${schema.dataPath ?? (schema.storage !== void 0 ? `(storage) ${schema.storage.path}` : `(dataSource) ${schema.dataSource?.path}`)}\`
940
+ `;
941
+ }
942
+ /** Copy one skill copy + the records + RESTORE.md into `archiveDir`. */
943
+ async function writeArchive(collection, archiveDir, workspaceRoot) {
944
+ const staging = stagingSkillDir(workspaceRoot, collection.slug);
945
+ await cp(await pathExists(staging) ? staging : collection.skillDir, path.join(archiveDir, "skill"), { recursive: true });
946
+ if (await pathExists(collection.dataDir)) await cp(collection.dataDir, path.join(archiveDir, "records"), { recursive: true });
947
+ if (collection.storageFile !== void 0 && await pathExists(collection.storageFile)) {
948
+ const checkpointed = await checkpointSqliteDatabase(collection.storageFile);
949
+ await cp(collection.storageFile, path.join(archiveDir, path.basename(collection.storageFile)));
950
+ if (!checkpointed) for (const suffix of [
951
+ "-wal",
952
+ "-journal",
953
+ "-shm"
954
+ ]) {
955
+ const sidecar = `${collection.storageFile}${suffix}`;
956
+ if (await pathExists(sidecar)) await cp(sidecar, path.join(archiveDir, path.basename(sidecar)));
957
+ }
958
+ }
959
+ await writeFile(path.join(archiveDir, "RESTORE.md"), buildRestoreDoc(collection), "utf-8");
960
+ }
961
+ /** Remove all three locations. `rm -rf`-style (force) so a missing dir
962
+ * is a no-op; the now-empty data parent (`data/<slug>/` after its
963
+ * `items/` is gone) is swept too, but only when empty. */
964
+ async function removeLocations(collection, workspaceRoot) {
965
+ await rm(stagingSkillDir(workspaceRoot, collection.slug), {
966
+ recursive: true,
967
+ force: true
968
+ });
969
+ await rm(collection.skillDir, {
970
+ recursive: true,
971
+ force: true
972
+ });
973
+ await rm(collection.dataDir, {
974
+ recursive: true,
975
+ force: true
976
+ });
977
+ await rmdir(path.dirname(collection.dataDir)).catch(() => void 0);
978
+ if (collection.storageFile !== void 0) {
979
+ await rm(collection.storageFile, { force: true });
980
+ await rm(`${collection.storageFile}-wal`, { force: true });
981
+ await rm(`${collection.storageFile}-journal`, { force: true });
982
+ await rm(`${collection.storageFile}-shm`, { force: true });
983
+ }
984
+ }
985
+ async function deleteCollection(collection, opts = {}) {
986
+ const { slug } = collection;
987
+ const workspaceRoot = opts.workspaceRoot ?? getWorkspaceRoot();
988
+ if (collection.source === "user") return {
989
+ kind: "user-scope",
990
+ slug
991
+ };
992
+ if (isPresetSlug$1(slug)) return {
993
+ kind: "preset",
994
+ slug
995
+ };
996
+ if (!isDataDirSafe(collection.dataDir, slug, workspaceRoot)) {
997
+ log.warn("collections", "deleteCollection refused: dataDir is not under the per-collection root", {
998
+ slug,
999
+ dataDir: collection.dataDir
1000
+ });
1001
+ return {
1002
+ kind: "unsafe-data-path",
1003
+ slug
1004
+ };
1005
+ }
1006
+ if (deleteTargets(collection, workspaceRoot).some((target) => !isContainedInRoot(target, workspaceRoot))) {
1007
+ log.warn("collections", "deleteCollection refused: a target escapes the workspace", { slug });
1008
+ return {
1009
+ kind: "path-escape",
1010
+ slug
1011
+ };
1012
+ }
1013
+ const archiveRel = path.join(archiveDir(), `${opts.dateStamp ?? todayStamp()}-${randomUUID()}`);
1014
+ const archiveDir$1 = path.join(workspaceRoot, archiveRel);
1015
+ await mkdir(archiveDir$1, { recursive: true });
1016
+ await writeArchive(collection, archiveDir$1, workspaceRoot);
1017
+ await removeLocations(collection, workspaceRoot);
1018
+ log.info("collections", "collection deleted + archived", {
1019
+ slug,
1020
+ archive: archiveRel
1021
+ });
1022
+ return {
1023
+ kind: "ok",
1024
+ slug,
1025
+ archivePath: archiveRel
1026
+ };
1027
+ }
1028
+ //#endregion
1029
+ //#region src/collection/server/views.ts
1030
+ async function fileExists(target) {
1031
+ try {
1032
+ await stat(target);
1033
+ return true;
1034
+ } catch (err) {
1035
+ const { code } = err;
1036
+ if (code === "ENOENT" || code === "ENOTDIR") return false;
1037
+ throw err;
1038
+ }
1039
+ }
1040
+ /** The authoritative base dir for a collection's schema.json + view HTML.
1041
+ * For a project collection, prefer the staging tree when its schema.json is
1042
+ * present (authoring layout); otherwise fall back to the active skill dir
1043
+ * (imported layout — staging never materialised). For feed / user, it's
1044
+ * always the discovered skillDir. Matches `readCustomViewHtml` so reads and
1045
+ * deletes agree on both layouts. */
1046
+ async function canonicalBase(collection, workspaceRoot, safeSlug) {
1047
+ if (collection.source !== "project") return collection.skillDir;
1048
+ const staging = path.join(skillsStagingDir(workspaceRoot), safeSlug);
1049
+ if (await fileExists(path.join(staging, "schema.json"))) return staging;
1050
+ return collection.skillDir;
1051
+ }
1052
+ /** Every on-disk schema.json that must reflect the removal. The active
1053
+ * `<skillDir>/schema.json` is the discovery anchor and is always present.
1054
+ * The staging copy is included only when it actually exists, so an imported
1055
+ * project collection (no staging mirror) doesn't have an empty staging tree
1056
+ * materialised by a side effect of the delete. */
1057
+ async function schemaWriteTargets(collection, workspaceRoot, safeSlug) {
1058
+ const active = path.join(collection.skillDir, SCHEMA_FILE$1);
1059
+ if (collection.source !== "project") return [active];
1060
+ const stagingSchema = path.join(skillsStagingDir(workspaceRoot), safeSlug, SCHEMA_FILE$1);
1061
+ const targets = [];
1062
+ if (await fileExists(stagingSchema)) targets.push(stagingSchema);
1063
+ targets.push(active);
1064
+ return targets;
1065
+ }
1066
+ /** Idempotent unlink — a missing file is fine (the schema entry still gets
1067
+ * cleaned), but a real error (permissions, etc.) propagates. */
1068
+ async function unlinkIfPresent(target) {
1069
+ try {
1070
+ await unlink(target);
1071
+ } catch (err) {
1072
+ if (err.code !== "ENOENT") throw err;
1073
+ }
1074
+ }
1075
+ /** Re-read the canonical schema.json, drop the `views[]` entry, and write the
1076
+ * result back to every on-disk copy so staging + active stay identical. Reads
1077
+ * raw (not `collection.schema`) so fields the typed schema doesn't model are
1078
+ * preserved verbatim. */
1079
+ async function removeViewFromSchemas(collection, viewId, workspaceRoot, safeSlug) {
1080
+ const base = await canonicalBase(collection, workspaceRoot, safeSlug);
1081
+ const canonical = path.join(base, SCHEMA_FILE$1);
1082
+ const parsed = JSON.parse(await readFile(canonical, "utf-8"));
1083
+ if (Array.isArray(parsed.views)) parsed.views = parsed.views.filter((entry) => entry?.id !== viewId);
1084
+ const serialized = `${JSON.stringify(parsed, null, 2)}\n`;
1085
+ for (const target of await schemaWriteTargets(collection, workspaceRoot, safeSlug)) await writeFileAtomic(target, serialized);
1086
+ }
1087
+ /** Delete one custom view from `collection`: unlink its HTML file and drop it
1088
+ * from every schema.json copy. User-scope and preset (mc-*) collections are
1089
+ * refused (read-only / re-seeded on boot), consistent with `deleteCollection`. */
1090
+ async function deleteCustomView(collection, viewId, opts = {}) {
1091
+ if (collection.source === "user") return { kind: "user-scope" };
1092
+ if (isPresetSlug$1(collection.slug)) return { kind: "preset" };
1093
+ const safeSlug = safeSlugName(collection.slug);
1094
+ if (safeSlug === null) return {
1095
+ kind: "unsafe-path",
1096
+ viewId
1097
+ };
1098
+ const views = collection.schema.views ?? [];
1099
+ const view = views.find((entry) => entry.id === viewId);
1100
+ if (!view) return {
1101
+ kind: "not-found",
1102
+ viewId
1103
+ };
1104
+ const workspaceRoot = opts.workspaceRoot ?? getWorkspaceRoot();
1105
+ const htmlPath = resolveTemplatePath(await canonicalBase(collection, workspaceRoot, safeSlug), view.file);
1106
+ if (htmlPath === null) return {
1107
+ kind: "unsafe-path",
1108
+ viewId
1109
+ };
1110
+ await removeViewFromSchemas(collection, viewId, workspaceRoot, safeSlug);
1111
+ if (!views.some((entry) => entry.id !== viewId && entry.file === view.file)) await unlinkIfPresent(htmlPath);
1112
+ return {
1113
+ kind: "ok",
1114
+ viewId
1115
+ };
1116
+ }
1117
+ /** True for a launcher-managed preset slug (`mc-<something>`). The sync logic uses
1118
+ * this to bound which active skills it may refresh/prune, so user-authored skills are
1119
+ * never touched. */
1120
+ function isPresetSlug(slug) {
1121
+ return slug.startsWith("mc-") && slug.length > 3;
1122
+ }
1123
+ //#endregion
1124
+ //#region src/collection/server/manageTool.ts
1125
+ /** Refuse an unselective getItems beyond this many records — a silent
1126
+ * truncation would read as "covered everything", and an unbounded dump
1127
+ * of a large collection is a token bomb. `ids` or `fields` lifts it. */
1128
+ var MAX_UNSELECTIVE_ITEMS = 200;
1129
+ /** schema.json basename under a skill dir (canonical staging + active mirror). */
1130
+ var SCHEMA_FILE = "schema.json";
1131
+ /** The collection-authoring reference, served by the `schemaDocs` action. */
1132
+ var SCHEMA_DOCS_FILE = "collection-skills.md";
1133
+ /** Cap the rejected-schema issue list so a deeply-broken schema can't flood the result. */
1134
+ var MAX_SCHEMA_ISSUES = 20;
1135
+ /** The workspace help-docs dir both hosts seed (`@mulmoclaude/core/workspace-setup`
1136
+ * syncs the bundled assets here) — the user-editable copy schemaDocs prefers. */
1137
+ var HELPS_DIR = "config/helps";
1138
+ /** Resolve the workspace root the same way every collections call does:
1139
+ * the injected override (tests) or the configured collection host. */
1140
+ function resolveBase(deps) {
1141
+ return deps.workspaceRoot ?? getWorkspaceRoot();
1142
+ }
1143
+ /** Shared "unknown collection" message — its schema.json is missing or
1144
+ * failed validation, so discovery skipped it. */
1145
+ function unknownCollection(slug) {
1146
+ return `manageCollection: unknown collection '${defangForPrompt(slug)}' — its schema.json is missing or failed validation.`;
1147
+ }
1148
+ function optionalStringArray(value, name) {
1149
+ if (value === void 0) return { ok: true };
1150
+ if (!Array.isArray(value) || !value.every((entry) => typeof entry === "string" && entry.length > 0)) return {
1151
+ ok: false,
1152
+ error: `manageCollection: \`${name}\` must be an array of non-empty strings when present.`
1153
+ };
1154
+ return {
1155
+ ok: true,
1156
+ value
1157
+ };
1158
+ }
1159
+ /** Project a record down to the requested fields. The primary key is
1160
+ * always kept so every returned record stays addressable for a
1161
+ * follow-up getItems/putItems. */
1162
+ function projectFields(record, fields, primaryKey) {
1163
+ const keys = fields.includes(primaryKey) ? fields : [primaryKey, ...fields];
1164
+ return Object.fromEntries(keys.filter((key) => key in record).map((key) => [key, record[key]]));
1165
+ }
1166
+ /** The validation warning appended to a getItems result when stored
1167
+ * record files are malformed (they're silently skipped at read time,
1168
+ * so without this they'd just look missing). Issue strings quote
1169
+ * record-controlled text → defanged, mirroring the presentCollection
1170
+ * dispatch. The record VALUES in `items` ride verbatim, like a raw
1171
+ * file Read — only host-composed report strings are defanged. */
1172
+ async function recordIssuesWarning(collection, deps) {
1173
+ if (deps.ablateValidation) return void 0;
1174
+ const issues = await validateCollectionRecords(collection, { workspaceRoot: deps.workspaceRoot });
1175
+ if (issues.length === 0) return void 0;
1176
+ const lines = issues.map((issue) => `- ${defangForPrompt(issue.file)}: ${defangForPrompt(issue.problem)}`).join("\n");
1177
+ return `${issues.length} record file(s) have data problems and are missing from this result. Fix each (Read → correct → Write):\n${lines}`;
1178
+ }
1179
+ async function loadRequestedItems(collection, ids, deps) {
1180
+ const store = storeFor(collection, { workspaceRoot: deps.workspaceRoot });
1181
+ if (!ids) return {
1182
+ items: await store.list(),
1183
+ missing: []
1184
+ };
1185
+ const items = [];
1186
+ const missing = [];
1187
+ for (const recordId of ids) {
1188
+ const item = await store.read(recordId).catch(() => null);
1189
+ if (item) items.push(item);
1190
+ else missing.push(recordId);
1191
+ }
1192
+ return {
1193
+ items,
1194
+ missing
1195
+ };
1196
+ }
1197
+ async function handleGetItems(collection, args, deps) {
1198
+ const { items, missing } = await loadRequestedItems(collection, args.ids, deps);
1199
+ if (!args.ids && !args.fields && items.length > 200) return `manageCollection: refused — '${collection.slug}' has ${items.length} records, over the unselective limit of 200. Pass \`ids\` for specific records or \`fields\` to project only the columns you need.`;
1200
+ const enriched = await enrichItems(collection, items, deps);
1201
+ const projected = args.fields ? enriched.map((item) => projectFields(item, args.fields, collection.schema.primaryKey)) : enriched;
1202
+ const warning = !args.ids || missing.length > 0 ? await recordIssuesWarning(collection, deps) : void 0;
1203
+ return JSON.stringify({
1204
+ collection: collection.slug,
1205
+ count: projected.length,
1206
+ items: projected,
1207
+ ...missing.length > 0 ? { missing: missing.map((recordId) => defangForPrompt(recordId)) } : {},
1208
+ ...warning ? { warning } : {}
1209
+ });
1210
+ }
1211
+ /** Reject writes that set host-computed keys, with a pointer at the
1212
+ * writable source of truth (the toggle's enum) where one exists. */
1213
+ function computedKeyProblem(record, schema) {
1214
+ for (const key of Object.keys(record)) {
1215
+ const spec = schema.fields[key];
1216
+ if (!spec || !COMPUTED_TYPES.has(spec.type)) continue;
1217
+ if (spec.type === "toggle" && spec.field) return `'${key}' is a toggle projection — write the enum field '${spec.field}' instead`;
1218
+ return `'${key}' is ${{
1219
+ derived: "derived",
1220
+ embed: "an embed",
1221
+ backlinks: "a backlinks view",
1222
+ rollup: "a rollup"
1223
+ }[spec.type] ?? "computed"} — computed by the host, remove it from the record`;
1224
+ }
1225
+ return null;
1226
+ }
1227
+ /** `mode: "merge"` resolves the row against the EXISTING record —
1228
+ * a partial row updates just the fields it carries, instead of a
1229
+ * whole-record upsert silently erasing the optional fields it omits
1230
+ * (an upsert of `{id, status}` would pass validation yet drop
1231
+ * `notes`/`lesson`/…). Merge is a partial UPDATE by definition, so a
1232
+ * missing record is a reject, not an implicit create — a merged-over-
1233
+ * nothing partial record is exactly the data shape this mode exists
1234
+ * to prevent.
1235
+ *
1236
+ * Computed keys found in the STORED record are stripped before the
1237
+ * merge: the caller's own row was already computed-key-rejected, but a
1238
+ * raw-written / legacy record can carry a stale `derived`/`embed`/
1239
+ * `toggle` value, and re-writing it would perpetuate a forged
1240
+ * host-computed value. A merge heals the record instead.
1241
+ *
1242
+ * the store read THROWS on a malformed stored file (only ENOENT is null) —
1243
+ * downgraded to a per-row rejection here, like loadRequestedItems'
1244
+ * `missing`, so one broken file can't abort the whole putItems batch. */
1245
+ async function mergeWithExisting(collection, store, record, itemId) {
1246
+ let existing;
1247
+ try {
1248
+ existing = await store.read(itemId);
1249
+ } catch {
1250
+ return `'${itemId}' has a malformed stored file — mode "merge" needs to read it; fix the file (Read → correct → Write) or replace it whole with "upsert"`;
1251
+ }
1252
+ if (!existing) return `'${itemId}' not found — mode "merge" updates an existing record; use "upsert" or "create" to add it`;
1253
+ const stored = Object.entries(existing).filter(([key]) => {
1254
+ const spec = collection.schema.fields[key];
1255
+ return !spec || !COMPUTED_TYPES.has(spec.type);
1256
+ });
1257
+ return {
1258
+ ...Object.fromEntries(stored),
1259
+ ...record
1260
+ };
1261
+ }
1262
+ async function putOneItem(collection, store, write, record, mode, deps) {
1263
+ const { schema } = collection;
1264
+ const itemId = resolveCreateItemId(schema, record);
1265
+ const reject = (about, problem) => ({ rejected: {
1266
+ id: defangForPrompt(about),
1267
+ problem: defangForPrompt(problem)
1268
+ } });
1269
+ if (itemId === null) return reject("(no id)", `record has no '${schema.primaryKey}' value — set it (it doubles as the filename)`);
1270
+ const computed = computedKeyProblem(record, schema);
1271
+ if (computed) return reject(itemId, computed);
1272
+ let toWrite = record;
1273
+ if (mode === "merge") {
1274
+ const merged = await mergeWithExisting(collection, store, record, itemId);
1275
+ if (typeof merged === "string") return reject(itemId, merged);
1276
+ toWrite = merged;
1277
+ }
1278
+ if (!deps.ablateValidation) {
1279
+ const invalid = validateRecordObject(toWrite, itemId, schema);
1280
+ if (invalid) return reject(itemId, invalid);
1281
+ }
1282
+ const result = await write(itemId, toWrite, { refuseOverwrite: mode === "create" });
1283
+ if (result.kind === "ok") return { written: result.itemId };
1284
+ if (result.kind === "invalid-id") return reject(itemId, `'${itemId}' is not a valid record id (letters/digits at the ends; -, _, or . inside; no '..' or path characters)`);
1285
+ if (result.kind === "conflict") return reject(itemId, `'${itemId}' already exists — mode "create" refuses overwrite; use "upsert" to update it`);
1286
+ return reject(itemId, "write refused: the collection's data dir escapes the workspace");
1287
+ }
1288
+ /** Aggregation over a collection via the structured query DSL
1289
+ * (`core/queryZ.ts`) — the paved road for counts / sums / group-bys
1290
+ * that a row listing can't answer honestly. The engine choice (native
1291
+ * store query vs enrich-then-JSONL fallback) lives in
1292
+ * `runCollectionQuery`, shared with the desktop custom view's `/query`
1293
+ * route so the two surfaces can never drift. */
1294
+ async function handleQueryItems(collection, queryArg, deps) {
1295
+ const parsed = CollectionQueryZ.safeParse(queryArg);
1296
+ if (!parsed.success) return `manageCollection: \`query\` rejected — fix and retry:\n${parsed.error.issues.slice(0, 20).map((issue) => `- ${issue.path.map(String).join(".") || "(root)"}: ${defangForPrompt(issue.message)}`).join("\n")}`;
1297
+ const rows = await runCollectionQuery(collection, parsed.data, { workspaceRoot: deps.workspaceRoot });
1298
+ return JSON.stringify({
1299
+ collection: collection.slug,
1300
+ count: rows.length,
1301
+ rows
1302
+ });
1303
+ }
1304
+ async function handlePutItems(collection, args, deps) {
1305
+ const store = storeFor(collection, { workspaceRoot: deps.workspaceRoot });
1306
+ const { write } = store;
1307
+ if (!write) return `manageCollection: ${readOnlyRefusal(collection.slug)} (its records are the rows of '${collection.schema.dataSource?.path}'; edit that file to change the data).`;
1308
+ const written = [];
1309
+ const rejected = [];
1310
+ for (const record of args.items) {
1311
+ const outcome = await putOneItem(collection, store, write, record, args.mode, deps);
1312
+ if (outcome.written) written.push(outcome.written);
1313
+ if (outcome.rejected) rejected.push(outcome.rejected);
1314
+ }
1315
+ return JSON.stringify({
1316
+ collection: collection.slug,
1317
+ written,
1318
+ rejected
1319
+ });
1320
+ }
1321
+ function parsePutItems(args, slug) {
1322
+ const { items, mode } = args;
1323
+ if (!(Array.isArray(items) && items.length > 0 && items.every((entry) => Boolean(entry) && typeof entry === "object" && !Array.isArray(entry)))) return "manageCollection: `items` is required for putItems — a non-empty array of record objects.";
1324
+ if (mode !== void 0 && mode !== "upsert" && mode !== "create" && mode !== "merge") return "manageCollection: `mode` must be \"upsert\" (default), \"create\", or \"merge\".";
1325
+ return {
1326
+ slug,
1327
+ items,
1328
+ mode: mode ?? "upsert"
1329
+ };
1330
+ }
1331
+ /** The machine-readable workspace ontology: every collection with its
1332
+ * identity, record count, and outbound `ref`/`embed` relations. Slugs
1333
+ * are discovery-sanitized; titles/labels are workspace-authored schema
1334
+ * text and ride verbatim — the same trust class as the record values
1335
+ * getItems returns. */
1336
+ async function handleGetOntology(deps) {
1337
+ const collections = await buildWorkspaceOntology(deps);
1338
+ return JSON.stringify({
1339
+ count: collections.length,
1340
+ collections
1341
+ });
1342
+ }
1343
+ /** Return the collection-authoring reference (`collection-skills.md`).
1344
+ * Workspace copy first (reflects user edits), bundled asset as the
1345
+ * always-present fallback. Both reads guarded; if neither resolves the
1346
+ * agent still gets an actionable message instead of a thrown call. */
1347
+ async function handleSchemaDocs(deps) {
1348
+ const candidates = [path.join(resolveBase(deps), HELPS_DIR, SCHEMA_DOCS_FILE), ...deps.bundledHelpsDir ? [path.join(deps.bundledHelpsDir(), SCHEMA_DOCS_FILE)] : []];
1349
+ for (const candidate of candidates) try {
1350
+ return await readFile(candidate, "utf-8");
1351
+ } catch {}
1352
+ return `manageCollection: could not read the collection-authoring reference (${SCHEMA_DOCS_FILE}).`;
1353
+ }
1354
+ /** Return the raw schema.json of an existing collection, for editing.
1355
+ * Staging (the canonical writable copy) first, the active mirror as a
1356
+ * fallback for user-scope skills that have no staging copy. Raw text —
1357
+ * not the parsed schema — so the agent edits the true on-disk source. */
1358
+ async function handleGetSchema(slug, deps) {
1359
+ const collection = await loadCollection(slug, deps);
1360
+ if (!collection) return unknownCollection(slug);
1361
+ const candidates = [path.join(dataSkillDir(resolveBase(deps), collection.slug), SCHEMA_FILE), path.join(collection.skillDir, SCHEMA_FILE)];
1362
+ for (const candidate of candidates) try {
1363
+ return await readFile(candidate, "utf-8");
1364
+ } catch {}
1365
+ return `manageCollection: '${defangForPrompt(slug)}' has no readable ${SCHEMA_FILE}.`;
1366
+ }
1367
+ /** Refuse a schema edit the host can't honour: user-scope/feed collections
1368
+ * are read-only, and presets (mc-*) re-seed on restart so an edit is lost. */
1369
+ function schemaEditRefusal(collection, slug) {
1370
+ if (collection.source !== "project") return `manageCollection: '${defangForPrompt(slug)}' is ${collection.source}-scope and read-only here — only project collections (data/skills/) can be edited.`;
1371
+ if (isPresetSlug(slug)) return `manageCollection: '${defangForPrompt(slug)}' is a preset (mc-*) and re-seeds on restart — copy it under a different slug to customise.`;
1372
+ return null;
1373
+ }
1374
+ /** Turn a CollectionSchemaZ failure into a short, actionable list the
1375
+ * agent can fix, pointing back at the field reference. */
1376
+ function formatSchemaIssues(issues) {
1377
+ const shown = issues.slice(0, 20);
1378
+ const lines = shown.map((issue) => `- ${issue.path.map(String).join(".") || "(root)"}: ${defangForPrompt(issue.message)}`).join("\n");
1379
+ const omitted = issues.length - shown.length;
1380
+ return `manageCollection: schema rejected — fix and retry (call schemaDocs for the field reference):\n${lines}${omitted > 0 ? `\n- …and ${omitted} more issue(s); fix these first and retry.` : ""}`;
1381
+ }
1382
+ /** Write the validated schema to the canonical staging copy, then mirror
1383
+ * it into the active `.claude/skills/` tree discovery reads — an internal
1384
+ * write doesn't fire the skill-bridge hook, so we mirror explicitly. */
1385
+ async function writeAndMirrorSchema(slug, schema, deps) {
1386
+ const base = resolveBase(deps);
1387
+ await writeFileAtomic(path.join(dataSkillDir(base, slug), SCHEMA_FILE), `${JSON.stringify(schema, null, 2)}\n`);
1388
+ mirrorSkillWrite(base, {
1389
+ slug,
1390
+ relSegments: [SCHEMA_FILE]
1391
+ });
1392
+ try {
1393
+ await deps.refreshAfterWrite?.();
1394
+ } catch {}
1395
+ }
1396
+ /** The post-Zod acceptance gates discovery applies before a parsed schema
1397
+ * becomes a live collection. Mirrors discovery's checks (`loadOneCollection`)
1398
+ * so a write can't pass here yet be silently skipped on the next load.
1399
+ * putSchema only runs for project-scope collections, so the feed-`ingest`
1400
+ * gate doesn't apply. Returns a one-line reason, or null when the schema
1401
+ * would be accepted. */
1402
+ function schemaDiscoveryGate(schema, base) {
1403
+ const primaryField = schema.fields[schema.primaryKey];
1404
+ if (!primaryField) return `primaryKey '${schema.primaryKey}' is not one of the declared fields`;
1405
+ if (primaryField.primary !== true) return `the primaryKey field '${schema.primaryKey}' must be flagged \`primary: true\``;
1406
+ if (schema.dataPath !== void 0 && resolveDataDir(schema.dataPath, base) === null) return `dataPath '${schema.dataPath}' escapes the workspace`;
1407
+ if (schema.dataSource !== void 0 && resolveDataDir(schema.dataSource.path, base) === null) return `dataSource.path '${schema.dataSource.path}' escapes the workspace`;
1408
+ return null;
1409
+ }
1410
+ /** Validate a schema against CollectionSchemaZ and, on success, persist it.
1411
+ * Edit-only: a new collection is created by writing SKILL.md + schema.json
1412
+ * under data/skills/<slug>/ (the normal create flow), not through here. */
1413
+ async function handlePutSchema(slug, schemaArg, deps) {
1414
+ if (!schemaArg || typeof schemaArg !== "object" || Array.isArray(schemaArg)) return "manageCollection: `schema` is required for putSchema — the full collection schema object.";
1415
+ const collection = await loadCollection(slug, deps);
1416
+ if (!collection) return `manageCollection: unknown collection '${defangForPrompt(slug)}' — create it by writing SKILL.md + ${SCHEMA_FILE} under data/skills/${defangForPrompt(slug)}/, then edit it here.`;
1417
+ const refusal = schemaEditRefusal(collection, slug);
1418
+ if (refusal) return refusal;
1419
+ const parsed = CollectionSchemaZ.safeParse(schemaArg);
1420
+ if (!parsed.success) return formatSchemaIssues(parsed.error.issues);
1421
+ const gate = schemaDiscoveryGate(parsed.data, resolveBase(deps));
1422
+ if (gate) return `manageCollection: schema rejected — ${gate} (call schemaDocs for the field reference). It passes basic validation but discovery would skip it, hiding the collection.`;
1423
+ await writeAndMirrorSchema(collection.slug, parsed.data, deps);
1424
+ return JSON.stringify({
1425
+ collection: collection.slug,
1426
+ written: true
1427
+ });
1428
+ }
1429
+ var MANAGE_COLLECTION_PROMPT = "Use `manageCollection` instead of raw Read/Write/Edit when working with a collection's records OR its schema (raw file I/O stays available as the escape hatch). Before authoring or changing a collection's `schema.json`, call `schemaDocs` to load the field/DSL reference, then read with `getSchema` and write with `putSchema` — `putSchema` validates the whole schema before writing and returns actionable errors instead of silently failing discovery's validation. `getItems` is the only way to see computed values — `derived` fields (e.g. a portfolio's value), `toggle` projections, and `embed` records are host-computed and never present in the stored JSON files. On large collections pass `ids` and/or `fields` to keep the result small. For a question that spans collections (\"which clients have unpaid invoices?\"), start with `getOntology`: it lists every collection with its primaryKey, record count, and outbound `ref`/`embed` relations, so you know which collections to join before reading any records. `putItems` validates every row against the schema before writing (required fields, enum values, primaryKey = record id) and returns `{ written, rejected }`; fix each rejected row using its `problem` text and retry just those rows. Never include computed fields in a row you write. To update a few fields of an existing record, use `mode: \"merge\"` with a partial row ({ id, <changed fields> }) — the default upsert replaces the WHOLE record, so a partial upsert would silently erase every optional field it omits. Answer aggregation questions (counts, sums, averages, group-bys) with `queryItems` on ANY collection — on a dataSource (CSV) collection it scans the whole file (getItems is row-capped, so aggregates computed from its output can be silently wrong on large files); on a file-backed collection it aggregates the enriched records, so computed fields (derived/rollup/toggle) are queryable columns.";
1430
+ /** Validate getItems' optional `ids`/`fields` args, then delegate. */
1431
+ async function dispatchGetItems(collection, args, deps) {
1432
+ const ids = optionalStringArray(args.ids, "ids");
1433
+ if (!ids.ok) return ids.error;
1434
+ const fields = optionalStringArray(args.fields, "fields");
1435
+ if (!fields.ok) return fields.error;
1436
+ return handleGetItems(collection, {
1437
+ slug: collection.slug,
1438
+ ids: ids.value,
1439
+ fields: fields.value
1440
+ }, deps);
1441
+ }
1442
+ async function manageCollectionHandler(deps, args) {
1443
+ const action = typeof args.action === "string" ? args.action : "";
1444
+ if (action === "schemaDocs") return handleSchemaDocs(deps);
1445
+ if (action === "getOntology") return handleGetOntology(deps);
1446
+ const slug = typeof args.slug === "string" ? args.slug.trim() : "";
1447
+ if (!slug) return "manageCollection: `slug` is required (the collection's slug).";
1448
+ if (action === "getSchema") return handleGetSchema(slug, deps);
1449
+ if (action === "putSchema") return handlePutSchema(slug, args.schema, deps);
1450
+ if (action !== "getItems" && action !== "putItems" && action !== "queryItems") return "manageCollection: `action` must be \"getItems\", \"putItems\", \"queryItems\", \"getOntology\", \"schemaDocs\", \"getSchema\", or \"putSchema\".";
1451
+ const collection = await loadCollection(slug, deps);
1452
+ if (!collection) return unknownCollection(slug);
1453
+ if (action === "getItems") return dispatchGetItems(collection, args, deps);
1454
+ if (action === "queryItems") return handleQueryItems(collection, args.query, deps);
1455
+ const parsed = parsePutItems(args, slug);
1456
+ if (typeof parsed === "string") return parsed;
1457
+ return handlePutItems(collection, parsed, deps);
1458
+ }
1459
+ var MANAGE_COLLECTION_DEFINITION = {
1460
+ name: "manageCollection",
1461
+ description: "Read and write a schema-driven collection through the host — both its records and its structure. getItems returns records WITH computed values (derived formulas, toggles, embeds) the stored JSON files don't contain; putItems validates each row against the schema before writing. getOntology maps the whole workspace: every collection with its record count and outbound ref/embed relations — call it first for cross-collection questions. schemaDocs returns the collection-authoring reference; getSchema/putSchema read and validate-then-write the collection's schema.json. Prefer it over raw file I/O on collections.",
1462
+ inputSchema: {
1463
+ type: "object",
1464
+ properties: {
1465
+ action: {
1466
+ type: "string",
1467
+ enum: [
1468
+ "getItems",
1469
+ "putItems",
1470
+ "queryItems",
1471
+ "getOntology",
1472
+ "schemaDocs",
1473
+ "getSchema",
1474
+ "putSchema"
1475
+ ],
1476
+ description: "What to do."
1477
+ },
1478
+ slug: {
1479
+ type: "string",
1480
+ description: "The collection's slug (its directory name, e.g. `stock-quotes`). Required for everything except schemaDocs and getOntology."
1481
+ },
1482
+ ids: {
1483
+ type: "array",
1484
+ items: { type: "string" },
1485
+ description: "getItems: only these record ids (primary-key values). Omit for all records."
1486
+ },
1487
+ fields: {
1488
+ type: "array",
1489
+ items: { type: "string" },
1490
+ description: "getItems: only these fields per record (the primary key is always included). Omit for all fields. Use on large collections."
1491
+ },
1492
+ items: {
1493
+ type: "array",
1494
+ items: { type: "object" },
1495
+ description: "putItems: the record objects to store. Each must carry the schema's primaryKey value (it doubles as the filename)."
1496
+ },
1497
+ mode: {
1498
+ type: "string",
1499
+ enum: [
1500
+ "upsert",
1501
+ "create",
1502
+ "merge"
1503
+ ],
1504
+ description: "putItems: \"upsert\" (default) replaces existing records WHOLE; \"create\" rejects rows whose id already exists; \"merge\" updates only the fields a row carries, keeping the rest of the existing record (rejects unknown ids). Use \"merge\" when changing a few fields."
1505
+ },
1506
+ schema: {
1507
+ type: "object",
1508
+ description: "putSchema: the full collection schema object (same shape as schema.json — title, icon, dataPath, primaryKey, fields, …). Call getSchema first for the current one, and schemaDocs for the field DSL."
1509
+ },
1510
+ query: {
1511
+ type: "object",
1512
+ description: "queryItems: a structured aggregation query — `{ groupBy?: [\"col\"], aggregates?: { alias: { op: \"count\"|\"sum\"|\"avg\"|\"min\"|\"max\", column? } }, where?: [{ field, op, value }], orderBy?: [{ field, dir? }], limit? }`. At least one of groupBy/aggregates. On a dataSource (CSV) collection it scans the WHOLE file uncapped (unlike getItems); on a file-backed collection it aggregates the ENRICHED records, so computed fields (derived/rollup/toggle) are queryable columns. Use it for counts / sums / averages / group-bys instead of arithmetic over getItems output."
1513
+ }
1514
+ },
1515
+ required: ["action"]
1516
+ }
1517
+ };
1518
+ function makeManageCollectionTool(deps = {}) {
1519
+ return {
1520
+ definition: MANAGE_COLLECTION_DEFINITION,
1521
+ alwaysActive: true,
1522
+ prompt: MANAGE_COLLECTION_PROMPT,
1523
+ handler: (args) => manageCollectionHandler(deps, args)
1524
+ };
1525
+ }
1526
+ //#endregion
1527
+ export { validateCollectionRecords as C, runCollectionQuery as D, recordFieldProblem as E, enrichItems as O, firstMutateParamProblem as S, compileRecordZ as T, errorMessage as _, deleteCollection as a, schemaRelations as b, computeSuccessor as c, isTriggerDue as d, maybeSpawnSuccessor as f, ONE_SECOND_MS as g, successorId as h, deleteCustomView as i, runQueryOverRows as k, daysInMonth as l, resolveEvery as m, MAX_UNSELECTIVE_ITEMS as n, deleteCollectionRefusalMessage as o, parseCivil as p, makeManageCollectionTool as r, advanceTriggerDate as s, MAX_SCHEMA_ISSUES as t, formatCivil as u, computeCollectionIcon as v, validateRecordObject as w, applyMutateAction as x, buildWorkspaceOntology as y };
1528
+
1529
+ //# sourceMappingURL=server-BI3wnTwl.js.map