@mulmoclaude/core 0.26.0 → 0.27.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 (88) hide show
  1. package/assets/helps/error-recovery.md +55 -0
  2. package/dist/collection/core/errorMessage.d.ts +1 -4
  3. package/dist/collection/core/ontologyGraph.d.ts +58 -0
  4. package/dist/collection/core/uiTypes.d.ts +7 -0
  5. package/dist/collection/index.cjs +81 -10
  6. package/dist/collection/index.cjs.map +1 -1
  7. package/dist/collection/index.d.ts +1 -0
  8. package/dist/collection/index.js +74 -4
  9. package/dist/collection/index.js.map +1 -1
  10. package/dist/collection/registry/server/index.cjs +8 -7
  11. package/dist/collection/registry/server/index.cjs.map +1 -1
  12. package/dist/collection/registry/server/index.js +3 -2
  13. package/dist/collection/registry/server/index.js.map +1 -1
  14. package/dist/collection/server/index.cjs +3 -3
  15. package/dist/collection/server/index.js +3 -3
  16. package/dist/collection/server/ontology.d.ts +2 -24
  17. package/dist/collection/server/util.d.ts +1 -2
  18. package/dist/collection-watchers/index.cjs +5 -4
  19. package/dist/collection-watchers/index.cjs.map +1 -1
  20. package/dist/collection-watchers/index.js +4 -3
  21. package/dist/collection-watchers/index.js.map +1 -1
  22. package/dist/{discovery-QUi_7aNG.js → discovery-B9Vfojyy.js} +2 -2
  23. package/dist/{discovery-QUi_7aNG.js.map → discovery-B9Vfojyy.js.map} +1 -1
  24. package/dist/{discovery-cwtfyDxl.cjs → discovery-BxbJy2VN.cjs} +2 -2
  25. package/dist/{discovery-cwtfyDxl.cjs.map → discovery-BxbJy2VN.cjs.map} +1 -1
  26. package/dist/errors-7P5eMOSX.cjs +30 -0
  27. package/dist/errors-7P5eMOSX.cjs.map +1 -0
  28. package/dist/errors-eid6Mes3.js +19 -0
  29. package/dist/errors-eid6Mes3.js.map +1 -0
  30. package/dist/feeds/index.cjs +2 -2
  31. package/dist/feeds/index.js +2 -2
  32. package/dist/feeds/server/index.cjs +4 -4
  33. package/dist/feeds/server/index.js +4 -4
  34. package/dist/google/index.cjs +8 -18
  35. package/dist/google/index.cjs.map +1 -1
  36. package/dist/google/index.js +3 -13
  37. package/dist/google/index.js.map +1 -1
  38. package/dist/google/util.d.ts +2 -4
  39. package/dist/{ids-P2T89Gou.js → ids-D1M1T6KJ.js} +26 -3
  40. package/dist/ids-D1M1T6KJ.js.map +1 -0
  41. package/dist/{ids-Dl9Ij63K.cjs → ids-DWmHjm17.cjs} +37 -2
  42. package/dist/ids-DWmHjm17.cjs.map +1 -0
  43. package/dist/{ingestTypes-C-IQB4nw.js → ingestTypes-Ci4eOgv-.js} +2 -2
  44. package/dist/{ingestTypes-C-IQB4nw.js.map → ingestTypes-Ci4eOgv-.js.map} +1 -1
  45. package/dist/{ingestTypes-DZpAC3N_.cjs → ingestTypes-DbuQNuK6.cjs} +2 -2
  46. package/dist/{ingestTypes-DZpAC3N_.cjs.map → ingestTypes-DbuQNuK6.cjs.map} +1 -1
  47. package/dist/{promptSafety-BOc1B3im.cjs → promptSafety-0ZKHX-6J.cjs} +5 -39
  48. package/dist/promptSafety-0ZKHX-6J.cjs.map +1 -0
  49. package/dist/{promptSafety-B5KPkaNY.js → promptSafety-RE1SPxBN.js} +3 -25
  50. package/dist/promptSafety-RE1SPxBN.js.map +1 -0
  51. package/dist/remote-host/server/index.cjs +4 -4
  52. package/dist/remote-host/server/index.cjs.map +1 -1
  53. package/dist/remote-host/server/index.js +1 -1
  54. package/dist/scheduler/index.cjs +2 -4
  55. package/dist/scheduler/index.cjs.map +1 -1
  56. package/dist/scheduler/index.js +1 -3
  57. package/dist/scheduler/index.js.map +1 -1
  58. package/dist/{server-B7mtx4Cd.cjs → server-DOGKfUuD.cjs} +9 -17
  59. package/dist/server-DOGKfUuD.cjs.map +1 -0
  60. package/dist/{server-CNLZZONa.js → server-sGNe-msA.js} +9 -11
  61. package/dist/server-sGNe-msA.js.map +1 -0
  62. package/dist/text-CaAh9ZSO.cjs +27 -0
  63. package/dist/text-CaAh9ZSO.cjs.map +1 -0
  64. package/dist/text-CjDbP2O1.js +22 -0
  65. package/dist/text-CjDbP2O1.js.map +1 -0
  66. package/dist/utils/errors.d.ts +2 -0
  67. package/dist/utils/index.cjs +6 -0
  68. package/dist/utils/index.d.ts +2 -0
  69. package/dist/utils/index.js +3 -0
  70. package/dist/utils/text.d.ts +12 -0
  71. package/dist/whisper/index.cjs +7 -9
  72. package/dist/whisper/index.cjs.map +1 -1
  73. package/dist/whisper/index.js +1 -3
  74. package/dist/whisper/index.js.map +1 -1
  75. package/dist/whisper/internal.d.ts +1 -1
  76. package/dist/workspace-setup/index.js +12 -3
  77. package/dist/workspace-setup/index.js.map +1 -1
  78. package/package.json +7 -1
  79. package/dist/errorMessage--LvXe_Jx.cjs +0 -16
  80. package/dist/errorMessage--LvXe_Jx.cjs.map +0 -1
  81. package/dist/errorMessage-DIdhheHk.js +0 -11
  82. package/dist/errorMessage-DIdhheHk.js.map +0 -1
  83. package/dist/ids-Dl9Ij63K.cjs.map +0 -1
  84. package/dist/ids-P2T89Gou.js.map +0 -1
  85. package/dist/promptSafety-B5KPkaNY.js.map +0 -1
  86. package/dist/promptSafety-BOc1B3im.cjs.map +0 -1
  87. package/dist/server-B7mtx4Cd.cjs.map +0 -1
  88. package/dist/server-CNLZZONa.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/workspace-setup/sync.ts","../../src/workspace-setup/assets.ts"],"sourcesContent":["// Preset skills bundled with mulmoclaude.\n//\n// History: introduced in #1210 to ship launcher-managed \"factory\"\n// skills like `mc-library`. Originally synced straight into\n// `<workspaceRoot>/.claude/skills/<slug>/`, which made every preset\n// auto-active and inflated the Claude system prompt as new presets\n// landed.\n//\n// #1335 PR-A flipped the destination to the catalog\n// (`<workspaceRoot>/data/skills/catalog/preset/<slug>/`). Catalog\n// entries are visible to UI / tooling but NOT discovered by Claude\n// Code's slash-command resolver — they don't enter the system\n// prompt unless the user (or a later UI in PR-B) explicitly copies\n// one into `.claude/skills/`.\n//\n// The launcher overwrites catalog entries unconditionally on every\n// boot — they're factory defaults, not user state. Anything in\n// `.claude/skills/` (active layer) is left untouched.\n//\n// `syncPresetSkills(...)` is exported as a pure-ish helper (takes\n// paths + a logger sink, returns a summary) so tests can drive it\n// against tmpdirs without touching a real workspace.\n\nimport { copyFileSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, type Dirent } from \"node:fs\";\nimport { randomUUID } from \"node:crypto\";\nimport path from \"node:path\";\nimport { PRESET_SLUG_PREFIX, isPresetSlug } from \"./slug.js\";\n\n// Inlined (was the host's ../utils/errors.js) so the package has no host coupling.\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n// Recursively mirror `srcDir` into `destDir`. Used by the preset\n// sync so a preset skill that ships sibling assets (e.g.\n// `schema.json` for schema-driven apps, `templates/*.html`) gets\n// copied alongside `SKILL.md` rather than silently dropped. Only\n// regular files and directories are followed — symlinks / FIFOs /\n// sockets are skipped because the preset tree is launcher-managed\n// and shouldn't contain them.\nfunction copyDirTreeSync(srcDir: string, destDir: string): void {\n mkdirSync(destDir, { recursive: true });\n for (const entry of readdirSync(srcDir, { withFileTypes: true })) {\n const srcPath = path.join(srcDir, entry.name);\n const destPath = path.join(destDir, entry.name);\n if (entry.isDirectory()) {\n copyDirTreeSync(srcPath, destPath);\n } else if (entry.isFile()) {\n copyFileSync(srcPath, destPath);\n }\n }\n}\n\nconst SKILL_FILENAME = \"SKILL.md\";\n\nexport interface SyncPresetSkillsOptions {\n /** Source directory: `<launcher>/server/workspace/skills-preset/`. */\n sourceDir: string;\n /** Destination directory:\n * `<workspaceRoot>/data/skills/catalog/preset/`. The catalog\n * half of the catalog-vs-active split — entries here are visible\n * to UI but NOT to Claude Code's prompt-time skill resolver. */\n destDir: string;\n /** Logger callbacks — kept injectable so tests don't need to\n * spin up the structured logger. The boot-side wrapper threads\n * these through to `log.info` / `log.warn`. */\n onInfo?: (message: string, data?: Record<string, unknown>) => void;\n onWarn?: (message: string, data?: Record<string, unknown>) => void;\n}\n\nexport interface SyncPresetSkillsResult {\n /** Slugs successfully copied (or refreshed) from source to dest. */\n copied: string[];\n /** Slugs removed from dest because they no longer exist in source.\n * Bounded to `mc-*` entries — user-authored slugs are never\n * considered for removal. */\n removed: string[];\n /** Source entries that failed validation (wrong prefix, missing\n * SKILL.md, etc.) and were skipped. Each entry is human-readable. */\n skipped: string[];\n}\n\n// Classification of one source entry. `silent` distinguishes\n// structural skips (hidden files, non-directory entries — not the\n// dev's fault) from misconfigurations (bad slug, missing or\n// non-regular SKILL.md — the dev WANTS to know). The boolean lives\n// on the verdict so the caller never has to string-match `reason`,\n// which would silently drop warnings if reason wording changed\n// (CodeRabbit review).\ntype Verdict = { ok: true } | { ok: false; reason: string; silent: boolean };\n\nfunction classifySourceEntry(sourceDir: string, entry: string): Verdict {\n if (entry.startsWith(\".\")) return { ok: false, reason: \"hidden\", silent: true };\n const slugDir = path.join(sourceDir, entry);\n let dirInfo;\n try {\n dirInfo = statSync(slugDir);\n } catch {\n return { ok: false, reason: \"stat failed\", silent: true };\n }\n if (!dirInfo.isDirectory()) return { ok: false, reason: \"not a directory\", silent: true };\n if (!isPresetSlug(entry)) return { ok: false, reason: `slug must start with \"${PRESET_SLUG_PREFIX}\"`, silent: false };\n // Validate SKILL.md is a regular file — `existsSync` alone\n // accepts a directory at that path, which would then crash\n // copyFileSync. Codex review caught this edge case.\n const skillPath = path.join(slugDir, SKILL_FILENAME);\n let skillInfo;\n try {\n skillInfo = statSync(skillPath);\n } catch {\n return { ok: false, reason: `missing ${SKILL_FILENAME}`, silent: false };\n }\n if (!skillInfo.isFile()) return { ok: false, reason: `${SKILL_FILENAME} must be a regular file`, silent: false };\n return { ok: true };\n}\n\n/** Prepare the destination slug dir. Returns false if the slot is\n * occupied by a regular file (local corruption / hand edits) — the\n * caller logs + skips so one bad entry can't crash the whole boot\n * (Codex review iter-1). */\nfunction ensureDestSlugDir(destSlugDir: string): boolean {\n let info;\n try {\n info = statSync(destSlugDir);\n } catch {\n mkdirSync(destSlugDir, { recursive: true });\n return true;\n }\n return info.isDirectory();\n}\n\n/** Filesystem ops `_replaceSlugTree` depends on — injectable so the\n * mid-swap failure path can be regression-tested without real IO faults. */\nexport interface SlugTreeFsOps {\n copyTree: (src: string, dest: string) => void;\n rename: (from: string, dest: string) => void;\n remove: (target: string) => void;\n exists: (target: string) => boolean;\n}\n\nconst REAL_FS_OPS: SlugTreeFsOps = {\n copyTree: copyDirTreeSync,\n rename: renameSync,\n remove: (target) => rmSync(target, { recursive: true, force: true }),\n exists: existsSync,\n};\n\n/** Refresh one preset slot as a rollback-safe stage-and-swap. Wipe-and-replace\n * (not merge) so stale sibling assets — e.g. a schema.json dropped between\n * releases — don't linger; the catalog preset slot is launcher-owned, so user\n * edits there are not preserved across boots.\n *\n * The live slot is never left without a recoverable copy:\n * 1. Stage: copy the source into a temp sibling. A copy failure leaves the\n * existing preset untouched (temp dir removed).\n * 2. Move the existing tree ASIDE to a backup (rename, not delete), so the\n * old contents survive even if the next step fails.\n * 3. Move the staged copy into place. On failure, restore from the backup;\n * if even the restore fails, BOTH backup and staging are preserved for\n * manual recovery rather than deleted.\n * 4. On success, drop the backup.\n *\n * Exported with a `_` prefix only so the rename-failure-after-move path can be\n * regression-tested via the injected `fsOps`. Throws on failure (caller records\n * + skips). */\nexport function _replaceSlugTree(sourceSlugDir: string, destSlugDir: string, fsOps: SlugTreeFsOps = REAL_FS_OPS): void {\n const staging = `${destSlugDir}.tmp-${randomUUID()}`;\n try {\n fsOps.copyTree(sourceSlugDir, staging);\n } catch (err) {\n fsOps.remove(staging); // dest untouched\n throw err;\n }\n const backup = `${destSlugDir}.bak-${randomUUID()}`;\n let backedUp = false;\n if (fsOps.exists(destSlugDir)) {\n try {\n fsOps.rename(destSlugDir, backup);\n backedUp = true;\n } catch (err) {\n fsOps.remove(staging); // dest untouched; nothing was moved\n throw err;\n }\n }\n try {\n fsOps.rename(staging, destSlugDir);\n } catch (err) {\n if (backedUp) {\n try {\n fsOps.rename(backup, destSlugDir); // roll back to the previous tree\n fsOps.remove(staging);\n } catch {\n // Rollback failed — preserve BOTH backup and staging for manual\n // recovery rather than leaving the slot empty.\n }\n } else {\n fsOps.remove(staging); // dest never existed; nothing to restore\n }\n throw err;\n }\n if (backedUp) fsOps.remove(backup);\n}\n\nfunction copySourcesIntoDest(sourceDir: string, destDir: string, opts: SyncPresetSkillsOptions, result: SyncPresetSkillsResult): Set<string> {\n // `keep` is the set of slugs the retirement pass must NOT prune. It tracks\n // valid SOURCE slugs (present + usable dest slot), NOT successful copies — so\n // a slug whose refresh fails transiently keeps its existing contents (left\n // intact by the stage-and-swap above) instead of being pruned as \"retired\".\n const keep = new Set<string>();\n for (const entry of readdirSync(sourceDir)) {\n const verdict = classifySourceEntry(sourceDir, entry);\n if (!verdict.ok) {\n if (!verdict.silent) {\n result.skipped.push(`${entry}: ${verdict.reason}`);\n opts.onWarn?.(\"preset entry skipped\", { slug: entry, reason: verdict.reason });\n }\n continue;\n }\n const destSlugDir = path.join(destDir, entry);\n if (!ensureDestSlugDir(destSlugDir)) {\n const reason = \"destination slot occupied by a non-directory; skipping\";\n result.skipped.push(`${entry}: ${reason}`);\n opts.onWarn?.(\"preset entry skipped\", { slug: entry, reason, destSlugDir });\n continue;\n }\n // The slug exists in source with a usable dest slot — keep it regardless of\n // whether the refresh below succeeds, so a transient failure doesn't get it\n // pruned by `removeRetiredPresets`.\n keep.add(entry);\n // Per-slug isolation: a transient IO error / permission issue / partial\n // corruption on one preset must not abort syncing the rest, nor destroy\n // the existing copy. Skip the offender (recorded) and continue.\n try {\n _replaceSlugTree(path.join(sourceDir, entry), destSlugDir);\n result.copied.push(entry);\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n result.skipped.push(`${entry}: ${reason}`);\n opts.onWarn?.(\"preset copy failed, skipping\", { slug: entry, reason });\n }\n }\n return keep;\n}\n\nfunction removeRetiredPresets(destDir: string, keep: ReadonlySet<string>, opts: SyncPresetSkillsOptions, result: SyncPresetSkillsResult): void {\n for (const entry of readdirSync(destDir)) {\n if (!isPresetSlug(entry)) continue;\n if (keep.has(entry)) continue;\n const stalePath = path.join(destDir, entry);\n try {\n if (!statSync(stalePath).isDirectory()) continue;\n } catch {\n continue;\n }\n rmSync(stalePath, { recursive: true, force: true });\n result.removed.push(entry);\n opts.onInfo?.(\"removed retired preset skill\", { slug: entry });\n }\n}\n\n/** Copy every preset slug from `sourceDir` into `destDir` (the\n * preset slot under the catalog root), then remove any `mc-*`\n * entries in `destDir` that no longer have a source. The catalog\n * preset subdir is fully launcher-owned, so the `mc-*` prefix\n * check at destination is defence-in-depth: a stray non-preset\n * slug landing in `catalog/preset/` is unexpected, and we'd\n * rather skip it than silently delete a directory we don't\n * recognise. */\nexport function syncPresetSkills(opts: SyncPresetSkillsOptions): SyncPresetSkillsResult {\n const result: SyncPresetSkillsResult = { copied: [], removed: [], skipped: [] };\n if (!existsSync(opts.sourceDir)) {\n // No preset directory in the launcher tarball — nothing to do.\n // This is the legitimate \"no presets shipped yet\" state.\n return result;\n }\n // Source-side validation: the launcher's preset path COULD exist\n // as a regular file (a packaging bug, a corrupted install). Without\n // this guard, `readdirSync(sourceDir)` would throw ENOTDIR and\n // crash boot. Codex review iter-3.\n let sourceInfo;\n try {\n sourceInfo = statSync(opts.sourceDir);\n } catch (err) {\n const reason = `source path stat failed: ${errorMessage(err)}`;\n result.skipped.push(`${opts.sourceDir}: ${reason}`);\n opts.onWarn?.(\"preset sync aborted\", { sourceDir: opts.sourceDir, reason });\n return result;\n }\n if (!sourceInfo.isDirectory()) {\n const reason = \"source path exists as a non-directory; preset sync skipped\";\n result.skipped.push(`${opts.sourceDir}: ${reason}`);\n opts.onWarn?.(\"preset sync aborted\", { sourceDir: opts.sourceDir, reason });\n return result;\n }\n // The root dest itself can be corrupted into a regular file by a\n // user / external tool; mkdirSync would throw EEXIST and crash\n // boot. Treat it as a recoverable \"skip the entire sync\" state\n // — log a clear warning so the user sees what to fix.\n // (Codex review iter-2.)\n if (!ensureDestSlugDir(opts.destDir)) {\n const reason = \"root dest exists as a non-directory; preset sync skipped\";\n result.skipped.push(`${opts.destDir}: ${reason}`);\n opts.onWarn?.(\"preset sync aborted\", { destDir: opts.destDir, reason });\n return result;\n }\n const keep = copySourcesIntoDest(opts.sourceDir, opts.destDir, opts, result);\n removeRetiredPresets(opts.destDir, keep, opts, result);\n if (result.copied.length > 0 || result.removed.length > 0) {\n opts.onInfo?.(\"preset skills synced\", {\n copied: result.copied.length,\n removed: result.removed.length,\n skipped: result.skipped.length,\n });\n }\n return result;\n}\n\n// ---------------------------------------------------------------\n// Active-layer sync: keep starred mc-* presets in lockstep with\n// their launcher-bundled source.\n//\n// Motivation: the catalog sync above refreshes\n// `data/skills/catalog/preset/<slug>/` on every boot, but once a\n// user stars an entry the active copy in\n// `<workspace>/.claude/skills/<slug>/` is never updated even when\n// the launcher ships a new SKILL.md (e.g. a typo fix or, as the\n// trigger for this code, the schema-driven-apps → collections\n// rename). The SKILL.md front-matter explicitly says\n// \"do not edit this file in the workspace, it is overwritten on\n// every server boot\" — until this function existed, that was a\n// promise the active layer didn't keep.\n//\n// Safety model:\n// - Only `mc-*` slugs are touched (defensive prefix check —\n// never touches user-authored skills).\n// - Per-file diff: a file is overwritten only if its bytes\n// differ from the source. No-op when already up to date.\n// - User-added files inside an active slug dir are left alone\n// (we walk the source tree, not the dest tree).\n// - If a file IS overwritten, the previous contents are first\n// renamed to `<file>.bak.<timestamp>` so a user who had\n// locally tweaked the preset can recover.\n// - A slug whose active dir doesn't exist (= not starred yet)\n// is skipped entirely, never auto-starred.\n// ---------------------------------------------------------------\n\nexport interface SyncActivePresetSkillsOptions {\n /** Source directory: `<launcher>/server/workspace/skills-preset/`. */\n sourceDir: string;\n /** Active skills directory: `<workspaceRoot>/.claude/skills/`. */\n activeDir: string;\n onInfo?: (message: string, data?: Record<string, unknown>) => void;\n onWarn?: (message: string, data?: Record<string, unknown>) => void;\n}\n\nexport interface SyncActivePresetSkillsResult {\n /** Slugs whose active copy had at least one file overwritten. */\n updated: string[];\n /** Slugs whose active copy already matched the source — no-op. */\n unchanged: string[];\n /** Slugs that haven't been starred yet (no active dir present).\n * Listed for diagnostics; the function never auto-stars. */\n notActive: string[];\n /** Active `mc-*` slugs pruned because the launcher no longer ships a\n * source preset for them (a retired preset). Bounded to `mc-*` —\n * user-authored skills are never removed. */\n removed: string[];\n /** Per-slug failure messages (permission errors, etc.). */\n skipped: string[];\n /** Common timestamp suffix used for every backup file produced by\n * this run. Exposed so the boot-time log can point a user at the\n * exact glob to inspect. */\n backupSuffix: string | null;\n}\n\ntype FileSyncOutcome = \"updated\" | \"unchanged\" | \"skipped\";\n\nfunction filesEqual(left: string, right: string): boolean {\n try {\n return readFileSync(left).equals(readFileSync(right));\n } catch {\n return false;\n }\n}\n\n/** Copy `srcPath` over `destPath`. If `destPath` already exists and\n * differs, rename it to `destPath + backupExt` first so the user's\n * prior contents are recoverable. If `destPath` doesn't exist, just\n * copy (no backup needed). Pure: no logging here — caller decides. */\nfunction syncOneFile(srcPath: string, destPath: string, backupExt: string): FileSyncOutcome {\n let destExists: boolean;\n try {\n destExists = statSync(destPath).isFile();\n } catch {\n destExists = false;\n }\n if (!destExists) {\n try {\n copyFileSync(srcPath, destPath);\n return \"updated\";\n } catch {\n return \"skipped\";\n }\n }\n if (filesEqual(srcPath, destPath)) return \"unchanged\";\n try {\n renameSync(destPath, destPath + backupExt);\n copyFileSync(srcPath, destPath);\n return \"updated\";\n } catch {\n return \"skipped\";\n }\n}\n\ninterface DirSyncStats {\n updated: number;\n unchanged: number;\n skipped: number;\n}\n\nfunction syncDirTreeDiff(srcDir: string, destDir: string, backupExt: string): DirSyncStats {\n const stats: DirSyncStats = { updated: 0, unchanged: 0, skipped: 0 };\n try {\n mkdirSync(destDir, { recursive: true });\n } catch {\n stats.skipped++;\n return stats;\n }\n let entries: Dirent[];\n try {\n entries = readdirSync(srcDir, { withFileTypes: true });\n } catch {\n stats.skipped++;\n return stats;\n }\n for (const entry of entries) {\n const srcPath = path.join(srcDir, entry.name);\n const destPath = path.join(destDir, entry.name);\n if (entry.isDirectory()) {\n const sub = syncDirTreeDiff(srcPath, destPath, backupExt);\n stats.updated += sub.updated;\n stats.unchanged += sub.unchanged;\n stats.skipped += sub.skipped;\n } else if (entry.isFile()) {\n const outcome = syncOneFile(srcPath, destPath, backupExt);\n stats[outcome]++;\n }\n // Symlinks / sockets / FIFOs intentionally ignored (the launcher\n // preset tree shouldn't contain them).\n }\n return stats;\n}\n\nfunction abortActiveSync(opts: SyncActivePresetSkillsOptions, result: SyncActivePresetSkillsResult, reason: string): SyncActivePresetSkillsResult {\n result.skipped.push(`${opts.sourceDir}: ${reason}`);\n opts.onWarn?.(\"active preset sync aborted\", { sourceDir: opts.sourceDir, reason });\n return result;\n}\n\n/** True iff `absPath`'s realpath resolves inside `rootPath`'s\n * realpath. Defends `processActiveSlug` against a starred `mc-*`\n * slug that's actually a symlink to somewhere outside\n * `activeDir`: without this check, the recursive copy below would\n * follow the symlink and write through to the link's target\n * (potentially anywhere on disk). Returns false on any error so\n * the caller treats unreadable paths as \"refused\" rather than\n * \"OK to write\". */\nfunction isRealpathInside(absPath: string, rootPath: string): boolean {\n try {\n const real = realpathSync(absPath);\n const rootReal = realpathSync(rootPath);\n return real === rootReal || real.startsWith(rootReal + path.sep);\n } catch {\n return false;\n }\n}\n\ntype DestVerdict = { ok: true } | { ok: false; reason: string } | { kind: \"not-active\" };\n\n/** Validate the active dest slug dir before writing through it.\n * Returns:\n * - `{ ok: true }` — proceed with the sync\n * - `{ kind: \"not-active\" }` — slug hasn't been starred yet\n * - `{ ok: false; reason }` — refuse to write (symlink escape,\n * non-directory, ancestor escape)\n *\n * Symlink defenses (Codex P1 review on PR #1490): `statSync`\n * follows symlinks, so a starred `mc-*` slug that's actually a\n * symlink to /etc would let the recursive copy below write\n * outside the workspace. Two-layer defense:\n * 1. `lstatSync` to see the link itself; if it's a symlink,\n * only accept when its target stays inside `activeDir`.\n * 2. Always realpath-verify the full path (catches the case\n * where an ancestor like `.claude/` is symlinked even when\n * the slug dir itself is a regular directory). */\nfunction classifyActiveDest(slug: string, destSlugDir: string, activeDir: string): DestVerdict {\n let destInfo;\n try {\n destInfo = lstatSync(destSlugDir);\n } catch {\n return { kind: \"not-active\" };\n }\n if (destInfo.isSymbolicLink()) {\n if (!isRealpathInside(destSlugDir, activeDir)) {\n return { ok: false, reason: \"active slot is a symlink whose target escapes activeDir; refusing to write through it\" };\n }\n return { ok: true };\n }\n if (!destInfo.isDirectory()) {\n return { ok: false, reason: \"active slot is occupied by a non-directory; skipping\" };\n }\n if (!isRealpathInside(destSlugDir, activeDir)) {\n return { ok: false, reason: \"active slug dir escapes activeDir via an ancestor symlink\" };\n }\n return { ok: true };\n}\n\n/** Per-slug worker for `syncActivePresetSkills`. Extracted to keep\n * the outer function under the `sonarjs/cognitive-complexity`\n * threshold; no behavior difference vs the inline loop. */\nfunction processActiveSlug(slug: string, opts: SyncActivePresetSkillsOptions, result: SyncActivePresetSkillsResult, backupExt: string): void {\n const srcSlugDir = path.join(opts.sourceDir, slug);\n try {\n if (!statSync(srcSlugDir).isDirectory()) return;\n } catch {\n return;\n }\n const destSlugDir = path.join(opts.activeDir, slug);\n const verdict = classifyActiveDest(slug, destSlugDir, opts.activeDir);\n if (\"kind\" in verdict) {\n result.notActive.push(slug);\n return;\n }\n if (!verdict.ok) {\n result.skipped.push(`${slug}: ${verdict.reason}`);\n opts.onWarn?.(\"active preset sync skipped\", { slug, reason: verdict.reason, destSlugDir });\n return;\n }\n const stats = syncDirTreeDiff(srcSlugDir, destSlugDir, backupExt);\n if (stats.updated > 0) {\n result.updated.push(slug);\n opts.onInfo?.(\"active preset skill updated from source\", { slug, files: stats.updated, backupSuffix: backupExt });\n } else if (stats.skipped === 0) {\n result.unchanged.push(slug);\n }\n if (stats.skipped > 0) {\n result.skipped.push(`${slug}: ${stats.skipped} file(s) skipped`);\n opts.onWarn?.(\"active preset skill partial update\", { slug, skipped: stats.skipped });\n }\n}\n\n/** Realpath targets of active symlinks. Used so the prune below never\n * deletes a directory that's serving as a symlink target (e.g. a\n * git-managed checkout the user symlinks an active slug to). */\nfunction collectSymlinkTargets(activeDir: string, entries: readonly string[]): Set<string> {\n const targets = new Set<string>();\n for (const slug of entries) {\n const entryPath = path.join(activeDir, slug);\n try {\n if (lstatSync(entryPath).isSymbolicLink()) targets.add(realpathSync(entryPath));\n } catch {\n /* unreadable — ignore */\n }\n }\n return targets;\n}\n\n/** True iff the active `slug` is a retired preset safe to delete: an\n * `mc-*` real directory inside `activeDir`, with no source preset, and\n * not itself a symlink or a symlink target. */\nfunction isRetiredActiveSlug(slug: string, activeDir: string, sourceSlugs: ReadonlySet<string>, symlinkTargets: ReadonlySet<string>): boolean {\n if (!isPresetSlug(slug) || sourceSlugs.has(slug)) return false;\n const destSlugDir = path.join(activeDir, slug);\n let info;\n try {\n info = lstatSync(destSlugDir);\n } catch {\n return false;\n }\n if (info.isSymbolicLink() || !info.isDirectory()) return false;\n if (!isRealpathInside(destSlugDir, activeDir)) return false;\n try {\n return !symlinkTargets.has(realpathSync(destSlugDir));\n } catch {\n return false;\n }\n}\n\n/** Prune active `mc-*` slugs whose launcher source preset no longer\n * exists (a retired preset). Without this, an upgraded workspace that\n * had starred a since-removed preset (e.g. `mc-manage-sources`) keeps\n * the active copy forever — Claude would still discover a skill whose\n * backend was deleted. Bounded to `mc-*` real directories that stay\n * inside `activeDir` (never a symlink escape, never a user skill). */\nfunction removeRetiredActivePresets(opts: SyncActivePresetSkillsOptions, result: SyncActivePresetSkillsResult, sourceSlugs: ReadonlySet<string>): void {\n let activeEntries: string[];\n try {\n activeEntries = readdirSync(opts.activeDir);\n } catch {\n return; // no active dir yet → nothing to prune\n }\n const symlinkTargets = collectSymlinkTargets(opts.activeDir, activeEntries);\n for (const slug of activeEntries) {\n if (!isRetiredActiveSlug(slug, opts.activeDir, sourceSlugs, symlinkTargets)) continue;\n try {\n rmSync(path.join(opts.activeDir, slug), { recursive: true, force: true });\n result.removed.push(slug);\n opts.onInfo?.(\"removed retired active preset skill\", { slug });\n } catch (err) {\n result.skipped.push(`${slug}: prune failed: ${errorMessage(err)}`);\n opts.onWarn?.(\"active preset prune failed\", { slug, reason: errorMessage(err) });\n }\n }\n}\n\n/** Refresh every already-starred `mc-*` preset's active copy in\n * `<workspaceRoot>/.claude/skills/<slug>/` to match the source.\n * Per-file diff with `.bak.<timestamp>` backup on overwrite. Slugs\n * that aren't starred yet are listed in `notActive` but never\n * auto-created. */\nexport function syncActivePresetSkills(opts: SyncActivePresetSkillsOptions): SyncActivePresetSkillsResult {\n const result: SyncActivePresetSkillsResult = { updated: [], unchanged: [], notActive: [], removed: [], skipped: [], backupSuffix: null };\n if (!existsSync(opts.sourceDir)) return result;\n let sourceInfo;\n try {\n sourceInfo = statSync(opts.sourceDir);\n } catch (err) {\n return abortActiveSync(opts, result, `source path stat failed: ${errorMessage(err)}`);\n }\n if (!sourceInfo.isDirectory()) {\n return abortActiveSync(opts, result, \"source path exists as a non-directory; active preset sync skipped\");\n }\n let sourceEntries: string[];\n try {\n sourceEntries = readdirSync(opts.sourceDir);\n } catch (err) {\n return abortActiveSync(opts, result, `source readdir failed: ${errorMessage(err)}`);\n }\n // Single timestamp per run so a multi-file update produces sibling\n // backups with a matching suffix — easier to grep / restore.\n const backupExt = `.bak.${Date.now()}`;\n result.backupSuffix = backupExt;\n const sourceSlugs = new Set<string>();\n for (const slug of sourceEntries) {\n if (slug.startsWith(\".\")) continue;\n if (!isPresetSlug(slug)) continue;\n sourceSlugs.add(slug);\n processActiveSlug(slug, opts, result, backupExt);\n }\n // Prune active copies of presets the launcher no longer ships.\n removeRetiredActivePresets(opts, result, sourceSlugs);\n if (result.updated.length > 0 || result.removed.length > 0) {\n opts.onInfo?.(\"active preset skills synced\", {\n updated: result.updated.length,\n unchanged: result.unchanged.length,\n notActive: result.notActive.length,\n removed: result.removed.length,\n skipped: result.skipped.length,\n backupSuffix: backupExt,\n });\n }\n return result;\n}\n","// Resolve the package's BUNDLED assets (shipped via package.json `files`) and seed\n// them into a workspace. ESM-only: `import.meta.url` points at this module under\n// `dist/workspace-setup/`, so `../../assets` is the package's assets dir at the\n// package root. (The workspace-setup entries build ESM only — `import.meta.url`\n// isn't available under CJS; both hosts run the server as ESM via tsx.)\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { copyFileSync, mkdirSync, readdirSync } from \"node:fs\";\n\n// The asset dir is shipped separately (package.json `files`), NOT bundled, so\n// this URL must resolve at runtime. `@vite-ignore` silences Vite's build-time\n// \"doesn't exist at build time\" warning — runtime resolution is intended.\nconst ASSETS_DIR = fileURLToPath(new URL(/* @vite-ignore */ \"../../assets\", import.meta.url));\n\n/** The bundled help-docs source dir (`assets/helps/`). */\nexport function helpsAssetDir(): string {\n return path.join(ASSETS_DIR, \"helps\");\n}\n\n/** The bundled preset-skills source dir (`assets/skills-preset/`) — pass as the\n * `sourceDir` of `syncPresetSkills` / `syncActivePresetSkills`. */\nexport function presetSkillsAssetDir(): string {\n return path.join(ASSETS_DIR, \"skills-preset\");\n}\n\n/** Copy every bundled help doc into `destDir` (created if missing). Idempotent —\n * overwrites on each call so the help docs always track the package's version. */\nexport function seedHelps(opts: { destDir: string }): void {\n mkdirSync(opts.destDir, { recursive: true });\n const src = helpsAssetDir();\n for (const file of readdirSync(src)) {\n copyFileSync(path.join(src, file), path.join(opts.destDir, file));\n }\n}\n"],"mappings":";;;;;;AA6BA,SAAS,aAAa,KAAsB;CAC1C,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACxD;AASA,SAAS,gBAAgB,QAAgB,SAAuB;CAC9D,UAAU,SAAS,EAAE,WAAW,KAAK,CAAC;CACtC,KAAK,MAAM,SAAS,YAAY,QAAQ,EAAE,eAAe,KAAK,CAAC,GAAG;EAChE,MAAM,UAAU,KAAK,KAAK,QAA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QAAQ;EACxB,cAAc;CAChB,CAAC;CAEH,OAAO;AACT;;;AC1oBA,IAAM,aAAa,cAAc,IAAI;;CAAuB;CAAgB,OAAO,KAAK;AAAG,CAAC;;AAG5F,SAAgB,gBAAwB;CACtC,OAAO,KAAK,KAAK,YAAY,OAAO;AACtC;;;AAIA,SAAgB,uBAA+B;CAC7C,OAAO,KAAK,KAAK,YAAY,eAAe;AAC9C;;;AAIA,SAAgB,UAAU,MAAiC;CACzD,UAAU,KAAK,SAAS,EAAE,WAAW,KAAK,CAAC;CAC3C,MAAM,MAAM,cAAc;CAC1B,KAAK,MAAM,QAAQ,YAAY,GAAG,GAChC,aAAa,KAAK,KAAK,KAAK,IAAI,GAAG,KAAK,KAAK,KAAK,SAAS,IAAI,CAAC;AAEpE"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/utils/errors.ts","../../src/workspace-setup/sync.ts","../../src/workspace-setup/assets.ts"],"sourcesContent":["// Canonical error helpers for the whole monorepo. Host (`server/`, `src/`)\n// re-exports these rather than keeping its own copy — before #2217 the same\n// function existed 14 times across 4 behaviours, and the two that mattered\n// disagreed on gRPC-shaped errors: `{ code, details, metadata }` surfaced as\n// \"quota exceeded\" through the host copy and as \"[object Object]\" through the\n// core ones. Browser-safe: pure string work, no node imports.\n\n// Non-Error objects with a `details` (gRPC convention) or `message` string\n// field have that field surfaced — without this they stringify to\n// `[object Object]`.\n//\n// `fallback` covers the route-handler idiom where a throw of a plain non-Error\n// value should surface as a descriptive message (\"rebuild failed\") rather than\n// `String(err)` noise. Pass one at error-response boundaries; omit it for\n// logging contexts where `String(err)` is fine.\nexport function errorMessage(err: unknown, fallback?: string): string {\n if (err instanceof Error) return err.message;\n if (err !== null && typeof err === \"object\") {\n const obj = err as { details?: unknown; message?: unknown };\n if (typeof obj.details === \"string\" && obj.details) return obj.details;\n if (typeof obj.message === \"string\" && obj.message) return obj.message;\n }\n if (fallback !== undefined) return fallback;\n return String(err);\n}\n\n// Coerce an unknown caught value into an Error, preserving the original if it\n// already was one. Use in error boundaries / Promise rejections / event-handler\n// onerror callbacks where the downstream API wants an Error object.\n//\n// `fallback` is the message used when coercing a non-Error value — pass a\n// descriptive string for cases where `String(err)` would just produce noise\n// (e.g. `<img>.onerror` hands you an Event, not the underlying load failure).\nexport function toError(err: unknown, fallback?: string): Error {\n if (err instanceof Error) return err;\n return new Error(fallback ?? errorMessage(err));\n}\n","// Preset skills bundled with mulmoclaude.\n//\n// History: introduced in #1210 to ship launcher-managed \"factory\"\n// skills like `mc-library`. Originally synced straight into\n// `<workspaceRoot>/.claude/skills/<slug>/`, which made every preset\n// auto-active and inflated the Claude system prompt as new presets\n// landed.\n//\n// #1335 PR-A flipped the destination to the catalog\n// (`<workspaceRoot>/data/skills/catalog/preset/<slug>/`). Catalog\n// entries are visible to UI / tooling but NOT discovered by Claude\n// Code's slash-command resolver — they don't enter the system\n// prompt unless the user (or a later UI in PR-B) explicitly copies\n// one into `.claude/skills/`.\n//\n// The launcher overwrites catalog entries unconditionally on every\n// boot — they're factory defaults, not user state. Anything in\n// `.claude/skills/` (active layer) is left untouched.\n//\n// `syncPresetSkills(...)` is exported as a pure-ish helper (takes\n// paths + a logger sink, returns a summary) so tests can drive it\n// against tmpdirs without touching a real workspace.\n\nimport { copyFileSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, type Dirent } from \"node:fs\";\nimport { randomUUID } from \"node:crypto\";\nimport path from \"node:path\";\nimport { PRESET_SLUG_PREFIX, isPresetSlug } from \"./slug.js\";\nimport { errorMessage } from \"../utils/errors.js\";\n\n// Recursively mirror `srcDir` into `destDir`. Used by the preset\n// sync so a preset skill that ships sibling assets (e.g.\n// `schema.json` for schema-driven apps, `templates/*.html`) gets\n// copied alongside `SKILL.md` rather than silently dropped. Only\n// regular files and directories are followed — symlinks / FIFOs /\n// sockets are skipped because the preset tree is launcher-managed\n// and shouldn't contain them.\nfunction copyDirTreeSync(srcDir: string, destDir: string): void {\n mkdirSync(destDir, { recursive: true });\n for (const entry of readdirSync(srcDir, { withFileTypes: true })) {\n const srcPath = path.join(srcDir, entry.name);\n const destPath = path.join(destDir, entry.name);\n if (entry.isDirectory()) {\n copyDirTreeSync(srcPath, destPath);\n } else if (entry.isFile()) {\n copyFileSync(srcPath, destPath);\n }\n }\n}\n\nconst SKILL_FILENAME = \"SKILL.md\";\n\nexport interface SyncPresetSkillsOptions {\n /** Source directory: `<launcher>/server/workspace/skills-preset/`. */\n sourceDir: string;\n /** Destination directory:\n * `<workspaceRoot>/data/skills/catalog/preset/`. The catalog\n * half of the catalog-vs-active split — entries here are visible\n * to UI but NOT to Claude Code's prompt-time skill resolver. */\n destDir: string;\n /** Logger callbacks — kept injectable so tests don't need to\n * spin up the structured logger. The boot-side wrapper threads\n * these through to `log.info` / `log.warn`. */\n onInfo?: (message: string, data?: Record<string, unknown>) => void;\n onWarn?: (message: string, data?: Record<string, unknown>) => void;\n}\n\nexport interface SyncPresetSkillsResult {\n /** Slugs successfully copied (or refreshed) from source to dest. */\n copied: string[];\n /** Slugs removed from dest because they no longer exist in source.\n * Bounded to `mc-*` entries — user-authored slugs are never\n * considered for removal. */\n removed: string[];\n /** Source entries that failed validation (wrong prefix, missing\n * SKILL.md, etc.) and were skipped. Each entry is human-readable. */\n skipped: string[];\n}\n\n// Classification of one source entry. `silent` distinguishes\n// structural skips (hidden files, non-directory entries — not the\n// dev's fault) from misconfigurations (bad slug, missing or\n// non-regular SKILL.md — the dev WANTS to know). The boolean lives\n// on the verdict so the caller never has to string-match `reason`,\n// which would silently drop warnings if reason wording changed\n// (CodeRabbit review).\ntype Verdict = { ok: true } | { ok: false; reason: string; silent: boolean };\n\nfunction classifySourceEntry(sourceDir: string, entry: string): Verdict {\n if (entry.startsWith(\".\")) return { ok: false, reason: \"hidden\", silent: true };\n const slugDir = path.join(sourceDir, entry);\n let dirInfo;\n try {\n dirInfo = statSync(slugDir);\n } catch {\n return { ok: false, reason: \"stat failed\", silent: true };\n }\n if (!dirInfo.isDirectory()) return { ok: false, reason: \"not a directory\", silent: true };\n if (!isPresetSlug(entry)) return { ok: false, reason: `slug must start with \"${PRESET_SLUG_PREFIX}\"`, silent: false };\n // Validate SKILL.md is a regular file — `existsSync` alone\n // accepts a directory at that path, which would then crash\n // copyFileSync. Codex review caught this edge case.\n const skillPath = path.join(slugDir, SKILL_FILENAME);\n let skillInfo;\n try {\n skillInfo = statSync(skillPath);\n } catch {\n return { ok: false, reason: `missing ${SKILL_FILENAME}`, silent: false };\n }\n if (!skillInfo.isFile()) return { ok: false, reason: `${SKILL_FILENAME} must be a regular file`, silent: false };\n return { ok: true };\n}\n\n/** Prepare the destination slug dir. Returns false if the slot is\n * occupied by a regular file (local corruption / hand edits) — the\n * caller logs + skips so one bad entry can't crash the whole boot\n * (Codex review iter-1). */\nfunction ensureDestSlugDir(destSlugDir: string): boolean {\n let info;\n try {\n info = statSync(destSlugDir);\n } catch {\n mkdirSync(destSlugDir, { recursive: true });\n return true;\n }\n return info.isDirectory();\n}\n\n/** Filesystem ops `_replaceSlugTree` depends on — injectable so the\n * mid-swap failure path can be regression-tested without real IO faults. */\nexport interface SlugTreeFsOps {\n copyTree: (src: string, dest: string) => void;\n rename: (from: string, dest: string) => void;\n remove: (target: string) => void;\n exists: (target: string) => boolean;\n}\n\nconst REAL_FS_OPS: SlugTreeFsOps = {\n copyTree: copyDirTreeSync,\n rename: renameSync,\n remove: (target) => rmSync(target, { recursive: true, force: true }),\n exists: existsSync,\n};\n\n/** Refresh one preset slot as a rollback-safe stage-and-swap. Wipe-and-replace\n * (not merge) so stale sibling assets — e.g. a schema.json dropped between\n * releases — don't linger; the catalog preset slot is launcher-owned, so user\n * edits there are not preserved across boots.\n *\n * The live slot is never left without a recoverable copy:\n * 1. Stage: copy the source into a temp sibling. A copy failure leaves the\n * existing preset untouched (temp dir removed).\n * 2. Move the existing tree ASIDE to a backup (rename, not delete), so the\n * old contents survive even if the next step fails.\n * 3. Move the staged copy into place. On failure, restore from the backup;\n * if even the restore fails, BOTH backup and staging are preserved for\n * manual recovery rather than deleted.\n * 4. On success, drop the backup.\n *\n * Exported with a `_` prefix only so the rename-failure-after-move path can be\n * regression-tested via the injected `fsOps`. Throws on failure (caller records\n * + skips). */\nexport function _replaceSlugTree(sourceSlugDir: string, destSlugDir: string, fsOps: SlugTreeFsOps = REAL_FS_OPS): void {\n const staging = `${destSlugDir}.tmp-${randomUUID()}`;\n try {\n fsOps.copyTree(sourceSlugDir, staging);\n } catch (err) {\n fsOps.remove(staging); // dest untouched\n throw err;\n }\n const backup = `${destSlugDir}.bak-${randomUUID()}`;\n let backedUp = false;\n if (fsOps.exists(destSlugDir)) {\n try {\n fsOps.rename(destSlugDir, backup);\n backedUp = true;\n } catch (err) {\n fsOps.remove(staging); // dest untouched; nothing was moved\n throw err;\n }\n }\n try {\n fsOps.rename(staging, destSlugDir);\n } catch (err) {\n if (backedUp) {\n try {\n fsOps.rename(backup, destSlugDir); // roll back to the previous tree\n fsOps.remove(staging);\n } catch {\n // Rollback failed — preserve BOTH backup and staging for manual\n // recovery rather than leaving the slot empty.\n }\n } else {\n fsOps.remove(staging); // dest never existed; nothing to restore\n }\n throw err;\n }\n if (backedUp) fsOps.remove(backup);\n}\n\nfunction copySourcesIntoDest(sourceDir: string, destDir: string, opts: SyncPresetSkillsOptions, result: SyncPresetSkillsResult): Set<string> {\n // `keep` is the set of slugs the retirement pass must NOT prune. It tracks\n // valid SOURCE slugs (present + usable dest slot), NOT successful copies — so\n // a slug whose refresh fails transiently keeps its existing contents (left\n // intact by the stage-and-swap above) instead of being pruned as \"retired\".\n const keep = new Set<string>();\n for (const entry of readdirSync(sourceDir)) {\n const verdict = classifySourceEntry(sourceDir, entry);\n if (!verdict.ok) {\n if (!verdict.silent) {\n result.skipped.push(`${entry}: ${verdict.reason}`);\n opts.onWarn?.(\"preset entry skipped\", { slug: entry, reason: verdict.reason });\n }\n continue;\n }\n const destSlugDir = path.join(destDir, entry);\n if (!ensureDestSlugDir(destSlugDir)) {\n const reason = \"destination slot occupied by a non-directory; skipping\";\n result.skipped.push(`${entry}: ${reason}`);\n opts.onWarn?.(\"preset entry skipped\", { slug: entry, reason, destSlugDir });\n continue;\n }\n // The slug exists in source with a usable dest slot — keep it regardless of\n // whether the refresh below succeeds, so a transient failure doesn't get it\n // pruned by `removeRetiredPresets`.\n keep.add(entry);\n // Per-slug isolation: a transient IO error / permission issue / partial\n // corruption on one preset must not abort syncing the rest, nor destroy\n // the existing copy. Skip the offender (recorded) and continue.\n try {\n _replaceSlugTree(path.join(sourceDir, entry), destSlugDir);\n result.copied.push(entry);\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n result.skipped.push(`${entry}: ${reason}`);\n opts.onWarn?.(\"preset copy failed, skipping\", { slug: entry, reason });\n }\n }\n return keep;\n}\n\nfunction removeRetiredPresets(destDir: string, keep: ReadonlySet<string>, opts: SyncPresetSkillsOptions, result: SyncPresetSkillsResult): void {\n for (const entry of readdirSync(destDir)) {\n if (!isPresetSlug(entry)) continue;\n if (keep.has(entry)) continue;\n const stalePath = path.join(destDir, entry);\n try {\n if (!statSync(stalePath).isDirectory()) continue;\n } catch {\n continue;\n }\n rmSync(stalePath, { recursive: true, force: true });\n result.removed.push(entry);\n opts.onInfo?.(\"removed retired preset skill\", { slug: entry });\n }\n}\n\n/** Copy every preset slug from `sourceDir` into `destDir` (the\n * preset slot under the catalog root), then remove any `mc-*`\n * entries in `destDir` that no longer have a source. The catalog\n * preset subdir is fully launcher-owned, so the `mc-*` prefix\n * check at destination is defence-in-depth: a stray non-preset\n * slug landing in `catalog/preset/` is unexpected, and we'd\n * rather skip it than silently delete a directory we don't\n * recognise. */\nexport function syncPresetSkills(opts: SyncPresetSkillsOptions): SyncPresetSkillsResult {\n const result: SyncPresetSkillsResult = { copied: [], removed: [], skipped: [] };\n if (!existsSync(opts.sourceDir)) {\n // No preset directory in the launcher tarball — nothing to do.\n // This is the legitimate \"no presets shipped yet\" state.\n return result;\n }\n // Source-side validation: the launcher's preset path COULD exist\n // as a regular file (a packaging bug, a corrupted install). Without\n // this guard, `readdirSync(sourceDir)` would throw ENOTDIR and\n // crash boot. Codex review iter-3.\n let sourceInfo;\n try {\n sourceInfo = statSync(opts.sourceDir);\n } catch (err) {\n const reason = `source path stat failed: ${errorMessage(err)}`;\n result.skipped.push(`${opts.sourceDir}: ${reason}`);\n opts.onWarn?.(\"preset sync aborted\", { sourceDir: opts.sourceDir, reason });\n return result;\n }\n if (!sourceInfo.isDirectory()) {\n const reason = \"source path exists as a non-directory; preset sync skipped\";\n result.skipped.push(`${opts.sourceDir}: ${reason}`);\n opts.onWarn?.(\"preset sync aborted\", { sourceDir: opts.sourceDir, reason });\n return result;\n }\n // The root dest itself can be corrupted into a regular file by a\n // user / external tool; mkdirSync would throw EEXIST and crash\n // boot. Treat it as a recoverable \"skip the entire sync\" state\n // — log a clear warning so the user sees what to fix.\n // (Codex review iter-2.)\n if (!ensureDestSlugDir(opts.destDir)) {\n const reason = \"root dest exists as a non-directory; preset sync skipped\";\n result.skipped.push(`${opts.destDir}: ${reason}`);\n opts.onWarn?.(\"preset sync aborted\", { destDir: opts.destDir, reason });\n return result;\n }\n const keep = copySourcesIntoDest(opts.sourceDir, opts.destDir, opts, result);\n removeRetiredPresets(opts.destDir, keep, opts, result);\n if (result.copied.length > 0 || result.removed.length > 0) {\n opts.onInfo?.(\"preset skills synced\", {\n copied: result.copied.length,\n removed: result.removed.length,\n skipped: result.skipped.length,\n });\n }\n return result;\n}\n\n// ---------------------------------------------------------------\n// Active-layer sync: keep starred mc-* presets in lockstep with\n// their launcher-bundled source.\n//\n// Motivation: the catalog sync above refreshes\n// `data/skills/catalog/preset/<slug>/` on every boot, but once a\n// user stars an entry the active copy in\n// `<workspace>/.claude/skills/<slug>/` is never updated even when\n// the launcher ships a new SKILL.md (e.g. a typo fix or, as the\n// trigger for this code, the schema-driven-apps → collections\n// rename). The SKILL.md front-matter explicitly says\n// \"do not edit this file in the workspace, it is overwritten on\n// every server boot\" — until this function existed, that was a\n// promise the active layer didn't keep.\n//\n// Safety model:\n// - Only `mc-*` slugs are touched (defensive prefix check —\n// never touches user-authored skills).\n// - Per-file diff: a file is overwritten only if its bytes\n// differ from the source. No-op when already up to date.\n// - User-added files inside an active slug dir are left alone\n// (we walk the source tree, not the dest tree).\n// - If a file IS overwritten, the previous contents are first\n// renamed to `<file>.bak.<timestamp>` so a user who had\n// locally tweaked the preset can recover.\n// - A slug whose active dir doesn't exist (= not starred yet)\n// is skipped entirely, never auto-starred.\n// ---------------------------------------------------------------\n\nexport interface SyncActivePresetSkillsOptions {\n /** Source directory: `<launcher>/server/workspace/skills-preset/`. */\n sourceDir: string;\n /** Active skills directory: `<workspaceRoot>/.claude/skills/`. */\n activeDir: string;\n onInfo?: (message: string, data?: Record<string, unknown>) => void;\n onWarn?: (message: string, data?: Record<string, unknown>) => void;\n}\n\nexport interface SyncActivePresetSkillsResult {\n /** Slugs whose active copy had at least one file overwritten. */\n updated: string[];\n /** Slugs whose active copy already matched the source — no-op. */\n unchanged: string[];\n /** Slugs that haven't been starred yet (no active dir present).\n * Listed for diagnostics; the function never auto-stars. */\n notActive: string[];\n /** Active `mc-*` slugs pruned because the launcher no longer ships a\n * source preset for them (a retired preset). Bounded to `mc-*` —\n * user-authored skills are never removed. */\n removed: string[];\n /** Per-slug failure messages (permission errors, etc.). */\n skipped: string[];\n /** Common timestamp suffix used for every backup file produced by\n * this run. Exposed so the boot-time log can point a user at the\n * exact glob to inspect. */\n backupSuffix: string | null;\n}\n\ntype FileSyncOutcome = \"updated\" | \"unchanged\" | \"skipped\";\n\nfunction filesEqual(left: string, right: string): boolean {\n try {\n return readFileSync(left).equals(readFileSync(right));\n } catch {\n return false;\n }\n}\n\n/** Copy `srcPath` over `destPath`. If `destPath` already exists and\n * differs, rename it to `destPath + backupExt` first so the user's\n * prior contents are recoverable. If `destPath` doesn't exist, just\n * copy (no backup needed). Pure: no logging here — caller decides. */\nfunction syncOneFile(srcPath: string, destPath: string, backupExt: string): FileSyncOutcome {\n let destExists: boolean;\n try {\n destExists = statSync(destPath).isFile();\n } catch {\n destExists = false;\n }\n if (!destExists) {\n try {\n copyFileSync(srcPath, destPath);\n return \"updated\";\n } catch {\n return \"skipped\";\n }\n }\n if (filesEqual(srcPath, destPath)) return \"unchanged\";\n try {\n renameSync(destPath, destPath + backupExt);\n copyFileSync(srcPath, destPath);\n return \"updated\";\n } catch {\n return \"skipped\";\n }\n}\n\ninterface DirSyncStats {\n updated: number;\n unchanged: number;\n skipped: number;\n}\n\nfunction syncDirTreeDiff(srcDir: string, destDir: string, backupExt: string): DirSyncStats {\n const stats: DirSyncStats = { updated: 0, unchanged: 0, skipped: 0 };\n try {\n mkdirSync(destDir, { recursive: true });\n } catch {\n stats.skipped++;\n return stats;\n }\n let entries: Dirent[];\n try {\n entries = readdirSync(srcDir, { withFileTypes: true });\n } catch {\n stats.skipped++;\n return stats;\n }\n for (const entry of entries) {\n const srcPath = path.join(srcDir, entry.name);\n const destPath = path.join(destDir, entry.name);\n if (entry.isDirectory()) {\n const sub = syncDirTreeDiff(srcPath, destPath, backupExt);\n stats.updated += sub.updated;\n stats.unchanged += sub.unchanged;\n stats.skipped += sub.skipped;\n } else if (entry.isFile()) {\n const outcome = syncOneFile(srcPath, destPath, backupExt);\n stats[outcome]++;\n }\n // Symlinks / sockets / FIFOs intentionally ignored (the launcher\n // preset tree shouldn't contain them).\n }\n return stats;\n}\n\nfunction abortActiveSync(opts: SyncActivePresetSkillsOptions, result: SyncActivePresetSkillsResult, reason: string): SyncActivePresetSkillsResult {\n result.skipped.push(`${opts.sourceDir}: ${reason}`);\n opts.onWarn?.(\"active preset sync aborted\", { sourceDir: opts.sourceDir, reason });\n return result;\n}\n\n/** True iff `absPath`'s realpath resolves inside `rootPath`'s\n * realpath. Defends `processActiveSlug` against a starred `mc-*`\n * slug that's actually a symlink to somewhere outside\n * `activeDir`: without this check, the recursive copy below would\n * follow the symlink and write through to the link's target\n * (potentially anywhere on disk). Returns false on any error so\n * the caller treats unreadable paths as \"refused\" rather than\n * \"OK to write\". */\nfunction isRealpathInside(absPath: string, rootPath: string): boolean {\n try {\n const real = realpathSync(absPath);\n const rootReal = realpathSync(rootPath);\n return real === rootReal || real.startsWith(rootReal + path.sep);\n } catch {\n return false;\n }\n}\n\ntype DestVerdict = { ok: true } | { ok: false; reason: string } | { kind: \"not-active\" };\n\n/** Validate the active dest slug dir before writing through it.\n * Returns:\n * - `{ ok: true }` — proceed with the sync\n * - `{ kind: \"not-active\" }` — slug hasn't been starred yet\n * - `{ ok: false; reason }` — refuse to write (symlink escape,\n * non-directory, ancestor escape)\n *\n * Symlink defenses (Codex P1 review on PR #1490): `statSync`\n * follows symlinks, so a starred `mc-*` slug that's actually a\n * symlink to /etc would let the recursive copy below write\n * outside the workspace. Two-layer defense:\n * 1. `lstatSync` to see the link itself; if it's a symlink,\n * only accept when its target stays inside `activeDir`.\n * 2. Always realpath-verify the full path (catches the case\n * where an ancestor like `.claude/` is symlinked even when\n * the slug dir itself is a regular directory). */\nfunction classifyActiveDest(slug: string, destSlugDir: string, activeDir: string): DestVerdict {\n let destInfo;\n try {\n destInfo = lstatSync(destSlugDir);\n } catch {\n return { kind: \"not-active\" };\n }\n if (destInfo.isSymbolicLink()) {\n if (!isRealpathInside(destSlugDir, activeDir)) {\n return { ok: false, reason: \"active slot is a symlink whose target escapes activeDir; refusing to write through it\" };\n }\n return { ok: true };\n }\n if (!destInfo.isDirectory()) {\n return { ok: false, reason: \"active slot is occupied by a non-directory; skipping\" };\n }\n if (!isRealpathInside(destSlugDir, activeDir)) {\n return { ok: false, reason: \"active slug dir escapes activeDir via an ancestor symlink\" };\n }\n return { ok: true };\n}\n\n/** Per-slug worker for `syncActivePresetSkills`. Extracted to keep\n * the outer function under the `sonarjs/cognitive-complexity`\n * threshold; no behavior difference vs the inline loop. */\nfunction processActiveSlug(slug: string, opts: SyncActivePresetSkillsOptions, result: SyncActivePresetSkillsResult, backupExt: string): void {\n const srcSlugDir = path.join(opts.sourceDir, slug);\n try {\n if (!statSync(srcSlugDir).isDirectory()) return;\n } catch {\n return;\n }\n const destSlugDir = path.join(opts.activeDir, slug);\n const verdict = classifyActiveDest(slug, destSlugDir, opts.activeDir);\n if (\"kind\" in verdict) {\n result.notActive.push(slug);\n return;\n }\n if (!verdict.ok) {\n result.skipped.push(`${slug}: ${verdict.reason}`);\n opts.onWarn?.(\"active preset sync skipped\", { slug, reason: verdict.reason, destSlugDir });\n return;\n }\n const stats = syncDirTreeDiff(srcSlugDir, destSlugDir, backupExt);\n if (stats.updated > 0) {\n result.updated.push(slug);\n opts.onInfo?.(\"active preset skill updated from source\", { slug, files: stats.updated, backupSuffix: backupExt });\n } else if (stats.skipped === 0) {\n result.unchanged.push(slug);\n }\n if (stats.skipped > 0) {\n result.skipped.push(`${slug}: ${stats.skipped} file(s) skipped`);\n opts.onWarn?.(\"active preset skill partial update\", { slug, skipped: stats.skipped });\n }\n}\n\n/** Realpath targets of active symlinks. Used so the prune below never\n * deletes a directory that's serving as a symlink target (e.g. a\n * git-managed checkout the user symlinks an active slug to). */\nfunction collectSymlinkTargets(activeDir: string, entries: readonly string[]): Set<string> {\n const targets = new Set<string>();\n for (const slug of entries) {\n const entryPath = path.join(activeDir, slug);\n try {\n if (lstatSync(entryPath).isSymbolicLink()) targets.add(realpathSync(entryPath));\n } catch {\n /* unreadable — ignore */\n }\n }\n return targets;\n}\n\n/** True iff the active `slug` is a retired preset safe to delete: an\n * `mc-*` real directory inside `activeDir`, with no source preset, and\n * not itself a symlink or a symlink target. */\nfunction isRetiredActiveSlug(slug: string, activeDir: string, sourceSlugs: ReadonlySet<string>, symlinkTargets: ReadonlySet<string>): boolean {\n if (!isPresetSlug(slug) || sourceSlugs.has(slug)) return false;\n const destSlugDir = path.join(activeDir, slug);\n let info;\n try {\n info = lstatSync(destSlugDir);\n } catch {\n return false;\n }\n if (info.isSymbolicLink() || !info.isDirectory()) return false;\n if (!isRealpathInside(destSlugDir, activeDir)) return false;\n try {\n return !symlinkTargets.has(realpathSync(destSlugDir));\n } catch {\n return false;\n }\n}\n\n/** Prune active `mc-*` slugs whose launcher source preset no longer\n * exists (a retired preset). Without this, an upgraded workspace that\n * had starred a since-removed preset (e.g. `mc-manage-sources`) keeps\n * the active copy forever — Claude would still discover a skill whose\n * backend was deleted. Bounded to `mc-*` real directories that stay\n * inside `activeDir` (never a symlink escape, never a user skill). */\nfunction removeRetiredActivePresets(opts: SyncActivePresetSkillsOptions, result: SyncActivePresetSkillsResult, sourceSlugs: ReadonlySet<string>): void {\n let activeEntries: string[];\n try {\n activeEntries = readdirSync(opts.activeDir);\n } catch {\n return; // no active dir yet → nothing to prune\n }\n const symlinkTargets = collectSymlinkTargets(opts.activeDir, activeEntries);\n for (const slug of activeEntries) {\n if (!isRetiredActiveSlug(slug, opts.activeDir, sourceSlugs, symlinkTargets)) continue;\n try {\n rmSync(path.join(opts.activeDir, slug), { recursive: true, force: true });\n result.removed.push(slug);\n opts.onInfo?.(\"removed retired active preset skill\", { slug });\n } catch (err) {\n result.skipped.push(`${slug}: prune failed: ${errorMessage(err)}`);\n opts.onWarn?.(\"active preset prune failed\", { slug, reason: errorMessage(err) });\n }\n }\n}\n\n/** Refresh every already-starred `mc-*` preset's active copy in\n * `<workspaceRoot>/.claude/skills/<slug>/` to match the source.\n * Per-file diff with `.bak.<timestamp>` backup on overwrite. Slugs\n * that aren't starred yet are listed in `notActive` but never\n * auto-created. */\nexport function syncActivePresetSkills(opts: SyncActivePresetSkillsOptions): SyncActivePresetSkillsResult {\n const result: SyncActivePresetSkillsResult = { updated: [], unchanged: [], notActive: [], removed: [], skipped: [], backupSuffix: null };\n if (!existsSync(opts.sourceDir)) return result;\n let sourceInfo;\n try {\n sourceInfo = statSync(opts.sourceDir);\n } catch (err) {\n return abortActiveSync(opts, result, `source path stat failed: ${errorMessage(err)}`);\n }\n if (!sourceInfo.isDirectory()) {\n return abortActiveSync(opts, result, \"source path exists as a non-directory; active preset sync skipped\");\n }\n let sourceEntries: string[];\n try {\n sourceEntries = readdirSync(opts.sourceDir);\n } catch (err) {\n return abortActiveSync(opts, result, `source readdir failed: ${errorMessage(err)}`);\n }\n // Single timestamp per run so a multi-file update produces sibling\n // backups with a matching suffix — easier to grep / restore.\n const backupExt = `.bak.${Date.now()}`;\n result.backupSuffix = backupExt;\n const sourceSlugs = new Set<string>();\n for (const slug of sourceEntries) {\n if (slug.startsWith(\".\")) continue;\n if (!isPresetSlug(slug)) continue;\n sourceSlugs.add(slug);\n processActiveSlug(slug, opts, result, backupExt);\n }\n // Prune active copies of presets the launcher no longer ships.\n removeRetiredActivePresets(opts, result, sourceSlugs);\n if (result.updated.length > 0 || result.removed.length > 0) {\n opts.onInfo?.(\"active preset skills synced\", {\n updated: result.updated.length,\n unchanged: result.unchanged.length,\n notActive: result.notActive.length,\n removed: result.removed.length,\n skipped: result.skipped.length,\n backupSuffix: backupExt,\n });\n }\n return result;\n}\n","// Resolve the package's BUNDLED assets (shipped via package.json `files`) and seed\n// them into a workspace. ESM-only: `import.meta.url` points at this module under\n// `dist/workspace-setup/`, so `../../assets` is the package's assets dir at the\n// package root. (The workspace-setup entries build ESM only — `import.meta.url`\n// isn't available under CJS; both hosts run the server as ESM via tsx.)\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { copyFileSync, mkdirSync, readdirSync } from \"node:fs\";\n\n// The asset dir is shipped separately (package.json `files`), NOT bundled, so\n// this URL must resolve at runtime. `@vite-ignore` silences Vite's build-time\n// \"doesn't exist at build time\" warning — runtime resolution is intended.\nconst ASSETS_DIR = fileURLToPath(new URL(/* @vite-ignore */ \"../../assets\", import.meta.url));\n\n/** The bundled help-docs source dir (`assets/helps/`). */\nexport function helpsAssetDir(): string {\n return path.join(ASSETS_DIR, \"helps\");\n}\n\n/** The bundled preset-skills source dir (`assets/skills-preset/`) — pass as the\n * `sourceDir` of `syncPresetSkills` / `syncActivePresetSkills`. */\nexport function presetSkillsAssetDir(): string {\n return path.join(ASSETS_DIR, \"skills-preset\");\n}\n\n/** Copy every bundled help doc into `destDir` (created if missing). Idempotent —\n * overwrites on each call so the help docs always track the package's version. */\nexport function seedHelps(opts: { destDir: string }): void {\n mkdirSync(opts.destDir, { recursive: true });\n const src = helpsAssetDir();\n for (const file of readdirSync(src)) {\n copyFileSync(path.join(src, file), path.join(opts.destDir, file));\n }\n}\n"],"mappings":";;;;;;AAeA,SAAgB,aAAa,KAAc,UAA2B;CACpE,IAAI,eAAe,OAAO,OAAO,IAAI;CACrC,IAAI,QAAQ,QAAQ,OAAO,QAAQ,UAAU;EAC3C,MAAM,MAAM;EACZ,IAAI,OAAO,IAAI,YAAY,YAAY,IAAI,SAAS,OAAO,IAAI;EAC/D,IAAI,OAAO,IAAI,YAAY,YAAY,IAAI,SAAS,OAAO,IAAI;CACjE;CACA,IAAI,aAAa,KAAA,GAAW,OAAO;CACnC,OAAO,OAAO,GAAG;AACnB;;;ACYA,SAAS,gBAAgB,QAAgB,SAAuB;CAC9D,UAAU,SAAS,EAAE,WAAW,KAAK,CAAC;CACtC,KAAK,MAAM,SAAS,YAAY,QAAQ,EAAE,eAAe,KAAK,CAAC,GAAG;EAChE,MAAM,UAAU,KAAK,KAAK,QAAQ,MAAM,IAAI;EAC5C,MAAM,WAAW,KAAK,KAAK,SAAS,MAAM,IAAI;EAC9C,IAAI,MAAM,YAAY,GACpB,gBAAgB,SAAS,QAAQ;OAC5B,IAAI,MAAM,OAAO,GACtB,aAAa,SAAS,QAAQ;CAElC;AACF;AAEA,IAAM,iBAAiB;AAsCvB,SAAS,oBAAoB,WAAmB,OAAwB;CACtE,IAAI,MAAM,WAAW,GAAG,GAAG,OAAO;EAAE,IAAI;EAAO,QAAQ;EAAU,QAAQ;CAAK;CAC9E,MAAM,UAAU,KAAK,KAAK,WAAW,KAAK;CAC1C,IAAI;CACJ,IAAI;EACF,UAAU,SAAS,OAAO;CAC5B,QAAQ;EACN,OAAO;GAAE,IAAI;GAAO,QAAQ;GA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I,CAAC;AAEpE"}
