@mulmoclaude/core 0.22.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/assets/helps/collection-skills.md +102 -1
  2. package/assets/helps/custom-view.md +34 -0
  3. package/assets/helps/error-recovery.md +36 -0
  4. package/assets/helps/mulmoscript.md +2 -0
  5. package/dist/collection/core/queryZ.d.ts +90 -0
  6. package/dist/collection/core/schema.d.ts +14 -1
  7. package/dist/collection/core/schemaZ.d.ts +18 -1
  8. package/dist/collection/index.cjs +3 -2
  9. package/dist/collection/index.cjs.map +1 -1
  10. package/dist/collection/index.d.ts +1 -0
  11. package/dist/collection/index.js +3 -3
  12. package/dist/collection/index.js.map +1 -1
  13. package/dist/collection/registry/server/index.cjs +12 -4
  14. package/dist/collection/registry/server/index.cjs.map +1 -1
  15. package/dist/collection/registry/server/index.js +12 -4
  16. package/dist/collection/registry/server/index.js.map +1 -1
  17. package/dist/collection/server/csvQuery.d.ts +19 -0
  18. package/dist/collection/server/csvStore.d.ts +49 -0
  19. package/dist/collection/server/discoveredCollection.d.ts +9 -1
  20. package/dist/collection/server/discovery.d.ts +7 -3
  21. package/dist/collection/server/index.cjs +15 -2
  22. package/dist/collection/server/index.d.ts +5 -0
  23. package/dist/collection/server/index.js +3 -3
  24. package/dist/collection/server/manageTool.d.ts +4 -0
  25. package/dist/collection/server/store.d.ts +31 -0
  26. package/dist/collection-watchers/index.cjs +104 -3
  27. package/dist/collection-watchers/index.cjs.map +1 -1
  28. package/dist/collection-watchers/index.js +102 -3
  29. package/dist/collection-watchers/index.js.map +1 -1
  30. package/dist/feeds/index.cjs +2 -2
  31. package/dist/feeds/index.js +2 -2
  32. package/dist/feeds/server/index.cjs +3 -3
  33. package/dist/feeds/server/index.js +3 -3
  34. package/dist/google/auth.d.ts +8 -2
  35. package/dist/google/calendar.d.ts +44 -0
  36. package/dist/google/index.cjs +86 -9
  37. package/dist/google/index.cjs.map +1 -1
  38. package/dist/google/index.d.ts +2 -2
  39. package/dist/google/index.js +82 -10
  40. package/dist/google/index.js.map +1 -1
  41. package/dist/{ingestTypes-DEjpiZGM.js → ingestTypes-B-dXxUF9.js} +2 -2
  42. package/dist/{ingestTypes-DEjpiZGM.js.map → ingestTypes-B-dXxUF9.js.map} +1 -1
  43. package/dist/{ingestTypes-Dh5lniBL.cjs → ingestTypes-Cev9q77C.cjs} +2 -2
  44. package/dist/{ingestTypes-Dh5lniBL.cjs.map → ingestTypes-Cev9q77C.cjs.map} +1 -1
  45. package/dist/{promptSafety-DN5V__Ku.cjs → promptSafety-DRd15gQ6.cjs} +15 -1
  46. package/dist/promptSafety-DRd15gQ6.cjs.map +1 -0
  47. package/dist/{promptSafety-DyG3EuC7.js → promptSafety-rDWA9_JS.js} +10 -2
  48. package/dist/promptSafety-rDWA9_JS.js.map +1 -0
  49. package/dist/{server-Bd8l1bhv.js → server--FgDORd3.js} +678 -79
  50. package/dist/server--FgDORd3.js.map +1 -0
  51. package/dist/{server-Bh-DPK-H.cjs → server-Q7ld-FlZ.cjs} +754 -76
  52. package/dist/server-Q7ld-FlZ.cjs.map +1 -0
  53. package/package.json +3 -1
  54. package/dist/promptSafety-DN5V__Ku.cjs.map +0 -1
  55. package/dist/promptSafety-DyG3EuC7.js.map +0 -1
  56. package/dist/server-Bd8l1bhv.js.map +0 -1
  57. package/dist/server-Bh-DPK-H.cjs.map +0 -1
@@ -1,5 +1,5 @@
1
1
  const require_rolldown_runtime = require("./rolldown-runtime-D6vf50IK.cjs");
2
- const require_promptSafety = require("./promptSafety-DN5V__Ku.cjs");
2
+ const require_promptSafety = require("./promptSafety-DRd15gQ6.cjs");
3
3
  const require_collection_paths = require("./collection/paths.cjs");
4
4
  const require_skill_bridge_index = require("./skill-bridge/index.cjs");
5
5
  let node_path = require("node:path");
@@ -7,6 +7,9 @@ node_path = require_rolldown_runtime.__toESM(node_path, 1);
7
7
  let node_fs = require("node:fs");
8
8
  let node_fs_promises = require("node:fs/promises");
9
9
  let node_crypto = require("node:crypto");
10
+ let node_os = require("node:os");
11
+ let iconv_lite = require("iconv-lite");
12
+ iconv_lite = require_rolldown_runtime.__toESM(iconv_lite, 1);
10
13
  let zod = require("zod");
11
14
  //#region src/collection/server/host.ts
12
15
  var current = null;
@@ -574,7 +577,7 @@ function promptPathsFor(collection, workspaceRoot) {
574
577
  const skillDir = (rel === "" || rel.startsWith("..") ? collection.skillDir : rel).split(node_path.default.sep).join("/");
575
578
  return {
576
579
  slug: collection.slug,
577
- dataPath: collection.schema.dataPath,
580
+ dataPath: collection.schema.dataPath ?? collection.schema.dataSource?.path ?? "",
578
581
  skillDir
579
582
  };
580
583
  }
