@mulmoclaude/core 0.23.0 → 0.23.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.
@@ -795,17 +795,18 @@ function whereFragment(cond) {
795
795
  params: [cond.value]
796
796
  };
797
797
  }
798
- /** Compile a validated query. Returns the SQL (whose FIRST placeholder is
799
- * the CSV path — the executor binds it) and the where-value parameters
800
- * that follow it. Callers MUST have run `CollectionQueryZ` first; this
801
- * function trusts the shape (aliases already charset-checked, orderBy
802
- * membership already enforced). */
803
- function compileCsvQuery(query, primaryKey) {
798
+ /** Compile a validated query against `fromSql` (a table-function call
799
+ * whose FIRST placeholder is the source path — the executor binds it).
800
+ * Returns the SQL and the where-value parameters that follow the path.
801
+ * Callers MUST have run `CollectionQueryZ` first; this function trusts
802
+ * the shape (aliases already charset-checked, orderBy membership already
803
+ * enforced). */
804
+ function compileQuery(query, fromSql) {
804
805
  const groupBy = query.groupBy ?? [];
805
806
  const aggregates = Object.entries(query.aggregates ?? {});
806
807
  const selectList = [...groupBy.map(quoteIdent), ...aggregates.map(([alias, aggregate]) => `${aggregateExpr(aggregate)} AS ${quoteIdent(alias)}`)];
807
808
  const where = (query.where ?? []).map(whereFragment);
808
- const clauses = [`SELECT ${selectList.join(", ")}`, `FROM read_csv(${readCsvArgs(primaryKey)})`];
809
+ const clauses = [`SELECT ${selectList.join(", ")}`, `FROM ${fromSql}`];
809
810
  if (where.length > 0) clauses.push(`WHERE ${where.map((fragment) => fragment.sql).join(" AND ")}`);
810
811
  if (groupBy.length > 0) clauses.push(`GROUP BY ${groupBy.map(quoteIdent).join(", ")}`);
811
812
  const orderBy = (query.orderBy ?? []).map((order) => quoteIdent(order.field) + (order.dir === "desc" ? " DESC" : " ASC"));
@@ -816,6 +817,21 @@ function compileCsvQuery(query, primaryKey) {
816
817
  params: where.flatMap((fragment) => fragment.params)
817
818
  };
818
819
  }
820
+ /** Compile against a CSV file (the dataSource store's engine). */
821
+ function compileCsvQuery(query, primaryKey) {
822
+ return compileQuery(query, `read_csv(${readCsvArgs(primaryKey)})`);
823
+ }
824
+ /** Compile against a JSONL file of ENRICHED records — the file-backed
825
+ * collections' engine (see `jsonlQuery.ts`). No VARCHAR key pin needed:
826
+ * enriched record ids are already strings. `sample_size=-1` makes the
827
+ * schema inference scan EVERY line — with the default sample, a sparse
828
+ * optional/derived field first appearing past the sample would not be
829
+ * inferred as a column and the query would binder-error on it (Codex P2
830
+ * on #2165). The full scan costs nothing extra here: aggregation reads
831
+ * the whole file anyway. */
832
+ function compileJsonlQuery(query) {
833
+ return compileQuery(query, `read_json(?, format='newline_delimited', sample_size=-1)`);
834
+ }
819
835
  //#endregion
820
836
  //#region src/collection/server/csvStore.ts
821
837
  /** `list()` row cap. Over-cap files are truncated with a warn — the v1
@@ -1136,6 +1152,74 @@ function storeFor(collection, opts = {}) {
1136
1152
  };
1137
1153
  }
1138
1154
  //#endregion
1155
+ //#region src/collection/server/jsonlQuery.ts
1156
+ /** SQL semantics for an aggregate-only query over ZERO rows: one scalar
1157
+ * row (`count` = 0, everything else NULL) — the same shape the CSV path
1158
+ * produces for a header-only file, so callers reading `rows[0]` never
1159
+ * break on storage kind or emptiness. A grouped query over zero rows is
1160
+ * zero groups (`[]`), also matching SQL. Synthesized here because DuckDB
1161
+ * has no empty file to infer a schema from. */
1162
+ function emptyCollectionResult(query) {
1163
+ if ((query.groupBy?.length ?? 0) > 0) return [];
1164
+ const aggregates = Object.entries(query.aggregates ?? {});
1165
+ return [Object.fromEntries(aggregates.map(([alias, aggregate]) => [alias, aggregate.op === "count" ? 0 : null]))];
1166
+ }
1167
+ /** The SOURCE columns a query reads: groupBy columns, aggregate input
1168
+ * columns, and where fields. (orderBy resolves to groupBy columns or
1169
+ * aggregate ALIASES — never to a new source column — so it adds none.) */
1170
+ function referencedSourceColumns(query) {
1171
+ const columns = new Set(query.groupBy ?? []);
1172
+ for (const aggregate of Object.values(query.aggregates ?? {})) if (aggregate.column !== void 0) columns.add(aggregate.column);
1173
+ for (const cond of query.where ?? []) columns.add(cond.field);
1174
+ return [...columns];
1175
+ }
1176
+ /** Referenced columns that appear in NO row — a freshly-added optional
1177
+ * field, or a derived field whose inputs no record has yet. DuckDB only
1178
+ * infers columns from keys that occur in the JSONL, so without help a
1179
+ * valid query on such a field binder-errors here while the CSV path
1180
+ * (whose header always declares the column) returns NULLs. Padding the
1181
+ * FIRST line with `col: null` makes the column exist (full-scan
1182
+ * inference unions keys across lines) with matching NULL semantics. */
1183
+ function absentReferencedColumns(rows, query) {
1184
+ const present = /* @__PURE__ */ new Set();
1185
+ for (const row of rows) for (const key of Object.keys(row)) present.add(key);
1186
+ return referencedSourceColumns(query).filter((column) => !present.has(column));
1187
+ }
1188
+ /** Run a validated query over enriched collection rows. */
1189
+ async function runQueryOverRows(rows, query) {
1190
+ if (rows.length === 0) return emptyCollectionResult(query);
1191
+ await (0, node_fs_promises.mkdir)(cacheDir(), {
1192
+ recursive: true,
1193
+ mode: 448
1194
+ });
1195
+ const jsonlPath = node_path.default.join(cacheDir(), `q-${(0, node_crypto.randomBytes)(8).toString("hex")}.jsonl`);
1196
+ try {
1197
+ const nullPads = Object.fromEntries(absentReferencedColumns(rows, query).map((column) => [column, null]));
1198
+ const handle = await (0, node_fs_promises.open)(jsonlPath, "wx", 384);
1199
+ try {
1200
+ let first = true;
1201
+ for (const row of rows) {
1202
+ await handle.write(`${JSON.stringify(first ? {
1203
+ ...nullPads,
1204
+ ...row
1205
+ } : row)}\n`);
1206
+ first = false;
1207
+ }
1208
+ } finally {
1209
+ await handle.close();
1210
+ }
1211
+ const { sql, params } = compileJsonlQuery(query);
1212
+ return (await queryCsv(sql, [jsonlPath, ...params])).map((row) => Object.fromEntries(Object.entries(row).map(([key, value]) => [key, normalizeCsvValue(value)])));
1213
+ } finally {
1214
+ await (0, node_fs_promises.unlink)(jsonlPath).catch((err) => {
1215
+ if (err.code !== "ENOENT") log.warn("collections", "temp JSONL cleanup failed", {
1216
+ path: jsonlPath,
1217
+ error: String(err)
1218
+ });
1219
+ });
1220
+ }
1221
+ }
1222
+ //#endregion
1139
1223
  //#region src/collection/core/recordZ.ts
1140
1224
  /** The emptiness rule shared by `required` and the "only check present
1141
1225
  * values" gate. NOT a truthiness check — `0` and `false` are filled. */
@@ -3176,17 +3260,27 @@ async function putOneItem(collection, record, mode, deps) {
3176
3260
  if (result.kind === "conflict") return reject(itemId, `'${itemId}' already exists — mode "create" refuses overwrite; use "upsert" to update it`);
3177
3261
  return reject(itemId, "write refused: the collection's data dir escapes the workspace");
3178
3262
  }
3179
- /** Aggregation over a dataSource collection's WHOLE file via the
3180
- * structured query DSL (`core/queryZ.ts`) — the paved road for counts /
3181
- * sums / group-bys that `getItems` (row-capped, unaggregated) can't
3182
- * answer honestly. File-backed collections have no query engine yet:
3183
- * refuse with a pointer instead of silently emulating. */
3263
+ /** Aggregation over a collection via the structured query DSL
3264
+ * (`core/queryZ.ts`) — the paved road for counts / sums / group-bys
3265
+ * that a row listing can't answer honestly. Two engines behind one
3266
+ * shape: a dataSource collection queries its CSV natively through the
3267
+ * store (`store.query`, uncapped whole-file scan); a file-backed
3268
+ * collection aggregates its ENRICHED records (computed fields —
3269
+ * `derived` / `rollup` / `toggle` — are real columns) through the same
3270
+ * compiled SQL over a temp JSONL (`runQueryOverRows`). */
3184
3271
  async function handleQueryItems(collection, queryArg, deps) {
3185
- const store = storeFor(collection, { workspaceRoot: deps.workspaceRoot });
3186
- if (!store.query) return `manageCollection: '${collection.slug}' is file-backed — queryItems currently supports only dataSource (CSV) collections; use getItems (with \`fields\`) instead.`;
3187
3272
  const parsed = CollectionQueryZ.safeParse(queryArg);
3188
3273
  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)"}: ${require_promptSafety.defangForPrompt(issue.message)}`).join("\n")}`;
3189
- const rows = await store.query(parsed.data);
3274
+ const store = storeFor(collection, { workspaceRoot: deps.workspaceRoot });
3275
+ if (store.query) {
3276
+ const rows = await store.query(parsed.data);
3277
+ return JSON.stringify({
3278
+ collection: collection.slug,
3279
+ count: rows.length,
3280
+ rows
3281
+ });
3282
+ }
3283
+ const rows = await runQueryOverRows(await enrichItems(collection, await store.list(), deps), parsed.data);
3190
3284
  return JSON.stringify({
3191
3285
  collection: collection.slug,
3192
3286
  count: rows.length,
@@ -3316,7 +3410,7 @@ async function handlePutSchema(slug, schemaArg, deps) {
3316
3410
  written: true
3317
3411
  });
3318
3412
  }
3319
- 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. On a dataSource (CSV) collection, answer aggregation questions (counts, sums, averages, group-bys) with `queryItems` — it scans the WHOLE file, while getItems is row-capped, so an aggregate computed from getItems output can be silently wrong on large files.";
3413
+ 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.";
3320
3414
  /** Validate getItems' optional `ids`/`fields` args, then delegate. */
3321
3415
  async function dispatchGetItems(collection, args, deps) {
3322
3416
  const ids = optionalStringArray(args.ids, "ids");
@@ -3399,7 +3493,7 @@ var MANAGE_COLLECTION_DEFINITION = {
3399
3493
  },
3400
3494
  query: {
3401
3495
  type: "object",
3402
- description: "queryItems (dataSource/CSV collections only): a structured aggregation query over the WHOLE file — `{ 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. Runs uncapped over the full file (unlike getItems), so use it for counts / sums / group-bys on large CSVs."
3496
+ 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."
3403
3497
  }
3404
3498
  },
3405
3499
  required: ["action"]
@@ -3522,6 +3616,12 @@ Object.defineProperty(exports, "compileCsvQuery", {
3522
3616
  return compileCsvQuery;
3523
3617
  }
3524
3618
  });
3619
+ Object.defineProperty(exports, "compileJsonlQuery", {
3620
+ enumerable: true,
3621
+ get: function() {
3622
+ return compileJsonlQuery;
3623
+ }
3624
+ });
3525
3625
  Object.defineProperty(exports, "compileRecordZ", {
3526
3626
  enumerable: true,
3527
3627
  get: function() {
@@ -3786,6 +3886,12 @@ Object.defineProperty(exports, "resolveTemplatePath", {
3786
3886
  return resolveTemplatePath;
3787
3887
  }
3788
3888
  });
3889
+ Object.defineProperty(exports, "runQueryOverRows", {
3890
+ enumerable: true,
3891
+ get: function() {
3892
+ return runQueryOverRows;
3893
+ }
3894
+ });
3789
3895
  Object.defineProperty(exports, "safeRecordId", {
3790
3896
  enumerable: true,
3791
3897
  get: function() {
@@ -3859,4 +3965,4 @@ Object.defineProperty(exports, "writeItem", {
3859
3965
  }
3860
3966
  });
3861
3967
 
3862
- //# sourceMappingURL=server-Q7ld-FlZ.cjs.map
3968
+ //# sourceMappingURL=server-Jaogu3Ky.cjs.map