package/package.json CHANGED
@@ -1,9 +1,15 @@
1
1
  {
2
2
  "name": "@mulmoclaude/core",
3
- "version": "0.26.0",
3
+ "version": "0.27.0",
4
4
  "description": "Shared server-side core for MulmoClaude and MulmoTerminal — the always-shipped-together subsystems consolidated behind subpath exports so the two hosts can't drift. Server-only except the browser-safe ./whisper/client, ./workspace-setup/slug, ./translation/client, ./remote-view and ./remote-host entries. All host specifics are injected.",
5
5
  "type": "module",
6
6
  "exports": {
7
+ "./utils": {
8
+ "types": "./dist/utils/index.d.ts",
9
+ "import": "./dist/utils/index.js",
10
+ "require": "./dist/utils/index.cjs",
11
+ "default": "./dist/utils/index.js"
12
+ },
7
13
  "./collection": {
8
14
  "types": "./dist/collection/index.d.ts",
9
15
  "import": "./dist/collection/index.js",
@@ -1,16 +0,0 @@
1
- //#region src/collection/core/errorMessage.ts
2
- /** Normalise an unknown thrown value to a display string. The view layer's host
3
- * capabilities already return normalised `{ ok: false, error }` results, so this
4
- * only backs the defensive `catch` around an unexpected throw. */
5
- function errorMessage(err) {
6
- return err instanceof Error ? err.message : String(err);
7
- }
8
- //#endregion
9
- Object.defineProperty(exports, "errorMessage", {
10
- enumerable: true,
11
- get: function() {
12
- return errorMessage;
13
- }
14
- });
15
-
16
- //# sourceMappingURL=errorMessage--LvXe_Jx.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"errorMessage--LvXe_Jx.cjs","names":[],"sources":["../src/collection/core/errorMessage.ts"],"sourcesContent":["/** Normalise an unknown thrown value to a display string. The view layer's host\n * capabilities already return normalised `{ ok: false, error }` results, so this\n * only backs the defensive `catch` around an unexpected throw. */\nexport function errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n"],"mappings":";;;;AAGA,SAAgB,aAAa,KAAsB;CACjD,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACxD"}
@@ -1,11 +0,0 @@
1
- //#region src/collection/core/errorMessage.ts
2
- /** Normalise an unknown thrown value to a display string. The view layer's host
3
- * capabilities already return normalised `{ ok: false, error }` results, so this
4
- * only backs the defensive `catch` around an unexpected throw. */
5
- function errorMessage(err) {
6
- return err instanceof Error ? err.message : String(err);
7
- }
8
- //#endregion
9
- export { errorMessage as t };
10
-
11
- //# sourceMappingURL=errorMessage-DIdhheHk.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"errorMessage-DIdhheHk.js","names":[],"sources":["../src/collection/core/errorMessage.ts"],"sourcesContent":["/** Normalise an unknown thrown value to a display string. The view layer's host\n * capabilities already return normalised `{ ok: false, error }` results, so this\n * only backs the defensive `catch` around an unexpected throw. */\nexport function errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n"],"mappings":";;;;AAGA,SAAgB,aAAa,KAAsB;CACjD,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AACxD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"ids-Dl9Ij63K.cjs","names":[],"sources":["../src/collection/core/schema.ts","../src/collection/core/ids.ts"],"sourcesContent":["// Schema-driven collection types. A \"collection\" is a skill (under\n// .claude/skills/<slug>/) that also ships a sibling `schema.json`.\n// The host's <CollectionView> reads the schema + records and renders\n// a table/form; Claude reads SKILL.md and CRUDs the records as JSON\n// files.\n//\n// SINGLE SOURCE OF TRUTH: every type describing the schema.json contract is\n// derived (`z.infer`) from the zod definitions in `./schemaZ` — the shapes,\n// their doc comments, and the validation rules live THERE; this module only\n// re-derives the TypeScript names consumers import. The imports from\n// `./schemaZ` are type-only, so zod never reaches the browser bundle through\n// the isomorphic barrel; at runtime the dependency points the other way\n// (schemaZ imports this module's consts).\n//\n// Field specs are a DISCRIMINATED UNION on `type`: narrow with\n// `field.type === \"enum\"` (etc.) before reading a variant key like `values`,\n// `to`, `formula`, or `of`.\n\nimport type { z } from \"zod\";\nimport type {\n ActionSpecZ,\n CollectionSchemaZ,\n CustomViewZ,\n DataSourceZ,\n DynamicIconRuleZ,\n DynamicIconSourceZ,\n DynamicIconSpecZ,\n EveryFieldDrivenZ,\n EveryLiteralZ,\n EveryZ,\n FieldSpecZ,\n IngestZ,\n SpawnZ,\n StorageZ,\n SubFieldSpecZ,\n WhenZ,\n} from \"./schemaZ\";\n\n/** Minimal \"this collection is a feed\" descriptor carried on the schema.\n * Deliberately narrow — the canonical collection contract stays\n * independent of the host's feeds subsystem. The host's richer retrieval\n * spec (`IngestSpec` in `feeds/ingestTypes.ts`) is a subtype, so feed code\n * reads the extra fields by typing feed schemas with that subtype;\n * collection rendering only needs these three + the presence check. */\nexport interface CollectionIngest {\n kind: string;\n schedule: string;\n /** Optional time-of-day anchor for `schedule: \"daily\"` — the hour (0–23) to\n * refresh around (the host ticks hourly, so the run lands within that hour).\n * Ignored for non-daily schedules. Absent ⇒ elapsed-based daily (\"≥24 h since\n * the last run\"). NOTE: **UTC**, not local — compared via `getUTCHours()` for\n * an unambiguous, DST-free check (matching the rest of the scheduler), so\n * convert local times before writing (e.g. 07:00 JST → `atHour: 22`). */\n atHour?: number;\n /** Declarative retrievers (`rss`/`atom`/`http-json`) only — the host fetches\n * this URL on the schedule. Absent for `kind: \"agent\"`, where the agent owns\n * retrieval. */\n url?: string;\n /** `kind: \"agent\"` only: role id the scheduled hidden worker runs in. */\n role?: string;\n /** `kind: \"agent\"` only: skill-relative template path (under `templates/`)\n * whose prose tells the worker how to refresh the records. */\n template?: string;\n}\n\n/** Declarative retriever kinds a Feed's `ingest.kind` may declare. The host's\n * feeds engine dispatches on these; they live here (with the schema contract)\n * so the schema validator can enforce them. The host re-exports these from\n * `server/workspace/feeds/ingestTypes.ts`. */\nexport const INGEST_KINDS = [\"rss\", \"atom\", \"http-json\"] as const;\nexport type IngestKind = (typeof INGEST_KINDS)[number];\n\n/** The agent-performed ingest kind. Instead of a declarative fetch, the host\n * dispatches a hidden background chat (origin `system`) in `ingest.role`,\n * seeded with `ingest.template` + a summary of every record, on the\n * `ingest.schedule` cadence; the worker edits records via the collections io\n * layer. Kept separate from {@link INGEST_KINDS} (which the declarative\n * retriever registry keys on) so the schema validator can model `ingest` as a\n * discriminated union without the feeds engine gaining an \"agent\" retriever. */\nexport const AGENT_INGEST_KIND = \"agent\" as const;\nexport type AgentIngestKind = typeof AGENT_INGEST_KIND;\n\n/** Refresh cadences a Feed's `ingest.schedule` may declare. */\nexport const FEED_SCHEDULES = [\"hourly\", \"daily\", \"weekly\", \"on-demand\"] as const;\nexport type FeedSchedule = (typeof FEED_SCHEDULES)[number];\n\n// \"feed\" collections live in the non-skill `<workspace>/feeds/` registry\n// and carry an `ingest` block; they reuse the same storage + rendering\n// as skill-backed collections but are never loaded into the agent prompt.\nexport type CollectionSource = \"user\" | \"project\" | \"feed\";\n\n/** One field of a record — a discriminated union on `type`; see the variant\n * docs in `./schemaZ` (`FieldSpecZ`). */\nexport type CollectionFieldSpec = z.infer<typeof FieldSpecZ>;\n\n/** A `table` field's row sub-schema entry — the field union minus `table` /\n * `derived` / display-only types (see `SubFieldSpecZ`). */\nexport type CollectionSubFieldSpec = z.infer<typeof SubFieldSpecZ>;\n\nexport type CollectionFieldType = CollectionFieldSpec[\"type\"];\n\n/** The computed-boolean variant — a `where` predicate bound to a field\n * name; see `FlagFieldZ`. */\nexport type CollectionFlagField = Extract<CollectionFieldSpec, { type: \"flag\" }>;\n\n/** derived/embed/backlinks/rollup/toggle/flag are host-computed or\n * projected — never written to the record JSON, so required / value\n * checks and edit-draft slots must not apply to them. THE single source\n * for \"computed\" — lives here (zod-free at runtime) so browser code\n * (`./draft`) and the zod record compiler (`./recordZ`, which re-exports\n * it) share one set instead of drifting copies. */\nexport const COMPUTED_TYPES: ReadonlySet<CollectionFieldType> = new Set<CollectionFieldType>([\"derived\", \"embed\", \"backlinks\", \"rollup\", \"toggle\", \"flag\"]);\n\n/** Optional visibility predicate: the target (an action button or a\n * field) renders only when the open record's `field` (stringified) is\n * one of `in`. Generic and domain-free — the host evaluates it against\n * the record with no knowledge of what the field means. Absent ⇒\n * always shown. */\nexport type CollectionWhen = z.infer<typeof WhenZ>;\n\n/** @deprecated Name retained for back-compat; use {@link CollectionWhen}.\n * Both actions and fields share the same predicate shape. No in-repo\n * consumers, but the package is public API (MulmoTerminal). */\n// eslint-disable-next-line sonarjs/redundant-type-aliases -- deliberate deprecated back-compat export\nexport type CollectionActionWhen = CollectionWhen;\n\n/** A schema-declared, per-record action rendered as a button in the\n * read-only detail view. Pure UI/behaviour directive — never stored,\n * never validated against record data. All domain specifics (label,\n * role, template — or the declarative `set`) live in the schema / skill\n * folder, so the host stays generic. A discriminated union on `kind`;\n * see `ActionSpecZ`. */\nexport type CollectionAction = z.infer<typeof ActionSpecZ>;\n\n/** The kind of work an action kicks off: `\"chat\"` (visible LLM chat),\n * `\"agent\"` (hidden LLM worker), or `\"mutate\"` (declarative host write,\n * no LLM). */\nexport type CollectionActionKind = CollectionAction[\"kind\"];\n\n/** The LLM-seeded action variants (`role` + `template`). */\nexport type CollectionSeededAction = Extract<CollectionAction, { kind: \"chat\" | \"agent\" }>;\n\n/** The declarative host-write variant (`set` + optional `require`/`params`). */\nexport type CollectionMutateAction = Extract<CollectionAction, { kind: \"mutate\" }>;\n\n/** A custom (LLM-authored) HTML view for a collection. The host renders\n * `file` in a sandboxed iframe over the collection's records; the view\n * reaches its data only through a slug- and capability-scoped token (see\n * `server/api/auth/viewToken.ts`). Pure data — the host holds no\n * view-specific code; meaning lives in the HTML file + this registration.\n * See `CustomViewZ` for the per-key contracts. */\nexport type CollectionCustomView = z.infer<typeof CustomViewZ>;\n\n/** What a custom view's capability token is allowed to do against the\n * collection's data endpoint. `read` returns enriched records (getItems\n * semantics); `write` validates-and-stores rows (putItems semantics).\n * There is deliberately no `delete` — a view can never do more than the\n * agent's own `manageCollection` tool. */\nexport type CollectionViewCapability = NonNullable<CollectionCustomView[\"capabilities\"]>[number];\n\n/** How a `spawn` advances the source item's `triggerField` date to\n * produce the successor's. All arithmetic is done on the civil\n * (year, month, day) triple — never by adding milliseconds — so month\n * lengths and leap years are handled correctly. */\nexport type CollectionEvery = z.infer<typeof EveryLiteralZ>;\n\n/** Recurrence unit for a `spawn.every` advance. */\nexport type CollectionRecurUnit = CollectionEvery[\"unit\"];\n\n/** Field-driven recurrence: the advance interval is selected PER RECORD by\n * the value of an `enum` field (`fromField`), looked up in `map`. See\n * `EveryFieldDrivenZ`. */\nexport type CollectionEveryFieldDriven = z.infer<typeof EveryFieldDrivenZ>;\n\n/** The `every` of a `spawn`: either a single literal interval applied to\n * every record, or a per-record interval selected by an `enum` field. The\n * literal arm is what `advanceTriggerDate` consumes — the field-driven arm\n * is resolved down to one of its `map` values before the date math runs. */\nexport type CollectionSpawnEvery = z.infer<typeof EveryZ>;\n\n/** Narrowing guard: true when `every` is the field-driven arm. */\nexport function isFieldDrivenEvery(every: CollectionSpawnEvery): every is CollectionEveryFieldDriven {\n return \"fromField\" in every;\n}\n\n/** Host-driven recurrence. See `SpawnZ`. */\nexport type CollectionSpawn = z.infer<typeof SpawnZ>;\n\n/** One rule in a `dynamicIcon.rules` list: when the resolved source\n * record matches `where` (an AND of typed conditions, see `./where`),\n * the collection's effective launcher icon becomes `icon`. Evaluated top\n * to bottom — the first match wins. */\nexport type DynamicIconRule = z.infer<typeof DynamicIconRuleZ>;\n\n/** Where a {@link DynamicIconSpec}'s source record comes from: a (possibly\n * cross-collection) pool of records, optionally narrowed by `where` and\n * reduced to a single record by `from`. */\nexport type DynamicIconSource = z.infer<typeof DynamicIconSourceZ>;\n\n/** Declarative \"data state → icon\" mapping for a collection's launcher\n * shortcut icon (see `CollectionSchema.dynamicIcon`). When absent, the\n * launcher icon is the static `schema.icon`. */\nexport type DynamicIconSpec = z.infer<typeof DynamicIconSpecZ>;\n\n/** The `ingest` block as the schema validator accepts it — a discriminated\n * union on `kind` (declarative retrievers | agent worker). The feeds\n * subsystem's `IngestSpec` is the same union under its historical name. */\nexport type CollectionIngestSpec = z.infer<typeof IngestZ>;\n\n/** The `dataSource` block: this collection's records are the rows of an\n * external read-only data file (v1: CSV). See `DataSourceZ`. */\nexport type CollectionDataSource = z.infer<typeof DataSourceZ>;\n\n/** The `storage` block: an alternative WRITABLE record backend (v1:\n * sqlite). See `StorageZ`. */\nexport type CollectionStorage = z.infer<typeof StorageZ>;\n\n/** Every storage backend a schema can select. `file` is the implicit\n * default (`dataPath`); `csv` is implied by `dataSource`; other kinds are\n * named explicitly via `storage.type`. The server's store factory registry\n * (`server/store.ts`) is keyed by this. */\nexport type CollectionStorageKind = \"file\" | \"csv\" | \"sqlite\";\n\n/** Which storage backend serves this schema's records. Derived, not stored:\n * existing schemas carry no `storage` key and must keep resolving exactly\n * as before (`dataSource` ⇒ csv, else file). */\nexport function storageKindFor(schema: Pick<CollectionSchema, \"dataSource\" | \"storage\">): CollectionStorageKind {\n if (schema.dataSource !== undefined) return \"csv\";\n return schema.storage?.type ?? \"file\";\n}\n\n/** The whole `schema.json` contract. Key-level docs live on\n * `CollectionSchemaZ` in `./schemaZ`. */\nexport type CollectionSchema = z.infer<typeof CollectionSchemaZ>;\n\n/** True when `schema` declares an external `dataSource` — i.e. the\n * collection is READ-ONLY through every UI/tool write path (updates\n * happen by editing/replacing the data file itself). Isomorphic: both\n * the server write guards and the client's control hiding key off this\n * one predicate. */\nexport function isReadOnlySchema(schema: Pick<CollectionSchema, \"dataSource\">): boolean {\n return schema.dataSource !== undefined;\n}\n\nexport interface CollectionSummary {\n slug: string;\n title: string;\n icon: string;\n source: CollectionSource;\n /** Present (true) when the collection is backed by an external\n * `dataSource` and therefore read-only in every UI/tool write path.\n * Absent-when-writable, matching the other optional summary flags. */\n readonly?: true;\n /** Slugs of the source collection(s) a `dynamicIcon` icon was computed\n * from — present only when `schema.dynamicIcon` is set. Lets a client\n * know which collection change-channel(s) to watch for a live icon\n * update (see `useDynamicShortcutIcons`). */\n iconSources?: string[];\n}\n\nexport interface CollectionDetail extends CollectionSummary {\n schema: CollectionSchema;\n}\n\nexport type CollectionItem = Record<string, unknown>;\n\n/** Resolve an `embed` field's target record id: the fixed `id`, or the value\n * of the sibling `idField` on this record (empty string when neither applies\n * — the caller renders that as \"no record\"). Pure + isomorphic so the server\n * projection (`derive.ts`) and the client preview (`useCollectionRendering`)\n * resolve embeds identically. Non-`embed` fields resolve to \"no record\". */\nexport function embedTargetId(field: CollectionFieldSpec, record: CollectionItem | null): string {\n if (field.type !== \"embed\") return \"\";\n if (field.id) return field.id;\n if (field.idField && record) return String(record[field.idField] ?? \"\");\n return \"\";\n}\n","// Pure slug / record-id character rules. Shared by the isomorphic schema\n// validator (`./schemaZ`) — which must stay node-free — and the server-side\n// path sanitisers (`../server/paths`), which wrap these patterns with the\n// `path.basename` round-trip CodeQL recognises as a `js/path-injection`\n// sanitiser. Both layers MUST gate on the same patterns; importing them from\n// here is what keeps them in sync.\n\n// The ONE slug pattern — `server/workspace/skills/catalog.ts` imports it\n// for its own sanitiser, so there is no second copy to keep in sync.\n// Bounded character classes, no nested quantifiers; ReDoS-safe.\n// eslint-disable-next-line security/detect-unsafe-regex -- non-overlapping character classes, no catastrophic backtracking\nexport const SAFE_SLUG_PATTERN = /^[a-zA-Z0-9](?:[a-zA-Z0-9_-]*[a-zA-Z0-9])?$/;\n\n// Record ids are a superset of slugs: they're only ever filename stems\n// (`<id>.json`), never directory names or URL segments, so they may carry\n// dots — natural keys like a Slack ts (`1718900000.123456`), a SemVer\n// (`1.2.3`), or a decimal timestamp. The interior class adds `.` to the slug\n// set; the explicit `..` reject in `isSafeRecordId` keeps a\n// parent-dir-looking segment out while still allowing repeated `-`/`_`\n// (`a--b`, `a__b`). Start/end stay alphanumeric so leading/trailing dots\n// (hidden files, the special `.`/`..` names) and `..`-only ids are all\n// excluded.\n// eslint-disable-next-line security/detect-unsafe-regex -- non-overlapping character classes, no catastrophic backtracking\nexport const SAFE_RECORD_ID_PATTERN = /^[a-zA-Z0-9](?:[a-zA-Z0-9_.-]*[a-zA-Z0-9])?$/;\n\n/** True when `value` is a well-formed collection slug (alphanumeric /\n * hyphen / underscore, no path separators). The pattern admits no `/`,\n * `\\`, or `.`, so a passing value is trivially also a safe basename —\n * validation callers need no `path.basename` round-trip (path-building\n * callers use `../server/paths#safeSlugName`, which adds it). */\nexport function isSafeSlug(value: string): boolean {\n return typeof value === \"string\" && SAFE_SLUG_PATTERN.test(value);\n}\n\n/** True when `value` is a well-formed record id (slug charset plus interior\n * dots), with any `..` substring rejected explicitly. Validation-only\n * counterpart of `../server/paths#safeRecordId`. */\nexport function isSafeRecordId(value: string): boolean {\n if (typeof value !== \"string\" || !SAFE_RECORD_ID_PATTERN.test(value)) return false;\n return !value.includes(\"..\");\n}\n"],"mappings":";;;;;AAqEA,IAAa,eAAe;CAAC;CAAO;CAAQ;AAAW;;;;;;;;AAUvD,IAAa,oBAAoB;;AAIjC,IAAa,iBAAiB;CAAC;CAAU;CAAS;CAAU;AAAW;;;;;;;AA4BvE,IAAa,iCAAmD,IAAI,IAAyB;CAAC;CAAW;CAAS;CAAa;CAAU;CAAU;AAAM,CAAC;;AAsE1J,SAAgB,mBAAmB,OAAkE;CACnG,OAAO,eAAe;AACxB;;;;AA2CA,SAAgB,eAAe,QAAiF;CAC9G,IAAI,OAAO,eAAe,KAAA,GAAW,OAAO;CAC5C,OAAO,OAAO,SAAS,QAAQ;AACjC;;;;;;AAWA,SAAgB,iBAAiB,QAAuD;CACtF,OAAO,OAAO,eAAe,KAAA;AAC/B;;;;;;AA6BA,SAAgB,cAAc,OAA4B,QAAuC;CAC/F,IAAI,MAAM,SAAS,SAAS,OAAO;CACnC,IAAI,MAAM,IAAI,OAAO,MAAM;CAC3B,IAAI,MAAM,WAAW,QAAQ,OAAO,OAAO,OAAO,MAAM,YAAY,EAAE;CACtE,OAAO;AACT;;;ACzQA,IAAa,oBAAoB;AAYjC,IAAa,yBAAyB;;;;;;AAOtC,SAAgB,WAAW,OAAwB;CACjD,OAAO,OAAO,UAAU,YAAY,kBAAkB,KAAK,KAAK;AAClE;;;;AAKA,SAAgB,eAAe,OAAwB;CACrD,IAAI,OAAO,UAAU,YAAY,CAAC,uBAAuB,KAAK,KAAK,GAAG,OAAO;CAC7E,OAAO,CAAC,MAAM,SAAS,IAAI;AAC7B"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"ids-P2T89Gou.js","names":[],"sources":["../src/collection/core/schema.ts","../src/collection/core/ids.ts"],"sourcesContent":["// Schema-driven collection types. A \"collection\" is a skill (under\n// .claude/skills/<slug>/) that also ships a sibling `schema.json`.\n// The host's <CollectionView> reads the schema + records and renders\n// a table/form; Claude reads SKILL.md and CRUDs the records as JSON\n// files.\n//\n// SINGLE SOURCE OF TRUTH: every type describing the schema.json contract is\n// derived (`z.infer`) from the zod definitions in `./schemaZ` — the shapes,\n// their doc comments, and the validation rules live THERE; this module only\n// re-derives the TypeScript names consumers import. The imports from\n// `./schemaZ` are type-only, so zod never reaches the browser bundle through\n// the isomorphic barrel; at runtime the dependency points the other way\n// (schemaZ imports this module's consts).\n//\n// Field specs are a DISCRIMINATED UNION on `type`: narrow with\n// `field.type === \"enum\"` (etc.) before reading a variant key like `values`,\n// `to`, `formula`, or `of`.\n\nimport type { z } from \"zod\";\nimport type {\n ActionSpecZ,\n CollectionSchemaZ,\n CustomViewZ,\n DataSourceZ,\n DynamicIconRuleZ,\n DynamicIconSourceZ,\n DynamicIconSpecZ,\n EveryFieldDrivenZ,\n EveryLiteralZ,\n EveryZ,\n FieldSpecZ,\n IngestZ,\n SpawnZ,\n StorageZ,\n SubFieldSpecZ,\n WhenZ,\n} from \"./schemaZ\";\n\n/** Minimal \"this collection is a feed\" descriptor carried on the schema.\n * Deliberately narrow — the canonical collection contract stays\n * independent of the host's feeds subsystem. The host's richer retrieval\n * spec (`IngestSpec` in `feeds/ingestTypes.ts`) is a subtype, so feed code\n * reads the extra fields by typing feed schemas with that subtype;\n * collection rendering only needs these three + the presence check. */\nexport interface CollectionIngest {\n kind: string;\n schedule: string;\n /** Optional time-of-day anchor for `schedule: \"daily\"` — the hour (0–23) to\n * refresh around (the host ticks hourly, so the run lands within that hour).\n * Ignored for non-daily schedules. Absent ⇒ elapsed-based daily (\"≥24 h since\n * the last run\"). NOTE: **UTC**, not local — compared via `getUTCHours()` for\n * an unambiguous, DST-free check (matching the rest of the scheduler), so\n * convert local times before writing (e.g. 07:00 JST → `atHour: 22`). */\n atHour?: number;\n /** Declarative retrievers (`rss`/`atom`/`http-json`) only — the host fetches\n * this URL on the schedule. Absent for `kind: \"agent\"`, where the agent owns\n * retrieval. */\n url?: string;\n /** `kind: \"agent\"` only: role id the scheduled hidden worker runs in. */\n role?: string;\n /** `kind: \"agent\"` only: skill-relative template path (under `templates/`)\n * whose prose tells the worker how to refresh the records. */\n template?: string;\n}\n\n/** Declarative retriever kinds a Feed's `ingest.kind` may declare. The host's\n * feeds engine dispatches on these; they live here (with the schema contract)\n * so the schema validator can enforce them. The host re-exports these from\n * `server/workspace/feeds/ingestTypes.ts`. */\nexport const INGEST_KINDS = [\"rss\", \"atom\", \"http-json\"] as const;\nexport type IngestKind = (typeof INGEST_KINDS)[number];\n\n/** The agent-performed ingest kind. Instead of a declarative fetch, the host\n * dispatches a hidden background chat (origin `system`) in `ingest.role`,\n * seeded with `ingest.template` + a summary of every record, on the\n * `ingest.schedule` cadence; the worker edits records via the collections io\n * layer. Kept separate from {@link INGEST_KINDS} (which the declarative\n * retriever registry keys on) so the schema validator can model `ingest` as a\n * discriminated union without the feeds engine gaining an \"agent\" retriever. */\nexport const AGENT_INGEST_KIND = \"agent\" as const;\nexport type AgentIngestKind = typeof AGENT_INGEST_KIND;\n\n/** Refresh cadences a Feed's `ingest.schedule` may declare. */\nexport const FEED_SCHEDULES = [\"hourly\", \"daily\", \"weekly\", \"on-demand\"] as const;\nexport type FeedSchedule = (typeof FEED_SCHEDULES)[number];\n\n// \"feed\" collections live in the non-skill `<workspace>/feeds/` registry\n// and carry an `ingest` block; they reuse the same storage + rendering\n// as skill-backed collections but are never loaded into the agent prompt.\nexport type CollectionSource = \"user\" | \"project\" | \"feed\";\n\n/** One field of a record — a discriminated union on `type`; see the variant\n * docs in `./schemaZ` (`FieldSpecZ`). */\nexport type CollectionFieldSpec = z.infer<typeof FieldSpecZ>;\n\n/** A `table` field's row sub-schema entry — the field union minus `table` /\n * `derived` / display-only types (see `SubFieldSpecZ`). */\nexport type CollectionSubFieldSpec = z.infer<typeof SubFieldSpecZ>;\n\nexport type CollectionFieldType = CollectionFieldSpec[\"type\"];\n\n/** The computed-boolean variant — a `where` predicate bound to a field\n * name; see `FlagFieldZ`. */\nexport type CollectionFlagField = Extract<CollectionFieldSpec, { type: \"flag\" }>;\n\n/** derived/embed/backlinks/rollup/toggle/flag are host-computed or\n * projected — never written to the record JSON, so required / value\n * checks and edit-draft slots must not apply to them. THE single source\n * for \"computed\" — lives here (zod-free at runtime) so browser code\n * (`./draft`) and the zod record compiler (`./recordZ`, which re-exports\n * it) share one set instead of drifting copies. */\nexport const COMPUTED_TYPES: ReadonlySet<CollectionFieldType> = new Set<CollectionFieldType>([\"derived\", \"embed\", \"backlinks\", \"rollup\", \"toggle\", \"flag\"]);\n\n/** Optional visibility predicate: the target (an action button or a\n * field) renders only when the open record's `field` (stringified) is\n * one of `in`. Generic and domain-free — the host evaluates it against\n * the record with no knowledge of what the field means. Absent ⇒\n * always shown. */\nexport type CollectionWhen = z.infer<typeof WhenZ>;\n\n/** @deprecated Name retained for back-compat; use {@link CollectionWhen}.\n * Both actions and fields share the same predicate shape. No in-repo\n * consumers, but the package is public API (MulmoTerminal). */\n// eslint-disable-next-line sonarjs/redundant-type-aliases -- deliberate deprecated back-compat export\nexport type CollectionActionWhen = CollectionWhen;\n\n/** A schema-declared, per-record action rendered as a button in the\n * read-only detail view. Pure UI/behaviour directive — never stored,\n * never validated against record data. All domain specifics (label,\n * role, template — or the declarative `set`) live in the schema / skill\n * folder, so the host stays generic. A discriminated union on `kind`;\n * see `ActionSpecZ`. */\nexport type CollectionAction = z.infer<typeof ActionSpecZ>;\n\n/** The kind of work an action kicks off: `\"chat\"` (visible LLM chat),\n * `\"agent\"` (hidden LLM worker), or `\"mutate\"` (declarative host write,\n * no LLM). */\nexport type CollectionActionKind = CollectionAction[\"kind\"];\n\n/** The LLM-seeded action variants (`role` + `template`). */\nexport type CollectionSeededAction = Extract<CollectionAction, { kind: \"chat\" | \"agent\" }>;\n\n/** The declarative host-write variant (`set` + optional `require`/`params`). */\nexport type CollectionMutateAction = Extract<CollectionAction, { kind: \"mutate\" }>;\n\n/** A custom (LLM-authored) HTML view for a collection. The host renders\n * `file` in a sandboxed iframe over the collection's records; the view\n * reaches its data only through a slug- and capability-scoped token (see\n * `server/api/auth/viewToken.ts`). Pure data — the host holds no\n * view-specific code; meaning lives in the HTML file + this registration.\n * See `CustomViewZ` for the per-key contracts. */\nexport type CollectionCustomView = z.infer<typeof CustomViewZ>;\n\n/** What a custom view's capability token is allowed to do against the\n * collection's data endpoint. `read` returns enriched records (getItems\n * semantics); `write` validates-and-stores rows (putItems semantics).\n * There is deliberately no `delete` — a view can never do more than the\n * agent's own `manageCollection` tool. */\nexport type CollectionViewCapability = NonNullable<CollectionCustomView[\"capabilities\"]>[number];\n\n/** How a `spawn` advances the source item's `triggerField` date to\n * produce the successor's. All arithmetic is done on the civil\n * (year, month, day) triple — never by adding milliseconds — so month\n * lengths and leap years are handled correctly. */\nexport type CollectionEvery = z.infer<typeof EveryLiteralZ>;\n\n/** Recurrence unit for a `spawn.every` advance. */\nexport type CollectionRecurUnit = CollectionEvery[\"unit\"];\n\n/** Field-driven recurrence: the advance interval is selected PER RECORD by\n * the value of an `enum` field (`fromField`), looked up in `map`. See\n * `EveryFieldDrivenZ`. */\nexport type CollectionEveryFieldDriven = z.infer<typeof EveryFieldDrivenZ>;\n\n/** The `every` of a `spawn`: either a single literal interval applied to\n * every record, or a per-record interval selected by an `enum` field. The\n * literal arm is what `advanceTriggerDate` consumes — the field-driven arm\n * is resolved down to one of its `map` values before the date math runs. */\nexport type CollectionSpawnEvery = z.infer<typeof EveryZ>;\n\n/** Narrowing guard: true when `every` is the field-driven arm. */\nexport function isFieldDrivenEvery(every: CollectionSpawnEvery): every is CollectionEveryFieldDriven {\n return \"fromField\" in every;\n}\n\n/** Host-driven recurrence. See `SpawnZ`. */\nexport type CollectionSpawn = z.infer<typeof SpawnZ>;\n\n/** One rule in a `dynamicIcon.rules` list: when the resolved source\n * record matches `where` (an AND of typed conditions, see `./where`),\n * the collection's effective launcher icon becomes `icon`. Evaluated top\n * to bottom — the first match wins. */\nexport type DynamicIconRule = z.infer<typeof DynamicIconRuleZ>;\n\n/** Where a {@link DynamicIconSpec}'s source record comes from: a (possibly\n * cross-collection) pool of records, optionally narrowed by `where` and\n * reduced to a single record by `from`. */\nexport type DynamicIconSource = z.infer<typeof DynamicIconSourceZ>;\n\n/** Declarative \"data state → icon\" mapping for a collection's launcher\n * shortcut icon (see `CollectionSchema.dynamicIcon`). When absent, the\n * launcher icon is the static `schema.icon`. */\nexport type DynamicIconSpec = z.infer<typeof DynamicIconSpecZ>;\n\n/** The `ingest` block as the schema validator accepts it — a discriminated\n * union on `kind` (declarative retrievers | agent worker). The feeds\n * subsystem's `IngestSpec` is the same union under its historical name. */\nexport type CollectionIngestSpec = z.infer<typeof IngestZ>;\n\n/** The `dataSource` block: this collection's records are the rows of an\n * external read-only data file (v1: CSV). See `DataSourceZ`. */\nexport type CollectionDataSource = z.infer<typeof DataSourceZ>;\n\n/** The `storage` block: an alternative WRITABLE record backend (v1:\n * sqlite). See `StorageZ`. */\nexport type CollectionStorage = z.infer<typeof StorageZ>;\n\n/** Every storage backend a schema can select. `file` is the implicit\n * default (`dataPath`); `csv` is implied by `dataSource`; other kinds are\n * named explicitly via `storage.type`. The server's store factory registry\n * (`server/store.ts`) is keyed by this. */\nexport type CollectionStorageKind = \"file\" | \"csv\" | \"sqlite\";\n\n/** Which storage backend serves this schema's records. Derived, not stored:\n * existing schemas carry no `storage` key and must keep resolving exactly\n * as before (`dataSource` ⇒ csv, else file). */\nexport function storageKindFor(schema: Pick<CollectionSchema, \"dataSource\" | \"storage\">): CollectionStorageKind {\n if (schema.dataSource !== undefined) return \"csv\";\n return schema.storage?.type ?? \"file\";\n}\n\n/** The whole `schema.json` contract. Key-level docs live on\n * `CollectionSchemaZ` in `./schemaZ`. */\nexport type CollectionSchema = z.infer<typeof CollectionSchemaZ>;\n\n/** True when `schema` declares an external `dataSource` — i.e. the\n * collection is READ-ONLY through every UI/tool write path (updates\n * happen by editing/replacing the data file itself). Isomorphic: both\n * the server write guards and the client's control hiding key off this\n * one predicate. */\nexport function isReadOnlySchema(schema: Pick<CollectionSchema, \"dataSource\">): boolean {\n return schema.dataSource !== undefined;\n}\n\nexport interface CollectionSummary {\n slug: string;\n title: string;\n icon: string;\n source: CollectionSource;\n /** Present (true) when the collection is backed by an external\n * `dataSource` and therefore read-only in every UI/tool write path.\n * Absent-when-writable, matching the other optional summary flags. */\n readonly?: true;\n /** Slugs of the source collection(s) a `dynamicIcon` icon was computed\n * from — present only when `schema.dynamicIcon` is set. Lets a client\n * know which collection change-channel(s) to watch for a live icon\n * update (see `useDynamicShortcutIcons`). */\n iconSources?: string[];\n}\n\nexport interface CollectionDetail extends CollectionSummary {\n schema: CollectionSchema;\n}\n\nexport type CollectionItem = Record<string, unknown>;\n\n/** Resolve an `embed` field's target record id: the fixed `id`, or the value\n * of the sibling `idField` on this record (empty string when neither applies\n * — the caller renders that as \"no record\"). Pure + isomorphic so the server\n * projection (`derive.ts`) and the client preview (`useCollectionRendering`)\n * resolve embeds identically. Non-`embed` fields resolve to \"no record\". */\nexport function embedTargetId(field: CollectionFieldSpec, record: CollectionItem | null): string {\n if (field.type !== \"embed\") return \"\";\n if (field.id) return field.id;\n if (field.idField && record) return String(record[field.idField] ?? \"\");\n return \"\";\n}\n","// Pure slug / record-id character rules. Shared by the isomorphic schema\n// validator (`./schemaZ`) — which must stay node-free — and the server-side\n// path sanitisers (`../server/paths`), which wrap these patterns with the\n// `path.basename` round-trip CodeQL recognises as a `js/path-injection`\n// sanitiser. Both layers MUST gate on the same patterns; importing them from\n// here is what keeps them in sync.\n\n// The ONE slug pattern — `server/workspace/skills/catalog.ts` imports it\n// for its own sanitiser, so there is no second copy to keep in sync.\n// Bounded character classes, no nested quantifiers; ReDoS-safe.\n// eslint-disable-next-line security/detect-unsafe-regex -- non-overlapping character classes, no catastrophic backtracking\nexport const SAFE_SLUG_PATTERN = /^[a-zA-Z0-9](?:[a-zA-Z0-9_-]*[a-zA-Z0-9])?$/;\n\n// Record ids are a superset of slugs: they're only ever filename stems\n// (`<id>.json`), never directory names or URL segments, so they may carry\n// dots — natural keys like a Slack ts (`1718900000.123456`), a SemVer\n// (`1.2.3`), or a decimal timestamp. The interior class adds `.` to the slug\n// set; the explicit `..` reject in `isSafeRecordId` keeps a\n// parent-dir-looking segment out while still allowing repeated `-`/`_`\n// (`a--b`, `a__b`). Start/end stay alphanumeric so leading/trailing dots\n// (hidden files, the special `.`/`..` names) and `..`-only ids are all\n// excluded.\n// eslint-disable-next-line security/detect-unsafe-regex -- non-overlapping character classes, no catastrophic backtracking\nexport const SAFE_RECORD_ID_PATTERN = /^[a-zA-Z0-9](?:[a-zA-Z0-9_.-]*[a-zA-Z0-9])?$/;\n\n/** True when `value` is a well-formed collection slug (alphanumeric /\n * hyphen / underscore, no path separators). The pattern admits no `/`,\n * `\\`, or `.`, so a passing value is trivially also a safe basename —\n * validation callers need no `path.basename` round-trip (path-building\n * callers use `../server/paths#safeSlugName`, which adds it). */\nexport function isSafeSlug(value: string): boolean {\n return typeof value === \"string\" && SAFE_SLUG_PATTERN.test(value);\n}\n\n/** True when `value` is a well-formed record id (slug charset plus interior\n * dots), with any `..` substring rejected explicitly. Validation-only\n * counterpart of `../server/paths#safeRecordId`. */\nexport function isSafeRecordId(value: string): boolean {\n if (typeof value !== \"string\" || !SAFE_RECORD_ID_PATTERN.test(value)) return false;\n return !value.includes(\"..\");\n}\n"],"mappings":";;;;;AAqEA,IAAa,eAAe;CAAC;CAAO;CAAQ;AAAW;;;;;;;;AAUvD,IAAa,oBAAoB;;AAIjC,IAAa,iBAAiB;CAAC;CAAU;CAAS;CAAU;AAAW;;;;;;;AA4BvE,IAAa,iCAAmD,IAAI,IAAyB;CAAC;CAAW;CAAS;CAAa;CAAU;CAAU;AAAM,CAAC;;AAsE1J,SAAgB,mBAAmB,OAAkE;CACnG,OAAO,eAAe;AACxB;;;;AA2CA,SAAgB,eAAe,QAAiF;CAC9G,IAAI,OAAO,eAAe,KAAA,GAAW,OAAO;CAC5C,OAAO,OAAO,SAAS,QAAQ;AACjC;;;;;;AAWA,SAAgB,iBAAiB,QAAuD;CACtF,OAAO,OAAO,eAAe,KAAA;AAC/B;;;;;;AA6BA,SAAgB,cAAc,OAA4B,QAAuC;CAC/F,IAAI,MAAM,SAAS,SAAS,OAAO;CACnC,IAAI,MAAM,IAAI,OAAO,MAAM;CAC3B,IAAI,MAAM,WAAW,QAAQ,OAAO,OAAO,OAAO,MAAM,YAAY,EAAE;CACtE,OAAO;AACT;;;ACzQA,IAAa,oBAAoB;AAYjC,IAAa,yBAAyB;;;;;;AAOtC,SAAgB,WAAW,OAAwB;CACjD,OAAO,OAAO,UAAU,YAAY,kBAAkB,KAAK,KAAK;AAClE;;;;AAKA,SAAgB,eAAe,OAAwB;CACrD,IAAI,OAAO,UAAU,YAAY,CAAC,uBAAuB,KAAK,KAAK,GAAG,OAAO;CAC7E,OAAO,CAAC,MAAM,SAAS,IAAI;AAC7B"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"promptSafety-B5KPkaNY.js","names":[],"sources":["../src/collection/core/fieldText.ts","../src/collection/core/actionVisible.ts","../src/collection/core/backlinks.ts","../src/collection/core/where.ts","../src/collection/core/completion.ts","../src/collection/core/dynamicIcon.ts","../src/collection/core/derivedFormula.ts","../src/collection/core/deriveAll.ts","../src/collection/core/calendarGrid.ts","../src/collection/core/promptSafety.ts"],"sourcesContent":["// Turning a record field into text.\n//\n// `CollectionItem` is `Record<string, unknown>`, so a field holds whatever the\n// record's JSON had — including arrays and objects (real workspace data has\n// plenty: weather `hourly`, GeoJSON `geometry`, `sites` lists). Bare\n// `String(value)` on one of those yields `\"[object Object]\"`, which then gets\n// compared, matched or displayed as if it were a value. Nothing throws; a\n// predicate just silently stops matching, or the UI shows `[object Object]`.\n//\n// These two helpers are the only sanctioned way to read a field as text. The\n// rule they encode was already in `itemLabelOf`: accept primitives, let\n// everything else fall through to the caller's fallback.\n\n/** A field value that has a meaningful text form. Dates are included because\n * a JSON record can carry one once it has been revived. */\nconst isTextable = (value: unknown): value is string | number | boolean | Date =>\n typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\" || value instanceof Date;\n\n/** The field's text, or `null` when it has no meaningful one (absent, or an\n * array/object that would stringify to `\"[object Object]\"`).\n *\n * Returning `null` rather than `\"\"` keeps \"the field is empty\" distinct from\n * \"the field can't be text\" — a matcher must not treat an object-valued field\n * as an empty string and match `\"\"`. */\nexport function fieldTextOrNull(value: unknown): string | null {\n if (value === undefined || value === null) return null;\n if (!isTextable(value)) return null;\n if (value instanceof Date) {\n // `new Date(\"nonsense\")` is still `instanceof Date`, and `toISOString()`\n // throws `RangeError` on it. This helper sits on the match, sort and\n // display paths, so one unparseable date in one record would take the whole\n // render down — the loud version of the bug this module exists to prevent.\n return Number.isNaN(value.getTime()) ? null : value.toISOString();\n }\n return String(value);\n}\n\n/** The field's text, or `fallback` (default `\"\"`) when it has none. Use where\n * a string is required and an empty one is a safe stand-in — display, sort\n * keys, CSV cells. Where the distinction matters, use {@link fieldTextOrNull}. */\nexport function fieldText(value: unknown, fallback = \"\"): string {\n return fieldTextOrNull(value) ?? fallback;\n}\n","// Pure `when`-predicate visibility helpers for schema-driven\n// collections — used both for action buttons and for conditionally\n// shown fields. Kept as their own module (no Vue) so CollectionView\n// can stay thin and the match semantics are pinned by unit tests.\n// Domain-free: the host compares the stringified record value against\n// the allowed set with no knowledge of what the field means.\n\nimport { fieldTextOrNull } from \"./fieldText\";\n\n/** A `when` predicate: render only when the open record's `field`\n * (stringified) is one of `in`. Shared shape for action buttons and\n * conditionally visible fields. */\nexport interface WhenPredicate {\n field: string;\n in: string[];\n}\n\n/** Core matcher:\n * - no `when` ⇒ always true (visible);\n * - otherwise true only when `record[when.field]` is present and its\n * stringified value is one of `when.in`.\n * A missing/undefined/null field is treated as \"not a match\"\n * (hidden), so a status-gated target never shows on a record that\n * lacks the status. */\nexport function whenMatches(when: WhenPredicate | undefined, record: Record<string, unknown>): boolean {\n if (!when) return true;\n // `fieldTextOrNull` rather than `String(...)`: an array/object field would\n // stringify to \"[object Object]\" and could match a `when.in` entry by\n // accident. No text ⇒ no match, same as an absent field.\n const text = fieldTextOrNull(record[when.field]);\n if (text === null) return false;\n return when.in.includes(text);\n}\n\n/** Minimal shape this helper needs from an action — the optional state\n * gate, whichever name its kind uses: `when` on the seeded kinds\n * (chat/agent), `require` on mutate. Accepts the full CollectionAction\n * union (each variant declares at most one of the two). */\nexport interface ActionWithWhen {\n when?: WhenPredicate;\n require?: WhenPredicate;\n}\n\n/** True when the action's button should render against `record` — and,\n * server-side, whether it may RUN (visibility is the authorization\n * rule, for every kind). */\nexport function actionVisible(action: ActionWithWhen, record: Record<string, unknown>): boolean {\n return whenMatches(action.when ?? action.require, record);\n}\n\n/** The run key naming one in-flight `kind: \"agent\"` action button —\n * written by the server's dispatch guard, read back by the client from\n * the detail response's `runningActions` to drive the spinner. ONE\n * builder (isomorphic) so the two sides can't drift. Collection-level\n * and per-record actions live in distinct namespaces so an id collision\n * between `actions` and `collectionActions` can't alias. */\nexport function agentActionRunKey(actionId: string, itemId?: string): string {\n return itemId === undefined ? `collection/${actionId}` : `item/${itemId}/${actionId}`;\n}\n\n/** Minimal shape this helper needs from a field spec — just its\n * optional `when` predicate. Accepts the full FieldSpec too. */\nexport interface FieldWithWhen {\n when?: WhenPredicate;\n}\n\n/** True when the field should render against `record`. A field with\n * no `when` is always shown; otherwise it's shown only when the\n * record matches (e.g. hide a rating field until `visited` is true).\n * Purely presentational — a hidden field's stored value is never\n * altered, so toggling the gate back on restores it. */\nexport function fieldVisible(field: FieldWithWhen, record: Record<string, unknown>): boolean {\n return whenMatches(field.when, record);\n}\n","// Pure resolution for `backlinks` fields (plan step ② of\n// plans/done/collection-ontology.md): the display-only reverse side of `ref`.\n// Both the server enrichment (`server/derive.ts`) and the client detail\n// view derive the row set through THESE helpers, so the LLM (getItems)\n// and the user (record panel) always see the same rows — the same\n// single-implementation rule `deriveAll` follows for formulas. No zod,\n// no I/O; safe for the browser barrel.\n\nimport { whenMatches } from \"./actionVisible\";\nimport { fieldTextOrNull } from \"./fieldText\";\nimport type { CollectionFieldSpec, CollectionItem } from \"./schema\";\n\n/** The `backlinks` member of the field-spec union. */\nexport type BacklinksFieldSpec = Extract<CollectionFieldSpec, { type: \"backlinks\" }>;\n\n/** The SOURCE records whose `via` field stores `recordId` (compared as\n * strings, like every ref deref), with the optional `filter` applied —\n * in the source items' given order. Fail-soft by construction: a `via`\n * key that doesn't exist on the source records simply matches nothing.\n * Callers pass DERIVED source records, so a `filter`/`display` on a\n * derived column works when its formula is SELF-CONTAINED (an invoice\n * `total` = sum over its own line items); a source column that derefs\n * yet another collection stays absent — the same each-record-derives-\n * against-itself rule ref targets follow. */\nexport function backlinkRows(spec: Pick<BacklinksFieldSpec, \"via\" | \"filter\">, recordId: string, sourceItems: CollectionItem[]): CollectionItem[] {\n if (!recordId) return [];\n // A `via` field holding an array/object has no id to compare — skip it\n // rather than testing \"[object Object]\" against the record id.\n return sourceItems.filter((item) => fieldTextOrNull(item[spec.via]) === recordId && whenMatches(spec.filter, item));\n}\n\n/** Project one backlink row to the keys consumers surface: the source\n * collection's primaryKey (rows must stay addressable — it's the link\n * target) plus the declared `display` columns. Keys the row doesn't\n * carry are simply absent, mirroring `projectFields` in getItems. */\nexport function projectBacklinkRow(row: CollectionItem, display: readonly string[], primaryKey: string): CollectionItem {\n const keys = display.includes(primaryKey) ? display : [primaryKey, ...display];\n return Object.fromEntries(keys.filter((key) => key in row).map((key) => [key, row[key]]));\n}\n\n/** The `rollup` member of the field-spec union. */\nexport type RollupFieldSpec = Extract<CollectionFieldSpec, { type: \"rollup\" }>;\n\n/** Numeric coercion shared by the strict record lint (`./recordZ`) and\n * rollup sums: a plain number, or a non-blank numeric string (renderers\n * coerce those via `Number(...)`, so they display fine). Anything else —\n * arrays (`[]` stringifies to `\"\"` = 0, `[42]` to `\"42\"`), booleans,\n * objects — is NaN. Lives here (zod-free) so both consumers share one\n * definition of \"numeric\". */\nexport function coerceNumeric(value: unknown): number {\n if (typeof value === \"number\") return value;\n if (typeof value === \"string\" && value.trim() !== \"\") return Number(value);\n return NaN;\n}\n\n/** The rollup aggregate over the matching source rows (plan step ⑤):\n * `count` = how many rows match; `sum` = the total of `column` over\n * them, skipping non-numeric / absent values (a partially-filled source\n * still sums what's there). An EMPTY match set is a real 0 — the\n * fail-soft null lives at the caller, for a source collection that\n * couldn't be resolved at all. Same derived-source-records contract as\n * `backlinkRows`: pass records derived against themselves, so summing a\n * self-contained derived column (an invoice `total`) works. */\nexport function rollupValue(spec: Pick<RollupFieldSpec, \"via\" | \"filter\" | \"op\" | \"column\">, recordId: string, sourceItems: CollectionItem[]): number {\n const rows = backlinkRows(spec, recordId, sourceItems);\n if (spec.op === \"count\") return rows.length;\n let total = 0;\n for (const row of rows) {\n const value = coerceNumeric(spec.column === undefined ? undefined : row[spec.column]);\n if (Number.isFinite(value)) total += value;\n }\n return total;\n}\n","// Pure SQL-like `where` predicate for `dynamicIcon` (see\n// `DynamicIconSource.where` / `DynamicIconRule.where` in `./schema`).\n// An AND of typed conditions — richer than the single-field `CollectionWhen`\n// used elsewhere (fields/actions via `./actionVisible`), which stays as-is\n// for its existing callers. No fs, no host state. The condition SHAPES are\n// derived from the zod source of truth in `./schemaZ` (type-only imports —\n// this evaluator stays zod-free at runtime).\n\nimport type { z } from \"zod\";\nimport type { ValueRefZ, WhereCondZ, WhereZ } from \"./schemaZ\";\n\n/** Reads the comparison value from a field instead of a schema literal:\n * - `record` set → another record: `recordsById[record][field]` (e.g. a\n * `_config` singleton's `defaultCity`, following a per-user setting);\n * - `record` omitted → the SAME record being matched (field-to-field, e.g.\n * `spent > budget`). */\nexport type ValueRef = z.infer<typeof ValueRefZ>;\n\n/** One typed condition: `record[field] <op> value`. The comparison value is\n * either a literal `value` (a plain string for every op except `in`, which\n * takes the allowed set) or a `valueFrom` reference resolved against the\n * `recordsById` map passed to `matchesWhere`. Exactly one of the two is\n * expected — enforced by zod at the schema boundary (`./schemaZ`), not\n * here. */\nexport type WhereCond = z.infer<typeof WhereCondZ>;\n\n/** Comparison operators one `WhereCond` may apply to `record[field]`. */\nexport type WhereOp = WhereCond[\"op\"];\n\n/** A `where` clause is the AND of its conditions — every one must match. */\nexport type Where = z.infer<typeof WhereZ>;\n\n/** True when `record[field]` is absent (`undefined`/`null`) — the only case\n * where `ne` and every other op disagree on the result. */\nfunction isMissing(raw: unknown): boolean {\n return raw === undefined || raw === null;\n}\n\n/** The effective comparison value for `cond`: its literal `value`, or — for\n * a `valueFrom` reference — the target field read out of `recordsById`.\n * `undefined` means UNRESOLVED (no such record, or the field on it is\n * missing); the caller must treat that as \"never matches\", not as a\n * literal `undefined` value to compare against. */\nfunction resolveValue(cond: WhereCond, record: Record<string, unknown>, recordsById: Record<string, Record<string, unknown>>): string | string[] | undefined {\n if (!cond.valueFrom) return cond.value;\n const { record: refRecord, field } = cond.valueFrom;\n const target = refRecord === undefined ? record : recordsById[refRecord];\n const raw = target?.[field];\n return isMissing(raw) ? undefined : String(raw);\n}\n\nfunction matchesNumericOp(operator: \"gt\" | \"gte\" | \"lt\" | \"lte\", left: number, right: number): boolean {\n if (operator === \"gt\") return left > right;\n if (operator === \"gte\") return left >= right;\n if (operator === \"lt\") return left < right;\n return left <= right;\n}\n\n/** `Number(\"\")` / `Number(\" \")` are `0`, not `NaN`, so treat a blank string\n * as non-numeric explicitly — an empty field must fail a numeric compare,\n * not read as zero. */\nfunction toNumber(raw: string): number {\n return raw.trim() === \"\" ? NaN : Number(raw);\n}\n\nfunction matchesNumeric(operator: \"gt\" | \"gte\" | \"lt\" | \"lte\", raw: string, value: string | string[]): boolean {\n if (Array.isArray(value)) return false;\n const left = toNumber(raw);\n const right = toNumber(value);\n if (Number.isNaN(left) || Number.isNaN(right)) return false;\n return matchesNumericOp(operator, left, right);\n}\n\n/** True when the present string `raw` satisfies `operator` against the\n * resolved `value` (field known to exist — MISSING is handled by the\n * caller before this runs, and an UNRESOLVED `valueFrom` never reaches\n * here either). */\nfunction matchesPresent(operator: WhereOp, raw: string, value: string | string[]): boolean {\n switch (operator) {\n case \"eq\":\n return raw === String(value);\n case \"ne\":\n return raw !== String(value);\n case \"in\":\n return Array.isArray(value) && value.includes(raw);\n case \"contains\":\n return raw.includes(String(value));\n case \"gt\":\n case \"gte\":\n case \"lt\":\n case \"lte\":\n return matchesNumeric(operator, raw, value);\n default:\n return false;\n }\n}\n\n/** True when `record` satisfies one condition, given `recordsById` to\n * resolve a `valueFrom` reference. Two independent MISSING cases, checked\n * in order:\n * - `record[cond.field]` absent (`undefined`/`null`) → matches only `ne`\n * (vacuously true — \"not equal to X\" holds when there's no value at\n * all); every other op is false. Unchanged from the literal-`value`\n * behaviour, regardless of whether `valueFrom` would also resolve.\n * - the resolved comparison value is UNRESOLVED (a `valueFrom` whose\n * target record/field doesn't exist) → false for EVERY op, including\n * `ne` — a broken reference must never spuriously match. */\nfunction matchesCond(cond: WhereCond, record: Record<string, unknown>, recordsById: Record<string, Record<string, unknown>>): boolean {\n const raw = record[cond.field];\n if (isMissing(raw)) return cond.op === \"ne\";\n const value = resolveValue(cond, record, recordsById);\n if (value === undefined) return false;\n return matchesPresent(cond.op, String(raw), value);\n}\n\n/** True when `record` satisfies every condition in `where` (AND). An empty\n * `where` matches everything. `recordsById` — the source collection's\n * records keyed by primaryKey — resolves any `valueFrom` reference;\n * omitted (default `{}`) for callers with no cross-record lookups, in\n * which case every `valueFrom` condition is UNRESOLVED and so never\n * matches. */\nexport function matchesWhere(where: Where, record: Record<string, unknown>, recordsById: Record<string, Record<string, unknown>> = {}): boolean {\n return where.every((cond) => matchesCond(cond, record, recordsById));\n}\n","// The \"is this record done?\" predicate — THE single implementation,\n// shared by the notification reconciler (bell clearing, collection-watchers),\n// spawn (successor-predicate fallback, ../server/spawn.ts), and view-side\n// completion filters. Zod-free and I/O-free like the rest of `core/`, so\n// it is browser-safe through the collection barrel.\n//\n// Two completion forms (see `CollectionSchemaZ`'s completion refine):\n// - legacy pair: `completionField` names a stored field and\n// `completionDoneValues` lists the values that mean done —\n// done ⇔ `String(item[completionField])` ∈ `completionDoneValues`.\n// - flag form: `completionField` names a `flag` field (and\n// `completionDoneValues` is absent) — done ⇔ the flag's `where`\n// matches. Evaluated directly against the raw record here (NOT read\n// from a materialized value) because callers like the reconciler and\n// spawn work on records straight off disk, before any `deriveAll`\n// enrichment. That raw evaluation is CORRECT BY CONSTRUCTION: a\n// schema-level refine rejects a completion flag whose `where`\n// references computed fields, so every condition reads stored data.\n\nimport { fieldTextOrNull } from \"./fieldText\";\nimport { matchesWhere, type Where } from \"./where\";\n\n/** The slice of a parsed schema the done predicate reads — minimal\n * structural shape (like `DerivableSchema`) so the client and server\n * `CollectionSchema` types both satisfy it as-is. */\nexport interface CompletionSchemaView {\n /** Optional so legacy-pair callers (and their test fixtures) that\n * never consult field specs keep working; only the flag form needs\n * to look the completion field up. */\n fields?: Record<string, { type: string; where?: Where }>;\n completionField?: string;\n completionDoneValues?: readonly string[];\n}\n\n/** True iff the schema declares completion tracking AND `item` is done\n * under whichever completion form the schema uses (see module doc). */\nexport function itemIsDone(schema: CompletionSchemaView, item: Record<string, unknown>): boolean {\n const { completionField, completionDoneValues } = schema;\n if (!completionField) return false;\n const spec = schema.fields?.[completionField];\n if (spec?.type === \"flag\" && spec.where) return matchesWhere(spec.where, item);\n if (!completionDoneValues) return false;\n // An array/object field has no text form; treat it as \"not done\" rather than\n // letting \"[object Object]\" match a configured done-value.\n const text = fieldTextOrNull(item[completionField]);\n if (text === null) return false;\n return completionDoneValues.includes(text);\n}\n","// Pure resolver for a collection's dynamic launcher-shortcut icon (see\n// `CollectionSchema.dynamicIcon`). Selects one \"source\" record from a\n// (possibly cross-collection, optionally `where`-filtered) records pool,\n// then maps it through a first-match-wins rules list to an icon name.\n// No fs, no host state — the server-side compute\n// (`packages/core/src/collection/server/dynamicIcon.ts`) loads the source\n// collection's records and calls these.\n\nimport { matchesWhere } from \"./where\";\nimport type { CollectionFieldSpec, CollectionItem, CollectionSchema, DynamicIconSource, DynamicIconSpec } from \"./schema\";\n\n/** The record with the greatest `String(record[field])` (localeCompare) —\n * ties keep the first-seen record (stable left-to-right `reduce`). */\nfunction latestByField(pool: CollectionItem[], field: string): CollectionItem {\n return pool.reduce((latest, candidate) => (String(candidate[field] ?? \"\").localeCompare(String(latest[field] ?? \"\")) > 0 ? candidate : latest));\n}\n\n/** Reduce `records` to the one record that decides the effective icon, per\n * `source`'s `where` filter + `from` strategy:\n * - pool = `source.where`-filtered records, or every record when unset;\n * - an empty pool resolves to `null` (no source record → fallback);\n * - `from: \"first\"` / `\"when\"` → the first pool record (storage order);\n * - `from: \"latest\"` (default), with `orderBy` given → the pool record\n * whose `String(record[orderBy])` sorts highest;\n * - `from: \"latest\"`, with no `orderBy` → the last pool record.\n * `recordsById` (the source collection's records keyed by primaryKey)\n * resolves any `valueFrom` reference inside `source.where`; omitted for\n * callers with no cross-record lookups. */\nexport function selectDynamicRecord(\n records: CollectionItem[],\n source: DynamicIconSource,\n orderBy: string | undefined,\n recordsById: Record<string, CollectionItem> = {},\n): CollectionItem | null {\n const { where } = source;\n const pool = where ? records.filter((record) => matchesWhere(where, record, recordsById)) : records;\n if (pool.length === 0) return null;\n if (source.from === \"first\" || source.from === \"when\") return pool[0];\n return orderBy ? latestByField(pool, orderBy) : pool[pool.length - 1];\n}\n\n/** Map a resolved source record to the effective icon: `spec.fallback`\n * (or the collection's own static `icon`) when there's no record or no\n * rule matches; otherwise the `icon` of the first rule whose `where`\n * matches the record. `recordsById` resolves any `valueFrom` reference\n * inside a rule's `where`, same as `selectDynamicRecord`. */\nexport function resolveIcon(\n record: CollectionItem | null,\n spec: DynamicIconSpec,\n staticIcon: string,\n recordsById: Record<string, CollectionItem> = {},\n): string {\n const fallback = spec.fallback ?? staticIcon;\n if (!record) return fallback;\n const matched = spec.rules.find((rule) => matchesWhere(rule.where, record, recordsById));\n return matched ? matched.icon : fallback;\n}\n\nconst isDateLikeField = (field: CollectionFieldSpec): boolean => field.type === \"date\" || field.type === \"datetime\";\n\n/** The first field key (declaration order) whose type is `date` or\n * `datetime` — the default `orderBy` for `from: \"latest\"` when a\n * `DynamicIconSource` doesn't name one. `undefined` when the schema has\n * no date-like field. */\nexport function firstDateField(schema: CollectionSchema): string | undefined {\n return Object.entries(schema.fields).find(([, field]) => isDateLikeField(field))?.[0];\n}\n","// Tiny expression evaluator for the `derived` field type on\n// schema-driven collections (see plans/done/feat-mc-invoice.md).\n//\n// Grammar (recursive-descent, no precedence climbing — six\n// non-terminals total):\n//\n// expr := term (('+' | '-') term)*\n// term := factor (('*' | '/') factor)*\n// factor := number | sumCall | refAccess | identifier | '(' expr ')'\n// sumCall:= 'sum' '(' sumArg ')'\n// sumArg := tableCol (('*' | '/') tableCol)* // e.g. lineItems[].quantity * lineItems[].rate\n// tableCol := identifier '[]' '.' identifier\n// refAccess := identifier '.' identifier // e.g. ticker.price — deref a ref field into its target record\n//\n// `identifier` accepts top-level field names (single segment).\n// Inside `sumArg`, identifiers are the `<table>[].col` form.\n// A two-segment `<field>.<col>` at factor level is a *ref deref*:\n// `<field>` must be a `ref`-typed field on this record (its stored\n// value is the target item's slug), and `<col>` is a numeric column\n// read from that target record. The caller resolves the target into\n// `ctx.refs` (it owns the schema + the loaded target collection);\n// the evaluator stays pure and never does I/O.\n//\n// What's deliberately NOT supported (and would parse-error rather\n// than silently misbehave):\n// - String literals, boolean operators, comparisons, conditionals\n// - Nested function calls beyond `sum(...)`\n// - Anything in the record that isn't a number / table-of-objects\n//\n// All evaluation is pure — no eval(), no Function constructor.\n// Returns `null` on any failure (parse error, unbound identifier,\n// non-finite arithmetic). The caller renders `null` as em-dash in\n// the table cell + form display.\n\nexport interface FormulaContext {\n /** The record being evaluated. For derived fields in the form,\n * this is the live draft (text + table both converted via the\n * same `draftToRecord` pipeline). For the main table cell,\n * this is the persisted item. */\n record: Record<string, unknown>;\n /** Resolved ref-target records for THIS row, keyed by the local\n * `ref` field name. The caller (which has the schema + the linked\n * collection's items loaded) maps each ref field's stored slug to\n * the full target record and passes it here, so a `<field>.<col>`\n * formula can read a numeric column off the referenced record\n * (e.g. `shares * ticker.price`). A missing key or `null` value\n * (unknown field / dangling slug) makes that deref evaluate to\n * NaN → the whole formula returns `null` → em-dash, consistent\n * with every other failure mode. Absent ⇒ no refs available. */\n refs?: Record<string, Record<string, unknown> | null>;\n}\n\nexport function evaluateDerived(formula: string, ctx: FormulaContext): number | null {\n let tokens: Token[];\n try {\n tokens = tokenize(formula);\n } catch {\n return null;\n }\n // eslint-disable-next-line @typescript-eslint/no-use-before-define -- Parser class is defined later in the file (grouped with its AST + evaluator); evaluateDerived runs after module init so the TDZ concern doesn't apply.\n const parser = new Parser(tokens);\n let ast: Node;\n try {\n ast = parser.parseExpr();\n if (!parser.atEnd()) return null; // trailing junk\n } catch {\n return null;\n }\n const value = evaluate(ast, ctx);\n return Number.isFinite(value) ? value : null;\n}\n\n// ─── Tokens ────────────────────────────────────────────────\n\ntype TokenKind = \"number\" | \"ident\" | \"(\" | \")\" | \"+\" | \"-\" | \"*\" | \"/\" | \"[]\" | \".\";\n\ninterface Token {\n kind: TokenKind;\n value?: string | number;\n}\n\nconst SINGLE_CHAR_PUNCT = new Set<TokenKind>([\"(\", \")\", \"+\", \"-\", \"*\", \"/\", \".\"]);\n\ninterface Cursor {\n input: string;\n index: number;\n}\n\nfunction consumeWhitespace(cur: Cursor): boolean {\n const char = cur.input[cur.index];\n if (char === \" \" || char === \"\\t\" || char === \"\\n\") {\n cur.index++;\n return true;\n }\n return false;\n}\n\nfunction consumeNumber(cur: Cursor): Token | null {\n const char = cur.input[cur.index] ?? \"\";\n const next = cur.input[cur.index + 1] ?? \"\";\n if (!isDigit(char) && !(char === \".\" && isDigit(next))) return null;\n let raw = \"\";\n while (cur.index < cur.input.length) {\n const here = cur.input[cur.index] ?? \"\";\n if (!isDigit(here) && here !== \".\") break;\n raw += here;\n cur.index++;\n }\n const num = Number(raw);\n if (!Number.isFinite(num)) throw new Error(\"bad number\");\n return { kind: \"number\", value: num };\n}\n\nfunction consumeIdent(cur: Cursor): Token | null {\n const char = cur.input[cur.index] ?? \"\";\n if (!isIdentStart(char)) return null;\n let raw = \"\";\n while (cur.index < cur.input.length && isIdentChar(cur.input[cur.index] ?? \"\")) {\n raw += cur.input[cur.index];\n cur.index++;\n }\n return { kind: \"ident\", value: raw };\n}\n\nfunction consumePunct(cur: Cursor): Token | null {\n const char = cur.input[cur.index] ?? \"\";\n if (char === \"[\" && cur.input[cur.index + 1] === \"]\") {\n cur.index += 2;\n return { kind: \"[]\" };\n }\n if (SINGLE_CHAR_PUNCT.has(char as TokenKind)) {\n cur.index++;\n return { kind: char as TokenKind };\n }\n return null;\n}\n\nfunction tokenize(input: string): Token[] {\n const tokens: Token[] = [];\n const cur: Cursor = { input, index: 0 };\n while (cur.index < input.length) {\n if (consumeWhitespace(cur)) continue;\n // Number FIRST so a leading-dot literal (`.25`) isn't split by\n // the `.` punctuation branch.\n const numTok = consumeNumber(cur);\n if (numTok) {\n tokens.push(numTok);\n continue;\n }\n const punctTok = consumePunct(cur);\n if (punctTok) {\n tokens.push(punctTok);\n continue;\n }\n const identTok = consumeIdent(cur);\n if (identTok) {\n tokens.push(identTok);\n continue;\n }\n throw new Error(`unexpected char ${input[cur.index]}`);\n }\n return tokens;\n}\n\nfunction isDigit(char: string): boolean {\n return char >= \"0\" && char <= \"9\";\n}\nfunction isIdentStart(char: string): boolean {\n return (char >= \"a\" && char <= \"z\") || (char >= \"A\" && char <= \"Z\") || char === \"_\";\n}\nfunction isIdentChar(char: string): boolean {\n return isIdentStart(char) || isDigit(char);\n}\n\n// ─── AST + Parser ───────────────────────────────────────────\n\ntype Node =\n | { kind: \"num\"; value: number }\n | { kind: \"ident\"; name: string }\n | { kind: \"ref\"; field: string; col: string }\n | { kind: \"binop\"; operator: \"+\" | \"-\" | \"*\" | \"/\"; left: Node; right: Node }\n | { kind: \"sum\"; arg: SumArg };\n\ninterface SumArg {\n // factors multiplied/divided together; each is a (tableName, colName) ref into a row.\n factors: { table: string; col: string }[];\n /** Operators between factors: length = factors.length - 1; each\n * is \"*\" or \"/\". For a single-factor sum (`sum(lineItems[].amount)`)\n * this is empty. */\n operators: (\"*\" | \"/\")[];\n}\n\nclass Parser {\n private cursor = 0;\n constructor(private readonly tokens: Token[]) {}\n\n atEnd(): boolean {\n return this.cursor >= this.tokens.length;\n }\n private peek(): Token | undefined {\n return this.tokens[this.cursor];\n }\n private consume(): Token {\n const tok = this.tokens[this.cursor++];\n if (!tok) throw new Error(\"unexpected end of input\");\n return tok;\n }\n private expect(kind: TokenKind): Token {\n const tok = this.consume();\n if (tok.kind !== kind) throw new Error(`expected ${kind}, got ${tok.kind}`);\n return tok;\n }\n\n parseExpr(): Node {\n let left = this.parseTerm();\n while (this.peek()?.kind === \"+\" || this.peek()?.kind === \"-\") {\n const operator = this.consume().kind as \"+\" | \"-\";\n const right = this.parseTerm();\n left = { kind: \"binop\", operator, left, right };\n }\n return left;\n }\n\n private parseTerm(): Node {\n let left = this.parseFactor();\n while (this.peek()?.kind === \"*\" || this.peek()?.kind === \"/\") {\n const operator = this.consume().kind as \"*\" | \"/\";\n const right = this.parseFactor();\n left = { kind: \"binop\", operator, left, right };\n }\n return left;\n }\n\n private parseFactor(): Node {\n const tok = this.peek();\n if (!tok) throw new Error(\"unexpected end in factor\");\n if (tok.kind === \"number\") {\n this.consume();\n return { kind: \"num\", value: tok.value as number };\n }\n if (tok.kind === \"(\") {\n this.consume();\n const inner = this.parseExpr();\n this.expect(\")\");\n return inner;\n }\n if (tok.kind === \"ident\") {\n const name = (tok.value as string) ?? \"\";\n // sum(...) — only function call we support\n if (name === \"sum\" && this.tokens[this.cursor + 1]?.kind === \"(\") {\n this.consume(); // ident\n this.expect(\"(\");\n const arg = this.parseSumArg();\n this.expect(\")\");\n return { kind: \"sum\", arg };\n }\n this.consume(); // ident\n // ref deref: `<field>.<col>` (e.g. ticker.price). The table-row\n // form `<table>[].col` only appears inside sum(), so a `.`\n // immediately after a top-level ident is unambiguously a ref\n // dereference here.\n if (this.peek()?.kind === \".\") {\n this.consume(); // '.'\n const col = this.expect(\"ident\");\n return { kind: \"ref\", field: name, col: col.value as string };\n }\n return { kind: \"ident\", name };\n }\n throw new Error(`unexpected token ${tok.kind} in factor`);\n }\n\n private parseSumArg(): SumArg {\n const factors: { table: string; col: string }[] = [];\n const operators: (\"*\" | \"/\")[] = [];\n factors.push(this.parseTableCol());\n while (this.peek()?.kind === \"*\" || this.peek()?.kind === \"/\") {\n const operator = this.consume().kind as \"*\" | \"/\";\n operators.push(operator);\n factors.push(this.parseTableCol());\n }\n return { factors, operators };\n }\n\n private parseTableCol(): { table: string; col: string } {\n const tableTok = this.expect(\"ident\");\n this.expect(\"[]\");\n this.expect(\".\");\n const colTok = this.expect(\"ident\");\n return { table: tableTok.value as string, col: colTok.value as string };\n }\n}\n\n// ─── Evaluator ──────────────────────────────────────────────\n\nfunction evaluate(node: Node, ctx: FormulaContext): number {\n if (node.kind === \"num\") return node.value;\n if (node.kind === \"ident\") {\n const raw = ctx.record[node.name];\n return toFiniteNumber(raw);\n }\n if (node.kind === \"ref\") {\n // `<field>.<col>`: read `col` off the resolved target record the\n // caller put in ctx.refs. Unknown field / dangling slug → null →\n // NaN, so the whole formula fails soft to an em-dash.\n const target = ctx.refs?.[node.field] ?? null;\n if (!target) return Number.NaN;\n return toFiniteNumber(target[node.col]);\n }\n if (node.kind === \"binop\") {\n const left = evaluate(node.left, ctx);\n const right = evaluate(node.right, ctx);\n return applyBinop(node.operator, left, right);\n }\n if (node.kind === \"sum\") {\n return evaluateSum(node.arg, ctx);\n }\n // Exhaustive — TS narrows above branches but throw keeps runtime honest.\n throw new Error(`unknown node`);\n}\n\nfunction applyBinop(operator: \"+\" | \"-\" | \"*\" | \"/\", left: number, right: number): number {\n if (!Number.isFinite(left) || !Number.isFinite(right)) return Number.NaN;\n if (operator === \"+\") return left + right;\n if (operator === \"-\") return left - right;\n if (operator === \"*\") return left * right;\n // operator === \"/\"\n if (right === 0) return Number.NaN;\n return left / right;\n}\n\nfunction evaluateSum(arg: SumArg, ctx: FormulaContext): number {\n if (arg.factors.length === 0) return 0;\n const tableName = arg.factors[0].table;\n // All factors must reference the SAME table (you can't multiply\n // a row from lineItems against a row from another table — the\n // semantics would be ambiguous). Reject mismatch.\n for (const factor of arg.factors) {\n if (factor.table !== tableName) return Number.NaN;\n }\n const rows = ctx.record[tableName];\n if (!Array.isArray(rows)) return 0;\n let total = 0;\n for (const row of rows) {\n if (!row || typeof row !== \"object\") continue;\n let product = toFiniteNumber((row as Record<string, unknown>)[arg.factors[0].col]);\n if (!Number.isFinite(product)) return Number.NaN;\n for (let i = 1; i < arg.factors.length; i++) {\n const value = toFiniteNumber((row as Record<string, unknown>)[arg.factors[i].col]);\n if (!Number.isFinite(value)) return Number.NaN;\n product = applyBinop(arg.operators[i - 1], product, value);\n }\n total += product;\n }\n return total;\n}\n\nfunction toFiniteNumber(value: unknown): number {\n if (typeof value === \"number\") return Number.isFinite(value) ? value : Number.NaN;\n if (typeof value === \"string\" && value.length > 0) {\n const num = Number(value);\n return Number.isFinite(num) ? num : Number.NaN;\n }\n return Number.NaN;\n}\n","// The derived-field saturation loop for schema-driven collections,\n// extracted from `composables/collections/useCollectionRendering.ts` so\n// the server (manageCollection getItems enrichment) and the client\n// (table cells, form display) evaluate formulas through ONE\n// implementation — if the two ever diverged, the UI and the LLM would\n// disagree on a number. Pure module: no Vue, no I/O.\n//\n// Like `actionVisible.ts`, the input types are minimal structural\n// shapes so both the client `FieldSpec`/`CollectionSchema`\n// (src/components/collectionTypes.ts) and the server\n// `CollectionFieldSpec`/`CollectionSchema`\n// (server/workspace/collections/types.ts) satisfy them as-is.\n\nimport { evaluateDerived, type FormulaContext } from \"./derivedFormula\";\nimport { matchesWhere, type Where } from \"./where\";\n\n/** Minimal field shape the derive loop needs — accepts both the client\n * FieldSpec and the server CollectionFieldSpec. */\nexport interface DerivableFieldSpec {\n type: string;\n /** When type === \"ref\": slug of the target collection. */\n to?: string;\n /** When type === \"derived\": formula evaluated against the record. */\n formula?: string;\n /** When type === \"flag\": predicate matched against the record. */\n where?: Where;\n}\n\n/** Minimal schema shape: just the ordered field map. */\nexport interface DerivableSchema {\n fields: Record<string, DerivableFieldSpec>;\n}\n\nexport type DerivableRecord = Record<string, unknown>;\n\n/** Per-target-collection cache of loaded referenced records:\n * target collection slug → item slug → full record. Mirrors the\n * client's `RefRecordCache` / the server's enrichment loader. */\nexport type DeriveRefRecords = Record<string, Record<string, DerivableRecord>>;\n\n/** Map each `ref` field's stored slug to its loaded target record (or\n * null when dangling / not loaded), keyed by the LOCAL field name —\n * the shape `evaluateDerived` reads for `<field>.<col>` derefs. */\nexport function resolveRowRefs(schema: DerivableSchema, record: DerivableRecord, refRecords: DeriveRefRecords): NonNullable<FormulaContext[\"refs\"]> {\n const refs: NonNullable<FormulaContext[\"refs\"]> = {};\n for (const [key, field] of Object.entries(schema.fields)) {\n if (field.type !== \"ref\" || !field.to) continue;\n const slug = record[key];\n refs[key] = typeof slug === \"string\" ? (refRecords[field.to]?.[slug] ?? null) : null;\n }\n return refs;\n}\n\n/** True for the field types the saturation loop below (re)computes:\n * `derived` formulas and `flag` predicates. */\nfunction isLoopComputed(field: DerivableFieldSpec): boolean {\n return field.type === \"derived\" || field.type === \"flag\";\n}\n\n/** The value one loop-computed field takes against the current\n * `enriched` record: a `derived` formula result (`null` = failed) or a\n * `flag` predicate match (total — always a boolean). `undefined` for\n * every other field type (nothing to compute). */\nfunction computeFieldValue(\n field: DerivableFieldSpec,\n enriched: DerivableRecord,\n refs: NonNullable<FormulaContext[\"refs\"]>,\n): number | boolean | null | undefined {\n if (field.type === \"derived\" && field.formula) return evaluateDerived(field.formula, { record: enriched, refs });\n if (field.type === \"flag\" && field.where) return matchesWhere(field.where, enriched);\n return undefined;\n}\n\n/** Evaluate every `derived` and `flag` field against `base`, saturating\n * so a computed field can read another one computed in an earlier pass\n * (`subtotal → tax → total` converges in ≤ field-count passes; a flag\n * may read a derived value, or another flag via its stringified\n * boolean). Cycles can't loop forever — passes are bounded by the\n * number of computed fields and the loop breaks as soon as a pass\n * changes nothing. Failed formulas stay ABSENT (the UI renders them as\n * em-dash); flags are total (always true/false). Returns a copy;\n * `base` is never mutated.\n *\n * Computed keys already present in `base` are stripped before\n * evaluation: computed output is host-truth, never persisted-input\n * fallback. A record JSON can carry a stale (or forged) computed value\n * — raw Write/Edit, legacy data — and without the strip, a failing\n * formula would silently surface that value as if the host computed\n * it. */\nexport function deriveAll(schema: DerivableSchema, base: DerivableRecord, refRecords: DeriveRefRecords): DerivableRecord {\n const computedKeys = new Set(\n Object.entries(schema.fields)\n .filter(([, field]) => isLoopComputed(field))\n .map(([key]) => key),\n );\n const enriched: DerivableRecord = Object.fromEntries(Object.entries(base).filter(([key]) => !computedKeys.has(key)));\n const refs = resolveRowRefs(schema, base, refRecords);\n for (let pass = 0; pass < computedKeys.size; pass++) {\n let mutated = false;\n for (const [key, field] of Object.entries(schema.fields)) {\n const next = computeFieldValue(field, enriched, refs);\n if (next !== undefined && next !== null && enriched[key] !== next) {\n enriched[key] = next;\n mutated = true;\n }\n }\n if (!mutated) break;\n }\n return enriched;\n}\n","// Pure, deterministic helpers for the collection calendar view: parse\n// `date`-field values, build a month grid, and bucket records onto the\n// days they cover. No `Date.now()` / `new Date()` (argless) here — every\n// function takes its inputs explicitly so the logic is unit-testable\n// without faking the clock. All internal arithmetic runs in UTC (which\n// has no DST), so fixed 86_400_000 ms steps never skip or double a day.\n\nconst MS_PER_DAY = 86_400_000;\nconst ISO_DATE_RE = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n// A two-digit field (hours / minutes / seconds) of a clock value.\nconst TWO_DIGIT_RE = /^\\d{2}$/;\n// A single clock token inside a free-form `time` string field (e.g. the\n// \"14:00-17:00\" / \"17:00-\" / \"16:30\" / \"終日\" shapes seen in user data).\nconst CLOCK_RE = /(\\d{1,2}):(\\d{2})/g;\n// Range separators we tolerate between two clock tokens: ASCII hyphen, en/em\n// dash, tilde, and the Japanese wave dashes.\nconst RANGE_SEP_RE = /[-–—~〜~]/;\n\n/** Minutes in a full day — the timeline's vertical extent. */\nexport const MINUTES_PER_DAY = 1440;\n\n/** A civil date triple. `month` is 1-12 (NOT the 0-based `Date` month). */\nexport interface Ymd {\n year: number;\n month: number;\n day: number;\n}\n\n/** One cell of the 6×7 month grid. */\nexport interface DayCell {\n ymd: Ymd;\n /** False for the leading/trailing days that belong to the adjacent\n * month (rendered greyed). */\n inMonth: boolean;\n /** Canonical `YYYY-MM-DD` key for this cell. */\n key: string;\n}\n\n/** A record placed on the calendar: the inclusive `[start, end]` span of\n * days it covers. `end === start` for a single-day record. `startMin` /\n * `endMin` are minutes-of-day for the time-allocation (day) view, resolved\n * from either a `datetime` field's clock or a separate time-string field.\n * `null` means \"no clock\" — `startMin === null && endMin === null` is an\n * all-day record; a non-null `startMin` with a null `endMin` is a\n * point-in-time record (rendered as a single line). */\nexport interface RecordSpan<T> {\n item: T;\n start: Ymd;\n end: Ymd;\n startMin: number | null;\n endMin: number | null;\n}\n\nfunction pad2(value: number): string {\n return String(value).padStart(2, \"0\");\n}\n\n/** Canonical `YYYY-MM-DD` string for a civil date. */\nexport function ymdKey(ymd: Ymd): string {\n return `${String(ymd.year).padStart(4, \"0\")}-${pad2(ymd.month)}-${pad2(ymd.day)}`;\n}\n\n/** Strictly parse a `YYYY-MM-DD` string into a civil date, rejecting\n * anything that isn't a real calendar day (e.g. `2026-02-30`, `2026-13-01`).\n * Returns null for non-strings and malformed values so callers can route\n * records with no usable date into the \"no date\" tray rather than crash. */\nexport function parseIsoDate(value: unknown): Ymd | null {\n if (typeof value !== \"string\") return null;\n const match = ISO_DATE_RE.exec(value.trim());\n if (!match) return null;\n const year = Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n // Round-trip through a UTC Date to reject impossible days: a value the\n // Date constructor rolls over (Feb 30 → Mar 2) won't match back.\n const probe = new Date(Date.UTC(year, month - 1, day));\n if (probe.getUTCFullYear() !== year || probe.getUTCMonth() !== month - 1 || probe.getUTCDate() !== day) return null;\n return { year, month, day };\n}\n\n/** Minutes-of-day for an `HH:MM` pair, or null when out of range. */\nfunction clockToMinutes(hours: number, minutes: number): number | null {\n if (hours < 0 || hours > 23 || minutes < 0 || minutes > 59) return null;\n return hours * 60 + minutes;\n}\n\n/** Strictly parse a `YYYY-MM-DDTHH:MM` (optional `:SS`) datetime into its\n * civil date and minutes-of-day. Returns null for anything that isn't a real\n * calendar day or a valid 24h clock. */\nexport function parseIsoDateTime(value: unknown): { ymd: Ymd; minutes: number } | null {\n if (typeof value !== \"string\") return null;\n const trimmed = value.trim();\n const tIndex = trimmed.indexOf(\"T\");\n if (tIndex === -1) return null;\n const ymd = parseIsoDate(trimmed.slice(0, tIndex));\n if (!ymd) return null;\n // `HH:MM` with an optional `:SS` the browser appends for non-zero seconds.\n const parts = trimmed.slice(tIndex + 1).split(\":\");\n if (parts.length < 2 || parts.length > 3 || !parts.every((part) => TWO_DIGIT_RE.test(part))) return null;\n const minutes = clockToMinutes(Number(parts[0]), Number(parts[1]));\n if (minutes === null) return null;\n return { ymd, minutes };\n}\n\n/** Civil date from either a `YYYY-MM-DD` or a `YYYY-MM-DDTHH:MM` value, so the\n * month grid buckets date-only and datetime anchors alike. */\nexport function dateOf(value: unknown): Ymd | null {\n return parseIsoDate(value) ?? parseIsoDateTime(value)?.ymd ?? null;\n}\n\n/** Minutes-of-day from a datetime value, or null for date-only / invalid. */\nfunction timeOf(value: unknown): number | null {\n return parseIsoDateTime(value)?.minutes ?? null;\n}\n\n/** Parse a free-form time-string field into start/end minutes-of-day.\n * Handles the common shapes in user data:\n * \"14:00-17:00\" → { start: 840, end: 1020 } (range → block)\n * \"17:00-\" → { start: 1020, end: null } (open end → single line)\n * \"16:30\" → { start: 990, end: null } (point in time → single line)\n * \"終日\" / \"\" → null (no clock → all-day)\n * Returns null when no clock token is parseable. */\nexport function parseTimeRange(value: unknown): { startMin: number | null; endMin: number | null } | null {\n if (typeof value !== \"string\") return null;\n const text = value.trim();\n if (!text) return null;\n const tokens = [...text.matchAll(CLOCK_RE)];\n if (tokens.length === 0) return null;\n const minutesOf = (match: RegExpMatchArray): number | null => clockToMinutes(Number(match[1]), Number(match[2]));\n // No separator → a single point in time (start only).\n if (!RANGE_SEP_RE.test(text)) {\n const startMin = minutesOf(tokens[0]);\n return startMin === null ? null : { startMin, endMin: null };\n }\n // Separator present → assign each token to the side of the first separator.\n const sepIndex = text.search(RANGE_SEP_RE);\n let startMin: number | null = null;\n let endMin: number | null = null;\n for (const token of tokens) {\n if ((token.index ?? 0) < sepIndex) startMin = minutesOf(token);\n else endMin = minutesOf(token);\n }\n // A start-less range (\"-09:00\") has no anchor on the timeline → treat as\n // unparseable so the record falls back to the all-day strip.\n if (startMin === null) return null;\n return { startMin, endMin };\n}\n\nfunction ymdToUtcMs(ymd: Ymd): number {\n return Date.UTC(ymd.year, ymd.month - 1, ymd.day);\n}\n\nfunction utcMsToYmd(epochMs: number): Ymd {\n const date = new Date(epochMs);\n return { year: date.getUTCFullYear(), month: date.getUTCMonth() + 1, day: date.getUTCDate() };\n}\n\n/** Chronological comparison: negative if `left` precedes `right`, 0 if the\n * same day, positive if after. */\nexport function compareYmd(left: Ymd, right: Ymd): number {\n return ymdToUtcMs(left) - ymdToUtcMs(right);\n}\n\n/** True iff `day` falls within the inclusive span `[span.start, span.end]`. */\nexport function spanCoversDay<T>(span: RecordSpan<T>, day: Ymd): boolean {\n return compareYmd(span.start, day) <= 0 && compareYmd(day, span.end) <= 0;\n}\n\n/** Build the 6×7 (42-cell) grid for the given month, including the\n * leading/trailing days of the adjacent months so every week is full.\n * `month` is 1-12. `weekStartsOn` is 0 (Sunday) … 6 (Saturday). */\nexport function buildMonthGrid(year: number, month: number, weekStartsOn = 0): DayCell[] {\n const firstWeekday = new Date(Date.UTC(year, month - 1, 1)).getUTCDay();\n const lead = (firstWeekday - weekStartsOn + 7) % 7;\n const startMs = Date.UTC(year, month - 1, 1) - lead * MS_PER_DAY;\n const cells: DayCell[] = [];\n for (let i = 0; i < 42; i++) {\n const ymd = utcMsToYmd(startMs + i * MS_PER_DAY);\n cells.push({ ymd, inMonth: ymd.year === year && ymd.month === month, key: ymdKey(ymd) });\n }\n return cells;\n}\n\n/** Resolve a record's calendar span from its date/datetime fields. Returns\n * null when the anchor date is missing/invalid (→ the caller's \"no date\"\n * tray). An end date that is missing, invalid, or earlier than the start\n * collapses to a single-day span — never an inverted range.\n *\n * Times for the day (time-allocation) view come from, in priority order:\n * 1. the clock on a `datetime` anchor/end value, else\n * 2. `timeField` — a separate free-form time-string column (e.g. \"14:00-17:00\").\n * A record with no resolvable clock has `startMin === endMin === null`. */\nexport function recordSpan<T extends Record<string, unknown>>(item: T, anchorField: string, endField?: string, timeField?: string): RecordSpan<T> | null {\n const startRaw = item[anchorField];\n const start = dateOf(startRaw);\n if (!start) return null;\n let end = start;\n let startMin = timeOf(startRaw);\n let endMin: number | null = null;\n if (endField) {\n const endRaw = item[endField];\n const parsedEnd = dateOf(endRaw);\n if (parsedEnd && compareYmd(parsedEnd, start) >= 0) {\n end = parsedEnd;\n endMin = timeOf(endRaw);\n }\n }\n // Fall back to a separate time-string field only when the date fields\n // carried no clock (the date-only anchor + `time` column shape).\n if (timeField && startMin === null && endMin === null) {\n const range = parseTimeRange(item[timeField]);\n if (range) {\n ({ startMin, endMin } = range);\n }\n }\n return { item, start, end, startMin, endMin };\n}\n\n/** Split records into those that land on the calendar (with their spans)\n * and those with no usable anchor date (the \"no date\" tray). Spans are\n * sorted by start day so same-day stacking is stable across renders. */\nexport function bucketRecords<T extends Record<string, unknown>>(\n items: readonly T[],\n anchorField: string,\n endField?: string,\n timeField?: string,\n): { spans: RecordSpan<T>[]; noDate: T[] } {\n const spans: RecordSpan<T>[] = [];\n const noDate: T[] = [];\n for (const item of items) {\n const span = recordSpan(item, anchorField, endField, timeField);\n if (span) spans.push(span);\n else noDate.push(item);\n }\n spans.sort((left, right) => compareYmd(left.start, right.start));\n return { spans, noDate };\n}\n\n/** Geometry for one record on one day of the time-allocation view.\n * `kind`:\n * \"allDay\" — no clock anywhere → render in the bottom all-day strip.\n * \"line\" — a single point in time → a 1px marker at `startMin`.\n * \"block\" — a [startMin, endMin) span, clamped to this day's [0, 1440).\n * `bleedsBefore` / `bleedsAfter` flag a multi-day span that began on an\n * earlier day or continues onto a later one (so the view can show arrows). */\nexport interface DaySlice {\n kind: \"allDay\" | \"line\" | \"block\";\n startMin: number;\n endMin: number;\n bleedsBefore: boolean;\n bleedsAfter: boolean;\n}\n\n/** Project a record's span onto a single day for the time-allocation view, or\n * null when the span doesn't cover that day. */\nexport function daySlice<T>(span: RecordSpan<T>, day: Ymd): DaySlice | null {\n if (!spanCoversDay(span, day)) return null;\n const hasStart = span.startMin !== null;\n const hasEnd = span.endMin !== null;\n if (!hasStart && !hasEnd) {\n return { kind: \"allDay\", startMin: 0, endMin: MINUTES_PER_DAY, bleedsBefore: false, bleedsAfter: false };\n }\n const singleDay = compareYmd(span.start, span.end) === 0;\n const isStartDay = compareYmd(day, span.start) === 0;\n const isEndDay = compareYmd(day, span.end) === 0;\n // A point in time: a start clock with no end, all on one day.\n if (singleDay && hasStart && !hasEnd) {\n return { kind: \"line\", startMin: span.startMin as number, endMin: span.startMin as number, bleedsBefore: false, bleedsAfter: false };\n }\n const startMin = isStartDay && hasStart ? (span.startMin as number) : 0;\n const endMin = isEndDay && hasEnd ? (span.endMin as number) : MINUTES_PER_DAY;\n // Zero-length or inverted same-day range → degrade to a line.\n if (singleDay && endMin <= startMin) {\n return { kind: \"line\", startMin, endMin: startMin, bleedsBefore: false, bleedsAfter: false };\n }\n return { kind: \"block\", startMin, endMin, bleedsBefore: !isStartDay, bleedsAfter: !isEndDay };\n}\n\n/** Side-by-side lane assignment for overlapping timeline blocks. Each input\n * is an `[startMin, endMin)` interval; the result (parallel to the input)\n * gives each item its `lane` (column index) and the `lanes` total of its\n * overlap cluster, so a renderer can size every block to `1 / lanes` width\n * and offset it by `lane / lanes`. Non-overlapping items get `lanes === 1`. */\nexport interface LaneSpan {\n startMin: number;\n endMin: number;\n}\nexport interface LaneAssignment {\n lane: number;\n lanes: number;\n}\n\nexport function assignLanes(blocks: readonly LaneSpan[]): LaneAssignment[] {\n const order = [...blocks.keys()].sort((left, right) => blocks[left].startMin - blocks[right].startMin || blocks[left].endMin - blocks[right].endMin);\n const result: LaneAssignment[] = blocks.map(() => ({ lane: 0, lanes: 1 }));\n let cluster: number[] = [];\n let clusterEnd = Number.NEGATIVE_INFINITY;\n const laneEnds: number[] = [];\n const flush = (): void => {\n for (const index of cluster) result[index].lanes = laneEnds.length;\n cluster = [];\n laneEnds.length = 0;\n clusterEnd = Number.NEGATIVE_INFINITY;\n };\n for (const index of order) {\n const block = blocks[index];\n if (cluster.length > 0 && block.startMin >= clusterEnd) flush();\n let lane = laneEnds.findIndex((end) => end <= block.startMin);\n if (lane === -1) {\n lane = laneEnds.length;\n laneEnds.push(block.endMin);\n } else {\n laneEnds[lane] = block.endMin;\n }\n result[index].lane = lane;\n cluster.push(index);\n clusterEnd = Math.max(clusterEnd, block.endMin);\n }\n flush();\n return result;\n}\n\n/** Month label key inputs — returns the 1st of the month as a `Date` so the\n * component can feed it to `Intl.DateTimeFormat(locale, …)` for a localized\n * \"April 2026\" header without this module taking a locale dependency. */\nexport function monthAnchorDate(year: number, month: number): Date {\n return new Date(Date.UTC(year, month - 1, 1));\n}\n","// Neutralize structural prompt-injection vectors in a short, record-derived\n// string before it rides into an LLM-facing prompt: strip angle brackets,\n// defang backticks / `${` template openings, collapse whitespace (so an\n// embedded newline can't fabricate a pseudo-instruction on its own line), and\n// clip to a small budget. Mirrors the host server's own defang so the two\n// can't drift (#1677).\n\n/** Max chars kept — the first batch of a validation issue is enough to act on. */\nconst DEFANG_MAX_LEN = 200;\n\nexport function defangForPrompt(value: string): string {\n return value.replace(/[<>]/g, \"\").replace(/`/g, \"'\").replace(/\\$\\{/g, \"$ {\").replace(/\\s+/g, \" \").slice(0, DEFANG_MAX_LEN);\n}\n"],"mappings":";;;AAeA,IAAM,cAAc,UAClB,OAAO,UAAU,YAAY,OAAO,UAAU,YAAY,OAAO,UAAU,aAAa,iBAAiB;;;;;;;AAQ3G,SAAgB,gBAAgB,OAA+B;CAC7D,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO;CAClD,IAAI,CAAC,WAAW,KAAK,GAAG,OAAO;CAC/B,IAAI,iBAAiB,MAKnB,OAAO,OAAO,MAAM,MAAM,QAAQ,CAAC,IAAI,OAAO,MAAM,YAAY;CAElE,OAAO,OAAO,KAAK;AACrB;;;;AAKA,SAAgB,UAAU,OAAgB,WAAW,IAAY;CAC/D,OAAO,gBAAgB,KAAK,KAAK;AACnC;;;;;;;;;;AClBA,SAAgB,YAAY,MAAiC,QAA0C;CACrG,IAAI,CAAC,MAAM,OAAO;CAIlB,MAAM,OAAO,gBAAgB,OAAO,KAAK,MAAM;CAC/C,IAAI,SAAS,MAAM,OAAO;CAC1B,OAAO,KAAK,GAAG,SAAS,IAAI;AAC9B;;;;AAcA,SAAgB,cAAc,QAAwB,QAA0C;CAC9F,OAAO,YAAY,OAAO,QAAQ,OAAO,SAAS,MAAM;AAC1D;;;;;;;AAQA,SAAgB,kBAAkB,UAAkB,QAAyB;CAC3E,OAAO,WAAW,KAAA,IAAY,cAAc,aAAa,QAAQ,OAAO,GAAG;AAC7E;;;;;;AAaA,SAAgB,aAAa,OAAsB,QAA0C;CAC3F,OAAO,YAAY,MAAM,MAAM,MAAM;AACvC;;;;;;;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