@@ -637,6 +640,502 @@ ${dataJson}
637
640
  ${templateText}`;
638
641
  }
639
642
  //#endregion
643
+ //#region src/collection/core/queryZ.ts
644
+ /** Result-column aliases double as SQL identifiers and JSON keys — keep
645
+ * them to a conservative identifier charset so neither side needs
646
+ * escaping gymnastics. */
647
+ var SAFE_ALIAS_PATTERN = /^[A-Za-z_]\w{0,63}$/;
648
+ /** Hard ceiling on returned rows; `limit` clamps below it. A group-by on
649
+ * a near-unique column would otherwise return one row per source row —
650
+ * the exact materialization the aggregate path exists to avoid. */
651
+ var MAX_QUERY_ROWS = 1e4;
652
+ /** Default row cap when the query declares no `limit`. */
653
+ var DEFAULT_QUERY_ROWS = 1e3;
654
+ /** One aggregate column: `count` (rows; `column` optional to count
655
+ * non-null cells) or `sum`/`avg`/`min`/`max` over a named CSV column. */
656
+ var QueryAggregateZ = zod.z.object({
657
+ op: zod.z.enum([
658
+ "count",
659
+ "sum",
660
+ "avg",
661
+ "min",
662
+ "max"
663
+ ]),
664
+ column: zod.z.string().min(1).optional()
665
+ }).refine((aggregate) => aggregate.op === "count" || aggregate.column !== void 0, {
666
+ message: "`column` is required for every aggregate op except `count`",
667
+ path: ["column"]
668
+ });
669
+ /** One filter condition. Same op vocabulary as the schema-level `where`
670
+ * (`core/where.ts`) so authors learn one set; values may be typed
671
+ * (number / boolean) since CSV columns are. `in` requires an array
672
+ * value, every other op a scalar. */
673
+ var QueryWhereZ = zod.z.object({
674
+ field: zod.z.string().min(1),
675
+ op: zod.z.enum([
676
+ "eq",
677
+ "ne",
678
+ "in",
679
+ "gt",
680
+ "gte",
681
+ "lt",
682
+ "lte",
683
+ "contains"
684
+ ]),
685
+ value: zod.z.union([
686
+ zod.z.string(),
687
+ zod.z.number(),
688
+ zod.z.boolean(),
689
+ zod.z.array(zod.z.union([
690
+ zod.z.string(),
691
+ zod.z.number(),
692
+ zod.z.boolean()
693
+ ])).min(1).max(100)
694
+ ])
695
+ }).refine((cond) => cond.op === "in" === Array.isArray(cond.value), {
696
+ message: "`in` requires an array value (the allowed set); every other op requires a scalar value",
697
+ path: ["value"]
698
+ });
699
+ var QueryOrderZ = zod.z.object({
700
+ /** A `groupBy` column or an aggregate alias — membership enforced by
701
+ * the whole-query refine below. */
702
+ field: zod.z.string().min(1),
703
+ dir: zod.z.enum(["asc", "desc"]).optional()
704
+ });
705
+ /** The whole query. At least one of `groupBy` / `aggregates` must be
706
+ * present: bare `groupBy` is a DISTINCT listing, bare `aggregates` a
707
+ * whole-file scalar row, together a grouped aggregation. */
708
+ var CollectionQueryZ = zod.z.object({
709
+ groupBy: zod.z.array(zod.z.string().min(1)).max(8).refine((columns) => new Set(columns.map((column) => column.toLowerCase())).size === columns.length, { message: "`groupBy` columns must be unique (case-insensitively — SQL identifiers ignore case)" }).optional(),
710
+ aggregates: zod.z.record(zod.z.string().regex(SAFE_ALIAS_PATTERN, "aggregate aliases must be simple identifiers (letters/digits/underscore)"), QueryAggregateZ).optional(),
711
+ where: zod.z.array(QueryWhereZ).max(16).optional(),
712
+ orderBy: zod.z.array(QueryOrderZ).max(4).optional(),
713
+ limit: zod.z.number().int().min(1).max(MAX_QUERY_ROWS).optional()
714
+ }).refine((query) => (query.groupBy?.length ?? 0) > 0 || Object.keys(query.aggregates ?? {}).length > 0, {
715
+ message: "declare at least one of `groupBy` (columns to bucket by) or `aggregates` (values to compute)",
716
+ path: ["groupBy"]
717
+ }).refine((query) => Object.keys(query.aggregates ?? {}).length <= 32, {
718
+ message: `\`aggregates\` supports at most 32 entries`,
719
+ path: ["aggregates"]
720
+ }).refine((query) => {
721
+ const groupLower = new Set((query.groupBy ?? []).map((column) => column.toLowerCase()));
722
+ const seen = /* @__PURE__ */ new Set();
723
+ return Object.keys(query.aggregates ?? {}).every((alias) => {
724
+ const lower = alias.toLowerCase();
725
+ if (groupLower.has(lower) || seen.has(lower)) return false;
726
+ seen.add(lower);
727
+ return true;
728
+ });
729
+ }, {
730
+ message: "aggregate aliases must be unique and must not collide with `groupBy` column names (case-insensitively — SQL identifiers ignore case)",
731
+ path: ["aggregates"]
732
+ }).refine((query) => {
733
+ const sortable = /* @__PURE__ */ new Set([...query.groupBy ?? [], ...Object.keys(query.aggregates ?? {})]);
734
+ return (query.orderBy ?? []).every((order) => sortable.has(order.field));
735
+ }, {
736
+ message: "every `orderBy.field` must be a `groupBy` column or an aggregate alias",
737
+ path: ["orderBy"]
738
+ });
739
+ //#endregion
740
+ //#region src/collection/server/csvQuery.ts
741
+ /** Double-quote a SQL identifier (CSV column name / result alias). */
742
+ function quoteIdent(name) {
743
+ return `"${name.replaceAll("\"", "\"\"")}"`;
744
+ }
745
+ /** Single-quote a SQL string literal (a `types={...}` struct key). */
746
+ function quoteLiteral(value) {
747
+ return `'${value.replaceAll("'", "''")}'`;
748
+ }
749
+ /** The `read_csv` argument list shared by every CSV query: the (prepared)
750
+ * path plus a `types` pin forcing the key column to VARCHAR — without it
751
+ * DuckDB's sniffer turns `001` into BIGINT 1, so leading zeros vanish
752
+ * and distinct keys collapse. */
753
+ function readCsvArgs(primaryKey) {
754
+ return `?, types={${quoteLiteral(primaryKey)}: 'VARCHAR'}`;
755
+ }
756
+ /** One aggregate's SQL expression. `sum`/`avg` TRY_CAST to DOUBLE so a
757
+ * column the sniffer kept as VARCHAR (mixed values) aggregates over its
758
+ * numeric cells instead of erroring; non-numeric cells become NULL and
759
+ * are skipped — standard BI tolerance. `min`/`max` stay native (they are
760
+ * meaningful on strings and dates too). */
761
+ function aggregateExpr(aggregate) {
762
+ const { op, column } = aggregate;
763
+ if (op === "count") return column === void 0 ? "count(*)" : `count(${quoteIdent(column)})`;
764
+ if (op === "sum" || op === "avg") return `${op}(TRY_CAST(${quoteIdent(column ?? "")} AS DOUBLE))`;
765
+ return `${op}(${quoteIdent(column ?? "")})`;
766
+ }
767
+ /** One where condition → SQL fragment + its bound parameters. String
768
+ * equality compares against `CAST(col AS VARCHAR)` so a sniffer-typed
769
+ * column still matches its textual value; numeric/boolean values compare
770
+ * natively (DuckDB coerces the column side). */
771
+ function whereFragment(cond) {
772
+ const column = quoteIdent(cond.field);
773
+ const asText = `CAST(${column} AS VARCHAR)`;
774
+ if (cond.op === "in") {
775
+ const values = cond.value;
776
+ return {
777
+ sql: `${values.every((value) => typeof value === "string") ? asText : column} IN (${values.map(() => "?").join(", ")})`,
778
+ params: values
779
+ };
780
+ }
781
+ if (cond.op === "contains") return {
782
+ sql: `contains(${asText}, ?)`,
783
+ params: [String(cond.value)]
784
+ };
785
+ const operator = {
786
+ eq: "=",
787
+ ne: "<>",
788
+ gt: ">",
789
+ gte: ">=",
790
+ lt: "<",
791
+ lte: "<="
792
+ }[cond.op];
793
+ return {
794
+ sql: `${typeof cond.value === "string" && (cond.op === "eq" || cond.op === "ne") ? asText : column} ${operator} ?`,
795
+ params: [cond.value]
796
+ };
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) {
804
+ const groupBy = query.groupBy ?? [];
805
+ const aggregates = Object.entries(query.aggregates ?? {});
806
+ const selectList = [...groupBy.map(quoteIdent), ...aggregates.map(([alias, aggregate]) => `${aggregateExpr(aggregate)} AS ${quoteIdent(alias)}`)];
807
+ const where = (query.where ?? []).map(whereFragment);
808
+ const clauses = [`SELECT ${selectList.join(", ")}`, `FROM read_csv(${readCsvArgs(primaryKey)})`];
809
+ if (where.length > 0) clauses.push(`WHERE ${where.map((fragment) => fragment.sql).join(" AND ")}`);
810
+ if (groupBy.length > 0) clauses.push(`GROUP BY ${groupBy.map(quoteIdent).join(", ")}`);
811
+ const orderBy = (query.orderBy ?? []).map((order) => quoteIdent(order.field) + (order.dir === "desc" ? " DESC" : " ASC"));
812
+ if (orderBy.length > 0) clauses.push(`ORDER BY ${orderBy.join(", ")}`);
813
+ clauses.push(`LIMIT ${query.limit ?? 1e3}`);
814
+ return {
815
+ sql: clauses.join(" "),
816
+ params: where.flatMap((fragment) => fragment.params)
817
+ };
818
+ }
819
+ //#endregion
820
+ //#region src/collection/server/csvStore.ts
821
+ /** `list()` row cap. Over-cap files are truncated with a warn — the v1
822
+ * contract is "browse + per-record views", not full-table analytics. */
823
+ var MAX_CSV_ROWS = 5e3;
824
+ /** Record ids minted from non-safe key values: `id0x` + utf-8 hex. Raw key
825
+ * values that themselves match this pattern are ALSO encoded, so the
826
+ * encoded namespace never collides with a raw value (injective mapping). */
827
+ var ENCODED_ID_PATTERN = /^id0x([0-9a-f]+)$/;
828
+ /** A CSV key value → the record id it's addressed by. Safe values pass
829
+ * through untouched; everything else (and anything shaped like an encoded
830
+ * id) becomes `id0x<hex>`. Pure + exported for unit tests. */
831
+ function encodeCsvRecordId(rawKey) {
832
+ if (safeRecordId(rawKey) === rawKey && !ENCODED_ID_PATTERN.test(rawKey)) return rawKey;
833
+ return `id0x${Buffer.from(rawKey, "utf-8").toString("hex")}`;
834
+ }
835
+ /** A record id → the CSV key value to look up. Inverse of
836
+ * `encodeCsvRecordId` for encoded ids; anything else is already the raw
837
+ * value. Pure + exported for unit tests. */
838
+ function decodeCsvRecordId(itemId) {
839
+ const match = ENCODED_ID_PATTERN.exec(itemId);
840
+ if (!match) return itemId;
841
+ return Buffer.from(match[1], "hex").toString("utf-8");
842
+ }
843
+ /** Normalize one DuckDB JS value into a JSON-safe record value: BigInt →
844
+ * number (string beyond the safe range), DATE/TIMESTAMP → ISO string
845
+ * (date-only when the clock is exactly UTC midnight, matching the `date`
846
+ * field contract), exotic DuckDB values → their string form. Pure +
847
+ * exported for unit tests. */
848
+ function normalizeCsvValue(value) {
849
+ if (typeof value === "bigint") return value <= BigInt(Number.MAX_SAFE_INTEGER) && value >= BigInt(-Number.MAX_SAFE_INTEGER) ? Number(value) : value.toString();
850
+ if (value instanceof Date) {
851
+ const iso = value.toISOString();
852
+ return iso.endsWith("T00:00:00.000Z") ? iso.slice(0, 10) : iso;
853
+ }
854
+ if (value !== null && typeof value === "object") return String(value);
855
+ return value;
856
+ }
857
+ /** One raw DuckDB row → a CollectionItem, or null when the key cell is
858
+ * missing/empty (the row can't be addressed). The primaryKey field is
859
+ * OVERWRITTEN with the (possibly encoded) record id so `item[primaryKey]`
860
+ * and the record's address never drift — same invariant the file store's
861
+ * write path enforces. Pure + exported for unit tests. */
862
+ function csvRowToItem(row, primaryKey) {
863
+ const normalized = Object.fromEntries(Object.entries(row).map(([key, value]) => [key, normalizeCsvValue(value)]));
864
+ const rawKey = normalized[primaryKey];
865
+ if (rawKey === null || rawKey === void 0 || String(rawKey) === "") return null;
866
+ return {
867
+ ...normalized,
868
+ [primaryKey]: encodeCsvRecordId(String(rawKey))
869
+ };
870
+ }
871
+ /** Dedupe by record id, LAST row wins (matches `csvRead`'s last-match
872
+ * pick). Returns the surviving items in first-seen order. Pure +
873
+ * exported for unit tests. */
874
+ function dedupeByRecordId(items, primaryKey) {
875
+ const byId = /* @__PURE__ */ new Map();
876
+ for (const item of items) byId.set(String(item[primaryKey]), item);
877
+ return {
878
+ items: [...byId.values()],
879
+ duplicates: items.length - byId.size
880
+ };
881
+ }
882
+ /** True when a thrown DuckDB error is the `types` pin naming a column the
883
+ * CSV doesn't have — the schema/file-mismatch case the caller downgrades
884
+ * to "empty collection + warn" instead of a 500. */
885
+ function isMissingKeyColumnError(err) {
886
+ return String(err).includes("do not exist in the CSV");
887
+ }
888
+ /** Bytes sniffed for UTF-8 validity. The trailing 3 bytes of the sample
889
+ * are dropped so a multibyte char split at the boundary can't produce a
890
+ * false negative on a valid file. */
891
+ var SNIFF_BYTES = 1024 * 1024;
892
+ function isValidUtf8(buf) {
893
+ try {
894
+ new TextDecoder("utf-8", { fatal: true }).decode(buf);
895
+ return true;
896
+ } catch {
897
+ return false;
898
+ }
899
+ }
900
+ /** Detect the (best-effort) encoding of a non-UTF-8 buffer. BOMs decide
901
+ * UTF-16; otherwise cp932 (the Shift_JIS superset — Excel-exported
902
+ * Japanese CSVs are the primary non-UTF-8 case this feature serves). */
903
+ function fallbackEncoding(buf) {
904
+ if (buf.length >= 2 && buf[0] === 255 && buf[1] === 254) return "utf-16le";
905
+ if (buf.length >= 2 && buf[0] === 254 && buf[1] === 255) return "utf-16be";
906
+ return "cp932";
907
+ }
908
+ function cacheDir() {
909
+ return node_path.default.join((0, node_os.tmpdir)(), "mulmoclaude-csv-utf8");
910
+ }
911
+ /** Read only the first `bytes` of a file — the encoding sniff must not
912
+ * pull a multi-hundred-MB CSV into memory on the (common) UTF-8 path. */
913
+ async function readHead(absPath, bytes) {
914
+ const handle = await (0, node_fs_promises.open)(absPath, "r");
915
+ try {
916
+ const { size } = await handle.stat();
917
+ const buf = Buffer.alloc(Math.min(bytes, size));
918
+ await handle.read(buf, 0, buf.length, 0);
919
+ return buf;
920
+ } finally {
921
+ await handle.close();
922
+ }
923
+ }
924
+ /** Decode the whole file into a UTF-8 cache copy and return its path.
925
+ * Cache key = (path, mtime, size), so a replaced CSV re-decodes and an
926
+ * unchanged one never does. */
927
+ async function pathExists$1(target) {
928
+ try {
929
+ await (0, node_fs_promises.stat)(target);
930
+ return true;
931
+ } catch {
932
+ return false;
933
+ }
934
+ }
935
+ /** Best-effort removal of older decode-cache entries for the same source
936
+ * path — a frequently-replaced large CSV would otherwise accumulate one
937
+ * full copy per (mtime, size) forever. Runs AFTER the current copy is
938
+ * published; a concurrent reader holding an old fd is unaffected
939
+ * (unlink-while-open is safe on POSIX). */
940
+ async function evictSupersededCache(key, keepBasename) {
941
+ try {
942
+ const entries = await (0, node_fs_promises.readdir)(cacheDir());
943
+ await Promise.all(entries.filter((name) => name.startsWith(`${key}-`) && name !== keepBasename).map((name) => (0, node_fs_promises.unlink)(node_path.default.join(cacheDir(), name)).catch(() => void 0)));
944
+ } catch {}
945
+ }
946
+ /** Decode the whole file into a UTF-8 cache copy and return its path.
947
+ * Cache key = (path, mtime, size), so a replaced CSV re-decodes and an
948
+ * unchanged one never does; superseded copies are evicted. The cache
949
+ * lives in the SHARED OS tmpdir, so the dir is 0700 and files 0600 —
950
+ * decoded rows must not be readable by other local users. */
951
+ async function decodeToCache(absPath, info) {
952
+ const key = (0, node_crypto.createHash)("sha256").update(absPath).digest("hex").slice(0, 16);
953
+ const cached = node_path.default.join(cacheDir(), `${key}-${Math.trunc(info.mtimeMs)}-${info.size}.csv`);
954
+ if (!await pathExists$1(cached)) {
955
+ const whole = await (0, node_fs_promises.readFile)(absPath);
956
+ const encoding = fallbackEncoding(whole);
957
+ const text = iconv_lite.default.decode(whole, encoding);
958
+ await (0, node_fs_promises.mkdir)(cacheDir(), {
959
+ recursive: true,
960
+ mode: 448
961
+ });
962
+ const tmp = `${cached}.${(0, node_crypto.randomBytes)(4).toString("hex")}.tmp`;
963
+ await (0, node_fs_promises.writeFile)(tmp, text, {
964
+ encoding: "utf-8",
965
+ mode: 384
966
+ });
967
+ await (0, node_fs_promises.rename)(tmp, cached);
968
+ log.info("collections", "decoded non-UTF-8 dataSource file to cache", {
969
+ path: absPath,
970
+ encoding
971
+ });
972
+ await evictSupersededCache(key, node_path.default.basename(cached));
973
+ }
974
+ return cached;
975
+ }
976
+ /** Re-validate the dataSource file at READ time, mirroring the JSON
977
+ * store's per-read defenses: realpath containment (a symlink swapped in
978
+ * after discovery must not walk out of the workspace) and an lstat
979
+ * regular-file check (a symlink leaf is refused outright, even one
980
+ * pointing inside the workspace — same rule as `isRegularFile` on
981
+ * record files). Returns the stat info, or null for "no readable file"
982
+ * (ENOENT / refused), which callers render as an empty collection. */
983
+ async function safeCsvStat(absPath, workspaceRoot) {
984
+ if (!isContainedInRoot(absPath, workspaceRoot)) {
985
+ log.warn("collections", "dataSource read refused: path escapes workspace", { path: absPath });
986
+ return null;
987
+ }
988
+ let info;
989
+ try {
990
+ info = await (0, node_fs_promises.lstat)(absPath);
991
+ } catch (err) {
992
+ if (err.code === "ENOENT") return null;
993
+ throw err;
994
+ }
995
+ if (!info.isFile()) {
996
+ log.warn("collections", "dataSource read refused: not a regular file (symlink?)", { path: absPath });
997
+ return null;
998
+ }
999
+ return info;
1000
+ }
1001
+ /** Return a path DuckDB can read as UTF-8: the original file when it
1002
+ * already is UTF-8 (the cheap, common case — only the head is sniffed),
1003
+ * else a decoded cache copy (see `decodeToCache`). Returns null when
1004
+ * there is no readable file (missing, symlink, or containment-refused —
1005
+ * see `safeCsvStat`), which callers render as an empty collection. */
1006
+ async function ensureUtf8CsvPath(absPath, workspaceRoot) {
1007
+ const info = await safeCsvStat(absPath, workspaceRoot);
1008
+ if (info === null) return null;
1009
+ const head = await readHead(absPath, SNIFF_BYTES);
1010
+ const sample = head.length === SNIFF_BYTES ? head.subarray(0, SNIFF_BYTES - 3) : head;
1011
+ if (!(head.length >= 2 && (head[0] === 255 && head[1] === 254 || head[0] === 254 && head[1] === 255)) && isValidUtf8(sample)) return absPath;
1012
+ return decodeToCache(absPath, info);
1013
+ }
1014
+ var instancePromise = null;
1015
+ /** Lazily create one shared in-memory DuckDB instance. The dynamic import
1016
+ * keeps the native module OUT of core's load path — a platform where the
1017
+ * prebuilt binding is missing degrades to a per-query error on dataSource
1018
+ * collections only, never a broken core. A failed init is retried on the
1019
+ * next call (the promise is reset). */
1020
+ async function duckDbInstance() {
1021
+ if (instancePromise === null) instancePromise = import("@duckdb/node-api").then((mod) => mod.DuckDBInstance.create(":memory:"));
1022
+ try {
1023
+ return await instancePromise;
1024
+ } catch (err) {
1025
+ instancePromise = null;
1026
+ throw new Error(`DuckDB is unavailable on this host (@duckdb/node-api failed to load: ${String(err)}) — dataSource collections cannot be read`);
1027
+ }
1028
+ }
1029
+ async function queryCsv(sql, params) {
1030
+ const connection = await (await duckDbInstance()).connect();
1031
+ try {
1032
+ return (await connection.runAndReadAll(sql, params)).getRowObjectsJS();
1033
+ } finally {
1034
+ connection.disconnectSync();
1035
+ }
1036
+ }
1037
+ /** Every row of the CSV as records — capped, deduped, id-encoded. The
1038
+ * key column is pinned to VARCHAR (see `readCsvArgs`). `workspaceRoot`
1039
+ * drives the per-read containment check; omitted, the configured host
1040
+ * root is used. */
1041
+ async function csvList(absPath, primaryKey, workspaceRoot) {
1042
+ const utf8Path = await ensureUtf8CsvPath(absPath, workspaceRoot ?? getWorkspaceRoot());
1043
+ if (utf8Path === null) return [];
1044
+ let rows;
1045
+ try {
1046
+ rows = await queryCsv(`SELECT * FROM read_csv(${readCsvArgs(primaryKey)}) LIMIT 5001`, [utf8Path]);
1047
+ } catch (err) {
1048
+ if (!isMissingKeyColumnError(err)) throw err;
1049
+ log.warn("collections", "dataSource CSV has no primaryKey column — every row is skipped", {
1050
+ path: absPath,
1051
+ primaryKey
1052
+ });
1053
+ return [];
1054
+ }
1055
+ if (rows.length > 5e3) {
1056
+ log.warn("collections", "dataSource CSV truncated to row cap", {
1057
+ path: absPath,
1058
+ cap: MAX_CSV_ROWS
1059
+ });
1060
+ rows.length = MAX_CSV_ROWS;
1061
+ }
1062
+ const items = rows.map((row) => csvRowToItem(row, primaryKey)).filter((item) => item !== null);
1063
+ const skipped = rows.length - items.length;
1064
+ if (skipped > 0) log.warn("collections", "dataSource CSV rows skipped (empty key cell)", {
1065
+ path: absPath,
1066
+ skipped
1067
+ });
1068
+ const deduped = dedupeByRecordId(items, primaryKey);
1069
+ if (deduped.duplicates > 0) log.warn("collections", "dataSource CSV has duplicate key values (last row wins)", {
1070
+ path: absPath,
1071
+ duplicates: deduped.duplicates
1072
+ });
1073
+ return deduped.items;
1074
+ }
1075
+ /** The scan-order ordinal column the last-match read adds. Underscore
1076
+ * prefix keeps it out of any plausible CSV header namespace; it is
1077
+ * stripped from the returned record either way. */
1078
+ var ROW_ORDINAL = "__mc_row";
1079
+ /** One record by id. The comparison value rides as a prepared-statement
1080
+ * parameter, and the LAST matching row is selected IN DuckDB (scan-order
1081
+ * ordinal + LIMIT 1) — a CSV with thousands of duplicate keys must not
1082
+ * materialize them all for one detail read. Consistent with csvList's
1083
+ * last-wins dedupe. */
1084
+ async function csvRead(absPath, primaryKey, itemId, workspaceRoot) {
1085
+ const utf8Path = await ensureUtf8CsvPath(absPath, workspaceRoot ?? getWorkspaceRoot());
1086
+ if (utf8Path === null) return null;
1087
+ const rawKey = decodeCsvRecordId(itemId);
1088
+ const last = (await queryCsv(`SELECT * FROM (SELECT *, row_number() OVER () AS ${quoteIdent(ROW_ORDINAL)} FROM read_csv(${readCsvArgs(primaryKey)})) WHERE CAST(${quoteIdent(primaryKey)} AS VARCHAR) = ? ORDER BY ${quoteIdent(ROW_ORDINAL)} DESC LIMIT 1`, [utf8Path, rawKey])).at(0);
1089
+ if (last === void 0) return null;
1090
+ const { [ROW_ORDINAL]: __ordinal, ...record } = last;
1091
+ return csvRowToItem(record, primaryKey);
1092
+ }
1093
+ /** Run a validated aggregation query (the structured DSL — see
1094
+ * `core/queryZ.ts`) over the WHOLE file: no row cap on the scan (a
1095
+ * capped aggregate would be a wrong number), only the result-row LIMIT
1096
+ * the compiler emits. Values are normalized like list/read rows so a
1097
+ * chart consumer gets plain JSON scalars. */
1098
+ async function csvRunQuery(absPath, primaryKey, query, workspaceRoot) {
1099
+ const utf8Path = await ensureUtf8CsvPath(absPath, workspaceRoot ?? getWorkspaceRoot());
1100
+ if (utf8Path === null) return [];
1101
+ const { sql, params } = compileCsvQuery(query, primaryKey);
1102
+ return (await queryCsv(sql, [utf8Path, ...params])).map((row) => Object.fromEntries(Object.entries(row).map(([key, value]) => [key, normalizeCsvValue(value)])));
1103
+ }
1104
+ //#endregion
1105
+ //#region src/collection/server/store.ts
1106
+ /** True when the collection accepts UI/tool writes. A `dataSource`
1107
+ * collection is read-only: updates happen by editing/replacing the
1108
+ * data file itself. Every write entry point checks this BEFORE calling
1109
+ * `writeItem`/`deleteItem` — server-enforced, not just UI-hidden. */
1110
+ function collectionWritable(collection) {
1111
+ return !require_promptSafety.isReadOnlySchema(collection.schema);
1112
+ }
1113
+ /** The one-line refusal write paths surface (HTTP 405 / MCP error text). */
1114
+ function readOnlyRefusal(slug) {
1115
+ return `collection '${slug}' is read-only (backed by an external dataSource) — update the data file itself instead`;
1116
+ }
1117
+ /** Pick the store implementation for a discovered collection. A
1118
+ * `dataSource` schema whose `dataSourceFile` failed to resolve yields a
1119
+ * read-only EMPTY store rather than falling back to the (writable) file
1120
+ * store — a half-loaded read-only collection must never become writable. */
1121
+ function storeFor(collection, opts = {}) {
1122
+ if (require_promptSafety.isReadOnlySchema(collection.schema)) {
1123
+ const file = collection.dataSourceFile;
1124
+ const key = collection.schema.primaryKey;
1125
+ return {
1126
+ capabilities: { writable: false },
1127
+ list: () => file === void 0 ? Promise.resolve([]) : csvList(file, key, opts.workspaceRoot),
1128
+ read: (itemId) => file === void 0 ? Promise.resolve(null) : csvRead(file, key, itemId, opts.workspaceRoot),
1129
+ query: (query) => file === void 0 ? Promise.resolve([]) : csvRunQuery(file, key, query, opts.workspaceRoot)
1130
+ };
1131
+ }
1132
+ return {
1133
+ capabilities: { writable: true },
1134
+ list: () => listItems(collection.dataDir, opts),
1135
+ read: (itemId) => readItem(collection.dataDir, itemId, opts)
1136
+ };
1137
+ }
1138
+ //#endregion
640
1139
  //#region src/collection/core/recordZ.ts
641
1140
  /** The emptiness rule shared by `required` and the "only check present
642
1141
  * values" gate. NOT a truthiness check — `0` and `false` are filled. */
@@ -753,6 +1252,7 @@ async function listRecordFilenames(dataDir, workspaceRoot) {
753
1252
  }
754
1253
  }
755
1254
  async function validateCollectionRecords(collection, opts = {}) {
1255
+ if (collection.schema.dataSource !== void 0) return [];
756
1256
  const workspaceRoot = opts.workspaceRoot ?? getWorkspaceRoot();
757
1257
  const entries = await listRecordFilenames(collection.dataDir, workspaceRoot);
758
1258
  const issues = [];
@@ -1402,10 +1902,24 @@ function fieldDrivenFromFieldCarried(schema) {
1402
1902
  }
1403
1903
  return (carry ?? []).includes(driven.fromField);
1404
1904
  }
1905
+ /** External-data collection: the records ARE the rows of a user-supplied
1906
+ * data file (v1: CSV), queried through DuckDB — never copied into
1907
+ * `<dataDir>/<id>.json` files. Declaring `dataSource` makes the collection
1908
+ * **read-only** in every UI/tool write path; updates happen by replacing /
1909
+ * editing the file itself (file-watch republishes the views). `path` is
1910
+ * workspace-relative and containment-checked exactly like `dataPath`. The
1911
+ * row-id column is the schema's existing `primaryKey` — there is
1912
+ * deliberately no second key concept here.
1913
+ * See plans/feat-collection-csv-duckdb-source.md. */
1914
+ var DataSourceZ = zod.z.object({
1915
+ type: zod.z.literal("csv"),
1916
+ path: zod.z.string().min(1)
1917
+ });
1405
1918
  var CollectionSchemaZ = zod.z.object({
1406
1919
  title: zod.z.string().min(1),
1407
1920
  icon: zod.z.string().min(1),
1408
- dataPath: zod.z.string().min(1),
1921
+ dataPath: zod.z.string().min(1).optional(),
1922
+ dataSource: DataSourceZ.optional(),
1409
1923
  primaryKey: zod.z.string().min(1),
1410
1924
  singleton: zod.z.string().trim().min(1).optional(),
1411
1925
  fields: zod.z.record(zod.z.string(), FieldSpecZ),
@@ -1425,6 +1939,15 @@ var CollectionSchemaZ = zod.z.object({
1425
1939
  notifyWhen: WhenZ.optional(),
1426
1940
  ingest: IngestZ.optional(),
1427
1941
  dynamicIcon: DynamicIconSpecZ.optional()
1942
+ }).refine((schema) => schema.dataPath !== void 0 !== (schema.dataSource !== void 0), {
1943
+ message: "declare exactly one of `dataPath` (native JSON records) or `dataSource` (external read-only data file), never both or neither",
1944
+ path: ["dataPath"]
1945
+ }).refine((schema) => schema.dataSource === void 0 || schema.singleton === void 0 && schema.ingest === void 0 && schema.spawn === void 0, {
1946
+ message: "a `dataSource` collection is read-only — it cannot declare `singleton`, `ingest`, or `spawn` (all of them write records)",
1947
+ path: ["dataSource"]
1948
+ }).refine((schema) => schema.dataSource === void 0 || [...schema.actions ?? [], ...schema.collectionActions ?? []].every((action) => action.kind !== "mutate"), {
1949
+ message: "a `dataSource` collection is read-only — its actions cannot use `kind: \"mutate\"` (a host write); use `chat`/`agent` actions instead",
1950
+ path: ["dataSource"]
1428
1951
  }).refine((schema) => schema.singleton === void 0 || require_promptSafety.isSafeRecordId(schema.singleton), {
1429
1952
  message: "schema `singleton` must be a valid item id (alphanumeric / hyphen / underscore / interior dot, no `..` or path separators)",
1430
1953
  path: ["singleton"]
@@ -1550,6 +2073,12 @@ function applyFeedSchemaDefaults(parsed, slug) {
1550
2073
  dataPath: `data/feeds/${slug}`
1551
2074
  };
1552
2075
  }
2076
+ /** The conventional per-slug records dir a `dataSource` collection gets as
2077
+ * its `dataDir` (records never live there, but archive/delete paths stay
2078
+ * well-defined — same shape the registry's R3 normalization uses). */
2079
+ function conventionalDataPath(slug) {
2080
+ return `data/collections/${slug}/items`;
2081
+ }
1553
2082
  /** The acceptance gates discovery applies AFTER `CollectionSchemaZ` parses,
1554
2083
  * before a schema becomes a live collection:
1555
2084
  *
@@ -1559,7 +2088,8 @@ function applyFeedSchemaDefaults(parsed, slug) {
1559
2088
  * edit is dropped with no error;
1560
2089
  * - a `feed` schema must declare an `ingest` block (else it's a dead,
1561
2090
  * non-refreshable card);
1562
- * - `dataPath` must resolve INSIDE the workspace.
2091
+ * - `dataPath` — or a `dataSource`'s `path` — must resolve INSIDE the
2092
+ * workspace (same realpath containment for both).
1563
2093
  *
1564
2094
  * Exported so `manageCollection`'s `putSchema` can run the SAME gates before
1565
2095
  * it reports success — a schema that passes `CollectionSchemaZ` but fails one
@@ -1579,7 +2109,24 @@ function acceptParsedSchema(schema, opts) {
1579
2109
  ok: false,
1580
2110
  reason: "a feed schema must declare an `ingest` block"
1581
2111
  };
1582
- const dataDir = resolveDataDir(schema.dataPath, opts.workspaceRoot);
2112
+ if (schema.dataSource !== void 0) {
2113
+ const dataSourceFile = resolveDataDir(schema.dataSource.path, opts.workspaceRoot);
2114
+ if (dataSourceFile === null) return {
2115
+ ok: false,
2116
+ reason: `dataSource.path '${schema.dataSource.path}' escapes the workspace`
2117
+ };
2118
+ const dataDir = resolveDataDir(conventionalDataPath(opts.slug), opts.workspaceRoot);
2119
+ if (dataDir === null) return {
2120
+ ok: false,
2121
+ reason: `slug '${opts.slug}' yields no workspace-contained data dir`
2122
+ };
2123
+ return {
2124
+ ok: true,
2125
+ dataDir,
2126
+ dataSourceFile
2127
+ };
2128
+ }
2129
+ const dataDir = resolveDataDir(schema.dataPath ?? "", opts.workspaceRoot);
1583
2130
  if (dataDir === null) return {
1584
2131
  ok: false,
1585
2132
  reason: `dataPath '${schema.dataPath}' escapes the workspace`
@@ -1627,7 +2174,8 @@ async function loadOneCollection(skillsRoot, slug, source, workspaceRoot) {
1627
2174
  const schema = parsed.data;
1628
2175
  const acceptance = acceptParsedSchema(schema, {
1629
2176
  source,
1630
- workspaceRoot
2177
+ workspaceRoot,
2178
+ slug: safeName
1631
2179
  });
1632
2180
  if (!acceptance.ok) {
1633
2181
  log.warn("collections", "schema.json rejected after validation, skipping", {
@@ -1641,6 +2189,7 @@ async function loadOneCollection(skillsRoot, slug, source, workspaceRoot) {
1641
2189
  source,
1642
2190
  schema,
1643
2191
  dataDir: acceptance.dataDir,
2192
+ ...acceptance.dataSourceFile !== void 0 ? { dataSourceFile: acceptance.dataSourceFile } : {},
1644
2193
  skillDir: node_path.default.join(skillsRoot, safeName)
1645
2194
  };
1646
2195
  }
@@ -1712,7 +2261,8 @@ function toSummary(collection) {
1712
2261
  slug: collection.slug,
1713
2262
  title: collection.schema.title,
1714
2263
  icon: collection.schema.icon,
1715
- source: collection.source
2264
+ source: collection.source,
2265
+ ...collection.schema.dataSource !== void 0 ? { readonly: true } : {}
1716
2266
  };
1717
2267
  }
1718
2268
  function toDetail(collection) {
@@ -1767,6 +2317,20 @@ async function countRecordFiles(dataDir, workspaceRoot) {
1767
2317
  return 0;
1768
2318
  }
1769
2319
  }
2320
+ /** A collection's record count for the ontology. File-backed: the cheap
2321
+ * readdir count. `dataSource`-backed: the row count via the CSV store
2322
+ * (subject to its row cap) — the dataDir is a phantom there, so the
2323
+ * readdir count would always misreport 0. Fail-soft to 0 like
2324
+ * `countRecordFiles` (an unreadable file / missing DuckDB must not
2325
+ * break the whole ontology). */
2326
+ async function countRecords(collection, workspaceRoot) {
2327
+ if (!collectionWritable(collection)) try {
2328
+ return (await storeFor(collection, { workspaceRoot }).list()).length;
2329
+ } catch {
2330
+ return 0;
2331
+ }
2332
+ return countRecordFiles(collection.dataDir, workspaceRoot);
2333
+ }
1770
2334
  async function toOntologyEntry(collection, workspaceRoot) {
1771
2335
  const { schema } = collection;
1772
2336
  return {
@@ -1775,7 +2339,7 @@ async function toOntologyEntry(collection, workspaceRoot) {
1775
2339
  icon: schema.icon,
1776
2340
  primaryKey: schema.primaryKey,
1777
2341
  displayField: schema.displayField ?? schema.primaryKey,
1778
- recordCount: await countRecordFiles(collection.dataDir, workspaceRoot),
2342
+ recordCount: await countRecords(collection, workspaceRoot),
1779
2343
  relations: schemaRelations(schema)
1780
2344
  };
1781
2345
  }
@@ -1821,7 +2385,7 @@ function uniqueBacklinkSources(schema) {
1821
2385
  async function loadTarget(slug, opts) {
1822
2386
  const target = await loadCollection(slug, opts);
1823
2387
  if (!target) return null;
1824
- const items = await listItems(target.dataDir, { workspaceRoot: opts.workspaceRoot });
2388
+ const items = await storeFor(target, { workspaceRoot: opts.workspaceRoot }).list();
1825
2389
  const byId = {};
1826
2390
  for (const item of items) {
1827
2391
  const itemId = item[target.schema.primaryKey];
@@ -1939,7 +2503,7 @@ async function computeCollectionIcon(collection, opts = {}) {
1939
2503
  try {
1940
2504
  const source = await loadCollection(spec.source.collection, opts);
1941
2505
  if (!source) return spec.fallback ?? schema.icon;
1942
- const ordered = sortByPrimaryKey(await listItems(source.dataDir, { workspaceRoot: opts.workspaceRoot }), source.schema.primaryKey);
2506
+ const ordered = sortByPrimaryKey(await storeFor(source, { workspaceRoot: opts.workspaceRoot }).list(), source.schema.primaryKey);
1943
2507
  const orderBy = spec.source.orderBy ?? require_promptSafety.firstDateField(source.schema);
1944
2508
  const recordsById = buildRecordsById(ordered, source.schema.primaryKey);
1945
2509
  return require_promptSafety.resolveIcon(require_promptSafety.selectDynamicRecord(ordered, spec.source, orderBy, recordsById), spec, schema.icon, recordsById);
@@ -2237,6 +2801,20 @@ function isDataDirSafe(dataDir, slug, workspaceRoot) {
2237
2801
  const resolved = node_path.default.resolve(dataDir);
2238
2802
  return acceptableRoots.some((root) => resolved === root || resolved.startsWith(root + node_path.default.sep));
2239
2803
  }
2804
+ /** Step 2 of the restore doc — how to bring the records back. A
2805
+ * `dataSource` collection has no record files to copy (its rows live in
2806
+ * the external data file, which the delete never touches). */
2807
+ function restoreRecordsStep(schema) {
2808
+ if (schema.dataPath === void 0) return `2. Records: nothing to copy. This is a \`dataSource\` collection —
2809
+ its records are the rows of \`${schema.dataSource?.path}\`, which the
2810
+ delete never touched.`;
2811
+ return `2. Copy the item data: \`cp\` every file under \`records/\` into
2812
+ \`${schema.dataPath}/\`. The records are part of the collection and
2813
+ must be restored. They are plain data files (NOT bridged), so use
2814
+ \`cp\` — the Write-tool rule in step 1 applies ONLY to the skill
2815
+ files, not to these records (there may be many; copy them, do not
2816
+ Write them one by one).`;
2817
+ }
2240
2818
  function buildRestoreDoc(collection) {
2241
2819
  const { slug, schema } = collection;
2242
2820
  return `# Restore "${schema.title}" (collection \`${slug}\`)
@@ -2257,18 +2835,13 @@ Follow these steps to restore it.
2257
2835
  \`.claude/skills/\` directly is not an option either: that path is
2258
2836
  permission-gated.)
2259
2837
 
2260
- 2. Copy the item data: \`cp\` every file under \`records/\` into
2261
- \`${schema.dataPath}/\`. The records are part of the collection and
2262
- must be restored. They are plain data files (NOT bridged), so use
2263
- \`cp\` — the Write-tool rule in step 1 applies ONLY to the skill
2264
- files, not to these records (there may be many; copy them, do not
2265
- Write them one by one).
2838
+ ${restoreRecordsStep(schema)}
2266
2839
 
2267
2840
  3. Confirm the collection reappears at \`/collections/${slug}\`.
2268
2841
 
2269
2842
  - slug: \`${slug}\`
2270
2843
  - title: ${schema.title}
2271
- - dataPath: \`${schema.dataPath}\`
2844
+ - dataPath: \`${schema.dataPath ?? `(dataSource) ${schema.dataSource?.path}`}\`
2272
2845
  `;
2273
2846
  }
2274
2847
  /** Copy one skill copy + the records + RESTORE.md into `archiveDir`. */
@@ -2491,14 +3064,15 @@ async function recordIssuesWarning(collection, deps) {
2491
3064
  return `${issues.length} record file(s) have data problems and are missing from this result. Fix each (Read → correct → Write):\n${lines}`;
2492
3065
  }
2493
3066
  async function loadRequestedItems(collection, ids, deps) {
3067
+ const store = storeFor(collection, { workspaceRoot: deps.workspaceRoot });
2494
3068
  if (!ids) return {
2495
- items: await listItems(collection.dataDir, { workspaceRoot: deps.workspaceRoot }),
3069
+ items: await store.list(),
2496
3070
  missing: []
2497
3071
  };
2498
3072
  const items = [];
2499
3073
  const missing = [];
2500
3074
  for (const recordId of ids) {
2501
- const item = await readItem(collection.dataDir, recordId, { workspaceRoot: deps.workspaceRoot }).catch(() => null);
3075
+ const item = await store.read(recordId).catch(() => null);
2502
3076
  if (item) items.push(item);
2503
3077
  else missing.push(recordId);
2504
3078
  }
@@ -2602,7 +3176,25 @@ async function putOneItem(collection, record, mode, deps) {
2602
3176
  if (result.kind === "conflict") return reject(itemId, `'${itemId}' already exists — mode "create" refuses overwrite; use "upsert" to update it`);
2603
3177
  return reject(itemId, "write refused: the collection's data dir escapes the workspace");
2604
3178
  }
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. */
3184
+ 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
+ const parsed = CollectionQueryZ.safeParse(queryArg);
3188
+ 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);
3190
+ return JSON.stringify({
3191
+ collection: collection.slug,
3192
+ count: rows.length,
3193
+ rows
3194
+ });
3195
+ }
2605
3196
  async function handlePutItems(collection, args, deps) {
3197
+ if (!collectionWritable(collection)) return `manageCollection: ${readOnlyRefusal(collection.slug)} (its records are the rows of '${collection.schema.dataSource?.path}'; edit that file to change the data).`;
2606
3198
  const written = [];
2607
3199
  const rejected = [];
2608
3200
  for (const record of args.items) {
@@ -2701,7 +3293,8 @@ function schemaDiscoveryGate(schema, base) {
2701
3293
  const primaryField = schema.fields[schema.primaryKey];
2702
3294
  if (!primaryField) return `primaryKey '${schema.primaryKey}' is not one of the declared fields`;
2703
3295
  if (primaryField.primary !== true) return `the primaryKey field '${schema.primaryKey}' must be flagged \`primary: true\``;
2704
- if (resolveDataDir(schema.dataPath, base) === null) return `dataPath '${schema.dataPath}' escapes the workspace`;
3296
+ if (schema.dataPath !== void 0 && resolveDataDir(schema.dataPath, base) === null) return `dataPath '${schema.dataPath}' escapes the workspace`;
3297
+ if (schema.dataSource !== void 0 && resolveDataDir(schema.dataSource.path, base) === null) return `dataSource.path '${schema.dataSource.path}' escapes the workspace`;
2705
3298
  return null;
2706
3299
  }
2707
3300
  /** Validate a schema against CollectionSchemaZ and, on success, persist it.
@@ -2723,7 +3316,7 @@ async function handlePutSchema(slug, schemaArg, deps) {
2723
3316
  written: true
2724
3317
  });
2725
3318
  }
2726
- 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.";
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.";
2727
3320
  /** Validate getItems' optional `ids`/`fields` args, then delegate. */
2728
3321
  async function dispatchGetItems(collection, args, deps) {
2729
3322
  const ids = optionalStringArray(args.ids, "ids");
@@ -2744,82 +3337,113 @@ async function manageCollectionHandler(deps, args) {
2744
3337
  if (!slug) return "manageCollection: `slug` is required (the collection's slug).";
2745
3338
  if (action === "getSchema") return handleGetSchema(slug, deps);
2746
3339
  if (action === "putSchema") return handlePutSchema(slug, args.schema, deps);
2747
- if (action !== "getItems" && action !== "putItems") return "manageCollection: `action` must be \"getItems\", \"putItems\", \"getOntology\", \"schemaDocs\", \"getSchema\", or \"putSchema\".";
3340
+ if (action !== "getItems" && action !== "putItems" && action !== "queryItems") return "manageCollection: `action` must be \"getItems\", \"putItems\", \"queryItems\", \"getOntology\", \"schemaDocs\", \"getSchema\", or \"putSchema\".";
2748
3341
  const collection = await loadCollection(slug, deps);
2749
3342
  if (!collection) return unknownCollection(slug);
2750
3343
  if (action === "getItems") return dispatchGetItems(collection, args, deps);
3344
+ if (action === "queryItems") return handleQueryItems(collection, args.query, deps);
2751
3345
  const parsed = parsePutItems(args, slug);
2752
3346
  if (typeof parsed === "string") return parsed;
2753
3347
  return handlePutItems(collection, parsed, deps);
2754
3348
  }
2755
- function makeManageCollectionTool(deps = {}) {
2756
- return {
2757
- definition: {
2758
- name: "manageCollection",
2759
- 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.",
2760
- inputSchema: {
3349
+ var MANAGE_COLLECTION_DEFINITION = {
3350
+ name: "manageCollection",
3351
+ 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.",
3352
+ inputSchema: {
3353
+ type: "object",
3354
+ properties: {
3355
+ action: {
3356
+ type: "string",
3357
+ enum: [
3358
+ "getItems",
3359
+ "putItems",
3360
+ "queryItems",
3361
+ "getOntology",
3362
+ "schemaDocs",
3363
+ "getSchema",
3364
+ "putSchema"
3365
+ ],
3366
+ description: "What to do."
3367
+ },
3368
+ slug: {
3369
+ type: "string",
3370
+ description: "The collection's slug (its directory name, e.g. `stock-quotes`). Required for everything except schemaDocs and getOntology."
3371
+ },
3372
+ ids: {
3373
+ type: "array",
3374
+ items: { type: "string" },
3375
+ description: "getItems: only these record ids (primary-key values). Omit for all records."
3376
+ },
3377
+ fields: {
3378
+ type: "array",
3379
+ items: { type: "string" },
3380
+ description: "getItems: only these fields per record (the primary key is always included). Omit for all fields. Use on large collections."
3381
+ },
3382
+ items: {
3383
+ type: "array",
3384
+ items: { type: "object" },
3385
+ description: "putItems: the record objects to store. Each must carry the schema's primaryKey value (it doubles as the filename)."
3386
+ },
3387
+ mode: {
3388
+ type: "string",
3389
+ enum: [
3390
+ "upsert",
3391
+ "create",
3392
+ "merge"
3393
+ ],
3394
+ 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."
3395
+ },
3396
+ schema: {
2761
3397
  type: "object",
2762
- properties: {
2763
- action: {
2764
- type: "string",
2765
- enum: [
2766
- "getItems",
2767
- "putItems",
2768
- "getOntology",
2769
- "schemaDocs",
2770
- "getSchema",
2771
- "putSchema"
2772
- ],
2773
- description: "What to do."
2774
- },
2775
- slug: {
2776
- type: "string",
2777
- description: "The collection's slug (its directory name, e.g. `stock-quotes`). Required for everything except schemaDocs and getOntology."
2778
- },
2779
- ids: {
2780
- type: "array",
2781
- items: { type: "string" },
2782
- description: "getItems: only these record ids (primary-key values). Omit for all records."
2783
- },
2784
- fields: {
2785
- type: "array",
2786
- items: { type: "string" },
2787
- description: "getItems: only these fields per record (the primary key is always included). Omit for all fields. Use on large collections."
2788
- },
2789
- items: {
2790
- type: "array",
2791
- items: { type: "object" },
2792
- description: "putItems: the record objects to store. Each must carry the schema's primaryKey value (it doubles as the filename)."
2793
- },
2794
- mode: {
2795
- type: "string",
2796
- enum: [
2797
- "upsert",
2798
- "create",
2799
- "merge"
2800
- ],
2801
- 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."
2802
- },
2803
- schema: {
2804
- type: "object",
2805
- 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."
2806
- }
2807
- },
2808
- required: ["action"]
3398
+ 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."
3399
+ },
3400
+ query: {
3401
+ 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."
2809
3403
  }
2810
3404
  },
3405
+ required: ["action"]
3406
+ }
3407
+ };
3408
+ function makeManageCollectionTool(deps = {}) {
3409
+ return {
3410
+ definition: MANAGE_COLLECTION_DEFINITION,
2811
3411
  alwaysActive: true,
2812
3412
  prompt: MANAGE_COLLECTION_PROMPT,
2813
3413
  handler: (args) => manageCollectionHandler(deps, args)
2814
3414
  };
2815
3415
  }
2816
3416
  //#endregion
3417
+ Object.defineProperty(exports, "CollectionQueryZ", {
3418
+ enumerable: true,
3419
+ get: function() {
3420
+ return CollectionQueryZ;
3421
+ }
3422
+ });
2817
3423
  Object.defineProperty(exports, "CollectionSchemaZ", {
2818
3424
  enumerable: true,
2819
3425
  get: function() {
2820
3426
  return CollectionSchemaZ;
2821
3427
  }
2822
3428
  });
3429
+ Object.defineProperty(exports, "DEFAULT_QUERY_ROWS", {
3430
+ enumerable: true,
3431
+ get: function() {
3432
+ return DEFAULT_QUERY_ROWS;
3433
+ }
3434
+ });
3435
+ Object.defineProperty(exports, "MAX_CSV_ROWS", {
3436
+ enumerable: true,
3437
+ get: function() {
3438
+ return MAX_CSV_ROWS;
3439
+ }
3440
+ });
3441
+ Object.defineProperty(exports, "MAX_QUERY_ROWS", {
3442
+ enumerable: true,
3443
+ get: function() {
3444
+ return MAX_QUERY_ROWS;
3445
+ }
3446
+ });
2823
3447
  Object.defineProperty(exports, "MAX_SCHEMA_ISSUES", {
2824
3448
  enumerable: true,
2825
3449
  get: function() {
@@ -2880,12 +3504,24 @@ Object.defineProperty(exports, "buildWorkspaceOntology", {
2880
3504
  return buildWorkspaceOntology;
2881
3505
  }
2882
3506
  });
3507
+ Object.defineProperty(exports, "collectionWritable", {
3508
+ enumerable: true,
3509
+ get: function() {
3510
+ return collectionWritable;
3511
+ }
3512
+ });
2883
3513
  Object.defineProperty(exports, "collectionsRegistriesConfigPath", {
2884
3514
  enumerable: true,
2885
3515
  get: function() {
2886
3516
  return collectionsRegistriesConfigPath;
2887
3517
  }
2888
3518
  });
3519
+ Object.defineProperty(exports, "compileCsvQuery", {
3520
+ enumerable: true,
3521
+ get: function() {
3522
+ return compileCsvQuery;
3523
+ }
3524
+ });
2889
3525
  Object.defineProperty(exports, "compileRecordZ", {
2890
3526
  enumerable: true,
2891
3527
  get: function() {
@@ -2910,12 +3546,30 @@ Object.defineProperty(exports, "configureCollectionHost", {
2910
3546
  return configureCollectionHost;
2911
3547
  }
2912
3548
  });
3549
+ Object.defineProperty(exports, "csvRowToItem", {
3550
+ enumerable: true,
3551
+ get: function() {
3552
+ return csvRowToItem;
3553
+ }
3554
+ });
2913
3555
  Object.defineProperty(exports, "daysInMonth", {
2914
3556
  enumerable: true,
2915
3557
  get: function() {
2916
3558
  return daysInMonth;
2917
3559
  }
2918
3560
  });
3561
+ Object.defineProperty(exports, "decodeCsvRecordId", {
3562
+ enumerable: true,
3563
+ get: function() {
3564
+ return decodeCsvRecordId;
3565
+ }
3566
+ });
3567
+ Object.defineProperty(exports, "dedupeByRecordId", {
3568
+ enumerable: true,
3569
+ get: function() {
3570
+ return dedupeByRecordId;
3571
+ }
3572
+ });
2919
3573
  Object.defineProperty(exports, "deleteCollection", {
2920
3574
  enumerable: true,
2921
3575
  get: function() {
@@ -2946,6 +3600,12 @@ Object.defineProperty(exports, "discoverCollections", {
2946
3600
  return discoverCollections;
2947
3601
  }
2948
3602
  });
3603
+ Object.defineProperty(exports, "encodeCsvRecordId", {
3604
+ enumerable: true,
3605
+ get: function() {
3606
+ return encodeCsvRecordId;
3607
+ }
3608
+ });
2949
3609
  Object.defineProperty(exports, "enrichItems", {
2950
3610
  enumerable: true,
2951
3611
  get: function() {
@@ -3042,6 +3702,12 @@ Object.defineProperty(exports, "maybeSpawnSuccessor", {
3042
3702
  return maybeSpawnSuccessor;
3043
3703
  }
3044
3704
  });
3705
+ Object.defineProperty(exports, "normalizeCsvValue", {
3706
+ enumerable: true,
3707
+ get: function() {
3708
+ return normalizeCsvValue;
3709
+ }
3710
+ });
3045
3711
  Object.defineProperty(exports, "parseCivil", {
3046
3712
  enumerable: true,
3047
3713
  get: function() {
@@ -3078,6 +3744,12 @@ Object.defineProperty(exports, "readItem", {
3078
3744
  return readItem;
3079
3745
  }
3080
3746
  });
3747
+ Object.defineProperty(exports, "readOnlyRefusal", {
3748
+ enumerable: true,
3749
+ get: function() {
3750
+ return readOnlyRefusal;
3751
+ }
3752
+ });
3081
3753
  Object.defineProperty(exports, "readSkillTemplate", {
3082
3754
  enumerable: true,
3083
3755
  get: function() {
@@ -3138,6 +3810,12 @@ Object.defineProperty(exports, "setCollectionChangePublisher", {
3138
3810
  return setCollectionChangePublisher;
3139
3811
  }
3140
3812
  });
3813
+ Object.defineProperty(exports, "storeFor", {
3814
+ enumerable: true,
3815
+ get: function() {
3816
+ return storeFor;
3817
+ }
3818
+ });
3141
3819
  Object.defineProperty(exports, "successorId", {
3142
3820
  enumerable: true,
3143
3821
  get: function() {
@@ -3181,4 +3859,4 @@ Object.defineProperty(exports, "writeItem", {
3181
3859
  }
3182
3860
  });
3183
3861
 
3184
- //# sourceMappingURL=server-Bh-DPK-H.cjs.map
3862
+ //# sourceMappingURL=server-Q7ld-FlZ.cjs.map